Exemple #1
0
    def openScript(self):
        if self.hasChanged:
            ret = QMessageBox.warning(self, self.tr('Unsaved changes'),
                                      self.tr('There are unsaved changes in script. Continue?'),
                                      QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if ret == QMessageBox.No:
                return

        if self.algType == self.SCRIPT_PYTHON:
            scriptDir = ScriptUtils.scriptsFolders()[0]
            filterName = self.tr('Python scripts (*.py)')
        elif self.algType == self.SCRIPT_R:
            scriptDir = RUtils.RScriptsFolders()[0]
            filterName = self.tr('Processing R script (*.rsx)')

        self.filename, fileFilter = QFileDialog.getOpenFileName(
            self, self.tr('Open script'), scriptDir, filterName)

        if self.filename == '':
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        with codecs.open(self.filename, 'r', encoding='utf-8') as f:
            txt = f.read()

        self.editor.setText(txt)
        self.hasChanged = False
        self.editor.setModified(False)
        self.editor.recolor()
        QApplication.restoreOverrideCursor()
Exemple #2
0
    def canvasReleaseEvent(self, e):
        point = self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(e.x(), e.y())
        point = self.plugin.transform(point)

        p = "POINT(%.3lf %.3lf)" % (point.x(), point.y())

        try:
            QApplication.setOverrideCursor(Qt.WaitCursor)

            fs = self.plugin.retrieve(u"st_contains(wkb_geometry,st_geomfromtext('{}'::text,{}))".format(
                p, self.plugin.getepsg()
            ))

            if not self.plugin.logQuery("eigentuemerInfo", p, [i['flsnr'] for i in fs]):
                QMessageBox.information(None, u"Hinweis", u"Flurstücke werden ohne Protokollierung nicht angezeigt.")
                return

            if len(fs) == 0:
                QMessageBox.information(None, u"Hinweis", u"Kein Flurstück gefunden.")
                return

            fs = self.plugin.highlight(fs=fs, zoomTo=False)

        finally:
            QApplication.restoreOverrideCursor()

        page = self.getPage(fs)
        if page is not None:
            Info.showInfo(self.plugin, page, fs[0]['gmlid'], self.iface.mainWindow())
Exemple #3
0
    def setData(self, index, value, role):
        if role != Qt.EditRole or index.column() != 0:
            return False

        item = index.internalPointer()
        new_value = unicode(value)

        if isinstance(item, SchemaItem) or isinstance(item, TableItem):
            obj = item.getItemData()

            # rename schema or table or view
            if new_value == obj.name:
                return False

            QApplication.setOverrideCursor(Qt.WaitCursor)
            try:
                obj.rename(new_value)
                self._onDataChanged(index)
            except BaseError as e:
                DlgDbError.showError(e, self.treeView)
                return False
            finally:
                QApplication.restoreOverrideCursor()

            return True

        return False
    def createGeomColumn(self):
        """ first check whether everything's fine """
        if self.editName.text() == "":
            QMessageBox.critical(self, self.tr("DB Manager"), self.tr("field name must not be empty"))
            return

        name = self.editName.text()
        geom_type = self.GEOM_TYPES[self.cboType.currentIndex()]
        dim = self.spinDim.value()
        try:
            srid = int(self.editSrid.text())
        except ValueError:
            srid = -1
        createSpatialIndex = False

        # now create the geometry column
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self.table.addGeometryColumn(name, geom_type, srid, dim, createSpatialIndex)
        except DbError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()

        self.accept()
Exemple #5
0
    def fetchAvailablePlugins(self, reloadMode):
        """ Fetch plugins from all enabled repositories."""
        """  reloadMode = true:  Fully refresh data from QSettings to mRepositories  """
        """  reloadMode = false: Fetch unready repositories only """
        QApplication.setOverrideCursor(Qt.WaitCursor)

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

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

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

        QApplication.restoreOverrideCursor()

        # display error messages for every unavailable reposioty, unless Shift pressed nor all repositories are unavailable
        keepQuiet = QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier)
        if repositories.allUnavailable() and repositories.allUnavailable() != repositories.allEnabled():
            for key in repositories.allUnavailable():
                if not keepQuiet:
                    QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Error reading repository:") + " " + key + "\n\n" + repositories.all()[key]["error"])
                if QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier):
                    keepQuiet = True
        # finally, rebuild plugins from the caches
        plugins.rebuild()
    def deleteConstraint(self):
        """ delete a constraint """

        index = self.currentConstraint()
        if index == -1:
            return

        m = self.viewConstraints.model()
        constr = m.getObject(index)

        res = QMessageBox.question(self, self.tr("Are you sure"),
                                   self.tr("really delete constraint '%s'?") % constr.name,
                                   QMessageBox.Yes | QMessageBox.No)
        if res != QMessageBox.Yes:
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.aboutToChangeTable.emit()
        try:
            constr.delete()
            self.populateViews()
        except BaseError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()
Exemple #7
0
def main():
    """Main function to run the example."""
    app = QApplication([])

    default_value_parameter = DefaultValueParameter()
    default_value_parameter.name = 'Value parameter'
    default_value_parameter.help_text = 'Help text'
    default_value_parameter.description = 'Description'
    default_value_parameter.labels = [
        'Setting', 'Do not report', 'Custom']
    default_value_parameter.options = [0, 1, None]

    parameters = [
        default_value_parameter
    ]

    extra_parameters = [
        (DefaultValueParameter, DefaultValueParameterWidget)
    ]

    parameter_container = ParameterContainer(
        parameters, extra_parameters=extra_parameters)
    parameter_container.setup_ui()

    widget = QWidget()
    layout = QGridLayout()
    layout.addWidget(parameter_container)

    widget.setLayout(layout)
    widget.setGeometry(0, 0, 500, 500)

    widget.show()

    sys.exit(app.exec_())
Exemple #8
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
Exemple #9
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"})
    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()
 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 editColumn(self):
        """ open dialog to change column info and alter table appropriately """
        index = self.currentColumn()
        if index == -1:
            return

        m = self.viewFields.model()
        # get column in table
        # (there can be missing number if someone deleted a column)
        fld = m.getObject(index)

        dlg = DlgFieldProperties(self, fld, self.table)
        if not dlg.exec_():
            return
        new_fld = dlg.getField(True)

        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.aboutToChangeTable.emit()
        try:
            fld.update(new_fld.name, new_fld.type2String(), new_fld.notNull, new_fld.default2String())
            self.populateViews()
        except BaseError as e:
            DlgDbError.showError(e, self)
            return
        finally:
            QApplication.restoreOverrideCursor()
    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)
Exemple #14
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)
    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
Exemple #16
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)
Exemple #17
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
Exemple #18
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
 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)
    def treeLoaded(self, reply):
        """
        update the tree of scripts/models whenever
        HTTP request is finished
        """
        QApplication.restoreOverrideCursor()
        if reply.error() != QNetworkReply.NoError:
            self.popupError(reply.error(), reply.request().url().toString())
        else:
            resources = unicode(reply.readAll()).splitlines()
            resources = [r.split(',') for r in resources]
            self.resources = {f: (v, n) for f, v, n in resources}
            for filename, version, name in sorted(resources, key=lambda kv: kv[2].lower()):
                treeBranch = self.getTreeBranchForState(filename, float(version))
                item = TreeItem(filename, name, self.icon)
                treeBranch.addChild(item)
                if treeBranch != self.notinstalledItem:
                    item.setCheckState(0, Qt.Checked)

        reply.deleteLater()
        self.tree.addTopLevelItem(self.toupdateItem)
        self.tree.addTopLevelItem(self.notinstalledItem)
        self.tree.addTopLevelItem(self.uptodateItem)

        self.txtHelp.setHtml(self.HELP_TEXT)
    def zip_db(self):
        force_another_db = False
        dbpath=None
        if self.db:
            use_current_db = utils.Askuser("YesNo",'Vill du göra backup av %s?'%self.db,'Which database?')
            if use_current_db.result == 1:
                dbpath = self.db
                force_another_db = False
            elif use_current_db.result == 0:
                force_another_db = True
            elif use_current_db.result == '':
                return
        if not self.db or force_another_db:
            dbpath = QFileDialog.getOpenFileName(None, 'Ange db som du vill skapa backup utav','',"Spatialite (*.sqlite)")[0]

        if dbpath:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            connection = utils.dbconnection(dbpath)
            connection.connect2db()
            connection.conn.cursor().execute("begin immediate")

            file_path = os.path.realpath(dbpath)
            dir_path = os.path.dirname(file_path)
            current_dir = dir_path.split(os.sep)[-1]

            bkupname = dbpath + datetime.datetime.now().strftime('%Y%m%dT%H%M') + '.zip'
            zf = zipfile.ZipFile(bkupname, mode='w')
            zf.write(dbpath,os.path.basename(dbpath), compress_type=compression) #compression will depend on if zlib is found or not
            zf.close()
            connection.conn.rollback()
            connection.closedb()
            self.iface.messageBar().pushMessage("Information","Database backup was written to " + bkupname, 1,duration=15)
            QApplication.restoreOverrideCursor()
Exemple #22
0
    def runAction(self, action):
        action = unicode(action)

        if action.startswith("vacuumanalyze/"):
            if action == "vacuumanalyze/run":
                self.runVacuumAnalyze()
                return True

        elif action.startswith("rule/"):
            parts = action.split('/')
            rule_name = parts[1]
            rule_action = parts[2]

            msg = u"Do you want to %s rule %s?" % (rule_action, rule_name)

            QApplication.restoreOverrideCursor()

            try:
                if QMessageBox.question(None, self.tr("Table rule"), msg,
                                        QMessageBox.Yes | QMessageBox.No) == QMessageBox.No:
                    return False
            finally:
                QApplication.setOverrideCursor(Qt.WaitCursor)

            if rule_action == "delete":
                self.aboutToChange.emit()
                self.database().connector.deleteTableRule(rule_name, (self.schemaName(), self.name))
                self.refreshRules()
                return True

        return Table.runAction(self, action)
Exemple #23
0
    def finish(self, result, context, feedback):
        keepOpen = ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN)

        if self.iterateParam is None:

            # add html results to results dock
            for out in self.alg.outputDefinitions():
                if isinstance(out, QgsProcessingOutputHtml) and out.name() in result and result[out.name()]:
                    resultsList.addResult(icon=self.alg.icon(), name=out.description(),
                                          result=result[out.name()])

            if not handleAlgorithmResults(self.alg, context, feedback, not keepOpen):
                self.resetGUI()
                return

        self.executed = True
        self.setInfo(self.tr('Algorithm \'{0}\' finished').format(self.alg.displayName()), escape_html=False)
        QApplication.restoreOverrideCursor()

        if not keepOpen:
            self.close()
        else:
            self.resetGUI()
            if self.alg.hasHtmlOutputs():
                self.setInfo(
                    self.tr('HTML output has been generated by this algorithm.'
                            '\nOpen the results dialog to check it.'), escape_html=False)
 def resetGUI(self):
     QApplication.restoreOverrideCursor()
     self.lblProgress.setText('')
     self.progressBar.setMaximum(100)
     self.progressBar.setValue(0)
     self.btnRun.setEnabled(True)
     self.btnClose.setEnabled(True)
Exemple #25
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
Exemple #26
0
 def copy(self):
     """Copy text to clipboard... or keyboard interrupt"""
     if self.hasSelectedText():
         text = self.selectedText()
         text = text.replace('>>> ', '').replace('... ', '').strip()  # removing prompts
         QApplication.clipboard().setText(text)
     else:
         raise KeyboardInterrupt
Exemple #27
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)
def execute(func):
    try:
        QCoreApplication.processEvents()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        return func()
    finally:
        QApplication.restoreOverrideCursor()
        QCoreApplication.processEvents()
    def __init__(self, parent=None):
        super(EditorWidgetTms, self).__init__(parent)
        self.setupUi(self)
        self.tms_validator = LineEditColorValidator(self.txtUrl, 'http[s]?://.+', error_tooltip='http{s}://any_text/{z}/{x}/{y}/')
        self.txtCrsId.setValidator(QIntValidator())
        self.txtPostgisCrsId.setValidator(QIntValidator())

        QApplication.instance().focusChanged.connect(self.focus_changed)
Exemple #30
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)
Exemple #31
0
 def error(self, msg):
     QApplication.restoreOverrideCursor()
     self.setInfo(msg, True)
     self.resetGUI()
     self.tabWidget.setCurrentIndex(1)
 def choose_linked_feature():
     dlg = QApplication.activeModalWidget()
     dlg.setSelectedFeatures([f.id()])
     dlg.accept()
Exemple #33
0
from stdm.utils.util import (
    entity_id_to_attr
)
from stdm.utils.util import getIndex

# Document Type Enumerations
DEFAULT_DOCUMENT = 2020
STATUTORY_REF_PAPER = 2021
SURVEYOR_REF = 2022
NOTARY_REF = 2023
TAX_RECEIPT_PRIVATE = 2024
TAX_RECEIPT_STATE = 2025

# Display text for document types
DOC_TYPE_MAPPING = {
    DEFAULT_DOCUMENT: str(QApplication.translate("sourceDocument",
                                                 "Supporting Document"))
}

# Display text for STR document types
STR_DOC_TYPE_MAPPING = {}
document_type_class = {}
# Mode for initializing the document widget
UPLOAD_MODE = 2100
DOWNLOAD_MODE = 2101
LOGGER = logging.getLogger('stdm')


class SourceDocumentManager(QObject):
    """
    Manages the display of source documents in vertical layout container(s).
    """
Exemple #34
0
        else:
            self.tabListScript = []
        self.settings.setValue("pythonConsole/tabScripts", self.tabListScript)

    def saveSettingsConsole(self):
        self.settings.setValue("pythonConsole/splitterConsole",
                               self.splitter.saveState())
        self.settings.setValue("pythonConsole/splitterObj",
                               self.splitterObj.saveState())
        self.settings.setValue("pythonConsole/splitterEditor",
                               self.splitterEditor.saveState())

        self.shell.writeHistoryFile(True)

    def restoreSettingsConsole(self):
        storedTabScripts = self.settings.value("pythonConsole/tabScripts", [])
        self.tabListScript = storedTabScripts
        self.splitter.restoreState(
            self.settings.value("pythonConsole/splitterConsole", QByteArray()))
        self.splitterEditor.restoreState(
            self.settings.value("pythonConsole/splitterEditor", QByteArray()))
        self.splitterObj.restoreState(
            self.settings.value("pythonConsole/splitterObj", QByteArray()))


if __name__ == '__main__':
    a = QApplication(sys.argv)
    console = PythonConsoleWidget()
    console.show()
    a.exec_()
Exemple #35
0
    def registerDatabaseActions(self, mainWindow):
        action = QAction(
            QApplication.translate("DBManagerPlugin", "&Re-connect"), self)
        mainWindow.registerAction(
            action, QApplication.translate("DBManagerPlugin", "&Database"),
            self.reconnectActionSlot)

        if self.schemas() is not None:
            action = QAction(
                QApplication.translate("DBManagerPlugin", "&Create schema"),
                self)
            mainWindow.registerAction(
                action, QApplication.translate("DBManagerPlugin", "&Schema"),
                self.createSchemaActionSlot)
            action = QAction(
                QApplication.translate("DBManagerPlugin",
                                       "&Delete (empty) schema"), self)
            mainWindow.registerAction(
                action, QApplication.translate("DBManagerPlugin", "&Schema"),
                self.deleteSchemaActionSlot)

        action = QAction(
            QApplication.translate("DBManagerPlugin", "Delete selected item"),
            self)
        mainWindow.registerAction(action, None, self.deleteActionSlot)
        action.setShortcuts(QKeySequence.Delete)

        action = QAction(
            QIcon(":/db_manager/actions/create_table"),
            QApplication.translate("DBManagerPlugin", "&Create table"), self)
        mainWindow.registerAction(
            action, QApplication.translate("DBManagerPlugin", "&Table"),
            self.createTableActionSlot)
        action = QAction(
            QIcon(":/db_manager/actions/edit_table"),
            QApplication.translate("DBManagerPlugin", "&Edit table"), self)
        mainWindow.registerAction(
            action, QApplication.translate("DBManagerPlugin", "&Table"),
            self.editTableActionSlot)
        action = QAction(
            QIcon(":/db_manager/actions/del_table"),
            QApplication.translate("DBManagerPlugin", "&Delete table/view"),
            self)
        mainWindow.registerAction(
            action, QApplication.translate("DBManagerPlugin", "&Table"),
            self.deleteTableActionSlot)
        action = QAction(
            QApplication.translate("DBManagerPlugin", "&Empty table"), self)
        mainWindow.registerAction(
            action, QApplication.translate("DBManagerPlugin", "&Table"),
            self.emptyTableActionSlot)

        if self.schemas() is not None:
            action = QAction(
                QApplication.translate("DBManagerPlugin", "&Move to schema"),
                self)
            action.setMenu(QMenu(mainWindow))

            def invoke_callback():
                return mainWindow.invokeCallback(
                    self.prepareMenuMoveTableToSchemaActionSlot)

            action.menu().aboutToShow.connect(invoke_callback)
            mainWindow.registerAction(
                action, QApplication.translate("DBManagerPlugin", "&Table"))
Exemple #36
0
    def create_mesure_layer(self):
        """ Create an temporary point layer in the Qgis canvas """
        try:
            QApplication.setOverrideCursor(
                Qt.WaitCursor)  ## Start the 'wait' cursor
            if self.list_mesures:

                vl = QgsVectorLayer("Linestring?crs=" + self.selected_epsg,
                                    self.layer_name, "memory")
                pr = vl.dataProvider()

                # add fields
                pr.addAttributes([
                    QgsField("station", QVariant.String),
                    QgsField("st_num", QVariant.Int),
                    QgsField("st_y", QVariant.Double, "double", 12, 4),
                    QgsField("st_x", QVariant.Double, "double", 12, 4),
                    QgsField("st_h", QVariant.Double, "double", 10, 4),
                    QgsField("st_hi", QVariant.Double),
                    QgsField("vise", QVariant.String),
                    QgsField("vise_y", QVariant.Double, "double", 12, 4),
                    QgsField("vise_x", QVariant.Double, "double", 12, 4),
                    QgsField("vise_h", QVariant.Double, "double", 10, 4),
                    QgsField("vise_hs", QVariant.Double),
                    QgsField("vise_category", QVariant.Int),
                    QgsField("dhz", QVariant.Double),
                    QgsField("dh", QVariant.Double)
                ])
                vl.updateFields(
                )  # tell the vector layer to fetch changes from the provider

                # add features
                for item in self.list_mesures:
                    st_y = float(item[2])
                    st_x = float(item[3])
                    vise_y = float(item[7])
                    vise_x = float(item[8])
                    fet = QgsFeature()
                    fet.setGeometry(
                        QgsGeometry.fromPolyline(
                            [QgsPoint(st_y, st_x),
                             QgsPoint(vise_y, vise_x)]))
                    fet.setAttributes(list(item))
                    pr.addFeatures([fet])

                # Calculate the "dhz" and "dh" columns
                expression1 = QgsExpression(
                    "round((sqrt((st_y - vise_y)^2 + (st_x - vise_x)^2)), 3)")
                expression2 = QgsExpression(
                    "round((vise_h + vise_hs - st_h - st_hi), 3)")
                context = QgsExpressionContext()
                context.appendScopes(
                    QgsExpressionContextUtils.globalProjectLayerScopes(vl))

                vl.startEditing()
                for f in vl.getFeatures():
                    context.setFeature(f)
                    f["dhz"] = expression1.evaluate(context)
                    f["dh"] = expression2.evaluate(context)
                    vl.updateFeature(f)
                vl.commitChanges()

                # add preconfigured qgis.qml style file
                plugin_folder = os.path.dirname(os.path.dirname(__file__))
                qml_file = Path(plugin_folder) / "qml" / self.qml_style_mesure
                if qml_file.is_file(
                ):  # Test if file exist, avoid error if he is missing
                    vl.loadNamedStyle(str(qml_file))

                # update layer's extent when new features have been added
                vl.updateExtents()

                # zoom to the layer extent
                canvas = iface.mapCanvas()
                canvas.setExtent(vl.extent())

                # Show in project
                self.rmv_old_qgs_mesure_layer()
                QgsProject.instance().addMapLayer(vl)
        except:
            print(
                "Mesures -> Failed to create a new measurements Qgis layer (def create_mesure_layer)"
            )
            QApplication.restoreOverrideCursor()  ## Stop the 'wait' cursor
        finally:
            QApplication.restoreOverrideCursor()  ## Stop the 'wait' cursor
def find_window(name):
    for widget in QApplication.topLevelWidgets():
        if widget.objectName() == name:
            return widget
    return None
Exemple #38
0
    def onGenerate(self):
        """
        Slot raised to initiate the certificate generation process.
        """
        self._notif_bar.clear()
        success_status = True
        config = self.current_config()
        self.last_data_source = config.data_source()
        if config is None:
            self._notif_bar.insertErrorNotification(QApplication.translate("DocumentGeneratorDialog", \
                                                                           "The entity configuration could not be extracted."))
            return

        # Get selected records and validate
        records = self.tabWidget.currentWidget().entities()

        if self.chk_template_datasource.isChecked():
            records = self._dummy_template_records()

        if len(records) == 0:
            self._notif_bar.insertErrorNotification(QApplication.translate("DocumentGeneratorDialog", \
                                                                           "Please load at least one entity record"))
            return

        if not self._docTemplatePath:
            self._notif_bar.insertErrorNotification(QApplication.translate("DocumentGeneratorDialog", \
                                                                           "Please select a document template to use"))
            return

        documentNamingAttrs = self.lstDocNaming.selectedMappings()

        if self.chkUseOutputFolder.checkState() == Qt.Checked and len(
                documentNamingAttrs) == 0:
            self._notif_bar.insertErrorNotification(QApplication.translate("DocumentGeneratorDialog", \
                                                                           "Please select at least one field for naming the output document"))

            return

        # Set output file properties
        if self.rbExpImage.isChecked():
            outputMode = DocumentGenerator.Image
            fileExtension = self.cboImageType.currentText()
            saveAsText = "Image File"

        else:
            outputMode = DocumentGenerator.PDF
            fileExtension = "pdf"
            saveAsText = "PDF File"

        # Show save file dialog if not using output folder
        if self.chkUseOutputFolder.checkState() == Qt.Unchecked:
            docDir = source_document_location()

            if self._outputFilePath:
                fileInfo = QFileInfo(self._outputFilePath)
                docDir = fileInfo.dir().path()

            self._outputFilePath, _ = QFileDialog.getSaveFileName(
                self,
                QApplication.translate("DocumentGeneratorDialog",
                                       "Save Document"), docDir,
                "{0} (*.{1})".format(
                    QApplication.translate("DocumentGeneratorDialog",
                                           saveAsText), fileExtension))

            if not self._outputFilePath:
                self._notif_bar.insertErrorNotification(
                    QApplication.translate(
                        "DocumentGeneratorDialog",
                        "Process aborted. No output file was specified."))

                return

            # Include extension in file name
            self._outputFilePath = self._outputFilePath  # + "." + fileExtension

        # else:
        # Multiple files to be generated.
        # pass

        self._doc_generator.set_link_field(config.link_field())

        self._doc_generator.clear_attr_value_formatters()

        if not self.chk_template_datasource.isChecked():
            # Apply cell formatters for naming output files
            self._doc_generator.set_attr_value_formatters(config.formatters())

        entity_field_name = "id"

        # Iterate through the selected records
        progressDlg = QProgressDialog(self)
        progressDlg.setMaximum(len(records))

        try:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

            for i, record in enumerate(records):
                progressDlg.setValue(i)

                if progressDlg.wasCanceled():
                    success_status = False
                    break

                # User-defined location
                if self.chkUseOutputFolder.checkState() == Qt.Unchecked:
                    status, msg = self._doc_generator.run(
                        self._docTemplatePath,
                        entity_field_name,
                        record.id,
                        outputMode,
                        data_source=self.ds_entity.name,
                        filePath=self._outputFilePath)
                    self._doc_generator.clear_temporary_layers()
                # Output folder location using custom naming
                else:

                    status, msg = self._doc_generator.run(
                        self._docTemplatePath,
                        entity_field_name,
                        record.id,
                        outputMode,
                        dataFields=documentNamingAttrs,
                        fileExtension=fileExtension,
                        data_source=self.ds_entity.name)
                    self._doc_generator.clear_temporary_layers()

                if not status:
                    result = QMessageBox.warning(
                        self,
                        QApplication.translate("DocumentGeneratorDialog",
                                               "Document Generate Error"), msg,
                        QMessageBox.Ignore | QMessageBox.Abort)

                    if result == QMessageBox.Abort:
                        progressDlg.close()
                        progressDlg.deleteLater()
                        del progressDlg
                        success_status = False

                        # Restore cursor
                        QApplication.restoreOverrideCursor()

                        return

                    # If its the last record and user has selected to ignore
                    if i + 1 == len(records):
                        progressDlg.close()
                        progressDlg.deleteLater()
                        del progressDlg
                        success_status = False

                        # Restore cursor
                        QApplication.restoreOverrideCursor()

                        return

                else:
                    progressDlg.setValue(len(records))

            QApplication.restoreOverrideCursor()

            QMessageBox.information(
                self,
                QApplication.translate("DocumentGeneratorDialog",
                                       "Document Generation Complete"),
                QApplication.translate(
                    "DocumentGeneratorDialog",
                    "Document generation has successfully completed."))

        except DummyException as ex:
            LOGGER.debug(str(ex))
            err_msg = sys.exc_info()[1]
            QApplication.restoreOverrideCursor()

            QMessageBox.critical(
                self, "STDM",
                QApplication.translate(
                    "DocumentGeneratorDialog",
                    "Error Generating documents - %s" % (err_msg)))
            success_status = False

        progressDlg.deleteLater()
        del progressDlg

        # Reset UI
        self.reset(success_status)
    def canvasReleaseEvent(self, event):
        """ With left click the digitizing is finished """

        if event.button() == Qt.LeftButton:

            # Get coordinates
            event_point = self.snapper_manager.get_event_point(event)

            # Simple selection
            if not self.dragging:

                # Snap to connec or gully
                result = self.snapper_manager.snap_to_background_layers(
                    event_point)
                if not self.snapper_manager.result_is_valid():
                    return

                # Check if it belongs to 'connec' or 'gully' group
                layer = self.snapper_manager.get_snapped_layer(result)
                feature_id = self.snapper_manager.get_snapped_feature_id(
                    result)
                exist_connec = self.snapper_manager.check_connec_group(layer)
                exist_gully = self.snapper_manager.check_gully_group(layer)
                if exist_connec or exist_gully:
                    key = QApplication.keyboardModifiers()
                    # If Ctrl+Shift is clicked: deselect snapped feature
                    if key == (Qt.ControlModifier | Qt.ShiftModifier):
                        layer.deselect([feature_id])
                    else:
                        # If Ctrl is not clicked: remove previous selection
                        if key != Qt.ControlModifier:
                            layer.removeSelection()
                        layer.select([feature_id])

                    # Hide marker
                    self.vertex_marker.hide()

            # Multiple selection
            else:

                # Set valid values for rectangle's width and height
                if self.select_rect.width() == 1:
                    self.select_rect.setLeft(self.select_rect.left() + 1)

                if self.select_rect.height() == 1:
                    self.select_rect.setBottom(self.select_rect.bottom() + 1)

                self.set_rubber_band()
                self.select_multiple_features(self.selected_rectangle)
                self.dragging = False

                # Refresh map canvas
                self.rubber_band.reset()

        elif event.button() == Qt.RightButton:

            # Check selected records
            number_features = 0
            layer = self.snapper_manager.layer_connec
            if layer:
                number_features += layer.selectedFeatureCount()

            if number_features > 0:
                message = "Number of features selected in the group of"
                title = "Interpolate value - Do you want to update values"
                answer = self.controller.ask_question(message,
                                                      title,
                                                      parameter='connec: ' +
                                                      str(number_features))
                if answer:
                    # Create link
                    self.link_selected_features('connec', layer)
                    self.cancel_map_tool()

            layer = self.snapper_manager.layer_gully
            if layer:
                # Check selected records
                number_features = 0
                number_features += layer.selectedFeatureCount()

                if number_features > 0:
                    message = "Number of features selected in the group of"
                    title = "Interpolate value - Do you want to update values"
                    answer = self.controller.ask_question(message,
                                                          title,
                                                          parameter='gully: ' +
                                                          str(number_features))
                    if answer:
                        # Create link
                        self.link_selected_features('gully', layer)
                        self.cancel_map_tool()

        # Force reload dataProvider of layer
        self.controller.set_layer_index('v_edit_link')
        self.controller.set_layer_index('v_edit_vnode')
Exemple #40
0
 def __enter__(self):
     QApplication.setOverrideCursor(self.cursor)
Exemple #41
0
    def insertDocumentFromFile(self, path, doc_type_id, entity, record_count=1):
        """
        Insert a new document into one of the registered containers with the
        document type id. This document is registered
        :param path: The local user path of the document
        :type path: String
        :param doc_type_id: The entity document type id
        :type doc_type_id: Integer
        :param entity: The entity in which the document is inserted into.
        :type entity: Entity class
        :param record_count: The number of records for which a
        document is uploaded. Default is 1. For instance, more
        records could be used in STR wizard in multi-party.
        :type record_count: Integer
        :return: None
        :rtype: NoneType
        """
        if len(self.containers) > 0:
            if doc_type_id in self.containers:
                container = self.containers[doc_type_id]

                # Check if the file exists
                if QFile.exists(path):

                    network_location = network_document_path()

                    if not network_location:
                        self._doc_repository_error()

                        return

                    # Check if the directory exists
                    doc_dir = QDir(network_location)

                    if not doc_dir.exists():
                        msg = QApplication.translate(
                            "sourceDocumentManager",
                            "The root document "
                            "repository '{0}' does "
                            "not exist.\nPlease "
                            "check the path settings."
                        )
                        parent = self.parent()
                        if not isinstance(parent, QWidget):
                            parent = None

                        QMessageBox.critical(
                            parent,
                            QApplication.translate(
                                "sourceDocumentManager",
                                "Document Manager"
                            ),
                            msg.format(network_location)
                        )
                        return

                    for i in range(record_count):
                        # Use the default network file manager
                        networkManager = NetworkFileManager(
                            network_location, self.parent()
                        )
                        # Add document widget
                        docWidg = DocumentWidget(
                            self.document_model,
                            networkManager,
                            parent=self.parent(),
                            view_manager=self._doc_view_manager
                        )
                        # Connect slot once the document
                        # has been successfully uploaded.
                        docWidg.fileUploadComplete.connect(
                            lambda: self.onFileUploadComplete(doc_type_id)
                        )
                        self._linkWidgetRemovedSignal(docWidg)

                        doc_type_entity = entity.supporting_doc.document_type_entity
                        doc_type_value = entity_id_to_attr(
                            doc_type_entity, 'value', doc_type_id
                        )

                        docWidg.setFile(
                            path, entity.name, doc_type_value, doc_type_id
                        )
                        container.addWidget(docWidg)
Exemple #42
0
    def registerDatabaseActions(self, mainWindow):
        action = QAction(QApplication.translate(
            "DBManagerPlugin", "&Re-connect"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Database"), self.reconnectActionSlot)

        if self.schemas():
            action = QAction(QApplication.translate(
                "DBManagerPlugin", "&Create Schema…"), self)
            mainWindow.registerAction(action, QApplication.translate(
                "DBManagerPlugin", "&Schema"), self.createSchemaActionSlot)
            action = QAction(QApplication.translate(
                "DBManagerPlugin", "&Delete (Empty) Schema…"), self)
            mainWindow.registerAction(action, QApplication.translate(
                "DBManagerPlugin", "&Schema"), self.deleteSchemaActionSlot)

        action = QAction(QApplication.translate(
            "DBManagerPlugin", "Delete Selected Item"), self)
        mainWindow.registerAction(action, None, self.deleteActionSlot)
        action.setShortcuts(QKeySequence.Delete)

        action = QAction(QgsApplication.getThemeIcon("/mActionCreateTable.svg"),
                         QApplication.translate(
                             "DBManagerPlugin", "&Create Table…"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Table"), self.createTableActionSlot)
        action = QAction(QgsApplication.getThemeIcon("/mActionEditTable.svg"),
                         QApplication.translate(
                             "DBManagerPlugin", "&Edit Table…"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Table"), self.editTableActionSlot)
        action = QAction(QgsApplication.getThemeIcon("/mActionDeleteTable.svg"),
                         QApplication.translate(
                             "DBManagerPlugin", "&Delete Table/View…"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Table"), self.deleteTableActionSlot)
        action = QAction(QApplication.translate(
            "DBManagerPlugin", "&Empty Table…"), self)
        mainWindow.registerAction(action, QApplication.translate(
            "DBManagerPlugin", "&Table"), self.emptyTableActionSlot)
Exemple #43
0
    def matrix_dem_build(self, dem_dataset, height, width, scale, spacing_mm,
                         roi_x_max, roi_x_min, roi_y_min, h_base, z_scale,
                         projected):

        # Calculate DEM parameters
        dem_col = dem_dataset.RasterXSize
        dem_row = dem_dataset.RasterYSize

        geotransform = dem_dataset.GetGeoTransform()
        dem_x_min = geotransform[0]
        dem_y_max = geotransform[3]
        dem_y_min = dem_y_max + dem_row * geotransform[5]
        dem_x_max = dem_x_min + dem_col * geotransform[1]

        spacing_deg = spacing_mm * (roi_x_max - roi_x_min) / width

        row_stl = int(math.ceil(height / spacing_mm) + 1)
        col_stl = int(math.ceil(width / spacing_mm) + 1)
        matrix_dem = [list(range(col_stl)) for i in range(row_stl)]

        var_y = height
        for i in range(row_stl):
            self.updateProgress.emit()
            QApplication.processEvents()
            var_x = 0
            for j in range(col_stl):
                # Model coordinate x(mm), y(mm)
                x_model = round(var_x, 2)
                y_model = round(var_y, 2)

                # Model maps geo_coordinates
                if projected:
                    x = x_model * scale / 1000 + roi_x_min
                    y = y_model * scale / 1000 + roi_y_min
                else:
                    x = x_model * spacing_deg / spacing_mm + roi_x_min
                    y = y_model * spacing_deg / spacing_mm + roi_y_min

                # Model layer geo_coordinates to query z value
                point = QgsPoint(x, y)
                source = self.parameters["crs_map"]
                target = self.parameters["crs_layer"]
                if source != target:
                    transform = QgsCoordinateTransform(source, target)
                    point = transform.transform(point)
                    x = point.x()
                    y = point.y()

                # From x(m) get Column in DEM file
                col_dem = (x - dem_x_min) * dem_col / (dem_x_max - dem_x_min)
                col_dem = int(math.floor(col_dem))
                if col_dem == dem_col:
                    col_dem -= 1
                # From y(m) get Row in DEM file
                row_dem = (dem_y_max - y) * dem_row / (dem_y_max - dem_y_min)
                row_dem = int(math.floor(row_dem))
                if row_dem == dem_row:
                    row_dem -= 1

                # Model coordinate z(mm)
                if col_dem < 0 or row_dem < 0:
                    z_model = 2
                elif self.get_dem_z(dem_dataset, col_dem, row_dem, 1,
                                    1)[0] <= h_base:
                    z_model = 2
                elif math.isnan(
                        self.get_dem_z(dem_dataset, col_dem, row_dem, 1,
                                       1)[0]):
                    z_model = 2
                else:
                    z_model = round(
                        (self.get_dem_z(dem_dataset, col_dem, row_dem, 1, 1)[0]
                         - h_base) / scale * 1000 * z_scale, 2) + 2

                matrix_dem[i][j] = self.pto(x=x_model, y=y_model, z=z_model)

                var_x += spacing_mm
                if var_x > width:
                    var_x = width
            var_y = spacing_mm * (row_stl - (i + 2))
            if self.quit:
                return 0
        return matrix_dem
    def convert(self):
        """
        Convert the project to a portable project.

        :param offline_editing: The offline editing instance
        :param export_folder:   The folder to export to
        """

        project = QgsProject.instance()
        original_project = project

        original_project_path = project.fileName()
        project_filename = project.baseName()

        # Write a backup of the current project to a temporary file
        project_backup_folder = tempfile.mkdtemp()
        backup_project_path = os.path.join(project_backup_folder,
                                           project_filename + '.qgs')
        QgsProject.instance().write(backup_project_path)

        try:
            if not os.path.exists(self.export_folder):
                os.makedirs(self.export_folder)

            QApplication.setOverrideCursor(Qt.WaitCursor)

            self.__offline_layers = list()
            self.__layers = list(project.mapLayers().values())

            original_layer_info = {}
            for layer in self.__layers:
                original_layer_info[layer.id()] = (layer.source(),
                                                   layer.name())

            # We store the pks of the original vector layers
            # and we check that the primary key fields names don't
            # have a comma in the name
            original_pk_fields_by_layer_name = {}
            for layer in self.__layers:
                if layer.type() == QgsMapLayer.VectorLayer:
                    keys = []
                    for idx in layer.primaryKeyAttributes():
                        key = layer.fields()[idx].name()
                        assert (','
                                not in key), 'Comma in field names not allowed'
                        keys.append(key)
                    original_pk_fields_by_layer_name[layer.name()] = ','.join(
                        keys)

            self.total_progress_updated.emit(0, 1,
                                             self.trUtf8('Creating base map…'))
            # Create the base map before layers are removed
            if self.project_configuration.create_base_map:
                if 'processing' not in qgis.utils.plugins:
                    QMessageBox.warning(
                        None, self.tr('QFieldSync requires processing'),
                        self.
                        tr('Creating a basemap with QFieldSync requires the processing plugin to be enabled. Processing is not enabled on your system. Please go to Plugins > Manage and Install Plugins and enable processing.'
                           ))
                    return

                if self.project_configuration.base_map_type == ProjectProperties.BaseMapType.SINGLE_LAYER:
                    self.createBaseMapLayer(
                        None, self.project_configuration.base_map_layer,
                        self.project_configuration.base_map_tile_size,
                        self.project_configuration.base_map_mupp)
                else:
                    self.createBaseMapLayer(
                        self.project_configuration.base_map_theme, None,
                        self.project_configuration.base_map_tile_size,
                        self.project_configuration.base_map_mupp)

            # Loop through all layers and copy/remove/offline them
            pathResolver = QgsProject.instance().pathResolver()
            copied_files = list()
            for current_layer_index, layer in enumerate(self.__layers):
                self.total_progress_updated.emit(
                    current_layer_index - len(self.__offline_layers),
                    len(self.__layers), self.trUtf8('Copying layers…'))

                layer_source = LayerSource(layer)
                if not layer_source.is_supported:
                    project.removeMapLayer(layer)
                    continue

                if layer.dataProvider() is not None:
                    md = QgsProviderRegistry.instance().providerMetadata(
                        layer.dataProvider().name())
                    if md is not None:
                        decoded = md.decodeUri(layer.source())
                        if "path" in decoded:
                            path = pathResolver.writePath(decoded["path"])
                            if path.startswith("localized:"):
                                # Layer stored in localized data path, skip
                                continue

                if layer_source.action == SyncAction.OFFLINE:
                    if self.project_configuration.offline_copy_only_aoi and not self.project_configuration.offline_copy_only_selected_features:
                        layer.selectByRect(self.extent)
                    elif self.project_configuration.offline_copy_only_aoi and self.project_configuration.offline_copy_only_selected_features:
                        # This option is only possible via API
                        QgsApplication.instance().messageLog().logMessage(
                            self.
                            tr('Both "Area of Interest" and "only selected features" options were enabled, tha latter takes precedence.'
                               ), 'QFieldSync')
                    self.__offline_layers.append(layer)

                    # Store the primary key field name(s) as comma separated custom property
                    if layer.type() == QgsMapLayer.VectorLayer:
                        key_fields = ','.join([
                            layer.fields()[x].name()
                            for x in layer.primaryKeyAttributes()
                        ])
                        layer.setCustomProperty(
                            'QFieldSync/sourceDataPrimaryKeys', key_fields)

                elif layer_source.action == SyncAction.NO_ACTION:
                    copied_files = layer_source.copy(self.export_folder,
                                                     copied_files)
                elif layer_source.action == SyncAction.KEEP_EXISTENT:
                    layer_source.copy(self.export_folder, copied_files, True)
                elif layer_source.action == SyncAction.REMOVE:
                    project.removeMapLayer(layer)

            project_path = os.path.join(self.export_folder,
                                        project_filename + "_qfield.qgs")

            # save the original project path
            ProjectConfiguration(
                project).original_project_path = original_project_path

            # save the offline project twice so that the offline plugin can "know" that it's a relative path
            QgsProject.instance().write(project_path)

            # export the DCIM folder
            copy_images(
                os.path.join(os.path.dirname(original_project_path), "DCIM"),
                os.path.join(os.path.dirname(project_path), "DCIM"))
            try:
                # Run the offline plugin for gpkg
                gpkg_filename = "data.gpkg"
                if self.__offline_layers:
                    offline_layer_ids = [l.id() for l in self.__offline_layers]
                    only_selected = self.project_configuration.offline_copy_only_aoi or self.project_configuration.offline_copy_only_selected_features
                    if Qgis.QGIS_VERSION_INT < 31601:
                        if not self.offline_editing.convertToOfflineProject(
                                self.export_folder, gpkg_filename,
                                offline_layer_ids, only_selected,
                                self.offline_editing.GPKG):
                            raise Exception(
                                self.
                                tr("Error trying to convert layers to offline layers"
                                   ))
                    else:
                        if not self.offline_editing.convertToOfflineProject(
                                self.export_folder, gpkg_filename,
                                offline_layer_ids, only_selected,
                                self.offline_editing.GPKG, None):
                            raise Exception(
                                self.
                                tr("Error trying to convert layers to offline layers"
                                   ))
            except AttributeError:
                # Run the offline plugin for spatialite
                spatialite_filename = "data.sqlite"
                if self.__offline_layers:
                    offline_layer_ids = [l.id() for l in self.__offline_layers]
                    only_selected = self.project_configuration.offline_copy_only_aoi or self.project_configuration.offline_copy_only_selected_features
                    if Qgis.QGIS_VERSION_INT < 31601:
                        if not self.offline_editing.convertToOfflineProject(
                                self.export_folder, spatialite_filename,
                                offline_layer_ids, only_selected,
                                self.offline_editing.SpatiaLite):
                            raise Exception(
                                self.
                                tr("Error trying to convert layers to offline layers"
                                   ))
                    else:
                        if not self.offline_editing.convertToOfflineProject(
                                self.export_folder, spatialite_filename,
                                offline_layer_ids, only_selected,
                                self.offline_editing.SpatiaLite, None):
                            raise Exception(
                                self.
                                tr("Error trying to convert layers to offline layers"
                                   ))

            # Disable project options that could create problems on a portable
            # project with offline layers
            if self.__offline_layers:
                QgsProject.instance().setEvaluateDefaultValues(False)
                QgsProject.instance().setAutoTransaction(False)

                # check if value relations point to offline layers and adjust if necessary
                for layer in project.mapLayers().values():
                    if layer.type() == QgsMapLayer.VectorLayer:

                        # Before QGIS 3.14 the custom properties of a layer are not
                        # kept into the new layer during the conversion to offline project
                        # So we try to identify the new created layer by its name and
                        # we set the custom properties again.
                        if not layer.customProperty(
                                'QFieldSync/cloudPrimaryKeys'):
                            original_layer_name = layer.name().rsplit(' ',
                                                                      1)[0]
                            stored_fields = original_pk_fields_by_layer_name.get(
                                original_layer_name, None)
                            if stored_fields:
                                layer.setCustomProperty(
                                    'QFieldSync/sourceDataPrimaryKeys',
                                    stored_fields)

                        for field in layer.fields():
                            ews = field.editorWidgetSetup()
                            if ews.type() == 'ValueRelation':
                                widget_config = ews.config()
                                online_layer_id = widget_config['Layer']
                                if project.mapLayer(online_layer_id):
                                    continue

                                layer_id = None
                                loose_layer_id = None
                                for offline_layer in project.mapLayers(
                                ).values():
                                    if offline_layer.customProperty(
                                            'remoteSource'
                                    ) == original_layer_info[online_layer_id][
                                            0]:
                                        #  First try strict matching: the offline layer should have a "remoteSource" property
                                        layer_id = offline_layer.id()
                                        break
                                    elif Qgis.QGIS_VERSION_INT < 31601 and offline_layer.name().startswith(original_layer_info[online_layer_id][1] + ' ') or \
                                            Qgis.QGIS_VERSION_INT >= 31601 and offline_layer.name() == original_layer_info[online_layer_id][1]:
                                        #  If that did not work, go with loose matching
                                        #  On older versions (<31601) the offline layer should start with the online layer name + a translated version of " (offline)"
                                        loose_layer_id = offline_layer.id()
                                widget_config[
                                    'Layer'] = layer_id or loose_layer_id
                                offline_ews = QgsEditorWidgetSetup(
                                    ews.type(), widget_config)
                                layer.setEditorWidgetSetup(
                                    layer.fields().indexOf(field.name()),
                                    offline_ews)

            # Now we have a project state which can be saved as offline project
            QgsProject.instance().write(project_path)
        finally:
            # We need to let the app handle events before loading the next project or QGIS will crash with rasters
            QCoreApplication.processEvents()
            QgsProject.instance().clear()
            QCoreApplication.processEvents()
            QgsProject.instance().read(backup_project_path)
            QgsProject.instance().setFileName(original_project_path)
            QApplication.restoreOverrideCursor()

        self.offline_editing.layerProgressUpdated.disconnect(
            self.on_offline_editing_next_layer)
        self.offline_editing.progressModeSet.disconnect(
            self.on_offline_editing_max_changed)
        self.offline_editing.progressUpdated.disconnect(
            self.offline_editing_task_progress)

        self.total_progress_updated.emit(100, 100, self.tr('Finished'))
    def accept(self):
        self.algs = []
        self.load = []
        self.canceled = False

        for row in range(self.mainWidget.tblParameters.rowCount()):
            alg = self.alg.getCopy()
            col = 0
            for param in alg.parameters:
                if param.hidden:
                    continue
                wrapper = self.mainWidget.wrappers[row][col]
                if not self.mainWidget.setParamValue(param, wrapper, alg):
                    self.bar.pushMessage(
                        "",
                        self.tr(
                            'Wrong or missing parameter value: %s (row %d)') %
                        (param.description, row + 1),
                        level=QgsMessageBar.WARNING,
                        duration=5)
                    self.algs = None
                    return
                col += 1
            for out in alg.outputs:
                if out.hidden:
                    continue

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

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

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

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

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

        self.finish()
Exemple #46
0
 def addLayer(self, layer, headers, types, features):
     tab = QWidget()
     tab.layer = layer
     p1_vertical = QVBoxLayout(tab)
     p1_vertical.setContentsMargins(0,0,0,0)
     
     table = QTableWidget()
     table.itemSelectionChanged.connect(self.highlight_features)
     table.title = layer.name()
     table.crs = layer.crs()
     table.setColumnCount(len(headers))
     if len(features) > 0:
         table.setRowCount(len(features))
         nbrow = len(features)
         self.loadingWindow.show()
         self.loadingWindow.setLabelText(table.title)
         self.loadingWindow.activateWindow()
         self.loadingWindow.showNormal()
         
         # Table population
         m = 0
         for feature in features:
             n = 0
             for cell in feature.attributes():
                 item = QTableWidgetItem()
                 item.setData(Qt.DisplayRole, cell)
                 item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                 item.feature = feature
                 table.setItem(m, n, item)
                 n += 1
             m += 1
             self.loadingWindow.setValue(int((float(m)/nbrow)*100))  
             QApplication.processEvents()
         
     else:
         table.setRowCount(0)  
                         
     table.setHorizontalHeaderLabels(headers)
     table.horizontalHeader().setSectionsMovable(True)
     
     table.types = types
     table.filter_op = []
     table.filters = []
     for i in range(0, len(headers)):
         table.filters.append('')
         table.filter_op.append(0)
     
     header = table.horizontalHeader()
     header.setContextMenuPolicy(Qt.CustomContextMenu)
     header.customContextMenuRequested.connect(partial(self.filterMenu, table))
         
     table.setSortingEnabled(True)
     
     p1_vertical.addWidget(table)
     
     # Status bar to display informations (ie: area)
     tab.sb = QStatusBar()
     p1_vertical.addWidget(tab.sb)
     
     title = table.title
     # We reduce the title's length to 20 characters
     if len(title)>20:
         title = title[:20]+'...'
     
     # We add the number of elements to the tab's title.
     title += ' ('+str(len(features))+')'
         
     self.tabWidget.addTab(tab, title) # Add the tab to the conatiner
     self.tabWidget.setTabToolTip(self.tabWidget.indexOf(tab), table.title) # Display a tooltip with the layer's full name
Exemple #47
0
            barra = QProgressBar(self)
            barra.show()
            barra.setMinimum(0)
            barra.setMaximum(9)
            for a in range(10):
                time.sleep(1)
                barra.setValue(a)

            path = self.percorso
            os.popen('dropdb -U postgres pyarchinit')
            os.popen(
                'createdb -U postgres -p 5432 -h localhost -E UTF8  -T template_postgis_20 -e pyarchinit'
            )
            os.popen(
                'pg_restore --host localhost --port 5432 --username postgres --dbname pyarchinit --role postgres --no-password  --verbose %s'
                % str(path))
            QMessageBox.warning(self, 'Messaggio', 'Ripristino completato',
                                QMessageBox.Ok)
        except Exception as e:
            QMessageBox.warning(self, 'Messaggio',
                                'Ripristino fallito!!' + str(e),
                                QMessageBox.Ok)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = pyarchinit_dbmanagment()
    ui.show()
    sys.exit(app.exec_())
Exemple #48
0
from processing.core.ProcessingConfig import ProcessingConfig, Setting
from processing.gui.MessageDialog import MessageDialog
from processing.gui.AlgorithmDialog import AlgorithmDialog
from qgis.utils import iface
from qgis.core import QgsApplication
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:pointsinpolygon': analysisToolsMenu,
    'qgis:countpointsinpolygon': analysisToolsMenu,
    'qgis:listuniquevalues': analysisToolsMenu,
    'qgis:basicstatisticsforfields': analysisToolsMenu,
    'qgis:nearestneighbouranalysis': analysisToolsMenu,
    'qgis:meancoordinates': analysisToolsMenu,
    'qgis:lineintersections': analysisToolsMenu
})
researchToolsMenu = vectorMenu + "/" + Processing.tr('&Research Tools')
defaultMenuEntries.update({
    'qgis:randomselection': researchToolsMenu,
    def search_data(self, **kwargs):
        """
        Get plot geometries associated with parcels, both collected and official, zoom to them, activate map swipe tool
            and fill comparison table.

        :param kwargs: key-value (field name-field value) to search in parcel tables, both collected and official
                       Normally, keys are parcel_number, old_parcel_number or FMI, but if duplicates are found, an
                       additional t_id disambiguates only for the collected source. In the Official source we assume
                       we will not find duplicates, if there are, we will choose the first record found an will not deal
                       with letting the user choose one of the duplicates by hand (as we do for the collected source).
        """
        self.chk_show_all_plots.setEnabled(False)
        self.chk_show_all_plots.setChecked(True)
        self.initialize_tools_and_layers()  # Reset any filter on layers
        already_zoomed_in = False

        self.clear_result_table()

        search_field = self.cbo_parcel_fields.currentData()
        search_value = list(kwargs.values())[0]

        # Get OFFICIAL parcel's t_id and get related plot(s)
        expression = QgsExpression("{}='{}'".format(search_field,
                                                    search_value))
        request = QgsFeatureRequest(expression)
        field_idx = self.utils._official_layers[PARCEL_TABLE][LAYER].fields(
        ).indexFromName(ID_FIELD)
        request.setFlags(QgsFeatureRequest.NoGeometry)
        request.setSubsetOfAttributes([field_idx
                                       ])  # Note: this adds a new flag
        official_parcels = [
            feature for feature in self.utils._official_layers[PARCEL_TABLE]
            [LAYER].getFeatures(request)
        ]

        if len(official_parcels) > 1:
            # We do not expect duplicates in the official source!
            pass  # We'll choose the first one anyways
        elif len(official_parcels) == 0:
            print("No parcel found!", search_field, search_value)

        official_plot_t_ids = []
        if official_parcels:
            official_plot_t_ids = self.utils.ladm_data.get_plots_related_to_parcels(
                self.utils._official_db, [official_parcels[0][ID_FIELD]],
                field_name=ID_FIELD,
                plot_layer=self.utils._official_layers[PLOT_TABLE][LAYER],
                uebaunit_table=self.utils._official_layers[UEBAUNIT_TABLE]
                [LAYER])

            if official_plot_t_ids:
                self._current_official_substring = "\"{}\" IN ('{}')".format(
                    ID_FIELD,
                    "','".join([str(t_id) for t_id in official_plot_t_ids]))
                self.parent.request_zoom_to_features(
                    self.utils._official_layers[PLOT_TABLE][LAYER], list(),
                    official_plot_t_ids)
                already_zoomed_in = True

        # Now get COLLECTED parcel's t_id and get related plot(s)
        collected_parcel_t_id = None
        if 'collected_parcel_t_id' in kwargs:
            # This is the case when this panel is called and we already know the parcel number is duplicated
            collected_parcel_t_id = kwargs['collected_parcel_t_id']
            search_criterion_collected = {
                ID_FIELD: collected_parcel_t_id
            }  # As there are duplicates, we need to use t_ids
        else:
            # This is the case when:
            #   + Either this panel was called and we know the parcel number is not duplicated, or
            #   + This panel was shown without knowing about duplicates (e.g., individual parcel search) and we still
            #     need to discover whether we have duplicates for this search criterion
            search_criterion_collected = {search_field: search_value}

            request = QgsFeatureRequest(expression)
            request.setFlags(QgsFeatureRequest.NoGeometry)
            request.setSubsetOfAttributes(
                [ID_FIELD], self.utils._layers[PARCEL_TABLE]
                [LAYER].fields())  # Note this adds a new flag
            collected_parcels = self.utils._layers[PARCEL_TABLE][
                LAYER].getFeatures(request)
            collected_parcels_t_ids = [
                feature[ID_FIELD] for feature in collected_parcels
            ]

            if collected_parcels_t_ids:
                collected_parcel_t_id = collected_parcels_t_ids[0]
                if len(collected_parcels_t_ids
                       ) > 1:  # Duplicates in collected source after a search
                    QApplication.restoreOverrideCursor(
                    )  # Make sure cursor is not waiting (it is if on an identify)
                    QCoreApplication.processEvents()
                    dlg_select_parcel = SelectDuplicateParcelDialog(
                        self.utils, collected_parcels_t_ids, self.parent)
                    dlg_select_parcel.exec_()

                    if dlg_select_parcel.parcel_t_id:  # User selected one of the duplicated parcels
                        collected_parcel_t_id = dlg_select_parcel.parcel_t_id
                        search_criterion_collected = {
                            ID_FIELD: collected_parcel_t_id
                        }
                    else:
                        return  # User just cancelled the dialog, there is nothing more to do

        search_criterion_official = {search_field: search_value}

        self.fill_table(search_criterion_official, search_criterion_collected)

        if collected_parcel_t_id is not None:
            plot_t_ids = self.utils.ladm_data.get_plots_related_to_parcels(
                self.utils._db, [collected_parcel_t_id],
                field_name=ID_FIELD,
                plot_layer=self.utils._layers[PLOT_TABLE][LAYER],
                uebaunit_table=self.utils._layers[UEBAUNIT_TABLE][LAYER])
            if plot_t_ids:
                self._current_substring = "{} IN ('{}')".format(
                    ID_FIELD, "','".join([str(t_id) for t_id in plot_t_ids]))
                if not already_zoomed_in:
                    self.parent.request_zoom_to_features(
                        self.utils._layers[PLOT_TABLE][LAYER], list(),
                        plot_t_ids)

                # Send a custom mouse move on the map to make the map swipe tool's limit appear on the canvas

                # Activate Swipe Tool
                self.utils.qgis_utils.activate_layer_requested.emit(
                    self.utils._official_layers[PLOT_TABLE][LAYER])
                if official_plot_t_ids:  # Otherwise the map swipe tool doesn't add any value :)
                    self.parent.activate_map_swipe_tool()

                    plots = self.utils.ladm_data.get_features_from_t_ids(
                        self.utils._layers[PLOT_TABLE][LAYER], plot_t_ids,
                        True)
                    plots_extent = QgsRectangle()
                    for plot in plots:
                        plots_extent.combineExtentWith(
                            plot.geometry().boundingBox())

                    coord_x = plots_extent.xMaximum() - (plots_extent.xMaximum(
                    ) - plots_extent.xMinimum()) / 9  # 90%
                    coord_y = plots_extent.yMaximum() - (plots_extent.yMaximum(
                    ) - plots_extent.yMinimum()) / 2  # 50%

                    coord_transform = self.utils.iface.mapCanvas(
                    ).getCoordinateTransform()
                    map_point = coord_transform.transform(coord_x, coord_y)
                    widget_point = map_point.toQPointF().toPoint()
                    global_point = self.utils.canvas.mapToGlobal(widget_point)

                    self.utils.canvas.mousePressEvent(
                        QMouseEvent(QEvent.MouseButtonPress, global_point,
                                    Qt.LeftButton, Qt.LeftButton,
                                    Qt.NoModifier))
                    self.utils.canvas.mouseMoveEvent(
                        QMouseEvent(QEvent.MouseMove,
                                    widget_point + QPoint(1, 0), Qt.NoButton,
                                    Qt.LeftButton, Qt.NoModifier))
                    self.utils.canvas.mouseReleaseEvent(
                        QMouseEvent(QEvent.MouseButtonRelease,
                                    widget_point + QPoint(1, 0), Qt.LeftButton,
                                    Qt.LeftButton, Qt.NoModifier))

        # Once the query is done, activate the checkbox to alternate all plots/only selected plot
        self.chk_show_all_plots.setEnabled(True)
Exemple #50
0
    def testCopyPaste(self):
        p = QgsProject()
        l = QgsLayout(p)

        # clear clipboard
        mime_data = QMimeData()
        mime_data.setData("text/xml", QByteArray())
        clipboard = QApplication.clipboard()
        clipboard.setMimeData(mime_data)

        # add an item
        item1 = QgsLayoutItemLabel(l)
        item1.setText('label 1')
        l.addLayoutItem(item1)
        item1.setSelected(True)
        item2 = QgsLayoutItemLabel(l)
        item2.setText('label 2')
        l.addLayoutItem(item2)
        item2.setSelected(True)

        # multiframes
        multiframe1 = QgsLayoutItemHtml(l)
        multiframe1.setHtml('mf1')
        l.addMultiFrame(multiframe1)
        frame1 = QgsLayoutFrame(l, multiframe1)
        frame1.setId('frame1a')
        multiframe1.addFrame(frame1)
        frame1b = QgsLayoutFrame(l, multiframe1)
        frame1b.setId('frame1b')
        multiframe1.addFrame(frame1b)  # not selected
        frame1c = QgsLayoutFrame(l, multiframe1)
        frame1c.setId('frame1b')
        multiframe1.addFrame(frame1c)  # not selected

        multiframe2 = QgsLayoutItemHtml(l)
        multiframe2.setHtml('mf2')
        l.addMultiFrame(multiframe2)
        frame2 = QgsLayoutFrame(l, multiframe2)
        frame2.setId('frame2')
        multiframe2.addFrame(frame2)

        frame1.setSelected(True)
        frame2.setSelected(True)

        view = QgsLayoutView()
        view.setCurrentLayout(l)
        self.assertFalse(view.hasItemsInClipboard())

        view.copySelectedItems(QgsLayoutView.ClipboardCopy)
        self.assertTrue(view.hasItemsInClipboard())

        pasted = view.pasteItems(QgsLayoutView.PasteModeCursor)
        self.assertEqual(len(pasted), 4)

        new_multiframes = [
            m for m in l.multiFrames() if m not in [multiframe1, multiframe2]
        ]
        self.assertEqual(len(new_multiframes), 2)

        self.assertIn(pasted[0], l.items())
        self.assertIn(pasted[1], l.items())
        labels = [
            p for p in pasted if p.type() == QgsLayoutItemRegistry.LayoutLabel
        ]
        self.assertIn(
            sip.cast(labels[0], QgsLayoutItemLabel).text(),
            ('label 1', 'label 2'))
        self.assertIn(
            sip.cast(labels[1], QgsLayoutItemLabel).text(),
            ('label 1', 'label 2'))
        frames = [
            p for p in pasted if p.type() == QgsLayoutItemRegistry.LayoutFrame
        ]
        pasted_frame1 = sip.cast(frames[0], QgsLayoutFrame)
        pasted_frame2 = sip.cast(frames[1], QgsLayoutFrame)
        self.assertIn(pasted_frame1.multiFrame(), new_multiframes)
        self.assertIn(new_multiframes[0].frames()[0].uuid(),
                      (pasted_frame1.uuid(), pasted_frame2.uuid()))
        self.assertIn(pasted_frame2.multiFrame(), new_multiframes)
        self.assertIn(new_multiframes[1].frames()[0].uuid(),
                      (pasted_frame1.uuid(), pasted_frame2.uuid()))

        self.assertEqual(frame1.multiFrame(), multiframe1)
        self.assertCountEqual(multiframe1.frames(), [frame1, frame1b, frame1c])
        self.assertEqual(frame1b.multiFrame(), multiframe1)
        self.assertEqual(frame1c.multiFrame(), multiframe1)
        self.assertEqual(frame2.multiFrame(), multiframe2)
        self.assertCountEqual(multiframe2.frames(), [frame2])

        # copy specific item
        view.copyItems([item2], QgsLayoutView.ClipboardCopy)
        l2 = QgsLayout(p)
        view2 = QgsLayoutView()
        view2.setCurrentLayout(l2)
        pasted = view2.pasteItems(QgsLayoutView.PasteModeCursor)
        self.assertEqual(len(pasted), 1)
        self.assertIn(pasted[0], l2.items())
        self.assertEqual(
            sip.cast(pasted[0], QgsLayoutItemLabel).text(), 'label 2')
Exemple #51
0
    def runAction(self, action):
        action = unicode(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
Exemple #52
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     QApplication.restoreOverrideCursor()
Exemple #53
0
 def _translate(context, text, disambig):
     return QApplication.translate(context, text, disambig)
Exemple #54
0
    def paint(self, painter, option, widget=None):
        rect = self.itemRect()

        if isinstance(self.element, QgsProcessingModelParameter):
            color = QColor(238, 242, 131)
            stroke = QColor(234, 226, 118)
            selected = QColor(116, 113, 68)
        elif isinstance(self.element, QgsProcessingModelChildAlgorithm):
            color = QColor(255, 255, 255)
            stroke = Qt.gray
            selected = QColor(50, 50, 50)
        else:
            color = QColor(172, 196, 114)
            stroke = QColor(90, 140, 90)
            selected = QColor(42, 65, 42)
        if self.isSelected():
            stroke = selected
            color = color.darker(110)
        if self.hover_over_item:
            color = color.darker(105)
        painter.setPen(QPen(stroke, 0))  # 0 width "cosmetic" pen
        painter.setBrush(QBrush(color, Qt.SolidPattern))
        painter.drawRect(rect)
        font = QFont('Verdana', 8)
        font.setPixelSize(12)
        painter.setFont(font)
        painter.setPen(QPen(Qt.black))
        text = self.getAdjustedText(self.text)
        if isinstance(self.element, QgsProcessingModelChildAlgorithm
                      ) and not self.element.isActive():
            painter.setPen(QPen(Qt.gray))
            text = text + "\n(deactivated)"
        fm = QFontMetricsF(font)
        text = self.getAdjustedText(self.text)
        h = fm.ascent()
        pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25,
                     ModelerGraphicItem.BOX_HEIGHT / 2.0 - h + 1)
        painter.drawText(pt, text)
        painter.setPen(QPen(QApplication.palette().color(QPalette.WindowText)))
        if isinstance(self.element, QgsProcessingModelChildAlgorithm):
            h = -(fm.height() * 1.2)
            h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5
            pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h)
            painter.drawText(pt, 'In')
            i = 1
            if not self.element.parametersCollapsed():
                for param in [
                        p for p in
                        self.element.algorithm().parameterDefinitions()
                        if not p.isDestination()
                ]:
                    if not param.flags(
                    ) & QgsProcessingParameterDefinition.FlagHidden:
                        text = self.getAdjustedText(param.description())
                        h = -(fm.height() * 1.2) * (i + 1)
                        h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5
                        pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h)
                        painter.drawText(pt, text)
                        i += 1
            h = fm.height() * 1.1
            h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0
            pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h)
            painter.drawText(pt, 'Out')
            if not self.element.outputsCollapsed():
                for i, out in enumerate(
                        self.element.algorithm().outputDefinitions()):
                    text = self.getAdjustedText(out.description())
                    h = fm.height() * 1.2 * (i + 2)
                    h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0
                    pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h)
                    painter.drawText(pt, text)
        if self.pixmap:
            painter.drawPixmap(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8,
                               self.pixmap)
        elif self.picture:
            painter.drawPicture(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8,
                                self.picture)
Exemple #55
0
def tr(text, context='@default'):
    return QApplication.translate(context, text)
Exemple #56
0
    def run(self):
        project_id = self.settings.value("project/id")
        epsg = self.settings.value("project/epsg")
        self.project_dir = self.settings.value("project/projectdir")
        self.project_id = self.settings.value("project/id")

        locale = QSettings().value('locale/userLocale')[
            0:2]  # this is for multilingual legends

        if locale == "fr":
            pass
        elif locale == "it":
            pass
        else:
            locale = "de"

        if not project_id:
            self.message_bar.pushCritical(
                "Error",
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "project_id not set", None))
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            group = _translate("VeriSO_NPLSO_Erschliessungsplan",
                               "Referenzlayer - Erschliessungsplan", None)
            group += " (" + str(project_id) + ")"

            for file in os.listdir(self.project_dir):
                if file.endswith(".tif"):
                    layer = {
                        "type": "gdal",
                        "title": _translate("VeriSO_NPLSO_Gesamtplan", file,
                                            None),
                        "url": os.path.join(self.project_dir, file),
                        "group": group
                    }
                    vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate(
                    "VeriSO_NPLSO_Erschliessungsplan",
                    "Bewirtschaftungseinheiten mit Direktzahlungsgrösse",
                    None),
                "params": {
                    "dbhost": "geodb.verw.rootso.org",
                    "dbport": 5432,
                    "dbname": "sogis",
                    "dbschema": "gelan"
                },
                "featuretype":
                "gelanx_so_bewe",
                "geom":
                "wkb_geometry",
                "key":
                "ogc_fid",
                "sql":
                "typ_name = 'Anerkannt nach LBV' OR typ_name = 'Betriebsgemeinschaft' OR typ_name='LBV ohne DZ'",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_kant_daten/gelan_bewirtschaftungseinheiten.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "Gelan-Standorte", None),
                "params": {
                    "dbhost": "geodb.verw.rootso.org",
                    "dbport": 5432,
                    "dbname": "sogis",
                    "dbschema": "gelan"
                },
                "featuretype":
                "gelanx_so_stao_point",
                "geom":
                "wkb_geometry",
                "key":
                "ogc_fid",
                "sql":
                "betriebtyp = 'Anerkannt nach LBV' OR betriebtyp = 'Betriebsgemeinschaft' OR betriebtyp='LBV ohne DZ'",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_kant_daten/gelan_standorte.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "Grundwasserschutzzonen und -areale", None),
                "params": {
                    "dbhost": "geodb.verw.rootso.org",
                    "dbport": 5432,
                    "dbname": "sogis",
                    "dbschema": "public"
                },
                "featuretype":
                "aww_gszoar",
                "geom":
                "wkb_geometry",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_kant_daten/grundwasserschutz.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "Archäologische Fundstellen - Punktfundstellen",
                           None),
                "params": {
                    "dbhost": "geodb.verw.rootso.org",
                    "dbport": 5432,
                    "dbname": "sogis",
                    "dbschema": "ada_adagis_a"
                },
                "featuretype":
                "punktfundstellen",
                "geom":
                "geometrie",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_kant_daten/archaeologische_fundstellen_punktfundstellen.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "Archäologische Fundstellen - Flächenfundstellen",
                           None),
                "params": {
                    "dbhost": "geodb.verw.rootso.org",
                    "dbport": 5432,
                    "dbname": "sogis",
                    "dbschema": "ada_adagis_a"
                },
                "featuretype":
                "flaechenfundstellen",
                "geom":
                "geometrie",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_kant_daten/archaeologische_fundstellen_flaechenfundstellen.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "historische Verkehrswege", None),
                "params": {
                    "dbhost": "geodb.verw.rootso.org",
                    "dbport": 5432,
                    "dbname": "sogis",
                    "dbschema": "public"
                },
                "featuretype":
                "arp_ivsso_line",
                "geom":
                "wkb_geometry",
                "key":
                "ogc_fid",
                "sql":
                "archive=0",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_kant_daten/historische_verkehrswege.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "Grundnutzung Linie", None),
                "featuretype":
                "t_nutzungsplanung_grundnutzung",
                "geom":
                "geometrie",
                "key":
                "t_id",
                "sql":
                "typ_code_kommunal::numeric > 1919",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_erschliessung/t_grundnutzung_linie.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "Erschliessung Flaechenobjekt", None),
                "featuretype":
                "t_erschliessung_flaechenobjekt",
                "geom":
                "geometrie",
                "key":
                "t_id",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_erschliessung/t_erschliessung_flaechenobjekt.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "Erschliessung Linienobjekt", None),
                "featuretype":
                "t_erschliessung_linienobjekt",
                "geom":
                "geometrie",
                "key":
                "t_id",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_erschliessung/t_erschliessung_linienobjekt.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "Erschliessung Punktobjekt", None),
                "featuretype":
                "t_erschliessung_punktobjekt",
                "geom":
                "geometrie",
                "key":
                "t_id",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_erschliessung/t_erschliessung_punktobjekt.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "90000 Grundstücke aggregiert", None),
                "featuretype":
                "t_grundstuecke_90000_aggregiert",
                "geom":
                "geometrie",
                "key":
                "id",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_erschliessung/t_grundstuecke_90000_aggregiert.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "AV Gewaesser gepuffert 4m", None),
                "featuretype":
                "t_av_gewaesser_gepuffert",
                "geom":
                "geometrie",
                "key":
                "id",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_erschliessung/t_av_gewaesser_gepuffert.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_NPLSO_Erschliessungsplan",
                           "Verkehrszone gepuffert 4m, 5m, 6m", None),
                "featuretype":
                "t_verkehrszone_gepuffert",
                "geom":
                "geometrie",
                "key":
                "t_id",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "referenzlayer_erschliessung/t_verkehrszone_gepuffert.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True, False)

        except Exception:
            QApplication.restoreOverrideCursor()
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.message_bar.pushMessage(
                "Error",
                str(traceback.format_exc(exc_traceback)),
                level=QgsMessageBar.CRITICAL,
                duration=0)
        QApplication.restoreOverrideCursor()
Exemple #57
0
 def apply_values(self, new_values):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.handler.select(self.selection_tool.selected_geometries, all_touched_cells=self.all_touched)
     self.handler.write_block(new_values)
     QApplication.restoreOverrideCursor()
     self.raster.triggerRepaint()
    def accept(self, *args, **kwargs):
        if not self.validate():
            return False
        try:

            QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

            LOGGER.info('{st}\nProcessing {} Raster'.format(
                self.cboMethod.currentText(), st='*' * 50))
            self.iface.mainWindow().statusBar().showMessage(
                'Processing {} Raster'.format(self.cboMethod.currentText()))

            # Add settings to log
            settingsStr = 'Parameters:---------------------------------------'
            settingsStr += '\n    {:30}\t{}'.format(
                'Layer:',
                self.mcboTargetLayer.currentLayer().name())
            settingsStr += '\n    {:30}\t{}'.format('For Band: ',
                                                    self.cboBand.currentText())
            settingsStr += '\n    {:30}\t{}'.format(
                'Method: ', self.cboMethod.currentText())
            if self.cboMethod.currentText() == 'Rescale':
                settingsStr += '\n    {:30}\t{} - {}'.format(
                    'Between:', self.dsbRescaleLower.value(),
                    self.dsbRescaleUpper.value())
            settingsStr += '\n    {:30}\t{}'.format(
                'Output Raster File:', self.lneSaveRasterFile.text())

            LOGGER.info(settingsStr)

            lyrTarget = self.mcboTargetLayer.currentLayer()
            rasterOut = self.lneSaveRasterFile.text()
            removeFileFromQGIS(rasterOut)

            rasterIn = get_layer_source(lyrTarget)
            # need this to maintain correct wkt otherwise gda/mga defaults to utm zonal
            in_crswkt = lyrTarget.crs().toWkt()

            band_num = int(self.cboBand.currentText().replace('Band ', ''))
            with rasterio.open(os.path.normpath(rasterIn)) as src:
                if self.cboMethod.currentText() == 'Rescale':
                    rast_result = rescale(src,
                                          self.dsbRescaleLower.value(),
                                          self.dsbRescaleUpper.value(),
                                          band_num=band_num,
                                          ignore_nodata=True)
                else:
                    rast_result = normalise(src,
                                            band_num=band_num,
                                            ignore_nodata=True)
                meta = src.meta.copy()

                meta['crs'] = str(in_crswkt)
                meta['count'] = 1
                meta['dtype'] = rasterio.float32

            with rasterio.open(os.path.normpath(rasterOut), 'w',
                               **meta) as dst:
                dst.write_band(1, rast_result)

            rasterLyr = addRasterFileToQGIS(rasterOut, atTop=False)

            QApplication.restoreOverrideCursor()
            self.iface.mainWindow().statusBar().clearMessage()
            return super(RescaleNormaliseDialog, self).accept(*args, **kwargs)

        except Exception as err:
            QApplication.restoreOverrideCursor()
            self.cleanMessageBars(True)
            self.iface.mainWindow().statusBar().clearMessage()

            self.send_to_messagebar(str(err),
                                    level=Qgis.Critical,
                                    duration=0,
                                    addToLog=True,
                                    exc_info=sys.exc_info())
            return False  # leave dialog open
    def test(self):

        # This test is quite fragile as it depends on windows manager behavior
        # regarding focus, so not surprising it doesn't pass
        # on other platforms than Linux.
        # if 'TRAVIS_OS_NAME' in os.environ and os.environ['TRAVIS_OS_NAME'] == 'osx':
        #    return

        main_dialog = QgsProviderRegistry.instance().createSelectionWidget(
            "WFS")
        main_dialog.setProperty("hideDialogs", True)

        self.assertIsNotNone(main_dialog)

        # Create new connection
        btnNew = main_dialog.findChild(QWidget, "btnNew")
        self.assertIsNotNone(btnNew)
        QTest.mouseClick(btnNew, Qt.LeftButton)
        new_conn = find_window('QgsNewHttpConnectionBase')
        self.assertIsNotNone(new_conn)
        txtName = new_conn.findChild(QLineEdit, "txtName")
        self.assertIsNotNone(txtName)
        txtName.setText("test_connection")
        txtUrl = new_conn.findChild(QLineEdit, "txtUrl")
        self.assertIsNotNone(txtUrl)
        txtUrl.setText("test_url")
        new_conn.accept()

        # Wait for object to be destroyed
        new_conn = self.wait_object_destruction(new_conn)

        # Try to connect
        btnConnect = main_dialog.findChild(QWidget, "btnConnect")
        self.assertIsNotNone(btnConnect)
        QTest.mouseClick(btnConnect, Qt.LeftButton)
        # Depends on asynchronous signal
        QApplication.processEvents()
        error_box = find_window('WFSCapabilitiesErrorBox')
        self.assertIsNotNone(error_box)
        # Close error box
        error_box.accept()

        # Wait for object to be destroyed
        error_box = self.wait_object_destruction(error_box)

        # Edit connection
        btnEdit = main_dialog.findChild(QWidget, "btnEdit")
        self.assertIsNotNone(btnEdit)
        QTest.mouseClick(btnEdit, Qt.LeftButton)
        new_conn = find_window('QgsNewHttpConnectionBase', )
        self.assertIsNotNone(new_conn)
        txtName = new_conn.findChild(QLineEdit, "txtName")
        self.assertIsNotNone(txtName)
        txtName.setText("test_connection")
        txtUrl = new_conn.findChild(QLineEdit, "txtUrl")
        self.assertIsNotNone(txtUrl)

        endpoint = self.basetestpath + '/fake_qgis_http_endpoint'
        expected_endpoint = endpoint
        if sys.platform == 'win32' and expected_endpoint[1] == ':':
            expected_endpoint = expected_endpoint[0] + expected_endpoint[2:]
        with open(
                sanitize(
                    endpoint,
                    '?SERVICE=WFS?REQUEST=GetCapabilities?ACCEPTVERSIONS=2.0.0,1.1.0,1.0.0'
                ), 'wb') as f:
            f.write("""
<wfs:WFS_Capabilities version="2.0.0" xmlns="http://www.opengis.net/wfs/2.0" xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:gml="http://schemas.opengis.net/gml/3.2" xmlns:fes="http://www.opengis.net/fes/2.0">
  <FeatureTypeList>
    <FeatureType>
      <Name>my:typename</Name>
      <Title>Title</Title>
      <Abstract>Abstract</Abstract>
      <DefaultCRS>urn:ogc:def:crs:EPSG::4326</DefaultCRS>
      <ows:WGS84BoundingBox>
        <ows:LowerCorner>-71.123 66.33</ows:LowerCorner>
        <ows:UpperCorner>-65.32 78.3</ows:UpperCorner>
      </ows:WGS84BoundingBox>
    </FeatureType>
  </FeatureTypeList>
  <fes:Filter_Capabilities>
    <fes:Spatial_Capabilities>
      <fes:GeometryOperands>
        <fes:GeometryOperand name="gml:Envelope"/>
        <fes:GeometryOperand name="gml:Point"/>
        <fes:GeometryOperand name="gml:MultiPoint"/>
        <fes:GeometryOperand name="gml:LineString"/>
        <fes:GeometryOperand name="gml:MultiLineString"/>
        <fes:GeometryOperand name="gml:Polygon"/>
        <fes:GeometryOperand name="gml:MultiPolygon"/>
        <fes:GeometryOperand name="gml:MultiGeometry"/>
      </fes:GeometryOperands>
      <fes:SpatialOperators>
        <fes:SpatialOperator name="Disjoint"/>
        <fes:SpatialOperator name="Equals"/>
        <fes:SpatialOperator name="DWithin"/>
        <fes:SpatialOperator name="Beyond"/>
        <fes:SpatialOperator name="Intersects"/>
        <fes:SpatialOperator name="Touches"/>
        <fes:SpatialOperator name="Crosses"/>
        <fes:SpatialOperator name="Within"/>
        <fes:SpatialOperator name="Contains"/>
        <fes:SpatialOperator name="Overlaps"/>
        <fes:SpatialOperator name="BBOX"/>
      </fes:SpatialOperators>
    </fes:Spatial_Capabilities>
    <fes:Functions>
      <fes:Function name="abs">
        <fes:Returns>xs:int</fes:Returns>
        <fes:Arguments>
          <fes:Argument name="param">
            <fes:Type>xs:int</fes:Type>
          </fes:Argument>
        </fes:Arguments>
      </fes:Function>
    </fes:Functions>
  </fes:Filter_Capabilities>
</wfs:WFS_Capabilities>""".encode('UTF-8'))

        txtUrl.setText("http://" + endpoint)
        new_conn.accept()

        # Wait for object to be destroyed
        new_conn = self.wait_object_destruction(new_conn)

        # Try to connect
        btnConnect = main_dialog.findChild(QWidget, "btnConnect")
        self.assertIsNotNone(btnConnect)
        QTest.mouseClick(btnConnect, Qt.LeftButton)

        buttonAdd = self.get_button_add(main_dialog)
        for i in range(10):
            QApplication.processEvents()
            if buttonAdd.isEnabled():
                break
        self.assertTrue(buttonAdd.isEnabled())

        # Add layer
        self.addWfsLayer_uri = None
        self.addWfsLayer_layer_name = None
        main_dialog.addVectorLayer.connect(self.slotAddWfsLayer)
        QTest.mouseClick(buttonAdd, Qt.LeftButton)
        self.assertEqual(
            self.addWfsLayer_uri,
            ' restrictToRequestBBOX=\'1\' srsname=\'EPSG:4326\' typename=\'my:typename\' url=\''
            + "http://" + expected_endpoint +
            '\' version=\'auto\' table="" sql=')
        self.assertEqual(self.addWfsLayer_layer_name, 'my:typename')

        # Click on Build Query
        buttonBuildQuery = self.get_button_build_query(main_dialog)
        self.assertTrue(buttonBuildQuery.isEnabled())
        QTest.mouseClick(buttonBuildQuery, Qt.LeftButton)
        error_box = find_window('WFSFeatureTypeErrorBox')
        self.assertIsNotNone(error_box)
        # Close error box
        error_box.accept()
        # Wait for object to be destroyed
        error_box = self.wait_object_destruction(error_box)

        # Click again but with valid DescribeFeatureType

        with open(
                sanitize(
                    endpoint,
                    '?SERVICE=WFS&REQUEST=DescribeFeatureType&VERSION=2.0.0&TYPENAME=my:typename'
                ), 'wb') as f:
            f.write("""
<xsd:schema xmlns:my="http://my" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://my">
  <xsd:import namespace="http://www.opengis.net/gml/3.2"/>
  <xsd:complexType name="typenameType">
    <xsd:complexContent>
      <xsd:extension base="gml:AbstractFeatureType">
        <xsd:sequence>
          <xsd:element maxOccurs="1" minOccurs="0" name="intfield" nillable="true" type="xsd:int"/>
          <xsd:element maxOccurs="1" minOccurs="0" name="geometryProperty" nillable="true" type="gml:PolygonPropertyType"/>
        </xsd:sequence>
      </xsd:extension>
    </xsd:complexContent>
  </xsd:complexType>
  <xsd:element name="typename" substitutionGroup="gml:_Feature" type="my:typenameType"/>
</xsd:schema>
""".encode('UTF-8'))
        QTest.mouseClick(buttonBuildQuery, Qt.LeftButton)

        # Check that the combos are properly initialized
        dialog = find_window('QgsSQLComposerDialogBase')
        self.assertIsNotNone(dialog)

        mTablesCombo = dialog.findChild(QComboBox, "mTablesCombo")
        self.assertIsNotNone(mTablesCombo)
        self.assertEqual(mTablesCombo.itemText(1), 'typename (Title)')

        mColumnsCombo = dialog.findChild(QComboBox, "mColumnsCombo")
        self.assertIsNotNone(mColumnsCombo)
        self.assertEqual(mColumnsCombo.itemText(1), 'intfield (int)')
        self.assertEqual(mColumnsCombo.itemText(mColumnsCombo.count() - 2),
                         'geometryProperty (geometry)')
        self.assertEqual(mColumnsCombo.itemText(mColumnsCombo.count() - 1),
                         '*')

        mFunctionsCombo = dialog.findChild(QComboBox, "mFunctionsCombo")
        self.assertIsNotNone(mFunctionsCombo)
        self.assertEqual(mFunctionsCombo.itemText(1), 'abs(param: int): int')

        mSpatialPredicatesCombo = dialog.findChild(QComboBox,
                                                   "mSpatialPredicatesCombo")
        self.assertIsNotNone(mSpatialPredicatesCombo)
        self.assertEqual(mSpatialPredicatesCombo.itemText(1),
                         'ST_Disjoint(geometry, geometry): boolean')

        mWhereEditor = dialog.findChild(QTextEdit, "mWhereEditor")
        self.assertIsNotNone(mWhereEditor)
        mWhereEditor.setText('1 = 1')

        dialog.accept()
        # Wait for object to be destroyed
        dialog = self.wait_object_destruction(dialog)

        # Add layer
        buttonAdd = self.get_button_add(main_dialog)
        self.assertTrue(buttonAdd.isEnabled())

        self.addWfsLayer_uri = None
        self.addWfsLayer_layer_name = None
        main_dialog.addVectorLayer.connect(self.slotAddWfsLayer)
        QTest.mouseClick(buttonAdd, Qt.LeftButton)
        self.assertEqual(
            self.addWfsLayer_uri,
            ' restrictToRequestBBOX=\'1\' srsname=\'EPSG:4326\' typename=\'my:typename\' url=\''
            + "http://" + expected_endpoint +
            '\' version=\'auto\' table="" sql=SELECT * FROM typename WHERE 1 = 1'
        )
        self.assertEqual(self.addWfsLayer_layer_name, 'my:typename')
Exemple #60
0
 def apply_low_pass_filter(self):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.handler.select(self.selection_tool.selected_geometries, all_touched_cells=self.all_touched)
     self.handler.write_block(low_pass_filter=True)
     QApplication.restoreOverrideCursor()
     self.raster.triggerRepaint()