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)
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)
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()
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 ''
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()
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
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))
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
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())
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()
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 ''
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()
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
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 = ""
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
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))
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'])
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 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")
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
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
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
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)
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)
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()
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
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()
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()
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()
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)