def setData(self, index, value, role): if role != Qt.EditRole or index.column() != 0: return False item = index.internalPointer() new_value = unicode(value) if isinstance(item, SchemaItem) or isinstance(item, TableItem): obj = item.getItemData() # rename schema or table or view if new_value == obj.name: return False QApplication.setOverrideCursor(Qt.WaitCursor) try: obj.rename(new_value) self._onDataChanged(index) except BaseError as e: DlgDbError.showError(e, self.treeView) return False finally: QApplication.restoreOverrideCursor() return True return False
def 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()
def fetchAvailablePlugins(self, reloadMode): """ Fetch plugins from all enabled repositories.""" """ reloadMode = true: Fully refresh data from QSettings to mRepositories """ """ reloadMode = false: Fetch unready repositories only """ QApplication.setOverrideCursor(Qt.WaitCursor) if reloadMode: repositories.load() plugins.clearRepoCache() plugins.getAllInstalled() for key in repositories.allEnabled(): if reloadMode or repositories.all()[key]["state"] == 3: # if state = 3 (error or not fetched yet), try to fetch once again repositories.requestFetching(key) if repositories.fetchingInProgress(): fetchDlg = QgsPluginInstallerFetchingDialog(iface.mainWindow()) fetchDlg.exec_() del fetchDlg for key in repositories.all(): repositories.killConnection(key) QApplication.restoreOverrideCursor() # display error messages for every unavailable reposioty, unless Shift pressed nor all repositories are unavailable keepQuiet = QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier) if repositories.allUnavailable() and repositories.allUnavailable() != repositories.allEnabled(): for key in repositories.allUnavailable(): if not keepQuiet: QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Error reading repository:") + " " + key + "\n\n" + repositories.all()[key]["error"]) if QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier): keepQuiet = True # finally, rebuild plugins from the caches plugins.rebuild()
def resetGUI(self): QApplication.restoreOverrideCursor() self.lblProgress.setText('') self.progressBar.setMaximum(100) self.progressBar.setValue(0) self.btnRun.setEnabled(True) self.btnClose.setEnabled(True)
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_V+D_BB", "project_id not set", None)) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_V+D_BB", "Grundstücke", None) group += " (" + str(project_id) + ")" layer = { "type": "postgres", "title": _translate("VeriSO_V+D_BB", "LS.Liegenschaften", None), "featuretype": "v_liegenschaften_liegenschaft", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "grundstuecke/liegenschaften.qml" } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_BB", "LS.GrundstueckPos (" "Liegenschaften)", None), "featuretype": "v_liegenschaften_grundstueckpos", "geom": "pos", "key": "ogc_fid", "sql": "art = 'Liegenschaft'", "readonly": True, "group": group, "style": "grundstuecke/grundstueckpos.qml" } vlayer = self.layer_loader.load(layer, False, True) 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()
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
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_V+D_BB", "project_id not set", None) ) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_V+D_BB", "Bodenbedeckung", None) group += " (" + str(project_id) + ")" layer = { "type": "postgres", "title": _translate("VeriSO_V+D_BB", "BB.BoFlaeche", None), "featuretype": "bodenbedeckung_boflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bodenbedeckung/boflaeche_color.qml" } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_BB", "BB.ProjBoFlaeche", None), "featuretype": "bodenbedeckung_projboflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bodenbedeckung/projboflaeche_color.qml" } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_BB", "EO.Flaechenelemente", None), "featuretype": "v_einzelobjekte_flaechenelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "einzelobjekte/eo_flaeche_color.qml" } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_BB", "EO.Linienelemente", None), "featuretype": "v_einzelobjekte_linienelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "einzelobjekte/eo_linie_color.qml" } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_BB", "EO.Punktelemente", None), "featuretype": "v_einzelobjekte_punktelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "einzelobjekte/eo_punkte_color.qml" } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "postgres", "title": _translate("VeriSO_V+D_BB", "BB.Symbole", None), "featuretype": "v_bodenbedeckung_boflaechesymbol", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bodenbedeckung/bb_symbole.qml" } vlayer = self.layer_loader.load(layer, True, True) # export some statistics here. layer = { "type": "postgres", "title": _translate("VeriSO_V+D_BB", "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() self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() # self.export_lfp3_pro_ts(vlayer_lfp3_pro_ts) 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()
def accept(self): self.algs = [] self.load = [] self.canceled = False for row in range(self.mainWidget.tblParameters.rowCount()): alg = self.alg.getCopy() # hack - remove when getCopy is removed alg.setProvider(self.alg.provider()) col = 0 for param in alg.parameters: if param.hidden: continue wrapper = self.mainWidget.wrappers[row][col] if not self.mainWidget.setParamValue(param, wrapper, alg): self.bar.pushMessage( "", self.tr( 'Wrong or missing parameter value: {0} (row {1})'). format(param.description, row + 1), level=QgsMessageBar.WARNING, duration=5) self.algs = None return col += 1 for out in alg.outputs: if out.hidden: continue widget = self.mainWidget.tblParameters.cellWidget(row, col) text = widget.getValue() if text.strip() != '': out.value = text col += 1 else: self.bar.pushMessage( "", self.tr('Wrong or missing output value: {0} (row {1})' ).format(out.description, row + 1), level=QgsMessageBar.WARNING, duration=5) self.algs = None return self.algs.append(alg) if self.alg.getVisibleOutputsCount(): widget = self.mainWidget.tblParameters.cellWidget(row, col) self.load.append(widget.currentIndex() == 0) else: self.load.append(False) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.mainWidget.setEnabled(False) self.progressBar.setMaximum(len(self.algs)) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass context = dataobjects.createContext() for count, alg in enumerate(self.algs): self.setText( self.tr('\nProcessing algorithm {0}/{1}...').format( count + 1, len(self.algs))) self.setInfo( self.tr('<b>Algorithm {0} starting...</b>').format( alg.displayName())) if execute(alg, context, self.feedback) and not self.canceled: if self.load[count]: handleAlgorithmResults(alg, context, self.feedback, False) self.setInfo( self.tr('Algorithm {0} correctly executed...').format( alg.displayName())) else: QApplication.restoreOverrideCursor() return self.finish()
def restore_cursor(self): QApplication.restoreOverrideCursor() self.buttonBox.setEnabled(True)
def accept(self, *args, **kwargs): 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) # Add settings to log settingsStr = 'Parameters:---------------------------------------' settingsStr += '\n {:20}\t{}'.format( 'Line layer:', self.mcboLineLayer.currentLayer().name()) settingsStr += '\n {:20}\t{}'.format( 'Distance between points (m):', self.dsbDistBtwnPoints.value()) settingsStr += '\n {:20}\t{}'.format( 'Line offset distance (m):', self.dsbLineOffsetDist.value()) if self.chkUseSelected.isChecked(): settingsStr += '\n {:20}\t{} with {} selected features'.format( 'Layer:', self.mcboLineLayer.currentLayer().name(), self.mcboLineLayer.currentLayer().selectedFeatureCount()) settingsStr += '\n {:30}\t{} - {}'.format( 'Output coordinate system:', self.mCRSoutput.crs().authid(), self.mCRSoutput.crs().description()) settingsStr += '\n {:30}\t{}'.format( 'Output points :', self.lneSavePointsFile.text()) if self.lneSaveLinesFile.text() == '': settingsStr += '\n {:30}\t{}\n'.format( 'Output lines:', self.lneSaveLinesFile.text()) LOGGER.info(settingsStr) lyr_line = self.mcboLineLayer.currentLayer() if self.chkUseSelected.isChecked(): line_shapefile = os.path.join(TEMPDIR, lyr_line.name() + '_lines.shp') if os.path.exists(line_shapefile): removeFileFromQGIS(line_shapefile) QgsVectorFileWriter.writeAsVectorFormat( lyr_line, line_shapefile, "utf-8", self.mCRSoutput.crs(), driverName="ESRI Shapefile", onlySelected=True) if self.DISP_TEMP_LAYERS: addVectorFileToQGIS( line_shapefile, layer_name=os.path.splitext( os.path.basename(line_shapefile))[0], group_layer_name='DEBUG', atTop=True) else: line_shapefile = get_layer_source(lyr_line) lines_desc = describe.VectorDescribe(line_shapefile) gdf_lines = lines_desc.open_geo_dataframe() epsgOut = int(self.mCRSoutput.crs().authid().replace('EPSG:', '')) out_lines = None if self.lneSaveLinesFile.text() == '': out_lines = self.lneSaveLinesFile.text() _ = create_points_along_line( gdf_lines, lines_desc.crs, self.dsbDistBtwnPoints.value(), self.dsbLineOffsetDist.value(), epsgOut, out_points_shapefile=self.lneSavePointsFile.text(), out_lines_shapefile=out_lines) out_lyr_points = addVectorFileToQGIS( self.lneSavePointsFile.text(), atTop=True, layer_name=os.path.splitext( os.path.basename(self.lneSavePointsFile.text()))[0]) vector_apply_unique_value_renderer(out_lyr_points, 'Strip_Name') if self.lneSaveLinesFile.text() == '': out_lyr_lines = addVectorFileToQGIS( self.lneSaveLinesFile.text(), atTop=True, layer_name=os.path.splitext( os.path.basename(self.lneSaveLinesFile.text()))[0]) vector_apply_unique_value_renderer(out_lyr_lines, 'Strip_Name') self.cleanMessageBars(True) self.fraMain.setDisabled(False) self.iface.mainWindow().statusBar().clearMessage() self.iface.messageBar().popWidget() QApplication.restoreOverrideCursor() return super(StripTrialPointsDialog, 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
def create_project(self, project_name, project_dir, is_public, namespace): """ After user has selected project name, this function does the communication. 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 QApplication.restoreOverrideCursor() if not project_dir: # not going to upload anything so just pop a "success" message and exit self.depopulate() QMessageBox.information( None, 'Create Project', "An empty project has been created on the server", QMessageBox.Close) return ## 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(): self.depopulate() QMessageBox.warning( None, "Create Project", "The project directory is empty - nothing to upload.") return 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 if not dlg.is_complete: # we were cancelled - but no need to show a message box about that...? return settings = QSettings() settings.setValue( 'Mergin/localProjects/{}/path'.format(full_project_name), project_dir) 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') self.depopulate( ) # make sure the project item has the link between remote and local project we have just added QMessageBox.information( None, 'Create Project', "Mergin project created and uploaded successfully", QMessageBox.Close)
def sync_project(self): if not self.path: return if not self._unsaved_changes_check(): return pull_changes, push_changes, push_changes_summary = self.mc.project_status( self.path) if not sum( len(v) for v in list(pull_changes.values()) + list(push_changes.values())): QMessageBox.information(None, 'Project sync', 'Project is already up-to-date', QMessageBox.Close) return dlg = SyncDialog() dlg.pull_start(self.mc, self.path, self.project_name) dlg.exec_() # blocks until success, failure or cancellation if dlg.exception: # pull 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 {self.project_name} due to an unhandled exception." ) return if dlg.pull_conflicts: msg = "Following conflicts between local and server version found: \n\n" for item in dlg.pull_conflicts: msg += item + "\n" msg += "\nYou may want to fix them before upload otherwise they will be uploaded as new files. " \ "Do you wish to proceed?" btn_reply = QMessageBox.question(None, 'Conflicts found', msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if btn_reply == QMessageBox.No: QApplication.restoreOverrideCursor() return if not dlg.is_complete: # we were cancelled return # pull finished, start push if any(push_changes.values()) and not self._have_writing_permissions(): QMessageBox.information( None, "Project sync", "You have no writing rights to this project", QMessageBox.Close) return dlg = SyncDialog() dlg.push_start(self.mc, self.path, self.project_name) dlg.exec_() # blocks until success, failure or cancellation self._reload_project( ) # TODO: only reload project if we pulled a newer version 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 {self.project_name} due to an unhandled exception." ) return if dlg.is_complete: # TODO: report success only when we have actually done anything msg = "Mergin project {} synchronized successfully".format( self.project_name) QMessageBox.information(None, 'Project sync', msg, QMessageBox.Close) else: # we were cancelled - but no need to show a message box about that...? pass
def download(self): settings = QSettings() last_parent_dir = settings.value('Mergin/lastUsedDownloadDir', '') parent_dir = QFileDialog.getExistingDirectory(None, "Open Directory", last_parent_dir, QFileDialog.ShowDirsOnly) if not parent_dir: return settings.setValue('Mergin/lastUsedDownloadDir', parent_dir) target_dir = os.path.abspath( os.path.join(parent_dir, self.project['name'])) if os.path.exists(target_dir): QMessageBox.warning( None, "Download Project", "The target directory already exists:\n" + target_dir + "\n\nPlease select a different directory.") return dlg = SyncDialog() dlg.download_start(self.mc, target_dir, self.project_name) dlg.exec_() # blocks until completion / failure / cancellation if dlg.exception: if isinstance(dlg.exception, (URLError, ValueError)): QgsApplication.messageLog().logMessage("Mergin plugin: " + str(dlg.exception)) msg = "Failed to download your project {}.\n" \ "Please make sure your Mergin settings are correct".format(self.project_name) QMessageBox.critical(None, 'Project download', msg, QMessageBox.Close) elif isinstance(dlg.exception, LoginError): login_error_message(dlg.exception) else: unhandled_exception_message( dlg.exception_details(), "Project download", f"Failed to download project {self.project_name} due to an unhandled exception." ) return if not dlg.is_complete: return # either it has been cancelled or an error has been thrown settings.setValue( 'Mergin/localProjects/{}/path'.format(self.project_name), target_dir) self.path = target_dir self.setIcon(QIcon(os.path.join(icon_path, "folder-solid.svg"))) QApplication.restoreOverrideCursor() msg = "Your project {} has been successfully downloaded. " \ "Do you want to open project file?".format(self.project_name) btn_reply = QMessageBox.question(None, 'Project download', msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if btn_reply == QMessageBox.Yes: self.open_project()
def update_clicked(self, commit_status=True): """Called when update btn clicked""" # set cursor to busy QApplication.setOverrideCursor(Qt.WaitCursor) # setup self.message = "" self.api_key = self.le_key.text() self.updates = [] # canals if self.chbx_canals.isChecked(): self.topo_layer_processing("canal_polygons") # lagoon if self.chbx_lagoons.isChecked(): self.topo_layer_processing("lagoon_polygons") # lake if self.chbx_lakes.isChecked(): self.topo_layer_processing("lake_polygons") # pond if self.chbx_ponds.isChecked(): self.topo_layer_processing("pond_polygons") # rivers if self.chbx_rivers.isChecked(): self.topo_layer_processing("river_polygons") # swamp if self.chbx_swamps.isChecked(): self.topo_layer_processing("swamp_polygons") # huts if self.chbx_huts.isChecked(): self.topo_layer_processing("hut_points") # shelters if self.chbx_shelters.isChecked(): self.topo_layer_processing("shelter_points") # bivouacs if self.chbx_bivouacs.isChecked(): self.topo_layer_processing("bivouac_points") # protected areas if self.chbx_protected_areas.isChecked(): self.topo_layer_processing("protected_areas_polygons") # coastlines and islands (placeholder) if self.chbx_coastline_and_islands.isChecked(): self.message += "The coastlines and islands table must be updated manually" if self.db._open_cursor is None: self.db.open_cursor() # suburb localities if self.chbx_suburbs.isChecked(): # update building_outlines suburb values (changed, deleted & added) # delete remove suburbs and update modified suburbs db.execute_no_commit( "SELECT buildings_reference.building_outlines_update_changed_and_deleted_suburb();" ) # add new suburbs and update building outlines db.execute_no_commit( "SELECT buildings_reference.building_outlines_update_added_suburb();" ) # update messages and log self.update_message("updated", "suburb_locality") self.updates.append("suburb_locality") # town_city if self.chbx_town.isChecked(): town_list = [] # delete existing areas where the external id is no longer in the town_city table result = db.execute_no_commit( "SELECT buildings_reference.town_city_delete_removed_areas();") if result is not None: town_list.extend(result.fetchone()[0]) # modify all existing areas to check they are up to date result = db.execute_no_commit( "SELECT buildings_reference.town_city_insert_new_areas();") if result is not None: town_list.extend(result.fetchone()[0]) # insert into table ids in nz_localities that are not in town_city result = db.execute_no_commit( "SELECT buildings_reference.town_city_update_areas();") if result is not None: town_list.extend(result.fetchone()[0]) # update bulk_load_outlines town/city values db.execute_no_commit( "SELECT buildings_bulk_load.bulk_load_outlines_update_all_town_cities(%s);", (town_list, ), ) # update building outlines town/city values db.execute_no_commit( "SELECT buildings.building_outlines_update_town_city(%s);", (town_list, )) # update messages and log self.update_message("updated", "town_city") self.updates.append("town_city") # territorial authority and grid if self.chbx_ta.isChecked(): ta_list = [] # delete removed TA areas result = db.execute_no_commit( "SELECT buildings_reference.territorial_auth_delete_areas();") if result is not None: ta_list.extend(result.fetchone()[0]) # Insert TA areas result = db.execute_no_commit( "SELECT buildings_reference.territorial_auth_insert_areas();") if result is not None: ta_list.extend(result.fetchone()[0]) # Update new TA areas result = db.execute_no_commit( "SELECT buildings_reference.territorial_auth_update_areas();") if result is not None: ta_list.extend(result.fetchone()[0]) # update bulk_load_outlines territorial authority values db.execute_no_commit( "SELECT buildings_bulk_load.bulk_load_outlines_update_all_territorial_authorities(%s);", (ta_list, ), ) # update building outlines territorial authority values db.execute_no_commit( "SELECT buildings.building_outlines_update_territorial_authority(%s);", (ta_list, ), ) # update message and log self.update_message("updated", "territorial_authority") self.updates.append("territorial_authority") # refresh grid db.execute_no_commit(reference_select.refresh_ta_grid_view) self.update_message("updated", "territorial_authority_grid") self.updates.append("territorial_authority_grid") # create log for this update if len(self.updates) > 0: sql = "SELECT buildings_reference.reference_update_log_insert_log(%s);" self.db.execute_no_commit(sql, (self.updates, )) # restore cursor QApplication.restoreOverrideCursor() # final message box if self.message == "": self.message = "No layers were updated." self.msgbox.setText(self.message) self.msgbox.exec_() if commit_status: self.db.commit_open_cursor()
def handleAlgorithmResults(alg, context, feedback=None, showResults=True): wrongLayers = [] if feedback is None: feedback = QgsProcessingFeedback() feedback.setProgressText( QCoreApplication.translate('Postprocessing', 'Loading resulting layers')) i = 0 for l, details in context.layersToLoadOnCompletion().items(): if feedback.isCanceled(): return False if len(context.layersToLoadOnCompletion()) > 2: # only show progress feedback if we're loading a bunch of layers feedback.setProgress( 100 * i / float(len(context.layersToLoadOnCompletion()))) try: layer = QgsProcessingUtils.mapLayerFromString(l, context) if layer is not None: layer.setName(details.name) details.project.addMapLayer( context.temporaryLayerStore().takeMapLayer(layer)) else: name = details.name if ProcessingConfig.getSetting( ProcessingConfig.USE_FILENAME_AS_LAYER_NAME): name = os.path.basename(l) dataobjects.load(l, name, alg.crs, RenderingStyles.getStyle(alg.id(), l)) except Exception: QgsMessageLog.logMessage( "Error loading result layer:\n" + traceback.format_exc(), 'Processing', QgsMessageLog.CRITICAL) #wrongLayers.append(out.description()) wrongLayers.append(l) # for out in alg.outputs: # feedback.setProgress(100 * i / float(len(alg.outputs))) # if out.flags() & QgsProcessingParameterDefinition.FlagHidden or not out.open: # continue # if isinstance(out, (OutputRaster, OutputVector, OutputTable)): # try: # layer = QgsProcessingUtils.mapLayerFromString(out.value, context) # if layer: # layer.setName(out.description) # QgsProject.instance().addMapLayer(context.temporaryLayerStore().takeMapLayer(layer)) # else: # if ProcessingConfig.getSetting( # ProcessingConfig.USE_FILENAME_AS_LAYER_NAME): # name = os.path.basename(out.value) # else: # name = out.description # # isRaster = True if isinstance(out, OutputRaster) else False # dataobjects.load(out.value, name, alg.crs, # RenderingStyles.getStyle(alg.id(), out.name), # isRaster) # except Exception: # QgsMessageLog.logMessage("Error loading result layer:\n" + traceback.format_exc(), 'Processing', QgsMessageLog.CRITICAL) # wrongLayers.append(out.description) # elif isinstance(out, OutputHTML): # resultsList.addResult(alg.icon(), out.description, out.value) i += 1 QApplication.restoreOverrideCursor() if wrongLayers: msg = "The following layers were not correctly generated.<ul>" msg += "".join(["<li>%s</li>" % lay for lay in wrongLayers]) + "</ul>" msg += "You can check the log messages to find more information about the execution of the algorithm" feedback.reportError(msg) return len(wrongLayers) == 0
def __init__(self, iface, parent=None): QMainWindow.__init__(self, parent) if QApplication.overrideCursor(): QApplication.restoreOverrideCursor() self.setAttribute(Qt.WA_DeleteOnClose) tdir = os.path.dirname(os.path.realpath(__file__)) uif = os.path.join(tdir, "ui", "ui_rivergis.ui") self.ui = uic.loadUi(uif, self) self.conn = None self.curConnName = None self.schema = None self.passwd = None self.rdb = None self.iface = iface # self.mapRegistry = QgsMapLayerRegistry.instance() self.rivergisPath = os.path.dirname(__file__) self.dtms = [] # restore settings self.readSettings() self.menus = self.ui.menubar.findChildren(QMenu) self.toolbars = self.findChildren(QToolBar) # MENU Actions # DB self.ui.actionRefreshConnections.triggered.connect(self.connChanged) self.ui.actionCreateNewSchema.triggered.connect(self.dbCreateSchema) self.ui.actionDeleteSchema.triggered.connect(self.dbDeleteSchema) self.ui.actionRASCreateRdbTables.triggered.connect(self.rasCreateRdbTables) self.ui.actionRASLoadRdbTablesIntoQGIS.triggered.connect(self.rasLoadRdbTablesIntoQGIS) self.ui.actionRASImportLayersIntoRdbTables.triggered.connect(self.rasImportLayersIntoRdbTables) # Settings self.ui.actionOptions.triggered.connect(self.options) self.ui.actionRestoreDefaultOptions.triggered.connect(lambda: self.readSettings(defaults=True)) # RAS Geometry # 1D self.ui.actionRASTopology1D.triggered.connect(lambda: r1d.ras1dStreamCenterlineTopology(self)) self.ui.actionRASLengthsStations.triggered.connect(lambda: r1d.ras1dStreamCenterlineLengthsStations(self)) self.ui.actionCopyStreamCenterlines2Flowpaths.triggered.connect(lambda: r1d.ras1dStreamCenterlines2Flowpaths(self)) self.ui.actionRASStreamCenterlineAll.triggered.connect(lambda: r1d.ras1dStreamCenterlineAll(self)) self.ui.actionRASXSRiverReachNames.triggered.connect(lambda: r1d.ras1dXSRiverReachNames(self)) self.ui.actionRASXSStationing.triggered.connect(lambda: r1d.ras1dXSStationing(self)) self.ui.actionRASXSBankStations.triggered.connect(lambda: r1d.ras1dXSBankStations(self)) self.ui.actionRASXSDownstreamReachLengths.triggered.connect(lambda: r1d.ras1dXSDownstreamLengths(self)) self.ui.actionRASXSElevations.triggered.connect(lambda: r1d.ras1dXSElevations(self)) self.ui.actionRASXSAll.triggered.connect(lambda: r1d.ras1dXSAll(self)) self.ui.actionRASHealLanduseGeometries.triggered.connect(lambda: r1d.ras1dHealLanduseGeoms(self)) self.ui.actionRASManningsNValues.triggered.connect(lambda: r1d.ras1dXSExtractMannings(self)) self.ui.actionRASLevees.triggered.connect(lambda: r1d.ras1dLevees(self)) self.ui.actionRASIneffectiveFlowAreas.triggered.connect(lambda: r1d.ras1dIneffective(self)) self.ui.actionRASBlockedObstructions.triggered.connect(lambda: r1d.ras1dObstructions(self)) self.ui.actionRASXSUpdateInsertMeasuredPoints.triggered.connect(lambda: r1d.ras1dXSUpdateInsertMeasuredPts(self)) self.ui.actionRASBRRiverReachNames.triggered.connect(lambda: r1d.ras1dBRRiverReachNames(self)) self.ui.actionRASBRStationing.triggered.connect(lambda: r1d.ras1dBRStationing(self)) self.ui.actionRASBRElevations.triggered.connect(lambda: r1d.ras1dBRElevations(self)) self.ui.actionRASBRAll.triggered.connect(lambda: r1d.ras1dRASBRAll(self)) self.ui.actionRASInlRiverReachNames.triggered.connect(lambda: r1d.ras1dISRiverReachNames(self)) self.ui.actionRASInlStationing.triggered.connect(lambda: r1d.ras1dISStationing(self)) self.ui.actionRASInlElevations.triggered.connect(lambda: r1d.ras1dISElevations(self)) self.ui.actionRASInlAll.triggered.connect(lambda: r1d.ras1dISAll(self)) self.ui.actionRASLatRiverReachNames.triggered.connect(lambda: r1d.ras1dLatRiverReachNames(self)) self.ui.actionRASLatStationing.triggered.connect(lambda: r1d.ras1dLatStationing(self)) self.ui.actionRASLatElevations.triggered.connect(lambda: r1d.ras1dLatElevations(self)) self.ui.actionRASLatAll.triggered.connect(lambda: r1d.ras1dLatAll(self)) self.ui.actionRASSAElevationVolumeData.triggered.connect(lambda: r1d.ras1dSAVolumeData(self)) self.ui.actionRASSATerrainPointExtraction.triggered.connect(lambda: r1d.ras1dSAElevations(self)) self.ui.actionRASSAAll.triggered.connect(lambda: r1d.ras1dSAAll(self)) self.ui.actionRASSacAssignNearestSA.triggered.connect(lambda: r1d.ras1dSACAssignNearestSA(self)) self.ui.actionRASSacElevations.triggered.connect(lambda: r1d.ras1dSACElevations(self)) self.ui.actionRASSacAll.triggered.connect(lambda: r1d.ras1dSACAll(self)) self.ui.actionRASCreateRASGISImport.triggered.connect(lambda: r1d.ras1dCreateRasGisImportFile(self)) # 2D self.ui.actionRASCreate2dAreaPoints.triggered.connect(lambda: r2d.ras2dCreate2dPoints(self)) self.ui.actionRASPreview2DMesh.triggered.connect(lambda: r2d.ras2dPreviewMesh(self)) self.ui.actionRASSave2DPointsToHECRASGeometry.triggered.connect(lambda: r2d.ras2dSaveMeshPtsToGeometry(self)) # HELP self.ui.actionHelpContents.triggered.connect(self.showRGisHelp) self.ui.actionWebsite.triggered.connect(self.showWebsite) self.ui.actionAbout.triggered.connect(self.about) # combos self.ui.crsWidget.crsChanged.connect(self.updateDefaultCrs) self.ui.connsCbo.activated.connect(self.connChanged) self.ui.schemasCbo.activated.connect(self.schemaChanged) # Welcome message self.ui.textEdit.append('<b>Welcome to RiverGIS!</b><br><br>Start building your model with 3 simple steps:<br>1. <b>Choose a connection</b> to PostGIS database<br>2. choose or create database <b>schema</b> (schema = model container or folder)<br>3. select a <b>projection</b> for the river database objects (projection = Coordinate Reference System, CRS).') self.ui.textEdit.append('<br>If you can\'t see any connection, please, create a new one from menu Layer > Add layer > Add PostGIS layers... <br>') self.ui.textEdit.append('----------------------------------------------------------------------------') # restore the window state s = QSettings() self.restoreGeometry(s.value("/rivergis/mainWindow/geometry", QByteArray(), type=QByteArray)) self.restoreState(s.value("/rivergis/mainWindow/windowState", QByteArray(), type=QByteArray)) # get PostGIS connections details and populate connections' combo self.connChanged() # restore settings self.readSettings() # set QGIS projection CRS as a default for RiverGIS self.ui.crsWidget.setCrs(self.iface.mapCanvas().mapSettings().destinationCrs()) self.updateDefaultCrs() # check if we should connect to previously used RDB if self.open_last_conn: try: self.connChanged(conn_name=self.opts['rdb']['last_conn'], schema_name=self.opts['rdb']['last_schema']) except: pass # disable some actions until a connection to river database is established if not self.rdb: self.disableActions()
def installPlugin(self, key, quiet=False): """ Install given plugin """ error = False infoString = ('', '') plugin = plugins.all()[key] previousStatus = plugin["status"] if not plugin: return if plugin["status"] == "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) dlg.exec_() if dlg.result(): error = True infoString = (self.tr("Plugin installation failed"), dlg.result()) elif not QDir(qgis.utils.home_plugin_path + "/" + key).exists(): error = True infoString = ( self.tr("Plugin has disappeared"), self. tr("The plugin seems to have been installed but I don't know where. Probably the plugin package contained a wrong named directory.\nPlease search the list of installed plugins. I'm nearly sure you'll find the plugin there, but I just can't determine which of them it is. It also means that I won't be able to determine if this plugin is installed and inform you about available updates. However the plugin may work. Please contact the plugin author and submit this issue." )) 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() # 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 QgsMessageBar.CRITICAL or QgsMessageBar.INFO msg = "<b>%s:</b>%s" % (infoString[0], infoString[1]) iface.pluginManagerInterface().pushMessage(msg, level)
def accept(self, *args, **kwargs): if not self.validate(): return False try: # disable form via a frame, this will still allow interaction with the message bar self.stackedWidget.setDisabled(True) # clean gui and Qgis messagebars self.cleanMessageBars(True) # self.iface.messageBar().clearWidgets() # Change cursor to Wait cursor QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) self.iface.mainWindow().statusBar().showMessage('Processing {}'.format(self.windowTitle())) 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) gp_layer_name = '' LOGGER.info('{st}\nProcessing {}'.format(self.windowTitle(), st='*' * 50)) # Add settings to log settingsStr = 'Parameters:---------------------------------------' if self.optFile.isChecked(): settingsStr += '\n {:30}\t{}'.format('File:', self.lneInCSVFile.text()) settingsStr += '\n {:30}\t{}, {}'.format('Geometry Fields:', self.cboXField.currentText(), self.cboYField.currentText()) settingsStr += '\n {:30}\t{} - {}'.format('CSV Coordinate System:', self.qgsCRScsv.crs().authid(), self.qgsCRScsv.crs().description()) else: if self.chkUseSelected.isChecked(): settingsStr += '\n {:30}\t{} with {} selected features'.format('Layer:', self.mcboTargetLayer.currentLayer().name(), self.mcboTargetLayer.currentLayer().selectedFeatureCount()) else: settingsStr += '\n {:30}\t{}'.format('Layer:', self.mcboTargetLayer.currentLayer().name()) crs_units = QgsUnitTypes.toString(self.mCRSoutput.crs().mapUnits()) settingsStr += '\n {:30}\t{} {}'.format('Thinning Distance:', self.dsbThinDist.value(),crs_units) settingsStr += '\n {:30}\t{} {}'.format("Aggregate Distance:", self.dsbAggregateDist.value(),crs_units) settingsStr += '\n {:30}\t{} {}'.format("Buffer Distance:", self.dsbBufferDist.value(),crs_units) settingsStr += '\n {:30}\t{} {}'.format("Shrink Distance:", self.dsbShrinkDist.value(),crs_units) settingsStr += '\n {:30}\t{}'.format('Output Polygon Shapefile:', self.lneSavePolyFile.text()) if self.lneSavePointsFile.text() == '': settingsStr += '\n {:30}\t{}'.format('Saved Points Shapefile:', self.lneSavePointsFile.text()) settingsStr += '\n {:30}\t{} - {}\n\n'.format('Output Projected Coordinate System:', self.mCRSoutput.crs().authid(), self.mCRSoutput.crs().description()) LOGGER.info(settingsStr) stepTime = time.time() if self.optFile.isChecked(): in_epsg = int(self.qgsCRScsv.crs().authid().replace('EPSG:','')) in_crs = self.qgsCRScsv.crs() else: in_epsg =self.mcboTargetLayer.currentLayer().crs().authid().replace('EPSG:','') in_crs = self.mcboTargetLayer.currentLayer().crs() out_epsg = int(self.mCRSoutput.crs().authid().replace('EPSG:','')) filePoly = None gdfPoints = None filePoints = None if self.optFile.isChecked(): if self.DEBUG: filePoints = os.path.join(TEMPDIR, os.path.splitext(os.path.basename(self.lneSavePolyFile.text()))[0] + '_table2pts.shp') if os.path.splitext(self.lneInCSVFile.text())[-1] == '.csv': gdfPoints, gdfPtsCrs = convert.convert_csv_to_points(self.lneInCSVFile.text() , out_shapefilename=filePoints, coord_columns=[self.cboXField.currentText(), self.cboYField.currentText()], coord_columns_epsg=in_epsg) elif os.path.splitext(self.lneInCSVFile.text())[-1] in ['.xls', '.xlsx', '.ods']: xls_file = pd.ExcelFile(self.lneInCSVFile.text()) pdfxls = xls_file.parse(self.sheet(), skiprows=self.linesToIgnore() - 1) del xls_file gdfPoints, gdfPtsCrs = convert.add_point_geometry_to_dataframe(pdfxls, coord_columns=[ self.cboXField.currentText(), self.cboYField.currentText()], coord_columns_epsg=in_epsg) del pdfxls LOGGER.info('{:<30} {d:<15} {}'.format('Add Geometry to Table','', d=str(timedelta(seconds=time.time() - stepTime)))) stepTime = time.time() if filePoints is not None: describe.save_geopandas_tofile(gdfPoints, filePoints) #, file_encoding=self.file_encoding) if self.DISP_TEMP_LAYERS and filePoints is not None: addVectorFileToQGIS(filePoints, layer_name=os.path.splitext(os.path.basename(filePoints))[0], group_layer_name='DEBUG', atTop=True) else: layerPts = self.mcboTargetLayer.currentLayer() if layerPts.providerType() == 'delimitedtext' or \ os.path.splitext(get_layer_source(layerPts))[-1] == '.vrt' or \ self.chkUseSelected.isChecked() or self.optFile.isChecked(): filePoints = os.path.join(TEMPDIR, "{}_points.shp".format(layerPts.name())) if self.chkUseSelected.isChecked(): filePoints = os.path.join(TEMPDIR, "{}_selected_points.shp".format(layerPts.name())) if os.path.exists(filePoints): removeFileFromQGIS(filePoints) ptsLayer = copyLayerToMemory(layerPts, layerPts.name() + "_memory", bAddUFI=True, bOnlySelectedFeat=self.chkUseSelected.isChecked()) _writer = QgsVectorFileWriter.writeAsVectorFormat(ptsLayer, filePoints, "utf-8", self.mCRSoutput.crs(), driverName="ESRI Shapefile") LOGGER.info('{:<30} {d:<15} {}'.format('Save layer/selection to file',filePoints, d=str(timedelta(seconds=time.time() - stepTime) ))) stepTime = time.time() del ptsLayer if self.DISP_TEMP_LAYERS: addVectorFileToQGIS(filePoints, layer_name=os.path.splitext(os.path.basename(filePoints))[0], group_layer_name='DEBUG', atTop=True) else: filePoints = get_layer_source(layerPts) if gdfPoints is None: ptsDesc = describe.VectorDescribe(filePoints) gdfPtsCrs = ptsDesc.crs gdfPoints = ptsDesc.open_geo_dataframe() if in_crs.authid() != self.mCRSoutput.crs().authid(): gdfPoints = gdfPoints.to_crs(epsg=out_epsg) gdfPtsCrs = pyprecag_crs.crs() gdfPtsCrs.getFromEPSG(out_epsg) LOGGER.info('{:<30} {d:<15} {} to {}'.format('Reproject points', in_crs.authid(), self.mCRSoutput.crs().authid(), d=str(timedelta(seconds=time.time() - stepTime)))) if self.DEBUG: filePoints = os.path.join(TEMPDIR, os.path.basename(self.lneSavePolyFile.text().replace('.csv', '_ptsprj.shp'))) removeFileFromQGIS(filePoints) describe.save_geopandas_tofile(gdfPoints, filePoints) if self.DISP_TEMP_LAYERS: if self.DEBUG: addVectorFileToQGIS(filePoints, layer_name=os.path.splitext(os.path.basename(filePoints))[0], group_layer_name='DEBUG', atTop=True) else: addVectorFileToQGIS(filePoints, layer_name=os.path.splitext(os.path.basename(filePoints))[0], atTop=True) stepTime = time.time() result = processing.create_polygon_from_point_trail(gdfPoints, gdfPtsCrs, out_filename=self.lneSavePolyFile.text(), thin_dist_m=self.dsbThinDist.value(), aggregate_dist_m=self.dsbAggregateDist.value(), buffer_dist_m=self.dsbBufferDist.value(), shrink_dist_m=self.dsbShrinkDist.value()) addVectorFileToQGIS(self.lneSavePolyFile.text(), atTop=True) self.cleanMessageBars(True) self.stackedWidget.setDisabled(False) QApplication.restoreOverrideCursor() self.iface.messageBar().popWidget() self.iface.mainWindow().statusBar().clearMessage() if result is not None: self.fraMain.setDisabled(False) self.send_to_messagebar(result, level=Qgis.Warning, duration=0, addToLog=False) return False # leave dialog open return super(PointTrailToPolygonDialog, self).accept(*args, **kwargs) except Exception as err: QApplication.restoreOverrideCursor() self.iface.mainWindow().statusBar().clearMessage() self.cleanMessageBars(True) self.stackedWidget.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
def ras2dCreate2dPoints(rgis): """ Create 2D computational points for each 2D flow area. Points are regularly spaced (based on CellSize attribute of the FlowArea2D table) except for breaklines, where they are aligned to form a cell face exactly at a breakline. Points spacing along and across a breakline is read from CellSizeAlong and CellSizeAcross attributes of BreakLines2D table, respectively. A number of cells rows to align with a beakline can be given. Create breakpoints at locations where a cell face is needed (on a breakline). """ rgis.addInfo('<br><b>Creating computational points for 2D flow areas<b>') # and create breaklines with a linear measure qry = 'SELECT * FROM "{0}"."FlowAreas2d"'.format(rgis.rdb.SCHEMA) chk2dAreas = rgis.rdb.run_query(qry, fetch=True) if not chk2dAreas: rgis.addInfo( 'No 2d flow area in the database.<br> Import or create it before generating 2d computational points.<br> Cancelling...' ) return QApplication.setOverrideCursor(Qt.WaitCursor) rgis.addInfo('Creating regular mesh points...') # create regular mesh points # and delete points located too close to the 2D area boundary rgis.rdb.process_hecobject(heco.MeshPoints2d, 'pg_create_table') rgis.rdb.process_hecobject(heco.MeshPoints2d, 'pg_create_mesh') # find which breakline line belongs to which 2d flow area # and create breaklines with a linear measure rgis.rdb.process_hecobject(heco.BreakLines2d, 'pg_flow_to_breakline') rgis.rdb.process_hecobject(heco.BreakLines2d, 'pg_breaklines_m') rgis.rdb.process_hecobject(heco.BreakLines2d, 'pg_drop_by_buffer') rgis.addInfo('Creating mesh points along structures...') # check if breaklines and breakpoints exist in the database bls_exist = False bps_exist = False for t in rgis.rdb.list_tables(): if t == 'BreakLines2d': bls_exist = True if t == 'BreakPoints2d': bps_exist = True if bls_exist: # find measures of breakpoints along breaklines # there was a change in the alg name between PostGIS 2.0 and 2.1 # ST_Line_Locate_Point -> ST_LineLocatePoint qry = 'SELECT PostGIS_Full_Version() AS ver;' postgisVersion = rgis.rdb.run_query(qry, True)[0]['ver'].split('\"')[1][:5] pgMajV = int(postgisVersion[:1]) pgMinV = int(postgisVersion[2:3]) if pgMajV < 2: locate = 'ST_Line_Locate_Point' elif pgMajV >= 2 and pgMinV == 0: locate = 'ST_Line_Locate_Point' else: locate = 'ST_LineLocatePoint' # find breakline that a breakpoint is located on ( tolerance = 10 [map units] ) if bps_exist: breakPtsLocTol = 10 rgis.rdb.process_hecobject(heco.BreakPoints2d, 'pg_bpoints_along_blines', tolerance=breakPtsLocTol, func_name=locate) # find breaklines with measures qry = ''' SELECT "BLmID", "AreaID", "CellSizeAlong" AS csx, "CellSizeAcross" AS csy, ST_Length(geom) AS len, "RowsAligned" AS rows FROM "{0}"."BreakLines2d_m"; ''' qry = qry.format(rgis.rdb.SCHEMA) bls = rgis.rdb.run_query(qry, True) for line in bls: if not line['csx'] or not line['csy'] or not line['rows']: rgis.addInfo( '<br><b> Empty BreakLines2d attribute! Cancelling...<b><br>' ) QApplication.restoreOverrideCursor() return dist_x = float(line['csx']) width = float(line['csy']) id = line['BLmID'] leng = float(line['len']) rows = int(line['rows']) imax = int(leng / (dist_x)) # check if breakpoints exist on the breakline qry = ''' SELECT bp."BPID" FROM "{0}"."BreakLines2d_m" AS bl, "{0}"."BreakPoints2d" AS bp WHERE bl."BLmID" = {1} AND bp."BLmID" = bl."BLmID"; ''' try: qry = qry.format(rgis.rdb.SCHEMA, id) bp_on_bl = rgis.rdb.run_query(qry, True) if rgis.DEBUG: rgis.addInfo('Breakline BLmID={0}, {1}'.format( id, bp_on_bl)) except ProgrammingError: bp_on_bl = None if not bp_on_bl: # no BreakPoints2d: create aligned mesh at regular interval = CellSizeAlong if rgis.DEBUG: rgis.addInfo( 'Creating regular points for breakline BLmID={0} (no breakpoints)' .format(id)) for i in range(0, imax + 1): dist = i * dist_x for j in range(0, rows): rgis.rdb.process_hecobject(heco.MeshPoints2d, 'pg_aligned_mesh', cellsize=dist_x, measure=dist, offset=j * width + width / 2, blid=id) # create cell faces at breakline's breakpoints else: qry = ''' SELECT DISTINCT p."Fraction" FROM "{0}"."BreakPoints2d" AS p WHERE p."BLmID" = {1}; ''' qry = qry.format(rgis.rdb.SCHEMA, id) ms = rgis.rdb.run_query(qry, True) if rgis.DEBUG: rgis.addInfo( 'Creating breakpoints for structure id={0} (with breakpoints)' .format(id)) sm_param = 4 db_min = 10.**9 # breakpoints m list (linear locations on current structure) bm = [] # linear measures of mesh points to be created mpts = [] for m in ms: bm.append(float(m['Fraction'])) if rgis.DEBUG: rgis.addInfo('BreakPoint2d fraction: {0}'.format( float(m['Fraction']))) # sort the list bm.sort() for i, m in enumerate(bm): # calculate minimal distance between breakpoints if i > 0: db_min = min(bm[i] - bm[i - 1], db_min) if rgis.DEBUG: rgis.addInfo( 'Min dist between breakpoints db_min={0}'.format( db_min)) # create 2 mesh points on both sides of a breakpoint at a distance db_min / sm_param dist_min = min(db_min / sm_param, 0.5 * dist_x / leng) cs_min = dist_min * leng if rgis.DEBUG: rgis.addInfo('dist_min={0}, cs_min={1}'.format( dist_min, cs_min)) for m in bm: mpts.append(max(0.0001, m - dist_min)) mpts.append(min(m + dist_min, 0.9999)) # find gaps between points along a breakline longer than 3 * dist_min gaps = [] for i, m in enumerate(mpts): if rgis.DEBUG: rgis.addInfo('m={0}'.format(m)) if i > 0: dist = m - mpts[i - 1] if dist > 3 * dist_min: gaps.append([m, dist]) # create mesh points filling the gaps for g in gaps: m, dist = g # how many points to insert? k = int(floor(dist / (2 * dist_min))) # distance between new points cs = dist / k for j in range(1, k): mpts.append(m - j * cs) if rgis.DEBUG: rgis.addInfo('gap: dist={0}, m={1}'.format( cs, m - j * cs)) # insert aligned mesh points into table for m in sorted(mpts): for j in range(0, rows): rgis.rdb.process_hecobject(heco.MeshPoints2d, 'pg_aligned_mesh', cellsize=cs_min, measure=m * leng, offset=j * width + width / 2, blid=id) rgis.addInfo( 'Deleting mesh points located too close to each other or outside the 2D area...' ) rgis.rdb.process_hecobject(heco.MeshPoints2d, 'pg_clean_points') rgis.addInfo('Done') QApplication.restoreOverrideCursor()
def accept(self): super(AlgorithmDialog, self)._saveGeometry() context = dataobjects.createContext() checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: feedback = self.createFeedback() parameters = self.getParamValues() if checkCRS and not self.alg.validateInputCrs(parameters, context): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Layers do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return checkExtentCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS) #TODO if False and checkExtentCRS and self.checkExtentCRS(): reply = QMessageBox.question( self, self.tr("Extent CRS"), self. tr('Extent parameters must use the same CRS as the input layers.\n' 'Your input layers do not have the same extent as the project, ' 'so the extent might be in a wrong CRS if you have selected it from the canvas.\n' 'Do you want to continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return ok, msg = self.alg.checkParameterValues(parameters, context) if msg: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.btnRun.setEnabled(False) self.btnClose.setEnabled(False) buttons = self.mainWidget.iterateButtons self.iterateParam = None for i in range(len(list(buttons.values()))): button = list(buttons.values())[i] if button.isChecked(): self.iterateParam = list(buttons.keys())[i] break self.progressBar.setMaximum(0) self.lblProgress.setText(self.tr('Processing algorithm...')) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setInfo( self.tr('<b>Algorithm \'{0}\' starting...</b>').format( self.alg.displayName()), escape_html=False) feedback.pushInfo(self.tr('Input parameters:')) feedback.pushCommandInfo(pformat(parameters)) feedback.pushInfo('') start_time = time.time() if self.iterateParam: self.buttonCancel.setEnabled( self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel) if executeIterating(self.alg, parameters, self.iterateParam, context, feedback): feedback.pushInfo( self.tr( 'Execution completed in {0:0.2f} seconds'.format( time.time() - start_time))) self.buttonCancel.setEnabled(False) self.finish(parameters, context, feedback) else: self.buttonCancel.setEnabled(False) QApplication.restoreOverrideCursor() self.resetGUI() else: command = self.alg.asPythonCommand(parameters, context) if command: ProcessingLog.addToLog(command) self.buttonCancel.setEnabled( self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel) result = executeAlgorithm(self.alg, parameters, context, feedback) feedback.pushInfo( self.tr('Execution completed in {0:0.2f} seconds'.format( time.time() - start_time))) feedback.pushInfo(self.tr('Results:')) feedback.pushCommandInfo(pformat(result)) feedback.pushInfo('') self.buttonCancel.setEnabled(False) self.finish(result, context, feedback) 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)
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_Seltene_Objekte", "project_id not set", None)) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_PNF_Seltene_Objekte", "Lagekontrolle - Seltene Objekte", None) group += " (" + str(project_id) + ")" layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Orthofoto CIR", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto.cir", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Orthofoto RGB", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto_rgb", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "DTM Hangneigung", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.hangneigung", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Gemeindegrenze", None), "featuretype": "gemeindegrenzen_gemeindegrenze", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "gemeindegrenze/gemgre_strichliert.qml" } gemgrelayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "BB.BoFlaeche", None), "featuretype": "bodenbedeckung_boflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_seltene_objekte_ortho.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Einzelobjekt", None), "featuretype": "einzelobjekte_einzelobjekt", "geom": "", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } eoeolayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Flaechenelement", None), "featuretype": "einzelobjekte_flaechenelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_fl_seltene_objekte_ortho.qml" } eoflayer = self.layer_loader.load(layer, True, False) if eoflayer <> False: self.iface.legendInterface().setLayerVisible(eoflayer, True) if eoeolayer <> False and eoflayer <> False: joinLayerId = eoeolayer.id() for feature in eoeolayer.getFeatures(): joinIdx = feature.fieldNameIndex("ogc_fid") for t_feature in eoflayer.getFeatures(): targetIdx = t_feature.fieldNameIndex("flaechenelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "flaechenelement_von" joinInfo.memoryCache = True eoflayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Linienelement", None), "featuretype": "einzelobjekte_linienelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_li_seltene_objekte_ortho.qml" } eolilayer = self.layer_loader.load(layer, True, False) if eolilayer <> False: self.iface.legendInterface().setLayerVisible(eolilayer, True) if eoeolayer <> False and eolilayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eolilayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("linienelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "linienelement_von" joinInfo.memoryCache = True eolilayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "EO.Punktelement", None), "featuretype": "einzelobjekte_punktelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_pk_seltene_objekte_ortho.qml" } eopklayer = self.layer_loader.load(layer, True, False) if eopklayer <> False: self.iface.legendInterface().setLayerVisible(eopklayer, True) if eoeolayer <> False and eopklayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eopklayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("punktelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "punktelement_von" joinInfo.memoryCache = True eopklayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Abbaustellen (AfU)", None), "params": { "dbhost": "localhost", "dbport": 5432, "dbname": "grundlagen", "dbschema": "sogis" }, "featuretype": "abbaustellen_afu", "geom": "wkb_geometry", "key": "gid", "sql": "", "readonly": True, "group": group, "style": "sogis/abbaustellen_afu.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Flachmoor (AfU)", None), "params": { "dbhost": "localhost", "dbport": 5432, "dbname": "grundlagen", "dbschema": "sogis" }, "featuretype": "flachmoor_afu", "geom": "wkb_geometry", "key": "gid", "sql": "", "readonly": True, "group": group, "style": "sogis/flachmoor_afu.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Freileitungen (ARP)", None), "params": { "dbhost": "localhost", "dbport": 5432, "dbname": "grundlagen", "dbschema": "sogis" }, "featuretype": "freileitungen_arp", "geom": "wkb_geometry", "key": "gid", "sql": "", "readonly": True, "group": group, "style": "sogis/freileitungen_arp.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Seltene_Objekte", "LI.Liegenschaft", None), "featuretype": "liegenschaften_liegenschaft", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "li/liegenschaft_ortho.qml" } vlayer = self.layer_loader.load(layer, False, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Flachmoor (BAFU)", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bafu.bundesinventare-flachmoore", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Hochmoor (BAFU)", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bafu.bundesinventare-hochmoore", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Mobilfunkantennen GSM", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bakom.mobil-antennenstandorte-gsm", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Mobilfunkantennen UMTS", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bakom.mobil-antennenstandorte-umts", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Seltene_Objekte", "Radio- und Fernsehsender", None), "url": "http://wms.geo.admin.ch/", "layers": "ch.bakom.radio-fernsehsender", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, False) if gemgrelayer: rect = gemgrelayer.extent() self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() 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()
def copy_data_sources(link=False): messages = [] # error messages # overwrite enabled by default, don't ask user # overwrite = [] # files to overwrite project_dir = os.path.dirname(self.plugin.project.fileName()) # collect files to be copied publish_files = {} for ds in list(self._datasources.values()): for dsfile in ds: if os.path.exists(dsfile) and os.path.isfile(dsfile): publish_path = os.path.dirname( self._publish_dir + dsfile[len(project_dir):]) if publish_path not in publish_files: publish_files[publish_path] = [] if os.path.splitext(dsfile)[1] == '.shp': # Esri Shapefile (copy all files) shpname = os.path.splitext(dsfile)[0] for shpext in ('shp', 'shx', 'dbf', 'sbn', 'sbx', 'fbn', 'fbx', 'ain', 'aih', 'atx', 'ixs', 'mxs', 'prj', 'xml', 'cpg'): shpfile = '{0}.{1}'.format(shpname, shpext) if os.path.exists(shpfile): dstfile = os.path.join( publish_path, shpfile) # if os.path.exists(dstfile): # overwrite.append(dstfile) publish_files[publish_path].append(shpfile) else: # other formats (we expect one file per datasource) dstfile = os.path.join(publish_path, os.path.basename(dsfile)) # if os.path.exists(dstfile): # overwrite.append(dstfile) publish_files[publish_path].append(dsfile) elif 'url' in dsfile.lower(): # skip OWS layers (ugly: assuming URL in data source) continue else: messages.append( "Unsupported data source: {0} is not a file". format(dsfile)) # if overwrite: # response = QMessageBox.question(self.dialog, "Overwrite", # "Files:\n{0}\nalready exists. Do you want to overwrite them?".format( # os.linesep.join(overwrite if len(overwrite) < 6 else overwrite[:5] + ['...']) # ), # QMessageBox.Yes, QMessageBox.No) # if response == QMessageBox.Yes: # overwrite = None # set busy cursor QApplication.setOverrideCursor(Qt.WaitCursor) # copy/link collected project files fn = os.symlink if link else shutil.copy for publish_dir, project_files in list(publish_files.items()): try: # create dirs if not exists if not os.path.exists(os.path.dirname(publish_path)): os.makedirs(os.path.dirname(publish_path)) for dsfile in project_files: # if overwrite: # # skip existing files # dstfile = os.path.join(publish_path, os.path.basename(dsfile)) # if dstfile in overwrite: # continue dstfile = os.path.join(publish_path, os.path.basename(dsfile)) # copy target only if doesn't exist or out-dated if not os.path.exists(dstfile) or \ os.stat(dsfile).st_mtime > os.stat(dstfile).st_mtime: # check if target directories exist dirname = os.path.dirname(dstfile) if not os.path.exists(dirname): os.makedirs(dirname) fn(dsfile, dstfile) except (shutil.Error, IOError) as e: messages.append( "Failed to copy data source: {0}".format(e)) # restore original cursor QApplication.restoreOverrideCursor() if messages: raise Exception("Copying project files failed:\n{0}".format( os.linesep.join(messages)))
def accept(self): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: self.setParamValues() if checkCRS and not self.alg.checkInputCRS(): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Layers do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return checkExtentCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS) if checkExtentCRS and self.checkExtentCRS(): reply = QMessageBox.question( self, self.tr("Extent CRS"), self. tr('Extent parameters must use the same CRS as the input layers.\n' 'Your input layers do not have the same extent as the project, ' 'so the extent might be in a wrong CRS if you have selected it from the canvas.\n' 'Do you want to continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return msg = self.alg._checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.btnRun.setEnabled(False) self.btnClose.setEnabled(False) buttons = self.mainWidget.iterateButtons self.iterateParam = None for i in range(len(list(buttons.values()))): button = list(buttons.values())[i] if button.isChecked(): self.iterateParam = list(buttons.keys())[i] break self.progressBar.setMaximum(0) self.lblProgress.setText(self.tr('Processing algorithm...')) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setInfo( self.tr('<b>Algorithm %s starting...</b>') % self.alg.name) if self.iterateParam: if runalgIterating(self.alg, self.iterateParam, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() else: command = self.alg.getAsCommand() if command: ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, command) if runalg(self.alg, self): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox.accepted.connect( lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.bar.clearWidgets() self.bar.pushMessage("", "Wrong or missing parameter value: %s" % e.parameter.description, level=QgsMessageBar.WARNING, duration=5)
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)) try: _bytes = float_to_bytes(round(targetWidth, 4), _domain22, _range22) except Exception: _bytes = float_to_bytes(round(0.0, 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
def acceptDialog(self): QApplication.setOverrideCursor(Qt.WaitCursor) if not self.ui.xsTol.text() == '': tol = self.ui.xsTol.text() else: self.rgis.addInfo("XS tolerance must be specifeid. Cancelling.") QApplication.restoreOverrideCursor() return # create bathymetry points table obj = self.rgis.rdb.process_hecobject(heco.Bathymetry, 'pg_create_table') try: self.rgis.addInfo(' Table {0} created.'.format(obj.name)) except: self.rgis.addInfo(' Could not create bathymetry points table.') # get the bathymetry points data data = { 'cbo': self.ui.cboMeasuredLayer, 'className': 'Bathymetry', 'attrs': { 'Elevation': { 'cbo': self.ui.cboMeasuredElevation, 'checkName': ['elevation', 'elev'] } }, 'geomType': 0 # points } if not data['cbo'].currentText() == '': curInd = data['cbo'].currentIndex() lid = data['cbo'].itemData(curInd) layer = QgsProject.instance().mapLayer(lid) attrMap = {} for attr, attrData in data['attrs'].items(): curText = attrData['cbo'].currentText() if curText: attrMap[attr] = curText self.rgis.rdb.insert_layer( layer, self.rgis.rdb.register[data['className']], attr_map=attrMap, selected=self.ui.chkOnlySelected.isChecked()) # Update area defined by bank lines if self.ui.groupBanksExt.isChecked(): # check if bank stations are calculated for each cross-section qry = ''' SELECT DISTINCT "RiverCode", "ReachCode" FROM "{0}"."XSCutLines" as xs WHERE xs."LeftBank" IS NULL OR xs."RightBank" IS NULL; '''.format(self.rgis.rdb.SCHEMA) miss = self.rgis.rdb.run_query(qry, fetch=True) if miss: for id in miss: self.rgis.addInfo( 'There is at least one NULL bank station on river {}, reach {}' .format(id[0], id[1])) self.rgis.addInfo( ' Cannot continue with NULL bank station. Please, set the bank stations and try again.<br> Cancelling...' ) QApplication.restoreOverrideCursor() return upArea = self.ui.cboInterpArea.currentText() self.rgis.rdb.process_hecobject(heco.XSCutLines, 'pg_update_banks', area=upArea, xs_tol=tol) # Update area defined by bathymetry extents polygons else: # create bathymetry extents table obj = self.rgis.rdb.process_hecobject(heco.BathymetryExtents, 'pg_create_table') try: self.rgis.addInfo(' Table {0} created.'.format(obj.name)) except: self.rgis.addInfo( ' Could not create bathymetry extents table.') # insert bathymetry extents into the database data = { 'cbo': self.ui.cboBathyExtLayer, 'className': 'BathymetryExtents', 'attrs': {}, 'geomType': 2 # polygons } if not data['cbo'].currentText() == '': curInd = data['cbo'].currentIndex() lid = data['cbo'].itemData(curInd) layer = QgsProject.instance().mapLayer(lid) attrMap = {} for attr, attrData in data['attrs'].items(): curText = attrData['cbo'].currentText() if curText: attrMap[attr] = curText self.rgis.rdb.insert_layer( layer, self.rgis.rdb.register[data['className']], attr_map=attrMap) self.rgis.rdb.process_hecobject(heco.XSCutLines, 'pg_update_polygons', xs_tol=tol) self.rgis.addInfo(" Done.") self.rgis.iface.mapCanvas().refresh() QApplication.restoreOverrideCursor() QDialog.accept(self)
def error(self, msg): QApplication.restoreOverrideCursor() self.setInfo(msg, True) self.resetGUI() self.tabWidget.setCurrentIndex(1)
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
def run_query(self): """ Process for running the query """ # Block the button and save the initial text self.output_directory.setDisabled(True) self.pushButton_generateQuery.setDisabled(True) QApplication.setOverrideCursor(Qt.WaitCursor) self.start_process() QApplication.processEvents() # Get all values query = self.textEdit_query.toPlainText() output_directory = self.output_directory.filePath() prefix_file = self.lineEdit_filePrefix.text() nominatim = self.nominatim_value() # Set bbox bbox = None if self.cb_query_type.isEnabled(): query_type = self.cb_query_type.currentData() if query_type in ['layer', 'canvas']: nominatim = None bbox = self.get_bounding_box() # Check nominatim if nominatim == '': nominatim = None # Which geometry at the end ? output_geometry_types = self.get_output_geometry_types() white_list_values = self.get_white_list_values() try: # Test values if not output_geometry_types: raise OutPutGeomTypesException if output_directory and not isdir(output_directory): raise DirectoryOutPutException if not nominatim and \ re.search(r'\{\{nominatim\}\}', query) or \ re.search(r'\{\{nominatimArea:\}\}', query) or \ re.search(r'\{\{geocodeArea:\}\}', query): raise MissingParameterException(suffix="nominatim field") num_layers = process_query( dialog=self, query=query, output_dir=output_directory, prefix_file=prefix_file, output_geometry_types=output_geometry_types, white_list_values=white_list_values, nominatim=nominatim, bbox=bbox) if num_layers: display_message_bar(tr('Successful query'), level=Qgis.Success, duration=5) self.label_progress.setText(tr('Successful query')) else: display_message_bar(tr('Successful query, but no result.'), level=Qgis.Warning, duration=7) except QuickOsmException as e: self.display_geo_algorithm_exception(e) pass except Exception as e: # pylint: disable=broad-except self.display_exception(e) pass finally: # Resetting the button self.output_directory.setDisabled(False) self.pushButton_generateQuery.setDisabled(False) QApplication.restoreOverrideCursor() self.end_process() QApplication.processEvents()
def __exit__(self, exc_type, exc_val, exc_tb): QApplication.restoreOverrideCursor()
def set_cursor_restore(self): """ Restore to previous cursors """ QApplication.restoreOverrideCursor()
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", "Lagekontrolle - Bebautes Gebiet", None) group += " (" + str(project_id) + ")" layer = { "type": "wms", "title": _translate("VeriSO_PNF_Baugebiet", "Orthofoto CIR", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto.cir", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Baugebiet", "Orthofoto RGB", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto_rgb", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Baugebiet", "DTM Hangneigung", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.hangneigung", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Baugebiet", "Gewässer", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.afu.fliessgewaesser.netz", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "Gemeindegrenze", None), "featuretype": "gemeindegrenzen_gemeindegrenze", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "gemeindegrenze/gemgre_strichliert.qml" } gemgrelayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "BB.BoFlaeche", None), "featuretype": "bodenbedeckung_boflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_baugebiet_ortho.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "EO.Einzelobjekt", None), "featuretype": "einzelobjekte_einzelobjekt", "geom": "", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, #"style": "bodenbedeckung/projboflaeche_color.qml" } eoeolayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "EO.Flaechenelement", None), "featuretype": "einzelobjekte_flaechenelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_fl_baugebiet_ortho.qml" } eoflayer = self.layer_loader.load(layer, True, False) if eoflayer <> False: self.iface.legendInterface().setLayerVisible(eoflayer, True) if eoeolayer <> False and eoflayer <> False: joinLayerId = eoeolayer.id() for feature in eoeolayer.getFeatures(): joinIdx = feature.fieldNameIndex("ogc_fid") for t_feature in eoflayer.getFeatures(): targetIdx = t_feature.fieldNameIndex("flaechenelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "flaechenelement_von" joinInfo.memoryCache = True eoflayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "EO.Linienelement", None), "featuretype": "einzelobjekte_linienelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_li_baugebiet_ortho.qml" } eolilayer = self.layer_loader.load(layer, True, False) if eolilayer <> False: self.iface.legendInterface().setLayerVisible(eolilayer, True) if eoeolayer <> False and eolilayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("tid") targetProvider = eolilayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("linienelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "linienelement_von" joinInfo.memoryCache = True eolilayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "EO.Punktelement", None), "featuretype": "einzelobjekte_punktelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_pk_andere.qml" } eopklayer = self.layer_loader.load(layer, True, False) if eopklayer <> False: self.iface.legendInterface().setLayerVisible(eopklayer, True) if eoeolayer <> False and eopklayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eopklayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("punktelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "punktelement_von" joinInfo.memoryCache = True eopklayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "LI.Liegenschaft", None), "featuretype": "liegenschaften_liegenschaft", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "li/liegenschaft_ortho.qml" } vlayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "BB.Objektname", None), "featuretype": "v_bb_objektnamen", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_objektnamen.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "EO.Objektname", None), "featuretype": "v_eo_objektnamen", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_objektnamen.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "Reservoir (AfU)", None), "params": { "dbhost": "localhost", "dbport": 5432, "dbname": "grundlagen", "dbschema": "sogis" }, "featuretype": "reservoir_afu", "geom": "wkb_geometry", "key": "gid", "sql": "", "readonly": True, "group": group, "style": "sogis/reservoir_afu.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "Kontrollraster (Planeinteilung)", None), "featuretype": "t_kontrollraster_plan_bebaut", "geom": "the_geom", "key": "ogc_fid", "sql": "", "readonly": False, "group": group, "style": "kontrollraster/kontrollraster.qml" } vlayer = self.layer_loader.load(layer, True, False) if vlayer <> False: self.iface.legendInterface().setLayerVisible(vlayer, False) provider = vlayer.dataProvider() provider.attributeIndexes() ogc_fid_idx = provider.fieldNameIndex("ogc_fid") vlayer.setEditorWidgetV2(0, "Hidden") plannummer_idx = provider.fieldNameIndex("plannummer") vlayer.setEditorWidgetV2(2, "Hidden") kontrolliert_idx = provider.fieldNameIndex("kontrolliert") vlayer.setEditorWidgetV2(1, "CheckBox") vlayer.setEditorWidgetV2Config( 1, { 'fieldEditable': "1", 'UncheckedState': 'f', 'CheckedState': 't' }) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Baugebiet", "Kontrollraster", None), "featuretype": "t_kontrollraster_strasse_500", "geom": "the_geom", "key": "ogc_fid", "sql": "", "readonly": False, "group": group, "style": "kontrollraster/kontrollraster.qml" } vlayer = self.layer_loader.load(layer, True, False) if vlayer <> False: self.iface.legendInterface().setLayerVisible(vlayer, True) provider = vlayer.dataProvider() provider.attributeIndexes() ogc_fid_idx = provider.fieldNameIndex("ogc_fid") vlayer.setEditorWidgetV2(0, "Hidden") kontrolliert_idx = provider.fieldNameIndex("kontrolliert") vlayer.setEditorWidgetV2(1, "CheckBox") vlayer.setEditorWidgetV2Config( 1, { 'fieldEditable': "1", 'UncheckedState': 'f', 'CheckedState': 't' }) if gemgrelayer: rect = gemgrelayer.extent() self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() 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()
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_Gewaesser", "project_id not set", None) ) return QApplication.setOverrideCursor(Qt.WaitCursor) try: group = _translate("VeriSO_PNF_Gewaesser", "Lagekontrolle - Gewaesser", None) group += " (" + str(project_id) + ")" layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "Orthofoto CIR", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.orthofoto.cir", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "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, True, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "DTM Hangneigung", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.hangneigung", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "DTM", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.agi.lidar_2014.dtm", "format": "image/jpeg", "crs": "EPSG:" + str(epsg), "group": group } vlayer = self.layer_loader.load(layer, False, True) layer = { "type": "wms", "title": _translate("VeriSO_PNF_Gewaesser", "Gewässer", None), "url": "https://geo.so.ch/wms?", "layers": "ch.so.afu.fliessgewaesser.netz", "format": "image/png", "crs": "EPSG:" + str(epsg), "group": group, "style": "gewaesser/gewisso.qml" } vlayer = self.layer_loader.load(layer, True, True) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "Gemeindegrenze", None), "featuretype": "gemeindegrenzen_gemeindegrenze", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "gemeindegrenze/gemgre_strichliert.qml" } gemgrelayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "BB.BoFlaeche", None), "featuretype": "bodenbedeckung_boflaeche", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_gewaesser_ortho.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Einzelobjekt", None), "featuretype": "einzelobjekte_einzelobjekt", "geom": "", "key": "ogc_fid", "sql": "", "readonly": True, "group": group } eoeolayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Flaechenelement", None), "featuretype": "einzelobjekte_flaechenelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_fl_gewaesser_ortho.qml" } eoflayer = self.layer_loader.load(layer, True, False) if eoflayer <> False: self.iface.legendInterface().setLayerVisible(eoflayer, True) if eoeolayer <> False and eoflayer <> False: joinLayerId = eoeolayer.id() for feature in eoeolayer.getFeatures(): joinIdx=feature.fieldNameIndex("ogc_fid") for t_feature in eoflayer.getFeatures(): targetIdx=t_feature.fieldNameIndex("flaechenelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "flaechenelement_von" joinInfo.memoryCache = True eoflayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Linienelement", None), "featuretype": "einzelobjekte_linienelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_li_gewaesser_ortho.qml" } eolilayer = self.layer_loader.load(layer, True, False) if eolilayer <> False: self.iface.legendInterface().setLayerVisible(eolilayer, True) if eoeolayer <> False and eolilayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eolilayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("linienelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "linienelement_von" joinInfo.memoryCache = True eolilayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Punktelement", None), "featuretype": "einzelobjekte_punktelement", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_pk_andere.qml" } eopklayer = self.layer_loader.load(layer, True, False) if eopklayer <> False: self.iface.legendInterface().setLayerVisible(eopklayer, True) if eoeolayer <> False and eopklayer <> False: joinLayerId = eoeolayer.id() joinProvider = eoeolayer.dataProvider() joinProvider.attributeIndexes() joinIdx = joinProvider.fieldNameIndex("ogc_fid") targetProvider = eopklayer.dataProvider() targetProvider.attributeIndexes() targetIdx = targetProvider.fieldNameIndex("punktelement_von") joinInfo = QgsVectorJoinInfo() joinInfo.joinFieldIndex = joinIdx joinInfo.joinFieldName = "ogc_fid" joinInfo.joinLayerId = joinLayerId joinInfo.targetFieldIndex = targetIdx joinInfo.targetFieldName = "punktelement_von" joinInfo.memoryCache = True eopklayer.addJoin(joinInfo) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "BB.Symbole", None), "featuretype": "v_bodenbedeckung_boflaechesymbol", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_symbole.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Symbole", None), "featuretype": "t_eo_symbole", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_symbole.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "LI.Liegenschaft", None), "featuretype": "liegenschaften_liegenschaft", "geom": "geometrie", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "li/liegenschaft_ortho.qml" } vlayer = self.layer_loader.load(layer, False, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "BB.Objektname", None), "featuretype": "v_bb_objektnamen", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "bb/bb_objektnamen.qml" } vlayer = self.layer_loader.load(layer, True, False) layer = { "type": "postgres", "title": _translate("VeriSO_PNF_Gewaesser", "EO.Objektname", None), "featuretype": "v_eo_objektnamen", "geom": "pos", "key": "ogc_fid", "sql": "", "readonly": True, "group": group, "style": "eo/eo_objektnamen.qml" } vlayer = self.layer_loader.load(layer, True, False) if gemgrelayer: rect = gemgrelayer.extent() self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() 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()
def create_new_db( self, verno, user_select_CRS=True, EPSG_code='4326', set_locale=False, ): #CreateNewDB(self, verno): """Open a new DataBase (create an empty one if file doesn't exists) and set as default DB""" if user_select_CRS: EPSGID = str(self.ask_for_CRS(set_locale)[0]) else: EPSGID = EPSG_code QApplication.setOverrideCursor(Qt.WaitCursor) if EPSGID == '0' or not EPSGID: utils.pop_up_info("Cancelling...") else: # If a CRS is selectd, go on and create the database #path and name of new db if self.dbpath == '': self.dbpath = QFileDialog.getSaveFileName( None, "Ny tolknings-DB", "midv_tolkndb.sqlite", "Spatialite (*.sqlite)")[0] if not self.dbpath: QApplication.restoreOverrideCursor() return '' #create Spatialite database else: #delete the file if exists if os.path.exists(self.dbpath): try: os.remove(self.dbpath) except OSError as e: utils.pop_up_info("Error: %s - %s." % (e.filename, e.strerror)) QApplication.restoreOverrideCursor() return '' try: # creating/connecting the test_db self.conn = spatialite_connect(self.dbpath) # creating a Cursor self.cur = self.conn.cursor() self.cur.execute( "PRAGMA foreign_keys = ON" ) #Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection separately. except: utils.pop_up_info( "Impossible to connect to selected DataBase") QApplication.restoreOverrideCursor() return '' #First, find spatialite version versionstext = self.cur.execute( 'select spatialite_version()').fetchall() # load sql syntax to initialise spatial metadata, automatically create GEOMETRY_COLUMNS and SPATIAL_REF_SYS # then the syntax defines a Midvatten TOLKNINGS-db according to the loaded .sql-file if not int( versionstext[0][0][0] ) > 3: # which file to use depends on spatialite version installed utils.pop_up_info( "midv_tolkn plugin needs spatialite4.\nDatabase can not be created" ) return '' filenamestring = "create_tolkn_db.sql" SQLFile = os.path.join(os.sep, os.path.dirname(__file__), "sql_strings", filenamestring) qgisverno = Qgis.QGIS_VERSION #We want to store info about which qgis-version that created the db with open(SQLFile, 'r') as f: f.readline() # first line is encoding info.... try: for line in f: if not line: continue if line.startswith("#"): continue for replace_word, replace_with in [ ('CHANGETORELEVANTEPSGID', str(EPSGID)), ('CHANGETOPLUGINVERSION', str(verno)), ('CHANGETOQGISVERSION', str(qgisverno)), ('CHANGETOSPLITEVERSION', str(versionstext[0][0])) ]: line = line.replace(replace_word, replace_with) #replaced_line = line.replace('CHANGETOQGISVERSION',str(qgisverno)).replace('CHANGETOSPLITEVERSION',str(versionstext[0][0])) self.cur.execute( line ) # use tags to find and replace SRID and versioning info except Exception as e: utils.pop_up_info( 'Failed to create DB! sql failed:\n' + line + '\n\nerror msg:\n' + str(e)) except: utils.pop_up_info('Failed to create DB!') try: #spatial_ref_sys_aux not implemented until spatialite 4.3 self.cur.execute( r"""delete from spatial_ref_sys_aux where srid NOT IN ('%s', '4326')""" % EPSGID) except: pass self.cur.execute( r"""delete from spatial_ref_sys where srid NOT IN ('%s', '4326')""" % EPSGID) self.insert_datadomains() self.add_triggers() #self.cur.execute('vacuum') #FINISHED WORKING WITH THE DATABASE, CLOSE CONNECTIONS self.conn.commit() self.conn.close() #create SpatiaLite Connection in QGIS QSettings settings = QSettings() settings.beginGroup('/SpatiaLite/connections') settings.setValue( '%s/sqlitepath' % os.path.basename(self.dbpath), '%s' % self.dbpath) settings.endGroup() #Finally add the layer styles info into the data base AddLayerStyles(self.dbpath) QApplication.restoreOverrideCursor()
def handleAlgorithmResults(alg, context, feedback=None, showResults=True): wrongLayers = [] if feedback is None: feedback = QgsProcessingFeedback() feedback.setProgressText( QCoreApplication.translate('Postprocessing', 'Loading resulting layers')) i = 0 for l, details in context.layersToLoadOnCompletion().items(): if feedback.isCanceled(): return False if len(context.layersToLoadOnCompletion()) > 2: # only show progress feedback if we're loading a bunch of layers feedback.setProgress( 100 * i / float(len(context.layersToLoadOnCompletion()))) try: layer = QgsProcessingUtils.mapLayerFromString(l, context) if layer is not None: if not ProcessingConfig.getSetting( ProcessingConfig.USE_FILENAME_AS_LAYER_NAME): layer.setName(details.name) style = None if details.outputName: style = RenderingStyles.getStyle(alg.id(), details.outputName) if style is None: if layer.type() == QgsMapLayer.RasterLayer: style = ProcessingConfig.getSetting( ProcessingConfig.RASTER_STYLE) else: if layer.geometryType() == QgsWkbTypes.PointGeometry: style = ProcessingConfig.getSetting( ProcessingConfig.VECTOR_POINT_STYLE) elif layer.geometryType() == QgsWkbTypes.LineGeometry: style = ProcessingConfig.getSetting( ProcessingConfig.VECTOR_LINE_STYLE) else: style = ProcessingConfig.getSetting( ProcessingConfig.VECTOR_POLYGON_STYLE) if style: layer.loadNamedStyle(style) details.project.addMapLayer( context.temporaryLayerStore().takeMapLayer(layer)) except Exception: QgsMessageLog.logMessage( "Error loading result layer:\n" + traceback.format_exc(), 'Processing', QgsMessageLog.CRITICAL) wrongLayers.append(str(l)) i += 1 QApplication.restoreOverrideCursor() if wrongLayers: msg = "The following layers were not correctly generated.<ul>" msg += "".join(["<li>%s</li>" % lay for lay in wrongLayers]) + "</ul>" msg += "You can check the log messages to find more information about the execution of the algorithm" feedback.reportError(msg) return len(wrongLayers) == 0