Example #1
0
    def loadAlgorithms(self):
        self.algs = []
        folders = ScriptUtils.scriptsFolders()
        for folder in folders:
            items = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
            for entry in items:
                if entry.lower().endswith(".py"):
                    moduleName = os.path.splitext(os.path.basename(entry))[0]
                    filePath = os.path.abspath(os.path.join(folder, entry))
                    alg = ScriptUtils.loadAlgorithm(moduleName, filePath)
                    if alg is not None:
                        self.algs.append(alg)

        for a in self.algs:
            self.addAlgorithm(a)
Example #2
0
    def loadAlgorithms(self):
        self.algs = []
        folders = ScriptUtils.scriptsFolders()
        for folder in folders:
            items = os.scandir(folder)
            for entry in items:
                if entry.name.lower().endswith(".py") and entry.is_file():
                    moduleName = os.path.splitext(entry.name)[0]
                    filePath = os.path.abspath(os.path.join(folder, entry.name))
                    alg = ScriptUtils.loadAlgorithm(moduleName, filePath)
                    if alg is not None:
                        self.algs.append(alg)

        for a in self.algs:
            self.addAlgorithm(a)
Example #3
0
    def openScript(self):
        if self.hasChanged:
            ret = QMessageBox.warning(self, self.tr('Unsaved changes'),
                self.tr('There are unsaved changes in script. Continue?'),
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if ret == QMessageBox.No:
                return

        if self.algType == self.SCRIPT_PYTHON:
            scriptDir = ScriptUtils.scriptsFolder()
            filterName = self.tr('Python scripts (*.py)')
        elif self.algType == self.SCRIPT_R:
            scriptDir = RUtils.RScriptsFolder()
            filterName = self.tr('Processing R script (*.rsx)')

        self.filename = QFileDialog.getOpenFileName(
            self, self.tr('Save script'), scriptDir, filterName)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        with codecs.open(self.filename, 'r', encoding='utf-8') as f:
            txt = f.read()

        self.editor.setText(txt)
        self.hasChanged = False
        self.editor.setModified(False)
        self.editor.recolor()
        QApplication.restoreOverrideCursor()
    def saveScript(self, saveAs):
        newPath = None
        if self.filePath is None or saveAs:
            scriptDir = ScriptUtils.scriptsFolders()[0]
            newPath, _ = QFileDialog.getSaveFileName(self,
                                                     self.tr("Save script"),
                                                     scriptDir,
                                                     self.tr("Processing scripts (*.py *.PY)"))

            if newPath:
                if not newPath.lower().endswith(".py"):
                    newPath += ".py"

                self.filePath = newPath

        if self.filePath:
            text = self.editor.text()
            try:
                with codecs.open(self.filePath, "w", encoding="utf-8") as f:
                    f.write(text)
            except IOError as e:
                QMessageBox.warning(self,
                                    self.tr("I/O error"),
                                    self.tr("Unable to save edits:\n{}").format(str(e))
                                    )
                return

            self.setHasChanged(False)

        QgsApplication.processingRegistry().providerById("script").refreshAlgorithms()
Example #5
0
 def execute(self):
     filePath = ScriptUtils.findAlgorithmSource(self.itemData.name())
     if filePath is not None:
         dlg = ScriptEditorDialog(filePath, iface.mainWindow())
         dlg.show()
     else:
         QMessageBox.warning(None,
                             self.tr("Edit Script"),
                             self.tr("Can not find corresponding script file.")
                             )
Example #6
0
    def testResetScriptFolder(self):
        # if folder exist
        defaultScriptFolder = ScriptUtils.defaultScriptsFolder()
        folder = ScriptUtils.resetScriptFolder(defaultScriptFolder)
        self.assertEqual(folder, defaultScriptFolder)
        folder = ScriptUtils.resetScriptFolder('.')
        self.assertEqual(folder, '.')
        # if folder does not exist and not absolute
        folder = ScriptUtils.resetScriptFolder('fake')
        self.assertEqual(folder, None)
        # if absolute but not relative to QgsApplication.qgisSettingsDirPath()
        folder = os.path.join(tempfile.gettempdir(), 'fakePath')
        newFolder = ScriptUtils.resetScriptFolder(folder)
        self.assertEqual(newFolder, folder)

        # if absolute profile but poiting somewhere
        # reset the path as pointing to profile into the current settings
        folder = QgsApplication.qgisSettingsDirPath()

        # modify default profile changing absolute path pointing somewhere
        paths = folder.split(os.sep)
        paths[0] = '/'
        paths[1] = 'fakelocation'
        folder = os.path.join(*paths)

        folder = ScriptUtils.resetScriptFolder(folder)
        self.assertEqual(folder, QgsApplication.qgisSettingsDirPath())
Example #7
0
    def load(self):
        ProcessingConfig.settingIcons[self.name()] = self.icon()
        ProcessingConfig.addSetting(Setting(self.name(),
                                            ScriptUtils.SCRIPTS_FOLDERS,
                                            self.tr("Scripts folder(s)"),
                                            ScriptUtils.defaultScriptsFolder(),
                                            valuetype=Setting.MULTIPLE_FOLDERS))

        ProviderActions.registerProviderActions(self, self.actions)
        ProviderContextMenuActions.registerProviderContextMenuActions(self.contextMenuActions)

        ProcessingConfig.readSettings()
        self.refreshAlgorithms()

        return True
Example #8
0
    def loadAlgorithms(self):
        self.algs = []
        folders = ScriptUtils.scriptsFolders()
        # always add default script folder to the list
        defaultScriptFolder = ScriptUtils.defaultScriptsFolder()
        if defaultScriptFolder not in folders:
            folders.append(defaultScriptFolder)
        # load all scripts
        for folder in folders:
            folder = ScriptUtils.resetScriptFolder(folder)
            if not folder:
                continue

            items = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
            for entry in items:
                if entry.lower().endswith(".py"):
                    moduleName = os.path.splitext(os.path.basename(entry))[0]
                    filePath = os.path.abspath(os.path.join(folder, entry))
                    alg = ScriptUtils.loadAlgorithm(moduleName, filePath)
                    if alg is not None:
                        self.algs.append(alg)

        for a in self.algs:
            self.addAlgorithm(a)
Example #9
0
 def execute(self):
     reply = QMessageBox.question(None,
                                  self.tr("Delete Script"),
                                  self.tr("Are you sure you want to delete this script?"),
                                  QMessageBox.Yes | QMessageBox.No,
                                  QMessageBox.No)
     if reply == QMessageBox.Yes:
         filePath = ScriptUtils.findAlgorithmSource(self.itemData.__class__.__name__)
         if filePath is not None:
             os.remove(filePath)
             QgsApplication.processingRegistry().providerById("script").refreshAlgorithms()
         else:
             QMessageBox.warning(None,
                                 self.tr("Delete Script"),
                                 self.tr("Can not find corresponding script file.")
                                 )
Example #10
0
    def load(self):
        with QgsRuntimeProfiler.profile('Script Provider'):
            ProcessingConfig.settingIcons[self.name()] = self.icon()
            ProcessingConfig.addSetting(Setting(self.name(),
                                                ScriptUtils.SCRIPTS_FOLDERS,
                                                self.tr("Scripts folder(s)"),
                                                ScriptUtils.defaultScriptsFolder(),
                                                valuetype=Setting.MULTIPLE_FOLDERS))

            ProviderActions.registerProviderActions(self, self.actions)
            ProviderContextMenuActions.registerProviderContextMenuActions(self.contextMenuActions)

            ProcessingConfig.readSettings()
            self.refreshAlgorithms()

        return True
Example #11
0
 def execute(self):
     reply = QMessageBox.question(
         None, self.tr("Delete Script"),
         self.tr("Are you sure you want to delete this script?"),
         QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
     if reply == QMessageBox.Yes:
         filePath = ScriptUtils.findAlgorithmSource(
             self.itemData.__class__.__name__)
         if filePath is not None:
             os.remove(filePath)
             QgsApplication.processingRegistry().providerById(
                 "script").refreshAlgorithms()
         else:
             QMessageBox.warning(
                 None, self.tr("Delete Script"),
                 self.tr("Can not find corresponding script file."))
Example #12
0
    def saveScript(self, saveAs):
        if self.filename is None or saveAs:
            if self.algType == self.SCRIPT_PYTHON:
                scriptDir = ScriptUtils.scriptsFolder()
                filterName = self.tr('Python scripts (*.py)')
            elif self.algType == self.SCRIPT_R:
                scriptDir = RUtils.RScriptsFolder()
                filterName = self.tr('Processing R script (*.rsx)')

            self.filename = unicode(
                QFileDialog.getSaveFileName(self, self.tr('Save script'),
                                            scriptDir, filterName))

        if self.filename:
            if self.algType == self.SCRIPT_PYTHON \
                        and not self.filename.lower().endswith('.py'):
                self.filename += '.py'
            if self.algType == self.SCRIPT_R \
                        and not self.filename.lower().endswith('.rsx'):
                self.filename += '.rsx'

            text = unicode(self.editor.text())
            if self.alg is not None:
                self.alg.script = text
            try:
                with codecs.open(self.filename, 'w', encoding='utf-8') as fout:
                    fout.write(text)
            except IOError:
                QMessageBox.warning(
                    self, self.tr('I/O error'),
                    self.tr('Unable to save edits. Reason:\n %s') %
                    unicode(sys.exc_info()[1]))
                return
            self.update = True

            # If help strings were defined before saving the script for
            # the first time, we do it here
            if self.help:
                with open(self.filename + '.help', 'w') as f:
                    json.dump(self.help, f)
                self.help = None
            self.setHasChanged(False)
        else:
            self.filename = None
Example #13
0
    def openScript(self):
        if self.hasChanged:
            ret = QMessageBox.warning(
                self, self.tr("Unsaved changes"),
                self.tr("There are unsaved changes in the script. Continue?"),
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if ret == QMessageBox.No:
                return

        scriptDir = ScriptUtils.scriptsFolders()[0]
        fileName, _ = QFileDialog.getOpenFileName(
            self, self.tr("Open script"), scriptDir,
            self.tr("Processing scripts (*.py *.PY)"))

        if fileName == "":
            return

        with OverrideCursor(Qt.WaitCursor):
            self._loadFile(fileName)
Example #14
0
    def saveScript(self, saveAs):
        if self.filename is None or saveAs:
            if self.algType == self.SCRIPT_PYTHON:
                scriptDir = ScriptUtils.scriptsFolder()
                filterName = self.tr('Python scripts (*.py)')
            elif self.algType == self.SCRIPT_R:
                scriptDir = RUtils.RScriptsFolder()
                filterName = self.tr('Processing R script (*.rsx)')

            self.filename = unicode(QFileDialog.getSaveFileName(self,
                                    self.tr('Save script'), scriptDir,
                                    filterName))

        if self.filename:
            if self.algType == self.SCRIPT_PYTHON \
                        and not self.filename.lower().endswith('.py'):
                self.filename += '.py'
            if self.algType == self.SCRIPT_R \
                        and not self.filename.lower().endswith('.rsx'):
                self.filename += '.rsx'

            text = unicode(self.editor.text())
            if self.alg is not None:
                self.alg.script = text
            try:
                with codecs.open(self.filename, 'w', encoding='utf-8') as fout:
                    fout.write(text)
            except IOError:
                QMessageBox.warning(self, self.tr('I/O error'),
                        self.tr('Unable to save edits. Reason:\n %s')
                        % unicode(sys.exc_info()[1]))
                return
            self.update = True

            # If help strings were defined before saving the script for
            # the first time, we do it here
            if self.help:
                with open(self.filename + '.help', 'w') as f:
                    json.dump(self.help, f)
                self.help = None
            self.setHasChanged(False)
        else:
            self.filename = None
    def openScript(self):
        if self.hasChanged:
            ret = QMessageBox.warning(self,
                                      self.tr("Unsaved changes"),
                                      self.tr("There are unsaved changes in the script. Continue?"),
                                      QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if ret == QMessageBox.No:
                return

        scriptDir = ScriptUtils.scriptsFolders()[0]
        fileName, _ = QFileDialog.getOpenFileName(self,
                                                  self.tr("Open script"),
                                                  scriptDir,
                                                  self.tr("Processing scripts (*.py *.PY)"))

        if fileName == "":
            return

        with OverrideCursor(Qt.WaitCursor):
            self._loadFile(fileName)
Example #16
0
    def execute(self):
        settings = QgsSettings()
        lastDir = settings.value("processing/lastScriptsDir", "")
        files, _ = QFileDialog.getOpenFileNames(self.toolbox,
                                                self.tr("Add script(s)"),
                                                lastDir,
                                                self.tr("Processing scripts (*.py *.PY)"))
        if files:
            settings.setValue("processing/lastScriptsDir", os.path.dirname(files[0]))

            valid = 0
            for f in files:
                try:
                    shutil.copy(f, ScriptUtils.scriptsFolders()[0])
                    valid += 1
                except OSError as e:
                    QgsMessageLog.logMessage(self.tr("Could not copy script '{}'\n{}").format(f, str(e)),
                                             "Processing",
                                             Qgis.Warning)

            if valid > 0:
                QgsApplication.processingRegistry().providerById("script").refreshAlgorithms()
Example #17
0
    def execute(self):
        settings = QgsSettings()
        lastDir = settings.value("processing/lastScriptsDir", "")
        files, _ = QFileDialog.getOpenFileNames(self.toolbox,
                                                self.tr("Add script(s)"),
                                                lastDir,
                                                self.tr("Processing scripts (*.py *.PY)"))
        if files:
            settings.setValue("processing/lastScriptsDir", os.path.dirname(files[0]))

            valid = 0
            for f in files:
                try:
                    shutil.copy(f, ScriptUtils.scriptsFolders()[0])
                    valid += 1
                except OSError as e:
                    QgsMessageLog.logMessage(self.tr("Could not copy script '{}'\n{}").format(f, str(e)),
                                             "Processing",
                                             Qgis.Warning)

            if valid > 0:
                QgsApplication.processingRegistry().providerById("script").refreshAlgorithms()
 def scripts_folder(self):
     """Return the default processing scripts folder."""
     return ScriptUtils.defaultScriptsFolder()
 def scripts_folder(self):
     """Return the default processing scripts folder."""
     return ScriptUtils.defaultScriptsFolder()