Ejemplo n.º 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()
Ejemplo n.º 2
0
    def canvasReleaseEvent(self, e):
        point = self.plugin.transform(
            self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(e.x(), e.y())
        )

        QApplication.setOverrideCursor(Qt.WaitCursor)

        fs = self.plugin.highlight(
            where=u"st_contains(wkb_geometry,st_geomfromtext('POINT(%.3lf %.3lf)'::text,%d))" % (
                point.x(), point.y(), self.plugin.getepsg()
            )
        )

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

        try:
            s = QSettings("norBIT", "EDBSgen/PRO")
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(("localhost", int(s.value("norGISPort", "6102"))))
            sock.send("NORGIS_MAIN#EDBS#ALBKEY#{}#".format(fs[0]['flsnr']).encode("utf-8"))
            sock.close()

            if win32:
                window = win32gui.FindWindow(None, s.value("albWin", "norGIS"))
                win32gui.SetForegroundWindow(window)
        except socket.error:
            QMessageBox.information(None, u"Fehler", u"Verbindung zu norGIS schlug fehl.")

        QApplication.restoreOverrideCursor()
Ejemplo n.º 3
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())
Ejemplo n.º 4
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()
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
    def runAction(self, action):
        action = str(action)

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

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

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

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

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

        return Table.runAction(self, action)
    def refresh_databases(self):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        if self.clouddb:
            db_list = self.api.read_databases()
            if self.show_api_error(db_list):
                QApplication.restoreOverrideCursor()
                return
            self.db_connections = DbConnections()
            for db in db_list:
                self.db_connections.add_from_json(db)

            self.ui.tabDatabases.clear()
            self.ui.btnDbDelete.setEnabled(False)
            self.ui.cbUploadDatabase.clear()
            self.ui.cbUploadDatabase.setEditable(True)
            self.ui.cbUploadDatabase.lineEdit().setReadOnly(True)
            if self.db_connections.count() == 0:
                self.ui.cbUploadDatabase.setEditText(self.tr("No databases"))
            else:
                for name, db in list(self.db_connections.iteritems()):
                    it = QListWidgetItem(name)
                    it.setToolTip(db.description())
                    self.ui.tabDatabases.addItem(it)
                    self.ui.cbUploadDatabase.addItem(name)
                if self.ui.cbUploadDatabase.count() > 1:
                    # Display the "Select database" text if more than one db is available
                    self.ui.cbUploadDatabase.setCurrentIndex(-1)
                    self.ui.cbUploadDatabase.setEditText(self.tr("Select database"))
            self.db_connections.refresh(self.user)

        self.db_size(self.db_connections)
        QApplication.restoreOverrideCursor()
Ejemplo n.º 8
0
    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()
Ejemplo n.º 9
0
    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()
Ejemplo n.º 10
0
    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()
Ejemplo n.º 11
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
Ejemplo n.º 12
0
    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()
Ejemplo n.º 13
0
 def updateAlgsList():
     """Call this method when there has been any change that
     requires the list of algorithms to be created again from
     algorithm providers.
     """
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     Processing.loadFromProviders()
     QApplication.restoreOverrideCursor()
Ejemplo n.º 14
0
def execute(func):
    try:
        QCoreApplication.processEvents()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        return func()
    finally:
        QApplication.restoreOverrideCursor()
        QCoreApplication.processEvents()
Ejemplo n.º 15
0
 def addLessons(self):
     ret, __ = QFileDialog.getOpenFileName(self, "Select lessons ZIP file" , "", '*.zip')
     if ret:
         try:
             QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
             installLessonsFromZipFile(ret)
             self.fillTree()
         finally:
             QApplication.restoreOverrideCursor()
Ejemplo n.º 16
0
    def runAction(self, action):
        action = str(action)

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

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

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

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

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

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

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

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

        return False
Ejemplo n.º 17
0
 def tabChanged(self, index):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     try:
         self.refreshTabs()
     except BaseError as e:
         DlgDbError.showError(e, self)
         return
     finally:
         QApplication.restoreOverrideCursor()
Ejemplo n.º 18
0
    def createTable(self):
        """ create table with chosen fields, optionally add a geometry column """
        if not self.hasSchemas:
            schema = None
        else:
            schema = str(self.cboSchema.currentText())
            if len(schema) == 0:
                QMessageBox.information(self, self.tr("DB Manager"), self.tr("select schema!"))
                return

        table = str(self.editName.text())
        if len(table) == 0:
            QMessageBox.information(self, self.tr("DB Manager"), self.tr("enter table name!"))
            return

        m = self.fields.model()
        if m.rowCount() == 0:
            QMessageBox.information(self, self.tr("DB Manager"), self.tr("add some fields!"))
            return

        useGeomColumn = self.chkGeomColumn.isChecked()
        if useGeomColumn:
            geomColumn = str(self.editGeomColumn.text())
            if len(geomColumn) == 0:
                QMessageBox.information(self, self.tr("DB Manager"), self.tr("set geometry column name"))
                return

            geomType = self.GEOM_TYPES[self.cboGeomType.currentIndex()]
            geomDim = self.spinGeomDim.value()
            try:
                geomSrid = int(self.editGeomSrid.text())
            except ValueError:
                geomSrid = 0
            useSpatialIndex = self.chkSpatialIndex.isChecked()

        flds = m.getFields()
        pk_index = self.cboPrimaryKey.currentIndex()
        if pk_index >= 0:
            flds[pk_index].primaryKey = True

        # commit to DB
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            if not useGeomColumn:
                self.db.createTable(table, flds, schema)
            else:
                geom = geomColumn, geomType, geomSrid, geomDim, useSpatialIndex
                self.db.createVectorTable(table, flds, geom, schema)

        except (ConnectionError, DbError) as e:
            DlgDbError.showError(e, self)
            return

        finally:
            QApplication.restoreOverrideCursor()

        QMessageBox.information(self, self.tr("Good"), self.tr("everything went fine"))
Ejemplo n.º 19
0
 def grabHTTP(self, url, loadFunction, arguments=None):
     """Grab distant content via QGIS internal classes and QtNetwork."""
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     request = QUrl(url)
     reply = self.manager.get(QNetworkRequest(request))
     if arguments:
         reply.finished.connect(partial(loadFunction, reply, arguments))
     else:
         reply.finished.connect(partial(loadFunction, reply))
Ejemplo n.º 20
0
def run(item, action, mainwindow):
    from .dlg_versioning import DlgVersioning

    dlg = DlgVersioning(item, mainwindow)

    QApplication.restoreOverrideCursor()
    try:
        dlg.exec_()
    finally:
        QApplication.setOverrideCursor(Qt.WaitCursor)
Ejemplo n.º 21
0
    def loadSqlLayer(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            layer = self._getSqlLayer(self.filter)
            if layer is None:
                return

            QgsProject.instance().addMapLayers([layer], True)
        finally:
            QApplication.restoreOverrideCursor()
 def getHtmlFromTemplate(self, tplPath, replaceDict):
     '''
     Get the content of a template file
     and replace all variables with given data
     '''
     QApplication.setOverrideCursor(Qt.WaitCursor)
     try:
         return super().getHtmlFromTemplate(tplPath, replaceDict)
     finally:
         QApplication.restoreOverrideCursor()
Ejemplo n.º 23
0
 def deleteActionSlot(self, item, action, parent):
     if isinstance(item, Schema):
         self.deleteSchemaActionSlot(item, action, parent)
     elif isinstance(item, Table):
         self.deleteTableActionSlot(item, action, parent)
     else:
         QApplication.restoreOverrideCursor()
         parent.infoBar.pushMessage(QApplication.translate("DBManagerPlugin", "Cannot delete the selected item."),
                                    QgsMessageBar.INFO, parent.iface.messageTimeout())
         QApplication.setOverrideCursor(Qt.WaitCursor)
Ejemplo n.º 24
0
 def uninstallPlugin(self, key, quiet=False):
     """ Uninstall given plugin """
     if key in plugins.all():
         plugin = plugins.all()[key]
     else:
         plugin = plugins.localCache[key]
     if not plugin:
         return
     if not quiet:
         warning = self.tr("Are you sure you want to uninstall the following plugin?") + "\n(" + plugin["name"] + ")"
         if plugin["status"] == "orphan" and not plugin["error"]:
             warning += "\n\n" + self.tr("Warning: this plugin isn't available in any accessible repository!")
         if (
             QMessageBox.warning(
                 iface.mainWindow(),
                 self.tr("QGIS Python Plugin Installer"),
                 warning,
                 QMessageBox.Yes,
                 QMessageBox.No,
             )
             == QMessageBox.No
         ):
             return
     # unload the plugin
     QApplication.setOverrideCursor(Qt.WaitCursor)
     try:
         unloadPlugin(key)
     except:
         pass
     pluginDir = qgis.utils.home_plugin_path + "/" + plugin["id"]
     result = removeDir(pluginDir)
     if result:
         QApplication.restoreOverrideCursor()
         msg = "<b>%s:</b>%s" % (self.tr("Plugin uninstall failed"), result)
         iface.pluginManagerInterface().pushMessage(msg, QgsMessageBar.CRITICAL)
     else:
         # safe remove
         try:
             unloadPlugin(plugin["id"])
         except:
             pass
         try:
             exec("plugins[%s].unload()" % plugin["id"])
             exec("del plugins[%s]" % plugin["id"])
         except:
             pass
         try:
             exec("del sys.modules[%s]" % plugin["id"])
         except:
             pass
         plugins.getAllInstalled()
         plugins.rebuild()
         self.exportPluginsToManager()
         QApplication.restoreOverrideCursor()
         iface.pluginManagerInterface().pushMessage(self.tr("Plugin uninstalled successfully"), QgsMessageBar.INFO)
 def publish_map(self):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     srs=QgsMapSettings().destinationCrs()
     
     if "USER" in srs.authid():
         QMessageBox.warning(None, self.tr('Warning!'),  self.tr("The project has a user defined CRS. The use of user defined CRS is not supported. Please correct the project CRS before publishing!"))
         QApplication.restoreOverrideCursor()
         return 
         
     layer_dict = QgsProject.instance().mapLayers()
     layers = list(layer_dict.values())                    
     layerList = ''
     
     for layer in layers:
         if "USER" in layer.crs().authid():
              layerList += "'"+layer.name()+"' "
     
     if len(layerList) > 0:
         QMessageBox.warning(None, self.tr('Warning!'),  self.tr("The layer(s) {layerlist}have user defined CRS. The use of user defined CRS is not supported. Please correct the CRS before publishing!").format(layerlist=layerList))
         QApplication.restoreOverrideCursor()
         return
              
     saved = self.check_project_saved()
     if not saved:
         self.statusBar().showMessage(self.tr("Cancelled"))
     elif self.check_login() and self.check_layers():
         self.statusBar().showMessage(self.tr("Publishing map"))
         try:
             fullExtent = self.iface.mapCanvas().fullExtent()
             config = {
                 'fullExtent': {
                     'xmin': fullExtent.xMinimum(),
                     'ymin': fullExtent.yMinimum(),
                     'xmax': fullExtent.xMaximum(),
                     'ymax': fullExtent.yMaximum()
                     #},
                     # 'svgPaths': QgsApplication.svgPaths() #For resolving absolute symbol paths in print composer
                 }
             }
             
             fname = str(QgsProject.instance().fileName())
             map = self.api.create_map( self.map(), fname, config)['map']
             self.show_api_error(map)
             if map['config']['missingSvgSymbols']:
                 self.publish_symbols(map['config']['missingSvgSymbols'])
             self.update_urls()
             self._push_message(self.tr("QGIS Cloud"), self.tr(
                 "Map successfully published"), level=0, duration=2)
             self.statusBar().showMessage(
                 self.tr("Map successfully published"))
         except Exception as e:
             self.statusBar().showMessage("")
             ErrorReportDialog(self.tr("Error uploading project"), self.tr("An error occured."), str(e) + "\n" + traceback.format_exc(), self.user, self).exec_()
     self.refresh_maps()
     QApplication.restoreOverrideCursor()
Ejemplo n.º 26
0
    def navigate(self):
        """manage navigation / paging"""

        caller = self.sender().objectName()

        if caller == 'btnFirst':
            self.startfrom = 0
        elif caller == 'btnLast':
            self.startfrom = self.catalog.results['matches'] - self.maxrecords
        elif caller == 'btnNext':
            self.startfrom += self.maxrecords
            if self.startfrom >= self.catalog.results["matches"]:
                msg = self.tr('End of results. Go to start?')
                res = QMessageBox.information(self, self.tr('Navigation'),
                                              msg,
                                              (QMessageBox.Ok |
                                               QMessageBox.Cancel))
                if res == QMessageBox.Ok:
                    self.startfrom = 0
                else:
                    return
        elif caller == "btnPrev":
            self.startfrom -= self.maxrecords
            if self.startfrom <= 0:
                msg = self.tr('Start of results. Go to end?')
                res = QMessageBox.information(self, self.tr('Navigation'),
                                              msg,
                                              (QMessageBox.Ok |
                                               QMessageBox.Cancel))
                if res == QMessageBox.Ok:
                    self.startfrom = (self.catalog.results['matches'] -
                                      self.maxrecords)
                else:
                    return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            self.catalog.getrecords2(constraints=self.constraints,
                                     maxrecords=self.maxrecords,
                                     startposition=self.startfrom, esn='full')
        except ExceptionReport as err:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, self.tr('Search error'),
                                self.tr('Search error: %s') % err)
            return
        except Exception as err:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, self.tr('Connection error'),
                                self.tr('Connection error: %s') % err)
            return

        QApplication.restoreOverrideCursor()

        self.display_results()
Ejemplo n.º 27
0
    def runVacuumActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, (DBPlugin, Table)) or item.database() is None:
                parent.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."),
                                           QgsMessageBar.INFO, parent.iface.messageTimeout())
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        self.runVacuum()
Ejemplo n.º 28
0
    def runRefreshMaterializedViewSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, PGTable) or item._relationType != 'm':
                parent.infoBar.pushMessage(self.tr("Select a materialized view for refresh."), QgsMessageBar.INFO,
                                           parent.iface.messageTimeout())
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.runRefreshMaterializedView()
Ejemplo n.º 29
0
    def createTableActionSlot(self, item, action, parent):
        QApplication.restoreOverrideCursor()
        if not hasattr(item, 'database') or item.database() is None:
            parent.infoBar.pushMessage(
                QApplication.translate("DBManagerPlugin", "No database selected or you are not connected to it."),
                QgsMessageBar.INFO, parent.iface.messageTimeout())
            return
        from ..dlg_create_table import DlgCreateTable

        DlgCreateTable(item, parent).exec_()
        QApplication.setOverrideCursor(Qt.WaitCursor)
Ejemplo n.º 30
0
    def moveTableToSchemaActionSlot(self, item, action, parent, new_schema):
        QApplication.restoreOverrideCursor()
        try:
            if not isinstance(item, Table):
                parent.infoBar.pushMessage(QApplication.translate("DBManagerPlugin", "Select a table/view."),
                                           QgsMessageBar.INFO, parent.iface.messageTimeout())
                return
        finally:
            QApplication.setOverrideCursor(Qt.WaitCursor)

        item.moveToSchema(new_schema)
Ejemplo n.º 31
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_PNF_Baugebiet", "project_id not "
                           "set", None))
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            group = _translate("VeriSO_PNF_Baugebiet",
                               "Checklayer - Bebautes Gebiet", None)
            group += " (" + str(project_id) + ")"

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "BB.Objektname 'u.'", None),
                "featuretype":
                "t_bbobj_u",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "EO.Objektname 'u.'", None),
                "featuretype":
                "t_eoobj_u",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet",
                           "EO.Treppe nicht ein Objekt", None),
                "featuretype":
                "t_treppe_modellbildung",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet",
                           "EO.Flächenelement 'übrig. Geb.teil' freistehend",
                           None),
                "featuretype":
                "t_gebteil_frei",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate(
                    "VeriSO_PNF_Baugebiet",
                    "EO.Linienelement 'übrig. Geb.teil' ausserhalb Gebäude",
                    None),
                "featuretype":
                "t_gebteil_ausserhalb",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate(
                    "VeriSO_PNF_Baugebiet",
                    "EO.Flächenelement 'übrig. Geb.teil' innerhalb Gebäude",
                    None),
                "featuretype":
                "t_gebteil_geb",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "EO.Pfeiler im Gebäude",
                           None),
                "featuretype":
                "t_pfeiler_gebaeude",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet",
                           "EO.uebriger_Gebaeudeteil < 1.5 m2", None),
                "featuretype":
                "t_gebteil_15",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "Ein EO.Objekt pro Element",
                           None),
                "featuretype":
                "t_eo_modellbildung",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet",
                           "BB. Wasserbecken mit EO.Mauer", None),
                "featuretype":
                "t_mauer_wasserbecken",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "EO.Linienelement Mauer",
                           None),
                "featuretype":
                "t_mauer_linien",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate(
                    "VeriSO_PNF_Baugebiet",
                    "EO Linienelement Mauer ausserhalb EO.Flächenelement Mauer",
                    None),
                "featuretype":
                "t_mauer_ausserhalb",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "EO.Mauer freistehend",
                           None),
                "featuretype":
                "t_mauer_freistehend",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "EO.Mauer nicht ein Objekt",
                           None),
                "featuretype":
                "t_mauer_modellbildung",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet",
                           "BB.Gebaeude ohne Gartenanlage", None),
                "featuretype":
                "t_abgrenzung_gartenanlage",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet",
                           "BB.Gebaeude ohne Erschliessung", None),
                "featuretype":
                "t_geb_ohne_ersch",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "BB.Parkplatz < 100 m2",
                           None),
                "featuretype":
                "t_pp_kleiner_100",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet",
                           "BB.Gebaeude mit mehreren Adressen", None),
                "featuretype":
                "t_2_gebein",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "BB.Gebaeude < 6 m2", None),
                "featuretype":
                "t_gebaeude_kleiner_6",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet",
                           "EO.Linienelement unterird. Gebaeude", None),
                "featuretype":
                "t_u_geb_linien",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, True, False)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_PNF_Baugebiet", "EO.Unterstand auf Gebäude",
                           None),
                "featuretype":
                "t_unterstand_auf_geb",
                "geom":
                "the_geom",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "checks/checklayer_punkt.qml"
            }
            vlayer = self.layer_loader.load(layer, 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()
Ejemplo n.º 32
0
    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_path = project.fileName()
        project_filename, _ = os.path.splitext(
            os.path.basename(original_project_path))

        # 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())

            self.total_progress_updated.emit(0, 1,
                                             self.tr('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
            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.tr('Copying layers'))
                layer_source = LayerSource(layer)

                if layer_source.action == SyncAction.OFFLINE:
                    if self.project_configuration.offline_copy_only_aoi:
                        layer.selectByRect(self.extent)
                    self.__offline_layers.append(layer)
                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)
            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]
                    if not self.offline_editing.convertToOfflineProject(
                            self.export_folder, gpkg_filename,
                            offline_layer_ids,
                            self.project_configuration.offline_copy_only_aoi,
                            self.offline_editing.GPKG):
                        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]
                    if not self.offline_editing.convertToOfflineProject(
                            self.export_folder, spatialite_filename,
                            offline_layer_ids,
                            self.project_configuration.offline_copy_only_aoi):
                        raise Exception(
                            self.
                            tr("Error trying to convert layers to offline layers"
                               ))

            # 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.total_progress_updated.emit(100, 100, self.tr('Finished'))
Ejemplo n.º 33
0
    def accept(self):
        alg_parameters = []
        load = []

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

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

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

            alg_parameters.append(parameters)

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

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

        start_time = time.time()

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

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

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

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

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

        self.finish(algorithm_results)
        self.buttonCancel.setEnabled(False)
Ejemplo n.º 34
0
def execute(func):
    QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
    try:
        return func()
    finally:
        QApplication.restoreOverrideCursor()
Ejemplo n.º 35
0
    def run(self):
        project_id = self.settings.value("project/id")
        epsg = self.settings.value("project/epsg")

        locale = QSettings().value('locale/userLocale')[0:2]

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

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            group = _translate("VeriSO_EE_Geb_LokTest",
                               "Gebaeudeadressen - Lokalisationstest", None)
            group += " (" + str(project_id) + ")"

            # TODO: Check "tid" vs. t_ili_tid... in queries. Do not import
            # i_ili_tid?

            # define layer names here
            lokalisation = _translate("VeriSO_EE_Geb_LokTest",
                                      "Lokalisation Lokalisationstest", None)
            strassenstueck_geometrie = _translate(
                "VeriSO_EE_Geb_LokTest", "Strassenstueck (geometrie) "
                "Lokalisationstest", None)
            strassenstueck_anfangspunkt = _translate(
                "VeriSO_EE_Geb_LokTest", "Strassenstueck ("
                "anfangspunkt) "
                "Lokalisationstest", None)
            benanntesgebiet = _translate("VeriSO_EE_Geb_LokTest",
                                         "Benanntes Gebiet Lokalisationstest",
                                         None)
            gebaeudeeingang = _translate("VeriSO_EE_Geb_LokTest",
                                         "Gebaeudeeingang Lokalisationstest",
                                         None)
            shortestline = _translate("VeriSO_EE_Geb_LokTest",
                                      "Kuerzeste Linie Lokalisationstest",
                                      None)
            hausnummerpos = _translate("VeriSO_EE_Geb_LokTest",
                                       "HausnummerPos Lokalisationstest", None)
            lokalisationsname = _translate("VeriSO_EE_Geb_LokTest",
                                           "LokalisationsName", None)

            vlayer_lokalisation = self.get_vector_layer_by_name(lokalisation)
            if not vlayer_lokalisation:
                layer = {
                    "type": "postgres",
                    "title": lokalisation,
                    "featuretype": "gebaeudeadressen_lokalisation",
                    "key": "ogc_fid",
                    "sql": "ogc_fid = -1",
                    "readonly": True,
                    "group": group
                }
                vlayer_lokalisation = self.layer_loader.load(layer)

            vlayer_strassenstueck_geometrie = self.get_vector_layer_by_name(
                strassenstueck_geometrie)
            if not vlayer_strassenstueck_geometrie:
                layer = {
                    "type":
                    "postgres",
                    "title":
                    "Strassenstueck (geometrie) Lokalisationstest",
                    "featuretype":
                    "gebaeudeadressen_strassenstueck",
                    "geom":
                    "geometrie",
                    "key":
                    "ogc_fid",
                    "sql":
                    "strassenstueck_von = -1",
                    "readonly":
                    True,
                    "group":
                    group,
                    "style":
                    "global_qml/gebaeudeadressen/strassenachsen_rot"
                    ".qml"
                }
                vlayer_strassenstueck_geometrie = self.layer_loader.load(layer)

            vlayer_strassenstueck_anfangspunkt = self.get_vector_layer_by_name(
                strassenstueck_anfangspunkt)
            if not vlayer_strassenstueck_anfangspunkt:
                layer = {
                    "type": "postgres",
                    "title": "Strassenstueck (anfangspunkt) Lokalisationstest",
                    "featuretype": "gebaeudeadressen_strassenstueck",
                    "geom": "anfangspunkt",
                    "key": "ogc_fid",
                    "sql": "strassenstueck_von = -1",
                    "readonly": True,
                    "group": group,
                    "style": "global_qml/gebaeudeadressen/anfangspunkt_rot.qml"
                }
                vlayer_strassenstueck_anfangspunkt = self.layer_loader.load(
                    layer)

            vlayer_benanntesgebiet = self.get_vector_layer_by_name(
                benanntesgebiet)
            if not vlayer_benanntesgebiet:
                layer = {
                    "type":
                    "postgres",
                    "title":
                    "Benanntes Gebiet Lokalisationstest",
                    "featuretype":
                    "gebaeudeadressen_benanntesgebiet",
                    "geom":
                    "flaeche",
                    "key":
                    "ogc_fid",
                    "sql":
                    "benanntesgebiet_von = -1",
                    "readonly":
                    True,
                    "group":
                    group,
                    "style":
                    "global_qml/gebaeudeadressen/benanntesgebiet_rot"
                    ".qml"
                }
                vlayer_benanntesgebiet = self.layer_loader.load(layer)

            vlayer_gebaeudeeingang = self.get_vector_layer_by_name(
                gebaeudeeingang)
            if not vlayer_gebaeudeeingang:
                layer = {
                    "type":
                    "postgres",
                    "title":
                    "Gebaeudeeingang Lokalisationstest",
                    "featuretype":
                    "gebaeudeadressen_gebaeudeeingang",
                    "geom":
                    "lage",
                    "key":
                    "ogc_fid",
                    "sql":
                    "gebaeudeeingang_von = -1",
                    "readonly":
                    True,
                    "group":
                    group,
                    "style":
                    "global_qml/gebaeudeadressen/gebaeudeeingang_rot"
                    ".qml"
                }
                vlayer_gebaeudeeingang = self.layer_loader.load(layer)

            vlayer_shortestline = self.get_vector_layer_by_name(shortestline)
            if not vlayer_shortestline:
                layer = {
                    "type":
                    "postgres",
                    "title":
                    "Kuerzeste Linie Lokalisationstest",
                    "featuretype":
                    "t_shortestline_hausnummerpos",
                    "geom":
                    "the_geom",
                    "key":
                    "ogc_fid",
                    "sql":
                    "lok_tid = -1",
                    "readonly":
                    True,
                    "group":
                    group,
                    "style":
                    "global_qml/gebaeudeadressen/shortestline_linie_rot.qml"
                }
                vlayer_shortestline = self.layer_loader.load(layer)

            vlayer_hausnummerpos = self.get_vector_layer_by_name(hausnummerpos)
            if not vlayer_hausnummerpos:
                layer = {
                    "type": "postgres",
                    "title": "HausnummerPos Lokalisationstest",
                    "featuretype": "v_gebaeudeadressen_hausnummerpos",
                    "geom": "pos",
                    "key": "ogc_fid",
                    "sql": "lok_tid = -1",
                    "readonly": True,
                    "group": group,
                    "style":
                    "global_qml/gebaeudeadressen/hausnummerpos_rot.qml"
                }
                vlayer_hausnummerpos = self.layer_loader.load(layer)

            vlayer_lokalisationsname = self.get_vector_layer_by_name(
                lokalisationsname)
            if not vlayer_lokalisationsname:
                self.message_bar.pushMessage(
                    "Error",
                    _translate("VeriSO_EE_Geb_LokTest",
                               "Layer _LokalisationsName_ not found.", None),
                    level=Qgis.Critical,
                    duration=0)
                QApplication.restoreOverrideCursor()
                return

            iterator = vlayer_lokalisationsname.getFeatures()
            ids = []

            for feature in iterator:
                ids.append(feature.id())

            if vlayer_lokalisationsname.selectedFeatureCount() < 1:
                self.message_bar.pushCritical(
                    "Error",
                    _translate("VeriSO_EE_Geb_LokTest",
                               "No _LokalisationsName_ selected.", None))
                QApplication.restoreOverrideCursor()
                return

            if vlayer_lokalisationsname.selectedFeatureCount() > 1:
                self.message_bar.pushCritical(
                    "Error",
                    _translate(
                        "VeriSO_EE_Geb_LokTest",
                        "Please select only one (1) _LokalisationsName_.",
                        None))
                QApplication.restoreOverrideCursor()
                return

            feat = QgsFeature()
            id = vlayer_lokalisationsname.selectedFeatureIds()[0]
            feat = vlayer_lokalisationsname.selectedFeatures()[0]
            idx = ids.index(id)

            benannte_idx = vlayer_lokalisationsname.lookupField("benannte")
            text_idx = vlayer_lokalisationsname.lookupField("atext")

            if benannte_idx == -1 or text_idx == -1:
                self.message_bar.pushCritical(
                    "Error",
                    _translate("VeriSO_EE_Geb_LokTest",
                               "Field _benannte_ or _text_ not found.", None))
                QApplication.restoreOverrideCursor()
                return

            benannte = feat.attributes()[benannte_idx]
            lokalisationsname = feat.attributes()[text_idx]

            vlayer_strassenstueck_geometrie.setSubsetString(
                "(strassenstueck_von = " + str(benannte) + ")")
            vlayer_strassenstueck_anfangspunkt.setSubsetString(
                "(strassenstueck_von = " + str(benannte) + ")")
            vlayer_benanntesgebiet.setSubsetString("(benanntesgebiet_von = " +
                                                   str(benannte) + ")")
            vlayer_gebaeudeeingang.setSubsetString("(gebaeudeeingang_von = " +
                                                   str(benannte) + ")")
            vlayer_lokalisation.setSubsetString("(ogc_fid = " + str(benannte) +
                                                ")")
            vlayer_shortestline.setSubsetString("(lok_tid = " + str(benannte) +
                                                ")")
            vlayer_hausnummerpos.setSubsetString("(lok_tid = " +
                                                 str(benannte) + ")")

            if vlayer_strassenstueck_geometrie.featureCount() > 0:
                x_min = vlayer_strassenstueck_geometrie.extent().xMinimum()
                y_min = vlayer_strassenstueck_geometrie.extent().yMinimum()
                x_max = vlayer_strassenstueck_geometrie.extent().xMaximum()
                y_max = vlayer_strassenstueck_geometrie.extent().yMaximum()

            if vlayer_benanntesgebiet.featureCount() > 0:
                x_min = vlayer_benanntesgebiet.extent().xMinimum()
                y_min = vlayer_benanntesgebiet.extent().yMinimum()
                x_max = vlayer_benanntesgebiet.extent().xMaximum()
                y_max = vlayer_benanntesgebiet.extent().yMaximum()

            try:
                if vlayer_gebaeudeeingang.featureCount() > 0:
                    if vlayer_gebaeudeeingang.extent().xMinimum() < x_min:
                        x_min = vlayer_gebaeudeeingang.extent().xMinimum()
                    if vlayer_gebaeudeeingang.extent().yMinimum() < y_min:
                        y_min = vlayer_gebaeudeeingang.extent().yMinimum()
                    if vlayer_gebaeudeeingang.extent().xMaximum() > x_max:
                        x_max = vlayer_gebaeudeeingang.extent().xMaximum()
                    if vlayer_gebaeudeeingang.extent().yMaximum() > y_max:
                        y_max = vlayer_gebaeudeeingang.extent().yMaximum()

                rect = QgsRectangle(x_min, y_min, x_max, y_max)
                rect.scale(1.3)

            except UnboundLocalError:
                vlayer_gemeindegrenze = self.getVectorLayerByName(
                    "Gemeindegrenze")
                if vlayer_gemeindegrenze is None:
                    rect = self.canvas.fullExtent()
                else:
                    rect = vlayer_gemeindegrenze.extent()

            self.iface.mapCanvas().setExtent(rect)
            self.iface.mapCanvas().refresh()

            iterator = vlayer_lokalisation.getFeatures()

            # only one feature is selected
            for feature in iterator:
                prinzip_idx = vlayer_lokalisation.lookupField(
                    "nummerierungsprinzip_txt")
                attributeprovisorisch_idx = vlayer_lokalisation.lookupField(
                    "attributeprovisorisch_txt")
                offiziell_idx = vlayer_lokalisation.lookupField(
                    "istoffiziellebezeichnung_txt")
                status_idx = vlayer_lokalisation.lookupField("status_txt")
                inaenderung_idx = vlayer_lokalisation.lookupField(
                    "inaenderung_txt")
                art_idx = vlayer_lokalisation.lookupField("art_txt")

                something_missing = (prinzip_idx == -1
                                     or attributeprovisorisch_idx == -1
                                     or offiziell_idx == -1 or status_idx == -1
                                     or inaenderung_idx == -1 or art_idx == -1)
                if something_missing:
                    self.message_bar.pushMessage("Error",
                                                 _translate(
                                                     "VeriSO_EE_Geb_LokTest",
                                                     "Field not found.", None),
                                                 level=Qgis.Critical,
                                                 duration=0)
                    QApplication.restoreOverrideCursor()
                    return

                prinzip = feature.attributes()[prinzip_idx]
                attributeprovisorisch = feature.attributes(
                )[attributeprovisorisch_idx]
                offiziell = feature.attributes()[offiziell_idx]
                status = feature.attributes()[status_idx]
                inaenderung = feature.attributes()[inaenderung_idx]
                art = feature.attributes()[art_idx]

            map_extent = self.canvas.extent()
            x = map_extent.xMinimum()
            y = map_extent.yMaximum()

            text_item_found = False
            items = list(self.iface.mapCanvas().scene().items())
            for i in range(len(items)):
                try:
                    name = items[i].data(0)
                    if str(name) == "LokalisationsInfo":
                        text_item = items[i]
                        text_item_found = True
                except Exception:
                    pass

            if not text_item_found:
                text_item = QgsTextAnnotation(self.canvas)
                # text_item.setData(0, "LokalisationsInfo")

            # noinspection PyUnboundLocalVariable
            text_item.setMapPosition(
                QgsPointXY(x + 10 * self.canvas.mapUnitsPerPixel(),
                           y - 10 * self.canvas.mapUnitsPerPixel()))
            text_item.setHasFixedMapPosition(False)
            # text_item.setFrameBorderWidth(0.0)
            # text_item.setFrameColor(QColor(250, 250, 250, 255))
            # text_item.setFrameBackgroundColor(QColor(250, 250, 250, 123))
            text_item.setFrameSize(QSizeF(250, 150))
            text_document = QTextDocument()
            text_document.setHtml(
                "<table style='font-size:12px;'><tr><td>Lok.Name: </td><td>" +
                lokalisationsname + "</td></tr><tr><td>TID: </td><td>" +
                str(benannte) + "</td></tr> <tr><td>Num.prinzip: "
                "</td><td>" + str(prinzip) +
                "</td></tr> <tr><td>Attr. prov.: </td><td>" +
                str(attributeprovisorisch) + "</td></tr> <tr><td>ist "
                "offiziell: </td><td>" + str(offiziell) +
                "</td></tr> <tr><td>Status: "
                "</td><td>" + str(status) + "</td></tr> <tr><td>in Aenderung: "
                "</td><td>" + str(inaenderung) + "</td></tr> <tr><td>Art: "
                "</td><td>" + str(art) + "</td></tr>  </table>")
            text_item.setDocument(text_document)

            # This is a workaround: first ever position is not correct.
            text_item.setMapPosition(
                QgsPointXY(x + 10 * self.canvas.mapUnitsPerPixel(),
                           y - 10 * self.canvas.mapUnitsPerPixel()))
            text_item.update()

            self.iface.mapCanvas().refresh()

            try:
                vlayer_lokalisationsname.selectByIds([ids[idx + 1]])
            except IndexError:
                self.message_bar.pushInfo(
                    "Information",
                    _translate("VeriSO_EE_Geb_LokTest", "End of table.", None))

        except Exception as e:
            QApplication.restoreOverrideCursor()
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.message_bar.pushMessage(
                "Error",
                str(traceback.format_exc(exc_traceback)),
                level=Qgis.Critical,
                duration=0)
        QApplication.restoreOverrideCursor()
Ejemplo n.º 36
0
    def get_z_max_z_min(self):

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        rec = QgsRectangle(self.roi_x_min, self.roi_y_min, self.roi_x_max, self.roi_y_max)
        canvasCRS = self.map_crs
        dataCRS = self.layer.crs()
        if canvasCRS != dataCRS:
            transform = QgsCoordinateTransform(canvasCRS, dataCRS, QgsProject.instance())
            rec = transform.transform(rec)

        x_max = rec.xMaximum()
        x_min = rec.xMinimum()
        y_max = rec.yMaximum()
        y_min = rec.yMinimum()
        x_off = int(math.floor((x_min - self.raster_x_min) * self.cols / (self.raster_x_max - self.raster_x_min)))
        y_off = int(math.floor((self.raster_y_max - y_max) * self.rows / (self.raster_y_max - self.raster_y_min)))
        col_size = int(math.floor((x_max - x_min) / self.cell_size))
        row_size = int(math.floor((y_max - y_min) / self.cell_size))

        if x_off < 0:
            x_off = 0
        if y_off < 0:
            y_off = 0
        if x_off >= self.cols:
            x_off = self.cols - 1
        if y_off >= self.rows:
            y_off = self.rows - 1
        if x_off + col_size > self.cols:
            col_size = self.cols - x_off
        if row_size + row_size > self.rows:
            row_size = self.rows - y_off

        provider = self.layer.dataProvider()
        path = provider.dataSourceUri()
        path_layer = path.split('|')
        dem_dataset = gdal.Open(path_layer[0])
        data = Model.get_dem_z(dem_dataset, x_off, y_off, col_size, row_size)

        if data is not None:
            self.z_max = max(data)
            self.z_min = self.z_max
            no_data = dem_dataset.GetRasterBand(1).GetNoDataValue()

            if min(data) == no_data:
                for z_cell in data:
                    if z_cell != no_data and z_cell < self.z_min:
                        self.z_min = z_cell
            elif math.isnan(min(data)):
                self.z_max = 0
                self.z_min = 0
                for z_cell in data:
                    if not math.isnan(z_cell):
                        if self.z_min > z_cell:
                            self.z_min = z_cell
                        if self.z_max < z_cell:
                            self.z_max = z_cell
            else:
                self.z_min = min(data)

            self.z_max = round(self.z_max, 3)
            self.z_min = round(self.z_min, 3)
            self.ui.ZMaxLabel.setText(str(self.z_max) + ' m')
            self.ui.ZMinLabel.setText(str(self.z_min) + ' m')

        dem_dataset = None
        QApplication.restoreOverrideCursor()
Ejemplo n.º 37
0
    def run(self):

        project_id = self.settings.value("project/id")
        epsg = self.settings.value("project/epsg")
        # this is for multilingual legends
        locale = QSettings().value('locale/userLocale')[0:2]

        # If locale is different to frence or italian, german will be used.
        # Otherwise we get into troubles with the legends, e.g. locale = "en"
        # but
        # there is no english legend (qml file).
        if locale == "fr":
            pass
        elif locale == "it":
            pass
        else:
            locale = "de"

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

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            group = _translate("Veribe", "Isolierte_Uebrigen_Gebaeudeteile",
                               None)
            group += " (" + str(project_id) + ")"

            layer = {
                "type":
                "postgres",
                "title":
                _translate("Veribe",
                           "Isolierte Uebrigen Gebaeudeteile Flachen", None),
                "featuretype":
                "v_uebriger_gebaeudeteil_isolierte_flaeche",
                "geom":
                "geometrie",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("Veribe", "Isolierte Uebrigen Gebaeudeteile Linien",
                           None),
                "featuretype":
                "v_uebriger_gebaeudeteil_isolierte_linien",
                "geom":
                "geometrie",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("Veribe", "Isolierte Uebrigen Gebaeudeteile Punkte",
                           None),
                "featuretype":
                "v_uebriger_gebaeudeteil_isolierte_punkte",
                "geom":
                "geometrie",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
            }

            vlayer = self.layer_loader.load(layer)

            # Visibility and if legend and/or groupd should be collapsed can
            # be set with parameters in the self.layer_loader.load()
            # method:
            # load(layer, visibility=True, collapsed_legend=False,
            # collapsed_group=False)
            # vlayer = self.layer_loader.load(layer)

        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=Qgis.Critical,
                duration=0)
        QApplication.restoreOverrideCursor()
Ejemplo n.º 38
0
    def accept(self):
        # sanity checks
        if self.editOutputFile.text() == "":
            QMessageBox.information(self, self.tr("Export to file"), self.tr("Output file name is required"))
            return

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

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

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

            options = {}

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

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

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

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

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

            # do the export!
            ret, errMsg = QgsVectorLayerExporter.exportLayer(self.inLayer, uri, providerName, outCrs,
                                                             False, options)
        except Exception as e:
            ret = -1
            errMsg = str(e)

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

        if ret != 0:
            QMessageBox.warning(self, self.tr("Export to file"), self.tr("Error {0}\n{1}").format(ret, errMsg))
            return

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

        QMessageBox.information(self, self.tr("Export to file"), self.tr("Export finished."))
        return QDialog.accept(self)
Ejemplo n.º 39
0
    def accept(self):
        self.settings.setValue("/Processing/dialogBase", self.saveGeometry())

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

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

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

            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

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

            if self.iterateParam:
                if executeIterating(self.alg, self.iterateParam,
                                    self.feedback):
                    self.finish()
                else:
                    QApplication.restoreOverrideCursor()
                    self.resetGUI()
            else:
                command = self.alg.getAsCommand()
                if command:
                    ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM,
                                           command)
                if execute(self.alg, self.feedback):
                    self.finish()
                else:
                    QApplication.restoreOverrideCursor()
                    self.resetGUI()
        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox.accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.bar.clearWidgets()
            self.bar.pushMessage(
                "",
                self.tr("Wrong or missing parameter value: {0}").format(
                    e.parameter.description),
                level=QgsMessageBar.WARNING,
                duration=5)
Ejemplo n.º 40
0
    def accept(self):
        self.algs = []
        self.load = []
        self.canceled = False

        for row in range(self.mainWidget.tblParameters.rowCount()):
            alg = self.alg.getCopy()
            col = 0
            for param in alg.parameters:
                if param.hidden:
                    continue
                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()
Ejemplo n.º 41
0
    def runAlgorithm(algOrName, onFinish, *args, **kwargs):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = Processing.getAlgorithm(algOrName)
        if alg is None:
            # fix_print_with_import
            print('Error: Algorithm not found\n')
            QgsMessageLog.logMessage(
                Processing.tr('Error: Algorithm {0} not found\n').format(
                    algOrName), Processing.tr("Processing"))
            return
        alg = alg.getCopy()

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

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

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

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

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

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

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

        if overrideCursor:
            QApplication.restoreOverrideCursor()
        if isinstance(feedback, MessageBarProgress):
            feedback.close()
        return alg
Ejemplo n.º 42
0
    def installPlugin(self, key, quiet=False, stable=True):
        """ Install given plugin """
        error = False
        status_key = 'status' if stable else 'status_exp'
        infoString = ('', '')
        plugin = plugins.all()[key]
        previousStatus = plugin[status_key]
        if not plugin:
            return
        if plugin[status_key] == "newer" and not plugin[
                "error"]:  # ask for confirmation if user downgrades an usable plugin
            if QMessageBox.warning(
                    iface.mainWindow(),
                    self.tr("QGIS Python Plugin Installer"),
                    self.
                    tr("Are you sure you want to downgrade the plugin to the latest available version? The installed one is newer!"
                       ), QMessageBox.Yes, QMessageBox.No) == QMessageBox.No:
                return

        dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(),
                                                 plugin,
                                                 stable=stable)
        dlg.exec_()

        plugin_path = qgis.utils.home_plugin_path + "/" + key
        if dlg.result():
            error = True
            infoString = (self.tr("Plugin installation failed"), dlg.result())
        elif not QDir(plugin_path).exists():
            error = True
            infoString = (
                self.tr("Plugin has disappeared"),
                self.
                tr("The plugin seems to have been installed but it's not possible to know where. The directory \"{}\" "
                   "has not been found. Probably the plugin package contained a wrong named directory.\nPlease search "
                   "the list of installed plugins. You should find the plugin there, but it's not possible to "
                   "determine which of them it is and it's also not possible to inform you about available updates. "
                   "Please contact the plugin author and submit this issue."
                   ).format(plugin_path))
            QApplication.setOverrideCursor(Qt.WaitCursor)
            plugins.getAllInstalled()
            plugins.rebuild()
            self.exportPluginsToManager()
            QApplication.restoreOverrideCursor()
        else:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            # update the list of plugins in plugin handling routines
            updateAvailablePlugins()
            self.processDependencies(plugin["id"])
            # try to load the plugin
            loadPlugin(plugin["id"])
            plugins.getAllInstalled()
            plugins.rebuild()
            plugin = plugins.all()[key]
            if not plugin["error"]:
                if previousStatus in ["not installed", "new"]:
                    infoString = (self.tr("Plugin installed successfully"), "")
                    if startPlugin(plugin["id"]):
                        settings = QgsSettings()
                        settings.setValue("/PythonPlugins/" + plugin["id"],
                                          True)
                else:
                    settings = QgsSettings()
                    if settings.value(
                            "/PythonPlugins/" + key, False, type=bool
                    ):  # plugin will be reloaded on the fly only if currently loaded
                        reloadPlugin(
                            key)  # unloadPlugin + loadPlugin + startPlugin
                        infoString = (
                            self.tr("Plugin reinstalled successfully"), "")
                    else:
                        unloadPlugin(
                            key
                        )  # Just for a case. Will exit quietly if really not loaded
                        loadPlugin(key)
                        infoString = (
                            self.tr("Plugin reinstalled successfully"),
                            self.
                            tr("Python plugin reinstalled.\nYou need to restart QGIS in order to reload it."
                               ))
                if quiet:
                    infoString = (None, None)
                QApplication.restoreOverrideCursor()
            else:
                QApplication.restoreOverrideCursor()
                if plugin["error"] == "incompatible":
                    message = self.tr(
                        "The plugin is not compatible with this version of QGIS. It's designed for QGIS versions:"
                    )
                    message += " <b>" + plugin["error_details"] + "</b>"
                elif plugin["error"] == "dependent":
                    message = self.tr(
                        "The plugin depends on some components missing on your system. You need to install the following Python module in order to enable it:"
                    )
                    message += "<b> " + plugin["error_details"] + "</b>"
                else:
                    message = self.tr("The plugin is broken. Python said:")
                    message += "<br><b>" + plugin["error_details"] + "</b>"
                dlg = QgsPluginInstallerPluginErrorDialog(
                    iface.mainWindow(), message)
                dlg.exec_()
                if dlg.result():
                    # revert installation
                    pluginDir = qgis.utils.home_plugin_path + "/" + plugin["id"]
                    result = removeDir(pluginDir)
                    if QDir(pluginDir).exists():
                        error = True
                        infoString = (self.tr("Plugin uninstall failed"),
                                      result)
                        try:
                            exec("sys.path_importer_cache.clear()")
                            exec("import %s" % plugin["id"])
                            exec("reload (%s)" % plugin["id"])
                        except:
                            pass
                    else:
                        try:
                            exec("del sys.modules[%s]" % plugin["id"])
                        except:
                            pass
                    plugins.getAllInstalled()
                    plugins.rebuild()

            self.exportPluginsToManager()

        if infoString[0]:
            level = error and Qgis.Critical or Qgis.Info
            msg = "<b>%s</b>" % infoString[0]
            if infoString[1]:
                msg += "<b>:</b> %s" % infoString[1]
            iface.pluginManagerInterface().pushMessage(msg, level)
    def accept(self, *args, **kwargs):
        """Run the processing"""
        try:

            if not self.validate():
                return False

            # disable form via a frame, this will still allow interaction with the message bar
            self.fraMain.setDisabled(True)
            # clean gui and Qgis messagebars
            self.cleanMessageBars(True)

            # Change cursor to Wait cursor
            QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
            self.iface.mainWindow().statusBar().showMessage('Processing {}'.format(self.windowTitle()))
            LOGGER.info('{st}\nProcessing {}'.format(self.windowTitle(), st='*' * 50))

            self.send_to_messagebar("Please wait.. QGIS will be locked... See log panel for progress.",
                                    level=Qgis.Warning,
                                    duration=0, addToLog=False, core_QGIS=False, showLogPanel=True)

            selectedIndices = [x.text() for x in self.chkgrpIndices.buttons() if x.isChecked()]

            # Add settings to log
            settingsStr = 'Parameters:---------------------------------------'

            settingsStr += '\n    {:20}\t{}'.format('Image layer:', self.mcboRasterLayer.currentLayer().name())
            settingsStr += '\n    {:20}\t{}'.format('Image nodata value:', self.lblNoDataVal.text())

            if self.mcboPolygonLayer.currentLayer() is not None:
                if self.chkUseSelected.isChecked():
                    settingsStr += '\n    {:20}\t{} with {} selected features'.format('Layer:',
                                                                                      self.mcboPolygonLayer.currentLayer().name(),
                                                                                      self.mcboPolygonLayer.currentLayer().selectedFeatureCount())
                else:
                    settingsStr += '\n    {:20}\t{}'.format('Boundary layer:',
                                                            self.mcboPolygonLayer.currentLayer().name())

                if self.mFieldComboBox.currentField():
                    settingsStr += '\n    {:20}\t{}'.format('Block ID field:', self.mFieldComboBox.currentField())

            settingsStr += '\n    {:20}\t{}'.format('Resample pixel size: ', self.dsbPixelSize.value())

            for k, v in self.band_mapping.items():
                if v > 0:
                    settingsStr += '\n    {:20}\t{}'.format('{} Band:'.format(k.title()), v)

            settingsStr += '\n    {:20}\t{}'.format('Calculate Indices: ', ', '.join(selectedIndices))
            settingsStr += '\n    {:30}\t{} - {}'.format('Output Coordinate System:',
                                                         self.mCRSoutput.crs().authid(),
                                                         self.mCRSoutput.crs().description())

            settingsStr += '\n    {:30}\t{}\n'.format('Output Folder:', self.lneOutputFolder.text())

            LOGGER.info(settingsStr)

            lyrRaster = self.mcboRasterLayer.currentLayer()
            filePoly=None
            if self.mcboPolygonLayer.currentLayer() is not None:
                lyrBoundary = self.mcboPolygonLayer.currentLayer()

                if self.chkUseSelected.isChecked():
                    savePlyName = lyrBoundary.name() + '_poly.shp'
                    filePoly = os.path.join(TEMPDIR, savePlyName)
                    if os.path.exists(filePoly):  removeFileFromQGIS(filePoly)

                    QgsVectorFileWriter.writeAsVectorFormat(lyrBoundary, filePoly, "utf-8", lyrBoundary.crs(),
                                                            driverName="ESRI Shapefile", onlySelected=True)

                    if self.DISP_TEMP_LAYERS:
                        addVectorFileToQGIS(filePoly, layer_name=os.path.splitext(os.path.basename(filePoly))[0]
                                            , group_layer_name='DEBUG', atTop=True)
                else:
                    filePoly = get_layer_source(lyrBoundary)

            # convert string to float or int without knowing which
            x = self.lneNoDataVal.text()
            nodata_val = int(float(x)) if int(float(x)) == float(x) else float(x)

            files = calc_indices_for_block(get_layer_source(lyrRaster),
                                           self.dsbPixelSize.value(),
                                           self.band_mapping,
                                           self.lneOutputFolder.text(),
                                           indices=selectedIndices,
                                           image_epsg=int(lyrRaster.crs().authid().replace('EPSG:', '')),
                                           image_nodata=nodata_val,
                                           polygon_shapefile=filePoly,
                                           groupby=self.mFieldComboBox.currentField() if self.mFieldComboBox.currentField() else None,
                                           out_epsg=int(self.mCRSoutput.crs().authid().replace('EPSG:', '')))

            if self.chkAddToDisplay.isChecked():
                for ea_file in files:
                    raster_sym = RASTER_SYMBOLOGY['Image Indices (ie PCD, NDVI)']
                    group_name =  os.path.basename(os.path.dirname(ea_file))
                    if self.mFieldComboBox.currentField():
                        group_name = os.path.basename(ea_file).split('_')[0] + ' - ' + os.path.basename(os.path.dirname(ea_file))
                    
                    raster_lyr = addRasterFileToQGIS(ea_file,atTop=False, group_layer_name=group_name)

                    raster_apply_classified_renderer(raster_lyr,
                                    rend_type=raster_sym['type'],
                                    num_classes=raster_sym['num_classes'],
                                    color_ramp=raster_sym['colour_ramp'])

            self.cleanMessageBars(True)
            self.fraMain.setDisabled(False)

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

        except Exception as err:

            QApplication.restoreOverrideCursor()
            self.iface.mainWindow().statusBar().clearMessage()
            self.cleanMessageBars(True)
            self.fraMain.setDisabled(False)

            self.send_to_messagebar(str(err), level=Qgis.Critical,
                                    duration=0, addToLog=True, core_QGIS=False, showLogPanel=True,
                                    exc_info=sys.exc_info())

            return False  # leave dialog open
Ejemplo n.º 44
0
    def run(self):
        project_id = self.settings.value("project/id")
        epsg = self.settings.value("project/epsg")

        locale = QSettings().value('locale/userLocale')[0:2]

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

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            group = _translate("VeriSO_EE_Geb_Basis",
                               "Gebaeudeadressen - Basislayer", None)
            group += " (" + str(project_id) + ")"

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_EE_Geb_Basis", "Bodenbedeckung", None),
                "featuretype":
                "bodenbedeckung_boflaeche",
                "geom":
                "geometrie",
                "key":
                "ogc_fid",
                "sql":
                "art_txt LIKE 'Gebaeude%' OR art_txt LIKE "
                "'befestigt.Strasse_Weg%' OR art_txt LIKE "
                "'befestigt.Trottoir%' OR art_txt LIKE "
                "'befestigt.uebrige_befestigte%'",
                "readonly":
                True,
                "group":
                group,
                "style":
                "bodenbedeckung/gebaeude_strassen_trottoir_erschliessung"
                ".qml"
            }
            # Use 'LIKE' instead of 'IN' or '='. Now you can model extensions
            #  like different kinds of 'uebrige_befestigte'.

            # Visibility and if legend and/or groupd should be collapsed can
            # be set with parameters in the self.layer_loader.load()
            # method:
            # load(layer, visibility=True, collapsed_legend=False,
            # collapsed_group=False)
            vlayer = self.layer_loader.load(layer)

            # noinspection PyPep8
            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_EE_Geb_Basis", "EO.Flaechenelemente", None),
                "featuretype":
                "v_einzelobjekte_flaechenelement",
                "geom":
                "geometrie",
                "key":
                "ogc_fid",
                "sql":
                "art_txt LIKE 'unterirdisches_Gebaeude%' OR "
                "art_txt LIKE 'uebriger_Gebaeudeteil%' OR art_txt "
                "LIKE 'Reservoir%' OR art_txt LIKE 'Unterstand%'",
                "readonly":
                True,
                "group":
                group,
                "style":
                "einzelobjekte/eo_flaeche_gebdetail_unterstand_reservoir_unterirdisch.qml"
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_EE_Geb_Basis", "EO.Linienelemente", None),
                "featuretype":
                "v_einzelobjekte_linienelement",
                "geom":
                "geometrie",
                "key":
                "ogc_fid",
                "sql":
                "art_txt LIKE 'uebriger_Gebaeudeteil%'",
                "readonly":
                True,
                "group":
                group,
                "style":
                "einzelobjekte/eo_linie_gebdetail.qml"
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type": "postgres",
                "title": _translate("VeriSO_EE_Geb_Basis", "GEB.Nachführung",
                                    None),
                "featuretype": "gebaeudeadressen_gebnachfuehrung",
                "key": "ogc_fid",
                "sql": "",
                "readonly": True,
                "group": group
            }
            # layer["geom"] = "perimeter" # Will be loaded as geometryless
            # layer.

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_EE_Geb_Basis", "Benanntes Gebiet", None),
                "featuretype":
                "gebaeudeadressen_benanntesgebiet",
                "geom":
                "flaeche",
                "key":
                "ogc_fid",
                "sql":
                "",
                "readonly":
                True,
                "group":
                group,
                "style":
                "global_qml/gebaeudeadressen/benanntesgebiet_gruen.qml"
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_EE_Geb_Basis", "Strassenstueck (geometrie)",
                           None),
                "featuretype":
                "gebaeudeadressen_strassenstueck",
                "geom":
                "geometrie",
                "key":
                "ogc_fid",
                "sql":
                "",
                "group":
                group,
                "style":
                "global_qml/gebaeudeadressen/strassenachsen_gruen.qml"
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_EE_Geb_Basis",
                           "Strassenstueck (anfangspunkt)", None),
                "featuretype":
                "gebaeudeadressen_strassenstueck",
                "geom":
                "anfangspunkt",
                "key":
                "ogc_fid",
                "sql":
                "",
                "group":
                group,
                "style":
                "global_qml/gebaeudeadressen/anfangspunkt_gruen.qml"
            }

            vlayer = self.layer_loader.load(layer)

            # noinspection PyPep8
            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_EE_Geb_Basis", "Gebaeudeeingang", None),
                "featuretype":
                "gebaeudeadressen_gebaeudeeingang",
                "geom":
                "lage",
                "key":
                "ogc_fid",
                "sql":
                "",
                "group":
                group,
                "style":
                "global_qml/gebaeudeadressen/gebaeudeeingang_blaues_viereck_mit_label.qml"
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type": "postgres",
                "title": _translate("VeriSO_EE_Geb_Basis", "HausnummerPos",
                                    None),
                "featuretype": "v_gebaeudeadressen_hausnummerpos",
                "geom": "pos",
                "key": "ogc_fid",
                "sql": "",
                "group": group,
                "style": "global_qml/gebaeudeadressen/hausnummerpos.qml"
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_EE_Geb_Basis", "LokalisationsName", None),
                "featuretype":
                "gebaeudeadressen_lokalisationsname",
                "key":
                "ogc_fid",
                "sql":
                "",
                "group":
                group
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type":
                "postgres",
                "title":
                _translate("VeriSO_EE_Geb_Basis", "LokalisationsNamePos",
                           None),
                "featuretype":
                "t_gebaeudeadressen_lokalisationsnamepos",
                "geom":
                "pos",
                "key":
                "ogc_fid",
                "sql":
                "",
                "group":
                group,
                "style":
                "global_qml/gebaeudeadressen/lokalisationsnamepos.qml"
            }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type": "postgres",
                "title": _translate("VeriSO_EE_Geb_Basis", "Gemeindegrenze",
                                    None),
                "featuretype": "gemeindegrenzen_gemeindegrenze",
                "geom": "geometrie",
                "key": "ogc_fid",
                "sql": "",
                "readonly": True,
                "group": group,
                "style": "global_qml/gemeindegrenze/gemgre_strichliert.qml"
            }

            gemgrelayer = self.layer_loader.load(layer)

            if gemgrelayer:
                rect = gemgrelayer.extent()
                rect.scale(5)
                self.iface.mapCanvas().setExtent(rect)
                self.iface.mapCanvas().refresh()

        except Exception as e:
            QApplication.restoreOverrideCursor()
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.message_bar.pushMessage(
                "Error",
                str(traceback.format_exc(exc_traceback)),
                level=Qgis.Critical,
                duration=0)
        QApplication.restoreOverrideCursor()
    def create_project(self, project_name, project_dir, is_public, namespace):
        """
        Create new Mergin project.
        If project_dir is None, we are creating empty project without upload.
        """

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self.mc.create_project(project_name, is_public, namespace)
        except Exception as e:
            QApplication.restoreOverrideCursor()
            QMessageBox.critical(None, "Create Project",
                                 "Failed to create Mergin project.\n" + str(e))
            return False

        QApplication.restoreOverrideCursor()

        if not project_dir:
            # not going to upload anything so just pop a "success" message and exit
            QMessageBox.information(
                None, "Create Project",
                "An empty project has been created on the server",
                QMessageBox.Close)
            return True

        # let's do initial upload of the project data

        mp = MerginProject(project_dir)
        full_project_name = "{}/{}".format(namespace, project_name)
        mp.metadata = {"name": full_project_name, "version": "v0", "files": []}
        if not mp.inspect_files():
            QMessageBox.warning(
                None, "Create Project",
                "The project directory is empty - nothing to upload.")
            return True

        dlg = SyncDialog()
        dlg.push_start(self.mc, project_dir, full_project_name)

        dlg.exec_()  # blocks until success, failure or cancellation

        if dlg.exception:
            # push failed for some reason
            if isinstance(dlg.exception, LoginError):
                login_error_message(dlg.exception)
            elif isinstance(dlg.exception, ClientError):
                QMessageBox.critical(None, "Project sync",
                                     "Client error: " + str(dlg.exception))
            else:
                unhandled_exception_message(
                    dlg.exception_details(),
                    "Project sync",
                    f"Failed to sync project {project_name} due to an unhandled exception.",
                )
            return True

        if not dlg.is_complete:
            # we were cancelled - but no need to show a message box about that...?
            return True

        settings = QSettings()
        server_url = self.mc.url.rstrip("/")
        settings.setValue(f"Mergin/localProjects/{full_project_name}/path",
                          project_dir)
        settings.setValue(f"Mergin/localProjects/{full_project_name}/server",
                          server_url)
        if (project_dir == QgsProject.instance().absolutePath()
                or project_dir + "/" in QgsProject.instance().absolutePath()):
            write_project_variables(self.mc.username(), project_name,
                                    full_project_name, "v1", server_url)

        QMessageBox.information(
            None, "Create Project",
            "Mergin project created and uploaded successfully",
            QMessageBox.Close)

        return True
Ejemplo n.º 46
0
    def run_query(self):
        """
        Process for running the query
        """

        # Block the button and save the initial text
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.output_directory.setDisabled(True)
        self.pushButton_showQuery.setDisabled(True)
        self.start_process()
        QApplication.processEvents()

        # Get all values
        key = str(self.comboBox_key.currentText())
        value = str(self.comboBox_value.currentText())
        nominatim = self.nominatim_value()
        timeout = self.spinBox_timeout.value()
        output_directory = self.output_directory.filePath()
        prefix_file = self.lineEdit_filePrefix.text()
        if self.comboBox_in_around.currentIndex() == 1:
            is_around = True
        else:
            is_around = False
        distance = self.spinBox_distance_point.value()

        # Which geometry at the end ?
        output_geometry_types = self.get_output_geometry_types()

        # Which osm objects ?
        osm_objects = self._get_osm_objects()

        try:
            # Test values
            if not osm_objects:
                raise OsmObjectsException

            if not output_geometry_types:
                raise OutPutGeomTypesException

            # If bbox, we must set None to nominatim, we can't have both
            bbox = None
            if self.radioButton_extentLayer.isChecked() or \
                    self.radioButton_extentMapCanvas.isChecked():
                nominatim = None
                bbox = self.get_bounding_box()

            if nominatim == '':
                nominatim = None

            if output_directory and not isdir(output_directory):
                raise DirectoryOutPutException

            num_layers = process_quick_query(
                dialog=self,
                key=key,
                value=value,
                nominatim=nominatim,
                is_around=is_around,
                distance=distance,
                bbox=bbox,
                osm_objects=osm_objects,
                timeout=timeout,
                output_directory=output_directory,
                prefix_file=prefix_file,
                output_geometry_types=output_geometry_types)

            # We can test numLayers to see if there are some results
            if num_layers:
                self.label_progress.setText(
                    tr('QuickOSM', u'Successful query !'))

                display_message_bar(tr('QuickOSM', u'Successful query !'),
                                    level=Qgis.Success,
                                    duration=5)
            else:
                self.label_progress.setText(tr("QuickOSM", u'No result'))

                display_message_bar(tr('QuickOSM',
                                       u'Successful query, but no result.'),
                                    level=Qgis.Warning,
                                    duration=7)

        except QuickOsmException as e:
            self.display_geo_algorithm_exception(e)
        except Exception as e:  # pylint: disable=broad-except
            self.display_exception(e)

        finally:
            # Resetting the button
            self.output_directory.setDisabled(False)
            self.pushButton_showQuery.setDisabled(False)
            QApplication.restoreOverrideCursor()
            self.end_process()
            QApplication.processEvents()
Ejemplo n.º 47
0
def set_cursor_wait():
    """ Change cursor to 'WaitCursor' """
    while get_override_cursor() is not None:
        restore_cursor()
    QApplication.setOverrideCursor(Qt.WaitCursor)
Ejemplo n.º 48
0
    def accept(self):
        if self.mode == self.ASK_FOR_INPUT_MODE:
            # create the input layer (if not already done) and
            # update available options
            self.reloadInputLayer()

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

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

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

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

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

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

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

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

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

            # get output params, update output URI
            self.outUri.setDataSource(schema, table, geom, "", pk)
            uri = self.outUri.uri(False)

            providerName = self.db.dbplugin().providerName()

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

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

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

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

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

            onlySelected = self.chkSelectedFeatures.isChecked()

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

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

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

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

        QMessageBox.information(self, self.tr("Import to database"),
                                self.tr("Import was successful."))
        return QDialog.accept(self)
Ejemplo n.º 49
0
 def set_cursor(self, cursor):
     if cursor != self._lastCursor:
         self.unset_cursor()
         QApplication.setOverrideCursor(
             NavigationToolbar.Cursor.toQCursor(cursor))
         self._lastCursor = cursor
Ejemplo n.º 50
0
    def run(self):
        project_id = self.settings.value("project/id")
        epsg = self.settings.value("project/epsg")

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

        # If locale is different to frence or italian, german will be used.
        # Otherwise we get into troubles with the legends, e.g. locale = "en"
        # but
        # there is no english legend (qml file).
        if locale == "fr":
            pass
        elif locale == "it":
            pass
        else:
            locale = "de"

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

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            group = _translate("VeriSO_EE_FP3", "FixpunkteKategorie3", None)
            group += " (" + str(project_id) + ")"

            layer = {
                "type": "postgres",
                "title": _translate("VeriSO_EE_FP3", "Toleranzstufen",
                                    None),
                "featuretype": "tseinteilung_toleranzstufe",
                "geom": "geometrie", "key": "ogc_fid", "sql": "",
                "readonly": True, "group": group,
                "style": "tseinteilung/toleranzstufe_" + locale + ".qml"
                }

            # Visibility and if legend and/or groupd should be collapsed can
            # be set with parameters in the self.layer_loader.load()
            # method:
            # load(layer, visibility=True, collapsed_legend=False,
            # collapsed_group=False)
            vlayer = self.layer_loader.load(layer)

            layer = {
                "type": "postgres",
                "title": _translate("VeriSO_EE_FP3", "LFP3 Nachführung",
                                    None),
                "featuretype": "fixpunktekategorie3_lfp3nachfuehrung",
                "geom": "perimeter", "key": "ogc_fid", "sql": "",
                "readonly": True, "group": group
                }

            vlayer = self.layer_loader.load(layer, False, True)

            layer = {
                "type": "postgres",
                "title": _translate("VeriSO_EE_FP3", "LFP3", None),
                "featuretype": "fixpunktekategorie3_lfp3", "geom": "geometrie",
                "key": "ogc_fid", "sql": "", "readonly": True, "group": group,
                "style": "fixpunkte/lfp3_" + locale + ".qml"
                }

            vlayer = self.layer_loader.load(layer)

            layer = {
                "type": "postgres", "title": _translate("VeriSO_EE_FP3",
                                                        "LFP3 ausserhalb "
                                                        "Gemeinde",
                                                        None),
                "featuretype": "t_lfp3_ausserhalb_gemeinde",
                "geom": "geometrie", "key": "ogc_fid", "sql": "",
                "readonly": True, "group": group,
                "style": "fixpunkte/lfp3ausserhalb.qml"
                }

            vlayer = self.layer_loader.load(layer)

            # This is how WMS layer work.
            layer = {
                "type": "wms",
                "title": _translate("VeriSO_EE_FP3", "LFP1 + LFP2 Schweiz",
                                    None),
                "url": "http://wms.geo.admin.ch/",
                "layers": "ch.swisstopo.fixpunkte-lfp1,"
                          "ch.swisstopo.fixpunkte-lfp2",
                "format": "image/png", "crs": "EPSG:" + str(epsg),
                "group": group
                }

            vlayer = self.layer_loader.load(layer, False, True)

            layer = {
                "type": "postgres",
                "title": _translate("VeriSO_EE_FP3", "Gemeindegrenze",
                                    None),
                "featuretype": "gemeindegrenzen_gemeindegrenze",
                "geom": "geometrie", "key": "ogc_fid", "sql": "",
                "readonly": True, "group": group,
                "style": "global_qml/gemeindegrenze/gemgre_strichliert.qml"
                }

            gemgrelayer = self.layer_loader.load(layer)

            # Change map extent.
            # Bug (?) in QGIS: http://hub.qgis.org/issues/10980
            # Closed for the lack of feedback. Upsi...
            # Still a problem? (sz / 2015-04-12)
            if gemgrelayer:
                rect = gemgrelayer.extent()
                rect.scale(5)
                self.iface.mapCanvas().setExtent(rect)
                self.iface.mapCanvas().refresh()
                # Sometimes it does make much more sense
                # to zoom to maximal extent:
                # self.iface.mapCanvas().zoomToFullExtent()

        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=Qgis.Critical,
                duration=0)
        QApplication.restoreOverrideCursor()
Ejemplo n.º 51
0
    def CreateMISB(self):
        ''' Create MISB Video '''
        ''' Only tested using DJI Data '''
        # Create ProgressBar
        self.iface.messageBar().clearWidgets()
        progressMessageBar = self.iface.messageBar().createMessage(
            "Creating video packets...")
        progress = QProgressBar()
        progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        self.iface.messageBar().pushWidget(progressMessageBar, QGis.Info)

        QApplication.setOverrideCursor(Qt.WaitCursor)
        QApplication.processEvents()

        HFOV = self.sp_hfov.value()

        index = self.cmb_telemetry.currentIndex()
        out_record = self.cmb_telemetry.itemData(index)
        rowCount = self.GetRows(out_record)
        progress.setMaximum(rowCount)

        d = {}
        with open(out_record, encoding=encoding) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                date_start = datetime.strptime(row["CUSTOM.updateTime"],
                                               '%Y/%m/%d %H:%M:%S.%f')
                break

        with open(out_record, encoding=encoding) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                for k in row:
                    stripK = k.strip()
                    stripV = row[k].strip()
                    d[stripK] = stripV

                # We create the klv file for every moment
                sizeTotal = 0
                bufferData = b''
                cnt = 0

                for k, v in d.items():
                    try:
                        if k == "CUSTOM.updateTime":
                            # We prevent it from failing in the exact times that don't have milliseconds
                            try:
                                date_end = datetime.strptime(
                                    v, '%Y/%m/%d %H:%M:%S.%f')
                            except Exception:
                                date_end = datetime.strptime(
                                    v, '%Y/%m/%d %H:%M:%S')

                            _bytes = datetime_to_bytes(date_end)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key2 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Platform Heading Angle
                        if k == "OSD.yaw":
                            OSD_yaw = float(v)
                            if OSD_yaw < 0:
                                OSD_yaw = OSD_yaw + 360
                            _bytes = float_to_bytes(round(OSD_yaw, 4),
                                                    _domain5, _range5)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key5 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Platform Pitch Angle
                        if k == "OSD.pitch":
                            OSD_pitch = float(v)
                            _bytes = float_to_bytes(round(OSD_pitch, 4),
                                                    _domain6, _range6)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key6 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Platform Roll Angle
                        if k == "OSD.roll":
                            OSD_roll = float(v)
                            _bytes = float_to_bytes(round(OSD_roll, 4),
                                                    _domain7, _range7)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key7 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Sensor Latitude
                        if k == "OSD.latitude":
                            OSD_latitude = float(v)
                            _bytes = float_to_bytes(round(OSD_latitude, 4),
                                                    _domain13, _range13)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key13 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Sensor Longitude
                        if k == "OSD.longitude":
                            OSD_longitude = float(v)
                            _bytes = float_to_bytes(OSD_longitude, _domain14,
                                                    _range14)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key14 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Sensor True Altitude
                        if k == "OSD.altitude [m]":
                            OSD_altitude = float(v)
                            _bytes = float_to_bytes(round(OSD_altitude, 4),
                                                    _domain15, _range15)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key15 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Sensor Ellipsoid Height
                        if k == "OSD.height [m]":
                            OSD_height = float(v)
                            _bytes = float_to_bytes(round(OSD_height, 4),
                                                    _domain75, _range75)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key75 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Sensor Relative Azimuth Angle
                        if k == "GIMBAL.yaw":
                            # GIMBAL_yaw = float(v)
                            GIMBAL_yaw = 0.0
                            _bytes = float_to_bytes(round(GIMBAL_yaw, 4),
                                                    _domain18, _range18)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key18 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Sensor Relative Elevation Angle
                        if k == "GIMBAL.pitch":
                            GIMBAL_pitch = float(v)
                            _bytes = float_to_bytes(round(GIMBAL_pitch, 4),
                                                    _domain19, _range19)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key19 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                        # Sensor Relative Roll Angle
                        if k == "GIMBAL.roll":
                            GIMBAL_roll = float(v)
                            _bytes = float_to_bytes(round(GIMBAL_roll, 4),
                                                    _domain20, _range20)
                            _len = int_to_bytes(len(_bytes))
                            _bytes = _key20 + _len + _bytes
                            sizeTotal += len(_bytes)
                            bufferData += _bytes

                    except Exception:
                        print("Multiplexer error")
                        continue

                try:
                    # Diference time
                    td = date_end - date_start
                    end_path = self.klv_folder + "/%.1f.klv" % (round(
                        td.total_seconds(), 1))

                    # CheckSum
                    v = abs(hash(end_path)) % (10**4)
                    _bytes = int_to_bytes(v, 4)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key1 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # Sensor Horizontal Field of View
                    v = self.sp_hfov.value()
                    _bytes = float_to_bytes(float(v), _domain16, _range16)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key16 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # Sensor Vertical Field of View
                    v = self.sp_vfov.value()
                    _bytes = float_to_bytes(float(v), _domain17, _range17)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key17 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # TODO : Check these calculations
                    # Slant Range
                    anlge = 180 + (OSD_pitch + GIMBAL_pitch)
                    slantRange = abs(OSD_altitude / (cos(radians(anlge))))

                    _bytes = float_to_bytes(round(slantRange, 4), _domain21,
                                            _range21)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key21 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # Target Width
                    # targetWidth = 0.0
                    targetWidth = 2.0 * slantRange * tan(radians(HFOV / 2.0))

                    _bytes = float_to_bytes(round(targetWidth, 4), _domain22,
                                            _range22)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key22 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # Frame Center Latitude
                    angle = 90 + (OSD_pitch + GIMBAL_pitch)
                    tgHzDist = OSD_altitude * tan(radians(angle))
                    r_earth = 6371008.8

                    dy = tgHzDist * cos(radians(OSD_yaw))
                    framecenterlatitude = OSD_latitude + (dy /
                                                          r_earth) * (180 / pi)

                    _bytes = float_to_bytes(round(framecenterlatitude, 4),
                                            _domain23, _range23)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key23 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # Frame Center Longitude
                    dx = tgHzDist * sin(radians(OSD_yaw))
                    framecenterlongitude = OSD_longitude + (dx / r_earth) * (
                        180 / pi) / cos(OSD_latitude * pi / 180)

                    _bytes = float_to_bytes(round(framecenterlongitude, 4),
                                            _domain24, _range24)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key24 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # Frame Center Elevation
                    frameCenterElevation = 0.0

                    _bytes = float_to_bytes(frameCenterElevation, _domain25,
                                            _range25)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key25 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # TODO : If we save the corners in the klv have a overflow
                    #                     # CALCULATE CORNERS COORDINATES
                    #                     sensor = (OSD_longitude, OSD_latitude, OSD_altitude)
                    #                     frameCenter = (destPoint[0], destPoint[1], frameCenterElevation)
                    #                     FOV = (VFOV, HFOV)
                    #                     others = (OSD_yaw, GIMBAL_yaw, targetWidth, slantRange)
                    #                     cornerPointUL, cornerPointUR, cornerPointLR, cornerPointLL = CornerEstimationWithoutOffsets(sensor=sensor, frameCenter=frameCenter, FOV=FOV, others=others)
                    #
                    #                     # Corner Latitude Point 1 (Full)
                    #                     _bytes = float_to_bytes(round(cornerPointUL[0],4), _domain82, _range82)
                    #                     _len = int_to_bytes(len(_bytes))
                    #                     _bytes = _key82 + _len + _bytes
                    #                     sizeTotal += len(_bytes)
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Longitude Point 1 (Full)
                    #                     _bytes = float_to_bytes(round(cornerPointUL[1],4), _domain83, _range83)
                    #                     _len = int_to_bytes(len(_bytes))
                    #                     _bytes = _key83 + _len + _bytes
                    #                     sizeTotal += len(_bytes)
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Latitude Point 2 (Full)
                    #                     _bytes = float_to_bytes(round(cornerPointUR[0],4), _domain84, _range84)
                    #                     _len = int_to_bytes(len(_bytes))
                    #                     _bytes = _key84 + _len + _bytes
                    #                     sizeTotal += len(_bytes)
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Longitude Point 2 (Full)
                    #                     _bytes = float_to_bytes(round(cornerPointUR[1],4), _domain85, _range85)
                    #                     _len = int_to_bytes(len(_bytes))
                    #                     _bytes = _key85 + _len + _bytes
                    #                     sizeTotal += len(_bytes)
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Latitude Point 3 (Full)
                    #                     _bytes = float_to_bytes(round(cornerPointLR[0],4), _domain86, _range86)
                    #                     _len = int_to_bytes(len(_bytes))
                    #                     _bytes = _key86 + _len + _bytes
                    #                     sizeTotal += len(_bytes)
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Longitude Point 3 (Full)
                    #                     _bytes = float_to_bytes(round(cornerPointLR[1],4), _domain87, _range87)
                    #                     _len = int_to_bytes(len(_bytes))
                    #                     _bytes = _key87 + _len + _bytes
                    #                     sizeTotal += len(_bytes)
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Latitude Point 4 (Full)
                    #                     _bytes = float_to_bytes(round(cornerPointLL[0],4), _domain88, _range88)
                    #                     _len = int_to_bytes(len(_bytes))
                    #                     _bytes = _key88 + _len + _bytes
                    #                     sizeTotal += len(_bytes)
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Longitude Point 4 (Full)
                    #                     _bytes = float_to_bytes(round(cornerPointLL[1],4), _domain89, _range89)
                    #                     _len = int_to_bytes(len(_bytes))
                    #                     _bytes = _key89 + _len + _bytes
                    #                     sizeTotal += len(_bytes)
                    #                     bufferData += _bytes

                    # Platform Pitch Angle (Full)
                    _bytes = float_to_bytes(round(OSD_pitch, 4), _domain90,
                                            _range90)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key90 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # Platform Roll Angle (Full)
                    _bytes = float_to_bytes(round(OSD_roll, 4), _domain91,
                                            _range91)
                    _len = int_to_bytes(len(_bytes))
                    _bytes = _key91 + _len + _bytes
                    sizeTotal += len(_bytes)
                    bufferData += _bytes

                    # set packet header
                    writeData = cle
                    writeData += int_to_bytes(sizeTotal)
                    writeData += bufferData

                    # Write packet
                    f_write = open(end_path, "wb+")
                    f_write.write(writeData)
                    f_write.close()

                    cnt += 1

                    progress.setValue(cnt)

                except Exception as e:
                    print("Multiplexer error : " + str(e))

        QApplication.restoreOverrideCursor()
        QApplication.processEvents()
        progress.setValue(rowCount)
        self.iface.messageBar().clearWidgets()
        # We add it to the manager
        _, name = os.path.split(self.video_file)
        self.parent.AddFileRowToManager(name,
                                        self.video_file,
                                        islocal=True,
                                        klv_folder=self.klv_folder)
        # Close dialog
        self.close()
        return
Ejemplo n.º 52
0
    def run_stats(self):
        """Main function which do the process."""

        # Get the common fields.
        self.admin_layer = self.cbx_aggregation_layer.currentLayer()

        if self.use_point_layer:
            # If we use a point layer.
            point_layer = self.cbx_case_layer.currentLayer()
        else:
            # If we use a column with number of case.
            case_column = self.cbx_case_field.currentField()
            index_case = self.admin_layer.fields().indexFromName(case_column)
            #Replace laer.fieldNameIndex(name) to layer.fields().lookup\Field(name)
            #http://learn.openwaterfoundation.org/owf-app-geoprocessor-python-doc-dev/resources/migrate-qgis2-qgis3/

        if not self.use_area:
            # If we don't use density.
            population = self.cbx_population_field.currentField()
            index_population = self.admin_layer.fields().indexFromName(population)

        self.name_field=self.le_new_column.text()
        if not self.name_field:
            self.name_field = self.le_new_column.placeholderText()

        # Add new column.
        add_nb_intersections = self.checkBox_addNbIntersections.isChecked()

        # Ratio
        ratio = self.cbx_ratio.currentText()
        ratio = ratio.replace(' ', '')

        # Output.
        self.output_file_path = self.le_output_filepath.text()

        try:
            self.button_box_ok.setDisabled(True)
            # noinspection PyArgumentList
            QApplication.setOverrideCursor(Qt.WaitCursor)
            # noinspection PyArgumentList
            QApplication.processEvents()

            if not self.admin_layer:
                QMessageBox.information(None, "DEBUG:", str("There is no layer"))
                raise NoLayerProvidedException

            if not self.admin_layer and self.use_point_layer:
                QMessageBox.information(None, "DEBUG:", str("There is no layer"))
                raise NoLayerProvidedException

            crs_admin_layer = self.admin_layer.crs()

            if self.use_point_layer:
                crs_point_layer = point_layer.crs()
                if crs_admin_layer != crs_point_layer:
                    QMessageBox.information(None, "DEBUG:", str("CRS of two layers are not the same. Please set CRS."))
                    raise DifferentCrsException(
                        epsg1=crs_point_layer.authid(),
                        epsg2=crs_admin_layer.authid())

            if not self.use_point_layer and not self.use_area:
                if index_population == index_case:
                    QMessageBox.information(None, "DEBUG:", str("You are using the same variable for case and population. Please change."))
                    raise FieldException(field_1='Population', field_2='Case')

            try:
                ratio = float(ratio)
            except ValueError:
                QMessageBox.information(None, "DEBUG:", str("The variable is not number."))
                raise NotANumberException(suffix=ratio)

            # Output
            if not self.output_file_path:
                temp_file = NamedTemporaryFile(
                    delete=False,
                    suffix='-geohealth.shp')
                self.output_file_path = temp_file.name
                temp_file.flush()
                temp_file.close()
            else:
                with open(self.output_file_path, 'w') as document: pass

            admin_layer_provider = self.admin_layer.dataProvider()
            fields = self.admin_layer.fields()

            if admin_layer_provider.fields().indexFromName(self.name_field) != -1:
                QMessageBox.information(None, "DEBUG:", str("The field name already exist."))
                raise FieldExistingException(field=self.name_field)

            fields.append(QgsField(self.name_field, QVariant.Double))

            if add_nb_intersections:
                fields.append(QgsField('nb_of_intersections', QVariant.Int))

            data = []

            file_writer = QgsVectorFileWriter(
                self.output_file_path,
                'utf-8',
                fields,
                QgsWkbTypes.Polygon,
                self.admin_layer.crs(),
                'ESRI Shapefile')

            if self.use_point_layer:
                total_case = point_layer.featureCount()
            else:
                total_case = 0

            for i, feature in enumerate(self.admin_layer.getFeatures()):
                attributes = feature.attributes()

                if self.use_point_layer:
                    count = 0
                    for f in point_layer.getFeatures():
                        if f.geometry().intersects(feature.geometry()):
                            count += 1
                else:
                    count = int(attributes[index_case])
                    total_case += count

                try:
                    if self.use_area:
                        area = feature.geometry().area()
                        value = float(count) / area * ratio
                    else:
                        try:
                            population = float(attributes[index_population])
                        except ValueError:
                            QMessageBox.information(None, "DEBUG:", str("This is not a number."))
                            raise NotANumberException(
                                suffix=attributes[index_population])
                        value = float(count) / population * ratio

                except ZeroDivisionError:
                    value = None
                except TypeError:
                    value = None

                data.append(value)
                attributes.append(value)

                if add_nb_intersections:
                    attributes.append(count)

                new_feature = QgsFeature()
                new_geom = QgsGeometry(feature.geometry())
                new_feature.setAttributes(attributes)
                new_feature.setGeometry(new_geom)

                file_writer.addFeature(new_feature)

            del file_writer

            self.output_layer = QgsVectorLayer(
                self.output_file_path,
                self.name_field,
                'ogr')
            QgsProject.instance().addMapLayer(self.output_layer)

            if self.checkBox_incidence_runStats.isChecked():

                stats = Stats(data)

                items_stats = [
                    'Incidence null,%d' % stats.null_values(),
                    'Count(point),%d' % total_case,
                    'Count(polygon),%d' % self.admin_layer.featureCount(),
                    'Min,%d' % stats.min(),
                    'Average,%f' % stats.average(),
                    'Max,%d' % stats.max(),
                    'Median,%f' % stats.median(),
                    'Range,%d' % stats.range(),
                    'Variance,%f' % stats.variance(),
                    'Standard deviation,%f' % stats.standard_deviation()
                ]

                self.tableWidget.clear()
                self.tableWidget.setColumnCount(2)
                labels = ['Parameters', 'Values']
                self.tableWidget.setHorizontalHeaderLabels(labels)
                self.tableWidget.setRowCount(len(items_stats))

                for i, item in enumerate(items_stats):
                    s = item.split(',')
                    self.tableWidget.setItem(i, 0, QTableWidgetItem(s[0]))
                    self.tableWidget.setItem(i, 1, QTableWidgetItem(s[1]))
                self.tableWidget.resizeRowsToContents()

                self.draw_plot(data)

            else:
                self.hide()

            if self.symbology.isChecked():
                self.add_symbology()

            self.signalStatus.emit(3, tr('Successful process'))

        except GeoPublicHealthException as e:
            display_message_bar(msg=e.msg, level=e.level, duration=e.duration)

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

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

        QApplication.setOverrideCursor(Qt.WaitCursor)
        QApplication.processEvents()

        HFOV = self.sp_hfov.value()
        VFOV = self.sp_vfov.value()

        index = self.cmb_telemetry.currentIndex()
        out_record = self.cmb_telemetry.itemData(index)
        rowCount = self.GetRows(out_record)
        progress.setMaximum(rowCount)

        d = {}
        with open(out_record, encoding=encoding) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                date_start = datetime.strptime(row["CUSTOM.updateTime"],
                                               "%Y/%m/%d %H:%M:%S.%f")
                break

        with open(out_record, encoding=encoding) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                for k in row:
                    stripK = k.strip()
                    stripV = row[k].strip()
                    d[stripK] = stripV

                # We create the klv file for every moment
                bufferData = b""
                cnt = 0

                for k, v in d.items():
                    try:
                        if k == "CUSTOM.updateTime":
                            # We prevent it from failing in the exact times
                            # that don't have milliseconds
                            try:
                                date_end = datetime.strptime(
                                    v, "%Y/%m/%d %H:%M:%S.%f")
                            except Exception:
                                date_end = datetime.strptime(
                                    v, "%Y/%m/%d %H:%M:%S")

                            _bytes = bytes(
                                PrecisionTimeStamp(
                                    datetime_to_bytes(date_end)))
                            bufferData += _bytes

                        # Platform Heading Angle
                        if k == "OSD.yaw":
                            OSD_yaw = float(v)
                            if OSD_yaw < 0:
                                OSD_yaw = OSD_yaw + 360

                            _bytes = bytes(PlatformHeadingAngle(OSD_yaw))
                            bufferData += _bytes

                        # Platform Pitch Angle
                        if k == "OSD.pitch":
                            OSD_pitch = float(v)
                            _bytes = bytes(PlatformPitchAngle(OSD_pitch))
                            bufferData += _bytes

                        # Platform Roll Angle
                        if k == "OSD.roll":
                            OSD_roll = float(v)
                            _bytes = bytes(PlatformRollAngle(OSD_roll))
                            bufferData += _bytes

                        # Sensor Latitude
                        if k == "OSD.latitude":
                            OSD_latitude = float(v)
                            _bytes = bytes(SensorLatitude(OSD_latitude))
                            bufferData += _bytes

                        # Sensor Longitude
                        if k == "OSD.longitude":
                            OSD_longitude = float(v)
                            _bytes = bytes(SensorLongitude(OSD_longitude))
                            bufferData += _bytes

                        # Sensor True Altitude
                        if k == "OSD.altitude [m]":
                            OSD_altitude = float(v)
                            _bytes = bytes(SensorTrueAltitude(OSD_altitude))
                            bufferData += _bytes

                        # Sensor Ellipsoid Height
                        if k == "OSD.height [m]":
                            OSD_height = float(v)
                            _bytes = bytes(
                                SensorEllipsoidHeightConversion(OSD_height))
                            bufferData += _bytes

                        # Sensor Relative Azimuth Angle
                        if k == "GIMBAL.yaw":
                            # GIMBAL_yaw = float(v)
                            GIMBAL_yaw = 0.0
                            _bytes = bytes(
                                SensorRelativeAzimuthAngle(GIMBAL_yaw))
                            bufferData += _bytes

                        # Sensor Relative Elevation Angle
                        if k == "GIMBAL.pitch":
                            GIMBAL_pitch = float(v)
                            _bytes = bytes(
                                SensorRelativeElevationAngle(GIMBAL_pitch))
                            bufferData += _bytes

                        # Sensor Relative Roll Angle
                        if k == "GIMBAL.roll":
                            GIMBAL_roll = float(v)
                            _bytes = bytes(
                                SensorRelativeRollAngle(GIMBAL_roll))
                            bufferData += _bytes

                    except Exception as e:
                        qgsu.showUserAndLogMessage(
                            QCoreApplication.translate(
                                "Multiplexor", "Multiplexer error") + e,
                            onlyLog=True,
                        )
                        continue

                try:
                    # Diference time
                    td = date_end - date_start
                    end_path = self.klv_folder + "/%.1f.klv" % (round(
                        td.total_seconds(), 1))

                    # CheckSum
                    v = abs(hash(end_path)) % (10**4)
                    _bytes = bytes(Checksum(v))
                    bufferData += _bytes

                    # Sensor Horizontal Field of View
                    v = self.sp_hfov.value()
                    _bytes = bytes(SensorHorizontalFieldOfView(float(v)))
                    bufferData += _bytes

                    # Sensor Vertical Field of View
                    v = self.sp_vfov.value()
                    _bytes = bytes(SensorVerticalFieldOfView(float(v)))
                    bufferData += _bytes

                    # TODO : Check these calculations
                    # Slant Range
                    anlge = 180 + (OSD_pitch + GIMBAL_pitch)
                    slantRange = abs(OSD_altitude / (cos(radians(anlge))))

                    _bytes = bytes(SlantRange(slantRange))
                    bufferData += _bytes

                    # Target Width
                    # targetWidth = 0.0
                    targetWidth = 2.0 * slantRange * tan(radians(HFOV / 2.0))

                    try:
                        _bytes = bytes(TargetWidth(targetWidth))
                    except Exception:
                        _bytes = bytes(TargetWidth(0.0))

                    bufferData += _bytes

                    # Frame Center Latitude
                    angle = 90 + (OSD_pitch + GIMBAL_pitch)
                    tgHzDist = OSD_altitude * tan(radians(angle))

                    dy = tgHzDist * cos(radians(OSD_yaw))
                    framecenterlatitude = OSD_latitude + degrees(
                        (dy / EARTH_MEAN_RADIUS))

                    _bytes = bytes(FrameCenterLatitude(framecenterlatitude))
                    bufferData += _bytes

                    # Frame Center Longitude
                    dx = tgHzDist * sin(radians(OSD_yaw))
                    framecenterlongitude = OSD_longitude + degrees(
                        (dx / EARTH_MEAN_RADIUS)) / cos(radians(OSD_latitude))

                    _bytes = bytes(FrameCenterLongitude(framecenterlongitude))
                    bufferData += _bytes

                    # Frame Center Elevation
                    frameCenterElevation = 0.0
                    _bytes = bytes(FrameCenterElevation(frameCenterElevation))
                    bufferData += _bytes

                    # CALCULATE CORNERS COORDINATES
                    # FIXME : If we add this values, the klv parse has a overflow
                    # Probably the packets is not created correctly
                    #                     sensor = (OSD_longitude, OSD_latitude, OSD_altitude)
                    #                     frameCenter = (framecenterlongitude, framecenterlatitude, frameCenterElevation)
                    #                     FOV = (VFOV, HFOV)
                    #                     others = (OSD_yaw, GIMBAL_yaw, targetWidth, slantRange)
                    #                     cornerPointUL, cornerPointUR, cornerPointLR, cornerPointLL = CornerEstimationWithoutOffsets(sensor=sensor, frameCenter=frameCenter, FOV=FOV, others=others)
                    #
                    #                     # Corner Latitude Point 1 (Full) CornerLatitudePoint1Full
                    #                     _bytes = bytes(CornerLatitudePoint1Full(cornerPointUL[0]))
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Longitude Point 1 (Full)
                    #                     _bytes = bytes(CornerLongitudePoint1Full(cornerPointUL[1]))
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Latitude Point 2 (Full)
                    #                     _bytes = bytes(CornerLatitudePoint2Full(cornerPointUR[0]))
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Longitude Point 2 (Full)
                    #                     _bytes = bytes(CornerLongitudePoint2Full(cornerPointUR[1]))
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Latitude Point 3 (Full)
                    #                     _bytes = bytes(CornerLatitudePoint3Full(cornerPointLR[0]))
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Longitude Point 3 (Full)
                    #                     _bytes = bytes(CornerLongitudePoint3Full(cornerPointLR[1]))
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Latitude Point 4 (Full)
                    #                     _bytes = bytes(CornerLatitudePoint4Full(cornerPointLL[0]))
                    #                     bufferData += _bytes
                    #
                    #                     # Corner Longitude Point 4 (Full)
                    #                     _bytes = bytes(CornerLongitudePoint4Full(cornerPointLL[1]))
                    #                     bufferData += _bytes

                    # Platform Pitch Angle (Full)
                    _bytes = bytes(PlatformPitchAngleFull(OSD_pitch))
                    bufferData += _bytes

                    # Platform Roll Angle (Full)
                    _bytes = bytes(PlatformRollAngleFull(OSD_roll))
                    bufferData += _bytes

                    # set packet header
                    writeData = UASLocalMetadataSet
                    sizeTotal = len(bufferData)
                    writeData += int_to_bytes(sizeTotal)
                    writeData += bufferData

                    # Write packet
                    f_write = open(end_path, "wb+")
                    f_write.write(writeData)
                    f_write.close()

                    cnt += 1

                    progress.setValue(cnt)

                except Exception as e:
                    qgsu.showUserAndLogMessage(
                        QCoreApplication.translate(
                            "Multiplexor", "Multiplexer error") + str(e),
                        onlyLog=True,
                    )

        QApplication.restoreOverrideCursor()
        QApplication.processEvents()
        progress.setValue(rowCount)
        self.iface.messageBar().clearWidgets()
        # We add it to the manager
        _, name = os.path.split(self.video_file)
        self.parent.AddFileRowToManager(name,
                                        self.video_file,
                                        islocal=True,
                                        klv_folder=self.klv_folder)
        # Close dialog
        self.close()
        return
Ejemplo n.º 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_Gesamtplan", "project_id not set",
                           None))
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            group = _translate("VeriSO_NPLSO_Gesamtplan",
                               "Grundlagelayer - Gesamtplan", None)
            group += " (" + str(project_id) + ")"

            layer = {
                "type":
                "wms",
                "title":
                _translate("VeriSO_NPLSO_Gesamtplan",
                           "Hintergrundkarte schwarz-weiss (WMS)", None),
                "url":
                "https://geo.so.ch/wms?",
                "layers":
                "ch.so.agi.hintergrundkarte_sw",
                "format":
                "image/png",
                "crs":
                "EPSG:" + str(epsg),
                "group":
                group
            }
            vlayer = self.layer_loader.load(layer, True, True, False)

            layer = {
                "type":
                "wms",
                "title":
                _translate("VeriSO_NPLSO_Gesamtplan", "Orthofoto RGB", None),
                "url":
                "https://geo.so.ch/wms?",
                "layers":
                "ch.so.agi.orthofoto_rgb",
                "format":
                "image/jpeg",
                "crs":
                "EPSG:" + str(epsg),
                "group":
                group
            }
            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()
Ejemplo n.º 57
0
 def __enter__(self):
     QApplication.setOverrideCursor(self.cursor)
Ejemplo n.º 58
0
    def open_file(self):
        """
        Open the osm file with the osmconf
        """

        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.start_process()
        QApplication.processEvents()

        # Get fields
        osm_file = self.osm_file.filePath()
        osm_conf = self.osm_conf.filePath()
        output_directory = self.output_directory.filePath()
        prefix_file = self.lineEdit_filePrefix.text()
        load_only = self.radioButton_osmConf.isChecked()

        # Which geometry at the end ?
        output_geometry_types = self.get_output_geometry_types()

        try:
            if not output_geometry_types:
                raise OutPutGeomTypesException

            if not isfile(osm_file):
                raise FileDoesntExistException(suffix="*.osm or *.pbf")

            if load_only:
                if not isfile(osm_conf):
                    raise FileDoesntExistException(suffix="*.ini")

            if output_directory and not isdir(output_directory):
                raise DirectoryOutPutException

            if load_only:
                # Legacy, waiting to remove the OsmParser for QGIS >= 3.6
                # Change in osm_file_dialog.py L131 too
                output_geom_legacy = [
                    l.value.lower() for l in output_geometry_types
                ]
                osm_parser = OsmParser(osm_file,
                                       load_only=True,
                                       osm_conf=osm_conf,
                                       layers=output_geom_legacy)
                layers = osm_parser.parse()

                for item in list(layers.values()):
                    QgsProject.instance().addMapLayer(item)

            else:
                open_file(dialog=self,
                          osm_file=osm_file,
                          output_geom_types=output_geometry_types,
                          output_dir=output_directory,
                          prefix_file=prefix_file)
                display_message_bar(tr('Successful query'),
                                    level=Qgis.Success,
                                    duration=5)

        except QuickOsmException as e:
            self.display_geo_algorithm_exception(e)
        except Exception as e:  # pylint: disable=broad-except
            self.display_exception(e)
        finally:
            QApplication.restoreOverrideCursor()
            self.end_process()
            QApplication.processEvents()
Ejemplo n.º 59
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_PNF_Bestockt",
                                                     "project_id not set",
                                                     None))
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            group = _translate("VeriSO_PNF_Bestockt", "Maengel - Bestockte Flaeche" , None)
            group += " (" + str(project_id) + ")"

            layer = {
                "type": "postgres",
                "title": _translate("VeriSO_PNF_Bestockt", "Fehlerarten",
                                    None),
                "featuretype": "t_maengel_fehler",
                "geom": "", "key": "ogc_fid", "sql": "",
                "readonly": True, "group": group
            }
            lyr_fehlerarten = self.layer_loader.load(layer, False, True)

            layer = {
                "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt",
                                                        "Maengelarten",
                                                        None),
                "featuretype": "t_maengel_art",
                "geom": "", "key": "ogc_fid",
                "sql": "gruppe = 'Bestockte Flaeche'", "readonly": True,
                "group": group
            }
            lyr_maengelarten = self.layer_loader.load(layer, False, True)
            
            layer = {
                "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt",
                                                        "Maengelliste (Punkte)",
                                                        None),
                "featuretype": "t_maengel",
                "geom": "the_geom", "key": "ogc_fid",
                "sql": "gruppe = 'Bestockte Flaeche'", "readonly": False,
                "group": group, "style": "maengel/maengel.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True)
            
            if vlayer <> False:
                self.iface.legendInterface().setLayerVisible(vlayer, True) 
                vlayer.setLayerName(u"Mängelliste (Punkte)")
                #vlayer.saveDefaultStyle()            

                provider = vlayer.dataProvider()
                provider.attributeIndexes()
                ogc_fid_idx = provider.fieldNameIndex("ogc_fid")
                gruppe_idx = provider.fieldNameIndex("gruppe")
                art_idx = provider.fieldNameIndex("art")
                fehler_idx = provider.fieldNameIndex("fehler")
                feld_idx = provider.fieldNameIndex("feldkontrolle")
                lnf_idx = provider.fieldNameIndex("lnf")
                terr_idx = provider.fieldNameIndex("terrestrisch")
                bemerkung_idx = provider.fieldNameIndex("bemerkung")
                datum_idx = provider.fieldNameIndex("datum")  

                vlayer.addAttributeAlias(gruppe_idx, "Gruppe:")
                vlayer.addAttributeAlias(art_idx, "Art:")
                vlayer.addAttributeAlias(fehler_idx, "Fehler:")
                vlayer.addAttributeAlias(feld_idx, "Feldkontrolle:")
                vlayer.addAttributeAlias(lnf_idx, u"Laufende Nachführung:")
                vlayer.addAttributeAlias(terr_idx, "Terrestrische Aufnahme:")
                vlayer.addAttributeAlias(bemerkung_idx, "Bemerkung:")
      
                vlayer.setEditorWidgetV2(0,"Hidden")
                vlayer.setEditorWidgetV2(1, "ValueRelation")
                vlayer.setEditorWidgetV2(2, "ValueRelation")
                vlayer.setEditorWidgetV2(3, "ValueRelation")
                vlayer.setEditorWidgetV2(4, "CheckBox")
                vlayer.setEditorWidgetV2(5, "CheckBox")
                vlayer.setEditorWidgetV2(6, "CheckBox")
                vlayer.setEditorWidgetV2(7, "TextEdit")            
                vlayer.setEditorWidgetV2(8, "Hidden")        
                 
                vlayer.setEditorWidgetV2Config(1, {'Layer':lyr_maengelarten.id(), 'Key':'gruppe', 'Value':'gruppe', 'OrderByValue':"1", 'AllowNull':"0", 'AllowMutli':'0'})
                vlayer.setEditorWidgetV2Config(2, {'Layer':lyr_maengelarten.id(), 'Key':'art_txt', 'Value':'art_txt', 'OrderByValue':"1", 'AllowNull':"1", 'AllowMutli':'0' })
                vlayer.setEditorWidgetV2Config(3, {'Layer':lyr_fehlerarten.id(), 'Key':'fehler_txt', 'Value':'fehler_txt', 'OrderByValue':"1", 'AllowNull':"1", 'AllowMutli':'0' })
                vlayer.setEditorWidgetV2Config(4, {'fieldEditable':"1", 'UncheckedState':'f','CheckedState':'t'})
                vlayer.setEditorWidgetV2Config(5, {'fieldEditable':"1", 'UncheckedState':'f','CheckedState':'t'})
                vlayer.setEditorWidgetV2Config(6, {'fieldEditable':"1", 'UncheckedState':'f','CheckedState':'t'})
                vlayer.setEditorWidgetV2Config(7, {'IsMultiline':"1", 'fieldEditable':"1", 'UseHtml':"0", 'labelOnTop':"0"})

            
            layer = {
                "type": "postgres", "title": _translate("VeriSO_PNF_Bestockt",
                                                        "Maengelliste (Linien)",
                                                        None),
                "featuretype": "t_maengel_linie",
                "geom": "the_geom", "key": "ogc_fid",
                "sql": "gruppe = 'Bestockte Flaeche'", "readonly": False,
                "group": group, "style": "maengel/maengel_linie.qml"
            }
            vlayer = self.layer_loader.load(layer, False, True)
            
            if vlayer <> False:
                self.iface.legendInterface().setLayerVisible(vlayer, True) 
                vlayer.setLayerName(u"Mängelliste (Linie)")
                #vlayer.saveDefaultStyle()            

                provider = vlayer.dataProvider()
                provider.attributeIndexes()
                ogc_fid_idx = provider.fieldNameIndex("ogc_fid")
                gruppe_idx = provider.fieldNameIndex("gruppe")
                art_idx = provider.fieldNameIndex("art")
                fehler_idx = provider.fieldNameIndex("fehler")
                feld_idx = provider.fieldNameIndex("feldkontrolle")
                lnf_idx = provider.fieldNameIndex("lnf")
                terr_idx = provider.fieldNameIndex("terrestrisch")
                bemerkung_idx = provider.fieldNameIndex("bemerkung")
                datum_idx = provider.fieldNameIndex("datum")  

                vlayer.addAttributeAlias(gruppe_idx, "Gruppe:")
                vlayer.addAttributeAlias(art_idx, "Art:")
                vlayer.addAttributeAlias(fehler_idx, "Fehler:")
                vlayer.addAttributeAlias(feld_idx, "Feldkontrolle:")
                vlayer.addAttributeAlias(lnf_idx, u"Laufende Nachführung:")
                vlayer.addAttributeAlias(terr_idx, "Terrestrische Aufnahme:")
                vlayer.addAttributeAlias(bemerkung_idx, "Bemerkung:")
      
                vlayer.setEditorWidgetV2(0,"Hidden")
                vlayer.setEditorWidgetV2(1, "ValueRelation")
                vlayer.setEditorWidgetV2(2, "ValueRelation")
                vlayer.setEditorWidgetV2(3, "ValueRelation")
                vlayer.setEditorWidgetV2(4, "CheckBox")
                vlayer.setEditorWidgetV2(5, "CheckBox")
                vlayer.setEditorWidgetV2(6, "CheckBox")
                vlayer.setEditorWidgetV2(7, "TextEdit")            
                vlayer.setEditorWidgetV2(8, "Hidden")        
                 
                vlayer.setEditorWidgetV2Config(1, {'Layer':lyr_maengelarten.id(), 'Key':'gruppe', 'Value':'gruppe', 'OrderByValue':"1", 'AllowNull':"0", 'AllowMutli':'0'})
                vlayer.setEditorWidgetV2Config(2, {'Layer':lyr_maengelarten.id(), 'Key':'art_txt', 'Value':'art_txt', 'OrderByValue':"1", 'AllowNull':"1", 'AllowMutli':'0' })
                vlayer.setEditorWidgetV2Config(3, {'Layer':lyr_fehlerarten.id(), 'Key':'fehler_txt', 'Value':'fehler_txt', 'OrderByValue':"1", 'AllowNull':"1", 'AllowMutli':'0' })
                vlayer.setEditorWidgetV2Config(4, {'fieldEditable':"1", 'UncheckedState':'f','CheckedState':'t'})
                vlayer.setEditorWidgetV2Config(5, {'fieldEditable':"1", 'UncheckedState':'f','CheckedState':'t'})
                vlayer.setEditorWidgetV2Config(6, {'fieldEditable':"1", 'UncheckedState':'f','CheckedState':'t'})
                vlayer.setEditorWidgetV2Config(7, {'IsMultiline':"1", 'fieldEditable':"1", 'UseHtml':"0", 'labelOnTop':"0"})

        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()
Ejemplo n.º 60
0
    def runAction(self, action):
        action = str(action)

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

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

            msg = QApplication.translate(
                "DBManagerPlugin",
                "Do you want to {0} all triggers?").format(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 {0} trigger {1}?").format(
                    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