def initVariables(self): self.dialog = Interface() self.msgBox = QMessageBox()
def ok(self): if not self.reload: if self.dlg.imp.text() == '': if self.selectOutp(): return elif not os.path.isabs(self.dlg.imp.text()): if self.selectOutp(): return else: self.reload = False self.csvFile = self.dlg.imp.text() status = False if not self.dlg.checkBox.isChecked(): self.current = self.dlg.comboBox.currentText() status = self.current.upper() == 'WORLD CAPITALS' if status: self.csvFile = os.path.join(self.plugin_dir, 'World Capitals.csv') if not self.dlg.checkBox.isChecked() and not status: self.csvFile = os.path.join(self.plugin_dir, 'Countries.csv') with open(self.csvFile, 'r') as f_all: self.all_cities = [] for line in f_all: mm = line.rstrip(', ').upper() if self.current.upper() in mm: self.all_cities.append(mm[:-1]) else: try: with open(self.csvFile, 'r') as f: self.all_cities = [line.rstrip('\n').upper() for line in f] except: msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Warning) msgBox.setWindowTitle('QWeather') msgBox.setText('Please define a csv file path.') msgBox.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint | Qt.WindowCloseButtonHint) msgBox.exec_() return self.outQWeatherGeoJson = os.path.join(self.plugin_dir, 'QWeather.geojson') basename = os.path.basename(self.outQWeatherGeoJson) self.layerTemp = basename[:-8] try: f = open(self.outQWeatherGeoJson, "w") f.close() except: self.selectOutp() self.dlg.ok.setEnabled(False) self.dlg.closebutton.setEnabled(False) self.dlg.toolButtonImport.setEnabled(False) if not self.iface.actionSelectRectangle().isChecked(): self.iface.actionSelectRectangle().trigger() if not self.iface.actionMapTips().isChecked(): self.iface.actionMapTips().trigger() if len(self.all_cities) > 1000: msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Warning) msgBox.setWindowTitle('Warning') msgBox.setText('Maximum locations must be below from 1000.') msgBox.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint | Qt.WindowCloseButtonHint) msgBox.exec_() ########################################### self.dlg.progressBar.setValue(100) self.dlg.progressBar.setValue(0) self.dlg.ok.setEnabled(True) self.dlg.closebutton.setEnabled(True) self.dlg.toolButtonImport.setEnabled(True) return # do stuff if self.dlg.Celsius.isChecked(): self.unit = 'C' self.unitDirection = "degrees" self.unitSpeed = "km/h" self.unitHumidity = "%" self.unitVisibility = "km" self.unitPressure = "hPa" self.style = 'weather_c' self.style2 = 'direction_c' else: self.unit = 'F' self.unitDirection = "degrees" self.unitSpeed = "mph" self.unitHumidity = "%" self.unitVisibility = "mi" self.unitPressure = "psi" self.style = 'weather_f' self.style2 = 'direction_f' self.geoinfo = [] self.call_import_temps_task()
def error_message(self, message): msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setWindowTitle("STDM") msg.setText(message) msg.exec_()
def accepted(self): self._running_tool = True self.txtStdout.clear() self.progress_bar.setValue(0) self.bar.clearWidgets() java_home_set = self.java_dependency.set_java_home() if not java_home_set: message_java = QCoreApplication.translate( "DialogExportData", """Configuring Java {}...""").format(JAVA_REQUIRED_VERSION) self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() self.txtStdout.setText(message_java) self.java_dependency.get_java_on_demand() self.disable() return ili2db = Ili2DB() configuration = self.update_configuration(ili2db) if configuration.disable_validation: # If data validation at export is disabled, we ask for confirmation self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Question) self.msg.setText( QCoreApplication.translate( "DialogExportData", "Are you sure you want to export your data without validation?" )) self.msg.setWindowTitle( QCoreApplication.translate("DialogExportData", "Export XTF without validation?")) self.msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) res = self.msg.exec_() if res == QMessageBox.No: self._running_tool = False return if not self.xtf_file_line_edit.validator().validate( configuration.xtffile, 0)[0] == QValidator.Acceptable: self._running_tool = False message_error = QCoreApplication.translate( "DialogExportData", "Please set a valid XTF file before exporting data.") self.txtStdout.setText(message_error) self.show_message(message_error, Qgis.Warning) self.xtf_file_line_edit.setFocus() return if not self.get_ili_models(): self._running_tool = False message_error = QCoreApplication.translate( "DialogExportData", "Please set a valid schema to export. This schema does not have information to export." ) self.txtStdout.setText(message_error) self.show_message(message_error, Qgis.Warning) self.export_models_list_view.setFocus() return # If xtf browser was opened and the file exists, the user already chose # to overwrite the file if os.path.isfile(self.xtf_file_line_edit.text().strip() ) and not self.xtf_browser_was_opened: self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Warning) self.msg.setText( QCoreApplication.translate( "DialogExportData", "{filename} already exists.\nDo you want to replace it?"). format(filename=os.path.basename( self.xtf_file_line_edit.text().strip()))) self.msg.setWindowTitle( QCoreApplication.translate("DialogExportData", "Save in XTF Transfer File")) self.msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box = self.msg.exec_() if msg_box == QMessageBox.No: self._running_tool = False return self.progress_bar.show() self.disable() self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() self._connect_ili2db_signals(ili2db) self.save_configuration(configuration) res, msg = ili2db.export(self.db, configuration) self._disconnect_ili2db_signals(ili2db) self._running_tool = False self.progress_bar.setValue(25) if res: self.buttonBox.clear() self.buttonBox.setEnabled(True) self.buttonBox.addButton(QDialogButtonBox.Close) self.progress_bar.setValue(100) else: # Since the export was not successful, we'll try to remove any temp XTF generated if os.path.exists(configuration.xtffile): try: os.remove(configuration.xtffile) except: pass message_type = Qgis.Success if res else Qgis.Warning self.show_message(msg, message_type) # Inform other classes whether the execution was successful or not self.on_result.emit(res)
load_external_package(library_name, library_version, exec_number, unzip) print("\nChecking dependencies!") #scipy try: import scipy print("scipy already installed. version: " + scipy.__version__ + " Locale:" + scipy.__file__) #except ModuleNotFoundError: except Exception: msg_box = QMessageBox() msg_box.setIcon(QMessageBox.Warning) msg_box.setText( 'scipy library not found. Please go to github: https://github.com/gustavowillam/SmartMapPlugin and see how to install python libraries.' ) msg_box.exec_() #pandas try: import pandas print("pandas already installed. version: " + pandas.__version__ + " Locale:" + pandas.__file__) #except ModuleNotFoundError: except Exception:
def message_box(self): return QMessageBox(QMessageBox.Information, "Note", self.message, buttons=QMessageBox.Ok)
def search(self): try: # Current service service = self.tab.tabText(self.tab.currentIndex()) # Params params = {'geometry': self.polygonInput.text()} # Set auth and add params according to service if service == 'BaseMap': # ! Auth self.bmSetAuth() # Set request attributes url = 'https://view.geoapi-airbusds.com/api/v1/images' auth = self.bmAuth headers = None # Update params params.update({ 'size': self.maxResultsInput.value(), 'insertdtstart': '1970-01-01T00:00:00', 'insertdtend': self.now() }) # Dates if self.bmFromCheck.isChecked(): params['insertdtstart'] = self.bmFromInput.dateTime( ).toString(Qt.ISODate) if self.bmToCheck.isChecked(): params['insertdtend'] = self.bmToInput.dateTime().toString( Qt.ISODate) else: # ! Auth self.dtSetAuth() url = 'https://search.oneatlas.geoapi-airbusds.com/api/v1/opensearch' auth = None headers = self.dtHeaders # Constellations (at least one) constellations = [] if self.dtSpotCheck.isChecked(): constellations.append('SPOT') if self.dtPleiadesCheck.isChecked(): constellations.append('PHR') # Dates # MAYBE remove hours from dates dateFrom, dateTo = '1970-01-01T00:00:00', self.now() if self.dtFromCheck.isChecked(): dateFrom = self.dtFromInput.dateTime().toString(Qt.ISODate) if self.dtToCheck.isChecked(): dateTo = self.dtToInput.dateTime().toString(Qt.ISODate) # Angles angleMin, angleMax = 0, 30 if self.dtAngleMinCheck.isChecked(): angleMin = self.dtAngleMinInput.value() if self.dtAngleMaxCheck.isChecked(): angleMax = self.dtAngleMaxInput.value() # Covers (directlly update params) if self.dtCloudCheck.isChecked(): params['cloudCover'] = f'[0,{self.dtCloudInput.value()}]' if self.dtSnowCheck.isChecked(): params['snowCover'] = f'[0,{self.dtSnowInput.value()}]' # Workspaces (at leat one) workspaces = [] if self.dtPublicCheck.isChecked(): workspaces.append('0e33eb50-3404-48ad-b835-b0b4b72a5625') if self.dtPrivateCheck.isChecked(): workspaces.append(self.dtWorkspaceId) # Update all params with right format params.update({ 'itemsPerPage': self.maxResultsInput.value(), 'constellation': ','.join(constellations), 'acquisitionDate': f'[{dateFrom},{dateTo}]', 'incidenceAngle': f'[{angleMin},{angleMax}]', 'workspace': ','.join(workspaces) }) # Finally do the api call t = datetime.datetime.now() print(f'START {service} search') r = self.session.get(url, auth=auth, headers=headers, params=params) rSearch = r.json() # Exception request error if r.status_code != 200: self.error( f'{service} search error {r.status_code}\n{rSearch["message"]}' ) return # Create the search result layer with fields according to current service layer = QgsVectorLayer( f'Polygon?crs=epsg:4326&index=yes&{FIELDS[service]}', providerLib='memory', baseName=f'{service} search results') # Extract features features = [] self.errorFeatures = [] for rFeature in rSearch['features']: # Add a feature of the bbox on the new layer feature = QgsFeature(layer.fields()) # Try to get each attributes feature['service'] = service feature['constellation'] = self.getPropertie( rFeature, 'constellation') feature['incidenceAngle'] = self.getPropertie( rFeature, 'incidenceAngle') feature['cloudCover'] = self.getPropertie( rFeature, 'cloudCover') if service == 'BaseMap': feature['id'] = rFeature['id'] feature['insertionDate'] = self.getPropertie( rFeature, 'insertionDate') feature['wmts'] = self.getPropertie(rFeature, 'wmts') # Bbox fBbox = rFeature['properties']['bbox'] rectangle = QgsRectangle(fBbox[0], fBbox[1], fBbox[2], fBbox[3]) else: feature['id'] = self.getPropertie(rFeature, 'id') feature['acquisitionDate'] = self.getPropertie( rFeature, 'acquisitionDate') feature['snowCover'] = self.getPropertie( rFeature, 'snowCover') try: for json in rFeature['_links']['imagesWmts']: feature[f'wmts_{json["name"]}'] = json['href'] for json in rFeature['_links']['imagesWcs']: if 'buffer' in rFeature['rights']: feature[f'wcs_{json["name"]}'] = json['href'] else: feature[f'wcs_{json["name"]}'] = None except Exception as e: print( f'ERROR * eF = qgis.utils.plugins["OneAtlas"].mySearch.errorFeatures[{len(self.errorFeatures)}]' ) print(str(e)) self.errorFeatures.append(rFeature) continue # Bbox coordinates = rFeature['geometry']['coordinates'][0] rectangle = QgsRectangle(coordinates[0][0], coordinates[0][1], coordinates[2][0], coordinates[2][1]) # Add geometry from rectangle feature.setGeometry( QgsGeometry.fromWkt(rectangle.asWktPolygon())) # Add feature to list features.append(feature) # Total if service == 'BaseMap': # Note : rSearch['totalResults'] is maybe the number of total element in bbox ? # and numberOfElements is the true total result total = rSearch['numberOfElements'] color = QColor.fromRgb(0, 250, 0) else: total = rSearch['totalResults'] color = QColor.fromRgb(0, 250, 250) if len(self.errorFeatures) > 0: total -= len(self.errorFeatures) print(f'* {len(self.errorFeatures)} error feature') # Notification for number of total results msgBox = QMessageBox() msgBox.setWindowTitle(WINDOW_TITLE) msgBox.setText(f'There are {total} results') if total > len(features): msgBox.setIcon(QMessageBox.Warning) msgBox.setInformativeText( f'The maximum is configured to {self.maxResultsInput.value()}\nPlease refine your criteria or your AOI' ) msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Ignore) msgBox.setDefaultButton(QMessageBox.Retry) else: msgBox.setIcon(QMessageBox.Information) msgBox.setStandardButtons(QMessageBox.Retry | QMessageBox.Ok) msgBox.setDefaultButton(QMessageBox.Ok) msgBox.button(QMessageBox.Retry).setText('Refine') msgBox.button(QMessageBox.Retry).setIcon( QIcon(os.path.dirname(__file__) + f'/search.png')) reply = msgBox.exec_() if reply == QMessageBox.Retry or len(features) == 0: return # Add result feature to the new layer (res, outFeats) = layer.dataProvider().addFeatures(features) # Change layer syle programmatically # Note : if we styling before save and add layer, we avoid to update legend style # => self.iface.layerTreeView().refreshLayerSymbology(vlayer.id()) symbol = layer.renderer().symbol() symbol.setOpacity(0.2) symbol.setColor(color) QgsProject.instance().addMapLayer(layer) # And refresh view layer.triggerRepaint() self.close() except: return
def check(self, data_info: dict): logger.debug("Checking data access conditions and limitation") limitations = data_info.get("limitations", None) # if there are no limits, ok for adding the layer if len(limitations) == 0: logger.debug( "No limitations found, let's add this layer to the canvas !") self.layer_adder.adding(layer_info=data_info.get("layer")) else: li_lim = [] for lim in limitations: lim = Limitation(**lim) if lim.directive: directive = Directive(**lim.directive) else: directive = Directive() # for 'legal' limitations, fill the list if lim.type == "legal": # for this directive, no need to informe the user if (lim.restriction == "other" and directive._id == "6756c1875d06446982ed941555102c72"): pass # for other legal limitations, need to informe the user else: logger.debug( "legal limitation detected : {}".format(lim)) li_lim.append(lim) # for any 'security' limitation, let's show the blocking popup and end the method elif lim.type == "security": popup = QMessageBox() popup.setWindowTitle("Limitations") popup_txt = self.tr( "This data is subject to a security limitation :", __class__.__name__, ) if lim.description != "": popup_txt += "\n - {}".format(lim.description) else: popup_txt += self.tr("\n - No description provided", context=__class__.__name__) popup.setText(popup_txt) popup.setInformativeText( self.tr( "Do you want to add the layer to the canvas anyway ?", context=__class__.__name__, )) popup.setStandardButtons(QMessageBox.Yes | QMessageBox.No) popup.setDefaultButton(QMessageBox.No) popup.finished.connect( partial(self.finished_slot, data_info.get("layer"))) popup.exec() return else: logger.info("Unexpected data limitation type : {}".format( lim.to_str())) pass # if all limitations are 'legal' type and 'No limit' INSPIRE directive, let's add the layer if len(li_lim) == 0: self.layer_adder.adding(layer_info=data_info.get("layer")) return # if there are other 'legal' type limitation, let's inform the user before adding the layer else: self.lim_sig.emit(li_lim) self.layer_adder.adding(layer_info=data_info.get("layer")) return
def __new_project(self): fil, __ = QFileDialog.getSaveFileName( None, u"New project name (no space, plain ascii)", QgsProject.instance().readEntry("albion", "last_dir", "")[0], "QGIS poject file (*.qgs)", ) if not fil: return fil = fil if len(fil) > 4 and fil[-4:] == ".qgs" else fil + ".qgs" fil = fil.replace(" ", "_") if len(fil) != len(fil.encode()): self.__iface.messageBar().pushError( "Albion:", "project name may only contain asci character (no accent)") return srid, ok = QInputDialog.getText( self.__iface.mainWindow(), "Project SRID", "Project SRID EPSG:", QLineEdit.Normal, "32632", ) if not ok: return srid = int(srid) project_name = str(os.path.split(fil)[1][:-4]) if Project.exists(project_name): if (QMessageBox.Yes != QMessageBox( QMessageBox.Information, "Delete existing DB", "Database {} exits, do you want to delete it ?".format( project_name), QMessageBox.Yes | QMessageBox.No, ).exec_()): self.__iface.messageBar().pushInfo( "Albion:", "keeping existing database...") else: Project.delete(project_name) self.__iface.messageBar().pushInfo("Albion:", "creating project...") Project.create(project_name, srid) else: self.__iface.messageBar().pushInfo("Albion:", "creating project...") Project.create(project_name, srid) if os.path.exists(fil): os.remove(fil) # load template open(fil, "w").write( open(resource("template_project.qgs")).read().replace( "template_project", project_name).replace("32632", str(srid))) self.__iface.newProject() QgsProject.instance().setFileName(fil) QgsProject.instance().read() QgsProject.instance().writeEntry("albion", "project_name", project_name) QgsProject.instance().writeEntry("albion", "srid", srid) QgsProject.instance().write() self.__qgis__project__loaded()
def readMapping(self,filename): if self.dlg.interlinkTable.rowCount()!=0: tree = ET.parse(filename) root = tree.getroot() filedata=root.find('file')[0] self.dlg.interlinkNameSpace.setText(filedata.get("namespace")) self.dlg.interlinkOwlClassInput.setText(filedata.get("class")) for neighbor in root.iter('column'): name=neighbor.get("name") proptype=neighbor.get("prop") propiri=neighbor.get("propiri") concept=neighbor.get("concept") query=neighbor.get("query") triplestoreurl=neighbor.get("triplestoreurl") valuemappings={} for vmap in neighbor.findall("valuemapping"): valuemappings[vmap.get("from")]=vmap.get("to") for row in range(self.dlg.interlinkTable.rowCount()): columnname=self.dlg.interlinkTable.item(row,3).text() if columnname==name: if propiri!=None: item=QTableWidgetItem(propiri) item.setText(propiri) item.setData(1,propiri) self.dlg.interlinkTable.setItem(row,4,item) if proptype!=None: comboboxx=self.dlg.interlinkTable.cellWidget(row,5) if proptype=="annotation": comboboxx.setCurrentIndex(comboboxx.findText("AnnotationProperty", QtCore.Qt.MatchFixedString)) elif proptype=="obj": comboboxx.setCurrentIndex(comboboxx.findText("ObjectProperty", QtCore.Qt.MatchFixedString)) elif proptype=="data": comboboxx.setCurrentIndex(comboboxx.findText("DataProperty", QtCore.Qt.MatchFixedString)) elif proptype=="subclass": comboboxx.setCurrentIndex(comboboxx.findText("SubClass", QtCore.Qt.MatchFixedString)) else: comboboxx.setCurrentIndex(comboboxx.findText("Automatic", QtCore.Qt.MatchFixedString)) if concept!=None: item=QTableWidgetItem(concept) item.setText(concept) item.setData(1,concept) self.dlg.interlinkTable.setItem(row,6,item) if valuemappings!={} and valuemappings!=None: item=QTableWidgetItem("ValueMap{}") item.setText("ValueMap{}") item.setData(1,valuemappings) if query!=None: item.setData(2,query) item.setData(3,triplestoreurl) self.dlg.interlinkTable.setItem(row,7,item) elif query!=None: item=QTableWidgetItem("ValueMap{}") item.setText("ValueMap{}") item.setData(2,query) item.setData(3,triplestoreurl) if valuemappings!={} and valuemappings!=None: item.setData(1,valuemappings) self.dlg.interlinkTable.setItem(row,7,item) else: msgBox=QMessageBox() msgBox.setText("Please first load a dataset to enrich before loading a mapping file") msgBox.exec()
def pintarPredios(self): url = self.CFG.url_BC_getPredios_id resArray = [] for id in self.idPredios: try: headers = { 'Content-Type': 'application/json', 'Authorization': self.UTI.obtenerToken() } respuesta = requests.get(url + id, headers=headers) except requests.exceptions.RequestException: self.UTI.mostrarAlerta("Error de servidor loc2", QMessageBox().Critical, "Busqueda de predio por id") print('ERROR: BD0000') if respuesta.status_code == 200: data = respuesta.content else: self.UTI.mostrarAlerta('Error en peticion:\n' + response.text, QMessageBox().Critical, "Busqueda de predio por cve") print('ERROR: BCP0001') res = json.loads(data.decode('utf-8')) if not bool(res): self.UTI.mostrarAlerta("Error de servidor pintcap", QMessageBox().Critical, "Cargar capa de consulta") print('ERROR: BCP0002') resArray.append(res) #si se consulto mas de 1 predio, fusionaremos los features en los resultados de cada consulta for j in range(0, len(resArray)): res = resArray[j] if len(resArray) > 1: for i in range(1, len(resArray)): res['features'].append(resArray[i]['features']) xPredG = QSettings().value('xPredGeom') self.xPredGeom = QgsProject.instance().mapLayer(xPredG) if self.xPredGeom is None: self.UTI.mostrarAlerta('No existe la capa ' + str(xPredG), QMessageBox().Critical, 'Cargar capas') return srid = QSettings().value("srid") inSpatialRef = osr.SpatialReference() inSpatialRef.ImportFromEPSG(int(srid)) outSpatialRef = osr.SpatialReference() outSpatialRef.ImportFromEPSG(int(srid)) coordTrans = osr.CoordinateTransformation(inSpatialRef, outSpatialRef) varKeys = res['features'][0]['properties'] self.datosPredio = varKeys keys = list(varKeys.keys()) properties = [] geoms = [] for feature in res['features']: geom = feature['geometry'] property = feature['properties'] geom = json.dumps(geom) geometry = ogr.CreateGeometryFromJson(geom) geometry.Transform(coordTrans) geoms.append(geometry.ExportToWkt()) l = [] for i in range(0, len(keys)): l.append(property[keys[i]]) properties.append(l) prov = self.xPredGeom.dataProvider() feats = [QgsFeature() for i in range(len(geoms))] parsed_geoms = [] for i, feat in enumerate(feats): feat.setAttributes(properties[i]) parse_geom = QgsGeometry.fromWkt(geoms[i]) feat.setGeometry(parse_geom) parsed_geoms.append(parse_geom) prov.addFeatures(feats) geometria = parsed_geoms[0] for i in range(1, len(parsed_geoms)): geometria = geometria.combine(geometria[i]) bbox = geometria.boundingBox() self.iface.mapCanvas().setExtent(bbox) self.iface.mapCanvas().refresh() #if nombreCapa == 'predios.geom': # self.cargarPrediosEnComboDividir(feats) self.xPredGeom.triggerRepaint()
def _about(self): QMessageBox().information(None, 'Quant a', 'qVista - Versió 0.1')
def ok(self): # Here check if select OK button, get the layer fields # Initialize # [JUNCTIONS] if self.dlg.out.text() == '': if self.selectOutp(): return elif os.path.isabs(self.dlg.out.text()) == False: if self.selectOutp(): return self.outEpanetName = self.dlg.out.text() try: f = open(self.outEpanetName, "w") f.close() except: msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Warning) msgBox.setWindowTitle('Warning') msgBox.setText('Please define Epanet Inp File location.') msgBox.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint | Qt.WindowCloseButtonHint) msgBox.exec_() return if not self.layers: msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Warning) msgBox.setWindowTitle('Warning') msgBox.setText('No layers selected.') msgBox.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint | Qt.WindowCloseButtonHint) msgBox.exec_() return xypipes_id = [] xypipesvert = [] for sect in self.sections: exec('sect' + sect + '=[]') in globals(), locals() exec('xy' + sect + '=[]') in globals(), locals() if eval('self.dlg.sect_' + sect + '.currentText()') != 'NONE': # Get layer field names indLayerName = self.layer_list.index( eval('self.dlg.sect_' + sect + '.currentText()')) - 1 provider = self.layers[indLayerName].dataProvider() fields = provider.fields() field_names = [field.name() for field in fields] for elem in self.layers[indLayerName].getFeatures(): eval('sect' + sect + '.append(dict(zip(field_names, elem.attributes())))') if any(sect in s for s in self.sections[0:5]): geom = elem.geometry() if self.layers[indLayerName].geometryType() == 0: eval('xy' + sect + '.append(geom.asPoint())') elif self.layers[indLayerName].geometryType() == 1: eval('xy' + sect + '.append(geom.asPolyline())') if sect == 'pipes': if len(geom.asPolyline()) > 2: for pp in range( len(geom.asPolyline()) - 2): xypipes_id.append(elem.attributes()[0]) xypipesvert.append( geom.asPolyline()[pp]) if sect == 'junctions': if 'Elevation' not in locals()['sect' + sect][0].keys(): QMessageBox.warning(QWidget(), "Message", "Elevation field is missing.") # (myDirectory,nameFile) = os.path.split(self.iface.activeLayer().dataProvider().dataSourceUri()) my_directory = '' f = open(self.outEpanetName, 'wt') f.write('[TITLE]\n') f.write('Export input file via plugin ExportEpanetInpFiles. \n\n') f.write('[JUNCTIONS]\n') node_i_ds = [] for i in range(len(locals()['sectjunctions'])): node_i_ds.append(locals()['sectjunctions'][i]['ID']) f.write(locals()['sectjunctions'][i]['ID'] + ' ' + str(locals()['sectjunctions'][i]['Elevation']) + '\n') f.write('\n[RESERVOIRS]\n') for i in range(len(locals()['sectreservoirs'])): node_i_ds.append(locals()['sectreservoirs'][i]['ID']) f.write(locals()['sectreservoirs'][i]['ID'] + ' ' + str(locals()['sectreservoirs'][i]['Head']) + '\n') f.write('\n[TANKS]\n') for i in range(len(locals()['secttanks'])): node_i_ds.append(locals()['secttanks'][i]['ID']) if locals()['secttanks'][i]['VolumeCurv'] == None: locals()['secttanks'][i]['VolumeCurv'] = "" f.write(locals()['secttanks'][i]['ID'] + ' ' + str(locals()['secttanks'][i]['Elevation']) + ' ' + str(locals()['secttanks'][i]['InitLevel']) + ' ' + str(locals()['secttanks'][i]['MinLevel']) + ' ' + str(locals()['secttanks'][i]['MaxLevel']) + ' ' + str(locals()['secttanks'][i]['Diameter']) + ' ' + str(locals()['secttanks'][i]['MinVolume']) + ' ' + str(locals()['secttanks'][i]['VolumeCurv']) + ' ' + '\n') f.write('\n[PIPES]\n') for i in range(len(locals()['sectpipes'])): if (locals()['sectpipes'][i]['NodeFrom'] in node_i_ds) and (locals()['sectpipes'][i]['NodeTo'] in node_i_ds): f.write(locals()['sectpipes'][i]['ID'] + ' ' + locals()['sectpipes'][i]['NodeFrom'] + ' ' + locals()['sectpipes'][i]['NodeTo'] + ' ' + str(locals()['sectpipes'][i]['Length']) + ' ' + str(locals()['sectpipes'][i]['Diameter']) + ' ' + str(locals()['sectpipes'][i]['Roughness']) + ' ' + str(locals()['sectpipes'][i]['MinorLoss']) + ' ' + locals()['sectpipes'][i]['Status'] + '\n') f.write('\n[PUMPS]\n') for i in range(len(locals()['sectpumps'])): if locals()['sectpumps'][i]['Curve'] != 'NULL': try: locals()['sectpumps'][i]['Curve'] = 'HEAD ' + locals( )['sectpumps'][i]['Curve'] except: locals()['sectpumps'][i]['Curve'] = 'HEAD ' else: locals()['sectpumps'][i]['Curve'] = '' if locals()['sectpumps'][i]['Pattern'] != 'NULL': try: locals()['sectpumps'][i]['Pattern'] = 'PATTERN ' + locals( )['sectpumps'][i]['Pattern'] except: locals()['sectpumps'][i]['Pattern'] = "PATTERN " else: locals()['sectpumps'][i]['Pattern'] = '' if locals()['sectpumps'][i]['Power'] != 'NULL': try: locals()['sectpumps'][i]['Power'] = 'POWER ' + locals( )['sectpumps'][i]['Power'] except: locals()['sectpumps'][i]['Power'] = "POWER " else: locals()['sectpumps'][i]['Power'] = '' try: f.write(locals()['sectpumps'][i]['ID'] + ' ' + locals()['sectpumps'][i]['NodeFrom'] + ' ' + locals()['sectpumps'][i]['NodeTo'] + ' ' + locals()['sectpumps'][i]['Curve'] + ' ' + str(locals()['sectpumps'][i]['Pattern']) + ' ' + str(locals()['sectpumps'][i]['Power']) + '\n') except: f.write(locals()['sectpumps'][i]['ID'] + '\n') f.write('\n[VALVES]\n') if self.dlg.sect_valves.currentText() != 'NONE': for i in range(len(locals()['sectvalves'])): try: locals()['sectvalves'][i]['NodeFrom'] = locals( )['sectvalves'][i]['NodeFrom'] + '' except: locals()['sectvalves'][i]['NodeFrom'] = "" try: locals()['sectvalves'][i]['NodeTo'] = locals( )['sectvalves'][i]['NodeTo'] + '' except: locals()['sectvalves'][i]['NodeTo'] = "" f.write("{} {} {} {} {} {} {}\n".format( locals()['sectvalves'][i]['ID'], locals()['sectvalves'][i]['NodeFrom'], locals()['sectvalves'][i]['NodeTo'], str(locals()['sectvalves'][i]['Diameter']), locals()['sectvalves'][i]['Type'], str(locals()['sectvalves'][i]['Setting']), str(locals()['sectvalves'][i]['MinorLoss']))) f.write('\n[DEMANDS]\n') for i in range(len(locals()['sectjunctions'])): for u in range(int((len(locals()['sectjunctions'][i]) - 2) / 2)): if locals( )['sectjunctions'][i]['Demand' + str(u + 1)] == 0 and str( locals()['sectjunctions'][i]['Pattern' + str(u + 1)]) == 'None': continue if str(locals()['sectjunctions'][i] ['Pattern' + str(u + 1)]) == 'NULL' or str( locals()['sectjunctions'][i]['Pattern' + str(u + 1)]) == 'None': locals()['sectjunctions'][i]['Pattern' + str(u + 1)] = '' f.write( locals()['sectjunctions'][i]['ID'] + ' ' + str(locals()['sectjunctions'][i]['Demand' + str(u + 1)]) + ' ' + str(locals()['sectjunctions'][i]['Pattern' + str(u + 1)]) + '\n') f.write('\n[STATUS]\n') for i in range(len(locals()['sectSTATUS'])): f.write("{} {}\n".format( locals()['sectSTATUS'][i]['Link_ID'], locals()['sectSTATUS'][i]['Status/Set'])) f.write('\n[PATTERNS]\n') for i in range(len(locals()['sectPATTERNS'])): f.write("{} {}\n".format( locals()['sectPATTERNS'][i]['Pattern_ID'], locals()['sectPATTERNS'][i]['Multiplier'])) f.write('\n[CURVES]\n') for i in range(len(locals()['sectCURVES'])): f.write(";{}:\n {} {} {}\n".format( locals()['sectCURVES'][i]['Type'], locals()['sectCURVES'][i]['Curve_ID'], str(locals()['sectCURVES'][i]['X-Value']), str(locals()['sectCURVES'][i]['Y-Value']))) f.write('\n[CONTROLS]\n') for i in range(len(locals()['sectCONTROLS'])): f.write("{}\n".format(locals()['sectCONTROLS'][i]['Controls'])) f.write('\n[RULES]\n') for i in range(len(locals()['sectRULES'])): f.write("RULE {}\n {}\n".format( locals()['sectRULES'][i]['Rule_ID'], locals()['sectRULES'][i]['Rule'])) f.write('\n[ENERGY]\n') if locals()['sectENERGY']: try: f.write('Global Efficiency ' + str(locals()['sectENERGY'][0]['GlobalEffi']) + '\n') except: pass try: f.write('Global Price ' + str(locals()['sectENERGY'][0]['GlobalPric']) + '\n') except: pass try: f.write('Demand Charge ' + str(locals()['sectENERGY'][0]['DemCharge']) + '\n') except: pass f.write('\n[REACTIONS]\n') if locals()['sectREACTIONS']: try: f.write('Order Bulk ' + str(locals()['sectREACTIONS'][0]['OrderBulk']) + '\n') except: pass try: f.write('Order Tank ' + str(locals()['sectREACTIONS'][0]['OrderTank']) + '\n') except: pass try: f.write('Order Wall ' + str(locals()['sectREACTIONS'][0]['OrderWall']) + '\n') except: pass try: f.write('Global Bulk ' + str(locals()['sectREACTIONS'][0]['GlobalBulk']) + '\n') except: pass try: f.write('Global Wall ' + str(locals()['sectREACTIONS'][0]['GlobalWall']) + '\n') except: pass try: f.write('Limiting Potential ' + str(locals()['sectREACTIONS'][0]['LimPotent']) + '\n') except: pass try: f.write('Roughness Correlation ' + str(locals()['sectREACTIONS'][0]['RoughCorr']) + '\n') except: pass f.write('\n[REACTIONS]\n') for i in range(len(locals()['sectREACTIONS_I'])): f.write('{} {} {} \n'.format( locals()['sectREACTIONS_I'][i]['Type'], locals()['sectREACTIONS_I'][i]['Pipe/Tank'], str(locals()['sectREACTIONS_I'][i]['Coeff.']))) f.write('\n[EMITTERS]\n') for i in range(len(locals()['sectEMITTERS'])): f.write('{} {}\n'.format( locals()['sectEMITTERS'][i]['Junc_ID'], str(locals()['sectEMITTERS'][i]['Coeff.']))) f.write('\n[SOURCES]\n') for i in range(len(locals()['sectSOURCES'])): try: locals()['sectSOURCES'][i]['Pattern'] = locals( )['sectSOURCES'][i]['Pattern'] + '' except: locals()['sectSOURCES'][i]['Pattern'] = '' f.write("{} {} {} {}\n".format( locals()['sectSOURCES'][i]['Node_ID'], locals()['sectSOURCES'][i]['Type'], str(locals()['sectSOURCES'][i]['Strength']), locals()['sectSOURCES'][i]['Pattern'])) f.write('\n[MIXING]\n') for i in range(len(locals()['sectMIXING'])): f.write('{} {} {} \n'.format( locals()['sectMIXING'][i]['Tank_ID'], locals()['sectMIXING'][i]['Model'], str(locals()['sectMIXING'][i]['Fraction']))) f.write('\n[TIMES]\n') if locals()['sectTIMES']: try: f.write('Duration ' + str(locals()['sectTIMES'][0]['Duration']) + '\n') except: pass try: f.write('Hydraulic Timestep ' + str(locals()['sectTIMES'][0]['HydStep']) + '\n') except: pass try: f.write('Quality Timestep ' + str(locals()['sectTIMES'][0]['QualStep']) + '\n') except: pass try: f.write('Pattern Timestep ' + str(locals()['sectTIMES'][0]['PatStep']) + '\n') except: pass try: f.write('Pattern Start ' + str(locals()['sectTIMES'][0]['PatStart']) + '\n') except: pass try: f.write('Report Timestep ' + str(locals()['sectTIMES'][0]['RepStep']) + '\n') except: pass try: f.write('Report Start ' + str(locals()['sectTIMES'][0]['RepStart']) + '\n') except: pass try: f.write('Start ClockTime ' + str(locals()['sectTIMES'][0]['StartClock']) + '\n') except: pass try: f.write('Statistic ' + str(locals()['sectTIMES'][0]['Statistic']) + '\n') except: pass f.write('\n[REPORT]\n') if locals()['sectREPORT']: try: f.write('Status ' + locals()['sectREPORT'][0]['Status'] + '\n') except: pass try: f.write('Summary ' + locals()['sectREPORT'][0]['Summary'] + '\n') except: pass try: f.write('Page ' + locals()['sectREPORT'][0]['Page'] + '\n') except: pass f.write('\n[OPTIONS]\n') if locals()['sectOPTIONS']: try: f.write('Units ' + str(locals()['sectOPTIONS'][0]['Units']) + '\n') except: pass try: f.write('Headloss ' + str(locals()['sectOPTIONS'][0]['Headloss']) + '\n') except: pass try: f.write('Specific Gravity ' + str(locals()['sectOPTIONS'][0]['SpecGrav']) + '\n') except: pass try: f.write('Viscosity ' + str(locals()['sectOPTIONS'][0]['Viscosity']) + '\n') except: pass try: f.write('Trials ' + str(locals()['sectOPTIONS'][0]['Trials']) + '\n') except: pass try: f.write('Accuracy ' + str(locals()['sectOPTIONS'][0]['Accuracy']) + '\n') except: pass try: f.write('CHECKFREQ ' + str(locals()['sectOPTIONS'][0]['CheckFreq']) + '\n') except: pass try: f.write('MAXCHECK ' + str(locals()['sectOPTIONS'][0]['MaxCheck']) + '\n') except: pass try: f.write('DAMPLIMIT ' + str(locals()['sectOPTIONS'][0]['DampLimit']) + '\n') except: pass try: f.write('Unbalanced ' + str(locals()['sectOPTIONS'][0]['Unbalanced']) + '\n') except: pass try: f.write('Pattern ' + str(locals()['sectOPTIONS'][0]['PatID']) + '\n') except: pass try: f.write('Demand Multiplier ' + str(locals()['sectOPTIONS'][0]['DemMult']) + '\n') except: pass try: f.write('Emitter Exponent ' + str(locals()['sectOPTIONS'][0]['EmitExp']) + '\n') except: pass try: f.write('Quality ' + str(locals()['sectOPTIONS'][0]['Quality']) + '\n') except: pass try: f.write('Diffusivity ' + str(locals()['sectOPTIONS'][0]['Diffusivit']) + '\n') except: pass try: f.write('Tolerance ' + str(locals()['sectOPTIONS'][0]['Tolerance']) + '\n') except: pass f.write('\n[COORDINATES]\n') for i in range(len(locals()['sectjunctions'])): f.write(locals()['sectjunctions'][i]['ID'] + ' ' + str(locals()['xyjunctions'][i][0]) + ' ' + str(locals()['xyjunctions'][i][1]) + '\n') for i in range(len(locals()['sectreservoirs'])): f.write(locals()['sectreservoirs'][i]['ID'] + ' ' + str(locals()['xyreservoirs'][i][0]) + ' ' + str(locals()['xyreservoirs'][i][1]) + '\n') for i in range(len(locals()['secttanks'])): f.write(locals()['secttanks'][i]['ID'] + ' ' + str(locals()['xytanks'][i][0]) + ' ' + str(locals()['xytanks'][i][1]) + '\n') f.write('\n[VERTICES]\n') for l in range(len(xypipes_id)): f.write(xypipes_id[l] + ' ' + str(xypipesvert[l][0]) + ' ' + str(xypipesvert[l][1]) + '\n') f.write('\n[END]\n') f.close() self.cancel() msgBox = QMessageBox() msgBox.setWindowTitle('Export Options') msgBox.setText('Export Epanet Inp File "' + self.outEpanetName + '" succesful.') msgBox.exec_()
def exec_warning_dialog(title, msg, body=None): box = QMessageBox(QMessageBox.Warning, title, msg, QMessageBox.Close) if not body is None: box.setDetailedText(body) return box.exec_()
def accepted(self): configuration = self.update_configuration() if not self.get_checked_schema(): message_error = QCoreApplication.translate( "DialogExportData", "You need to select a valid schema where to get the data from." ) self.txtStdout.setText(message_error) self.show_message(message_error, Qgis.Warning) self.connection_setting_button.setFocus() return if not self.xtf_file_line_edit.validator().validate( configuration.xtffile, 0)[0] == QValidator.Acceptable: message_error = QCoreApplication.translate( "DialogExportData", "Please set a valid XTF file before exporting data.") self.txtStdout.setText(message_error) self.show_message(message_error, Qgis.Warning) self.xtf_file_line_edit.setFocus() return if not self.get_ili_models(): message_error = QCoreApplication.translate( "DialogExportData", "Please set a valid schema to export. This schema does not have information to export." ) self.txtStdout.setText(message_error) self.show_message(message_error, Qgis.Warning) self.export_models_list_view.setFocus() return if not configuration.iliexportmodels: message_error = QCoreApplication.translate( "DialogExportData", "Please set a model before exporting data.") self.txtStdout.setText(message_error) self.show_message(message_error, Qgis.Warning) self.export_models_list_view.setFocus() return if self.type_combo_box.currentData() == 'gpkg': if not configuration.dbfile or self.gpkg_file_line_edit.validator( ).validate(configuration.dbfile, 0)[0] != QValidator.Acceptable: message_error = QCoreApplication.translate( "DialogExportData", "Please set an existing database file before creating the project." ) self.txtStdout.setText(message_error) self.show_message(message_error, Qgis.Warning) self.gpkg_file_line_edit.setFocus() return # If xtf browser was opened and the file exists, the user already chose # to overwrite the file if os.path.isfile(self.xtf_file_line_edit.text().strip() ) and not self.xtf_browser_was_opened: self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Warning) self.msg.setText( QCoreApplication.translate( "DialogExportData", "{filename} already exists.\nDo you want to replace it?"). format(filename=os.path.basename( self.xtf_file_line_edit.text().strip()))) self.msg.setWindowTitle( QCoreApplication.translate("DialogExportData", "Save in XTF Transfer File")) self.msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box = self.msg.exec_() if msg_box == QMessageBox.No: return with OverrideCursor(Qt.WaitCursor): self.progress_bar.show() self.progress_bar.setValue(0) self.disable() self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() exporter = iliexporter.Exporter() exporter.tool_name = 'ili2pg' if self.type_combo_box.currentData( ) == 'pg' else 'ili2gpkg' exporter.configuration = configuration self.save_configuration(configuration) exporter.stdout.connect(self.print_info) exporter.stderr.connect(self.on_stderr) exporter.process_started.connect(self.on_process_started) exporter.process_finished.connect(self.on_process_finished) self.progress_bar.setValue(25) try: if exporter.run() != iliexporter.Exporter.SUCCESS: self.enable() self.progress_bar.hide() self.show_message( QCoreApplication.translate( "DialogExportData", "An error occurred when exporting the data. For more information see the log..." ), Qgis.Warning) return except JavaNotFoundError: # Set JAVA PATH get_java_path_dlg = DialogGetJavaPath() get_java_path_dlg.setModal(True) if get_java_path_dlg.exec_(): configuration = self.update_configuration() if not get_java_path_from_qgis_model_baker(): message_error_java = QCoreApplication.translate( "DialogExportData", """Java could not be found. You can configure the JAVA_HOME environment variable, restart QGIS and try again.""" ) self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() self.txtStdout.setText(message_error_java) self.show_message(message_error_java, Qgis.Warning) self.enable() self.progress_bar.hide() return self.buttonBox.clear() self.buttonBox.setEnabled(True) self.buttonBox.addButton(QDialogButtonBox.Close) self.progress_bar.setValue(100) self.show_message( QCoreApplication.translate( "DialogExportData", "Export of the data was successfully completed."), Qgis.Success)
def keyPressEvent(self, event): print("Key: " + str(event.key())) print("Modifier: " + str(event.modifiers())) layers = QgsProject.instance().layerTreeRoot().children() selectedLayerIndex = 0 tc = self.textCursor() #msgBox=QMessageBox() #msgBox.setText(str(selection)) #msgBox.exec() if len(layers) > 0 and event.key() == Qt.Key_Space and event.modifiers( ) == Qt.ControlModifier: self.createVarInputDialog() event.accept() return elif len(layers) == 0 and event.key( ) == Qt.Key_Space and event.modifiers() == Qt.ControlModifier: msgBox = QMessageBox() msgBox.setText( "No layer has been loaded in QGIS. Therefore no query variables may be created from a given QGIS layer." ) msgBox.exec() event.accept() return elif (event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return) and not self.completer.popup( ).isVisible() and event.modifiers() == Qt.ControlModifier: self.buildSearchDialog(-1, -1, -1, self, True, True) event.accept() return elif (event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return) and self.completer.popup().isVisible(): self.completer.insertText.emit(self.completer.getSelected()) self.completer.setCompletionMode(QCompleter.PopupCompletion) event.accept() return QPlainTextEdit.keyPressEvent(self, event) seltext = self.textUnderCursor(tc) tc.select(QTextCursor.LineUnderCursor) selline = tc.selectedText().strip() sellinearr = selline.split(" ") if len(sellinearr) == 2 and (sellinearr[0].startswith("?")): print("subject is variable") self.updateCompleterData(list( self.autocomplete["propdict"].keys())) self.changedCompleterSetting = True #msgBox=QMessageBox() #msgBox.setText(str(list(self.autocomplete["completerClassList"].keys()))) #msgBox.exec() elif len(sellinearr) == 3 and (sellinearr[0].startswith("?")): print("subject and predicate") self.updateCompleterData( list(self.autocomplete["clsdict"].keys()) + list(self.autocomplete["completerClassList"].keys())) self.changedCompleterSetting = True #msgBox=QMessageBox() #msgBox.setText(str(list(self.autocomplete["completerClassList"].keys()))) #msgBox.exec() elif self.changedCompleterSetting: self.updateCompleterData( list(self.autocomplete["clsdict"].keys()) + list(self.autocomplete["propdict"].keys()) + list(self.autocomplete["completerClassList"].keys())) self.changedCompleterSetting = False #msgBox=QMessageBox() #msgBox.setText(str(list(self.autocomplete["completerClassList"].keys()))+" - "+str(self.changedCompleterSetting)) #msgBox.exec() #for m in re.finditer(r'\S+', selline): # num, part = m.start(), m.group() # if (part=="." and num<len(selline)-1) or (part==";" and num<len(selline)-1) or (part=="{" and num<len(selline)-1 and num!=1) or (part=="}" and num<len(selline)-1 and num!=1): # tc.setPosition(tc.selectionEnd()-1) # tc.insertText(os.linesep) cr = self.cursorRect() if len(seltext) > 0: self.completer.setCompletionPrefix(seltext) popup = self.completer.popup() popup.setCurrentIndex(self.completer.completionModel().index(0, 0)) cr.setWidth( self.completer.popup().sizeHintForColumn(0) + self.completer.popup().verticalScrollBar().sizeHint().width()) self.completer.complete(cr) else: self.completer.popup().hide() event.accept()
def generate_report(self, db, report_type): # Check if mapfish and Jasper are installed, otherwise show where to # download them from and return base_path = os.path.join(os.path.expanduser('~'), 'Asistente-LADM_COL', 'impresion') bin_path = os.path.join(base_path, 'bin') if not os.path.exists(bin_path): self.qgis_utils.message_with_button_download_report_dependency_emitted.emit( QCoreApplication.translate( "ReportGenerator", "The dependency library to generate reports is not installed. Click on the button to download and install it." )) return # Check version required_version_found = True version_path = os.path.join(base_path, 'version') if not os.path.exists(version_path): required_version_found = False else: version_found = '' with open(version_path) as f: version_found = f.read() if version_found.strip() != REPORTS_REQUIRED_VERSION: required_version_found = False if not required_version_found: self.qgis_utils.message_with_button_remove_report_dependency_emitted.emit( QCoreApplication.translate( "ReportGenerator", "The dependency library to generate reports was found, but does not match with the version required. Click the button to remove the installed version and try again." )) return # Check if JAVA_HOME path is set, otherwise use path from QGIS Model Baker if not Utils.set_java_home(): get_java_path_dlg = GetJavaPathDialog() get_java_path_dlg.setModal(True) get_java_path_dlg.exec_() if not Utils.set_java_home(): self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Information) self.msg.setText( QCoreApplication.translate( "ReportGenerator", "JAVA_HOME environment variable is not defined, please define it as an enviroment variable and restart QGIS before generating the annex 17." )) self.msg.setWindowTitle( QCoreApplication.translate("ReportGenerator", "JAVA_HOME not defined")) self.msg.setStandardButtons(QMessageBox.Close) self.msg.exec_() return plot_layer = self.qgis_utils.get_layer(db, PLOT_TABLE, QgsWkbTypes.PolygonGeometry, load=True) if not plot_layer: return selected_plots = plot_layer.selectedFeatures() if not selected_plots: self.qgis_utils.message_emitted.emit( QCoreApplication.translate( "ReportGenerator", "To generate reports, first select at least a plot!"), Qgis.Warning) return # Where to store the reports? previous_folder = QSettings().value( "Asistente-LADM_COL/reports/save_into_dir", ".") save_into_folder = QFileDialog.getExistingDirectory( None, QCoreApplication.translate( "ReportGenerator", "Select a folder to save the reports to be generated"), previous_folder) if not save_into_folder: self.qgis_utils.message_emitted.emit( QCoreApplication.translate( "ReportGenerator", "You need to select a folder where to save the reports before continuing." ), Qgis.Warning) return QSettings().setValue("Asistente-LADM_COL/reports/save_into_dir", save_into_folder) config_path = os.path.join(base_path, report_type) json_spec_file = os.path.join(config_path, 'spec_json_file.json') script_name = '' if os.name == 'posix': script_name = 'print' elif os.name == 'nt': script_name = 'print.bat' script_path = os.path.join(bin_path, script_name) if not os.path.isfile(script_path): print("### SCRIPT FILE WASN'T FOUND") return self.enable_action_requested.emit(report_type, False) # Update config file yaml_config_path = self.update_yaml_config(db, config_path) print("CONFIG FILE:", yaml_config_path) total = len(selected_plots) step = 0 count = 0 tmp_dir = self.get_tmp_dir() # Progress bar setup progress = QProgressBar() if total == 1: progress.setRange(0, 0) else: progress.setRange(0, 100) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.qgis_utils.create_progress_message_bar_emitted.emit( QCoreApplication.translate("ReportGenerator", "Generating {} report{}...").format( total, '' if total == 1 else 's'), progress) polygons_with_holes = [] multi_polygons = [] for selected_plot in selected_plots: plot_id = selected_plot[ID_FIELD] geometry = selected_plot.geometry() abstract_geometry = geometry.get() if abstract_geometry.ringCount() > 1: polygons_with_holes.append(str(plot_id)) self.log.logMessage( QCoreApplication.translate( "ReportGenerator", "Skipping Annex 17 for plot with {}={} because it has holes. The reporter module does not support such polygons." ).format(ID_FIELD, plot_id), PLUGIN_NAME, Qgis.Warning) continue if abstract_geometry.numGeometries() > 1: multi_polygons.append(str(plot_id)) self.log.logMessage( QCoreApplication.translate( "ReportGenerator", "Skipping Annex 17 for plot with {}={} because it is a multi-polygon. The reporter module does not support such polygons." ).format(ID_FIELD, plot_id), PLUGIN_NAME, Qgis.Warning) continue # Generate data file json_file = self.update_json_data(db, json_spec_file, plot_id, tmp_dir, report_type) print("JSON FILE:", json_file) # Run sh/bat passing config and data files proc = QProcess() proc.readyReadStandardError.connect( functools.partial(self.stderr_ready, proc=proc)) proc.readyReadStandardOutput.connect( functools.partial(self.stdout_ready, proc=proc)) parcel_number = self.ladm_data.get_parcels_related_to_plots( db, [plot_id], PARCEL_NUMBER_FIELD) or [''] file_name = '{}_{}_{}.pdf'.format(report_type, plot_id, parcel_number[0]) current_report_path = os.path.join(save_into_folder, file_name) proc.start(script_path, [ '-config', yaml_config_path, '-spec', json_file, '-output', current_report_path ]) if not proc.waitForStarted(): # Grant execution permissions os.chmod( script_path, stat.S_IXOTH | stat.S_IXGRP | stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP) proc.start(script_path, [ '-config', yaml_config_path, '-spec', json_file, '-output', current_report_path ]) if not proc.waitForStarted(): proc = None print("### COULDN'T EXECUTE SCRIPT TO GENERATE REPORT...") else: loop = QEventLoop() proc.finished.connect(loop.exit) loop.exec() print(plot_id, ':', proc.exitCode()) if proc.exitCode() == 0: count += 1 step += 1 progress.setValue(step * 100 / total) os.remove(yaml_config_path) self.enable_action_requested.emit(report_type, True) self.qgis_utils.clear_message_bar_emitted.emit() if total == count: if total == 1: msg = QCoreApplication.translate( "ReportGenerator", "The report <a href='file:///{}'>{}</a> was successfully generated!" ).format(normalize_local_url(save_into_folder), file_name) else: msg = QCoreApplication.translate( "ReportGenerator", "All reports were successfully generated in folder <a href='file:///{path}'>{path}</a>!" ).format(path=normalize_local_url(save_into_folder)) self.qgis_utils.message_with_duration_emitted.emit( msg, Qgis.Success, 0) else: details_msg = '' if polygons_with_holes: details_msg += QCoreApplication.translate( "ReportGenerator", " The following polygons were skipped because they have holes and are not supported: {}." ).format(", ".join(polygons_with_holes)) if multi_polygons: details_msg += QCoreApplication.translate( "ReportGenerator", " The following polygons were skipped because they are multi-polygons and are not supported: {}." ).format(", ".join(multi_polygons)) if total == 1: msg = QCoreApplication.translate( "ReportGenerator", "The report for plot {} couldn't be generated!{} See QGIS log (tab '{}') for details." ).format(plot_id, details_msg, self.LOG_TAB) else: if count == 0: msg = QCoreApplication.translate( "ReportGenerator", "No report could be generated!{} See QGIS log (tab '{}') for details." ).format(details_msg, self.LOG_TAB) else: msg = QCoreApplication.translate( "ReportGenerator", "At least one report couldn't be generated!{details_msg} See QGIS log (tab '{log_tab}') for details. Go to <a href='file:///{path}'>{path}</a> to see the reports that were generated." ).format(details_msg=details_msg, path=normalize_local_url(save_into_folder), log_tab=self.LOG_TAB) self.qgis_utils.message_with_duration_emitted.emit( msg, Qgis.Warning, 0)
def accepted(self, edited_command=None): configuration = self.updated_configuration() ili_mode = self.type_combo_box.currentData() db_id = ili_mode & ~DbIliMode.ili interlis_mode = ili_mode & DbIliMode.ili if not edited_command: if interlis_mode: if not self.ili_file_line_edit.text().strip(): if not self.ili_models_line_edit.text().strip(): self.txtStdout.setText( self.tr('Please set a valid INTERLIS model before creating the project.')) self.ili_models_line_edit.setFocus() return if self.ili_file_line_edit.text().strip() and \ self.ili_file_line_edit.validator().validate(configuration.ilifile, 0)[0] != QValidator.Acceptable: self.txtStdout.setText( self.tr('Please set a valid INTERLIS file before creating the project.')) self.ili_file_line_edit.setFocus() return res, message = self._lst_panel[db_id].is_valid() if not res: self.txtStdout.setText(message) return configuration.dbschema = configuration.dbschema or configuration.database self.save_configuration(configuration) db_factory = self.db_simple_factory.create_factory(db_id) try: # raise warning when the schema or the database file already exists config_manager = db_factory.get_db_command_config_manager(configuration) db_connector = db_factory.get_db_connector( config_manager.get_uri(configuration.db_use_super_login) or config_manager.get_uri(), configuration.dbschema) if db_connector.db_or_schema_exists(): if interlis_mode: warning_box = QMessageBox(self) warning_box.setIcon(QMessageBox.Information) warning_title = self.tr("{} already exists").format( db_factory.get_specific_messages()['db_or_schema'] ).capitalize() warning_box.setWindowTitle(warning_title) warning_box.setText(self.tr("{warning_title}:\n{db_or_schema_name}\n\nDo you want to " "import into the existing {db_or_schema}?").format( warning_title=warning_title, db_or_schema=db_factory.get_specific_messages()['db_or_schema'].capitalize(), db_or_schema_name=configuration.dbschema or config_manager.get_uri() )) warning_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) warning_box_result = warning_box.exec_() if warning_box_result == QMessageBox.No: return except (DBConnectorError, FileNotFoundError): # we don't mind when the database file is not yet created pass # create schema with superuser res, message = db_factory.pre_generate_project(configuration) if not res: self.txtStdout.setText(message) return with OverrideCursor(Qt.WaitCursor): self.progress_bar.show() self.progress_bar.setValue(0) self.disable() self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() if interlis_mode: importer = iliimporter.Importer() importer.tool = self.type_combo_box.currentData() importer.configuration = configuration importer.stdout.connect(self.print_info) importer.stderr.connect(self.on_stderr) importer.process_started.connect(self.on_process_started) importer.process_finished.connect(self.on_process_finished) try: if importer.run(edited_command) != iliimporter.Importer.SUCCESS: self.enable() self.progress_bar.hide() return except JavaNotFoundError as e: self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() self.txtStdout.setText(e.error_string) self.enable() self.progress_bar.hide() return try: config_manager = db_factory.get_db_command_config_manager(configuration) uri = config_manager.get_uri() mgmt_uri = config_manager.get_uri(configuration.db_use_super_login) generator = Generator(configuration.tool, uri, configuration.inheritance, configuration.dbschema, mgmt_uri=mgmt_uri) generator.stdout.connect(self.print_info) generator.new_message.connect(self.show_message) self.progress_bar.setValue(50) except (DBConnectorError, FileNotFoundError): self.txtStdout.setText( self.tr('There was an error connecting to the database. Check connection parameters.')) self.enable() self.progress_bar.hide() return if not interlis_mode: if not generator.db_or_schema_exists(): self.txtStdout.setText( self.tr('Source {} does not exist. Check connection parameters.').format( db_factory.get_specific_messages()['db_or_schema'] )) self.enable() self.progress_bar.hide() return res, message = db_factory.post_generate_project_validations(configuration) if not res: self.txtStdout.setText(message) self.enable() self.progress_bar.hide() return self.print_info( self.tr('\nObtaining available layers from the database…')) available_layers = generator.layers() if not available_layers: text = self.tr('The {} has no layers to load into QGIS.').format( db_factory.get_specific_messages()['layers_source']) self.txtStdout.setText(text) self.enable() self.progress_bar.hide() return self.progress_bar.setValue(70) self.print_info( self.tr('Obtaining relations from the database…')) relations, bags_of_enum = generator.relations(available_layers) self.progress_bar.setValue(75) self.print_info(self.tr('Arranging layers into groups…')) legend = generator.legend(available_layers) self.progress_bar.setValue(85) project = Project() project.layers = available_layers project.relations = relations project.bags_of_enum = bags_of_enum project.legend = legend self.print_info(self.tr('Configuring forms and widgets…')) project.post_generate() self.progress_bar.setValue(90) qgis_project = QgsProject.instance() self.print_info(self.tr('Generating QGIS project…')) project.create(None, qgis_project) # Set the extent of the mapCanvas from the first layer extent found for layer in project.layers: if layer.extent is not None: self.iface.mapCanvas().setExtent(layer.extent) self.iface.mapCanvas().refresh() break self.buttonBox.clear() self.buttonBox.setEnabled(True) self.buttonBox.addButton(QDialogButtonBox.Close) self.progress_bar.setValue(100) self.print_info(self.tr('\nDone!'), '#004905')
def InfoMessage(self, message): # Information message box msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText(message) msg.exec_()
def show_message(self, message): msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setWindowTitle(QApplication.translate("AttributeEditor", "STDM")) msg.setText(message) msg.exec_()
def stream(self): goForStream = True # Avoid auth exception if you reopen the project and don't open the search if self.mySearch == None: self.mySearch = MySearch(self.iface) # Get selected feature of active layer service = self.selectedFeature['service'] # Setup raster params isWcs = False if service == 'BaseMap': if self.mySearch.bmAuth is None: try: self.mySearch.bmSetAuth() except: return username = self.mySearch.bmUsernameInput.text() password = self.mySearch.bmPasswordInput.text() layers = self.mySearch.bmGetLayer(self.selectedFeature['wmts']) styles = 'default' tileMatrixSet = '4326' urlAttr = 'wmts' elif service == 'Data': if self.mySearch.dtHeaders is None: try: self.mySearch.dtSetAuth() except: return username = '******' password = self.mySearch.dtApikeyInput.text() # Dialog for image choice (panchro/multi & wmts/wcs) self.msgBox = QMessageBox() self.msgBox.setWindowTitle(self.menu) if self.selectedFeature['processingLevel'] == 'ALBUM': self.iface.messageBar().pushMessage("Warning", "The feature can't be displayed (no WMTS for Archive features)", level=Qgis.Warning) goForStream = False else: protocolGroup = QGroupBox('Protocol') protocolGrid = QGridLayout() wmtsRadio = QRadioButton('WMTS') wcsRadio = QRadioButton('WCS') protocolGrid.addWidget(wmtsRadio, 0, 0) protocolGrid.addWidget(wcsRadio, 0, 1) protocolGroup.setLayout(protocolGrid) styleGroup = QGroupBox('Style') styleGrid = QGridLayout() multispectralRadio = QRadioButton('multispectral') panchromaticRadio = QRadioButton('panchromatic') pmsRadio = QRadioButton('pms') styleGrid.addWidget(multispectralRadio, 0, 0) styleGrid.addWidget(panchromaticRadio, 0, 1) styleGrid.addWidget(pmsRadio, 0, 2) styleGroup.setLayout(styleGrid) self.msgBox.layout().addWidget(protocolGroup, 0, 0) self.msgBox.layout().addWidget(styleGroup, 1, 0) wmtsRadio.setChecked(True) if type(self.selectedFeature['wcs_multispectral']) != str and type(self.selectedFeature['wcs_panchromatic']) != str and type(self.selectedFeature['wcs_pms']) != str: protocolGroup.setEnabled(False) if type(self.selectedFeature['wmts_pms']) != str: multispectralRadio.setEnabled(True) panchromaticRadio.setEnabled(True) pmsRadio.setEnabled(False) multispectralRadio.setChecked(True) else: multispectralRadio.setEnabled(True) panchromaticRadio.setEnabled(True) pmsRadio.setEnabled(True) pmsRadio.setChecked(True) self.msgBox.setStandardButtons(QMessageBox.Abort | QMessageBox.Ok) reply = self.msgBox.exec_() if reply == QMessageBox.Abort: return if wmtsRadio.isChecked(): urlAttr = 'wmts_' layers = 'default' styles = 'rgb' tileMatrixSet = 'EPSG4326' else: urlAttr = 'wcs_' isWcs = True if multispectralRadio.isChecked(): urlAttr += 'multispectral' elif panchromaticRadio.isChecked(): urlAttr += 'panchromatic' else: urlAttr += 'pms' else: self.error(f'Service "{service}" of the feature ocg_fid={self.selectedFeature.id()} isn\'t recognized\nIt should be "Basemap" or "Data"') return if goForStream: # Add a WMTS raster layer # Order of url parameters are important ! # Why layers is required, maybe is an internal id for wmts gesture ? # What is styles ? try: url = self.selectedFeature[urlAttr] name = f'{service} {self.selectedFeature["id"]}' if isWcs: rlayer = QgsRasterLayer(f'dpiMode=7&identifier=default&password={password}&url={url}&username={username}', name, 'wcs') else: rlayer = QgsRasterLayer(f'crs=EPSG:4326&dpiMode=7&format=image/png&layers={layers}&password={password}&styles={styles}&tileMatrixSet={tileMatrixSet}&url={url}&username={username}', name, 'wms') except Exception as e: self.error(f'Error in protocol connection\n\n{str(e)}') return if rlayer.isValid() == False: self.error(f'Raster layer is invalid\n\n{rlayer.error()}') return QgsProject.instance().addMapLayer(rlayer)
def getClassesFromLabel(self, comboBox): viewlist = [] resultlist = [] label = self.conceptSearchEdit.text() if label == "": return language = "en" results = {} self.searchResult.clear() query = "" position = self.tripleStoreEdit.currentIndex() if self.tripleStoreEdit.currentIndex() > len(self.triplestoreconf): if self.findProperty.isChecked(): self.addVocab[self.addVocab.keys()[ position - len(self.triplestoreconf)]]["source"]["properties"] viewlist = {k: v for k, v in d.iteritems() if label in k} else: self.addVocab[self.addVocab.keys()[ position - len(self.triplestoreconf)]]["source"]["classes"] viewlist = {k: v for k, v in d.iteritems() if label in k} for res in viewlist: item = QListWidgetItem() item.setData(1, val) item.setText(key) self.searchResult.addItem(item) else: if self.findProperty.isChecked(): if "propertyfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["propertyfromlabelquery"].replace( "%%label%%", label) else: if "classfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["classfromlabelquery"].replace("%%label%%", label) if query == "": msgBox = QMessageBox() msgBox.setText( "No search query specified for this triplestore") msgBox.exec() return if "SELECT" in query: query = query.replace("%%label%%", label).replace("%%language%%", language) sparql = SPARQLWrapper( self.triplestoreconf[self.tripleStoreEdit.currentIndex() + 1]["endpoint"], agent= "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11" ) #msgBox=QMessageBox() #msgBox.setText(query+" - "+self.triplestoreconf[self.tripleStoreEdit.currentIndex()+1]["endpoint"]) #msgBox.exec() sparql.setQuery( self.prefixes[self.tripleStoreEdit.currentIndex() + 1] + query) sparql.setReturnFormat(JSON) results = sparql.query().convert() #msgBox=QMessageBox() #msgBox.setText(str(results)) #msgBox.exec() if len(results["results"]) == 0: msgBox = QMessageBox() msgBox.setWindowTitle("Empty search result") msgBox.setText("The search yielded no results") msgBox.exec() return for res in results["results"]["bindings"]: item = QListWidgetItem() item.setData(1, str(res["class"]["value"])) if "label" in res: item.setText( str(res["label"]["value"] + " (" + res["class"]["value"] + ")")) else: item.setText(str(res["class"]["value"])) self.searchResult.addItem(item) else: myResponse = json.loads(requests.get(query).text) qids = [] for ent in myResponse["search"]: qid = ent["concepturi"] if "http://www.wikidata.org/entity/" in qid and self.findProperty.isChecked( ): qid = "http://www.wikidata.org/prop/direct/" + ent["id"] elif "http://www.wikidata.org/wiki/" in qid and self.findConcept.isChecked( ): qid = "http://www.wikidata.org/entity/" + ent["id"] qids.append(qid) label = ent["label"] + " (" + ent["id"] + ") " if "description" in ent: label += "[" + ent["description"] + "]" results[qid] = label i = 0 for result in results: item = QListWidgetItem() item.setData(1, qids[i]) item.setText(str(results[result])) self.searchResult.addItem(item) i += 1 return viewlist
def accepted(self): self._running_tool = True self.txtStdout.clear() self.progress_bar.setValue(0) self.bar.clearWidgets() if not os.path.isfile(self.xtf_file_line_edit.text().strip()): self._running_tool = False error_msg = QCoreApplication.translate("DialogImportData", "Please set a valid XTF file before importing data. XTF file does not exist.") self.txtStdout.setText(error_msg) self.show_message(error_msg, Qgis.Warning) self.xtf_file_line_edit.setFocus() return java_home_set = self.java_dependency.set_java_home() if not java_home_set: message_java = QCoreApplication.translate("DialogImportData", """Configuring Java {}...""").format(JAVA_REQUIRED_VERSION) self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() self.txtStdout.setText(message_java) self.java_dependency.get_java_on_demand() self.disable() return ili2db = Ili2DB() configuration = self.update_configuration(ili2db) configuration = self.apply_role_model_configuration(configuration) if configuration.disable_validation: # If data validation at import is disabled, we ask for confirmation self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Question) self.msg.setText(QCoreApplication.translate("DialogImportData", "Are you sure you want to import your data without validation?")) self.msg.setWindowTitle(QCoreApplication.translate("DialogImportData", "Import XTF without validation?")) self.msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) res = self.msg.exec_() if res == QMessageBox.No: self._running_tool = False return if not self.xtf_file_line_edit.validator().validate(configuration.xtffile, 0)[0] == QValidator.Acceptable: self._running_tool = False error_msg = QCoreApplication.translate("DialogImportData", "Please set a valid XTF before importing data.") self.txtStdout.setText(error_msg) self.show_message(error_msg, Qgis.Warning) self.xtf_file_line_edit.setFocus() return if not self.get_ili_models(): self._running_tool = False error_msg = QCoreApplication.translate("DialogImportData", "The selected XTF file does not have information according to the LADM-COL model to import.") self.txtStdout.setText(error_msg) self.show_message(error_msg, Qgis.Warning) self.import_models_list_view.setFocus() return # Get list of models present in the XTF file, in the DB and in the list of required models (by the plugin) ili_models = set([ili_model for ili_model in self.get_ili_models()]) supported_models_in_ili = set([m.full_name() for m in self.__ladmcol_models.supported_models()]).intersection(ili_models) if not supported_models_in_ili: self._running_tool = False error_msg = QCoreApplication.translate("DialogImportData", "The selected XTF file does not have data from any LADM-COL model supported by the LADM-COL Assistant. " \ "Therefore, you cannot import it! These are the models supported:\n\n * {}").format(" \n * ".join([m.full_alias() for m in self.__ladmcol_models.supported_models()])) self.txtStdout.setText(error_msg) self.show_message(error_msg, Qgis.Warning) self.import_models_list_view.setFocus() return db_models = set(self.db.get_models()) suggested_models = sorted(ili_models.difference(db_models)) if not ili_models.issubset(db_models): self._running_tool = False error_msg = QCoreApplication.translate("DialogImportData", "IMPORT ERROR: The XTF file to import does not have the same models as the target database schema. " \ "Please create a schema that also includes the following missing modules:\n\n * {}").format( " \n * ".join(suggested_models)) self.txtStdout.clear() self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.setText(error_msg) self.show_message(error_msg, Qgis.Warning) self.xtf_file_line_edit.setFocus() # button is removed to define order in GUI for button in self.buttonBox.buttons(): if button.text() == self.BUTTON_NAME_IMPORT_DATA: self.buttonBox.removeButton(button) # Check if button was previously added self.remove_create_structure_button() if self.link_to_import_schema: self.buttonBox.addButton(self.BUTTON_NAME_GO_TO_CREATE_STRUCTURE, QDialogButtonBox.AcceptRole).setStyleSheet("color: #aa2222;") self.buttonBox.addButton(self.BUTTON_NAME_IMPORT_DATA, QDialogButtonBox.AcceptRole) return self.progress_bar.show() self.disable() self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() self._connect_ili2db_signals(ili2db) self.save_configuration(configuration) res, msg = ili2db.import_data(self.db, configuration) self._disconnect_ili2db_signals(ili2db) self._running_tool = False self.progress_bar.setValue(25) if res: self.buttonBox.clear() self.buttonBox.setEnabled(True) self.buttonBox.addButton(QDialogButtonBox.Close) self.progress_bar.setValue(100) message_type = Qgis.Success if res else Qgis.Warning self.show_message(msg, message_type)
def accept(self): """ This is called when the user has clicked on the "OK" button to create the chart.""" if self.layerComboBox.count() == 0: return self.readChartParams() uniqueCustomFields = [] if self.selectedRadialUnit == 5 or self.selectedCircleUnit == 5: if self.customFieldCol == -1: self.iface.messageBar().pushMessage( "", "Custom Category Filed cannot be selected because none is selected", level=Qgis.Warning, duration=3) return uniqueCustomFields = self.selectedLayer.uniqueValues( self.customFieldCol) if len(uniqueCustomFields) > 40: # We have too many categories self.iface.messageBar().pushMessage( "", "There are too many custom categories for a chart", level=Qgis.Warning, duration=3) return folder = askForFolder(self) if not folder: return # Set aside some space to accumulate the statistics data = AutoDict() rvlist = AutoDict() cvlist = AutoDict() request = QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry) isdt = self.dtRadioButton.isChecked() attributes = [] if isdt: attributes.append(self.selectedDateTimeCol) else: attributes.extend([self.selectedDateCol, self.selectedTimeCol]) if self.customFieldCol != -1: attributes.append(self.customFieldCol) request.setSubsetOfAttributes(attributes) if isdt: col1 = self.selectedDateTimeCol col2 = self.selectedDateTimeCol else: col1 = self.selectedDateCol col2 = self.selectedTimeCol # Iterate through each feature and parse and process the date/time values iter = self.selectedLayer.getFeatures(request) for f in iter: try: if self.selectedRadialUnit == 5: rv = f[self.customFieldCol] if rv == None: continue else: rv = self.parseDateTimeValues(self.selectedRadialUnit, f[col1], f[col2]) if self.selectedCircleUnit == 5: cv = f[self.customFieldCol] if cv == None: continue else: cv = self.parseDateTimeValues(self.selectedCircleUnit, f[col1], f[col2]) except: continue rvlist[rv] += 1 cvlist[cv] += 1 data[rv][cv] += 1 if not any(cvlist) or not any(rvlist): self.iface.messageBar().pushMessage("", "Valid dates were not found", level=Qgis.Warning, duration=3) return rvrange, segCnt, rvunits = self.getUnitStr(rvlist, self.selectedRadialUnit) cvrange, bandCnt, cvunits = self.getUnitStr(cvlist, self.selectedCircleUnit) if rvunits is None or cvunits is None: self.iface.messageBar().pushMessage( "", "There is too large of a year range to create chart", level=Qgis.Warning, duration=3) return # Create the web page with all the JavaScript variables datastr = self.formatData(data, rvrange, cvrange) chartSize = self.chartInnerRadius * 2 + ( bandCnt + 1) * 2 * self.chartBandHeight + 10 # 10 is additional margin style = (".legendContainer {{\n" " height: {};\n" "}}\n" ".legend svg {{\n" " width: {}px;\n" " height: {}px;\n" "}}\n" "#chart svg {{\n" " height: {}px;\n" " width: {}px;\n" "}}\n").format(chartSize, self.legendBoxWidth, self.legendHeight, chartSize, chartSize) script = [] script.append('var segHeight={};'.format(self.chartBandHeight)) script.append('var segCnt={};'.format(segCnt)) script.append('var bandCnt={};'.format(bandCnt)) script.append('var segLabels={};'.format(rvunits)) script.append('var bandLabels={};'.format(cvunits)) script.append('var innerRadius={};'.format(self.chartInnerRadius)) script.append('var edata=[{}];'.format(datastr)) script.append('var startColor="{}";'.format(self.beginningColor)) script.append('var endColor="{}";'.format(self.endingColor)) script.append('var noDataColor="{}";'.format(self.noDataColor)) rl = '' if self.showRadialLabels: rl = '\n\t.segmentLabels(segLabels)' bl = '' if self.showBandLabels: bl = '\n\t.radialLabels(bandLabels)' ll = '' if self.showLegend: ll = '\n\t.legDivId("legend")\n\t.legendSettings({{width: {}, height: {}, legBlockWidth: {}}})\n\t.data(edata)\n'.format( self.legendBoxWidth, self.legendHeight, self.legendWidth) script.append( 'var chart = circularHeatChart()\n\t.range([startColor,endColor])\n\t.nullColor(noDataColor)\n\t.segmentHeight(segHeight)\n\t.innerRadius(innerRadius)\n\t.numSegments(segCnt){}{}{};' .format(rl, bl, ll)) script.append( 'd3.select(\'#chart\')\n\t.selectAll(\'svg\')\n\t.data([edata])\n\t.enter()\n\t.append(\'svg\')\n\t.call(chart);' ) if self.showDataValues: script.append( 'd3.selectAll("#chart path").on(\'mouseover\', function() {\n\tvar d = d3.select(this).data();\n\td3.select("#info").text(\'' + self.dataValueLabel + ' \' + d);\n});') if self.showLegend: script.append('d3.select("#legendTitle").html("' + str(self.legendEdit.text()).replace('"', '\\"') + '");\n') values = { "@TITLE@": self.chartTitle, "@STYLE@": style, "@SCRIPT@": '\n'.join(script) } template = os.path.join(os.path.dirname(__file__), "templates", "index.html") html = replaceInTemplate(template, values) filename = os.path.join(folder, "index.html") try: fout = open(filename, 'w') except: self.iface.messageBar().pushMessage("", "Error opening output file", level=Qgis.Critical, duration=3) return fout.write(html) fout.close() #Copy over the d3 libraries copyfile(os.path.join(os.path.dirname(__file__), "d3", "d3.min.js"), os.path.join(folder, "d3.min.js")) copyfile( os.path.join(os.path.dirname(__file__), "d3", "circularHeatChart.js"), os.path.join(folder, "circularHeatChart.js")) # open the web browser url = QUrl.fromLocalFile(filename).toString() webbrowser.open(url, new=2) # new=2 is a new tab if possible QMessageBox().information(self, "Date Time Heatmap", "Chart has been created")
def accepted(self): """ We start checking the document repository configuration and only allow to continue if we have a valid repo or if the repo won't be used. Then, check if connection to DB/schema is valid, if not, block the dialog. If valid, check it complies with LADM. If not, block the dialog. If it complies, we have two options: To emit db_connection changed or not. Finally, we store options in QSettings. """ res_doc_repo, msg_doc_repo = self.check_document_repository_before_saving_settings( ) if not res_doc_repo: self.show_message(msg_doc_repo, Qgis.Warning, 0) return # Do not close the dialog ladm_col_schema = False db = self._get_db_connector_from_gui() test_level = EnumTestLevel.DB_SCHEMA if self._action_type == EnumDbActionType.SCHEMA_IMPORT: # Limit the validation (used in GeoPackage) test_level |= EnumTestLevel.SCHEMA_IMPORT res, code, msg = db.test_connection( test_level ) # No need to pass required_models, we don't test that much if res: if self._action_type != EnumDbActionType.SCHEMA_IMPORT: # Only check LADM-schema if we are not in an SCHEMA IMPORT. # We know in an SCHEMA IMPORT, at this point the schema is still not LADM. ladm_col_schema, code, msg = db.test_connection( EnumTestLevel.LADM, required_models=self._required_models) if not ladm_col_schema and self._action_type != EnumDbActionType.SCHEMA_IMPORT: if self._blocking_mode: self.show_message(msg, Qgis.Warning) return # Do not close the dialog else: if self._blocking_mode: self.show_message(msg, Qgis.Warning) return # Do not close the dialog # Connection is valid and complies with LADM current_db_engine = self.cbo_db_engine.currentData() if self._lst_panel[current_db_engine].state_changed( ) or self.init_db_engine != current_db_engine: # Emit db_connection_changed if self._db is not None: self._db.close_connection() self._db = db # Update db connect with new db conn self.conn_manager.set_db_connector_for_source( self._db, self.db_source) # Emmit signal when db source changes self.db_connection_changed.emit(self._db, ladm_col_schema, self.db_source) self.logger.debug( __name__, "Settings dialog emitted a db_connection_changed.") if not ladm_col_schema and self._action_type == EnumDbActionType.CONFIG: msg_box = QMessageBox(self) msg_box.setIcon(QMessageBox.Question) msg_box.setText( QCoreApplication.translate( "SettingsDialog", "No LADM-COL DB has been configured! You'll continue with limited functionality until you configure a LADM-COL DB.\n\nDo you want to go to 'Create LADM-COL structure' dialog?" )) msg_box.setWindowTitle( QCoreApplication.translate("SettingsDialog", "Important")) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.Ignore) msg_box.setDefaultButton(QMessageBox.Ignore) msg_box.button(QMessageBox.Yes).setText( QCoreApplication.translate("SettingsDialog", "Yes, go to create structure")) msg_box.button(QMessageBox.Ignore).setText( QCoreApplication.translate("SettingsDialog", "No, I'll do it later")) reply = msg_box.exec_() if reply == QMessageBox.Yes: self._open_dlg_import_schema = True # We will open it when we've closed this Settings dialog # If active role is changed (a check and confirmation may be needed), refresh the GUI # Note: Better to leave this check as the last one in the accepted() method. selected_role = self.get_selected_role() if self.roles.get_active_role() != selected_role: b_change_role = True if STSession().is_user_logged(): reply = QMessageBox.question( self.parent, QCoreApplication.translate("SettingsDialog", "Warning"), QCoreApplication.translate( "SettingsDialog", "You have a ST connection opened and you want to change your role.\nIf you confirm that you want to change your role, you'll be logged out from the ST.\n\nDo you really want to change your role?" ), QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel) if reply == QMessageBox.Yes: STSession().logout() elif reply == QMessageBox.Cancel: # No need to switch back selected role, the Settings Dialog gets it from role registry b_change_role = False if b_change_role: self.logger.info( __name__, "The active role has changed from '{}' to '{}'.".format( self.roles.get_active_role(), selected_role)) self.roles.set_active_role( selected_role ) # Emits signal that refreshed the plugin for this role self.save_settings(db) QDialog.accept(self) self.close() if self._open_dlg_import_schema: # After Settings dialog has been closed, we could call Import Schema depending on user's answer above self.open_dlg_import_schema.emit(Context()) self.logger.debug( __name__, "Settings dialog emitted a show Import Schema dialog.")
def popFatalErrorBox(self, error_msg): msgBox = QMessageBox() msgBox.setWindowTitle("Error") msgBox.setText(error_msg) msgBox.exec_()
def getPredio(self): url = self.CFG.url_BC_getPredios cve = self.dockwidget.leReg.text() + self.dockwidget.leManz.text() + self.dockwidget.leLote.text() + self.dockwidget.leCondo.text() if self.dockwidget.leReg.text() == '' and self.dockwidget.leManz.text() == '' and self.dockwidget.leLote.text() == '' and self.dockwidget.leCondo.text() == '': self.UTI.mostrarAlerta("Llene los campos requeridos", QMessageBox().Critical, "Busqueda de predio por cve") return print(f"cve:{cve}") try: headers = {'Content-Type': 'application/json', 'Authorization': self.UTI.obtenerToken()} respuesta = requests.get(url + cve, headers=headers) except requests.exceptions.RequestException: self.UTI.mostrarAlerta("Error de servidor loc2", QMessageBox().Critical, "Busqueda de predio por cve") print('ERROR: BCP0000') if respuesta.status_code == 200: data = respuesta.content else: self.UTI.mostrarAlerta('Error en peticion:\n' + respuesta.text, QMessageBox().Critical, "Busqueda de predio por cve") print('ERROR: BCP0001') res = json.loads(data.decode('utf-8')) print(res) xPredG = QSettings().value('xPredGeom') self.xPredGeom = QgsProject.instance().mapLayer(xPredG) if self.xPredGeom is None: self.UTI.mostrarAlerta('No existe la capa ' + str(xPredG), QMessageBox().Critical, 'Cargar capas') return print(self.xPredGeom.name()) srid = QSettings().value("srid") print(srid) inSpatialRef = osr.SpatialReference() inSpatialRef.ImportFromEPSG(int(srid)) outSpatialRef = osr.SpatialReference() outSpatialRef.ImportFromEPSG(int(srid)) coordTrans = osr.CoordinateTransformation(inSpatialRef, outSpatialRef) if not bool(res): self.UTI.mostrarAlerta("Error de servidor pintcap", QMessageBox().Critical, "Cargar capa de consulta") print('ERROR: BCP0002') # Obtenemos todos los atributos del JSON if res['features'] == []: return if res['features'] == None: self.UTI.mostrarAlerta("El documento no se genero, intente de nuevo", QMessageBox().Critical, "Cargar capa de consulta") else: varKeys = res['features'][0]['properties'] self.datosPredio = varKeys keys = list(varKeys.keys()) properties = [] geoms = [] for feature in res['features']: geom = feature['geometry'] property = feature['properties'] geom = json.dumps(geom) geometry = ogr.CreateGeometryFromJson(geom) geometry.Transform(coordTrans) geoms.append(geometry.ExportToWkt()) l = [] for i in range(0, len(keys)): l.append(property[keys[i]]) properties.append(l) prov = self.xPredGeom.dataProvider() feats = [QgsFeature() for i in range(len(geoms))] parsed_geoms = [] for i, feat in enumerate(feats): feat.setAttributes(properties[i]) parse_geom = QgsGeometry.fromWkt(geoms[i]) feat.setGeometry(parse_geom) parsed_geoms.append(parse_geom) prov.addFeatures(feats) geometria = parsed_geoms[0] for i in range(1, len(parsed_geoms)): geometria = geometria.combine(geometria[i]) bbox = geometria.boundingBox() self.iface.mapCanvas().setExtent(bbox) self.iface.mapCanvas().refresh() #if nombreCapa == 'predios.geom': # self.cargarPrediosEnComboDividir(feats) self.xPredGeom.triggerRepaint()
def accepted(self): configuration = self.updated_configuration() if not self.xtf_file_line_edit.validator().validate(configuration.xtffile, 0)[0] == QValidator.Acceptable: self.txtStdout.setText( self.tr('Please set a valid INTERLIS XTF file before exporting data.')) self.xtf_file_line_edit.setFocus() return if not configuration.iliexportmodels: self.txtStdout.setText( self.tr('Please set a model before exporting data.')) self.export_models_view.setFocus() return db_id = self.type_combo_box.currentData() res, message = self._lst_panel[db_id].is_valid() if not res: self.txtStdout.setText(message) return # If xtf browser was opened and the file exists, the user already chose # to overwrite the file if os.path.isfile(self.xtf_file_line_edit.text().strip()) and not self.xtf_browser_was_opened: self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Warning) self.msg.setText(self.tr("{filename} already exists.\nDo you want to replace it?").format(filename=os.path.basename(self.xtf_file_line_edit.text().strip()))) self.msg.setWindowTitle(self.tr("Save in XTF Transfer File")) self.msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box = self.msg.exec_() if msg_box == QMessageBox.No: return with OverrideCursor(Qt.WaitCursor): self.progress_bar.show() self.progress_bar.setValue(0) self.disable() self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() exporter = iliexporter.Exporter() exporter.tool = self.type_combo_box.currentData() exporter.configuration = configuration self.save_configuration(configuration) exporter.stdout.connect(self.print_info) exporter.stderr.connect(self.on_stderr) exporter.process_started.connect(self.on_process_started) exporter.process_finished.connect(self.on_process_finished) self.progress_bar.setValue(25) try: if exporter.run() != iliexporter.Exporter.SUCCESS: self.enable() self.progress_bar.hide() return except JavaNotFoundError as e: self.txtStdout.setTextColor(QColor('#000000')) self.txtStdout.clear() self.txtStdout.setText(e.error_string) self.enable() self.progress_bar.hide() return self.buttonBox.clear() self.buttonBox.setEnabled(True) self.buttonBox.addButton(QDialogButtonBox.Close) self.progress_bar.setValue(100)
def installFromZipFile(self, filePath): if not os.path.isfile(filePath): return settings = QgsSettings() settings.setValue(settingsGroup + '/lastZipDirectory', QFileInfo(filePath).absoluteDir().absolutePath()) pluginName = None with zipfile.ZipFile(filePath, 'r') as zf: # search for metadata.txt. In case of multiple files, we can assume that # the shortest path relates <pluginname>/metadata.txt metadatafiles = sorted(f for f in zf.namelist() if f.endswith('metadata.txt')) if len(metadatafiles) > 0: pluginName = os.path.split(metadatafiles[0])[0] pluginFileName = os.path.splitext(os.path.basename(filePath))[0] if not pluginName: msg_box = QMessageBox() msg_box.setIcon(QMessageBox.Warning) msg_box.setWindowTitle( self.tr("QGIS Python Install from ZIP Plugin Installer")) msg_box.setText( self. tr("The Zip file is not a valid QGIS python plugin. No root folder was found inside." )) msg_box.setStandardButtons(QMessageBox.Ok) more_info_btn = msg_box.addButton(self.tr("More Information"), QMessageBox.HelpRole) msg_box.exec() if msg_box.clickedButton() == more_info_btn: QgsHelp.openHelp( "plugins/plugins.html#the-install-from-zip-tab") return pluginsDirectory = qgis.utils.home_plugin_path if not QDir(pluginsDirectory).exists(): QDir().mkpath(pluginsDirectory) pluginDirectory = QDir.cleanPath( os.path.join(pluginsDirectory, pluginName)) # If the target directory already exists as a link, # remove the link without resolving QFile(pluginDirectory).remove() password = None infoString = None success = False keepTrying = True while keepTrying: try: # Test extraction. If fails, then exception will be raised and no removing occurs unzip(filePath, pluginsDirectory, password) # Removing old plugin files if exist removeDir(pluginDirectory) # Extract new files unzip(filePath, pluginsDirectory, password) keepTrying = False success = True except Exception as e: success = False if 'password' in str(e): infoString = self.tr('Aborted by user') if 'Bad password' in str(e): msg = self.tr( 'Wrong password. Please enter a correct password to the zip file.' ) else: msg = self.tr( 'The zip file is encrypted. Please enter password.' ) # Display a password dialog with QgsPasswordLineEdit dlg = QDialog() dlg.setWindowTitle(self.tr('Enter password')) buttonBox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal) buttonBox.rejected.connect(dlg.reject) buttonBox.accepted.connect(dlg.accept) lePass = QgsPasswordLineEdit() layout = QVBoxLayout() layout.addWidget(QLabel(msg)) layout.addWidget(lePass) layout.addWidget(buttonBox) dlg.setLayout(layout) keepTrying = dlg.exec_() password = lePass.text() else: infoString = self.tr( "Failed to unzip the plugin package\n{}.\nProbably it is broken" .format(filePath)) keepTrying = False if success: with OverrideCursor(Qt.WaitCursor): updateAvailablePlugins() self.processDependencies(pluginName) loadPlugin(pluginName) plugins.getAllInstalled() plugins.rebuild() if settings.contains('/PythonPlugins/' + pluginName): # Plugin was available? if settings.value('/PythonPlugins/' + pluginName, False, bool): # Plugin was also active? reloadPlugin( pluginName ) # unloadPlugin + loadPlugin + startPlugin else: unloadPlugin(pluginName) loadPlugin(pluginName) else: if startPlugin(pluginName): settings.setValue('/PythonPlugins/' + pluginName, True) self.exportPluginsToManager() msg = "<b>%s</b>" % self.tr("Plugin installed successfully") else: msg = "<b>%s:</b> %s" % (self.tr("Plugin installation failed"), infoString) level = Qgis.Info if success else Qgis.Critical iface.pluginManagerInterface().pushMessage(msg, level)
def show_error_message(self, message): # Error Message Box msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText(message) msg.exec_()