def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = QtCore.QFileInfo(
            QgsApplication.qgisUserDatabaseFilePath()).path(
            ) + "/python/plugins/bulkvectorexport"
        # initialize locale
        localePath = ""
        locale = QtCore.QSettings().value("locale/userLocale")[0:2]

        if QtCore.QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/bulkvectorexport_" + \
                locale + ".qm"

        if QtCore.QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)

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

        # Create the dialog (after translation) and keep reference
        self.dlg = BulkVectorExportDialog()
        # Set CRS.
        self.epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326")
示例#2
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = QtCore.QFileInfo(
            QgsApplication.qgisUserDatabaseFilePath()).path(
            ) + "/python/plugins/DigitizingTools"
        # initialize locale
        QgsMessageLog.logMessage("dir = " + self.plugin_dir)
        localePath = ""

        try:
            locale = QtCore.QSettings().value("locale/userLocale",
                                              "en",
                                              type=str)[0:2]
        except:
            locale = "en"

        if QtCore.QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/digitizingtools_" + locale + ".qm"

        if QtCore.QFileInfo(localePath).exists():
            self.translator = QtCore.QTranslator()
            self.translator.load(localePath)
            QtCore.QCoreApplication.installTranslator(self.translator)
def addDraggedUrisToWorkspace(uris, catalog, workspace, explorer, tree):
    if uris and workspace:
        toPublish = []
        allLayers = qgislayers.getAllLayersAsDict()
        publishableLayers = qgislayers.getPublishableLayersAsDict()
        for i, uri in enumerate(uris):
            layer = None
            if isinstance(uri, QgsMimeDataUtils.Uri):
                layer = qgislayers.layerFromUri(uri)
            source = uri if isinstance(uri, str) else uri.uri
            source = source.split("|")[0]
            if layer is None:
                if source in allLayers:
                    layer = publishableLayers.get(source, None)
                else:
                    if isinstance(uri, str):
                        layerName = QtCore.QFileInfo(uri).completeBaseName()
                        layer = QgsRasterLayer(uri, layerName)
                    else:
                        layer = QgsRasterLayer(uri.uri, uri.name)
                    if not layer.isValid(
                    ) or layer.type() != QgsMapLayer.RasterLayer:
                        if isinstance(uri, str):
                            layerName = QtCore.QFileInfo(
                                uri).completeBaseName()
                            layer = QgsVectorLayer(uri, layerName, "ogr")
                        else:
                            layer = QgsVectorLayer(uri.uri, uri.name,
                                                   uri.providerKey)
                        if not layer.isValid(
                        ) or layer.type() != QgsMapLayer.VectorLayer:
                            layer.deleteLater()
                            layer = None
                if layer is None:
                    name = "'%s'" % allLayers[
                        source] if source in allLayers else "with source '%s'" % source
                    msg = "Could not resolve layer " + name
                    QgsMessageLog.logMessage(msg, level=Qgis.Critical)
                else:
                    toPublish.append([layer, workspace])
            else:
                toPublish.append([layer, workspace])

        if toPublish:

            def layersUploaded():
                explorer.resetActivity()
                tree.findAllItems(catalog)[0].refreshContent(explorer)

            _publishLayers(catalog, toPublish, layersUploaded)
示例#4
0
    def openSampleDatasource(self):
        self.closeSampleDatasource()

        filePath = self.samplePath()
        finfo = QtCore.QFileInfo(filePath)
        if not finfo.exists():
            return False
        dataSource = ogr.Open(filePath, 0)
        if dataSource is None:
            self.messageBar.pushMessage(u"Could not open {}".format(filePath),
                                        Qgis.Warning, 5)
        self.sampleDatasource = dataSource
示例#5
0
    def openDataSource(self):
        self.closeDataSource()

        filePath = self.filePath()
        self.finfo = QtCore.QFileInfo(filePath)
        if not self.finfo.exists():
            return

        dataSource = ogr.Open(filePath, 0)
        if dataSource is None:
            self.messageBar.pushMessage(u"Could not open {}".format(filePath),
                                        Qgis.Warning, 5)
        self.dataSource = dataSource

        if self.dataSource and self.dataSource.GetDriver().GetName() in [
                'XLS'
        ]:
            self.setEofDetection(True)
        else:
            self.setEofDetection(False)
示例#6
0
    def populate_template_combobox(self, path, unwanted_templates=None):
        """Helper method for populating template combobox.

        :param unwanted_templates: List of templates that isn't an option.
        :type unwanted_templates: list

        .. versionadded: 4.3.0
        """
        templates_dir = QtCore.QDir(path)
        templates_dir.setFilter(QtCore.QDir.Files
                                | QtCore.QDir.NoSymLinks
                                | QtCore.QDir.NoDotAndDotDot)
        templates_dir.setNameFilters(['*.qpt', '*.QPT'])
        report_files = templates_dir.entryList()
        if not unwanted_templates:
            unwanted_templates = []
        for unwanted_template in unwanted_templates:
            if unwanted_template in report_files:
                report_files.remove(unwanted_template)

        for f in report_files:
            self.template_combo.addItem(
                QtCore.QFileInfo(f).baseName(), path + '/' + f)
    def __init__(self, parent, boundingbox):
        super(ExtentDialog, self).__init__(parent)
        self.setupUi(self)
        self.superParent = None
        temp = self.parent()
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)
        while self.superParent is None:
            if issubclass(type(temp),
                          geographicinformationPanel.Ui_geographicinfo):
                self.superParent = temp
            else:
                temp = temp.parent()
        for info in self.findChildren(qwidgets.QPushButton,
                                      qcore.QRegExp('info_*')):
            info.setIcon(qgui.QIcon(':/resourcesFolder/icons/help_icon.svg'))
            info.setText('')
            info.pressed.connect(self.printHelp)

        self.layers = []
        self.maxExt = None
        self.boundingbox = boundingbox
        self.outBB = False

        # Create MapCanvas
        self.canvas = gui.QgsMapCanvas(self)

        # Append to Dialog Layout
        self.toolBar = qwidgets.QToolBar()
        self.layout = qwidgets.QVBoxLayout(self.frame)
        self.layout.addWidget(self.toolBar)
        self.layout.addWidget(self.canvas)

        # Trigger on scaleChanged
        self.canvas.scaleChanged.connect(self.scaleChanged)
        # Trigger on renderStarting
        self.canvas.renderStarting.connect(self.renderStarting)

        # Create Map Tools
        actionFullExt = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/globe.svg'), "Mapa total",
            self)
        actionPan = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/pan.svg'), "Mover", self)
        actionZoomIn = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/zoom_in.svg'), "Aproximar",
            self)
        actionZoomOut = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/zoom_out.svg'), "Afastar",
            self)
        actionSelect = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/selection.svg'), 'Desenhar',
            self)
        actionFromLayer = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/layers.svg'),
            'Obter de camada', self)

        actionFullExt.setCheckable(False)
        actionPan.setCheckable(True)
        actionZoomIn.setCheckable(True)
        actionZoomOut.setCheckable(True)
        actionSelect.setCheckable(True)

        actionFullExt.triggered.connect(self.fullext)
        actionPan.triggered.connect(self.pan)
        actionZoomIn.triggered.connect(self.zoomIn)
        actionZoomOut.triggered.connect(self.zoomOut)
        actionSelect.triggered.connect(self.select)
        actionFromLayer.triggered.connect(self.chooseLayer)

        # Add to created ToolBar
        self.toolBar.addAction(actionFullExt)
        self.toolBar.addSeparator()
        self.toolBar.addAction(actionPan)
        self.toolBar.addAction(actionZoomIn)
        self.toolBar.addAction(actionZoomOut)
        self.toolBar.addAction(actionSelect)
        self.toolBar.addAction(actionFromLayer)

        self.toolFullExtent = gui.QgsMapToolPan(self.canvas)
        self.toolFullExtent.setAction(actionFullExt)
        self.toolPan = gui.QgsMapToolPan(self.canvas)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = gui.QgsMapToolZoom(self.canvas, False)  # false = in
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = gui.QgsMapToolZoom(self.canvas, True)  # true = out
        self.toolZoomOut.setAction(actionZoomOut)
        self.toolSelect = SelectionTool(self.canvas, self)
        self.resourcebox.setChecked(True)
        self.pan()

        lugin_path = utils.pluginDirectory('EditorMetadadosMarswInforbiomares')

        # Load Vector
        layerpath = os.path.join(plugin_path, "resourcesFolder/World.shp")
        llayer = core.QgsVectorLayer(layerpath, "WorldLayer", "ogr")

        # Set Layer Symbology
        props = {
            'color_border': '0,0,0,125',
            'style': 'no',
            'style_border': 'solid'
        }
        #s = core.QgsFillSymbolV2.createSimple(props)
        s = core.QgsFillSymbol.createSimple(props)
        #llayer.setRendererV2(core.QgsSingleSymbolRendererV2(s))
        llayer.setRenderer(core.QgsSingleSymbolRenderer(s))

        # Set CRS - necessary to load Raster - it assumes this default CRS
        s = qcore.QSettings()
        oldValidation = str(
            s.value("/Projections/defaultBehaviour", "useGlobal"))
        s.setValue("/Projections/defaultBehaviour", "useGlobal")

        # Load Raster
        fileName = os.path.join(plugin_path, "resourcesFolder/GMRT.tif")
        fileInfo = qcore.QFileInfo(fileName)
        baseName = fileInfo.baseName()
        layer = core.QgsRasterLayer(fileName, baseName)
        layer.setCrs(
            core.QgsCoordinateReferenceSystem(
                4326, core.QgsCoordinateReferenceSystem.EpsgCrsId))
        s.setValue("/Projections/defaultBehaviour", oldValidation)

        # Set Raster ColorRamp
        # layer.setDrawingStyle("SingleBandPseudoColor") # deprecated remove in 2.1.0 please
        vmin = -5683.08
        vmax = 2763.86
        vrange = vmax - vmin
        vadd = vrange // 2
        vint = vmin + vadd
        colDic = {
            'brown': '#90330a',
            'lightblue': '#d5f5f9',
            'blue': '#2099d4'
        }
        valueList = [vmin, vint, vmax]

        lst = [core.QgsColorRampShader.ColorRampItem(valueList[0], qgui.QColor(colDic['blue'])), \
               core.QgsColorRampShader.ColorRampItem(valueList[1],
                                                     qgui.QColor(colDic['lightblue'])), \
               core.QgsColorRampShader.ColorRampItem(valueList[2], qgui.QColor(colDic['brown']))]
        myRasterShader = core.QgsRasterShader()
        myColorRamp = core.QgsColorRampShader()
        myColorRamp.setColorRampItemList(lst)
        myColorRamp.setColorRampType(core.QgsColorRampShader.Interpolated)
        myRasterShader.setRasterShaderFunction(myColorRamp)
        myPseudoRenderer = core.QgsSingleBandPseudoColorRenderer(
            layer.dataProvider(), layer.type(), myRasterShader)
        layer.setRenderer(myPseudoRenderer)

        ## Add vector to map
        #core.QgsMapLayerRegistry.instance().addMapLayer(llayer, False)
        core.QgsProject.instance().addMapLayer(llayer, False)
        ## Add raster to map
        #core.QgsMapLayerRegistry.instance().addMapLayer(layer, False)
        core.QgsProject.instance().addMapLayer(layer, False)

        ## Save Max Extent
        self.maxExt = core.QgsRectangle(-180., -90., 180., 90.)

        # ----------------------------------
        ## Set initial general extent to ZEE or, if one is selected, from the selected boundingbox
        if self.boundingbox.selectionModel().hasSelection() == False:
            ## Change button's title
            self.add_extent.setText(u"Adicionar")
            initialrect = core.QgsRectangle(-46.63064, 22.52146, 9.64473,
                                            47.31826)
        else:
            ## Get selected bounding box coords and resource flag
            index = self.boundingbox.selectionModel().selectedRows()[0].row()
            row = self.boundingbox.model().matrix[index]

            minx = float(row[0].replace(',', '.'))
            miny = float(row[3].replace(',', '.'))
            maxx = float(row[1].replace(',', '.'))
            maxy = float(row[2].replace(',', '.'))

            if minx == 0. and miny == 0. and maxx == 0. and maxy == 0.:
                initialrect = core.QgsRectangle(-46.63064, 22.52146, 9.64473,
                                                47.31826)
            else:
                ## Set fields with these values
                self.xMin.setValue(minx)
                self.xMax.setValue(maxx)
                self.yMin.setValue(miny)
                self.yMax.setValue(maxy)
                self.resourcebox.setChecked(bool(row[4]))

                ## Set the extent and add a bit of zoom out of the selected extent
                initialrect = core.QgsRectangle(minx - minx * 0.1,
                                                miny - miny * 0.1,
                                                maxx + maxx * 0.1,
                                                maxy + maxy * 0.1)

                ## Draw initial extent on the map
                self.toolSelect.drawRect(minx, miny, maxx, maxy)

                ## Change button's title
                self.add_extent.setText(u"Alterar")

        self.canvas.setExtent(initialrect)
        # ----------------------------------

        ## Append layers to MapCanvas
        self.layers.append(llayer)
        self.layers.append(layer)
        #self.layers.append(gui.QgsMapCanvasLayer(llayer))
        #self.layers.append(gui.QgsMapCanvasLayer(layer))
        #self.canvas.setLayerSet(self.layers)
        self.canvas.setLayers([llayer, layer])

        ## Set triggers to buttons
        self.add_extent.clicked.connect(self.add_new_extent)
        self.btn_close.clicked.connect(lambda: self.done(QDialog.Rejected))
        self.finished.connect(self.cleanup)

        ## Disabled coord fields
        self.xMin.setEnabled(False)
        self.xMax.setEnabled(False)
        self.yMin.setEnabled(False)
        self.yMax.setEnabled(False)
 def setLastOpenPath(self, filepath):
     if not filepath:
         return
     self.last_open_dir = QtCore.QFileInfo(filepath).dir().absolutePath()
    def run(self):
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result == 1:
            # get target directory
            dirName = self.dlg.ui.dirEdit.text()
            # Export path field empty? Raise warning and break with return.
            if dirName == "":
                QtWidgets.QMessageBox.critical(self.dlg, "BulkVectorExport", \
                    "Please input directory name")
                return
            # Check for valid directory path.
            if dirName[len(dirName) - 1] != "/":
                dirName = dirName + "/"
            if not QtCore.QFileInfo(dirName).isDir():
                QtWidgets.QMessageBox.critical(self.dlg, "BulkVectorExport", \
                    "No such directory : " + dirName)
                return
            ogr_driver_name = "GeoJSON"
            ogr_driver_name_raster = "GTiff"
            print("Driver name: " + ogr_driver_name)
            layers = qgis.utils.iface.mapCanvas().layers()
            project = QgsProject.instance()
            mapInfo = {
                "name": os.path.basename(project.fileName()),
                "layers": [],
                "bounds": []
            }
            tempPath = tempfile.mkdtemp('bulkexport') + os.sep
            fileNames = []
            for layer in reversed(layers):
                layerType = layer.type()
                if layerType == QgsMapLayer.RasterLayer:
                    renderer = layer.renderer()
                    hasIcon = False
                    print('Writing: ' + str(layer.name()))
                    layer_filename_r = tempPath + str(uuid.uuid4()) + '.tif'
                    print('Filename: ' + layer_filename_r)
                    provider = layer.dataProvider()
                    src_crs = layer.crs()
                    dst_crs = QgsCoordinateReferenceSystem("EPSG:4326")
                    source_path = " -of GTiff " + provider.dataSourceUri()
                    cmd = "gdalwarp -overwrite -r bilinear -s_srs EPSG:" + \
                                            str(src_crs.postgisSrid()) + \
                                            " -t_srs EPSG:" + \
                                            str(dst_crs.postgisSrid()) + \
                                            " " + \
                                            source_path + \
                                            " " + \
                                            layer_filename_r
                    result4 = os.system(cmd)
                    print("geotiff export Status: " + str(result4))
                    if result4 != 0:
                        QtWidgets.QMessageBox.warning(self.dlg, "BulkVectorExport",\
                            "Failed to export: " + layer.name() + \
                            "Status: " + str(result4))
                    result5 = False
                    mapInfo['layers'].append({
                        "title":
                        str(layer.name()),
                        "geotiff":
                        os.path.basename(layer_filename_r)  # + '.tif'
                    })
                    fileNames.append(layer_filename_r)
                elif layerType == QgsMapLayer.VectorLayer:
                    renderer = layer.renderer()
                    hasIcon = False
                    if isinstance(renderer, QgsSingleSymbolRenderer):
                        copySymbols(renderer.symbol(), tempPath, fileNames)
                        hasIcon = True
                    print('Writing:' + str(layer.name()))
                    layer_filename = tempPath + str(uuid.uuid4())
                    print('Filename: ' + layer_filename)
                    crs = QgsCoordinateReferenceSystem("EPSG:4326")
                    result2 = qgis.core.QgsVectorFileWriter.writeAsVectorFormat(
                        layer, layer_filename, "utf-8", crs, ogr_driver_name)
                    print("Status: " + str(result2))
                    if result2[0] != 0:
                        QtWidgets.QMessageBox.warning(self.dlg, "BulkVectorExport",\
                            "Failed to export: " + layer.name() + \
                            "Status: " + str(result2))
                    sld_filename = os.path.join(
                        tempPath,
                        os.path.basename(layer_filename) + '.sld')
                    print('Filename: ' + sld_filename)
                    result3 = False
                    layer.saveSldStyle(sld_filename)
                    mapInfo['layers'].append({
                        "title":
                        str(layer.name()),
                        "geojson":
                        os.path.basename(layer_filename) + '.geojson',
                        "sld":
                        os.path.basename(sld_filename),
                        ## opacity value has to be rounded, otherwise python 3.6 writes 0.99 instead of 1.0
                        "opacity":
                        round(1 - (layer.opacity() / 100.0), 1),
                        "hasIcon":
                        hasIcon
                    })
                    fileNames.append(layer_filename + '.geojson')
                    fileNames.append(sld_filename)
                    print(fileNames)

            ## initial bounding box is visible extent
            canvas = self.iface.mapCanvas()
            canvasExtent = canvas.extent()
            crsDest = QgsCoordinateReferenceSystem("EPSG:4326")
            try:
                crsSrc = canvas.mapSettings().destinationCrs()
            except:
                crsSrc = canvas.mapRenderer().destinationCrs()
            xform = QgsCoordinateTransform(crsSrc, crsDest,
                                           QgsProject.instance())
            canvasExtentTransformed = xform.transform(canvasExtent)

            initialBounds = [
                canvasExtentTransformed.xMinimum(),
                canvasExtentTransformed.yMinimum(),
                canvasExtentTransformed.xMaximum(),
                canvasExtentTransformed.yMaximum()
            ]

            mapInfo['bounds'] = bounds(layers)
            mapInfo['maxZoom'] = 11
            mapInfo['minZoom'] = 6
            mapInfo['description'] = ""
            mapInfo['attribution'] = ""
            mapInfo['popupTemplate'] = ""
            mapInfo['initialBounds'] = initialBounds
            mapInfo['limitedInitialBounds'] = False
            mapInfo['popupLayerIndex'] = -1
            mapInfo['hasLayerControl'] = True
            mapInfo['hasZoomControl'] = True
            mapInfo['hasLayerLegend'] = True
            mapInfo['basemap'] = 'bmapgrau'
            map_filename = tempPath + 'metadata.json'
            with open(map_filename, 'w') as outfile:
                json.dump(mapInfo, outfile)

            fileNames.append(map_filename)

            ## if .svg file present, add to packlist
            for svgfile in os.listdir(tempPath):
                if svgfile.endswith(".svg"):
                    fileNames.append(tempPath + svgfile)

            ## zip all
            zf = zipfile.ZipFile(
                dirName + os.sep + os.path.basename(str(project.fileName())) +
                '.globus.zip', "w")

            for fileName in fileNames:
                zf.write(os.path.join(fileName),
                         arcname=os.path.split(fileName)[1])
                os.remove(fileName)

            shutil.rmtree(tempPath, ignore_errors=True, onerror=None)
            zf.close()
示例#10
0
def setLastDir(filename, tool_name=''):
    path = QtCore.QFileInfo(filename).absolutePath()
    settings = QtCore.QSettings(tool_name,"")
    settings.setValue("lastUsedDir", str(unicode(path)))