Esempio n. 1
0
    def accept(self):
        qsettings = QgsSettings()
        for setting in list(self.items.keys()):
            if setting.group != menusSettingsGroup or self.saveMenus:
                if isinstance(setting.value, bool):
                    setting.setValue(
                        self.items[setting].checkState() == Qt.Checked)
                else:
                    try:
                        setting.setValue(str(self.items[setting].text()))
                    except ValueError as e:
                        QMessageBox.warning(
                            self, self.tr('Wrong value'),
                            self.tr('Wrong value for parameter "{0}":\n\n{1}').
                            format(setting.description, str(e)))
                        return
                setting.save(qsettings)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        for p in QgsApplication.processingRegistry().providers():
            p.refreshAlgorithms()
        QApplication.restoreOverrideCursor()

        settingsWatcher.settingsChanged.emit()
Esempio n. 2
0
    def __init__(self, canvas, layerfrom, layerto, mapping, validation_method):
        """
            mapping - A dict of field - field mapping with values to
                            copy to the new layer
        """
        QgsMapTool.__init__(self, canvas)
        self.layerfrom = layerfrom
        self.layerto = layerto
        self.fields = mapping
        self.validation_method = validation_method
        self.band = QgsRubberBand(canvas, QgsWkbTypes.PolygonGeometry)
        self.band.setColor(QColor.fromRgb(255, 0, 0, 65))
        self.band.setWidth(5)

        self.cursor = QCursor(
            QPixmap([
                "16 16 3 1", "      c None", ".     c #FF0000",
                "+     c #FFFFFF", "                ", "       +.+      ",
                "      ++.++     ", "     +.....+    ", "    +.     .+   ",
                "   +.   .   .+  ", "  +.    .    .+ ", " ++.    .    .++",
                " ... ...+... ...", " ++.    .    .++", "  +.    .    .+ ",
                "   +.   .   .+  ", "   ++.     .+   ", "    ++.....+    ",
                "      ++.++     ", "       +.+      "
            ]))
Esempio n. 3
0
    def runAlgorithm(algOrName, onFinish, *args, **kwargs):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = QgsApplication.processingRegistry().algorithmById(algOrName)
        if alg is None:
            # fix_print_with_import
            print('Error: Algorithm not found\n')
            QgsMessageLog.logMessage(Processing.tr('Error: Algorithm {0} not found\n').format(algOrName),
                                     Processing.tr("Processing"))
            return
        # hack - remove when getCopy is removed
        provider = alg.provider()
        alg = alg.getCopy()
        #hack pt2
        alg.setProvider(provider)

        if len(args) == 1 and isinstance(args[0], dict):
            # Set params by name and try to run the alg even if not all parameter values are provided,
            # by using the default values instead.
            setParams = []
            for (name, value) in list(args[0].items()):
                param = alg.getParameterFromName(name)
                if param and param.setValue(value):
                    setParams.append(name)
                    continue
                output = alg.getOutputFromName(name)
                if output and output.setValue(value):
                    continue
                # fix_print_with_import
                print('Error: Wrong parameter value %s for parameter %s.' % (value, name))
                QgsMessageLog.logMessage(
                    Processing.tr('Error: Wrong parameter value {0} for parameter {1}.').format(value, name),
                    Processing.tr("Processing"))
                QgsMessageLog.logMessage(Processing.tr('Error in {0}. Wrong parameter value {1} for parameter {2}.').format(
                    alg.name(), value, name
                ), Processing.tr("Processing"),
                    QgsMessageLog.CRITICAL
                )
                return
            # fill any missing parameters with default values if allowed
            for param in alg.parameters:
                if param.name not in setParams:
                    if not param.setDefaultValue():
                        # fix_print_with_import
                        print('Error: Missing parameter value for parameter %s.' % param.name)
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Missing parameter value for parameter {0}.').format(param.name),
                            Processing.tr("Processing"))
                        return
        else:
            if len(args) != alg.getVisibleParametersCount() + alg.getVisibleOutputsCount():
                # fix_print_with_import
                print('Error: Wrong number of parameters')
                QgsMessageLog.logMessage(Processing.tr('Error: Wrong number of parameters'),
                                         Processing.tr("Processing"))
                processing.algorithmHelp(algOrName)
                return
            i = 0
            for param in alg.parameters:
                if not param.hidden:
                    if not param.setValue(args[i]):
                        # fix_print_with_import
                        print('Error: Wrong parameter value: ' + str(args[i]))
                        QgsMessageLog.logMessage(Processing.tr('Error: Wrong parameter value: ') + str(args[i]),
                                                 Processing.tr("Processing"))
                        return
                    i = i + 1

            for output in alg.outputs:
                if not output.hidden:
                    if not output.setValue(args[i]):
                        # fix_print_with_import
                        print('Error: Wrong output value: ' + str(args[i]))
                        QgsMessageLog.logMessage(Processing.tr('Error: Wrong output value: ') + str(args[i]),
                                                 Processing.tr("Processing"))
                        return
                    i = i + 1

        context = None
        if kwargs is not None and 'context' in list(kwargs.keys()):
            context = kwargs["context"]
        else:
            context = dataobjects.createContext()

        msg = alg._checkParameterValuesBeforeExecuting(context)
        if msg:
            # fix_print_with_import
            print('Unable to execute algorithm\n' + str(msg))
            QgsMessageLog.logMessage(Processing.tr('Unable to execute algorithm\n{0}').format(msg),
                                     Processing.tr("Processing"))
            return

        if not alg.checkInputCRS(context):
            print('Warning: Not all input layers use the same CRS.\n' +
                  'This can cause unexpected results.')
            QgsMessageLog.logMessage(
                Processing.tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'),
                Processing.tr("Processing"))

        # Don't set the wait cursor twice, because then when you
        # restore it, it will still be a wait cursor.
        overrideCursor = False
        if iface is not None:
            cursor = QApplication.overrideCursor()
            if cursor is None or cursor == 0:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True
            elif cursor.shape() != Qt.WaitCursor:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True

        feedback = None
        if kwargs is not None and "feedback" in list(kwargs.keys()):
            feedback = kwargs["feedback"]
        elif iface is not None:
            feedback = MessageBarProgress(alg.displayName())

        ret = execute(alg, context, feedback)
        if ret:
            if onFinish is not None:
                onFinish(alg, context, feedback)
        else:
            QgsMessageLog.logMessage(Processing.tr("There were errors executing the algorithm."),
                                     Processing.tr("Processing"))

        if overrideCursor:
            QApplication.restoreOverrideCursor()
        if isinstance(feedback, MessageBarProgress):
            feedback.close()
        return alg
Esempio n. 4
0
    def accept(self):
        alg_parameters = []
        load = []

        feedback = self.createFeedback()
        context = dataobjects.createContext(feedback)

        for row in range(self.mainWidget.tblParameters.rowCount()):
            col = 0
            parameters = {}
            for param in self.alg.parameterDefinitions():
                if param.flags() & QgsProcessingParameterDefinition.FlagHidden or param.isDestination():
                    continue
                wrapper = self.mainWidget.wrappers[row][col]
                parameters[param.name()] = wrapper.value()
                if not param.checkValueIsAcceptable(wrapper.value(), context):
                    self.bar.pushMessage("", self.tr('Wrong or missing parameter value: {0} (row {1})').format(
                                         param.description(), row + 1),
                                         level=QgsMessageBar.WARNING, duration=5)
                    return
                col += 1
            count_visible_outputs = 0
            for out in self.alg.destinationParameterDefinitions():
                if out.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    continue

                count_visible_outputs += 1
                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                text = widget.getValue()
                if param.checkValueIsAcceptable(text, context):
                    if isinstance(out, (QgsProcessingParameterRasterDestination,
                                        QgsProcessingParameterFeatureSink)):
                        # load rasters and sinks on completion
                        parameters[out.name()] = QgsProcessingOutputLayerDefinition(text, context.project())
                    else:
                        parameters[out.name()] = text
                    col += 1
                else:
                    self.bar.pushMessage("", self.tr('Wrong or missing output value: {0} (row {1})').format(
                                         out.description(), row + 1),
                                         level=QgsMessageBar.WARNING, duration=5)
                    return

            alg_parameters.append(parameters)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.mainWidget.setEnabled(False)
        self.buttonCancel.setEnabled(True)

        # Make sure the Log tab is visible before executing the algorithm
        try:
            self.tabWidget.setCurrentIndex(1)
            self.repaint()
        except:
            pass

        start_time = time.time()

        algorithm_results = []
        for count, parameters in enumerate(alg_parameters):
            if feedback.isCanceled():
                break
            self.setText(self.tr('\nProcessing algorithm {0}/{1}...').format(count + 1, len(alg_parameters)))
            self.setInfo(self.tr('<b>Algorithm {0} starting...</b>').format(self.alg.displayName()), escape_html=False)

            feedback.pushInfo(self.tr('Input parameters:'))
            feedback.pushCommandInfo(pformat(parameters))
            feedback.pushInfo('')

            alg_start_time = time.time()
            ret, results = execute(self.alg, parameters, context, feedback)
            if ret:
                self.setInfo(self.tr('Algorithm {0} correctly executed...').format(self.alg.displayName()), escape_html=False)
                feedback.setProgress(100)
                feedback.pushInfo(
                    self.tr('Execution completed in {0:0.2f} seconds'.format(time.time() - alg_start_time)))
                feedback.pushInfo(self.tr('Results:'))
                feedback.pushCommandInfo(pformat(results))
                feedback.pushInfo('')
                algorithm_results.append(results)
            else:
                break

        feedback.pushInfo(self.tr('Batch execution completed in {0:0.2f} seconds'.format(time.time() - start_time)))

        handleAlgorithmResults(self.alg, context, feedback, False)

        self.finish(algorithm_results)
        self.buttonCancel.setEnabled(False)
Esempio n. 5
0
 def setCursor(self,cursor):
         self.cursor = QCursor(cursor)
Esempio n. 6
0
    def accept(self):
        self.algs = []
        self.load = []
        self.canceled = False

        for row in range(self.mainWidget.tblParameters.rowCount()):
            alg = self.alg.getCopy()
            # hack - remove when getCopy is removed
            alg.setProvider(self.alg.provider())
            col = 0
            for param in alg.parameters:
                if param.hidden:
                    continue
                wrapper = self.mainWidget.wrappers[row][col]
                if not self.mainWidget.setParamValue(param, wrapper, alg):
                    self.bar.pushMessage(
                        "",
                        self.tr(
                            'Wrong or missing parameter value: {0} (row {1})').
                        format(param.description, row + 1),
                        level=QgsMessageBar.WARNING,
                        duration=5)
                    self.algs = None
                    return
                col += 1
            for out in alg.outputs:
                if out.hidden:
                    continue

                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                text = widget.getValue()
                if text.strip() != '':
                    out.value = text
                    col += 1
                else:
                    self.bar.pushMessage(
                        "",
                        self.tr('Wrong or missing output value: {0} (row {1})'
                                ).format(out.description, row + 1),
                        level=QgsMessageBar.WARNING,
                        duration=5)
                    self.algs = None
                    return

            self.algs.append(alg)
            if self.alg.getVisibleOutputsCount():
                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                self.load.append(widget.currentIndex() == 0)
            else:
                self.load.append(False)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.mainWidget.setEnabled(False)

        self.progressBar.setMaximum(len(self.algs))
        # Make sure the Log tab is visible before executing the algorithm
        try:
            self.tabWidget.setCurrentIndex(1)
            self.repaint()
        except:
            pass

        context = dataobjects.createContext()

        for count, alg in enumerate(self.algs):
            self.setText(
                self.tr('\nProcessing algorithm {0}/{1}...').format(
                    count + 1, len(self.algs)))
            self.setInfo(
                self.tr('<b>Algorithm {0} starting...</b>').format(
                    alg.displayName()))
            if execute(alg, context, self.feedback) and not self.canceled:
                if self.load[count]:
                    handleAlgorithmResults(alg, context, self.feedback, False)
                self.setInfo(
                    self.tr('Algorithm {0} correctly executed...').format(
                        alg.displayName()))
            else:
                QApplication.restoreOverrideCursor()
                return

        self.finish()
Esempio n. 7
0
    def writeOL(cls, iface, feedback, layers, groups, popup, visible,
                interactive, json, clustered, getFeatureInfo, settings,
                folder):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        mapSettings = iface.mapCanvas().mapSettings()
        controlCount = 0
        stamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S_%f")
        folder = os.path.join(folder, 'qgis2web_' + stamp)
        restrictToExtent = settings["Scale/Zoom"]["Restrict to extent"]
        matchCRS = settings["Appearance"]["Match project CRS"]
        precision = settings["Data export"]["Precision"]
        optimize = settings["Data export"]["Minify GeoJSON files"]
        extent = settings["Scale/Zoom"]["Extent"]
        mapbounds = bounds(iface, extent == "Canvas extent", layers, matchCRS)
        fullextent = bounds(iface, False, layers, matchCRS)
        geolocateUser = settings["Appearance"]["Geolocate user"]
        maxZoom = int(settings["Scale/Zoom"]["Max zoom level"])
        minZoom = int(settings["Scale/Zoom"]["Min zoom level"])
        popupsOnHover = settings["Appearance"]["Show popups on hover"]
        highlightFeatures = settings["Appearance"]["Highlight on hover"]
        geocode = settings["Appearance"]["Add address search"]
        measureTool = settings["Appearance"]["Measure tool"]
        addLayersList = settings["Appearance"]["Add layers list"]
        htmlTemplate = settings["Appearance"]["Template"]
        layerSearch = settings["Appearance"]["Layer search"]
        searchLayer = settings["Appearance"]["Search layer"]
        widgetAccent = settings["Appearance"]["Widget Icon"]
        widgetBackground = settings["Appearance"]["Widget Background"]

        writeFiles(folder, restrictToExtent, feedback)
        exportLayers(iface, layers, folder, precision, optimize, popup, json,
                     restrictToExtent, extent, feedback, matchCRS)
        mapUnitsLayers = exportStyles(layers, folder, clustered, feedback)
        mapUnitLayers = getMapUnitLayers(mapUnitsLayers)
        osmb = writeLayersAndGroups(layers, groups, visible, interactive,
                                    folder, popup, settings, json, matchCRS,
                                    clustered, getFeatureInfo, iface,
                                    restrictToExtent, extent, mapbounds,
                                    mapSettings.destinationCrs().authid())
        (jsAddress, cssAddress,
         controlCount) = writeHTMLstart(settings, controlCount, osmb, feedback)
        (geojsonVars, wfsVars,
         styleVars) = writeScriptIncludes(layers, json, matchCRS)
        popupLayers = "popupLayers = [%s];" % ",".join(
            ['1' for field in popup])
        project = QgsProject.instance()
        controls = getControls(project, measureTool, geolocateUser)
        layersList = getLayersList(addLayersList)
        pageTitle = project.title()
        backgroundColor = getBackground(mapSettings, widgetAccent,
                                        widgetBackground)
        (geolocateCode, controlCount) = geolocateStyle(geolocateUser,
                                                       controlCount)
        backgroundColor += geolocateCode
        mapextent = "extent: %s," % mapbounds if restrictToExtent else ""
        onHover = str(popupsOnHover).lower()
        highlight = str(highlightFeatures).lower()
        highlightFill = mapSettings.selectionColor().name()
        (proj, proj4, view) = getCRSView(mapextent, fullextent, maxZoom,
                                         minZoom, matchCRS, mapSettings)
        (measureControl, measuring, measure, measureUnit, measureStyle,
         controlCount) = getMeasure(measureTool, controlCount)
        geolocateHead = geolocationHead(geolocateUser)
        geolocate = geolocation(geolocateUser)
        geocodingLinks = geocodeLinks(geocode)
        geocodingJS = geocodeJS(geocode)
        geocodingScript = geocodeScript(geocode)
        m2px = getM2px(mapUnitsLayers)
        (extracss, controlCount) = getCSS(geocode, geolocateUser, layerSearch,
                                          controlCount)
        (jsAddress, cssAddress, layerSearch,
         controlCount) = writeLayerSearch(cssAddress, jsAddress, controlCount,
                                          layerSearch, searchLayer, feedback)
        ol3layerswitcher = getLayerSwitcher()
        ol3popup = getPopup()
        ol3qgis2webjs = getJS(osmb)
        ol3layers = getLayers()
        mapSize = iface.mapCanvas().size()
        exp_js = getExpJS()
        grid = getGrid(project)
        values = {
            "@PAGETITLE@": pageTitle,
            "@CSSADDRESS@": cssAddress,
            "@EXTRACSS@": extracss,
            "@JSADDRESS@": jsAddress,
            "@MAP_WIDTH@": str(mapSize.width()) + "px",
            "@MAP_HEIGHT@": str(mapSize.height()) + "px",
            "@OL3_STYLEVARS@": styleVars,
            "@OL3_BACKGROUNDCOLOR@": backgroundColor,
            "@OL3_POPUP@": ol3popup,
            "@OL3_GEOJSONVARS@": geojsonVars,
            "@OL3_WFSVARS@": wfsVars,
            "@OL3_PROJ4@": proj4,
            "@OL3_PROJDEF@": proj,
            "@OL3_GEOCODINGLINKS@": geocodingLinks,
            "@OL3_GEOCODINGJS@": geocodingJS,
            "@QGIS2WEBJS@": ol3qgis2webjs,
            "@OL3_LAYERSWITCHER@": ol3layerswitcher,
            "@OL3_LAYERS@": ol3layers,
            "@OL3_MEASURESTYLE@": measureStyle,
            "@EXP_JS@": exp_js,
            "@LEAFLET_ADDRESSCSS@": "",
            "@LEAFLET_MEASURECSS@": "",
            "@LEAFLET_EXTRAJS@": "",
            "@LEAFLET_ADDRESSJS@": "",
            "@LEAFLET_MEASUREJS@": "",
            "@LEAFLET_CRSJS@": "",
            "@LEAFLET_LAYERSEARCHCSS@": "",
            "@LEAFLET_LAYERSEARCHJS@": "",
            "@LEAFLET_CLUSTERCSS@": "",
            "@LEAFLET_CLUSTERJS@": ""
        }
        with open(os.path.join(folder, "index.html"), "w") as f:
            htmlTemplate = htmlTemplate
            if htmlTemplate == "":
                htmlTemplate = "full-screen"
            templateOutput = replaceInTemplate(htmlTemplate + ".html", values)
            templateOutput = re.sub(r'\n[\s_]+\n', '\n', templateOutput)
            f.write(templateOutput)
        values = {
            "@GEOLOCATEHEAD@": geolocateHead,
            "@BOUNDS@": mapbounds,
            "@CONTROLS@": ",".join(controls),
            "@LAYERSLIST@": layersList,
            "@POPUPLAYERS@": popupLayers,
            "@VIEW@": view,
            "@LAYERSEARCH@": layerSearch,
            "@ONHOVER@": onHover,
            "@DOHIGHLIGHT@": highlight,
            "@HIGHLIGHTFILL@": highlightFill,
            "@GEOLOCATE@": geolocate,
            "@GEOCODINGSCRIPT@": geocodingScript,
            "@MEASURECONTROL@": measureControl,
            "@MEASURING@": measuring,
            "@MEASURE@": measure,
            "@MEASUREUNIT@": measureUnit,
            "@GRID@": grid,
            "@M2PX@": m2px,
            "@MAPUNITLAYERS@": mapUnitLayers
        }
        with open(os.path.join(folder, "resources", "qgis2web.js"), "w") as f:
            out = replaceInScript("qgis2web.js", values)
            f.write(out)
        QApplication.restoreOverrideCursor()
        return os.path.join(folder, "index.html")
Esempio n. 8
0
    def accept(self):
        # sanity checks
        if self.editOutputFile.text() == "":
            QMessageBox.information(self, self.tr("Export to file"),
                                    self.tr("Output file name is required"))
            return

        if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
            try:
                sourceSrid = int(self.editSourceSrid.text())
            except ValueError:
                QMessageBox.information(
                    self, self.tr("Export to file"),
                    self.tr("Invalid source srid: must be an integer"))
                return

        if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
            try:
                targetSrid = int(self.editTargetSrid.text())
            except ValueError:
                QMessageBox.information(
                    self, self.tr("Export to file"),
                    self.tr("Invalid target srid: must be an integer"))
                return

        # override cursor
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        # store current input layer crs, so I can restore it later
        prevInCrs = self.inLayer.crs()
        try:
            uri = self.editOutputFile.text()
            providerName = "ogr"

            options = {}

            # set the OGR driver will be used
            driverName = self.cboFileFormat.itemData(
                self.cboFileFormat.currentIndex())
            options['driverName'] = driverName

            # set the output file encoding
            if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked():
                enc = self.cboEncoding.currentText()
                options['fileEncoding'] = enc

            if self.chkDropTable.isChecked():
                options['overwrite'] = True

            outCrs = None
            if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(
            ):
                targetSrid = int(self.editTargetSrid.text())
                outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid)

            # update input layer crs
            if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(
            ):
                sourceSrid = int(self.editSourceSrid.text())
                inCrs = qgis.core.QgsCoordinateReferenceSystem(sourceSrid)
                self.inLayer.setCrs(inCrs)

            # do the export!
            ret, errMsg = qgis.core.QgsVectorLayerImport.importLayer(
                self.inLayer, uri, providerName, outCrs, False, False, options)
        except Exception as e:
            ret = -1
            errMsg = unicode(e)

        finally:
            # restore input layer crs and encoding
            self.inLayer.setCrs(prevInCrs)
            # restore cursor
            QApplication.restoreOverrideCursor()

        if ret != 0:
            QMessageBox.warning(self, self.tr("Export to file"),
                                self.tr("Error %d\n%s") % (ret, errMsg))
            return

        # create spatial index
        # if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked():
        #       self.db.connector.createSpatialIndex( (schema, table), geom )

        QMessageBox.information(self, self.tr("Export to file"),
                                self.tr("Export finished."))
        return QDialog.accept(self)
Esempio n. 9
0
    def writeLeaflet(cls, iface, feedback, folder, layer_list, visible,
                     interactive, cluster, json, getFeatureInfo, params,
                     popup):
        outputProjectFileName = folder
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        legends = {}
        mapUnitLayers = []
        canvas = iface.mapCanvas()
        project = QgsProject.instance()
        mapSettings = canvas.mapSettings()
        title = project.title()
        pluginDir = os.path.dirname(os.path.realpath(__file__))
        stamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S_%f")
        outputProjectFileName = os.path.join(outputProjectFileName,
                                             'qgis2web_' + stamp)
        outputIndex = os.path.join(outputProjectFileName, 'index.html')

        minify = params["Data export"]["Minify GeoJSON files"]
        precision = params["Data export"]["Precision"]
        extent = params["Scale/Zoom"]["Extent"]
        minZoom = params["Scale/Zoom"]["Min zoom level"]
        maxZoom = params["Scale/Zoom"]["Max zoom level"]
        restrictToExtent = params["Scale/Zoom"]["Restrict to extent"]
        matchCRS = params["Appearance"]["Match project CRS"]
        addressSearch = params["Appearance"]["Add address search"]
        locate = params["Appearance"]["Geolocate user"]
        measure = params["Appearance"]["Measure tool"]
        highlight = params["Appearance"]["Highlight on hover"]
        layerSearch = params["Appearance"]["Layer search"]
        popupsOnHover = params["Appearance"]["Show popups on hover"]
        template = params["Appearance"]["Template"]
        widgetAccent = params["Appearance"]["Widget Icon"]
        widgetBackground = params["Appearance"]["Widget Background"]

        usedFields = [ALL_ATTRIBUTES] * len(popup)

        QgsApplication.initQgis()

        dataStore, cssStore = writeFoldersAndFiles(pluginDir, feedback,
                                                   outputProjectFileName,
                                                   cluster, measure, matchCRS,
                                                   layerSearch, canvas,
                                                   addressSearch, locate)
        writeCSS(cssStore,
                 mapSettings.backgroundColor().name(), feedback, widgetAccent,
                 widgetBackground)

        wfsLayers = ""
        labelCode = ""
        vtLabels = {}
        vtStyles = {}
        useMultiStyle = False
        useHeat = False
        useVT = False
        useShapes = False
        useOSMB = False
        useWMS = False
        useWMTS = False
        useRaster = False
        scaleDependentLayers = ""
        labelVisibility = ""
        new_src = ""
        jsons = ""
        crs = QgsCoordinateReferenceSystem.EpsgCrsId
        exp_crs = QgsCoordinateReferenceSystem(4326, crs)
        lyrCount = 0
        for layer, jsonEncode, eachPopup, clst in zip(layer_list, json, popup,
                                                      cluster):
            rawLayerName = layer.name()
            safeLayerName = safeName(rawLayerName) + "_" + str(lyrCount)
            vts = layer.customProperty("VectorTilesReader/vector_tile_url")
            if layer.providerType() != 'WFS' or jsonEncode is True:
                if layer.type() == QgsMapLayer.VectorLayer and vts is None:
                    feedback.showFeedback('Exporting %s to JSON...' %
                                          layer.name())
                    exportVector(layer, safeLayerName, dataStore,
                                 restrictToExtent, iface, extent, precision,
                                 exp_crs, minify)
                    jsons += jsonScript(safeLayerName)
                    scaleDependentLabels = \
                        scaleDependentLabelScript(layer, safeLayerName)
                    labelVisibility += scaleDependentLabels
                    feedback.completeStep()

                elif layer.type() == QgsMapLayer.RasterLayer:
                    if layer.dataProvider().name() != "wms":
                        layersFolder = os.path.join(outputProjectFileName,
                                                    "data")
                        exportRaster(layer, lyrCount, layersFolder, feedback,
                                     iface, matchCRS)
            if layer.hasScaleBasedVisibility():
                scaleDependentLayers += scaleDependentLayerScript(
                    layer, safeLayerName, clst)
            lyrCount += 1
        if scaleDependentLayers != "":
            scaleDependentLayers = scaleDependentScript(scaleDependentLayers)

        crsSrc = mapSettings.destinationCrs()
        crsAuthId = crsSrc.authid()
        crsProj4 = crsSrc.toProj4()
        middle = """
        """
        if highlight or popupsOnHover:
            selectionColor = mapSettings.selectionColor().name()
            middle += highlightScript(highlight, popupsOnHover, selectionColor)
        if extent == "Canvas extent":
            pt0 = canvas.extent()
            crsDest = QgsCoordinateReferenceSystem(4326)
            try:
                xform = QgsCoordinateTransform(crsSrc, crsDest,
                                               QgsProject.instance())
            except Exception:
                xform = QgsCoordinateTransform(crsSrc, crsDest)
            pt1 = xform.transformBoundingBox(pt0)
            bounds = '[[' + str(pt1.yMinimum()) + ','
            bounds += str(pt1.xMinimum()) + '],['
            bounds += str(pt1.yMaximum()) + ','
            bounds += str(pt1.xMaximum()) + ']]'
            if matchCRS and crsAuthId != 'EPSG:4326':
                middle += crsScript(crsAuthId, crsProj4)
        else:
            bounds = 0
            if matchCRS and crsAuthId != 'EPSG:4326':
                middle += crsScript(crsAuthId, crsProj4)
        middle += mapScript(extent, matchCRS, crsAuthId, measure, maxZoom,
                            minZoom, bounds, locate)
        middle += featureGroupsScript()
        extentCode = extentScript(extent, restrictToExtent)
        new_src += middle
        new_src += extentCode

        for count, layer in enumerate(layer_list):
            rawLayerName = layer.name()
            safeLayerName = safeName(rawLayerName) + "_" + str(count)
            if (layer.type() == QgsMapLayer.VectorLayer
                    and layer.wkbType() != QgsWkbTypes.NoGeometry):
                (new_src, legends, wfsLayers, labelCode, vtLabels, vtStyles,
                 useMapUnits, useMultiStyle, useHeat, useVT,
                 useShapes, useOSMB) = writeVectorLayer(
                     layer, safeLayerName, usedFields[count], highlight,
                     popupsOnHover, popup[count], outputProjectFileName,
                     wfsLayers, cluster[count], visible[count],
                     interactive[count], json[count], legends, new_src, canvas,
                     count, restrictToExtent, extent, feedback, labelCode,
                     vtLabels, vtStyles, useMultiStyle, useHeat, useVT,
                     useShapes, useOSMB)
                if useMapUnits:
                    mapUnitLayers.append(safeLayerName)
            elif layer.type() == QgsMapLayer.RasterLayer:
                if layer.dataProvider().name() == "wms":
                    feedback.showFeedback('Writing %s as WMS layer...' %
                                          layer.name())
                    new_obj, useWMS, useWMTS = wmsScript(
                        layer, safeLayerName, useWMS, useWMTS,
                        getFeatureInfo[count])
                    feedback.completeStep()
                else:
                    useRaster = True
                    feedback.showFeedback('Writing %s as raster layer...' %
                                          layer.name())
                    new_obj = rasterScript(layer, safeLayerName)
                    feedback.completeStep()
                if visible[count]:
                    new_obj += """
        map.addLayer(layer_""" + safeLayerName + """);"""
                new_src += new_obj
        the_src = new_src
        new_src = jsons + """
        <script>"""
        if len(mapUnitLayers) > 0:
            new_src += """
        var m2px = 1;
        function newM2px() {
            var centerLatLng = map.getCenter();
            var pointC = map.latLngToContainerPoint(centerLatLng);
            var pointX = [pointC.x + 100, pointC.y];

            var latLngC = map.containerPointToLatLng(pointC);
            var latLngX = map.containerPointToLatLng(pointX);

            var distanceX = latLngC.distanceTo(latLngX)/100;

            reciprocal = 1 / distanceX;
            m2px = reciprocal;
        }
        function geoStyle(m) {
            return Math.ceil(m * m2px);
        }"""
        new_src += getVTStyles(vtStyles)
        new_src += getVTLabels(vtLabels)
        new_src += the_src + scaleDependentLayers
        if title != "":
            titleStart = titleSubScript(title)
            new_src += titleStart
        if addressSearch:
            address_text = addressSearchScript()
            new_src += address_text

        if (params["Appearance"]["Add layers list"]
                and params["Appearance"]["Add layers list"] != ""
                and params["Appearance"]["Add layers list"] != "None"):
            new_src += addLayersList(
                [], matchCRS, layer_list, cluster, legends,
                params["Appearance"]["Add layers list"] == "Expanded")
        if project.readBoolEntry("ScaleBar", "/Enabled", False)[0]:
            # placement = project.readNumEntry("ScaleBar", "/Placement", 0)[0]
            # placement = PLACEMENT[placement]
            # end = scaleBar(placement)
            end = scaleBar()
        else:
            end = ''
        layerType = "layer"
        try:
            if cluster[count]:
                layerType = "cluster"
        except Exception:
            pass
        searchLayer = "%s_%s" % (layerType,
                                 params["Appearance"]["Search layer"])
        labelList = []
        for count, layer in enumerate(layer_list):
            vts = layer.customProperty("VectorTilesReader/vector_tile_url")
            safeLayerName = safeName(layer.name()) + "_" + str(count)
            if (layer.type() == QgsMapLayer.VectorLayer and vts is None):
                labelling = layer.labeling()
                if labelling is not None:
                    palyr = labelling.settings()
                    if palyr.fieldName and palyr.fieldName != "":
                        labelList.append("layer_%s" % safeLayerName)
        labelsList = ",".join(labelList)
        end += endHTMLscript(wfsLayers, layerSearch, labelCode,
                             labelVisibility, searchLayer, useHeat, useRaster,
                             labelsList, mapUnitLayers)
        new_src += end
        try:
            writeHTMLstart(outputIndex, title, cluster, addressSearch, measure,
                           matchCRS, layerSearch, canvas, locate, new_src,
                           template, feedback, useMultiStyle, useHeat,
                           useShapes, useOSMB, useWMS, useWMTS, useVT)
        except Exception:
            QgsMessageLog.logMessage(traceback.format_exc(),
                                     "qgis2web",
                                     level=Qgis.Critical)
        finally:
            QApplication.restoreOverrideCursor()
        return outputIndex
Esempio n. 10
0
    def accept(self):
        self.alg_parameters = []
        self.load = []
        self.canceled = False

        context = dataobjects.createContext()

        for row in range(self.mainWidget.tblParameters.rowCount()):
            col = 0
            parameters = {}
            for param in self.alg.parameterDefinitions():
                if param.flags(
                ) & QgsProcessingParameterDefinition.FlagHidden or param.isDestination(
                ):
                    continue
                wrapper = self.mainWidget.wrappers[row][col]
                parameters[param.name()] = wrapper.value()
                if not param.checkValueIsAcceptable(wrapper.value(), context):
                    self.bar.pushMessage(
                        "",
                        self.tr(
                            'Wrong or missing parameter value: {0} (row {1})').
                        format(param.description(), row + 1),
                        level=QgsMessageBar.WARNING,
                        duration=5)
                    self.algs = None
                    return
                col += 1
            for out in alg.destinationParameterDefinitions():
                if out.flags() & QgsProcessingParameterDefinition.FlagHidden:
                    continue

                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                text = widget.getValue()
                if text.strip() != '':
                    out.value = text
                    col += 1
                else:
                    self.bar.pushMessage(
                        "",
                        self.tr('Wrong or missing output value: {0} (row {1})'
                                ).format(out.description(), row + 1),
                        level=QgsMessageBar.WARNING,
                        duration=5)
                    self.algs = None
                    return

            self.alg_parameters.append(parameters)
            if self.alg.countVisibleOutputs():
                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                self.load.append(widget.currentIndex() == 0)
            else:
                self.load.append(False)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.mainWidget.setEnabled(False)

        self.progressBar.setMaximum(len(self.algs))
        # Make sure the Log tab is visible before executing the algorithm
        try:
            self.tabWidget.setCurrentIndex(1)
            self.repaint()
        except:
            pass

        for count, parameters in enumerate(self.alg_parameters):
            self.setText(
                self.tr('\nProcessing algorithm {0}/{1}...').format(
                    count + 1, len(self.alg_parameters)))
            self.setInfo(
                self.tr('<b>Algorithm {0} starting...</b>').format(
                    self.alg.displayName()))
            ret, results = execute(self.alg, parameters, context,
                                   self.feedback)
            if ret and not self.canceled:
                if self.load[count]:
                    handleAlgorithmResults(self.alg, context, self.feedback,
                                           False)
                self.setInfo(
                    self.tr('Algorithm {0} correctly executed...').format(
                        self.alg.displayName()))
            else:
                QApplication.restoreOverrideCursor()
                return

        self.finish()
Esempio n. 11
0
    def mouseMoveEvent(self, event):
        """
        @type event: QMouseEvent
        @param event:
        @return:
        """
        # Magnifier mouseMoveEvent
        # Magnifier can move on black screen for show image borders
        if self._interaction.magnifier:
            if event.buttons():
                self.dragPos = event.pos()
                self.UpdateSurface()

        # check if the point  is on picture (not in black borders)
        if(not vut.IsPointOnScreen(event.x(), event.y(), self.surface)):
            self.setCursor(QCursor(Qt.ArrowCursor))
            self.Cursor_Canvas_RubberBand.reset(QgsWkbTypes.PointGeometry)
            return

        # Prevent draw on video if not started or finished
        if self.parent.player.position() == 0:
            return

        # Mouser cursor drawing
        if self._interaction.pointDrawer or self._interaction.polygonDrawer or self._interaction.lineDrawer or self._interaction.measureDistance or self._interaction.measureArea or self._interaction.censure or self._interaction.objectTracking:
            self.setCursor(QCursor(Qt.CrossCursor))

        # Cursor Coordinates
        if self.gt is not None:

            Longitude, Latitude, Altitude = vut.GetPointCommonCoords(
                event, self.surface)

            tr = QgsCoordinateTransform( QgsCoordinateReferenceSystem( 'EPSG:4326' ), iface.mapCanvas().mapSettings().destinationCrs(), QgsProject.instance().transformContext() )
            mapPt = tr.transform( QgsPointXY(Longitude, Latitude) )
            
            vertices = self.Cursor_Canvas_RubberBand.numberOfVertices()
            if vertices > 0:
                self.Cursor_Canvas_RubberBand.removePoint(0, True, 0)
                self.Cursor_Canvas_RubberBand.movePoint( mapPt, 0)
            else:
                self.Cursor_Canvas_RubberBand.addPoint( mapPt )

            if self._MGRS:
                try:
                    mgrsCoords = mgrs.toMgrs(Latitude, Longitude)
                except Exception:
                    mgrsCoords = ""

                txt = "<span style='font-size:9pt; font-weight:normal;'>" + \
                    ("%s" % mgrsCoords) + "</span>"

            else:

                txt = "<span style='font-size:10pt; font-weight:bold;'>Lon : </span>"
                txt += "<span style='font-size:9pt; font-weight:normal;'>" + \
                    ("%.3f" % Longitude) + "</span>"
                txt += "<span style='font-size:10pt; font-weight:bold;'> Lat : </span>"
                txt += "<span style='font-size:9pt; font-weight:normal;'>" + \
                    ("%.3f" % Latitude) + "</span>"

                if hasElevationModel():
                    txt += "<span style='font-size:10pt; font-weight:bold;'> Alt : </span>"
                    txt += "<span style='font-size:9pt; font-weight:normal;'>" + \
                        ("%.0f" % Altitude) + "</span>"
                else:
                    txt += "<span style='font-size:10pt; font-weight:bold;'> Alt : </span>"
                    txt += "<span style='font-size:9pt; font-weight:normal;'>-</span>"

            self.parent.lb_cursor_coord.setText(txt)

            # Polygon drawer mouseMoveEvent
            if self._interaction.polygonDrawer:
                self.AddMoveEventValue(self.drawPolygon, Longitude, Latitude, Altitude)

            # Line drawer mouseMoveEvent
            if self._interaction.lineDrawer:
                self.AddMoveEventValue(self.drawLines, Longitude, Latitude, Altitude)

            # Measure Distance drawer mouseMoveEvent
            if self._interaction.measureDistance and self.drawMeasureDistance:
                self.AddMoveEventValue(self.drawMeasureDistance, Longitude, Latitude, Altitude)

            # Measure Area drawer mouseMoveEvent
            if self._interaction.measureArea and self.drawMeasureArea:
                self.AddMoveEventValue(self.drawMeasureArea, Longitude, Latitude, Altitude)

        else:
            self.parent.lb_cursor_coord.setText("<span style='font-size:10pt; font-weight:bold;'>Lon :</span>" +
                                                "<span style='font-size:9pt; font-weight:normal;'>-</span>" +
                                                "<span style='font-size:10pt; font-weight:bold;'> Lat :</span>" +
                                                "<span style='font-size:9pt; font-weight:normal;'>-</span>" +
                                                "<span style='font-size:10pt; font-weight:bold;'> Alt :</span>" +
                                                "<span style='font-size:9pt; font-weight:normal;'>-</span>")

        if not event.buttons():
            return

        # Object tracking rubberband
        if not self.Tracking_Video_RubberBand.isHidden():
            self.Tracking_Video_RubberBand.setGeometry(
                QRect(self.origin, event.pos()).normalized())

        # Censure rubberband
        if not self.Censure_RubberBand.isHidden():
            self.Censure_RubberBand.setGeometry(
                QRect(self.origin, event.pos()).normalized())
Esempio n. 12
0
    def findAtPoint(self,
                    layer,
                    point,
                    canvas,
                    onlyTheClosestOne=True,
                    onlyIds=False):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # recupera il valore del raggio di ricerca
        settings = QgsSettings()
        radius = settings.value("/Map/searchRadiusMM",
                                Qgis.DEFAULT_SEARCH_RADIUS_MM,
                                type=float)
        if radius <= 0:
            radius = Qgis.DEFAULT_SEARCH_RADIUS_MM
        radius = canvas.extent().width() * radius / 100

        # crea il rettangolo da usare per la ricerca
        rect = QgsRectangle()
        rect.setXMinimum(point.x() - radius)
        rect.setXMaximum(point.x() + radius)
        rect.setYMinimum(point.y() - radius)
        rect.setYMaximum(point.y() + radius)
        rect = canvas.mapSettings().mapToLayerCoordinates(layer, rect)

        # recupera le feature che intersecano il rettangolo
        ret = None

        if onlyTheClosestOne:
            request = QgsFeatureRequest()
            request.setFilterRect(rect)

            minDist = -1
            featureId = None
            rect = QgsGeometry.fromRect(rect)
            count = 0

            for f in layer.getFeatures(request):
                if onlyTheClosestOne:
                    geom = f.geometry()
                    distance = geom.distance(rect)
                    if minDist < 0 or distance < minDist:
                        minDist = distance
                        featureId = f.id()

            if onlyIds:
                ret = featureId
            elif featureId != None:
                f = QgsFeature()
                feats = layer.getFeature(QgsFeatureRequest(featureId))
                feats.nextFeature(f)
                ret = f

        else:
            IDs = []
            for f in layer.getFeatures():
                IDs.append(f.id())

            if onlyIds:
                ret = IDs
            else:
                ret = []
                request = QgsFeatureRequest()
                QgsFeatureRequest.setFilterFids(IDs)
                for f in layer.getFeatures(request):
                    ret.append(f)

        QApplication.restoreOverrideCursor()
        return ret
 def createDatabases(self, parameterDict):
     dbCreator = DbCreatorFactory().createDbCreatorFactory(parameterDict['driverName'], parameterDict['factoryParam'], parentWidget = self)
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     dbDict, errorDict = dbCreator.createDbWithAutoIncrementingName(parameterDict['dbBaseName'], parameterDict['srid'], parameterDict['numberOfDatabases'], prefix = parameterDict['prefix'], sufix = parameterDict['sufix'], paramDict = parameterDict['templateInfo'])
     QApplication.restoreOverrideCursor()
     return dbDict, errorDict
Esempio n. 14
0
 def leaveEvent(self, _):
     self.parent.lb_cursor_coord.setText("")
     self.setCursor(QCursor(Qt.ArrowCursor))
Esempio n. 15
0
    def mouseMoveEvent(self, event):
        """
        :type event: QMouseEvent
        :param event:
        :return:
        """
        # Magnifier mouseMoveEvent
        # Magnifier can move on black screen for show image borders
        if self._interaction.magnifier:
            if event.buttons():
                self.dragPos = event.pos()
                self.UpdateSurface()

        # check if the point  is on picture (not in black borders)
        if (not vut.IsPointOnScreen(event.x(), event.y(), self.surface)):
            self.setCursor(QCursor(Qt.ArrowCursor))
            return

        # Prevent draw on video if not started or finished
        if self.parent.player.position() == 0:
            return

        # Mouser cursor drawing
        if self._interaction.pointDrawer or self._interaction.polygonDrawer or self._interaction.lineDrawer or self._interaction.measureDistance or self._interaction.measureArea or self._interaction.censure or self._interaction.objectTracking:
            self.setCursor(QCursor(Qt.CrossCursor))

        # Cursor Coordinates
        if self.gt is not None:

            Longitude, Latitude, Altitude = vut.GetPointCommonCoords(
                event, self.surface)

            if self._MGRS:
                try:
                    mgrsCoords = mgrs.toMgrs(Latitude, Longitude)
                except Exception:
                    mgrsCoords = ""

                txt = "<span style='font-size:9pt; font-weight:normal;'>" + \
                    ("%s" % mgrsCoords) + "</span>"

            else:

                txt = "<span style='font-size:10pt; font-weight:bold;'>Lon : </span>"
                txt += "<span style='font-size:9pt; font-weight:normal;'>" + \
                    ("%.3f" % Longitude) + "</span>"
                txt += "<span style='font-size:10pt; font-weight:bold;'> Lat : </span>"
                txt += "<span style='font-size:9pt; font-weight:normal;'>" + \
                    ("%.3f" % Latitude) + "</span>"

                if hasElevationModel():
                    txt += "<span style='font-size:10pt; font-weight:bold;'> Alt : </span>"
                    txt += "<span style='font-size:9pt; font-weight:normal;'>" + \
                        ("%.0f" % Altitude) + "</span>"
                else:
                    txt += "<span style='font-size:10pt; font-weight:bold;'> Alt : </span>"
                    txt += "<span style='font-size:9pt; font-weight:normal;'>-</span>"

            self.parent.lb_cursor_coord.setText(txt)

            # Polygon drawer mouseMoveEvent
            if self._interaction.polygonDrawer:
                self.AddMoveEventValue(self.drawPolygon, Longitude, Latitude,
                                       Altitude)

            # Line drawer mouseMoveEvent
            if self._interaction.lineDrawer:
                self.AddMoveEventValue(self.drawLines, Longitude, Latitude,
                                       Altitude)

            # Measure Distance drawer mouseMoveEvent
            if self._interaction.measureDistance and self.drawMeasureDistance:
                self.AddMoveEventValue(self.drawMeasureDistance, Longitude,
                                       Latitude, Altitude)

            # Measure Area drawer mouseMoveEvent
            if self._interaction.measureArea and self.drawMeasureArea:
                self.AddMoveEventValue(self.drawMeasureArea, Longitude,
                                       Latitude, Altitude)

        else:
            self.parent.lb_cursor_coord.setText(
                "<span style='font-size:10pt; font-weight:bold;'>Lon :</span>"
                + "<span style='font-size:9pt; font-weight:normal;'>-</span>" +
                "<span style='font-size:10pt; font-weight:bold;'> Lat :</span>"
                + "<span style='font-size:9pt; font-weight:normal;'>-</span>" +
                "<span style='font-size:10pt; font-weight:bold;'> Alt :</span>"
                + "<span style='font-size:9pt; font-weight:normal;'>-</span>")

        if not event.buttons():
            return

        # Object tracking rubberband
        if not self.Tracking_Video_RubberBand.isHidden():
            self.Tracking_Video_RubberBand.setGeometry(
                QRect(self.origin, event.pos()).normalized())

        # Censure rubberband
        if not self.Censure_RubberBand.isHidden():
            self.Censure_RubberBand.setGeometry(
                QRect(self.origin, event.pos()).normalized())
Esempio n. 16
0
from qgis.PyQt.QtCore import pyqtSignal
from qgis.PyQt.QtGui import QCursor, QIcon
from qgis.PyQt.QtWidgets import QApplication

from qgis.gui import QgsMapToolEmitPoint, QgsMapMouseEvent
from qgis.core import QgsCoordinateTransform

from ..core.utils import maybe_transform_wgs84

CUSTOM_CURSOR = QCursor(
    QIcon(":images/themes/default/cursors/mCapturePoint.svg").pixmap(48, 48))


class PointTool(QgsMapToolEmitPoint):

    canvasClicked = pyqtSignal("QgsPointXY")

    def canvasReleaseEvent(self, event: QgsMapMouseEvent):
        # Get the click and emit a transformed point
        crs_canvas = self.canvas().mapSettings().destinationCrs()
        self.canvasClicked.emit(
            maybe_transform_wgs84(
                event.mapPoint(),
                crs_canvas,
                QgsCoordinateTransform.ForwardTransform,
            ))

    def activate(self):
        super().activate()
        QApplication.setOverrideCursor(CUSTOM_CURSOR)
Esempio n. 17
0
    def accept(self):
        super(AlgorithmDialog, self)._saveGeometry()

        context = dataobjects.createContext()

        checkCRS = ProcessingConfig.getSetting(
            ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            parameters = self.getParamValues()

            QgsMessageLog.logMessage(str(parameters), 'Processing',
                                     QgsMessageLog.CRITICAL)

            # TODO
            if False and checkCRS and not self.alg.checkInputCRS():
                reply = QMessageBox.question(
                    self, self.tr("Unmatching CRS's"),
                    self.tr('Layers do not all use the same CRS. This can '
                            'cause unexpected results.\nDo you want to '
                            'continue?'), QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            checkExtentCRS = ProcessingConfig.getSetting(
                ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS)
            #TODO
            if False and checkExtentCRS and self.checkExtentCRS():
                reply = QMessageBox.question(
                    self, self.tr("Extent CRS"),
                    self.
                    tr('Extent parameters must use the same CRS as the input layers.\n'
                       'Your input layers do not have the same extent as the project, '
                       'so the extent might be in a wrong CRS if you have selected it from the canvas.\n'
                       'Do you want to continue?'),
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            ok, msg = self.alg.checkParameterValues(parameters, context)
            if msg:
                QMessageBox.warning(self,
                                    self.tr('Unable to execute algorithm'),
                                    msg)
                return
            self.btnRun.setEnabled(False)
            self.btnClose.setEnabled(False)
            buttons = self.mainWidget.iterateButtons
            self.iterateParam = None

            for i in range(len(list(buttons.values()))):
                button = list(buttons.values())[i]
                if button.isChecked():
                    self.iterateParam = list(buttons.keys())[i]
                    break

            self.progressBar.setMaximum(0)
            self.lblProgress.setText(self.tr('Processing algorithm...'))
            # Make sure the Log tab is visible before executing the algorithm
            try:
                self.tabWidget.setCurrentIndex(1)
                self.repaint()
            except:
                pass

            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

            self.setInfo(
                self.tr('<b>Algorithm {0} starting...</b>').format(
                    self.alg.displayName()))

            if self.iterateParam:
                if executeIterating(self.alg, parameters, self.iterateParam,
                                    context, self.feedback):
                    self.finish(parameters, context)
                else:
                    QApplication.restoreOverrideCursor()
                    self.resetGUI()
            else:
                # TODO
                #command = self.alg.getAsCommand()
                #if command:
                #    ProcessingLog.addToLog(command)
                self.buttonCancel.setEnabled(
                    self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)
                result = executeAlgorithm(self.alg, parameters, context,
                                          self.feedback)
                self.buttonCancel.setEnabled(False)
                self.finish(result, context)
                #TODO
                #else:
                #    QApplication.restoreOverrideCursor()
                #    self.resetGUI()
        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox.accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.bar.clearWidgets()
            self.bar.pushMessage(
                "",
                self.tr("Wrong or missing parameter value: {0}").format(
                    e.parameter.description()),
                level=QgsMessageBar.WARNING,
                duration=5)
Esempio n. 18
0
    def importgeopkg(self, layer, branch, message, authorName, authorEmail,
                     interchange):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        filename, layername = namesFromLayer(layer)
        r = requests.get(self.url + "beginTransaction",
                         params={"output_format": "json"})
        r.raise_for_status()
        transactionId = r.json()["response"]["Transaction"]["ID"]
        self._checkoutbranch(branch, transactionId)
        payload = {
            "authorEmail": authorEmail,
            "authorName": authorName,
            "message": message,
            'destPath': layername,
            "format": "gpkg",
            "transactionId": transactionId
        }
        # fix_print_with_import
        if interchange:
            payload["interchange"] = True
            filename = self.saveaudittables(filename, layername)
        files = {
            'fileUpload': (os.path.basename(filename), open(filename, 'rb'))
        }

        encoder = MultipartEncoder(files)
        total = float(encoder.len)

        def callback(m):
            done = int(100 * m.bytes_read / total)
            iface.mainWindow().statusBar().showMessage(
                "Transferring geopkg to GeoGig server [{}%]".format(done))

        monitor = MultipartEncoderMonitor(encoder, callback)
        r = requests.post(self.url + "import.json",
                          params=payload,
                          data=monitor,
                          headers={'Content-Type': monitor.content_type})
        self.__log(r.url, r.text, payload, "POST")
        r.raise_for_status()
        resp = r.json()
        taskId = resp["task"]["id"]
        checker = TaskChecker(self.rootUrl, taskId)
        loop = QEventLoop()
        checker.taskIsFinished.connect(loop.exit, Qt.QueuedConnection)
        checker.start()
        loop.exec_(flags=QEventLoop.ExcludeUserInputEvents)
        QApplication.restoreOverrideCursor()
        iface.mainWindow().statusBar().showMessage("")
        if not checker.ok and "error" in checker.response["task"]:
            errorMessage = checker.response["task"]["error"]["message"]
            raise GeoGigException("Cannot import layer: %s" % errorMessage)
        if interchange:
            try:
                nconflicts = checker.response["task"]["result"]["Merge"][
                    "conflicts"]
            except KeyError, e:
                nconflicts = 0
            if nconflicts:
                mergeCommitId = self.HEAD
                importCommitId = checker.response["task"]["result"]["import"][
                    "importCommit"]["id"]
                ancestor = checker.response["task"]["result"]["Merge"][
                    "ancestor"]
                remote = checker.response["task"]["result"]["Merge"]["ours"]
                try:
                    featureIds = checker.response["task"]["result"]["import"][
                        "NewFeatures"]["type"][0].get("ids", [])
                except:
                    featureIds = []
                con = sqlite3.connect(filename)
                cursor = con.cursor()
                geomField = cursor.execute(
                    "SELECT column_name FROM gpkg_geometry_columns WHERE table_name='%s';"
                    % layername).fetchone()[0]

                def _local(fid):
                    cursor.execute(
                        "SELECT gpkg_fid FROM %s_fids WHERE geogig_fid='%s';" %
                        (layername, fid))
                    gpkgfid = int(cursor.fetchone()[0])
                    request = QgsFeatureRequest()
                    request.setFilterFid(gpkgfid)
                    try:
                        feature = next(layer.getFeatures(request))
                    except:
                        return None

                    def _ensureNone(v):
                        if v == NULL:
                            return None
                        else:
                            return v

                    local = {
                        f.name(): _ensureNone(feature[f.name()])
                        for f in layer.pendingFields()
                    }
                    try:
                        local[geomField] = feature.geometry().exportToWkt()
                    except:
                        local[geomField] = None
                    return local

                conflicts = []
                conflictsResponse = _ensurelist(
                    checker.response["task"]["result"]["Merge"]["Feature"])
                for c in conflictsResponse:
                    if c["change"] == "CONFLICT":
                        remoteFeatureId = c["ourvalue"]
                        localFeatureId = c["theirvalue"]
                        localFeature = _local(c["id"].split("/")[-1])
                        conflicts.append(
                            ConflictDiff(self, c["id"], ancestor, remote,
                                         importCommitId, localFeature,
                                         localFeatureId, remoteFeatureId,
                                         transactionId))
                cursor.close()
                con.close()
            else:
                #self._checkoutbranch("master", transactionId)
                self.closeTransaction(transactionId)
                mergeCommitId = checker.response["task"]["result"][
                    "newCommit"]["id"]
                importCommitId = checker.response["task"]["result"][
                    "importCommit"]["id"]
                try:
                    featureIds = checker.response["task"]["result"][
                        "NewFeatures"]["type"][0].get("id", [])
                except:
                    featureIds = []
                conflicts = []
            featureIds = [(f["provided"], f["assigned"]) for f in featureIds]
            return mergeCommitId, importCommitId, conflicts, featureIds
Esempio n. 19
0
    def accept(self):
        if self.mode == self.ASK_FOR_INPUT_MODE:
            # create the input layer (if not already done) and
            # update available options
            self.reloadInputLayer()

        # sanity checks
        if self.inLayer is None:
            QMessageBox.information(
                self, self.tr("Import to database"),
                self.tr("Input layer missing or not valid"))
            return

        if self.cboTable.currentText() == "":
            QMessageBox.information(self, self.tr("Import to database"),
                                    self.tr("Output table name is required"))
            return

        if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
            try:
                sourceSrid = self.editSourceSrid.text()
            except ValueError:
                QMessageBox.information(
                    self, self.tr("Import to database"),
                    self.tr("Invalid source srid: must be an integer"))
                return

        if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
            try:
                targetSrid = self.editTargetSrid.text()
            except ValueError:
                QMessageBox.information(
                    self, self.tr("Import to database"),
                    self.tr("Invalid target srid: must be an integer"))
                return

        # override cursor
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        # store current input layer crs and encoding, so I can restore it
        prevInCrs = self.inLayer.crs()
        prevInEncoding = self.inLayer.dataProvider().encoding()

        try:
            schema = self.outUri.schema() if not self.cboSchema.isEnabled(
            ) else self.cboSchema.currentText()
            table = self.cboTable.currentText()

            # get pk and geom field names from the source layer or use the
            # ones defined by the user
            srcUri = QgsDataSourceURI(self.inLayer.source())

            pk = srcUri.keyColumn() if not self.chkPrimaryKey.isChecked(
            ) else self.editPrimaryKey.text()
            if not pk:
                pk = self.default_pk

            if self.inLayer.hasGeometryType() and self.chkGeomColumn.isEnabled(
            ):
                geom = srcUri.geometryColumn(
                ) if not self.chkGeomColumn.isChecked(
                ) else self.editGeomColumn.text()
                if not geom:
                    geom = self.default_geom
            else:
                geom = None

            options = {}
            if self.chkLowercaseFieldNames.isEnabled(
            ) and self.chkLowercaseFieldNames.isChecked():
                pk = pk.lower()
                if geom:
                    geom = geom.lower()
                options['lowercaseFieldNames'] = True

            # get output params, update output URI
            self.outUri.setDataSource(schema, table, geom, "", pk)
            typeName = self.db.dbplugin().typeName()
            providerName = self.db.dbplugin().providerName()
            if typeName == 'gpkg':
                uri = self.outUri.database()
                options['update'] = True
                options['driverName'] = 'GPKG'
                options['layerName'] = table
            else:
                uri = self.outUri.uri(False)

            if self.chkDropTable.isChecked():
                options['overwrite'] = True

            if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked(
            ):
                options['forceSinglePartGeometryType'] = True

            outCrs = None
            if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(
            ):
                targetSrid = int(self.editTargetSrid.text())
                outCrs = QgsCoordinateReferenceSystem(targetSrid)

            # update input layer crs and encoding
            if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(
            ):
                sourceSrid = int(self.editSourceSrid.text())
                inCrs = QgsCoordinateReferenceSystem(sourceSrid)
                self.inLayer.setCrs(inCrs)

            if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked():
                enc = self.cboEncoding.currentText()
                self.inLayer.setProviderEncoding(enc)

            onlySelected = self.chkSelectedFeatures.isChecked()

            # do the import!
            ret, errMsg = QgsVectorLayerImport.importLayer(
                self.inLayer, uri, providerName, outCrs, onlySelected, False,
                options)
        except Exception as e:
            ret = -1
            errMsg = unicode(e)

        finally:
            # restore input layer crs and encoding
            self.inLayer.setCrs(prevInCrs)
            self.inLayer.setProviderEncoding(prevInEncoding)
            # restore cursor
            QApplication.restoreOverrideCursor()

        if ret != 0:
            output = QgsMessageViewer()
            output.setTitle(self.tr("Import to database"))
            output.setMessageAsPlainText(
                self.tr("Error %d\n%s") % (ret, errMsg))
            output.showMessage()
            return

        # create spatial index
        if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked(
        ):
            self.db.connector.createSpatialIndex((schema, table), geom)

        self.db.connection().reconnect()
        self.db.refresh()
        QMessageBox.information(self, self.tr("Import to database"),
                                self.tr("Import was successful."))
        return QDialog.accept(self)
Esempio n. 20
0
 def cursor(name):
     pix = QPixmap(name)
     pix = pix.scaled(QSize(24, 24))
     return QCursor(pix)
Esempio n. 21
0
def execute(func):
    QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
    try:
        return func()
    finally:
        QApplication.restoreOverrideCursor()
Esempio n. 22
0
    def accept(self):
        self.algs = []
        self.load = []
        self.canceled = False

        for row in range(self.mainWidget.tblParameters.rowCount()):
            alg = self.alg.getCopy()
            col = 0
            for param in alg.parameters:
                if param.hidden:
                    continue
                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                if not self.mainWidget.setParamValue(param, widget, alg):
                    self.lblProgress.setText(
                        self.tr('<b>Missing parameter value: %s (row %d)</b>')
                        % (param.description, row + 1))
                    self.algs = None
                    return
                col += 1
            for out in alg.outputs:
                if out.hidden:
                    continue

                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                text = widget.getValue()
                if text.strip() != '':
                    out.value = text
                    col += 1
                else:
                    self.lblProgress.setText(
                        self.
                        tr('<b>Wrong or missing parameter value: %s (row %d)</b>'
                           ) % (out.description, row + 1))
                    self.algs = None
                    return

            self.algs.append(alg)
            if self.alg.getVisibleOutputsCount():
                widget = self.mainWidget.tblParameters.cellWidget(row, col)
                self.load.append(widget.currentIndex() == 0)
            else:
                self.load.append(False)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.mainWidget.setEnabled(False)

        self.progressBar.setMaximum(len(self.algs))
        # Make sure the Log tab is visible before executing the algorithm
        try:
            self.tabWidget.setCurrentIndex(1)
            self.repaint()
        except:
            pass

        for count, alg in enumerate(self.algs):
            self.setText(
                self.tr('\nProcessing algorithm %d/%d...') %
                (count + 1, len(self.algs)))
            self.setInfo(self.tr('<b>Algorithm %s starting...</b>' % alg.name))
            if runalg(alg, self) and not self.canceled:
                if self.load[count]:
                    handleAlgorithmResults(alg, self, False)
                self.setInfo(
                    self.tr('Algorithm %s correctly executed...') % alg.name)
            else:
                QApplication.restoreOverrideCursor()
                return

        self.finish()
Esempio n. 23
0
 def __init__(self, canvas,button):
         QgsMapTool.__init__(self,canvas)
         self.canvas = canvas
         self.cursor = QCursor(Qt.CrossCursor)
         self.button = button
	def __init__(self, icon_path, text, toolbar, action_group, iface, settings, controller, plugin_dir):
		
		self.iface = iface
		self.settings = settings
		self.controller = controller
		self.plugin_dir = plugin_dir
		
		self.show_help = bool(int(self.settings.value('status/show_help', 1)))
		self.layer_arc = None
		self.layer_connec = None
		self.layer_gully = None
		self.layer_node = None
		self.snapper_manager = SnappingConfigManager(self.iface)
		self.snapper_manager.controller = controller
		
		self.canvas = iface.mapCanvas()
		super().__init__(self.canvas)
		
		
		icon = None
		if os.path.exists(icon_path):
			icon = QIcon(icon_path)
		
		self.action = None
		if icon is None:
			self.action = QAction(text, action_group)
		else:
			self.action = QAction(icon, text, action_group)
			
		self.action.setObjectName(text)
		self.action.setCheckable(True)
		self.action.triggered.connect(self.clicked_event)
		
		# Change map tool cursor
		self.cursor = QCursor()
		self.cursor.setShape(Qt.CrossCursor)
		
		# Get default cursor
		# noinspection PyCallingNonCallable
		self.std_cursor = self.parent().cursor()
		
		# Set default vertex marker
		color = QColor(255, 100, 255)
		self.vertex_marker = QgsVertexMarker(self.canvas)
		self.vertex_marker.setIconType(QgsVertexMarker.ICON_CIRCLE)
		self.vertex_marker.setColor(color)
		self.vertex_marker.setIconSize(15)
		self.vertex_marker.setPenWidth(3)
		
		# Set default rubber band
		color_selection = QColor(254, 178, 76, 63)
		self.rubber_band = QgsRubberBand(self.canvas, 2)
		self.rubber_band.setColor(color)
		self.rubber_band.setFillColor(color_selection)
		self.rubber_band.setWidth(1)
		self.reset()
		
		self.force_active_layer = True
		
		toolbar.addAction(self.action)
		self.setAction(self.action)
 def on_buttonBox_accepted(self):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     exceptionList = []
     customJsonDict = dict()
     for i in list(self.customDict.keys()):
         customJsonDict[i] = []
     correspondenceDict = {
         self.customDict[i]: i
         for i in list(self.customDict.keys())
     }
     nCustom = 0
     for key in list(self.contentsDict.keys()):
         for widgetItem in self.contentsDict[key]['widgetList']:
             nCustom += 1
     progress = ProgressWidget(
         1,
         nCustom,
         self.tr('Preparing to export customizations... '),
         parent=self)
     progress.initBar()
     for key in list(self.contentsDict.keys()):
         jsonTagList = []
         for widget in self.contentsDict[key]['widgetList']:
             currJsonItem = {'jsonUi': None, 'dbJsonTagList': []}
             currentWidget = widget.layout().itemAt(0).widget()
             try:
                 jsonTagList = currentWidget.getJSONTag()
                 jsonUi = currentWidget.getUiParameterJsonDict()
             except Exception as e:
                 exceptionList.append(':'.join(e.args))
             if len(exceptionList) == 0:
                 currJsonItem['jsonUi'] = jsonUi
                 for jsonItem in jsonTagList:
                     if jsonItem not in currJsonItem['dbJsonTagList']:
                         currJsonItem['dbJsonTagList'].append(jsonItem)
                 if currJsonItem not in customJsonDict[
                         correspondenceDict[key]]:
                     customJsonDict[correspondenceDict[key]].append(
                         currJsonItem)
             progress.step()
     QApplication.restoreOverrideCursor()
     if self.validateJsonDict(customJsonDict) and len(exceptionList) == 0:
         versionText = 'database_' + self.edgvVersion
         finalJsonDict = {versionText: customJsonDict}
         self.customizationManager.createSetting(self.customizationName,
                                                 self.edgvVersion,
                                                 finalJsonDict)
         QMessageBox.information(
             self, self.tr('Success!'),
             self.tr('Database Customization ') + self.customizationName +
             self.tr(' created successfuly!'))
         #EMIT to reload?
         self.close()
     else:
         msg = ''
         if len(exceptionList) > 0:
             msg += self.tr(
                 '\Errors occured while trying to export customs built. Check qgis log for further details.'
             )
             for error in exceptionList:
                 QgsMessageLog.logMessage(
                     self.tr('Customization error: ') + error,
                     "DSGTools Plugin", Qgis.Critical)
             QMessageBox.warning(self, self.tr('Error!'), msg)
    def clicked_event(self):

        # Create main menu and get cursor click position
        main_menu = QMenu()
        cursor = QCursor()
        x = cursor.pos().x()
        y = cursor.pos().y()
        click_point = QPoint(x + 5, y + 5)
        schema_name = self.schema_name.replace('"', '')
        # Get parent layers
        sql = (
            "SELECT distinct ( CASE parent_layer WHEN 'v_edit_node' THEN 'Node' "
            "WHEN 'v_edit_arc' THEN 'Arc' WHEN 'v_edit_connec' THEN 'Connec' "
            "WHEN 'v_edit_gully' THEN 'Gully' END ), parent_layer FROM cat_feature "
            "ORDER BY parent_layer")
        parent_layers = self.controller.get_rows(sql)

        for parent_layer in parent_layers:

            # Get child layers
            sql = (
                f"SELECT DISTINCT(child_layer), lower(feature_type), cat_feature.id as alias, style as style_id, "
                f" group_layer "
                f" FROM cat_feature "
                f" LEFT JOIN config_table ON config_table.id = child_layer "
                f"WHERE parent_layer = '{parent_layer[1]}' "
                f"AND child_layer IN ("
                f"   SELECT table_name FROM information_schema.tables"
                f"   WHERE table_schema = '{schema_name}')"
                f" ORDER BY child_layer")

            child_layers = self.controller.get_rows(sql)
            if not child_layers: continue

            # Create sub menu
            sub_menu = main_menu.addMenu(str(parent_layer[0]))
            child_layers.insert(
                0,
                ['Load all', 'Load all', 'Load all', 'Load all', 'Load all'])
            for child_layer in child_layers:
                # Create actions
                action = QAction(str(child_layer[2]), sub_menu, checkable=True)

                # Get load layers and create child layers menu (actions)
                layers_list = []
                layers = self.iface.mapCanvas().layers()
                for layer in layers:
                    layers_list.append(str(layer.name()))

                if str(child_layer[0]) in layers_list:
                    action.setChecked(True)

                sub_menu.addAction(action)
                if child_layer[0] == 'Load all':
                    action.triggered.connect(
                        partial(from_postgres_to_toc,
                                child_layers=child_layers))

                else:
                    layer_name = child_layer[0]
                    the_geom = "the_geom"
                    geom_field = child_layer[1] + "_id"
                    style_id = child_layer[3]
                    group = child_layer[4] if child_layer[
                        4] is not None else 'GW Layers'
                    action.triggered.connect(
                        partial(from_postgres_to_toc, layer_name, the_geom,
                                geom_field, None, group, style_id))

        main_menu.exec_(click_point)
Esempio n. 27
0
    def accept(self):
        self.settings.setValue("/Processing/dialogBase", self.saveGeometry())

        checkCRS = ProcessingConfig.getSetting(
            ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            self.setParamValues()
            if checkCRS and not self.alg.checkInputCRS():
                reply = QMessageBox.question(
                    self, self.tr("Unmatching CRS's"),
                    self.tr('Layers do not all use the same CRS. This can '
                            'cause unexpected results.\nDo you want to '
                            'continue?'), QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            checkExtentCRS = ProcessingConfig.getSetting(
                ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS)
            if checkExtentCRS and self.checkExtentCRS():
                reply = QMessageBox.question(
                    self, self.tr("Extent CRS"),
                    self.
                    tr('Extent parameters must use the same CRS as the input layers.\n'
                       'Your input layers do not have the same extent as the project, '
                       'so the extent might be in a wrong CRS if you have selected it from the canvas.\n'
                       'Do you want to continue?'),
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            msg = self.alg._checkParameterValuesBeforeExecuting()
            if msg:
                QMessageBox.warning(self,
                                    self.tr('Unable to execute algorithm'),
                                    msg)
                return
            self.btnRun.setEnabled(False)
            self.btnClose.setEnabled(False)
            buttons = self.mainWidget.iterateButtons
            self.iterateParam = None

            for i in range(len(list(buttons.values()))):
                button = list(buttons.values())[i]
                if button.isChecked():
                    self.iterateParam = list(buttons.keys())[i]
                    break

            self.progressBar.setMaximum(0)
            self.lblProgress.setText(self.tr('Processing algorithm...'))
            # Make sure the Log tab is visible before executing the algorithm
            try:
                self.tabWidget.setCurrentIndex(1)
                self.repaint()
            except:
                pass

            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

            self.setInfo(
                self.tr('<b>Algorithm %s starting...</b>') % self.alg.name)

            if self.iterateParam:
                if runalgIterating(self.alg, self.iterateParam, self.feedback):
                    self.finish()
                else:
                    QApplication.restoreOverrideCursor()
                    self.resetGUI()
            else:
                command = self.alg.getAsCommand()
                if command:
                    ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM,
                                           command)
                if runalg(self.alg, self.feedback):
                    self.finish()
                else:
                    QApplication.restoreOverrideCursor()
                    self.resetGUI()
        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox.accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.bar.clearWidgets()
            self.bar.pushMessage("",
                                 "Wrong or missing parameter value: %s" %
                                 e.parameter.description,
                                 level=QgsMessageBar.WARNING,
                                 duration=5)
Esempio n. 28
0
class FeatureDragger(FeaturePicker):
    '''
    tool for moving features on the map canvas with drag & drop,
    does not change the geometry of the dragged feature but draws a marker
    at the new position and emits the geometry

    Attributes
    ----------
    feature_dragged : pyqtSignal
        emitted when a feature is dragged or clicked on the map canvas,
        (feature id, release position)
    drag_cursor : QCursor
        the appearance of the cursor while dragging a feature
    '''
    feature_dragged = pyqtSignal(int, QgsPointXY)
    drag_cursor = QCursor(Qt.DragMoveCursor)

    def __init__(self,
                 ui_element: QWidget,
                 layers: List[QgsVectorLayer] = [],
                 canvas: QgsMapCanvas = None):
        '''
        Parameters
        ----------
        ui_element : QWidget
            clickable UI element, clicking on it will adctivate/deactivate this
            tool
        layers : list, optional
            the layers containing the features that can be picked,
            defaults to not setting any layers
        canvas : QgsMapCanvas, optional
            the map canvas the tool will work on, defaults to the map canvas of
            the QGIS UI
        '''
        super().__init__(ui_element, layers=layers, canvas=canvas)
        self._marker = None
        self._picked_feature = None
        self._dragging = False

    def reset(self):
        '''
        reset the feature picker to it's initial state
        '''
        self.remove_marker()
        self._picked_feature = None

    def remove_marker(self):
        '''
        remove the marker from the map
        '''
        if not self._marker:
            return
        self.canvas.scene().removeItem(self._marker)
        self._marker = None

    def canvasPressEvent(self, e):
        '''
        override, remember feature on click and move marker (create one if not
        drawn yet)
        '''
        if self._picked_feature is None:
            features = QgsMapToolIdentify(self.canvas).identify(
                e.pos().x(),
                e.pos().y(), self._layers,
                QgsMapToolIdentify.TopDownStopAtFirst)
            if len(features) == 0:
                return
            feature = features[0].mFeature
            self._picked_feature = feature.id()
        # there is a feature -> drag it
        self._dragging = True
        self.canvas.setCursor(self.drag_cursor)
        # not marked yet -> mark position
        if not self._marker:
            color = QColor(0, 0, 255)
            color.setAlpha(100)
            self._marker = QgsVertexMarker(self.canvas)
            self._marker.setColor(color)
            self._marker.setIconSize(10)
            self._marker.setIconType(QgsVertexMarker.ICON_CIRCLE)
            self._marker.setPenWidth(10)
        point = self.toMapCoordinates(e.pos())
        self._marker.setCenter(point)

    def canvasMoveEvent(self, e):
        '''
        override, move marker if mouse dragging is active and mouse is moved
        '''
        if not self._marker or not self._dragging:
            return
        # update position of marker while dragging
        point = self.toMapCoordinates(e.pos())
        self._marker.setCenter(point)

    def canvasReleaseEvent(self, mouseEvent):
        '''
        override, emit geometry of position of marker on mouse release
        '''
        self._dragging = False
        if self._picked_feature is None:
            return
        self.canvas.setCursor(self.cursor)
        point = self.toMapCoordinates(self._marker.pos().toPoint())
        self.feature_dragged.emit(self._picked_feature, point)
Esempio n. 29
0
    def runAlgorithm(algOrName, onFinish, *args, **kwargs):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = Processing.getAlgorithm(algOrName)
        if alg is None:
            # fix_print_with_import
            print('Error: Algorithm not found\n')
            QgsMessageLog.logMessage(
                Processing.tr('Error: Algorithm {0} not found\n').format(
                    algOrName), Processing.tr("Processing"))
            return
        alg = alg.getCopy()

        if len(args) == 1 and isinstance(args[0], dict):
            # Set params by name and try to run the alg even if not all parameter values are provided,
            # by using the default values instead.
            setParams = []
            for (name, value) in args[0].items():
                param = alg.getParameterFromName(name)
                if param and param.setValue(value):
                    setParams.append(name)
                    continue
                output = alg.getOutputFromName(name)
                if output and output.setValue(value):
                    continue
                # fix_print_with_import
                print('Error: Wrong parameter value %s for parameter %s.' %
                      (value, name))
                QgsMessageLog.logMessage(
                    Processing.tr(
                        'Error: Wrong parameter value {0} for parameter {1}.').
                    format(value, name), Processing.tr("Processing"))
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_ERROR,
                    Processing.
                    tr('Error in %s. Wrong parameter value %s for parameter %s.'
                       ) % (alg.name, value, name))
                return
            # fill any missing parameters with default values if allowed
            for param in alg.parameters:
                if param.name not in setParams:
                    if not param.setDefaultValue():
                        # fix_print_with_import
                        print(
                            'Error: Missing parameter value for parameter %s.'
                            % param.name)
                        QgsMessageLog.logMessage(
                            Processing.
                            tr('Error: Missing parameter value for parameter {0}.'
                               ).format(param.name),
                            Processing.tr("Processing"))
                        ProcessingLog.addToLog(
                            ProcessingLog.LOG_ERROR,
                            Processing.
                            tr('Error in %s. Missing parameter value for parameter %s.'
                               ) % (alg.name, param.name))
                        return
        else:
            if len(args) != alg.getVisibleParametersCount(
            ) + alg.getVisibleOutputsCount():
                # fix_print_with_import
                print('Error: Wrong number of parameters')
                QgsMessageLog.logMessage(
                    Processing.tr('Error: Wrong number of parameters'),
                    Processing.tr("Processing"))
                processing.alghelp(algOrName)
                return
            i = 0
            for param in alg.parameters:
                if not param.hidden:
                    if not param.setValue(args[i]):
                        # fix_print_with_import
                        print('Error: Wrong parameter value: ' +
                              unicode(args[i]))
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Wrong parameter value: ') +
                            unicode(args[i]), Processing.tr("Processing"))
                        return
                    i = i + 1

            for output in alg.outputs:
                if not output.hidden:
                    if not output.setValue(args[i]):
                        # fix_print_with_import
                        print('Error: Wrong output value: ' + unicode(args[i]))
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Wrong output value: ') +
                            unicode(args[i]), Processing.tr("Processing"))
                        return
                    i = i + 1

        msg = alg._checkParameterValuesBeforeExecuting()
        if msg:
            # fix_print_with_import
            print('Unable to execute algorithm\n' + unicode(msg))
            QgsMessageLog.logMessage(
                Processing.tr('Unable to execute algorithm\n{0}').format(msg),
                Processing.tr("Processing"))
            return

        if not alg.checkInputCRS():
            print('Warning: Not all input layers use the same CRS.\n' +
                  'This can cause unexpected results.')
            QgsMessageLog.logMessage(
                Processing.
                tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'
                   ), Processing.tr("Processing"))

        # Don't set the wait cursor twice, because then when you
        # restore it, it will still be a wait cursor.
        overrideCursor = False
        if iface is not None:
            cursor = QApplication.overrideCursor()
            if cursor is None or cursor == 0:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True
            elif cursor.shape() != Qt.WaitCursor:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True

        progress = None
        if kwargs is not None and "progress" in kwargs.keys():
            progress = kwargs["progress"]
        elif iface is not None:
            progress = MessageBarProgress(alg.name)

        ret = runalg(alg, progress)
        if ret:
            if onFinish is not None:
                onFinish(alg, progress)
        else:
            QgsMessageLog.logMessage(
                Processing.tr("There were errors executing the algorithm."),
                Processing.tr("Processing"))

        if overrideCursor:
            QApplication.restoreOverrideCursor()
        if isinstance(progress, MessageBarProgress):
            progress.close()
        return alg
    def _add_child_layer(self):

        # Create main menu and get cursor click position
        main_menu = QMenu()
        cursor = QCursor()
        x = cursor.pos().x()
        y = cursor.pos().y()
        click_point = QPoint(x + 5, y + 5)

        # Get load layers
        layer_list = []

        for layer in QgsProject.instance().mapLayers().values():
            layer_list.append(tools_qgis.get_layer_source_table_name(layer))

        body = tools_gw.create_body()
        json_result = tools_gw.execute_procedure('gw_fct_getaddlayervalues',
                                                 body)
        if not json_result or json_result['status'] == 'Failed':
            return False

        dict_menu = {}

        for field in json_result['body']['data']['fields']:
            if field['context'] is not None:
                context = json.loads(field['context'])
                if 'level_1' in context and context['level_1'] not in dict_menu:
                    menu_level_1 = main_menu.addMenu(f"{context['level_1']}")
                    dict_menu[context['level_1']] = menu_level_1
                if 'level_2' in context and f"{context['level_1']}_{context['level_2']}" not in dict_menu:
                    menu_level_2 = dict_menu[context['level_1']].addMenu(
                        f"{context['level_2']}")
                    dict_menu[
                        f"{context['level_1']}_{context['level_2']}"] = menu_level_2
                if 'level_3' in context and f"{context['level_1']}_{context['level_2']}_{context['level_3']}" not in dict_menu:
                    menu_level_3 = dict_menu[
                        f"{context['level_1']}_{context['level_2']}"].addMenu(
                            f"{context['level_3']}")
                    dict_menu[
                        f"{context['level_1']}_{context['level_2']}_{context['level_3']}"] = menu_level_3
                if 'level_3' in context:
                    if f"{context['level_1']}_{context['level_2']}_{context['level_3']}_load_all" not in dict_menu:
                        action = QAction(
                            "Load all",
                            dict_menu[
                                f"{context['level_1']}_{context['level_2']}_{context['level_3']}"],
                            checkable=True)
                        action.triggered.connect(
                            partial(
                                self._manage_load_all,
                                fields=json_result['body']['data']['fields'],
                                group=context['level_1'],
                                sub_group=context['level_2'],
                                sub_sub_group=context['level_3']))
                        dict_menu[
                            f"{context['level_1']}_{context['level_2']}_{context['level_3']}"].addAction(
                                action)
                        dict_menu[
                            f"{context['level_1']}_{context['level_2']}_{context['level_3']}_load_all"] = True
                    action = QAction(
                        field['layerName'],
                        dict_menu[
                            f"{context['level_1']}_{context['level_2']}_{context['level_3']}"],
                        checkable=True)
                    dict_menu[
                        f"{context['level_1']}_{context['level_2']}_{context['level_3']}"].addAction(
                            action)
                else:
                    if f"{context['level_1']}_{context['level_2']}_load_all" not in dict_menu:
                        action = QAction(
                            "Load all",
                            dict_menu[
                                f"{context['level_1']}_{context['level_2']}"],
                            checkable=True)
                        action.triggered.connect(
                            partial(
                                self._manage_load_all,
                                fields=json_result['body']['data']['fields'],
                                group=context['level_1'],
                                sub_group=context['level_2']))
                        dict_menu[
                            f"{context['level_1']}_{context['level_2']}"].addAction(
                                action)
                        dict_menu[
                            f"{context['level_1']}_{context['level_2']}_load_all"] = True
                    action = QAction(
                        field['layerName'],
                        dict_menu[
                            f"{context['level_1']}_{context['level_2']}"],
                        checkable=True)
                    dict_menu[
                        f"{context['level_1']}_{context['level_2']}"].addAction(
                            action)

                if f"{field['tableName']}" in layer_list:
                    action.setChecked(True)

                layer_name = field['tableName']
                if field['geomField'] == "None":
                    the_geom = None
                else:
                    the_geom = field['geomField']
                geom_field = field['tableId']
                style_id = field['style_id']
                group = context['level_1']
                sub_group = context['level_2']

                action.triggered.connect(
                    partial(self._check_action_ischecked, layer_name, the_geom,
                            geom_field, group, sub_group, style_id))

        main_menu.exec_(click_point)