Esempio n. 1
0
    def defineCharacteristicsFromFile(self):
        lines = open(self.descriptionFile)
        line = lines.readline().strip('\n').strip()
        self.name = line
        self.i18n_name = QCoreApplication.translate("TAUDEMAlgorithm", line)
        line = lines.readline().strip('\n').strip()
        self.cmdName = line
        line = lines.readline().strip('\n').strip()
        self.group = line
        self.i18n_group = QCoreApplication.translate("TAUDEMAlgorithm", line)

        line = lines.readline().strip('\n').strip()
        while line != '':
            try:
                line = line.strip('\n').strip()
                if line.startswith('Parameter'):
                    param = getParameterFromString(line)
                    self.addParameter(param)
                else:
                    self.addOutput(getOutputFromString(line))
                line = lines.readline().strip('\n').strip()
            except Exception as e:
                ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                       self.tr('Could not load TauDEM algorithm: %s\n%s' % (self.descriptionFile, line)))
                raise e
        lines.close()
Esempio n. 2
0
def removeDir(path):
    result = ""
    if not QFile(path).exists():
        result = QCoreApplication.translate("QgsPluginInstaller", "Nothing to remove! Plugin directory doesn't exist:") + "\n" + path
    elif QFile(path).remove():  # if it is only link, just remove it without resolving.
        pass
    else:
        fltr = QDir.Dirs | QDir.Files | QDir.Hidden
        iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
        while iterator.hasNext():
            item = iterator.next()
            if QFile(item).remove():
                pass
        fltr = QDir.Dirs | QDir.Hidden
        iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
        while iterator.hasNext():
            item = iterator.next()
            if QDir().rmpath(item):
                pass
    if QFile(path).exists():
        result = QCoreApplication.translate("QgsPluginInstaller", "Failed to remove the directory:") + "\n" + path + "\n" + QCoreApplication.translate("QgsPluginInstaller", "Check permissions or remove it manually")
    # restore plugin directory if removed by QDir().rmpath()
    pluginDir = qgis.utils.home_plugin_path
    if not QDir(pluginDir).exists():
        QDir().mkpath(pluginDir)
    return result
Esempio n. 3
0
def removeDir(path):
    result = ""
    if not QFile(path).exists():
        result = QCoreApplication.translate(
            "QgsPluginInstaller",
            "Nothing to remove! Plugin directory doesn't exist:") + "\n" + path
    elif QFile(path).remove(
    ):  # if it is only link, just remove it without resolving.
        pass
    else:
        fltr = QDir.Dirs | QDir.Files | QDir.Hidden
        iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
        while iterator.hasNext():
            item = iterator.next()
            if QFile(item).remove():
                pass
        fltr = QDir.Dirs | QDir.Hidden
        iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories)
        while iterator.hasNext():
            item = iterator.next()
            if QDir().rmpath(item):
                pass
    if QFile(path).exists():
        result = QCoreApplication.translate(
            "QgsPluginInstaller", "Failed to remove the directory:"
        ) + "\n" + path + "\n" + QCoreApplication.translate(
            "QgsPluginInstaller", "Check permissions or remove it manually")
    # restore plugin directory if removed by QDir().rmpath()
    pluginDir = qgis.utils.home_plugin_path
    if not QDir(pluginDir).exists():
        QDir().mkpath(pluginDir)
    return result
Esempio n. 4
0
def startServerPlugin(packageName):
    """ initialize the plugin """
    global server_plugins, server_active_plugins, serverIface

    if packageName in server_active_plugins:
        return False
    if packageName not in sys.modules:
        return False

    package = sys.modules[packageName]

    errMsg = QCoreApplication.translate(
        "Python", "Couldn't load server plugin %s") % packageName

    # create an instance of the plugin
    try:
        server_plugins[packageName] = package.serverClassFactory(serverIface)
    except:
        _unloadPluginModules(packageName)
        msg = QCoreApplication.translate(
            "Python",
            "%s due to an error when calling its serverClassFactory() method"
        ) % errMsg
        showException(sys.exc_info()[0],
                      sys.exc_info()[1],
                      sys.exc_info()[2], msg)
        return False

    # add to active plugins
    server_active_plugins.append(packageName)
    return True
Esempio n. 5
0
    def defineCharacteristicsFromFile(self):
        lines = open(self.descriptionFile)
        line = lines.readline().strip('\n').strip()
        self.name = line
        self.i18n_name = QCoreApplication.translate("TAUDEMAlgorithm", line)
        line = lines.readline().strip('\n').strip()
        self.cmdName = line
        line = lines.readline().strip('\n').strip()
        self.group = line
        self.i18n_group = QCoreApplication.translate("TAUDEMAlgorithm", line)

        line = lines.readline().strip('\n').strip()
        while line != '':
            try:
                line = line.strip('\n').strip()
                if line.startswith('Parameter'):
                    param = getParameterFromString(line)
                    self.addParameter(param)
                else:
                    self.addOutput(getOutputFromString(line))
                line = lines.readline().strip('\n').strip()
            except Exception as e:
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_ERROR,
                    self.tr('Could not load TauDEM algorithm: %s\n%s' %
                            (self.descriptionFile, line)))
                raise e
        lines.close()
Esempio n. 6
0
def startServerPlugin(packageName):
    """ initialize the plugin """
    global server_plugins, server_active_plugins, serverIface

    if packageName in server_active_plugins:
        return False
    if packageName not in sys.modules:
        return False

    package = sys.modules[packageName]

    errMsg = QCoreApplication.translate("Python", "Couldn't load server plugin %s") % packageName

    # create an instance of the plugin
    try:
        server_plugins[packageName] = package.serverClassFactory(serverIface)
    except:
        _unloadPluginModules(packageName)
        msg = (
            QCoreApplication.translate("Python", "%s due to an error when calling its serverClassFactory() method")
            % errMsg
        )
        showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg)
        return False

    # add to active plugins
    server_active_plugins.append(packageName)
    return True
Esempio n. 7
0
    def initGui(self):
        """startup"""

        # run
        run_icon = QIcon('%s/%s' % (self.context.ppath,
                                    'images/MetaSearch.png'))
        self.action_run = QAction(run_icon, 'MetaSearch',
                                  self.iface.mainWindow())
        self.action_run.setWhatsThis(QCoreApplication.translate('MetaSearch',
                                                                'MetaSearch plugin'))
        self.action_run.setStatusTip(QCoreApplication.translate('MetaSearch',
                                                                'Search Metadata Catalogues'))

        self.action_run.triggered.connect(self.run)

        self.iface.addWebToolBarIcon(self.action_run)
        self.iface.addPluginToWebMenu(self.web_menu, self.action_run)

        # help
        help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png'))
        self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow())
        self.action_help.setWhatsThis(QCoreApplication.translate('MetaSearch',
                                                                 'MetaSearch plugin help'))
        self.action_help.setStatusTip(QCoreApplication.translate('MetaSearch',
                                                                 'Get Help on MetaSearch'))
        self.action_help.triggered.connect(self.help)

        self.iface.addPluginToWebMenu(self.web_menu, self.action_help)

        # prefab the dialog but not open it yet
        self.dialog = MetaSearchDialog(self.iface)
Esempio n. 8
0
    def switchToolMode(self):
        self.setCommandViewerEnabled(not self.batchCheck.isChecked())
        self.progressBar.setVisible(self.batchCheck.isChecked())
        self.formatLabel.setVisible(self.batchCheck.isChecked())
        self.formatCombo.setVisible(self.batchCheck.isChecked())

        self.inSelector.setType(self.inSelector.FILE if self.batchCheck.isChecked() else self.inSelector.FILE_LAYER)
        self.outSelector.clear()

        if self.batchCheck.isChecked():
            self.inFileLabel = self.label.text()
            self.outFileLabel = self.label_1.text()
            self.label.setText(QCoreApplication.translate("GdalTools", "&Input directory"))
            self.label_1.setText(QCoreApplication.translate("GdalTools", "&Output directory"))

            self.inSelector.selectClicked.disconnect(self.fillInputFile)
            self.outSelector.selectClicked.disconnect(self.fillOutputFile)

            self.inSelector.selectClicked.connect(self. fillInputDir)
            self.outSelector.selectClicked.connect(self.fillOutputDir)
        else:
            self.label.setText(self.inFileLabel)
            self.label_1.setText(self.outFileLabel)

            self.inSelector.selectClicked.disconnect(self.fillInputDir)
            self.outSelector.selectClicked.disconnect(self.fillOutputDir)

            self.inSelector.selectClicked.connect(self.fillInputFile)
            self.outSelector.selectClicked.connect(self.fillOutputFile)
Esempio n. 9
0
    def switchToolMode(self):
        self.setCommandViewerEnabled(not self.batchCheck.isChecked())
        self.progressBar.setVisible(self.batchCheck.isChecked())

        self.inSelector.setType(self.inSelector.FILE if self.batchCheck.
                                isChecked() else self.inSelector.FILE_LAYER)
        self.outSelector.clear()

        if self.batchCheck.isChecked():
            self.inFileLabel = self.label.text()
            self.outFileLabel = self.label_2.text()
            self.label.setText(
                QCoreApplication.translate("GdalTools", "&Input directory"))
            self.label_2.setText(
                QCoreApplication.translate("GdalTools", "&Output directory"))

            self.inSelector.selectClicked.disconnect(self.fillInputFile)
            self.outSelector.selectClicked.disconnect(self.fillOutputFileEdit)

            self.inSelector.selectClicked.connect(self.fillInputDir)
            self.outSelector.selectClicked.connect(self.fillOutputDir)
        else:
            self.label.setText(self.inFileLabel)
            self.label_2.setText(self.outFileLabel)

            self.inSelector.selectClicked.disconnect(self.fillInputDir)
            self.outSelector.selectClicked.disconnect(self.fillOutputDir)

            self.inSelector.selectClicked.connect(self.fillInputFile)
            self.outSelector.selectClicked.connect(self.fillOutputFileEdit)
Esempio n. 10
0
    def initGui(self):
        """startup"""

        # run
        run_icon = QIcon("%s/%s" % (self.context.ppath, "images/MetaSearch.png"))
        self.action_run = QAction(run_icon, "MetaSearch", self.iface.mainWindow())
        self.action_run.setWhatsThis(QCoreApplication.translate("MetaSearch", "MetaSearch plugin"))
        self.action_run.setStatusTip(QCoreApplication.translate("MetaSearch", "Search Metadata Catalogues"))

        self.action_run.triggered.connect(self.run)

        self.iface.addWebToolBarIcon(self.action_run)
        self.iface.addPluginToWebMenu(self.web_menu, self.action_run)

        # help
        help_icon = QgsApplication.getThemeIcon("/mActionHelpContents.svg")
        self.action_help = QAction(help_icon, "Help", self.iface.mainWindow())
        self.action_help.setWhatsThis(QCoreApplication.translate("MetaSearch", "MetaSearch plugin help"))
        self.action_help.setStatusTip(QCoreApplication.translate("MetaSearch", "Get Help on MetaSearch"))
        self.action_help.triggered.connect(self.help)

        self.iface.addPluginToWebMenu(self.web_menu, self.action_help)

        # prefab the dialog but not open it yet
        self.dialog = MetaSearchDialog(self.iface)
Esempio n. 11
0
    def saveAsScriptFile(self, index=None):
        tabWidget = self.tabEditorWidget.currentWidget()
        if not index:
            index = self.tabEditorWidget.currentIndex()
        if not tabWidget.path:
            fileName = self.tabEditorWidget.tabText(index) + '.py'
            folder = self.settings.value("pythonConsole/lastDirPath", QDir.home())
            pathFileName = os.path.join(folder, fileName)
            fileNone = True
        else:
            pathFileName = tabWidget.path
            fileNone = False
        saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As")
        filename = QFileDialog.getSaveFileName(self,
                                               saveAsFileTr,
                                               pathFileName, "Script file (*.py)")
        if filename:
            try:
                tabWidget.save(filename)
            except (IOError, OSError) as error:
                msgText = QCoreApplication.translate('PythonConsole',
                                                     'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path,
                                                                                                                  error.strerror)
                self.callWidgetMessageBarEditor(msgText, 2, False)
                if fileNone:
                    tabWidget.path = None
                else:
                    tabWidget.path = pathFileName
                return

            if not fileNone:
                self.updateTabListScript(pathFileName, action='remove')
Esempio n. 12
0
    def initGui(self):
        """startup"""

        # run
        run_icon = QIcon('%s/%s' %
                         (self.context.ppath, 'images/MetaSearch.png'))
        self.action_run = QAction(run_icon, 'MetaSearch',
                                  self.iface.mainWindow())
        self.action_run.setWhatsThis(
            QCoreApplication.translate('MetaSearch', 'MetaSearch plugin'))
        self.action_run.setStatusTip(
            QCoreApplication.translate('MetaSearch',
                                       'Search Metadata Catalogues'))

        self.action_run.triggered.connect(self.run)

        self.iface.addWebToolBarIcon(self.action_run)
        self.iface.addPluginToWebMenu(self.web_menu, self.action_run)

        # help
        help_icon = QIcon('%s/%s' % (self.context.ppath, 'images/help.png'))
        self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow())
        self.action_help.setWhatsThis(
            QCoreApplication.translate('MetaSearch', 'MetaSearch plugin help'))
        self.action_help.setStatusTip(
            QCoreApplication.translate('MetaSearch', 'Get Help on MetaSearch'))
        self.action_help.triggered.connect(self.help)

        self.iface.addPluginToWebMenu(self.web_menu, self.action_help)

        # prefab the dialog but not open it yet
        self.dialog = MetaSearchDialog(self.iface)
Esempio n. 13
0
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setWindowTitle(QCoreApplication.translate("SettingsDialogPythonConsole", "Settings Python Console"))
        self.parent = parent
        self.setupUi(self)

        self.listPath = []
        self.lineEdit.setReadOnly(True)

        self.restoreSettings()
        self.initialCheck()

        self.addAPIpath.setIcon(QIcon(":/images/themes/default/symbologyAdd.svg"))
        self.addAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Add API path"))
        self.removeAPIpath.setIcon(QIcon(":/images/themes/default/symbologyRemove.svg"))
        self.removeAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Remove API path"))

        self.preloadAPI.stateChanged.connect(self.initialCheck)
        self.addAPIpath.clicked.connect(self.loadAPIFile)
        self.removeAPIpath.clicked.connect(self.removeAPI)
        self.compileAPIs.clicked.connect(self._prepareAPI)

        self.resetFontColor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png"))
        self.resetFontColor.setIconSize(QSize(18, 18))
        self.resetFontColorEditor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png"))
        self.resetFontColorEditor.setIconSize(QSize(18, 18))
        self.resetFontColor.clicked.connect(self._resetFontColor)
        self.resetFontColorEditor.clicked.connect(self._resetFontColorEditor)
Esempio n. 14
0
    def saveAsScriptFile(self, index=None):
        tabWidget = self.tabEditorWidget.currentWidget()
        if not index:
            index = self.tabEditorWidget.currentIndex()
        if not tabWidget.path:
            fileName = self.tabEditorWidget.tabText(index) + '.py'
            folder = self.settings.value("pythonConsole/lastDirPath",
                                         QDir.home())
            pathFileName = os.path.join(folder, fileName)
            fileNone = True
        else:
            pathFileName = tabWidget.path
            fileNone = False
        saveAsFileTr = QCoreApplication.translate("PythonConsole",
                                                  "Save File As")
        filename = QFileDialog.getSaveFileName(self, saveAsFileTr,
                                               pathFileName,
                                               "Script file (*.py)")
        if filename:
            try:
                tabWidget.save(filename)
            except (IOError, OSError) as error:
                msgText = QCoreApplication.translate(
                    'PythonConsole',
                    'The file <b>{0}</b> could not be saved. Error: {1}'
                ).format(tabWidget.path, error.strerror)
                self.callWidgetMessageBarEditor(msgText, 2, False)
                if fileNone:
                    tabWidget.path = None
                else:
                    tabWidget.path = pathFileName
                return

            if not fileNone:
                self.updateTabListScript(pathFileName, action='remove')
Esempio n. 15
0
def open_stack_dialog(type, value, tb, msg, pop_error=True):
    if pop_error:
        iface.messageBar().popWidget()

    if msg is None:
        msg = QCoreApplication.translate(
            'Python', 'An error has occurred while executing Python code:')

    # TODO Move this to a template HTML file
    txt = u'''<font color="red"><b>{msg}</b></font>
<br>
<h3>{main_error}</h3>
<pre>
{error}
</pre>
<br>
<b>{version_label}</b> {num}
<br>
<b>{qgis_label}</b> {qversion} {qgisrelease}, {devversion}
<br>
<h4>{pypath_label}</h4>
<ul>
{pypath}
</ul>'''

    error = ''
    lst = traceback.format_exception(type, value, tb)
    for s in lst:
        error += s.decode('utf-8', 'replace') if hasattr(s, 'decode') else s
    error = error.replace('\n', '<br>')

    main_error = lst[-1].decode('utf-8', 'replace') if hasattr(
        lst[-1], 'decode') else lst[-1]

    version_label = QCoreApplication.translate('Python', 'Python version:')
    qgis_label = QCoreApplication.translate('Python', 'QGIS version:')
    pypath_label = QCoreApplication.translate('Python', 'Python Path:')
    txt = txt.format(msg=msg,
                     main_error=main_error,
                     error=error,
                     version_label=version_label,
                     num=sys.version,
                     qgis_label=qgis_label,
                     qversion=QGis.QGIS_VERSION,
                     qgisrelease=QGis.QGIS_RELEASE_NAME,
                     devversion=QGis.QGIS_DEV_VERSION,
                     pypath_label=pypath_label,
                     pypath=u"".join(u"<li>{}</li>".format(path)
                                     for path in sys.path))

    txt = txt.replace('  ', '&nbsp; ')  # preserve whitespaces for nicer output

    dlg = QgsMessageOutput.createMessageOutput()
    dlg.setTitle(msg)
    dlg.setMessage(txt, QgsMessageOutput.MessageHtml)
    dlg.showMessage()
Esempio n. 16
0
def open_stack_dialog(type, value, tb, msg, pop_error=True):
    if pop_error:
        iface.messageBar().popWidget()

    if msg is None:
        msg = QCoreApplication.translate("Python", "An error has occurred while executing Python code:")

    # TODO Move this to a template HTML file
    txt = u"""<font color="red"><b>{msg}</b></font>
<br>
<h3>{main_error}</h3>
<pre>
{error}
</pre>
<br>
<b>{version_label}</b> {num}
<br>
<b>{qgis_label}</b> {qversion} {qgisrelease}, {devversion}
<br>
<h4>{pypath_label}</h4>
<ul>
{pypath}
</ul>"""

    error = ""
    lst = traceback.format_exception(type, value, tb)
    for s in lst:
        error += s.decode("utf-8", "replace") if hasattr(s, "decode") else s
    error = error.replace("\n", "<br>")

    main_error = lst[-1].decode("utf-8", "replace") if hasattr(lst[-1], "decode") else lst[-1]

    version_label = QCoreApplication.translate("Python", "Python version:")
    qgis_label = QCoreApplication.translate("Python", "QGIS version:")
    pypath_label = QCoreApplication.translate("Python", "Python Path:")
    txt = txt.format(
        msg=msg,
        main_error=main_error,
        error=error,
        version_label=version_label,
        num=sys.version,
        qgis_label=qgis_label,
        qversion=QGis.QGIS_VERSION,
        qgisrelease=QGis.QGIS_RELEASE_NAME,
        devversion=QGis.QGIS_DEV_VERSION,
        pypath_label=pypath_label,
        pypath=u"".join(u"<li>{}</li>".format(path) for path in sys.path),
    )

    txt = txt.replace("  ", "&nbsp; ")  # preserve whitespaces for nicer output

    dlg = QgsMessageOutput.createMessageOutput()
    dlg.setTitle(msg)
    dlg.setMessage(txt, QgsMessageOutput.MessageHtml)
    dlg.showMessage()
Esempio n. 17
0
def startPlugin(packageName):
    """ initialize the plugin """
    global plugins, active_plugins, iface, plugin_times

    if packageName in active_plugins:
        return False
    if packageName not in sys.modules:
        return False

    package = sys.modules[packageName]

    errMsg = QCoreApplication.translate(
        "Python", "Couldn't load plugin %s") % packageName

    start = time.clock()
    # create an instance of the plugin
    try:
        plugins[packageName] = package.classFactory(iface)
    except:
        _unloadPluginModules(packageName)
        msg = QCoreApplication.translate(
            "Python",
            "%s due to an error when calling its classFactory() method"
        ) % errMsg
        showException(sys.exc_info()[0],
                      sys.exc_info()[1],
                      sys.exc_info()[2],
                      msg,
                      messagebar=True)
        return False

    # initGui
    try:
        plugins[packageName].initGui()
    except:
        del plugins[packageName]
        _unloadPluginModules(packageName)
        msg = QCoreApplication.translate(
            "Python",
            "%s due to an error when calling its initGui() method") % errMsg
        showException(sys.exc_info()[0],
                      sys.exc_info()[1],
                      sys.exc_info()[2],
                      msg,
                      messagebar=True)
        return False

    # add to active plugins
    active_plugins.append(packageName)
    end = time.clock()
    plugin_times[packageName] = "{0:02f}s".format(end - start)

    return True
Esempio n. 18
0
    def defineCharacteristicsFromFile(self):
        content = open(self.descriptionFile).read()
        dom_model = ET.fromstring(content)

        self.appkey = dom_model.find('key').text
        self.cliName = dom_model.find('exec').text
        self.name = dom_model.find('longname').text
        self.i18n_name = QCoreApplication.translate("OTBAlgorithm", self.name)
        self.group = dom_model.find('group').text
        self.i18n_group = QCoreApplication.translate("OTBAlgorithm",
                                                     self.group)

        rebu = None
        the_result = None

        try:
            rebu = self.get_list_from_node(dom_model)
            the_result = map(self.adapt_list_to_string, rebu)
        except Exception as e:
            ProcessingLog.addToLog(
                ProcessingLog.LOG_ERROR,
                self.tr('Could not open OTB algorithm: %s\n%s' %
                        (self.descriptionFile, traceback.format_exc())))
            raise e

        for line in the_result:
            try:
                if line.startswith("Parameter") or line.startswith(
                        "*Parameter"):
                    if line.startswith("*Parameter"):
                        param = getParameterFromString(line[1:])
                        param.isAdvanced = True
                    else:
                        param = getParameterFromString(line)
                    # Hack for initializing the elevation parameters from Processing configuration
                    if param.name == "-elev.dem.path" or param.name == "-elev.dem" or "elev.dem" in param.name:
                        param.default = OTBUtils.otbSRTMPath()
                    elif param.name == "-elev.dem.geoid" or param.name == "-elev.geoid" or "elev.geoid" in param.name:
                        param.default = OTBUtils.otbGeoidPath()
                    self.addParameter(param)
                elif line.startswith("Extent"):
                    self.addParameter(
                        ParameterExtent(self.REGION_OF_INTEREST,
                                        "Region of interest", "0,1,0,1"))
                    self.hasROI = True
                else:
                    self.addOutput(getOutputFromString(line))
            except Exception as e:
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_ERROR,
                    self.tr('Could not open OTB algorithm: %s\n%s' %
                            (self.descriptionFile, line)))
                raise e
Esempio n. 19
0
    def onError(self, error):
        if error == QProcess.FailedToStart:
            msg = QCoreApplication.translate("GdalTools", "The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.")
        elif error == QProcess.Crashed:
            msg = QCoreApplication.translate("GdalTools", "The process crashed some time after starting successfully.")
        else:
            msg = QCoreApplication.translate("GdalTools", "An unknown error occurred.")

        QErrorMessage(self).showMessage(msg)
        QApplication.processEvents()  # give the user chance to see the message

        self.stop()
Esempio n. 20
0
 def runLAStools(commands, progress):
     loglines = []
     commandline = " ".join(commands)
     loglines.append(QCoreApplication.translate("LAStoolsUtils", "LAStools command line"))
     loglines.append(commandline)
     loglines.append(QCoreApplication.translate("LAStoolsUtils", "LAStools console output"))
     proc = subprocess.Popen(commandline, shell=True, stdout=subprocess.PIPE, stdin=open(os.devnull),
                             stderr=subprocess.STDOUT, universal_newlines=False).stdout
     for line in iter(proc.readline, ""):
         loglines.append(line)
         progress.setConsoleInfo(line)
     ProcessingLog.addToLog(ProcessingLog.LOG_INFO, loglines)
Esempio n. 21
0
def showException(type, value, tb, msg, messagebar=False):
    if msg is None:
        msg = QCoreApplication.translate(
            'Python', 'An error has occurred while executing Python code:')

    logmessage = ''
    for s in traceback.format_exception(type, value, tb):
        logmessage += s.decode('utf-8', 'replace') if hasattr(s,
                                                              'decode') else s

    title = QCoreApplication.translate('Python', 'Python error')
    QgsMessageLog.logMessage(logmessage, title)

    try:
        blockingdialog = QApplication.instance().activeModalWidget()
        window = QApplication.instance().activeWindow()
    except:
        blockingdialog = QApplication.activeModalWidget()
        window = QApplication.activeWindow()

    # Still show the normal blocking dialog in this case for now.
    if blockingdialog or not window or not messagebar or not iface:
        open_stack_dialog(type, value, tb, msg)
        return

    bar = iface.messageBar()

    # If it's not the main window see if we can find a message bar to report the error in
    if not window.objectName() == "QgisApp":
        widgets = window.findChildren(QgsMessageBar)
        if widgets:
            # Grab the first message bar for now
            bar = widgets[0]

    item = bar.currentItem()
    if item and item.property("Error") == msg:
        # Return of we already have a message with the same error message
        return

    widget = bar.createMessage(
        title, msg + " " + QCoreApplication.translate(
            "Python", "See message log (Python Error) for more details."))
    widget.setProperty("Error", msg)
    stackbutton = QPushButton(
        QCoreApplication.translate("Python", "Stack trace"),
        pressed=functools.partial(open_stack_dialog, type, value, tb, msg))
    button = QPushButton(QCoreApplication.translate("Python",
                                                    "View message log"),
                         pressed=show_message_log)
    widget.layout().addWidget(stackbutton)
    widget.layout().addWidget(button)
    bar.pushWidget(widget, QgsMessageBar.WARNING)
Esempio n. 22
0
def showException(type, value, tb, msg, messagebar=False):
    if msg is None:
        msg = QCoreApplication.translate("Python", "An error has occurred while executing Python code:")

    logmessage = ""
    for s in traceback.format_exception(type, value, tb):
        logmessage += s.decode("utf-8", "replace") if hasattr(s, "decode") else s

    title = QCoreApplication.translate("Python", "Python error")
    QgsMessageLog.logMessage(logmessage, title)

    try:
        blockingdialog = QApplication.instance().activeModalWidget()
        window = QApplication.instance().activeWindow()
    except:
        blockingdialog = QApplication.activeModalWidget()
        window = QApplication.activeWindow()

    # Still show the normal blocking dialog in this case for now.
    if blockingdialog or not window or not messagebar or not iface:
        open_stack_dialog(type, value, tb, msg)
        return

    bar = iface.messageBar()

    # If it's not the main window see if we can find a message bar to report the error in
    if not window.objectName() == "QgisApp":
        widgets = window.findChildren(QgsMessageBar)
        if widgets:
            # Grab the first message bar for now
            bar = widgets[0]

    item = bar.currentItem()
    if item and item.property("Error") == msg:
        # Return of we already have a message with the same error message
        return

    widget = bar.createMessage(
        title, msg + " " + QCoreApplication.translate("Python", "See message log (Python Error) for more details.")
    )
    widget.setProperty("Error", msg)
    stackbutton = QPushButton(
        QCoreApplication.translate("Python", "Stack trace"),
        pressed=functools.partial(open_stack_dialog, type, value, tb, msg),
    )
    button = QPushButton(QCoreApplication.translate("Python", "View message log"), pressed=show_message_log)
    widget.layout().addWidget(stackbutton)
    widget.layout().addWidget(button)
    bar.pushWidget(widget, QgsMessageBar.WARNING)
Esempio n. 23
0
 def _preparationFinished(self):
     self._clearLexer()
     if os.path.exists(self._pap_file):
         os.remove(self._pap_file)
     self.ui.label.setText(QCoreApplication.translate("PythonConsole", "Saving prepared file..."))
     prepd = self._api.savePrepared(unicode(self._pap_file))
     rslt = self.trUtf8("Error")
     if prepd:
         rslt = QCoreApplication.translate("PythonConsole", "Saved")
     self.ui.label.setText(u'{0} {1}'.format(self.ui.label.text(), rslt))
     self._api = None
     self.ui.progressBar.setVisible(False)
     self.ui.buttonBox.button(QDialogButtonBox.Cancel).setText(
         QCoreApplication.translate("PythonConsole", "Done"))
     self.adjustSize()
Esempio n. 24
0
 def close(self):
     if self.msg:
         dlg = MessageDialog()
         dlg.setTitle(QCoreApplication.translate('MessageBarProgress', 'Problem executing algorithm'))
         dlg.setMessage("<br>".join(self.msg))
         dlg.exec_()
     iface.messageBar().clearWidgets()
Esempio n. 25
0
def executeSaga(progress):
    if isWindows():
        command = ['cmd.exe', '/C ', sagaBatchJobFilename()]
    else:
        os.chmod(sagaBatchJobFilename(), stat.S_IEXEC
                 | stat.S_IREAD | stat.S_IWRITE)
        command = [sagaBatchJobFilename()]
    loglines = []
    loglines.append(QCoreApplication.translate('SagaUtils', 'SAGA execution console output'))
    proc = subprocess.Popen(
        command,
        shell=True,
        stdout=subprocess.PIPE,
        stdin=open(os.devnull),
        stderr=subprocess.STDOUT,
        universal_newlines=True,
    ).stdout
    try:
        for line in iter(proc.readline, ''):
            if '%' in line:
                s = ''.join([x for x in line if x.isdigit()])
                try:
                    progress.setPercentage(int(s))
                except:
                    pass
            else:
                line = line.strip()
                if line != '/' and line != '-' and line != '\\' and line != '|':
                    loglines.append(line)
                    progress.setConsoleInfo(line)
    except:
        pass
    if ProcessingConfig.getSetting(SAGA_LOG_CONSOLE):
        ProcessingLog.addToLog(ProcessingLog.LOG_INFO, loglines)
Esempio n. 26
0
    def requestFetching(self, key):
        """ start fetching the repository given by key """
        self.mRepositories[key]["state"] = 1
        url = QUrl(self.mRepositories[key]["url"] + self.urlParams())
        #v=str(QGis.QGIS_VERSION_INT)
        #url.addQueryItem('qgis', '.'.join([str(int(s)) for s in [v[0], v[1:3]]]) ) # don't include the bugfix version!

        self.mRepositories[key]["QRequest"] = QNetworkRequest(url)
        authcfg = self.mRepositories[key]["authcfg"]
        if authcfg and isinstance(authcfg, basestring):
            if not QgsAuthManager.instance().updateNetworkRequest(
                    self.mRepositories[key]["QRequest"], authcfg.strip()):
                msg = QCoreApplication.translate(
                    "QgsPluginInstaller",
                    "Update of network request with authentication "
                    "credentials FAILED for configuration '{0}'").format(
                        authcfg)
                iface.pluginManagerInterface().pushMessage(
                    msg, QgsMessageBar.WARNING)
                self.mRepositories[key]["QRequest"] = None
                return
        self.mRepositories[key]["QRequest"].setAttribute(
            QNetworkRequest.User, key)
        self.mRepositories[key]["xmlData"] = QgsNetworkAccessManager.instance(
        ).get(self.mRepositories[key]["QRequest"])
        self.mRepositories[key]["xmlData"].setProperty('reposName', key)
        self.mRepositories[key]["xmlData"].downloadProgress.connect(
            self.mRepositories[key]["Relay"].dataReadProgress)
        self.mRepositories[key]["xmlData"].finished.connect(self.xmlDownloaded)
Esempio n. 27
0
def loadPlugin(packageName):
    """ load plugin's package """

    try:
        __import__(packageName)
        return True
    except:
        pass  # continue...

    # snake in the grass, we know it's there
    sys.path_importer_cache.clear()

    # retry
    try:
        __import__(packageName)
        return True
    except:
        msgTemplate = QCoreApplication.translate("Python",
                                                 "Couldn't load plugin '%s'")
        msg = msgTemplate % packageName
        showException(sys.exc_info()[0],
                      sys.exc_info()[1],
                      sys.exc_info()[2],
                      msg,
                      messagebar=True)
        return False
Esempio n. 28
0
def showWarning(message, category, filename, lineno, file=None, line=None):
    stk = ""
    for s in traceback.format_stack()[:-2]:
        stk += s.decode('utf-8', 'replace') if hasattr(s, 'decode') else s
    QgsMessageLog.logMessage(
        "warning:%s\ntraceback:%s" %
        (warnings.formatwarning(message, category, filename, lineno), stk),
        QCoreApplication.translate("Python", "Python warning"))
Esempio n. 29
0
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.parent = parent
        self.setWindowTitle(QCoreApplication.translate("PythonConsole",
                                                       "Python Console - Command History"))
        self.listView.setToolTip(QCoreApplication.translate("PythonConsole",
                                                            "Double click on item to execute"))
        self.model = QStandardItemModel(self.listView)

        self._reloadHistory()

        self.deleteScut = QShortcut(QKeySequence(Qt.Key_Delete), self)
        self.deleteScut.activated.connect(self._deleteItem)
        self.listView.doubleClicked.connect(self._runHistory)
        self.reloadHistory.clicked.connect(self._reloadHistory)
        self.saveHistory.clicked.connect(self._saveHistory)
Esempio n. 30
0
 def _preparationFinished(self):
     self._clearLexer()
     if os.path.exists(self._pap_file):
         os.remove(self._pap_file)
     self.ui.label.setText(
         QCoreApplication.translate("PythonConsole",
                                    "Saving prepared file..."))
     prepd = self._api.savePrepared(unicode(self._pap_file))
     rslt = self.trUtf8("Error")
     if prepd:
         rslt = QCoreApplication.translate("PythonConsole", "Saved")
     self.ui.label.setText(u'{0} {1}'.format(self.ui.label.text(), rslt))
     self._api = None
     self.ui.progressBar.setVisible(False)
     self.ui.buttonBox.button(QDialogButtonBox.Cancel).setText(
         QCoreApplication.translate("PythonConsole", "Done"))
     self.adjustSize()
Esempio n. 31
0
def showWarning(message, category, filename, lineno, file=None, line=None):
    stk = ""
    for s in traceback.format_stack()[:-2]:
        stk += s.decode("utf-8", "replace") if hasattr(s, "decode") else s
    QgsMessageLog.logMessage(
        "warning:%s\ntraceback:%s" % (warnings.formatwarning(message, category, filename, lineno), stk),
        QCoreApplication.translate("Python", "Python warning"),
    )
Esempio n. 32
0
    def defineCharacteristicsFromFile(self):
        content = open(self.descriptionFile).read()
        dom_model = ET.fromstring(content)

        self.appkey = dom_model.find('key').text
        self.cliName = dom_model.find('exec').text
        self.name = dom_model.find('longname').text
        self.i18n_name = QCoreApplication.translate("OTBAlgorithm", self.name)
        self.group = dom_model.find('group').text
        self.i18n_group = QCoreApplication.translate("OTBAlgorithm", self.group)

        rebu = None
        the_result = None

        try:
            rebu = self.get_list_from_node(dom_model)
            the_result = map(self.adapt_list_to_string, rebu)
        except Exception as e:
            ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                   self.tr('Could not open OTB algorithm: %s\n%s' % (self.descriptionFile, traceback.format_exc())))
            raise e

        for line in the_result:
            try:
                if line.startswith("Parameter") or line.startswith("*Parameter"):
                    if line.startswith("*Parameter"):
                        param = getParameterFromString(line[1:])
                        param.isAdvanced = True
                    else:
                        param = getParameterFromString(line)
                    # Hack for initializing the elevation parameters from Processing configuration
                    if param.name == "-elev.dem.path" or param.name == "-elev.dem" or "elev.dem" in param.name:
                        param.default = OTBUtils.otbSRTMPath()
                    elif param.name == "-elev.dem.geoid" or param.name == "-elev.geoid" or "elev.geoid" in param.name:
                        param.default = OTBUtils.otbGeoidPath()
                    self.addParameter(param)
                elif line.startswith("Extent"):
                    self.addParameter(ParameterExtent(self.REGION_OF_INTEREST, "Region of interest", "0,1,0,1"))
                    self.hasROI = True
                else:
                    self.addOutput(getOutputFromString(line))
            except Exception as e:
                ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                       self.tr('Could not open OTB algorithm: %s\n%s' % (self.descriptionFile, line)))
                raise e
Esempio n. 33
0
 def contextMenuEvent(self, e):
     menu = QMenu(self)
     subMenu = QMenu(menu)
     titleHistoryMenu = QCoreApplication.translate("PythonConsole", "Command History")
     subMenu.setTitle(titleHistoryMenu)
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Show"),
         self.showHistory, 'Ctrl+Shift+SPACE')
     subMenu.addSeparator()
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Save"),
         self.writeHistoryFile)
     subMenu.addSeparator()
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Clear File"),
         self.clearHistory)
     subMenu.addAction(
         QCoreApplication.translate("PythonConsole", "Clear Session"),
         self.clearHistorySession)
     menu.addMenu(subMenu)
     menu.addSeparator()
     copyAction = menu.addAction(
         QCoreApplication.translate("PythonConsole", "Copy"),
         self.copy, QKeySequence.Copy)
     pasteAction = menu.addAction(
         QCoreApplication.translate("PythonConsole", "Paste"),
         self.paste, QKeySequence.Paste)
     copyAction.setEnabled(False)
     pasteAction.setEnabled(False)
     if self.hasSelectedText():
         copyAction.setEnabled(True)
     if QApplication.clipboard().text():
         pasteAction.setEnabled(True)
     menu.exec_(self.mapToGlobal(e.pos()))
Esempio n. 34
0
    def onError(self, error):
        if error == QProcess.FailedToStart:
            msg = QCoreApplication.translate(
                "GdalTools",
                "The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program."
            )
        elif error == QProcess.Crashed:
            msg = QCoreApplication.translate(
                "GdalTools",
                "The process crashed some time after starting successfully.")
        else:
            msg = QCoreApplication.translate("GdalTools",
                                             "An unknown error occurred.")

        QErrorMessage(self).showMessage(msg)
        QApplication.processEvents()  # give the user chance to see the message

        self.stop()
Esempio n. 35
0
 def saveScriptFile(self):
     tabWidget = self.tabEditorWidget.currentWidget()
     try:
         tabWidget.save()
     except (IOError, OSError) as error:
         msgText = QCoreApplication.translate('PythonConsole',
                                              'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path,
                                                                                                           error.strerror)
         self.callWidgetMessageBarEditor(msgText, 2, False)
Esempio n. 36
0
 def clearHistory(self, clearSession=False):
     if clearSession:
         self.history = []
         msgText = QCoreApplication.translate('PythonConsole',
                                              'Session and file history cleared successfully.')
         self.parent.callWidgetMessageBar(msgText)
         return
     ok = False
     try:
         cH = codecs.open(_historyFile, 'w', encoding='utf-8')
         ok = True
     except:
         raise
     cH.close()
     if ok:
         msgText = QCoreApplication.translate('PythonConsole',
                                              'History cleared successfully.')
         self.parent.callWidgetMessageBar(msgText)
Esempio n. 37
0
    def populate(self):
        groups = {}
        count = 0
        provider = Processing.algs[self.providerName]
        algs = provider.values()

        name = 'ACTIVATE_' + self.providerName.upper().replace(' ', '_')
        active = ProcessingConfig.getSetting(name)

        # Add algorithms
        for alg in algs:
            if not alg.showInToolbox:
                continue
            if alg.group in groups:
                groupItem = groups[alg.group]
            else:
                groupItem = QTreeWidgetItem()
                name = alg.i18n_group or alg.group
                if not active:
                    groupItem.setForeground(0, Qt.darkGray)
                groupItem.setText(0, name)
                groupItem.setToolTip(0, name)
                groups[alg.group] = groupItem
            algItem = TreeAlgorithmItem(alg)
            if not active:
                algItem.setForeground(0, Qt.darkGray)
            groupItem.addChild(algItem)
            count += 1

        actions = Processing.actions[self.providerName]
        for action in actions:
            if action.group in groups:
                groupItem = groups[action.group]
            else:
                groupItem = QTreeWidgetItem()
                groupItem.setText(0, action.group)
                groups[action.group] = groupItem
            algItem = TreeActionItem(action)
            groupItem.addChild(algItem)

        text = self.provider.getDescription()

        if not active:
            def activateProvider():
                self.toolbox.activateProvider(self.providerName)
            label = QLabel(text + "&nbsp;&nbsp;&nbsp;&nbsp;<a href='%s'>Activate</a>")
            label.setStyleSheet("QLabel {background-color: white; color: grey;}")
            label.linkActivated.connect(activateProvider)
            self.tree.setItemWidget(self, 0, label)

        else:
            text += QCoreApplication.translate("TreeProviderItem", " [{0} geoalgorithms]").format(count)
        self.setText(0, text)
        self.setToolTip(0, self.text(0))
        for groupItem in groups.values():
            self.addChild(groupItem)
Esempio n. 38
0
    def defineCharacteristicsFromFile(self):
        lines = open(self.descriptionFile)
        line = lines.readline().strip('\n').strip()
        self.name = line
        if '|' in self.name:
            tokens = self.name.split('|')
            self.name = tokens[0]
            #cmdname is the name of the algorithm in SAGA, that is, the name to use to call it in the console
            self.cmdname = tokens[1]

        else:
            self.cmdname = self.name
            self.i18n_name = QCoreApplication.translate(
                "SAGAAlgorithm", unicode(self.name))
        #_commandLineName is the name used in processing to call the algorithm
        #Most of the time will be equal to the cmdname, but in same cases, several processing algorithms
        #call the same SAGA one
        self._commandLineName = self.createCommandLineName(self.name)
        self.name = decoratedAlgorithmName(self.name)
        self.i18n_name = QCoreApplication.translate("SAGAAlgorithm",
                                                    unicode(self.name))
        line = lines.readline().strip('\n').strip()
        self.undecoratedGroup = line
        self.group = decoratedGroupName(self.undecoratedGroup)
        self.i18n_group = QCoreApplication.translate("SAGAAlgorithm",
                                                     self.group)
        line = lines.readline().strip('\n').strip()
        while line != '':
            if line.startswith('Hardcoded'):
                self.hardcodedStrings.append(line[len('Hardcoded|'):])
            elif line.startswith('Parameter'):
                self.addParameter(getParameterFromString(line))
            elif line.startswith('AllowUnmatching'):
                self.allowUnmatchingGridExtents = True
            elif line.startswith('Extent'):
                # An extent parameter that wraps 4 SAGA numerical parameters
                self.extentParamNames = line[6:].strip().split(' ')
                self.addParameter(
                    ParameterExtent(self.OUTPUT_EXTENT, 'Output extent', ''))
            else:
                self.addOutput(getOutputFromString(line))
            line = lines.readline().strip('\n').strip()
        lines.close()
Esempio n. 39
0
def load_user_expressions(path):
    """
    Load all user expressions from the given paths
    """
    #Loop all py files and import them
    modules = glob.glob(path + "/*.py")
    names = [os.path.basename(f)[:-3] for f in modules]
    for name in names:
        if name == "__init__":
            continue
        # As user expression functions should be registered with qgsfunction
        # just importing the file is enough to get it to load the functions into QGIS
        try:
            __import__("expressions.{0}".format(name), locals(), globals())
        except:
            error = traceback.format_exc()
            msgtitle = QCoreApplication.translate("UserExpressions", "User expressions")
            msg = QCoreApplication.translate("UserExpressions", "The user expression {0} is not valid").format(name)
            QgsMessageLog.logMessage(msg + "\n" + error, msgtitle, QgsMessageLog.WARNING)
Esempio n. 40
0
 def saveScriptFile(self):
     tabWidget = self.tabEditorWidget.currentWidget()
     try:
         tabWidget.save()
     except (IOError, OSError) as error:
         msgText = QCoreApplication.translate(
             'PythonConsole',
             'The file <b>{0}</b> could not be saved. Error: {1}').format(
                 tabWidget.path, error.strerror)
         self.callWidgetMessageBarEditor(msgText, 2, False)
Esempio n. 41
0
 def runLAStools(commands, progress):
     loglines = []
     commandline = " ".join(commands)
     loglines.append(
         QCoreApplication.translate("LAStoolsUtils",
                                    "LAStools command line"))
     loglines.append(commandline)
     loglines.append(
         QCoreApplication.translate("LAStoolsUtils",
                                    "LAStools console output"))
     proc = subprocess.Popen(commandline,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stdin=open(os.devnull),
                             stderr=subprocess.STDOUT,
                             universal_newlines=False).stdout
     for line in iter(proc.readline, ""):
         loglines.append(line)
         progress.setConsoleInfo(line)
     ProcessingLog.addToLog(ProcessingLog.LOG_INFO, loglines)
Esempio n. 42
0
    def popupError(self, error=None, url=None):
        """Popups an Error message bar for network errors."""
        disambiguation = self.tr_disambiguation[self.resourceType]
        widget = iface.messageBar().createMessage(self.tr('Connection problem', disambiguation),
                                                  self.tr('Could not connect to scripts/models repository', disambiguation))
        if error and url:
            QgsMessageLog.logMessage(self.tr(u"Network error code: {} on URL: {}").format(error, url), self.tr(u"Processing"), QgsMessageLog.CRITICAL)
            button = QPushButton(QCoreApplication.translate("Python", "View message log"), pressed=show_message_log)
            widget.layout().addWidget(button)

        iface.messageBar().pushWidget(widget, level=QgsMessageBar.CRITICAL, duration=5)
Esempio n. 43
0
    def insertInitText(self):
        txtInit = QCoreApplication.translate("PythonConsole",
                                             "Python Console \n"
                                             "Use iface to access QGIS API interface or Type help(iface) for more info")

        ## some translation string for the console header ends without '\n'
        ## and the first command in console will be appended at the header text.
        ## The following code add a '\n' at the end of the string if not present.
        if txtInit.endswith('\n'):
            self.setText(txtInit)
        else:
            self.setText(txtInit + '\n')
Esempio n. 44
0
    def defineCharacteristicsFromFile(self):
        lines = open(self.descriptionFile)
        line = lines.readline().strip('\n').strip()
        self.name = line
        if '|' in self.name:
            tokens = self.name.split('|')
            self.name = tokens[0]
            #cmdname is the name of the algorithm in SAGA, that is, the name to use to call it in the console
            self.cmdname = tokens[1]

        else:
            self.cmdname = self.name
            self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", unicode(self.name))
        #_commandLineName is the name used in processing to call the algorithm
        #Most of the time will be equal to the cmdname, but in same cases, several processing algorithms
        #call the same SAGA one
        self._commandLineName = self.createCommandLineName(self.name)
        self.name = decoratedAlgorithmName(self.name)
        self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", unicode(self.name))
        line = lines.readline().strip('\n').strip()
        self.undecoratedGroup = line
        self.group = decoratedGroupName(self.undecoratedGroup)
        self.i18n_group = QCoreApplication.translate("SAGAAlgorithm", self.group)
        line = lines.readline().strip('\n').strip()
        while line != '':
            if line.startswith('Hardcoded'):
                self.hardcodedStrings.append(line[len('Hardcoded|'):])
            elif line.startswith('Parameter'):
                self.addParameter(getParameterFromString(line))
            elif line.startswith('AllowUnmatching'):
                self.allowUnmatchingGridExtents = True
            elif line.startswith('Extent'):
                # An extent parameter that wraps 4 SAGA numerical parameters
                self.extentParamNames = line[6:].strip().split(' ')
                self.addParameter(ParameterExtent(self.OUTPUT_EXTENT,
                                                  'Output extent', ''))
            else:
                self.addOutput(getOutputFromString(line))
            line = lines.readline().strip('\n').strip()
        lines.close()
Esempio n. 45
0
 def __init__(self, api_lexer, api_files, pap_file, parent=None):
     QDialog.__init__(self, parent)
     self.ui = Ui_APIsDialogPythonConsole()
     self.ui.setupUi(self)
     self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Compile APIs"))
     self.ui.plainTextEdit.setVisible(False)
     self.ui.textEdit_Qsci.setVisible(False)
     self.adjustSize()
     self._api = None
     self.ui.buttonBox.rejected.connect(self._stopPreparation)
     self._api_files = api_files
     self._api_lexer = api_lexer
     self._pap_file = pap_file
Esempio n. 46
0
    def insertInitText(self):
        txtInit = QCoreApplication.translate(
            "PythonConsole", "Python Console \n"
            "Use iface to access QGIS API interface or Type help(iface) for more info"
        )

        ## some translation string for the console header ends without '\n'
        ## and the first command in console will be appended at the header text.
        ## The following code add a '\n' at the end of the string if not present.
        if txtInit.endswith('\n'):
            self.setText(txtInit)
        else:
            self.setText(txtInit + '\n')
Esempio n. 47
0
    def __init__(self, parent=None):
        QDockWidget.__init__(self, parent)
        self.setObjectName("PythonConsole")
        self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console"))
        #self.setAllowedAreas(Qt.BottomDockWidgetArea)

        self.console = PythonConsoleWidget(self)
        self.setWidget(self.console)
        self.setFocusProxy(self.console)

        # try to restore position from stored main window state
        if iface and not iface.mainWindow().restoreDockWidget(self):
            iface.mainWindow().addDockWidget(Qt.BottomDockWidgetArea, self)
Esempio n. 48
0
def startPlugin(packageName):
    """ initialize the plugin """
    global plugins, active_plugins, iface, plugin_times

    if packageName in active_plugins:
        return False
    if packageName not in sys.modules:
        return False

    package = sys.modules[packageName]

    errMsg = QCoreApplication.translate("Python", "Couldn't load plugin %s") % packageName

    start = time.clock()
    # create an instance of the plugin
    try:
        plugins[packageName] = package.classFactory(iface)
    except:
        _unloadPluginModules(packageName)
        msg = QCoreApplication.translate("Python", "%s due to an error when calling its classFactory() method") % errMsg
        showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True)
        return False

    # initGui
    try:
        plugins[packageName].initGui()
    except:
        del plugins[packageName]
        _unloadPluginModules(packageName)
        msg = QCoreApplication.translate("Python", "%s due to an error when calling its initGui() method") % errMsg
        showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True)
        return False

    # add to active plugins
    active_plugins.append(packageName)
    end = time.clock()
    plugin_times[packageName] = "{0:02f}s".format(end - start)

    return True
Esempio n. 49
0
def handleAlgorithmResults(alg, progress=None, showResults=True):
    wrongLayers = []
    htmlResults = False
    if progress is None:
        progress = SilentProgress()
    progress.setText(
        QCoreApplication.translate('Postprocessing',
                                   'Loading resulting layers'))
    i = 0
    for out in alg.outputs:
        progress.setPercentage(100 * i / float(len(alg.outputs)))
        if out.hidden or not out.open:
            continue
        if isinstance(out, (OutputRaster, OutputVector, OutputTable)):
            try:
                if hasattr(out, "layer") and out.layer is not None:
                    out.layer.setLayerName(out.description)
                    QgsMapLayerRegistry.instance().addMapLayers([out.layer])
                else:
                    if ProcessingConfig.getSetting(
                            ProcessingConfig.USE_FILENAME_AS_LAYER_NAME):
                        name = os.path.basename(out.value)
                    else:
                        name = out.description
                    dataobjects.load(
                        out.value, name, alg.crs,
                        RenderingStyles.getStyle(alg.commandLineName(),
                                                 out.name))
            except Exception:
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_ERROR,
                    "Error loading result layer:\n" + traceback.format_exc())
                wrongLayers.append(out.description)
        elif isinstance(out, OutputHTML):
            ProcessingResults.addResult(out.description, out.value)
            htmlResults = True
        i += 1

    QApplication.restoreOverrideCursor()
    if wrongLayers:
        msg = "The following layers were not correctly generated.<ul>"
        msg += "".join(["<li>%s</li>" % lay for lay in wrongLayers]) + "</ul>"
        msg += "You can check the log messages to find more information about the execution of the algorithm"
        progress.error(msg)

    if showResults and htmlResults and not wrongLayers:
        dlg = ResultsDialog()
        dlg.exec_()

    return len(wrongLayers) == 0
Esempio n. 50
0
    def __init__(self, parent=None):
        QDockWidget.__init__(self, parent)
        self.setObjectName("PythonConsole")
        self.setWindowTitle(
            QCoreApplication.translate("PythonConsole", "Python Console"))
        #self.setAllowedAreas(Qt.BottomDockWidgetArea)

        self.console = PythonConsoleWidget(self)
        self.setWidget(self.console)
        self.setFocusProxy(self.console)

        # try to restore position from stored main window state
        if iface and not iface.mainWindow().restoreDockWidget(self):
            iface.mainWindow().addDockWidget(Qt.BottomDockWidgetArea, self)
Esempio n. 51
0
 def writeHistoryFile(self, fromCloseConsole=False):
     ok = False
     try:
         wH = codecs.open(_historyFile, 'w', encoding='utf-8')
         for s in self.history:
             wH.write(s + '\n')
         ok = True
     except:
         raise
     wH.close()
     if ok and not fromCloseConsole:
         msgText = QCoreApplication.translate('PythonConsole',
                                              'History saved successfully.')
         self.parent.callWidgetMessageBar(msgText)
Esempio n. 52
0
 def __init__(self, api_lexer, api_files, pap_file, parent=None):
     QDialog.__init__(self, parent)
     self.ui = Ui_APIsDialogPythonConsole()
     self.ui.setupUi(self)
     self.setWindowTitle(
         QCoreApplication.translate("PythonConsole", "Compile APIs"))
     self.ui.plainTextEdit.setVisible(False)
     self.ui.textEdit_Qsci.setVisible(False)
     self.adjustSize()
     self._api = None
     self.ui.buttonBox.rejected.connect(self._stopPreparation)
     self._api_files = api_files
     self._api_lexer = api_lexer
     self._pap_file = pap_file
Esempio n. 53
0
    def switchToolMode(self):
        self.recurseCheck.setVisible(self.inputDirCheck.isChecked())
        self.inSelector.clear()

        if self.inputDirCheck.isChecked():
            self.inFileLabel = self.label.text()
            self.label.setText(QCoreApplication.translate("GdalTools", "&Input directory"))

            self.inSelector.selectClicked.disconnect(self.fillInputFilesEdit)
            self.inSelector.selectClicked.connect(self.fillInputDir)
        else:
            self.label.setText(self.inFileLabel)

            self.inSelector.selectClicked.connect(self.fillInputFilesEdit)
            self.inSelector.selectClicked.disconnect(self.fillInputDir)