def processAlgorithm(self, parameters, context, feedback):

        if Qgis.QGIS_VERSION_INT >= 31400:
            connection_name = self.parameterAsConnectionName(
                parameters, self.CONNECTION_NAME, context)
        else:
            connection_name = self.parameterAsString(
                parameters, self.CONNECTION_NAME, context)

        # Write the file out again
        project_file = self.parameterAsString(parameters, self.PROJECT_FILE, context)

        metadata = QgsProviderRegistry.instance().providerMetadata('postgres')
        connection = metadata.findConnection(connection_name)

        # Read in the template file
        template_file = resources_path('projects', 'pg_metadata_administration.qgs')
        with open(template_file, 'r') as fin:
            file_data = fin.read()

        # Replace the database connection information
        file_data = file_data.replace("service='pgmetadata'", connection.uri())

        with open(project_file, 'w') as fout:
            fout.write(file_data)

        add_connection(connection_name)

        msg = tr('QGIS Administration project has been successfully created from the database connection')
        msg += ': {}'.format(connection_name)
        feedback.pushInfo(msg)

        return {}
Ejemplo n.º 2
0
    def export_dock_content(self, output_format: OutputFormats):
        """ Export the current displayed metadata sheet to the given format. """
        layer_name = iface.activeLayer().name()

        file_path = os.path.join(
            self.settings.value("UI/lastFileNameWidgetDir"),
            '{name}.{ext}'.format(name=layer_name,
                                  ext=output_format.value['ext']))
        output_file = QFileDialog.getSaveFileName(
            self,
            tr("Save File as {format}").format(
                format=output_format.value['label']), file_path,
            "{label} (*.{ext})".format(
                label=output_format.value['label'],
                ext=output_format.value['ext'],
            ))
        if output_file[0] == '':
            return

        self.settings.setValue("UI/lastFileNameWidgetDir",
                               os.path.dirname(output_file[0]))

        if output_format == OutputFormats.Pdf:
            printer = QPrinter()
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setPageMargins(20, 20, 20, 20, QPrinter.Millimeter)
            printer.setOutputFileName(output_file[0])
            self.viewer.print(printer)
            iface.messageBar().pushSuccess(
                tr("Export PDF"),
                tr("The metadata has been exported as PDF successfully"))

        elif output_format in [OutputFormats.Html, OutputFormats.Dcat]:
            if output_format == OutputFormats.Html:
                data_str = self.viewer.page().currentFrame().toHtml()
            else:
                sql = self.sql_for_layer(self.current_datasource_uri,
                                         output_format=OutputFormats.Dcat)
                data = self.current_connection.executeSql(sql)
                with open(resources_path('xml', 'dcat.xml')) as xml_file:
                    xml_template = xml_file.read()

                locale = QgsSettings().value("locale/userLocale",
                                             QLocale().name())
                locale = locale.split('_')[0].lower()

                xml = parseString(
                    xml_template.format(locale=locale, content=data[0][0]))
                data_str = xml.toprettyxml()

            file_writer = open(output_file[0], "w")
            file_writer.write(data_str)
            file_writer.close()
            iface.messageBar().pushSuccess(
                tr("Export") + ' ' + output_format.value['label'],
                tr("The metadata has been exported as {format} successfully").
                format(format=output_format.value['label']))
Ejemplo n.º 3
0
    def set_html_content(self, title=None, body=None):
        """ Set the content in the dock. """

        css_file = resources_path('css', 'dock.css')
        with open(css_file, 'r') as f:
            css = f.read()

        html = '<html><head><style>{css}</style></head><body>'.format(css=css)

        if title:
            html += '<h2>{title}</h2>'.format(title=title)

        if body:
            html += body

        html += '</body></html>'

        # It must be a file, even if it does not exist on the file system.
        base_url = QUrl.fromLocalFile(resources_path('images', 'must_be_a_file.png'))
        self.viewer.setHtml(html, base_url)
Ejemplo n.º 4
0
def icon_for_geometry_type(geometry_type: str) -> QIcon():
    """ Return the correct icon according to the geometry type. """
    if geometry_type == NULL:
        return QgsLayerItem.iconTable()

    elif geometry_type == 'POINT':
        return QgsLayerItem.iconPoint()

    elif geometry_type == 'LINESTRING':
        return QgsLayerItem.iconLine()

    elif geometry_type == 'MULTIPOLYGON':
        return QgsLayerItem.iconPolygon()

    # Default icon
    return QIcon(resources_path('icons', 'icon.png'))
Ejemplo n.º 5
0
    def processAlgorithm(self, parameters, context, feedback):
        metadata = QgsProviderRegistry.instance().providerMetadata('postgres')
        if Qgis.QGIS_VERSION_INT >= 31400:
            connection_name = self.parameterAsConnectionName(
                parameters, self.CONNECTION_NAME, context)
        else:
            connection_name = self.parameterAsString(parameters,
                                                     self.CONNECTION_NAME,
                                                     context)

        connection = metadata.findConnection(connection_name)
        if not connection:
            raise QgsProcessingException(
                tr("The connection {} does not exist.").format(
                    connection_name))

        for template in ["contact", "link", "main"]:
            feedback.pushInfo(tr('Reset {}.html').format(template))

            sql = ("DELETE FROM pgmetadata.html_template "
                   "WHERE section = '{}'").format(template)
            try:
                connection.executeSql(sql)
            except QgsProviderConnectionException as e:
                feedback.reportError(str(e))

            html_file = resources_path("html", "{}.html".format(template))
            with open(html_file, "r") as f:
                sql = (
                    "INSERT INTO pgmetadata.html_template (section, content) "
                    "VALUES ('{section}', '{value}');".format(section=template,
                                                              value=f.read()))
            try:
                connection.executeSql(sql)
            except QgsProviderConnectionException as e:
                feedback.reportError(str(e))

        add_connection(connection_name)

        results = {}
        return results
Ejemplo n.º 6
0
    def initGui(self):
        """ Build the plugin GUI. """
        self.initProcessing()

        icon = QIcon(resources_path('icons', 'icon.png'))

        # Open the online help
        self.help_action = QAction(icon, 'PgMetadata', iface.mainWindow())
        iface.pluginHelpMenu().addAction(self.help_action)
        self.help_action.triggered.connect(self.open_help)

        if not self.dock:
            self.dock = PgMetadataDock()
            iface.addDockWidget(Qt.RightDockWidgetArea, self.dock)

            # Open/close the dock from plugin menu
            self.dock_action = QAction(icon, 'PgMetadata', iface.mainWindow())
            iface.pluginMenu().addAction(self.dock_action)
            self.dock_action.triggered.connect(self.open_dock)

        if not self.locator_filter:
            self.locator_filter = LocatorFilter(iface)
            iface.registerLocatorFilter(self.locator_filter)
Ejemplo n.º 7
0
 def icon(self):
     return QIcon(resources_path("icons", "icon.png"))