def set_existing_extra_keywords(self):
     """Set extra keywords from the value from metadata."""
     extra_keywords = self.parent.get_existing_keyword('extra_keywords')
     for key, widgets in list(self.widgets_dict.items()):
         value = extra_keywords.get(key)
         if value is None:
             widgets[0].setChecked(False)
         else:
             widgets[0].setChecked(True)
             if isinstance(widgets[1], QLineEdit):
                 widgets[1].setText(value)
             elif isinstance(widgets[1], QComboBox):
                 value_index = widgets[1].findData(value)
                 widgets[1].setCurrentIndex(value_index)
             elif isinstance(widgets[1], QDoubleSpinBox):
                 try:
                     value = float(value)
                     widgets[1].setValue(value)
                 except ValueError:
                     LOGGER.warning('Failed to convert %s to float' % value)
             elif isinstance(widgets[1], QDateTimeEdit):
                 try:
                     value_datetime = datetime.strptime(
                         value, "%Y-%m-%dT%H:%M:%S.%f")
                     widgets[1].setDateTime(value_datetime)
                 except ValueError:
                     try:
                         value_datetime = datetime.strptime(
                             value, "%Y-%m-%dT%H:%M:%S")
                         widgets[1].setDateTime(value_datetime)
                     except ValueError:
                         LOGGER.info(
                             'Failed to convert %s to datetime' % value)
Exemple #2
0
 def set_existing_extra_keywords(self):
     """Set extra keywords from the value from metadata."""
     extra_keywords = self.parent.get_existing_keyword('extra_keywords')
     for key, widgets in list(self.widgets_dict.items()):
         value = extra_keywords.get(key)
         if value is None:
             widgets[0].setChecked(False)
         else:
             widgets[0].setChecked(True)
             if isinstance(widgets[1], QLineEdit):
                 widgets[1].setText(value)
             elif isinstance(widgets[1], QComboBox):
                 value_index = widgets[1].findData(value)
                 widgets[1].setCurrentIndex(value_index)
             elif isinstance(widgets[1], QDoubleSpinBox):
                 try:
                     value = float(value)
                     widgets[1].setValue(value)
                 except ValueError:
                     LOGGER.warning('Failed to convert %s to float' % value)
             elif isinstance(widgets[1], QDateTimeEdit):
                 try:
                     value_datetime = datetime.strptime(
                         value, "%Y-%m-%dT%H:%M:%S.%f")
                     widgets[1].setDateTime(value_datetime)
                 except ValueError:
                     try:
                         value_datetime = datetime.strptime(
                             value, "%Y-%m-%dT%H:%M:%S")
                         widgets[1].setDateTime(value_datetime)
                     except ValueError:
                         LOGGER.info(
                             'Failed to convert %s to datetime' % value)
Exemple #3
0
 def show_field_mapping(self):
     """Show InaSAFE Field Mapping."""
     from safe.gui.tools.field_mapping_dialog import FieldMappingDialog
     dialog = FieldMappingDialog(
         parent=self.iface.mainWindow(),
         iface=self.iface,
     )
     if dialog.exec_():  # modal
         LOGGER.debug('Show field mapping accepted')
         self.dock_widget.layer_changed(self.iface.activeLayer())
     else:
         LOGGER.debug('Show field mapping not accepted')
Exemple #4
0
def organisation_logo_path(feature, parent):
    """Retrieve the full path of used specified organisation logo."""
    _ = feature, parent  # NOQA
    organisation_logo_file = setting(
        inasafe_organisation_logo_path['setting_key'])
    if os.path.exists(organisation_logo_file):
        return organisation_logo_file
    else:
        LOGGER.info(
            'The custom organisation logo is not found in {logo_path}. '
            'Default organisation logo will be used.').format(
            logo_path=organisation_logo_file)
        return inasafe_default_settings['organisation_logo_path']
Exemple #5
0
def north_arrow_path(feature, parent):
    """Retrieve the full path of default north arrow logo."""
    _ = feature, parent  # NOQA

    north_arrow_file = setting(inasafe_north_arrow_path['setting_key'])
    if os.path.exists(north_arrow_file):
        return north_arrow_file
    else:
        LOGGER.info(
            'The custom north arrow is not found in {north_arrow_file}. '
            'Default north arrow will be used.').format(
            north_arrow_file=north_arrow_file)
        return inasafe_default_settings['north_arrow_path']
Exemple #6
0
def organisation_logo_path(feature, parent):
    """Retrieve the full path of used specified organisation logo."""
    _ = feature, parent  # NOQA
    organisation_logo_file = setting(
        inasafe_organisation_logo_path['setting_key'])
    if os.path.exists(organisation_logo_file):
        return organisation_logo_file
    else:
        LOGGER.info(
            'The custom organisation logo is not found in {logo_path}. '
            'Default organisation logo will be used.').format(
                logo_path=organisation_logo_file)
        return inasafe_default_settings['organisation_logo_path']
Exemple #7
0
def north_arrow_path(feature, parent):
    """Retrieve the full path of default north arrow logo."""
    _ = feature, parent  # NOQA

    north_arrow_file = setting(inasafe_north_arrow_path['setting_key'])
    if os.path.exists(north_arrow_file):
        return north_arrow_file
    else:
        LOGGER.info(
            'The custom north arrow is not found in {north_arrow_file}. '
            'Default north arrow will be used.').format(
                north_arrow_file=north_arrow_file)
        return inasafe_default_settings['north_arrow_path']
Exemple #8
0
    def clear_modules():
        """Unload inasafe functions and try to return QGIS to before InaSAFE.

        .. todo:: I think this function can be removed. TS.
        """
        # next lets force remove any inasafe related modules
        modules = []
        for module in sys.modules:
            if 'inasafe' in module:
                # Check if it is really one of our modules i.e. exists in the
                # plugin directory
                tokens = module.split('.')
                path = ''
                for myToken in tokens:
                    path += os.path.sep + myToken
                parent = os.path.abspath(
                    os.path.join(__file__, os.path.pardir, os.path.pardir))
                full_path = os.path.join(parent, path + '.py')
                if os.path.exists(os.path.abspath(full_path)):
                    LOGGER.debug('Removing: %s' % module)
                    modules.append(module)
        for module in modules:
            del (sys.modules[module])
        for module in sys.modules:
            if 'inasafe' in module:
                print(module)

        # Lets also clean up all the path additions that were made
        package_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), os.path.pardir))
        LOGGER.debug('Path to remove: %s' % package_path)
        # We use a list comprehension to ensure duplicate entries are removed
        LOGGER.debug(sys.path)
        sys.path = [y for y in sys.path if package_path not in y]
        LOGGER.debug(sys.path)
def clean_layer(layer):
    """Clean a vector layer.

    :param layer: The vector layer.
    :type layer: QgsVectorLayer

    :return: The buffered vector layer.
    :rtype: QgsVectorLayer
    """
    output_layer_name = clean_geometry_steps['output_layer_name']
    output_layer_name = output_layer_name % layer.keywords['layer_purpose']

    # start editing
    layer.startEditing()
    count = 0

    # iterate through all features
    request = QgsFeatureRequest().setSubsetOfAttributes([])
    for feature in layer.getFeatures(request):
        geom = feature.geometry()
        was_valid, geometry_cleaned = geometry_checker(geom)

        if was_valid:
            # Do nothing if it was valid
            pass
        elif not was_valid and geometry_cleaned:
            # Update the geometry if it was not valid, and clean now
            layer.changeGeometry(feature.id(), geometry_cleaned, True)
        else:
            # Delete if it was not valid and not able to be cleaned
            count += 1
            layer.deleteFeature(feature.id())

    if count:
        LOGGER.critical(
            '%s features have been removed from %s because of invalid '
            'geometries.' % (count, layer.name()))
    else:
        LOGGER.info('No feature has been removed from the layer: %s' %
                    layer.name())

    # save changes
    layer.commitChanges()
    layer.keywords['title'] = output_layer_name

    check_layer(layer)
    return layer
Exemple #10
0
def clean_layer(layer):
    """Clean a vector layer.

    :param layer: The vector layer.
    :type layer: QgsVectorLayer

    :return: The buffered vector layer.
    :rtype: QgsVectorLayer
    """
    output_layer_name = clean_geometry_steps['output_layer_name']
    output_layer_name = output_layer_name % layer.keywords['layer_purpose']

    # start editing
    layer.startEditing()
    count = 0

    # iterate through all features
    request = QgsFeatureRequest().setSubsetOfAttributes([])
    for feature in layer.getFeatures(request):
        geom = feature.geometry()
        was_valid, geometry_cleaned = geometry_checker(geom)

        if was_valid:
            # Do nothing if it was valid
            pass
        elif not was_valid and geometry_cleaned:
            # Update the geometry if it was not valid, and clean now
            layer.changeGeometry(feature.id(), geometry_cleaned, True)
        else:
            # Delete if it was not valid and not able to be cleaned
            count += 1
            layer.deleteFeature(feature.id())

    if count:
        LOGGER.critical(
            '%s features have been removed from %s because of invalid '
            'geometries.' % (count, layer.name()))
    else:
        LOGGER.info(
            'No feature has been removed from the layer: %s' % layer.name())

    # save changes
    layer.commitChanges()
    layer.keywords['title'] = output_layer_name

    check_layer(layer)
    return layer
Exemple #11
0
def clean_layer(layer):
    """Clean a vector layer.

    :param layer: The vector layer.
    :type layer: qgis.core.QgsVectorLayer

    :return: The buffered vector layer.
    :rtype: qgis.core.QgsVectorLayer
    """
    output_layer_name = clean_geometry_steps['output_layer_name']
    output_layer_name = output_layer_name % layer.keywords['layer_purpose']

    count = layer.featureCount()

    parameters = {'INPUT': layer, 'OUTPUT': 'memory:'}

    initialize_processing()

    feedback = create_processing_feedback()
    context = create_processing_context(feedback=feedback)
    result = processing.run('qgis:fixgeometries', parameters, context=context)
    if result is None:
        raise ProcessingInstallationError

    cleaned = result['OUTPUT']
    cleaned.setName(output_layer_name)

    removed_count = count - cleaned.featureCount()

    if removed_count:
        LOGGER.critical(
            '{removed_count} features have been removed from {layer_name} '
            'because of invalid geometries.'.format(
                removed_count=removed_count, layer_name=layer.name()))
    else:
        LOGGER.info('No feature has been removed from the layer: '
                    '{layer_name}'.format(layer_name=layer.name()))

    cleaned.keywords = layer.keywords.copy()
    cleaned.keywords['title'] = output_layer_name
    check_layer(cleaned)

    return cleaned
Exemple #12
0
def clean_layer(layer, callback=None):
    """Clean a vector layer.

    :param layer: The vector layer.
    :type layer: QgsVectorLayer

    :param callback: A function to all to indicate progress. The function
        editing should accept params 'current' (int), 'maximum' (int) and
        'step' (str). Defaults to None.
    :type callback: function

    :return: The buffered vector layer.
    :rtype: QgsVectorLayer
    """
    output_layer_name = clean_geometry_steps['output_layer_name']
    processing_step = clean_geometry_steps['step_name']  # NOQA
    output_layer_name = output_layer_name % layer.keywords['layer_purpose']

    # start editing
    layer.startEditing()
    count = 0

    # iterate through all features
    for feature in layer.getFeatures():
        geom = feature.geometry()
        geometry_cleaned = geometry_checker(geom)
        if geometry_cleaned:
            feature.setGeometry(geometry_cleaned)
        else:
            count += 1
            layer.deleteFeature(feature.id())

    LOGGER.critical(
        '%s features have been removed from %s because of invalid geometries.'
        % (count, layer.name()))

    # save changes
    layer.commitChanges()

    layer.keywords['title'] = output_layer_name

    check_layer(layer)
    return layer