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)
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
def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) self.loaded = False self.app = QCoreApplication([])
def __init__(self, iface): if not valid: return # Save reference to the QGIS interface self.iface = iface try: self.QgisVersion = unicode(QGis.QGIS_VERSION_INT) except: self.QgisVersion = unicode(QGis.qgisVersion)[0] if QGis.QGIS_VERSION[0:3] < "1.5": # For i18n support userPluginPath = qgis.utils.home_plugin_path + "/GdalTools" systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools" overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool) if not overrideLocale: localeFullName = QLocale.system().name() else: localeFullName = QSettings().value("locale/userLocale", "", type=str) if QFileInfo(userPluginPath).exists(): translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" else: translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" self.localePath = translationPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator) # The list of actions added to menus, so we can remove them when unloading the plugin self._menuActions = []
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()
def setInfo(self, msg, error=False): if error: self.txtLog.append('<span style="color:red"><br>%s<br></span>' % msg) else: self.txtLog.append(msg) QCoreApplication.processEvents()
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
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)
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)
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
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)
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)
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)
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')
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')
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()
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
def rewritefile(layer): with file(filename, 'w') as f: f.write( "name,size,id\ntoad,small,5\nmole,medium,6\nbadger,big,7\n" ) # print "Rewritten file - sleeping" time.sleep(1) QCoreApplication.instance().processEvents()
def deletefile(layer): try: os.remove(filename) except: file(filename, "w").close() assert os.path.getsize(filename) == 0, "removal and truncation of {} failed".format(filename) # print "Deleted file - sleeping" time.sleep(1) QCoreApplication.instance().processEvents()
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(' ', ' ') # preserve whitespaces for nicer output dlg = QgsMessageOutput.createMessageOutput() dlg.setTitle(msg) dlg.setMessage(txt, QgsMessageOutput.MessageHtml) dlg.showMessage()
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(" ", " ") # preserve whitespaces for nicer output dlg = QgsMessageOutput.createMessageOutput() dlg.setTitle(msg) dlg.setMessage(txt, QgsMessageOutput.MessageHtml) dlg.showMessage()
def deletefile(layer): try: os.remove(filename) except: file(filename, "w").close() assert os.path.getsize( filename ) == 0, "removal and truncation of {} failed".format(filename) # print "Deleted file - sleeping" time.sleep(1) QCoreApplication.instance().processEvents()
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()
def grabHTTP(self, url, loadFunction, arguments=None): """Grab distant content via QGIS internal classes and QtNetwork.""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) request = QUrl(url) reply = self.manager.get(QNetworkRequest(request)) if arguments: reply.finished.connect(partial(loadFunction, reply, arguments)) else: reply.finished.connect(partial(loadFunction, reply)) while not reply.isFinished(): QCoreApplication.processEvents()
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
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)
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
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)
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)
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()
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()
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)
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
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)
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"), )
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()
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"))
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)
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()))
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
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()
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)
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)
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 + " <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)
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()
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)
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)
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)
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)
def write(self, m): if self.style == "_traceback": # Show errors in red stderrColor = QColor(self.sO.settings.value("pythonConsole/stderrFontColor", QColor(Qt.red))) self.sO.SendScintilla(QsciScintilla.SCI_STYLESETFORE, 0o01, stderrColor) self.sO.SendScintilla(QsciScintilla.SCI_STYLESETITALIC, 0o01, True) self.sO.SendScintilla(QsciScintilla.SCI_STYLESETBOLD, 0o01, True) pos = self.sO.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS) self.sO.SendScintilla(QsciScintilla.SCI_STARTSTYLING, pos, 31) self.sO.append(m) self.sO.SendScintilla(QsciScintilla.SCI_SETSTYLING, len(m), 0o01) else: self.sO.append(m) if self.out: self.out.write(m) self.move_cursor_to_end() if self.style != "_traceback": QCoreApplication.processEvents()
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')