def preprocess(self, layer): ''' Preprocesses the layer with the corresponding preprocess hook and returns the path to the resulting layer. If no preprocessing is performed, it returns the input layer itself ''' if not processingOk: return layer if layer.type() == layer.RasterLayer: try: hookFile = str(QtCore.QSettings().value("/GeoServer/Settings/GeoServer/PreuploadRasterHook", "")) alg = self.getAlgorithmFromHookFile(hookFile) if (len(alg.parameters) == 1 and isinstance(alg.parameters[0], ParameterRaster) and len(alg.outputs) == 1 and isinstance(alg.outputs[0], OutputRaster)): alg.parameters[0].setValue(layer) if runalg(alg, SilentProgress()): return load(alg.outputs[0].value) return layer except: return layer elif layer.type() == layer.VectorLayer: try: hookFile = str(QtCore.QSettings().value("/GeoServer/Settings/GeoServer/PreuploadVectorHook", "")) alg = self.getAlgorithmFromHookFile(hookFile) if (len(alg.parameters) == 1 and isinstance(alg.parameters[0], ParameterVector) and len(alg.outputs) == 1 and isinstance(alg.outputs[0], OutputVector)): alg.parameters[0].setValue(layer) if runalg(alg, SilentProgress()): return load(alg.outputs[0].value) return layer except: return layer
def _executeAlgorithm(alg): message = alg.checkBeforeOpeningParametersDialog() if message: dlg = MessageDialog() dlg.setTitle(Processing.tr('Missing dependency')) dlg.setMessage( Processing.tr('<h3>Missing dependency. This algorithm cannot ' 'be run :-( </h3>\n%s') % message) dlg.exec_() return alg = alg.getCopy() if (alg.getVisibleParametersCount() + alg.getVisibleOutputsCount()) > 0: dlg = alg.getCustomParametersDialog() if not dlg: dlg = AlgorithmDialog(alg) canvas = iface.mapCanvas() prevMapTool = canvas.mapTool() dlg.show() dlg.exec_() if canvas.mapTool() != prevMapTool: try: canvas.mapTool().reset() except: pass canvas.setMapTool(prevMapTool) else: progress = MessageBarProgress() runalg(alg, progress) handleAlgorithmResults(alg, progress) progress.close()
def accept(self): keepOpen = ProcessingConfig.getSetting( ProcessingConfig.KEEP_DIALOG_OPEN) try: if self.setParamValues(): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, self.alg.getAsCommand()) ret = runalg(self.alg, self) QApplication.restoreOverrideCursor() if ret: handleAlgorithmResults(self.alg, self, not keepOpen) self.executed = True QDialog.reject(self) else: QMessageBox.critical(self, self.tr('Unable to execute algorithm'), self.tr('Wrong or missing parameter ' 'values')) return except GeoAlgorithmExecutionException, e: QApplication.restoreOverrideCursor() QMessageBox.critical(self, "Error",e.msg) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, e.msg) self.executed = False QDialog.reject(self)
def accept(self): self.canceled = False self.algs = [] self.load = [] for row in range(self.table.rowCount()): alg = self.alg.getCopy() col = 0 for param in alg.parameters: if param.hidden: continue widget = self.table.cellWidget(row, col) if not self.setParameterValueFromWidget(param, widget, alg): self.progressLabel.setText( self.tr('<b>Missing parameter value: %s (row %d)</b>') % (param.description, row + 1)) self.algs = None return col += 1 for out in alg.outputs: if out.hidden: continue widget = self.table.cellWidget(row, col) text = widget.getValue() if text.strip() != '': out.value = text col += 1 else: self.progressLabel.setText( self.tr('<b>Wrong or missing parameter value: %s (row %d)</b>') % (out.description, row + 1)) self.algs = None return self.algs.append(alg) if self.alg.getVisibleOutputsCount(): widget = self.table.cellWidget(row, col) self.load.append(widget.currentIndex() == 0) else: self.load.append(False) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.table.setEnabled(False) self.tabWidget.setCurrentIndex(1) self.progress.setMaximum(len(self.algs)) # make sure the log tab is visible before executing the algorithm try: self.repaint() except: pass for (i, alg) in enumerate(self.algs): self.setBaseText(self.tr('Processing algorithm %d/%d...') %(i + 1, len(self.algs))) self.setInfo(self.tr('<b>Algorithm %s starting...</b>' % alg.name)) if runalg(alg, self) and not self.canceled: if self.load[i]: handleAlgorithmResults(alg, self, False) self.setInfo(self.tr('Algorithm %s correctly executed...') % alg.name) else: QApplication.restoreOverrideCursor() return self.finishAll()
def executeAlgorithm(self): item = self.algorithmTree.currentItem() if isinstance(item, TreeAlgorithmItem): alg = Processing.getAlgorithm(item.alg.commandLineName()) message = alg.checkBeforeOpeningParametersDialog() if message: dlg = MessageDialog() dlg.setTitle(self.tr('Error executing algorithm')) dlg.setMessage( self.tr('<h3>This algorithm cannot ' 'be run :-( </h3>\n%s') % message) dlg.exec_() return alg = alg.getCopy() if (alg.getVisibleParametersCount() + alg.getVisibleOutputsCount()) > 0: dlg = alg.getCustomParametersDialog() if not dlg: dlg = AlgorithmDialog(alg) canvas = iface.mapCanvas() prevMapTool = canvas.mapTool() dlg.show() dlg.exec_() if canvas.mapTool() != prevMapTool: try: canvas.mapTool().reset() except: pass canvas.setMapTool(prevMapTool) if dlg.executed: showRecent = ProcessingConfig.getSetting( ProcessingConfig.SHOW_RECENT_ALGORITHMS) if showRecent: self.addRecentAlgorithms(True) else: progress = MessageBarProgress() runalg(alg, progress) handleAlgorithmResults(alg, progress) progress.close() if isinstance(item, TreeActionItem): action = item.action action.setData(self) action.execute()
def accept(self): keepOpen = ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN) try: if self.setParamValues(): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, self.alg.getAsCommand()) self.executed = runalg(self.alg, self.feedback) if self.executed: handleAlgorithmResults(self.alg, self.feedback, not keepOpen) if not keepOpen: QDialog.reject(self) finally: QApplication.restoreOverrideCursor()
def accept(self): keepOpen = ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN) try: if self.setParamValues(): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, self.alg.getAsCommand()) self.executed = runalg(self.alg, self) if self.executed: handleAlgorithmResults(self.alg, self, not keepOpen) if not keepOpen: QDialog.reject(self) else: QMessageBox.critical(self, self.tr('Unable to execute algorithm'), self.tr('Wrong or missing parameter ' 'values')) finally: QApplication.restoreOverrideCursor()
def accept(self): self.algs = [] self.load = [] self.canceled = False for row in range(self.mainWidget.tblParameters.rowCount()): alg = self.alg.getCopy() col = 0 for param in alg.parameters: if param.hidden: continue wrapper = self.mainWidget.wrappers[row][col] if not self.mainWidget.setParamValue(param, wrapper, alg): self.bar.pushMessage("", self.tr('Wrong or missing parameter value: %s (row %d)') % (param.description, row + 1), level=QgsMessageBar.WARNING, duration=5) self.algs = None return col += 1 for out in alg.outputs: if out.hidden: continue widget = self.mainWidget.tblParameters.cellWidget(row, col) text = widget.getValue() if text.strip() != '': out.value = text col += 1 else: self.bar.pushMessage("", self.tr('Wrong or missing output value: %s (row %d)') % (out.description, row + 1), level=QgsMessageBar.WARNING, duration=5) self.algs = None return self.algs.append(alg) if self.alg.getVisibleOutputsCount(): widget = self.mainWidget.tblParameters.cellWidget(row, col) self.load.append(widget.currentIndex() == 0) else: self.load.append(False) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.mainWidget.setEnabled(False) self.progressBar.setMaximum(len(self.algs)) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass for count, alg in enumerate(self.algs): self.setText(self.tr('\nProcessing algorithm %d/%d...') % (count + 1, len(self.algs))) self.setInfo(self.tr('<b>Algorithm %s starting...</b>' % alg.name)) if runalg(alg, self) and not self.canceled: if self.load[count]: handleAlgorithmResults(alg, self, False) self.setInfo(self.tr('Algorithm %s correctly executed...') % alg.name) else: QApplication.restoreOverrideCursor() return self.finish()
def runAlgorithm(algOrName, onFinish, *args): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: print 'Error: Algorithm not found\n' return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in args[0].items(): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue print 'Error: Wrong parameter value %s for parameter %s.' \ % (value, name) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, Processing.tr('Error in %s. Wrong parameter value %s for parameter %s.') \ % (alg.name, value, name)) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setValue(None): print ('Error: Missing parameter value for parameter %s.' % (param.name)) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, Processing.tr('Error in %s. Missing parameter value for parameter %s.') \ % (alg.name, param.name)) return else: if len(args) != alg.getVisibleParametersCount() \ + alg.getVisibleOutputsCount(): print 'Error: Wrong number of parameters' processing.alghelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): print 'Error: Wrong parameter value: ' \ + unicode(args[i]) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): print 'Error: Wrong output value: ' + unicode(args[i]) return i = i + 1 msg = alg.checkParameterValuesBeforeExecuting() if msg: print 'Unable to execute algorithm\n' + msg return if not alg.checkInputCRS(): print 'Warning: Not all input layers use the same CRS.\n' \ + 'This can cause unexpected results.' if iface is not None: # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) progress = None if iface is not None : progress = MessageBarProgress() ret = runalg(alg, progress) if onFinish is not None and ret: onFinish(alg, progress) if iface is not None: QApplication.restoreOverrideCursor() progress.close() return alg
def runAlgorithm(algOrName, onFinish, *args, **kwargs): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: # fix_print_with_import print("Error: Algorithm not found\n") QgsMessageLog.logMessage( Processing.tr("Error: Algorithm {0} not found\n").format(algOrName), Processing.tr("Processing") ) return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in list(args[0].items()): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue # fix_print_with_import print("Error: Wrong parameter value %s for parameter %s." % (value, name)) QgsMessageLog.logMessage( Processing.tr("Error: Wrong parameter value {0} for parameter {1}.").format(value, name), Processing.tr("Processing"), ) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing.tr("Error in %s. Wrong parameter value %s for parameter %s.") % (alg.name, value, name), ) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setDefaultValue(): # fix_print_with_import print("Error: Missing parameter value for parameter %s." % param.name) QgsMessageLog.logMessage( Processing.tr("Error: Missing parameter value for parameter {0}.").format(param.name), Processing.tr("Processing"), ) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing.tr("Error in %s. Missing parameter value for parameter %s.") % (alg.name, param.name), ) return else: if len(args) != alg.getVisibleParametersCount() + alg.getVisibleOutputsCount(): # fix_print_with_import print("Error: Wrong number of parameters") QgsMessageLog.logMessage( Processing.tr("Error: Wrong number of parameters"), Processing.tr("Processing") ) processing.alghelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): # fix_print_with_import print("Error: Wrong parameter value: " + str(args[i])) QgsMessageLog.logMessage( Processing.tr("Error: Wrong parameter value: ") + str(args[i]), Processing.tr("Processing") ) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): # fix_print_with_import print("Error: Wrong output value: " + str(args[i])) QgsMessageLog.logMessage( Processing.tr("Error: Wrong output value: ") + str(args[i]), Processing.tr("Processing") ) return i = i + 1 msg = alg._checkParameterValuesBeforeExecuting() if msg: # fix_print_with_import print("Unable to execute algorithm\n" + str(msg)) QgsMessageLog.logMessage( Processing.tr("Unable to execute algorithm\n{0}").format(msg), Processing.tr("Processing") ) return if not alg.checkInputCRS(): print("Warning: Not all input layers use the same CRS.\n" + "This can cause unexpected results.") QgsMessageLog.logMessage( Processing.tr("Warning: Not all input layers use the same CRS.\nThis can cause unexpected results."), Processing.tr("Processing"), ) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. overrideCursor = False if iface is not None: cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True progress = None if kwargs is not None and "progress" in list(kwargs.keys()): progress = kwargs["progress"] elif iface is not None: progress = MessageBarProgress(alg.name) ret = runalg(alg, progress) if ret: if onFinish is not None: onFinish(alg, progress) else: QgsMessageLog.logMessage( Processing.tr("There were errors executing the algorithm."), Processing.tr("Processing") ) if overrideCursor: QApplication.restoreOverrideCursor() if isinstance(progress, MessageBarProgress): progress.close() return alg
def accept(self): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) checkCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_CRS) try: self.setParamValues() if checkCRS and not self.alg.checkInputCRS(): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr( "Layers do not all use the same CRS. This can " "cause unexpected results.\nDo you want to " "continue?" ), QMessageBox.Yes | QMessageBox.No, QMessageBox.No, ) if reply == QMessageBox.No: return msg = self.alg._checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning(self, self.tr("Unable to execute algorithm"), msg) return self.btnRun.setEnabled(False) self.btnClose.setEnabled(False) buttons = self.mainWidget.iterateButtons self.iterateParam = None for i in range(len(buttons.values())): button = buttons.values()[i] if button.isChecked(): self.iterateParam = buttons.keys()[i] break self.progressBar.setMaximum(0) self.lblProgress.setText(self.tr("Processing algorithm...")) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setInfo(self.tr("<b>Algorithm %s starting...</b>") % self.alg.name) if self.iterateParam: if runalgIterating(self.alg, self.iterateParam, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() else: command = self.alg.getAsCommand() if command: ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, command) if runalg(self.alg, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox.accepted.connect(lambda: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) self.lblProgress.setText(self.tr("<b>Missing parameter value: %s</b>") % e.parameter.description) return except: QMessageBox.critical( self, self.tr("Unable to execute algorithm"), self.tr("Wrong or missing parameter values") )
def accept(self): checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: self.setParamValues() if checkCRS and not self.alg.checkInputCRS(): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Layers do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return msg = self.alg.checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.runButton.setEnabled(False) self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False) buttons = self.paramTable.iterateButtons self.iterateParam = None for i in range(len(buttons.values())): button = buttons.values()[i] if button.isChecked(): self.iterateParam = buttons.keys()[i] break self.tabWidget.setCurrentIndex(1) # Log tab self.progress.setMaximum(0) self.progressLabel.setText(self.tr('Processing algorithm...')) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setInfo( self.tr('<b>Algorithm %s starting...</b>') % self.alg.name) # make sure the log tab is visible before executing the algorithm try: self.repaint() except: pass if self.iterateParam: if runalgIterating(self.alg, self.iterateParam, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() else: command = self.alg.getAsCommand() if command: ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, command) if runalg(self.alg, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() except AlgorithmExecutionDialog.InvalidParameterValue, ex: try: self.buttonBox.accepted.connect( lambda: ex.widget.setPalette(QPalette())) palette = ex.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) ex.widget.setPalette(palette) self.progressLabel.setText( self.tr('<b>Missing parameter value: %s</b>' % ex.parameter.description)) return except: QMessageBox.critical( self, self.tr('Unable to execute algorithm'), self.tr('Wrong or missing parameter values'))
def accept(self): self.canceled = False self.algs = [] self.load = [] for row in range(self.table.rowCount()): alg = self.alg.getCopy() col = 0 for param in alg.parameters: if param.hidden: continue widget = self.table.cellWidget(row, col) if not self.setParameterValueFromWidget(param, widget, alg): self.progressLabel.setText('<b>Missing parameter value: ' + param.description + ' (row ' + str(row + 1) + ')</b>') self.algs = None return col += 1 for out in alg.outputs: if out.hidden: continue widget = self.table.cellWidget(row, col) text = widget.getValue() if text.strip() != '': out.value = text col += 1 else: self.progressLabel.setText( '<b>Wrong or missing parameter value: ' + out.description + ' (row ' + str(row + 1) + ')</b>') self.algs = None return self.algs.append(alg) if self.alg.getVisibleOutputsCount(): widget = self.table.cellWidget(row, col) self.load.append(widget.currentIndex() == 0) else: self.load.append(False) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.table.setEnabled(False) self.tabWidget.setCurrentIndex(1) self.progress.setMaximum(len(self.algs)) # make sure the log tab is visible before executing the algorithm try: self.repaint() except: pass for (i, alg) in enumerate(self.algs): self.setBaseText('Processing algorithm ' + str(i + 1) + '/' + str(len(self.algs)) + '...') self.setInfo('<b>Algorithm %s starting...</b>' % alg.name) if runalg(alg, self) and not self.canceled: if self.load[i]: handleAlgorithmResults(alg, self, False) self.setInfo('Algorithm %s correctly executed...' % alg.name) else: QApplication.restoreOverrideCursor() return self.finishAll()
def accept(self): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) checkCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_CRS) try: self.setParamValues() if checkCRS and not self.alg.checkInputCRS(): reply = QMessageBox.question(self, self.tr("Unmatching CRS's"), self.tr('Layers do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return checkExtentCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS) if checkExtentCRS and self.checkExtentCRS(): reply = QMessageBox.question(self, self.tr("Extent CRS"), self.tr('Extent parameters must use the same CRS as the input layers.\n' 'Your input layers do not have the same extent as the project, ' 'so the extent might be in a wrong CRS if you have selected it from the canvas.\n' 'Do you want to continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return msg = self.alg._checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning( self, self.tr('Unable to execute algorithm'), msg) return self.btnRun.setEnabled(False) self.btnClose.setEnabled(False) buttons = self.mainWidget.iterateButtons self.iterateParam = None for i in range(len(list(buttons.values()))): button = list(buttons.values())[i] if button.isChecked(): self.iterateParam = list(buttons.keys())[i] break self.progressBar.setMaximum(0) self.lblProgress.setText(self.tr('Processing algorithm...')) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setInfo( self.tr('<b>Algorithm %s starting...</b>') % self.alg.name) if self.iterateParam: if runalgIterating(self.alg, self.iterateParam, self.feedback): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() else: command = self.alg.getAsCommand() if command: ProcessingLog.addToLog( ProcessingLog.LOG_ALGORITHM, command) if runalg(self.alg, self.feedback): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox.accepted.connect(lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.bar.clearWidgets() self.bar.pushMessage("", "Wrong or missing parameter value: %s" % e.parameter.description, level=QgsMessageBar.WARNING, duration=5)
def runAlgorithm(algOrName, onFinish, *args, **kwargs): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: # fix_print_with_import print('Error: Algorithm not found\n') QgsMessageLog.logMessage( Processing.tr('Error: Algorithm {0} not found\n').format( algOrName), Processing.tr("Processing")) return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in list(args[0].items()): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue # fix_print_with_import print('Error: Wrong parameter value %s for parameter %s.' % (value, name)) QgsMessageLog.logMessage( Processing.tr( 'Error: Wrong parameter value {0} for parameter {1}.'). format(value, name), Processing.tr("Processing")) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing. tr('Error in %s. Wrong parameter value %s for parameter %s.' ) % (alg.name, value, name)) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setDefaultValue(): # fix_print_with_import print( 'Error: Missing parameter value for parameter %s.' % param.name) QgsMessageLog.logMessage( Processing. tr('Error: Missing parameter value for parameter {0}.' ).format(param.name), Processing.tr("Processing")) ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, Processing. tr('Error in %s. Missing parameter value for parameter %s.' ) % (alg.name, param.name)) return else: if len(args) != alg.getVisibleParametersCount( ) + alg.getVisibleOutputsCount(): # fix_print_with_import print('Error: Wrong number of parameters') QgsMessageLog.logMessage( Processing.tr('Error: Wrong number of parameters'), Processing.tr("Processing")) processing.alghelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): # fix_print_with_import print('Error: Wrong parameter value: ' + str(args[i])) QgsMessageLog.logMessage( Processing.tr('Error: Wrong parameter value: ') + str(args[i]), Processing.tr("Processing")) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): # fix_print_with_import print('Error: Wrong output value: ' + str(args[i])) QgsMessageLog.logMessage( Processing.tr('Error: Wrong output value: ') + str(args[i]), Processing.tr("Processing")) return i = i + 1 msg = alg._checkParameterValuesBeforeExecuting() if msg: # fix_print_with_import print('Unable to execute algorithm\n' + str(msg)) QgsMessageLog.logMessage( Processing.tr('Unable to execute algorithm\n{0}').format(msg), Processing.tr("Processing")) return if not alg.checkInputCRS(): print('Warning: Not all input layers use the same CRS.\n' + 'This can cause unexpected results.') QgsMessageLog.logMessage( Processing. tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.' ), Processing.tr("Processing")) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. overrideCursor = False if iface is not None: cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) overrideCursor = True progress = None if kwargs is not None and "progress" in list(kwargs.keys()): progress = kwargs["progress"] elif iface is not None: progress = MessageBarProgress(alg.name) ret = runalg(alg, progress) if ret: if onFinish is not None: onFinish(alg, progress) else: QgsMessageLog.logMessage( Processing.tr("There were errors executing the algorithm."), Processing.tr("Processing")) if overrideCursor: QApplication.restoreOverrideCursor() if isinstance(progress, MessageBarProgress): progress.close() return alg
def accept(self): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: self.setParamValues() if checkCRS and not self.alg.checkInputCRS(): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Layers do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return checkExtentCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS) if checkExtentCRS and self.checkExtentCRS(): reply = QMessageBox.question( self, self.tr("Extent CRS"), self. tr('Extent parameters must use the same CRS as the input layers.\n' 'Your input layers do not have the same extent as the project, ' 'so the extent might be in a wrong CRS if you have selected it from the canvas.\n' 'Do you want to continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return msg = self.alg._checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.btnRun.setEnabled(False) self.btnClose.setEnabled(False) buttons = self.mainWidget.iterateButtons self.iterateParam = None for i in range(len(buttons.values())): button = buttons.values()[i] if button.isChecked(): self.iterateParam = buttons.keys()[i] break self.progressBar.setMaximum(0) self.lblProgress.setText(self.tr('Processing algorithm...')) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setInfo( self.tr('<b>Algorithm %s starting...</b>') % self.alg.name) if self.iterateParam: if runalgIterating(self.alg, self.iterateParam, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() else: command = self.alg.getAsCommand() if command: ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, command) if runalg(self.alg, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox.accepted.connect( lambda: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) self.lblProgress.setText( self.tr('<b>Missing parameter value: %s</b>') % e.parameter.description) return except: QMessageBox.critical( self, self.tr('Unable to execute algorithm'), self.tr('Wrong or missing parameter values'))
def accept(self): checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: self.setParamValues() if checkCRS and not self.alg.checkInputCRS(): reply = QMessageBox.question(self, "Unmatching CRS's", 'Layers do not all use the same CRS.\n' + 'This can cause unexpected results.\n' + 'Do you want to continue?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return msg = self.alg.checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning(self, 'Unable to execute algorithm', msg) return self.runButton.setEnabled(False) self.buttonBox.button( QDialogButtonBox.Close).setEnabled(False) buttons = self.paramTable.iterateButtons self.iterateParam = None for i in range(len(buttons.values())): button = buttons.values()[i] if button.isChecked(): self.iterateParam = buttons.keys()[i] break self.tabWidget.setCurrentIndex(1) # Log tab self.progress.setMaximum(0) self.progressLabel.setText('Processing algorithm...') QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setInfo('<b>Algorithm %s starting...</b>' % self.alg.name) # make sure the log tab is visible before executing the algorithm try: self.repaint() except: pass if self.iterateParam: if runalgIterating(self.alg, self.iterateParam, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() else: command = self.alg.getAsCommand() if command: ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, command) if runalg(self.alg, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() except AlgorithmExecutionDialog.InvalidParameterValue, ex: try: self.buttonBox.accepted.connect(lambda : ex.widget.setPalette(QPalette())) palette = ex.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) ex.widget.setPalette(palette) self.progressLabel.setText('<b>Missing parameter value: ' + ex.parameter.description + '</b>') return except: QMessageBox.critical(self, 'Unable to execute algorithm', 'Wrong or missing parameter values')
def runAlgorithm(algOrName, onFinish, *args): if isinstance(algOrName, GeoAlgorithm): alg = algOrName else: alg = Processing.getAlgorithm(algOrName) if alg is None: print 'Error: Algorithm not found\n' return alg = alg.getCopy() if len(args) == 1 and isinstance(args[0], dict): # Set params by name and try to run the alg even if not all parameter values are provided, # by using the default values instead. setParams = [] for (name, value) in args[0].items(): param = alg.getParameterFromName(name) if param and param.setValue(value): setParams.append(name) continue output = alg.getOutputFromName(name) if output and output.setValue(value): continue print 'Error: Wrong parameter value %s for parameter %s.' \ % (value, name) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, "Error in %s. Wrong parameter value %s for parameter %s." \ % (alg.name, value, name)) return # fill any missing parameters with default values if allowed for param in alg.parameters: if param.name not in setParams: if not param.setValue(None): print( "Error: Missing parameter value for parameter %s." % (param.name)) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, "Error in %s. Missing parameter value for parameter %s." \ % (alg.name, param.name)) return else: if len(args) != alg.getVisibleParametersCount() \ + alg.getVisibleOutputsCount(): print 'Error: Wrong number of parameters' processing.alghelp(algOrName) return i = 0 for param in alg.parameters: if not param.hidden: if not param.setValue(args[i]): print 'Error: Wrong parameter value: ' \ + unicode(args[i]) return i = i + 1 for output in alg.outputs: if not output.hidden: if not output.setValue(args[i]): print 'Error: Wrong output value: ' + unicode(args[i]) return i = i + 1 msg = alg.checkParameterValuesBeforeExecuting() if msg: print 'Unable to execute algorithm\n' + msg return if not alg.checkInputCRS(): print 'Warning: Not all input layers use the same CRS.\n' \ + 'This can cause unexpected results.' ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, alg.getAsCommand()) # Don't set the wait cursor twice, because then when you # restore it, it will still be a wait cursor. cursor = QApplication.overrideCursor() if cursor is None or cursor == 0: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) elif cursor.shape() != Qt.WaitCursor: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) progress = None if iface is not None: progress = MessageBarProgress() ret = runalg(alg, progress) if onFinish is not None and ret: onFinish(alg, progress) QApplication.restoreOverrideCursor() progress.close() return alg