def setUp(self):
     self.qgis_app, self.canvas, self.iface = set_up_interface()
     utils.plugin_paths = [os.path.expanduser('~/.qgis2/python/plugins')]
     utils.updateAvailablePlugins()
     utils.loadPlugin('pointsamplingtool')
     utils.iface = self.iface
     utils.startPlugin('pointsamplingtool')
 def setUp(self):
     self.qgis_app, self.canvas, self.iface = set_up_interface()
     utils.plugin_paths = [os.path.expanduser('~/.qgis2/python/plugins')]
     utils.updateAvailablePlugins()
     utils.loadPlugin('pointsamplingtool')
     utils.iface = self.iface
     utils.startPlugin('pointsamplingtool')
예제 #3
0
  def run(self):
    plugin = currentPlugin()
    #update the plugin list first! The plugin could be removed from the list if was temporarily broken.
    updateAvailablePlugins()
    #try to load from scratch the plugin saved in QSettings if not loaded
    if plugin not in plugins:
      try:
        loadPlugin(plugin)
        startPlugin(plugin)
      except:
        pass
    updateAvailablePlugins()
    #give one chance for correct (not a loop)
    if plugin not in plugins:
      self.configure()
      plugin = currentPlugin()
    if plugin in plugins:
      state = self.iface.mainWindow().saveState()

      # Unload submodules
      for key in [key for key in sys.modules.keys()]:
        if '{}.'.format(plugin) in key:
          if hasattr(sys.modules[key], 'qCleanupResources'):
            sys.modules[key].qCleanupResources()
          del sys.modules[key]

      reloadPlugin(plugin)
      self.iface.mainWindow().restoreState(state)
      self.iface.messageBar().pushMessage("<b>{}</b> reloaded.".format(plugin), QGis.Info)
예제 #4
0
def upgradeInstalledPlugins():
    installer = pyplugin_installer.instance()
    initPluginManager(installer)

    errors = []
    pluginsList = plugins.all().copy()
    for plugin in pluginsList:
        if isBoundlessPlugin(pluginsList[plugin]):
            if pluginsList[plugin]['installed'] and pluginsList[plugin]['status'] == 'upgradeable':
                dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(), plugins.all()[plugin])
                dlg.exec_()
                if dlg.result():
                    errors.append(dlg.result())
                else:
                    updateAvailablePlugins()
                    loadPlugin(plugins.all()[plugin]['id'])
                    plugins.getAllInstalled(testLoad=True)
                    plugins.rebuild()
                    if not plugins.all()[plugin]["error"]:
                        if startPlugin(plugins.all()[plugin]['id']):
                            settings = QSettings()
                            settings.setValue('/PythonPlugins/' + plugins.all()[plugin]['id'], True)

    installer.exportPluginsToManager()
    return errors
 def _enableProcessing():
     loadPlugin("processing")
     startPlugin("processing")
     QtCore.QSettings().setValue('/PythonPlugins/processing', True)
     updateAvailablePlugins()
     updatePluginManager()
     assert "processing" in active_plugins
예제 #6
0
  def __init__(self, parent):
    super().__init__()
    self.iface = parent
    self.setupUi(self)
    #update the plugin list first! The plugin could be removed from the list if was temporarily broken.
    #Still doesn't work in every case. TODO?: try to load from scratch the plugin saved in QSettings if doesn't exist
    plugin = currentPlugin()
    updateAvailablePlugins()
    #if plugin not in plugins:
      #try:
        #loadPlugin(plugin)
        #startPlugin(plugin)
      #except:
        #pass
    #updateAvailablePlugins()

    plugins_list = sorted(plugins.keys())
    for plugin in plugins_list:
      try:
        icon = QIcon(plugin_installer.plugins.all()[plugin]['icon'])
      except KeyError:
        icon = QIcon()
      self.comboPlugin.addItem(icon, plugin)
    plugin = currentPlugin()
    if plugin in plugins:
      self.comboPlugin.setCurrentIndex(plugins_list.index(plugin))
예제 #7
0
    def run(self):
        plugin = currentPlugin()
        #update the plugin list first! The plugin could be removed from the list if was temporarily broken.
        updateAvailablePlugins()
        #try to load from scratch the plugin saved in QSettings if not loaded
        if plugin not in plugins:
            try:
                loadPlugin(plugin)
                startPlugin(plugin)
            except:
                pass
        updateAvailablePlugins()
        #give one chance for correct (not a loop)
        if plugin not in plugins:
            self.configure()
            plugin = currentPlugin()
        if plugin in plugins:
            state = self.iface.mainWindow().saveState()

            # Unload submodules
            for key in [key for key in sys.modules.keys()]:
                if '{}.'.format(plugin) in key:
                    if hasattr(sys.modules[key], 'qCleanupResources'):
                        sys.modules[key].qCleanupResources()
                    del sys.modules[key]

            handleExtraCommands(self.iface.messageBar(), self.tr)
            reloadPlugin(plugin)
            self.iface.mainWindow().restoreState(state)
            if notificationsEnabled():
                self.iface.messageBar().pushMessage(
                    self.tr('<b>{}</b> reloaded.').format(plugin), Qgis.Info)
예제 #8
0
 def _enableProcessing():
     loadPlugin("processing")
     startPlugin("processing")
     QSettings().setValue('/PythonPlugins/processing', True)
     updateAvailablePlugins()
     updatePluginManager()
     assert "processing" in active_plugins
예제 #9
0
    def __init__(self, parent):
        super().__init__()
        self.iface = parent
        self.setupUi(self)
        self.cbNotifications.setChecked(notificationsEnabled())
        self.pteExtraCommands.setPlainText(getExtraCommands())

        #update the plugin list first! The plugin could be removed from the list if was temporarily broken.
        #Still doesn't work in every case. TODO?: try to load from scratch the plugin saved in QSettings if doesn't exist
        plugin = currentPlugin()
        updateAvailablePlugins()
        #if plugin not in plugins:
        #try:
        #loadPlugin(plugin)
        #startPlugin(plugin)
        #except:
        #pass
        #updateAvailablePlugins()

        plugins_list = sorted(plugins.keys())
        for plugin in plugins_list:
            try:
                icon = QIcon(plugin_installer.plugins.all()[plugin]['icon'])
            except KeyError:
                icon = QIcon()
            self.comboPlugin.addItem(icon, plugin)
        plugin = currentPlugin()
        if plugin in plugins:
            self.comboPlugin.setCurrentIndex(plugins_list.index(plugin))
예제 #10
0
def installAllFromRepository():
    """Install Boundless plugins from remote repository
    """
    installer = pyplugin_installer.instance()
    initPluginManager(installer)

    errors = []
    pluginsList = plugins.all().copy()
    for plugin in pluginsList:
        if isBoundlessPlugin(pluginsList[plugin]):
            if (pluginsList[plugin]['installed'] and pluginsList[plugin]['deprecated']) or \
                    not pluginsList[plugin]['deprecated'] and \
                    pluginsList[plugin]["zip_repository"] != '':
                dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(), plugins.all()[plugin])
                dlg.exec_()
                if dlg.result():
                    errors.append(dlg.result())
                else:
                    updateAvailablePlugins()
                    loadPlugin(plugins.all()[plugin]['id'])
                    plugins.getAllInstalled(testLoad=True)
                    plugins.rebuild()
                    if not plugins.all()[plugin]["error"]:
                        if startPlugin(plugins.all()[plugin]['id']):
                            settings = QSettings()
                            settings.setValue('/PythonPlugins/' + plugins.all()[plugin]['id'], True)

    installer.exportPluginsToManager()
    return errors
예제 #11
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)
예제 #12
0
    def __init__(self):
        """ Initialize data objects, starts fetching if appropriate, and warn about/removes obsolete plugins """

        QObject.__init__(
            self)  # initialize QObject in order to to use self.tr()
        repositories.load()
        plugins.getAllInstalled()

        if repositories.checkingOnStart() and repositories.timeForChecking(
        ) and repositories.allEnabled():
            # start fetching repositories
            self.statusLabel = QLabel(iface.mainWindow().statusBar())
            iface.mainWindow().statusBar().addPermanentWidget(self.statusLabel)
            self.statusLabel.linkActivated.connect(
                self.showPluginManagerWhenReady)
            repositories.checkingDone.connect(self.checkingDone)
            for key in repositories.allEnabled():
                repositories.requestFetching(key)
        else:
            # no fetching at start, so mark all enabled repositories as requesting to be fetched.
            for key in repositories.allEnabled():
                repositories.setRepositoryData(key, "state", 3)

        # look for obsolete plugins updates (the user-installed one is older than the core one)
        for key in plugins.obsoletePlugins:
            plugin = plugins.localCache[key]
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setWindowTitle(self.tr("QGIS Python Plugin Installer"))
            msg.addButton(self.tr("Uninstall (recommended)"),
                          QMessageBox.AcceptRole)
            msg.addButton(self.tr("I will uninstall it later"),
                          QMessageBox.RejectRole)
            msg.setText("%s <b>%s</b><br/><br/>%s" % (
                self.tr("Obsolete plugin:"), plugin["name"],
                self.
                tr("QGIS has detected an obsolete plugin that masks its more recent version shipped with this copy of QGIS. This is likely due to files associated with a previous installation of QGIS. Do you want to remove the old plugin right now and unmask the more recent version?"
                   )))
            msg.exec_()
            if not msg.result():
                settings = QgsSettings()
                plugin_is_active = settings.value("/PythonPlugins/" + key,
                                                  False,
                                                  type=bool)

                # uninstall the update, update utils and reload if enabled
                self.uninstallPlugin(key, quiet=True)
                updateAvailablePlugins()
                if plugin_is_active:
                    settings.setValue("/PythonPlugins/watchDog/" + key, True)
                    loadPlugin(key)
                    startPlugin(key)
                    settings.remove("/PythonPlugins/watchDog/" + key)
예제 #13
0
def installFromZipFile(pluginPath):
    """Install and activate plugin from the specified package
    """
    result = None

    with zipfile.ZipFile(pluginPath, 'r') as zf:
        pluginName = os.path.split(zf.namelist()[0])[0]

    pluginFileName = os.path.splitext(os.path.basename(pluginPath))[0]

    pluginsDirectory = home_plugin_path
    if not QDir(pluginsDirectory).exists():
        QDir().mkpath(pluginsDirectory)

    # If the target directory already exists as a link,
    # remove the link without resolving
    QFile(os.path.join(pluginsDirectory, pluginFileName)).remove()

    try:
        # Test extraction. If fails, then exception will be raised
        # and no removing occurs
        unzip(unicode(pluginPath), unicode(pluginsDirectory))
        # Removing old plugin files if exist
        removeDir(QDir.cleanPath(os.path.join(pluginsDirectory, pluginFileName)))
        # Extract new files
        unzip(unicode(pluginPath), unicode(pluginsDirectory))
    except:
        result = QCoreApplication.translate('BoundlessConnect',
            'Failed to unzip the plugin package\n{}.\nProbably it is broken'.format(pluginPath))

    if result is None:
        updateAvailablePlugins()
        loadPlugin(pluginName)
        plugins.getAllInstalled(testLoad=True)
        plugins.rebuild()
        plugin = plugins.all()[pluginName]

        settings = QSettings()
        if settings.contains('/PythonPlugins/' + pluginName):
            if settings.value('/PythonPlugins/' + pluginName, False, bool):
                startPlugin(pluginName)
                reloadPlugin(pluginName)
            else:
                unloadPlugin(pluginName)
                loadPlugin(pluginName)
        else:
            if startPlugin(pluginName):
                settings.setValue('/PythonPlugins/' + pluginName, True)

    return result
예제 #14
0
파일: installer.py 프로젝트: Zakui/QGIS
    def __init__(self):
        """ Initialize data objects, starts fetching if appropriate, and warn about/removes obsolete plugins """

        QObject.__init__(self)  # initialize QObject in order to to use self.tr()
        repositories.load()
        plugins.getAllInstalled()

        if repositories.checkingOnStart() and repositories.timeForChecking() and repositories.allEnabled():
            # start fetching repositories
            self.statusLabel = QLabel(self.tr("Looking for new plugins...") + " ", iface.mainWindow().statusBar())
            iface.mainWindow().statusBar().insertPermanentWidget(0, self.statusLabel)
            self.statusLabel.linkActivated.connect(self.showPluginManagerWhenReady)
            repositories.checkingDone.connect(self.checkingDone)
            for key in repositories.allEnabled():
                repositories.requestFetching(key)
        else:
            # no fetching at start, so mark all enabled repositories as requesting to be fetched.
            for key in repositories.allEnabled():
                repositories.setRepositoryData(key, "state", 3)

        # look for obsolete plugins (the user-installed one is newer than core one)
        for key in plugins.obsoletePlugins:
            plugin = plugins.localCache[key]
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setWindowTitle(self.tr("QGIS Python Plugin Installer"))
            msg.addButton(self.tr("Uninstall (recommended)"), QMessageBox.AcceptRole)
            msg.addButton(self.tr("I will uninstall it later"), QMessageBox.RejectRole)
            msg.setText(
                "%s <b>%s</b><br/><br/>%s"
                % (
                    self.tr("Obsolete plugin:"),
                    plugin["name"],
                    self.tr(
                        "QGIS has detected an obsolete plugin that masks its more recent version shipped with this copy of QGIS. This is likely due to files associated with a previous installation of QGIS. Do you want to remove the old plugin right now and unmask the more recent version?"
                    ),
                )
            )
            msg.exec_()
            if not msg.result():
                # uninstall, update utils and reload if enabled
                self.uninstallPlugin(key, quiet=True)
                updateAvailablePlugins()
                settings = QSettings()
                if settings.value("/PythonPlugins/" + key, False, type=bool):
                    settings.setValue("/PythonPlugins/watchDog/" + key, True)
                    loadPlugin(key)
                    startPlugin(key)
                    settings.remove("/PythonPlugins/watchDog/" + key)
예제 #15
0
def __get_plugin_deps(plugin_id):
    result = {}
    updateAvailablePlugins()
    try:
        parser = metadataParser()[plugin_id]
        plugin_deps = parser.get('general', 'plugin_dependencies')
    except (NoOptionError, NoSectionError, KeyError):
        return result

    for dep in plugin_deps.split(','):
        if dep.find('==') > 0:
            name, version_required = dep.split('==')
        else:
            name = dep
            version_required = None
        result[name] = version_required
    return result
예제 #16
0
def __get_plugin_deps(plugin_id):
    result = {}
    updateAvailablePlugins()
    try:
        parser = metadataParser()[plugin_id]
        plugin_deps = parser.get('general', 'plugin_dependencies')
    except (NoOptionError, NoSectionError, KeyError):
        return result

    for dep in plugin_deps.split(','):
        if dep.find('==') > 0:
            name, version_required = dep.split('==')
        else:
            name = dep
            version_required = None
        result[name] = version_required
    return result
예제 #17
0
 def run(self):
   plugin = currentPlugin()
   #update the plugin list first! The plugin could be removed from the list if was temporarily broken.
   updateAvailablePlugins()
   #try to load from scratch the plugin saved in QSettings if not loaded
   if not plugins.has_key(plugin):
     try:
       loadPlugin(plugin)
       startPlugin(plugin)
     except:
       pass
   updateAvailablePlugins()
   #give one chance for correct (not a loop)
   if not plugins.has_key(plugin):
     self.configure()
     plugin = currentPlugin()
   if plugins.has_key(plugin):
     reloadPlugin(plugin)
예제 #18
0
 def run(self):
     plugin = currentPlugin()
     #update the plugin list first! The plugin could be removed from the list if was temporarily broken.
     updateAvailablePlugins()
     #try to load from scratch the plugin saved in QSettings if not loaded
     if not plugins.has_key(plugin):
         try:
             loadPlugin(plugin)
             startPlugin(plugin)
         except:
             pass
     updateAvailablePlugins()
     #give one chance for correct (not a loop)
     if not plugins.has_key(plugin):
         self.configure()
         plugin = currentPlugin()
     if plugins.has_key(plugin):
         reloadPlugin(plugin)
예제 #19
0
    def test_update_available_plugins(self):
        utils.plugin_paths = [
            os.path.join(unitTestDataPath(), "test_plugin_path")
        ]
        utils.updateAvailablePlugins(True)
        self.assertIn("PluginPathTest", utils.available_plugins)
        self.assertIn("dependent_plugin_1", utils.available_plugins)
        self.assertIn("dependent_plugin_2", utils.available_plugins)

        idx_independent_plugin = utils.available_plugins.index(
            "PluginPathTest")
        idx_dependent_plugin_1 = utils.available_plugins.index(
            "dependent_plugin_1")
        idx_dependent_plugin_2 = utils.available_plugins.index(
            "dependent_plugin_2")

        self.assertGreater(idx_dependent_plugin_2, idx_dependent_plugin_1)
        self.assertGreater(idx_dependent_plugin_1, idx_independent_plugin)
예제 #20
0
    def test_sort_by_dependency(self):
        plugins = [
            "dependent_plugin_2", "dependent_plugin_1", "PluginPathTest"
        ]
        plugin_name_map = {
            "Dependent plugin 2": "dependent_plugin_2",
            "Dependent plugin 1": "dependent_plugin_1",
            "plugin path test": "PluginPathTest"
        }

        utils.plugin_paths = [
            os.path.join(unitTestDataPath(), "test_plugin_path")
        ]
        utils.updateAvailablePlugins(
        )  # Required to have a proper plugins_metadata_parser
        sorted_plugins = utils._sortAvailablePlugins(plugins, plugin_name_map)

        expected_sorted_plugins = [
            "PluginPathTest", "dependent_plugin_1", "dependent_plugin_2"
        ]
        self.assertEqual(sorted_plugins, expected_sorted_plugins)
예제 #21
0
def applyPlugins(profile):
    if profile.plugins is None:
        return
    toInstall = [
        p for p in profile.plugins if p not in utils.available_plugins
    ]
    pluginErrors = []
    for p in toInstall:
        error = installPlugin(p)
        if error:
            pluginErrors.append(error)

    settings = QSettings()

    ignore = list(pluginsToIgnore)
    layers = list(QgsMapLayerRegistry.instance().mapLayers().values())
    for lyr in layers:
        if lyr.type() == QgsMapLayer.PluginLayer:
            ignore.extend(pluginsWithLayers)
            break

    tounload = [p for p in utils.active_plugins if p not in ignore]
    for p in tounload:
        try:
            unloadPlugin(p)
        except:
            pass
        settings.setValue('/PythonPlugins/' + p, False)

    updateAvailablePlugins()

    for p in profile.plugins:
        if p not in utils.active_plugins and p in utils.available_plugins:
            loadPlugin(p)
            startPlugin(p)
            settings.setValue('/PythonPlugins/' + p, True)
    updateAvailablePlugins()
    updatePluginManager()

    return pluginErrors
예제 #22
0
 def install(self, ref, progress = None):
     filename = tempFilename("zip")
     tmpFolder = tempSubFolder()
     url = "https://github.com/%s/%s/archive/%s.zip" % (self.user, self.reponame, ref)
     urllib.urlretrieve(url, filename, reporthook=progress)        
     with open(filename, 'rb') as f:
         z = zipfile.ZipFile(f)
         z.extractall(tmpFolder)
     packageName = os.path.basename(self.folder)
     path = os.path.join(tmpFolder, "%s-%s" % (self.reponame, ref), packageName)
     print path
     print filename
     print self.folder
     if os.path.exists(self.folder):
         shutil.rmtree(self.folder, True)
     #mkdir(self.folder)
     shutil.copytree(path, self.folder)
     with open(self.commitIdFile(), "w") as f:
         f.write("\n".join([ref, self.dateFromRef(ref)]))
     updateAvailablePlugins()
     
     loadPlugin(packageName)
예제 #23
0
 def run(self):
     plugin = currentPlugin()
     #update the plugin list first! The plugin could be removed from the list if was temporarily broken.
     updateAvailablePlugins()
     #try to load from scratch the plugin saved in QSettings if not loaded
     if plugin not in plugins:
         try:
             loadPlugin(plugin)
             startPlugin(plugin)
         except:
             pass
     updateAvailablePlugins()
     #give one chance for correct (not a loop)
     if plugin not in plugins:
         self.configure()
         plugin = currentPlugin()
     if plugin in plugins:
         state = self.iface.mainWindow().saveState()
         reloadPlugin(plugin)
         self.iface.mainWindow().restoreState(state)
         self.iface.messageBar().pushMessage("<b>%s</b> reloaded." % plugin,
                                             QGis.Info)
예제 #24
0
  def __init__(self, parent):
    QDialog.__init__(self)
    self.iface = parent
    self.setupUi(self)
    #update the plugin list first! The plugin could be removed from the list if was temporarily broken.
    #Still doesn't work in every case. TODO?: try to load from scratch the plugin saved in QSettings if doesn't exist
    plugin = currentPlugin()
    updateAvailablePlugins()
    #if plugin not in plugins:
      #try:
        #loadPlugin(plugin)
        #startPlugin(plugin)
      #except:
        #pass
    #updateAvailablePlugins()

    plugins_list = sorted(plugins.keys())
    for plugin in plugins_list:
      self.comboPlugin.addItem(plugin)
    plugin = currentPlugin()
    if plugin in plugins:
      self.comboPlugin.setCurrentIndex(plugins_list.index(plugin))
예제 #25
0
def applyPlugins(profile):
    if profile.plugins is None:
        return
    toInstall = [p  for p in profile.plugins if p not in utils.available_plugins]
    pluginErrors = []
    for p in toInstall:
        error = installPlugin(p)
        if error:
            pluginErrors.append(error)

    settings = QSettings()

    ignore = list(pluginsToIgnore)
    layers = QgsMapLayerRegistry.instance().mapLayers().values()
    for lyr in layers:
        if lyr.type() == QgsMapLayer.PluginLayer:
            ignore.extend(pluginsWithLayers)
            break

    tounload = [p for p in utils.active_plugins if p not in ignore]
    for p in tounload:
        try:
            unloadPlugin(p)
        except:
            pass
        settings.setValue('/PythonPlugins/' + p, False)

    updateAvailablePlugins()

    for p in profile.plugins:
        if p not in utils.active_plugins and p in utils.available_plugins:
            loadPlugin(p)
            startPlugin(p)
            settings.setValue('/PythonPlugins/' + p, True)
    updateAvailablePlugins()
    updatePluginManager()

    return pluginErrors
예제 #26
0
  def __init__(self, parent):
    QDialog.__init__(self)
    self.iface = parent
    self.setupUi(self)
    self.plugins = plugins.keys()
    self.plugins.sort()
    #update the plugin list first! The plugin could be removed from the list if was temporarily broken.
    #Still doesn't work in every case. TODO?: try to load from scratch the plugin saved in QSettings if doesn't exist
    plugin = currentPlugin()
    updateAvailablePlugins()
    #if not plugins.has_key(plugin):
      #try:
        #loadPlugin(plugin)
        #startPlugin(plugin)
      #except:
        #pass
    #updateAvailablePlugins()

    for plugin in self.plugins:
      self.comboPlugin.addItem(plugin)
    plugin = currentPlugin()
    if plugins.has_key(plugin):
      self.comboPlugin.setCurrentIndex(self.plugins.index(plugin))
예제 #27
0
    def install(self, ref, progress=None):
        filename = tempFilename("zip")
        tmpFolder = tempSubFolder()
        url = "https://github.com/%s/%s/archive/%s.zip" % (self.user,
                                                           self.reponame, ref)
        urllib.urlretrieve(url, filename, reporthook=progress)
        with open(filename, 'rb') as f:
            z = zipfile.ZipFile(f)
            z.extractall(tmpFolder)
        packageName = os.path.basename(self.folder)
        path = os.path.join(tmpFolder, "%s-%s" % (self.reponame, ref),
                            packageName)
        print path
        print filename
        print self.folder
        if os.path.exists(self.folder):
            shutil.rmtree(self.folder, True)
        #mkdir(self.folder)
        shutil.copytree(path, self.folder)
        with open(self.commitIdFile(), "w") as f:
            f.write("\n".join([ref, self.dateFromRef(ref)]))
        updateAvailablePlugins()

        loadPlugin(packageName)
예제 #28
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)
예제 #29
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)
예제 #30
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)
예제 #31
0
def find_dependencies(plugin_id, plugin_data=None, plugin_deps=None, installed_plugins=None):
    """Finds the plugin dependencies and checks if they can be installed or upgraded

    :param plugin_id: plugin id
    :type plugin_id: str
    :param plugin_data: for testing only: dictionary of plugin data from the repo, defaults to None
    :param plugin_data: dict, optional
    :param plugin_deps: for testing only: dict of plugin id -> version_required, parsed from metadata value for "plugin_dependencies", defaults to None
    :param plugin_deps: dict, optional
    :param installed_plugins: for testing only: dict of plugin id -> version_installed
    :param installed_plugins: dict, optional
    :return: result dictionaries keyed by plugin name with: to_install, to_upgrade, not_found
    :rtype: tuple of dicts
    """

    to_install = {}
    to_upgrade = {}
    not_found = {}

    if plugin_deps is None:
        plugin_deps = __get_plugin_deps(plugin_id)

    if installed_plugins is None:
        updateAvailablePlugins()
        metadata_parser = updateAvailablePlugins()
        installed_plugins = {metadata_parser[k].get('general', 'name'): metadata_parser[k].get('general', 'version') for k, v in metadata_parser.items()}

    if plugin_data is None:
        plugin_data = plugin_installer.plugins.all()

    plugins_map = __plugin_name_map(plugin_data.values())

    # Review all dependencies
    for name, version_required in plugin_deps.items():
        try:
            p_id = plugins_map[name]
        except KeyError:
            not_found.update({name: {
                'id': None,
                'version_installed': None,
                'version_required': None,
                'version_available': None,
                'action': None,
                'error': 'missing_id'
            }})
            continue

        affected_plugin = dict({
            "id": p_id,
            # "version_installed": installed_plugins.get(p_id, {}).get('installed_plugins', None),
            "version_installed": installed_plugins.get(name, None),
            "version_required": version_required,
            "version_available": plugin_data[p_id].get('version_available', None),
            "action": None,
        })

        # Install is needed
        if name not in installed_plugins:
            affected_plugin['action'] = 'install'
            destination_list = to_install
        # Upgrade is needed
        elif version_required is not None and compareVersions(installed_plugins[name], version_required) == 2:
            affected_plugin['action'] = 'upgrade'
            destination_list = to_upgrade
        # TODO @elpaso: review installed but not activated
        # No action is needed
        else:
            continue

        if affected_plugin['version_required'] == affected_plugin['version_available'] or affected_plugin['version_required'] is None:
            destination_list.update({name: affected_plugin})
        else:
            affected_plugin['error'] = 'unavailable {}'.format(affected_plugin['action'])
            not_found.update({name: affected_plugin})

    return to_install, to_upgrade, not_found
예제 #32
0
  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 _removeTestPlugin():
     unloadPlugin("what3words")
     updateAvailablePlugins()
     updatePluginManager()
     assert "what3words" not in available_plugins
    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)
예제 #35
0
def find_dependencies(plugin_id, plugin_data=None, plugin_deps=None, installed_plugins=None):
    """Finds the plugin dependencies and checks if they can be installed or upgraded

    :param plugin_id: plugin id
    :type plugin_id: str
    :param plugin_data: for testing only: dictionary of plugin data from the repo, defaults to None
    :param plugin_data: dict, optional
    :param plugin_deps: for testing only: dict of plugin id -> version_required, parsed from metadata value for "plugin_dependencies", defaults to None
    :param plugin_deps: dict, optional
    :param installed_plugins: for testing only: dict of plugin id -> version_installed
    :param installed_plugins: dict, optional
    :return: result dictionaries keyed by plugin name with: to_install, to_upgrade, not_found
    :rtype: tuple of dicts
    """

    to_install = {}
    to_upgrade = {}
    not_found = {}

    if plugin_deps is None:
        plugin_deps = __get_plugin_deps(plugin_id)

    if installed_plugins is None:
        updateAvailablePlugins()
        metadata_parser = updateAvailablePlugins()
        installed_plugins = {metadata_parser[k].get('general', 'name'): metadata_parser[k].get('general', 'version') for k, v in metadata_parser.items()}

    if plugin_data is None:
        plugin_data = plugin_installer.plugins.all()

    plugins_map = __plugin_name_map(plugin_data.values())

    # Review all dependencies
    for name, version_required in plugin_deps.items():
        try:
            p_id = plugins_map[name]
        except KeyError:
            not_found.update({name: {
                'id': None,
                'version_installed': None,
                'version_required': None,
                'version_available': None,
                'action': None,
                'error': 'missing_id'
            }})
            continue

        affected_plugin = dict({
            "id": p_id,
            # "version_installed": installed_plugins.get(p_id, {}).get('installed_plugins', None),
            "version_installed": installed_plugins.get(name, None),
            "version_required": version_required,
            "version_available": plugin_data[p_id].get('version_available', None),
            "action": None,
        })

        # Install is needed
        if name not in installed_plugins:
            affected_plugin['action'] = 'install'
            destination_list = to_install
        # Upgrade is needed
        elif version_required is not None and compareVersions(installed_plugins[name], version_required) == 2:
            affected_plugin['action'] = 'upgrade'
            destination_list = to_upgrade
        # TODO @elpaso: review installed but not activated
        # No action is needed
        else:
            continue

        if affected_plugin['version_required'] == affected_plugin['version_available'] or affected_plugin['version_required'] is None:
            destination_list.update({name: affected_plugin})
        else:
            affected_plugin['error'] = 'unavailable {}'.format(affected_plugin['action'])
            not_found.update({name: affected_plugin})

    return to_install, to_upgrade, not_found
예제 #36
0
    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])
예제 #37
0
 def _removeTestPlugin():
     unloadPlugin("what3words")
     updateAvailablePlugins()
     updatePluginManager()
     assert "what3words" not in available_plugins