Esempio n. 1
0
    def getSpatialInfo(self):
        ret = []

        info = self.db.connector.getSpatialInfo()
        if info is None:
            return

        tbl = [
            (QApplication.translate("DBManagerPlugin", "Library:"), info[0]),
            (QApplication.translate("DBManagerPlugin", "Scripts:"), info[3]),
            ("GEOS:", info[1]),
            ("Proj:", info[2])
        ]
        ret.append(HtmlTable(tbl))

        if info[1] is not None and info[1] != info[2]:
            ret.append(HtmlParagraph(QApplication.translate("DBManagerPlugin",
                                                            "<warning> Version of installed scripts doesn't match version of released scripts!\n"
                                                            "This is probably a result of incorrect PostGIS upgrade.")))

        if not self.db.connector.has_geometry_columns:
            ret.append(HtmlParagraph(
                QApplication.translate("DBManagerPlugin", "<warning> geometry_columns table doesn't exist!\n"
                                                          "This table is essential for many GIS applications for enumeration of tables.")))
        elif not self.db.connector.has_geometry_columns_access:
            ret.append(HtmlParagraph(QApplication.translate("DBManagerPlugin",
                                                            "<warning> This user doesn't have privileges to read contents of geometry_columns table!\n"
                                                            "This table is essential for many GIS applications for enumeration of tables.")))

        return ret
Esempio n. 2
0
    def _opendb(self):

        self.gdal_ds = None
        if hasattr(gdal, 'OpenEx'):
            # GDAL >= 2
            self.gdal_ds = gdal.OpenEx(self.dbname, gdal.OF_UPDATE)
            if self.gdal_ds is None:
                self.gdal_ds = gdal.OpenEx(self.dbname)
            if self.gdal_ds is None or self.gdal_ds.GetDriver().ShortName != 'GPKG':
                raise ConnectionError(QApplication.translate("DBManagerPlugin", '"{0}" not found').format(self.dbname))
            self.has_raster = self.gdal_ds.RasterCount != 0 or self.gdal_ds.GetMetadata('SUBDATASETS') is not None
            self.connection = None
            self.gdal2 = True
        else:
            # GDAL 1.X compat. To be removed at some point
            self.gdal_ds = ogr.Open(self.dbname, update=1)
            if self.gdal_ds is None:
                self.gdal_ds = ogr.Open(self.dbname)
            if self.gdal_ds is None or self.gdal_ds.GetDriver().GetName() != 'GPKG':
                raise ConnectionError(QApplication.translate("DBManagerPlugin", '"{0}" not found').format(self.dbname))
            # For GDAL 1.X, we cannot issue direct SQL SELECT to the OGR datasource
            # so we need a direct sqlite connection
            try:
                self.connection = spatialite_connect(str(self.dbname))
            except self.connection_error_types() as e:
                raise ConnectionError(e)
            self.gdal2 = False
 def __signal_checkBoxEnableMap_stateChanged(self, state):
     enable = False
     if state == Qt.Unchecked:
         self.__marker.reset()
     else:
         if self.__canvas.layerCount() == 0:
             QMessageBox.warning(self, QApplication.translate(
                 "OpenLayersOverviewWidget",
                 "OpenLayers Overview"), QApplication.translate(
                     "OpenLayersOverviewWidget",
                     "At least one layer in map canvas required"))
             self.checkBoxEnableMap.setCheckState(Qt.Unchecked)
         else:
             enable = True
             if not self.__initLayerOL:
                 self.__initLayerOL = True
                 self.__setWebViewMap(0)
             else:
                 self.__refreshMapOL()
     # GUI
     if enable:
         self.lbStatusRead.setVisible(False)
         self.webViewMap.setVisible(True)
     else:
         self.lbStatusRead.setText("")
         self.lbStatusRead.setVisible(True)
         self.webViewMap.setVisible(False)
     self.webViewMap.setEnabled(enable)
     self.comboBoxTypeMap.setEnabled(enable)
     self.pbRefresh.setEnabled(enable)
     self.pbAddRaster.setEnabled(enable)
     self.pbCopyKml.setEnabled(enable)
     self.pbSaveImg.setEnabled(enable)
     self.checkBoxHideCross.setEnabled(enable)
Esempio n. 4
0
 def connectionDetails(self):
     tbl = [
         (QApplication.translate("DBManagerPlugin", "Host:"), self.db.connector.host),
         (QApplication.translate("DBManagerPlugin", "User:"******"DBManagerPlugin", "Database:"), self.db.connector.dbname)
     ]
     return HtmlTable(tbl)
 def __exportShp(self, asPnt):
     u = Util(self.iface)
     if asPnt is True:
         caption = QApplication.translate("code", "Punkt Shapefile exportieren")
     else:
         caption = QApplication.translate("code", "Linien Shapefile exportieren")
     fileName, file_ext = u.getFileName(caption, [["shp", "shp"]], self.filePath)
     if fileName == "":
         return
     fInfo = QFileInfo(fileName)
     self.filePath = fInfo.path()
     QgsSettings().setValue("vogisprofiltoolmain/savepath", self.filePath)
     expShp = ExportShape(self.iface,
                          (self.ui.IDC_chkHekto.checkState() == Qt.Checked),
                          (self.ui.IDC_chkLineAttributes.checkState() == Qt.Checked),
                          self.__getDelimiter(),
                          self.__getDecimalDelimiter(),
                          fileName,
                          self.settings,
                          self.profiles
                          )
     if asPnt is False:
         expShp.exportLine()
     else:
         expShp.exportPoint()
    def addToLayout(self):
        mgr = QgsProject.instance().layoutManager()
        layout = None
        layouts = mgr.layouts()
        if len(layouts) == 0:
            QMessageBox.warning(self,
                                QApplication.translate("code", "Keine Layouts"),
                                QApplication.translate("code", "Zuerst ein Layout erstellen"))
            return
        elif len(layouts) == 1:
            layout = layouts[0]
        else:
            d = VoGISProfilToolLayoutsDialog(self, layouts)
            result = d.exec_()
            if result == QDialog.Accepted:
                layout = mgr.layoutByName(d.ui.cmbLayouts.currentText())
            else:
                return

        u = Util(self.iface)
        caption = QApplication.translate("code", "PNG Datei")
        file_format = []
        file_format.append(["PNG files", "png"])
        fileName, fileExt = u.getFileName(caption, file_format, QgsProject.instance().homePath())
        if fileName == "":
            return
        fInfo = QFileInfo(fileName)
        self.filePath = fInfo.path()
        figure = self.subplot.figure
        figure.savefig(fileName, format="png")

        image = QgsLayoutItemPicture(layout)
        image.setPicturePath(fileName)
        image.attemptResize(QgsLayoutSize(200, 200))
        layout.addLayoutItem(image)
    def exportTxt(self):
        delimiter = self.__getDelimiter()
        decimalDelimiter = self.__getDecimalDelimiter()
        if delimiter == decimalDelimiter:
            msg = QApplication.translate("code", "Gleiches Dezimal- und Spaltentrennzeichen gewählt!")
            QMessageBox.warning(self.iface.mainWindow(), "VoGIS-Profiltool", msg)
            return

        u = Util(self.iface)
        caption = QApplication.translate("code", "Textdatei exportieren")
        fileName, file_ext = u.getFileName(caption, [["txt", "txt"]], self.filePath)
        if fileName == "":
            return
        fInfo = QFileInfo(fileName)
        self.filePath = fInfo.path()
        QgsSettings().setValue("vogisprofiltoolmain/savepath", self.filePath)
        hekto = (self.ui.IDC_chkHekto.checkState() == Qt.Checked)
        attribs = (self.ui.IDC_chkLineAttributes.checkState() == Qt.Checked)
        txt = open(fileName, "w")

        txt.write(self.profiles[0].writeHeader(self.settings.mapData.rasters.selectedRasters(), hekto, attribs, delimiter))
        for p in self.profiles:
            #txt.write("=====Profil {0}======{1}".format(p.id, os.linesep))
            #txt.write("Segments:{0}{1}".format(len(p.segments), os.linesep))
            #for s in p.segments:
            #    txt.write("Vertices:{0}{1}".format(len(s.vertices), os.linesep))
            txt.write(p.toString(hekto,
                                 attribs,
                                 delimiter,
                                 decimalDelimiter
                                 ))
        txt.close()
Esempio n. 8
0
    def runAction(self, action):
        action = str(action)

        if action.startswith("spatialindex/"):
            parts = action.split('/')
            spatialIndex_action = parts[1]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to %s spatial index for field %s?") % (
                spatialIndex_action, self.geomColumn)
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Spatial Index"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if spatialIndex_action == "create":
                self.createSpatialIndex()
                return True
            elif spatialIndex_action == "delete":
                self.deleteSpatialIndex()
                return True

        if action.startswith("extent/"):
            if action == "extent/get":
                self.refreshTableExtent()
                return True

            if action == "extent/estimated/get":
                self.refreshTableEstimatedExtent()
                return True

        return Table.runAction(self, action)
Esempio n. 9
0
    def spatialInfo(self):
        ret = []
        if self.table.geomType is None:
            return ret

        tbl = [
            (QApplication.translate("DBManagerPlugin", "Column:"), self.table.geomColumn),
            (QApplication.translate("DBManagerPlugin", "Geometry:"), self.table.geomType)
        ]

        # only if we have info from geometry_columns
        srid = self.table.srid if self.table.srid is not None else -1
        sr_info = self.table.database().connector.getSpatialRefInfo(srid) if srid != -1 else QApplication.translate(
            "DBManagerPlugin", "Undefined")
        if sr_info:
            tbl.append((QApplication.translate("DBManagerPlugin", "Spatial ref:"), u"%s (%d)" % (sr_info, srid)))

        # extent
        if self.table.extent is not None and self.table.extent[0] is not None:
            extent_str = '%.5f, %.5f - %.5f, %.5f' % self.table.extent
        else:
            extent_str = QApplication.translate("DBManagerPlugin",
                                                '(unknown) (<a href="action:extent/get">find out</a>)')
        tbl.append((QApplication.translate("DBManagerPlugin", "Extent:"), extent_str))

        ret.append(HtmlTable(tbl))
        return ret
Esempio n. 10
0
    def initGui(self):
        self.action = QAction(
            QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin", "DB Manager"), self.iface.mainWindow()
        )
        self.action.setObjectName("dbManager")
        self.action.triggered.connect(self.run)
        # Add toolbar button and menu item
        if hasattr(self.iface, "addDatabaseToolBarIcon"):
            self.iface.addDatabaseToolBarIcon(self.action)
        else:
            self.iface.addToolBarIcon(self.action)
        if hasattr(self.iface, "addPluginToDatabaseMenu"):
            self.iface.addPluginToDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)
        else:
            self.iface.addPluginToMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)

        self.layerAction = QAction(
            QIcon(":/db_manager/icon"),
            QApplication.translate("DBManagerPlugin", "Update Sql Layer"),
            self.iface.mainWindow(),
        )
        self.layerAction.setObjectName("dbManagerUpdateSqlLayer")
        self.layerAction.triggered.connect(self.onUpdateSqlLayer)
        self.iface.legendInterface().addLegendLayerAction(
            self.layerAction, "", "dbManagerUpdateSqlLayer", QgsMapLayer.VectorLayer, False
        )
        for l in QgsMapLayerRegistry.instance().mapLayers().values():
            self.onLayerWasAdded(l)
        QgsMapLayerRegistry.instance().layerWasAdded.connect(self.onLayerWasAdded)
Esempio n. 11
0
    def spatialInfo(self):
        ret = []

        info = self.db.connector.getSpatialInfo()
        if not info:
            return

        tbl = [
            (QApplication.translate("DBManagerPlugin", "Oracle\
            Spatial:"),
             info[0])
        ]
        ret.append(HtmlTable(tbl))

        if not self.db.connector.has_geometry_columns:
            ret.append(
                HtmlParagraph(
                    QApplication.translate(
                        "DBManagerPlugin",
                        (u"<warning> ALL_SDO_GEOM_METADATA"
                         u" view doesn't exist!\n"
                         u"This view is essential for many"
                         u"GIS applications for enumeration of tables."))))

        return ret
Esempio n. 12
0
    def constraintsDetails(self):
        if not self.table.constraints():
            return None

        tbl = []

        # define the table header
        header = (QApplication.translate("DBManagerPlugin", "Name"),
                  QApplication.translate("DBManagerPlugin", "Type"),
                  QApplication.translate("DBManagerPlugin", "Column"),
                  QApplication.translate("DBManagerPlugin", "Status"),
                  QApplication.translate("DBManagerPlugin", "Validated"),
                  QApplication.translate("DBManagerPlugin", "Generated"),
                  QApplication.translate("DBManagerPlugin", "Check condition"),
                  QApplication.translate("DBManagerPlugin", "Foreign Table"),
                  QApplication.translate("DBManagerPlugin", "Foreign column"),
                  QApplication.translate("DBManagerPlugin", "On Delete"))
        tbl.append(HtmlTableHeader(header))

        # add table contents
        for con in self.table.constraints():
            tbl.append((con.name, con.type2String(), con.column,
                        con.status, con.validated, con.generated,
                        con.checkSource, con.foreignTable,
                        con.foreignKey, con.foreignOnDelete))

        return HtmlTable(tbl, {"class": "header"})
Esempio n. 13
0
 def privilegesDetails(self):
     details = self.db.connector.getDatabasePrivileges()
     lst = []
     if details[0]:
         lst.append(QApplication.translate("DBManagerPlugin", "create new schemas"))
     if details[1]:
         lst.append(QApplication.translate("DBManagerPlugin", "create temporary tables"))
     return HtmlList(lst)
Esempio n. 14
0
    def __unicode__(self):
        if self.query is None:
            return BaseError.__unicode__(self)

        msg = QApplication.translate("DBManagerPlugin", "Error:\n{0}").format(BaseError.__unicode__(self))
        if self.query:
            msg += QApplication.translate("DBManagerPlugin", "\n\nQuery:\n{0}").format(self.query)
        return msg
Esempio n. 15
0
 def privilegesDetails(self):
     details = self.schema.database().connector.getSchemaPrivileges(self.schema.name)
     lst = []
     if details[0]:
         lst.append(QApplication.translate("DBManagerPlugin", "create new objects"))
     if details[1]:
         lst.append(QApplication.translate("DBManagerPlugin", "access objects"))
     return HtmlList(lst)
Esempio n. 16
0
    def __unicode__(self):
        if self.query is None:
            return BaseError.__unicode__(self)

        msg = QApplication.translate("DBManagerPlugin", "Error:\n%s") % BaseError.__unicode__(self)
        if self.query:
            msg += QApplication.translate("DBManagerPlugin", "\n\nQuery:\n%s") % self.query
        return msg
Esempio n. 17
0
    def runAction(self, action):
        action = str(action)

        if action.startswith("rows/"):
            if action == "rows/count":
                self.refreshRowCount()
                return True

        elif action.startswith("triggers/"):
            parts = action.split('/')
            trigger_action = parts[1]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to %s all triggers?") % trigger_action
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Table triggers"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if trigger_action == "enable" or trigger_action == "disable":
                enable = trigger_action == "enable"
                self.aboutToChange.emit()
                self.database().connector.enableAllTableTriggers(enable, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

        elif action.startswith("trigger/"):
            parts = action.split('/')
            trigger_name = parts[1]
            trigger_action = parts[2]

            msg = QApplication.translate("DBManagerPlugin", "Do you want to %s trigger %s?") % (
                trigger_action, trigger_name)
            QApplication.restoreOverrideCursor()
            try:
                if QMessageBox.question(None, QApplication.translate("DBManagerPlugin", "Table trigger"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if trigger_action == "delete":
                self.aboutToChange.emit()
                self.database().connector.deleteTableTrigger(trigger_name, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

            elif trigger_action == "enable" or trigger_action == "disable":
                enable = trigger_action == "enable"
                self.aboutToChange.emit()
                self.database().connector.enableTableTrigger(trigger_name, enable, (self.schemaName(), self.name))
                self.refreshTriggers()
                return True

        return False
Esempio n. 18
0
 def generalInfo(self):
     tbl = [
         # ("Tables:", self.schema.tableCount)
     ]
     if self.schema.owner:
         tbl.append((QApplication.translate("DBManagerPlugin", "Owner:"), self.schema.owner))
     if self.schema.comment:
         tbl.append((QApplication.translate("DBManagerPlugin", "Comment:"), self.schema.comment))
     return HtmlTable(tbl)
Esempio n. 19
0
    def initGui(self):
        # Create action that will start plugin configuration
        self.action = QAction(QIcon(":/b4udignl.png"), \
            QApplication.translate("B4UdigNL","KLIC Viewer"), self.iface.mainWindow())
        # connect the action to the run method
        self.action.triggered.connect(self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(QApplication.translate("B4UdigNL","&KLIC Viewer"), self.action)
    def __getSettingsFromGui(self):
        self.settings.linesExplode = (self.ui.IDC_chkLinesExplode.checkState() == Qt.Checked)
        self.settings.linesMerge = (self.ui.IDC_chkLinesMerge.checkState() == Qt.Checked)
        self.settings.onlySelectedFeatures = (self.ui.IDC_chkOnlySelectedFeatures.checkState() == Qt.Checked)
        self.settings.equiDistance = self.ui.IDC_dblspinDistance.value()
        self.settings.vertexCnt = self.ui.IDC_dblspinVertexCnt.value()
        #self.settings.createHekto = (self.ui.IDC_chkCreateHekto.checkState() == Qt.Checked)
        self.settings.nodesAndVertices = (self.ui.IDC_chkNodesAndVertices.checkState() == Qt.Checked)

        self.settings.mapData.selectedLineLyr = (self.ui.IDC_cbLineLayers.itemData(self.ui.IDC_cbLineLayers.currentIndex()))

        if self.settings.onlySelectedFeatures is True and self.settings.mapData.selectedLineLyr.line.selectedFeatureCount() < 1:
            QMessageBox.warning(self.iface.mainWindow(),
                                "VoGIS-Profiltool",
                                QApplication.translate("code", u"Der gewählte Layer hat keine selektierten Elemente."))
            return False

        if self.ui.IDC_rbDigi.isChecked():
            self.settings.modeLine = enumModeLine.customLine
        elif self.ui.IDC_rbShapeLine.isChecked():
            self.settings.modeLine = enumModeLine.line
        else:
            #self.ui.IDC_rbStraigthLine
            self.settings.modeLine = enumModeLine.straightLine

        if self.ui.IDC_rbEquiDistance.isChecked():
            self.settings.modeVertices = enumModeVertices.equiDistant
        else:
            self.settings.modeVertices = enumModeVertices.vertexCnt

        if self.ui.IDC_rbStraigthLine.isChecked():
            ut = Util(self.iface)
            if ut.isFloat(self.ui.IDC_tbFromX.text(), QApplication.translate("code", "Rechtswert von")) is False:
                return False
            else:
                fromX = float(self.ui.IDC_tbFromX.text())
            if ut.isFloat(self.ui.IDC_tbFromY.text(), QApplication.translate("code", "Hochwert von")) is False:
                return False
            else:
                fromY = float(self.ui.IDC_tbFromY.text())
            if ut.isFloat(self.ui.IDC_tbToX.text(), QApplication.translate("code", "Rechtswert nach")) is False:
                return False
            else:
                toX = float(self.ui.IDC_tbToX.text())
            if ut.isFloat(self.ui.IDC_tbToY.text(), QApplication.translate("code", "Hochwert nach")) is False:
                return False
            else:
                toY = float(self.ui.IDC_tbToY.text())

            fromPnt = QgsPointXY(fromX, fromY)
            toPnt = QgsPointXY(toX, toY)

            self.settings.mapData.customLine = ut.createQgLineFeature([fromPnt, toPnt])

        return True
Esempio n. 21
0
    def type2String(self):
        if self.type == ORTableConstraint.TypeCheck:
            return QApplication.translate("DBManagerPlugin", "Check")
        if self.type == ORTableConstraint.TypePrimaryKey:
            return QApplication.translate("DBManagerPlugin", "Primary key")
        if self.type == ORTableConstraint.TypeForeignKey:
            return QApplication.translate("DBManagerPlugin", "Foreign key")
        if self.type == ORTableConstraint.TypeUnique:
            return QApplication.translate("DBManagerPlugin", "Unique")

        return QApplication.translate("DBManagerPlugin", 'Unknown')
Esempio n. 22
0
    def removeActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            res = QMessageBox.question(parent, QApplication.translate("DBManagerPlugin", "hey!"),
                                       QApplication.translate("DBManagerPlugin",
                                                              "Really remove connection to %s?") % item.connectionName(),
                                       QMessageBox.Yes | QMessageBox.No)
            if res != QMessageBox.Yes:
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.remove()
Esempio n. 23
0
    def unload(self):
        # Remove the plugin menu item and icon
        if hasattr(self.iface, 'removePluginDatabaseMenu'):
            self.iface.removePluginDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)
        else:
            self.iface.removePluginMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)
        if hasattr(self.iface, 'removeDatabaseToolBarIcon'):
            self.iface.removeDatabaseToolBarIcon(self.action)
        else:
            self.iface.removeToolBarIcon(self.action)

        if self.dlg is not None:
            self.dlg.close()
Esempio n. 24
0
    def spatialInfo(self):
        ret = []
        if self.table.geomType is None:
            return ret

        tbl = [
            (QApplication.translate("DBManagerPlugin", "Column:"), self.table.geomColumn),
            (QApplication.translate("DBManagerPlugin", "Geometry:"), self.table.geomType)
        ]

        # only if we have info from geometry_columns
        if self.table.geomDim:
            tbl.append((QApplication.translate("DBManagerPlugin", "Dimension:"), self.table.geomDim))

        srid = self.table.srid if self.table.srid is not None else -1
        sr_info = self.table.database().connector.getSpatialRefInfo(srid) if srid != -1 else QApplication.translate(
            "DBManagerPlugin", "Undefined")
        if sr_info:
            tbl.append((QApplication.translate("DBManagerPlugin", "Spatial ref:"), u"%s (%d)" % (sr_info, srid)))

        # estimated extent
        if not self.table.isView:
            if self.table.estimatedExtent is None:
                # estimated extent information is not displayed yet, so just block
                # table signals to avoid double refreshing (infoViewer->refreshEstimatedExtent->tableChanged->infoViewer)
                self.table.blockSignals(True)
                self.table.refreshTableEstimatedExtent()
                self.table.blockSignals(False)

            if self.table.estimatedExtent is not None and self.table.estimatedExtent[0] is not None:
                estimated_extent_str = '%.5f, %.5f - %.5f, %.5f' % self.table.estimatedExtent
                tbl.append((QApplication.translate("DBManagerPlugin", "Estimated extent:"), estimated_extent_str))

        # extent
        if self.table.extent is not None and self.table.extent[0] is not None:
            extent_str = '%.5f, %.5f - %.5f, %.5f' % self.table.extent
        else:
            extent_str = QApplication.translate("DBManagerPlugin",
                                                '(unknown) (<a href="action:extent/get">find out</a>)')
        tbl.append((QApplication.translate("DBManagerPlugin", "Extent:"), extent_str))

        ret.append(HtmlTable(tbl))

        # is there an entry in geometry_columns?
        if self.table.geomType.lower() == 'geometry':
            ret.append(HtmlParagraph(
                QApplication.translate("DBManagerPlugin", "<warning> There is no entry in geometry_columns!")))

        # find out whether the geometry column has spatial index on it
        if not self.table.isView:
            if not self.table.hasSpatialIndex():
                ret.append(HtmlParagraph(QApplication.translate("DBManagerPlugin",
                                                                '<warning> No spatial index defined (<a href="action:spatialindex/create">create it</a>)')))

        return ret
Esempio n. 25
0
 def writeHeader(self, selectedRasters, hekto, attribs, delimiter):
     #Profillaenge;Segmentlaenge;Rechtswert;Hochwert;
     #"Laser - Hoehenmodell Oberflaeche 1m";"Laser Hoehenmodell Gelaende1m";
     #Profilnummer;Segmentnummer;Punktnummer;Punktklasse;
     #Hektometer
     #ATTRIBUTE
     hdr_prof_len = QApplication.translate('code', 'Profillaenge')
     hdr_seg_len = QApplication.translate('code', 'Segmentlaenge')
     hdr_xval = QApplication.translate('code', 'Rechtswert')
     hdr_yval = QApplication.translate('code', 'Hochwert')
     hdr_prof_nr = QApplication.translate('code', 'Profilnummer')
     hdr_seg_nr = QApplication.translate('code', 'Segmentnummer')
     hdr_pnt_nr = QApplication.translate('code', 'Punktnummer')
     hdr_pnt_class = QApplication.translate('code', 'Punktklasse')
     hdr = '{1}{0}{2}{0}{3}{0}{4}'.format(delimiter, hdr_prof_len, hdr_seg_len, hdr_xval, hdr_yval)
     for r in selectedRasters:
         hdr += '{0}"{1}"'.format(delimiter, r.name)
     hdr += '{0}{1}{0}{2}{0}{3}{0}{4}'.format(delimiter, hdr_prof_nr, hdr_seg_nr, hdr_pnt_nr, hdr_pnt_class)
     if hekto is True:
         hdr += '{0}{1}'.format(delimiter, 'Hektometer')
     if attribs is True:
         for fldName in self.segments[0].vertices[0].attribNames:
             hdr += '{0}{1}'.format(delimiter, fldName)
     #hdr += '\r\n'
     #hdr += os.linesep
     hdr += '\n'
     return hdr
Esempio n. 26
0
    def writeArrayHeader(self, selectedRasters, hekto, attribs):
        """ Kopfzeile fuer Excel        """
        #Profillaenge;Segmentlaenge;Rechtswert;Hochwert;
        #"Laser - Hoehenmodell Oberflaeche 1m";"Laser Hoehenmodell Gelaende1m";
        #Profilnummer;Segmentnummer;Punktnummer;Punktklasse;
        #Hektometer
        #ATTRIBUTE
        hdr_prof_len = QApplication.translate('code', 'Profillaenge')
        hdr_seg_len = QApplication.translate('code', 'Segmentlaenge')
        hdr_xval = QApplication.translate('code', 'Rechtswert')
        hdr_yval = QApplication.translate('code', 'Hochwert')
        hdr_prof_nr = QApplication.translate('code', 'Profilnummer')
        hdr_seg_nr = QApplication.translate('code', 'Segmentnummer')
        hdr_pnt_nr = QApplication.translate('code', 'Punktnummer')
        hdr_pnt_class = QApplication.translate('code', 'Punktklasse')

        hdr = []
        hdr.append(hdr_prof_len)
        hdr.append(hdr_seg_len)
        hdr.append(hdr_xval)
        hdr.append(hdr_yval)
        for r in selectedRasters:
            hdr.append(r.name)
        hdr.append(hdr_prof_nr)
        hdr.append(hdr_seg_nr)
        hdr.append(hdr_pnt_nr)
        hdr.append(hdr_pnt_class)
        if hekto is True:
            hdr.append('Hektometer')
        if attribs is True:
            for fldName in self.segments[0].vertices[0].attribNames:
                hdr.append(fldName)
        return hdr
Esempio n. 27
0
 def initGui(self):
     self.action = QAction(QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin", "DB Manager"),
                           self.iface.mainWindow())
     self.action.setObjectName("dbManager")
     self.action.triggered.connect(self.run)
     # Add toolbar button and menu item
     if hasattr(self.iface, 'addDatabaseToolBarIcon'):
         self.iface.addDatabaseToolBarIcon(self.action)
     else:
         self.iface.addToolBarIcon(self.action)
     if hasattr(self.iface, 'addPluginToDatabaseMenu'):
         self.iface.addPluginToDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)
     else:
         self.iface.addPluginToMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action)
 def __signal_webViewMap_loadFinished(self, ok):
     if ok is False:
         QMessageBox.warning(self, QApplication.translate(
             "OpenLayersOverviewWidget", "OpenLayers Overview"),
                             QApplication.translate(
                                 "OpenLayersOverviewWidget",
                                 "Error loading page!"))
     else:
         # wait until OpenLayers map is ready
         self.__checkMapReady()
     self.lbStatusRead.setVisible(False)
     self.webViewMap.setVisible(True)
     self.webViewMap.page().mainFrame().loadFinished.disconnect(
         self.__signal_webViewMap_loadFinished)
Esempio n. 29
0
    def indexesDetails(self):
        if not self.table.indexes():
            return None

        tbl = []

        # define the table header
        header = (QApplication.translate("DBManagerPlugin", "Name"),
                  QApplication.translate("DBManagerPlugin", "Column(s)"),
                  QApplication.translate("DBManagerPlugin", "Index Type"),
                  QApplication.translate("DBManagerPlugin", "Status"),
                  QApplication.translate("DBManagerPlugin", "Last analyzed"),
                  QApplication.translate("DBManagerPlugin", "Compression"),
                  QApplication.translate("DBManagerPlugin", "Uniqueness"),
                  QApplication.translate("DBManagerPlugin", "Action"))
        tbl.append(HtmlTableHeader(header))

        # add table contents
        for idx in self.table.indexes():
            # get the fields the index is defined on
            tbl.append((idx.name, idx.column, idx.indexType,
                        idx.status, idx.analyzed, idx.compression,
                        idx.isUnique,
                        (u'<a href="action:index/{}/rebuild">Rebuild'
                         u"""</a>""".format(idx.name))))

        return HtmlTable(tbl, {"class": "header"})
Esempio n. 30
0
    def _opendb(self):

        # Keep this explicit assignment to None to make sure the file is
        # properly closed before being re-opened
        self.gdal_ds = None
        self.gdal_ds = gdal.OpenEx(self.dbname, gdal.OF_UPDATE)
        if self.gdal_ds is None:
            self.gdal_ds = gdal.OpenEx(self.dbname)
        if self.gdal_ds is None:
            raise ConnectionError(QApplication.translate("DBManagerPlugin", '"{0}" not found').format(self.dbname))
        if self.gdal_ds.GetDriver().ShortName != 'GPKG':
            raise ConnectionError(QApplication.translate("DBManagerPlugin", '"{dbname}" not recognized as GPKG ({shortname} reported instead.)').format(dbname=self.dbname, shortname=self.gdal_ds.GetDriver().ShortName))
        self.has_raster = self.gdal_ds.RasterCount != 0 or self.gdal_ds.GetMetadata('SUBDATASETS') is not None
        self.connection = None
        self._current_thread = None
Esempio n. 31
0
    def __init__(self, uri):
        DBConnector.__init__(self, uri)

        self.dbname = uri.database()
        if not QFile.exists(self.dbname):
            raise ConnectionError(
                QApplication.translate("DBManagerPlugin",
                                       '"{0}" not found').format(self.dbname))

        try:
            self.connection = sqlite.connect(self._connectionInfo())

        except self.connection_error_types() as e:
            raise ConnectionError(e)

        self._checkSpatial()
        self._checkRaster()
        self._checkGeopackage()
Esempio n. 32
0
    def validate(self):
        """
        Check user configuration and validate if they are correct.
        :return: Returns True if user configuration is correct, otherwise
        False.
        :rtype: bool
        """
        if not self.cbo_lookup.currentText():
            msg = QApplication.translate(
                'LookupDialog',
                'Please select the referenced lookup table.'
            )
            self._notif_bar.clear()
            self._notif_bar.insertWarningNotification(msg)

            return False

        return True
Esempio n. 33
0
    def _load_lookup_tables(self):
        # Load lookup table names
        c_profile = self._current_profile
        if c_profile is None:
            msg = QApplication.translate(
                'LookupDialog',
                'Current profile could not be determined.'
            )
            self._notif_bar.clear()
            self._notif_bar.insertErrorNotification(msg)

            return

        lookups = [e.name for e in c_profile.value_lists()]

        self.cbo_lookup.clear()
        self.cbo_lookup.addItem('')
        self.cbo_lookup.addItems(lookups)
Esempio n. 34
0
    def triggersDetails(self):
        if not self.table.triggers():
            return None

        ret = []

        tbl = []
        # define the table header
        header = (
            QApplication.translate("DBManagerPlugin", "Name"),
            QApplication.translate("DBManagerPlugin", "Event"),
            QApplication.translate("DBManagerPlugin", "Type"),
            QApplication.translate("DBManagerPlugin", "Enabled"))
        tbl.append(HtmlTableHeader(header))

        # add table contents
        for trig in self.table.triggers():
            name = (u"""{0} (<a href="action:trigger/"""
                    u"""{0}/{1}">{1}</a>)""".format(trig.name, "delete"))

            if trig.enabled == u"ENABLED":
                enabled, action = (
                    QApplication.translate("DBManagerPlugin", "Yes"),
                    u"disable")
            else:
                enabled, action = (
                    QApplication.translate("DBManagerPlugin", "No"),
                    "enable")

            txt_enabled = (u"""{0} (<a href="action:trigger/"""
                           u"""{1}/{2}">{2}</a>)""".format(
                               enabled, trig.name, action))

            tbl.append((name, trig.event, trig.type, txt_enabled))

        ret.append(HtmlTable(tbl, {"class": "header"}))

        ret.append(
            HtmlParagraph(
                QApplication.translate(
                    "DBManagerPlugin",
                    (u'<a href="action:triggers/enable">'
                     u'Enable all triggers</a> / '
                     u'<a href="action:triggers/disable">'
                     u'Disable all triggers</a>'))))

        return ret
Esempio n. 35
0
    def _loadTablePreview(self, table, limit=False):
        """ if has geometry column load to map canvas """
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.setRenderFlag(False)
        vl = None

        if table and table.geomType:
            # limit the query result if required
            if limit and table.rowCount > 1000:
                uniqueField = table.getValidQGisUniqueFields(True)
                if uniqueField is None:
                    self.parent.tabs.setCurrentWidget(self.parent.info)
                    self.parent.infoBar.pushMessage(
                        QApplication.translate("DBManagerPlugin", "Unable to find a valid unique field"),
                        QgsMessageBar.WARNING, self.parent.iface.messageTimeout())
                    return

                uri = table.database().uri()
                uri.setDataSource("", u"(SELECT * FROM %s LIMIT 1000)" % table.quotedName(), table.geomColumn, "",
                                  uniqueField.name)
                provider = table.database().dbplugin().providerName()
                vl = QgsVectorLayer(uri.uri(False), table.name, provider)
            else:
                vl = table.toMapLayer()

            if not vl.isValid():
                vl.deleteLater()
                vl = None

        # remove old layer (if any) and set new
        if self.currentLayer:
            QgsMapLayerRegistry.instance().removeMapLayers([self.currentLayer.id()])

        if vl:
            self.setLayerSet([QgsMapCanvasLayer(vl)])
            QgsMapLayerRegistry.instance().addMapLayers([vl], False)
            self.zoomToFullExtent()
        else:
            self.setLayerSet([])

        self.currentLayer = vl

        self.setRenderFlag(True)
        QApplication.restoreOverrideCursor()
Esempio n. 36
0
    def _loadTablePreview(self, table, limit=False):
        """ if has geometry column load to map canvas """
        with OverrideCursor(Qt.WaitCursor):
            self.freeze()
            vl = None

            if table and table.geomType:
                # limit the query result if required
                if limit and table.rowCount > 1000:
                    uniqueField = table.getValidQgisUniqueFields(True)
                    if uniqueField is None:
                        self.parent.tabs.setCurrentWidget(self.parent.info)
                        self.parent.infoBar.pushMessage(
                            QApplication.translate(
                                "DBManagerPlugin",
                                "Unable to find a valid unique field"),
                            Qgis.Warning, self.parent.iface.messageTimeout())
                        return

                    uri = table.database().uri()
                    uri.setDataSource(
                        "",
                        u"(SELECT * FROM %s LIMIT 1000)" % table.quotedName(),
                        table.geomColumn, "", uniqueField.name)
                    provider = table.database().dbplugin().providerName()
                    vl = QgsVectorLayer(uri.uri(False), table.name, provider)
                else:
                    vl = table.toMapLayer()

                if vl and not vl.isValid():
                    vl.deleteLater()
                    vl = None

            if vl and vl.isValid():
                self.current_layer = vl
                self.setLayers([self.current_layer])
                self.zoomToFullExtent()
            else:
                self.setLayers([])
                self.current_layer = None

            self.freeze(False)
            super().refresh()
Esempio n. 37
0
    def apply(self):
        """
        Persists the settings specified by the user.
        """
        for s in self._settings_mappers:
            if s.is_mandatory() and s.valueHandler().supportsMandatory():
                if s.valueHandler().value() == s.valueHandler().default():
                    # Notify user
                    msg = WARNING, "{0} is a required setting.".format(s.setting_key())
                    self.notified.emit([msg])

                    break

            s.bind_configuration_value()

        msg = SUCCESS, QApplication.translate("SettingsWidgetMapper",
                                              "%s settings successfully updated." % (
                                              self._capitalize_first_char(self._context),))
        self.notified.emit([msg])
Esempio n. 38
0
    def composer_data_source(self, template_document):
        """
        :param template_document: Document containing document composition
        information.
        :type template_document: QDomDocument
        :return: Returns the data source defined in the template document.
        :rtype: ComposerDataSource
        """
        composer_ds = ComposerDataSource.create(template_document)

        if not self.data_source_exists(composer_ds):
            msg = QApplication.translate("DocumentGenerator",
                                             "'{0}' data source does not exist in the database."
                                             "\nPlease contact your database "
                                             "administrator.".format(composer_ds.name()))

            return None, msg

        return composer_ds, ""
Esempio n. 39
0
    def _editTemplate(self, templatePath, newName):
        """
        Updates the template document to use the new name.
        """
        templateFile = QFile(templatePath)

        if not templateFile.open(QIODevice.ReadOnly):
            QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Open Operation Error"), \
                                 "{0}\n{1}".format(
                                     QApplication.translate("TemplateDocumentSelector", "Cannot read template file."), \
                                     templateFile.errorString()
                                 ))
            return (False, "")

        templateDoc = QDomDocument()

        if templateDoc.setContent(templateFile):
            composerElement = templateDoc.documentElement()
            titleAttr = composerElement.attributeNode("_title")
            if not titleAttr.isNull():
                titleAttr.setValue(newName)

            # Try remove file
            status = templateFile.remove()

            if not status:
                return (False, "")

            # Create new file
            newTemplatePath = self._composerTemplatesPath(
            ) + "/" + newName + ".sdt"
            newTemplateFile = QFile(newTemplatePath)

            if not newTemplateFile.open(QIODevice.WriteOnly):
                QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Save Operation Error"), \
                                     "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector",
                                                                              "Could not save template file."), \
                                                       newTemplateFile.errorString()
                                                       ))
                return (False, "")

            if newTemplateFile.write(templateDoc.toByteArray()) == -1:
                QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Save Error"), \
                                     QApplication.translate("TemplateDocumentSelector",
                                                            "Could not save template file."))
                return (False, "")

            newTemplateFile.close()

            return (True, newTemplatePath)
Esempio n. 40
0
    def spatial_unit_layer(self, spatial_unit, active_layer):
        """
        Check whether the layer is parcel layer or not.
        :param active_layer: The layer to be checked
        :type QGIS vectorlayer
        :return: Boolean
        """
        if self.active_layer_check():
            for _, layer in QgsProject.instance().mapLayers().items():
                layer_source = self.get_layer_source(layer)
                if layer_source == spatial_unit.name:
                    self.iface().setActiveLayer(layer)
                    return True

            not_sp_msg = QApplication.translate(
                'SpatialPreview',
                'You have selected a non-spatial_unit layer. '
                'Please select a spatial unit layer to preview.')
            QMessageBox.information(self._iface.mainWindow(), "Error",
                                    not_sp_msg)
Esempio n. 41
0
    def accept_action(self):
        """
        A slot raised when the user clicks on the Accept button.
        :return: None
        :rtype: NoneType
        """
        if not self.checkBoxAgree.isChecked():
            msg = QApplication.translate(
                'LicenseAgreement', 'To use STDM, please accept the terms '
                'and conditions by selecting'
                ' the checkbox "I have read and agree ..."')

            self.notice_bar.clear()
            self.notice_bar.insertNotification(msg, ERROR)
            return

        else:
            self.reg_config.write({SHOW_LICENSE: 0})
            self.accepted = True
            self.close()
Esempio n. 42
0
    def load(self):
        """
        Loads the spatial overlay page into the QWebView.
        This method is only called once on initializing the view. Subsequent object calls
        are made to the 'addOverlay' method.
        """
        if not QFile.exists(self.url()[0]):
            errmsg = QApplication.translate(
                "WebSpatialLoader", "The source HTML file could not be found.")
            self.loadError.emit(errmsg)

            return

        self.olPage.mainFrame().load(QUrl(self.url()[1]))
        self.webview.setPage(self.olPage)
        try:
            self.olPage.mainFrame().javaScriptWindowObjectCleared.disconnect()
        except TypeError:
            pass
        self.olPage.mainFrame().javaScriptWindowObjectCleared.connect(
            self._populate_js_window_object)
Esempio n. 43
0
    def triggersDetails(self):
        if self.table.triggers() is None or len(self.table.triggers()) <= 0:
            return None

        ret = []

        tbl = []
        # define the table header
        header = (QApplication.translate("DBManagerPlugin", "Name"),
                  QApplication.translate("DBManagerPlugin", "Function"),
                  QApplication.translate("DBManagerPlugin", "Type"),
                  QApplication.translate("DBManagerPlugin", "Enabled"))
        tbl.append(HtmlTableHeader(header))

        # add table contents
        for trig in self.table.triggers():
            name = u'%(name)s (<a href="action:trigger/%(name)s/%(action)s">%(action)s</a>)' % {
                "name": trig.name,
                "action": "delete"
            }

            (enabled,
             action) = (QApplication.translate("DBManagerPlugin", "Yes"),
                        "disable") if trig.enabled else (
                            QApplication.translate("DBManagerPlugin", "No"),
                            "enable")
            txt_enabled = u'%(enabled)s (<a href="action:trigger/%(name)s/%(action)s">%(action)s</a>)' % {
                "name": trig.name,
                "action": action,
                "enabled": enabled
            }

            tbl.append((name, trig.function, trig.type2String(), txt_enabled))

        ret.append(HtmlTable(tbl, {"class": "header"}))

        ret.append(
            HtmlParagraph(
                QApplication.translate(
                    "DBManagerPlugin",
                    '<a href="action:triggers/enable">Enable all triggers</a> / <a href="action:triggers/disable">Disable all triggers</a>'
                )))
        return ret
Esempio n. 44
0
    def _load_translator_dialog(self, config_key):
        """
        Load translator dialog.
        """
        dest_column = self._selected_destination_column()
        src_column = self._selected_source_column()

        if dest_column:
            # Check if there is an existing dialog in the manager
            trans_dlg = self._trans_widget_mgr.translator_widget(dest_column)

            if trans_dlg is None:
                trans_config = ValueTranslatorConfig.translators.get(config_key, None)

                # Safety precaution
                if trans_config is None:
                    return

                try:
                    trans_dlg = trans_config.create(
                        self,
                        self._source_columns(),
                        self.targetTab,
                        dest_column,
                        src_column
                    )

                except RuntimeError as re:
                    QMessageBox.critical(
                        self,
                        QApplication.translate(
                            'ImportData',
                            'Value Translator'
                        ),
                        str(re)
                    )

                    return

            self._handle_translator_dlg(dest_column, trans_dlg)
Esempio n. 45
0
    def validateInput(self):
        '''
        Assert whether required fields have been entered
        '''
        if str(self.txtUserName.text()) == "":
            QMessageBox.critical(
                self, QApplication.translate("newUserDlg", "Required field"),
                QApplication.translate("LoginDialog",
                                       "UserName cannot be empty"))
            self.txtUserName.setFocus()
            return False

        if str(self.txtPass.text()) == "":
            QMessageBox.critical(
                self, QApplication.translate("newUserDlg", "Required field"),
                QApplication.translate("newUserDlg",
                                       "Password cannot be empty"))
            self.txtPass.setFocus()
            return False

        if str(self.txtConfirmPass.text()) == "":
            QMessageBox.critical(
                self, QApplication.translate("newUserDlg", "Required field"),
                QApplication.translate("newUserDlg",
                                       "Confirm Password cannot be empty"))
            self.txtConfirmPass.setFocus()
            return False

        if self.txtPass.text() != self.txtConfirmPass.text():
            QMessageBox.critical(
                self, QApplication.translate("newUserDlg", "Password Compare"),
                QApplication.translate("newUserDlg", "Passwords do not match"))
            self.txtConfirmPass.setFocus()
            return False

        else:
            return True
Esempio n. 46
0
    def onEditTemplate(self):
        """
        Slot raised to edit document template.
        """
        self.notifBar.clear()

        if self.documentMapping() is None:
            self.notifBar.insertErrorNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "Please select a document template to edit"))
            return

        templateName, filePath = self.documentMapping()

        docName, ok = QInputDialog.getText(self, \
                                           QApplication.translate("TemplateDocumentSelector", "Edit Template"), \
                                           QApplication.translate("TemplateDocumentSelector",
                                                                  "Please enter the new template name below"), \
                                           text=templateName)
        if ok and docName == "":
            self.notifBar.insertErrorNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                         "Template name cannot be empty"))
            return

        elif docName == templateName:
            return

        elif ok and docName != "":
            result, newTemplatePath = self._editTemplate(filePath, docName)

            if result:
                # Update view
                mIndices = self._selectedMappings()

                docNameItem = self._docItemModel.itemFromIndex(mIndices[0])
                filePathItem = self._docItemModel.itemFromIndex(mIndices[1])

                docNameItem.setText(docName)
                filePathItem.setText(newTemplatePath)

                self.notifBar.insertSuccessNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                               "'{0}' template has been successfully updated".format(
                                                                                   docName)))

            else:
                self.notifBar.insertErrorNotification(QApplication.translate("TemplateDocumentSelector", \
                                                                             "Error: '{0}' template could not be updated".format(
                                                                                 templateName)))
Esempio n. 47
0
    def initGui(self):
        '''
        Set control properties
        '''
        # Set properties for 'Users' button box
        btnUserNew = self.btnManageUsers.button(QDialogButtonBox.Ok)
        btnUserNew.setText(QApplication.translate("manageAccountsDlg", "New") + "...")
        btnUserNew.clicked.connect(self.onNewUser)

        btnUserEdit = self.btnManageUsers.button(QDialogButtonBox.Save)
        btnUserEdit.setText(QApplication.translate("manageAccountsDlg", "Edit"))
        btnUserEdit.clicked.connect(self.onEditUser)

        btnUserDelete = self.btnManageUsers.button(QDialogButtonBox.Cancel)
        btnUserDelete.setText(QApplication.translate("manageAccountsDlg", "Delete"))
        btnUserDelete.clicked.connect(self.onDeleteUser)

        # Set properties for 'Roles' button box
        btnRoleNew = self.btnManageRoles.button(QDialogButtonBox.Ok)
        btnRoleNew.setText(QApplication.translate("manageAccountsDlg", "New") + "...")
        btnRoleNew.clicked.connect(self.onNewRole)

        btnRoleDelete = self.btnManageRoles.button(QDialogButtonBox.Cancel)
        btnRoleDelete.setText(QApplication.translate("manageAccountsDlg", "Delete"))
        btnRoleDelete.clicked.connect(self.onDeleteRole)

        btnRoleSync = self.btnManageRoles.button(QDialogButtonBox.Apply)
        btnRoleSync.setText(QApplication.translate("manageAccountsDlg", "Sync"))
        btnRoleSync.setToolTip(
            QApplication.translate("manageAccountsDlg", "Synchronize STDM roles with database roles"))
        btnRoleSync.clicked.connect(self.onSyncRoles)

        # Data view signals
        self.lstRoles.clicked.connect(self.onRoleSelected)
        self.lstRoles.activated.connect(self.onRoleSelected)
        self.lstMappingRoles.clicked.connect(self.onRoleMappingSelected)
        self.lstMappingRoles.activated.connect(self.onRoleMappingSelected)
        self.lstMappingUsers.clicked.connect(self.onUserMappingSelected)
        self.lstMappingUsers.activated.connect(self.onUserMappingSelected)

        # Disable any action by the user in the user roles mapping list view
        self.lstMappingUsers.setEnabled(False)
Esempio n. 48
0
    def acceptdlg(self):
        '''
        On user clicking the create user button
        '''
        if self.validateInput():

            member = Membership()

            try:
                if self._setUser() == 'NEW':
                    member.createUser(self.user)
                else:
                    member.update_user(self.user)

                self.accept()

            except SecurityException as se:
                QMessageBox.critical(
                    self,
                    QApplication.translate("newUserDlg", "Create User Error"),
                    str(se))
                self.user = None
Esempio n. 49
0
    def _insert_metadata_info(self):
        # Insert version and build numbers respectively.
        if not self._metadata is None:
            installed_version = self._metadata.get('version_installed', None)
        else:
            installed_version = version_from_metadata()

        if installed_version is None:
            return

        cursor = self.txtAbout.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertBlock()
        cursor.insertBlock()

        # Insert installed version text
        version_msg = QApplication.translate('AboutSTDMDialog', 'STDM version')
        version_text = '{0} {1}'.format(version_msg, installed_version)
        char_format = cursor.blockCharFormat()
        text_format = QTextCharFormat(char_format)
        text_format.setFontWeight(75)
        cursor.insertText(version_text, text_format)
Esempio n. 50
0
    def __init__(self, config, treeview, parent=None):

        super(EntityNodeFormatter, self).__init__(config, treeview, parent)

        prefix = self.curr_profile.prefix
        self._str_ref = str(prefix) + "_social_tenure_relationship"

        self._str_title = QApplication.translate("STRFormatterBase",
                                                 "Social Tenure Relationship")

        self._str_model, self._str_doc_model = entity_model(
            self.curr_profile.social_tenure, False, True)
        # Cache for entity supporting document tables.
        # [table_name]:[list of supporting document tables]
        self._entity_supporting_doc_tables = {}

        self._str_model_disp_mapping = {}
        if self._str_model is not None:
            self._str_model_disp_mapping = entity_display_columns(
                self.curr_profile.social_tenure, True)

        self._fk_references = [
            (e.entity_relation.child_column, e.entity_relation.parent.name,
             e.entity_relation.parent_column)
            for e in list(self.curr_profile.social_tenure.columns.values())
            if e.TYPE_INFO == 'FOREIGN_KEY'
        ]

        self._str_num_char_cols = entity_display_columns(
            self.curr_profile.social_tenure)

        self._current_data_source_fk_ref = self._current_data_source_foreign_key_reference(
        )
        # numeric_char_cols for entities - party and sp_unit
        self._numeric_char_cols = entity_display_columns(
            self.curr_profile.entity_by_name(config.data_source_name))
        self._spatial_data_sources = list(
            profile_spatial_tables(self.curr_profile).keys())
Esempio n. 51
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        self._vboxLayout = QVBoxLayout(self)
        self._vboxLayout.setMargin(0)

        self._cboItem = QComboBox(self)
        self._cboItem.setMinimumSize(QSize(0, 30))
        self._vboxLayout.addWidget(self._cboItem)

        self._txtOther = QLineEdit(self)
        self._txtOther.setMinimumSize(QSize(0, 30))
        self._txtOther.setVisible(False)
        self._vboxLayout.addWidget(self._txtOther)

        # We are using random text here so that the custom line edit is not shown on selecting a blank item in the list.
        self._activatorText = QApplication.translate("ComboBoxWithOther",
                                                     "Other")

        # Connect signals
        self._cboItem.currentIndexChanged[str].connect(
            self.onComboIndexChanged)
Esempio n. 52
0
 def __init__(self):
     """
     Initialize the STR component class.
     """
     super(ComponentUtility, self).__init__()
     self.current_profile = current_profile()
     self.social_tenure = self.current_profile.social_tenure
     self.parties = self.social_tenure.parties
     self.spatial_units = self.social_tenure.spatial_units
     self.str_model = None
     self.str_doc_model = None
     if len(self.parties) > 0:
         self.party_1 = self.parties[0]
     if len(self.spatial_units) > 0:
         self.spatial_unit_1 = self.spatial_units[0]
     try:
         self.str_model, self.str_doc_model = entity_model(
             self.social_tenure, False, True)
     except DummyException as ex:
         QMessageBox.critical(
             iface.mainWindow(),
             QApplication.translate('ComponentUtility', 'Database Error'),
             str(ex))
Esempio n. 53
0
    def validate_text(self, text):
        """
        Validates and updates the entered text if necessary.
        Spaces are replaced by _ and capital letters are replaced by small.
        :param text: The text entered
        :type text: String
        """
        text_edit = self.sender()
        cursor_position = text_edit.cursorPosition()
        text_edit.setValidator(None)
        if len(text) == 0:
            return
        locale = (QSettings().value("locale/userLocale") or 'en-US')[0:2]

        name_regex = QRegExp('^(?=.{0,40}$)[ _a-zA-Z][a-zA-Z0-9_ ]*$')
        name_validator = QRegExpValidator(name_regex)
        text_edit.setValidator(name_validator)
        QApplication.processEvents()
        last_character = text[-1:]
        state = name_validator.validate(text, text.index(last_character))[0]
        msg = QApplication.translate('EntityEditor',
                                     'is not allowed at this position.')

        if state != QValidator.Acceptable:
            self.show_notification('"{}" {}'.format(last_character, msg))
            text = text[:-1]

        # remove space and underscore at the beginning of the text
        if len(text) > 1:
            if text[0] == ' ' or text[0] == '_':
                text = text[1:]

        self.blockSignals(True)
        text_edit.setText(text)
        text_edit.setCursorPosition(cursor_position)
        self.blockSignals(False)
        text_edit.setValidator(None)
Esempio n. 54
0
    def __init__(self, showSearch=True):
        super(ConfigDialog, self).__init__(None)
        self.setupUi(self)

        self.groupIcon = QgsApplication.getThemeIcon('mIconFolder.svg')

        self.model = QStandardItemModel()
        self.tree.setModel(self.model)

        self.delegate = SettingDelegate()
        self.tree.setItemDelegateForColumn(1, self.delegate)

        if showSearch:
            if hasattr(self.searchBox, 'setPlaceholderText'):
                self.searchBox.setPlaceholderText(QApplication.translate('ConfigDialog', 'Search…'))
            self.searchBox.textChanged.connect(self.textChanged)
        else:
            self.searchBox.hide()

        self.fillTree()

        self.saveMenus = False
        self.tree.expanded.connect(self.itemExpanded)
        self.auto_adjust_columns = True
    def profiles_finished(self, profiles, intersections, cadastre):
        QApplication.restoreOverrideCursor()
        self.ui.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        self.thread.quit()
        self.thread.wait()

        #QGIS 2.0 http://gis.stackexchange.com/a/58754 http://gis.stackexchange.com/a/57090
        self.iface.mainWindow().statusBar().showMessage(
            "VoGIS-Profiltool, {0} Profile".format(len(profiles)))
        QgsMessageLog.logMessage("Profile Count: {0}".format(len(profiles)),
                                 "VoGis", Qgis.Info)

        if len(profiles) < 1:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(
                self.iface.mainWindow(), "VoGIS-Profiltool",
                QApplication.translate(
                    "code", "Es konnten keine Profile erstellt werden."))
            return

        dlg = VoGISProfilToolPlotDialog(self.iface, self.settings, profiles,
                                        intersections, cadastre)
        dlg.show()
        dlg.exec_()
Esempio n. 56
0
    def format_display(self):
        # Display based on the configured display columns.
        if self.current_item is None:
            return
        QApplication.processEvents()
        display_value = RelatedEntityLineEdit.process_display(
            self.column,
            self.current_item
        )
        try:
            self.setText(display_value)
        except RuntimeError:

            QMessageBox.warning(
                None,
                QApplication.translate(
                    'AdministrativeUnitLineEdit',
                    "Attribute Table Error"
                ),
                'The change is not saved. '
                'Please use the form to edit data.'
            )
        except TypeError:
            pass
Esempio n. 57
0
    def generalInfo(self):
        if self.table.rowCount is None:
            # row count information is not displayed yet, so just block
            # table signals to avoid double refreshing (infoViewer->refreshRowCount->tableChanged->infoViewer)
            self.table.blockSignals(True)
            self.table.refreshRowCount()
            self.table.blockSignals(False)

        tbl = [(QApplication.translate("DBManagerPlugin", "Relation type:"),
                QApplication.translate("DBManagerPlugin", "View")
                if self.table.isView else QApplication.translate(
                    "DBManagerPlugin", "Table")),
               (QApplication.translate("DBManagerPlugin",
                                       "Rows:"), self.table.rowCount
                if self.table.rowCount is not None else QApplication.translate(
                    "DBManagerPlugin",
                    'Unknown (<a href="action:rows/count">find out</a>)'))]
        if self.table.comment:
            tbl.append(
                (QApplication.translate("DBManagerPlugin",
                                        "Comment:"), self.table.comment))

        return HtmlTable(tbl)
Esempio n. 58
0
from processing.gui.MessageDialog import MessageDialog
from processing.gui.AlgorithmDialog import AlgorithmDialog
from qgis.utils import iface
from qgis.core import QgsApplication, QgsMessageLog, QgsStringUtils, QgsProcessingAlgorithm
from qgis.gui import QgsGui
from processing.gui.MessageBarProgress import MessageBarProgress
from processing.gui.AlgorithmExecutor import execute
from processing.gui.Postprocessing import handleAlgorithmResults
from processing.core.Processing import Processing
from processing.tools import dataobjects

algorithmsToolbar = None
menusSettingsGroup = 'Menus'

defaultMenuEntries = {}
vectorMenu = QApplication.translate('MainWindow', 'Vect&or')
analysisToolsMenu = vectorMenu + "/" + Processing.tr('&Analysis Tools')
defaultMenuEntries.update({'qgis:distancematrix': analysisToolsMenu,
                           'qgis:sumlinelengths': analysisToolsMenu,
                           'qgis:countpointsinpolygon': analysisToolsMenu,
                           'qgis:listuniquevalues': analysisToolsMenu,
                           'qgis:basicstatisticsforfields': analysisToolsMenu,
                           'qgis:nearestneighbouranalysis': analysisToolsMenu,
                           'native:meancoordinates': analysisToolsMenu,
                           'native:lineintersections': analysisToolsMenu})
researchToolsMenu = vectorMenu + "/" + Processing.tr('&Research Tools')
defaultMenuEntries.update({'qgis:creategrid': researchToolsMenu,
                           'qgis:randomselection': researchToolsMenu,
                           'qgis:randomselectionwithinsubsets': researchToolsMenu,
                           'qgis:randompointsinextent': researchToolsMenu,
                           'qgis:randompointsinlayerbounds': researchToolsMenu,
Esempio n. 59
0
 def _translate(context, text, disambig):
     return QApplication.translate(context, text, disambig)