Example #1
0
    def _on_test_cmis_connection(self):
        # Slot raised to test connection to CMIS service
        status = self._validate_cmis_properties()
        if not status:
            return

        self.notif_bar.clear()

        atom_pub_url = self.txt_atom_pub_url.text()
        auth_conf_id = self.cbo_auth_config_name.itemData(
            self.cbo_auth_config_name.currentIndex())

        cmis_mgr = CmisManager(url=atom_pub_url, auth_config_id=auth_conf_id)

        QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        status = cmis_mgr.connect()
        QgsApplication.restoreOverrideCursor()

        if status:
            msg = self.tr('Connection to the CMIS server succeeded.')
            self.notif_bar.insertSuccessNotification(msg)
        else:
            msg = self.tr(
                'Failed to connect to the CMIS server. Check URL and/or '
                'credentials.')
            self.notif_bar.insertErrorNotification(msg)
    def getHttp(self, uri, params):
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            rq = QUrl(uri)
            q = QUrlQuery()
            for (k, v) in params.items():
                q.addQueryItem(k, v)

            rq.setQuery(q)
            req = QNetworkRequest(rq)

            try:
                reply = self.nominatim_networkAccessManager.blockingGet(req)
                resource = reply.content().data().decode('utf8')
                r = json.loads(resource)

                if (isinstance(r, list)):
                    self.populateTable(r)
                else:
                    self.populateTable([r])
            except:
                self.tableResult.clearContents()

        finally:
            QgsApplication.restoreOverrideCursor()
    def getHttp(self, uri, params):
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            rq = QUrl(uri)
            q = QUrlQuery()
            for (k, v) in params.items():
                q.addQueryItem(k, v)

            rq.setQuery(q)
            req = QNetworkRequest(rq)

            try:
                reply = self.nominatim_networkAccessManager.blockingGet(req)
                resource = reply.content().data().decode('utf8')
                r = json.loads(resource)

                if (isinstance(r, list)):
                    self.populateTable(r)
                else:
                    self.populateTable([r])
            except:
                self.tableResult.clearContents()

        finally:
            QgsApplication.restoreOverrideCursor()
    def accept(self):
        QgsSettings().setValue("CreateRasterAttributeTable/geometry",
                               self.saveGeometry(), QgsSettings.Plugins)

        # Create the RAT
        is_dbf = self.mDbfRadioButton.isChecked()
        rat_path = self.layer.publicSource() + ('.vat.dbf'
                                                if is_dbf else '.aux.xml')
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        rat = create_rat_from_raster(self.layer, is_dbf, rat_path)
        QgsApplication.restoreOverrideCursor()
        if not rat.isValid():
            self.iface.messageBar().pushMessage(
                QCoreApplication.translate('RAT', "Error"),
                QCoreApplication.translate(
                    'RAT', "There was an error creating the RAT."),
                level=Qgis.Critical)
        else:
            if not rat.save(self.layer.renderer().band()):
                self.iface.messageBar().pushMessage(
                    QCoreApplication.translate('RAT', "Error"),
                    QCoreApplication.translate(
                        'RAT', "There was an error saving the RAT."),
                    level=Qgis.Critical)
            else:
                rat_log(
                    "The Raster Attribute Table has been successfully saved to: %s"
                    % rat_path)
                self.ratCreated.emit(self.layer)

        super().accept()
Example #5
0
def getHttp(uri, params):
    nam = QgsNetworkAccessManager.instance()
    QgsApplication.setOverrideCursor(Qt.WaitCursor)
    try:
        rq = QUrl(uri)
        q = QUrlQuery()
        for (k, v) in params.items():
            q.addQueryItem(k, v)

        rq.setQuery(q)
        req = QNetworkRequest(rq)
        try:
            reply = nam.blockingGet(req)
            resource = reply.content().data().decode("utf8")
            r = json.loads(resource)

            if isinstance(r, list):
                return r
            else:
                return [r]

        except Exception as e:
            for m in e.args:
                QgsMessageLog.logMessage(m, "Extensions")

    finally:
        QgsApplication.restoreOverrideCursor()

    return None
    def initMenus(self):
        menuBar = self.iface.editMenu().parentWidget()
        for action in self.menubarActions:
            menuBar.removeAction(action)
            del action

        self.menubarActions = []

        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        for project in self.projects:
            try:
                doc = QtXml.QDomDocument()
                xml = QFile(project["file"])
                if xml.open(QIODevice.ReadOnly | QIODevice.Text):
                    doc.setContent(xml)

                self.addMenu(project["name"], project["file"], doc)
            except Exception as e:
                QgsMessageLog.logMessage(
                    'Menu from layer: Invalid {}'.format(project["file"]),
                    'Extensions')
                for m in e.args:
                    QgsMessageLog.logMessage(m, 'Extensions')

        QgsApplication.restoreOverrideCursor()
    def initMenus(self):
        menuBar = self.iface.editMenu().parentWidget()
        for action in self.menubarActions:
            menuBar.removeAction(action)
            del action

        self.menubarActions = []

        menuBar = self.iface.addLayerMenu()
        for action in self.layerMenubarActions:
            menuBar.removeAction(action)
            del action

        self.layerMenubarActions = []

        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        previous = None
        for project in self.projects:
            try:
                project["valid"] = True
                uri = project["file"]
                doc, path = self.getQgsDoc(uri)
                previous = self.addMenu(project["name"], uri, path, doc,
                                        project["location"], previous)
            except Exception as e:
                project["valid"] = False
                self.log("Menu from layer: Invalid {}".format(uri))
                for m in e.args:
                    self.log(m)

        QgsApplication.restoreOverrideCursor()
    def get_contrib(self):
        QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            ExtraSources.load_contrib_pack()
            QgsApplication.restoreOverrideCursor()
            info_message = self.tr('Last version of contrib pack was downloaded!')
            QMessageBox.information(self, PluginSettings.product_name(), info_message)
        except:
            QgsApplication.restoreOverrideCursor()
            error_message = self.tr('Error on getting contrib pack: %s %s') % (sys.exc_type, sys.exc_value)
            QMessageBox.critical(self, PluginSettings.product_name(), error_message)
    def get_contrib(self):
        QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            ExtraSources().load_contrib_pack()
            QgsApplication.restoreOverrideCursor()
            info_message = self.tr('Last version of contrib pack was downloaded!')
            QMessageBox.information(self, PluginSettings.product_name(), info_message)

            self.dsManagerViewModel.resetModel()
        except:
            QgsApplication.restoreOverrideCursor()
            error_message = self.tr('Error on getting contrib pack: %s %s') % (sys.exc_type, sys.exc_value)
            QMessageBox.critical(self, PluginSettings.product_name(), error_message)
Example #10
0
 def overlay(self):
     measure = self.dlg.fcbMeasure.layer()
     area = self.dlg.fcbArea.layer()
     params = {
         'INPUT': measure,
         'OVERLAY': area,
         'OUTPUT': "memory:land_water",
         'INTERSECTION': "memory:land_water"
     }
     QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     self.iface.messageBar().pushMessage("Atitude correction",
                                         "Running overlay",
                                         level=Qgis.Info,
                                         duration=3)
     output = processing.runAndLoadResults("qgis:intersection", params)
     QgsApplication.restoreOverrideCursor()
     self.iface.messageBar().pushMessage("Atitude correction",
                                         "Overlay finished",
                                         level=Qgis.Success,
                                         duration=3)
     self.overlaylayer = QgsProject.instance().mapLayer(output['OUTPUT'])
     self.dlg.lcbOverlay.setLayer(self.overlaylayer)
Example #11
0
    def insert_line(self, method):
        layer = self.iface.activeLayer()
        if not isinstance(layer,
                          QgsVectorLayer) or layer.geometryType() != QGis.Line:
            self.iface.messageBar().pushMessage(
                self.tr("ReconstructLine"),
                self.
                tr("Line can\'t be inserted! Select lines layer for inserting new geom!"
                   ),
                level=QgsMessageBar.WARNING,
                duration=5)
            return

        if not layer.isEditable():
            self.iface.messageBar().pushMessage(
                self.tr("ReconstructLine"),
                self.tr("Line can\'t be inserted! Layer is not editable!"),
                level=QgsMessageBar.WARNING,
                duration=5)
            return

        if not self._geom_buffer:
            self.iface.messageBar().pushMessage(
                self.tr("ReconstructLine"),
                self.tr("Line can\'t be inserted! Copy points first!"),
                level=QgsMessageBar.WARNING,
                duration=5)
            return

        #show message
        self.iface.messageBar().clearWidgets()
        self.iface.messageBar().pushMessage(
            self.tr("ReconstructLine"),
            self.tr("Processing points. Please wait..."),
            level=QgsMessageBar.INFO)
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        QgsApplication.processEvents()
        QgsApplication.processEvents()
        QgsApplication.processEvents()

        try:
            # Create line

            # QGS geoms to np
            points = [(in_geom.x(), in_geom.y())
                      for in_geom in self._geom_buffer]
            data = np.array(points)

            # Make line

            if method == 'MST':
                conn = MST(data)
                result = conn.connect()
            elif method == 'SOM':
                som = SOM1d(data)
                result = som.connect()
            else:
                raise ValueError

            #np to QGS
            lines = []
            for line in result:
                lines.append(
                    [QgsPoint(out_geom[0], out_geom[1]) for out_geom in line])

            geom_list = []
            if layer.wkbType() == QGis.WKBMultiLineString:
                geom_list.append(QgsGeometry.fromMultiPolyline(lines))
            else:
                for line in lines:
                    geom_list.append(QgsGeometry.fromPolyline(line))

            # Check crs and reproject
            target_crs = layer.crs()
            if target_crs.srsid() != self._srid.srsid():
                transf = QgsCoordinateTransform(self._srid, target_crs)
                for geom in geom_list:
                    geom.transform(transf)

            # Insert feature(s)
            features = []
            for geom in geom_list:
                feat = QgsFeature()
                feat.setFields(layer.dataProvider().fields())
                feat.setGeometry(geom)
                features.append(feat)

            default_suppress = (method == 'MST')
            suppressForm = QSettings().value(
                "/qgis/digitizing/disable_enter_attribute_values_dialog",
                type=bool,
                defaultValue=default_suppress)

            if suppressForm:
                # quite insert feature
                result = layer.addFeatures(features)
            else:
                # show dialog
                QgsApplication.restoreOverrideCursor()
                for feat in features:
                    attrDialog = QgsAttributeDialog(layer, feat, False)
                    attrDialog.setIsAddDialog(True)
                    result = attrDialog.exec_()

            # show message
            self.iface.messageBar().clearWidgets()
            if result:
                self.iface.messageBar().pushMessage(
                    self.tr("ReconstructLine"),
                    self.tr("%s line segment(s) was sucesfull added" %
                            (len(features))),
                    level=QgsMessageBar.INFO)
            else:
                self.iface.messageBar().pushMessage(
                    self.tr("ReconstructLine"),
                    self.tr("Line was not added"),
                    level=QgsMessageBar.CRITICAL)

            self.iface.mapCanvas().refresh()
        finally:
            QgsApplication.restoreOverrideCursor()
Example #12
0
    def insert_line(self):
        layer = self.iface.activeLayer()
        if not isinstance(layer, QgsVectorLayer) or layer.geometryType() != QGis.Line:
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                    self.tr("Line can\'t be inserted! Select lines layer for inserting new geom!"),
                                    level=QgsMessageBar.WARNING,
                                    duration=5)
            return

        if not layer.isEditable():
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                    self.tr("Line can\'t be inserted! Layer is not editable!"),
                                    level=QgsMessageBar.WARNING,
                                    duration=5)
            return

        if not self._geom_buffer:
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                        self.tr("Line can\'t be inserted! Copy points first!"),
                        level=QgsMessageBar.WARNING,
                        duration=5)
            return

        #show message
        self.iface.messageBar().clearWidgets()
        self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                            self.tr("Processing points. Please wait..."),
                                            level=QgsMessageBar.INFO
                                            )
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        QgsApplication.processEvents()
        QgsApplication.processEvents()
        QgsApplication.processEvents()

        try:
            # Create line

            # QGS geoms to np
            points = [(in_geom.x(), in_geom.y()) for in_geom in self._geom_buffer]
            data = np.array(points)

            # Make line
            som = SOM1d(data)
            result = som.connect()

            #np to QGS
            self._geom_buffer = [QgsPoint(out_geom[0], out_geom[1]) for out_geom in result]

            if layer.wkbType() == QGis.WKBMultiLineString:
                geom = QgsGeometry.fromMultiPolyline([self._geom_buffer])
            else:
                geom = QgsGeometry.fromPolyline(self._geom_buffer)

            # Check crs and reproject
            target_crs = layer.crs()
            if target_crs.srsid() != self._srid.srsid():
                transf = QgsCoordinateTransform(self._srid, target_crs)
                geom.transform(transf)

            # Insert feature
            feat = QgsFeature()
            feat.setFields(layer.dataProvider().fields())
            feat.setGeometry(geom)

            suppressForm = QSettings().value("/qgis/digitizing/disable_enter_attribute_values_dialog", type=bool, defaultValue=False)

            if suppressForm:
                # quite insert feature
                result = layer.addFeatures([feat])
            else:
                # show dialog
                QgsApplication.restoreOverrideCursor()
                attrDialog = QgsAttributeDialog(layer, feat, False)
                attrDialog.setIsAddDialog(True)
                result = attrDialog.exec_()

            # show message
            self.iface.messageBar().clearWidgets()
            if result:
                self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                                self.tr("One line was sucesfull added"),
                                                level=QgsMessageBar.INFO)
            else:
                self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                                self.tr("Line was not added"),
                                                level=QgsMessageBar.CRITICAL)

            self.iface.mapCanvas().refresh()
        finally:
            QgsApplication.restoreOverrideCursor()
    def do_aeag_menu(self,
                     fileName,
                     who,
                     menu=None,
                     visible=None,
                     expanded=None):
        self.canvas.freeze(True)
        self.canvas.setRenderFlag(False)
        group = None
        theLayer = None
        groupName = None
        QgsApplication.setOverrideCursor(Qt.WaitCursor)

        try:
            if (type(menu.parentWidget()) == QMenu or type(menu.parentWidget())
                    == QWidget) and self.optionCreateGroup:
                groupName = menu.title().replace("&", "")
                group = QgsProject.instance().layerTreeRoot().findGroup(
                    groupName)
                if group is None:
                    group = QgsProject.instance().layerTreeRoot().addGroup(
                        groupName)

            # load all layers
            if fileName is None and who is None and self.optionLoadAll:
                for action in menu.actions():
                    if ((action.text() != self.tr("&Load all"))
                            and (action.text() != "Load all")):
                        action.trigger()
            else:
                # read QGis project
                doc = QtXml.QDomDocument()
                xml = QFile(fileName)
                if xml.open(QIODevice.ReadOnly | QIODevice.Text):
                    doc.setContent(xml)

                # is project in relative path ?
                absolute = self.isAbsolute(doc)

                node = getFirstChildByTagNameValue(doc.documentElement(),
                                                   "maplayer", "id", who)
                if node:
                    idNode = node.namedItem("id")
                    layerType = node.toElement().attribute("type", "vector")
                    # give it a new id (for multiple import)
                    import re
                    newLayerId = "L%s" % re.sub("[{}-]", "",
                                                QUuid.createUuid().toString())
                    try:
                        idNode.firstChild().toText().setData(newLayerId)
                    except:
                        pass

                    # if relative path, adapt datasource
                    if not absolute:
                        try:
                            datasourceNode = node.namedItem("datasource")
                            ds = datasourceNode.firstChild().toText().data()
                            providerNode = node.namedItem("provider")
                            provider = providerNode.firstChild().toText().data(
                            )

                            if provider == "ogr" and (ds.find(".") == 0):
                                projectpath = QFileInfo(
                                    os.path.realpath(fileName)).path()
                                newlayerpath = projectpath + "/" + ds
                                datasourceNode.firstChild().toText().setData(
                                    newlayerpath)
                        except:
                            pass

                    # read modified layer node
                    if self.optionCreateGroup and group is not None:
                        """# sol 1 bug : layer incomplete
                        # because of API strange behaviour, we clone the layer... 
                        theLayer = QgsProject.instance().mapLayer(newLayerId)
                        cloneLayer = theLayer.clone()
                        # removing the first
                        QgsProject.instance().removeMapLayer(newLayerId)
                        # adding the clone...
                        treeNode = group.addLayer(cloneLayer)
                        treeNode.setExpanded(expanded)
                        treeNode.setItemVisibilityChecked(visible)"""

                        # solution 2, ok !
                        if layerType == "raster":
                            theLayer = QgsRasterLayer()
                        else:
                            theLayer = QgsVectorLayer()

                        theLayer.readLayerXml(node.toElement(),
                                              QgsReadWriteContext())
                        # needed
                        QgsProject.instance().addMapLayer(theLayer, False)
                        # add to group
                        treeNode = group.addLayer(theLayer)
                        treeNode.setExpanded(expanded)
                        treeNode.setItemVisibilityChecked(visible)
                    else:
                        # create layer
                        QgsProject.instance().readLayer(node)

        except Exception as e:
            QgsMessageLog.logMessage(
                'Menu from layer: Invalid ' +
                (fileName if fileName is not None else ""), 'Extensions')
            for m in e.args:
                QgsMessageLog.logMessage(m, 'Extensions')

        self.canvas.freeze(False)
        self.canvas.setRenderFlag(True)
        self.canvas.refresh()
        QgsApplication.restoreOverrideCursor()
    def loadLayer(self,
                  uri,
                  fileName,
                  layerId,
                  menu=None,
                  visible=None,
                  expanded=None):
        """Load the chosen layer(s)

        :param uri: The layer URI (file path or PG URI)
        :type uri: basestring

        :param layerId: The layer ID to look for in the project.
        :type layerId: basestring

        """
        self.canvas.freeze(True)
        self.canvas.setRenderFlag(False)
        group = None
        QgsApplication.setOverrideCursor(Qt.WaitCursor)

        try:
            if (isinstance(menu.parentWidget(), (QMenu, QWidget))
                    and self.optionCreateGroup):
                groupName = menu.title().replace("&", "")
                group = QgsProject.instance().layerTreeRoot().findGroup(
                    groupName)
                if group is None:
                    group = QgsProject.instance().layerTreeRoot().insertGroup(
                        0, groupName)

            # load all layers
            if fileName is None and layerId is None and self.optionLoadAll:
                for action in menu.actions():
                    if (action.text() != self.tr("Load all")
                            and action.text() != "Load all"):
                        action.trigger()
            else:
                layer = self.addLayer(uri, fileName, layerId, group, visible,
                                      expanded)

                # is joined layers exists ?
                if layer:
                    for j in layer.vectorJoins():
                        try:
                            joinLayer = self.addLayer(uri, fileName,
                                                      j.joinLayerId(), group)
                            if joinLayer:
                                j.setJoinLayerId(joinLayer.id())
                                j.setJoinLayer(joinLayer)
                                layer.addJoin(j)
                        except Exception as e:
                            self.log("Joined layer {} not added.".format(
                                j.joinLayerId()))
                            pass

        except Exception as e:
            # fixme fileName is not defined
            # self.log(
            #     'Menu from layer: Invalid ' + (fileName if fileName is not None else ""))
            for m in e.args:
                self.log(m)

        self.canvas.freeze(False)
        self.canvas.setRenderFlag(True)
        self.canvas.refresh()
        QgsApplication.restoreOverrideCursor()