Beispiel #1
0
    def __init__(self, parent=None):
        """Constructor for the dialog.

        Show the grid converter dialog.

        :param parent: parent - widget to use as parent.
        :type parent: QWidget

        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %1 Converter').arg(
            get_version()))

        self.warning_text = set()
        self.on_leInputPath_textChanged()
        self.on_leOutputPath_textChanged()
        self.update_warning()

        # Event register
        QObject.connect(self.cBDefaultOutputLocation,
                        SIGNAL('toggled(bool)'),
                        self.get_output_from_input)
        QObject.connect(self.leInputPath,
                        SIGNAL('textChanged(QString)'),
                        self.on_leInputPath_textChanged)
        QObject.connect(self.leOutputPath,
                        SIGNAL('textChanged(QString)'),
                        self.on_leOutputPath_textChanged)

        self.show_info()
Beispiel #2
0
    def __init__(self, parent=None):
        """Constructor for the dialog.

        Show the grid converter dialog.

        :param parent: parent - widget to use as parent.
        :type parent: QWidget

        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %1 Converter').arg(get_version()))

        self.warning_text = set()
        self.on_leInputPath_textChanged()
        self.on_leOutputPath_textChanged()
        self.update_warning()

        # Event register
        QObject.connect(self.cBDefaultOutputLocation, SIGNAL('toggled(bool)'),
                        self.get_output_from_input)
        QObject.connect(self.leInputPath, SIGNAL('textChanged(QString)'),
                        self.on_leInputPath_textChanged)
        QObject.connect(self.leOutputPath, SIGNAL('textChanged(QString)'),
                        self.on_leOutputPath_textChanged)

        self.show_info()
Beispiel #3
0
    def __init__(self, parent=None):
        """Constructor for the dialog.

        Show the grid converter dialog.

        :param parent: parent - widget to use as parent.
        :type parent: QWidget

        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)
        self.setWindowTitle(
            self.tr('InaSAFE %s Shakemap Converter' % get_version()))
        self.warning_text = set()
        self.on_input_path_textChanged()
        self.on_output_path_textChanged()
        self.update_warning()

        # Event register
        #noinspection PyUnresolvedReferences
        self.use_output_default.toggled.connect(self.get_output_from_input)
        #noinspection PyUnresolvedReferences
        self.input_path.textChanged.connect(self.on_input_path_textChanged)
        #noinspection PyUnresolvedReferences
        self.output_path.textChanged.connect(self.on_output_path_textChanged)
        # Set up things for context help
        help_button = self.button_box.button(QDialogButtonBox.Help)
        help_button.clicked.connect(ShakemapImporter.show_help)

        self.show_info()
    def __init__(self, iface, dock=None, parent=None):
        """Constructor for the dialog.

        :param iface: A Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param parent: Parent widget of this dialog
        :type parent: QWidget

        :param dock: Optional dock widget instance that we can notify of
            changes to the keywords.
        :type dock: Dock
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %s Options' % get_version()))
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = dock
        self.keywordIO = KeywordIO()
        # Set up things for context help
        myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        myButton.clicked.connect(self.show_help)
        self.grpNotImplemented.hide()
        self.adjustSize()
        self.restore_state()
        # hack prevent showing use thread visible and set it false see #557
        self.cbxUseThread.setChecked(True)
        self.cbxUseThread.setVisible(False)
Beispiel #5
0
    def __init__(self, parent=None, dict_filter=None):
        """Constructor for the dialog.

        This dialog will show the user impact function documentation.

        :param parent: Optional widget to use as parent
        :type parent: QWidget

        :param dict_filter: Optional filter to use to limit which functions
            are show to the user. See below.
        :type dict_filter: dict

        Example dict_filter::

            {'id': [],
             'title': [],
             'category': [],
             'subcategory': [],
             'layertype': [],
             'datatype': [],
             'unit': []}
        """
        QtGui.QDialog.__init__(self, parent)
        # Set up the user interface from Designer.
        self.setupUi(self)
        self.setWindowTitle(
            self.tr('InaSAFE %s Impact Functions Browser') % (get_version()))
        self.parent = parent

        self.no_filter = self.tr('No Filter')
        if dict_filter is None:
            dict_filter = {
                'id': [],
                'title': [],
                'category': [],
                'subcategory': [],
                'layertype': [],
                'datatype': [],
                'unit': []
            }

        self.dict_filter = dict_filter
        self.table = None  # for storing impact functions table
        self.show_table()
        self.combo_box_content = None  # for storing combo box content
        self.populate_combo_box()
        resetButton = self.myButtonBox.button(QtGui.QDialogButtonBox.Reset)
        resetButton.clicked.connect(self.reset_button_clicked)

        helpButton = self.myButtonBox.button(QtGui.QDialogButtonBox.Help)
        helpButton.clicked.connect(self.show_help)
        # Combo box change event
        self.comboBox_id.currentIndexChanged.connect(self.update_table)
        self.comboBox_title.currentIndexChanged.connect(self.update_table)
        self.comboBox_category.currentIndexChanged.connect(self.update_table)
        self.comboBox_subcategory.currentIndexChanged.connect(
            self.update_table)
        self.comboBox_layertype.currentIndexChanged.connect(self.update_table)
        self.comboBox_datatype.currentIndexChanged.connect(self.update_table)
        self.comboBox_unit.currentIndexChanged.connect(self.update_table)
Beispiel #6
0
    def __init__(self, iface, dock=None, parent=None):
        """Constructor for the dialog.

        :param iface: A Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param parent: Parent widget of this dialog
        :type parent: QWidget

        :param dock: Optional dock widget instance that we can notify of
            changes to the keywords.
        :type dock: Dock
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %s Options' % get_version()))
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = dock
        self.helpDialog = None
        self.keywordIO = KeywordIO()
        # Set up things for context help
        myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
                               self.show_help)
        self.grpNotImplemented.hide()
        self.adjustSize()
        self.restore_state()
        # hack prevent showing use thread visible and set it false see #557
        self.cbxUseThread.setChecked(True)
        self.cbxUseThread.setVisible(False)
Beispiel #7
0
    def __init__(self, theParent=None):
        """Constructor for the dialog.

                This dialog will show the user converter dialog

        Args:
           * theParent - Optional widget to use as parent
        Returns:
           not applicable
        Raises:
           no exceptions explicitly raised
        """
        QDialog.__init__(self, theParent)
        self.parent = theParent
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %1 Converter').arg(get_version()))
        # I'm too lazy to put a text :)
        # self.leInputPath.setText('/home/sunnii/Downloads/grid.xml')
        self.list_algorithm = ['Nearest', 'Invdist']
        self.test_mode = False
        self.populate_algorithm()
        self.warning_text = set()
        self.on_leInputPath_textChanged()
        self.on_leOutputPath_textChanged()
        self.update_warning()
        # Event register
        QObject.connect(self.cBDefaultOutputLocation, SIGNAL('toggled(bool)'),
                        self.get_output_from_input)
        QObject.connect(self.leInputPath, SIGNAL('textChanged(QString)'),
                        self.on_leInputPath_textChanged)
        QObject.connect(self.leOutputPath, SIGNAL('textChanged(QString)'),
                        self.on_leOutputPath_textChanged)
Beispiel #8
0
    def __init__(self, parent, iface, theDock=None):
        """Constructor for the dialog.

        Args:
           * parent - parent widget of this dialog
           * iface - a Quantum GIS QGisAppInterface instance.
           * theDock - Optional dock widget instance that we can notify of
             changes to the keywords.

        Returns:
           not applicable
        Raises:
           no exceptions explicitly raised
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %s Options' % get_version()))
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = theDock
        self.helpDialog = None
        self.keywordIO = KeywordIO()
        # Set up things for context help
        myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
                               self.showHelp)
        self.grpNotImplemented.hide()
        self.adjustSize()
        self.restoreState()
        # hack prevent showing use thread visible and set it false see #557
        self.cbxUseThread.setChecked(True)
        self.cbxUseThread.setVisible(False)
    def __init__(self, parent=None):
        """Constructor for the dialog.

        Show the grid converter dialog.

        :param parent: parent - widget to use as parent.
        :type parent: QWidget

        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %s Converter') % (
            get_version()))

        self.warning_text = set()
        self.on_input_path_textChanged()
        self.on_output_path_textChanged()
        self.update_warning()

        # Event register
        #noinspection PyUnresolvedReferences
        self.use_output_default.toggled.connect(
            self.get_output_from_input)
        #noinspection PyUnresolvedReferences
        self.input_path.textChanged.connect(self.on_input_path_textChanged)
        #noinspection PyUnresolvedReferences
        self.output_path.textChanged.connect(self.on_output_path_textChanged)
        # Set up things for context help
        help_button = self.button_box.button(QDialogButtonBox.Help)
        help_button.clicked.connect(self.show_help)

        self.show_info()
Beispiel #10
0
    def __init__(self, parent=None):
        """Constructor for the dialog.

        :param parent: Parent widget of this dialog
        :type parent: QWidget
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr('About InaSAFE %s' % get_version()))
        self.parent = parent

        # Set Limitations Text
        limitations_text = ''
        for index, limitation in enumerate(limitations()):
            limitations_text += '%s. %s \n' % (index + 1, limitation)
        self.limitations_text.setFontPointSize(11)
        self.limitations_text.setText(limitations_text)

        # Set Disclaimer Text
        self.disclaimer_text.setFontPointSize(11)
        self.disclaimer_text.setText(disclaimer())

        # Set Attributions text
        image_credits_text = ''
        for index, limitation in enumerate(self.attributions()):
            image_credits_text += '%s. %s \n' % (index + 1, limitation)
        self.image_credits_text.setFontPointSize(11)
        self.image_credits_text.setText(image_credits_text)
Beispiel #11
0
    def __init__(self, parent, iface, theDock=None):
        """Constructor for the dialog.

        Args:
           * parent - parent widget of this dialog
           * iface - a Quantum GIS QGisAppInterface instance.
           * theDock - Optional dock widget instance that we can notify of
             changes to the keywords.

        Returns:
           not applicable
        Raises:
           no exceptions explicitly raised
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %s Options' % get_version()))
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = theDock
        self.helpDialog = None
        self.keywordIO = KeywordIO()
        # Set up things for context help
        myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
                               self.showHelp)
        self.grpNotImplemented.hide()
        self.adjustSize()
        self.restoreState()
        # hack prevent showing use thread visible and set it false see #557
        self.cbxUseThread.setChecked(True)
        self.cbxUseThread.setVisible(False)
Beispiel #12
0
    def __init__(self, parent=None):
        """Constructor for the dialog.

        :param parent: Parent widget of this dialog
        :type parent: QWidget
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr('About InaSAFE %s' % get_version()))
        self.parent = parent

        # Set Limitations Text
        limitations_text = ''
        for index, limitation in enumerate(limitations()):
            limitations_text += '%s. %s \n' % (index + 1, limitation)
        self.limitations_text.setFontPointSize(11)
        self.limitations_text.setText(limitations_text)

        # Set Disclaimer Text
        self.disclaimer_text.setFontPointSize(11)
        self.disclaimer_text.setText(disclaimer())

        # Set Attributions text
        image_credits_text = ''
        for index, limitation in enumerate(self.attributions()):
            image_credits_text += '%s. %s \n' % (index + 1, limitation)
        self.image_credits_text.setFontPointSize(11)
        self.image_credits_text.setText(image_credits_text)
    def __init__(self, parent=None, dict_filter=None):
        """Constructor for the dialog.

        This dialog will show the user impact function documentation.

        :param parent: Optional widget to use as parent
        :type parent: QWidget

        :param dict_filter: Optional filter to use to limit which functions
            are show to the user. See below.
        :type dict_filter: dict

        Example dict_filter::

            {'id': [],
             'title': [],
             'category': [],
             'subcategory': [],
             'layertype': [],
             'datatype': [],
             'unit': []}
        """
        QtGui.QDialog.__init__(self, parent)
        # Set up the user interface from Designer.
        self.setupUi(self)
        self.setWindowTitle(
            self.tr('InaSAFE %s Impact Functions Browser') % (get_version()))
        self.parent = parent

        self.no_filter = self.tr('No Filter')
        if dict_filter is None:
            dict_filter = {
                'id': [],
                'title': [],
                'category': [],
                'subcategory': [],
                'layertype': [],
                'datatype': [],
                'unit': []}

        self.dict_filter = dict_filter
        self.table = None  # for storing impact functions table
        self.show_table()
        self.combo_box_content = None  # for storing combo box content
        self.populate_combo_box()
        resetButton = self.myButtonBox.button(QtGui.QDialogButtonBox.Reset)
        resetButton.clicked.connect(self.reset_button_clicked)

        helpButton = self.myButtonBox.button(QtGui.QDialogButtonBox.Help)
        helpButton.clicked.connect(self.show_help)
        # Combo box change event
        self.comboBox_id.currentIndexChanged.connect(self.update_table)
        self.comboBox_title.currentIndexChanged.connect(self.update_table)
        self.comboBox_category.currentIndexChanged.connect(self.update_table)
        self.comboBox_subcategory.currentIndexChanged.connect(
            self.update_table)
        self.comboBox_layertype.currentIndexChanged.connect(self.update_table)
        self.comboBox_datatype.currentIndexChanged.connect(self.update_table)
        self.comboBox_unit.currentIndexChanged.connect(self.update_table)
Beispiel #14
0
    def drawHostAndTime(self, theTopOffset):
        """Add a disclaimer to the composition.

        Args:
            theTopOffset - vertical offset at which to begin drawing
        Returns:
            None
        Raises:
            None
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        #elapsed_time: 11.612545
        #user: timlinux
        #host_name: ultrabook
        #time_stamp: 2012-10-13_23:10:31
        #myUser = self.keywordIO.readKeywords(self.layer, 'user')
        #myHost = self.keywordIO.readKeywords(self.layer, 'host_name')
        myDateTime = self.keywordIO.readKeywords(self.layer, 'time_stamp')
        myTokens = myDateTime.split('_')
        myDate = myTokens[0]
        myTime = myTokens[1]
        #myElapsedTime = self.keywordIO.readKeywords(self.layer,
        #                                            'elapsed_time')
        #myElapsedTime = humaniseSeconds(myElapsedTime)
        myLongVersion = get_version()
        myTokens = myLongVersion.split('.')
        myVersion = '%s.%s.%s' % (myTokens[0], myTokens[1], myTokens[2])
        myLabelText = self.tr('Date and time of assessment: %1 %2\n'
                              'Special note: This assessment is a guide - we '
                              'strongly recommend that you ground truth the '
                              'results shown here before deploying resources '
                              'and / or personnel.\n'
                              'Assessment carried out using InaSAFE release '
                              '%3 (QGIS plugin version).').arg(
                              myDate).arg(myTime).arg(myVersion)
        myFontSize = 6
        myFontWeight = QtGui.QFont.Normal
        myItalicsFlag = True
        myFont = QtGui.QFont('verdana',
                             myFontSize,
                             myFontWeight,
                             myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myLabel.setText(myLabelText)
        myLabel.adjustSizeToText()
        myLabelHeight = 50.0  # mm determined using qgis map composer
        myLabelWidth = (self.pageWidth / 2) - self.pageMargin
        myLeftOffset = self.pageWidth / 2  # put in right half of page
        myLabel.setItemPosition(myLeftOffset,
                                theTopOffset,
                                myLabelWidth,
                                myLabelHeight,
                                )
        myLabel.setFrame(self.showFramesFlag)
        self.composition.addItem(myLabel)
Beispiel #15
0
    def drawHostAndTime(self, theTopOffset):
        """Add a disclaimer to the composition.

        Args:
            theTopOffset - vertical offset at which to begin drawing
        Returns:
            None
        Raises:
            None
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        #elapsed_time: 11.612545
        #user: timlinux
        #host_name: ultrabook
        #time_stamp: 2012-10-13_23:10:31
        #myUser = self.keywordIO.readKeywords(self.layer, 'user')
        #myHost = self.keywordIO.readKeywords(self.layer, 'host_name')
        myDateTime = self.keywordIO.readKeywords(self.layer, 'time_stamp')
        myTokens = myDateTime.split('_')
        myDate = myTokens[0]
        myTime = myTokens[1]
        #myElapsedTime = self.keywordIO.readKeywords(self.layer,
        #                                            'elapsed_time')
        #myElapsedTime = humaniseSeconds(myElapsedTime)
        myLongVersion = get_version()
        myTokens = myLongVersion.split('.')
        myVersion = '%s.%s.%s' % (myTokens[0], myTokens[1], myTokens[2])
        myLabelText = self.tr(
            'Date and time of assessment: %1 %2\n'
            'Special note: This assessment is a guide - we '
            'strongly recommend that you ground truth the '
            'results shown here before deploying resources '
            'and / or personnel.\n'
            'Assessment carried out using InaSAFE release '
            '%3 (QGIS plugin version).').arg(myDate).arg(myTime).arg(myVersion)
        myFontSize = 6
        myFontWeight = QtGui.QFont.Normal
        myItalicsFlag = True
        myFont = QtGui.QFont('verdana', myFontSize, myFontWeight,
                             myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myLabel.setText(myLabelText)
        myLabel.adjustSizeToText()
        myLabelHeight = 50.0  # mm determined using qgis map composer
        myLabelWidth = (self.pageWidth / 2) - self.pageMargin
        myLeftOffset = self.pageWidth / 2  # put in right half of page
        myLabel.setItemPosition(
            myLeftOffset,
            theTopOffset,
            myLabelWidth,
            myLabelHeight,
        )
        myLabel.setFrame(self.showFramesFlag)
        self.composition.addItem(myLabel)
Beispiel #16
0
    def __init__(self, parent=None):
        """Constructor for the dialog.

        :param parent: Parent widget of this dialog
        :type parent: QWidget
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr('About InaSAFE %s' % get_version()))
        self.parent = parent
Beispiel #17
0
    def draw_host_and_time(self, top_offset):
        """Add a note with hostname and time to the composition.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        #elapsed_time: 11.612545
        #user: timlinux
        #host_name: ultrabook
        #time_stamp: 2012-10-13_23:10:31
        #myUser = self.keyword_io.readKeywords(self.layer, 'user')
        #myHost = self.keyword_io.readKeywords(self.layer, 'host_name')
        date_time = self.keyword_io.read_keywords(self.layer, 'time_stamp')
        tokens = date_time.split('_')
        date = tokens[0]
        time = tokens[1]
        #myElapsedTime = self.keyword_io.readKeywords(self.layer,
        #                                            'elapsed_time')
        #myElapsedTime = humaniseSeconds(myElapsedTime)
        long_version = get_version()
        tokens = long_version.split('.')
        version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])
        label_text = self.tr(
            'Date and time of assessment: %s %s\n'
            'Special note: This assessment is a guide - we strongly recommend '
            'that you ground truth the results shown here before deploying '
            'resources and / or personnel.\n'
            'Assessment carried out using InaSAFE release %s (QGIS '
            'plugin version).') % (date, time, version)
        font_size = 6
        font_weight = QtGui.QFont.Normal
        italics_flag = True
        font = QtGui.QFont(
            'verdana',
            font_size,
            font_weight,
            italics_flag)
        label = QgsComposerLabel(self.composition)
        label.setFont(font)
        label.setText(label_text)
        label.adjustSizeToText()
        label_height = 50.0  # mm determined using qgis map composer
        label_width = (self.page_width / 2) - self.page_margin
        left_offset = self.page_width / 2  # put in right half of page
        label.setItemPosition(
            left_offset,
            top_offset,
            label_width,
            label_height,)
        label.setFrameEnabled(self.show_frames)
        self.composition.addItem(label)
Beispiel #18
0
    def __init__(self, parent=None):
        """Constructor for the minimum needs dialog.

        :param parent: Parent widget of this dialog.
        :type parent: QWidget
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr(
            'InaSAFE %1 Minimum Needs Tool').arg(get_version()))
        self.polygon_layers_to_combo()
        self.show_info()
Beispiel #19
0
    def __init__(self, theParent=None, dict_filter=None):
        """Constructor for the dialog.

                This dialog will show the user impact function documentation.

        Args:
           * theParent - Optional widget to use as parent
        Returns:
           not applicable
        Raises:
           no exceptions explicitly raised
        """
        QtGui.QDialog.__init__(self, theParent)
        self.parent = theParent
        self.header = None  # for storing html header template
        self.footer = None  # for storing html footer template
        # Set up the user interface from Designer.
        self.setupUi(self)
        self.setWindowTitle(self.tr("InaSAFE %1 Impact Functions Browser").arg(get_version()))
        self.no_filter = self.tr("No Filter")
        if dict_filter is None:
            dict_filter = {
                "id": [],
                "title": [],
                "category": [],
                "subcategory": [],
                "layertype": [],
                "datatype": [],
                "unit": [],
            }

        self.dict_filter = dict_filter
        self.if_table = None  # for storing impact functions table
        self.showImpactFunctionsTable()
        self.combo_box_content = None  # for storing combo box content
        self.populate_combo_box()
        resetButton = self.myButtonBox.button(QtGui.QDialogButtonBox.Reset)
        QtCore.QObject.connect(resetButton, QtCore.SIGNAL("clicked()"), self.reset_button_clicked)

        # Set up help dialog showing logic.
        self.helpDialog = None
        helpButton = self.myButtonBox.button(QtGui.QDialogButtonBox.Help)
        QtCore.QObject.connect(helpButton, QtCore.SIGNAL("clicked()"), self.showHelp)
        # Combo box change event
        QtCore.QObject.connect(self.comboBox_id, QtCore.SIGNAL("currentIndexChanged(int)"), self.update_table)
        QtCore.QObject.connect(self.comboBox_title, QtCore.SIGNAL("currentIndexChanged(int)"), self.update_table)
        QtCore.QObject.connect(self.comboBox_category, QtCore.SIGNAL("currentIndexChanged(int)"), self.update_table)
        QtCore.QObject.connect(self.comboBox_subcategory, QtCore.SIGNAL("currentIndexChanged(int)"), self.update_table)
        QtCore.QObject.connect(self.comboBox_layertype, QtCore.SIGNAL("currentIndexChanged(int)"), self.update_table)
        QtCore.QObject.connect(self.comboBox_datatype, QtCore.SIGNAL("currentIndexChanged(int)"), self.update_table)
        QtCore.QObject.connect(self.comboBox_unit, QtCore.SIGNAL("currentIndexChanged(int)"), self.update_table)
Beispiel #20
0
    def draw_host_and_time(self, top_offset):
        """Add a note with hostname and time to the composition.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        #elapsed_time: 11.612545
        #user: timlinux
        #host_name: ultrabook
        #time_stamp: 2012-10-13_23:10:31
        #myUser = self.keyword_io.readKeywords(self.layer, 'user')
        #myHost = self.keyword_io.readKeywords(self.layer, 'host_name')
        date_time = self.keyword_io.read_keywords(self.layer, 'time_stamp')
        tokens = date_time.split('_')
        date = tokens[0]
        time = tokens[1]
        #myElapsedTime = self.keyword_io.readKeywords(self.layer,
        #                                            'elapsed_time')
        #myElapsedTime = humaniseSeconds(myElapsedTime)
        long_version = get_version()
        tokens = long_version.split('.')
        version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])
        label_text = self.tr(
            'Date and time of assessment: %s %s\n'
            'Special note: This assessment is a guide - we strongly recommend '
            'that you ground truth the results shown here before deploying '
            'resources and / or personnel.\n'
            'Assessment carried out using InaSAFE release %s (QGIS '
            'plugin version).') % (date, time, version)
        font_size = 6
        font_weight = QtGui.QFont.Normal
        italics_flag = True
        font = QtGui.QFont('verdana', font_size, font_weight, italics_flag)
        label = QgsComposerLabel(self.composition)
        label.setFont(font)
        label.setText(label_text)
        label.adjustSizeToText()
        label_height = 50.0  # mm determined using qgis map composer
        label_width = (self.page_width / 2) - self.page_margin
        left_offset = self.page_width / 2  # put in right half of page
        label.setItemPosition(
            left_offset,
            top_offset,
            label_width,
            label_height,
        )
        label.setFrameEnabled(self.show_frames)
        self.composition.addItem(label)
Beispiel #21
0
    def __init__(self, parent=None):
        """Constructor for the minimum needs dialog.

        :param parent: Parent widget of this dialog.
        :type parent: QWidget
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr(
            'InaSAFE %s Minimum Needs Tool' % get_version()))
        self.polygon_layers_to_combo()
        self.show_info()
        help_button = self.button_box.button(QtGui.QDialogButtonBox.Help)
        help_button.clicked.connect(self.show_help)
    def __init__(self, parent=None):
        """Constructor for the minimum needs dialog.

        :param parent: Parent widget of this dialog.
        :type parent: QWidget
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(
            self.tr('InaSAFE %s Minimum Needs Tool' % get_version()))
        self.polygon_layers_to_combo()
        self.show_info()
        help_button = self.button_box.button(QtGui.QDialogButtonBox.Help)
        help_button.clicked.connect(self.show_help)
Beispiel #23
0
    def __init__(self, parent):
        """Constructor for the dialog.

        Args:
           * parent - parent widget of this dialog.
           * iface - a Quantum GIS QGisAppInterface instance.

        Returns:
           not applicable.
        Raises:
           no exceptions explicitly raised.
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr("InaSAFE %1 Minimum Needs Tool").arg(get_version()))
        self.polygonLayersToCombo()
Beispiel #24
0
    def __init__(self, parent):
        """Constructor for the dialog.

        Args:
           * parent - parent widget of this dialog.
           * iface - a Quantum GIS QGisAppInterface instance.

        Returns:
           not applicable.
        Raises:
           no exceptions explicitly raised.
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(
            self.tr('InaSAFE %1 Minimum Needs Tool').arg(get_version()))
        self.polygonLayersToCombo()
Beispiel #25
0
    def __init__(self, iface, dock=None, parent=None):
        """Constructor for the dialog.

        :param iface: A Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param parent: Parent widget of this dialog
        :type parent: QWidget

        :param dock: Optional dock widget instance that we can notify of
            changes to the keywords.
        :type dock: Dock
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %s Options' % get_version()))
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = dock
        self.keyword_io = KeywordIO()
        self.defaults = get_defaults()

        # Set up things for context help
        button = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        button.clicked.connect(self.show_help)
        self.grpNotImplemented.hide()
        self.adjustSize()
        self.restore_state()
        # hack prevent showing use thread visible and set it false see #557
        self.cbxUseThread.setChecked(True)
        self.cbxUseThread.setVisible(False)

        # Set up listener for various UI
        self.custom_org_logo_checkbox.toggled.connect(
            self.set_organisation_logo)
        self.custom_north_arrow_checkbox.toggled.connect(self.set_north_arrow)
        self.custom_templates_dir_checkbox.toggled.connect(
            self.set_templates_dir)
        self.custom_org_disclaimer_checkbox.toggled.connect(
            self.set_org_disclaimer)
Beispiel #26
0
    def __init__(self, theParent=None):
        """Constructor for the dialog.

                This dialog will show the user converter dialog

        Args:
           * theParent - Optional widget to use as parent
        Returns:
           not applicable
        Raises:
           no exceptions explicitly raised
        """
        QDialog.__init__(self, theParent)
        self.parent = theParent
        self.setupUi(self)
        self.setWindowTitle(self.tr('InaSAFE %1 Converter').arg(
            get_version()))
        # I'm too lazy to put a text :)
        # self.leInputPath.setText('/home/sunnii/Downloads/grid.xml')
        self.list_algorithm = ['Nearest', 'Invdist']
        self.test_mode = False
        self.populate_algorithm()
        self.warning_text = set()
        self.on_leInputPath_textChanged()
        self.on_leOutputPath_textChanged()
        self.update_warning()
        # Event register
        QObject.connect(self.cBDefaultOutputLocation,
                        SIGNAL('toggled(bool)'),
                        self.get_output_from_input)
        QObject.connect(self.leInputPath,
                        SIGNAL('textChanged(QString)'),
                        self.on_leInputPath_textChanged)
        QObject.connect(self.leOutputPath,
                        SIGNAL('textChanged(QString)'),
                        self.on_leOutputPath_textChanged)
Beispiel #27
0
    def load_template(self):
        """Load a QgsComposer map from a template.
        """
        self.setup_composition()

        template_file = QtCore.QFile(self.template)
        template_file.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
        template_content = template_file.readAll()
        template_file.close()

        document = QtXml.QDomDocument()
        document.setContent(template_content)

        # get information for substitutions
        # date, time and plugin version
        date_time = self.keyword_io.read_keywords(self.layer, 'time_stamp')
        if date_time is None:
            date = ''
            time = ''
        else:
            tokens = date_time.split('_')
            date = tokens[0]
            time = tokens[1]
        long_version = get_version()
        tokens = long_version.split('.')
        version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])

        title = self.map_title()
        if not title:
            title = ''

        substitution_map = {
            'impact-title': title,
            'date': date,
            'time': time,
            'safe-version': version,
            'disclaimer': self.disclaimer
        }
        LOGGER.debug(substitution_map)
        load_ok = self.composition.loadFromTemplate(document, substitution_map)
        if not load_ok:
            raise ReportCreationError(
                self.tr('Error loading template %s') % self.template)

        self.page_width = self.composition.paperWidth()
        self.page_height = self.composition.paperHeight()

        # set InaSAFE logo
        image = self.composition.getComposerItemById('safe-logo')
        if image is not None:
            image.setPictureFile(self.safe_logo)
        else:
            raise ReportCreationError(
                self.tr('Image "safe-logo" could not be found'))

        # set north arrow
        image = self.composition.getComposerItemById('north-arrow')
        if image is not None:
            image.setPictureFile(self.north_arrow)
        else:
            raise ReportCreationError(
                self.tr('Image "north arrow" could not be found'))

        # set organisation logo
        image = self.composition.getComposerItemById('organisation-logo')
        if image is not None:
            image.setPictureFile(self.org_logo)
        else:
            raise ReportCreationError(
                self.tr('Image "organisation-logo" could not be found'))

        # set impact report table
        table = self.composition.getComposerItemById('impact-report')
        if table is not None:
            text = self.keyword_io.read_keywords(self.layer, 'impact_summary')
            if text is None:
                text = ''
            table.setText(text)
            table.setHtmlState(1)
        else:
            LOGGER.debug('"impact-report" element not found.')

        # Get the main map canvas on the composition and set
        # its extents to the event.
        composer_map = self.composition.getComposerItemById('impact-map')
        if composer_map is not None:
            # Recenter the composer map on the center of the extent
            # Note that since the composer map is square and the canvas may be
            # arbitrarily shaped, we center based on the longest edge
            canvas_extent = self.extent
            width = canvas_extent.width()
            height = canvas_extent.height()
            longest_width = width
            if width < height:
                longest_width = height
            half_length = longest_width / 2
            center = canvas_extent.center()
            min_x = center.x() - half_length
            max_x = center.x() + half_length
            min_y = center.y() - half_length
            max_y = center.y() + half_length
            square_extent = QgsRectangle(min_x, min_y, max_x, max_y)
            composer_map.setNewExtent(square_extent)

            # calculate intervals for grid
            split_count = 5
            x_interval = square_extent.width() / split_count
            composer_map.setGridIntervalX(x_interval)
            y_interval = square_extent.height() / split_count
            composer_map.setGridIntervalY(y_interval)
        else:
            raise ReportCreationError(
                self.tr('Map "impact-map" could not be found'))

        legend = self.composition.getComposerItemById('impact-legend')
        legend_attributes = self.map_legend_attributes()
        LOGGER.debug(legend_attributes)
        #legend_notes = mapLegendAttributes.get('legend_notes', None)
        #legend_units = mapLegendAttributes.get('legend_units', None)
        legend_title = legend_attributes.get('legend_title', None)

        symbol_count = 1
        if self.layer.type() == QgsMapLayer.VectorLayer:
            renderer = self.layer.rendererV2()
            if renderer.type() in ['', '']:
                symbol_count = len(self.layer.legendSymbologyItems())
        else:
            renderer = self.layer.renderer()
            if renderer.type() in ['']:
                symbol_count = len(self.layer.legendSymbologyItems())

        if symbol_count <= 5:
            legend.setColumnCount(1)
        else:
            legend.setColumnCount(symbol_count / 5 + 1)

        if legend_title is None:
            legend_title = ""
        legend.setTitle(legend_title)
        legend.updateLegend()

        # remove from legend all layers, except impact one
        model = legend.model()
        if model.rowCount() > 0 and model.columnCount() > 0:
            impact_item = model.findItems(self.layer.name())[0]
            row = impact_item.index().row()
            model.removeRows(row + 1, model.rowCount() - row)
            if row > 0:
                model.removeRows(0, row)
Beispiel #28
0
    def load_template(self):
        """Load a QgsComposer map from a template and render it.

        .. note:: THIS METHOD IS EXPERIMENTAL
        """
        self.setup_composition()

        template_file = QtCore.QFile(self.template)
        template_file.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
        template_content = template_file.readAll()
        template_file.close()

        document = QtXml.QDomDocument()
        document.setContent(template_content)

        # get information for substitutions
        # date, time and plugin version
        date_time = self.keyword_io.read_keywords(self.layer, 'time_stamp')
        tokens = date_time.split('_')
        date = tokens[0]
        time = tokens[1]
        long_version = get_version()
        tokens = long_version.split('.')
        version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])

        # map title
        LOGGER.debug('InaSAFE Map getMapTitle called')
        try:
            title = self.keyword_io.read_keywords(self.layer, 'map_title')
        except KeywordNotFoundError:
            title = None
        except Exception:
            title = None

        if not title:
            title = ''

        substitution_map = {
            'impact-title': title,
            'date': date,
            'time': time,
            'safe-version': version
        }
        LOGGER.debug(substitution_map)
        load_ok = self.composition.loadFromTemplate(document, substitution_map)
        if not load_ok:
            raise ReportCreationError(
                self.tr('Error loading template %s') % self.template)

        self.page_width = self.composition.paperWidth()
        self.page_height = self.composition.paperHeight()

        # set logo
        image = self.composition.getComposerItemById('safe-logo')
        image.setPictureFile(self.logo)

        # Get the main map canvas on the composition and set
        # its extents to the event.
        map = self.composition.getComposerItemById('impact-map')
        if map is not None:
            # Recenter the composer map on the center of the canvas
            # Note that since the composer map is square and the canvas may be
            # arbitrarily shaped, we center based on the longest edge
            canvas_extent = self.iface.mapCanvas().extent()
            width = canvas_extent.width()
            height = canvas_extent.height()
            longest_width = width
            if width < height:
                longest_width = height
            half_length = longest_width / 2
            center = canvas_extent.center()
            min_x = center.x() - half_length
            max_x = center.x() + half_length
            min_y = center.y() - half_length
            max_y = center.y() + half_length
            square_extent = QgsRectangle(min_x, min_y, max_x, max_y)
            map.setNewExtent(square_extent)

            # calculate intervals for grid
            split_count = 5
            x_interval = square_extent.width() / split_count
            map.setGridIntervalX(x_interval)
            y_interval = square_extent.height() / split_count
            map.setGridIntervalY(y_interval)
        else:
            raise ReportCreationError(
                self.tr('Map "impact-map" could not be found'))

        legend = self.composition.getComposerItemById('impact-legend')
        legend_attributes = self.map_legend_attributes()
        LOGGER.debug(legend_attributes)
        #legend_notes = mapLegendAttributes.get('legend_notes', None)
        #legend_units = mapLegendAttributes.get('legend_units', None)
        legend_title = legend_attributes.get('legend_title', None)
        if legend_title is None:
            legend_title = ""
        legend.setTitle(legend_title)
        legend.updateLegend()
    def __init__(self, theParent=None, dict_filter=None):
        '''Constructor for the dialog.

                This dialog will show the user impact function documentation.

        Args:
           * theParent - Optional widget to use as parent
        Returns:
           not applicable
        Raises:
           no exceptions explicitly raised
        '''
        QtGui.QDialog.__init__(self, theParent)
        self.parent = theParent
        self.header = None  # for storing html header template
        self.footer = None  # for storing html footer template
        # Set up the user interface from Designer.
        self.setupUi(self)
        self.setWindowTitle(
            self.tr('InaSAFE %1 Impact Functions Browser').arg(get_version()))
        self.no_filter = self.tr('No Filter')
        if dict_filter is None:
            dict_filter = {
                'id': [],
                'title': [],
                'category': [],
                'subcategory': [],
                'layertype': [],
                'datatype': [],
                'unit': []
            }

        self.dict_filter = dict_filter
        self.if_table = None  # for storing impact functions table
        self.showImpactFunctionsTable()
        self.combo_box_content = None  # for storing combo box content
        self.populate_combo_box()
        resetButton = self.myButtonBox.button(QtGui.QDialogButtonBox.Reset)
        QtCore.QObject.connect(resetButton, QtCore.SIGNAL('clicked()'),
                               self.reset_button_clicked)

        # Set up help dialog showing logic.
        self.helpDialog = None
        helpButton = self.myButtonBox.button(QtGui.QDialogButtonBox.Help)
        QtCore.QObject.connect(helpButton, QtCore.SIGNAL('clicked()'),
                               self.showHelp)
        # Combo box change event
        QtCore.QObject.connect(self.comboBox_id,
                               QtCore.SIGNAL('currentIndexChanged(int)'),
                               self.update_table)
        QtCore.QObject.connect(self.comboBox_title,
                               QtCore.SIGNAL('currentIndexChanged(int)'),
                               self.update_table)
        QtCore.QObject.connect(self.comboBox_category,
                               QtCore.SIGNAL('currentIndexChanged(int)'),
                               self.update_table)
        QtCore.QObject.connect(self.comboBox_subcategory,
                               QtCore.SIGNAL('currentIndexChanged(int)'),
                               self.update_table)
        QtCore.QObject.connect(self.comboBox_layertype,
                               QtCore.SIGNAL('currentIndexChanged(int)'),
                               self.update_table)
        QtCore.QObject.connect(self.comboBox_datatype,
                               QtCore.SIGNAL('currentIndexChanged(int)'),
                               self.update_table)
        QtCore.QObject.connect(self.comboBox_unit,
                               QtCore.SIGNAL('currentIndexChanged(int)'),
                               self.update_table)
Beispiel #30
0
def impact_attribution(keywords, inasafe_flag=False):
    """Make a little table for attribution of data sources used in impact.

    :param keywords: A keywords dict for an impact layer.
    :type keywords: dict

    :param inasafe_flag: bool - whether to show a little InaSAFE promotional
        text in the attribution output. Defaults to False.

    :returns: An html snippet containing attribution information for the impact
        layer. If no keywords are present or no appropriate keywords are
        present, None is returned.
    :rtype: safe.messaging.Message
    """
    if keywords is None:
        return None

    join_words = ' - %s ' % tr('sourced from')
    hazard_details = tr('Hazard details')
    hazard_title_keywords = 'hazard_title'
    hazard_source_keywords = 'hazard_source'
    exposure_details = tr('Exposure details')
    exposure_title_keywords = 'exposure_title'
    exposure_source_keyword = 'exposure_source'

    if hazard_title_keywords in keywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        hazard_title = safeTr(keywords[hazard_title_keywords])
    else:
        hazard_title = tr('Hazard layer')

    if hazard_source_keywords in keywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        hazard_source = safeTr(keywords[hazard_source_keywords])
    else:
        hazard_source = tr('an unknown source')

    if exposure_title_keywords in keywords:
        exposure_title = keywords[exposure_title_keywords]
    else:
        exposure_title = tr('Exposure layer')

    if exposure_source_keyword in keywords:
        exposure_source = keywords[exposure_source_keyword]
    else:
        exposure_source = tr('an unknown source')

    report = m.Message()
    report.add(m.Heading(hazard_details, **INFO_STYLE))
    report.add(m.Paragraph(
        hazard_title,
        join_words,
        hazard_source))

    report.add(m.Heading(exposure_details, **INFO_STYLE))
    report.add(m.Paragraph(
        exposure_title,
        join_words,
        exposure_source))

    if inasafe_flag:
        report.add(m.Heading(tr('Software notes'), **INFO_STYLE))
        # noinspection PyUnresolvedReferences
        inasafe_phrase = tr(
            'This report was created using InaSAFE version %s. Visit '
            'http://inasafe.org to get your free copy of this software!'
            'InaSAFE has been jointly developed by BNPB, AusAid/AIFDRR & the '
            'World Bank') % (get_version())

        report.add(m.Paragraph(m.Text(inasafe_phrase)))
    return report
Beispiel #31
0
    def __init__(self, parent, iface, dock=None, layer=None):
        """Constructor for the dialog.

        .. note:: In QtDesigner the advanced editor's predefined keywords
           list should be shown in english always, so when adding entries to
           cboKeyword, be sure to choose :safe_qgis:`Properties<<` and untick
           the :safe_qgis:`translatable` property.

        :param parent: Parent widget of this dialog.
        :type parent: QWidget

        :param iface: Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param dock: Dock widget instance that we can notify of changes to
            the keywords. Optional.
        :type dock: Dock
        """
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr(
            'InaSAFE %s Keywords Editor' % get_version()))
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = dock
        self.defaults = None

        # string constants
        self.global_default_string = metadata.global_default_attribute['name']
        self.do_not_use_string = metadata.do_not_use_attribute['name']
        self.global_default_data = metadata.global_default_attribute['id']
        self.do_not_use_data = metadata.do_not_use_attribute['id']

        if layer is None:
            self.layer = self.iface.activeLayer()
        else:
            self.layer = layer

        self.keyword_io = KeywordIO()

        # note the keys should remain untranslated as we need to write
        # english to the keywords file. The keys will be written as user data
        # in the combo entries.
        # .. seealso:: http://www.voidspace.org.uk/python/odict.html
        self.standard_exposure_list = OrderedDict(
            [('population', self.tr('population')),
             ('structure', self.tr('structure')),
             ('road', self.tr('road')),
             ('Not Set', self.tr('Not Set'))])
        self.standard_hazard_list = OrderedDict(
            [('earthquake [MMI]', self.tr('earthquake [MMI]')),
             ('tsunami [m]', self.tr('tsunami [m]')),
             ('tsunami [wet/dry]', self.tr('tsunami [wet/dry]')),
             ('tsunami [feet]', self.tr('tsunami [feet]')),
             ('flood [m]', self.tr('flood [m]')),
             ('flood [wet/dry]', self.tr('flood [wet/dry]')),
             ('flood [feet]', self.tr('flood [feet]')),
             ('tephra [kg2/m2]', self.tr('tephra [kg2/m2]')),
             ('volcano', self.tr('volcano')),
             ('generic [categorised]', self.tr('generic [categorised]')),
             ('Not Set', self.tr('Not Set'))])

        # noinspection PyUnresolvedReferences
        self.lstKeywords.itemClicked.connect(self.edit_key_value_pair)

        # Set up help dialog showing logic.
        help_button = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        help_button.clicked.connect(self.show_help)

        if self.layer is not None and is_polygon_layer(self.layer):
            # set some initial ui state:
            self.defaults = get_defaults()
            self.radPredefined.setChecked(True)
            self.dsbFemaleRatioDefault.blockSignals(True)
            self.dsbFemaleRatioDefault.setValue(self.defaults['FEMALE_RATIO'])
            self.dsbFemaleRatioDefault.blockSignals(False)

            self.dsbYouthRatioDefault.blockSignals(True)
            self.dsbYouthRatioDefault.setValue(self.defaults['YOUTH_RATIO'])
            self.dsbYouthRatioDefault.blockSignals(False)

            self.dsbAdultRatioDefault.blockSignals(True)
            self.dsbAdultRatioDefault.setValue(self.defaults['ADULT_RATIO'])
            self.dsbAdultRatioDefault.blockSignals(False)

            self.dsbElderlyRatioDefault.blockSignals(True)
            self.dsbElderlyRatioDefault.setValue(
                self.defaults['ELDERLY_RATIO'])
            self.dsbElderlyRatioDefault.blockSignals(False)
        else:
            self.radPostprocessing.hide()
            self.tab_widget.removeTab(1)

        if self.layer:
            self.load_state_from_keywords()

        # add a reload from keywords button
        reload_button = self.buttonBox.addButton(
            self.tr('Reload'), QtGui.QDialogButtonBox.ActionRole)
        reload_button.clicked.connect(self.load_state_from_keywords)
        self.resize_dialog()
        self.tab_widget.setCurrentIndex(0)
        # TODO No we should not have test related stuff in prod code. TS
        self.test = False
Beispiel #32
0
    def load_template(self):
        """Load a QgsComposer map from a template.
        """
        self.setup_composition()

        template_file = QtCore.QFile(self.template)
        template_file.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
        template_content = template_file.readAll()
        template_file.close()

        document = QtXml.QDomDocument()
        document.setContent(template_content)

        # get information for substitutions
        # date, time and plugin version
        date_time = self.keyword_io.read_keywords(self.layer, 'time_stamp')
        if date_time is None:
            date = ''
            time = ''
        else:
            tokens = date_time.split('_')
            date = tokens[0]
            time = tokens[1]
        long_version = get_version()
        tokens = long_version.split('.')
        version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])

        title = self.map_title()
        if not title:
            title = ''

        substitution_map = {
            'impact-title': title,
            'date': date,
            'time': time,
            'safe-version': version,
            'disclaimer': self.disclaimer
        }
        LOGGER.debug(substitution_map)
        load_ok = self.composition.loadFromTemplate(
            document, substitution_map)
        if not load_ok:
            raise ReportCreationError(
                self.tr('Error loading template %s') %
                self.template)

        self.page_width = self.composition.paperWidth()
        self.page_height = self.composition.paperHeight()

        # set InaSAFE logo
        image = self.composition.getComposerItemById('safe-logo')
        if image is not None:
            image.setPictureFile(self.safe_logo)
        else:
            raise ReportCreationError(self.tr(
                'Image "safe-logo" could not be found'))

        # set north arrow
        image = self.composition.getComposerItemById('north-arrow')
        if image is not None:
            image.setPictureFile(self.north_arrow)
        else:
            raise ReportCreationError(self.tr(
                'Image "north arrow" could not be found'))

        # set organisation logo
        image = self.composition.getComposerItemById('organisation-logo')
        if image is not None:
            image.setPictureFile(self.org_logo)
        else:
            raise ReportCreationError(self.tr(
                'Image "organisation-logo" could not be found'))

        # set impact report table
        table = self.composition.getComposerItemById('impact-report')
        if table is not None:
            text = self.keyword_io.read_keywords(self.layer, 'impact_summary')
            if text is None:
                text = ''
            table.setText(text)
            table.setHtmlState(1)
        else:
            LOGGER.debug('"impact-report" element not found.')

        # Get the main map canvas on the composition and set
        # its extents to the event.
        composer_map = self.composition.getComposerItemById('impact-map')
        if composer_map is not None:
            # Recenter the composer map on the center of the extent
            # Note that since the composer map is square and the canvas may be
            # arbitrarily shaped, we center based on the longest edge
            canvas_extent = self.extent
            width = canvas_extent.width()
            height = canvas_extent.height()
            longest_width = width
            if width < height:
                longest_width = height
            half_length = longest_width / 2
            center = canvas_extent.center()
            min_x = center.x() - half_length
            max_x = center.x() + half_length
            min_y = center.y() - half_length
            max_y = center.y() + half_length
            square_extent = QgsRectangle(min_x, min_y, max_x, max_y)
            composer_map.setNewExtent(square_extent)

            # calculate intervals for grid
            split_count = 5
            x_interval = square_extent.width() / split_count
            composer_map.setGridIntervalX(x_interval)
            y_interval = square_extent.height() / split_count
            composer_map.setGridIntervalY(y_interval)
        else:
            raise ReportCreationError(self.tr(
                'Map "impact-map" could not be found'))

        legend = self.composition.getComposerItemById('impact-legend')
        legend_attributes = self.map_legend_attributes()
        LOGGER.debug(legend_attributes)
        #legend_notes = mapLegendAttributes.get('legend_notes', None)
        #legend_units = mapLegendAttributes.get('legend_units', None)
        legend_title = legend_attributes.get('legend_title', None)

        symbol_count = 1
        if self.layer.type() == QgsMapLayer.VectorLayer:
            renderer = self.layer.rendererV2()
            if renderer.type() in ['', '']:
                symbol_count = len(self.layer.legendSymbologyItems())
        else:
            renderer = self.layer.renderer()
            if renderer.type() in ['']:
                symbol_count = len(self.layer.legendSymbologyItems())

        if symbol_count <= 5:
            legend.setColumnCount(1)
        else:
            legend.setColumnCount(symbol_count / 5 + 1)

        if legend_title is None:
            legend_title = ""
        legend.setTitle(legend_title)
        legend.updateLegend()

        # remove from legend all layers, except impact one
        model = legend.model()
        if model.rowCount() > 0 and model.columnCount() > 0:
            impact_item = model.findItems(self.layer.name())[0]
            row = impact_item.index().row()
            model.removeRows(row + 1, model.rowCount() - row)
            if row > 0:
                model.removeRows(0, row)
Beispiel #33
0
def impact_attribution(keywords, inasafe_flag=False):
    """Make a little table for attribution of data sources used in impact.

    :param keywords: A keywords dict for an impact layer.
    :type keywords: dict

    :param inasafe_flag: bool - whether to show a little InaSAFE promotional
        text in the attribution output. Defaults to False.

    :returns: An html snippet containing attribution information for the impact
        layer. If no keywords are present or no appropriate keywords are
        present, None is returned.
    :rtype: str
    """
    if keywords is None:
        return None

    myJoinWords = ' - %s ' % tr('sourced from')
    myHazardDetails = tr('Hazard details')
    myHazardTitleKeyword = 'hazard_title'
    myHazardSourceKeyword = 'hazard_source'
    myExposureDetails = tr('Exposure details')
    myExposureTitleKeyword = 'exposure_title'
    myExposureSourceKeyword = 'exposure_source'

    if myHazardTitleKeyword in keywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        myHazardTitle = safeTr(keywords[myHazardTitleKeyword])
    else:
        myHazardTitle = tr('Hazard layer')

    if myHazardSourceKeyword in keywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        myHazardSource = safeTr(keywords[myHazardSourceKeyword])
    else:
        myHazardSource = tr('an unknown source')

    if myExposureTitleKeyword in keywords:
        myExposureTitle = keywords[myExposureTitleKeyword]
    else:
        myExposureTitle = tr('Exposure layer')

    if myExposureSourceKeyword in keywords:
        myExposureSource = keywords[myExposureSourceKeyword]
    else:
        myExposureSource = tr('an unknown source')

    myReport = m.Message()
    myReport.add(m.Heading(myHazardDetails, **INFO_STYLE))
    myReport.add(m.Paragraph(
        myHazardTitle,
        myJoinWords,
        myHazardSource))

    myReport.add(m.Heading(myExposureDetails, **INFO_STYLE))
    myReport.add(m.Paragraph(
        myExposureTitle,
        myJoinWords,
        myExposureSource))

    if inasafe_flag:
        myReport.add(m.Heading(tr('Software notes'), **INFO_STYLE))
        myInaSAFEPhrase = tr(
            'This report was created using InaSAFE version %1. Visit '
            'http://inasafe.org to get your free copy of this software!'
            'InaSAFE has been jointly developed by BNPB, AusAid/AIFDRR & the '
            'World Bank').arg(get_version())

        myReport.add(m.Paragraph(m.Text(myInaSAFEPhrase)))
    return myReport
Beispiel #34
0
def impactLayerAttribution(theKeywords, theInaSAFEFlag=False):
    """Make a little table for attribution of data sources used in impact.

    Args:
        * theKeywords: dict{} - a keywords dict for an impact layer.
        * theInaSAFEFlag: bool - whether to show a little InaSAFE promotional
            text in the attribution output. Defaults to False.

    Returns:
        str: an html snippet containing attribution information for the impact
            layer. If no keywords are present or no appropriate keywords are
            present, None is returned.

    Raises:
        None
    """
    if theKeywords is None:
        return None
    myReport = ''
    myJoinWords = ' - %s ' % tr('sourced from')
    myHazardDetails = tr('Hazard details')
    myHazardTitleKeyword = 'hazard_title'
    myHazardSourceKeyword = 'hazard_source'
    myExposureDetails = tr('Exposure details')
    myExposureTitleKeyword = 'exposure_title'
    myExposureSourceKeyword = 'exposure_source'

    if myHazardTitleKeyword in theKeywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        myHazardTitle = safeTr(theKeywords[myHazardTitleKeyword])
    else:
        myHazardTitle = tr('Hazard layer')

    if myHazardSourceKeyword in theKeywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        myHazardSource = safeTr(theKeywords[myHazardSourceKeyword])
    else:
        myHazardSource = tr('an unknown source')

    if myExposureTitleKeyword in theKeywords:
        myExposureTitle = theKeywords[myExposureTitleKeyword]
    else:
        myExposureTitle = tr('Exposure layer')

    if myExposureSourceKeyword in theKeywords:
        myExposureSource = theKeywords[myExposureSourceKeyword]
    else:
        myExposureSource = tr('an unknown source')

    myReport += ('<table class="table table-striped condensed'
                 ' bordered-table">')
    myReport += '<tr><th>%s</th></tr>' % myHazardDetails
    myReport += '<tr><td>%s%s %s.</td></tr>' % (myHazardTitle, myJoinWords,
                                                myHazardSource)

    myReport += '<tr><th>%s</th></tr>' % myExposureDetails
    myReport += '<tr><td>%s%s %s.</td></tr>' % (myExposureTitle, myJoinWords,
                                                myExposureSource)

    if theInaSAFEFlag:
        myReport += '<tr><th>%s</th></tr>' % tr('Software notes')
        myInaSAFEPhrase = tr('This report was created using InaSAFE '
                             'version %1. Visit http://inasafe.org to get '
                             'your free copy of this software!').arg(
                                 get_version())
        myInaSAFEPhrase += tr('InaSAFE has been jointly developed by'
                              ' BNPB, AusAid & the World Bank')
        myReport += '<tr><td>%s</td></tr>' % myInaSAFEPhrase

    myReport += '</table>'

    return myReport
    def __init__(self, parent, iface, dock=None, layer=None):
        """Constructor for the dialog.

        .. note:: In QtDesigner the advanced editor's predefined keywords
           list should be shown in english always, so when adding entries to
           cboKeyword, be sure to choose :safe_qgis:`Properties<<` and untick
           the :safe_qgis:`translatable` property.

        :param parent: Parent widget of this dialog.
        :type parent: QWidget

        :param iface: Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param dock: Dock widget instance that we can notify of changes to
            the keywords. Optional.
        :type dock: Dock
        """
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(
            self.tr('InaSAFE %s Keywords Editor' % get_version()))
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = dock
        self.defaults = None

        # string constants
        self.global_default_string = metadata.global_default_attribute['name']
        self.do_not_use_string = metadata.do_not_use_attribute['name']
        self.global_default_data = metadata.global_default_attribute['id']
        self.do_not_use_data = metadata.do_not_use_attribute['id']

        if layer is None:
            self.layer = self.iface.activeLayer()
        else:
            self.layer = layer

        self.keyword_io = KeywordIO()

        # note the keys should remain untranslated as we need to write
        # english to the keywords file. The keys will be written as user data
        # in the combo entries.
        # .. seealso:: http://www.voidspace.org.uk/python/odict.html
        self.standard_exposure_list = OrderedDict([
            ('population', self.tr('population')),
            ('structure', self.tr('structure')), ('road', self.tr('road')),
            ('Not Set', self.tr('Not Set'))
        ])
        self.standard_hazard_list = OrderedDict([
            ('earthquake [MMI]', self.tr('earthquake [MMI]')),
            ('tsunami [m]', self.tr('tsunami [m]')),
            ('tsunami [wet/dry]', self.tr('tsunami [wet/dry]')),
            ('tsunami [feet]', self.tr('tsunami [feet]')),
            ('flood [m]', self.tr('flood [m]')),
            ('flood [wet/dry]', self.tr('flood [wet/dry]')),
            ('flood [feet]', self.tr('flood [feet]')),
            ('tephra [kg2/m2]', self.tr('tephra [kg2/m2]')),
            ('volcano', self.tr('volcano')),
            ('generic [categorised]', self.tr('generic [categorised]')),
            ('Not Set', self.tr('Not Set'))
        ])

        # noinspection PyUnresolvedReferences
        self.lstKeywords.itemClicked.connect(self.edit_key_value_pair)

        # Set up help dialog showing logic.
        help_button = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        help_button.clicked.connect(self.show_help)

        if self.layer is not None and is_polygon_layer(self.layer):
            # set some initial ui state:
            self.defaults = get_defaults()
            self.radPredefined.setChecked(True)
            self.dsbFemaleRatioDefault.blockSignals(True)
            self.dsbFemaleRatioDefault.setValue(self.defaults['FEMALE_RATIO'])
            self.dsbFemaleRatioDefault.blockSignals(False)

            self.dsbYouthRatioDefault.blockSignals(True)
            self.dsbYouthRatioDefault.setValue(self.defaults['YOUTH_RATIO'])
            self.dsbYouthRatioDefault.blockSignals(False)

            self.dsbAdultRatioDefault.blockSignals(True)
            self.dsbAdultRatioDefault.setValue(self.defaults['ADULT_RATIO'])
            self.dsbAdultRatioDefault.blockSignals(False)

            self.dsbElderlyRatioDefault.blockSignals(True)
            self.dsbElderlyRatioDefault.setValue(
                self.defaults['ELDERLY_RATIO'])
            self.dsbElderlyRatioDefault.blockSignals(False)
        else:
            self.radPostprocessing.hide()
            self.tab_widget.removeTab(1)

        if self.layer:
            self.load_state_from_keywords()

        # add a reload from keywords button
        reload_button = self.buttonBox.addButton(
            self.tr('Reload'), QtGui.QDialogButtonBox.ActionRole)
        reload_button.clicked.connect(self.load_state_from_keywords)
        self.resize_dialog()
        self.tab_widget.setCurrentIndex(0)
        # TODO No we should not have test related stuff in prod code. TS
        self.test = False
Beispiel #36
0
    def __init__(self, parent, iface, theDock=None, theLayer=None):
        """Constructor for the dialog.
        .. note:: In QtDesigner the advanced editor's predefined keywords
           list should be shown in english always, so when adding entries to
           cboKeyword, be sure to choose :safe_qgis:`Properties<<` and untick
           the :safe_qgis:`translatable` property.

        Args:
           * parent - parent widget of this dialog
           * iface - a Quantum GIS QGisAppInterface instance.
           * theDock - Optional dock widget instance that we can notify of
             changes to the keywords.

        Returns:
           not applicable
        Raises:
           no exceptions explicitly raised
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr(
            'InaSAFE %1 Keywords Editor').arg(get_version()))
        self.keywordIO = KeywordIO()
        # note the keys should remain untranslated as we need to write
        # english to the keywords file. The keys will be written as user data
        # in the combo entries.
        # .. seealso:: http://www.voidspace.org.uk/python/odict.html
        self.standardExposureList = OrderedDict([('population',
                                      self.tr('population')),
                                     ('structure', self.tr('structure')),
                                     ('road', self.tr('road')),
                                     ('Not Set', self.tr('Not Set'))])
        self.standardHazardList = OrderedDict([('earthquake [MMI]',
                                    self.tr('earthquake [MMI]')),
                                   ('tsunami [m]', self.tr('tsunami [m]')),
                                   ('tsunami [wet/dry]',
                                    self.tr('tsunami [wet/dry]')),
                                   ('tsunami [feet]',
                                    self.tr('tsunami [feet]')),
                                   ('flood [m]', self.tr('flood [m]')),
                                   ('flood [wet/dry]',
                                    self.tr('flood [wet/dry]')),
                                   ('flood [feet]', self.tr('flood [feet]')),
                                   ('tephra [kg2/m2]',
                                    self.tr('tephra [kg2/m2]')),
                                   ('volcano', self.tr('volcano')),
                                   ('Not Set', self.tr('Not Set'))])
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = theDock

        QtCore.QObject.connect(self.lstKeywords,
                               QtCore.SIGNAL("itemClicked(QListWidgetItem *)"),
                               self.makeKeyValueEditable)

        # Set up help dialog showing logic.
        self.helpDialog = None
        myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
                               self.showHelp)

        # set some inital ui state:
        self.defaults = getDefaults()
        self.pbnAdvanced.setChecked(True)
        self.pbnAdvanced.toggle()
        self.radPredefined.setChecked(True)
        self.dsbFemaleRatioDefault.blockSignals(True)
        self.dsbFemaleRatioDefault.setValue(self.defaults[
                                            'FEM_RATIO'])
        self.dsbFemaleRatioDefault.blockSignals(False)
        #myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        #myButton.setEnabled(False)
        if theLayer is None:
            self.layer = self.iface.activeLayer()
        else:
            self.layer = theLayer
        if self.layer:
            self.loadStateFromKeywords()

        #add a reload from keywords button
        myButton = self.buttonBox.addButton(self.tr('Reload'),
                                            QtGui.QDialogButtonBox.ActionRole)
        QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
                               self.loadStateFromKeywords)
Beispiel #37
0
    def __init__(self, parent, iface, dock=None, layer=None):
        """Constructor for the dialog.

        .. note:: In QtDesigner the advanced editor's predefined keywords
           list should be shown in english always, so when adding entries to
           cboKeyword, be sure to choose :safe_qgis:`Properties<<` and untick
           the :safe_qgis:`translatable` property.

        :param parent: Parent widget of this dialog.
        :type parent: QWidget

        :param iface: Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param dock: Dock widget instance that we can notify of changes to
            the keywords. Optional.
        :type dock: Dock
        """
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(
            self.tr('InaSAFE %s Keywords Editor' % get_version()))
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = dock

        if layer is None:
            self.layer = iface.activeLayer()
        else:
            self.layer = layer

        self.keyword_io = KeywordIO()

        # note the keys should remain untranslated as we need to write
        # english to the keywords file. The keys will be written as user data
        # in the combo entries.
        # .. seealso:: http://www.voidspace.org.uk/python/odict.html
        self.standard_exposure_list = OrderedDict([
            ('population', self.tr('population')),
            ('structure', self.tr('structure')), ('road', self.tr('road')),
            ('Not Set', self.tr('Not Set'))
        ])
        self.standard_hazard_list = OrderedDict([
            ('earthquake [MMI]', self.tr('earthquake [MMI]')),
            ('tsunami [m]', self.tr('tsunami [m]')),
            ('tsunami [wet/dry]', self.tr('tsunami [wet/dry]')),
            ('tsunami [feet]', self.tr('tsunami [feet]')),
            ('flood [m]', self.tr('flood [m]')),
            ('flood [wet/dry]', self.tr('flood [wet/dry]')),
            ('flood [feet]', self.tr('flood [feet]')),
            ('tephra [kg2/m2]', self.tr('tephra [kg2/m2]')),
            ('volcano', self.tr('volcano')), ('Not Set', self.tr('Not Set'))
        ])

        self.lstKeywords.itemClicked.connect(self.edit_key_value_pair)

        # Set up help dialog showing logic.
        help_button = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        help_button.clicked.connect(self.show_help)

        # set some initial ui state:
        self.defaults = breakdown_defaults()
        self.pbnAdvanced.setChecked(False)
        self.radPredefined.setChecked(True)
        self.dsbFemaleRatioDefault.blockSignals(True)
        self.dsbFemaleRatioDefault.setValue(self.defaults['FEM_RATIO'])
        self.dsbFemaleRatioDefault.blockSignals(False)

        if self.layer:
            self.load_state_from_keywords()

        # add a reload from keywords button
        reload_button = self.buttonBox.addButton(
            self.tr('Reload'), QtGui.QDialogButtonBox.ActionRole)
        reload_button.clicked.connect(self.load_state_from_keywords)
        self.grpAdvanced.setVisible(False)
        self.resize_dialog()
Beispiel #38
0
    def __init__(self, parent, iface, theDock=None, theLayer=None):
        """Constructor for the dialog.
        .. note:: In QtDesigner the advanced editor's predefined keywords
           list should be shown in english always, so when adding entries to
           cboKeyword, be sure to choose :safe_qgis:`Properties<<` and untick
           the :safe_qgis:`translatable` property.

        Args:
           * parent - parent widget of this dialog
           * iface - a Quantum GIS QGisAppInterface instance.
           * theDock - Optional dock widget instance that we can notify of
             changes to the keywords.

        Returns:
           not applicable
        Raises:
           no exceptions explicitly raised
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr(
            'InaSAFE %1 Keywords Editor').arg(get_version()))
        self.keywordIO = KeywordIO()
        # note the keys should remain untranslated as we need to write
        # english to the keywords file. The keys will be written as user data
        # in the combo entries.
        # .. seealso:: http://www.voidspace.org.uk/python/odict.html
        self.standardExposureList = OrderedDict([('population',
                                      self.tr('population')),
                                     ('structure', self.tr('structure')),
                                     ('road', self.tr('road')),
                                     ('Not Set', self.tr('Not Set'))])
        self.standardHazardList = OrderedDict([('earthquake [MMI]',
                                    self.tr('earthquake [MMI]')),
                                   ('tsunami [m]', self.tr('tsunami [m]')),
                                   ('tsunami [wet/dry]',
                                    self.tr('tsunami [wet/dry]')),
                                   ('tsunami [feet]',
                                    self.tr('tsunami [feet]')),
                                   ('flood [m]', self.tr('flood [m]')),
                                   ('flood [wet/dry]',
                                    self.tr('flood [wet/dry]')),
                                   ('flood [feet]', self.tr('flood [feet]')),
                                   ('tephra [kg2/m2]',
                                    self.tr('tephra [kg2/m2]')),
                                   ('volcano', self.tr('volcano')),
                                   ('Not Set', self.tr('Not Set'))])
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = theDock

        QtCore.QObject.connect(self.lstKeywords,
                               QtCore.SIGNAL("itemClicked(QListWidgetItem *)"),
                               self.makeKeyValueEditable)

        # Set up help dialog showing logic.
        self.helpDialog = None
        myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
                               self.showHelp)

        # set some inital ui state:
        self.defaults = getDefaults()
        self.pbnAdvanced.setChecked(True)
        self.pbnAdvanced.toggle()
        self.radPredefined.setChecked(True)
        self.dsbFemaleRatioDefault.blockSignals(True)
        self.dsbFemaleRatioDefault.setValue(self.defaults[
                                            'FEM_RATIO'])
        self.dsbFemaleRatioDefault.blockSignals(False)
        #myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        #myButton.setEnabled(False)
        if theLayer is None:
            self.layer = self.iface.activeLayer()
        else:
            self.layer = theLayer
        if self.layer:
            self.loadStateFromKeywords()

        #add a reload from keywords button
        myButton = self.buttonBox.addButton(self.tr('Reload'),
                                            QtGui.QDialogButtonBox.ActionRole)
        QtCore.QObject.connect(myButton, QtCore.SIGNAL('clicked()'),
                               self.loadStateFromKeywords)
Beispiel #39
0
    def load_template(self):
        """Load a QgsComposer map from a template and render it.

        .. note:: THIS METHOD IS EXPERIMENTAL
        """
        self.setup_composition()

        template_file = QtCore.QFile(self.template)
        template_file.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
        template_content = template_file.readAll()
        template_file.close()

        document = QtXml.QDomDocument()
        document.setContent(template_content)

        # get information for substitutions
        # date, time and plugin version
        date_time = self.keyword_io.read_keywords(self.layer, 'time_stamp')
        tokens = date_time.split('_')
        date = tokens[0]
        time = tokens[1]
        long_version = get_version()
        tokens = long_version.split('.')
        version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])

        # map title
        LOGGER.debug('InaSAFE Map getMapTitle called')
        try:
            title = self.keyword_io.read_keywords(self.layer, 'map_title')
        except KeywordNotFoundError:
            title = None
        except Exception:
            title = None

        if not title:
            title = ''

        substitution_map = {
            'impact-title': title,
            'date': date,
            'time': time,
            'safe-version': version
        }
        LOGGER.debug(substitution_map)
        load_ok = self.composition.loadFromTemplate(document,
                                                    substitution_map)
        if not load_ok:
            raise ReportCreationError(
                self.tr('Error loading template %s') %
                self.template)

        self.page_width = self.composition.paperWidth()
        self.page_height = self.composition.paperHeight()

        # set logo
        image = self.composition.getComposerItemById('safe-logo')
        image.setPictureFile(self.logo)

        # Get the main map canvas on the composition and set
        # its extents to the event.
        map = self.composition.getComposerItemById('impact-map')
        if map is not None:
            # Recenter the composer map on the center of the canvas
            # Note that since the composer map is square and the canvas may be
            # arbitrarily shaped, we center based on the longest edge
            canvas_extent = self.iface.mapCanvas().extent()
            width = canvas_extent.width()
            height = canvas_extent.height()
            longest_width = width
            if width < height:
                longest_width = height
            half_length = longest_width / 2
            center = canvas_extent.center()
            min_x = center.x() - half_length
            max_x = center.x() + half_length
            min_y = center.y() - half_length
            max_y = center.y() + half_length
            square_extent = QgsRectangle(min_x, min_y, max_x, max_y)
            map.setNewExtent(square_extent)

            # calculate intervals for grid
            split_count = 5
            x_interval = square_extent.width() / split_count
            map.setGridIntervalX(x_interval)
            y_interval = square_extent.height() / split_count
            map.setGridIntervalY(y_interval)
        else:
            raise ReportCreationError(self.tr(
                'Map "impact-map" could not be found'))

        legend = self.composition.getComposerItemById('impact-legend')
        legend_attributes = self.map_legend_attributes()
        LOGGER.debug(legend_attributes)
        #legend_notes = mapLegendAttributes.get('legend_notes', None)
        #legend_units = mapLegendAttributes.get('legend_units', None)
        legend_title = legend_attributes.get('legend_title', None)
        if legend_title is None:
            legend_title = ""
        legend.setTitle(legend_title)
        legend.updateLegend()
    def __init__(self, parent, iface, dock=None, layer=None):
        """Constructor for the dialog.

        .. note:: In QtDesigner the advanced editor's predefined keywords
           list should be shown in english always, so when adding entries to
           cboKeyword, be sure to choose :safe_qgis:`Properties<<` and untick
           the :safe_qgis:`translatable` property.

        :param parent: Parent widget of this dialog.
        :type parent: QWidget

        :param iface: Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param dock: Dock widget instance that we can notify of changes to
            the keywords. Optional.
        :type dock: Dock
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowTitle(self.tr("InaSAFE %s Keywords Editor") % (get_version()))
        self.keywordIO = KeywordIO()
        # note the keys should remain untranslated as we need to write
        # english to the keywords file. The keys will be written as user data
        # in the combo entries.
        # .. seealso:: http://www.voidspace.org.uk/python/odict.html
        self.standardExposureList = OrderedDict(
            [
                ("population", self.tr("population")),
                ("structure", self.tr("structure")),
                ("Not Set", self.tr("Not Set")),
            ]
        )
        self.standardHazardList = OrderedDict(
            [
                ("earthquake [MMI]", self.tr("earthquake [MMI]")),
                ("tsunami [m]", self.tr("tsunami [m]")),
                ("tsunami [wet/dry]", self.tr("tsunami [wet/dry]")),
                ("tsunami [feet]", self.tr("tsunami [feet]")),
                ("flood [m]", self.tr("flood [m]")),
                ("flood [wet/dry]", self.tr("flood [wet/dry]")),
                ("flood [feet]", self.tr("flood [feet]")),
                ("tephra [kg2/m2]", self.tr("tephra [kg2/m2]")),
                ("volcano", self.tr("volcano")),
                ("Not Set", self.tr("Not Set")),
            ]
        )
        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = dock

        self.lstKeywords.itemClicked.connect(self.edit_key_value_pair)

        # Set up help dialog showing logic.
        self.helpDialog = None
        helpButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        helpButton.clicked.connect(self.show_help)

        # set some inital ui state:
        self.defaults = breakdown_defaults()
        self.pbnAdvanced.setChecked(True)
        self.pbnAdvanced.toggle()
        self.radPredefined.setChecked(True)
        self.dsbFemaleRatioDefault.blockSignals(True)
        self.dsbFemaleRatioDefault.setValue(self.defaults["FEM_RATIO"])
        self.dsbFemaleRatioDefault.blockSignals(False)
        # myButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        # myButton.setEnabled(False)
        if layer is None:
            self.layer = self.iface.activeLayer()
        else:
            self.layer = layer
        if self.layer:
            self.load_state_from_keywords()

        # add a reload from keywords button
        reloadButton = self.buttonBox.addButton(self.tr("Reload"), QtGui.QDialogButtonBox.ActionRole)
        reloadButton.clicked.connect(self.load_state_from_keywords)
Beispiel #41
0
def impactLayerAttribution(theKeywords, theInaSAFEFlag=False):
    """Make a little table for attribution of data sources used in impact.

    Args:
        * theKeywords: dict{} - a keywords dict for an impact layer.
        * theInaSAFEFlag: bool - whether to show a little InaSAFE promotional
            text in the attribution output. Defaults to False.

    Returns:
        str: an html snippet containing attribution information for the impact
            layer. If no keywords are present or no appropriate keywords are
            present, None is returned.

    Raises:
        None
    """
    if theKeywords is None:
        return None
    myReport = ''
    myJoinWords = ' - %s ' % tr('sourced from')
    myHazardDetails = tr('Hazard details')
    myHazardTitleKeyword = 'hazard_title'
    myHazardSourceKeyword = 'hazard_source'
    myExposureDetails = tr('Exposure details')
    myExposureTitleKeyword = 'exposure_title'
    myExposureSourceKeyword = 'exposure_source'

    if myHazardTitleKeyword in theKeywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        myHazardTitle = safeTr(theKeywords[myHazardTitleKeyword])
    else:
        myHazardTitle = tr('Hazard layer')

    if myHazardSourceKeyword in theKeywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        myHazardSource = safeTr(theKeywords[myHazardSourceKeyword])
    else:
        myHazardSource = tr('an unknown source')

    if myExposureTitleKeyword in theKeywords:
        myExposureTitle = theKeywords[myExposureTitleKeyword]
    else:
        myExposureTitle = tr('Exposure layer')

    if myExposureSourceKeyword in theKeywords:
        myExposureSource = theKeywords[myExposureSourceKeyword]
    else:
        myExposureSource = tr('an unknown source')

    myReport += ('<table class="table table-striped condensed'
                 ' bordered-table">')
    myReport += '<tr><th>%s</th></tr>' % myHazardDetails
    myReport += '<tr><td>%s%s %s.</td></tr>' % (
        myHazardTitle,
        myJoinWords,
        myHazardSource)

    myReport += '<tr><th>%s</th></tr>' % myExposureDetails
    myReport += '<tr><td>%s%s %s.</td></tr>' % (
        myExposureTitle,
        myJoinWords,
        myExposureSource)

    if theInaSAFEFlag:
        myReport += '<tr><th>%s</th></tr>' % tr('Software notes')
        myInaSAFEPhrase = tr('This report was created using InaSAFE '
                              'version %1. Visit http://inasafe.org to get '
                              'your free copy of this software!').arg(
                                get_version())
        myInaSAFEPhrase += tr('InaSAFE has been jointly developed by'
                               ' BNPB, AusAid & the World Bank')
        myReport += '<tr><td>%s</td></tr>' % myInaSAFEPhrase

    myReport += '</table>'

    return myReport
Beispiel #42
0
def impact_attribution(keywords, inasafe_flag=False):
    """Make a little table for attribution of data sources used in impact.

    :param keywords: A keywords dict for an impact layer.
    :type keywords: dict

    :param inasafe_flag: bool - whether to show a little InaSAFE promotional
        text in the attribution output. Defaults to False.

    :returns: An html snippet containing attribution information for the impact
        layer. If no keywords are present or no appropriate keywords are
        present, None is returned.
    :rtype: str
    """
    if keywords is None:
        return None

    myJoinWords = ' - %s ' % tr('sourced from')
    myHazardDetails = tr('Hazard details')
    myHazardTitleKeyword = 'hazard_title'
    myHazardSourceKeyword = 'hazard_source'
    myExposureDetails = tr('Exposure details')
    myExposureTitleKeyword = 'exposure_title'
    myExposureSourceKeyword = 'exposure_source'

    if myHazardTitleKeyword in keywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        myHazardTitle = safeTr(keywords[myHazardTitleKeyword])
    else:
        myHazardTitle = tr('Hazard layer')

    if myHazardSourceKeyword in keywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        myHazardSource = safeTr(keywords[myHazardSourceKeyword])
    else:
        myHazardSource = tr('an unknown source')

    if myExposureTitleKeyword in keywords:
        myExposureTitle = keywords[myExposureTitleKeyword]
    else:
        myExposureTitle = tr('Exposure layer')

    if myExposureSourceKeyword in keywords:
        myExposureSource = keywords[myExposureSourceKeyword]
    else:
        myExposureSource = tr('an unknown source')

    myReport = m.Message()
    myReport.add(m.Heading(myHazardDetails, **INFO_STYLE))
    myReport.add(m.Paragraph(myHazardTitle, myJoinWords, myHazardSource))

    myReport.add(m.Heading(myExposureDetails, **INFO_STYLE))
    myReport.add(m.Paragraph(myExposureTitle, myJoinWords, myExposureSource))

    if inasafe_flag:
        myReport.add(m.Heading(tr('Software notes'), **INFO_STYLE))
        myInaSAFEPhrase = tr(
            'This report was created using InaSAFE version %1. Visit '
            'http://inasafe.org to get your free copy of this software!'
            'InaSAFE has been jointly developed by BNPB, AusAid/AIFDRR & the '
            'World Bank').arg(get_version())

        myReport.add(m.Paragraph(m.Text(myInaSAFEPhrase)))
    return myReport
Beispiel #43
0
def impact_attribution(keywords, inasafe_flag=False):
    """Make a little table for attribution of data sources used in impact.

    :param keywords: A keywords dict for an impact layer.
    :type keywords: dict

    :param inasafe_flag: bool - whether to show a little InaSAFE promotional
        text in the attribution output. Defaults to False.

    :returns: An html snippet containing attribution information for the impact
        layer. If no keywords are present or no appropriate keywords are
        present, None is returned.
    :rtype: safe.messaging.Message
    """
    if keywords is None:
        return None

    join_words = ' - %s ' % tr('sourced from')
    hazard_details = tr('Hazard details')
    hazard_title_keywords = 'hazard_title'
    hazard_source_keywords = 'hazard_source'
    exposure_details = tr('Exposure details')
    exposure_title_keywords = 'exposure_title'
    exposure_source_keyword = 'exposure_source'

    if hazard_title_keywords in keywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        hazard_title = safeTr(keywords[hazard_title_keywords])
    else:
        hazard_title = tr('Hazard layer')

    if hazard_source_keywords in keywords:
        # We use safe translation infrastructure for this one (rather than Qt)
        hazard_source = safeTr(keywords[hazard_source_keywords])
    else:
        hazard_source = tr('an unknown source')

    if exposure_title_keywords in keywords:
        exposure_title = keywords[exposure_title_keywords]
    else:
        exposure_title = tr('Exposure layer')

    if exposure_source_keyword in keywords:
        exposure_source = keywords[exposure_source_keyword]
    else:
        exposure_source = tr('an unknown source')

    report = m.Message()
    report.add(m.Heading(hazard_details, **INFO_STYLE))
    report.add(m.Paragraph(hazard_title, join_words, hazard_source))

    report.add(m.Heading(exposure_details, **INFO_STYLE))
    report.add(m.Paragraph(exposure_title, join_words, exposure_source))

    if inasafe_flag:
        report.add(m.Heading(tr('Software notes'), **INFO_STYLE))
        # noinspection PyUnresolvedReferences
        inasafe_phrase = tr(
            'This report was created using InaSAFE version %s. Visit '
            'http://inasafe.org to get your free copy of this software!'
            'InaSAFE has been jointly developed by BNPB, AusAid/AIFDRR & the '
            'World Bank') % (get_version())

        report.add(m.Paragraph(m.Text(inasafe_phrase)))
    return report