Exemplo n.º 1
0
 def unload(self):
     """Setting should be removed here, so they do not appear anymore
     when the plugin is unloaded.
     """
     ProcessingConfig.removeSetting('ACTIVATE_EXAMPLE')
     ProcessingConfig.removeSetting(
         ExampleAlgorithmProvider.MY_DUMMY_SETTING)
Exemplo n.º 2
0
def load(fileName, name=None, crs=None, style=None, isRaster=False):
    """Loads a layer/table into the current project, given its file.
    """

    if fileName is None:
        return
    prjSetting = None
    settings = QgsSettings()
    if crs is not None:
        prjSetting = settings.value('/Projections/defaultBehavior')
        settings.setValue('/Projections/defaultBehavior', '')
    if name is None:
        name = os.path.split(fileName)[1]

    if isRaster:
        qgslayer = QgsRasterLayer(fileName, name)
        if qgslayer.isValid():
            if crs is not None and qgslayer.crs() is None:
                qgslayer.setCrs(crs, False)
            if style is None:
                style = ProcessingConfig.getSetting(
                    ProcessingConfig.RASTER_STYLE)
            qgslayer.loadNamedStyle(style)
            QgsProject.instance().addMapLayers([qgslayer])
        else:
            if prjSetting:
                settings.setValue('/Projections/defaultBehavior', prjSetting)
            raise RuntimeError(
                QCoreApplication.translate(
                    'dataobject',
                    'Could not load layer: {0}\nCheck the processing framework log to look for errors.'
                ).format(fileName))
    else:
        qgslayer = QgsVectorLayer(fileName, name, 'ogr')
        if qgslayer.isValid():
            if crs is not None and qgslayer.crs() is None:
                qgslayer.setCrs(crs, False)
            if style is None:
                if qgslayer.geometryType() == QgsWkbTypes.PointGeometry:
                    style = ProcessingConfig.getSetting(
                        ProcessingConfig.VECTOR_POINT_STYLE)
                elif qgslayer.geometryType() == QgsWkbTypes.LineGeometry:
                    style = ProcessingConfig.getSetting(
                        ProcessingConfig.VECTOR_LINE_STYLE)
                else:
                    style = ProcessingConfig.getSetting(
                        ProcessingConfig.VECTOR_POLYGON_STYLE)
            qgslayer.loadNamedStyle(style)
            QgsProject.instance().addMapLayers([qgslayer])

    if prjSetting:
        settings.setValue('/Projections/defaultBehavior', prjSetting)

    return qgslayer
def createMenus():
    for alg in QgsApplication.processingRegistry().algorithms():
        menuPath = ProcessingConfig.getSetting("MENU_" + alg.id())
        addButton = ProcessingConfig.getSetting("BUTTON_" + alg.id())
        icon = ProcessingConfig.getSetting("ICON_" + alg.id())
        if icon and os.path.exists(icon):
            icon = QIcon(icon)
        else:
            icon = None
        if menuPath:
            paths = menuPath.split("/")
            addAlgorithmEntry(alg, paths[0], paths[-1], addButton=addButton, icon=icon)
Exemplo n.º 4
0
def handleAlgorithmResults(alg, context, feedback=None, showResults=True):
    wrongLayers = []
    if feedback is None:
        feedback = QgsProcessingFeedback()
    feedback.setProgressText(QCoreApplication.translate('Postprocessing', 'Loading resulting layers'))
    i = 0
    for l, details in context.layersToLoadOnCompletion().items():
        if feedback.isCanceled():
            return False

        if len(context.layersToLoadOnCompletion()) > 2:
            # only show progress feedback if we're loading a bunch of layers
            feedback.setProgress(100 * i / float(len(context.layersToLoadOnCompletion())))

        try:
            layer = QgsProcessingUtils.mapLayerFromString(l, context)
            if layer is not None:
                if not ProcessingConfig.getSetting(ProcessingConfig.USE_FILENAME_AS_LAYER_NAME):
                    layer.setName(details.name)

                style = None
                if details.outputName:
                    style = RenderingStyles.getStyle(alg.id(), details.outputName)
                if style is None:
                    if layer.type() == QgsMapLayer.RasterLayer:
                        style = ProcessingConfig.getSetting(ProcessingConfig.RASTER_STYLE)
                    else:
                        if layer.geometryType() == QgsWkbTypes.PointGeometry:
                            style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POINT_STYLE)
                        elif layer.geometryType() == QgsWkbTypes.LineGeometry:
                            style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_LINE_STYLE)
                        else:
                            style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POLYGON_STYLE)
                if style:
                    layer.loadNamedStyle(style)
                details.project.addMapLayer(context.temporaryLayerStore().takeMapLayer(layer))
            else:
                wrongLayers.append(str(l))
        except Exception:
            QgsMessageLog.logMessage(QCoreApplication.translate('Postprocessing', "Error loading result layer:") + "\n" + traceback.format_exc(), 'Processing', Qgis.Critical)
            wrongLayers.append(str(l))
        i += 1

    feedback.setProgress(100)

    if wrongLayers:
        msg = QCoreApplication.translate('Postprocessing', "The following layers were not correctly generated.")
        msg += "<ul>" + "".join(["<li>%s</li>" % lay for lay in wrongLayers]) + "</ul>"
        msg += QCoreApplication.translate('Postprocessing', "You can check the 'Log Messages Panel' in QGIS main window to find more information about the execution of the algorithm.")
        feedback.reportError(msg)

    return len(wrongLayers) == 0
 def load(self):
     ProcessingConfig.settingIcons[self.name()] = self.icon()
     ProcessingConfig.addSetting(
         Setting(self.name(),
                 ModelerUtils.MODELS_FOLDER,
                 self.tr('Models folder', 'ModelerAlgorithmProvider'),
                 ModelerUtils.defaultModelsFolder(),
                 valuetype=Setting.MULTIPLE_FOLDERS))
     ProviderActions.registerProviderActions(self, self.actions)
     ProviderContextMenuActions.registerProviderContextMenuActions(
         self.contextMenuActions)
     ProcessingConfig.readSettings()
     self.refreshAlgorithms()
     return True
    def addRecentAlgorithms(self, updating):
        showRecent = ProcessingConfig.getSetting(
            ProcessingConfig.SHOW_RECENT_ALGORITHMS)
        if showRecent:
            recent = ProcessingLog.getRecentAlgorithms()
            if len(recent) != 0:
                found = False
                if updating:
                    recentItem = self.algorithmTree.topLevelItem(0)
                    if recentItem.text(0) == self.tr('Recently used'):
                        treeWidget = recentItem.treeWidget()
                        treeWidget.takeTopLevelItem(
                            treeWidget.indexOfTopLevelItem(recentItem))

                recentItem = QTreeWidgetItem()
                recentItem.setText(0, self.tr('Recently used'))
                for algname in recent:
                    alg = QgsApplication.processingRegistry(
                    ).createAlgorithmById(algname)
                    if alg is not None:
                        algItem = TreeAlgorithmItem(alg)
                        recentItem.addChild(algItem)
                        found = True
                if found:
                    self.algorithmTree.insertTopLevelItem(0, recentItem)
                    recentItem.setExpanded(True)

            self.algorithmTree.setWordWrap(True)
    def selectFile(self):
        output = self.alg.parameterDefinition('OUTPUT')
        fileFilter = getFileFilter(output)

        settings = QgsSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)
        lastEncoding = settings.value('/Processing/encoding', 'System')
        fileDialog = QgsEncodingFileDialog(self, self.tr('Save file'), path,
                                           fileFilter, lastEncoding)
        fileDialog.setFileMode(QFileDialog.AnyFile)
        fileDialog.setAcceptMode(QFileDialog.AcceptSave)
        fileDialog.setOption(QFileDialog.DontConfirmOverwrite, False)
        if fileDialog.exec_() == QDialog.Accepted:
            files = fileDialog.selectedFiles()
            encoding = str(fileDialog.encoding())
            output.encoding = encoding
            filename = str(files[0])
            selectedFileFilter = str(fileDialog.selectedNameFilter())
            if not filename.lower().endswith(
                    tuple(re.findall("\\*(\\.[a-z]{1,10})", fileFilter))):
                ext = re.search("\\*(\\.[a-z]{1,10})", selectedFileFilter)
                if ext:
                    filename = filename + ext.group(1)
            self.leOutputFile.setText(filename)
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(filename))
            settings.setValue('/Processing/encoding', encoding)
    def textChanged(self):
        text = self.searchBox.text().strip(' ').lower()
        for item in list(self.disabledProviderItems.values()):
            item.setHidden(True)
        self._filterItem(self.algorithmTree.invisibleRootItem(),
                         [t for t in text.split(' ') if t])
        if text:
            self.algorithmTree.expandAll()
            self.disabledWithMatchingAlgs = []
            for provider in QgsApplication.processingRegistry().providers():
                if not provider.isActive():
                    for alg in provider.algorithms():
                        if text in alg.name():
                            self.disabledWithMatchingAlgs.append(provider.id())
                            break
            showTip = ProcessingConfig.getSetting(
                ProcessingConfig.SHOW_PROVIDERS_TOOLTIP)
            if showTip:
                self.txtDisabled.setVisible(bool(
                    self.disabledWithMatchingAlgs))

            if self.algorithmTree.currentItem(
            ) is None or self.algorithmTree.currentItem().isHidden():
                # if previously selected item was hidden, auto select the first visible algorithm
                first_visible = self._findFirstVisibleAlgorithm(
                    self.algorithmTree.invisibleRootItem())
                if first_visible is not None:
                    self.algorithmTree.setCurrentItem(first_visible)
        else:
            self.algorithmTree.collapseAll()
            self.algorithmTree.invisibleRootItem().child(0).setExpanded(True)
            self.txtDisabled.setVisible(False)
Exemplo n.º 9
0
    def loadVectorLayer(self, name, layer, external=False):
        """
        Creates a dedicated command to load a vector into
        temporary GRASS DB.
        :param name: name of the parameter
        :param layer: QgsMapLayer for the vector layer.
        :param external: use v.external (v.in.ogr if False).
        """
        # TODO: support multiple input formats
        if external is None:
            external = ProcessingConfig.getSetting(
                Grass7Utils.GRASS_USE_VEXTERNAL)

        # safety check: we can only use external for ogr layers which support random read
        if external:
            ds = ogr.Open(layer.source())
            if ds is not None:
                ogr_layer = ds.GetLayer()
                if ogr_layer is None or not ogr_layer.TestCapability(
                        ogr.OLCRandomRead):
                    external = False
            else:
                external = False

        self.inputLayers.append(layer)
        self.setSessionProjectionFromLayer(layer)
        destFilename = 'vector_{}'.format(os.path.basename(getTempFilename()))
        self.exportedLayers[name] = destFilename
        command = '{0}{1}{2} input="{3}" output="{4}" --overwrite -o'.format(
            'v.external' if external else 'v.in.ogr',
            ' min_area={}'.format(self.minArea) if not external else '',
            ' snap={}'.format(self.snapTolerance) if not external else '',
            os.path.normpath(layer.source()), destFilename)
        self.commands.append(command)
Exemplo n.º 10
0
def executeSaga(feedback):
    if isWindows():
        command = ['cmd.exe', '/C ', sagaBatchJobFilename()]
    else:
        os.chmod(sagaBatchJobFilename(), stat.S_IEXEC |
                 stat.S_IREAD | stat.S_IWRITE)
        command = ["'" + sagaBatchJobFilename() + "'"]
    loglines = []
    loglines.append(QCoreApplication.translate('SagaUtils', 'SAGA execution console output'))
    with subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stdin=subprocess.DEVNULL,
        stderr=subprocess.STDOUT,
        universal_newlines=True,
    ) as proc:
        try:
            for line in iter(proc.stdout.readline, ''):
                if '%' in line:
                    s = ''.join([x for x in line if x.isdigit()])
                    try:
                        feedback.setProgress(int(s))
                    except:
                        pass
                else:
                    line = line.strip()
                    if line != '/' and line != '-' and line != '\\' and line != '|':
                        loglines.append(line)
                        feedback.pushConsoleInfo(line)
        except:
            pass

    if ProcessingConfig.getSetting(SAGA_LOG_CONSOLE):
        QgsMessageLog.logMessage('\n'.join(loglines), 'Processing', Qgis.Info)
 def load(self):
     ProcessingConfig.settingIcons[self.name()] = self.icon()
     ProcessingConfig.addSetting(
         Setting("SAGA", 'ACTIVATE_SAGA', self.tr('Activate'), True))
     ProcessingConfig.addSetting(
         Setting("SAGA", SagaUtils.SAGA_IMPORT_EXPORT_OPTIMIZATION,
                 self.tr('Enable SAGA Import/Export optimizations'), False))
     ProcessingConfig.addSetting(
         Setting("SAGA", SagaUtils.SAGA_LOG_COMMANDS,
                 self.tr('Log execution commands'), True))
     ProcessingConfig.addSetting(
         Setting("SAGA", SagaUtils.SAGA_LOG_CONSOLE,
                 self.tr('Log console output'), True))
     ProcessingConfig.readSettings()
     self.refreshAlgorithms()
     return True
    def grassHelpPath():
        helpPath = ProcessingConfig.getSetting(Grass7Utils.GRASS_HELP_PATH)

        if helpPath is None:
            if isWindows() or isMac():
                if Grass7Utils.path is not None:
                    localPath = os.path.join(Grass7Utils.path, 'docs/html')
                    if os.path.exists(localPath):
                        helpPath = os.path.abspath(localPath)
            else:
                searchPaths = [
                    '/usr/share/doc/grass-doc/html', '/opt/grass/docs/html',
                    '/usr/share/doc/grass/docs/html'
                ]
                for path in searchPaths:
                    if os.path.exists(path):
                        helpPath = os.path.abspath(path)
                        break

        if helpPath is not None:
            return helpPath
        elif Grass7Utils.version:
            version = Grass7Utils.version.replace('.', '')[:2]
            return 'https://grass.osgeo.org/grass{}/manuals/'.format(version)
        else:
            # GRASS not available!
            return 'https://grass.osgeo.org/grass72/manuals/'
Exemplo n.º 13
0
    def finish(self, successful, result, context, feedback):
        keepOpen = not successful or ProcessingConfig.getSetting(
            ProcessingConfig.KEEP_DIALOG_OPEN)

        if self.iterateParam is None:

            # add html results to results dock
            for out in self.algorithm().outputDefinitions():
                if isinstance(out, QgsProcessingOutputHtml) and out.name(
                ) in result and result[out.name()]:
                    resultsList.addResult(icon=self.algorithm().icon(),
                                          name=out.description(),
                                          timestamp=time.localtime(),
                                          result=result[out.name()])

            if not handleAlgorithmResults(self.algorithm(), context, feedback,
                                          not keepOpen):
                self.resetGui()
                return

        self.setExecuted(True)
        self.setResults(result)
        self.setInfo(self.tr('Algorithm \'{0}\' finished').format(
            self.algorithm().displayName()),
                     escapeHtml=False)

        if not keepOpen:
            self.close()
        else:
            self.resetGui()
            if self.algorithm().hasHtmlOutputs():
                self.setInfo(self.tr(
                    'HTML output has been generated by this algorithm.'
                    '\nOpen the results dialog to check it.'),
                             escapeHtml=False)
Exemplo n.º 14
0
 def getRecentAlgorithms():
     recentAlgsSetting = ProcessingConfig.getSetting(
         ProcessingConfig.RECENT_ALGORITHMS)
     try:
         ProcessingLog.recentAlgs = recentAlgsSetting.split(';')
     except:
         pass
     return ProcessingLog.recentAlgs
 def initialize():
     if "model" in [
             p.id()
             for p in QgsApplication.processingRegistry().providers()
     ]:
         return
     # Add the basic providers
     for c in [
             QgisAlgorithmProvider, Grass7AlgorithmProvider,
             GdalAlgorithmProvider, SagaAlgorithmProvider,
             ScriptAlgorithmProvider, ModelerAlgorithmProvider
     ]:
         p = c()
         if QgsApplication.processingRegistry().addProvider(p):
             Processing.BASIC_PROVIDERS.append(p)
     # And initialize
     ProcessingConfig.initialize()
     ProcessingConfig.readSettings()
     RenderingStyles.loadStyles()
    def disabledProviders(self):
        showTip = ProcessingConfig.getSetting(
            ProcessingConfig.SHOW_PROVIDERS_TOOLTIP)
        if not showTip or self.tipWasClosed:
            return False

        for provider in QgsApplication.processingRegistry().providers():
            if not provider.isActive():
                return True

        return False
Exemplo n.º 17
0
 def addToLog(msg):
     try:
         # It seems that this fails sometimes depending on the msg
         # added. To avoid it stopping the normal functioning of the
         # algorithm, we catch all errors, assuming that is better
         # to miss some log info than breaking the algorithm.
         line = 'ALGORITHM' + LOG_SEPARATOR + datetime.datetime.now().strftime(
             ProcessingLog.DATE_FORMAT) + LOG_SEPARATOR \
             + msg + '\n'
         with codecs.open(ProcessingLog.logFilename(),
                          'a',
                          encoding='utf-8') as logfile:
             logfile.write(line)
         algname = msg[len('processing.run("'):]
         algname = algname[:algname.index('"')]
         if algname not in ProcessingLog.recentAlgs:
             ProcessingLog.recentAlgs.append(algname)
             recentAlgsString = ';'.join(ProcessingLog.recentAlgs[-6:])
             ProcessingConfig.setSettingValue(
                 ProcessingConfig.RECENT_ALGORITHMS, recentAlgsString)
     except:
         pass
    def grassPath():
        """
        Find GRASS path on the operating system.
        Sets global variable Grass7Utils.path
        """
        if Grass7Utils.path is not None:
            return Grass7Utils.path

        if not isWindows() and not isMac():
            return ''

        folder = ProcessingConfig.getSetting(Grass7Utils.GRASS_FOLDER) or ''
        if not os.path.exists(folder):
            folder = None

        if folder is None:
            # Under MS-Windows, we use OSGEO4W or QGIS Path for folder
            if isWindows():
                if "OSGEO4W_ROOT" in os.environ:
                    testfolder = os.path.join(str(os.environ['OSGEO4W_ROOT']),
                                              "apps")
                else:
                    testfolder = str(QgsApplication.prefixPath())
                testfolder = os.path.join(testfolder, 'grass')
                if os.path.isdir(testfolder):
                    for subfolder in os.listdir(testfolder):
                        if subfolder.startswith('grass-7'):
                            folder = os.path.join(testfolder, subfolder)
                            break
            elif isMac():
                # For MacOSX, we scan some well-known directories
                # Start with QGIS bundle
                for version in ['', '7', '70', '71', '72', '74']:
                    testfolder = os.path.join(str(QgsApplication.prefixPath()),
                                              'grass{}'.format(version))
                    if os.path.isdir(testfolder):
                        folder = testfolder
                        break
                    # If nothing found, try standalone GRASS installation
                    if folder is None:
                        for version in ['0', '1', '2', '4']:
                            testfolder = '/Applications/GRASS-7.{}.app/Contents/MacOS'.format(
                                version)
                            if os.path.isdir(testfolder):
                                folder = testfolder
                                break

        if folder is not None:
            Grass7Utils.path = folder

        return folder or ''
Exemplo n.º 19
0
def initializeMenus():
    for provider in QgsApplication.processingRegistry().providers():
        for alg in provider.algorithms():
            d = defaultMenuEntries.get(alg.id(), "")
            setting = Setting(menusSettingsGroup, "MENU_" + alg.id(),
                              "Menu path", d)
            ProcessingConfig.addSetting(setting)
            setting = Setting(menusSettingsGroup, "BUTTON_" + alg.id(),
                              "Add button", False)
            ProcessingConfig.addSetting(setting)
            setting = Setting(menusSettingsGroup, "ICON_" + alg.id(),
                              "Icon", "", valuetype=Setting.FILE)
            ProcessingConfig.addSetting(setting)

    ProcessingConfig.readSettings()
Exemplo n.º 20
0
 def load(self):
     ProcessingConfig.settingIcons[self.name()] = self.icon()
     ProcessingConfig.addSetting(
         Setting(self.name(), 'ACTIVATE_GDAL', self.tr('Activate'), True))
     ProcessingConfig.addSetting(
         Setting(self.name(), GdalUtils.GDAL_HELP_PATH,
                 self.tr('Location of GDAL docs'),
                 GdalUtils.gdalHelpPath()))
     ProcessingConfig.readSettings()
     self.refreshAlgorithms()
     return True
    def selectFile(self):
        file_filter = getFileFilter(self.parameter)
        settings = QgsSettings()
        if isinstance(self.parameter, QgsProcessingParameterFeatureSink):
            last_ext_path = '/Processing/LastVectorOutputExt'
            last_ext = settings.value(last_ext_path, '.gpkg')
        elif isinstance(self.parameter,
                        QgsProcessingParameterRasterDestination):
            last_ext_path = '/Processing/LastRasterOutputExt'
            last_ext = settings.value(last_ext_path, '.tif')
        else:
            last_ext_path = None
            last_ext = None

        # get default filter
        filters = file_filter.split(';;')
        try:
            last_filter = [
                f for f in filters if '*{}'.format(last_ext) in f.lower()
            ][0]
        except:
            last_filter = None

        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        filename, filter = QFileDialog.getSaveFileName(self,
                                                       self.tr("Save file"),
                                                       path, file_filter,
                                                       last_filter)
        if filename:
            self.use_temporary = False
            if not filename.lower().endswith(
                    tuple(re.findall("\\*(\\.[a-z]{1,10})", file_filter))):
                ext = re.search("\\*(\\.[a-z]{1,10})", filter)
                if ext:
                    filename += ext.group(1)
            self.leText.setText(filename)
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(filename))
            if not last_ext_path is None:
                settings.setValue(last_ext_path,
                                  os.path.splitext(filename)[1].lower())
    def executeAlgorithm(self):
        item = self.algorithmTree.currentItem()
        if isinstance(item, TreeAlgorithmItem):
            alg = QgsApplication.processingRegistry().createAlgorithmById(
                item.alg.id())
            if not alg:
                return

            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            if alg.countVisibleParameters() > 0:
                dlg = alg.createCustomParametersWidget(self)

                if not dlg:
                    dlg = AlgorithmDialog(alg)
                canvas = iface.mapCanvas()
                prevMapTool = canvas.mapTool()
                dlg.show()
                dlg.exec_()
                if canvas.mapTool() != prevMapTool:
                    try:
                        canvas.mapTool().reset()
                    except:
                        pass
                    canvas.setMapTool(prevMapTool)
                if dlg.wasExecuted():
                    showRecent = ProcessingConfig.getSetting(
                        ProcessingConfig.SHOW_RECENT_ALGORITHMS)
                    if showRecent:
                        self.addRecentAlgorithms(True)
            else:
                feedback = MessageBarProgress()
                context = dataobjects.createContext(feedback)
                parameters = {}
                ret, results = execute(alg, parameters, context, feedback)
                handleAlgorithmResults(alg, context, feedback)
                feedback.close()
Exemplo n.º 23
0
 def useLayerExtent(self):
     CANVAS_KEY = 'Use canvas extent'
     extentsDict = {}
     extentsDict[CANVAS_KEY] = {"extent": iface.mapCanvas().extent(),
                                "authid": iface.mapCanvas().mapSettings().destinationCrs().authid()}
     extents = [CANVAS_KEY]
     layers = QgsProcessingUtils.compatibleLayers(QgsProject.instance())
     for layer in layers:
         authid = layer.crs().authid()
         if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) \
                 and authid is not None:
             layerName = u'{} [{}]'.format(layer.name(), authid)
         else:
             layerName = layer.name()
         extents.append(layerName)
         extentsDict[layerName] = {"extent": layer.extent(), "authid": authid}
     (item, ok) = QInputDialog.getItem(self, self.tr('Select Extent'),
                                       self.tr('Use extent from'), extents, False)
     if ok:
         self.setValueFromRect(QgsReferencedRectangle(extentsDict[item]["extent"], QgsCoordinateReferenceSystem(extentsDict[item]["authid"])))
Exemplo n.º 24
0
 def load(self):
     """In this method we add settings needed to configure our
     provider.
     """
     ProcessingConfig.settingIcons[self.name()] = self.icon()
     # Deactivate provider by default
     ProcessingConfig.addSetting(
         Setting(self.name(), 'ACTIVATE_EXAMPLE', 'Activate', False))
     ProcessingConfig.addSetting(
         Setting('Example algorithms',
                 ExampleAlgorithmProvider.MY_DUMMY_SETTING,
                 'Example setting', 'Default value'))
     ProcessingConfig.readSettings()
     self.refreshAlgorithms()
     return True
Exemplo n.º 25
0
def createContext(feedback=None):
    """
    Creates a default processing context
    """
    context = QgsProcessingContext()
    context.setProject(QgsProject.instance())
    context.setFeedback(feedback)

    invalid_features_method = ProcessingConfig.getSetting(
        ProcessingConfig.FILTER_INVALID_GEOMETRIES)
    if invalid_features_method is None:
        invalid_features_method = QgsFeatureRequest.GeometryAbortOnInvalid
    context.setInvalidGeometryCheck(invalid_features_method)

    settings = QgsSettings()
    context.setDefaultEncoding(settings.value("/Processing/encoding",
                                              "System"))

    context.setExpressionContext(createExpressionContext())

    return context
    def saveToGeopackage(self):
        file_filter = self.tr('GeoPackage files (*.gpkg);;All files (*.*)',
                              'OutputFile')

        settings = QgsSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        filename, filter = QFileDialog.getSaveFileName(
            self,
            self.tr("Save to GeoPackage"),
            path,
            file_filter,
            options=QFileDialog.DontConfirmOverwrite)

        if not filename:
            return

        layer_name, ok = QInputDialog.getText(
            self,
            self.tr('Save to GeoPackage'),
            self.tr('Layer name'),
            text=self.parameter.name().lower())
        if ok:
            self.use_temporary = False
            if not filename.lower().endswith('.gpkg'):
                filename += '.gpkg'
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(filename))

            uri = QgsDataSourceUri()
            uri.setDatabase(filename)
            uri.setDataSource(
                '', layer_name, 'geom' if
                isinstance(self.parameter, QgsProcessingParameterFeatureSink)
                and self.parameter.hasGeometry() else None)
            self.leText.setText("ogr:" + uri.uri())
    def accept(self):
        keepOpen = ProcessingConfig.getSetting(
            ProcessingConfig.KEEP_DIALOG_OPEN)
        parameters = self.getParamValues()
        if parameters:
            with OverrideCursor(Qt.WaitCursor):
                self.feedback = FieldCalculatorFeedback(self)
                self.feedback.progressChanged.connect(self.setPercentage)

                context = dataobjects.createContext()
                ProcessingLog.addToLog(
                    self.alg.asPythonCommand(parameters, context))

                self.executed, results = execute(self.alg, parameters, context,
                                                 self.feedback)
                self.setPercentage(0)

                if self.executed:
                    handleAlgorithmResults(self.alg, context, self.feedback,
                                           not keepOpen)
                self._wasExecuted = self.executed or self._wasExecuted
                if not keepOpen:
                    QDialog.reject(self)
Exemplo n.º 28
0
def removeMenus():
    for alg in QgsApplication.processingRegistry().algorithms():
        menuPath = ProcessingConfig.getSetting("MENU_" + alg.id())
        if menuPath:
            paths = menuPath.split("/")
            removeAlgorithmEntry(alg, paths[0], paths[-1])
 def setActive(self, active):
     ProcessingConfig.setSettingValue('ACTIVATE_GRASS7', active)
 def isActive(self):
     return ProcessingConfig.getSetting('ACTIVATE_GRASS7')