Ejemplo n.º 1
0
    def add_styles(self, feedback, input_layers):
        """ Add all QML style in the resource folder to given layers. """
        feedback.pushInfo("Ajout des styles")
        qml_component = OrderedDict()
        qml_component['style'] = QgsMapLayer.Symbology
        qml_component['fields'] = QgsMapLayer.Fields
        qml_component['form'] = QgsMapLayer.Forms
        qml_component['labels'] = QgsMapLayer.Labeling
        qml_component['layer_configuration'] = QgsMapLayer.LayerConfiguration

        for layer_name, vector_layer in input_layers.items():
            qml_list = []
            has_labels = False
            for name, component in qml_component.items():
                qml_file = resources_path('qml', name,
                                          '{}.qml'.format(layer_name))
                if not os.path.exists(qml_file):
                    continue
                self.success_qml += 1
                qml_list.append(qml_file)
                if component == QgsMapLayer.Labeling:
                    has_labels = True

            if not qml_list:
                continue

            output_file = str(
                self.combine_qml(layer_name, qml_list, has_labels))
            feedback.pushDebugInfo(output_file)
            message, flag = vector_layer.loadNamedStyle(output_file)
            if flag:
                feedback.reportError(message)
            feedback.pushInfo(
                vector_layer.name() +
                " QML for {} successfully loaded".format(layer_name))
    def processAlgorithm(self, parameters, context, feedback):
        input_layer = self.parameterAsVectorLayer(parameters, self.INPUT_LAYER, context)
        self.output = self.parameterAsVectorLayer(parameters, self.OUTPUT_LAYER, context)

        self.input_fields = input_layer.fields().names()
        has_geom = 'latitude' in self.input_fields and 'longitude' in self.input_fields
        if has_geom:
            feedback.pushInfo('Les champs latitude et longitude sont détectés.')
        else:
            feedback.pushInfo('Les champs latitude et longitude ne sont pas détectés.')

        # Observation fields
        path = resources_path('data_models', 'observations.csv')
        csv = load_csv('observations', path)
        self.fields = list(csv.uniqueValues(1))
        self.fields.append('latitude')
        self.fields.append('longitude')

        for feature in input_layer.getFeatures():
            exists, existing = self.observation_exists(self.output, feature['id'])
            if exists:
                self.update_feature(feature, existing, has_geom, context, feedback)
            else:
                self.create_feature(feature, has_geom, context, feedback)

        return {}
Ejemplo n.º 3
0
    def combine_qml(layer_name: str, qml_list: list, has_labels: bool) -> Path:
        """ Combine a few QML together in a single file. """
        # Actions is missing from categories because it is managed with Python code
        qml_str = (
            '<!DOCTYPE qgis PUBLIC \'http://mrcc.com/qgis.dtd\' \'SYSTEM\'>\n'
            '<qgis simplifyAlgorithm="0" readOnly="0" simplifyLocal="1" simplifyDrawingHints="1" '
            'simplifyMaxScale="1" hasScaleBasedVisibilityFlag="0" maxScale="0" labelsEnabled="{label}" '
            'styleCategories="LayerConfiguration|Symbology|Symbology3D|Labeling|Fields|Forms|MapTips|Diagrams'
            '|AttributeTable|Rendering|CustomProperties|GeometryOptions|Relations|Temporal|Legend|Elevation" '
            'simplifyDrawingTol="1" version="{version}" minScale="100000000">\n'
            .format(label='1' if has_labels else '0',
                    version=Qgis.QGIS_VERSION))

        for qml in qml_list:
            with open(qml, 'r', encoding='utf-8') as f:
                qml_str += ''.join(f.readlines()[2:-1])

        qml_str += '</qgis>'

        output_file = Path(
            resources_path('qml', 'auto_generated',
                           '{}.qml'.format(layer_name)))
        if output_file.exists():
            # Do not use missing_ok, Python 3.8 min
            output_file.unlink()

        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(qml_str)

        return output_file
Ejemplo n.º 4
0
    def initGui(self):
        self.initProcessing()

        # Open the online help
        self.help_action = QAction(QIcon(resources_path('icons', 'icon.png')),
                                   'Mercicor', self.iface.mainWindow())
        self.iface.pluginHelpMenu().addAction(self.help_action)
        self.help_action.triggered.connect(self.open_help)
Ejemplo n.º 5
0
    def add_alias_from_csv(feedback, input_layers):
        """ The geopackage has been created from CSV files, but we need to set alias. """
        feedback.pushInfo(
            "Relecture du CSV pour réappliquer les alias sur les champs sur")

        for name, layer in input_layers.items():
            feedback.pushInfo("   {}".format(name))
            path = resources_path('data_models', '{}.csv'.format(name))
            csv = load_csv(name, path)

            for csv_feature in csv.getFeatures():
                index = layer.fields().indexOf(csv_feature['name'])
                if not index:
                    continue

                layer.setFieldAlias(index, csv_feature['alias'])
Ejemplo n.º 6
0
 def icon(self):
     icon = resources_path('icons', 'icon.png')
     if os.path.isfile(icon):
         return QIcon(icon)
     return super().icon()
Ejemplo n.º 7
0
 def icon(self):
     return QIcon(resources_path('icons', 'icon.png'))
Ejemplo n.º 8
0
    def create_geopackage(project_type: ProjectType, file_path, crs,
                          transform_context) -> None:
        """ Create the geopackage for the given path. """
        encoding = 'UTF-8'
        driver_name = QgsVectorFileWriter.driverForExtension('gpkg')
        for table in project_type.layers:

            layer_path = str(tables[table])
            if layer_path != 'None':
                layer_path += "?crs={}".format(crs.authid())

            vector_layer = QgsVectorLayer(layer_path, table, "memory")
            data_provider = vector_layer.dataProvider()

            fields = QgsFields()

            path = resources_path('data_models', '{}.csv'.format(table))
            csv = load_csv(table, path)

            for csv_feature in csv.getFeatures():
                field = QgsField(name=csv_feature['name'],
                                 type=int(csv_feature['type']))
                field.setComment(csv_feature['comment'])
                field.setAlias(csv_feature['alias'])
                fields.append(field)

            del csv

            # add fields
            data_provider.addAttributes(fields)
            vector_layer.updateFields()

            # set create file layer options
            options = QgsVectorFileWriter.SaveVectorOptions()
            options.driverName = driver_name
            options.fileEncoding = encoding

            options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteFile
            if os.path.exists(file_path):
                options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer

            options.layerName = vector_layer.name()
            options.layerOptions = ['FID=id']

            # write file
            if Qgis.QGIS_VERSION_INT >= 31900:
                write_result, error_message, _, _ = QgsVectorFileWriter.writeAsVectorFormatV3(
                    vector_layer, file_path, transform_context, options)
            else:
                # 3.10 <= QGIS <3.18
                write_result, error_message = QgsVectorFileWriter.writeAsVectorFormatV2(
                    vector_layer, file_path, transform_context, options)

            # result
            if write_result != QgsVectorFileWriter.NoError:
                raise QgsProcessingException(
                    '* ERROR: {}'.format(error_message))

            del fields
            del data_provider
            del vector_layer
Ejemplo n.º 9
0
 def icon(self):
     return QIcon(resources_path("icons", "icon.png"))