Пример #1
0
def action_checklist_report_extractor(impact_report, component_metadata):
    """Extracting action checklist of the impact layer to its own report.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.1
    """
    context = {}
    extra_args = component_metadata.extra_args

    components_list = resolve_from_dictionary(
        extra_args, 'components_list')

    context['brand_logo'] = resource_url(
        resources_path('img', 'logos', 'inasafe-logo-white.png'))
    for key, component in list(components_list.items()):
        context[key] = jinja2_output_as_string(
            impact_report, component['key'])

    context['inasafe_resources_base_dir'] = resources_path()

    return context
Пример #2
0
    def on_lstSubcategories_itemSelectionChanged(self):
        """Update subcategory description label.

        .. note:: This is an automatic Qt slot
           executed when the subcategory selection changes.
        """
        self.clear_further_steps()
        # Set widgets
        subcategory = self.selected_subcategory()
        # Exit if no selection
        if not subcategory:
            return
        # Set description label
        self.lblDescribeSubcategory.setText(subcategory['description'])

        icon_path = resources_path('img', 'wizard',
                                   'keyword-subcategory-%s.svg'
                                   % (subcategory['key'] or 'notset'))
        if not os.path.exists(icon_path):
            purpose = self.parent.step_kw_purpose.selected_purpose()
            icon_path = resources_path('img', 'wizard',
                                       'keyword-category-%s.svg'
                                       % (purpose['key']))
        self.lblIconSubcategory.setPixmap(QPixmap(icon_path))
        # Enable the next button
        self.parent.pbnNext.setEnabled(True)
Пример #3
0
def content():
    """Helper method that returns just the content.

    This method was added so that the text could be reused in the
    dock_help module.

    .. versionadded:: 4.1.0

    :returns: A message object without brand element.
    :rtype: safe.messaging.message.Message
    """
    message = m.Message()
    paragraph = m.Paragraph(
        m.Image(
            'file:///%s/img/screenshots/'
            'field-mapping-tool-screenshot.png' % resources_path()),
        style_class='text-center'
    )
    message.add(paragraph)

    paragraph = m.Paragraph(tr(
        'This tool allows you to define field mappings to use for demographic '
        'breakdowns of your analysis results. You can activate the '
        'tool on the InaSAFE toolbar:'),
        m.Image(
            'file:///%s/img/icons/'
            'show-mapping-tool.svg' % resources_path(),
            **SMALL_ICON_STYLE),

    )
    message.add(paragraph)
    message.add(field_mapping_help_content())
    return message
    def test_print_default_template(self):
        """Test printing report to pdf using default template works."""
        impact_layer_path = test_data_path(
            'impact', 'population_affected_entire_area.shp')
        layer, _ = load_layer(impact_layer_path)
        # noinspection PyUnresolvedReferences
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        # noinspection PyCallingNonCallable
        rect = QgsRectangle(106.8194, -6.2108, 106.8201, -6.1964)
        CANVAS.setExtent(rect)
        CANVAS.refresh()

        template = resources_path(
            'qgis-composer-templates', 'inasafe-portrait-a4.qpt')
        report = ImpactReport(IFACE, template, layer)
        out_path = unique_filename(
            prefix='map_default_template_test',
            suffix='.pdf',
            dir=temp_dir('test'))
        report.print_map_to_pdf(out_path)

        # Check the file exists
        message = 'Rendered output does not exist: %s' % out_path
        self.assertTrue(os.path.exists(out_path), message)

        # Check the file is not corrupt
        message = 'The output file %s is corrupt' % out_path
        out_size = os.stat(out_path).st_size
        self.assertTrue(out_size > 0, message)

        # Check the components in composition are default components
        if qgis_version() < 20500:
            safe_logo = report.composition.getComposerItemById(
                'safe-logo').pictureFile()
            north_arrow = report.composition.getComposerItemById(
                'north-arrow').pictureFile()
            org_logo = report.composition.getComposerItemById(
                'organisation-logo').pictureFile()
        else:
            safe_logo = report.composition.getComposerItemById(
                'safe-logo').picturePath()
            north_arrow = report.composition.getComposerItemById(
                'north-arrow').picturePath()
            org_logo = report.composition.getComposerItemById(
                'organisation-logo').picturePath()

        expected_safe_logo = resources_path(
            'img', 'logos', 'inasafe-logo-url.svg')
        expected_north_arrow = resources_path(
            'img', 'north_arrows', 'simple_north_arrow.png')
        expected_org_logo = resources_path('img', 'logos', 'supporters.png')

        message = 'The safe logo path is not the default one'
        self.assertEqual(expected_safe_logo, safe_logo, message)

        message = 'The north arrow path is not the default one'
        self.assertEqual(expected_north_arrow, north_arrow, message)

        message = 'The organisation logo path is not the default one'
        self.assertEqual(expected_org_logo, org_logo, message)
Пример #5
0
    def populate_function_table_1(self):
        """Populate the tblFunctions1 table with available functions."""
        # The hazard category radio buttons are now removed -
        # make this parameter of IFM.available_hazards() optional
        hazard_category = hazard_category_single_event
        hazards = self.impact_function_manager\
            .available_hazards(hazard_category['key'])
        # Remove 'generic' from hazards
        for h in hazards:
            if h['key'] == 'generic':
                hazards.remove(h)
        exposures = self.impact_function_manager.available_exposures()

        self.lblAvailableFunctions1.clear()
        self.tblFunctions1.clear()
        self.tblFunctions1.setColumnCount(len(hazards))
        self.tblFunctions1.setRowCount(len(exposures))
        for i in range(len(hazards)):
            h = hazards[i]
            item = QtGui.QTableWidgetItem()
            item.setIcon(QtGui.QIcon(
                resources_path('img', 'wizard', 'keyword-subcategory-%s.svg'
                               % (h['key'] or 'notset'))))
            item.setText(h['name'].capitalize())
            self.tblFunctions1.setHorizontalHeaderItem(i, item)
        for i in range(len(exposures)):
            e = exposures[i]
            item = QtGui.QTableWidgetItem()

            item.setIcon(QtGui.QIcon(resources_path(
                'img', 'wizard', 'keyword-subcategory-%s.svg'
                % (e['key'] or 'notset'))))
            item.setText(e['name'].capitalize())
            self.tblFunctions1.setVerticalHeaderItem(i, item)

        big_font = QtGui.QFont()
        big_font.setPointSize(80)

        for h in hazards:
            for e in exposures:
                item = QtGui.QTableWidgetItem()
                functions = \
                    self.impact_function_manager.functions_for_constraint(
                        h['key'], e['key'])
                if len(functions):
                    background_colour = QtGui.QColor(120, 255, 120)
                else:
                    background_colour = QtGui.QColor(220, 220, 220)
                    item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEnabled)
                    item.setFlags(item.flags() & ~QtCore.Qt.ItemIsSelectable)
                item.setBackground(QtGui.QBrush(background_colour))
                item.setFont(big_font)
                item.setTextAlignment(
                    QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter)
                item.setData(RoleFunctions, functions)
                item.setData(RoleHazard, h)
                item.setData(RoleExposure, e)
                self.tblFunctions1.setItem(
                    exposures.index(e), hazards.index(h), item)
        self.parent.pbnNext.setEnabled(False)
Пример #6
0
def _definition_screenshot_url(definition):
    jpg_image_path = resources_path(
        'img', 'definitions', definition['key'] + '_screenshot.jpg')
    png_image_path = resources_path(
        'img', 'definitions', definition['key'] + '_screenshot.png')
    if exists(jpg_image_path):
        url = resource_url(jpg_image_path)
    elif exists(png_image_path):
        url = resource_url(png_image_path)
    else:
        url = None
    return url
Пример #7
0
    def set_widgets(self):
        """Set widgets on the Impact Functions tab."""
        self.lstFunctions.clear()
        self.lblDescribeFunction.setText('')

        h, e, hc, ec = self.parent.selected_impact_function_constraints()
        functions = self.impact_function_manager.functions_for_constraint(
            h['key'], e['key'], hc['key'], ec['key'])
        self.lblSelectFunction.setText(
            select_function_question % (
                hc['name'], h['name'], ec['name'], e['name']))
        for f in functions:
            item = QtGui.QListWidgetItem(self.lstFunctions)
            item.setText(f['name'])
            item.setData(QtCore.Qt.UserRole, f)
        self.auto_select_one_item(self.lstFunctions)

        # Set hazard and exposure icons on next steps
        icon_path = resources_path(
            'img', 'wizard', 'keyword-subcategory-%s.svg'
            % (h['key'] or 'notset'))
        self.lblIconFunctionHazard.setPixmap(QPixmap(icon_path))
        self.parent.step_fc_hazlayer_origin.\
            lblIconIFCWHazardOrigin.setPixmap(QPixmap(icon_path))
        self.parent.step_fc_hazlayer_from_canvas.\
            lblIconIFCWHazardFromCanvas.setPixmap(QPixmap(icon_path))
        self.parent.step_fc_hazlayer_from_browser.\
            lblIconIFCWHazardFromBrowser.setPixmap(QPixmap(icon_path))
        icon_path = resources_path(
            'img', 'wizard', 'keyword-subcategory-%s.svg'
            % (e['key'] or 'notset'))
        self.lblIconFunctionExposure.setPixmap(QPixmap(icon_path))
        self.parent.step_fc_explayer_origin.\
            lblIconIFCWExposureOrigin.setPixmap(QPixmap(icon_path))
        self.parent.step_fc_explayer_from_canvas.\
            lblIconIFCWExposureFromCanvas.setPixmap(QPixmap(icon_path))
        self.parent.step_fc_explayer_from_browser.\
            lblIconIFCWExposureFromBrowser.setPixmap(QPixmap(icon_path))

        # icon_path = resources_path(
        #     'img', 'wizard', 'keyword-category-aggregation.svg')
        # Temporarily hide aggregation icon until we have one suitable
        # (as requested in a comment to PR #2060)
        icon_path = None
        self.parent.step_fc_agglayer_origin.\
            lblIconIFCWAggregationOrigin.setPixmap(QPixmap(icon_path))
        self.parent.step_fc_agglayer_from_canvas.\
            lblIconIFCWAggregationFromCanvas.setPixmap(QPixmap(icon_path))
        self.parent.step_fc_agglayer_from_browser.\
            lblIconIFCWAggregationFromBrowser.setPixmap(QPixmap(icon_path))
Пример #8
0
def _definition_icon_url(definition):
    if 'key' not in definition:
        return None
    svg_image_path = resources_path(
        'img', 'definitions', definition['key'] + '.svg')
    png_image_path = resources_path(
        'img', 'definitions', definition['key'] + '.png')
    if exists(svg_image_path):
        url = resource_url(svg_image_path)
    elif exists(png_image_path):
        url = resource_url(png_image_path)
    else:
        url = None
    return url
Пример #9
0
    def populate_function_table_1(self):
        """Populate the tblFunctions1 table with available functions."""
        hazards = deepcopy(hazard_all)
        exposures = exposure_all

        self.lblAvailableFunctions1.clear()
        self.tblFunctions1.clear()
        self.tblFunctions1.setColumnCount(len(hazards))
        self.tblFunctions1.setRowCount(len(exposures))
        for i in range(len(hazards)):
            hazard = hazards[i]
            item = QtGui.QTableWidgetItem()
            item.setIcon(QtGui.QIcon(
                resources_path('img', 'wizard', 'keyword-subcategory-%s.svg'
                               % (hazard['key'] or 'notset'))))
            item.setText(hazard['name'].capitalize())
            self.tblFunctions1.setHorizontalHeaderItem(i, item)
        for i in range(len(exposures)):
            exposure = exposures[i]
            item = QtGui.QTableWidgetItem()

            item.setIcon(QtGui.QIcon(resources_path(
                'img', 'wizard', 'keyword-subcategory-%s.svg'
                % (exposure['key'] or 'notset'))))
            item.setText(exposure['name'].capitalize())
            self.tblFunctions1.setVerticalHeaderItem(i, item)
        developer_mode = setting('developer_mode', False, bool)
        for hazard in hazards:
            for exposure in exposures:
                item = QtGui.QTableWidgetItem()
                if (exposure in hazard['disabled_exposures'] and not
                        developer_mode):
                    background_colour = unavailable_option_color
                    # Set it disable and un-selectable
                    item.setFlags(
                        item.flags() & ~
                        QtCore.Qt.ItemIsEnabled & ~
                        QtCore.Qt.ItemIsSelectable
                    )
                else:
                    background_colour = available_option_color
                item.setBackground(QtGui.QBrush(background_colour))
                item.setFont(big_font)
                item.setTextAlignment(
                    QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter)
                item.setData(RoleHazard, hazard)
                item.setData(RoleExposure, exposure)
                self.tblFunctions1.setItem(
                    exposures.index(exposure), hazards.index(hazard), item)
        self.parent.pbnNext.setEnabled(False)
Пример #10
0
    def Xtest_print_impact_table(self):
        """Test print impact table to pdf."""
        impact_layer_path = test_data_path(
            'impact', 'population_affected_entire_area.shp')
        layer, _ = load_layer(impact_layer_path)
        # noinspection PyUnresolvedReferences,PyArgumentList
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        # noinspection PyCallingNonCallable
        rect = QgsRectangle(106.8194, -6.2108, 106.8201, -6.1964)
        CANVAS.setExtent(rect)
        CANVAS.refresh()

        template = resources_path(
            'qgis-composer-templates', 'a4-portrait-blue.qpt')
        report = ImpactReport(IFACE, template, layer)
        report.template = template  # just to cover set template
        out_path = unique_filename(
            prefix='test_print_impact_table',
            suffix='.pdf',
            dir=temp_dir('test'))
        report.print_impact_table(out_path)

        # Check the file exists
        message = 'Rendered output does not exist: %s' % out_path
        self.assertTrue(os.path.exists(out_path), message)

        # Check the file is not corrupt
        message = 'The output file %s is corrupt' % out_path
        out_size = os.stat(out_path).st_size
        self.assertTrue(out_size > 0, message)
Пример #11
0
def show_keyword_version_message(sender, keyword_version, inasafe_version):
    """Show a message indicating that the keywords version is mismatch

    .. versionadded: 3.2

    :param keyword_version: The version of the layer's keywords
    :type keyword_version: str

    :param inasafe_version: The version of the InaSAFE
    :type inasafe_version: str

    .. note:: The print button will be disabled if this method is called.
    """
    LOGGER.debug('Showing Mismatch Version Message')
    message = generate_input_error_message(
        tr('Layer Keyword\'s Version Mismatch:'),
        m.Paragraph(
            tr(
                'Your layer\'s keyword\'s version ({layer_version}) does not '
                'match with your InaSAFE version ({inasafe_version}). If you '
                'wish to use it as an exposure, hazard, or aggregation layer '
                'in an analysis, please use the keyword wizard to update the '
                'keywords. You can open the wizard by clicking on '
                'the ').format(
                layer_version=keyword_version,
                inasafe_version=inasafe_version),
            m.Image(
                'file:///%s/img/icons/'
                'show-keyword-wizard.svg' % resources_path(),
                **SMALL_ICON_STYLE),
            tr(
                ' icon in the toolbar.'))
    )
    send_static_message(sender, message)
Пример #12
0
    def create_pdf(self, title, output_directory, impact_layer, count=0, index=None):
        """Create PDF report from impact layer.

        Create map & table report PDF based from impact_layer data.

        :param title: Report title.
        :type title: str

        :param output_directory: Output directory.
        :type output_directory: str

        :param impact_layer: Impact layer instance.
        :type impact_layer: QgsMapLayer

        :param count: The number of scenarios that were run.
        :type count: int

        :param index: A sequential number to place at the beginning of the
            file name.
        :type index: int, None

        See also:
            Dock.printMap()
        """
        # FIXME: check if impact_layer is the real impact layer...
        template = resources_path("qgis-composer-templates", "inasafe-portrait-a4.qpt")
        impact_report = ImpactReport(self.iface, template, impact_layer)

        LOGGER.debug("Create Report: %s" % title)
        map_path, table_path = self.report_path(output_directory, title, count, index)

        # create map and table pdf
        map_path, table_path = impact_report.print_to_pdf(map_path)

        LOGGER.debug("Report done %s %s" % (map_path, table_path))
Пример #13
0
    def __init__(self, iface, template, layer):
        """Constructor for the Composition Report class.

        :param iface: Reference to the QGIS iface object.
        :type iface: QgsAppInterface

        :param template: The QGIS template path.
        :type template: str
        """
        LOGGER.debug('InaSAFE Impact Report class initialised')
        self._iface = iface
        self._template = template
        self._layer = layer
        self._extent = self._iface.mapCanvas().extent()
        self._page_dpi = 300.0
        self._safe_logo = resources_path(
            'img', 'logos', 'inasafe-logo-url.svg')
        self._organisation_logo = default_organisation_logo_path()
        self._north_arrow = default_north_arrow_path()
        self._disclaimer = disclaimer()

        # For QGIS < 2.4 compatibility
        # QgsMapSettings is added in 2.4
        if qgis_version() < 20400:
            map_settings = self._iface.mapCanvas().mapRenderer()
        else:
            map_settings = self._iface.mapCanvas().mapSettings()

        self._template_composition = TemplateComposition(
            template_path=self.template,
            map_settings=map_settings)
        self._keyword_io = KeywordIO()
Пример #14
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)

        supporters_path = resources_path('img', 'logos', 'supporters.png')
        pixmap = QtGui.QPixmap(supporters_path)
        self.supporters_label.setPixmap(pixmap)
Пример #15
0
    def restore_state(self):
        """Reinstate the options based on the user's stored session info.
        """
        settings = QtCore.QSettings()

        flag = bool(settings.value(
            'inasafe/analysisExtentFlag', True, type=bool))
        self.analysis_extent_radio.setChecked(flag)
        self.current_extent_radio.setChecked(not flag)

        flag = bool(settings.value(
            'inasafe/useDefaultTemplates', True, type=bool))
        self.default_template_radio.setChecked(flag)
        self.custom_template_radio.setChecked(not flag)

        try:
            default_template_path = resources_path(
                'qgis-composer-templates', 'inasafe-map-report-portrait.qpt')
            path = settings.value(
                'inasafe/lastTemplate',
                default_template_path,
                type=str)
            self.template_combo.setCurrentIndex(
                self.template_combo.findData(path))
        except TypeError:
            self.template_combo.setCurrentIndex(2)

        try:
            path = settings.value('inasafe/lastCustomTemplate', '', type=str)
        except TypeError:
            path = ''
        self.template_path.setText(path)
Пример #16
0
def black_inasafe_logo_path():
    """Get the path to the Black InaSAFE SVG logo.

    .. versionadded:: 3.2
    """
    path = resources_path('img', 'logos', 'inasafe-logo-url.svg')
    return path
    def copy_keywords(self, shapefile_path):
        """Copy keywords from the OSM resource directory to the output path.

        .. versionadded: 3.3

        In addition to copying the template, tokens within the template will
        be replaced with new values for the date token and title token.

        :param shapefile_path: Path to the shapefile that will have the flooded
            field added.
        :type shapefile_path: basestring
        """
        source_xml_path = resources_path('petajakarta', 'flood-keywords.xml')
        output_xml_path = shapefile_path.replace('shp', 'xml')
        LOGGER.info('Copying xml to: %s' % output_xml_path)

        title_token = '[TITLE]'
        new_title = self.tr('Jakarta Floods - %s' % self.time_stamp)

        date_token = '[DATE]'
        new_date = self.time_stamp
        with open(source_xml_path) as source_file, \
                open(output_xml_path, 'w') as output_file:
            for line in source_file:
                line = line.replace(date_token, new_date)
                line = line.replace(title_token, new_title)
                output_file.write(line)
Пример #18
0
def black_inasafe_logo_path():
    """Get the path to the Black InaSAFE SVG logo.

    .. versionadded:: 3.2
    """
    path = resources_path("img", "logos", "inasafe-logo-url.svg")
    return path
    def set_widgets(self):
        """Set widgets on the Exposure Layer From Canvas tab"""
        # The list is already populated in the previous step, but now we
        # need to do it again in case we're back from the Keyword Wizard.
        # First, preserve self.parent.layer before clearing the list
        last_layer = self.parent.layer and self.parent.layer.id() or None
        self.lblDescribeCanvasExpLayer.clear()
        self.list_compatible_canvas_layers()
        self.auto_select_one_item(self.lstCanvasExpLayers)
        # Try to select the last_layer, if found:
        if last_layer:
            layers = []
            for indx in xrange(self.lstCanvasExpLayers.count()):
                item = self.lstCanvasExpLayers.item(indx)
                layers += [item.data(QtCore.Qt.UserRole)]
            if last_layer in layers:
                self.lstCanvasExpLayers.setCurrentRow(layers.index(last_layer))

        # Set icon
        exposure = self.parent.step_fc_functions1.selected_value(
            layer_purpose_exposure['key'])
        icon_path = resources_path(
            'img', 'wizard', 'keyword-subcategory-%s.svg'
                             % (exposure['key'] or 'notset'))
        self.lblIconIFCWExposureFromCanvas.setPixmap(QPixmap(icon_path))
Пример #20
0
def white_inasafe_logo_path():
    """Get the path to the White InaSAFE SVG logo.

    .. versionadded:: 3.2
    """
    path = resources_path("img", "logos", "inasafe-logo-url-white.svg")
    return path
Пример #21
0
def white_inasafe_logo_path():
    """Get the path to the White InaSAFE SVG logo.

    .. versionadded:: 3.2
    """
    path = resources_path('img', 'logos', 'inasafe-logo-url-white.svg')
    return path
Пример #22
0
def show_keywords_need_review_message(sender, message=None):
    """Show a message keywords are not adequate to run an analysis.

    .. versionadded: 4.0

    :param message: Additional message to display.
    :type message: str

    .. note:: The print button will be disabled if this method is called.
    """
    LOGGER.debug('Showing incorrect keywords for v4 message')
    message = generate_input_error_message(
        tr('Layer Keywords Outdated:'),
        m.Paragraph(
            tr(
                'Please update the keywords for your layers and then '
                'try to run the analysis again. Use the keyword wizard '),
            m.Image(
                'file:///%s/img/icons/'
                'show-keyword-wizard.svg' % resources_path(),
                **SMALL_ICON_STYLE),
            tr(
                ' icon in the toolbar to update your layer\'s keywords.'),
            message)
    )
    send_static_message(sender, message)
Пример #23
0
def default_north_arrow_path():
    """Get a default north arrow image path.

    :return: Default north arrow path.
    :rtype: str
    """
    path = resources_path("img", "north_arrows", "simple_north_arrow.png")
    return path
Пример #24
0
 def _create_batch_runner_action(self):
     """Create action for batch runner dialog."""
     icon = resources_path("img", "icons", "show-batch-runner.svg")
     self.action_batch_runner = QAction(QIcon(icon), self.tr("InaSAFE Batch Runner"), self.iface.mainWindow())
     self.action_batch_runner.setStatusTip(self.tr("Open InaSAFE Batch Runner"))
     self.action_batch_runner.setWhatsThis(self.tr("Open InaSAFE Batch Runner"))
     self.action_batch_runner.triggered.connect(self.show_batch_runner)
     self.add_action(self.action_batch_runner, add_to_toolbar=self.full_toolbar)
Пример #25
0
def default_organisation_logo_path():
    """Get a default organisation logo path.

    :return: Default organisation logo path.
    :rtype: str
    """
    path = resources_path('img', 'logos', 'supporters.png')
    return path
Пример #26
0
def default_north_arrow_path():
    """Get a default north arrow image path.

    :return: Default north arrow path.
    :rtype: str
    """
    path = resources_path('img', 'north_arrows', 'simple_north_arrow.png')
    return path
Пример #27
0
 def _create_shakemap_converter_action(self):
     """Create action for converter dialog."""
     icon = resources_path("img", "icons", "show-converter-tool.svg")
     self.action_shake_converter = QAction(QIcon(icon), self.tr("InaSAFE Converter"), self.iface.mainWindow())
     self.action_shake_converter.setStatusTip(self.tr("Open InaSAFE Converter"))
     self.action_shake_converter.setWhatsThis(self.tr("Open InaSAFE Converter"))
     self.action_shake_converter.triggered.connect(self.show_shakemap_importer)
     self.add_action(self.action_shake_converter, add_to_toolbar=self.full_toolbar)
Пример #28
0
 def _create_minimum_needs_action(self):
     """Create action for minimum needs dialog."""
     icon = resources_path("img", "icons", "show-minimum-needs.svg")
     self.action_minimum_needs = QAction(QIcon(icon), self.tr("InaSAFE Minimum Needs Tool"), self.iface.mainWindow())
     self.action_minimum_needs.setStatusTip(self.tr("Open InaSAFE minimum needs tool"))
     self.action_minimum_needs.setWhatsThis(self.tr("Open InaSAFE minimum needs tool"))
     self.action_minimum_needs.triggered.connect(self.show_minimum_needs)
     self.add_action(self.action_minimum_needs, add_to_toolbar=self.full_toolbar)
Пример #29
0
 def _create_options_dialog_action(self):
     """Create action for options dialog."""
     icon = resources_path("img", "icons", "configure-inasafe.svg")
     self.action_options = QAction(QIcon(icon), self.tr("InaSAFE Options"), self.iface.mainWindow())
     self.action_options.setStatusTip(self.tr("Open InaSAFE options dialog"))
     self.action_options.setWhatsThis(self.tr("Open InaSAFE options dialog"))
     self.action_options.triggered.connect(self.show_options)
     self.add_action(self.action_options, add_to_toolbar=self.full_toolbar)
Пример #30
0
def content():
    """Helper method that returns just the content.

    This method was added so that the text could be reused in the
    dock_help module.

    .. versionadded:: 4.0.0

    :returns: A message object without brand element.
    :rtype: safe.messaging.message.Message
    """
    message = m.Message()
    paragraph = m.Paragraph(
        m.Image(
            'file:///%s/img/screenshots/'
            'multi-buffer-screenshot.png' % resources_path()),
        style_class='text-center'
    )
    message.add(paragraph)
    message.add(m.Paragraph(tr(
        'This tool will generate a polygon layer by multi-buffering the input '
        'layer. '
        'To use this tool effectively:'
    )))
    tips = m.BulletedList()
    tips.add(tr(
        'Load a point or line layer in QGIS. Typically, the layer will '
        'represent hazard source such as volcano and river.'
    ))
    tips.add(tr(
        'Choose where to save the output layer to.'
    ))
    tips.add(tr(
        'Create one or more entries in the classes list, and define '
        'the appropriate distances for each buffer. You should give '
        'each buffer distance a corresponding name '
        'e.g. "high", "medium", "low". Click the add (+) button to '
        'record your entries.'
    ))
    tips.add(tr(
        'To remove the classification, select the classification you want to '
        'remove, then click the remove (-) button.'
    ))
    tips.add(tr(
        'Check the "launch keywords wizard" checkbox to launch the keywords '
        'creation wizard after the buffering is complete. If you want assign '
        'keywords later, uncheck the "launch keywords wizard" checkbox.'
    ))
    tips.add(tr(
        'A new layer will be added to QGIS after the buffering is complete. '
        'The layer will contain new buffer polygon(s) and the class name will '
        'be stored as an attribute of each polygon. If you check the '
        'launch keywords wizard checkbox, the keywords creation wizard will '
        'launch right after the buffering process has completed. '
        'You can assign the keywords to the output layer.'
    ))
    message.add(tips)
    return message
Пример #31
0
 def _create_shakemap_converter_action(self):
     """Create action for converter dialog."""
     icon = resources_path('img', 'icons', 'show-converter-tool.svg')
     self.action_shake_converter = QAction(
         QIcon(icon),
         self.tr('Shakemap Converter'), self.iface.mainWindow())
     self.action_shake_converter.setStatusTip(self.tr(
         'Open InaSAFE Converter'))
     self.action_shake_converter.setWhatsThis(self.tr(
         'Open InaSAFE Converter'))
     self.action_shake_converter.triggered.connect(
         self.show_shakemap_importer)
     self.add_action(
         self.action_shake_converter, add_to_toolbar=self.full_toolbar)
Пример #32
0
    def _create_test_layers_action(self):
        """Create action for adding layers (developer mode, non final only)."""
        if self.hide_developer_buttons:
            return

        icon = resources_path('img', 'icons', 'add-test-layers.svg')
        self.action_add_layers = QAction(QIcon(icon),
                                         self.tr('Add Test Layers'),
                                         self.iface.mainWindow())
        self.action_add_layers.setStatusTip(self.tr('Add test layers'))
        self.action_add_layers.setWhatsThis(self.tr('Add test layers'))
        self.action_add_layers.triggered.connect(self.add_test_layers)

        self.add_action(self.action_add_layers)
Пример #33
0
 def _create_analysis_extent_action(self):
     """Create action for analysis extent dialog."""
     icon = resources_path('img', 'icons', 'set-extents-tool.svg')
     self.action_extent_selector = QAction(
         QIcon(icon),
         self.tr('Set Analysis Area'),
         self.iface.mainWindow())
     self.action_extent_selector.setStatusTip(self.tr(
         'Set the analysis area for InaSAFE'))
     self.action_extent_selector.setWhatsThis(self.tr(
         'Set the analysis area for InaSAFE'))
     self.action_extent_selector.triggered.connect(
         self.show_extent_selector)
     self.add_action(self.action_extent_selector)
Пример #34
0
 def _create_field_mapping_action(self):
     """Create action for showing field mapping dialog."""
     icon = resources_path('img', 'icons', 'show-mapping-tool.svg')
     self.action_field_mapping = QAction(
         QIcon(icon), self.tr('InaSAFE Field Mapping Tool'),
         self.iface.mainWindow())
     self.action_field_mapping.setStatusTip(
         self.tr('Assign field mapping to layer.'))
     self.action_field_mapping.setWhatsThis(
         self.tr('Use this tool to assign field mapping in layer.'))
     self.action_field_mapping.setEnabled(False)
     self.action_field_mapping.triggered.connect(self.show_field_mapping)
     self.add_action(self.action_field_mapping,
                     add_to_toolbar=self.full_toolbar)
Пример #35
0
    def set_widgets(self):
        """Set widgets on the Exposure Layer Origin Type tab"""
        # First, list available layers in order to check if there are
        # any available layers. Note This will be repeated in
        # set_widgets_step_fc_explayer_from_canvas because we need
        # to list them again after coming back from the Keyword Wizard.
        self.parent.step_fc_explayer_from_canvas.\
            list_compatible_canvas_layers()
        lst_wdg = self.parent.step_fc_explayer_from_canvas.lstCanvasExpLayers
        if lst_wdg.count():
            self.rbExpLayerFromCanvas.setText(
                tr('I would like to use an exposure layer already loaded in QGIS'
                   '\n'
                   '(launches the %s for exposure if needed)') %
                self.parent.keyword_creation_wizard_name)
            self.rbExpLayerFromCanvas.setEnabled(True)
            self.rbExpLayerFromCanvas.click()
        else:
            self.rbExpLayerFromCanvas.setText(
                tr('I would like to use an exposure layer already loaded in QGIS'
                   '\n'
                   '(no suitable layers found)'))
            self.rbExpLayerFromCanvas.setEnabled(False)
            self.rbExpLayerFromBrowser.click()

        # Set the memo labels on this and next (exposure) steps
        (_, exposure, _, exposure_constraints) = self.\
            parent.selected_impact_function_constraints()

        layer_geometry = exposure_constraints['name']

        text = (select_exposure_origin_question %
                (layer_geometry, exposure['name']))
        self.lblSelectExpLayerOriginType.setText(text)

        text = (select_explayer_from_canvas_question %
                (layer_geometry, exposure['name']))
        self.parent.step_fc_explayer_from_canvas.lblSelectExposureLayer.\
            setText(text)

        text = (select_explayer_from_browser_question %
                (layer_geometry, exposure['name']))
        self.parent.step_fc_explayer_from_browser.lblSelectBrowserExpLayer.\
            setText(text)

        # Set icon
        icon_path = resources_path(
            'img', 'wizard',
            'keyword-subcategory-%s.svg' % (exposure['key'] or 'notset'))
        self.lblIconIFCWExposureOrigin.setPixmap(QPixmap(icon_path))
Пример #36
0
 def _create_minimum_needs_options_action(self):
     """Create action for global minimum needs dialog."""
     icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg')
     self.action_minimum_needs_config = QAction(
         QIcon(icon), self.tr('Minimum Needs Configuration'),
         self.iface.mainWindow())
     self.action_minimum_needs_config.setStatusTip(
         self.tr('Open InaSAFE minimum needs configuration'))
     self.action_minimum_needs_config.setWhatsThis(
         self.tr('Open InaSAFE minimum needs configuration'))
     self.action_minimum_needs_config.triggered.connect(
         self.show_minimum_needs_configuration)
     self.add_action(self.action_minimum_needs_config,
                     add_to_toolbar=self.full_toolbar)
Пример #37
0
 def _create_impact_merge_action(self):
     """Create action for impact layer merge Dialog."""
     icon = resources_path('img', 'icons', 'show-impact-merge.svg')
     self.action_impact_merge_dlg = QAction(
         QIcon(icon),
         self.tr('Impact Layer Merger'),
         self.iface.mainWindow())
     self.action_impact_merge_dlg.setStatusTip(self.tr(
         'Impact Layer Merger'))
     self.action_impact_merge_dlg.setWhatsThis(self.tr(
         'Impact Layer Merger'))
     self.action_impact_merge_dlg.triggered.connect(self.show_impact_merge)
     self.add_action(
         self.action_impact_merge_dlg, add_to_toolbar=self.full_toolbar)
Пример #38
0
 def _create_keywords_wizard_action(self):
     """Create action for keywords creation wizard."""
     icon = resources_path('img', 'icons', 'show-keyword-wizard.svg')
     self.action_keywords_wizard = QAction(
         QIcon(icon), self.tr('Keywords Creation Wizard'),
         self.iface.mainWindow())
     self.action_keywords_wizard.setStatusTip(
         self.tr('Open InaSAFE keywords creation wizard'))
     self.action_keywords_wizard.setWhatsThis(
         self.tr('Open InaSAFE keywords creation wizard'))
     self.action_keywords_wizard.setEnabled(False)
     self.action_keywords_wizard.triggered.connect(
         self.show_keywords_wizard)
     self.add_action(self.action_keywords_wizard)
Пример #39
0
def population_chart_legend_extractor(impact_report, component_metadata):
    """Extracting legend of population chart.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.2
    """
    context = {}

    context['inasafe_resources_base_dir'] = resources_path()

    """Population Charts"""

    population_donut_path = impact_report.component_absolute_output_path(
        'population-chart-png')

    css_label_classes = []
    try:
        population_chart_context = impact_report.metadata.component_by_key(
            'population-chart').context['context']
        """
        :type: safe.report.extractors.infographic_elements.svg_charts.
            DonutChartContext
        """
        for pie_slice in population_chart_context.slices:
            label = pie_slice['label']
            if not label:
                continue
            css_class = label.replace(' ', '').lower()
            css_label_classes.append(css_class)
    except KeyError:
        population_chart_context = None

    context['population_chart'] = {
        'img_path': resource_url(population_donut_path),
        'context': population_chart_context,
        'css_label_classes': css_label_classes
    }

    return context
Пример #40
0
 def _create_metadata_converter_action(self):
     """Create action for showing metadata converter dialog."""
     icon = resources_path('img', 'icons', 'show-metadata-converter.svg')
     self.action_metadata_converter = QAction(
         QIcon(icon), self.tr('InaSAFE Metadata Converter'),
         self.iface.mainWindow())
     self.action_metadata_converter.setStatusTip(
         self.tr('Convert metadata from version 4.3 to version 3.5.'))
     self.action_metadata_converter.setWhatsThis(
         self.tr('Use this tool to convert metadata 4.3 to version 3.5'))
     self.action_metadata_converter.triggered.connect(
         self.show_metadata_converter)
     self.add_action(self.action_metadata_converter,
                     add_to_toolbar=self.full_toolbar)
Пример #41
0
 def _create_add_osm_layer_action(self):
     """Create action for import OSM Dialog."""
     icon = resources_path('img', 'icons', 'add-osm-tiles-layer.svg')
     self.action_add_osm_layer = QAction(
         QIcon(icon),
         self.tr('Add OpenStreetMap Tile Layer'),
         self.iface.mainWindow())
     self.action_add_osm_layer.setStatusTip(self.tr(
         'Add OpenStreetMap Tile Layer'))
     self.action_add_osm_layer.setWhatsThis(self.tr(
         'Use this to add an OSM layer to your map. '
         'It needs internet access to function.'))
     self.action_add_osm_layer.triggered.connect(self.add_osm_layer)
     self.add_action(self.action_add_osm_layer)
Пример #42
0
 def _create_analysis_wizard_action(self):
     """Create action for IF-centric wizard."""
     icon = resources_path('img', 'icons', 'show-wizard.svg')
     self.action_function_centric_wizard = QAction(
         QIcon(icon), self.tr('Impact Function Centric Wizard'),
         self.iface.mainWindow())
     self.action_function_centric_wizard.setStatusTip(
         self.tr('Open InaSAFE impact function centric wizard'))
     self.action_function_centric_wizard.setWhatsThis(
         self.tr('Open InaSAFE impact function centric wizard'))
     self.action_function_centric_wizard.setEnabled(True)
     self.action_function_centric_wizard.triggered.connect(
         self.show_function_centric_wizard)
     self.add_action(self.action_function_centric_wizard)
Пример #43
0
def content():
    """Helper method that returns just the content.

    This method was added so that the text could be reused in the
    dock_help module.

    .. versionadded:: 3.2.2

    :returns: A message object without brand element.
    :rtype: safe.messaging.message.Message
    """
    message = m.Message()
    paragraph = m.Paragraph(m.Image('file:///%s/img/screenshots/'
                                    'analysis-area-screenshot.png' %
                                    resources_path()),
                            style_class='text-center')
    message.add(paragraph)

    paragraph = m.Paragraph(
        tr('This tool allows you to specify which geographical region should be '
           'used for your analysis. If you want to check what area will be '
           'included in your analysis, enable the \'Toggle scenario outlines\' '
           'tool on the InaSAFE toolbar:'),
        m.Image(
            'file:///%s/img/icons/'
            'toggle-rubber-bands.svg' % resources_path(), **SMALL_ICON_STYLE),
    )
    message.add(paragraph)
    paragraph = m.Paragraph(
        tr('Your user defined extent will be shown on the map as a rectangle. '
           'There are a number of different modes that can be used which are '
           'described below:'))
    message.add(paragraph)

    message.add(extent_mode_content())

    return message
Пример #44
0
def impact_table_extractor(impact_report, component_metadata):
    """Extracting impact summary of the impact layer.

    :param impact_report: the impact report that acts as a proxy to fetch
        all the data that extractor needed
    :type impact_report: safe.report.impact_report.ImpactReport

    :param component_metadata: the component metadata. Used to obtain
        information about the component we want to render
    :type component_metadata: safe.report.report_metadata.
        ReportComponentsMetadata

    :return: context for rendering phase
    :rtype: dict

    .. versionadded:: 4.0
    """
    context = {}
    extra_args = component_metadata.extra_args

    components_list = resolve_from_dictionary(
        extra_args, 'components_list')

    # TODO: Decide either to use it or not
    if not impact_report.impact_function.debug_mode:
        # only show experimental MMI Detail when in debug mode
        components_list.pop('mmi_detail', None)

    context['brand_logo'] = resource_url(
        resources_path('img', 'logos', 'inasafe-logo-white.png'))
    for key, component in list(components_list.items()):
        context[key] = jinja2_output_as_string(
            impact_report, component['key'])

    context['inasafe_resources_base_dir'] = resources_path()

    return context
Пример #45
0
    def set_widgets(self):
        """Set widgets on the Hazard Layer Origin Type tab."""
        # First, list available layers in order to check if there are
        # any available layers. Note This will be repeated in
        # set_widgets_step_fc_hazlayer_from_canvas because we need
        # to list them again after coming back from the Keyword Wizard.
        self.parent.step_fc_hazlayer_from_canvas.\
            list_compatible_canvas_layers()
        lst_wdg = self.parent.step_fc_hazlayer_from_canvas.lstCanvasHazLayers
        if lst_wdg.count():
            wizard_name = self.parent.keyword_creation_wizard_name
            self.rbHazLayerFromCanvas.setText(tr(
                'I would like to use a hazard layer already loaded in QGIS\n'
                '(launches the {wizard_name} for hazard if needed)'
            ).format(wizard_name=wizard_name))
            self.rbHazLayerFromCanvas.setEnabled(True)
            self.rbHazLayerFromCanvas.click()
        else:
            self.rbHazLayerFromCanvas.setText(tr(
                'I would like to use a hazard layer already loaded in QGIS\n'
                '(no suitable layers found)'))
            self.rbHazLayerFromCanvas.setEnabled(False)
            self.rbHazLayerFromBrowser.click()

        # Set the memo labels on this and next (hazard) steps
        (hazard, _, hazard_constraints, _) = self.\
            parent.selected_impact_function_constraints()

        layer_geometry = hazard_constraints['name']

        text = (select_hazard_origin_question % (
            layer_geometry, hazard['name']))
        self.lblSelectHazLayerOriginType.setText(text)

        text = (select_hazlayer_from_canvas_question % (
            layer_geometry, hazard['name']))
        self.parent.step_fc_hazlayer_from_canvas.\
            lblSelectHazardLayer.setText(text)

        text = (select_hazlayer_from_browser_question % (
            layer_geometry, hazard['name']))
        self.parent.step_fc_hazlayer_from_browser.\
            lblSelectBrowserHazLayer.setText(text)

        # Set icon
        icon_path = resources_path(
            'img', 'wizard', 'keyword-subcategory-%s.svg' % (
                hazard['key'] or 'notset'))
        self.lblIconIFCWHazardOrigin.setPixmap(QPixmap(icon_path))
Пример #46
0
    def __init__(self, parent=None, iface=iface_object):
        """Constructor for the multi exposure dialog.

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

        :param iface: An instance of QgisInterface
        :type iface: QgisInterface
        """
        QDialog.__init__(self, parent)
        self.use_selected_only = setting('useSelectedFeaturesOnly',
                                         expected_type=bool)
        self.parent = parent
        self.iface = iface
        self.setupUi(self)
        icon = resources_path('img', 'icons', 'show-multi-exposure.svg')
        self.setWindowIcon(QIcon(icon))
        self.tab_widget.setCurrentIndex(0)
        self.combos_exposures = OrderedDict()
        self.keyword_io = KeywordIO()
        self._create_exposure_combos()
        self._multi_exposure_if = None
        self._extent = Extent(iface)
        self._extent.show_rubber_bands = setting('showRubberBands', False,
                                                 bool)

        enable_messaging(self.message_viewer, self)

        self.btn_back.clicked.connect(self.back_clicked)
        self.btn_next.clicked.connect(self.next_clicked)
        self.btn_cancel.clicked.connect(self.reject)
        self.btn_run.clicked.connect(self.accept)
        self.validate_impact_function()
        self.tab_widget.currentChanged.connect(self._tab_changed)
        self.tree.itemSelectionChanged.connect(self._tree_selection_changed)
        self.list_layers_in_map_report.itemSelectionChanged.connect(
            self._list_selection_changed)
        self.add_layer.clicked.connect(self._add_layer_clicked)
        self.remove_layer.clicked.connect(self._remove_layer_clicked)
        self.move_up.clicked.connect(self.move_layer_up)
        self.move_down.clicked.connect(self.move_layer_down)
        self.cbx_hazard.currentIndexChanged.connect(
            self.validate_impact_function)
        self.cbx_aggregation.currentIndexChanged.connect(
            self.validate_impact_function)

        # Keep track of the current panel
        self._current_index = 0
        self.tab_widget.setCurrentIndex(self._current_index)
Пример #47
0
    def get_profiles(self):
        """Get all the minimum needs profiles.

        :returns: The minimum needs by name.
        :rtype: list
        """
        def sort_by_locale(unsorted_profiles, locale):
            """Sort the profiles by language settings.

            The profiles that are in the same language as the QGIS' locale
            will be sorted out first.

            :param unsorted_profiles: The user profiles profiles
            :type unsorted_profiles: list

            :param locale: The language settings string
            :type locale: str

            :returns: Ordered profiles
            :rtype: list
            """
            locale = '_%s' % locale[:2]
            profiles_our_locale = []
            profiles_remaining = []
            for profile_name in unsorted_profiles:
                if locale in profile_name:
                    profiles_our_locale.append(profile_name)
                else:
                    profiles_remaining.append(profile_name)

            return profiles_our_locale + profiles_remaining

        locale_minimum_needs_dir = os.path.join(str(self.root_directory),
                                                'minimum_needs')
        path_name = resources_path('minimum_needs')
        if not os.path.exists(locale_minimum_needs_dir):
            os.makedirs(locale_minimum_needs_dir)
        for file_name in os.listdir(path_name):
            source_file = os.path.join(path_name, file_name)
            destination_file = os.path.join(locale_minimum_needs_dir,
                                            file_name)
            if not os.path.exists(destination_file):
                copy(source_file, destination_file)
        profiles = [
            profile[:-5] for profile in os.listdir(locale_minimum_needs_dir)
            if profile[-5:] == '.json'
        ]
        profiles = sort_by_locale(profiles, self.locale)
        return profiles
Пример #48
0
    def __init__(self, parent=None):
        """Constructor for the dialog.

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

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

        icon = resources_path('img', 'icons', 'icon.png')
        self.setWindowIcon(QtGui.QIcon(icon))

        # 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)

        supporters_path = resources_path('img', 'logos', 'supporters.png')
        pixmap = QtGui.QPixmap(supporters_path)
        self.supporters_label.setPixmap(pixmap)
Пример #49
0
 def _create_add_petabencana_layer_action(self):
     """Create action for import OSM Dialog."""
     icon = resources_path('img', 'icons', 'add-petabencana-layer.svg')
     self.action_add_petabencana_layer = QAction(
         QIcon(icon), self.tr('Add PetaBencana Flood Layer'),
         self.iface.mainWindow())
     self.action_add_petabencana_layer.setStatusTip(
         self.tr('Add PetaBencana Flood Layer'))
     self.action_add_petabencana_layer.setWhatsThis(
         self.tr('Use this to add a PetaBencana layer to your map. '
                 'It needs internet access to function.'))
     self.action_add_petabencana_layer.triggered.connect(
         self.add_petabencana_layer)
     self.add_action(self.action_add_petabencana_layer,
                     add_to_toolbar=self.full_toolbar)
Пример #50
0
 def _create_keywords_action(self):
     """Create action for keywords editor."""
     icon = resources_path('img', 'icons', 'show-keyword-editor.svg')
     self.action_keywords_dialog = QAction(
         QIcon(icon), self.tr('InaSAFE Keyword Editor'),
         self.iface.mainWindow())
     self.action_keywords_dialog.setStatusTip(
         self.tr('Open InaSAFE keywords editor'))
     self.action_keywords_dialog.setWhatsThis(
         self.tr('Open InaSAFE keywords editor'))
     self.action_keywords_dialog.setEnabled(False)
     self.action_keywords_dialog.triggered.connect(
         self.show_keywords_editor)
     self.add_action(self.action_keywords_dialog,
                     add_to_toolbar=self.full_toolbar)
Пример #51
0
def get_image_path(definition):
    """Helper to get path of image from a definition in resource directory.

    :param definition: A definition (hazard, exposure).
    :type definition: dict

    :returns: The definition's image path.
    :rtype: str
    """
    path = resources_path('img', 'wizard',
                          'keyword-subcategory-%s.svg' % definition['key'])
    if os.path.exists(path):
        return path
    else:
        return not_set_image_path
Пример #52
0
def getting_started_message():
    """Generate a message for initial application state.

    :returns: Information for the user on how to get started.
    :rtype: safe.messaging.Message
    """
    message = m.Message()
    message.add(LOGO_ELEMENT)
    message.add(m.Heading(tr('Getting started'), **INFO_STYLE))
    notes = m.Paragraph(
        tr(
            'These are the minimum steps you need to follow in order '
            'to use InaSAFE:'))
    message.add(notes)
    basics_list = m.NumberedList()
    basics_list.add(m.Paragraph(
        tr('Add at least one '),
        m.ImportantText(tr('hazard'), **KEYWORD_STYLE),
        tr(' layer (e.g. earthquake MMI) to QGIS.')))
    basics_list.add(m.Paragraph(
        tr('Add at least one '),
        m.ImportantText(tr('exposure'), **KEYWORD_STYLE),
        tr(' layer (e.g. structures) to QGIS.')))
    basics_list.add(m.Paragraph(
        tr(
            'Make sure you have defined keywords for your hazard and '
            'exposure layers. You can do this using the '
            'keywords creation wizard '),
        m.Image(
            'file:///%s/img/icons/show-keyword-wizard.svg' %
            (resources_path()), **SMALL_ICON_STYLE),
        tr(' in the toolbar.')))
    basics_list.add(m.Paragraph(
        tr('Click on the '),
        m.ImportantText(tr('Run'), **KEYWORD_STYLE),
        tr(' button below.')))
    message.add(basics_list)

    message.add(m.Heading(tr('Limitations'), **WARNING_STYLE))
    caveat_list = m.NumberedList()
    for limitation in limitations():
        caveat_list.add(limitation)
    message.add(caveat_list)

    message.add(m.Heading(tr('Disclaimer'), **WARNING_STYLE))
    message.add(m.Paragraph(disclaimer()))

    return message
Пример #53
0
 def _create_dock_toggle_action(self):
     """Create action for plugin dockable window (show/hide)."""
     # pylint: disable=W0201
     icon = resources_path('img', 'icons', 'icon.svg')
     self.action_dock = QAction(
         QIcon(icon),
         self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow())
     self.action_dock.setObjectName('InaSAFEDockToggle')
     self.action_dock.setStatusTip(self.tr(
         'Show/hide InaSAFE dock widget'))
     self.action_dock.setWhatsThis(self.tr(
         'Show/hide InaSAFE dock widget'))
     self.action_dock.setCheckable(True)
     self.action_dock.setChecked(True)
     self.action_dock.triggered.connect(self.toggle_dock_visibility)
     self.add_action(self.action_dock)
Пример #54
0
    def template(self, template):
        """Set template that will be used for report generation.

        :param template: Path to composer template
        :type template: str
        """
        if isinstance(template, basestring) and os.path.exists(template):
            self._template = template
        else:
            self._template = resources_path(
                'qgis-composer-templates', 'a4-portrait-blue.qpt')

        # Also recreate template composition
        self._template_composition = TemplateComposition(
            template_path=self.template,
            map_settings=self._iface.mapCanvas().mapSettings())
Пример #55
0
    def test_update_template_component(self):
        """Test for custom template component."""
        # Default qpt
        component = update_template_component(map_report, '.')
        self.assertDictEqual(component, map_report)

        # Custom qpt
        target_directory = mkdtemp()
        default_qpt = resources_path('qgis-composer-templates',
                                     'inasafe-map-report-portrait.qpt')
        if exists(default_qpt):
            target_path = join(target_directory, split(default_qpt)[1])
            shutil.copy2(default_qpt, target_path)

        component = update_template_component(map_report, target_directory)
        self.assertTrue(component != map_report)
Пример #56
0
 def save_log_to_html(self):
     """Helper to write the log out as an html file."""
     html = html_header()
     html += ('<img src="file:///%s/img/logos/inasafe-logo-url.png" '
              'title="InaSAFE Logo" alt="InaSAFE Logo" />' %
              resources_path())
     html += ('<h5 class="info"><i class="icon-info-sign icon-white"></i> '
              '%s</h5>' % self.tr('Analysis log'))
     for item in self.dynamic_messages_log:
         html += "%s\n" % item.to_html()
     html += html_footer()
     if self.log_path is not None:
         html_to_file(html, self.log_path)
     else:
         msg = self.tr('log_path is not set')
         raise InvalidParameterError(msg)
Пример #57
0
    def _create_test_layers_action(self):
        """Create action for adding layers (developer mode, non final only)."""
        final_release = inasafe_release_status == 'final'
        settings = QSettings()
        self.developer_mode = settings.value('inasafe/developer_mode',
                                             False,
                                             type=bool)
        if not final_release and self.developer_mode:
            icon = resources_path('img', 'icons', 'add-test-layers.svg')
            self.action_add_layers = QAction(QIcon(icon),
                                             self.tr('Add Test Layers'),
                                             self.iface.mainWindow())
            self.action_add_layers.setStatusTip(self.tr('Add test layers'))
            self.action_add_layers.setWhatsThis(self.tr('Add test layers'))
            self.action_add_layers.triggered.connect(self.add_test_layers)

            self.add_action(self.action_add_layers)
Пример #58
0
    def __init__(self, iface, dock):
        """Constructor for the class."""
        QDialog.__init__(self)
        # Class Member
        self.iface = iface
        self.dock = dock
        self.output_directory = None
        self.exposure_layer = None
        self.hazard_layer = None
        self.aggregation_layer = None
        self.keyword_io = KeywordIO()

        icon = resources_path('img', 'icons', 'save-as-scenario.svg')
        self.setWindowIcon(QtGui.QIcon(icon))

        # Calling some init methods
        self.restore_state()
Пример #59
0
    def _create_run_test_action(self):
        """Create action for running tests (developer mode, non final only)."""
        final_release = release_status() == 'final'
        settings = QSettings()
        self.developer_mode = settings.value(
            'inasafe/developer_mode', False, type=bool)
        if not final_release and self.developer_mode:

            default_package = unicode(settings.value(
                'inasafe/testPackage', 'safe', type=str))
            msg = self.tr('Run tests in %s' % default_package)

            self.test_button = QToolButton()
            self.test_button.setMenu(QMenu())
            self.test_button.setPopupMode(QToolButton.MenuButtonPopup)

            icon = resources_path('img', 'icons', 'run-tests.svg')
            self.action_run_tests = QAction(
                QIcon(icon),
                msg,
                self.iface.mainWindow())

            self.action_run_tests.setStatusTip(msg)
            self.action_run_tests.setWhatsThis(msg)
            self.action_run_tests.triggered.connect(
                self.run_tests)

            self.test_button.menu().addAction(self.action_run_tests)
            self.test_button.setDefaultAction(self.action_run_tests)

            self.action_select_package = QAction(
                QIcon(icon),
                self.tr('Select package'),
                self.iface.mainWindow())

            self.action_select_package.setStatusTip(self.tr(
                'Select Test Package'))
            self.action_select_package.setWhatsThis(self.tr(
                'Select Test Package'))
            self.action_select_package.triggered.connect(
                self.select_test_package)
            self.test_button.menu().addAction(self.action_select_package)
            self.toolbar.addWidget(self.test_button)

            self.add_action(self.action_run_tests, add_to_toolbar=False)
            self.add_action(self.action_select_package, add_to_toolbar=False)
Пример #60
0
 def _create_rubber_bands_action(self):
     """Create action for toggling rubber bands."""
     icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
     self.action_toggle_rubberbands = QAction(
         QIcon(icon), self.tr('Toggle Scenario Outlines'),
         self.iface.mainWindow())
     message = self.tr('Toggle rubber bands showing scenario extents.')
     self.action_toggle_rubberbands.setStatusTip(message)
     self.action_toggle_rubberbands.setWhatsThis(message)
     # Set initial state
     self.action_toggle_rubberbands.setCheckable(True)
     flag = setting('showRubberBands', False, expected_type=bool)
     self.action_toggle_rubberbands.setChecked(flag)
     # noinspection PyUnresolvedReferences
     self.action_toggle_rubberbands.triggered.connect(
         self.dock_widget.toggle_rubber_bands)
     self.add_action(self.action_toggle_rubberbands)