Ejemplo n.º 1
0
    def __init__(self):
        super(ProcessingToolbox, self).__init__(None)
        self.tipWasClosed = False
        self.setupUi(self)
        self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)

        self.searchBox.textChanged.connect(self.textChanged)
        self.algorithmTree.customContextMenuRequested.connect(
            self.showPopupMenu)
        self.algorithmTree.doubleClicked.connect(self.executeAlgorithm)
        self.txtDisabled.setVisible(False)
        self.txtTip.setVisible(self.disabledProviders())
        self.txtDisabled.linkActivated.connect(self.showDisabled)

        def openSettings(url):
            if url == "close":
                self.txtTip.setVisible(False)
                self.tipWasClosed = True
            else:
                iface.showOptionsDialog(iface.mainWindow(), 'processingOptions')
                self.txtTip.setVisible(self.disabledProviders())
        self.txtTip.linkActivated.connect(openSettings)
        if hasattr(self.searchBox, 'setPlaceholderText'):
            self.searchBox.setPlaceholderText(self.tr('Search...'))

        self.fillTree()

        # connect to existing providers
        for p in QgsApplication.processingRegistry().providers():
            p.algorithmsLoaded.connect(self.updateProvider)

        QgsApplication.processingRegistry().providerRemoved.connect(self.removeProvider)
        QgsApplication.processingRegistry().providerAdded.connect(self.addProvider)
        settingsWatcher.settingsChanged.connect(self.fillTree)
Ejemplo n.º 2
0
    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()
Ejemplo n.º 3
0
    def execute(self):
        model = self.itemData
        if model is None:
            return # shouldn't happen, but let's be safe

        project_provider = model.provider().id() == PROJECT_PROVIDER_ID

        if project_provider:
            msg = self.tr('Are you sure you want to delete this model from the current project?', 'DeleteModelAction')
        else:
            msg = self.tr('Are you sure you want to delete this model?', 'DeleteModelAction')

        reply = QMessageBox.question(
            None,
            self.tr('Delete Model', 'DeleteModelAction'),
            msg,
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No)

        if reply == QMessageBox.Yes:
            if project_provider:
                provider = QgsApplication.processingRegistry().providerById(PROJECT_PROVIDER_ID)
                provider.remove_model(model)
                QgsProject.instance().setDirty(True)
            else:
                os.remove(model.sourceFilePath())
                QgsApplication.processingRegistry().providerById('model').refreshAlgorithms()
Ejemplo n.º 4
0
    def test_OTBParameterChoice_Gui(self):
        """
        This test is similar to GuiTests in processing that is done on other parameter widget in processing
        Main difference is this test uses create_wrapper_from_metadata() rather than create_wrapper_from_class()
        like rest of processing widgets.
        """
        param = OtbParameterChoice('test')

        alg = QgsApplication.processingRegistry().createAlgorithmById('otb:Smoothing')
        # algorithm dialog
        dlg = AlgorithmDialog(alg)
        wrapper = WidgetWrapperFactory.create_wrapper_from_metadata(param, dlg)
        self.assertIsNotNone(wrapper)
        self.assertIsInstance(wrapper, OtbChoiceWidgetWrapper)
        self.assertEqual(wrapper.dialog, dlg)
        self.assertIsNotNone(wrapper.widget)

        alg = QgsApplication.processingRegistry().createAlgorithmById('otb:Smoothing')
        # batch dialog
        dlg = BatchAlgorithmDialog(alg)
        wrapper = WidgetWrapperFactory.create_wrapper_from_metadata(param, dlg)
        self.assertIsNotNone(wrapper)
        self.assertIsInstance(wrapper, OtbChoiceWidgetWrapper)
        self.assertEqual(wrapper.dialog, dlg)
        self.assertIsNotNone(wrapper.widget)

        alg = QgsApplication.processingRegistry().createAlgorithmById('otb:Smoothing')
        # modeler dialog
        model = QgsProcessingModelAlgorithm()
        dlg = ModelerParametersDialog(alg, model)
        wrapper = WidgetWrapperFactory.create_wrapper_from_metadata(param, dlg)
        self.assertIsNotNone(wrapper)
        self.assertIsInstance(wrapper, OtbChoiceWidgetWrapper)
        self.assertEqual(wrapper.dialog, dlg)
        self.assertIsNotNone(wrapper.widget)
Ejemplo n.º 5
0
    def unload(self):
        self.toolbox.setVisible(False)
        self.iface.removeDockWidget(self.toolbox)
        self.iface.attributesToolBar().removeAction(self.toolboxAction)

        self.resultsDock.setVisible(False)
        self.iface.removeDockWidget(self.resultsDock)

        self.toolbox.deleteLater()
        self.menu.deleteLater()

        # delete temporary output files
        folder = QgsProcessingUtils.tempFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        # also delete temporary help files
        folder = tempHelpFolder()
        if QDir(folder).exists():
            shutil.rmtree(folder, True)

        self.iface.unregisterMainWindowAction(self.toolboxAction)
        self.iface.unregisterMainWindowAction(self.modelerAction)
        self.iface.unregisterMainWindowAction(self.historyAction)
        self.iface.unregisterMainWindowAction(self.resultsAction)

        self.iface.unregisterOptionsWidgetFactory(self.options_factory)
        self.iface.deregisterLocatorFilter(self.locator_filter)
        self.iface.unregisterCustomDropHandler(self.drop_handler)
        QgsApplication.dataItemProviderRegistry().removeProvider(self.item_provider)

        removeMenus()
        Processing.deinitialize()
Ejemplo n.º 6
0
    def fetchAvailablePlugins(self, reloadMode):
        """ Fetch plugins from all enabled repositories."""
        """  reloadMode = true:  Fully refresh data from QSettings to mRepositories  """
        """  reloadMode = false: Fetch unready repositories only """
        QApplication.setOverrideCursor(Qt.WaitCursor)

        if reloadMode:
            repositories.load()
            plugins.clearRepoCache()
            plugins.getAllInstalled()

        for key in repositories.allEnabled():
            if reloadMode or repositories.all()[key]["state"] == 3:  # if state = 3 (error or not fetched yet), try to fetch once again
                repositories.requestFetching(key)

        if repositories.fetchingInProgress():
            fetchDlg = QgsPluginInstallerFetchingDialog(iface.mainWindow())
            fetchDlg.exec_()
            del fetchDlg
            for key in repositories.all():
                repositories.killConnection(key)

        QApplication.restoreOverrideCursor()

        # display error messages for every unavailable reposioty, unless Shift pressed nor all repositories are unavailable
        keepQuiet = QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier)
        if repositories.allUnavailable() and repositories.allUnavailable() != repositories.allEnabled():
            for key in repositories.allUnavailable():
                if not keepQuiet:
                    QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Error reading repository:") + " " + key + "\n\n" + repositories.all()[key]["error"])
                if QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier):
                    keepQuiet = True
        # finally, rebuild plugins from the caches
        plugins.rebuild()
Ejemplo n.º 7
0
    def checkConstructWrapper(self, param, expected_wrapper_class):
        alg = QgsApplication.processingRegistry().createAlgorithmById('native:centroids')

        # algorithm dialog
        dlg = AlgorithmDialog(alg)
        wrapper = WidgetWrapperFactory.create_wrapper_from_class(param, dlg)
        self.assertIsNotNone(wrapper)
        self.assertIsInstance(wrapper, expected_wrapper_class)
        self.assertEqual(wrapper.dialog, dlg)
        self.assertIsNotNone(wrapper.widget)

        alg = QgsApplication.processingRegistry().createAlgorithmById('native:centroids')
        # batch dialog
        dlg = BatchAlgorithmDialog(alg)
        wrapper = WidgetWrapperFactory.create_wrapper_from_class(param, dlg)
        self.assertIsNotNone(wrapper)
        self.assertIsInstance(wrapper, expected_wrapper_class)
        self.assertEqual(wrapper.dialog, dlg)
        self.assertIsNotNone(wrapper.widget)

        alg = QgsApplication.processingRegistry().createAlgorithmById('native:centroids')

        # modeler dialog
        model = QgsProcessingModelAlgorithm()
        dlg = ModelerParametersDialog(alg, model)
        wrapper = WidgetWrapperFactory.create_wrapper_from_class(param, dlg)
        self.assertIsNotNone(wrapper)
        self.assertIsInstance(wrapper, expected_wrapper_class)
        self.assertEqual(wrapper.dialog, dlg)
        self.assertIsNotNone(wrapper.widget)
Ejemplo n.º 8
0
    def testTaskFromFunctionWithSubTaskCompletedIsCalledOnce(self):  # spellok
        """ test that when a parent task has subtasks it does emit taskCompleted only once"""

        self.finished = 0
        self.completed = 0

        def _on_finished(e):
            self.finished += 1

        def _on_completed():
            self.completed += 1

        task = QgsTask.fromFunction('test task', run_no_result, on_finished=_on_finished)
        task.taskCompleted.connect(_on_completed)
        spy = QSignalSpy(task.taskCompleted)
        sub_task_1 = QgsTask.fromFunction('test subtask 1', run_no_result, on_finished=_on_finished)
        sub_task_2 = QgsTask.fromFunction('test subtask 2', run_no_result, on_finished=_on_finished)
        task.addSubTask(sub_task_1, [], QgsTask.ParentDependsOnSubTask)
        task.addSubTask(sub_task_2, [], QgsTask.ParentDependsOnSubTask)

        QgsApplication.taskManager().addTask(task)
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            QCoreApplication.processEvents()
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        self.assertEqual(self.completed, 1)
        self.assertEqual(self.finished, 3)
        self.assertEqual(len(spy), 1)
Ejemplo n.º 9
0
    def __init__(self, parent, alg):
        super(BatchPanel, self).__init__(None)
        self.setupUi(self)

        self.wrappers = []

        self.btnAdvanced.hide()

        # Set icons
        self.btnAdd.setIcon(QgsApplication.getThemeIcon('/symbologyAdd.svg'))
        self.btnRemove.setIcon(QgsApplication.getThemeIcon('/symbologyRemove.svg'))
        self.btnOpen.setIcon(QgsApplication.getThemeIcon('/mActionFileOpen.svg'))
        self.btnSave.setIcon(QgsApplication.getThemeIcon('/mActionFileSave.svg'))
        self.btnAdvanced.setIcon(QIcon(os.path.join(pluginPath, 'images', 'alg.png')))

        self.alg = alg
        self.parent = parent

        self.btnAdd.clicked.connect(self.addRow)
        self.btnRemove.clicked.connect(self.removeRows)
        self.btnOpen.clicked.connect(self.load)
        self.btnSave.clicked.connect(self.save)
        self.btnAdvanced.toggled.connect(self.toggleAdvancedMode)
        self.tblParameters.horizontalHeader().sectionDoubleClicked.connect(
            self.fillParameterValues)

        self.initWidgets()
Ejemplo n.º 10
0
    def fillTreeUsingProviders(self):
        self.algorithmTree.clear()
        self.disabledProviderItems = {}

        # TODO - replace with proper model for toolbox!

        # first add qgis/native providers, since they create top level groups
        for provider in QgsApplication.processingRegistry().providers():
            if provider.id() in ('qgis', 'native', '3d'):
                self.addAlgorithmsFromProvider(provider, self.algorithmTree.invisibleRootItem())
            else:
                continue
        self.algorithmTree.sortItems(0, Qt.AscendingOrder)

        for provider in QgsApplication.processingRegistry().providers():
            if provider.id() in ('qgis', 'native', '3d'):
                # already added
                continue
            else:
                providerItem = TreeProviderItem(provider, self.algorithmTree, self)

                # insert non-native providers at end of tree, alphabetically
                for i in range(self.algorithmTree.invisibleRootItem().childCount()):
                    child = self.algorithmTree.invisibleRootItem().child(i)
                    if isinstance(child, TreeProviderItem):
                        if child.text(0) > providerItem.text(0):
                            break

                self.algorithmTree.insertTopLevelItem(i + 1, providerItem)
                if not provider.isActive():
                    providerItem.setHidden(True)
                    self.disabledProviderItems[provider.id()] = providerItem
Ejemplo n.º 11
0
    def grassPath():
        if not isWindows() and not isMac():
            return ''

        folder = ProcessingConfig.getSetting(GrassUtils.GRASS_FOLDER) or ''
        if not os.path.exists(folder):
            folder = None
        if folder is None:
            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-6'):
                            folder = os.path.join(testfolder, subfolder)
                            break
            else:
                folder = os.path.join(QgsApplication.prefixPath(), 'grass')
                if not os.path.isdir(folder):
                    folder = '/Applications/GRASS-6.4.app/Contents/MacOS'

        if folder:
            ProcessingConfig.setSettingValue(GrassUtils.GRASS_FOLDER, folder)
        return folder or ''
Ejemplo n.º 12
0
 def getGroupIcon(group):
     if group == ProcessingConfig.tr('General'):
         return QgsApplication.getThemeIcon("/processingAlgorithm.svg")
     if group in ProcessingConfig.settingIcons:
         return ProcessingConfig.settingIcons[group]
     else:
         return QgsApplication.getThemeIcon("/processingAlgorithm.svg")
Ejemplo n.º 13
0
    def testLayerRemovalBeforeRun(self):
        """test behavior when layer is removed before task begins"""
        path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif')
        raster_layer = QgsRasterLayer(path, "test")
        self.assertTrue(raster_layer.isValid())

        pipe = QgsRasterPipe()
        self.assertTrue(pipe.set(raster_layer.dataProvider().clone()))

        tmp = create_temp_filename('remove_layer.tif')
        writer = QgsRasterFileWriter(tmp)

        task = QgsRasterFileWriterTask(writer, pipe, 100, 100, raster_layer.extent(), raster_layer.crs())

        task.writeComplete.connect(self.onSuccess)
        task.errorOccurred.connect(self.onFail)

        # remove layer
        raster_layer = None

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        # in this case will still get a positive result - since the pipe is cloned before the task
        # begins the task is no longer dependent on the original layer
        self.assertTrue(self.success)
        self.assertFalse(self.fail)
        self.assertTrue(os.path.exists(tmp))
Ejemplo n.º 14
0
    def test_validate_pki_bundle(self):
        """Text the pki bundle validation"""

        # Valid bundle:
        bundle = self.mkPEMBundle('fra_cert.pem', 'fra_key.pem', 'password', 'chain_subissuer-issuer-root.pem')

        # Test valid bundle with intermediates and without trusted root
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle), ['The root certificate of the certificate chain is self-signed, and untrusted'])
        # Test valid without intermediates
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, False), ['The issuer certificate of a locally looked up certificate could not be found', 'No certificates could be verified'])
        # Test valid with intermediates and trusted root
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, True, True), [])

        # Wrong chain
        bundle = self.mkPEMBundle('fra_cert.pem', 'fra_key.pem', 'password', 'chain_issuer2-root2.pem')
        # Test invalid bundle with intermediates and without trusted root
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle), ['The issuer certificate of a locally looked up certificate could not be found', 'No certificates could be verified'])
        # Test valid without intermediates
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, False), ['The issuer certificate of a locally looked up certificate could not be found', 'No certificates could be verified'])
        # Test valid with intermediates and trusted root
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, True, True), ['The issuer certificate of a locally looked up certificate could not be found', 'No certificates could be verified'])

        # Wrong key
        bundle = self.mkPEMBundle('fra_cert.pem', 'ptolemy_key.pem', 'password', 'chain_subissuer-issuer-root.pem')
        # Test invalid bundle with intermediates and without trusted root
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle), ['The root certificate of the certificate chain is self-signed, and untrusted', 'Private key does not match client certificate public key.'])
        # Test invalid without intermediates
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, False), ['The issuer certificate of a locally looked up certificate could not be found', 'No certificates could be verified', 'Private key does not match client certificate public key.'])
        # Test invalid with intermediates and trusted root
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, True, True), ['Private key does not match client certificate public key.'])

        # Expired root CA
        bundle = self.mkPEMBundle('piri_cert.pem', 'piri_key.pem', 'password', 'chain_issuer3-root3-EXPIRED.pem')
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle), ['The root certificate of the certificate chain is self-signed, and untrusted', 'The certificate has expired'])
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, False), ['The issuer certificate of a locally looked up certificate could not be found', 'No certificates could be verified'])
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, True, True), ['The root certificate of the certificate chain is self-signed, and untrusted', 'The certificate has expired'])

        # Expired intermediate CA
        bundle = self.mkPEMBundle('marinus_cert-EXPIRED.pem', 'marinus_key_w-pass.pem', 'password', 'chain_issuer2-root2.pem')
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle), ['The root certificate of the certificate chain is self-signed, and untrusted', 'The certificate has expired'])
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, False), ['The issuer certificate of a locally looked up certificate could not be found', 'No certificates could be verified'])
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, True, True), ['The certificate has expired'])

        # Expired client cert
        bundle = self.mkPEMBundle('henricus_cert.pem', 'henricus_key_w-pass.pem', 'password', 'chain_issuer4-EXPIRED-root2.pem')
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle), ['The root certificate of the certificate chain is self-signed, and untrusted', 'The certificate has expired'])
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, False), ['The issuer certificate of a locally looked up certificate could not be found', 'No certificates could be verified'])
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, True, True), ['The certificate has expired'])

        # Untrusted root, positive test before untrust is applied
        bundle = self.mkPEMBundle('nicholas_cert.pem', 'nicholas_key.pem', 'password', 'chain_issuer2-root2.pem')
        # Test valid with intermediates and trusted root
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, True, True), [])
        # Untrust this root
        root2 = QgsAuthCertUtils.certFromFile(PKIDATA + '/' + 'root2_ca_cert.pem')
        QgsApplication.authManager().storeCertAuthority(root2)
        self.assertTrue(QgsApplication.authManager().storeCertTrustPolicy(root2, QgsAuthCertUtils.Untrusted))
        QgsApplication.authManager().rebuildCaCertsCache()
        # Test valid with intermediates and untrusted root
        self.assertEqual(QgsAuthCertUtils.validatePKIBundle(bundle, True, True), ['The issuer certificate of a locally looked up certificate could not be found'])
Ejemplo n.º 15
0
 def updateProgressBar(self, progressValue):
     QgsApplication.processEvents()
     if self.progressBar and not self.lockProgressBar:
         self.lockProgressBar = True
         self.progressBar.setValue(progressValue)
         self.progressValue = progressValue
         self.lockProgressBar = False
Ejemplo n.º 16
0
    def __init__(self, parent, alg):
        super(BatchPanel, self).__init__(None)
        self.setupUi(self)

        self.wrappers = []

        self.btnAdvanced.hide()

        # Set icons
        self.btnAdd.setIcon(QgsApplication.getThemeIcon('/symbologyAdd.svg'))
        self.btnRemove.setIcon(QgsApplication.getThemeIcon('/symbologyRemove.svg'))
        self.btnOpen.setIcon(QgsApplication.getThemeIcon('/mActionFileOpen.svg'))
        self.btnSave.setIcon(QgsApplication.getThemeIcon('/mActionFileSave.svg'))
        self.btnAdvanced.setIcon(QgsApplication.getThemeIcon("/processingAlgorithm.svg"))

        self.alg = alg
        self.parent = parent

        self.btnAdd.clicked.connect(self.addRow)
        self.btnRemove.clicked.connect(self.removeRows)
        self.btnOpen.clicked.connect(self.load)
        self.btnSave.clicked.connect(self.save)
        self.btnAdvanced.toggled.connect(self.toggleAdvancedMode)
        self.tblParameters.horizontalHeader().sectionDoubleClicked.connect(
            self.fillParameterValues)

        self.tblParameters.horizontalHeader().resizeSections(QHeaderView.ResizeToContents)
        self.tblParameters.horizontalHeader().setDefaultSectionSize(250)
        self.tblParameters.horizontalHeader().setMinimumSectionSize(150)

        self.initWidgets()
Ejemplo n.º 17
0
    def init(self, logo, title):
        from qgis.core import QgsApplication
        from PyQt4.QtGui import QApplication, QFont, QIcon
        from PyQt4.QtCore import QLocale, QTranslator
        try:
            import PyQt4.QtSql
        except ImportError:
            pass

        self.app = QgsApplication(self.sysargv, True)
        import roam.roam_style
        self.app.setStyleSheet(roam.roam_style.appstyle)
        QgsApplication.setPrefixPath(self.prefixpath, True)
        QgsApplication.initQgis()

        locale = QLocale.system().name()
        self.translationFile = os.path.join(self.i18npath, '{0}.qm'.format(locale))
        translator = QTranslator()
        translator.load(self.translationFile, "i18n")
        self.app.installTranslator(translator)

        QApplication.setStyle("Plastique")
        QApplication.setFont(QFont('Segoe UI'))
        QApplication.setWindowIcon(QIcon(logo))
        QApplication.setApplicationName(title)

        import roam.editorwidgets.core
        roam.editorwidgets.core.registerallwidgets()
        return self
Ejemplo n.º 18
0
    def __init__(self, resourceType):
        super(GetScriptsAndModelsDialog, self).__init__(iface.mainWindow())
        self.setupUi(self)

        if hasattr(self.leFilter, 'setPlaceholderText'):
            self.leFilter.setPlaceholderText(self.tr('Search...'))

        self.manager = QgsNetworkAccessManager.instance()

        repoUrl = ProcessingConfig.getSetting(ProcessingConfig.MODELS_SCRIPTS_REPO)

        self.resourceType = resourceType
        if self.resourceType == self.MODELS:
            self.folder = ModelerUtils.modelsFolders()[0]
            self.urlBase = '{}/models/'.format(repoUrl)
            self.icon = QgsApplication.getThemeIcon("/processingModel.svg")
        elif self.resourceType == self.SCRIPTS:
            self.folder = ScriptUtils.scriptsFolders()[0]
            self.urlBase = '{}/scripts/'.format(repoUrl)
            self.icon = QgsApplication.getThemeIcon("/processingScript.svg")

        self.lastSelectedItem = None
        self.updateProvider = False
        self.data = None

        self.populateTree()
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        self.tree.currentItemChanged.connect(self.currentItemChanged)
        self.leFilter.textChanged.connect(self.fillTree)
Ejemplo n.º 19
0
 def otbPath():
     folder = ProcessingConfig.getSetting(OTBUtils.OTB_FOLDER)
     if folder == None:
         folder = ""
         #try to configure the path automatically
         if ProcessingUtils.isMac():
             testfolder = os.path.join(str(QgsApplication.prefixPath()), "bin")
             if os.path.exists(os.path.join(testfolder, "otbcli")):
                 folder = testfolder
             else:
                 testfolder = "/usr/local/bin"
                 if os.path.exists(os.path.join(testfolder, "otbcli")):
                     folder = testfolder
         elif ProcessingUtils.isWindows():
             testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
             testfolder = os.path.dirname(testfolder)
             testfolder = os.path.join(testfolder,  "bin")
             path = os.path.join(testfolder, "otbcli.bat")
             if os.path.exists(path):
                 folder = testfolder
         else:
             testfolder = "/usr/bin"
             if os.path.exists(os.path.join(testfolder, "otbcli")):
                 folder = testfolder
     return folder
Ejemplo n.º 20
0
    def otbPath():
        folder = ProcessingConfig.getSetting(OTBUtils.OTB_FOLDER)
        if folder is None:
            folder = ''

            # Try to configure the path automatically
            if isMac():
                testfolder = os.path.join(str(QgsApplication.prefixPath()),
                        'bin')
                if os.path.exists(os.path.join(testfolder, 'otbcli')):
                    folder = testfolder
                else:
                    testfolder = '/usr/local/bin'
                    if os.path.exists(os.path.join(testfolder, 'otbcli')):
                        folder = testfolder
            elif isWindows():
                testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
                testfolder = os.path.dirname(testfolder)
                testfolder = os.path.join(testfolder, 'bin')
                path = os.path.join(testfolder, 'otbcli.bat')
                if os.path.exists(path):
                    folder = testfolder
            else:
                testfolder = '/usr/bin'
                if os.path.exists(os.path.join(testfolder, 'otbcli')):
                    folder = testfolder
        return folder
Ejemplo n.º 21
0
 def otbLibPath():
     folder = ProcessingConfig.getSetting(OTBUtils.OTB_LIB_FOLDER)
     if folder is None:
         folder = ''
         # Try to configure the path automatically
         if isMac():
             testfolder = os.path.join(str(QgsApplication.prefixPath()),
                     'lib/otb/applications')
             if os.path.exists(testfolder):
                 folder = testfolder
             else:
                 testfolder = '/usr/local/lib/otb/applications'
                 if os.path.exists(testfolder):
                     folder = testfolder
         elif isWindows():
             testfolder = os.path.dirname(str(QgsApplication.prefixPath()))
             testfolder = os.path.join(testfolder, 'orfeotoolbox')
             testfolder = os.path.join(testfolder, 'applications')
             if os.path.exists(testfolder):
                 folder = testfolder
         else:
             testfolder = '/usr/lib/otb/applications'
             if os.path.exists(testfolder):
                 folder = testfolder
     return folder
Ejemplo n.º 22
0
 def execute(self):
     settings = QgsSettings()
     lastDir = settings.value('Processing/lastScriptsDir', '')
     filenames, selected_filter = QFileDialog.getOpenFileNames(self.toolbox,
                                                               self.tr('Script files', 'AddScriptFromFileAction'), lastDir,
                                                               self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction'))
     if filenames:
         validAlgs = 0
         wrongAlgs = []
         for filename in filenames:
             try:
                 settings.setValue('Processing/lastScriptsDir',
                                   QFileInfo(filename).absoluteDir().absolutePath())
                 script = ScriptAlgorithm(filename)
                 destFilename = os.path.join(ScriptUtils.scriptsFolders()[0], os.path.basename(filename))
                 with open(destFilename, 'w') as f:
                     f.write(script.script)
                 validAlgs += 1
             except WrongScriptException:
                 wrongAlgs.append(os.path.basename(filename))
         if validAlgs:
             QgsApplication.processingRegistry().providerById('script').refreshAlgorithms()
         if wrongAlgs:
             QMessageBox.warning(self.toolbox,
                                 self.tr('Error reading scripts', 'AddScriptFromFileAction'),
                                 self.tr('The following files do not contain a valid script:\n-', 'AddScriptFromFileAction') +
                                 "\n-".join(wrongAlgs))
Ejemplo n.º 23
0
def init(args=None, guienabled=True, configpath=None, sysexit=True):
    """
    Create a new QGIS Qt application.

    You should use this before creating any Qt widgets or QGIS objects for
    your custom QGIS based application.

    usage:
        from wrappers import QGIS

        QGIS.init()

    args - args passed to the underlying QApplication.
    guienabled - True by default will create a QApplication with a GUI. Pass
                 False if you wish to create no GUI based app, e.g a server app.
    configpath - Custom config path QGIS will use to load settings.
    sysexit - Call sys.exit on app exit. True by default.
    """
    if not args:
        args = []
    if not configpath:
        configpath = ''
    app = QgsApplication(args, guienabled, configpath)
    QgsApplication.initQgis()
    return app
Ejemplo n.º 24
0
    def getHttp(self, uri, params):
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            rq = QUrl(uri)
            q = QUrlQuery()
            for (k, v) in params.items():
                q.addQueryItem(k, v)

            rq.setQuery(q)
            req = QNetworkRequest(rq)

            try:
                reply = self.nominatim_networkAccessManager.blockingGet(req)
                resource = reply.content().data().decode('utf8')
                r = json.loads(resource)

                if (isinstance(r, list)):
                    self.populateTable(r)
                else:
                    self.populateTable([r])
            except:
                self.tableResult.clearContents()

        finally:
            QgsApplication.restoreOverrideCursor()
Ejemplo n.º 25
0
    def grassPath():
        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:
            if isWindows():
                if "OSGEO4W_ROOT" in os.environ:
                    testfolder = os.path.join(unicode(os.environ['OSGEO4W_ROOT']), "apps")
                else:
                    testfolder = unicode(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)
                            fn = os.path.join(folder, "etc", "VERSIONNUMBER")
                            if not os.path.isfile(fn):
                                continue

                            f = open(fn, "r")
                            Grass7Utils.version = f.read().split(' ')[0]
                            f.close()

                            major, minor, patch = Grass7Utils.version.split('.')
                            Grass7Utils.command = "grass{}{}".format(major, minor)
                            break
            else:
                folder = os.path.join(unicode(QgsApplication.prefixPath()), 'grass7')
                if not os.path.isdir(folder):
                    folder = '/Applications/GRASS-7.0.app/Contents/MacOS'

        return folder or ''
Ejemplo n.º 26
0
Archivo: utils.py Proyecto: gltn/stdm
def qgis_app():
    """
    Start QGIS application to test against. Based on code from Inasafe plugin.
    :return: Reference to QGIS application, canvas and parent widget.
    :rtype:(QgsApplication, QWidget, QgsMapCanvas)
    """
    global QGIS_APP

    if QGIS_APP is None:
        gui_flag = True

        QCoreApplication.setOrganizationName('QGIS')
        QCoreApplication.setOrganizationDomain('qgis.org')
        QCoreApplication.setApplicationName('STDM_Testing')

        QGIS_APP = QgsApplication(sys.argv, gui_flag)
        QGIS_APP.initQgis()

    global PARENT
    if PARENT is None:
        PARENT = QWidget()

    global CANVAS
    if CANVAS is None:
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QSize(400, 400))

    return QGIS_APP, CANVAS, PARENT
Ejemplo n.º 27
0
    def progress_callback(self, current_value, maximum_value, message=None):
        """GUI based callback implementation for showing progress.

        :param current_value: Current progress.
        :type current_value: int

        :param maximum_value: Maximum range (point at which task is complete.
        :type maximum_value: int

        :param message: Optional message dictionary to containing content
            we can display to the user. See safe.definitions.analysis_steps
            for an example of the expected format
        :type message: dict
        """
        report = m.Message()
        report.add(LOGO_ELEMENT)
        report.add(m.Heading(
            tr('Analysis status'), **INFO_STYLE))
        if message is not None:
            report.add(m.ImportantText(message['name']))
            report.add(m.Paragraph(message['description']))
        report.add(self.impact_function.performance_log_message())
        send_static_message(self, report)
        self.progress_bar.setMaximum(maximum_value)
        self.progress_bar.setValue(current_value)
        QgsApplication.processEvents()
Ejemplo n.º 28
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())
Ejemplo n.º 29
0
    def __init__(self, iface):
        Plugin.__init__(self, iface, "PointsInPolygons")

        userPluginPath = QtCore.QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + '/python/plugins/points_in_polygons'
        systemPluginPath = QgsApplication.prefixPath() + '/python/plugins/points_in_polygons'

        overrideLocale = QtCore.QSettings().value('locale/overrideFlag', False, type=bool)
        if not overrideLocale:
            localeFullName = QtCore.QLocale.system().name()[:2]
        else:
            localeFullName = QtCore.QSettings().value("locale/userLocale", "")

        if QtCore.QFileInfo(userPluginPath).exists():
            translationPath = userPluginPath + '/i18n/pointsinpolygons_' + localeFullName + '.qm'
            self.pluginPath = userPluginPath
        else:
            translationPath = systemPluginPath + '/i18n/pointsinpolygons_' + localeFullName + '.qm'
            self.pluginPath = systemPluginPath

        self.localePath = translationPath
        if QtCore.QFileInfo(self.localePath).exists():
            self.translator = QtCore.QTranslator()
            self.translator.load(self.localePath)
            QgsApplication.installTranslator(self.translator)

        self.pointLayerName = ""
        self.polygonLayerName = ""
        self.fieldName = ""
Ejemplo n.º 30
0
    def testOwnership(self):
        """
        Test that registered color schemes do not require that a reference to them is kept.
        They should be parented to the registry (on transfer) and even if there's no reference
        to the registry around (see the `del` below) this childship should continue to exist.
        """
        class TestColorScheme(QgsColorScheme):

            def schemeName(self):
                return "TestScheme"

            def fetchColors(self, context, baseColors):
                return None

            def clone(self):
                return TestColorScheme()

            def flags(self):
                return 1

        reg = QgsApplication.instance().colorSchemeRegistry()
        reg.addColorScheme(TestColorScheme())
        del reg

        reg = QgsApplication.instance().colorSchemeRegistry()

        self.assertIn('TestScheme', [scheme.schemeName() for scheme in reg.schemes()])
    def createRequest(self, operation, original_request, outgoing_data):
        """
            Overridden method. See https://doc.qt.io/qt-5/qnetworkaccessmanager.html#createRequest
            :param operation: The operation
            :type operation: QNetworkAccessManager.Operation
            :param original_request: The request
            :type original_request: QNetworkRequest
            :param outgoing_data: The outgoing data
            :type outgoing_data: QIODevice
            :return: The reply in the open state
            :rtype: QNetworkReply
        """
        # Invoking the original method
        if not self.experiment:
            reply = super().createRequest(operation, original_request, outgoing_data)
            return reply

        qgs_logger = QgsApplication.messageLog()
        qgs_logger.logMessage('createRequest: overrided', tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)

        # 28 March 2019
        certificate = CsiCertificate()
        qba_cert = certificate.get_certificate()
        qba_key = certificate.get_key()
        qgs_logger.logMessage('_createRequest: csi cert {}'.format(qba_cert.__class__.__name__),
                              tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Warning)
        ssl_conf = original_request.sslConfiguration()
        ca_cert_list = ssl_conf.caCertificates()
        qgs_logger.logMessage('_createRequest: ca_cert_list {}'.format(ca_cert_list.__class__.__name__),
                              tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Warning)
        for ca in ca_cert_list:
            qgs_logger.logMessage('_createRequest: ca {}'.format(ca.__class__.__name__),
                                  tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Warning)

        ca_cert = QtNetwork.QSslCertificate.fromData(qba_cert, QtNetwork.QSsl.Pem)
        ca_cert_list.append(ca_cert)

        ssl_key = QtNetwork.QSslKey(qba_key, QtNetwork.QSsl.Rsa)
        ssl_cert = QtNetwork.QSslCertificate(qba_cert)
        ssl_conf.setLocalCertificate(ssl_cert)
        ssl_conf.setPrivateKey(ssl_key)
        ssl_conf.setProtocol(QtNetwork.QSsl.AnyProtocol)
        original_request.setSslConfiguration(ssl_conf)

        # Following is useful for testing issues on HTTPS and WMS Basic auth:
        if self.debug:
            qgs_logger.logMessage('createRequest: operation {}'.format(str(operation)),
                                  tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)
            qgs_logger.logMessage('createRequest: request {}'.format(original_request),
                                  tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)
            if outgoing_data is not None:
                qgs_logger.logMessage('createRequest: data {}'.format(str(outgoing_data)),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)
            if outgoing_data and hasattr(outgoing_data, 'bytesAvailable'):
                qgs_logger.logMessage('createRequest: data size {}'.format(str(outgoing_data.bytesAvailable())),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)

            # Logging URL data
            url = original_request.url()
            qgs_logger.logMessage('createRequest: url {}'.format(url),
                                  configuration=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)
            if hasattr(url, 'encodedPath'):
                qgs_logger.logMessage('createRequest: encoded query items {}'.format(url.encodedPath()),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)
            if hasattr(url, 'encodedQuery'):
                qgs_logger.logMessage('_createRequest: encoded query items {}'.format(url.encodedQuery()),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)
            if hasattr(url, 'encodedQueryItems'):
                qgs_logger.logMessage('_createRequest: encoded query items {}'.format(url.encodedQueryItems()),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)
            if hasattr(url, 'queryItems'):
                qgs_logger.logMessage('_createRequest: queryItems? {}'.format(url.queryItems()),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)
            qgs_logger.logMessage('_createRequest: headers {}'.format(original_request.rawHeaderList()),
                                  tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Info)

        # Generating the request
        reply = super().createRequest(operation, original_request, outgoing_data)
        return reply
Ejemplo n.º 32
0
 def icon(self):
     return QgsApplication.getThemeIcon(
         "/algorithms/mAlgorithmCentroids.svg")
Ejemplo n.º 33
0
    def test_makeKeyTokens_(self):
        # see http://www.w3.org/TR/REC-xml/#d0e804 for a list of valid characters

        invalidTokens = []
        validTokens = []

        # all test tokens will be generated by prepending or inserting characters to this token
        validBase = "valid"

        # some invalid characters, not allowed anywhere in a token
        # note that '/' must not be added here because it is taken as a separator by makeKeyTokens_()
        invalidChars = "+*,;<>|!$%()=?#\x01"

        # generate the characters that are allowed at the start of a token (and at every other position)
        validStartChars = ":_"
        charRanges = [
            (ord('a'), ord('z')),
            (ord('A'), ord('Z')),
            (0x00F8, 0x02FF),
            (0x0370, 0x037D),
            (0x037F, 0x1FFF),
            (0x200C, 0x200D),
            (0x2070, 0x218F),
            (0x2C00, 0x2FEF),
            (0x3001, 0xD7FF),
            (0xF900, 0xFDCF),
            (0xFDF0, 0xFFFD),
            #(0x10000, 0xEFFFF),   while actually valid, these are not yet accepted by makeKeyTokens_()
        ]
        for r in charRanges:
            for c in range(r[0], r[1]):
                validStartChars += chr(c)

        # generate the characters that are only allowed inside a token, not at the start
        validInlineChars = "-.\xB7"
        charRanges = [
            (ord('0'), ord('9')),
            (0x0300, 0x036F),
            (0x203F, 0x2040),
        ]
        for r in charRanges:
            for c in range(r[0], r[1]):
                validInlineChars += chr(c)

        # test forbidden start characters
        for c in invalidChars + validInlineChars:
            invalidTokens.append(c + validBase)

        # test forbidden inline characters
        for c in invalidChars:
            invalidTokens.append(validBase[:4] + c + validBase[4:])

        # test each allowed start character
        for c in validStartChars:
            validTokens.append(c + validBase)

        # test each allowed inline character
        for c in validInlineChars:
            validTokens.append(validBase[:4] + c + validBase[4:])

        logger = QgsApplication.messageLog()
        logger.messageReceived.connect(self.catchMessage)
        prj = QgsProject.instance()

        for token in validTokens:
            self.messageCaught = False
            prj.readEntry("test", token)
            myMessage = "valid token '%s' not accepted" % (token)
            assert not self.messageCaught, myMessage

        for token in invalidTokens:
            self.messageCaught = False
            prj.readEntry("test", token)
            myMessage = "invalid token '%s' accepted" % (token)
            assert self.messageCaught, myMessage

        logger.messageReceived.disconnect(self.catchMessage)
Ejemplo n.º 34
0
 def svgIconPath(self):
     return QgsApplication.iconPath(
         "/algorithms/mAlgorithmRegularPoints.svg")
Ejemplo n.º 35
0
 def icon(self):
     return QgsApplication.getThemeIcon(
         "/algorithms/mAlgorithmRegularPoints.svg")
Ejemplo n.º 36
0
 def svgIconPath(self):
     return QgsApplication.iconPath(
         "/algorithms/mAlgorithmUniqueValues.svg")
Ejemplo n.º 37
0
 def icon(self):
     return QgsApplication.getThemeIcon(
         "/algorithms/mAlgorithmUniqueValues.svg")
Ejemplo n.º 38
0
 def svgIconPath(self):
     return QgsApplication.iconPath("providerQgis.svg")
Ejemplo n.º 39
0
Archivo: menus.py Proyecto: Geoany/QGIS
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 slot_ssl_errors_handler(self, reply, errors):
        """
            Handler for the arisen SSL errors, usually encountered during set-up.
            See: https://doc.qt.io/qt-5/qnetworkaccessmanager.html#sslErrors
            :param reply: The request sent through the QNetworkAccessManager
            :type reply: QNetworkReply
            :param errors: The list of errors
            :type errors: QList of QSslError
        """
        qgs_logger = QgsApplication.messageLog()
        qgs_logger.logMessage('slot_ssl_errors_handler: connected', tag=configuration.NETWORK_LOGGER_TAG,
                              level=Qgis.Info)
        url = reply.url().toString()
        qgs_logger.logMessage('slot_ssl_errors_handler: ignoreSslErrors() {}'.format(url),
                              tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Warning)

        # The list of the fields identifiers to print (i.e. from 0 to 5 included)
        certificate_fields_list = range(0, 6)

        # Processing the errors
        errors_messages = []
        for e in errors:
            # Logging the error data
            qgs_logger.logMessage('slot_ssl_errors_handler: e {}'.format(e.__class__.__name__),
                                  tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Critical)
            qgs_logger.logMessage('slot_ssl_errors_handler: errorString {}'.format(e.errorString()),
                                  tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Critical)
            if len(errors_messages) > 0:
                errors_messages.append("\n")

            errors_messages.append(e.errorString())

            # In case the debug flag is enabled, log additional details
            if self.debug:
                # Logging the certificate
                certificate = e.certificate()
                qgs_logger.logMessage('slot_ssl_errors_handler: certificate {}'.format(certificate),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Warning)

                # Printing the certificate 'data' for subjectInfo and issuerInfo fields
                for i in certificate_fields_list:
                    qgs_logger.logMessage('slot_ssl_errors_handler: subjectInfo[{}] {}'
                                          .format(i, certificate.subjectInfo(i)), tag=configuration.NETWORK_LOGGER_TAG,
                                          level=Qgis.Warning)
                    qgs_logger.logMessage('slot_ssl_errors_handler: issuerInfo[{}] {}'
                                          .format(i, certificate.issuerInfo(i)), tag=configuration.NETWORK_LOGGER_TAG,
                                          level=Qgis.Warning)

                # Printing other certificate 'data'
                qgs_logger.logMessage('slot_ssl_errors_handler: version {}'.format(certificate.version()),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Warning)
                qgs_logger.logMessage('slot_ssl_errors_handler: effectiveDate {}'
                                      .format(certificate.effectiveDate().toString("dd.MM.yyyy hh:mm:ss.zzz")),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Warning)
                expiration_date = certificate.expiryDate().toString("dd.MM.yyyy hh:mm:ss.zzz")
                qgs_logger.logMessage('slot_ssl_errors_handler: expiryDate {}'.format(expiration_date),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Warning)
                public_key = certificate.publicKey()
                qgs_logger.logMessage('slot_ssl_errors_handler: publicKey {}'.format(public_key),
                                      tag=configuration.NETWORK_LOGGER_TAG, level=Qgis.Warning)

        # Letting the user decide to proceed
        message = "Si sta cercando di connettersi ad un indirizzo in HTTPs, ma sono sorti dei problemi. "
        if len(errors_messages) > 0:
            message += "Riscontrati i seguenti errori:\n\n"
            message += "".join(errors_messages)
        else:
            message += "Probabilmente problema di certificato SSL."
        message += "\n\nProcedere comunque?"
        user_answer = QMessageBox.question(None, 'Attenzione', message, QMessageBox.Yes, QMessageBox.No)
        if user_answer == QMessageBox.No:
            return

        reply.ignoreSslErrors()
Ejemplo n.º 41
0
    def __init__(self, model=None):
        super(ModelerDialog, self).__init__(None)
        self.setupUi(self)

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.centralWidget().layout().insertWidget(0, self.bar)

        try:
            self.setDockOptions(self.dockOptions()
                                | QMainWindow.GroupedDragging)
        except:
            pass

        self.mToolbar.setIconSize(iface.iconSize())
        self.mActionOpen.setIcon(
            QgsApplication.getThemeIcon('/mActionFileOpen.svg'))
        self.mActionSave.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSave.svg'))
        self.mActionSaveAs.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSaveAs.svg'))
        self.mActionZoomActual.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomActual.svg'))
        self.mActionZoomIn.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomIn.svg'))
        self.mActionZoomOut.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomOut.svg'))
        self.mActionExportImage.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveMapAsImage.svg'))
        self.mActionZoomToItems.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomFullExtent.svg'))
        self.mActionExportPdf.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveAsPDF.svg'))
        self.mActionExportSvg.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveAsSVG.svg'))
        self.mActionExportPython.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveAsPython.svg'))
        self.mActionEditHelp.setIcon(
            QgsApplication.getThemeIcon('/mActionEditHelpContent.svg'))
        self.mActionRun.setIcon(
            QgsApplication.getThemeIcon('/mActionStart.svg'))

        self.addDockWidget(Qt.LeftDockWidgetArea, self.propertiesDock)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.inputsDock)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.algorithmsDock)
        self.tabifyDockWidget(self.inputsDock, self.algorithmsDock)
        self.inputsDock.raise_()

        self.zoom = 1

        self.setWindowFlags(Qt.WindowMinimizeButtonHint
                            | Qt.WindowMaximizeButtonHint
                            | Qt.WindowCloseButtonHint)

        settings = QgsSettings()
        self.restoreState(
            settings.value("/Processing/stateModeler", QByteArray()))
        self.restoreGeometry(
            settings.value("/Processing/geometryModeler", QByteArray()))

        self.scene = ModelerScene(self, dialog=self)
        self.scene.setSceneRect(
            QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE))

        self.view.setScene(self.scene)
        self.view.setAcceptDrops(True)
        self.view.ensureVisible(0, 0, 10, 10)

        def _dragEnterEvent(event):
            if event.mimeData().hasText():
                event.acceptProposedAction()
            else:
                event.ignore()

        def _dropEvent(event):
            if event.mimeData().hasText():
                text = event.mimeData().text()
                if text in ModelerParameterDefinitionDialog.paramTypes:
                    self.addInputOfType(text, event.pos())
                else:
                    alg = QgsApplication.processingRegistry(
                    ).createAlgorithmById(text)
                    if alg is not None:
                        self._addAlgorithm(alg, event.pos())
                event.accept()
            else:
                event.ignore()

        def _dragMoveEvent(event):
            if event.mimeData().hasText():
                event.accept()
            else:
                event.ignore()

        def _wheelEvent(event):
            self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)

            settings = QgsSettings()
            factor = settings.value('/qgis/zoom_favor', 2.0)

            # "Normal" mouse has an angle delta of 120, precision mouses provide data
            # faster, in smaller steps
            factor = 1.0 + (factor - 1.0) / 120.0 * abs(event.angleDelta().y())

            if (event.modifiers() == Qt.ControlModifier):
                factor = 1.0 + (factor - 1.0) / 20.0

            if event.angleDelta().y() < 0:
                factor = 1 / factor

            self.view.scale(factor, factor)

        def _enterEvent(e):
            QGraphicsView.enterEvent(self.view, e)
            self.view.viewport().setCursor(Qt.ArrowCursor)

        def _mouseReleaseEvent(e):
            QGraphicsView.mouseReleaseEvent(self.view, e)
            self.view.viewport().setCursor(Qt.ArrowCursor)

        def _mousePressEvent(e):
            if e.button() == Qt.MidButton:
                self.previousMousePos = e.pos()
            else:
                QGraphicsView.mousePressEvent(self.view, e)

        def _mouseMoveEvent(e):
            if e.buttons() == Qt.MidButton:
                offset = self.previousMousePos - e.pos()
                self.previousMousePos = e.pos()

                self.view.verticalScrollBar().setValue(
                    self.view.verticalScrollBar().value() + offset.y())
                self.view.horizontalScrollBar().setValue(
                    self.view.horizontalScrollBar().value() + offset.x())
            else:
                QGraphicsView.mouseMoveEvent(self.view, e)

        self.view.setDragMode(QGraphicsView.ScrollHandDrag)
        self.view.dragEnterEvent = _dragEnterEvent
        self.view.dropEvent = _dropEvent
        self.view.dragMoveEvent = _dragMoveEvent
        self.view.wheelEvent = _wheelEvent
        self.view.enterEvent = _enterEvent
        self.view.mousePressEvent = _mousePressEvent
        self.view.mouseMoveEvent = _mouseMoveEvent

        def _mimeDataInput(items):
            mimeData = QMimeData()
            text = items[0].text(0)
            mimeData.setText(text)
            return mimeData

        self.inputsTree.mimeData = _mimeDataInput

        self.inputsTree.setDragDropMode(QTreeWidget.DragOnly)
        self.inputsTree.setDropIndicatorShown(True)

        def _mimeDataAlgorithm(items):
            item = items[0]
            mimeData = None
            if isinstance(item, TreeAlgorithmItem):
                mimeData = QMimeData()
                mimeData.setText(item.alg.id())
            return mimeData

        self.algorithmTree.mimeData = _mimeDataAlgorithm

        self.algorithmTree.setDragDropMode(QTreeWidget.DragOnly)
        self.algorithmTree.setDropIndicatorShown(True)

        if hasattr(self.searchBox, 'setPlaceholderText'):
            self.searchBox.setPlaceholderText(self.tr('Search...'))
        if hasattr(self.textName, 'setPlaceholderText'):
            self.textName.setPlaceholderText(self.tr('Enter model name here'))
        if hasattr(self.textGroup, 'setPlaceholderText'):
            self.textGroup.setPlaceholderText(self.tr('Enter group name here'))

        # Connect signals and slots
        self.inputsTree.doubleClicked.connect(self.addInput)
        self.searchBox.textChanged.connect(self.textChanged)
        self.algorithmTree.doubleClicked.connect(self.addAlgorithm)

        # Ctrl+= should also trigger a zoom in action
        ctrlEquals = QShortcut(QKeySequence("Ctrl+="), self)
        ctrlEquals.activated.connect(self.zoomIn)

        self.mActionOpen.triggered.connect(self.openModel)
        self.mActionSave.triggered.connect(self.save)
        self.mActionSaveAs.triggered.connect(self.saveAs)
        self.mActionZoomIn.triggered.connect(self.zoomIn)
        self.mActionZoomOut.triggered.connect(self.zoomOut)
        self.mActionZoomActual.triggered.connect(self.zoomActual)
        self.mActionZoomToItems.triggered.connect(self.zoomToItems)
        self.mActionExportImage.triggered.connect(self.exportAsImage)
        self.mActionExportPdf.triggered.connect(self.exportAsPdf)
        self.mActionExportSvg.triggered.connect(self.exportAsSvg)
        self.mActionExportPython.triggered.connect(self.exportAsPython)
        self.mActionEditHelp.triggered.connect(self.editHelp)
        self.mActionRun.triggered.connect(self.runModel)

        if model is not None:
            self.model = model.create()
            self.model.setSourceFilePath(model.sourceFilePath())
            self.textGroup.setText(self.model.group())
            self.textName.setText(self.model.displayName())
            self.repaintModel()

        else:
            self.model = QgsProcessingModelAlgorithm()
            self.model.setProvider(
                QgsApplication.processingRegistry().providerById('model'))

        self.fillInputsTree()
        self.fillTreeUsingProviders()

        self.view.centerOn(0, 0)
        self.help = None

        self.hasChanged = False
Ejemplo n.º 42
0
 def icon(self):
     return QgsApplication.getThemeIcon("/providerQgis.svg")
Ejemplo n.º 43
0
 def svgIconPath(self):
     return QgsApplication.iconPath(
         "/algorithms/mAlgorithmRandomPointsWithinPolygon.svg")
Ejemplo n.º 44
0
 def updateModel(self):
     QgsApplication.processingRegistry().providerById('model').refreshAlgorithms()
Ejemplo n.º 45
0
 def unload(self):
     QgsApplication.processingRegistry().removeProvider(self.provider)
Ejemplo n.º 46
0
 def addAlgorithm(self):
     item = self.algorithmTree.currentItem()
     if isinstance(item, TreeAlgorithmItem):
         alg = QgsApplication.processingRegistry().createAlgorithmById(
             item.alg.id())
         self._addAlgorithm(alg)
Ejemplo n.º 47
0
 def svgIconPath(self):
     return QgsApplication.iconPath("/algorithms/mAlgorithmSplitLayer.svg")
Ejemplo n.º 48
0
 def icon(self):
     return QgsApplication.getThemeIcon(
         "/algorithms/mAlgorithmRandomPointsWithinPolygon.svg")
Ejemplo n.º 49
0
def clearRegistry():
    # clear registry to start with
    for r in QgsApplication.rendererRegistry().renderersList():
        if r == 'singleSymbol':
            continue
        QgsApplication.rendererRegistry().removeRenderer(r)
Ejemplo n.º 50
0
 def initGui(self):
     QgsApplication.processingRegistry().addProvider(self.provider)
Ejemplo n.º 51
0
 def icon(self):
     return QgsApplication.getThemeIcon("/processingScript.svg")
Ejemplo n.º 52
0
 def icon(self):
     return QgsApplication.getThemeIcon("/algorithms/mAlgorithmSplitLayer.svg")
Ejemplo n.º 53
0
    def setUp(self):
        self.report = "<h1>Python QgsSvgCache Tests</h1>\n"

        self.fetched = True
        QgsApplication.svgCache().remoteSvgFetched.connect(self.svgFetched)
Ejemplo n.º 54
0
 def svgIconPath(self):
     return QgsApplication.iconPath("processingScript.svg")
Ejemplo n.º 55
0
    def initGui(self):
        self.toolbox = ProcessingToolbox()
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox)
        self.toolbox.hide()
        self.toolbox.visibilityChanged.connect(self.toolboxVisibilityChanged)

        self.resultsDock = ResultsDock()
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.resultsDock)
        self.resultsDock.hide()

        self.menu = QMenu(self.iface.mainWindow().menuBar())
        self.menu.setObjectName('processing')
        self.menu.setTitle(self.tr('Pro&cessing'))

        self.toolboxAction = QAction(self.tr('&Toolbox'),
                                     self.iface.mainWindow())
        self.toolboxAction.setCheckable(True)
        self.toolboxAction.setObjectName('toolboxAction')
        self.toolboxAction.setIcon(
            QgsApplication.getThemeIcon("/processingAlgorithm.svg"))
        self.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T')
        self.toolboxAction.toggled.connect(self.openToolbox)
        self.iface.attributesToolBar().insertAction(
            self.iface.actionOpenStatisticalSummary(), self.toolboxAction)
        self.menu.addAction(self.toolboxAction)

        self.modelerAction = QAction(
            QgsApplication.getThemeIcon("/processingModel.svg"),
            self.tr('Graphical &Modeler...'), self.iface.mainWindow())
        self.modelerAction.setObjectName('modelerAction')
        self.modelerAction.triggered.connect(self.openModeler)
        self.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M')
        self.menu.addAction(self.modelerAction)

        self.historyAction = QAction(
            QIcon(os.path.join(pluginPath, 'images', 'history.svg')),
            self.tr('&History...'), self.iface.mainWindow())
        self.historyAction.setObjectName('historyAction')
        self.historyAction.triggered.connect(self.openHistory)
        self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H')
        self.menu.addAction(self.historyAction)
        self.toolbox.processingToolbar.addAction(self.historyAction)

        self.resultsAction = self.resultsDock.toggleViewAction()
        self.resultsAction.setObjectName('resultsAction')
        self.resultsAction.setIcon(
            QgsApplication.getThemeIcon("/processingResult.svg"))
        self.resultsAction.setText(self.tr('&Results Viewer'))
        self.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R')
        self.menu.addAction(self.resultsAction)
        self.toolbox.processingToolbar.addAction(self.resultsAction)

        self.optionsAction = QAction(
            QgsApplication.getThemeIcon("/mActionOptions.svg"),
            self.tr('Options'), self.iface.mainWindow())
        self.optionsAction.setObjectName('optionsAction')
        self.optionsAction.triggered.connect(self.openProcessingOptions)
        self.toolbox.processingToolbar.addAction(self.optionsAction)

        menuBar = self.iface.mainWindow().menuBar()
        menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(),
                           self.menu)

        self.menu.addSeparator()

        initializeMenus()
        createMenus()
Ejemplo n.º 56
0
def userFolder():
    userDir = os.path.join(QgsApplication.qgisSettingsDirPath(), 'processing')
    if not QDir(userDir).exists():
        QDir().mkpath(userDir)

    return str(QDir.toNativeSeparators(userDir))
Ejemplo n.º 57
0
 def unload(self):
     self.fsModel = None
     QgsApplication.processingRegistry().removeProvider(self.provider)
Ejemplo n.º 58
0
 def icon(self):
     return QgsApplication.getThemeIcon('/processingAlgorithm.svg')
Ejemplo n.º 59
0
 def initGui(self):
     QgsApplication.processingRegistry().addProvider(self.provider)
     self.switchLangEn()
     for k, tab in self.connectors.items():
         tab.initGui()
# coding: utf-8
from PyQt4.QtCore import QSettings
from qgis.core import QgsApplication
from qgis.gui import QgsSVGFillSymbolLayerWidget
from qgis.utils import iface

layer = iface.activeLayer()

# Print the SVG paths
print(QgsApplication.svgPaths())

# Specific to our use case.
# QgsApplication.setDefaultSvgPaths did not alter all the paths.
# Default value for "svg/searchPathsForSVG" is $HOME but as we had many git
# repositories under $HOME, QGIS was scanning all of them to look for SVG.
# Uncomment or not depending of your case
# s = QSettings()
# s.setValue("svg/searchPathsForSVG", "/tmp")  # Change the path if on Windows

# To confirm the difference if you apply above two previous lines
print(QgsApplication.svgPaths())

svg_fill_symbol_layer_widget = QgsSVGFillSymbolLayerWidget(
    layer
)
svg_fill_symbol_layer_widget.show()