Exemplo n.º 1
0
    def triggerResult(self, result):
        alg = QgsApplication.processingRegistry().createAlgorithmById(result.userData)
        if alg:
            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Missing dependency'))
                dlg.setMessage(message)
                dlg.exec_()
                return

            if [d for d in alg.parameterDefinitions() if
                    d.name() not in ('INPUT', 'OUTPUT')]:
                dlg = alg.createCustomParametersWidget(parent=iface.mainWindow())
                if not dlg:
                    dlg = AlgorithmDialog(alg, True, parent=iface.mainWindow())
                canvas = iface.mapCanvas()
                prevMapTool = canvas.mapTool()
                dlg.show()
                dlg.exec_()
                if canvas.mapTool() != prevMapTool:
                    try:
                        canvas.mapTool().reset()
                    except:
                        pass
                    canvas.setMapTool(prevMapTool)
            else:
                feedback = MessageBarProgress(algname=alg.displayName())
                parameters = {}
                execute_in_place(alg, parameters, feedback=feedback)
Exemplo n.º 2
0
def rearrangeToolbars(profile):
    settings = QSettings()
    key = "profilesplugin/Profiles/%s/geometry" % profile
    if settings.contains(key):
        iface.mainWindow().restoreGeometry(settings.value(key))
    else:
        toolbars = [el for el in iface.mainWindow().children() if isinstance(el, QToolBar) and el.isVisible()]
        toolbars = sorted(toolbars, key=lambda t: (t.geometry().top(), t.geometry().left()))
        for toolbar in toolbars:
            iface.mainWindow().removeToolBarBreak(toolbar)
        for toolbar in toolbars:
            iface.mainWindow().insertToolBarBreak(toolbar)
        rowWidth = 0
        lastY = None
        for toolbar in toolbars:
            if lastY is None:
                lastY = toolbar.geometry().top()
            actions = [a for a in toolbar.actions() if a.isVisible()]
            toolbarWidth = toolbar.actionGeometry(actions[-1]).right()
            rowWidth += toolbarWidth
            #print toolbar.objectName(), toolbarWidth, rowWidth
            if rowWidth < iface.mainWindow().width():
                iface.mainWindow().removeToolBarBreak(toolbar)
            else:
                lastY += toolbar.geometry().height()
                rowWidth = toolbarWidth
            toolbar.move(QPoint(rowWidth - toolbarWidth, lastY))
Exemplo n.º 3
0
    def _open(self):
        if self.plugin["status"] == "upgradeable":
            reply = QMessageBox.question(
                iface.mainWindow(),
                "Plugin",
                "An older version of the plugin is already installed. Do you want to upgrade it?",
                QMessageBox.Yes | QMessageBox.No)
            if reply != QMessageBox.Yes:
                return
        elif self.plugin["status"] in ["not installed", "new"]:
            pass
        else:
            reply = QMessageBox.question(
                iface.mainWindow(),
                "Plugin",
                "The plugin is already installed. Do you want to reinstall it?",
                QMessageBox.Yes | QMessageBox.No)
            if reply != QMessageBox.Yes:
                return

        def _install():
            installer = pyplugin_installer.instance()
            installer.installPlugin(self.plugin["id"])
            self.plugin["status"] = "installed"

        execute(_install)
Exemplo n.º 4
0
 def addRepository(self):
     """ add new repository connection """
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.checkBoxEnabled.setCheckState(Qt.Checked)
     if not dlg.exec_():
         return
     for i in repositories.all().values():
         if dlg.editURL.text().strip() == i["url"]:
             QMessageBox.warning(
                 iface.mainWindow(),
                 self.tr("QGIS Python Plugin Installer"),
                 self.tr("Unable to add another repository with the same URL!"),
             )
             return
     settings = QSettings()
     settings.beginGroup(reposGroup)
     reposName = dlg.editName.text()
     reposURL = dlg.editURL.text().strip()
     if repositories.all().has_key(reposName):
         reposName = reposName + "(2)"
     # add to settings
     settings.setValue(reposName + "/url", reposURL)
     settings.setValue(reposName + "/enabled", bool(dlg.checkBoxEnabled.checkState()))
     # refresh lists and populate widgets
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
Exemplo n.º 5
0
def createAlgorithmDialog(algOrName, parameters={}):
    """
    Creates and returns an algorithm dialog for the specified algorithm, prepopulated
    with a given set of parameters. It is the caller's responsibility to execute
    and delete this dialog.

    :param algOrName: Either an instance of an algorithm, or an algorithm's ID
    :param parameters: Initial algorithm parameters dictionary

    :returns algorithm results as a dictionary, or None if execution failed
    :rtype: Union[dict, None]
    """
    if isinstance(algOrName, QgsProcessingAlgorithm):
        alg = algOrName.create()
    else:
        alg = QgsApplication.processingRegistry().createAlgorithmById(algOrName)

    if alg is None:
        return False

    dlg = alg.createCustomParametersWidget(iface.mainWindow())

    if not dlg:
        dlg = AlgorithmDialog(alg, parent=iface.mainWindow())

    dlg.setParameters(parameters)

    return dlg
Exemplo n.º 6
0
 def canvasMoveEvent(self, e):                
     pt = self.toMapCoordinates(e.pos())
     mgrsCoord = self.toMgrs(pt)
     if mgrsCoord:
         iface.mainWindow().statusBar().showMessage("MGRS Coordinate: " + mgrsCoord)
     else:
         iface.mainWindow().statusBar().showMessage("")
Exemplo n.º 7
0
def addAlgorithmEntry(alg, menuName, submenuName, actionText=None, icon=None, addButton=False):
    if actionText is None:
        if (QgsGui.higFlags() & QgsGui.HigMenuTextIsTitleCase) and not (alg.flags() & QgsProcessingAlgorithm.FlagDisplayNameIsLiteral):
            alg_title = QgsStringUtils.capitalize(alg.displayName(), QgsStringUtils.TitleCase)
        else:
            alg_title = alg.displayName()
        actionText = alg_title + QCoreApplication.translate('Processing', '…')
    action = QAction(icon or alg.icon(), actionText, iface.mainWindow())
    alg_id = alg.id()
    action.setData(alg_id)
    action.triggered.connect(lambda: _executeAlgorithm(alg_id))
    action.setObjectName("mProcessingUserMenu_%s" % alg_id)

    if menuName:
        menu = getMenu(menuName, iface.mainWindow().menuBar())
        submenu = getMenu(submenuName, menu)
        submenu.addAction(action)

    if addButton:
        global algorithmsToolbar
        if algorithmsToolbar is None:
            algorithmsToolbar = iface.addToolBar(QCoreApplication.translate('MainWindow', 'Processing Algorithms'))
            algorithmsToolbar.setObjectName("ProcessingAlgorithms")
            algorithmsToolbar.setToolTip(QCoreApplication.translate('MainWindow', 'Processing Algorithms Toolbar'))
        algorithmsToolbar.addAction(action)
Exemplo n.º 8
0
    def fetchAvailablePlugins(self, reloadMode):
        """ Fetch plugins from all enabled repositories."""
        """  reloadMode = true:  Fully refresh data from QSettings to mRepositories  """
        """  reloadMode = false: Fetch unready repositories only """
        QApplication.setOverrideCursor(Qt.WaitCursor)

        if reloadMode:
            repositories.load()
            plugins.clearRepoCache()
            plugins.getAllInstalled()

        for key in repositories.allEnabled():
            if reloadMode or repositories.all()[key]["state"] == 3:  # if state = 3 (error or not fetched yet), try to fetch once again
                repositories.requestFetching(key)

        if repositories.fetchingInProgress():
            fetchDlg = QgsPluginInstallerFetchingDialog(iface.mainWindow())
            fetchDlg.exec_()
            del fetchDlg
            for key in repositories.all():
                repositories.killConnection(key)

        QApplication.restoreOverrideCursor()

        # display error messages for every unavailable reposioty, unless Shift pressed nor all repositories are unavailable
        keepQuiet = QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier)
        if repositories.allUnavailable() and repositories.allUnavailable() != repositories.allEnabled():
            for key in repositories.allUnavailable():
                if not keepQuiet:
                    QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Error reading repository:") + " " + key + "\n\n" + repositories.all()[key]["error"])
                if QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier):
                    keepQuiet = True
        # finally, rebuild plugins from the caches
        plugins.rebuild()
Exemplo n.º 9
0
 def checkingDone(self):
     """ Remove the "Looking for new plugins..." label and display a notification instead if any updates or news available """
     if not self.statusLabel:
         # only proceed if the label is present
         return
     # rebuild plugins cache
     plugins.rebuild()
     # look for news in the repositories
     plugins.markNews()
     status = ""
     # first check for news
     for key in plugins.all():
         if plugins.all()[key]["status"] == "new":
             status = self.tr("There is a new plugin available")
             tabIndex = 4  # PLUGMAN_TAB_NEW
     # then check for updates (and eventually overwrite status)
     for key in plugins.all():
         if plugins.all()[key]["status"] == "upgradeable":
             status = self.tr("There is a plugin update available")
             tabIndex = 3  # PLUGMAN_TAB_UPGRADEABLE
     # finally set the notify label
     if status:
         self.statusLabel.setText(u' <a href="%d">%s</a>  ' % (tabIndex, status))
     else:
         iface.mainWindow().statusBar().removeWidget(self.statusLabel)
         self.statusLabel = None
Exemplo n.º 10
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"),
         )
Exemplo n.º 11
0
def applyButtons(profile):
    if profile.buttons is None:
        return

    for toolbar in customToolbarsWidgets[::-1]:
        toolbar.setVisible(False)
        iface.mainWindow().removeToolBar(toolbar)
        del toolbar

    del customToolbarsWidgets[:]

    currentToolbars = [el for el in iface.mainWindow().children()
                if isinstance(el, QToolBar)]

    customToolbars = defaultdict(list)
    toolbars = profile.buttons
    for toolbar in currentToolbars:
        if toolbar.objectName() in toolbars:
            hasVisibleActions = False
            actions = toolbar.actions()
            for i, action in enumerate(actions):
                objectName = action.objectName() or str(i)
                if objectName in toolbars[toolbar.objectName()]:
                    location = toolbars[toolbar.objectName()][objectName]
                    if location is not None:
                        newAction = QAction(action.icon(), action.text(), iface.mainWindow())
                        newAction.triggered.connect(action.trigger)
                        objectName = "%s_%i" % (location, len(customToolbars[location]))
                        newAction.setObjectName(objectName)
                        customToolbars[location].append(newAction)
                        action.setVisible(False)
                    else:
                        hasVisibleActions = True
                        action.setVisible(True)
                else:
                    if toolbars[toolbar.objectName()]:
                        action.setVisible(False)
                    else: #If toolbar definition is empty, means all buttons should be added
                        hasVisibleActions = True
                        action.setVisible(True)
                if isinstance(action, QWidgetAction) and not isinstance(action.defaultWidget(), QToolButton) and action.defaultWidget() is not None:
                    action.defaultWidget().setMinimumWidth(300)
                    #action.defaultWidget().setMaximumWidth(400)

            toolbar.setVisible(hasVisibleActions)

        else:
            toolbar.setVisible(False)

    for name, actions in customToolbars.iteritems():
        toolbar = iface.mainWindow().addToolBar(name)
        toolbar.setObjectName("toolbar_%s" % name)
        customToolbarsWidgets.append(toolbar)
        for action in actions:
            toolbar.addAction(action)
Exemplo n.º 12
0
    def __init__(self, parent=None):
        QDockWidget.__init__(self, parent)
        self.setObjectName("PythonConsole")
        self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console"))
        #self.setAllowedAreas(Qt.BottomDockWidgetArea) 

        self.console = PythonConsoleWidget(self)
        self.setWidget( self.console )

        # try to restore position from stored main window state
        if iface and not iface.mainWindow().restoreDockWidget(self):
            iface.mainWindow().addDockWidget(Qt.BottomDockWidgetArea, self)
Exemplo n.º 13
0
 def __init__(self, parent=None):
   QDockWidget.__init__(self, parent)
   self.setObjectName("Python Console")
   self.setAllowedAreas(Qt.BottomDockWidgetArea)
   self.widget = QWidget()
   self.l = QVBoxLayout(self.widget)
   self.edit = PythonEdit()
   self.l.addWidget(self.edit)
   self.setWidget(self.widget)
   self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console"))
   # try to restore position from stored main window state
   if not iface.mainWindow().restoreDockWidget(self):
     iface.mainWindow().addDockWidget(Qt.BottomDockWidgetArea, self)
Exemplo n.º 14
0
def addAlgorithmEntry(alg, menuName, submenuName, actionText=None, icon=None, addButton=False):
    action = QAction(icon or alg.getIcon(), actionText or alg.name, iface.mainWindow())
    action.triggered.connect(lambda: _executeAlgorithm(alg))

    if menuName:
        menu = getMenu(menuName, iface.mainWindow().menuBar())
        submenu = getMenu(submenuName, menu)
        submenu.addAction(action)

    if addButton:
        global algorithmsToolbar
        if algorithmsToolbar is None:
            algorithmsToolbar = iface.addToolBar('ProcessingAlgorithms')
        algorithmsToolbar.addAction(action)
Exemplo n.º 15
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(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)
Exemplo n.º 16
0
 def openSettings(url):
     if url == "close":
         self.txtTip.setVisible(False)
         self.tipWasClosed = True
     else:
         iface.showOptionsDialog(iface.mainWindow(), 'processingOptions')
         self.txtTip.setVisible(self.disabledProviders())
Exemplo n.º 17
0
 def __init__(self):
     """
     Initialize the STR component class.
     """
     super(ComponentUtility, self).__init__()
     self.current_profile = current_profile()
     self.social_tenure = self.current_profile.social_tenure
     self.parties = self.social_tenure.parties
     self.spatial_units = self.social_tenure.spatial_units
     self.str_model = None
     self.str_doc_model = None
     if len(self.parties) > 0:
         self.party_1 = self.parties[0]
     if len(self.spatial_units) > 0:
         self.spatial_unit_1 = self.spatial_units[0]
     try:
         self.str_model, self.str_doc_model = entity_model(
             self.social_tenure, False, True
         )
     except Exception as ex:
         QMessageBox.critical(
             iface.mainWindow(),
             QApplication.translate('ComponentUtility', 'Database Error'),
             str(ex)
         )
Exemplo n.º 18
0
    def runAsSingle(self):
        self.close()

        from processing.gui.AlgorithmDialog import AlgorithmDialog
        dlg = AlgorithmDialog(self.algorithm().create(), parent=iface.mainWindow())
        dlg.show()
        dlg.exec_()
Exemplo n.º 19
0
def addAlgorithmEntry(alg, menuName, submenuName, actionText=None, icon=None, addButton=False):
    action = QAction(icon or alg.icon(), actionText or alg.displayName(), iface.mainWindow())
    action.triggered.connect(lambda: _executeAlgorithm(alg))
    action.setObjectName("mProcessingUserMenu_%s" % alg.id())

    if menuName:
        menu = getMenu(menuName, iface.mainWindow().menuBar())
        submenu = getMenu(submenuName, menu)
        submenu.addAction(action)

    if addButton:
        global algorithmsToolbar
        if algorithmsToolbar is None:
            algorithmsToolbar = iface.addToolBar(QCoreApplication.translate('MainWindow', 'Processing Algorithms'))
            algorithmsToolbar.setToolTip(QCoreApplication.translate('MainWindow', 'Processing Algorithms Toolbar'))
        algorithmsToolbar.addAction(action)
Exemplo n.º 20
0
    def runModel(self):
        if len(self.model.childAlgorithms()) == 0:
            self.bar.pushMessage("", self.tr("Model doesn't contain any algorithm and/or parameter and can't be executed"), level=Qgis.Warning, duration=5)
            return

        dlg = AlgorithmDialog(self.model.create(), parent=iface.mainWindow())
        dlg.exec_()
Exemplo n.º 21
0
    def run(self):
        s = str(self.combo.currentText())
        if s.startswith('Processing algorithm: '):
            algName = s[len('Processing algorithm: '):]
            alg = algList.getAlgorithm(algName)
            if alg is not None:
                self.close()
                self.runAlgorithm(alg)
        elif s.startswith("Command: "):
            command = s[len("Command: "):]
            try:
                self.runCommand(command)
                self.close()
            except Exception as e:
                self.label.setVisible(True)
                self.label.setText('Error:' + str(e))

        elif s.startswith('Menu action: '):
            actionName = s[len('Menu action: '):]
            menuActions = []
            actions = iface.mainWindow().menuBar().actions()
            for action in actions:
                menuActions.extend(self.getActions(action))
            for action in menuActions:
                if action.text() == actionName:
                    self.close()
                    action.trigger()
                    return
        else:
            try:
                self.runCommand(s)
                self.close()
            except Exception as e:
                self.label.setVisible(True)
                self.label.setText('Error:' + str(e))
Exemplo n.º 22
0
 def openLink(self, url):
     if url.toString() == "log":
         self.close()
         logDock = iface.mainWindow().findChild(QDockWidget, 'MessageLog')
         logDock.show()
     else:
         QDesktopServices.openUrl(url)
Exemplo n.º 23
0
    def __init__(self, resourceType):
        super(GetScriptsAndModelsDialog, self).__init__(iface.mainWindow())
        self.setupUi(self)

        if hasattr(self.leFilter, 'setPlaceholderText'):
            self.leFilter.setPlaceholderText(self.tr('Search...'))

        self.manager = QgsNetworkAccessManager.instance()

        repoUrl = ProcessingConfig.getSetting(ProcessingConfig.MODELS_SCRIPTS_REPO)

        self.resourceType = resourceType
        if self.resourceType == self.MODELS:
            self.folder = ModelerUtils.modelsFolders()[0]
            self.urlBase = '{}/models/'.format(repoUrl)
            self.icon = QgsApplication.getThemeIcon("/processingModel.svg")
        elif self.resourceType == self.SCRIPTS:
            self.folder = ScriptUtils.scriptsFolders()[0]
            self.urlBase = '{}/scripts/'.format(repoUrl)
            self.icon = QgsApplication.getThemeIcon("/processingScript.svg")

        self.lastSelectedItem = None
        self.updateProvider = False
        self.data = None

        self.populateTree()
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        self.tree.currentItemChanged.connect(self.currentItemChanged)
        self.leFilter.textChanged.connect(self.fillTree)
Exemplo n.º 24
0
    def __init__(self, resourceType):
        super(GetScriptsAndModelsDialog, self).__init__(iface.mainWindow())
        self.setupUi(self)
        self.manager = QgsNetworkAccessManager.instance()

        self.resourceType = resourceType
        if self.resourceType == self.MODELS:
            self.folder = ModelerUtils.modelsFolder()
            self.urlBase = 'https://raw.githubusercontent.com/qgis/QGIS-Processing/master/models/'
            self.icon = QIcon(os.path.join(pluginPath, 'images', 'model.png'))
        elif self.resourceType == self.SCRIPTS:
            self.folder = ScriptUtils.scriptsFolder()
            self.urlBase = 'https://raw.githubusercontent.com/qgis/QGIS-Processing/master/scripts/'
            self.icon = QIcon(os.path.join(pluginPath, 'images', 'script.png'))
        else:
            self.folder = RUtils.RScriptsFolder()
            self.urlBase = 'https://raw.githubusercontent.com/qgis/QGIS-Processing/master/rscripts/'
            self.icon = QIcon(os.path.join(pluginPath, 'images', 'r.png'))

        self.lastSelectedItem = None
        self.updateToolbox = False
        self.populateTree()
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        self.tree.currentItemChanged.connect(self.currentItemChanged)
Exemplo n.º 25
0
    def show(self):
        if iface and not iface.mainWindow().restoreDockWidget(self):
            iface.mainWindow().addDockWidget(Qt.LeftDockWidgetArea, self)
        super(Visor, self).show()

        if self.firstRunThisSession is True:
            self.firstRunChecks()
            self.firstRunThisSession = False

        #If no dataset is selected yet, we will assume the first
        #thing the user will want to do is actually doing something
        #related to the servers (pick one from a list, or add a new
        #one) as there is little else that can be done at this point.
        #So we present them the screen to do so..
        if self.datasetInUse is None:
            self._onManageServersRequested()
Exemplo n.º 26
0
    def __init__(self, resourceType):
        super(GetScriptsAndModelsDialog, self).__init__(iface.mainWindow())
        self.setupUi(self)
        self.manager = QgsNetworkAccessManager.instance()

        repoUrl = ProcessingConfig.getSetting(ProcessingConfig.MODELS_SCRIPTS_REPO)

        self.resourceType = resourceType
        if self.resourceType == self.MODELS:
            self.folder = ModelerUtils.modelsFolders()[0]
            self.urlBase = '{}/models/'.format(repoUrl)
            self.icon = QIcon(os.path.join(pluginPath, 'images', 'model.png'))
        elif self.resourceType == self.SCRIPTS:
            self.folder = ScriptUtils.scriptsFolders()[0]
            self.urlBase = '{}/scripts/'.format(repoUrl)
            self.icon = QIcon(os.path.join(pluginPath, 'images', 'script.png'))
        else:
            self.folder = RUtils.RScriptsFolders()[0]
            self.urlBase = '{}/rscripts/'.format(repoUrl)
            self.icon = QIcon(os.path.join(pluginPath, 'images', 'r.svg'))

        self.lastSelectedItem = None
        self.updateProvider = False
        self.populateTree()
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        self.tree.currentItemChanged.connect(self.currentItemChanged)
Exemplo n.º 27
0
    def __init__(self, resourceType):
        super(GetScriptsAndModelsDialog, self).__init__(iface.mainWindow())
        self.setupUi(self)

        if hasattr(self.leFilter, "setPlaceholderText"):
            self.leFilter.setPlaceholderText(self.tr("Search..."))

        self.manager = QgsNetworkAccessManager.instance()

        self.resourceType = resourceType
        if self.resourceType == self.MODELS:
            self.folder = ModelerUtils.modelsFolders()[0]
            self.urlBase = "https://raw.githubusercontent.com/qgis/QGIS-Processing/master/models/"
            self.icon = QIcon(os.path.join(pluginPath, "images", "model.png"))
        elif self.resourceType == self.SCRIPTS:
            self.folder = ScriptUtils.scriptsFolders()[0]
            self.urlBase = "https://raw.githubusercontent.com/qgis/QGIS-Processing/master/scripts/"
            self.icon = QIcon(os.path.join(pluginPath, "images", "script.png"))
        else:
            self.folder = RUtils.RScriptsFolders()[0]
            self.urlBase = "https://raw.githubusercontent.com/qgis/QGIS-Processing/master/rscripts/"
            self.icon = QIcon(os.path.join(pluginPath, "images", "r.svg"))

        self.lastSelectedItem = None
        self.updateProvider = False
        self.data = None

        self.populateTree()
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        self.tree.currentItemChanged.connect(self.currentItemChanged)
        self.leFilter.textChanged.connect(self.fillTree)
Exemplo n.º 28
0
 def executeAlgorithmAsBatchProcess(self):
     alg = self.algorithmTree.selectedAlgorithm().create() if self.algorithmTree.selectedAlgorithm() is not None else None
     if alg is not None:
         dlg = BatchAlgorithmDialog(alg, iface.mainWindow())
         dlg.setAttribute(Qt.WA_DeleteOnClose)
         dlg.show()
         dlg.exec_()
def _openProfileManager():
    global profileManager
    if profileManager is None:
        profileManager = ProfileManager(iface.mainWindow())
        #profileManager.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
    profileManager.close()
    profileManager.show()
Exemplo n.º 30
0
 def createApp(self):
     try:
         appdef = self.createAppDefinition()
         problems = checkAppCanBeCreated(appdef)
         if problems:
             dlg = AppDefProblemsDialog(problems)
             dlg.exec_()
             if not dlg.ok:
                 return
         folder = askForFolder(self, "Select folder to store app")
         if folder:
             if os.path.exists(os.path.join(folder, "webapp")):
                 ret = QMessageBox.warning(self, "Output folder", " The selected folder already contains a 'webapp' subfolder.\n"
                                     "Do you confirm that you want to overwrite it?",
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                 if ret == QMessageBox.No:
                     return
             self._run(lambda: createApp(appdef, not self.checkBoxDeployData.isChecked(), folder, False, self.progress))
             box = QMessageBox()
             box.setWindowTitle("Web App Builder");
             box.setTextFormat(Qt.RichText)
             box.setText("Application files have been correctly generated.<br>"
                         "Use the  <a href='http://boundlessgeo.com/products/opengeo-suite/'> Boundless WebSDK </a> for building the final webapp from them.")
             box.exec_()
     except WrongValueException:
         pass
     except:
         QgsMessageLog.logMessage(traceback.format_exc(), level=QgsMessageLog.CRITICAL)
         QMessageBox.critical(iface.mainWindow(), "Error creating web app",
                              "Could not create web app.\nCheck the QGIS log for more details.")
    def __init__(self, iface: QgisInterface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        self.project = QgsProject.instance()
        self.layerTree = self.project.layerTreeRoot()

        self.service = Its4landAPI(API_URL, API_KEY)

        self._initLocale()

        self.baseRasterLayerName = __('Base')
        self.segmentsLayerName = __('Segments')
        self.simplifiedSegmentsLayerName = __('Simplified Segments')
        self.verticesLayerName = __('Vertices')
        self.candidatesLayerName = __('Candidates')
        self.finalLayerName = __('Final')
        self.finalLayerPolygonsName = __('Final Polygons')
        self.groupName = __('BoundaryDelineation')

        # map layers
        self.baseRasterLayer: Optional[QgsRasterLayer] = None
        self.segmentsLayer: Optional[QgsVectorLayer] = None
        self.simplifiedSegmentsLayer: Optional[QgsVectorLayer] = None
        self.verticesLayer: Optional[QgsVectorLayer] = None
        self.candidatesLayer: Optional[QgsVectorLayer] = None
        self.finalLayer: Optional[QgsVectorLayer] = None
        self.finalLayerPolygons: Optional[QgsVectorLayer] = None

        self.actions: typing.List[QAction] = []
        self.canvas = self.iface.mapCanvas()

        self.isMapSelectionToolEnabled = False
        self.isEditCandidatesToggled = False
        self.shouldAddLengthAttribute = False
        self.wasBaseRasterLayerInitiallyInLegend = True
        self.wasSegmentsLayerInitiallyInLegend = True
        self.previousMapTool = None
        self.selectionMode = SelectionModes.NONE
        self.previousSelectionMode = SelectionModes.NONE
        self.dockWidget: Optional[BoundaryDelineationDock] = None
        self.edgesWeightField = DEFAULT_WEIGHT_NAME
        self.lengthAttributeName = 'BD_LEN'
        self.metricClosureGraphs: typing.Dict[str, typing.Any] = {}
        self.graph: Optional[nx.MultiGraph] = None
        self.subgraphs: Optional[Collection[nx.Graph]] = None
        self.simplifiedSegmentsNumericFields: Optional[typing.Dict[str, typing.Any]] = None

        self.mapSelectionTool = MapSelectionTool(self.canvas)
        self.mapSelectionTool.polygonCreated.connect(self.onPolygonSelectionCreated)

        # Define visible toolbars
        iface.mainWindow().findChild(QToolBar, 'mDigitizeToolBar').setVisible(True)
        iface.mainWindow().findChild(QToolBar, 'mAdvancedDigitizeToolBar').setVisible(True)
        iface.mainWindow().findChild(QToolBar, 'mSnappingToolBar').setVisible(True)

        snappingConfig = self.canvas.snappingUtils().config()
        snappingConfig.setEnabled(True)

        self.canvas.snappingUtils().setConfig(snappingConfig)

        # Set projections settings for newly created layers, possible values are: prompt, useProject, useGlobal
        QSettings().setValue('/Projections/defaultBehaviour', 'useProject')
Exemplo n.º 32
0
 def openSettings(self):
     iface.showOptionsDialog(iface.mainWindow(), currentPage='consoleOptions')
Exemplo n.º 33
0
 def runAsBatch(self):
     self.close()
     dlg = BatchAlgorithmDialog(self.algorithm().create(),
                                parent=iface.mainWindow())
     dlg.show()
     dlg.exec_()
Exemplo n.º 34
0
    def confirmarCortes(self):  #Aqui cehcamos que los cortes esten en orden

        #cuentaCortes = 0
        rango = len(self.eventos.relaciones) - 1
        #for i in range(0, rango):
        #    geom = self.eventos.relaciones[i].geom
        #    if geom != None:
        #        cuentaCortes += 1
        #Obtenemos la cantidad de corte
        #print('cuentaCortes ', cuentaCortes)
        geoTemp = QgsGeometry.fromWkt(self.geomEnDivision.asWkt())
        cuentaSalida = self.subdividirPredio(
            geoTemp, True
        ) - 1  #Aqui enviamos una geomtria temporal, para ven en cuantos cortes quedara

        if cuentaSalida >= 2:

            listaNoTocar = []
            capaPredios = QgsProject.instance().mapLayer(
                self.ACA.obtenerIdCapa('predios.geom'))
            capaCondH = QgsProject.instance().mapLayersByName(
                'horizontales.geom')[0]
            capaCondV = QgsProject.instance().mapLayersByName('verticales')[0]
            capaConstru = QgsProject.instance().mapLayer(
                self.ACA.obtenerIdCapa('construcciones'))

            #Obtenemos los features que no deben tocarse
            for feat in capaConstru.getFeatures():
                geom = feat.geometry().buffer(-0.0000002, 1)
                if geom.intersects(self.geomEnDivision):
                    listaNoTocar.append(geom)

            for feat in capaCondH.getFeatures():
                geom = feat.geometry().buffer(-0.0000002, 1)
                if geom.intersects(self.geomEnDivision):
                    listaNoTocar.append(geom)

            for feat in capaCondV.getFeatures():
                geom = feat.geometry().buffer(-0.0000002, 1)
                if geom.intersects(self.geomEnDivision):
                    listaNoTocar.append(geom)

            bandera = True

            #Aqui checamos que cada linea no toque lo no tocable
            for i in range(0, rango):
                for comp in listaNoTocar:
                    geom = self.eventos.relaciones[i].geom
                    if geom != None:
                        if geom.buffer(0.0000001, 1).intersects(comp):
                            bandera = False
                            self.eventos.relaciones[i].rubber.setStrokeColor(
                                QColor(255, 0, 0, 255))
                        else:
                            self.eventos.relaciones[i].rubber.setStrokeColor(
                                QColor(0, 61, 240, 255))

            iface.mapCanvas().refresh()
            if bandera:  #Si todo esta en orden
                self.eventos.rubberPunto.reset(QgsWkbTypes.PointGeometry)
                self.apagarHerramientas()
                #mostramos mensaje de confirmacion
                mensaje = "La cantidad de predios que quedaran como resultado, es de: " + str(
                    cuentaSalida) + "\nDeseas continua?"
                respuesta = QMessageBox.question(
                    iface.mainWindow(), "Nota de subdivision de predio",
                    mensaje, QMessageBox.Yes, QMessageBox.No)

                #Si el usuario acepta....
                if respuesta == QMessageBox.Yes:
                    self.subdividirPredio(self.geomEnDivision, False)
                    self.rubberMarca.reset(
                        QgsWkbTypes.PolygonGeometry)  #Quitamos lo amarillito

                    for i in range(0, rango):
                        self.eventos.relaciones[i].rubber.reset(
                            QgsWkbTypes.LineGeometry)
                        self.eventos.relaciones[i].vaciarMarcadores()
                    self.eventos.recargarRelaciones()

                    capaPredios.startEditing()
                    capaPredios.dataProvider().deleteFeatures(
                        [self.predioEnDivision.id()])
                    capaPredios.triggerRepaint()
                    capaPredios.commitChanges()

                    self.VentanaAreas.close()
                    self.limpiarAreas()
                    self.vaciarRubbers()

                    self.UTI.mostrarAlerta(
                        "La division ha sido realizada con exito\nLos cambios se guardaran hasta que asignes las claves.",
                        QMessageBox().Information,
                        "Subdivision completa, Parte 1 de 2")
                    self.irAClaves(
                    )  #Mostramos la ventana que llena las claves
                    iface.actionSelect().trigger()
            else:
                self.UTI.mostrarAlerta(
                    "Las lineas de division no deben atravesar construcciones ni condominios\nLas lineas rojas presentan un corte invalido",
                    QMessageBox().Critical, "Error en subdivision")

        else:
            print('cuentasalida ', cuentaSalida)
            self.UTI.mostrarAlerta(
                "Primero debes dibujar las lineas de corte\nAsegurate que las lineas atraviesen por completo el predio",
                QMessageBox().Critical, "Error en subdivision")
Exemplo n.º 35
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)

            settings = QgsSettings()
            settings.remove("/PythonPlugins/" + key)
Exemplo n.º 36
0
def get_qgis_app(cleanup=True):
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    if iface:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface
        return QGIS_APP, CANVAS, IFACE, PARENT

    from qgis.core import QgsApplication
    from qgis.gui import QgsMapCanvas
    from qgis.PyQt.QtCore import QSize
    from qgis.PyQt.QtWidgets import QWidget
    from .qgis_interface import QgisInterface

    global QGISAPP  # pylint: disable=global-variable-undefined

    try:
        QGISAPP
    except NameError:
        myGuiFlag = True  # All test will run qgis in gui mode

        # In python3 we need to convert to a bytes object (or should
        # QgsApplication accept a QString instead of const char* ?)
        try:
            argvb = list(map(os.fsencode, sys.argv))
        except AttributeError:
            argvb = sys.argv

        # Note: QGIS_PREFIX_PATH is evaluated in QgsApplication -
        # no need to mess with it here.
        QGISAPP = QgsApplication(argvb, myGuiFlag)

        QGISAPP.initQgis()
        s = QGISAPP.showSettings()
        LOGGER.debug(s)

        def debug_log_message(message, tag, level):
            """
            Prints a debug message to a log
            :param message: message to print
            :param tag: log tag
            :param level: log message level (severity)
            :return:
            """
            print('{}({}): {}'.format(tag, level, message))

        QgsApplication.instance().messageLog().messageReceived.connect(
            debug_log_message)

        if cleanup:
            import atexit

            @atexit.register
            def exitQgis():  # pylint: disable=unused-variable
                """
                Gracefully closes the QgsApplication instance
                """
                try:
                    QGISAPP.exitQgis()  # pylint: disable=used-before-assignment
                    QGISAPP = None  # pylint: disable=redefined-outer-name
                except NameError:
                    pass

    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QWidget()

    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QSize(400, 400))

    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGISAPP, CANVAS, IFACE, PARENT
Exemplo n.º 37
0
# coding: utf-8
from PyQt4.QtCore import Qt
from qgis.gui import QgsCharacterSelectorDialog
from qgis.utils import iface

main_window = iface.mainWindow()
character_selector_dialog = QgsCharacterSelectorDialog(main_window,
                                                       fl=Qt.WindowFlags())

character_selector_dialog.show()
Exemplo n.º 38
0
    def __init__(self, alg):
        super(AlgorithmDialogBase, self).__init__(iface.mainWindow())
        self.setupUi(self)

        self.settings = QSettings()
        self.restoreGeometry(
            self.settings.value("/Processing/dialogBase", QByteArray()))

        self.executed = False
        self.mainWidget = None
        self.alg = alg

        # Rename OK button to Run
        self.btnRun = self.buttonBox.button(QDialogButtonBox.Ok)
        self.btnRun.setText(self.tr('Run'))

        self.btnClose = self.buttonBox.button(QDialogButtonBox.Close)

        self.setWindowTitle(self.alg.displayName())

        #~ desktop = QDesktopWidget()
        #~ if desktop.physicalDpiX() > 96:
        #~ self.txtHelp.setZoomFactor(desktop.physicalDpiX() / 96)

        algHelp = self.alg.shortHelp()
        if algHelp is None:
            self.textShortHelp.setVisible(False)
        else:
            self.textShortHelp.document().setDefaultStyleSheet(
                '''.summary { margin-left: 10px; margin-right: 10px; }
                                                    h2 { color: #555555; padding-bottom: 15px; }
                                                    a { text-decoration: none; color: #3498db; font-weight: bold; }
                                                    p { color: #666666; }
                                                    b { color: #333333; }
                                                    dl dd { margin-bottom: 5px; }'''
            )
            self.textShortHelp.setHtml(algHelp)

        self.textShortHelp.setOpenLinks(False)

        def linkClicked(url):
            webbrowser.open(url.toString())

        self.textShortHelp.anchorClicked.connect(linkClicked)

        isText, algHelp = self.alg.help()
        if algHelp is not None:
            algHelp = algHelp if isText else QUrl(algHelp)
            try:
                if isText:
                    self.txtHelp.setHtml(algHelp)
                else:
                    html = self.tr(
                        '<p>Downloading algorithm help... Please wait.</p>')
                    self.txtHelp.setHtml(html)
                    rq = QNetworkRequest(algHelp)
                    self.reply = QgsNetworkAccessManager.instance().get(rq)
                    self.reply.finished.connect(self.requestFinished)
            except Exception as e:
                self.tabWidget.removeTab(2)
        else:
            self.tabWidget.removeTab(2)

        self.showDebug = ProcessingConfig.getSetting(
            ProcessingConfig.SHOW_DEBUG_IN_DIALOG)
Exemplo n.º 39
0
def get_qgis_app():
    """ Start one QGIS application to test against.

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """

    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    if iface:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface
        return QGIS_APP, CANVAS, IFACE, PARENT

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from PyQt4 import QtGui, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from PyQt4.QtCore import QCoreApplication, QSettings
        from safe.test.qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    if QGIS_APP is None:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file instead
        # of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('QGIS2InaSAFETesting')

        # noinspection PyPep8Naming
        if 'argv' in dir(sys):
            QGIS_APP = QgsApplication(sys.argv, gui_flag)
        else:
            QGIS_APP = QgsApplication([], gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()
        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

        # Save some settings
        settings = QSettings()
        settings.setValue('locale/overrideFlag', True)
        settings.setValue('locale/userLocale', 'en_US')
        # We disabled message bars for now for extent selector as
        # we don't have a main window to show them in TS - version 3.2
        settings.setValue('inasafe/show_extent_confirmations', False)
        settings.setValue('inasafe/show_extent_warnings', False)
        settings.setValue('inasafe/showRubberBands', True)
        settings.setValue('inasafe/analysis_extents_mode', HAZARD_EXPOSURE)

    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtGui.QWidget()

    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Exemplo n.º 40
0
    def __init__(self, model=None):
        super().__init__(None)
        self.setAttribute(Qt.WA_DeleteOnClose)

        self.setupUi(self)

        # LOTS of bug reports when we include the dock creation in the UI file
        # see e.g. #16428, #19068
        # So just roll it all by hand......!
        self.propertiesDock = QgsDockWidget(self)
        self.propertiesDock.setFeatures(QDockWidget.DockWidgetFloatable
                                        | QDockWidget.DockWidgetMovable)
        self.propertiesDock.setObjectName("propertiesDock")
        propertiesDockContents = QWidget()
        self.verticalDockLayout_1 = QVBoxLayout(propertiesDockContents)
        self.verticalDockLayout_1.setContentsMargins(0, 0, 0, 0)
        self.verticalDockLayout_1.setSpacing(0)
        self.scrollArea_1 = QgsScrollArea(propertiesDockContents)
        sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding,
                                 QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.scrollArea_1.sizePolicy().hasHeightForWidth())
        self.scrollArea_1.setSizePolicy(sizePolicy)
        self.scrollArea_1.setFocusPolicy(Qt.WheelFocus)
        self.scrollArea_1.setFrameShape(QFrame.NoFrame)
        self.scrollArea_1.setFrameShadow(QFrame.Plain)
        self.scrollArea_1.setWidgetResizable(True)
        self.scrollAreaWidgetContents_1 = QWidget()
        self.gridLayout = QGridLayout(self.scrollAreaWidgetContents_1)
        self.gridLayout.setContentsMargins(6, 6, 6, 6)
        self.gridLayout.setSpacing(4)
        self.label_1 = QLabel(self.scrollAreaWidgetContents_1)
        self.gridLayout.addWidget(self.label_1, 0, 0, 1, 1)
        self.textName = QLineEdit(self.scrollAreaWidgetContents_1)
        self.gridLayout.addWidget(self.textName, 0, 1, 1, 1)
        self.label_2 = QLabel(self.scrollAreaWidgetContents_1)
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.textGroup = QLineEdit(self.scrollAreaWidgetContents_1)
        self.gridLayout.addWidget(self.textGroup, 1, 1, 1, 1)
        self.label_1.setText(self.tr("Name"))
        self.textName.setToolTip(self.tr("Enter model name here"))
        self.label_2.setText(self.tr("Group"))
        self.textGroup.setToolTip(self.tr("Enter group name here"))
        self.scrollArea_1.setWidget(self.scrollAreaWidgetContents_1)
        self.verticalDockLayout_1.addWidget(self.scrollArea_1)
        self.propertiesDock.setWidget(propertiesDockContents)
        self.addDockWidget(Qt.DockWidgetArea(1), self.propertiesDock)
        self.propertiesDock.setWindowTitle(self.tr("Model properties"))

        self.inputsDock = QgsDockWidget(self)
        self.inputsDock.setFeatures(QDockWidget.DockWidgetFloatable
                                    | QDockWidget.DockWidgetMovable)
        self.inputsDock.setObjectName("inputsDock")
        self.inputsDockContents = QWidget()
        self.verticalLayout_3 = QVBoxLayout(self.inputsDockContents)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.scrollArea_2 = QgsScrollArea(self.inputsDockContents)
        sizePolicy.setHeightForWidth(
            self.scrollArea_2.sizePolicy().hasHeightForWidth())
        self.scrollArea_2.setSizePolicy(sizePolicy)
        self.scrollArea_2.setFocusPolicy(Qt.WheelFocus)
        self.scrollArea_2.setFrameShape(QFrame.NoFrame)
        self.scrollArea_2.setFrameShadow(QFrame.Plain)
        self.scrollArea_2.setWidgetResizable(True)
        self.scrollAreaWidgetContents_2 = QWidget()
        self.verticalLayout = QVBoxLayout(self.scrollAreaWidgetContents_2)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(0)
        self.inputsTree = QTreeWidget(self.scrollAreaWidgetContents_2)
        self.inputsTree.setAlternatingRowColors(True)
        self.inputsTree.header().setVisible(False)
        self.verticalLayout.addWidget(self.inputsTree)
        self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)
        self.verticalLayout_3.addWidget(self.scrollArea_2)
        self.inputsDock.setWidget(self.inputsDockContents)
        self.addDockWidget(Qt.DockWidgetArea(1), self.inputsDock)
        self.inputsDock.setWindowTitle(self.tr("Inputs"))

        self.algorithmsDock = QgsDockWidget(self)
        self.algorithmsDock.setFeatures(QDockWidget.DockWidgetFloatable
                                        | QDockWidget.DockWidgetMovable)
        self.algorithmsDock.setObjectName("algorithmsDock")
        self.algorithmsDockContents = QWidget()
        self.verticalLayout_4 = QVBoxLayout(self.algorithmsDockContents)
        self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.scrollArea_3 = QgsScrollArea(self.algorithmsDockContents)
        sizePolicy.setHeightForWidth(
            self.scrollArea_3.sizePolicy().hasHeightForWidth())
        self.scrollArea_3.setSizePolicy(sizePolicy)
        self.scrollArea_3.setFocusPolicy(Qt.WheelFocus)
        self.scrollArea_3.setFrameShape(QFrame.NoFrame)
        self.scrollArea_3.setFrameShadow(QFrame.Plain)
        self.scrollArea_3.setWidgetResizable(True)
        self.scrollAreaWidgetContents_3 = QWidget()
        self.verticalLayout_2 = QVBoxLayout(self.scrollAreaWidgetContents_3)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setSpacing(4)
        self.searchBox = QgsFilterLineEdit(self.scrollAreaWidgetContents_3)
        self.verticalLayout_2.addWidget(self.searchBox)
        self.algorithmTree = QgsProcessingToolboxTreeView(
            None, QgsApplication.processingRegistry())
        self.algorithmTree.setAlternatingRowColors(True)
        self.algorithmTree.header().setVisible(False)
        self.verticalLayout_2.addWidget(self.algorithmTree)
        self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3)
        self.verticalLayout_4.addWidget(self.scrollArea_3)
        self.algorithmsDock.setWidget(self.algorithmsDockContents)
        self.addDockWidget(Qt.DockWidgetArea(1), self.algorithmsDock)
        self.algorithmsDock.setWindowTitle(self.tr("Algorithms"))
        self.searchBox.setToolTip(
            self.tr("Enter algorithm name to filter list"))
        self.searchBox.setShowSearchIcon(True)

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.centralWidget().layout().insertWidget(0, self.bar)

        try:
            self.setDockOptions(self.dockOptions()
                                | QMainWindow.GroupedDragging)
        except:
            pass

        if iface is not None:
            self.mToolbar.setIconSize(iface.iconSize())
            self.setStyleSheet(iface.mainWindow().styleSheet())

        self.toolbutton_export_to_script = QToolButton()
        self.toolbutton_export_to_script.setPopupMode(QToolButton.InstantPopup)
        self.export_to_script_algorithm_action = QAction(
            QCoreApplication.translate('ModelerDialog',
                                       'Export as Script Algorithm…'))
        self.toolbutton_export_to_script.addActions(
            [self.export_to_script_algorithm_action])
        self.mToolbar.insertWidget(self.mActionExportImage,
                                   self.toolbutton_export_to_script)
        self.export_to_script_algorithm_action.triggered.connect(
            self.export_as_script_algorithm)

        self.mActionOpen.setIcon(
            QgsApplication.getThemeIcon('/mActionFileOpen.svg'))
        self.mActionSave.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSave.svg'))
        self.mActionSaveAs.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSaveAs.svg'))
        self.mActionSaveInProject.setIcon(
            QgsApplication.getThemeIcon('/mAddToProject.svg'))
        self.mActionZoomActual.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomActual.svg'))
        self.mActionZoomIn.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomIn.svg'))
        self.mActionZoomOut.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomOut.svg'))
        self.mActionExportImage.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveMapAsImage.svg'))
        self.mActionZoomToItems.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomFullExtent.svg'))
        self.mActionExportPdf.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveAsPDF.svg'))
        self.mActionExportSvg.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveAsSVG.svg'))
        self.toolbutton_export_to_script.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveAsPython.svg'))
        self.mActionEditHelp.setIcon(
            QgsApplication.getThemeIcon('/mActionEditHelpContent.svg'))
        self.mActionRun.setIcon(
            QgsApplication.getThemeIcon('/mActionStart.svg'))

        self.addDockWidget(Qt.LeftDockWidgetArea, self.propertiesDock)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.inputsDock)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.algorithmsDock)
        self.tabifyDockWidget(self.inputsDock, self.algorithmsDock)
        self.inputsDock.raise_()

        self.zoom = 1

        self.setWindowFlags(Qt.WindowMinimizeButtonHint
                            | Qt.WindowMaximizeButtonHint
                            | Qt.WindowCloseButtonHint)

        settings = QgsSettings()
        self.restoreState(
            settings.value("/Processing/stateModeler", QByteArray()))
        self.restoreGeometry(
            settings.value("/Processing/geometryModeler", QByteArray()))

        self.scene = ModelerScene(self, dialog=self)
        self.scene.setSceneRect(
            QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE))

        self.view.setScene(self.scene)
        self.view.setAcceptDrops(True)
        self.view.ensureVisible(0, 0, 10, 10)

        def _dragEnterEvent(event):
            if event.mimeData().hasText() or event.mimeData().hasFormat(
                    'application/x-vnd.qgis.qgis.algorithmid'):
                event.acceptProposedAction()
            else:
                event.ignore()

        def _dropEvent(event):
            if event.mimeData().hasFormat(
                    'application/x-vnd.qgis.qgis.algorithmid'):
                data = event.mimeData().data(
                    'application/x-vnd.qgis.qgis.algorithmid')
                stream = QDataStream(data, QIODevice.ReadOnly)
                algorithm_id = stream.readQString()
                alg = QgsApplication.processingRegistry().createAlgorithmById(
                    algorithm_id)
                if alg is not None:
                    self._addAlgorithm(alg, event.pos())
                else:
                    assert False, algorithm_id
            elif event.mimeData().hasText():
                itemId = event.mimeData().text()
                if itemId in [
                        param.id() for param in QgsApplication.instance().
                        processingRegistry().parameterTypes()
                ]:
                    self.addInputOfType(itemId, event.pos())
                event.accept()
            else:
                event.ignore()

        def _dragMoveEvent(event):
            if event.mimeData().hasText() or event.mimeData().hasFormat(
                    'application/x-vnd.qgis.qgis.algorithmid'):
                event.accept()
            else:
                event.ignore()

        def _wheelEvent(event):
            self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)

            settings = QgsSettings()
            factor = settings.value('/qgis/zoom_favor', 2.0)

            # "Normal" mouse has an angle delta of 120, precision mouses provide data
            # faster, in smaller steps
            factor = 1.0 + (factor - 1.0) / 120.0 * abs(event.angleDelta().y())

            if (event.modifiers() == Qt.ControlModifier):
                factor = 1.0 + (factor - 1.0) / 20.0

            if event.angleDelta().y() < 0:
                factor = 1 / factor

            self.view.scale(factor, factor)

        def _enterEvent(e):
            QGraphicsView.enterEvent(self.view, e)
            self.view.viewport().setCursor(Qt.ArrowCursor)

        def _mouseReleaseEvent(e):
            QGraphicsView.mouseReleaseEvent(self.view, e)
            self.view.viewport().setCursor(Qt.ArrowCursor)

        def _mousePressEvent(e):
            if e.button() == Qt.MidButton:
                self.previousMousePos = e.pos()
            else:
                QGraphicsView.mousePressEvent(self.view, e)

        def _mouseMoveEvent(e):
            if e.buttons() == Qt.MidButton:
                offset = self.previousMousePos - e.pos()
                self.previousMousePos = e.pos()

                self.view.verticalScrollBar().setValue(
                    self.view.verticalScrollBar().value() + offset.y())
                self.view.horizontalScrollBar().setValue(
                    self.view.horizontalScrollBar().value() + offset.x())
            else:
                QGraphicsView.mouseMoveEvent(self.view, e)

        self.view.setDragMode(QGraphicsView.ScrollHandDrag)
        self.view.dragEnterEvent = _dragEnterEvent
        self.view.dropEvent = _dropEvent
        self.view.dragMoveEvent = _dragMoveEvent
        self.view.wheelEvent = _wheelEvent
        self.view.enterEvent = _enterEvent
        self.view.mousePressEvent = _mousePressEvent
        self.view.mouseMoveEvent = _mouseMoveEvent

        def _mimeDataInput(items):
            mimeData = QMimeData()
            text = items[0].data(0, Qt.UserRole)
            mimeData.setText(text)
            return mimeData

        self.inputsTree.mimeData = _mimeDataInput

        self.inputsTree.setDragDropMode(QTreeWidget.DragOnly)
        self.inputsTree.setDropIndicatorShown(True)

        self.algorithms_model = ModelerToolboxModel(
            self, QgsApplication.processingRegistry())
        self.algorithmTree.setToolboxProxyModel(self.algorithms_model)
        self.algorithmTree.setDragDropMode(QTreeWidget.DragOnly)
        self.algorithmTree.setDropIndicatorShown(True)

        self.algorithmTree.setFilters(
            QgsProcessingToolboxProxyModel.FilterModeler)

        if hasattr(self.searchBox, 'setPlaceholderText'):
            self.searchBox.setPlaceholderText(
                QCoreApplication.translate('ModelerDialog', 'Search…'))
        if hasattr(self.textName, 'setPlaceholderText'):
            self.textName.setPlaceholderText(self.tr('Enter model name here'))
        if hasattr(self.textGroup, 'setPlaceholderText'):
            self.textGroup.setPlaceholderText(self.tr('Enter group name here'))

        # Connect signals and slots
        self.inputsTree.doubleClicked.connect(self.addInput)
        self.searchBox.textChanged.connect(self.algorithmTree.setFilterString)
        self.algorithmTree.doubleClicked.connect(self.addAlgorithm)

        # Ctrl+= should also trigger a zoom in action
        ctrlEquals = QShortcut(QKeySequence("Ctrl+="), self)
        ctrlEquals.activated.connect(self.zoomIn)

        self.mActionOpen.triggered.connect(self.openModel)
        self.mActionSave.triggered.connect(self.save)
        self.mActionSaveAs.triggered.connect(self.saveAs)
        self.mActionSaveInProject.triggered.connect(self.saveInProject)
        self.mActionZoomIn.triggered.connect(self.zoomIn)
        self.mActionZoomOut.triggered.connect(self.zoomOut)
        self.mActionZoomActual.triggered.connect(self.zoomActual)
        self.mActionZoomToItems.triggered.connect(self.zoomToItems)
        self.mActionExportImage.triggered.connect(self.exportAsImage)
        self.mActionExportPdf.triggered.connect(self.exportAsPdf)
        self.mActionExportSvg.triggered.connect(self.exportAsSvg)
        #self.mActionExportPython.triggered.connect(self.exportAsPython)
        self.mActionEditHelp.triggered.connect(self.editHelp)
        self.mActionRun.triggered.connect(self.runModel)

        if model is not None:
            self.model = model.create()
            self.model.setSourceFilePath(model.sourceFilePath())
            self.textGroup.setText(self.model.group())
            self.textName.setText(self.model.displayName())
            self.repaintModel()

        else:
            self.model = QgsProcessingModelAlgorithm()
            self.model.setProvider(
                QgsApplication.processingRegistry().providerById('model'))

        self.fillInputsTree()

        self.view.centerOn(0, 0)
        self.help = None

        self.hasChanged = False
 def __init__(self, command):
     QtCore.QThread.__init__(self, iface.mainWindow())
     self.command = command
     self.returnValue = None
     self.exception = None
Exemplo n.º 42
0
    def executeAlgorithm(self, alg_id, parent, in_place=False, as_batch=False):
        """Executes a project model with GUI interaction if needed.

        :param alg_id: algorithm id
        :type alg_id: string
        :param parent: parent widget
        :type parent: QWidget
        :param in_place: in place flag, defaults to False
        :type in_place: bool, optional
        :param as_batch: execute as batch flag, defaults to False
        :type as_batch: bool, optional
        """

        config = {}
        if in_place:
            config['IN_PLACE'] = True

        alg = QgsApplication.instance().processingRegistry(
        ).createAlgorithmById(alg_id, config)

        if alg is not None:

            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            if as_batch:
                dlg = BatchAlgorithmDialog(alg, iface.mainWindow())
                dlg.setAttribute(Qt.WA_DeleteOnClose)
                dlg.show()
                dlg.exec_()
            else:
                in_place_input_parameter_name = 'INPUT'
                if hasattr(alg, 'inputParameterName'):
                    in_place_input_parameter_name = alg.inputParameterName()

                if in_place and not [
                        d
                        for d in alg.parameterDefinitions() if d.name() not in
                    (in_place_input_parameter_name, 'OUTPUT')
                ]:
                    parameters = {}
                    feedback = MessageBarProgress(algname=alg.displayName())
                    ok, results = execute_in_place(alg,
                                                   parameters,
                                                   feedback=feedback)
                    if ok:
                        iface.messageBar().pushSuccess(
                            '',
                            self.
                            tr('{algname} completed. %n feature(s) processed.',
                               n=results['__count']).format(
                                   algname=alg.displayName()))
                    feedback.close()
                    # MessageBarProgress handles errors
                    return

                if alg.countVisibleParameters() > 0:
                    dlg = alg.createCustomParametersWidget(parent)

                    if not dlg:
                        dlg = AlgorithmDialog(alg, in_place,
                                              iface.mainWindow())
                    canvas = iface.mapCanvas()
                    prevMapTool = canvas.mapTool()
                    dlg.show()
                    dlg.exec_()
                    if canvas.mapTool() != prevMapTool:
                        try:
                            canvas.mapTool().reset()
                        except Exception:
                            pass
                        canvas.setMapTool(prevMapTool)
                else:
                    feedback = MessageBarProgress(algname=alg.displayName())
                    context = dataobjects.createContext(feedback)
                    parameters = {}
                    ret, results = execute(alg, parameters, context, feedback)
                    handleAlgorithmResults(alg, context, feedback)
                    feedback.close()
Exemplo n.º 43
0
def get_qgis_app(requested_locale='en_US', qsetting=''):
    """ Start one QGIS application to test against.

    :param locale: The locale we want the qgis to launch with.
    :type locale: str

    :param qsetting: String to specify the QSettings. By default,
        use empty string.
    :type qsetting: str

    :returns: Handle to QGIS app, canvas, iface and parent. If there are any
        errors the tuple members will be returned as None.
    :rtype: (QgsApplication, CANVAS, IFACE, PARENT)

    If QGIS is already running the handle to that app will be returned.
    """
    global QGIS_APP, PARENT, IFACE, CANVAS  # pylint: disable=W0603

    from qgis.PyQt.QtCore import QSettings
    if qsetting:
        settings = QSettings(qsetting)
    else:
        settings = QSettings()

    default_user_directory = setting('defaultUserDirectory')
    current_locale = general_setting('locale/userLocale',
                                     default='en_US',
                                     qsettings=settings)
    locale_match = current_locale == requested_locale

    if iface and locale_match:
        from qgis.core import QgsApplication
        QGIS_APP = QgsApplication
        CANVAS = iface.mapCanvas()
        PARENT = iface.mainWindow()
        IFACE = iface

    try:
        from qgis.core import QgsApplication
        from qgis.gui import QgsMapCanvas  # pylint: disable=no-name-in-module
        # noinspection PyPackageRequirements
        from qgis.PyQt import QtWidgets, QtCore  # pylint: disable=W0621
        # noinspection PyPackageRequirements
        from qgis.PyQt.QtCore import QCoreApplication, QSettings
        from safe.test.qgis_interface import QgisInterface
    except ImportError:
        return None, None, None, None

    if qsetting:
        settings = QSettings(qsetting)
    else:
        settings = QSettings()

    if not QGIS_APP:
        gui_flag = True  # All test will run qgis in gui mode

        # AG: For testing purposes, we use our own configuration file
        # instead of using the QGIS apps conf of the host
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationName('QGIS')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setOrganizationDomain('qgis.org')
        # noinspection PyCallByClass,PyArgumentList
        QCoreApplication.setApplicationName('QGIS2InaSAFETesting')

        # We disabled message bars for now for extent selector as
        # we don't have a main window to show them in TS - version 3.2
        set_setting('show_extent_warnings', False, settings)
        set_setting('showRubberBands', True, settings)
        set_setting('show_extent_confirmations', False, settings)
        set_setting('analysis_extents_mode', HAZARD_EXPOSURE, settings)
        if default_user_directory:
            set_setting('defaultUserDirectory', default_user_directory,
                        settings)

        # noinspection PyPep8Naming
        if 'argv' in dir(sys):
            QGIS_APP = QgsApplication([p.encode('utf-8') for p in sys.argv],
                                      gui_flag)
        else:
            QGIS_APP = QgsApplication([], gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        QGIS_APP.initQgis()

        # Initialize processing
        processing.Processing.initialize()

        s = QGIS_APP.showSettings()
        LOGGER.debug(s)

    if not locale_match:
        """Setup internationalisation for the plugin."""

        # Save some settings
        set_general_setting('locale/overrideFlag', True, settings)
        set_general_setting('locale/userLocale', requested_locale, settings)

        locale_name = str(requested_locale).split('_')[0]
        # Also set the system locale to the user overridden local
        # so that the inasafe library functions gettext will work
        # .. see:: :py:func:`common.utilities`
        os.environ['LANG'] = str(locale_name)

        inasafe_translation_path = os.path.join(
            safe_dir('i18n'), 'inasafe_' + str(locale_name) + '.qm')

        if os.path.exists(inasafe_translation_path):
            if isinstance(QGIS_APP, sip.wrappertype):
                translator = QTranslator()
            else:
                translator = QTranslator(QGIS_APP)
            result = translator.load(inasafe_translation_path)
            if not result:
                message = 'Failed to load translation for %s' % locale_name
                raise Exception(message)
            # noinspection PyTypeChecker,PyCallByClass
            QCoreApplication.installTranslator(translator)

        # at the end, reload InaSAFE modules so it will get translated too
        reload_inasafe_modules()

    if PARENT is None:
        # noinspection PyPep8Naming
        PARENT = QtWidgets.QWidget()

    if CANVAS is None:
        # noinspection PyPep8Naming
        CANVAS = QgsMapCanvas(PARENT)
        CANVAS.resize(QtCore.QSize(400, 400))

    if IFACE is None:
        # QgisInterface is a stub implementation of the QGIS plugin interface
        # noinspection PyPep8Naming
        IFACE = QgisInterface(CANVAS)

    return QGIS_APP, CANVAS, IFACE, PARENT
Exemplo n.º 44
0
    def __init__(self, alg):
        super(AlgorithmDialogBase, self).__init__(iface.mainWindow() if iface else None)
        self.setupUi(self)

        # don't collapse parameters panel
        self.splitter.setCollapsible(0, False)

        # add collapse button to splitter
        splitterHandle = self.splitter.handle(1)
        handleLayout = QVBoxLayout()
        handleLayout.setContentsMargins(0, 0, 0, 0)
        self.btnCollapse = QToolButton(splitterHandle)
        self.btnCollapse.setAutoRaise(True)
        self.btnCollapse.setFixedSize(12, 12)
        self.btnCollapse.setCursor(Qt.ArrowCursor)
        handleLayout.addWidget(self.btnCollapse)
        handleLayout.addStretch()
        splitterHandle.setLayout(handleLayout)

        self.settings = QgsSettings()
        self.splitter.restoreState(self.settings.value("/Processing/dialogBaseSplitter", QByteArray()))
        self.restoreGeometry(self.settings.value("/Processing/dialogBase", QByteArray()))
        self.splitterState = self.splitter.saveState()
        self.splitterChanged(0, 0)

        self.executed = False
        self.mainWidget = None
        self.alg = alg

        self.setWindowTitle(self.alg.displayName())

        self.buttonBox.rejected.connect(self.reject)
        self.buttonBox.accepted.connect(self.accept)

        # Rename OK button to Run
        self.btnRun = self.buttonBox.button(QDialogButtonBox.Ok)
        self.btnRun.setText(self.tr('Run'))

        self.buttonCancel.setEnabled(False)

        self.btnClose = self.buttonBox.button(QDialogButtonBox.Close)

        self.buttonBox.helpRequested.connect(self.openHelp)

        self.btnCollapse.clicked.connect(self.toggleCollapsed)
        self.splitter.splitterMoved.connect(self.splitterChanged)

        # desktop = QDesktopWidget()
        # if desktop.physicalDpiX() > 96:
        # self.txtHelp.setZoomFactor(desktop.physicalDpiX() / 96)

        algHelp = self.formatHelp(self.alg)
        if algHelp is None:
            self.textShortHelp.hide()
        else:
            self.textShortHelp.document().setDefaultStyleSheet('''.summary { margin-left: 10px; margin-right: 10px; }
                                                    h2 { color: #555555; padding-bottom: 15px; }
                                                    a { text-decoration: none; color: #3498db; font-weight: bold; }
                                                    p { color: #666666; }
                                                    b { color: #333333; }
                                                    dl dd { margin-bottom: 5px; }''')
            self.textShortHelp.setHtml(algHelp)

        def linkClicked(url):
            webbrowser.open(url.toString())

        self.textShortHelp.anchorClicked.connect(linkClicked)

        self.showDebug = ProcessingConfig.getSetting(
            ProcessingConfig.SHOW_DEBUG_IN_DIALOG)
Exemplo n.º 45
0
def askForApiKey():
    global _apikey
    text, ok = QInputDialog.getText(iface.mainWindow(), 'what3words', 'Enter the API Key:')
    if ok:
        _apikey = text
        QSettings().setValue("/what3words/apikey/", text)
Exemplo n.º 46
0
    def executeAlgorithm(self):
        config = {}
        if self.in_place_mode:
            config['IN_PLACE'] = True
        alg = self.algorithmTree.selectedAlgorithm().create(
            config) if self.algorithmTree.selectedAlgorithm(
            ) is not None else None
        if alg is not None:
            ok, message = alg.canExecute()
            if not ok:
                dlg = MessageDialog()
                dlg.setTitle(self.tr('Error executing algorithm'))
                dlg.setMessage(
                    self.tr('<h3>This algorithm cannot '
                            'be run :-( </h3>\n{0}').format(message))
                dlg.exec_()
                return

            in_place_input_parameter_name = 'INPUT'
            if hasattr(alg, 'inputParameterName'):
                in_place_input_parameter_name = alg.inputParameterName()

            if self.in_place_mode and not [
                    d for d in alg.parameterDefinitions() if d.name() not in
                (in_place_input_parameter_name, 'OUTPUT')
            ]:
                parameters = {}
                feedback = MessageBarProgress(algname=alg.displayName())
                ok, results = execute_in_place(alg,
                                               parameters,
                                               feedback=feedback)
                if ok:
                    iface.messageBar().pushSuccess(
                        '',
                        self.tr(
                            '{algname} completed. %n feature(s) processed.',
                            n=results['__count']).format(
                                algname=alg.displayName()))
                feedback.close()
                # MessageBarProgress handles errors
                return

            if alg.countVisibleParameters() > 0:
                dlg = alg.createCustomParametersWidget(self)

                if not dlg:
                    dlg = AlgorithmDialog(alg, self.in_place_mode,
                                          iface.mainWindow())
                canvas = iface.mapCanvas()
                prevMapTool = canvas.mapTool()
                dlg.show()
                dlg.exec_()
                if canvas.mapTool() != prevMapTool:
                    try:
                        canvas.mapTool().reset()
                    except:
                        pass
                    canvas.setMapTool(prevMapTool)
            else:
                feedback = MessageBarProgress(algname=alg.displayName())
                context = dataobjects.createContext(feedback)
                parameters = {}
                ret, results = execute(alg, parameters, context, feedback)
                handleAlgorithmResults(alg, context, feedback)
                feedback.close()
Exemplo n.º 47
0
    def search_slot(self, result: dict, tags: dict):
        """ Slot connected to ApiRequester.search_sig signal. It updates widgets, using
        SearchFormManager appropiate methods to fill them from 'tags' parameter and put
        them in the right status. It also display the results contained in 'result'
        parameter by calling ResultManager.show_results method if necessary.

        :param dict result: parsed content of API's reply to a search request (passed by
        ApiRequester.handle_reply method)
        :param dict tags: tags contained in API's reply parsed and classed into a dict
        (passed by ApiRequester.handle_reply method)
        """
        QgsMessageLog.logMessage(
            message="Query sent & received: {}".format(result.get("query")),
            tag="Isogeo",
            level=0,
        )
        # Save entered text and filters in search form
        self.form_mng.old_text = self.form_mng.txt_input.text()
        params = self.form_mng.save_params()

        # Show how many results there are
        self.results_count = result.get("total")
        self.form_mng.btn_show.setText(
            str(self.results_count) + self.tr(" results"))
        page_count = str(
            plg_tools.results_pages_counter(total=self.results_count))
        self.form_mng.lbl_page.setText("page " + str(self.page_index) +
                                       self.tr(" on ") + page_count)

        # Clear widgets
        self.form_mng.tbl_result.clearContents()
        self.form_mng.tbl_result.setRowCount(0)

        # Initialize the widgets that dont't need to be updated
        if self.savedSearch == "_default" or self.hardReset is True:
            logger.debug("Default search or reset.")
            self.form_mng.init_steps()
        else:
            logger.debug("Not default search nor reset.")
            pass

        # Filling Advanced search comboboxes from tags
        self.form_mng.pop_as_cbbs(tags)
        # Filling quick searches comboboxes from json file (also the one in settings tab)
        qs_list = list(self.form_mng.qs_mng.load_file().keys())
        self.form_mng.pop_qs_cbbs(qs_list)
        # Sorting Advanced search comboboxes
        for cbb in self.cbbs_search_advanced:
            cbb.model().sort(0)

        # Putting comboboxes' selected index to the appropriate location
        # and updating key words checkable combobox
        if self.hardReset is True:
            # In case of a hard reset, we don't have to worry about comboboxes' selected index
            logger.debug("Reset search")
            self.form_mng.update_cbb_keywords(
                tags_keywords=tags.get("keywords"))
        else:
            logger.debug("Classical search or quicksearch (no reset search)")
            if self.savedSearch == "":
                # Putting all the comboboxes selected index to their previous location.
                logger.debug("Classic search case (not quicksearch)")
                # Setting widgets to their previous index
                self.form_mng.set_ccb_index(params=params)
                # Updating the keywords special combobox (filling + indexing)
                self.form_mng.update_cbb_keywords(
                    tags_keywords=tags.get("keywords"),
                    selected_keywords=params.get("keys"),
                )
            else:
                # Putting all the comboboxes selected index
                # according to params found in the json file
                logger.debug("Quicksearch case: {}".format(self.savedSearch))
                # Opening the json to get quick search's params
                search_params = self.form_mng.qs_mng.load_file().get(
                    self.savedSearch)
                # Putting widgets to their previous states according to the json content
                self.form_mng.set_ccb_index(params=search_params,
                                            quicksearch=self.savedSearch)
                self.savedSearch = ""
                # Updating the keywords special combobox (filling + indexing)
                keywords_list = [
                    v for k, v in search_params.items()
                    if k.startswith("keyword")
                ]
                self.form_mng.update_cbb_keywords(
                    tags_keywords=tags.get("keywords"),
                    selected_keywords=keywords_list)

        # tweaking
        plg_tools._ui_tweaker(
            ui_widgets=self.form_mng.tab_search.findChildren(QComboBox))

        # Formatting show result button according to the number of results
        if self.results_count == 0:
            self.form_mng.btn_show.setEnabled(False)
            self.form_mng.btn_show.setStyleSheet("QPushButton { }")
        else:
            self.form_mng.btn_show.setEnabled(True)
            self.form_mng.btn_show.setStyleSheet(
                "QPushButton "
                "{background-color: rgb(255, 144, 0); color: white}")

        # Showing result : if button 'show result', 'next page' or 'previous page' pressed
        if self.showResult is True:
            self.form_mng.fill_tbl_result(
                content=result,
                page_index=self.page_index,
                results_count=self.results_count,
            )
            iface.mainWindow().statusBar().removeWidget(self.bar)
            self.store = True
        else:
            pass

        # Re enable all user input fields now the search function is
        # finished.
        self.form_mng.switch_widgets_on_and_off(1)
        # Reseting attributes values
        self.hardReset = False
        self.showResult = False
Exemplo n.º 48
0
    def run(self):
        """Run method that loads and starts the plugin"""
        if not iface.building_toolbar:
            # Set up toolbar
            iface.building_toolbar = QToolBar(u"Building Tools")
            iface.addToolBar(iface.building_toolbar, Qt.RightToolBarArea)

        # Create the dockwidget and dialog and keep reference
        if not self.dockwidget:
            self.dockwidget = BuildingsDockwidget()

            # Connect with close
            self.dockwidget.closed.connect(self.on_dockwidget_closed)

            # Show the dockwidget as a tab
            layerdock = iface.mainWindow().findChild(QDockWidget, "Layers")
            iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
            iface.mainWindow().tabifyDockWidget(layerdock, self.dockwidget)

            self.setup_main_toolbar()
            dw = self.dockwidget
            # no base layers
            self.menu_frame = MenuFrame(self.dockwidget)
            dw.insert_into_frames("menu_frame", self.menu_frame)

            home_dir = os.path.dirname(__file__)

            if dw.lst_options.item(0) is None:
                icon_path = os.path.join(home_dir, "icons",
                                         "buildings_plugin.png")
                item = QListWidgetItem("Buildings")
                item.setIcon(QIcon(icon_path))
                dw.lst_options.addItem(item)
                dw.lst_options.setCurrentItem(item)

            icon_path = os.path.join(home_dir, "icons", "capture_source.png")
            item = QListWidgetItem("Capture Sources")
            item.setIcon(QIcon(icon_path))
            dw.lst_sub_menu.addItem(item)

            icon_path = os.path.join(home_dir, "icons", "bulk_load.png")
            item = QListWidgetItem("Bulk Load")
            item.setIcon(QIcon(icon_path))
            dw.lst_sub_menu.addItem(item)

            icon_path = os.path.join(home_dir, "icons", "edit.png")
            item = QListWidgetItem("Edit Outlines")
            item.setIcon(QIcon(icon_path))
            dw.lst_sub_menu.addItem(item)

            icon_path = os.path.join(home_dir, "icons", "settings.png")
            item = QListWidgetItem("Settings")
            item.setIcon(QIcon(icon_path))
            dw.lst_sub_menu.addItem(item)

            icon_path = os.path.join(home_dir, "icons", "reference.png")
            item = QListWidgetItem("Reference Data")
            item.setIcon(QIcon(icon_path))
            dw.lst_sub_menu.addItem(item)

            canvas = iface.mapCanvas()
            selectedcrs = "EPSG:2193"
            target_crs = QgsCoordinateReferenceSystem()
            target_crs.createFromUserInput(selectedcrs)
            canvas.setDestinationCrs(target_crs)
            self.on_click()

        self.dockwidget.show()
        self.dockwidget.raise_()
Exemplo n.º 49
0
 def __init__(self, func):
     QtCore.QThread.__init__(self, iface.mainWindow())
     self.func = func
     self.returnValue = None
     self.exception = None
Exemplo n.º 50
0
    def __init__(self, iface, ACA):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        self.CFG = None
        self.UTI = None
        self.DFS = None
        self.DBJ = None
        self.ELM = None
        self.ACA = ACA
        self.TPG = None
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'DivisionFusion_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference
        self.dlg = DivisionFusionDialog(parent=iface.mainWindow())
        #self.dlg.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&DivisionFusion')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'DivisionFusion')
        self.toolbar.setObjectName(u'DivisionFusion')

        #self.dlg.setMinimumSize(QSize(464, 465))
        #self.dlg.setMaximumSize(QSize(371, 372))
        #print(self.dlg.size())
        #self.dlg.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.eventos = EventoDivision(iface.mapCanvas(), self)
        self.VentanaAreas = VentanaAreas(self)

        self.VentanaFusion = VentanaFusionV3(iface, self)
        self.VentanaClaves = VentanaClavesV3(iface, self)
        self.rubberMarca = QgsRubberBand(iface.mapCanvas(),
                                         QgsWkbTypes.PolygonGeometry)
        self.rubberMarca.setFillColor(QColor(255, 255, 0, 12))
        self.rubberMarca.setStrokeColor(QColor(255, 150, 0, 255))
        self.rubberMarca.setWidth(2)
        self.listaNuevosPredios = []
        self.cargoPredio = False
        self.listaColores = []
        self.rubbersAreas = []

        self.dlg.btnDibujarCortes.setEnabled(False)
        self.dlg.btnEditarCortes.setEnabled(False)
        self.dlg.btnEliminarCortes.setEnabled(False)
        self.dlg.btnApagarHerramientas.setEnabled(False)
        self.dlg.btnConfirmarCortes.setEnabled(False)
        self.dlg.btnDeshacerTodo.setEnabled(False)
        self.dlg.btnCancelarSub.setEnabled(False)
        self.dlg.btnDeshacerCortes.setEnabled(False)
        self.dlg.btnLlamarCalcular.setEnabled(False)

        self.dlg.btnFusionar.clicked.connect(self.preguntarFusion)
        self.dlg.btnCargarPredio.clicked.connect(self.pasarAModoDivision)
        self.dlg.btnConfirmarCortes.clicked.connect(self.confirmarCortes)
        self.dlg.btnDibujarCortes.clicked.connect(self.encenderModoDividir)
        self.dlg.btnEliminarCortes.clicked.connect(self.encenderModoEliminar)
        self.dlg.btnApagarHerramientas.clicked.connect(self.apagarHerramientas)
        self.dlg.btnDeshacerTodo.clicked.connect(self.rollBack)
        self.dlg.btnCancelarSub.clicked.connect(self.cancelarSubdivision)
        self.dlg.btnDeshacerCortes.clicked.connect(self.vaciarLineasCorte)
        self.dlg.btnLlamarCalcular.clicked.connect(self.irAreas)
        self.dlg.btnEditarCortes.clicked.connect(self.encenderModoEditar)

        self.geomsAreas = []
Exemplo n.º 51
0
    def __init__(self, iface):
        QDockWidget.__init__(self, iface.mainWindow())
        self.setupUi(self)
        self.iface = iface

        # variables
        self.__mLastVfkFile = []
        self.__mOgrDataSource = None
        self.__mDataSourceName = ''
        self.__fileName = []
        self.__mLoadedLayers = {}
        self.__mDefaultPalette = self.vfkFileLineEdit.palette()

        # new lineEdits variables
        self.lineEditsCount = 1

        self.__browseButtons = {}
        self.__vfkLineEdits = {}

        # data will be load from source according to checked radiobox
        self.__source_for_data = 'file'

        # apply changes into main database
        self.__databases = {}
        # self.pb_applyChanges.setEnabled(False)
        self.changes_instance = ApplyChanges()

        # Connect ui with functions
        self.__createToolbarsAndConnect()

        # check GDAL version
        self.__gdal_version = int(gdal.VersionInfo())

        if self.__gdal_version < 2020000:
            self.actionZpracujZmeny.setEnabled(False)
            self.pb_nextFile.setEnabled(False)
            self.pb_nextFile.setToolTip(
                u'Není možné načíst více souborů, verze GDAL je nižší než 2.2.0.'
            )
            self.actionZpracujZmeny.setToolTip(
                u'Zpracování změn není povoleno, verze GDAL je nižší než 2.2.0.'
            )
            self.groupBox.setEnabled(False)

        # settings
        self.loadVfkButton.setDisabled(True)

        self.searchFormMainControls = SearchFormController.MainControls()
        self.searchFormMainControls.formCombobox = self.searchCombo
        self.searchFormMainControls.searchForms = self.searchForms
        self.searchFormMainControls.searchButton = self.searchButton

        self.searchForms = SearchFormController.SearchForms()
        self.searchForms.vlastnici = self.vlastniciSearchForm
        self.searchForms.parcely = self.parcelySearchForm
        self.searchForms.budovy = self.budovySearchForm
        self.searchForms.jednotky = self.jednotkySearchForm

        # search form controller
        self.__mSearchController = SearchFormController(
            self.searchFormMainControls, self.searchForms, self)

        self.__mSearchController.actionTriggered.connect(
            self.vfkBrowser.processAction)
        self.enableSearch.connect(self.searchButton.setEnabled)

        self.vfkBrowser.showParcely.connect(self.showParInMap)
        self.vfkBrowser.showBudovy.connect(self.showBudInMap)

        # connect lineEdits and returnPressed action
        self.vfkFileLineEdit.returnPressed.connect(self.loadVfkButton_clicked)
        self.vlastniciSearchForm.ui.jmenoLineEdit.returnPressed.connect(
            self.__mSearchController.search)
        self.vlastniciSearchForm.ui.rcIcoLineEdit.returnPressed.connect(
            self.__mSearchController.search)
        self.vlastniciSearchForm.ui.lvVlastniciLineEdit.returnPressed.connect(
            self.__mSearchController.search)

        self.parcelySearchForm.ui.parCisloLineEdit.returnPressed.connect(
            self.__mSearchController.search)
        self.parcelySearchForm.ui.lvParcelyLineEdit.returnPressed.connect(
            self.__mSearchController.search)

        self.budovySearchForm.ui.cisloDomovniLineEdit.returnPressed.connect(
            self.__mSearchController.search)
        self.budovySearchForm.ui.naParceleLineEdit.returnPressed.connect(
            self.__mSearchController.search)
        self.budovySearchForm.ui.lvBudovyLineEdit.returnPressed.connect(
            self.__mSearchController.search)

        self.jednotkySearchForm.ui.mCisloJednotkyLineEdit.returnPressed.connect(
            self.__mSearchController.search)
        self.jednotkySearchForm.ui.mCisloDomovniLineEdit.returnPressed.connect(
            self.__mSearchController.search)
        self.jednotkySearchForm.ui.mNaParceleLineEdit.returnPressed.connect(
            self.__mSearchController.search)
        self.jednotkySearchForm.ui.mLvJednotkyLineEdit.returnPressed.connect(
            self.__mSearchController.search)

        self.vfkBrowser.showHelpPage()

        # settings
        self.settings = QtCore.QSettings()
Exemplo n.º 52
0
    def __init__(self, parent):
        super().__init__(parent)

        self.canvas = iface.mapCanvas()
        self.dockwidget = wyszukiwarkaDzialekDockWidget()
        # self.menu = self.tr(PLUGIN_NAME)
        # self.toolbar = self.iface.addToolBar(PLUGIN_NAME)
        # self.toolbar.setObjectName(PLUGIN_NAME)

        self.teryt_search_result_collector = ResultCollectorSingle(self)
        self.map_point_search_result_collector = self.teryt_search_result_collector

        self.project = QgsProject.instance()
        self.wms_layer = None
        self.module_csv_import = None
        self.module_teryt_search = None
        self.module_point_layer_import = None
        self.module_wms_kieg_initialized = False
        self.module_map_point_search = MapPointSearch(
            self, self.teryt_search_result_collector)

        result_collector_factory = lambda parent, target_layer: ResultCollectorMultiple(
            self, target_layer)
        self.module_teryt_search = TerytSearch(
            self, self.dockwidget.tab_teryt_search_layout,
            self.teryt_search_result_collector, result_collector_factory,
            ResultCollectorMultiple.default_layer_factory)
        self.module_teryt_search.lpis_bbox_found.connect(self.add_wms_lpis)

        result_collector_factory = lambda parent, target_layer: ResultCollectorMultiple(
            self, target_layer)
        self.module_csv_import = CSVImport(
            self, self.dockwidget.tab_import_csv_layout,
            result_collector_factory,
            ResultCollectorMultiple.default_layer_factory)

        self.module_point_layer_import = PointLayerImport(
            self, self.dockwidget.tab_import_layer_point_layout)

        self.wms_kieg_layer = None
        self.dockwidget.button_wms_kieg.clicked.connect(self.add_wms_kieg)
        self.module_wms_kieg_initialized = True

        self.wms_lpis_layer = None
        self.dockwidget.button_wms_lpis.clicked.connect(self.add_wms_lpis)
        self.module_wms_lpis_initialized = True

        icon_info_path = ':/plugins/plugin/info.png'
        self.dockwidget.label_info_map_point_search.setPixmap(
            QPixmap(icon_info_path))
        self.dockwidget.label_info_map_point_search.setToolTip((
            "Wybierz narzędzie i kliknij na mapę.\n"
            "Narzędzie wyszuka działkę, w której zawierają się współrzędne kliknięcia."
        ))

        #Zarejestrowanie we wtyczce

        iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)

        self.uldk_toolbar_action = self.parent.add_action(
            ":/plugins/gissupport_plugin/uldk/uldk.svg",
            self.module_name,
            lambda state: self.dockwidget.setHidden(not state),
            checkable=True,
            parent=iface.mainWindow(),
            add_to_topmenu=True)

        self.dockwidget.visibilityChanged.connect(
            self.uldk_toolbar_action.setChecked)

        self.identify_action = self.parent.add_action(
            ":/plugins/gissupport_plugin/uldk/uldk_identify.svg",
            text="Identifykacja ULDK",
            callback=lambda toggle: iface.mapCanvas().setMapTool(
                self.module_map_point_search),
            parent=iface.mainWindow(),
            checkable=True,
            add_to_topmenu=False)
        self.module_map_point_search.setAction(self.identify_action)
        self.parent.toolbar.addSeparator()

        self.dockwidget.btnIdentify.setDefaultAction(self.identify_action)

        self.dockwidget.hide()
Exemplo n.º 53
0
def saveCurrentPluginState():
    global currentProfile
    if currentProfile is not None:
        settings.setValue(
            "profilesplugin/Profiles/%s/geometry" % currentProfile,
            iface.mainWindow().saveState())
    def alternatingSliceTilt(self, geom, polyLayer, targetArea, granularity,
                             tilt):
        """
        Slice a poly in alternating directions
        """
        global recurs
        recurs += 1
        if self.debug: print "******************************"
        if self.debug: print "Slicing, No of part: ", str(recurs)
        if self.debug:
            print "Slicing, Granularity remaining: ", str(granularity)
        if self.debug: print "Slicing, direction: ", tilt
        bbox = [
            geom.boundingBox().xMinimum(),
            geom.boundingBox().yMinimum(),
            geom.boundingBox().xMaximum(),
            geom.boundingBox().yMaximum()
        ]
        if tilt > 90:
            tilt_new = 180 - tilt
            if bbox[2] - bbox[0] > bbox[3] - bbox[1]:
                granulY = (bbox[3] - bbox[1]) / granularity
                stepY = granulY
                stepX = math.tan(math.radians(tilt_new)) * granulY
            else:
                granulX = (bbox[2] - bbox[0]) / granularity
                stepX = granulX
                stepY = granulX / math.tan(math.radians(tilt_new))
        else:
            if bbox[2] - bbox[0] > bbox[3] - bbox[1]:
                granulY = (bbox[3] - bbox[1]) / granularity
                stepY = -1 * granulY
                stepX = math.tan(math.radians(tilt)) * granulY
            else:
                granulX = (bbox[2] - bbox[0]) / granularity
                stepX = granulX
                stepY = -1 * granulX / math.tan(math.radians(tilt))

#         granulX=(bbox[2]-bbox[0])/granularity
#         granulY=(bbox[3]-bbox[1])/granularity
        baseX = bbox[0]
        pointerX = bbox[0]
        if 180 > tilt > 90:
            #             stepX = granulX / abs(math.cos(math.radians(tilt)))
            #             stepY = granulY / abs(math.sin(math.radians(tilt)))
            pointerY = bbox[1]
            baseY = bbox[1]
        elif 90 > tilt > 0:
            #             stepX = granulX / abs(math.cos(math.radians(tilt)))
            #             stepY = -1 * granulY / abs(math.sin(math.radians(tilt)))
            pointerY = bbox[3]
            baseY = bbox[3]
        elif tilt == 90 or tilt == 0 or tilt >= 180:
            QMessageBox.warning(
                iface.mainWindow(), "Warning",
                "The value of tilt is incorrect!\n It must be in range 0-180.\ntilt:%i"
                % tilt)
        totalArea = 0
        slices = 0
        #save the original geom
        tempGeom = QgsGeometry(geom)
        #start slicing until targetArea is reached
        stepMode = "course"
        stepDirection = 1  # +1 foreword, -1 backword
        fineStepX = stepX
        fineStepY = stepY
        while abs(totalArea - targetArea) / targetArea > 0.005:

            if self.debug: print stepMode + ":" + str(stepDirection)
            if self.debug: print "fineStepX" + ":" + str(fineStepX)
            if self.debug: print "fineStepY" + ":" + str(fineStepY)
            if self.debug: print "baseX" + ":" + str(baseX)
            if self.debug: print "baseY" + ":" + str(baseY)

            pointerX += fineStepX * stepDirection
            pointerY += fineStepY * stepDirection

            if self.debug: print "pointerX" + ":" + str(pointerX)
            if self.debug: print "pointerY" + ":" + str(pointerY)

            startPt = QgsPoint(pointerX, baseY)
            endPt = QgsPoint(baseX, pointerY)

            if tilt < 90:
                if stepDirection == 1:
                    (tempGeom,
                     multiGeom) = self.cutPoly(tempGeom, startPt, endPt)
                else:
                    (multiGeom,
                     tempGeom) = self.cutPoly(tempGeom, startPt, endPt)
            else:
                if stepDirection == 1:
                    (multiGeom,
                     tempGeom) = self.cutPoly(tempGeom, startPt, endPt)
                else:
                    (tempGeom,
                     multiGeom) = self.cutPoly(tempGeom, startPt, endPt)
            if multiGeom != None:
                totalArea += stepDirection * multiGeom.area()

            if totalArea > targetArea:
                stepMode = "fine"

            if stepMode == "fine":
                if totalArea > targetArea:
                    if stepDirection != -1:
                        fineStepX = fineStepX / 2
                        fineStepY = fineStepY / 2
                        tempGeom = multiGeom
                    stepDirection = -1
                else:
                    if stepDirection != 1:
                        fineStepX = fineStepX / 2
                        fineStepY = fineStepY / 2
                        tempGeom = multiGeom
                    stepDirection = 1
            if self.debug: print "totalArea" + ":" + str(totalArea)
            if self.debug: print "targetArea" + ":" + str(targetArea)
            slices += 1

        self.progress.setValue(recurs + 1)

        if self.debug: print "Slicing, Slices: ", str(slices)
        #do the real cutting when reached targetArea and add "left" feature to layer
        if self.debug: print "Cutting with line, Cutline:", startPt, ",", endPt

        if tilt < 90:
            (leftgeom, multiGeom) = self.cutPoly(geom, startPt, endPt, True)
        else:
            (multiGeom, leftgeom) = self.cutPoly(geom, startPt, endPt, True)

        if multiGeom:
            if self.debug:
                print "After split, Parts to the left:", str(
                    len(multiGeom.asGeometryCollection()))
        if leftgeom:
            if self.debug:
                print "After split, Parts to the right:", str(
                    len(geom.asGeometryCollection()))

        if leftgeom:
            if leftgeom.area() > targetArea:
                self.alternatingSliceTilt(leftgeom, polyLayer, targetArea,
                                          granularity, tilt)
            elif leftgeom.area() < targetArea / 2:
                multiGeom = geom
            else:
                self.addGeomToLayer(leftgeom, polyLayer)
        self.addGeomToLayer(multiGeom, polyLayer)
    def loadAppdef(self, appdef):
        try:
            self.titleBox.setText(appdef["Settings"]["Title"])
            self.logoBox.setText(appdef["Settings"]["Logo"])
            for button, widgetName in self.widgetButtons.iteritems():
                if widgetName in appdef["Widgets"]:
                    button.setChecked(True)
                    button.webAppWidget.setParameters(
                        appdef["Widgets"][widgetName]["Parameters"])
                else:
                    button.setChecked(False)
                    button.webAppWidget.resetParameters()

            for name in self.settingsItems:
                if name in appdef["Settings"]:
                    self.settingsItems[name].setValue(appdef["Settings"][name])
            theme = appdef["Settings"]["Theme"]
            for button, themeName in self.themesButtons.iteritems():
                if themeName == theme:
                    button.click()
            baseLayers = appdef["Base layers"]
            for button, name in self.baseLayers.iteritems():
                button.setChecked(name in baseLayers)
            for button, name in self.baseOverlays.iteritems():
                button.setChecked(name in baseLayers)
            items = []
            for i in xrange(self.layersTree.topLevelItemCount()):
                item = self.layersTree.topLevelItem(i)
                if isinstance(item, TreeLayerItem):
                    items.append(item)
                else:
                    try:
                        item.setShowContent(
                            appdef["Groups"][item.text(0)]["showContent"])
                        item.setIsGroupExpanded(
                            appdef["Groups"][item.text(0)]["isGroupExpanded"])
                    except:
                        pass
                    for j in xrange(item.childCount()):
                        subitem = item.child(j)
                        if isinstance(subitem, TreeLayerItem):
                            items.append(subitem)

            layers = {lay["layer"]: lay for lay in appdef["Layers"]}
            for item in items:
                if item.layer.name() in layers:
                    item.setCheckState(0, Qt.Checked)
                    layer = layers[item.layer.name()]
                    item.setValues(layer["visible"], layer["popup"],
                                   layer["clusterDistance"],
                                   layer["clusterColor"],
                                   layer["allowSelection"],
                                   layer["showInOverview"], layer["timeInfo"],
                                   layer["showInControls"],
                                   layer["singleTile"])
                else:
                    item.setCheckState(0, Qt.Unchecked)

        except Exception, e:
            QgsMessageLog.logMessage(traceback.format_exc(),
                                     level=QgsMessageLog.WARNING)
            QMessageBox.warning(
                iface.mainWindow(), "Error loading app definition",
                "App definition could not be loaded.\nCheck QGIS log for more details"
            )
    def splitSelectedByNumber(self,
                              layerName,
                              div,
                              method="h",
                              tilt=90,
                              checkNewShape=False,
                              shpPath="result",
                              checkExitingShape=False,
                              checkResultToMap=True):
        global recurs
        recurs = 0
        if layerName == "":
            QMessageBox.warning(iface.mainWindow(), "error",
                                "At least a polygon layer must be selected.")
            return
        maplist = QgsMapLayerRegistry.instance().mapLayersByName(layerName)
        layer = maplist[0]
        if layer:
            #Gets layer CRS for new layer
            crs = layer.crs().description()
            if self.debug: print "Starting, Layer crs: " + crs
            # Create a new memory layer and add an area attribute

            polName = "%s_%s_%i" % (layerName, method, div)
            polyLayer = QgsVectorLayer("MultiPolygon?crs=" + crs, polName,
                                       "memory")
            polyLayer.dataProvider().addAttributes(
                [QgsField("strataArea", QVariant.Double)])
            #QgsMapLayerRegistry.instance().addMapLayer(polyLayer)
            allFeatures = False
            if not layer.selectedFeatures():
                layer.invertSelection()
                allFeatures = True
            #save original target area
#             origTargetArea=targetArea
# Loop though all the selected features
            progressMessageBar = iface.messageBar().createMessage(
                "splitting...")
            self.progress = QProgressBar()
            self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            self.progress.setMaximum(div * layer.selectedFeatureCount())
            progressMessageBar.layout().addWidget(self.progress)
            iface.messageBar().pushWidget(progressMessageBar,
                                          iface.messageBar().INFO)
            self.progress.setValue(1)

            for feature in layer.selectedFeatures():
                geom = feature.geometry()
                targetArea = geom.area() / div
                granularity = div * 2
                if self.debug:
                    print "Starting Number of original geoms: ", str(
                        len(geom.asGeometryCollection()))
                if self.debug:
                    print "Starting Number of part to split into: ", str(
                        geom.area() / div)
                #                 div=round(geom.area()/origTargetArea)
                if div < 1:
                    div = 1
                if div > 1:
                    #                     granularity=round(granulFactor*geom.area()/targetArea)
                    #                     if self.debug: print "Granularity: ",granularity
                    #Figure out direction to start with from cutting method
                    #If alternating, start horizontally
                    if tilt == 0 or tilt == 90:
                        self.alternatingSlice(geom, polyLayer, targetArea,
                                              granularity, method, method)
                    else:
                        if method == "h":
                            self.alternatingSliceTilt(geom, polyLayer,
                                                      targetArea, granularity,
                                                      tilt + 90)
                        else:
                            self.alternatingSliceTilt(geom, polyLayer,
                                                      targetArea, granularity,
                                                      tilt)
                else:
                    self.addGeomToLayer(geom, polyLayer)
            polyLayer.commitChanges()
            self.progress.setValue(div * layer.selectedFeatureCount())

            polyLayer.updateExtents()
            #if self.debug: print recurs
            if checkResultToMap:
                QgsMapLayerRegistry.instance().addMapLayer(polyLayer)
            if checkNewShape:
                QgsVectorFileWriter.writeAsVectorFormat(
                    polyLayer, shpPath, 'utf-8', polyLayer.crs())
            if checkExitingShape:
                polyLayer.selectAll()
                layer.dataProvider().addFeatures(polyLayer.selectedFeatures())
                layer.updateExtents()
                layer.selectAll()
                layer.invertSelection()
            if allFeatures:
                layer.invertSelection()
            iface.messageBar().hide()
Exemplo n.º 57
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()
            self.processDependencies(plugin["id"])
            # try to load the plugin
            loadPlugin(plugin["id"])
            plugins.getAllInstalled()
            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 Qgis.Critical or Qgis.Info
            msg = "<b>%s</b>" % infoString[0]
            if infoString[1]:
                msg += "<b>:</b> %s" % infoString[1]
            iface.pluginManagerInterface().pushMessage(msg, level)
Exemplo n.º 58
0
    consl = splite.connect(database=database_QKan)
    cursl = consl.cursor()

    # iface.messageBar().pushMessage("Information", "SpatiaLite-Datenbank wird erstellt. Bitte warten...",
    #     level=QgsMessageBar.INFO)
    progressMessageBar = iface.messageBar().createMessage(
        "Doing something boring...")
    progress = QProgressBar()
    progress.setMaximum(10)
    progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
    progressMessageBar.layout().addWidget(progress)
    iface.messageBar().pushWidget(progressMessageBar, iface.messageBar().INFO)
    progress.setValue(2)
    iface.messageBar().clearWidgets()

    iface.mainWindow().statusBar().showMessage(
        "SpatiaLite-Datenbank wird erstellt. Bitte warten... {} %".format(20))
    import time
    time.sleep(1)

    sql = 'SELECT InitSpatialMetadata(transaction = TRUE)'
    cursl.execute(sql)

    iface.messageBar().pushMessage("Information",
                                   "SpatiaLite-Datenbank ist erstellt!",
                                   level=QgsMessageBar.INFO)

    createdbtables(consl, cursl)
    consl.close()
Exemplo n.º 59
0
    def __init__(self, filePath=None, parent=None):
        super(ScriptEditorDialog, self).__init__(parent)
        self.setupUi(self)

        QgsGui.instance().enableAutoGeometryRestore(self)

        self.editor.initLexer()
        self.searchWidget.setVisible(False)

        if iface is not None:
            self.toolBar.setIconSize(iface.iconSize())
            self.setStyleSheet(iface.mainWindow().styleSheet())

        self.actionOpenScript.setIcon(
            QgsApplication.getThemeIcon('/mActionScriptOpen.svg'))
        self.actionSaveScript.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSave.svg'))
        self.actionSaveScriptAs.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSaveAs.svg'))
        self.actionRunScript.setIcon(
            QgsApplication.getThemeIcon('/mActionStart.svg'))
        self.actionCut.setIcon(
            QgsApplication.getThemeIcon('/mActionEditCut.svg'))
        self.actionCopy.setIcon(
            QgsApplication.getThemeIcon('/mActionEditCopy.svg'))
        self.actionPaste.setIcon(
            QgsApplication.getThemeIcon('/mActionEditPaste.svg'))
        self.actionUndo.setIcon(
            QgsApplication.getThemeIcon('/mActionUndo.svg'))
        self.actionRedo.setIcon(
            QgsApplication.getThemeIcon('/mActionRedo.svg'))
        self.actionFindReplace.setIcon(
            QgsApplication.getThemeIcon('/mActionFindReplace.svg'))
        self.actionIncreaseFontSize.setIcon(
            QgsApplication.getThemeIcon('/mActionIncreaseFont.svg'))
        self.actionDecreaseFontSize.setIcon(
            QgsApplication.getThemeIcon('/mActionDecreaseFont.svg'))

        # Connect signals and slots
        self.actionOpenScript.triggered.connect(self.openScript)
        self.actionSaveScript.triggered.connect(self.save)
        self.actionSaveScriptAs.triggered.connect(self.saveAs)
        self.actionRunScript.triggered.connect(self.runAlgorithm)
        self.actionCut.triggered.connect(self.editor.cut)
        self.actionCopy.triggered.connect(self.editor.copy)
        self.actionPaste.triggered.connect(self.editor.paste)
        self.actionUndo.triggered.connect(self.editor.undo)
        self.actionRedo.triggered.connect(self.editor.redo)
        self.actionFindReplace.toggled.connect(self.toggleSearchBox)
        self.actionIncreaseFontSize.triggered.connect(self.editor.zoomIn)
        self.actionDecreaseFontSize.triggered.connect(self.editor.zoomOut)
        self.editor.textChanged.connect(lambda: self.setHasChanged(True))

        self.leFindText.returnPressed.connect(self.find)
        self.btnFind.clicked.connect(self.find)
        self.btnReplace.clicked.connect(self.replace)
        self.lastSearch = None

        self.filePath = None
        if filePath is not None:
            self._loadFile(filePath)

        self.needUpdate = False
        self.setHasChanged(False)
Exemplo n.º 60
0
def getWABDialog():
    for child in iface.mainWindow().children():
        if isinstance(child,
                      MainDialog) and child.objectName() == "WABMainDialog":
            return child
    return None