Ejemplo n.º 1
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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
 def uninstallPlugin(self, key, quiet=False):
     """ Uninstall given plugin """
     if plugins.all().has_key(key):
         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
     try:
         unloadPlugin(key)
     except:
         pass
     pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/" + plugin["id"]
     result = removeDir(pluginDir)
     if result:
         QMessageBox.warning(iface.mainWindow(), self.tr("Plugin uninstall failed"), result)
     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()
         QMessageBox.information(
             iface.mainWindow(),
             self.tr("Plugin uninstalled successfully"),
             self.tr("Plugin uninstalled successfully"),
         )
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
 def uninstallPlugin(self, key, quiet=False):
     """ Uninstall given plugin """
     if plugins.all().has_key(key):
         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
     try:
         unloadPlugin(key)
     except:
         pass
     pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path(
     ) + "/python/plugins/" + plugin["id"]
     result = removeDir(pluginDir)
     if result:
         QMessageBox.warning(iface.mainWindow(),
                             self.tr("Plugin uninstall failed"), result)
     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()
         QMessageBox.information(iface.mainWindow(),
                                 self.tr("Plugin uninstalled successfully"),
                                 self.tr("Plugin uninstalled successfully"))
Ejemplo n.º 6
0
 def uninstallPlugin(self,key):
   """ uninstall currently selected plugin """
   plugin = plugins.all()[key]
   if not plugin:
     return
   warning = self.tr("Are you sure you want to uninstall the following plugin?") + "\n(" + plugin["name"] + ")"
   if plugin["status"] == "orphan" and not plugin["error"]:
     warning += "\n\n"+self.tr("Warning: this plugin isn't available in any accessible repository!")
   if QMessageBox.warning(self, self.tr("QGIS Python Plugin Installer"), warning , QMessageBox.Yes, QMessageBox.No) == QMessageBox.No:
     return
   # unload the plugin if it's not plugin_installer itself (otherwise, do it after removing its directory):
   if key != "plugin_installer":
     try:
       unloadPlugin(key)
     except:
       pass
   pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/python/plugins/" + plugin["localdir"]
   result = removeDir(pluginDir)
   if result:
     QMessageBox.warning(self, self.tr("Plugin uninstall failed"), result)
   else:
     # if the uninstalled plugin is the installer itself, reload it and quit
     if key == "plugin_installer":
       if QGIS_15:
         try:
           QMessageBox.information(self, self.tr("QGIS Python Plugin Installer"), self.tr("Plugin Installer update uninstalled. Plugin Installer will now close and revert to its primary version. You can find it in the Plugins menu and continue operation."))
           reloadPlugin(key)
           return
         except:
           pass
       else:
         QMessageBox.information(self, self.tr("QGIS Python Plugin Installer"), self.tr("Plugin Installer update uninstalled. Please restart QGIS in order to load its primary version."))
     # safe remove
     try:
       unloadPlugin(plugin["localdir"])
     except:
       pass
     try:
       exec ("plugins[%s].unload()" % plugin["localdir"])
       exec ("del plugins[%s]" % plugin["localdir"])
     except:
       pass
     try:
       exec ("del sys.modules[%s]" % plugin["localdir"])
     except:
       pass
     plugins.getAllInstalled()
     plugins.rebuild()
     self.populatePluginTree()
     if QGIS_14: QMessageBox.information(self, self.tr("Plugin uninstalled successfully"), self.tr("Plugin uninstalled successfully"))
     else: QMessageBox.information(self, self.tr("Plugin uninstalled successfully"), self.tr("Python plugin uninstalled. Note that you may need to restart Quantum GIS in order to remove it completely."))
     history.markChange(key,'D')
Ejemplo n.º 7
0
def classFactory(iface):  # pylint: disable=invalid-name
    try:
        from qkan import Dummy as MainDummy
        if not MainDummy.instance:  # QKan isn't loaded
            raise Exception('The QKan main plugin has to be loaded before loading this extension.')

        dummy = Dummy(iface, MainDummy.instance)
        return dummy
    except ImportError:
        import traceback
        traceback.print_exc()
        unloadPlugin(__name__)
        raise Exception('The QKan main plugin has to be installed for this extension to work.')
    def testInstallFromZip(self):
        """Test plugin installation from ZIP package"""
        pluginPath = os.path.join(testPath, 'data', 'connecttest.zip')
        result = utils.installFromZipFile(pluginPath)
        self.assertIsNone(result), 'Error installing plugin: {}'.format(result)
        self.assertTrue('connecttest' in qgsutils.active_plugins), 'Plugin not activated'

        unloadPlugin('connecttest')
        result = removeDir(os.path.join(home_plugin_path, 'connecttest'))
        self.assertFalse(result, 'Plugin directory not removed')
        result = utils.installFromZipFile(pluginPath)
        self.assertIsNone(result), 'Error installing plugin: {}'.format(result)
        self.assertTrue('connecttest' in qgsutils.active_plugins), 'Plugin not activated after reinstallation'
Ejemplo n.º 9
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
Ejemplo n.º 10
0
    def unload(self):
        from qgis.utils import unloadPlugin
        # Unload all other instances
        for instance in self.instances:
            print('Unloading ', instance.name)
            if not unloadPlugin(instance.name):
                print('Failed to unload plugin!')

        # Remove entries from own menu
        for action in self.menu.actions():
            self.menu.removeAction(action)

        # Remove entries from Plugin menu and toolbar
        for action in self.actions:
            self.iface.removeToolBarIcon(action)

        # Remove the toolbar
        del self.toolbar

        # Remove menu
        self.iface.mainWindow().menuBar().removeAction(self.menu_action)

        # Call unload on all loaded plugins
        for plugin in self.plugins:
            plugin.unload()
Ejemplo n.º 11
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
Ejemplo n.º 12
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
Ejemplo n.º 13
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)
Ejemplo n.º 14
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)
 def _removeTestPlugin():
     unloadPlugin("what3words")
     updateAvailablePlugins()
     updatePluginManager()
     assert "what3words" not in available_plugins
Ejemplo n.º 16
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)
Ejemplo n.º 17
0
 def uninstallPlugin(self, key):
     """ uninstall currently selected plugin """
     plugin = plugins.all()[key]
     if not plugin:
         return
     warning = self.tr(
         "Are you sure you want to uninstall the following plugin?"
     ) + "\n(" + plugin["name"] + ")"
     if plugin["status"] == "orphan" and not plugin["error"]:
         warning += "\n\n" + self.tr(
             "Warning: this plugin isn't available in any accessible repository!"
         )
     if QMessageBox.warning(self, self.tr("QGIS Python Plugin Installer"),
                            warning, QMessageBox.Yes,
                            QMessageBox.No) == QMessageBox.No:
         return
     # unload the plugin if it's not plugin_installer itself (otherwise, do it after removing its directory):
     if key != "plugin_installer":
         try:
             unloadPlugin(key)
         except:
             pass
     pluginDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path(
     ) + "/python/plugins/" + plugin["localdir"]
     result = removeDir(pluginDir)
     if result:
         QMessageBox.warning(self, self.tr("Plugin uninstall failed"),
                             result)
     else:
         # if the uninstalled plugin is the installer itself, reload it and quit
         if key == "plugin_installer":
             if QGIS_15:
                 try:
                     QMessageBox.information(
                         self, self.tr("QGIS Python Plugin Installer"),
                         self.
                         tr("Plugin Installer update uninstalled. Plugin Installer will now close and revert to its primary version. You can find it in the Plugins menu and continue operation."
                            ))
                     reloadPlugin(key)
                     return
                 except:
                     pass
             else:
                 QMessageBox.information(
                     self, self.tr("QGIS Python Plugin Installer"),
                     self.
                     tr("Plugin Installer update uninstalled. Please restart QGIS in order to load its primary version."
                        ))
         # safe remove
         try:
             unloadPlugin(plugin["localdir"])
         except:
             pass
         try:
             exec("plugins[%s].unload()" % plugin["localdir"])
             exec("del plugins[%s]" % plugin["localdir"])
         except:
             pass
         try:
             exec("del sys.modules[%s]" % plugin["localdir"])
         except:
             pass
         plugins.getAllInstalled()
         plugins.rebuild()
         self.populatePluginTree()
         if QGIS_14:
             QMessageBox.information(
                 self, self.tr("Plugin uninstalled successfully"),
                 self.tr("Plugin uninstalled successfully"))
         else:
             QMessageBox.information(
                 self, self.tr("Plugin uninstalled successfully"),
                 self.
                 tr("Python plugin uninstalled. Note that you may need to restart Quantum GIS in order to remove it completely."
                    ))
         history.markChange(key, 'D')
Ejemplo n.º 18
0
 def _removeTestPlugin():
     unloadPlugin("what3words")
     updateAvailablePlugins()
     updatePluginManager()
     assert "what3words" not in available_plugins
def sigmena():
    #lo que pongamos aqui se va a reproducir cada vez que se abra un qgis en forma de ventana a la que hay que dar a aceptar, vale para informacion muy importante pero es un toston
    #QMessageBox.information(None, "SIGMENA", "Abres un QGIS configurado por SIGMENA") 
    iface.messageBar().pushMessage("SIGMENA", "Acabas de abrir una instancia de QGIS configurada por SIGMENA", duration=15)
    
#respecto a los sistemas de referencia con ello lo definimos por defecto a nivel usuario.
    crs = 'EPSG:25830'
    
    QSettings().setValue('/Projections/layerDefaultCrs', crs)
    QSettings().setValue("/app/projections/defaultProjectCrs", crs )
    QSettings().setValue("/app/projections/unknownCrsBehavior","UseProjectCrs")
    QSettings().setValue("/app/projections/newProjectCrsBehavior","UsePresetCrs")
    QSettings().setValue("/Projections/EPSG:23030//EPSG:25830_coordinateOp","+proj=pipeline +step +inv +proj=utm +zone=30 +ellps=intl +step +proj=hgridshift +grids=SPED2ETV2.gsb +step +proj=utm +zone=30 +ellps=GRS80")
    #Projections/showDatumTransformDialog
    
#informacion nueva en sigmena
    QSettings().setValue('/core/NewsFeed\httpsfeedqgisorg\disabled','false')

    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210324/title',"Complemento calcula hectareas mientras editas")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210324/content',"<p style=color:green;>Este complemento os ayudará a cuadrar las superficies en las propuestas</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210324/link',"O:/sigmena/notas/blog_sigmena/EDICION.html")



    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210225/title',"Ortofotos 2020")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210225/content',"<p>Empiezan a estar disponibles las ortofotos de PNOA 2020. En teoría tendremos disponible toda la provincia pero han empezado a liberar la zona oeste y norte. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210225/link',"O:/sigmena/notas/blog_sigmena/ORTOFOTOS.html")

    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210414/title',"Fotovoltaicos y Eolicos")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210414/content',"<p>Desde QGIS puedes visualizar la cartografia del MITECO de sensibilidad ambiental a estos parques. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210414/link',"O:/sigmena/notas/blog_sigmena/RENOVABLES.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210224/title',"Actualización a SIGPAC 2021")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210224/content',"<p> Nos han pasado desde Agricultura la cartografía del <b>Sigpac actualizada a 2021</b>. Si utilizais el complemento ya os carga la cartografía nueva. He aprovechado para actualizar el botón. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210224/link',"O:/sigmena/notas/blog_sigmena/SIGPAC.html")


    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210220/title',"Plan de Monitorización de Fauna")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210220/content',"<p style=color:red;> Tenemos nueva cartografía del <b>Plan de Monitorización de Fauna</b>. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210220/link',"O:/sigmena/notas/blog_sigmena/ESPECIES.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210219/title',"Visor MACOTE")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210219/content',"<p> Tragsa ha generado un visor para tratar de estimar las zonas con en las que es posible la <b>extración de madera con Teleferico</b>. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210219/link',"O:/sigmena/notas/blog_sigmena/TODOS_LOS_ARTICULOS.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210212/title',"Estado vuelos LiDAR - PNOA")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210212/content',"<p> Hay en el Blog información nueva respecto al estado del vuelo <b>LiDAR</b>. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210212/link',"O:/sigmena/notas/blog_sigmena/LIDAR.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210209/title',"CARTOGRAFÍA FORESTACIÓN DE TIERRAS AGRÁRIAS")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210209/content',"<p> En el Blog he añadido una entrada referente a la cartografía que han recopilado desde Tragsa del programa de <b>forestación</b> de tierras agrárias. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210209/link',"O:/sigmena/notas/blog_sigmena/FORESTACION.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210211/title',"PERÍMETRO INCENDIOS 2020")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210211/content',"<p> En el Blog he añadido una entrada para que sepais que ya está la capa de perímetros de incendios 2020. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210211/link',"O:/sigmena/notas/Blog_Sigmena/INCENDIOS.html")
    
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210202/title',"IMAGENES DE SENTINEL")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210202/content',"<p> En el Blog he añadido una entrada referente a como cargar imagenes de Sentinel que he descargado del 2020. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210202/link',"O:/sigmena/notas/Blog_Sigmena/SENTINEL.html")
    
    

    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210124/title',"Blog SIGMENA")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210124/content',"<p>He creado un blog para teneros informados de las novedades que vayamos teniendo en SIGMENA. Haz click aquí para acceder.</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/image',"file:///o:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210124/link',"O:/sigmena/notas/Blog_Sigmena/TODOS_LOS_ARTICULOS.html")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210124/sticky','true')


    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/title',"MANUAL COMPLEMENTOS SIGMENA")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/content',"<p>Animacion para ver como funcionan los complementos SIGMENA. Pincha en este texto para saber mas</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/image',"file:///o:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/link',r"O:/sigmena/utilidad/PROGRAMA/QGIS/Complementos/Manual/Manual_complementos_SIGMENA.htm")
    
#repositorio de complementos sigmena  
    QSettings().setValue('/app/plugin_installer/checkOnStart','false')
    QSettings().setValue('/app/plugin_repositories/SIGMENA/url','https://raw.githubusercontent.com/diezrabanos/qgis_plugins/master/servidor_descargas_sigmena.xml')
    QSettings().setValue('/app/plugin_repositories/SIGMENA/authcfg','')
    QSettings().setValue('/app/plugin_repositories/Repositorio%20oficial%20de%20complementos%20de%20QGIS\enabled','false')
    QSettings().setValue('/app/plugin_repositories/SIGMENA/enabled','true')

#compruebo que existe la carpeta con los complementos
    directorio = home_plugin_path
    #try:
    #print("empiezo",file=debug)
    if os.path.isdir(directorio):
        os.stat(directorio)
        #print(len(complementos_con_version),file=debug)
        #if len(complementos_con_version)==0:
        versioninstalada="0.0.0"
        #para desinstalar si no la version correcta de un complemento
        for i in range(0,len(complementos_con_version)):
                #print("todos los complementos de la lista", file=debug)
                #print(complementos_con_version[i][0], file=debug)
                
                for x in findPlugins(home_plugin_path):
                    #print("todos los complementos que encuentra", file=debug)
                    #print(x[0], file=debug)
                    #print(x[0], file=debug)       
                    if x[0]==complementos_con_version[i][0]:
                         
                        
                        versioninstalada=str(x[1].get('general',"version"))
                        #print(versioninstalada, file=debug)
                        
                    #else:
                        #versioninstalada="0.0.0"
                        #print("pongo version 0.0.0", file=debug)
                        

                if versioninstalada==complementos_con_version[i][1]:
                    #print("no deberia hacer nada porque no hay ninguna actualziacion", file=debug)
                    
                
                    continue
                else:
                    #print ("se supone que desinstalo",complementos_con_version[i][0], file = debug)
                    #print(versioninstalada,complementos_con_version[i][1], file = debug)
                    unloadPlugin(complementos_con_version[i][0])#desinstala si version antigua de un complemento instalado
                    #print("plugins a instalar ",complementos_con_version[i][0], file = debug)
                    #para instalar un complemento                
                    # Installing
                    zip_ref = zipfile.ZipFile('O:/sigmena/utilidad/PROGRAMA/QGIS/Complementos/'+complementos_con_version[i][0]+'.zip', 'r')
                    zip_ref.extractall(home_plugin_path)
                    zip_ref.close()
                    loadPlugin(complementos_con_version[i][0])
                    startPlugin(complementos_con_version[i][0])
                    #print("desinstalo e instalo",file=debug)
     

    else:
        os.mkdir(directorio)
        for i in range(0,len(complementos_con_version)):
        #para instalar un complemento                
                        # Installing
                        zip_ref = zipfile.ZipFile('O:/sigmena/utilidad/PROGRAMA/QGIS/Complementos/'+complementos_con_version[i][0]+'.zip', 'r')
                        zip_ref.extractall(home_plugin_path)
                        zip_ref.close()
                        loadPlugin(complementos_con_version[i][0])
                        startPlugin(complementos_con_version[i][0])

     

  
    
    #esto es para que si estan instalados los active    
    try:  
        QSettings().setValue('/PythonPlugins/zoomSigmena','true')
        QSettings().setValue('/PythonPlugins/alidadas','true')
        QSettings().setValue('/PythonPlugins/gpsDescargaCarga','true')
        QSettings().setValue('/PythonPlugins/hectareas','true')
        QSettings().setValue('/PythonPlugins/sigpac','true')
        QSettings().setValue('/PythonPlugins/silvilidar','true')
        QSettings().setValue('/PythonPlugins/puntossigmena','true')
        QSettings().setValue('/PythonPlugins/ptos2pol','true')
        QSettings().setValue('/PythonPlugins/censosPuntos','true')
        QSettings().setValue('/PythonPlugins/HectareasEdicion','true')
        
    except:
        pow
#para que no pierda tiempo buscando si hay actualizaciones de los complementos instalados
    QSettings().setValue("/app/plugin_installer/checkOnStart","false")

#para anadir los wms que sean interesantes, TIRA DE LAS DOS LISTAS DE ARRIBA

    for WMS_URL, WMS_NAME in zip(lista_WMS_URL,lista_WMS_NAME):
        if "Qgis/WMS/%s/authcfg" % WMS_NAME not in QSettings().allKeys():
            QSettings().setValue("/qgis/WMS/%s/authcfg" % WMS_NAME, "")
            QSettings().setValue("/qgis/WMS/%s/username" % WMS_NAME, "")
            QSettings().setValue("/qgis/WMS/%s/password" % WMS_NAME, "")
            QSettings().setValue("/qgis/connections-wms/%s/dpiMode" % WMS_NAME, 7)
            QSettings().setValue("/qgis/connections-wms/%s/ignoreAxisOrientation" % WMS_NAME, False)
            QSettings().setValue("/qgis/connections-wms/%s/ignoreGetFeatureInfoURI" % WMS_NAME, False)
            QSettings().setValue("/qgis/connections-wms/%s/ignoreGetMapURI" % WMS_NAME, False)
            QSettings().setValue("/qgis/connections-wms/%s/invertAxisOrientation" % WMS_NAME, False)
            QSettings().setValue("/qgis/connections-wms/%s/referer" % WMS_NAME, "")
            QSettings().setValue("/qgis/connections-wms/%s/smoothPixmapTransform" % WMS_NAME, "")
            QSettings().setValue("/qgis/connections-wms/%s/url" % WMS_NAME, WMS_URL)

#para anadir las imagenes de teselas

    for xyz_name, xyz_url in zip(lista_xyz_name,lista_xyz_url):
        if "qgis/connections-xyz/%s/url" % xyz_name not in QSettings().allKeys():
            #QSettings().setValue("/qgis/connections-xyz/Bing%20Sat%E9lite/url","http://ecn.t3.tiles.virtualearth.net/tiles/a{q}.jpeg?g=0&dir=dir_n\x2019")
            #QSettings().setValue("/qgis/connections-xyz/relieve/url","https://mt1.google.com/vt/lyrs=t&x={x}&y={y}&z={z}")
            QSettings().setValue("/qgis/connections-xyz/%s/url" % xyz_name, "%s" % xyz_url)
# Remove a QGIS toolbar (e.g., the File toolbar)
    #fileToolBar = self.iface.fileToolBar()
    #self.iface.mainWindow().removeToolBar( fileToolBar )
            
#para importar estilos de un archivo xml

    style=QgsStyle.defaultStyle()
    style.importXml(archivosestilos)
    for estilo in estilosfavoritos:
        print (estilo)
        style.addFavorite(QgsStyle.SymbolEntity, estilo)
#style.addFavorite(QgsStyle.SymbolEntity, 'vvpp')

#para que muestre el wms de sentibilidad ambiental
    QSettings().setValue("/qgis/connections-wms/Sensibilidad_ambiental_eolicos/ignoreGetMapURI","true")
    QSettings().setValue("/qgis/connections-wms/Sensibilidad_ambiental_fotovoltaicos/ignoreGetMapURI","true")

#para que por defecto coja la ruta donde estan las plantillas de mapas, composiciones de mapas en formato qpt
    QSettings().setValue("/app/LastComposerTemplateDir","O:/sigmena/leyendas")

#para evitar problemas con la codificacion de las capas, caracteres extranos
    QSettings().setValue("/UI/encoding","UTF-8")
    QSettings().setValue("/qgis/ignoreShapeEncoding","false")

#para establecer colores por defecto, la seleccion si no dice otra cosa el proyecto se hace en amarillo y semitransparente.
    QSettings().setValue("/qgis/default_selection_color_red","255")
    QSettings().setValue("/qgis/default_selection_color_green","255")
    QSettings().setValue("/qgis/default_selection_color_blue","0")
    QSettings().setValue("/qgis/default_selection_color_alpha","120")

#para hacer que las mediciones sean planimetricas, evitando el error por medir sobre el elipsoide
    #QSettings().setValue("/qgis/measure/planimetric","true")
    QSettings().setValue("/core/measure/planimetric","true")

#para que no compruebe si hay nuevas versiones
    QSettings().setValue("/qgis/checkVersion","false")

#para que el snapping este desactivado por defecto porque ralentiza mucho la edicion
    QSettings().setValue("/qgis/digitizing/default_snap_enabled","false")


#copiar el archivo de rejilla necesario, no me deja por los permisos de usuario lo hago con un bat
    
    #shutil.copy('O:/sigmena/utilidad/PROGRAMA/QGIS/SPED2ETV2.gsb', 'C:/Program Files/QGIS 3.10/share/proj/SPED2ETV2.gsb')


#activo la personalizacion de la visualizacion
    QSettings().setValue("/UI/Customization/enabled","true")
#copiar el archivo de configuracion visual de qgis
    usuario= QgsApplication.qgisSettingsDirPath()
    shutil.copy('O:/sigmena/utilidad/PROGRAMA/QGIS/QGISCUSTOMIZATION3.ini', os.path.join(usuario,'QGIS/QGISCUSTOMIZATION3.ini'))



#para copiar la funcion al usuario si no la tiene
    rutaexpresiones = home_plugin_path[:-7]+'expressions'
    if rutaexpresiones not in sys.path:
        sys.path.append(rutaexpresiones) 

    if os.path.isdir(rutaexpresiones):
        os.stat(rutaexpresiones)
        for elem in funciones:
            miruta=rutaexpresiones+'/'+elem+'.py'
            origen="O:/sigmena/utilidad/PROGRAMA/QGIS/Funciones/"+elem+'.py'
            if os.path.isfile(miruta):
                pass
            else: 
                copyfile(origen, miruta)
                #from intersecciona import intersecciona
                #QgsExpression.registerFunction(intersecciona)
                module = __import__(elem)
                func = getattr(module, elem)
                QgsExpression.registerFunction(func)
                
    else:
        os.mkdir(rutaexpresiones)
        for elem in funciones:
            miruta=rutaexpresiones+'/'+elem+'.py'
            origen="O:/sigmena/utilidad/PROGRAMA/QGIS/Funciones/"+elem+'.py'
            copyfile(origen, miruta)
            #from intersecciona import intersecciona
            #QgsExpression.registerFunction(intersecciona)
            module = __import__(elem)
            func = getattr(module, elem)
            QgsExpression.registerFunction(func)

    
    


#desabilito el snapping
    #iface.mainWindow().findChild(QDockWidget, 'Snapping and Digitizing Options').findChild(QDialog).findChild(QComboBox,'mSnapModeComboBox').setCurrentIndex(0) #0 = current layer 1 = all layers 2 = advanced
    #for item in QgsMapLayerRegistry.instance().mapLayers().values():
        #QgsProject.instance().setSnapSettingsForLayer(item.id(), False, 2, 0, 2, True)
    
    #iface.mapCanvas().snappingUtils().toggleEnabled()

#para incluir un decorador 
    from qgis.PyQt.Qt import QTextDocument
    from qgis.PyQt.QtGui import QFont
    mQFont = "Sans Serif"

    mQFontsize = 10
    mLabelQString = "SIGMENA"
    mMarginHorizontal = 0
    mMarginVertical = 0
    mLabelQColor = "#006600"
    mLabelQColor2 = "#FFFFFF"
    INCHES_TO_MM = 0.0393700787402 # 1 millimeter = 0.0393700787402 inches
    case = 3
    def add_copyright(p, text, xOffset, yOffset):
        p.translate( xOffset , yOffset )
        text.drawContents(p)
        p.setWorldTransform( p.worldTransform() )
    def _on_render_complete(p):
        deviceHeight = p.device().height() # Get paint device height on which this painter is currently painting
        deviceWidth = p.device().width() # Get paint device width on which this painter is currently painting
        # Create new container for structured rich text
        text = QTextDocument()
        font = QFont()
        font.setFamily(mQFont)
        font.setPointSize(int(mQFontsize))
        text.setDefaultFont(font)
        style = "<style type=\"text/css\"> p { color: " + mLabelQColor + " ; background: " + mLabelQColor2 + " }</style>" 
        text.setHtml( style + "<p>" + mLabelQString + "</p>" )
        # Text Size
        size = text.size()
        # RenderMillimeters
        pixelsInchX = p.device().logicalDpiX()
        pixelsInchY = p.device().logicalDpiY()
        xOffset = pixelsInchX * INCHES_TO_MM * int(mMarginHorizontal)
        yOffset = pixelsInchY * INCHES_TO_MM * int(mMarginVertical)
        # Calculate positions
        if case == 0:
            # Top Left
            add_copyright(p, text, xOffset, yOffset)
        elif case == 1:
            # Bottom Left
            yOffset = deviceHeight - yOffset - size.height()
            add_copyright(p, text, xOffset, yOffset)
        elif case == 2:
            # Top Right
            xOffset = deviceWidth - xOffset - size.width()
            add_copyright(p, text, xOffset, yOffset)
        elif case == 3:
            # Bottom Right
            yOffset = deviceHeight - yOffset - size.height()
            xOffset = deviceWidth - xOffset - size.width()
            add_copyright(p, text, xOffset, yOffset)
        elif case == 4:
            # Top Center
            xOffset = deviceWidth / 2
            add_copyright(p, text, xOffset, yOffset)
        else:
            # Bottom Center
            yOffset = deviceHeight - yOffset - size.height()
            xOffset = deviceWidth / 2
            add_copyright(p, text, xOffset, yOffset)
    # Emitted when the canvas has rendered
    iface.mapCanvas().renderComplete.connect(_on_render_complete)
    # Repaint the canvas map
    iface.mapCanvas().refresh()
    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)