def run(self): plugin = currentPlugin() #update the plugin list first! The plugin could be removed from the list if was temporarily broken. updateAvailablePlugins() #try to load from scratch the plugin saved in QSettings if not loaded if plugin not in plugins: try: loadPlugin(plugin) startPlugin(plugin) except: pass updateAvailablePlugins() #give one chance for correct (not a loop) if plugin not in plugins: self.configure() plugin = currentPlugin() if plugin in plugins: state = self.iface.mainWindow().saveState() # Unload submodules for key in [key for key in sys.modules.keys()]: if '{}.'.format(plugin) in key: if hasattr(sys.modules[key], 'qCleanupResources'): sys.modules[key].qCleanupResources() del sys.modules[key] reloadPlugin(plugin) self.iface.mainWindow().restoreState(state) self.iface.messageBar().pushMessage("<b>{}</b> reloaded.".format(plugin), QGis.Info)
def onClosePlugin(self): """Cleanup necessary items here when plugin dockwidget is closed""" print("** CLOSING AcATaMa") if ClassificationDialog.is_opened: self.dockwidget.classification_dialog.closing() self.dockwidget.classification_dialog.reject(is_ok_to_close=True) if AccuracyAssessmentDialog.is_opened: self.dockwidget.accuracy_assessment_dialog.closing() self.dockwidget.accuracy_assessment_dialog.reject( is_ok_to_close=True) self.removes_temporary_files() # disconnects self.dockwidget.closingPlugin.disconnect(self.onClosePlugin) # remove this statement if dockwidget is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: # self.dockwidget = None self.dockwidget.deleteLater() self.dockwidget = None self.pluginIsActive = False from qgis.utils import reloadPlugin reloadPlugin("AcATaMa")
def run(self): plugin = currentPlugin() #update the plugin list first! The plugin could be removed from the list if was temporarily broken. updateAvailablePlugins() #try to load from scratch the plugin saved in QSettings if not loaded if plugin not in plugins: try: loadPlugin(plugin) startPlugin(plugin) except: pass updateAvailablePlugins() #give one chance for correct (not a loop) if plugin not in plugins: self.configure() plugin = currentPlugin() if plugin in plugins: state = self.iface.mainWindow().saveState() # Unload submodules for key in [key for key in sys.modules.keys()]: if '{}.'.format(plugin) in key: if hasattr(sys.modules[key], 'qCleanupResources'): sys.modules[key].qCleanupResources() del sys.modules[key] handleExtraCommands(self.iface.messageBar(), self.tr) reloadPlugin(plugin) self.iface.mainWindow().restoreState(state) if notificationsEnabled(): self.iface.messageBar().pushMessage( self.tr('<b>{}</b> reloaded.').format(plugin), Qgis.Info)
def closePlugin(self): print("** CLOSING Plugin **") self.dlg.OutFolderButton.clicked.disconnect(self.exportTileButton) self.dlg.DSMpushButton.clicked.disconnect(self.importDsmButton) self.dlg.DTMpushButton.clicked.disconnect(self.importDtmButton) self.dlg.InputCrsButton.clicked.disconnect(self.crsDemButton) self.dlg.OutputCrsButton.clicked.disconnect(self.crsTileButton) self.dlg.InputEnte.textChanged.disconnect(self.handleEnte) self.dlg.InputYear.valueChanged.disconnect(self.handleAnno) self.dlg.clearButton.clicked.disconnect(self.clearButton) self.dlg.helpButton.clicked.disconnect(self.openHelpButton) self.dlg.pushButtonOk.clicked.disconnect(self.run) self.dlg.rejected.disconnect(self.closePlugin) self.pluginIsActive = False self.ext = [] self.layer = '' self.dsm_path_folder = '' self.dtm_path_folder = '' self.tile_path_folder = '' self.demselectedcrs = '' self.tileselectedcrs = '' self.dem_code = '' self.tile_code = '' self.annoText = 0 self.enteText = '' if self.tile_out_tempdir != '': self.tile_out_tempdir.cleanup() from qgis.utils import reloadPlugin reloadPlugin("LidarTileMaker")
def saveConfigXMLAndReloadPlugin(self): """Save config and reload""" QgsMessageLog.logMessage('Reading configuration file', tag="CropRows Generator", level=QgsMessageLog.INFO) xmlConfigFile = os.path.join( (os.path.dirname(os.path.abspath(__file__))), 'config.xml') QgsMessageLog.logMessage('Config file:' + xmlConfigFile, tag="CropRows Generator", level=QgsMessageLog.INFO) tree = ET.parse(xmlConfigFile) root = tree.getroot() root_tag = root.tag for cfg in root.iter('config'): cfg.find('processing_core_path' ).text = self.dlg.inputProcessingApiURL.text() cfg.find('osgeo_path').text = self.dlg.inputGdalOsgeoPath.text() cfg.find( 'temporal_path').text = self.dlg.inputSharedFolderPath.text() tree.write(xmlConfigFile) QgsMessageLog.logMessage('Current Configuration Saved', tag="CropRows Generator", level=QgsMessageLog.INFO) QMessageBox.information(None, 'Configuration Message', "Current Configuration Saved !", QMessageBox.Ok) self.dlg.close() reloadPlugin('PACropRows')
def installFromZipFile(self, filePath): if not os.path.isfile(filePath): return settings = QgsSettings() settings.setValue(settingsGroup + '/lastZipDirectory', QFileInfo(filePath).absoluteDir().absolutePath()) error = False infoString = None with zipfile.ZipFile(filePath, 'r') as zf: pluginName = os.path.split(zf.namelist()[0])[0] pluginFileName = os.path.splitext(os.path.basename(filePath))[0] pluginsDirectory = qgis.utils.home_plugin_path if not QDir(pluginsDirectory).exists(): QDir().mkpath(pluginsDirectory) # If the target directory already exists as a link, # remove the link without resolving QFile(os.path.join(pluginsDirectory, pluginFileName)).remove() try: # Test extraction. If fails, then exception will be raised # and no removing occurs unzip(str(filePath), str(pluginsDirectory)) # Removing old plugin files if exist removeDir(QDir.cleanPath(os.path.join(pluginsDirectory, pluginFileName))) # Extract new files unzip(str(filePath), str(pluginsDirectory)) except: error = True infoString = (self.tr("Plugin installation failed"), self.tr("Failed to unzip the plugin package\n{}.\nProbably it is broken".format(filePath))) if infoString is None: updateAvailablePlugins() loadPlugin(pluginName) plugins.getAllInstalled(testLoad=True) plugins.rebuild() if settings.contains('/PythonPlugins/' + pluginName): if settings.value('/PythonPlugins/' + pluginName, False, bool): startPlugin(pluginName) reloadPlugin(pluginName) else: unloadPlugin(pluginName) loadPlugin(pluginName) else: if startPlugin(pluginName): settings.setValue('/PythonPlugins/' + pluginName, True) infoString = (self.tr("Plugin installed successfully"), "") if infoString[0]: level = error and QgsMessageBar.CRITICAL or QgsMessageBar.INFO msg = "<b>%s:</b>%s" % (infoString[0], infoString[1]) iface.pluginManagerInterface().pushMessage(msg, level)
def closeEvent(self, QCloseEvent): try: self.canvas.scene().removeItem(self.vm_sa) self.canvas.scene().removeItem(self.vm_sb) self.canvas.scene().removeItem(self.vm_ea) self.canvas.scene().removeItem(self.vm_eb) except AttributeError: pass self.close() reloadPlugin('EqDistant')
def uninstallPlugin(self,key): """ uninstall currently selected plugin """ plugin = plugins.all()[key] if not plugin: return warning = self.tr("Are you sure you want to uninstall the following plugin?") + "\n(" + plugin["name"] + ")" if plugin["status"] == "orphan" and not plugin["error"]: warning += "\n\n"+self.tr("Warning: this plugin isn't available in any accessible repository!") if QMessageBox.warning(self, self.tr("QGIS Python Plugin Installer"), warning , QMessageBox.Yes, QMessageBox.No) == QMessageBox.No: return # unload the plugin if it's not plugin_installer itself (otherwise, do it after removing its directory): if key != "plugin_installer": try: unloadPlugin(key) except: pass pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/" + plugin["localdir"] result = removeDir(pluginDir) if result: QMessageBox.warning(self, self.tr("Plugin uninstall failed"), result) else: # if the uninstalled plugin is the installer itself, reload it and quit if key == "plugin_installer": if QGIS_15: try: QMessageBox.information(self, self.tr("QGIS Python Plugin Installer"), self.tr("Plugin Installer update uninstalled. Plugin Installer will now close and revert to its primary version. You can find it in the Plugins menu and continue operation.")) reloadPlugin(key) return except: pass else: QMessageBox.information(self, self.tr("QGIS Python Plugin Installer"), self.tr("Plugin Installer update uninstalled. Please restart QGIS in order to load its primary version.")) # safe remove try: unloadPlugin(plugin["localdir"]) except: pass try: exec ("plugins[%s].unload()" % plugin["localdir"]) exec ("del plugins[%s]" % plugin["localdir"]) except: pass try: exec ("del sys.modules[%s]" % plugin["localdir"]) except: pass plugins.getAllInstalled() plugins.rebuild() self.populatePluginTree() if QGIS_14: QMessageBox.information(self, self.tr("Plugin uninstalled successfully"), self.tr("Plugin uninstalled successfully")) else: QMessageBox.information(self, self.tr("Plugin uninstalled successfully"), self.tr("Python plugin uninstalled. Note that you may need to restart Quantum GIS in order to remove it completely.")) history.markChange(key,'D')
def installFromZipFile(pluginPath): """Install and activate plugin from the specified package """ result = None with zipfile.ZipFile(pluginPath, 'r') as zf: pluginName = os.path.split(zf.namelist()[0])[0] pluginFileName = os.path.splitext(os.path.basename(pluginPath))[0] pluginsDirectory = home_plugin_path if not QDir(pluginsDirectory).exists(): QDir().mkpath(pluginsDirectory) # If the target directory already exists as a link, # remove the link without resolving QFile(os.path.join(pluginsDirectory, pluginFileName)).remove() try: # Test extraction. If fails, then exception will be raised # and no removing occurs unzip(unicode(pluginPath), unicode(pluginsDirectory)) # Removing old plugin files if exist removeDir(QDir.cleanPath(os.path.join(pluginsDirectory, pluginFileName))) # Extract new files unzip(unicode(pluginPath), unicode(pluginsDirectory)) except: result = QCoreApplication.translate('BoundlessConnect', 'Failed to unzip the plugin package\n{}.\nProbably it is broken'.format(pluginPath)) if result is None: updateAvailablePlugins() loadPlugin(pluginName) plugins.getAllInstalled(testLoad=True) plugins.rebuild() plugin = plugins.all()[pluginName] settings = QSettings() if settings.contains('/PythonPlugins/' + pluginName): if settings.value('/PythonPlugins/' + pluginName, False, bool): startPlugin(pluginName) reloadPlugin(pluginName) else: unloadPlugin(pluginName) loadPlugin(pluginName) else: if startPlugin(pluginName): settings.setValue('/PythonPlugins/' + pluginName, True) return result
def run(self): #Check libraries self.Prerequisites() self.Prerequisites("requests") self.Prerequisites("httplib2") self.Prerequisites("simplejson") self.Prerequisites("six") if self.instaladas == True: reloadPlugin('instagram2qgis') return self.dlg = Insta2QgisDialog(self.iface) self.dlg.setWindowFlags(Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.dlg.exec_()
def run(self): #Check libraries self.Prerequisites() self.Prerequisites("requests") self.Prerequisites("httplib2") self.Prerequisites("simplejson") self.Prerequisites("six") if self.instaladas==True: reloadPlugin('instagram2qgis') return self.dlg = Insta2QgisDialog(self.iface) self.dlg.setWindowFlags(Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.dlg.exec_()
def reject(self): """ clear widget :return: """ self.input_path.clear() self.output_path.clear() self.select_band.clear() self.select_subdataset.clear() self.input_title.clear() self.input_crs.clear() #self.display_log.clear() self.close() reloadPlugin('CdfConverter')
def updatePlugin(self): currentVersion = self.getCurrentVersion() installedVersion = self.getInstalledVersion() if currentVersion != "" and currentVersion != installedVersion: msg = u"K dispozici je nová verze. Chcete ji instalovat?" install = QMessageBox.question(self.main.iface.mainWindow(), u"Nová verze", msg, QMessageBox.Yes, QMessageBox.No) if install == QMessageBox.Yes: self.downloadPlugin(currentVersion) msg = u"Nová verze byla nainstalována. Dojde k obnovení pluginu do výchozí pozice." QMessageBox.information(self.main.iface.mainWindow(), u"Nová verze", msg) utils.reloadPlugin('qgis_patrac'); self.done(0) else: msg = u"Máte aktuální verzi: " + currentVersion QMessageBox.information(self.main.iface.mainWindow(), u"Nová verze", msg)
def onClosePlugin(self): """Cleanup necessary items here when plugin is closed""" self.removes_temporary_files() # remove this statement if dialog is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: CCD_Plugin.dialog.close() CCD_Plugin.dialog = None # reset some variables self.pluginIsActive = False from qgis.utils import reloadPlugin reloadPlugin("CCD_Plugin - Thematic Raster Editor")
def run(self): plugin = currentPlugin() #update the plugin list first! The plugin could be removed from the list if was temporarily broken. updateAvailablePlugins() #try to load from scratch the plugin saved in QSettings if not loaded if not plugins.has_key(plugin): try: loadPlugin(plugin) startPlugin(plugin) except: pass updateAvailablePlugins() #give one chance for correct (not a loop) if not plugins.has_key(plugin): self.configure() plugin = currentPlugin() if plugins.has_key(plugin): reloadPlugin(plugin)
def exit(self): try: # global nFoto # nFoto = 1 # self.dlg.fotoField.setPixmap(QPixmap("")) # self.dlg.tb_refCat.setText("") # self.dlg.tb_supPar.setText("") # self.dlg.tb_supExpro.setText("") # self.dlg.tb_foTo.setText("") # self.dlg.cb_listLayers.clear() mc = self.iface.mapCanvas() layer = self.iface.activeLayer() layer.removeSelection() mc.refresh() reloadPlugin('viewAttributes') self.dlg.close() except: reloadPlugin('viewAttributes') self.dlg.close()
def onClosePlugin(self): """Cleanup necessary items here when plugin is closed""" self.removes_temporary_files() # disconnects PCA4CD.dialog.closingPlugin.disconnect(self.onClosePlugin) # remove this statement if dialog is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: PCA4CD.dialog.close() PCA4CD.dialog = None self.pluginIsActive = False from qgis.utils import reloadPlugin reloadPlugin("PCA4CD - PCA for change detection")
def run(self): plugin = currentPlugin() #update the plugin list first! The plugin could be removed from the list if was temporarily broken. updateAvailablePlugins() #try to load from scratch the plugin saved in QSettings if not loaded if plugin not in plugins: try: loadPlugin(plugin) startPlugin(plugin) except: pass updateAvailablePlugins() #give one chance for correct (not a loop) if plugin not in plugins: self.configure() plugin = currentPlugin() if plugin in plugins: state = self.iface.mainWindow().saveState() reloadPlugin(plugin) self.iface.mainWindow().restoreState(state) self.iface.messageBar().pushMessage("<b>%s</b> reloaded." % plugin, QGis.Info)
def onClosePlugin(self): """Cleanup necessary items here when plugin is closed""" from ThRasE.core.edition import LayerToEdit # restore the recode pixel table to original (if was changed) of the thematic raster to edit if LayerToEdit.current: ThRasE.dialog.restore_recode_table() # restore the opacity of all active layers to 100% [ al.update_layer_opacity(100) for als in [ view_widget.active_layers for view_widget in ThRasEDialog.view_widgets ] for al in als if al.opacity < 100 ] # close the navigation dialog if is open if LayerToEdit.current and LayerToEdit.current.navigation_dialog and LayerToEdit.current.navigation_dialog.isVisible( ): LayerToEdit.current.navigation_dialog.close() LayerToEdit.current.navigation_dialog = None self.removes_temporary_files() # remove this statement if dialog is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: ThRasE.dialog.close() ThRasE.dialog = None # reset some variables self.pluginIsActive = False ThRasEDialog.view_widgets = [] LayerToEdit.instances = {} LayerToEdit.current = None from qgis.utils import reloadPlugin reloadPlugin("ThRasE - Thematic Raster Editor")
def run(self): """ This prepares the user interface of the plugin and the performs the events once "OK" is clicked. :return: """ # Reloading the plugin reloadPlugin('assimila_datacube') # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = AssimilaDatacCubeDialog(self.iface) # Clears the values from previous run self.dlg.lineEdit.clear() #keyfile self.dlg.lineEdit_2.clear() #rasterfile # Displays key file path location #self.key_file = os.path.join(os.path.dirname(__file__), ".assimila_dq") self.key_file = os.path.join(expanduser("~"), "Documents", ".assimila_dq") # default location self.dlg.lineEdit.insert(self.key_file) # Display default raster file path location """ Not using temporary location due to permissioin error if you read the path from the lineEdit. Use tempfile.gettempdir to access temporary directory without permission error. raster_file = "Users\Jenny\AppData\Local\Temp" #default_temp_path = f"{tempfile.gettempdir()}/{filename}.nc" """ raster_file = os.path.join(expanduser("~"), "Documents") self.dlg.lineEdit_2.insert(raster_file) # Display dropdowns for products # Only runs on the first run as the products_comboBox is empty # Instead of clearing the products combobox and then appending everytime # Only searches for products once despite the number of times the plugin is run if self.dlg.products_comboBox.currentIndex() == -1: products = Search.products().name.tolist() self.dlg.products_comboBox.setDuplicatesEnabled(False) self.dlg.products_comboBox.addItems(products) # Display dropdown for subproducts self.dlg.subproducts_comboBox.addItem( 'rfe') # Defaulting 1st item Subprodusct is 'rfe' """ Issue: for nth run, perform nth subproduct_selectionchange """ self.dlg.products_comboBox.currentTextChanged.connect( self.subproduct_selectionchange) # For updating the subproduct self.dlg.subproducts_comboBox.removeItem( 1) # Removing default subproduct value of 'rfe' # Links the Radio buttons and datetime widgets self.dlg.multi_radioButton.toggled.connect( lambda: self.radio_btn_state(self.dlg.single_radioButton, self.dlg. dateTimeEdit_1, self.dlg. dateTimeEdit_2)) # Show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # Runs when OK button is pressed if result: # runs process using values in widgets product = (self.dlg.products_comboBox.currentText()).lower() print(f"The product being run is {product}") subproduct = self.dlg.subproducts_comboBox.currentText() print(f"The subproduct being run is {subproduct}") north = self.dlg.N_spinBox.value() print('N: ' + str(north)) east = self.dlg.E_spinBox.value() print('E: ' + str(east)) south = self.dlg.S_spinBox.value() print('S: ' + str(south)) west = self.dlg.W_spinBox.value() print('W: ' + str(west)) # Format start and end dates and hour for datecube start = self.dlg.dateTimeEdit_1.dateTime().toString( "yyyy-MM-ddTHH:00:00") if self.dlg.single_radioButton.isChecked(): end = start # Perform check method for d1 self.check(north, east, south, west, self.dlg.dateTimeEdit_1.dateTime(), self.dlg.dateTimeEdit_1.dateTime()) else: end = self.dlg.dateTimeEdit_2.dateTime().toString( "yyyy-MM-ddTHH:00:00") # Perform check method for d1 d2 self.check(north, east, south, west, self.dlg.dateTimeEdit_1.dateTime(), self.dlg.dateTimeEdit_2.dateTime()) print(start) print(end) # Get Xarray from datacube y = self.get_data_from_datacube_nesw(product, subproduct, north, east, south, west, start, end) # Write Xarray to file self.create_raster_file(product, subproduct, north, east, south, west, y) pass
def installPlugin(self, key, quiet=False): """ install currently selected plugin """ infoString = ('','') plugin = plugins.all()[key] previousStatus = plugin["status"] if not plugin: return if plugin["status"] == "newer" and not plugin["error"]: # ask for confirmation if user downgrades an usable plugin if QMessageBox.warning(self, self.tr("QGIS Python Plugin Installer"), self.tr("Are you sure you want to downgrade the plugin to the latest available version? The installed one is newer!"), QMessageBox.Yes, QMessageBox.No) == QMessageBox.No: return dlg = QgsPluginInstallerInstallingDialog(self,plugin) dlg.exec_() if dlg.result(): infoString = (self.tr("Plugin installation failed"), dlg.result()) elif not QDir(QDir.cleanPath(QgsApplication.qgisSettingsDirPath() + "/python/plugins/" + key)).exists(): infoString = (self.tr("Plugin has disappeared"), self.tr("The plugin seems to have been installed but I don't know where. Probably the plugin package contained a wrong named directory.\nPlease search the list of installed plugins. I'm nearly sure you'll find the plugin there, but I just can't determine which of them it is. It also means that I won't be able to determine if this plugin is installed and inform you about available updates. However the plugin may work. Please contact the plugin author and submit this issue.")) QApplication.setOverrideCursor(Qt.WaitCursor) plugins.getAllInstalled() plugins.rebuild() QApplication.restoreOverrideCursor() else: if QGIS_14: if QGIS_15: # update the list of plugins in plugin handling routines updateAvailablePlugins() # try to load the plugin loadPlugin(plugin["localdir"]) else: # QGIS < 1.4 try: exec ("sys.path_importer_cache.clear()") exec ("import %s" % plugin["localdir"]) exec ("reload (%s)" % plugin["localdir"]) except: pass plugins.getAllInstalled(testLoad=True) plugins.rebuild() plugin = plugins.all()[key] if not plugin["error"]: if previousStatus in ["not installed", "new"]: if QGIS_14: # plugins can be started in python from QGIS >= 1.4 infoString = (self.tr("Plugin installed successfully"), self.tr("Plugin installed successfully")) settings = QSettings() settings.setValue("/PythonPlugins/"+plugin["localdir"], QVariant(True)) startPlugin(plugin["localdir"]) else: infoString = (self.tr("Plugin installed successfully"), self.tr("Python plugin installed.\nNow you need to enable it in Plugin Manager.")) else: if QGIS_15: # plugins can be reloaded on the fly in QGIS >= 1.5 settings = QSettings() if key != 'plugin_installer' and settings.value("/PythonPlugins/"+key).toBool(): # plugin will be reloaded on the fly only if currently loaded infoString = (self.tr("Plugin reinstalled successfully"), self.tr("Plugin reinstalled successfully")) reloadPlugin(key) else: infoString = (self.tr("Plugin reinstalled successfully"), self.tr("Python plugin reinstalled.\nYou need to restart Quantum GIS in order to reload it.")) else: infoString = (self.tr("Plugin reinstalled successfully"), self.tr("Python plugin reinstalled.\nYou need to restart Quantum GIS in order to reload it.")) if quiet: infoString = (None, None) else: if plugin["error"] == "incompatible": message = self.tr("The plugin is designed for a newer version of Quantum GIS. The minimum required version is:") message += " <b>" + plugin["error_details"] + "</b>" elif plugin["error"] == "dependent": message = self.tr("The plugin depends on some components missing on your system. You need to install the following Python module in order to enable it:") message += "<b> " + plugin["error_details"] + "</b>" else: message = self.tr("The plugin is broken. Python said:") message += "<br><b>" + plugin["error_details"] + "</b>" dlg = QgsPluginInstallerPluginErrorDialog(self,message) dlg.exec_() if dlg.result(): # revert installation plugins.getAllInstalled() plugins.rebuild() pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/" + plugin["localdir"] removeDir(pluginDir) if QDir(pluginDir).exists(): infoString = (self.tr("Plugin uninstall failed"), result) try: exec ("sys.path_importer_cache.clear()") exec ("import %s" % plugin["localdir"]) exec ("reload (%s)" % plugin["localdir"]) except: pass else: try: exec ("del sys.modules[%s]" % plugin["localdir"]) except: pass plugins.getAllInstalled() plugins.rebuild() if plugins.all().has_key(key) and not plugins.all()[key]["status"] in ["not installed", "new"]: if previousStatus in ["not installed", "new"]: history.markChange(key,'A') else: history.markChange(key,'R') self.populatePluginTree() if infoString[0]: QMessageBox.information(self, infoString[0], infoString[1])
from pydevd import * except ImportError: None WindowsInstaller() else: # Linux Installer try: sys.path.append( "/home/fran/Escritorio/eclipse/plugins/org.python.pydev.core_7.2.1.201904261721/pysrc" ) from pydevd import * except ImportError: None LinuxInstaller() reloadPlugin('QGIS_FMV') iface.messageBar().pushMessage( "QGIS FMV", "QGIS Full Motion Video installed correctly!", QGis.Info, 3) QApplication.restoreOverrideCursor() except Exception as e: iface.messageBar().pushMessage( "QGIS FMV", "Ooops! QGIS Full Motion Video instalation failed!", QGis.Warning, 3) QApplication.restoreOverrideCursor() None def classFactory(iface): from .QgsFmv import Fmv return Fmv(iface)
from pydevd import * except ImportError: None WindowsInstaller() else: # Linux Installer try: sys.path.append( "/home/fragalop/.eclipse/360744286_linux_gtk_x86_64/plugins/org.python.pydev.core_8.1.0.202012051215/pysrc" ) from pydevd import * except ImportError: None LinuxInstaller() reloadPlugin("QGIS_FMV") iface.messageBar().pushMessage( "QGIS FMV", "QGIS Full Motion Video installed correctly!", QGis.Info, 3 ) QApplication.restoreOverrideCursor() except Exception as e: iface.messageBar().pushMessage( "QGIS FMV", "Ooops! QGIS Full Motion Video instalation failed!", QGis.Warning, 3 ) QApplication.restoreOverrideCursor() None def classFactory(iface): from .QgsFmv import Fmv
def installFromZipFile(self, filePath): if not os.path.isfile(filePath): return settings = QgsSettings() settings.setValue(settingsGroup + '/lastZipDirectory', QFileInfo(filePath).absoluteDir().absolutePath()) with zipfile.ZipFile(filePath, 'r') as zf: pluginName = os.path.split(zf.namelist()[0])[0] pluginFileName = os.path.splitext(os.path.basename(filePath))[0] if not pluginName: msg_box = QMessageBox() msg_box.setIcon(QMessageBox.Warning) msg_box.setWindowTitle(self.tr("QGIS Python Install from ZIP Plugin Installer")) msg_box.setText(self.tr("The Zip file is not a valid QGIS python plugin. No root folder was found inside.")) msg_box.setStandardButtons(QMessageBox.Ok) more_info_btn = msg_box.addButton(self.tr("More Information"), QMessageBox.HelpRole) msg_box.exec() if msg_box.clickedButton() == more_info_btn: QgsHelp.openHelp("plugins/plugins.html#the-install-from-zip-tab") return pluginsDirectory = qgis.utils.home_plugin_path if not QDir(pluginsDirectory).exists(): QDir().mkpath(pluginsDirectory) pluginDirectory = QDir.cleanPath(os.path.join(pluginsDirectory, pluginName)) # If the target directory already exists as a link, # remove the link without resolving QFile(pluginDirectory).remove() password = None infoString = None success = False keepTrying = True while keepTrying: try: # Test extraction. If fails, then exception will be raised and no removing occurs unzip(filePath, pluginsDirectory, password) # Removing old plugin files if exist removeDir(pluginDirectory) # Extract new files unzip(filePath, pluginsDirectory, password) keepTrying = False success = True except Exception as e: success = False if 'password' in str(e): infoString = self.tr('Aborted by user') if 'Bad password' in str(e): msg = self.tr('Wrong password. Please enter a correct password to the zip file.') else: msg = self.tr('The zip file is encrypted. Please enter password.') # Display a password dialog with QgsPasswordLineEdit dlg = QDialog() dlg.setWindowTitle(self.tr('Enter password')) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal) buttonBox.rejected.connect(dlg.reject) buttonBox.accepted.connect(dlg.accept) lePass = QgsPasswordLineEdit() layout = QVBoxLayout() layout.addWidget(QLabel(msg)) layout.addWidget(lePass) layout.addWidget(buttonBox) dlg.setLayout(layout) keepTrying = dlg.exec_() password = lePass.text() else: infoString = self.tr("Failed to unzip the plugin package\n{}.\nProbably it is broken".format(filePath)) keepTrying = False if success: updateAvailablePlugins() self.processDependencies(pluginName) loadPlugin(pluginName) plugins.getAllInstalled() plugins.rebuild() if settings.contains('/PythonPlugins/' + pluginName): if settings.value('/PythonPlugins/' + pluginName, False, bool): startPlugin(pluginName) reloadPlugin(pluginName) else: unloadPlugin(pluginName) loadPlugin(pluginName) else: if startPlugin(pluginName): settings.setValue('/PythonPlugins/' + pluginName, True) self.exportPluginsToManager() msg = "<b>%s</b>" % self.tr("Plugin installed successfully") else: msg = "<b>%s:</b> %s" % (self.tr("Plugin installation failed"), infoString) level = Qgis.Info if success else Qgis.Critical iface.pluginManagerInterface().pushMessage(msg, level)
def on_webViewProcessingStatus_loadFinished(self): """Task done""" QgsMessageLog.logMessage('Load results', tag="CropRows Generator", level=QgsMessageLog.INFO) self.dlg.statusBarProcessing2.setValue(60) xmlCropRowsResultsProcessing = (os.path.join( self.dlg.inputSharedFolderPath.text(), 'results', ('results_' + self.dlg.xmlCoreFile.text()))) #check if result file exists QgsMessageLog.logMessage('XML Result File: ' + str(xmlCropRowsResultsProcessing), tag="CropRows Generator", level=QgsMessageLog.INFO) QgsMessageLog.logMessage('results_' + self.dlg.xmlCoreFile.text(), tag="CropRows Generator", level=QgsMessageLog.INFO) self.dlg.statusBarProcessing2.setValue(65) if (os.path.exists(xmlCropRowsResultsProcessing) == False): #print("No croprows result file found !") QgsMessageLog.logMessage('No croprows result file found !', tag="CropRows Generator", level=QgsMessageLog.INFO) else: source = open(xmlCropRowsResultsProcessing, 'rb') tree = ET.parse(source) root = tree.getroot() for filexml in root.findall('filename'): resultVectorialFile = filexml.find('result').text resultVectorialBufferFile = filexml.find('buffer').text #print(resultVectorialFile) QgsMessageLog.logMessage(str(resultVectorialFile), tag="CropRows Generator", level=QgsMessageLog.INFO) QgsMessageLog.logMessage(str(resultVectorialBufferFile), tag="CropRows Generator", level=QgsMessageLog.INFO) resultTileFile = filexml.find('tile').text #print(resultTileFile) QgsMessageLog.logMessage(str(resultTileFile), tag="CropRows Generator", level=QgsMessageLog.INFO) self.dlg.statusBarProcessing2.setValue(60) #load result into qgis temporalPath = self.dlg.inputSharedFolderPath.text().replace( "/", "\\") outputFileMaskPath = os.path.join(temporalPath, "results", resultVectorialFile) outputFileMaskBufferPath = os.path.join( temporalPath, "results", resultVectorialBufferFile) maskVectorLayerExported = QgsVectorLayer( outputFileMaskPath, "croprows_lines", "ogr") maskVectorLayerBufferExported = QgsVectorLayer( outputFileMaskBufferPath, "croprows_lines_buffer", "ogr") self.dlg.statusBarProcessing2.setValue(70) #style for croprows lines result shapefile styleCropRows = os.path.join( (os.path.dirname(os.path.abspath(__file__))), 'styles', 'croprows_style_croplines.qml') maskVectorLayerExported.loadNamedStyle(styleCropRows) QgsMapLayerRegistry.instance().addMapLayer( maskVectorLayerExported) self.dlg.statusBarProcessing2.setValue(80) #style for buffer croprows lines result shapefile styleCropRowsBuf = os.path.join( (os.path.dirname(os.path.abspath(__file__))), 'styles', 'croprows_style_buffer.qml') maskVectorLayerBufferExported.loadNamedStyle(styleCropRowsBuf) QgsMapLayerRegistry.instance().addMapLayer( maskVectorLayerBufferExported) self.dlg.statusBarProcessing2.setValue(85) outputFileTilePath = os.path.join(temporalPath, "results", resultTileFile) maskVectorLayerTileExported = QgsVectorLayer( outputFileTilePath, "croprows_tiles", "ogr") self.dlg.statusBarProcessing2.setValue(90) #style for croprows tiles geojson styleTiles = os.path.join( (os.path.dirname(os.path.abspath(__file__))), 'styles', 'croprows_style_tileindex.qml') maskVectorLayerTileExported.loadNamedStyle(styleTiles) QgsMapLayerRegistry.instance().addMapLayer( maskVectorLayerTileExported) self.dlg.outputfilename.setText(str(outputFileMaskPath)) self.dlg.statusBarProcessing2.setValue(100) source.close() del source QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor) QMessageBox.information( None, 'Message !', "Crop Rows Generation Done !<br><b>Check Crop Rows Results ! <b/>", QMessageBox.Ok) self.dlg.close() reloadPlugin('PACropRows')
def run(self): """ This prepares the user interface of the plugin and the performs the events once "OK" is clicked. :return: """ # Reloading the plugin reloadPlugin('AssimilaDatacCube') # Removes raster base map layers (name: tmp) for i in QgsProject.instance().mapLayersByName("tmp"): QgsProject.instance().removeMapLayer(i) # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when # the plugin is started if self.first_start == True: self.first_start = False self.dlg = AssimilaDatacCubeDialog(self.iface) # Displays map on widget canvas self.display_map() # If there exists a shapefile on the canvas then will get coordinates # from that polygon #self.use_shapefile_layer() # Clears the values from previous run self.dlg.lineEdit.clear() #keyfile self.dlg.lineEdit_2.clear() #rasterfile # Displays key file path location self.key_file = os.path.join(expanduser("~"), "Documents", ".assimila_dq") self.dlg.lineEdit.insert(self.key_file) # Display default raster file path location """ Not using temporary location due to permissioin error if you read the path from the lineEdit. Use tempfile.gettempdir to access temporary directory without permission error. raster_file = "Users\Jenny\AppData\Local\Temp" #default_temp_path = f"{tempfile.gettempdir()}/{filename}.nc" """ raster_file = os.path.join(expanduser("~"), "Documents") self.dlg.lineEdit_2.insert(raster_file) # Display dropdowns for products # Only runs on the first run as the products_comboBox is empty # Instead of clearing the products combobox and then appending everytime # Only searches for products once if self.dlg.products_comboBox.currentIndex() == -1: products = Search.products().name.tolist() self.dlg.products_comboBox.setDuplicatesEnabled(False) self.dlg.products_comboBox.addItems(products) # Display dropdown for subproducts # Defaulting 1st item Subprodusct is 'rfe' self.dlg.subproducts_comboBox.addItem('rfe') # For updating the subproduct self.dlg.products_comboBox.currentTextChanged\ .connect(self.subproduct_selectionchange) # Removing default subproduct value of 'rfe' self.dlg.subproducts_comboBox.removeItem(1) # Links the Radio buttons and datetime widgets self.dlg.multi_radioButton.toggled\ .connect(lambda: self.radio_btn_state(self.dlg.single_radioButton, self.dlg.dateTimeEdit_1, self.dlg.dateTimeEdit_2)) # Links the radio buttons to their actions once clicked, # radioButtons must be connected first before checking # their status by calling get_change() self.dlg.nesw_radioButton.toggled\ .connect(lambda: self.get_change(self.dlg.nesw_radioButton, self.on_nesw_radioButton_clicked)) self.dlg.set_canvas_radioButton.toggled\ .connect(lambda: self.get_change( self.dlg.set_canvas_radioButton, self.on_set_canvas_radioButton_clicked)) self.dlg.search_tile_radioButton.toggled\ .connect(lambda: self.get_change( self.dlg.search_tile_radioButton, self.on_search_tile_radioButton_clicked)) self.dlg.shapefile_radioButton.toggled\ .connect(lambda: self.get_change( self.dlg.shapefile_radioButton, self.on_shapefile_radioButton_clicked )) # Show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # Runs when OK button is pressed if result: # runs process using values in widgets product = (self.dlg.products_comboBox.currentText()).lower() #print(f"The product being run is {product}") subproduct = self.dlg.subproducts_comboBox.currentText() #print(f"The subproduct being run is {subproduct}") north = float(self.dlg.N_box.displayText()) #print('N: ' + str(north)) east = float(self.dlg.E_box.displayText()) #print('E: ' + str(east)) south = float(self.dlg.S_box.displayText()) #print('S: ' + str(south)) west = float(self.dlg.W_box.displayText()) #print('W: ' + str(west)) # Format start and end dates and hour for datecube start = self.dlg.dateTimeEdit_1.dateTime()\ .toString("yyyy-MM-ddTHH:00:00") if self.dlg.single_radioButton.isChecked(): end = start # Perform check method for d1 self.check(north, east, south, west, self.dlg.dateTimeEdit_1.dateTime(), self.dlg.dateTimeEdit_1.dateTime()) else: end = self.dlg.dateTimeEdit_2.dateTime()\ .toString("yyyy-MM-ddTHH:00:00") # Perform check method for d1 d2 self.check(north, east, south, west, self.dlg.dateTimeEdit_1.dateTime(), self.dlg.dateTimeEdit_2.dateTime()) try: # Get Xarray from datacube y = self.get_data_from_datacube_nesw(product, subproduct, north, east, south, west, start, end) # Write Xarray to file self.create_raster_file(product, subproduct, north, east, south, west, y) except Exception as e: print( "Wrong keyfile location or contact Assimila for key file." + str(e)) pass
def installFromZipFile(self, filePath): if not os.path.isfile(filePath): return settings = QgsSettings() settings.setValue(settingsGroup + '/lastZipDirectory', QFileInfo(filePath).absoluteDir().absolutePath()) with zipfile.ZipFile(filePath, 'r') as zf: pluginName = os.path.split(zf.namelist()[0])[0] pluginFileName = os.path.splitext(os.path.basename(filePath))[0] pluginsDirectory = qgis.utils.home_plugin_path if not QDir(pluginsDirectory).exists(): QDir().mkpath(pluginsDirectory) pluginDirectory = QDir.cleanPath(os.path.join(pluginsDirectory, pluginName)) # If the target directory already exists as a link, # remove the link without resolving QFile(pluginDirectory).remove() password = None infoString = None success = False keepTrying = True while keepTrying: try: # Test extraction. If fails, then exception will be raised and no removing occurs unzip(filePath, pluginsDirectory, password) # Removing old plugin files if exist removeDir(pluginDirectory) # Extract new files unzip(filePath, pluginsDirectory, password) keepTrying = False success = True except Exception as e: success = False if 'password' in str(e): infoString = self.tr('Aborted by user') if 'Bad password' in str(e): msg = self.tr('Wrong password. Please enter a correct password to the zip file.') else: msg = self.tr('The zip file is encrypted. Please enter password.') # Display a password dialog with QgsPasswordLineEdit dlg = QDialog() dlg.setWindowTitle(self.tr('Enter password')) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal) buttonBox.rejected.connect(dlg.reject) buttonBox.accepted.connect(dlg.accept) lePass = QgsPasswordLineEdit() layout = QVBoxLayout() layout.addWidget(QLabel(msg)) layout.addWidget(lePass) layout.addWidget(buttonBox) dlg.setLayout(layout) keepTrying = dlg.exec_() password = lePass.text() else: infoString = self.tr("Failed to unzip the plugin package\n{}.\nProbably it is broken".format(filePath)) keepTrying = False if success: updateAvailablePlugins() loadPlugin(pluginName) plugins.getAllInstalled() plugins.rebuild() self.exportPluginsToManager() if settings.contains('/PythonPlugins/' + pluginName): if settings.value('/PythonPlugins/' + pluginName, False, bool): startPlugin(pluginName) reloadPlugin(pluginName) else: unloadPlugin(pluginName) loadPlugin(pluginName) else: if startPlugin(pluginName): settings.setValue('/PythonPlugins/' + pluginName, True) msg = "<b>%s</b>" % self.tr("Plugin installed successfully") else: msg = "<b>%s:</b> %s" % (self.tr("Plugin installation failed"), infoString) level = Qgis.Info if success else Qgis.Critical iface.pluginManagerInterface().pushMessage(msg, level)
def uninstallPlugin(self, key): """ uninstall currently selected plugin """ plugin = plugins.all()[key] if not plugin: return warning = self.tr( "Are you sure you want to uninstall the following plugin?" ) + "\n(" + plugin["name"] + ")" if plugin["status"] == "orphan" and not plugin["error"]: warning += "\n\n" + self.tr( "Warning: this plugin isn't available in any accessible repository!" ) if QMessageBox.warning(self, self.tr("QGIS Python Plugin Installer"), warning, QMessageBox.Yes, QMessageBox.No) == QMessageBox.No: return # unload the plugin if it's not plugin_installer itself (otherwise, do it after removing its directory): if key != "plugin_installer": try: unloadPlugin(key) except: pass pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/" + plugin["localdir"] result = removeDir(pluginDir) if result: QMessageBox.warning(self, self.tr("Plugin uninstall failed"), result) else: # if the uninstalled plugin is the installer itself, reload it and quit if key == "plugin_installer": if QGIS_15: try: QMessageBox.information( self, self.tr("QGIS Python Plugin Installer"), self. tr("Plugin Installer update uninstalled. Plugin Installer will now close and revert to its primary version. You can find it in the Plugins menu and continue operation." )) reloadPlugin(key) return except: pass else: QMessageBox.information( self, self.tr("QGIS Python Plugin Installer"), self. tr("Plugin Installer update uninstalled. Please restart QGIS in order to load its primary version." )) # safe remove try: unloadPlugin(plugin["localdir"]) except: pass try: exec("plugins[%s].unload()" % plugin["localdir"]) exec("del plugins[%s]" % plugin["localdir"]) except: pass try: exec("del sys.modules[%s]" % plugin["localdir"]) except: pass plugins.getAllInstalled() plugins.rebuild() self.populatePluginTree() if QGIS_14: QMessageBox.information( self, self.tr("Plugin uninstalled successfully"), self.tr("Plugin uninstalled successfully")) else: QMessageBox.information( self, self.tr("Plugin uninstalled successfully"), self. tr("Python plugin uninstalled. Note that you may need to restart Quantum GIS in order to remove it completely." )) history.markChange(key, 'D')
def installPlugin(self, key, quiet=False): """ install currently selected plugin """ infoString = ('', '') plugin = plugins.all()[key] previousStatus = plugin["status"] if not plugin: return if plugin["status"] == "newer" and not plugin[ "error"]: # ask for confirmation if user downgrades an usable plugin if QMessageBox.warning( self, self.tr("QGIS Python Plugin Installer"), self. tr("Are you sure you want to downgrade the plugin to the latest available version? The installed one is newer!" ), QMessageBox.Yes, QMessageBox.No) == QMessageBox.No: return dlg = QgsPluginInstallerInstallingDialog(self, plugin) dlg.exec_() if dlg.result(): infoString = (self.tr("Plugin installation failed"), dlg.result()) elif not QDir( QDir.cleanPath(QgsApplication.qgisSettingsDirPath() + "/python/plugins/" + key)).exists(): infoString = ( self.tr("Plugin has disappeared"), self. tr("The plugin seems to have been installed but I don't know where. Probably the plugin package contained a wrong named directory.\nPlease search the list of installed plugins. I'm nearly sure you'll find the plugin there, but I just can't determine which of them it is. It also means that I won't be able to determine if this plugin is installed and inform you about available updates. However the plugin may work. Please contact the plugin author and submit this issue." )) QApplication.setOverrideCursor(Qt.WaitCursor) plugins.getAllInstalled() plugins.rebuild() QApplication.restoreOverrideCursor() else: if QGIS_14: if QGIS_15: # update the list of plugins in plugin handling routines updateAvailablePlugins() # try to load the plugin loadPlugin(plugin["localdir"]) else: # QGIS < 1.4 try: exec("sys.path_importer_cache.clear()") exec("import %s" % plugin["localdir"]) exec("reload (%s)" % plugin["localdir"]) except: pass plugins.getAllInstalled(testLoad=True) plugins.rebuild() plugin = plugins.all()[key] if not plugin["error"]: if previousStatus in ["not installed", "new"]: if QGIS_14: # plugins can be started in python from QGIS >= 1.4 infoString = (self.tr("Plugin installed successfully"), self.tr("Plugin installed successfully")) settings = QSettings() settings.setValue( "/PythonPlugins/" + plugin["localdir"], QVariant(True)) startPlugin(plugin["localdir"]) else: infoString = ( self.tr("Plugin installed successfully"), self. tr("Python plugin installed.\nNow you need to enable it in Plugin Manager." )) else: if QGIS_15: # plugins can be reloaded on the fly in QGIS >= 1.5 settings = QSettings() if key != 'plugin_installer' and settings.value( "/PythonPlugins/" + key ).toBool( ): # plugin will be reloaded on the fly only if currently loaded infoString = ( self.tr("Plugin reinstalled successfully"), self.tr("Plugin reinstalled successfully")) reloadPlugin(key) else: infoString = ( self.tr("Plugin reinstalled successfully"), self. tr("Python plugin reinstalled.\nYou need to restart Quantum GIS in order to reload it." )) else: infoString = ( self.tr("Plugin reinstalled successfully"), self. tr("Python plugin reinstalled.\nYou need to restart Quantum GIS in order to reload it." )) if quiet: infoString = (None, None) else: if plugin["error"] == "incompatible": message = self.tr( "The plugin is designed for a newer version of Quantum GIS. The minimum required version is:" ) message += " <b>" + plugin["error_details"] + "</b>" elif plugin["error"] == "dependent": message = self.tr( "The plugin depends on some components missing on your system. You need to install the following Python module in order to enable it:" ) message += "<b> " + plugin["error_details"] + "</b>" else: message = self.tr("The plugin is broken. Python said:") message += "<br><b>" + plugin["error_details"] + "</b>" dlg = QgsPluginInstallerPluginErrorDialog(self, message) dlg.exec_() if dlg.result(): # revert installation plugins.getAllInstalled() plugins.rebuild() pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath( )).path() + "/python/plugins/" + plugin["localdir"] removeDir(pluginDir) if QDir(pluginDir).exists(): infoString = (self.tr("Plugin uninstall failed"), result) try: exec("sys.path_importer_cache.clear()") exec("import %s" % plugin["localdir"]) exec("reload (%s)" % plugin["localdir"]) except: pass else: try: exec("del sys.modules[%s]" % plugin["localdir"]) except: pass plugins.getAllInstalled() plugins.rebuild() if plugins.all().has_key(key) and not plugins.all()[key]["status"] in [ "not installed", "new" ]: if previousStatus in ["not installed", "new"]: history.markChange(key, 'A') else: history.markChange(key, 'R') self.populatePluginTree() if infoString[0]: QMessageBox.information(self, infoString[0], infoString[1])
def reload_plugin(self): """Reload Plugin""" reloadPlugin('PACropRows')
def cancelWizard(self): QgsMessageLog.logMessage('Cancel Wizard') self.dlg.close() reloadPlugin('PACropRows')
def installPlugin(self, key, quiet=False): """ Install given plugin """ error = False infoString = ('', '') plugin = plugins.all()[key] previousStatus = plugin["status"] if not plugin: return if plugin["status"] == "newer" and not plugin["error"]: # ask for confirmation if user downgrades an usable plugin if QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Are you sure you want to downgrade the plugin to the latest available version? The installed one is newer!"), QMessageBox.Yes, QMessageBox.No) == QMessageBox.No: return dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(), plugin) dlg.exec_() if dlg.result(): error = True infoString = (self.tr("Plugin installation failed"), dlg.result()) elif not QDir(qgis.utils.home_plugin_path + "/" + key).exists(): error = True infoString = (self.tr("Plugin has disappeared"), self.tr("The plugin seems to have been installed but I don't know where. Probably the plugin package contained a wrong named directory.\nPlease search the list of installed plugins. I'm nearly sure you'll find the plugin there, but I just can't determine which of them it is. It also means that I won't be able to determine if this plugin is installed and inform you about available updates. However the plugin may work. Please contact the plugin author and submit this issue.")) QApplication.setOverrideCursor(Qt.WaitCursor) plugins.getAllInstalled() plugins.rebuild() self.exportPluginsToManager() QApplication.restoreOverrideCursor() else: QApplication.setOverrideCursor(Qt.WaitCursor) # update the list of plugins in plugin handling routines updateAvailablePlugins() # try to load the plugin loadPlugin(plugin["id"]) plugins.getAllInstalled(testLoad=True) plugins.rebuild() plugin = plugins.all()[key] if not plugin["error"]: if previousStatus in ["not installed", "new"]: infoString = (self.tr("Plugin installed successfully"), "") if startPlugin(plugin["id"]): settings = QgsSettings() settings.setValue("/PythonPlugins/" + plugin["id"], True) else: settings = QgsSettings() if settings.value("/PythonPlugins/" + key, False, type=bool): # plugin will be reloaded on the fly only if currently loaded reloadPlugin(key) # unloadPlugin + loadPlugin + startPlugin infoString = (self.tr("Plugin reinstalled successfully"), "") else: unloadPlugin(key) # Just for a case. Will exit quietly if really not loaded loadPlugin(key) infoString = (self.tr("Plugin reinstalled successfully"), self.tr("Python plugin reinstalled.\nYou need to restart QGIS in order to reload it.")) if quiet: infoString = (None, None) QApplication.restoreOverrideCursor() else: QApplication.restoreOverrideCursor() if plugin["error"] == "incompatible": message = self.tr("The plugin is not compatible with this version of QGIS. It's designed for QGIS versions:") message += " <b>" + plugin["error_details"] + "</b>" elif plugin["error"] == "dependent": message = self.tr("The plugin depends on some components missing on your system. You need to install the following Python module in order to enable it:") message += "<b> " + plugin["error_details"] + "</b>" else: message = self.tr("The plugin is broken. Python said:") message += "<br><b>" + plugin["error_details"] + "</b>" dlg = QgsPluginInstallerPluginErrorDialog(iface.mainWindow(), message) dlg.exec_() if dlg.result(): # revert installation pluginDir = qgis.utils.home_plugin_path + "/" + plugin["id"] result = removeDir(pluginDir) if QDir(pluginDir).exists(): error = True infoString = (self.tr("Plugin uninstall failed"), result) try: exec("sys.path_importer_cache.clear()") exec("import %s" % plugin["id"]) exec("reload (%s)" % plugin["id"]) except: pass else: try: exec("del sys.modules[%s]" % plugin["id"]) except: pass plugins.getAllInstalled() plugins.rebuild() self.exportPluginsToManager() if infoString[0]: level = error and QgsMessageBar.CRITICAL or QgsMessageBar.INFO msg = "<b>%s:</b>%s" % (infoString[0], infoString[1]) iface.pluginManagerInterface().pushMessage(msg, level)
def closeEvent(self, QCloseEvent): reloadPlugin('StormClean')
def installPlugin(self, key, quiet=False): """ Install given plugin """ error = False infoString = ('', '') plugin = plugins.all()[key] previousStatus = plugin["status"] if not plugin: return if plugin["status"] == "newer" and not plugin["error"]: # ask for confirmation if user downgrades an usable plugin if QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Are you sure you want to downgrade the plugin to the latest available version? The installed one is newer!"), QMessageBox.Yes, QMessageBox.No) == QMessageBox.No: return dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(), plugin) dlg.exec_() if dlg.result(): error = True infoString = (self.tr("Plugin installation failed"), dlg.result()) elif not QDir(qgis.utils.home_plugin_path + "/" + key).exists(): error = True infoString = (self.tr("Plugin has disappeared"), self.tr("The plugin seems to have been installed but I don't know where. Probably the plugin package contained a wrong named directory.\nPlease search the list of installed plugins. I'm nearly sure you'll find the plugin there, but I just can't determine which of them it is. It also means that I won't be able to determine if this plugin is installed and inform you about available updates. However the plugin may work. Please contact the plugin author and submit this issue.")) QApplication.setOverrideCursor(Qt.WaitCursor) plugins.getAllInstalled() plugins.rebuild() self.exportPluginsToManager() QApplication.restoreOverrideCursor() else: QApplication.setOverrideCursor(Qt.WaitCursor) # update the list of plugins in plugin handling routines updateAvailablePlugins() # try to load the plugin loadPlugin(plugin["id"]) plugins.getAllInstalled(testLoad=True) plugins.rebuild() plugin = plugins.all()[key] if not plugin["error"]: if previousStatus in ["not installed", "new"]: infoString = (self.tr("Plugin installed successfully"), "") if startPlugin(plugin["id"]): settings = QSettings() settings.setValue("/PythonPlugins/" + plugin["id"], True) else: settings = QSettings() if settings.value("/PythonPlugins/" + key, False, type=bool): # plugin will be reloaded on the fly only if currently loaded reloadPlugin(key) # unloadPlugin + loadPlugin + startPlugin infoString = (self.tr("Plugin reinstalled successfully"), "") else: unloadPlugin(key) # Just for a case. Will exit quietly if really not loaded loadPlugin(key) infoString = (self.tr("Plugin reinstalled successfully"), self.tr("Python plugin reinstalled.\nYou need to restart QGIS in order to reload it.")) if quiet: infoString = (None, None) QApplication.restoreOverrideCursor() else: QApplication.restoreOverrideCursor() if plugin["error"] == "incompatible": message = self.tr("The plugin is not compatible with this version of QGIS. It's designed for QGIS versions:") message += " <b>" + plugin["error_details"] + "</b>" elif plugin["error"] == "dependent": message = self.tr("The plugin depends on some components missing on your system. You need to install the following Python module in order to enable it:") message += "<b> " + plugin["error_details"] + "</b>" else: message = self.tr("The plugin is broken. Python said:") message += "<br><b>" + plugin["error_details"] + "</b>" dlg = QgsPluginInstallerPluginErrorDialog(iface.mainWindow(), message) dlg.exec_() if dlg.result(): # revert installation pluginDir = qgis.utils.home_plugin_path + "/" + plugin["id"] result = removeDir(pluginDir) if QDir(pluginDir).exists(): error = True infoString = (self.tr("Plugin uninstall failed"), result) try: exec ("sys.path_importer_cache.clear()") exec ("import %s" % plugin["id"]) exec ("reload (%s)" % plugin["id"]) except: pass else: try: exec ("del sys.modules[%s]" % plugin["id"]) except: pass plugins.getAllInstalled() plugins.rebuild() self.exportPluginsToManager() if infoString[0]: level = error and QgsMessageBar.CRITICAL or QgsMessageBar.INFO msg = "<b>%s:</b>%s" % (infoString[0], infoString[1]) iface.pluginManagerInterface().pushMessage(msg, level)
def cancelWizard(self): QgsMessageLog.logMessage('Cancel Wizard', tag="CropRows Generator", level=QgsMessageLog.INFO) self.dlg.close() reloadPlugin('PACropRows')