def initialize(self): aux_path_plugin = 'python/plugins/' + constants.INFORME_PARCELAS_NAME qgisUserDbFilePath = QgsApplication.qgisUserDbFilePath() self.path_plugin = os.path.join( QFileInfo(QgsApplication.qgisUserDbFilePath()).path(), aux_path_plugin) path_file_qsettings = self.path_plugin + '/' + constants.INFORME_PARCELAS_SETTINGS_FILE_NAME self.settings = QSettings(path_file_qsettings, QSettings.IniFormat) self.lastPath = self.settings.value("last_path") if not self.lastPath: self.lastPath = QDir.currentPath() self.settings.setValue("last_path", self.lastPath) self.settings.sync() #Cargamos la capa para obtener la información layer = QgsVectorLayer( "C:/Informe_Parcelas/Poligonos Informe/Pol01_Fincas_Nuevos_Propietarios.shp", "Pol01_Fincas", "ogr") if not layer: print "Layer failed to load!" QgsMapLayerRegistry.instance().addMapLayer(layer) self.selec_PropietarioPushButton.setEnabled(True) self.selec_ParcelaPushButton.setEnabled(True) self.n_parcelaLineEdit.setEnabled(False) self.n_propietarioLineEdit.setEnabled(False) self.csvcFileLineEdit.setEnabled(False) self.csviFileLineEdit.setEnabled(False) self.kmlFileLineEdit.setEnabled(False) #self.listadoPushButton.setEnabled(False) #self.planoPushButton.setEnabled(False) #Selección para información e informes a generar QObject.connect(self.selec_ParcelaPushButton, SIGNAL("clicked(bool)"), self.selec_Parcela) QObject.connect(self.selec_PropietarioPushButton, SIGNAL("clicked(bool)"), self.selec_Propietario) QObject.connect(self.csvcFilePushButton, SIGNAL("clicked(bool)"), self.selec_CsvcFile) QObject.connect(self.csviFilePushButton, SIGNAL("clicked(bool)"), self.selec_CsviFile) QObject.connect(self.kmlFilePushButton, SIGNAL("clicked(bool)"), self.selec_KmlFile) #QObject.connect(self.listadoPushButton,SIGNAL("clicked(bool)"),self.getListado) #QObject.connect(self.planoPushButton,SIGNAL("clicked(bool)"),self.getPlano) QObject.connect(self.terminarPushButton, SIGNAL("clicked(bool)"), self.terminar) self.pointNumbers = [] self.num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')
def removeDir(path): result = QString() 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 = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins" if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) return result
def __init__(self, iface): self.dock = None self.results = [] # Save reference to the QGIS interface self.iface = iface self.iface.newProjectCreated.connect(self._hideMarker) self.iface.projectRead.connect(self._hideMarker) self.canvas = self.iface.mapCanvas() self.marker = QgsVertexMarker(self.iface.mapCanvas()) self.marker.setIconSize(20) self.marker.setPenWidth(3) self.marker.setIconType(QgsVertexMarker.ICON_CROSS) self.marker.hide() # Create the dialog and keep reference self.widget = gazetteerSearchDialog() self.widget.runSearch.connect(self.runSearch) self.widget.ui.clearButton.pressed.connect(self.clearResults) self.widget.zoomRequested.connect(self.zoomTo) # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/gazetteersearch" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/gazetteersearch_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): try: debug() except: print 'Debugger not enabled' # save reference to the QGIS interface # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = \ QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + \ "/python/plugins/qchainage" # initialize locale locale_path = "" locale = QSettings().value("locale/userLocale")[0:2] if QFileInfo(self.plugin_dir).exists(): locale_path = self.plugin_dir + "/i18n/qchainage_" + locale + ".qm" if QFileInfo(locale_path).exists(): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): Plugin.__init__(self, iface, "PointsInPolygons") userPluginPath = QtCore.QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + '/python/plugins/points_in_polygons' systemPluginPath = QgsApplication.prefixPath() + '/python/plugins/points_in_polygons' overrideLocale = QtCore.QSettings().value('locale/overrideFlag', False, type=bool) if not overrideLocale: localeFullName = QtCore.QLocale.system().name()[:2] else: localeFullName = QtCore.QSettings().value("locale/userLocale", "") if QtCore.QFileInfo(userPluginPath).exists(): translationPath = userPluginPath + '/i18n/pointsinpolygons_' + localeFullName + '.qm' self.pluginPath = userPluginPath else: translationPath = systemPluginPath + '/i18n/pointsinpolygons_' + localeFullName + '.qm' self.pluginPath = systemPluginPath self.localePath = translationPath if QtCore.QFileInfo(self.localePath).exists(): self.translator = QtCore.QTranslator() self.translator.load(self.localePath) QgsApplication.installTranslator(self.translator) self.pointLayerName = "" self.polygonLayerName = "" self.fieldName = ""
def getTranslate(namePlugin, nameDir=None): if nameDir is None: nameDir = namePlugin pluginPath = "python/plugins/{}".format(nameDir) userPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() userPluginPath = "{0}{1}".format(userPath, pluginPath) systemPath = QgsApplication.prefixPath() systemPluginPath = "{0}/{1}".format(systemPath, pluginPath) overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool) localeFullName = QLocale.system().name( ) if not overrideLocale else QSettings().value('locale/userLocale', '') qmPathFile = "/i18n/{0}_{1}.qm".format(namePlugin, localeFullName) pp = userPluginPath if QFileInfo( userPluginPath).exists() else systemPluginPath translationFile = "{0}{1}".format(pp, qmPathFile) if QFileInfo(translationFile).exists(): translator = QTranslator() translator.load(translationFile) QCoreApplication.installTranslator(translator) return translator
def removeDir(path): result = QString() 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 = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins" if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) return result
def requestFinished(self, requestId, state): if requestId != self.httpGetId: return self.buttonBox.setEnabled(False) if state: self.mResult = self.http.errorString() self.reject() return self.file.close() pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins" tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir+QString(QDir.separator())+self.plugin["localdir"]).remove() try: un = unzip() un.extract(unicode(tmpPath), unicode(pluginDir)) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath(pluginDir+"/"+self.plugin["localdir"])) # remove old plugin if exists un.extract(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr("Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:") + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def __init__(self, iface): self.dock = None self.results = [] # Save reference to the QGIS interface self.iface = iface self.iface.newProjectCreated.connect(self._hideMarker) self.iface.projectRead.connect(self._hideMarker) self.canvas = self.iface.mapCanvas() self.marker = QgsVertexMarker(self.iface.mapCanvas()) self.marker.setIconSize(20) self.marker.setPenWidth(3) self.marker.setIconType(QgsVertexMarker.ICON_CROSS) self.marker.hide() # Create the dialog and keep reference self.widget = gazetteerSearchDialog() self.widget.runSearch.connect(self.runSearch) self.widget.ui.clearButton.pressed.connect(self.clearResults) self.widget.zoomRequested.connect(self.zoomTo) # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/gazetteersearch" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/gazetteersearch_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/geometry_copier" # initialize locale locale_path = "" if sip.getapi("QVariant") > 1: # new API style locale = QSettings().value("locale/userLocale")[0:2] else: # the old API style locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): locale_path = self.plugin_dir + "/i18n/geometry_copier_" + locale + ".qm" if QFileInfo(locale_path).exists(): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self._geom_buffer = None
def userFolder(): userDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() \ + '/processing' if not QDir(userDir).exists(): QDir().mkpath(userDir) return unicode(QDir.toNativeSeparators(userDir))
def defaultOutputFolder(): folder = os.path.join(os.path.dirname(QgsApplication.qgisUserDbFilePath()), "processing", "outputs") if not QDir(folder).exists(): QDir().mkpath(folder) return unicode(QDir.toNativeSeparators(folder))
def get_QuickOSM_folder(): """ Get the user folder, ~/.qgis2/QuickOSM on linux for instance @rtype: str @return: path """ folder = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + 'QuickOSM' return unicode(QDir.toNativeSeparators(folder))
def get_QuickOSM_folder(): """ Get the user folder, ~/.qgis2/QuickOSM on linux for instance @rtype: str @return: path """ folder = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "QuickOSM" return unicode(QDir.toNativeSeparators(folder))
def _getCursor(self): dbpath = QgsApplication.qgisUserDbFilePath() if not hasattr(Transformation, '__connection'): try: Transformation.__connection = sqlite.connect( unicode(dbpath).encode('utf8')) except sqlite.OperationalError, e: QMessageBox.critical( None, u"Error opening the database", u"Can't open the database %s: %s" % (dbpath, e.args[0])) return
def _populate_bookmarks_list(self): """Read the sqlite database and populate the bookmarks list. If no bookmarks are found, the bookmarks radio button will be disabled and the label will be shown indicating that the user should add bookmarks in QGIS first. Every bookmark are reprojected to mapcanvas crs. """ # Connect to the QGIS sqlite database and check if the table exists. # noinspection PyArgumentList db_file_path = QgsApplication.qgisUserDbFilePath() db = sqlite3.connect(db_file_path) cursor = db.cursor() cursor.execute( 'SELECT COUNT(*) ' 'FROM sqlite_master ' 'WHERE type=\'table\' ' 'AND name=\'tbl_bookmarks\';') number_of_rows = cursor.fetchone()[0] if number_of_rows > 0: cursor.execute( 'SELECT * ' 'FROM tbl_bookmarks;') bookmarks = cursor.fetchall() canvas_srid = self.canvas.mapSettings().destinationCrs().srsid() for bookmark in bookmarks: name = bookmark[1] srid = bookmark[7] rectangle = QgsRectangle( bookmark[3], bookmark[4], bookmark[5], bookmark[6]) if srid != canvas_srid: transform = QgsCoordinateTransform( srid, canvas_srid) try: rectangle = transform.transform(rectangle) except QgsCsException: rectangle = None if rectangle is None or rectangle.isEmpty(): pass self.bookmarks_list.addItem(name, rectangle) if self.bookmarks_list.currentIndex() >= 0: self.create_bookmarks_label.hide() else: self.create_bookmarks_label.show() self.hazard_exposure_bookmark.setDisabled(True) self.bookmarks_list.hide()
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 _populate_bookmarks_list(self): """Read the sqlite database and populate the bookmarks list. Every bookmark are reprojected to mapcanvas crs. """ # Connect to the QGIS sqlite database and check if the table exists. db_file_path = QgsApplication.qgisUserDbFilePath() if not isfile(db_file_path): # If the database does not exist. return try: db = sqlite3.connect(db_file_path) cursor = db.cursor() cursor.execute( 'SELECT COUNT(*) ' 'FROM sqlite_master ' 'WHERE type=\'table\' ' 'AND name=\'tbl_bookmarks\';') number_of_rows = cursor.fetchone()[0] if number_of_rows > 0: cursor.execute( 'SELECT * ' 'FROM tbl_bookmarks;') bookmarks = cursor.fetchall() map_renderer = self.canvas.mapRenderer() canvas_srid = map_renderer.destinationCrs().srsid() for bookmark in bookmarks: name = bookmark[1] srid = bookmark[7] rectangle = QgsRectangle( bookmark[3], bookmark[4], bookmark[5], bookmark[6]) if srid != canvas_srid: transform = QgsCoordinateTransform( srid, canvas_srid) rectangle = transform.transform(rectangle) if rectangle.isEmpty(): pass self.comboBox_bookmarks_list.addItem(name, rectangle) except sqlite3.Error: # If we have any SQL error with SQLite. return
def requestFinished(self): reply = self.sender() self.buttonBox.setEnabled(False) if reply.error() != QNetworkReply.NoError: self.mResult = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mResult += "<br/><br/>" + QCoreApplication.translate( "QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options." ) self.reject() reply.deleteLater() return self.file.open(QFile.WriteOnly) self.file.write(reply.readAll()) self.file.close() self.stateChanged(0) reply.deleteLater() pluginDir = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins" tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir + unicode(QDir.separator()) + self.plugin["id"]).remove() try: unzip( unicode(tmpPath), unicode(pluginDir) ) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath( pluginDir + "/" + self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr( "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:" ) + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def installTranslator( self ): userPluginPath = os.path.join( os.path.dirname( str( QgsApplication.qgisUserDbFilePath() ) ), "python/plugins/SeismicRisk" ) systemPluginPath = os.path.join( str( QgsApplication.prefixPath() ), "python/plugins/SeismicRisk" ) translationPath = '' locale = QSettings().value( "locale/userLocale", type=str ) myLocale = str( locale[0:2] ) if myLocale == 'es': self.language='es' if os.path.exists( userPluginPath ): translationPath = os.path.join( userPluginPath, 'i18n', "AutoFields_" + myLocale + ".qm" ) else: translationPath = os.path.join( systemPluginPath, 'i18n', "AutoFields_" + myLocale + ".qm" ) if QFileInfo( translationPath ).exists(): self.translator = QTranslator() self.translator.load( translationPath ) QCoreApplication.installTranslator( self.translator )
def __init__(self, iface): self.iface = iface self.mapCanvas = iface.mapCanvas() # Initialise the translation environment. userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path()+"/python/plugins/intersectit" systemPluginPath = QgsApplication.prefixPath()+"/share/qgis/python/plugins/intersectit" locale = QSettings().value("locale/userLocale") myLocale = locale[0:2] pluginPath = "" # default case if QFileInfo(userPluginPath).exists(): pluginPath = '{}/i18n/intersectit_{}.qm'.format(userPluginPath, myLocale) elif QFileInfo(systemPluginPath).exists(): pluginPath = '{}/i18n/intersectit_{}.qm'.format(systemPluginPath, myLocale) self.localePath = pluginPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): self.iface = iface self.settings = MySettings() self.mainDialog = MainDialog() # Initialise the translation environment. userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path()+"/python/plugins/qwat" systemPluginPath = QgsApplication.prefixPath()+"/share/qgis/python/plugins/qwat" locale = QSettings().value("locale/userLocale") myLocale = locale[0:2] if QFileInfo(userPluginPath).exists(): pluginPath = userPluginPath+"/i18n/qwat_"+myLocale+".qm" elif QFileInfo(systemPluginPath).exists(): pluginPath = systemPluginPath+"/i18n/qwat_"+myLocale+".qm" self.localePath = pluginPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): """Constructor :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgisInterface """ # Save reference to the QGIS interface self.iface = iface # noinspection PyArgumentList self.user_plugin_dir = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + 'python/plugins' self.plugin_builder_path = os.path.dirname(__file__) # class members self.action = None self.dialog = None self.plugin_path = None
def __init__(self, iface): """Constructor :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # noinspection PyArgumentList self.user_plugin_dir = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + 'python/plugins' self.plugin_builder_path = os.path.dirname(__file__) # class members self.action = None self.dialog = None self.plugin_path = None
def __init__(self, iface): # Save reference to the QGIS interface self.context = zmq.Context() self.iface = iface # initialize plugin directory self.plugin_dir = \ QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + \ "/python/plugins/world_engine" # initialize locale locale_path = "" locale = QSettings().value("locale/userLocale")[0:2] if QFileInfo(self.plugin_dir).exists(): locale_path = self.plugin_dir + "/i18n/world_engine_" + locale + ".qm" if QFileInfo(locale_path).exists(): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface QGisLayers.setInterface(iface) # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/supervisedclassification" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale")[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/supervisedclassification_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): self.iface = iface self.settings = MySettings() self.mainDialog = MainDialog() # Initialise the translation environment. userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/qwat" systemPluginPath = QgsApplication.prefixPath( ) + "/share/qgis/python/plugins/qwat" locale = QSettings().value("locale/userLocale") myLocale = locale[0:2] if QFileInfo(userPluginPath).exists(): pluginPath = userPluginPath + "/i18n/qwat_" + myLocale + ".qm" elif QFileInfo(systemPluginPath).exists(): pluginPath = systemPluginPath + "/i18n/qwat_" + myLocale + ".qm" self.localePath = pluginPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator)
def requestFinished(self, requestId, state): if requestId != self.httpGetId: return self.buttonBox.setEnabled(False) if state: self.mResult = self.http.errorString() self.reject() return self.file.close() pluginDir = QFileInfo( QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins" tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir + QString(QDir.separator()) + self.plugin["localdir"]).remove() try: un = unzip() un.extract( unicode(tmpPath), unicode(pluginDir) ) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath( pluginDir + "/" + self.plugin["localdir"])) # remove old plugin if exists un.extract(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr( "Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:" ) + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface QGisLayers.setInterface(iface) # initialize plugin directory self.plugin_dir = ( QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/supervisedclassification" ) # initialize locale localePath = "" locale = QSettings().value("locale/userLocale")[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/supervisedclassification_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > "4.3.3": QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): # Save reference to the QGIS interface self.outdir = '' self.ilayers = QgsMapLayerRegistry.instance() self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/kuw_filter" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale")[0:5] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/kuw_filter_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = kuw_filterDialog()
def __init__(self, iface): self.iface = iface self.mapCanvas = iface.mapCanvas() # Initialise the translation environment. userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/intersectit" systemPluginPath = QgsApplication.prefixPath( ) + "/share/qgis/python/plugins/intersectit" locale = QSettings().value("locale/userLocale") myLocale = locale[0:2] if QFileInfo(userPluginPath).exists(): pluginPath = '{}/i18n/intersectit_{}.qm'.format( userPluginPath, myLocale) elif QFileInfo(systemPluginPath).exists(): pluginPath = '{}/i18n/intersectit_{}.qm'.format( systemPluginPath, myLocale) self.localePath = pluginPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator)
def uninstallPlugin(self): """ uninstall currently selected plugin """ if not self.treePlugins.currentItem(): return key = plugins.keyByUrl(self.treePlugins.currentItem().toolTip(5)) 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 pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/" + plugin["localdir"] result = removeDir(pluginDir) if result: QMessageBox.warning(self, self.tr("Plugin uninstall failed"), result) else: # safe remove 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 if not plugin["repository"]: plugins.remove(key) else: plugins.setPluginData(key, "status", "not installed") plugins.setPluginData(key, "version_inst", "") plugins.setPluginData(key, "desc_local", "") plugins.setPluginData(key, "error", "") plugins.setPluginData(key, "error_details", "") self.populatePluginTree() 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."))
def __init__(self, iface): self.iface = iface self.mapCanvas = iface.mapCanvas() memLay = MemoryLayers(iface) self.lineLayer = memLay.lineLayer self.pointLayer = memLay.pointLayer # Initialise the translation environment. userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/intersectit" systemPluginPath = QgsApplication.prefixPath( ) + "/share/qgis/python/plugins/intersectit" locale = QSettings().value("locale/userLocale") myLocale = locale[0:2] if QFileInfo(userPluginPath).exists(): pluginPath = userPluginPath + "/i18n/intersectit_" + myLocale + ".qm" elif QFileInfo(systemPluginPath).exists(): pluginPath = systemPluginPath + "/i18n/intersectit_" + myLocale + ".qm" self.localePath = pluginPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator)
def __init__(self, iface): # Save reference to the QGIS interface self.outdir = '' self.ilayers = QgsMapLayerRegistry.instance() self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/kuw_filter" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale")[0:5] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/kuw_filter_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = kuw_filterDialog()
def requestFinished(self): reply = self.sender() self.buttonBox.setEnabled(False) if reply.error() != QNetworkReply.NoError: self.mResult = reply.errorString() if reply.error() == QNetworkReply.OperationCanceledError: self.mResult += "<br/><br/>" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it might be caused by a timeout. In this case consider increasing the connection timeout value in QGIS options.") self.reject() reply.deleteLater() return self.file.open(QFile.WriteOnly) self.file.write( reply.readAll() ) self.file.close() self.stateChanged(0) reply.deleteLater() pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins" tmpPath = self.file.fileName() # make sure that the parent directory exists if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) # if the target directory already exists as a link, remove the link without resolving: QFile(pluginDir+unicode(QDir.separator())+self.plugin["id"]).remove() try: unzip(unicode(tmpPath), unicode(pluginDir)) # test extract. If fails, then exception will be raised and no removing occurs # removing old plugin files if exist removeDir(QDir.cleanPath(pluginDir+"/"+self.plugin["id"])) # remove old plugin if exists unzip(unicode(tmpPath), unicode(pluginDir)) # final extract. except: self.mResult = self.tr("Failed to unzip the plugin package. Probably it's broken or missing from the repository. You may also want to make sure that you have write permission to the plugin directory:") + "\n" + pluginDir self.reject() return try: # cleaning: removing the temporary zip file QFile(tmpPath).remove() except: pass self.close()
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/geometry_copier" # initialize locale locale_path = "" if sip.getapi("QVariant") > 1: # new API style locale = QSettings().value("locale/userLocale")[0:2] else: # the old API style locale = QSettings().value("locale/userLocale").toString()[0:2] if QFileInfo(self.plugin_dir).exists(): locale_path = self.plugin_dir + "/i18n/geometry_copier_" + locale + ".qm" if QFileInfo(locale_path).exists(): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self._geom_buffer = None
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 __init__(self, parent): QDialog.__init__(self, parent) self.setupUi(self) self.reposGroup = "/Qgis/plugin-repos" self.connect(self.lineFilter, SIGNAL("textChanged (QString)"), self.filterChanged) self.connect(self.comboFilter1, SIGNAL("currentIndexChanged (int)"), self.filterChanged) self.connect(self.comboFilter2, SIGNAL("currentIndexChanged (int)"), self.filterChanged) # grab clicks on trees self.connect(self.treePlugins, SIGNAL("itemSelectionChanged()"), self.pluginTreeClicked) self.connect(self.treeRepositories, SIGNAL("itemSelectionChanged()"), self.repositoryTreeClicked) # buttons self.connect(self.buttonUpgradeAll, SIGNAL("clicked()"), self.upgradeAllClicked) self.connect(self.buttonInstall, SIGNAL("clicked()"), self.installPluginClicked) self.connect(self.buttonUninstall, SIGNAL("clicked()"), self.uninstallPluginClicked) self.buttonInstall.setEnabled(False) self.buttonUninstall.setEnabled(False) self.buttonHelp.setEnabled(QGIS_14) self.connect(self.buttonHelp, SIGNAL("clicked()"), self.runHelp) # repositories handling self.connect(self.treeRepositories, SIGNAL("doubleClicked(QModelIndex)"), self.editRepository) #self.connect(self.buttonFetchRepositories, SIGNAL("clicked()"), self.addKnownRepositories) self.connect(self.buttonAddRep, SIGNAL("clicked()"), self.addRepository) self.connect(self.buttonEditRep, SIGNAL("clicked()"), self.editRepository) self.connect(self.buttonDeleteRep, SIGNAL("clicked()"), self.deleteRepository) self.buttonEditRep.setEnabled(False) self.buttonDeleteRep.setEnabled(False) # configuration widgets self.connect(self.checkUpdates, SIGNAL("toggled (bool)"), self.changeCheckingPolicy) self.connect(self.comboInterval, SIGNAL("currentIndexChanged (int)"), self.changeCheckingInterval) self.connect(self.radioPluginType0, SIGNAL("toggled (bool)"), self.changePluginPolicy) self.connect(self.radioPluginType1, SIGNAL("toggled (bool)"), self.changePluginPolicy) self.connect(self.radioPluginType2, SIGNAL("toggled (bool)"), self.changePluginPolicy) # increase default icon size self.treePlugins.setIconSize(QSize(22, 22)) if repositories.checkingOnStart(): self.checkUpdates.setChecked(Qt.Checked) else: self.checkUpdates.setChecked(Qt.Unchecked) interval = repositories.checkingOnStartInterval() intervals = [0,1,3,7,14,30] # days if intervals.count(interval): index = intervals.index(interval) else: index = 1 self.comboInterval.setCurrentIndex(index) self.populateMostWidgets() self.pluginDir.setText( self.tr( "The plugins will be installed to %1" ).arg( QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "python/plugins" ) )
***************************************************************************/ """ import json import os import tempfile import urllib2 from zipfile import ZipFile import shutil from PyQt4.QtCore import QUrl, QEventLoop, QFile, QIODevice from PyQt4.QtNetwork import QNetworkRequest, QNetworkReply from qgis.core import QgsApplication, QgsNetworkAccessManager from plugin_settings import PluginSettings LOCAL_SETTINGS_PATH = os.path.dirname(QgsApplication.qgisUserDbFilePath()) PLUGIN_SETTINGS_PATH = os.path.join(LOCAL_SETTINGS_PATH, PluginSettings.product_name()) CONTRIBUTE_DIR_PATH = os.path.join(PLUGIN_SETTINGS_PATH, 'Contribute') USER_DIR_PATH = os.path.join(PLUGIN_SETTINGS_PATH, 'User') DATA_SOURCES_DIR_NAME = 'data_sources' GROUPS_DIR_NAME = 'groups' CONTRIBUTE_REPO_URL = 'https://api.github.com/repos/nextgis/quickmapservices_contrib' class ExtraSources(): __replies = []
""" from __future__ import absolute_import import json import os import tempfile import urllib2 from zipfile import ZipFile import shutil from PyQt4.QtCore import QUrl, QEventLoop, QFile, QIODevice from PyQt4.QtNetwork import QNetworkRequest, QNetworkReply from qgis.core import QgsApplication, QgsNetworkAccessManager from .plugin_settings import PluginSettings LOCAL_SETTINGS_PATH = os.path.dirname(QgsApplication.qgisUserDbFilePath()) PLUGIN_SETTINGS_PATH = os.path.join(LOCAL_SETTINGS_PATH, PluginSettings.product_name()) CONTRIBUTE_DIR_PATH = os.path.join(PLUGIN_SETTINGS_PATH, 'Contribute') USER_DIR_PATH = os.path.join(PLUGIN_SETTINGS_PATH, 'User') DATA_SOURCES_DIR_NAME = 'data_sources' GROUPS_DIR_NAME = 'groups' CONTRIBUTE_REPO_URL = 'https://api.github.com/repos/nextgis/quickmapservices_contrib' class ExtraSources(object): __replies = []
def initialize(self): aux_path_plugin = 'python/plugins/' + constants.CONST_GNSS_3D_CAPTURE_NAME qgisUserDbFilePath = QgsApplication.qgisUserDbFilePath() self.path_plugin = os.path.join( QFileInfo(QgsApplication.qgisUserDbFilePath()).path(), aux_path_plugin) path_file_qsettings = self.path_plugin + '/' + constants.CONST_GNSS_3D_CAPTURE_SETTINGS_FILE_NAME self.settings = QSettings(path_file_qsettings, QSettings.IniFormat) self.lastPath = self.settings.value("last_path") if not self.lastPath: self.lastPath = QDir.currentPath() self.settings.setValue("last_path", self.lastPath) self.settings.sync() self.crsAuthId = self.settings.value("crsAuthId") if not self.crsAuthId: self.crsAuthId = self.iface.mapCanvas().mapRenderer( ).destinationCrs().authid() self.settings.setValue("crsAuthId", self.crsAuthId) self.settings.sync() self.crs = QgsCoordinateReferenceSystem() self.crs.createFromUserInput(self.crsAuthId) if self.crs.geographicFlag(): self.firstCoordinateLabel.setText("Longitude") self.secondCoordinateLabel.setText("Latitude") else: self.firstCoordinateLabel.setText("Easting") self.secondCoordinateLabel.setText("Northing") self.iface.mapCanvas().mapRenderer().setProjectionsEnabled(True) self.startPushButton.setEnabled(False) self.finishPushButton.setEnabled(False) self.capturePointGroupBox.setEnabled(False) QtCore.QObject.connect(self.configurePushButton, QtCore.SIGNAL("clicked(bool)"), self.selectConfigure) # QtCore.QObject.connect(self.crsPushButton,QtCore.SIGNAL("clicked(bool)"),self.selectCrs) # QtCore.QObject.connect(self.geoidCheckBox,QtCore.SIGNAL("clicked(bool)"),self.activateGeoid) QtCore.QObject.connect(self.startPushButton, QtCore.SIGNAL("clicked(bool)"), self.startProcess) QtCore.QObject.connect(self.updatePositionPushButton, QtCore.SIGNAL("clicked(bool)"), self.updatePosition) QtCore.QObject.connect(self.finishPushButton, QtCore.SIGNAL("clicked(bool)"), self.finishProcess) QtCore.QObject.connect(self.savePointPushButton, QtCore.SIGNAL("clicked(bool)"), self.savePoint) QtCore.QObject.connect(self.codePushButton, QtCore.SIGNAL("clicked(bool)"), self.selectCode) QtCore.QObject.connect(self.namePushButton, QtCore.SIGNAL("clicked(bool)"), self.selectName) QtCore.QObject.connect(self.numberPushButton, QtCore.SIGNAL("clicked(bool)"), self.selectNumber) QtCore.QObject.connect(self.heightAntennaPushButton, QtCore.SIGNAL("clicked(bool)"), self.selectAntennaHeight) self.pointNumbers = [] #self.configureDialog = None self.configureDialog = GNSS3DCaptureDialog(self.iface, self.lastPath, self.crs) self.num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')
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 installPlugin(self): """ install currently selected plugin """ if not self.treePlugins.currentItem(): return infoString = ('','') key = plugins.keyByUrl(self.treePlugins.currentItem().toolTip(5)) 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) self.getAllAvailablePlugins() QApplication.restoreOverrideCursor() else: try: exec ("sys.path_importer_cache.clear()") exec ("import %s" % plugin["localdir"]) exec ("reload (%s)" % plugin["localdir"]) except: pass plugins.updatePlugin(key, False) plugin = plugins.all()[key] if not plugin["error"]: if previousStatus in ["not installed", "new"]: infoString = (self.tr("Plugin installed successfully"), self.tr("Python plugin installed.\nNow you need to enable it in Plugin Manager.")) else: infoString = (self.tr("Plugin reinstalled successfully"), self.tr("Python plugin reinstalled.\nYou need to restart Quantum GIS in order to reload it.")) 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.setPluginData(key, "status", "not installed") plugins.setPluginData(key, "version_inst", "") plugins.setPluginData(key, "desc_local", "") plugins.setPluginData(key, "error", "") plugins.setPluginData(key, "error_details", "") 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 plugins.updatePlugin(key, False) else: try: exec ("del sys.modules[%s]" % plugin["localdir"]) except: pass if not plugin["repository"]: plugins.remove(key) self.populatePluginTree() if infoString[0]: QMessageBox.information(self, infoString[0], infoString[1])
from PyQt4.QtCore import QTranslator, QSettings, QFileInfo, QVariant, QLocale from PyQt4.QtGui import QApplication from qgis.core import QgsApplication import resources # For i18n support userPluginPath = QFileInfo( QgsApplication.qgisUserDbFilePath() ).path() + "/python/plugins/multiqml" systemPluginPath = QgsApplication.prefixPath() + "/python/plugins/multiqml" overrideLocale = QSettings().value( "locale/overrideFlag", QVariant( False ) ).toBool() if not overrideLocale: localeFullName = QLocale.system().name() else: localeFullName = QSettings().value( "locale/userLocale", QVariant( "" ) ).toString() if QFileInfo( userPluginPath ).exists(): translationPath = userPluginPath + "/translations/multiqml_" + localeFullName + ".qm" else: translationPath = systemPluginPath + "/translations/multiqml_" + localeFullName + ".qm" localePath = translationPath if QFileInfo( localePath ).exists(): translator = QTranslator() translator.load( localePath ) QApplication.installTranslator( translator ) mVersion = "0.3.17" def name(): return unicode(QApplication.translate("__init__", "MultiQml")) def description():
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')