Exemplo n.º 1
0
 def deleteRepository(self, reposName):
     """ delete repository connection """
     if not reposName:
         return
     reposName = reposName.decode('utf-8')
     settings = QSettings()
     settings.beginGroup(reposGroup)
     if settings.value(reposName + "/url", "",
                       type=unicode) == officialRepo[1]:
         iface.pluginManagerInterface().pushMessage(
             self.
             tr("You can't remove the official QGIS Plugin Repository. You can disable it if needed."
                ), QgsMessageBar.WARNING)
         return
     warning = self.tr(
         "Are you sure you want to remove the following repository?"
     ) + "\n" + reposName
     if QMessageBox.warning(iface.mainWindow(),
                            self.tr("QGIS Python Plugin Installer"),
                            warning, QMessageBox.Yes,
                            QMessageBox.No) == QMessageBox.No:
         return
     # delete from the settings, refresh data and repopulate all the widgets
     settings.remove(reposName)
     repositories.remove(reposName)
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
Exemplo n.º 2
0
 def exportRepositoriesToManager(self):
     """ Update manager's repository tree widget with current data """
     iface.pluginManagerInterface().clearRepositoryList()
     for key in repositories.all():
         url = repositories.all()[key]["url"] + repositories.urlParams()
         if repositories.inspectionFilter():
             enabled = (key == repositories.inspectionFilter())
         else:
             enabled = repositories.all()[key]["enabled"]
         iface.pluginManagerInterface().addToRepositoryList({
             "name":
             key,
             "url":
             url,
             "enabled":
             enabled and "true" or "false",
             "valid":
             repositories.all()[key]["valid"] and "true" or "false",
             "state":
             str(repositories.all()[key]["state"]),
             "error":
             repositories.all()[key]["error"],
             "inspection_filter":
             repositories.inspectionFilter() and "true" or "false"
         })
Exemplo n.º 3
0
 def addRepository(self):
     """ add new repository connection """
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.editParams.setText(repositories.urlParams())
     dlg.checkBoxEnabled.setCheckState(Qt.Checked)
     if not dlg.exec_():
         return
     for i in repositories.all().values():
         if dlg.editURL.text().strip() == i["url"]:
             iface.pluginManagerInterface().pushMessage(
                 self.tr(
                     "Unable to add another repository with the same URL!"),
                 QgsMessageBar.WARNING)
             return
     settings = QSettings()
     settings.beginGroup(reposGroup)
     reposName = dlg.editName.text()
     reposURL = dlg.editURL.text().strip()
     if reposName in repositories.all():
         reposName = reposName + "(2)"
     # add to settings
     settings.setValue(reposName + "/url", reposURL)
     settings.setValue(reposName + "/enabled",
                       bool(dlg.checkBoxEnabled.checkState()))
     # refresh lists and populate widgets
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
Exemplo n.º 4
0
    def requestFetching(self, key, url=None, redirectionCounter=0):
        """ start fetching the repository given by key """
        self.mRepositories[key]["state"] = 1
        if not url:
            url = QUrl(self.mRepositories[key]["url"] + self.urlParams())
        # v=str(Qgis.QGIS_VERSION_INT)
        # url.addQueryItem('qgis', '.'.join([str(int(s)) for s in [v[0], v[1:3]]]) ) # don't include the bugfix version!

        self.mRepositories[key]["QRequest"] = QNetworkRequest(url)
        authcfg = self.mRepositories[key]["authcfg"]
        if authcfg and isinstance(authcfg, str):
            if not QgsApplication.authManager().updateNetworkRequest(
                    self.mRepositories[key]["QRequest"], authcfg.strip()):
                msg = QCoreApplication.translate(
                    "QgsPluginInstaller",
                    "Update of network request with authentication "
                    "credentials FAILED for configuration '{0}'").format(
                        authcfg)
                iface.pluginManagerInterface().pushMessage(msg, Qgis.Warning)
                self.mRepositories[key]["QRequest"] = None
                return
        self.mRepositories[key]["QRequest"].setAttribute(
            QNetworkRequest.User, key)
        self.mRepositories[key]["xmlData"] = QgsNetworkAccessManager.instance(
        ).get(self.mRepositories[key]["QRequest"])
        self.mRepositories[key]["xmlData"].setProperty('reposName', key)
        self.mRepositories[key]["xmlData"].setProperty('redirectionCounter',
                                                       redirectionCounter)
        self.mRepositories[key]["xmlData"].downloadProgress.connect(
            self.mRepositories[key]["Relay"].dataReadProgress)
        self.mRepositories[key]["xmlData"].finished.connect(self.xmlDownloaded)
Exemplo n.º 5
0
 def deleteRepository(self, reposName):
     """ delete repository connection """
     if not reposName:
         return
     reposName = reposName.decode("utf-8")
     settings = QSettings()
     settings.beginGroup(reposGroup)
     if settings.value(reposName + "/url", "", type=unicode) == officialRepo[1]:
         iface.pluginManagerInterface().pushMessage(
             self.tr("You can't remove the official QGIS Plugin Repository. You can disable it if needed."),
             QgsMessageBar.WARNING,
         )
         return
     warning = self.tr("Are you sure you want to remove the following repository?") + "\n" + reposName
     if (
         QMessageBox.warning(
             iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), warning, QMessageBox.Yes, QMessageBox.No
         )
         == QMessageBox.No
     ):
         return
     # delete from the settings, refresh data and repopulate all the widgets
     settings.remove(reposName)
     repositories.remove(reposName)
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
Exemplo n.º 6
0
 def exportRepositoriesToManager(self):
     """ Update manager's repository tree widget with current data """
     iface.pluginManagerInterface().clearRepositoryList()
     for key in repositories.all():
         url = repositories.all()[key]["url"]
         v = str(QGis.QGIS_VERSION_INT)
         url += "?qgis=%d.%d" % (int(v[0]), int(v[1:3]))
         repository = repositories.all()[key]
         if repositories.inspectionFilter():
             enabled = (key == repositories.inspectionFilter())
         else:
             enabled = repositories.all()[key]["enabled"]
         iface.pluginManagerInterface().addToRepositoryList({
             "name":
             key,
             "url":
             url,
             "enabled":
             enabled and "true" or "false",
             "valid":
             repositories.all()[key]["valid"] and "true" or "false",
             "state":
             str(repositories.all()[key]["state"]),
             "error":
             repositories.all()[key]["error"],
             "inspection_filter":
             repositories.inspectionFilter() and "true" or "false"
         })
Exemplo n.º 7
0
 def addRepository(self):
     """ add new repository connection """
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.editParams.setText(repositories.urlParams())
     dlg.checkBoxEnabled.setCheckState(Qt.Checked)
     if not dlg.exec_():
         return
     for i in repositories.all().values():
         if dlg.editURL.text().strip() == i["url"]:
             iface.pluginManagerInterface().pushMessage(
                 self.tr("Unable to add another repository with the same URL!"), QgsMessageBar.WARNING
             )
             return
     settings = QSettings()
     settings.beginGroup(reposGroup)
     reposName = dlg.editName.text()
     reposURL = dlg.editURL.text().strip()
     if reposName in repositories.all():
         reposName = reposName + "(2)"
     # add to settings
     settings.setValue(reposName + "/url", reposURL)
     settings.setValue(reposName + "/authcfg", dlg.editAuthCfg.text().strip())
     settings.setValue(reposName + "/enabled", bool(dlg.checkBoxEnabled.checkState()))
     # refresh lists and populate widgets
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
Exemplo n.º 8
0
    def requestFetching(self, key, url=None, redirectionCounter=0):
        """ start fetching the repository given by key """
        self.mRepositories[key]["state"] = 1
        if not url:
            url = QUrl(self.mRepositories[key]["url"] + self.urlParams())
        # v=str(Qgis.QGIS_VERSION_INT)
        # url.addQueryItem('qgis', '.'.join([str(int(s)) for s in [v[0], v[1:3]]]) ) # don't include the bugfix version!

        self.mRepositories[key]["QRequest"] = QNetworkRequest(url)
        authcfg = self.mRepositories[key]["authcfg"]
        if authcfg and isinstance(authcfg, str):
            if not QgsApplication.authManager().updateNetworkRequest(
                    self.mRepositories[key]["QRequest"], authcfg.strip()):
                msg = QCoreApplication.translate(
                    "QgsPluginInstaller",
                    "Update of network request with authentication "
                    "credentials FAILED for configuration '{0}'").format(authcfg)
                iface.pluginManagerInterface().pushMessage(msg, Qgis.Warning)
                self.mRepositories[key]["QRequest"] = None
                return
        self.mRepositories[key]["QRequest"].setAttribute(QNetworkRequest.User, key)
        self.mRepositories[key]["xmlData"] = QgsNetworkAccessManager.instance().get(self.mRepositories[key]["QRequest"])
        self.mRepositories[key]["xmlData"].setProperty('reposName', key)
        self.mRepositories[key]["xmlData"].setProperty('redirectionCounter', redirectionCounter)
        self.mRepositories[key]["xmlData"].downloadProgress.connect(self.mRepositories[key]["Relay"].dataReadProgress)
        self.mRepositories[key]["xmlData"].finished.connect(self.xmlDownloaded)
Exemplo n.º 9
0
    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)
Exemplo n.º 10
0
    def uninstallPlugin(self, key, quiet=False):
        """ Uninstall given plugin """
        if key in plugins.all():
            plugin = plugins.all()[key]
        else:
            plugin = plugins.localCache[key]
        if not plugin:
            return
        if not quiet:
            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(iface.mainWindow(),
                                   self.tr("QGIS Python Plugin Installer"),
                                   warning, QMessageBox.Yes,
                                   QMessageBox.No) == QMessageBox.No:
                return
        # unload the plugin
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            unloadPlugin(key)
        except:
            pass
        pluginDir = qgis.utils.home_plugin_path + "/" + plugin["id"]
        result = removeDir(pluginDir)
        if result:
            QApplication.restoreOverrideCursor()
            msg = "<b>%s:</b>%s" % (self.tr("Plugin uninstall failed"), result)
            iface.pluginManagerInterface().pushMessage(msg, Qgis.Critical)
        else:
            # safe remove
            try:
                unloadPlugin(plugin["id"])
            except:
                pass
            try:
                exec("plugins[%s].unload()" % plugin["id"])
                exec("del plugins[%s]" % plugin["id"])
            except:
                pass
            try:
                exec("del sys.modules[%s]" % plugin["id"])
            except:
                pass
            try:
                exec("del plugins_metadata_parser[%s]" % plugin["id"])
            except:
                pass

            plugins.getAllInstalled()
            plugins.rebuild()
            self.exportPluginsToManager()
            QApplication.restoreOverrideCursor()
            iface.pluginManagerInterface().pushMessage(
                self.tr("Plugin uninstalled successfully"), Qgis.Info)
Exemplo n.º 11
0
 def editRepository(self, reposName):
     """ edit repository connection """
     if not reposName:
         return
     reposName = reposName.decode('utf-8')
     checkState = {False: Qt.Unchecked, True: Qt.Checked}
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.editName.setText(reposName)
     dlg.editURL.setText(repositories.all()[reposName]["url"])
     dlg.editAuthCfg.setText(repositories.all()[reposName]["authcfg"])
     dlg.editParams.setText(repositories.urlParams())
     dlg.checkBoxEnabled.setCheckState(
         checkState[repositories.all()[reposName]["enabled"]])
     if repositories.all()[reposName]["valid"]:
         dlg.checkBoxEnabled.setEnabled(True)
         dlg.labelInfo.setText("")
     else:
         dlg.checkBoxEnabled.setEnabled(False)
         dlg.labelInfo.setText(
             self.
             tr("This repository is blocked due to incompatibility with your QGIS version"
                ))
         dlg.labelInfo.setFrameShape(QFrame.Box)
     if not dlg.exec_():
         return  # nothing to do if cancelled
     for i in repositories.all().values():
         if dlg.editURL.text().strip() == i["url"] and dlg.editURL.text(
         ).strip() != repositories.all()[reposName]["url"]:
             iface.pluginManagerInterface().pushMessage(
                 self.tr(
                     "Unable to add another repository with the same URL!"),
                 QgsMessageBar.WARNING)
             return
     # delete old repo from QSettings and create new one
     settings = QSettings()
     settings.beginGroup(reposGroup)
     settings.remove(reposName)
     newName = dlg.editName.text()
     if newName in repositories.all() and newName != reposName:
         newName = newName + "(2)"
     settings.setValue(newName + "/url", dlg.editURL.text().strip())
     settings.setValue(newName + "/authcfg", dlg.editAuthCfg.text().strip())
     settings.setValue(newName + "/enabled",
                       bool(dlg.checkBoxEnabled.checkState()))
     if dlg.editAuthCfg.text().strip() != repositories.all(
     )[reposName]["authcfg"]:
         repositories.all()[reposName]["authcfg"] = dlg.editAuthCfg.text(
         ).strip()
     if dlg.editURL.text().strip() == repositories.all(
     )[reposName]["url"] and dlg.checkBoxEnabled.checkState() == checkState[
             repositories.all()[reposName]["enabled"]]:
         repositories.rename(reposName, newName)
         self.exportRepositoriesToManager()
         return  # nothing else to do if only repository name was changed
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
Exemplo n.º 12
0
 def uninstallPlugin(self, key, quiet=False):
     """ Uninstall given plugin """
     if key in plugins.all():
         plugin = plugins.all()[key]
     else:
         plugin = plugins.localCache[key]
     if not plugin:
         return
     if not quiet:
         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(
                 iface.mainWindow(),
                 self.tr("QGIS Python Plugin Installer"),
                 warning,
                 QMessageBox.Yes,
                 QMessageBox.No,
             )
             == QMessageBox.No
         ):
             return
     # unload the plugin
     QApplication.setOverrideCursor(Qt.WaitCursor)
     try:
         unloadPlugin(key)
     except:
         pass
     pluginDir = qgis.utils.home_plugin_path + "/" + plugin["id"]
     result = removeDir(pluginDir)
     if result:
         QApplication.restoreOverrideCursor()
         msg = "<b>%s:</b>%s" % (self.tr("Plugin uninstall failed"), result)
         iface.pluginManagerInterface().pushMessage(msg, QgsMessageBar.CRITICAL)
     else:
         # safe remove
         try:
             unloadPlugin(plugin["id"])
         except:
             pass
         try:
             exec("plugins[%s].unload()" % plugin["id"])
             exec("del plugins[%s]" % plugin["id"])
         except:
             pass
         try:
             exec("del sys.modules[%s]" % plugin["id"])
         except:
             pass
         plugins.getAllInstalled()
         plugins.rebuild()
         self.exportPluginsToManager()
         QApplication.restoreOverrideCursor()
         iface.pluginManagerInterface().pushMessage(self.tr("Plugin uninstalled successfully"), QgsMessageBar.INFO)
Exemplo n.º 13
0
def showPluginManager(boundlessOnly):
    """Show Plugin Manager with all plugins. This includes plugins from
    Official QGIS plugins repository and plugins from Boundless plugins
    repository (local or remote).
    If boundlessOnly=True, it will only show Boundless plugins
    """

    installer = pyplugin_installer.instance()

    initPluginManager(installer, boundlessOnly)
    iface.pluginManagerInterface().showPluginManager(2)
    # Restore repositories, as we don't want to keep local repo in cache
    repositories.load()
Exemplo n.º 14
0
 def editRepository(self, reposName):
     """ edit repository connection """
     if not reposName:
         return
     reposName = reposName.decode("utf-8")
     checkState = {False: Qt.Unchecked, True: Qt.Checked}
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.editName.setText(reposName)
     dlg.editURL.setText(repositories.all()[reposName]["url"])
     dlg.editAuthCfg.setText(repositories.all()[reposName]["authcfg"])
     dlg.editParams.setText(repositories.urlParams())
     dlg.checkBoxEnabled.setCheckState(checkState[repositories.all()[reposName]["enabled"]])
     if repositories.all()[reposName]["valid"]:
         dlg.checkBoxEnabled.setEnabled(True)
         dlg.labelInfo.setText("")
     else:
         dlg.checkBoxEnabled.setEnabled(False)
         dlg.labelInfo.setText(self.tr("This repository is blocked due to incompatibility with your QGIS version"))
         dlg.labelInfo.setFrameShape(QFrame.Box)
     if not dlg.exec_():
         return  # nothing to do if cancelled
     for i in repositories.all().values():
         if (
             dlg.editURL.text().strip() == i["url"]
             and dlg.editURL.text().strip() != repositories.all()[reposName]["url"]
         ):
             iface.pluginManagerInterface().pushMessage(
                 self.tr("Unable to add another repository with the same URL!"), QgsMessageBar.WARNING
             )
             return
     # delete old repo from QSettings and create new one
     settings = QSettings()
     settings.beginGroup(reposGroup)
     settings.remove(reposName)
     newName = dlg.editName.text()
     if newName in repositories.all() and newName != reposName:
         newName = newName + "(2)"
     settings.setValue(newName + "/url", dlg.editURL.text().strip())
     settings.setValue(newName + "/authcfg", dlg.editAuthCfg.text().strip())
     settings.setValue(newName + "/enabled", bool(dlg.checkBoxEnabled.checkState()))
     if dlg.editAuthCfg.text().strip() != repositories.all()[reposName]["authcfg"]:
         repositories.all()[reposName]["authcfg"] = dlg.editAuthCfg.text().strip()
     if (
         dlg.editURL.text().strip() == repositories.all()[reposName]["url"]
         and dlg.checkBoxEnabled.checkState() == checkState[repositories.all()[reposName]["enabled"]]
     ):
         repositories.rename(reposName, newName)
         self.exportRepositoriesToManager()
         return  # nothing else to do if only repository name was changed
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
    def processDependencies(self, plugin_id):
        """Processes plugin dependencies

        :param plugin_id: plugin id
        :type plugin_id: str
        """

        to_install, to_upgrade, not_found = find_dependencies(plugin_id)
        if to_install or to_upgrade or not_found:
            dlg = QgsPluginDependenciesDialog(plugin_id, to_install, to_upgrade, not_found)
            if dlg.exec_() == QgsPluginDependenciesDialog.Accepted:
                actions = dlg.actions()
                for dependency_plugin_id, action in actions.items():
                    try:
                        self.installPlugin(dependency_plugin_id)
                        if action == 'install':
                            iface.pluginManagerInterface().pushMessage(self.tr("Plugin dependency <b>%s</b> successfully installed") %
                                                                       dependency_plugin_id, Qgis.Info)
                        else:
                            iface.pluginManagerInterface().pushMessage(self.tr("Plugin dependency <b>%s</b> successfully upgraded") %
                                                                       dependency_plugin_id, Qgis.Info)
                    except Exception as ex:
                        if action == 'install':
                            iface.pluginManagerInterface().pushMessage(self.tr("Error installing plugin dependency <b>%s</b>: %s") %
                                                                       (dependency_plugin_id, ex), Qgis.Warning)
                        else:
                            iface.pluginManagerInterface().pushMessage(self.tr("Error upgrading plugin dependency <b>%s</b>: %s") %
                                                                       (dependency_plugin_id, ex), Qgis.Warning)
Exemplo n.º 16
0
 def exportRepositoriesToManager(self):
     """ Update manager's repository tree widget with current data """
     iface.pluginManagerInterface().clearRepositoryList()
     for key in repositories.all():
         url = repositories.all()[key]["url"] + repositories.urlParams()
         if repositories.inspectionFilter():
             enabled = (key == repositories.inspectionFilter())
         else:
             enabled = repositories.all()[key]["enabled"]
         iface.pluginManagerInterface().addToRepositoryList({
             "name": key,
             "url": url,
             "enabled": enabled and "true" or "false",
             "valid": repositories.all()[key]["valid"] and "true" or "false",
             "state": str(repositories.all()[key]["state"]),
             "error": repositories.all()[key]["error"],
             "inspection_filter": repositories.inspectionFilter() and "true" or "false"
         })
Exemplo n.º 17
0
    def showPluginManagerWhenReady(self, * params):
        """ Open the plugin manager window. If fetching is still in progress, it shows the progress window first """
        """ Optionally pass the index of tab to be opened in params """
        if self.statusLabel:
            iface.mainWindow().statusBar().removeWidget(self.statusLabel)
            self.statusLabel = None

        self.fetchAvailablePlugins(reloadMode=False)
        self.exportRepositoriesToManager()
        self.exportPluginsToManager()

        # finally, show the plugin manager window
        tabIndex = -1
        if len(params) == 1:
            indx = str(params[0])
            if indx.isdigit() and int(indx) > -1 and int(indx) < 7:
                tabIndex = int(indx)
        iface.pluginManagerInterface().showPluginManager(tabIndex)
Exemplo n.º 18
0
    def showPluginManagerWhenReady(self, * params):
        """ Open the plugin manager window. If fetching is still in progress, it shows the progress window first """
        """ Optionally pass the index of tab to be opened in params """
        if self.statusLabel:
            iface.mainWindow().statusBar().removeWidget(self.statusLabel)
            self.statusLabel = None

        self.fetchAvailablePlugins(reloadMode=False)
        self.exportRepositoriesToManager()
        self.exportPluginsToManager()

        # finally, show the plugin manager window
        tabIndex = -1
        if len(params) == 1:
            indx = str(params[0])
            if indx.isdigit() and int(indx) > -1 and int(indx) < 7:
                tabIndex = int(indx)
        iface.pluginManagerInterface().showPluginManager(tabIndex)
Exemplo n.º 19
0
 def exportRepositoriesToManager(self):
   """ Update manager's repository tree widget with current data """
   iface.pluginManagerInterface().clearRepositoryList()
   for key in repositories.all():
       url = repositories.all()[key]["url"]
       v=str(QGis.QGIS_VERSION_INT)
       url += "?qgis=%d.%d" % ( int(v[0]), int(v[1:3]) )
       repository = repositories.all()[key]
       if repositories.inspectionFilter():
         enabled = ( key == repositories.inspectionFilter() )
       else:
         enabled = repositories.all()[key]["enabled"]
       iface.pluginManagerInterface().addToRepositoryList({
         "name" : key,
         "url"  : url,
         "enabled" : enabled and "true" or "false",
         "valid" : repositories.all()[key]["valid"] and "true" or "false",
         "state" : str(repositories.all()[key]["state"]),
         "error" : repositories.all()[key]["error"],
         "inspection_filter" : repositories.inspectionFilter() and "true" or "false"
       })
 def exportPluginsToManager(self):
     """ Insert plugins metadata to QgsMetadataRegistry """
     iface.pluginManagerInterface().clearPythonPluginMetadata()
     for key in plugins.all():
         plugin = plugins.all()[key]
         iface.pluginManagerInterface().addPluginMetadata({
             "id": key,
             "plugin_id": plugin["plugin_id"] or "",
             "name": plugin["name"],
             "description": plugin["description"],
             "about": plugin["about"],
             "category": plugin["category"],
             "tags": plugin["tags"],
             "changelog": plugin["changelog"],
             "author_name": plugin["author_name"],
             "author_email": plugin["author_email"],
             "homepage": plugin["homepage"],
             "tracker": plugin["tracker"],
             "code_repository": plugin["code_repository"],
             "version_installed": plugin["version_installed"],
             "library": plugin["library"],
             "icon": plugin["icon"],
             "readonly": plugin["readonly"] and "true" or "false",
             "installed": plugin["installed"] and "true" or "false",
             "available": plugin["available"] and "true" or "false",
             "status": plugin["status"],
             "status_exp": plugin["status_exp"],
             "error": plugin["error"],
             "error_details": plugin["error_details"],
             "create_date": plugin["create_date"],
             "update_date": plugin["update_date"],
             "create_date_stable": plugin["create_date_stable"],
             "update_date_stable": plugin["update_date_stable"],
             "create_date_experimental": plugin["create_date_experimental"],
             "update_date_experimental": plugin["update_date_experimental"],
             "experimental": plugin["experimental"] and "true" or "false",
             "deprecated": plugin["deprecated"] and "true" or "false",
             "trusted": plugin["trusted"] and "true" or "false",
             "version_available": plugin["version_available"],
             "version_available_stable": plugin["version_available_stable"] or "",
             "version_available_experimental": plugin["version_available_experimental"] or "",
             "zip_repository": plugin["zip_repository"],
             "download_url": plugin["download_url"],
             "download_url_stable": plugin["download_url_stable"],
             "download_url_experimental": plugin["download_url_experimental"],
             "filename": plugin["filename"],
             "downloads": plugin["downloads"],
             "average_vote": plugin["average_vote"],
             "rating_votes": plugin["rating_votes"],
             "plugin_dependencies": plugin.get("plugin_dependencies", None),
             "pythonic": "true"
         })
     iface.pluginManagerInterface().reloadModel()
Exemplo n.º 21
0
 def exportPluginsToManager(self):
     """ Insert plugins metadata to QgsMetadataRegistry """
     iface.pluginManagerInterface().clearPythonPluginMetadata()
     for key in plugins.all():
         plugin = plugins.all()[key]
         iface.pluginManagerInterface().addPluginMetadata(
             {
                 "id": key,
                 "plugin_id": plugin["plugin_id"] or "",
                 "name": plugin["name"],
                 "description": plugin["description"],
                 "about": plugin["about"],
                 "category": plugin["category"],
                 "tags": plugin["tags"],
                 "changelog": plugin["changelog"],
                 "author_name": plugin["author_name"],
                 "author_email": plugin["author_email"],
                 "homepage": plugin["homepage"],
                 "tracker": plugin["tracker"],
                 "code_repository": plugin["code_repository"],
                 "version_installed": plugin["version_installed"],
                 "library": plugin["library"],
                 "icon": plugin["icon"],
                 "readonly": plugin["readonly"] and "true" or "false",
                 "installed": plugin["installed"] and "true" or "false",
                 "available": plugin["available"] and "true" or "false",
                 "status": plugin["status"],
                 "error": plugin["error"],
                 "error_details": plugin["error_details"],
                 "experimental": plugin["experimental"] and "true" or "false",
                 "deprecated": plugin["deprecated"] and "true" or "false",
                 "trusted": plugin["trusted"] and "true" or "false",
                 "version_available": plugin["version_available"],
                 "zip_repository": plugin["zip_repository"],
                 "download_url": plugin["download_url"],
                 "filename": plugin["filename"],
                 "downloads": plugin["downloads"],
                 "average_vote": plugin["average_vote"],
                 "rating_votes": plugin["rating_votes"],
                 "pythonic": "true",
             }
         )
     iface.pluginManagerInterface().reloadModel()
Exemplo n.º 22
0
    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)
Exemplo n.º 23
0
    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 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)
Exemplo n.º 25
0
    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)