def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() else: QMessageBox.warning(self, self.tr('Unable to add algorithm'), self.tr('Wrong or missing parameter values'))
def execute(self): settings = QSettings() lastDir = settings.value('Processing/lastModelsDir', '') filename = QFileDialog.getOpenFileName(self.toolbox, self.tr('Open model', 'AddModelFromFileAction'), lastDir, self.tr('Processing model files (*.model *.MODEL)', 'AddModelFromFileAction')) if filename: try: settings.setValue('Processing/lastModelsDir', QFileInfo(filename).absoluteDir().absolutePath()) ModelerAlgorithm.fromFile(filename) except WrongModelException: QMessageBox.warning( self.toolbox, self.tr('Error reading model', 'AddModelFromFileAction'), self.tr('The selected file does not contain a valid model', 'AddModelFromFileAction')) return except: QMessageBox.warning(self.toolbox, self.tr('Error reading model', 'AddModelFromFileAction'), self.tr('Cannot read file', 'AddModelFromFileAction')) return destFilename = os.path.join(ModelerUtils.modelsFolder(), os.path.basename(filename)) shutil.copyfile(filename, destFilename) self.toolbox.updateProvider('model')
def batchFinished(self): self.base.stop() if len(self.errors) > 0: msg = u"Processing of the following files ended with error: <br><br>" + "<br><br>".join(self.errors) QErrorMessage(self).showMessage(msg) inDir = self.getInputFileName() outDir = self.getOutputFileName() if outDir is None or inDir == outDir: self.outFiles = self.inFiles # load layers managing the render flag to avoid waste of time canvas = self.iface.mapCanvas() previousRenderFlag = canvas.renderFlag() canvas.setRenderFlag(False) notCreatedList = [] for item in self.outFiles: fileInfo = QFileInfo(item) if fileInfo.exists(): if self.base.loadCheckBox.isChecked(): self.addLayerIntoCanvas(fileInfo) else: notCreatedList.append(item) canvas.setRenderFlag(previousRenderFlag) if len(notCreatedList) == 0: QMessageBox.information(self, self.tr("Finished"), self.tr("Operation completed.")) else: QMessageBox.warning(self, self.tr("Warning"), self.tr("The following files were not created: \n{0}").format(', '.join(notCreatedList)))
def activateAlgorithm(self): if self.model.activateAlgorithm(self.element.name): self.model.updateModelerView() else: QMessageBox.warning(None, 'Could not activate Algorithm', 'The selected algorithm depends on other currently non-active algorithms.\n' 'Activate them them before trying to activate it.')
def execute(self): settings = QSettings() lastDir = settings.value('Processing/lastScriptsDir', '') filename = QFileDialog.getOpenFileName( self.toolbox, self.tr('Script files', 'AddScriptFromFileAction'), lastDir, self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction')) if filename: try: settings.setValue( 'Processing/lastScriptsDir', QFileInfo(filename).absoluteDir().absolutePath()) script = ScriptAlgorithm(filename) except WrongScriptException: QMessageBox.warning( self.toolbox, self.tr('Error reading script', 'AddScriptFromFileAction'), self.tr( 'The selected file does not contain a valid script', 'AddScriptFromFileAction')) return destFilename = os.path.join(ScriptUtils.scriptsFolder(), os.path.basename(filename)) with open(destFilename, 'w') as f: f.write(script.script) self.toolbox.updateProvider('script')
def execute(self): settings = QSettings() lastDir = settings.value('Processing/lastModelsDir', '') filename = QFileDialog.getOpenFileName( self.toolbox, self.tr('Open model', 'AddModelFromFileAction'), lastDir, self.tr('Processing model files (*.model *.MODEL)', 'AddModelFromFileAction')) if filename: try: settings.setValue( 'Processing/lastModelsDir', QFileInfo(filename).absoluteDir().absolutePath()) ModelerAlgorithm.fromFile(filename) except WrongModelException: QMessageBox.warning( self.toolbox, self.tr('Error reading model', 'AddModelFromFileAction'), self.tr('The selected file does not contain a valid model', 'AddModelFromFileAction')) return except: QMessageBox.warning( self.toolbox, self.tr('Error reading model', 'AddModelFromFileAction'), self.tr('Cannot read file', 'AddModelFromFileAction')) return destFilename = os.path.join(ModelerUtils.modelsFolder(), os.path.basename(filename)) shutil.copyfile(filename, destFilename) self.toolbox.updateProvider('model')
def refreshExtent(self): files = self.getInputFileNames() self.intersectCheck.setEnabled(len(files) > 1) if not self.intersectCheck.isChecked(): self.someValueChanged() return if len(files) < 2: self.intersectCheck.setChecked(False) return self.extent = self.getIntersectedExtent(files) if self.extent is None: QMessageBox.warning( self, self.tr("Error retrieving the extent"), self. tr('GDAL was unable to retrieve the extent from any file. \nThe "Use intersected extent" option will be unchecked.' )) self.intersectCheck.setChecked(False) return elif self.extent.isEmpty(): QMessageBox.warning( self, self.tr("Empty extent"), self. tr('The computed extent is empty. \nDisable the "Use intersected extent" option to have a nonempty output.' )) self.someValueChanged()
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 setParamValues(self): if self.mUpdateExistingGroupBox.isChecked(): fieldName = self.mExistingFieldComboBox.currentText() else: fieldName = self.mOutputFieldNameLineEdit.text() layer = dataobjects.getObjectFromName(self.cmbInputLayer.currentText()) self.alg.setParameterValue('INPUT_LAYER', layer) self.alg.setParameterValue('FIELD_NAME', fieldName) self.alg.setParameterValue('FIELD_TYPE', self.mOutputFieldTypeComboBox.currentIndex()) self.alg.setParameterValue('FIELD_LENGTH', self.mOutputFieldWidthSpinBox.value()) self.alg.setParameterValue('FIELD_PRECISION', self.mOutputFieldPrecisionSpinBox.value()) self.alg.setParameterValue('NEW_FIELD', self.mNewFieldGroupBox.isChecked()) self.alg.setParameterValue('FORMULA', self.builder.expressionText()) self.alg.setOutputValue('OUTPUT_LAYER', self.leOutputFile.text().strip() or None) msg = self.alg.checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning( self, self.tr('Unable to execute algorithm'), msg) return False return True
def setParamValues(self): if self.mUpdateExistingGroupBox.isChecked(): fieldName = self.mExistingFieldComboBox.currentText() else: fieldName = self.mOutputFieldNameLineEdit.text() layer = dataobjects.getObjectFromName(self.cmbInputLayer.currentText()) self.alg.setParameterValue('INPUT_LAYER', layer) self.alg.setParameterValue('FIELD_NAME', fieldName) self.alg.setParameterValue( 'FIELD_TYPE', self.mOutputFieldTypeComboBox.currentIndex()) self.alg.setParameterValue('FIELD_LENGTH', self.mOutputFieldWidthSpinBox.value()) self.alg.setParameterValue('FIELD_PRECISION', self.mOutputFieldPrecisionSpinBox.value()) self.alg.setParameterValue('NEW_FIELD', self.mNewFieldGroupBox.isChecked()) self.alg.setParameterValue('FORMULA', self.builder.expressionText()) self.alg.setOutputValue('OUTPUT_LAYER', self.leOutputFile.text().strip() or None) msg = self.alg.checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return False return True
def activateAlgorithm(self): if self.model.activateAlgorithm(self.element.name): self.model.updateModelerView() else: QMessageBox.warning( None, 'Could not activate Algorithm', 'The selected algorithm depends on other currently non-active algorithms.\n' 'Activate them them before trying to activate it.')
def activateProvider(self, providerName): name = 'ACTIVATE_' + providerName.upper().replace(' ', '_') ProcessingConfig.setSettingValue(name, True) self.fillTree() self.textChanged() self.showDisabled() provider = Processing.getProviderFromName(providerName) if not provider.canBeActivated(): QMessageBox.warning(self, "Activate provider", "The provider has been activated, but it might need additional configuration.")
def navigate(self): """manage navigation / paging""" caller = self.sender().objectName() if caller == 'btnFirst': self.startfrom = 0 elif caller == 'btnLast': self.startfrom = self.catalog.results['matches'] - self.maxrecords elif caller == 'btnNext': self.startfrom += self.maxrecords if self.startfrom >= self.catalog.results["matches"]: msg = self.tr('End of results. Go to start?') res = QMessageBox.information(self, self.tr('Navigation'), msg, (QMessageBox.Ok | QMessageBox.Cancel)) if res == QMessageBox.Ok: self.startfrom = 0 else: return elif caller == "btnPrev": self.startfrom -= self.maxrecords if self.startfrom <= 0: msg = self.tr('Start of results. Go to end?') res = QMessageBox.information(self, self.tr('Navigation'), msg, (QMessageBox.Ok | QMessageBox.Cancel)) if res == QMessageBox.Ok: self.startfrom = (self.catalog.results['matches'] - self.maxrecords) else: return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: self.catalog.getrecords2(constraints=self.constraints, maxrecords=self.maxrecords, startposition=self.startfrom, esn='full') except ExceptionReport as err: QApplication.restoreOverrideCursor() QMessageBox.warning(self, self.tr('Search error'), self.tr('Search error: %s') % err) return except Exception as err: QApplication.restoreOverrideCursor() QMessageBox.warning(self, self.tr('Connection error'), self.tr('Connection error: %s') % err) return QApplication.restoreOverrideCursor() self.display_results()
def importLayer(self, layerType, providerKey, layerName, uriString, parent): global isImportVectorAvail if not isImportVectorAvail: return False if layerType == 'raster': return False # not implemented yet inLayer = QgsRasterLayer(uriString, layerName, providerKey) else: inLayer = QgsVectorLayer(uriString, layerName, providerKey) if not inLayer.isValid(): # invalid layer QMessageBox.warning( None, self.tr("Invalid layer"), self.tr("Unable to load the layer %s") % inLayer.name()) return False # retrieve information about the new table's db and schema outItem = parent.internalPointer() outObj = outItem.getItemData() outDb = outObj.database() outSchema = None if isinstance(outItem, SchemaItem): outSchema = outObj elif isinstance(outItem, TableItem): outSchema = outObj.schema() # toIndex will point to the parent item of the new table toIndex = parent if isinstance(toIndex.internalPointer(), TableItem): toIndex = toIndex.parent() if inLayer.type() == inLayer.VectorLayer: # create the output uri schema = outSchema.name if outDb.schemas( ) is not None and outSchema is not None else "" pkCol = geomCol = "" # default pk and geom field name value if providerKey in ['postgres', 'spatialite']: inUri = QgsDataSourceURI(inLayer.source()) pkCol = inUri.keyColumn() geomCol = inUri.geometryColumn() outUri = outDb.uri() outUri.setDataSource(schema, layerName, geomCol, "", pkCol) self.importVector.emit(inLayer, outDb, outUri, toIndex) return True return False
def okPressed(self): if self.textTableName.text().strip() == "": self.textTableName.setStyleSheet("QLineEdit{background: yellow}") return item = self.treeConnections.currentItem() if isinstance(item, ConnectionItem): QMessageBox.warning(self, "Wrong selection", "Select a schema item in the tree") return self.schema = item.text(0) self.table = self.textTableName.text().strip() self.connection = item.parent().text(0) self.close()
def checkLayer(self): layerList = [] layerMap = QgsMapLayerRegistry.instance().mapLayers() for name, layer in layerMap.iteritems(): if layer.type() == QgsMapLayer.RasterLayer: layerList.append(unicode(layer.source())) if unicode(self.inputFileEdit.text()) in layerList: QMessageBox.warning(self, self.tr("Assign projection"), self.tr("This raster already found in map canvas")) return self.onRun()
def runModel(self): if len(self.alg.algs) == 0: QMessageBox.warning(self, self.tr('Empty model'), self.tr("Model doesn't contains any algorithms and/or " "parameters and can't be executed")) return if self.alg.provider is None: # Might happen if model is opened from modeler dialog self.alg.provider = ModelerUtils.providers['model'] alg = self.alg.getCopy() dlg = AlgorithmDialog(alg) dlg.exec_()
def importLayer(self, layerType, providerKey, layerName, uriString, parent): global isImportVectorAvail if not isImportVectorAvail: return False if layerType == 'raster': return False # not implemented yet inLayer = QgsRasterLayer(uriString, layerName, providerKey) else: inLayer = QgsVectorLayer(uriString, layerName, providerKey) if not inLayer.isValid(): # invalid layer QMessageBox.warning(None, self.tr("Invalid layer"), self.tr("Unable to load the layer %s") % inLayer.name()) return False # retrieve information about the new table's db and schema outItem = parent.internalPointer() outObj = outItem.getItemData() outDb = outObj.database() outSchema = None if isinstance(outItem, SchemaItem): outSchema = outObj elif isinstance(outItem, TableItem): outSchema = outObj.schema() # toIndex will point to the parent item of the new table toIndex = parent if isinstance(toIndex.internalPointer(), TableItem): toIndex = toIndex.parent() if inLayer.type() == inLayer.VectorLayer: # create the output uri schema = outSchema.name if outDb.schemas() is not None and outSchema is not None else "" pkCol = geomCol = "" # default pk and geom field name value if providerKey in ['postgres', 'spatialite']: inUri = QgsDataSourceURI(inLayer.source()) pkCol = inUri.keyColumn() geomCol = inUri.geometryColumn() outUri = outDb.uri() outUri.setDataSource(schema, layerName, geomCol, "", pkCol) self.importVector.emit(inLayer, outDb, outUri, toIndex) return True return False
def runModel(self): if len(self.alg.algs) == 0: QMessageBox.warning( self, self.tr('Empty model'), self.tr("Model doesn't contains any algorithms and/or " "parameters and can't be executed")) return if self.alg.provider is None: # Might happen if model is opened from modeler dialog self.alg.provider = ModelerUtils.providers['model'] alg = self.alg.getCopy() dlg = AlgorithmDialog(alg) dlg.exec_()
def removeElement(self): if isinstance(self.element, ModelerParameter): if not self.model.removeParameter(self.element.param.name): QMessageBox.warning(None, 'Could not remove element', 'Other elements depend on the selected one.\n' 'Remove them before trying to remove it.') else: self.model.updateModelerView() elif isinstance(self.element, Algorithm): if not self.model.removeAlgorithm(self.element.name): QMessageBox.warning(None, 'Could not remove element', 'Other elements depend on the selected one.\n' 'Remove them before trying to remove it.') else: self.model.updateModelerView()
def finished(self): outFn = self.getOutputFileName() if self.needOverwrite: oldFile = QFile(outFn) newFile = QFile(self.tempFile) if oldFile.remove(): newFile.rename(outFn) fileInfo = QFileInfo(outFn) if fileInfo.exists(): if self.base.loadCheckBox.isChecked(): self.addLayerIntoCanvas(fileInfo) QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed.")) else: QMessageBox.warning(self, self.tr("Warning"), self.tr("{0} not created.").format(outFn))
def openScript(self): if self.hasChanged: ret = QMessageBox.warning( self, self.tr('Unsaved changes'), self.tr('There are unsaved changes in script. Continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if ret == QMessageBox.No: return if self.algType == self.SCRIPT_PYTHON: scriptDir = ScriptUtils.scriptsFolder() filterName = self.tr('Python scripts (*.py)') elif self.algType == self.SCRIPT_R: scriptDir = RUtils.RScriptsFolder() filterName = self.tr('Processing R script (*.rsx)') self.filename = QFileDialog.getOpenFileName(self, self.tr('Save script'), scriptDir, filterName) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) with codecs.open(self.filename, 'r', encoding='utf-8') as f: txt = f.read() self.editor.setText(txt) self.hasChanged = False self.editor.setModified(False) self.editor.recolor() QApplication.restoreOverrideCursor()
def openScript(self): if self.hasChanged: ret = QMessageBox.warning(self, self.tr('Unsaved changes'), self.tr('There are unsaved changes in script. Continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if ret == QMessageBox.No: return if self.algType == self.SCRIPT_PYTHON: scriptDir = ScriptUtils.scriptsFolder() filterName = self.tr('Python scripts (*.py)') elif self.algType == self.SCRIPT_R: scriptDir = RUtils.RScriptsFolder() filterName = self.tr('Processing R script (*.rsx)') self.filename = QFileDialog.getOpenFileName( self, self.tr('Save script'), scriptDir, filterName) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) with codecs.open(self.filename, 'r', encoding='utf-8') as f: txt = f.read() self.editor.setText(txt) self.hasChanged = False self.editor.setModified(False) self.editor.recolor() QApplication.restoreOverrideCursor()
def add_default_connections(self): """add default connections""" filename = os.path.join(self.context.ppath, 'resources', 'connections-default.xml') doc = get_connections_from_file(self, filename) if doc is None: return self.settings.beginGroup('/MetaSearch/') keys = self.settings.childGroups() self.settings.endGroup() for server in doc.findall('csw'): name = server.attrib.get('name') # check for duplicates if name in keys: msg = self.tr('%s exists. Overwrite?') % name res = QMessageBox.warning(self, self.tr('Loading connections'), msg, QMessageBox.Yes | QMessageBox.No) if res != QMessageBox.Yes: continue # no dups detected or overwrite is allowed key = '/MetaSearch/%s' % name self.settings.setValue('%s/url' % key, server.attrib.get('url')) self.populate_connection_list()
def accept(self): for setting in self.items.keys(): if isinstance(setting.value, bool): setting.setValue(self.items[setting].checkState() == Qt.Checked) else: try: setting.setValue(unicode(self.items[setting].text())) except ValueError as e: QMessageBox.warning(self, self.tr('Wrong value'), self.tr('Wrong value for parameter "%s":\n\n%s' % (setting.description, unicode(e)))) return setting.save() Processing.updateAlgsList() updateMenus() QDialog.accept(self)
def load(self, items): """load connections""" self.settings.beginGroup('/MetaSearch/') keys = self.settings.childGroups() self.settings.endGroup() exml = etree.parse(self.filename).getroot() for csw in exml.findall('csw'): conn_name = csw.attrib.get('name') # process only selected connections if conn_name not in items: continue # check for duplicates if conn_name in keys: label = self.tr('File %s exists. Overwrite?') % conn_name res = QMessageBox.warning(self, self.tr('Loading Connections'), label, QMessageBox.Yes | QMessageBox.No) if res != QMessageBox.Yes: continue # no dups detected or overwrite is allowed url = '/MetaSearch/%s/url' % conn_name self.settings.setValue(url, csw.attrib.get('url'))
def finished(self, load): outFn = self.getOutputFileName() if outFn is None: return if outFn == '': QMessageBox.warning(self, self.tr("Warning"), self.tr("No output file created.")) return fileInfo = QFileInfo(outFn) if fileInfo.exists(): if load: self.addLayerIntoCanvas(fileInfo) QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed.")) else: #QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "%1 not created." ).arg( outFn ) ) QMessageBox.warning(self, self.tr("Warning"), self.tr("%s not created.") % outFn)
def enableRecurse(self): if self.recurseCheck.isChecked(): res = QMessageBox.warning(self, self.tr("Warning"), self.tr("Warning: CRS information for all raster in subfolders will be rewritten. Are you sure?"), QMessageBox.Yes | QMessageBox.No) if res != QMessageBox.Yes: self.recurseCheck.setCheckState(Qt.Unchecked) return
def removeElement(self): if isinstance(self.element, ModelerParameter): if not self.model.removeParameter(self.element.param.name): QMessageBox.warning( None, 'Could not remove element', 'Other elements depend on the selected one.\n' 'Remove them before trying to remove it.') else: self.model.updateModelerView() elif isinstance(self.element, Algorithm): if not self.model.removeAlgorithm(self.element.name): QMessageBox.warning( None, 'Could not remove element', 'Other elements depend on the selected one.\n' 'Remove them before trying to remove it.') else: self.model.updateModelerView()
def saveScript(self, saveAs): if self.filename is None or saveAs: if self.algType == self.SCRIPT_PYTHON: scriptDir = ScriptUtils.scriptsFolder() filterName = self.tr('Python scripts (*.py)') elif self.algType == self.SCRIPT_R: scriptDir = RUtils.RScriptsFolder() filterName = self.tr('Processing R script (*.rsx)') self.filename = unicode( QFileDialog.getSaveFileName(self, self.tr('Save script'), scriptDir, filterName)) if self.filename: if self.algType == self.SCRIPT_PYTHON and \ not self.filename.lower().endswith('.py'): self.filename += '.py' if self.algType == self.SCRIPT_R and \ not self.filename.lower().endswith('.rsx'): self.filename += '.rsx' text = unicode(self.editor.text()) if self.alg is not None: self.alg.script = text try: with codecs.open(self.filename, 'w', encoding='utf-8') as fout: fout.write(text) except IOError: QMessageBox.warning( self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n %s') % unicode(sys.exc_info()[1])) return self.update = True # If help strings were defined before saving the script for # the first time, we do it here if self.help: with open(self.filename + '.help', 'w') as f: json.dump(self.help, f) self.help = None self.setHasChanged(False) else: self.filename = None
def saveScript(self, saveAs): if self.filename is None or saveAs: if self.algType == self.SCRIPT_PYTHON: scriptDir = ScriptUtils.scriptsFolder() filterName = self.tr('Python scripts (*.py)') elif self.algType == self.SCRIPT_R: scriptDir = RUtils.RScriptsFolder() filterName = self.tr('Processing R script (*.rsx)') self.filename = unicode(QFileDialog.getSaveFileName(self, self.tr('Save script'), scriptDir, filterName)) if self.filename: if self.algType == self.SCRIPT_PYTHON and \ not self.filename.lower().endswith('.py'): self.filename += '.py' if self.algType == self.SCRIPT_R and \ not self.filename.lower().endswith('.rsx'): self.filename += '.rsx' text = unicode(self.editor.text()) if self.alg is not None: self.alg.script = text try: with codecs.open(self.filename, 'w', encoding='utf-8') as fout: fout.write(text) except IOError: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n %s') % unicode(sys.exc_info()[1]) ) return self.update = True # If help strings were defined before saving the script for # the first time, we do it here if self.help: with open(self.filename + '.help', 'w') as f: json.dump(self.help, f) self.help = None self.setHasChanged(False) else: self.filename = None
def _get_csw(self): """convenience function to init owslib.csw.CatalogueServiceWeb""" # connect to the server try: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.catalog = CatalogueServiceWeb(self.catalog_url, timeout=self.timeout) return True except ExceptionReport as err: msg = self.tr('Error connecting to service: %s') % err except ValueError as err: msg = self.tr('Value Error: %s') % err except Exception as err: msg = self.tr('Unknown Error: %s') % err QMessageBox.warning(self, self.tr('CSW Connection error'), msg) QApplication.restoreOverrideCursor() return False
def accept(self): """add CSW entry""" conn_name = self.leName.text().strip() conn_url = self.leURL.text().strip() if any([conn_name == '', conn_url == '']): QMessageBox.warning(self, self.tr('Save connection'), self.tr('Both Name and URL must be provided')) return if '/' in conn_name: QMessageBox.warning(self, self.tr('Save connection'), self.tr('Name cannot contain \'/\'')) return if conn_name is not None: key = '/MetaSearch/%s' % conn_name keyurl = '%s/url' % key key_orig = '/MetaSearch/%s' % self.conn_name_orig # warn if entry was renamed to an existing connection if all([ self.conn_name_orig != conn_name, self.settings.contains(keyurl) ]): res = QMessageBox.warning(self, self.tr('Save connection'), self.tr('Overwrite %s?') % conn_name, QMessageBox.Ok | QMessageBox.Cancel) if res == QMessageBox.Cancel: return # on rename delete original entry first if all([ self.conn_name_orig is not None, self.conn_name_orig != conn_name ]): self.settings.remove(key_orig) self.settings.setValue(keyurl, conn_url) self.settings.setValue('/MetaSearch/selected', conn_name) QDialog.accept(self)
def reject(self): if self.process.state() != QProcess.NotRunning: ret = QMessageBox.warning(self, self.tr("Warning"), self.tr("The command is still running. \nDo you want terminate it anyway?"), QMessageBox.Yes | QMessageBox.No) if ret == QMessageBox.No: return self.process.error.disconnect(self.processError) self.process.finished.disconnect(self.processFinished) self.closeClicked.emit()
def accept(self): for setting in self.items.keys(): if isinstance(setting.value, bool): setting.setValue( self.items[setting].checkState() == Qt.Checked) else: try: setting.setValue(unicode(self.items[setting].text())) except ValueError as e: QMessageBox.warning( self, self.tr('Wrong value'), self.tr('Wrong value for parameter "%s":\n\n%s' % (setting.description, unicode(e)))) return setting.save() Processing.updateAlgsList() updateMenus() QDialog.accept(self)
def use_rtree(self): idx = self.ui.table_idx.currentText() if idx in (None, "", " ", "Table (with Spatial Index)"): return try: tab_idx = idx.split(".")[0][1:-1] # remove " col_idx = idx.split(".")[1][1:-1] # remove ' except: QMessageBox.warning(self, "Use R-Tree", "All fields are necessary", QMessageBox.Cancel) tgt = self.ui.table_target.currentText() if tgt in (None, "", " ", "Table (Target)"): return tgt_tab = tgt.split('.')[0][1:-1] tgt_col = tgt.split('.')[1][1:-1] sql = "" if self.ui.where.toPlainText() not in (None, "", " "): sql += "\nAND" sql += self.db.spatialIndexClause(tab_idx, col_idx, tgt_tab, tgt_col) self.ui.where.insertPlainText(sql)
def batchRun(self): self.inFiles = Utils.getRasterFiles(self.getInputFileName(), self.isRecursiveScanEnabled()) if len(self.inFiles) == 0: QMessageBox.warning(self, self.tr("Warning"), self.tr("No input files to process.")) return self.outFiles = [] for f in self.inFiles: self.outFiles.append(self.getBatchOutputFileName(f)) self.base.enableRun(False) self.base.setCursor(Qt.WaitCursor) self.errors = [] self.batchIndex = 0 self.batchTotal = len(self.inFiles) self.setProgressRange(self.batchTotal) self.runItem(self.batchIndex, self.batchTotal)
def show_metadata(self): """show record metadata""" if not self.treeRecords.selectedItems(): return item = self.treeRecords.currentItem() if not item: return identifier = get_item_data(item, 'identifier') try: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) cat = CatalogueServiceWeb(self.catalog_url, timeout=self.timeout) cat.getrecordbyid( [self.catalog.records[identifier].identifier]) except ExceptionReport as err: QApplication.restoreOverrideCursor() QMessageBox.warning(self, self.tr('GetRecords error'), self.tr('Error getting response: %s') % err) return except KeyError as err: QMessageBox.warning(self, self.tr('Record parsing error'), 'Unable to locate record identifier') QApplication.restoreOverrideCursor() return QApplication.restoreOverrideCursor() record = cat.records[identifier] record.xml_url = cat.request crd = RecordDialog() metadata = render_template('en', self.context, record, 'record_metadata_dc.html') style = QgsApplication.reportStyleSheet() crd.textMetadata.document().setDefaultStyleSheet(style) crd.textMetadata.setHtml(metadata) crd.exec_()
def record_clicked(self): """record clicked signal""" # disable only service buttons self.reset_buttons(True, False, False) if not self.treeRecords.selectedItems(): return item = self.treeRecords.currentItem() if not item: return identifier = get_item_data(item, 'identifier') try: record = self.catalog.records[identifier] except KeyError as err: QMessageBox.warning(self, self.tr('Record parsing error'), 'Unable to locate record identifier') return # if the record has a bbox, show a footprint on the map if record.bbox is not None: points = bbox_to_polygon(record.bbox) if points is not None: src = QgsCoordinateReferenceSystem(4326) dst = self.map.mapRenderer().destinationCrs() geom = QgsGeometry.fromPolygon(points) if src.postgisSrid() != dst.postgisSrid(): ctr = QgsCoordinateTransform(src, dst) try: geom.transform(ctr) except Exception as err: QMessageBox.warning( self, self.tr('Coordinate Transformation Error'), unicode(err)) self.rubber_band.setToGeometry(geom, None) # figure out if the data is interactive and can be operated on self.find_services(record, item)
def execute(self): settings = QSettings() lastDir = settings.value('Processing/lastScriptsDir', '') filename = QFileDialog.getOpenFileName(self.toolbox, self.tr('Script files', 'AddScriptFromFileAction'), lastDir, self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction')) if filename: try: settings.setValue('Processing/lastScriptsDir', QFileInfo(filename).absoluteDir().absolutePath()) script = ScriptAlgorithm(filename) except WrongScriptException: QMessageBox.warning(self.toolbox, self.tr('Error reading script', 'AddScriptFromFileAction'), self.tr('The selected file does not contain a valid script', 'AddScriptFromFileAction')) return destFilename = os.path.join(ScriptUtils.scriptsFolder(), os.path.basename(filename)) with open(destFilename, 'w') as f: f.write(script.script) self.toolbox.updateProvider('script')
def accept(self): """add CSW entry""" conn_name = self.leName.text().strip() conn_url = self.leURL.text().strip() if any([conn_name == '', conn_url == '']): QMessageBox.warning(self, self.tr('Save connection'), self.tr('Both Name and URL must be provided')) return if '/' in conn_name: QMessageBox.warning(self, self.tr('Save connection'), self.tr('Name cannot contain \'/\'')) return if conn_name is not None: key = '/MetaSearch/%s' % conn_name keyurl = '%s/url' % key key_orig = '/MetaSearch/%s' % self.conn_name_orig # warn if entry was renamed to an existing connection if all([self.conn_name_orig != conn_name, self.settings.contains(keyurl)]): res = QMessageBox.warning(self, self.tr('Save connection'), self.tr('Overwrite %s?') % conn_name, QMessageBox.Ok | QMessageBox.Cancel) if res == QMessageBox.Cancel: return # on rename delete original entry first if all([self.conn_name_orig is not None, self.conn_name_orig != conn_name]): self.settings.remove(key_orig) self.settings.setValue(keyurl, conn_url) self.settings.setValue('/MetaSearch/selected', conn_name) QDialog.accept(self)
def reject(self): if self.process.state() != QProcess.NotRunning: ret = QMessageBox.warning( self, self.tr("Warning"), self. tr("The command is still running. \nDo you want terminate it anyway?" ), QMessageBox.Yes | QMessageBox.No) if ret == QMessageBox.No: return self.process.error.disconnect(self.processError) self.process.finished.disconnect(self.processFinished) self.closeClicked.emit()
def refreshExtent(self): files = self.getInputFileNames() self.intersectCheck.setEnabled(len(files) > 1) if not self.intersectCheck.isChecked(): self.someValueChanged() return if len(files) < 2: self.intersectCheck.setChecked(False) return self.extent = self.getIntersectedExtent(files) if self.extent is None: QMessageBox.warning(self, self.tr("Error retrieving the extent"), self.tr('GDAL was unable to retrieve the extent from any file. \nThe "Use intersected extent" option will be unchecked.')) self.intersectCheck.setChecked(False) return elif self.extent.isEmpty(): QMessageBox.warning(self, self.tr("Empty extent"), self.tr('The computed extent is empty. \nDisable the "Use intersected extent" option to have a nonempty output.')) self.someValueChanged()
def saveModel(self, saveAs): if unicode(self.textGroup.text()).strip() == '' \ or unicode(self.textName.text()).strip() == '': QMessageBox.warning( self, self.tr('Warning'), self.tr('Please enter group and model names before saving') ) return self.alg.name = unicode(self.textName.text()) self.alg.group = unicode(self.textGroup.text()) if self.alg.descriptionFile is not None and not saveAs: filename = self.alg.descriptionFile else: filename = unicode(QFileDialog.getSaveFileName(self, self.tr('Save Model'), ModelerUtils.modelsFolder(), self.tr('Processing models (*.model)'))) if filename: if not filename.endswith('.model'): filename += '.model' self.alg.descriptionFile = filename if filename: text = self.alg.toJson() try: fout = codecs.open(filename, 'w', encoding='utf-8') except: if saveAs: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n %s') % unicode(sys.exc_info()[1])) else: QMessageBox.warning(self, self.tr("Can't save model"), self.tr("This model can't be saved in its " "original location (probably you do not " "have permission to do it). Please, use " "the 'Save as...' option.")) return fout.write(text) fout.close() self.update = True QMessageBox.information(self, self.tr('Model saved'), self.tr('Model was correctly saved.')) self.hasChanged = False