Esempio n. 1
0
File: menus.py Progetto: ndavid/QGIS
def _executeAlgorithm(alg):
    ok, message = alg.canExecute()
    if not ok:
        dlg = MessageDialog()
        dlg.setTitle(Processing.tr('Missing dependency'))
        dlg.setMessage(
            Processing.tr('<h3>Missing dependency. This algorithm cannot '
                          'be run :-( </h3>\n{0}').format(message))
        dlg.exec_()
        return

    if (alg.countVisibleParameters()) > 0:
        dlg = alg.createCustomParametersWidget(None)
        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:
        feedback = MessageBarProgress()
        context = dataobjects.createContext(feedback)
        parameters = {}
        ret, results = execute(alg, parameters, context, feedback)
        handleAlgorithmResults(alg, context, feedback)
        feedback.close()
Esempio n. 2
0
    def executeAlgorithm(self):
        alg = self.algorithmTree.selectedAlgorithm()
        if alg is not None:
            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            if alg.countVisibleParameters() > 0:
                dlg = alg.createCustomParametersWidget(self)

                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:
                feedback = MessageBarProgress()
                context = dataobjects.createContext(feedback)
                parameters = {}
                ret, results = execute(alg, parameters, context, feedback)
                handleAlgorithmResults(alg, context, feedback)
                feedback.close()
Esempio n. 3
0
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{0}').format(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:
        feedback = MessageBarProgress()
        execute(alg, feedback)
        handleAlgorithmResults(alg, feedback)
        feedback.close()
Esempio n. 4
0
    def executeAlgorithm(self):
        item = self.algorithmTree.currentItem()
        if isinstance(item, TreeAlgorithmItem):
            alg = QgsApplication.processingRegistry().createAlgorithmById(item.alg.id())
            if not alg:
                return

            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            if alg.countVisibleParameters() > 0:
                dlg = alg.createCustomParametersWidget(self)

                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)
                # have to manually delete the dialog - otherwise it's owned by the
                # iface mainWindow and never deleted
                dlg.deleteLater()
            else:
                feedback = MessageBarProgress()
                context = dataobjects.createContext(feedback)
                parameters = {}
                ret, results = execute(alg, parameters, context, feedback)
                handleAlgorithmResults(alg, context, feedback)
                feedback.close()
        if isinstance(item, TreeActionItem):
            action = item.action
            action.setData(self)
            action.execute()
Esempio n. 5
0
    def executeAlgorithm(self):
        alg = self.algorithmTree.selectedAlgorithm().create() if self.algorithmTree.selectedAlgorithm() is not None else None
        if alg is not None:
            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            if self.in_place_mode and not [d for d in alg.parameterDefinitions() if d.name() not in ('INPUT', 'OUTPUT')]:
                parameters = {}
                feedback = MessageBarProgress(algname=alg.displayName())
                ok, results = execute_in_place(alg, parameters, feedback=feedback)
                if ok:
                    iface.messageBar().pushSuccess('', self.tr('{} complete').format(alg.displayName()))
                feedback.close()
                # MessageBarProgress handles errors
                return

            if alg.countVisibleParameters() > 0:
                dlg = alg.createCustomParametersWidget(self)

                if not dlg:
                    dlg = AlgorithmDialog(alg, self.in_place_mode, iface.mainWindow())
                dlg.setAttribute(Qt.WA_DeleteOnClose)
                canvas = iface.mapCanvas()
                prevMapTool = canvas.mapTool()
                dlg.show()
                dlg.exec_()
                if canvas.mapTool() != prevMapTool:
                    try:
                        canvas.mapTool().reset()
                    except:
                        pass
                    canvas.setMapTool(prevMapTool)
            else:
                feedback = MessageBarProgress(algname=alg.displayName())
                context = dataobjects.createContext(feedback)
                parameters = {}
                ret, results = execute(alg, parameters, context, feedback)
                handleAlgorithmResults(alg, context, feedback)
                feedback.close()
Esempio n. 6
0
def _executeAlgorithm(alg_id):
    alg = QgsApplication.processingRegistry().createAlgorithmById(alg_id)
    if alg is None:
        dlg = MessageDialog()
        dlg.setTitle(Processing.tr('Missing Algorithm'))
        dlg.setMessage(
            Processing.
            tr('The algorithm "{}" is no longer available. (Perhaps a plugin was uninstalled?)'
               ).format(alg_id))
        dlg.exec_()
        return

    ok, message = alg.canExecute()
    if not ok:
        dlg = MessageDialog()
        dlg.setTitle(Processing.tr('Missing Dependency'))
        dlg.setMessage(
            Processing.tr('<h3>Missing dependency. This algorithm cannot '
                          'be run :-( </h3>\n{0}').format(message))
        dlg.exec_()
        return

    if (alg.countVisibleParameters()) > 0:
        dlg = alg.createCustomParametersWidget(parent=iface.mainWindow())
        if not dlg:
            dlg = AlgorithmDialog(alg, parent=iface.mainWindow())
        canvas = iface.mapCanvas()
        prevMapTool = canvas.mapTool()
        dlg.show()
        dlg.exec_()
        if canvas.mapTool() != prevMapTool:
            try:
                canvas.mapTool().reset()
            except:
                pass
            canvas.setMapTool(prevMapTool)
    else:
        feedback = MessageBarProgress()
        context = dataobjects.createContext(feedback)
        parameters = {}
        ret, results = execute(alg, parameters, context, feedback)
        handleAlgorithmResults(alg, context, feedback)
        feedback.close()
Esempio n. 7
0
 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:
             feedback = MessageBarProgress()
             runalg(alg, feedback)
             handleAlgorithmResults(alg, feedback)
             feedback.close()
     if isinstance(item, TreeActionItem):
         action = item.action
         action.setData(self)
         action.execute()
Esempio n. 8
0
    def executeAlgorithm(self):
        alg = self.algorithmTree.selectedAlgorithm()
        if alg is not None:
            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            if self.in_place_mode and not [
                    d for d in alg.parameterDefinitions()
                    if d.name() not in ('INPUT', 'OUTPUT')
            ]:
                parameters = {}
                execute_in_place(alg, parameters)
                return

            if alg.countVisibleParameters() > 0:
                dlg = alg.createCustomParametersWidget(self)

                if not dlg:
                    dlg = AlgorithmDialog(alg, self.in_place_mode)
                canvas = iface.mapCanvas()
                prevMapTool = canvas.mapTool()
                dlg.show()
                dlg.exec_()
                if canvas.mapTool() != prevMapTool:
                    try:
                        canvas.mapTool().reset()
                    except:
                        pass
                    canvas.setMapTool(prevMapTool)
            else:
                feedback = MessageBarProgress()
                context = dataobjects.createContext(feedback)
                parameters = {}
                ret, results = execute(alg, parameters, context, feedback)
                handleAlgorithmResults(alg, context, feedback)
                feedback.close()
Esempio n. 9
0
 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()
Esempio n. 10
0
def _executeAlgorithm(alg_id):
    alg = QgsApplication.processingRegistry().createAlgorithmById(alg_id)
    if alg is None:
        dlg = MessageDialog()
        dlg.setTitle(Processing.tr('Missing Algorithm'))
        dlg.setMessage(
            Processing.tr('The algorithm "{}" is no longer available. (Perhaps a plugin was uninstalled?)').format(alg_id))
        dlg.exec_()
        return

    ok, message = alg.canExecute()
    if not ok:
        dlg = MessageDialog()
        dlg.setTitle(Processing.tr('Missing Dependency'))
        dlg.setMessage(
            Processing.tr('<h3>Missing dependency. This algorithm cannot '
                          'be run :-( </h3>\n{0}').format(message))
        dlg.exec_()
        return

    if (alg.countVisibleParameters()) > 0:
        dlg = alg.createCustomParametersWidget(parent=iface.mainWindow())
        if not dlg:
            dlg = AlgorithmDialog(alg, parent=iface.mainWindow())
        canvas = iface.mapCanvas()
        prevMapTool = canvas.mapTool()
        dlg.show()
        dlg.exec_()
        if canvas.mapTool() != prevMapTool:
            try:
                canvas.mapTool().reset()
            except:
                pass
            canvas.setMapTool(prevMapTool)
    else:
        feedback = MessageBarProgress()
        context = dataobjects.createContext(feedback)
        parameters = {}
        ret, results = execute(alg, parameters, context, feedback)
        handleAlgorithmResults(alg, context, feedback)
        feedback.close()
Esempio n. 11
0
    def executeAlgorithm(self):
        item = self.algorithmTree.currentItem()
        if isinstance(item, TreeAlgorithmItem):
            alg = QgsApplication.processingRegistry().createAlgorithmById(
                item.alg.id())
            if not alg:
                return

            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            if alg.countVisibleParameters() > 0:
                dlg = alg.createCustomParametersWidget(self)

                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:
                feedback = MessageBarProgress()
                context = dataobjects.createContext(feedback)
                parameters = {}
                ret, results = execute(alg, parameters, context, feedback)
                handleAlgorithmResults(alg, context, feedback)
                feedback.close()
Esempio n. 12
0
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{0}').format(message))
        dlg.exec_()
        return

    # hack - remove when getCopy is removed
    provider = alg.provider()
    alg = alg.getCopy()
    #hack pt 2
    alg.setProvider(provider)

    context = dataobjects.createContext()
    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:
        feedback = MessageBarProgress()
        execute(alg, context, feedback)
        handleAlgorithmResults(alg, context, feedback)
        feedback.close()
Esempio n. 13
0
    def triggerResult(self, result):
        config = {'IN_PLACE': True}
        alg = QgsApplication.processingRegistry().createAlgorithmById(result.userData, config)
        if alg:
            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Missing dependency'))
                dlg.setMessage(message)
                dlg.exec_()
                return

            in_place_input_parameter_name = 'INPUT'
            if hasattr(alg, 'inputParameterName'):
                in_place_input_parameter_name = alg.inputParameterName()

            if [d for d in alg.parameterDefinitions() if
                    d.name() not in (in_place_input_parameter_name, 'OUTPUT')]:
                dlg = alg.createCustomParametersWidget(parent=iface.mainWindow())
                if not dlg:
                    dlg = AlgorithmDialog(alg, True, parent=iface.mainWindow())
                canvas = iface.mapCanvas()
                prevMapTool = canvas.mapTool()
                dlg.show()
                dlg.exec_()
                if canvas.mapTool() != prevMapTool:
                    try:
                        canvas.mapTool().reset()
                    except:
                        pass
                    canvas.setMapTool(prevMapTool)
            else:
                feedback = MessageBarProgress(algname=alg.displayName())
                parameters = {}
                execute_in_place(alg, parameters, feedback=feedback)
                feedback.close()
Esempio n. 14
0
    def runAlgorithm(algOrName, onFinish, *args, **kwargs):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = QgsApplication.processingRegistry().algorithmById(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
        # hack - remove when getCopy is removed
        provider = alg.provider()
        alg = alg.getCopy()
        #hack pt2
        alg.setProvider(provider)

        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"))
                QgsMessageLog.logMessage(Processing.tr('Error in {0}. Wrong parameter value {1} for parameter {2}.').format(
                    alg.name(), value, name
                ), Processing.tr("Processing"),
                    QgsMessageLog.CRITICAL
                )
                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"))
                        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.algorithmHelp(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

        context = None
        if kwargs is not None and 'context' in list(kwargs.keys()):
            context = kwargs["context"]
        else:
            context = dataobjects.createContext()

        msg = alg._checkParameterValuesBeforeExecuting(context)
        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(context):
            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

        feedback = None
        if kwargs is not None and "feedback" in list(kwargs.keys()):
            feedback = kwargs["feedback"]
        elif iface is not None:
            feedback = MessageBarProgress(alg.displayName())

        ret = execute(alg, context, feedback)
        if ret:
            if onFinish is not None:
                onFinish(alg, context, feedback)
        else:
            QgsMessageLog.logMessage(Processing.tr("There were errors executing the algorithm."),
                                     Processing.tr("Processing"))

        if overrideCursor:
            QApplication.restoreOverrideCursor()
        if isinstance(feedback, MessageBarProgress):
            feedback.close()
        return alg
Esempio n. 15
0
    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
        if len(args) != alg.getVisibleParametersCount() \
                    + alg.getVisibleOutputsCount():
            print 'Error: Wrong number of parameters'
            processing.alghelp(algOrName)
            return

        alg = alg.getCopy()
        if isinstance(args, dict):
            # Set params by name
            for (name, value) in args.items():
                if alg.getParameterFromName(name).setValue(value):
                    continue
                if alg.getOutputFromName(name).setValue(value):
                    continue
                print 'Error: Wrong parameter value %s for parameter %s.' \
                    % (value, name)
                return
        else:
            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 = MessageBarProgress()
        ret = UnthreadedAlgorithmExecutor.runalg(alg, progress)
        if onFinish is not None and ret:
            onFinish(alg, progress)
        QApplication.restoreOverrideCursor()
        progress.close()
        return alg
Esempio n. 16
0
    def runAlgorithm(algOrName, parameters, onFinish=None, feedback=None, context=None):
        if isinstance(algOrName, QgsProcessingAlgorithm):
            alg = algOrName
        else:
            alg = QgsApplication.processingRegistry().createAlgorithmById(algOrName)

        if feedback is None:
            feedback = MessageBarProgress(alg.displayName() if alg else Processing.tr('Processing'))

        if alg is None:
            # fix_print_with_import
            print('Error: Algorithm not found\n')
            msg = Processing.tr('Error: Algorithm {0} not found\n').format(algOrName)
            feedback.reportError(msg)
            raise QgsProcessingException(msg)

        # check for any mandatory parameters which were not specified
        for param in alg.parameterDefinitions():
            if param.name() not in parameters:
                if not param.flags() & QgsProcessingParameterDefinition.FlagOptional:
                    # fix_print_with_import
                    msg = Processing.tr('Error: Missing parameter value for parameter {0}.').format(param.name())
                    print('Error: Missing parameter value for parameter %s.' % param.name())
                    feedback.reportError(msg)
                    raise QgsProcessingException(msg)

        if context is None:
            context = dataobjects.createContext(feedback)

        ok, msg = alg.checkParameterValues(parameters, context)
        if not ok:
            # fix_print_with_import
            print('Unable to execute algorithm\n' + str(msg))
            msg = Processing.tr('Unable to execute algorithm\n{0}').format(msg)
            feedback.reportError(msg)
            raise QgsProcessingException(msg)

        if not alg.validateInputCrs(parameters, context):
            print('Warning: Not all input layers use the same CRS.\n' +
                  'This can cause unexpected results.')
            feedback.pushInfo(
                Processing.tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'))

        ret, results = execute(alg, parameters, context, feedback)
        if ret:
            feedback.pushInfo(
                Processing.tr('Results: {}').format(results))

            if onFinish is not None:
                onFinish(alg, context, feedback)
            else:
                # auto convert layer references in results to map layers
                for out in alg.outputDefinitions():
                    if isinstance(out, (QgsProcessingOutputVectorLayer, QgsProcessingOutputRasterLayer, QgsProcessingOutputMapLayer)):
                        result = results[out.name()]
                        if not isinstance(result, QgsMapLayer):
                            layer = context.takeResultLayer(result) # transfer layer ownership out of context
                            if layer:
                                results[out.name()] = layer # replace layer string ref with actual layer (+ownership)
        else:
            msg = Processing.tr("There were errors executing the algorithm.")
            feedback.reportError(msg)
            raise QgsProcessingException(msg)

        if isinstance(feedback, MessageBarProgress):
            feedback.close()
        return results
Esempio n. 17
0
    def executeAlgorithm(self):
        config = {}
        if self.in_place_mode:
            config['IN_PLACE'] = True
        alg = self.algorithmTree.selectedAlgorithm().create(
            config) if self.algorithmTree.selectedAlgorithm(
            ) is not None else None
        if alg is not None:
            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            if self.in_place_mode and not [
                    d for d in alg.parameterDefinitions()
                    if d.name() not in ('INPUT', 'OUTPUT')
            ]:
                parameters = {}
                feedback = MessageBarProgress(algname=alg.displayName())
                ok, results = execute_in_place(alg,
                                               parameters,
                                               feedback=feedback)
                if ok:
                    iface.messageBar().pushSuccess(
                        '',
                        self.tr(
                            '{algname} completed. %n feature(s) processed.',
                            n=results['__count']).format(
                                algname=alg.displayName()))
                feedback.close()
                # MessageBarProgress handles errors
                return

            if alg.countVisibleParameters() > 0:
                dlg = alg.createCustomParametersWidget(self)

                if not dlg:
                    dlg = AlgorithmDialog(alg, self.in_place_mode,
                                          iface.mainWindow())
                canvas = iface.mapCanvas()
                prevMapTool = canvas.mapTool()
                dlg.show()
                dlg.exec_()
                if canvas.mapTool() != prevMapTool:
                    try:
                        canvas.mapTool().reset()
                    except:
                        pass
                    canvas.setMapTool(prevMapTool)
            else:
                feedback = MessageBarProgress(algname=alg.displayName())
                context = dataobjects.createContext(feedback)
                parameters = {}
                ret, results = execute(alg, parameters, context, feedback)
                handleAlgorithmResults(alg, context, feedback)
                feedback.close()
Esempio n. 18
0
    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
Esempio n. 19
0
    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
Esempio n. 20
0
    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
        if len(args) != alg.getVisibleParametersCount() \
                    + alg.getVisibleOutputsCount():
            print 'Error: Wrong number of parameters'
            processing.alghelp(algOrName)
            return

        alg = alg.getCopy()
        if isinstance(args, dict):
            # Set params by name
            for (name, value) in args.items():
                if alg.getParameterFromName(name).setValue(value):
                    continue
                if alg.getOutputFromName(name).setValue(value):
                    continue
                print 'Error: Wrong parameter value %s for parameter %s.' \
                    % (value, name)
                return
        else:
            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 = MessageBarProgress()
        ret = UnthreadedAlgorithmExecutor.runalg(alg, progress)
        if onFinish is not None and ret:
            onFinish(alg, progress)
        QApplication.restoreOverrideCursor()
        progress.close()
        return alg
Esempio n. 21
0
    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
Esempio n. 22
0
    def runAlgorithm(algOrName, parameters, onFinish=None, feedback=None, context=None):
        if isinstance(algOrName, QgsProcessingAlgorithm):
            alg = algOrName
        else:
            alg = QgsApplication.processingRegistry().createAlgorithmById(algOrName)

        if feedback is None:
            feedback = MessageBarProgress(alg.displayName() if alg else Processing.tr('Processing'))

        if alg is None:
            # fix_print_with_import
            print('Error: Algorithm not found\n')
            msg = Processing.tr('Error: Algorithm {0} not found\n').format(algOrName)
            feedback.reportError(msg)
            raise QgsProcessingException(msg)

        # check for any mandatory parameters which were not specified
        for param in alg.parameterDefinitions():
            if param.name() not in parameters:
                if not param.flags() & QgsProcessingParameterDefinition.FlagOptional:
                    # fix_print_with_import
                    msg = Processing.tr('Error: Missing parameter value for parameter {0}.').format(param.name())
                    print('Error: Missing parameter value for parameter %s.' % param.name())
                    feedback.reportError(msg)
                    raise QgsProcessingException(msg)

        if context is None:
            context = dataobjects.createContext(feedback)

        ok, msg = alg.checkParameterValues(parameters, context)
        if not ok:
            # fix_print_with_import
            print('Unable to execute algorithm\n' + str(msg))
            msg = Processing.tr('Unable to execute algorithm\n{0}').format(msg)
            feedback.reportError(msg)
            raise QgsProcessingException(msg)

        if not alg.validateInputCrs(parameters, context):
            print('Warning: Not all input layers use the same CRS.\n' +
                  'This can cause unexpected results.')
            feedback.pushInfo(
                Processing.tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'))

        ret, results = execute(alg, parameters, context, feedback)
        if ret:
            feedback.pushInfo(
                Processing.tr('Results: {}').format(results))

            if onFinish is not None:
                onFinish(alg, context, feedback)
            else:
                # auto convert layer references in results to map layers
                for out in alg.outputDefinitions():
                    if isinstance(out, (QgsProcessingOutputVectorLayer, QgsProcessingOutputRasterLayer, QgsProcessingOutputMapLayer)):
                        result = results[out.name()]
                        if not isinstance(result, QgsMapLayer):
                            layer = context.takeResultLayer(result) # transfer layer ownership out of context
                            if layer:
                                results[out.name()] = layer # replace layer string ref with actual layer (+ownership)
        else:
            msg = Processing.tr("There were errors executing the algorithm.")
            feedback.reportError(msg)
            raise QgsProcessingException(msg)

        if isinstance(feedback, MessageBarProgress):
            feedback.close()
        return results
Esempio n. 23
0
    def runAlgorithm(algOrName, onFinish, *args, **kwargs):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = QgsApplication.processingRegistry().algorithmById(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

        parameters = {}
        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.
            for (name, value) in list(args[0].items()):
                param = alg.parameterDefinition(name)
                if param:
                    parameters[param.name()] = 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"))
                QgsMessageLog.logMessage(
                    Processing.
                    tr('Error in {0}. Wrong parameter value {1} for parameter {2}.'
                       ).format(alg.name(), value, name),
                    Processing.tr("Processing"), QgsMessageLog.CRITICAL)
                return
            # check for any manadatory parameters which were not specified
            for param in alg.parameterDefinitions():
                if param.name() not in parameters:
                    if not param.flags(
                    ) & QgsProcessingParameterDefinition.FlagOptional:
                        # 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"))
                        return
        else:
            if len(args) != alg.countVisibleParameters():
                # fix_print_with_import
                print('Error: Wrong number of parameters')
                QgsMessageLog.logMessage(
                    Processing.tr('Error: Wrong number of parameters'),
                    Processing.tr("Processing"))
                processing.algorithmHelp(algOrName)
                return
            i = 0
            for param in alg.parameterDefinitions():
                if not param.flags(
                ) & QgsProcessingParameterDefinition.FlagHidden:
                    if not True:  # TODO 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
                    else:
                        parameters[param.name()] = args[i]
                    i = i + 1

            for output in alg.outputs:
                if not output.flags(
                ) & QgsProcessingParameterDefinition.FlagHidden:
                    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

        context = None
        if kwargs is not None and 'context' in list(kwargs.keys()):
            context = kwargs["context"]
        else:
            context = dataobjects.createContext()

        ok, msg = alg.checkParameterValues(parameters, context)
        if not ok:
            # 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.validateInputCrs(parameters, context):
            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

        feedback = None
        if kwargs is not None and "feedback" in list(kwargs.keys()):
            feedback = kwargs["feedback"]
        elif iface is not None:
            feedback = MessageBarProgress(alg.displayName())

        ret, results = execute(alg, parameters, context, feedback)
        if ret:
            if onFinish is not None:
                onFinish(alg, context, feedback)
        else:
            QgsMessageLog.logMessage(
                Processing.tr("There were errors executing the algorithm."),
                Processing.tr("Processing"))

        if overrideCursor:
            QApplication.restoreOverrideCursor()
        if isinstance(feedback, MessageBarProgress):
            feedback.close()
        return results
Esempio n. 24
0
    def executeAlgorithm(self, alg_id, parent, in_place=False, as_batch=False):
        """Executes a project model with GUI interaction if needed.

        :param alg_id: algorithm id
        :type alg_id: string
        :param parent: parent widget
        :type parent: QWidget
        :param in_place: in place flag, defaults to False
        :type in_place: bool, optional
        :param as_batch: execute as batch flag, defaults to False
        :type as_batch: bool, optional
        """

        config = {}
        if in_place:
            config['IN_PLACE'] = True

        alg = QgsApplication.instance().processingRegistry().createAlgorithmById(alg_id, config)

        if alg is not None:

            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            if as_batch:
                dlg = BatchAlgorithmDialog(alg, iface.mainWindow())
                dlg.show()
                dlg.exec_()
            else:
                in_place_input_parameter_name = 'INPUT'
                if hasattr(alg, 'inputParameterName'):
                    in_place_input_parameter_name = alg.inputParameterName()

                if in_place and not [d for d in alg.parameterDefinitions() if d.name() not in (in_place_input_parameter_name, 'OUTPUT')]:
                    parameters = {}
                    feedback = MessageBarProgress(algname=alg.displayName())
                    ok, results = execute_in_place(alg, parameters, feedback=feedback)
                    if ok:
                        iface.messageBar().pushSuccess('', self.tr('{algname} completed. %n feature(s) processed.', n=results['__count']).format(algname=alg.displayName()))
                    feedback.close()
                    # MessageBarProgress handles errors
                    return

                if alg.countVisibleParameters() > 0:
                    dlg = alg.createCustomParametersWidget(parent)

                    if not dlg:
                        dlg = AlgorithmDialog(alg, in_place, iface.mainWindow())
                    canvas = iface.mapCanvas()
                    prevMapTool = canvas.mapTool()
                    dlg.show()
                    dlg.exec_()
                    if canvas.mapTool() != prevMapTool:
                        try:
                            canvas.mapTool().reset()
                        except Exception:
                            pass
                        canvas.setMapTool(prevMapTool)
                else:
                    feedback = MessageBarProgress(algname=alg.displayName())
                    context = dataobjects.createContext(feedback)
                    parameters = {}
                    ret, results = execute(alg, parameters, context, feedback)
                    handleAlgorithmResults(alg, context, feedback)
                    feedback.close()
Esempio n. 25
0
    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 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: ' +
                              unicode(args[i]))
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Wrong parameter value: ') +
                            unicode(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: ' + unicode(args[i]))
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Wrong output value: ') +
                            unicode(args[i]), Processing.tr("Processing"))
                        return
                    i = i + 1

        msg = alg._checkParameterValuesBeforeExecuting()
        if msg:
            # fix_print_with_import
            print('Unable to execute algorithm\n' + unicode(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 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
Esempio n. 26
0
    def runAlgorithm(algOrName, onFinish, *args, **kwargs):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = QgsApplication.processingRegistry().algorithmById(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

        parameters = {}
        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.
            for (name, value) in list(args[0].items()):
                param = alg.parameterDefinition(name)
                if param:
                    parameters[param.name()] = 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"))
                QgsMessageLog.logMessage(Processing.tr('Error in {0}. Wrong parameter value {1} for parameter {2}.').format(
                    alg.name(), value, name
                ), Processing.tr("Processing"),
                    QgsMessageLog.CRITICAL
                )
                return
            # check for any manadatory parameters which were not specified
            for param in alg.parameterDefinitions():
                if param.name() not in parameters:
                    if not param.flags() & QgsProcessingParameterDefinition.FlagOptional:
                        # 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"))
                        return
        else:
            if len(args) != alg.countVisibleParameters():
                # fix_print_with_import
                print('Error: Wrong number of parameters')
                QgsMessageLog.logMessage(Processing.tr('Error: Wrong number of parameters'),
                                         Processing.tr("Processing"))
                processing.algorithmHelp(algOrName)
                return
            i = 0
            for param in alg.parameterDefinitions():
                if not param.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    if not True: # TODO 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
                    else:
                        parameters[param.name()] = args[i]
                    i = i + 1

            for output in alg.outputs:
                if not output.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    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

        context = None
        if kwargs is not None and 'context' in list(kwargs.keys()):
            context = kwargs["context"]
        else:
            context = dataobjects.createContext()

        ok, msg = alg.checkParameterValues(parameters, context)
        if not ok:
            # 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.validateInputCrs(parameters, context):
            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

        feedback = None
        if kwargs is not None and "feedback" in list(kwargs.keys()):
            feedback = kwargs["feedback"]
        elif iface is not None:
            feedback = MessageBarProgress(alg.displayName())

        ret, results = execute(alg, parameters, context, feedback)
        if ret:
            if onFinish is not None:
                onFinish(alg, context, feedback)
        else:
            QgsMessageLog.logMessage(Processing.tr("There were errors executing the algorithm."),
                                     Processing.tr("Processing"))

        if overrideCursor:
            QApplication.restoreOverrideCursor()
        if isinstance(feedback, MessageBarProgress):
            feedback.close()
        return results