def getTranslate(namePlugin, nameDir=None): if nameDir is None: nameDir = namePlugin pluginPath = os.path.join('python', 'plugins', nameDir) userPath = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() userPluginPath = os.path.join(userPath, pluginPath) systemPath = QgsApplication.prefixPath() systemPluginPath = os.path.join(systemPath, pluginPath) overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool) localeFullName = QLocale.system().name() if not overrideLocale else QSettings().value('locale/userLocale', '') qmPathFile = os.path.join('i18n', '{0}_{1}.qm'.format(namePlugin, localeFullName)) pp = userPluginPath if QFileInfo(userPluginPath).exists() else systemPluginPath translationFile = os.path.join(pp, qmPathFile) if QFileInfo(translationFile).exists(): translator = QTranslator() translator.load(translationFile) QCoreApplication.installTranslator(translator) QgsApplication.messageLog().logMessage(('Installed translation file {}'.format(translationFile)), 'Midvatten', level=Qgis.Info) return translator else: QgsApplication.messageLog().logMessage( ("translationFile {} didn't exist, no translation file installed!".format(translationFile)), 'Midvatten', level=Qgis.Info)
def testBlocker(self): app_log = QgsApplication.messageLog() spy = QSignalSpy(app_log.messageReceived) spy_received = QSignalSpy(app_log.messageReceived[bool]) QgsMessageLog.logMessage('test', 'tag', Qgis.Warning, notifyUser=True) self.assertEqual(len(spy), 1) self.assertEqual(spy[-1], ['test', 'tag', Qgis.Warning]) self.assertEqual(len(spy_received), 1) # block notifications b = QgsMessageLogNotifyBlocker() QgsMessageLog.logMessage('test', 'tag', Qgis.Warning, notifyUser=True) self.assertEqual(len(spy), 2) # should not be blocked self.assertEqual(len(spy_received), 1) # should be blocked # another blocker b2 = QgsMessageLogNotifyBlocker() QgsMessageLog.logMessage('test', 'tag', Qgis.Warning, notifyUser=True) self.assertEqual(len(spy), 3) # should not be blocked self.assertEqual(len(spy_received), 1) # should be blocked del b # still blocked because of b2 QgsMessageLog.logMessage('test', 'tag', Qgis.Warning, notifyUser=True) self.assertEqual(len(spy), 4) # should not be blocked self.assertEqual(len(spy_received), 1) # should be blocked del b2 # not blocked QgsMessageLog.logMessage('test', 'tag', Qgis.Warning, notifyUser=True) self.assertEqual(len(spy), 5) # should not be blocked self.assertEqual(len(spy_received), 2) # should not be blocked
def log(bar_msg=None, log_msg=None, duration=10, messagebar_level=Qgis.Info, log_level=Qgis.Info, button=True): if qgis.utils.iface is None: return None if bar_msg is not None: widget = qgis.utils.iface.messageBar().createMessage(returnunicode(bar_msg)) log_button = QPushButton(QCoreApplication.translate('MessagebarAndLog', "View message log"), pressed=show_message_log) if log_msg is not None and button: widget.layout().addWidget(log_button) qgis.utils.iface.messageBar().pushWidget(widget, level=messagebar_level, duration=duration) #This part can be used to push message to an additional messagebar, but dialogs closes after the timer if hasattr(qgis.utils.iface, 'optional_bar'): try: qgis.utils.iface.optional_bar.pushWidget(widget, level=messagebar_level, duration=duration) except: pass QgsApplication.messageLog().logMessage(returnunicode(bar_msg), 'Midvatten', level=log_level) if log_msg is not None: QgsApplication.messageLog().logMessage(returnunicode(log_msg), 'Midvatten', level=log_level)
def testMembers(self): self.assertTrue(QgsApplication.actionScopeRegistry()) # self.assertTrue(QgsApplication.annotationRegistry()) NOT AVAILABLE IN BINDINGS self.assertTrue(QgsApplication.colorSchemeRegistry()) self.assertTrue(QgsApplication.fieldFormatterRegistry()) self.assertTrue(QgsApplication.gpsConnectionRegistry()) self.assertTrue(QgsApplication.messageLog()) self.assertTrue(QgsApplication.paintEffectRegistry()) self.assertTrue(QgsApplication.pluginLayerRegistry()) self.assertTrue(QgsApplication.processingRegistry()) self.assertTrue(QgsApplication.profiler()) # self.assertTrue(QgsApplication.rasterRendererRegistry()) NOT AVAILABLE IN BINDINGS self.assertTrue(QgsApplication.rendererRegistry()) self.assertTrue(QgsApplication.svgCache()) self.assertTrue(QgsApplication.symbolLayerRegistry()) self.assertTrue(QgsApplication.taskManager())
def install_logger_hook( verbose: bool=False ) -> None: """ Install message log hook """ from qgis.core import Qgis, QgsApplication, QgsMessageLog # Add a hook to qgis message log def writelogmessage(message, tag, level): arg = '{}: {}'.format( tag, message ) if level == Qgis.Warning: LOGGER.warning(arg) elif level == Qgis.Critical: LOGGER.error(arg) elif verbose: # Qgis is somehow very noisy # log only if verbose is set LOGGER.info(arg) messageLog = QgsApplication.messageLog() messageLog.messageReceived.connect( writelogmessage )
def install_message_hook( verbose=False ): """ Install message log hook """ from qgis.core import Qgis, QgsApplication, QgsMessageLog # Add a hook to qgis message log def writelogmessage(message, tag, level): arg = '{}: {}'.format( tag, message ) if level == Qgis.Warning: print("Warning: %s" % arg, file=sys.stderr) elif level == Qgis.Critical: print("Error: %s" % arg, file=sys.stderr) elif verbose: # Qgis is somehow very noisy # log only if verbose is set print(arg, file=sys.stderr) messageLog = QgsApplication.messageLog() messageLog.messageReceived.connect( writelogmessage )
def testSignals(self): app_log = QgsApplication.messageLog() # signals should be emitted by application log app_spy = QSignalSpy(app_log.messageReceived) app_spy_received = QSignalSpy(app_log.messageReceived[bool]) QgsMessageLog.logMessage('test', 'tag', Qgis.Info, notifyUser=True) self.assertEqual(len(app_spy), 1) self.assertEqual(app_spy[-1], ['test', 'tag', Qgis.Info]) # info message, so messageReceived(bool) should not be emitted self.assertEqual(len(app_spy_received), 0) QgsMessageLog.logMessage('test', 'tag', Qgis.Warning, notifyUser=True) self.assertEqual(len(app_spy), 2) self.assertEqual(app_spy[-1], ['test', 'tag', Qgis.Warning]) # warning message, so messageReceived(bool) should be emitted self.assertEqual(len(app_spy_received), 1) QgsMessageLog.logMessage('test', 'tag', Qgis.Warning, notifyUser=False) self.assertEqual(len(app_spy), 3) # notifyUser was False self.assertEqual(len(app_spy_received), 1)
def parseresponse(self, response): # Trim callback result = response[len(self.config['callback']) + 1: -1] try: obj = json.loads(result) except: QgsApplication.messageLog().logMessage( 'Invalid JSON response from server: ' + result, __package__ ) # Check if we have an auth error if "User not authorized" in response: title = self.tr(u'Afvist af Kortforsyningen') message = self.tr(u'Manglende eller ukorrekt token til Kortforsyningen.') button_text = self.tr(u'Åbn settings') widget = self.qgisIface.messageBar().createMessage(title, message) button = QPushButton(widget) button.setText(button_text) button.pressed.connect(lambda : self.qgisIface.showOptionsDialog(currentPage='geosearchOptions')) widget.layout().addWidget(button) self.qgisIface.messageBar().pushWidget(widget, level=Qgis.Warning, duration=15) return None if 'status' not in obj: QgsApplication.messageLog().logMessage( 'Unexpected result from server: ' + result, __package__ ) return None if not obj['status'] == 'OK': QgsApplication.messageLog().logMessage( 'Server reported an error: ' + obj['message'], __package__ ) return None if "data" not in obj: return None data = obj['data'] if not data: return [(self.tr("Ingen resultater"),None)] # Make tuple with ("text", object) for each result return [(e['presentationString'], e) for e in data]
def __enter__(self): QgsApplication.messageLog().messageReceived.connect(self.logMessage) return self
def __init__(self, iface, db, qgis_utils, parent=None): QWizard.__init__(self, parent) self.setupUi(self) self.iface = iface self.log = QgsApplication.messageLog() self._db = db self.qgis_utils = qgis_utils self.help_strings = HelpStrings() self.insert_features_to_layer = InsertFeaturesToLayer() self.target_layer = None # Auxiliary data to set nonlinear next pages self.pages = [self.wizardPage1, self.wizardPage2, self.wizardPage3] self.dict_pages_ids = { self.pages[idx]: pid for idx, pid in enumerate(self.pageIds()) } # Set connections self.btn_browse_file.clicked.connect( make_file_selector(self.txt_file_path, file_filter=QCoreApplication.translate( "CreatePointsCadastreWizard", 'CSV File (*.csv *.txt)'))) self.txt_file_path.textChanged.connect(self.file_path_changed) self.crsSelector.crsChanged.connect(self.crs_changed) self.crs = QgsCoordinateReferenceSystem() self.txt_delimiter.textChanged.connect(self.fill_long_lat_combos) self.known_delimiters = [{ 'name': ';', 'value': ';' }, { 'name': ',', 'value': ',' }, { 'name': 'tab', 'value': '\t' }, { 'name': 'space', 'value': ' ' }, { 'name': '|', 'value': '|' }, { 'name': '~', 'value': '~' }, { 'name': 'Other', 'value': '' }] self.cbo_delimiter.addItems( [item['name'] for item in self.known_delimiters]) self.cbo_delimiter.currentTextChanged.connect(self.separator_changed) self.restore_settings() self.txt_file_path.textChanged.emit(self.txt_file_path.text()) self.rad_boundary_point.toggled.connect(self.point_option_changed) self.rad_control_point.toggled.connect(self.point_option_changed) self.rad_csv.toggled.connect(self.adjust_page_2_controls) self.point_option_changed() # Initialize it self.button(QWizard.FinishButton).clicked.connect(self.finished_dialog) self.currentIdChanged.connect(self.current_page_changed) self.mMapLayerComboBox.setFilters(QgsMapLayerProxyModel.PointLayer) self.txt_help_page_2.setHtml( self.help_strings.WIZ_ADD_POINTS_CADASTRE_PAGE_2_OPTION_CSV) self.wizardPage2.setButtonText( QWizard.FinishButton, QCoreApplication.translate("CreatePointsCadastreWizard", "Import")) self.txt_help_page_3.setHtml( self.help_strings.WIZ_ADD_POINTS_CADASTRE_PAGE_3_OPTION_CSV) self.txt_help_page_3.anchorClicked.connect(self.save_template) self.button(QWizard.HelpButton).clicked.connect(self.show_help) # Set MessageBar for QWizard self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.setLayout(QGridLayout()) self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)
def test_makeKeyTokens_(self): # see http://www.w3.org/TR/REC-xml/#d0e804 for a list of valid characters invalidTokens = [] validTokens = [] # all test tokens will be generated by prepending or inserting characters to this token validBase = "valid" # some invalid characters, not allowed anywhere in a token # note that '/' must not be added here because it is taken as a separator by makeKeyTokens_() invalidChars = "+*,;<>|!$%()=?#\x01" # generate the characters that are allowed at the start of a token (and at every other position) validStartChars = ":_" charRanges = [ (ord('a'), ord('z')), (ord('A'), ord('Z')), (0x00F8, 0x02FF), (0x0370, 0x037D), (0x037F, 0x1FFF), (0x200C, 0x200D), (0x2070, 0x218F), (0x2C00, 0x2FEF), (0x3001, 0xD7FF), (0xF900, 0xFDCF), (0xFDF0, 0xFFFD), # (0x10000, 0xEFFFF), while actually valid, these are not yet accepted by makeKeyTokens_() ] for r in charRanges: for c in range(r[0], r[1]): validStartChars += chr(c) # generate the characters that are only allowed inside a token, not at the start validInlineChars = "-.\xB7" charRanges = [ (ord('0'), ord('9')), (0x0300, 0x036F), (0x203F, 0x2040), ] for r in charRanges: for c in range(r[0], r[1]): validInlineChars += chr(c) # test forbidden start characters for c in invalidChars + validInlineChars: invalidTokens.append(c + validBase) # test forbidden inline characters for c in invalidChars: invalidTokens.append(validBase[:4] + c + validBase[4:]) # test each allowed start character for c in validStartChars: validTokens.append(c + validBase) # test each allowed inline character for c in validInlineChars: validTokens.append(validBase[:4] + c + validBase[4:]) logger = QgsApplication.messageLog() logger.messageReceived.connect(self.catchMessage) prj = QgsProject.instance() for token in validTokens: self.messageCaught = False prj.readEntry("test", token) myMessage = "valid token '%s' not accepted" % (token) assert not self.messageCaught, myMessage for token in invalidTokens: self.messageCaught = False prj.readEntry("test", token) myMessage = "invalid token '%s' accepted" % (token) assert self.messageCaught, myMessage logger.messageReceived.disconnect(self.catchMessage)
def __init__(self, iface, parent=None): super(GridExtractDialog, self).__init__(parent) # Set up the user interface from Designer. self.setupUi(self) self.iface = iface self.DISP_TEMP_LAYERS = read_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS', bool) self.DEBUG = config.get_debug_mode() self.layers_df = None self.pixel_size = ['0', 'm', ''] # Catch and redirect python errors directed at the log messages python error tab. QgsApplication.messageLog().messageReceived.connect(errorCatcher) if not os.path.exists(TEMPDIR): os.mkdir(TEMPDIR) # Setup for validation messagebar on gui----------------------------- self.messageBar = QgsMessageBar( self) # leave this message bar for bailouts self.validationLayout = QtWidgets.QFormLayout( self) # new layout to gui if isinstance(self.layout(), QtWidgets.QFormLayout): # create a validation layout so multiple messages can be added and cleaned up. self.layout().insertRow(0, self.validationLayout) self.layout().insertRow(0, self.messageBar) else: self.layout().insertWidget( 0, self.messageBar) # for use with Vertical/horizontal layout box # GUI Runtime Customisation ----------------------------------------------- self.mcboPointsLayer.setFilters(QgsMapLayerProxyModel.PointLayer) self.mcboPointsLayer.setExcludedProviders(['wms']) self.mcboRasterLayer.setFilters(QgsMapLayerProxyModel.RasterLayer) self.mcboRasterLayer.setExcludedProviders(['wms']) self.setMapLayers() self.setWindowIcon( QtGui.QIcon(':/plugins/pat/icons/icon_gridExtract.svg')) self.chkgrpStatistics.setExclusive(False) self.tabList.setColumnCount(2) self.tabList.setHorizontalHeaderItem(0, QTableWidgetItem("ID")) self.tabList.setHorizontalHeaderItem(1, QTableWidgetItem("0 Raster(s)")) self.tabList.horizontalHeader().setSectionResizeMode( QtWidgets.QHeaderView.Stretch) self.tabList.hideColumn(0) # don't need to display the unique layer ID self.pixel_size = ['0', 'm', ''] self.statsMapping = { 'mean': np.nanmean, 'minimum': np.nanmin, 'maximum': np.nanmax, 'standard deviation': np.nanstd, 'coefficient of variation': raster_ops.nancv, 'pixel count': raster_ops.pixelcount, }
def exportStyles(layers, folder, clustered): stylesFolder = os.path.join(folder, "styles") QDir().mkpath(stylesFolder) legendFolder = os.path.join(stylesFolder, "legend") QDir().mkpath(legendFolder) vtStyles = {} mapUnitLayers = [] for count, (layer, cluster) in enumerate(zip(layers, clustered)): sln = safeName(layer.name()) + "_" + unicode(count) if layer.type() != layer.VectorLayer: continue pattern = "" setPattern = "" vts = layer.customProperty("VectorTilesReader/vector_tile_url") labelText = getLabels(layer, folder, sln) defs = "var size = 0;\nvar placement = 'point';" try: renderer = layer.renderer() layer_alpha = layer.opacity() if isinstance(renderer, QgsSingleSymbolRenderer): (style, pattern, setPattern, value, useMapUnits) = singleSymbol(renderer, stylesFolder, layer_alpha, sln, legendFolder, layer) elif isinstance(renderer, QgsCategorizedSymbolRenderer): (style, pattern, setPattern, value, defs, useMapUnits) = categorized(defs, sln, layer, renderer, legendFolder, stylesFolder, layer_alpha) elif isinstance(renderer, QgsGraduatedSymbolRenderer): (style, pattern, setPattern, value, useMapUnits) = graduated(layer, renderer, legendFolder, sln, stylesFolder, layer_alpha) elif isinstance(renderer, QgsRuleBasedRenderer): (style, pattern, setPattern, value, useMapUnits) = ruleBased(renderer, folder, stylesFolder, layer_alpha, sln, layer) else: style = """ var style = [ new ol.style.Style({ text: createTextStyle(feature, resolution, labelText, labelFont, labelFill, placement) })];""" useMapUnits = False if useMapUnits: if vts is None: mapUnitLayers.append(sln) else: mapUnitLayers.append(safeName(vts)) (labelRes, size, face, color) = getLabelFormat(layer) if style != "": geom = TYPE_MAP[layer.wkbType()].replace("Multi", "") style = getStyle(style, cluster, labelRes, labelText, sln, size, face, color, value, geom) else: style = "''" except Exception as e: style = "" QgsApplication.messageLog().logMessage(traceback.format_exc(), "qgis2web", level=Qgis.Critical) if vts is None: path = os.path.join(stylesFolder, sln + "_style.js") with codecs.open(path, "w", "utf-8") as f: f.write('''%(defs)s %(pattern)s var style_%(name)s = %(style)s; %(setPattern)s''' % {"defs": defs, "pattern": pattern, "name": sln, "style": style, "setPattern": setPattern}) elif style != "" and style != "''": new_vtStyle = "if (feature.get('layer') == " new_vtStyle += """'%s' && feature.getGeometry().getType() == '%s'){ return %s(feature, resolution); }""" % ( layer.name(), TYPE_MAP[layer.wkbType()].replace("Multi", ""), style) try: old_vtStyles = vtStyles[vts] new_vtStyles = """%s %s""" % (old_vtStyles, new_vtStyle) except: new_vtStyles = new_vtStyle vtStyles[vts] = new_vtStyles for k, v in vtStyles.items(): styleName = safeName(k) styleString = v path = os.path.join(stylesFolder, styleName + "_style.js") with codecs.open(path, "w", "utf-8") as f: f.write(''' var style_%(name)s = function(feature, resolution) { %(style)s; }''' % {"defs": defs, "pattern": pattern, "name": styleName, "style": styleString, "setPattern": setPattern}) return mapUnitLayers
def __init__(self, iface, db, qgis_utils, parent=None): QDialog.__init__(self) self.setupUi(self) self.iface = iface self.log = QgsApplication.messageLog() self._la_group_party_table = None self._members_table = None self._fraction_table = None self._col_party_layer = None self._db = db self.qgis_utils = qgis_utils self.help_strings = HelpStrings() self.data = {} # {t_id: [display_text, denominator, numerator]} self.current_selected_parties = [] # [t_ids] self.parties_to_group = {} # {t_id: [denominator, numerator]} # Fill combo of types la_group_party_type_table = self.qgis_utils.get_layer( self._db, LA_GROUP_PARTY_TYPE_TABLE, None, True) if la_group_party_type_table is None: self.iface.messageBar().pushMessage( "Asistente LADM_COL", QCoreApplication.translate( "CreateGroupPartyCadastreWizard", "Group Party Type Table couldn't be found... {}").format( self._db.get_description()), Qgis.Warning) return domain_key_index = la_group_party_type_table.fields().indexOf( DOMAIN_KEY_FIELD[self._db.mode]) domain_keys = list( la_group_party_type_table.uniqueValues(domain_key_index)) domain_keys.sort() self.cbo_group_type.addItems(domain_keys) self.txt_search_party.setText("") self.btn_select.setEnabled(False) self.btn_deselect.setEnabled(False) self.tbl_selected_parties.setColumnCount(3) self.tbl_selected_parties.setColumnWidth(0, 140) self.tbl_selected_parties.setColumnWidth(1, 90) self.tbl_selected_parties.setColumnWidth(2, 90) self.tbl_selected_parties.sortItems(0, Qt.AscendingOrder) self.txt_search_party.textEdited.connect(self.search) self.lst_all_parties.itemSelectionChanged.connect( self.selection_changed_all) self.tbl_selected_parties.itemSelectionChanged.connect( self.selection_changed_selected) self.tbl_selected_parties.cellChanged.connect(self.valueEdited) self.btn_select_all.clicked.connect(self.select_all) self.btn_deselect_all.clicked.connect(self.deselect_all) self.btn_select.clicked.connect(self.select) self.btn_deselect.clicked.connect(self.deselect) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.setLayout(QGridLayout()) self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)
def test_makeKeyTokens_(self): # see http://www.w3.org/TR/REC-xml/#d0e804 for a list of valid characters invalidTokens = [] validTokens = [] # all test tokens will be generated by prepending or inserting characters to this token validBase = "valid" # some invalid characters, not allowed anywhere in a token # note that '/' must not be added here because it is taken as a separator by makeKeyTokens_() invalidChars = "+*,;<>|!$%()=?#\x01" # generate the characters that are allowed at the start of a token (and at every other position) validStartChars = ":_" charRanges = [ (ord('a'), ord('z')), (ord('A'), ord('Z')), (0x00F8, 0x02FF), (0x0370, 0x037D), (0x037F, 0x1FFF), (0x200C, 0x200D), (0x2070, 0x218F), (0x2C00, 0x2FEF), (0x3001, 0xD7FF), (0xF900, 0xFDCF), (0xFDF0, 0xFFFD), #(0x10000, 0xEFFFF), while actually valid, these are not yet accepted by makeKeyTokens_() ] for r in charRanges: for c in range(r[0], r[1]): validStartChars += chr(c) # generate the characters that are only allowed inside a token, not at the start validInlineChars = "-.\xB7" charRanges = [ (ord('0'), ord('9')), (0x0300, 0x036F), (0x203F, 0x2040), ] for r in charRanges: for c in range(r[0], r[1]): validInlineChars += chr(c) # test forbidden start characters for c in invalidChars + validInlineChars: invalidTokens.append(c + validBase) # test forbidden inline characters for c in invalidChars: invalidTokens.append(validBase[:4] + c + validBase[4:]) # test each allowed start character for c in validStartChars: validTokens.append(c + validBase) # test each allowed inline character for c in validInlineChars: validTokens.append(validBase[:4] + c + validBase[4:]) logger = QgsApplication.messageLog() logger.messageReceived.connect(self.catchMessage) prj = QgsProject.instance() for token in validTokens: self.messageCaught = False prj.readEntry("test", token) myMessage = "valid token '%s' not accepted" % (token) assert not self.messageCaught, myMessage for token in invalidTokens: self.messageCaught = False prj.readEntry("test", token) myMessage = "invalid token '%s' accepted" % (token) assert self.messageCaught, myMessage logger.messageReceived.disconnect(self.catchMessage)
def __exit__(self, type, value, traceback): QgsApplication.messageLog().messageReceived.disconnect(self.logMessage)
def add_postgres_layer(self, name, host, port, database_name, username, schema, table, geom_col, id_col, ssl, qml_file_path, sql_filter): """ Add the database table in the QGis TOC and apply its associated QML. :param name: The name :type name: str :param host: The hostname :type host: str :param port: Aggregated data separated by "|". The first element is the port, the second is the ssl request specification (e.g. require, allow, disable, prefer) :type port: str :param database_name: The database name :type database_name: str :param username: The username for connecting to the database :type username: str :param schema: The database schema :type schema: str :param table: Aggregated data separated by "|". The first is the table name, the second is the sql filter :type table: str :param geom_col: The geometry column name :type geom_col: str :param id_col: The identifier column name :type id_col: str :param ssl: The SSL type request. Expected one of: require, allow, disable or prefer. :type ssl: str :param qml_file_path: The *.qml file path :type qml_file_path: str :param sql_filter: The SQL where condition :type sql_filter: str """ qgs_logger = QgsApplication.messageLog() qgs_logger.logMessage('addWms: name = {}'.format(name), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: host = {}'.format(host), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: port = {}'.format(port), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage( 'addWms: database_name = {}'.format(database_name), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: username = {}'.format(username), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: schema = {}'.format(schema), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: table = {}'.format(table), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: geom_col = {}'.format(geom_col), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: id_col = {}'.format(id_col), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: ssl = {}'.format(ssl), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: self.session_user = {}'.format( str(self.session_user)), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage( 'addWms: qml_file_path = {}'.format(qml_file_path), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: sql_filter = {}'.format(sql_filter), tag=configuration.LOGGER_TAG, level=Qgis.Info) uri = QgsDataSourceUri() ssl_mode = QgsDataSourceUri.SslAllow if ssl == "require": ssl_mode = QgsDataSourceUri.SslRequire if ssl == "allow": ssl_mode = QgsDataSourceUri.SslAllow if ssl == "disable": ssl_mode = QgsDataSourceUri.SslDisable if ssl == "prefer": ssl_mode = QgsDataSourceUri.SslPrefer # Set the connection uri.setConnection(str(host), str(port), str(database_name), str(self.session_user), str(self.session_password), ssl_mode) # In case the geometry column is not defined ignore as parameter, otherwise set it if str(geom_col) == "": uri.setDataSource(str(schema), str(table), None, sql_filter, str(id_col)) else: uri.setDataSource(str(schema), str(table), str(geom_col), sql_filter, str(id_col)) # Instantiate postgres_layer = QgsVectorLayer(uri.uri(), str(name), 'postgres') # In case the layer is valid, add to the QGis TOC if postgres_layer.isValid(): QgsProject.instance().addMapLayer(postgres_layer) postgres_layer.loadNamedStyle(qml_file_path) else: par = "\nhost: " + str(host)\ + "\nport: " + str(port)\ + "\ndbname: " + str(database_name)\ + "\nuser: "******"\nssl: " + str(ssl)\ + "\nschema: " + str(schema)\ + "\ntable: " + str(table) \ + "\ngeom_col: " + str(geom_col) \ + "\nid_col: " + str(id_col) \ + "\npathQMLFile: " + str(qml_file_path) \ + "\nsqlFilter: " + str(sql_filter) self.show_message( "Attenzione!", "Impossibile aggiungere la tabella " + name + " al progetto.\n" + par)
def __enter__(self): QgsApplication.messageLog().messageReceived.connect(self.logMessage) return self
def exportStyles(layers, folder, clustered): stylesFolder = os.path.join(folder, "styles") QDir().mkpath(stylesFolder) legendFolder = os.path.join(stylesFolder, "legend") QDir().mkpath(legendFolder) vtStyles = {} mapUnitLayers = [] for count, (layer, cluster) in enumerate(zip(layers, clustered)): sln = safeName(layer.name()) + "_" + unicode(count) if layer.type() != layer.VectorLayer: continue pattern = "" setPattern = "" vts = layer.customProperty("VectorTilesReader/vector_tile_url") labelText = getLabels(layer, folder, sln) defs = "var size = 0;\nvar placement = 'point';" try: renderer = layer.renderer() layer_alpha = layer.opacity() if isinstance(renderer, QgsSingleSymbolRenderer): (style, pattern, setPattern, value, useMapUnits) = singleSymbol(renderer, stylesFolder, layer_alpha, sln, legendFolder, layer) elif isinstance(renderer, QgsCategorizedSymbolRenderer): (style, pattern, setPattern, value, defs, useMapUnits) = categorized(defs, sln, layer, renderer, legendFolder, stylesFolder, layer_alpha) elif isinstance(renderer, QgsGraduatedSymbolRenderer): (style, pattern, setPattern, value, useMapUnits) = graduated(layer, renderer, legendFolder, sln, stylesFolder, layer_alpha) elif isinstance(renderer, QgsRuleBasedRenderer): (style, pattern, setPattern, value, useMapUnits) = ruleBased(renderer, folder, stylesFolder, layer_alpha, sln, layer) else: value = "''" style = """ var style = [ new ol.style.Style({ text: createTextStyle(feature, resolution, labelText, labelFont, labelFill, placement, bufferColor, bufferWidth) })];""" useMapUnits = False if useMapUnits: if vts is None: mapUnitLayers.append(sln) else: mapUnitLayers.append(safeName(vts)) (labelRes, size, face, color, bufferColor, bufferWidth) = getLabelFormat(layer) if style != "": geom = TYPE_MAP[layer.wkbType()].replace("Multi", "") style = getStyle(style, cluster, labelRes, labelText, sln, size, face, color, bufferColor, bufferWidth, value, geom) else: style = "''" except Exception as e: style = "" QgsApplication.messageLog().logMessage(traceback.format_exc(), "qgis2web", level=Qgis.Critical) if vts is None: path = os.path.join(stylesFolder, sln + "_style.js") with codecs.open(path, "w", "utf-8") as f: f.write( '''%(defs)s %(pattern)s var style_%(name)s = %(style)s; %(setPattern)s''' % { "defs": defs, "pattern": pattern, "name": sln, "style": style, "setPattern": setPattern }) elif style != "" and style != "''": new_vtStyle = defs new_vtStyle += "if (feature.get('layer') == " new_vtStyle += """'%s' && feature.getGeometry().getType() == '%s'){ return %s(feature, resolution); }""" % (layer.name(), TYPE_MAP[layer.wkbType()].replace("Multi", ""), style) try: old_vtStyles = vtStyles[vts] new_vtStyles = """%s %s""" % (old_vtStyles, new_vtStyle) except: new_vtStyles = new_vtStyle vtStyles[vts] = new_vtStyles for k, v in vtStyles.items(): styleName = safeName(k) styleString = v path = os.path.join(stylesFolder, styleName + "_style.js") with codecs.open(path, "w", "utf-8") as f: f.write( ''' var style_%(name)s = function(feature, resolution) { %(style)s; }''' % { "defs": defs, "pattern": pattern, "name": styleName, "style": styleString, "setPattern": setPattern }) return mapUnitLayers
def __init__(self): QObject.__init__(self) self.log = QgsApplication.messageLog() self.translatable_config_strings = TranslatableConfigStrings()
def __init__(self): QObject.__init__(self) self.log = QgsApplication.messageLog()
def __exit__(self, type, value, traceback): QgsApplication.messageLog().messageReceived.disconnect(self.logMessage)
def addWms(self, wms_name, url, layers, mime_type, epsg_code, protocol): """ # Slot for exposing the same-name function to Javascript. # Adding the WMS to the QGis TOC. :param wms_name: The WMS name to add in TOC as group :type wms_name: str :param url: The WMS URL :type url: str :param layers: The list of the WMS layers to add :type layers: list of str :param mime_type: The image MIME TYPE (e.g. image/png) :type mime_type: str :param epsg_code: The EPSG code (e.g. the number 32632) :type epsg_code: int :param protocol: The protocol (i.e. should be 'ba' for applying basic authentication). Not yet managed. :type protocol: str """ qgs_logger = QgsApplication.messageLog() qgs_logger.logMessage('addWms: wms_name = {}'.format(wms_name), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: url = {}'.format(url), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: layers = {}'.format(layers), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: mime_type = {}'.format(mime_type), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: epsg_code = {}'.format(epsg_code), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('addWms: protocol = {}'.format(protocol), tag=configuration.LOGGER_TAG, level=Qgis.Info) # For storing the URI data uri = QgsDataSourceUri() # Split the host with the request data pieces = url.split("?") if len(pieces) == 1: qgs_logger.logMessage('len(pieces) == 1', tag=configuration.LOGGER_TAG, level=Qgis.Info) elif len(pieces) == 2: qgs_logger.logMessage('len(pieces) == 2', tag=configuration.LOGGER_TAG, level=Qgis.Info) # Overriding the URL url = "{}{}".format(pieces[0], "?") parameters_values = pieces[1].split("=") if len(parameters_values) == 2: qgs_logger.logMessage('len(parameters) == 2', tag=configuration.LOGGER_TAG, level=Qgis.Info) uri.setParam(parameters_values[0], parameters_values[1]) qgs_logger.logMessage('uri.param({}): {}'.format( parameters_values[0], uri.param(parameters_values[0])), tag=configuration.LOGGER_TAG, level=Qgis.Info) else: qgs_logger.logMessage('len(p) != 2', tag=configuration.LOGGER_TAG, level=Qgis.Info) else: qgs_logger.logMessage('len(pieces) > 2 Not yet managed!', tag=configuration.LOGGER_TAG, level=Qgis.Warning) # Setting the URL to the URI uri.setParam("url", url) # Process the layers accordingly if just an element or a list of elements layers_list = [] if "," in layers: layers_list = layers.split(",") else: layers_list.append(layers) # Setting the parameter 'layers' in the URI for val in layers_list: uri.setParam("layers", val) # Setting the other parameters # Styles seems required: https://gis.stackexchange.com/questions/183485/load-wms-with-pyqgis uri.setParam("styles", "") uri.setParam("format", mime_type) uri.setParam("crs", "EPSG:{}".format(epsg_code)) # https://docs.qgis.org/3.4/en/docs/pyqgis_developer_cookbook/loadlayer.html#raster-layers # Ignore GetCoverage URL advertised by GetCapabilities. May be necessary if a server is not configured properly. uri.setParam("IgnoreGetMapUrl", "1") # Adding the parameters for the basic authentication qgs_logger.logMessage('Applying Basic-Authentication', tag=configuration.LOGGER_TAG, level=Qgis.Info) uri.setParam("username", self.session_user) uri.setParam("password", self.session_password) # Logging the parameters for debugging qgs_logger.logMessage('uri.param(url): {}'.format(uri.param("url")), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.param(layers): {}'.format( uri.param("layers")), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.param(format): {}'.format( uri.param("format")), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.param(crs): {}'.format(uri.param("crs")), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.service(): {}'.format(uri.service()), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('encodedUri: {}'.format(str(uri.encodedUri())), tag=configuration.LOGGER_TAG, level=Qgis.Info) qgs_logger.logMessage('uri.uri(): {}'.format(uri.uri()), tag=configuration.LOGGER_TAG, level=Qgis.Info) # Generating the WMS layer wms_layer = QgsRasterLayer(str(uri.encodedUri()), wms_name, 'wms') # If the WMS is correctly generated, add to the QGis TOC if wms_layer.isValid(): QgsProject.instance().addMapLayer(wms_layer) else: qgs_logger.logMessage( 'Impossibile aggiungere il WMS: {}'.format(wms_name), tag=configuration.LOGGER_TAG, level=Qgis.Warning) self.show_message( "Attenzione!", "Impossibile aggiungere il WMS " + wms_name + " al progetto")