def read(self): qsettings = QSettings() value = qsettings.value(self.qname, None) if value is not None: if isinstance(self.value, bool): value = unicode(value).lower() == unicode(True).lower() self.value = value
def chooseOutputFile(self): # get last used dir settings = QSettings() lastUsedDir = settings.value(self.lastUsedVectorDirSettingsKey, ".") # get selected filter selectedFilter = self.cboFileFormat.itemData(self.cboFileFormat.currentIndex()) # ask for a filename filename = QFileDialog.getSaveFileName(self, self.tr("Choose where to save the file"), lastUsedDir, selectedFilter) if filename == "": return filterString = qgis.core.QgsVectorFileWriter.filterForDriver(selectedFilter) ext = filterString[filterString.find('.'):] ext = ext[:ext.find(' ')] if not filename.lower().endswith(ext): filename += ext # store the last used dir settings.setValue(self.lastUsedVectorDirSettingsKey, QFileInfo(filename).filePath()) self.editOutputFile.setText(filename)
def getVectorWriter(self, fields, geomType, crs, options=None): """Returns a suitable writer to which features can be added as a result of the algorithm. Use this to transparently handle output values instead of creating your own method. Executing this method might modify the object, adding additional information to it, so the writer can be later accessed and processed within QGIS. It should be called just once, since a new call might result in previous data being replaced, thus rendering a previously obtained writer useless. @param fields a list of QgsField @param geomType a suitable geometry type, as it would be passed to a QgsVectorFileWriter constructor @param crs the crs of the layer to create @return writer instance of the vector writer class """ if self.encoding is None: settings = QSettings() self.encoding = settings.value('/Processing/encoding', 'System', str) w = VectorWriter(self.value, self.encoding, fields, geomType, crs, options) self.layer = w.layer return w
def showFileSelectionDialog(self): settings = QSettings() text = unicode(self.text.text()) if os.path.isdir(text): path = text elif os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = unicode(settings.value('/Processing/LastInputPath')) else: path = '' ret = QFileDialog.getOpenFileNames(self, self.tr('Open file'), path, self.tr('All files(*.*);;') + self.param.getFileFilter()) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(unicode(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(unicode(f) for f in files)) else: rowdif = len(files) - (self.table.rowCount() - self.row) for i in range(rowdif): self.panel.addRow() for i, f in enumerate(files): self.table.cellWidget(i + self.row, self.col).setText(f)
def processAlgorithm(self, progress): """Here is where the processing itself takes place.""" # The first thing to do is retrieve the values of the parameters # entered by the user inputFilename = self.getParameterValue(self.INPUT_LAYER) output = self.getOutputValue(self.OUTPUT_LAYER) # Input layers vales are always a string with its location. # That string can be converted into a QGIS object (a # QgsVectorLayer in this case) using the # processing.getObjectFromUri() method. vectorLayer = dataobjects.getObjectFromUri(inputFilename) # And now we can process # First we create the output layer. The output value entered by # the user is a string containing a filename, so we can use it # directly settings = QSettings() systemEncoding = settings.value("/UI/encoding", "System") provider = vectorLayer.dataProvider() writer = QgsVectorFileWriter(output, systemEncoding, provider.fields(), provider.geometryType(), provider.crs()) # Now we take the features from input layer and add them to the # output. Method features() returns an iterator, considering the # selection that might exist in layer and the configuration that # indicates should algorithm use only selected features or all # of them features = vector.features(vectorLayer) for f in features: writer.addFeature(f)
def execute(self): settings = QSettings() lastDir = settings.value('Processing/lastModelsDir', '') filename = QFileDialog.getOpenFileName(self.toolbox, self.tr('Open model', 'AddModelFromFileAction'), lastDir, self.tr('Processing model files (*.model *.MODEL)', 'AddModelFromFileAction')) if filename: try: settings.setValue('Processing/lastModelsDir', QFileInfo(filename).absoluteDir().absolutePath()) ModelerAlgorithm.fromFile(filename) except WrongModelException: QMessageBox.warning( self.toolbox, self.tr('Error reading model', 'AddModelFromFileAction'), self.tr('The selected file does not contain a valid model', 'AddModelFromFileAction')) return except: QMessageBox.warning(self.toolbox, self.tr('Error reading model', 'AddModelFromFileAction'), self.tr('Cannot read file', 'AddModelFromFileAction')) return destFilename = os.path.join(ModelerUtils.modelsFolder(), os.path.basename(filename)) shutil.copyfile(filename, destFilename) self.toolbox.updateProvider('model')
def updateSeenPluginsList(self): """ update the list of all seen plugins """ settings = QSettings() seenPlugins = settings.value(seenPluginGroup, self.mPlugins.keys(), type=unicode) for i in self.mPlugins.keys(): if seenPlugins.count(i) == 0: seenPlugins += [i] settings.setValue(seenPluginGroup, seenPlugins)
def setLastUsedDir(filePath): settings = QSettings() fileInfo = QFileInfo(filePath) if fileInfo.isDir(): dirPath = fileInfo.filePath() else: dirPath = fileInfo.path() settings.setValue("/GdalTools/lastUsedDir", dirPath)
def markNews(self): """ mark all new plugins as new """ settings = QSettings() seenPlugins = settings.value(seenPluginGroup, self.mPlugins.keys(), type=unicode) if len(seenPlugins) > 0: for i in self.mPlugins.keys(): if seenPlugins.count(i) == 0 and self.mPlugins[i]["status"] == "not installed": self.mPlugins[i]["status"] = "new"
def exportVectorLayer(layer): """Takes a QgsVectorLayer and returns the filename to refer to it, which allows external apps which support only file-based layers to use it. It performs the necessary export in case the input layer is not in a standard format suitable for most applications, it is a remote one or db-based (non-file based) one, or if there is a selection and it should be used, exporting just the selected features. Currently, the output is restricted to shapefiles, so anything that is not in a shapefile will get exported. It also export to a new file if the original one contains non-ascii characters. """ settings = QSettings() systemEncoding = settings.value('/UI/encoding', 'System') filename = os.path.basename(unicode(layer.source())) idx = filename.rfind('.') if idx != -1: filename = filename[:idx] filename = unicode(layer.name()) validChars = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:' filename = ''.join(c for c in filename if c in validChars) if len(filename) == 0: filename = 'layer' output = getTempFilenameInTempFolder(filename + '.shp') provider = layer.dataProvider() useSelection = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED) if useSelection and layer.selectedFeatureCount() != 0: writer = QgsVectorFileWriter(output, systemEncoding, layer.pendingFields(), provider.geometryType(), layer.crs()) selection = layer.selectedFeatures() for feat in selection: writer.addFeature(feat) del writer return output else: isASCII = True try: unicode(layer.source()).decode('ascii') except UnicodeEncodeError: isASCII = False if not unicode(layer.source()).endswith('shp') or not isASCII: writer = QgsVectorFileWriter( output, systemEncoding, layer.pendingFields(), provider.geometryType(), layer.crs() ) for feat in layer.getFeatures(): writer.addFeature(feat) del writer return output else: return unicode(layer.source())
def convertUnsupportedFormats(self, progress): i = 0 progress.setText(self.tr('Converting outputs')) for out in self.outputs: if isinstance(out, OutputVector): if out.compatible is not None: layer = dataobjects.getObjectFromUri(out.compatible) if layer is None: # For the case of memory layer, if the # getCompatible method has been called continue provider = layer.dataProvider() writer = out.getVectorWriter( provider.fields(), provider.geometryType(), layer.crs() ) features = vector.features(layer) for feature in features: writer.addFeature(feature) elif isinstance(out, OutputRaster): if out.compatible is not None: layer = dataobjects.getObjectFromUri(out.compatible) format = self.getFormatShortNameFromFilename(out.value) orgFile = out.compatible destFile = out.value crsid = layer.crs().authid() settings = QSettings() path = unicode(settings.value('/GdalTools/gdalPath', '')) envval = unicode(os.getenv('PATH')) if not path.lower() in envval.lower().split(os.pathsep): envval += '%s%s' % (os.pathsep, path) os.putenv('PATH', envval) command = 'gdal_translate -of %s -a_srs %s %s %s' % (format, crsid, orgFile, destFile) if os.name == 'nt': command = command.split(" ") else: command = [command] proc = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=False, ) proc.communicate() elif isinstance(out, OutputTable): if out.compatible is not None: layer = dataobjects.getObjectFromUri(out.compatible) provider = layer.dataProvider() writer = out.getTableWriter(provider.fields()) features = vector.features(layer) for feature in features: writer.addRecord(feature) progress.setPercentage(100 * i / float(len(self.outputs)))
def loadAPIFile(self): settings = QSettings() lastDirPath = settings.value("pythonConsole/lastDirAPIPath", "", type=str) fileAPI = QFileDialog.getOpenFileName( self, "Open API File", lastDirPath, "API file (*.api)") if fileAPI: self.addAPI(fileAPI) lastDirPath = QFileInfo(fileAPI).path() settings.setValue("pythonConsole/lastDirAPIPath", fileAPI)
def connect(self, parent=None): conn_name = self.connectionName() settings = QSettings() settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name)) if not settings.contains("database"): # non-existent entry? raise InvalidDataException(self.tr('There is no defined database connection "%s".') % conn_name) from qgis.core import QgsDataSourceURI uri = QgsDataSourceURI() settingsList = ["service", "host", "port", "database", "username", "password", "authcfg"] service, host, port, database, username, password, authcfg = [settings.value(x, "", type=str) for x in settingsList] useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool) sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int) settings.endGroup() if service: uri.setConnection(service, database, username, password, sslmode, authcfg) else: uri.setConnection(host, port, database, username, password, sslmode, authcfg) uri.setUseEstimatedMetadata(useEstimatedMetadata) try: return self.connectToUri(uri) except ConnectionError: return False
def closeEvent(self, e): self.unregisterAllActions() # clear preview, this will delete the layer in preview tab self.preview.loadPreview(None) # save the window state settings = QSettings() settings.setValue("/DB_Manager/mainWindow/windowState", self.saveState()) settings.setValue("/DB_Manager/mainWindow/geometry", self.saveGeometry()) QMainWindow.closeEvent(self, e)
def initLexer(self): if self.lexerType == self.LEXER_PYTHON: self.lexer = QsciLexerPython() colorDefault = QColor('#2e3436') colorComment = QColor('#c00') colorCommentBlock = QColor('#3465a4') colorNumber = QColor('#4e9a06') colorType = QColor('#4e9a06') colorKeyword = QColor('#204a87') colorString = QColor('#ce5c00') self.lexer.setDefaultFont(self.defaultFont) self.lexer.setDefaultColor(colorDefault) self.lexer.setColor(colorComment, 1) self.lexer.setColor(colorNumber, 2) self.lexer.setColor(colorString, 3) self.lexer.setColor(colorString, 4) self.lexer.setColor(colorKeyword, 5) self.lexer.setColor(colorString, 6) self.lexer.setColor(colorString, 7) self.lexer.setColor(colorType, 8) self.lexer.setColor(colorCommentBlock, 12) self.lexer.setColor(colorString, 15) self.lexer.setFont(self.italicFont, 1) self.lexer.setFont(self.boldFont, 5) self.lexer.setFont(self.boldFont, 8) self.lexer.setFont(self.italicFont, 12) self.api = QsciAPIs(self.lexer) settings = QSettings() useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI', True)) if useDefaultAPI: # Load QGIS API shipped with Python console self.api.loadPrepared( os.path.join(QgsApplication.pkgDataPath(), 'python', 'qsci_apis', 'pyqgis.pap')) else: # Load user-defined API files apiPaths = settings.value('pythonConsole/userAPI', []) for path in apiPaths: self.api.load(path) self.api.prepare() self.lexer.setAPIs(self.api) elif self.lexerType == self.LEXER_R: # R lexer self.lexer = LexerR() self.setLexer(self.lexer)
def runGdal(commands, progress=None): if progress is None: progress = SilentProgress() envval = os.getenv('PATH') # We need to give some extra hints to get things picked up on OS X isDarwin = False try: isDarwin = platform.system() == 'Darwin' except IOError: # https://travis-ci.org/m-kuhn/QGIS#L1493-L1526 pass if isDarwin and os.path.isfile(os.path.join(QgsApplication.prefixPath(), "bin", "gdalinfo")): # Looks like there's a bundled gdal. Let's use it. os.environ['PATH'] = "{}{}{}".format(os.path.join(QgsApplication.prefixPath(), "bin"), os.pathsep, envval) os.environ['DYLD_LIBRARY_PATH'] = os.path.join(QgsApplication.prefixPath(), "lib") else: # Other platforms should use default gdal finder codepath settings = QSettings() path = settings.value('/GdalTools/gdalPath', '') if not path.lower() in envval.lower().split(os.pathsep): envval += '{}{}'.format(os.pathsep, path) os.putenv('PATH', envval) fused_command = ' '.join([unicode(c) for c in commands]) progress.setInfo('GDAL command:') progress.setCommand(fused_command) progress.setInfo('GDAL command output:') success = False retry_count = 0 while success == False: loglines = [] loglines.append('GDAL execution console output') try: proc = subprocess.Popen( fused_command, shell=True, stdout=subprocess.PIPE, stdin=open(os.devnull), stderr=subprocess.STDOUT, universal_newlines=True, ).stdout for line in proc: progress.setConsoleInfo(line) loglines.append(line) success = True except IOError as e: if retry_count < 5: retry_count += 1 else: raise IOError(e.message + u'\nTried 5 times without success. Last iteration stopped after reading {} line(s).\nLast line(s):\n{}'.format(len(loglines), u'\n'.join(loglines[-10:]))) ProcessingLog.addToLog(ProcessingLog.LOG_INFO, loglines) GdalUtils.consoleOutput = loglines
def populateFileFilters(self): # populate the combo with supported vector file formats for name, filt in qgis.core.QgsVectorFileWriter.ogrDriverList().items(): self.cboFileFormat.addItem(name, filt) # set the last used filter settings = QSettings() filt = settings.value(self.lastUsedVectorFilterSettingsKey, "ESRI Shapefile") idx = self.cboFileFormat.findText(filt) if idx < 0: idx = 0 self.cboFileFormat.setCurrentIndex(idx)
def selectFile(self): fileFilter = self.output.getFileFilter(self.alg) settings = QSettings() if settings.contains('/Processing/LastOutputPath'): path = settings.value('/Processing/LastOutputPath') else: path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER) encoding = settings.value('/Processing/encoding', 'System') fileDialog = QgsEncodingFileDialog( self, self.tr('Save file'), path, fileFilter, encoding) fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) fileDialog.setConfirmOverwrite(True) if fileDialog.exec_() == QDialog.Accepted: files = fileDialog.selectedFiles() encoding = unicode(fileDialog.encoding()) self.output.encoding = encoding fileName = unicode(files[0]) selectedFileFilter = unicode(fileDialog.selectedNameFilter()) if not fileName.lower().endswith( tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))): ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter) if ext: fileName += ext.group(1) self.leText.setText(fileName) settings.setValue('/Processing/LastOutputPath', os.path.dirname(fileName)) settings.setValue('/Processing/encoding', encoding)
def saveToSpatialite(self): fileFilter = self.output.tr('Spatialite files(*.sqlite)', 'OutputFile') settings = QSettings() if settings.contains('/Processing/LastOutputPath'): path = settings.value('/Processing/LastOutputPath') else: path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER) encoding = settings.value('/Processing/encoding', 'System') fileDialog = QgsEncodingFileDialog( self, self.tr('Save Spatialite'), path, fileFilter, encoding) fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) fileDialog.setConfirmOverwrite(False) if fileDialog.exec_() == QDialog.Accepted: files = fileDialog.selectedFiles() encoding = unicode(fileDialog.encoding()) self.output.encoding = encoding fileName = unicode(files[0]) selectedFileFilter = unicode(fileDialog.selectedNameFilter()) if not fileName.lower().endswith( tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))): ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter) if ext: fileName += ext.group(1) settings.setValue('/Processing/LastOutputPath', os.path.dirname(fileName)) settings.setValue('/Processing/encoding', encoding) uri = QgsDataSourceURI() uri.setDatabase(fileName) uri.setDataSource('', self.output.name.lower(), 'the_geom') self.leText.setText("spatialite:" + uri.uri())
def __init__(self, iface, parent=None): QMainWindow.__init__(self, parent) self.setAttribute(Qt.WA_DeleteOnClose) self.setupUi() self.iface = iface # restore the window state settings = QSettings() self.restoreGeometry(settings.value("/DB_Manager/mainWindow/geometry", QByteArray(), type=QByteArray)) self.restoreState(settings.value("/DB_Manager/mainWindow/windowState", QByteArray(), type=QByteArray)) self.tabs.currentChanged.connect(self.tabChanged) self.tree.selectedItemChanged.connect(self.itemChanged) self.itemChanged(None)
def selectDirectory(self): settings = QSettings() if settings.contains('/Processing/LastBatchOutputPath'): lastDir = unicode(settings.value('/Processing/LastBatchOutputPath')) else: lastDir = '' dirName = QFileDialog.getExistingDirectory(self, self.tr('Select directory'), lastDir, QFileDialog.ShowDirsOnly) if dirName: self.table.cellWidget(self.row, self.col).setValue(dirName) settings.setValue('/Processing/LastBatchOutputPath', dirName)
def timeForChecking(self): """ determine whether it's the time for checking for news and updates now """ if self.checkingOnStartInterval() == 0: return True settings = QSettings() try: # QSettings may contain ivalid value... interval = settings.value(settingsGroup + "/checkOnStartLastDate", type=QDate).daysTo(QDate.currentDate()) except: interval = 0 if interval >= self.checkingOnStartInterval(): return True else: return False
def __init__(self, parent=None): QgsMapCanvas.__init__(self, parent) self.parent = parent self.setCanvasColor(QColor(255, 255, 255)) self.item = None self.dirty = False self.currentLayer = None # reuse settings from QGIS settings = QSettings() self.enableAntiAliasing(settings.value("/qgis/enable_anti_aliasing", False, type=bool)) action = settings.value("/qgis/wheel_action", 0, type=float) zoomFactor = settings.value("/qgis/zoom_factor", 2, type=float) self.setWheelAction(QgsMapCanvas.WheelAction(action), zoomFactor)
def getTableWriter(self, fields): """ Returns a suitable writer to which records can be added as a result of the algorithm. Use this to transparently handle output values instead of creating your own method. @param fields a list of field titles @return writer instance of the table writer class """ if self.encoding is None: settings = QSettings() self.encoding = settings.value('/Processing/encoding', 'System') return TableWriter(self.value, self.encoding, fields)
def __init__(self, alg): super(AlgorithmDialogBase, self).__init__(iface.mainWindow()) self.setupUi(self) self.settings = QSettings() self.restoreGeometry(self.settings.value("/Processing/dialogBase", QByteArray())) self.executed = False self.mainWidget = None self.alg = alg # Rename OK button to Run self.btnRun = self.buttonBox.button(QDialogButtonBox.Ok) self.btnRun.setText(self.tr('Run')) self.btnClose = self.buttonBox.button(QDialogButtonBox.Close) self.setWindowTitle(AlgorithmClassification.getDisplayName(self.alg)) desktop = QDesktopWidget() if desktop.physicalDpiX() > 96: self.textHelp.setZoomFactor(desktop.physicalDpiX() / 96) algHelp = self.alg.shortHelp() if algHelp is None: self.textShortHelp.setVisible(False) else: self.textShortHelp.document().setDefaultStyleSheet('''.summary { margin-left: 10px; margin-right: 10px; } h2 { color: #555555; padding-bottom: 15px; } a { text-decoration: none; color: #3498db; font-weight: bold; } p { color: #666666; } b { color: #333333; } dl dd { margin-bottom: 5px; }''') self.textShortHelp.setHtml(algHelp) self.textShortHelp.setOpenLinks(False) def linkClicked(url): webbrowser.open(url.toString()) self.textShortHelp.anchorClicked.connect(linkClicked) self.textHelp.page().setNetworkAccessManager(QgsNetworkAccessManager.instance()) isText, algHelp = self.alg.help() if algHelp is not None: algHelp = algHelp if isText else QUrl(algHelp) try: if isText: self.textHelp.setHtml(algHelp) else: self.textHelp.settings().clearMemoryCaches() self.textHelp.load(algHelp) except: self.tabWidget.removeTab(2) else: self.tabWidget.removeTab(2) self.showDebug = ProcessingConfig.getSetting( ProcessingConfig.SHOW_DEBUG_IN_DIALOG)
def closeEvent(self, evt): settings = QSettings() settings.setValue("/Processing/splitterModeler", self.splitter.saveState()) settings.setValue("/Processing/geometryModeler", self.saveGeometry()) if self.hasChanged: ret = QMessageBox.question( self, self.tr('Unsaved changes'), self.tr('There are unsaved changes in model. Continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if ret == QMessageBox.Yes: evt.accept() else: evt.ignore() else: evt.accept()
def getObjectFromUri(uri, forceLoad=True): """Returns an object (layer/table) given a source definition. if forceLoad is true, it tries to load it if it is not currently open Otherwise, it will return the object only if it is loaded in QGIS. """ if uri is None: return None if uri in _loadedLayers: return _loadedLayers[uri] layers = getRasterLayers() for layer in layers: if normalizeLayerSource(layer.source()) == normalizeLayerSource(uri): return layer layers = getVectorLayers() for layer in layers: if normalizeLayerSource(layer.source()) == normalizeLayerSource(uri): return layer tables = getTables() for table in tables: if normalizeLayerSource(table.source()) == normalizeLayerSource(uri): return table if forceLoad: settings = QSettings() prjSetting = settings.value('/Projections/defaultBehaviour') settings.setValue('/Projections/defaultBehaviour', '') # If is not opened, we open it for provider in ['ogr', 'postgres', 'spatialite', 'virtual']: layer = QgsVectorLayer(uri, uri, provider) if layer.isValid(): if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) _loadedLayers[normalizeLayerSource(layer.source())] = layer return layer layer = QgsRasterLayer(uri, uri) if layer.isValid(): if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) _loadedLayers[normalizeLayerSource(layer.source())] = layer return layer if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) else: return None
def __init__(self, conn_name=None): """init""" QDialog.__init__(self) self.setupUi(self) self.settings = QSettings() self.conn_name = None self.conn_name_orig = conn_name
def checkingOnStartInterval(self): """ return checking for news and updates interval """ settings = QSettings() try: # QSettings may contain non-int value... i = settings.value(settingsGroup + "/checkOnStartInterval", 1, type=int) except: # fallback do 1 day by default i = 1 if i < 0: i = 1 # allowed values: 0,1,3,7,14,30 days interval = 0 for j in [1, 3, 7, 14, 30]: if i >= j: interval = j return interval
def connections(self): # get the list of connections conn_list = [] settings = QSettings() settings.beginGroup(self.connectionSettingsKey()) for name in settings.childGroups(): conn_list.append(createDbPlugin(self.typeName(), name)) settings.endGroup() return conn_list
def __init__(self, iface, parent=None): QMainWindow.__init__(self, parent) self.setAttribute(Qt.WA_DeleteOnClose) self.setupUi() self.iface = iface # restore the window state settings = QSettings() self.restoreGeometry( settings.value("/DB_Manager/mainWindow/geometry", QByteArray(), type=QByteArray)) self.restoreState( settings.value("/DB_Manager/mainWindow/windowState", QByteArray(), type=QByteArray)) self.tabs.currentChanged.connect(self.tabChanged) self.tree.selectedItemChanged.connect(self.itemChanged) self.itemChanged(None)
def load(fileName, name=None, crs=None, style=None): """Loads a layer/table into the current project, given its file. """ if fileName is None: return prjSetting = None settings = QSettings() if crs is not None: prjSetting = settings.value('/Projections/defaultBehaviour') settings.setValue('/Projections/defaultBehaviour', '') if name is None: name = os.path.split(fileName)[1] qgslayer = QgsVectorLayer(fileName, name, 'ogr') if qgslayer.isValid(): if crs is not None and qgslayer.crs() is None: qgslayer.setCrs(crs, False) if style is None: if qgslayer.geometryType() == QGis.Point: style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POINT_STYLE) elif qgslayer.geometryType() == QGis.Line: style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_LINE_STYLE) else: style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POLYGON_STYLE) qgslayer.loadNamedStyle(style) QgsMapLayerRegistry.instance().addMapLayers([qgslayer]) else: qgslayer = QgsRasterLayer(fileName, name) if qgslayer.isValid(): if crs is not None and qgslayer.crs() is None: qgslayer.setCrs(crs, False) if style is None: style = ProcessingConfig.getSetting(ProcessingConfig.RASTER_STYLE) qgslayer.loadNamedStyle(style) QgsMapLayerRegistry.instance().addMapLayers([qgslayer]) iface.legendInterface().refreshLayerSymbology(qgslayer) else: if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) raise RuntimeError('Could not load layer: ' + unicode(fileName) + '\nCheck the processing framework log to look for errors') if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) return qgslayer
def processAlgorithm(self, progress): connection = self.getParameterValue(self.DATABASE) settings = QSettings() mySettings = '/PostgreSQL/connections/' + connection try: database = settings.value(mySettings + '/database') username = settings.value(mySettings + '/username') host = settings.value(mySettings + '/host') port = settings.value(mySettings + '/port', type=int) password = settings.value(mySettings + '/password') except Exception as e: raise GeoAlgorithmExecutionException( self.tr('Wrong database connection name: %s' % connection)) try: self.db = postgis_utils.GeoDB(host=host, port=port, dbname=database, user=username, passwd=password) except postgis_utils.DbError as e: raise GeoAlgorithmExecutionException( self.tr("Couldn't connect to database:\n%s") % unicode(e)) sql = self.getParameterValue(self.SQL).replace('\n', ' ') try: self.db._exec_sql_and_commit(unicode(sql)) except postgis_utils.DbError as e: raise GeoAlgorithmExecutionException( self.tr('Error executing SQL:\n%s') % unicode(e))
def showFileSelectionDialog(self): settings = QSettings() text = unicode(self.text.text()) if os.path.isdir(text): path = text elif os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = unicode(settings.value('/Processing/LastInputPath')) else: path = '' ret = QFileDialog.getOpenFileNames( self, self.tr('Open file'), path, self.tr('All files(*.*);;') + self.param.getFileFilter()) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(unicode(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(unicode(f) for f in files)) else: rowdif = len(files) - (self.table.rowCount() - self.row) for i in range(rowdif): self.panel.addRow() for i, f in enumerate(files): self.table.cellWidget(i + self.row, self.col).setText(f)
def runalgIterating(alg, paramToIter, progress): # Generate all single-feature layers settings = QSettings() systemEncoding = settings.value('/UI/encoding', 'System') layerfile = alg.getParameterValue(paramToIter) layer = dataobjects.getObjectFromUri(layerfile, False) feat = QgsFeature() filelist = [] outputs = {} provider = layer.dataProvider() features = vector.features(layer) for feat in features: output = getTempFilename('shp') filelist.append(output) writer = QgsVectorFileWriter(output, systemEncoding, provider.fields(), provider.geometryType(), layer.crs()) writer.addFeature(feat) del writer # store output values to use them later as basenames for all outputs for out in alg.outputs: outputs[out.name] = out.value # now run all the algorithms for i, f in enumerate(filelist): alg.setParameterValue(paramToIter, f) for out in alg.outputs: filename = outputs[out.name] if filename: filename = filename[:filename.rfind('.')] + '_' + unicode(i) \ + filename[filename.rfind('.'):] out.value = filename progress.setText(tr('Executing iteration %s/%s...' % (unicode(i), unicode(len(filelist))))) progress.setPercentage(i * 100 / len(filelist)) if runalg(alg): handleAlgorithmResults(alg, None, False) else: return False return True
def processAlgorithm(self, progress): settings = QSettings() initial_method_setting = settings.value(settings_method_key, 1) method = self.getParameterValue(self.METHOD) if method != 0: settings.setValue(settings_method_key, method) try: self.doCheck(progress) finally: settings.setValue(settings_method_key, initial_method_setting)
def show_console(): """ called from QGIS to open the console """ global _console if _console is None: parent = iface.mainWindow() if iface else None _console = PythonConsole(parent) _console.show() # force show even if it was restored as hidden # set focus to the console so the user can start typing # defer the set focus event so it works also whether the console not visible yet QTimer.singleShot(0, _console.activate) else: _console.setVisible(not _console.isVisible()) # set focus to the console so the user can start typing if _console.isVisible(): _console.activate() ## Shows help on first launch of the console settings = QSettings() if settings.value('pythonConsole/contextHelpOnFirstLaunch', True, type=bool): QgsContextHelp.run("PythonConsole") settings.setValue('pythonConsole/contextHelpOnFirstLaunch', False)
def __init__(self, iface): if not valid: return # Save reference to the QGIS interface self.iface = iface try: self.QgisVersion = unicode(QGis.QGIS_VERSION_INT) except: self.QgisVersion = unicode(QGis.qgisVersion)[0] if QGis.QGIS_VERSION[0:3] < "1.5": # For i18n support userPluginPath = qgis.utils.home_plugin_path + "/GdalTools" systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools" overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool) if not overrideLocale: localeFullName = QLocale.system().name() else: localeFullName = QSettings().value("locale/userLocale", "", type=str) if QFileInfo(userPluginPath).exists(): translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" else: translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" self.localePath = translationPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator) # The list of actions added to menus, so we can remove them when unloading the plugin self._menuActions = []
def exportTable(table): """Takes a QgsVectorLayer and returns the filename to refer to its attributes table, which allows external apps which support only file-based layers to use it. It performs the necessary export in case the input layer is not in a standard format suitable for most applications, it isa remote one or db-based (non-file based) one. Currently, the output is restricted to DBF. It also export to a new file if the original one contains non-ascii characters. """ settings = QSettings() systemEncoding = settings.value('/UI/encoding', 'System') output = getTempFilename() provider = table.dataProvider() isASCII = True try: unicode(table.source()).decode('ascii') except UnicodeEncodeError: isASCII = False isDbf = unicode(table.source()).endswith('dbf') \ or unicode(table.source()).endswith('shp') if not isDbf or not isASCII: writer = QgsVectorFileWriter(output, systemEncoding, provider.fields(), QGis.WKBNoGeometry, QgsCoordinateReferenceSystem('4326')) for feat in table.getFeatures(): writer.addFeature(feat) del writer return output + '.dbf' else: filename = unicode(table.source()) if unicode(table.source()).endswith('shp'): return filename[:-3] + 'dbf' else: return filename
def setUpClass(cls): if not cls._BaseSetup: TestQgsPalLabeling.setUpClass() MAPSERV.startup() MAPSERV.web_dir_install(glob.glob(cls._PalDataDir + os.sep + '*.qml')) MAPSERV.web_dir_install(glob.glob(cls._PalDataDir + os.sep + '*.qgs')) # noinspection PyArgumentList cls._TestProj = QgsProject.instance() cls._TestProjName = 'test-labeling.qgs' cls._TestProj.setFileName( os.path.join(MAPSERV.web_dir(), cls._TestProjName)) # the blue background (set via layer style) to match renderchecker's TestQgsPalLabeling.loadFeatureLayer('background', True) settings = QSettings() # noinspection PyArgumentList cls._CacheDir = settings.value( "cache/directory", os.path.join(unicode(QgsApplication.qgisSettingsDirPath()), "cache"), type=unicode)
def loadShortHelp(): h = {} path = os.path.dirname(__file__) for f in os.listdir(path): if f.endswith("yaml"): filename = os.path.join(path, f) with open(filename) as stream: h.update(yaml.load(stream)) version = ".".join(QGis.QGIS_VERSION.split(".")[0:2]) overrideLocale = QSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QSettings().value('locale/userLocale', '') locale = locale.split("_")[0] def replace(s): if s is not None: return s.replace("{qgisdocs}", "https://docs.qgis.org/%s/%s/docs" % (version, locale)) else: return None h = {k: replace(v) for k, v in h.iteritems()} return h
def setFonts(self, size): # Load font from Python console settings settings = QSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', size)) self.defaultFont = QFont(fontName) self.defaultFont.setFixedPitch(True) self.defaultFont.setPointSize(fontSize) self.defaultFont.setStyleHint(QFont.TypeWriter) self.defaultFont.setStretch(QFont.SemiCondensed) self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0) self.defaultFont.setBold(False) self.boldFont = QFont(self.defaultFont) self.boldFont.setBold(True) self.italicFont = QFont(self.defaultFont) self.italicFont.setItalic(True) self.setFont(self.defaultFont) self.setMarginsFont(self.defaultFont)
def addRepository(self): """ add new repository connection """ dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow()) dlg.editParams.setText(repositories.urlParams()) dlg.checkBoxEnabled.setCheckState(Qt.Checked) if not dlg.exec_(): return for i in repositories.all().values(): if dlg.editURL.text().strip() == i["url"]: iface.pluginManagerInterface().pushMessage(self.tr("Unable to add another repository with the same URL!"), QgsMessageBar.WARNING) return settings = QSettings() settings.beginGroup(reposGroup) reposName = dlg.editName.text() reposURL = dlg.editURL.text().strip() if reposName in repositories.all(): reposName = reposName + "(2)" # add to settings settings.setValue(reposName + "/url", reposURL) settings.setValue(reposName + "/authcfg", dlg.editAuthCfg.text().strip()) settings.setValue(reposName + "/enabled", bool(dlg.checkBoxEnabled.checkState())) # refresh lists and populate widgets plugins.removeRepository(reposName) self.reloadAndExportData()
def chooseInputFile(self): vectorFormats = qgis.core.QgsProviderRegistry.instance( ).fileVectorFilters() # get last used dir and format settings = QSettings() lastDir = settings.value("/db_manager/lastUsedDir", "") lastVectorFormat = settings.value("/UI/lastVectorFileFilter", "") # ask for a filename (filename, lastVectorFormat) = QFileDialog.getOpenFileNameAndFilter( self, self.tr("Choose the file to import"), lastDir, vectorFormats, lastVectorFormat) if filename == "": return # store the last used dir and format settings.setValue("/db_manager/lastUsedDir", QFileInfo(filename).filePath()) settings.setValue("/UI/lastVectorFileFilter", lastVectorFormat) self.cboInputLayer.setEditText(filename)
def connect(self, parent=None): conn_name = self.connectionName() settings = QSettings() settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name)) if not settings.contains("sqlitepath"): # non-existent entry? raise InvalidDataException(u'there is no defined database connection "%s".' % conn_name) database = settings.value("sqlitepath") uri = QgsDataSourceURI() uri.setDatabase(database) return self.connectToUri(uri)
def deleteRepository(self, reposName): """ delete repository connection """ if not reposName: return reposName = reposName.decode('utf-8') settings = QSettings() settings.beginGroup(reposGroup) if settings.value(reposName + "/url", "", type=unicode) == officialRepo[1]: iface.pluginManagerInterface().pushMessage(self.tr("You can't remove the official QGIS Plugin Repository. You can disable it if needed."), QgsMessageBar.WARNING) return warning = self.tr("Are you sure you want to remove the following repository?") + "\n" + reposName if QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), warning, QMessageBox.Yes, QMessageBox.No) == QMessageBox.No: return # delete from the settings, refresh data and repopulate all the widgets settings.remove(reposName) repositories.remove(reposName) plugins.removeRepository(reposName) self.reloadAndExportData()
def selectDirectory(self): settings = QSettings() if settings.contains('/Processing/LastBatchOutputPath'): lastDir = unicode( settings.value('/Processing/LastBatchOutputPath')) else: lastDir = '' dirName = QFileDialog.getExistingDirectory(self, self.tr('Select directory'), lastDir, QFileDialog.ShowDirsOnly) if dirName: self.table.cellWidget(self.row, self.col).setValue(dirName) settings.setValue('/Processing/LastBatchOutputPath', dirName)
def __init__(self): """ Initialize data objects, starts fetching if appropriate, and warn about/removes obsolete plugins """ QObject.__init__(self) # initialize QObject in order to to use self.tr() repositories.load() plugins.getAllInstalled() if repositories.checkingOnStart() and repositories.timeForChecking() and repositories.allEnabled(): # start fetching repositories self.statusLabel = QLabel(self.tr("Looking for new plugins...") + " ", iface.mainWindow().statusBar()) iface.mainWindow().statusBar().insertPermanentWidget(0, self.statusLabel) self.statusLabel.linkActivated.connect(self.showPluginManagerWhenReady) repositories.checkingDone.connect(self.checkingDone) for key in repositories.allEnabled(): repositories.requestFetching(key) else: # no fetching at start, so mark all enabled repositories as requesting to be fetched. for key in repositories.allEnabled(): repositories.setRepositoryData(key, "state", 3) # look for obsolete plugins (the user-installed one is newer than core one) for key in plugins.obsoletePlugins: plugin = plugins.localCache[key] msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setWindowTitle(self.tr("QGIS Python Plugin Installer")) msg.addButton(self.tr("Uninstall (recommended)"), QMessageBox.AcceptRole) msg.addButton(self.tr("I will uninstall it later"), QMessageBox.RejectRole) msg.setText("%s <b>%s</b><br/><br/>%s" % (self.tr("Obsolete plugin:"), plugin["name"], self.tr("QGIS has detected an obsolete plugin that masks its more recent version shipped with this copy of QGIS. This is likely due to files associated with a previous installation of QGIS. Do you want to remove the old plugin right now and unmask the more recent version?"))) msg.exec_() if not msg.result(): # uninstall, update utils and reload if enabled self.uninstallPlugin(key, quiet=True) updateAvailablePlugins() settings = QSettings() if settings.value("/PythonPlugins/" + key, False, type=bool): settings.setValue("/PythonPlugins/watchDog/" + key, True) loadPlugin(key) startPlugin(key) settings.remove("/PythonPlugins/watchDog/" + key)
def selectOutput(self): if isinstance(self.output, OutputDirectory): self.selectDirectory() else: popupMenu = QMenu() actionSaveToTempFile = QAction(self.tr('Save to a temporary file'), self.btnSelect) actionSaveToTempFile.triggered.connect(self.saveToTemporaryFile) popupMenu.addAction(actionSaveToTempFile) actionSaveToFile = QAction(self.tr('Save to file...'), self.btnSelect) actionSaveToFile.triggered.connect(self.selectFile) popupMenu.addAction(actionSaveToFile) if isinstance(self.output, OutputVector) \ and self.alg.provider.supportsNonFileBasedOutput(): actionSaveToMemory = QAction(self.tr('Save to memory layer'), self.btnSelect) actionSaveToMemory.triggered.connect(self.saveToMemory) popupMenu.addAction(actionSaveToMemory) actionSaveToSpatialite = QAction( self.tr('Save to Spatialite table...'), self.btnSelect) actionSaveToSpatialite.triggered.connect(self.saveToSpatialite) popupMenu.addAction(actionSaveToSpatialite) actionSaveToPostGIS = QAction( self.tr('Save to PostGIS table...'), self.btnSelect) actionSaveToPostGIS.triggered.connect(self.saveToPostGIS) settings = QSettings() settings.beginGroup('/PostgreSQL/connections/') names = settings.childGroups() settings.endGroup() actionSaveToPostGIS.setEnabled(bool(names)) popupMenu.addAction(actionSaveToPostGIS) popupMenu.exec_(QCursor.pos())
def saveToPostGIS(self): dlg = PostgisTableSelector(self, self.output.name.lower()) dlg.exec_() if dlg.connection: settings = QSettings() mySettings = '/PostgreSQL/connections/' + dlg.connection dbname = settings.value(mySettings + '/database') user = settings.value(mySettings + '/username') host = settings.value(mySettings + '/host') port = settings.value(mySettings + '/port') password = settings.value(mySettings + '/password') uri = QgsDataSourceURI() uri.setConnection(host, str(port), dbname, user, password) uri.setDataSource(dlg.schema, dlg.table, "the_geom") connInfo = uri.connectionInfo() (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None) if success: QgsCredentials.instance().put(connInfo, user, passwd) self.leText.setText("postgis:" + uri.uri())
def addFile(self): settings = QSettings() if settings.contains('/Processing/LastInputPath'): path = settings.value('/Processing/LastInputPath') else: path = '' files = QFileDialog.getOpenFileNames(self, self.tr('Select file(s)'), path, self.tr('All files (*.*)')) if len(files) == 0: return model = self.lstLayers.model() for filePath in files: item = QStandardItem(filePath) model.appendRow(item) settings.setValue('/Processing/LastInputPath', os.path.dirname(files[0]))
def runGdal(commands, progress): envval = unicode(os.getenv('PATH')) # We need to give some extra hints to get things picked up on OS X if platform.system() == 'Darwin': if os.path.isfile(os.path.join(QgsApplication.prefixPath(), "bin", "gdalinfo")): # Looks like there's a bundled gdal. Let's use it. os.environ['PATH'] = "%s%s%s" % (os.path.join(QgsApplication.prefixPath(), "bin"), os.pathsep, envval) os.environ['DYLD_LIBRARY_PATH'] = os.path.join(QgsApplication.prefixPath(), "lib") else: # Nothing internal. Let's see if we can find it elsewhere. settings = QSettings() path = unicode(settings.value('/GdalTools/gdalPath', '')) envval += '%s%s' % (os.pathsep, path) os.putenv('PATH', envval) else: # Other platforms should use default gdal finder codepath settings = QSettings() path = unicode(settings.value('/GdalTools/gdalPath', '')) if not path.lower() in envval.lower().split(os.pathsep): envval += '%s%s' % (os.pathsep, path) os.putenv('PATH', envval) loglines = [] loglines.append('GDAL execution console output') fused_command = ''.join(['%s ' % c for c in commands]) progress.setInfo('GDAL command:') progress.setCommand(fused_command) proc = subprocess.Popen( fused_command, shell=True, stdout=subprocess.PIPE, stdin=open(os.devnull), stderr=subprocess.STDOUT, universal_newlines=True, ).stdout progress.setInfo('GDAL command output:') for line in iter(proc.readline, ''): progress.setConsoleInfo(line) loglines.append(line) ProcessingLog.addToLog(ProcessingLog.LOG_INFO, loglines) GdalUtils.consoleOutput = loglines
def showSelectionDialog(self): settings = QSettings() text = unicode(self.cmbText.currentText()) if os.path.isdir(text): path = text elif os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = unicode(settings.value('/Processing/LastInputPath')) else: path = '' filename = QFileDialog.getOpenFileName( self, self.tr('Select file'), path, self.tr('All files (*.*);;') + self.param.getFileFilter()) if filename: settings.setValue('/Processing/LastInputPath', os.path.dirname(unicode(filename))) filename = dataobjects.getRasterSublayer(filename, self.param) self.cmbText.addItem(filename, filename) self.cmbText.setCurrentIndex(self.cmbText.count() - 1)
def populateSchemas(self): if self.childCount() != 0: return settings = QSettings() connSettings = '/PostgreSQL/connections/' + self.connection database = settings.value(connSettings + '/database') user = settings.value(connSettings + '/username') host = settings.value(connSettings + '/host') port = settings.value(connSettings + '/port') passwd = settings.value(connSettings + '/password') uri = QgsDataSourceURI() uri.setConnection(host, str(port), database, user, passwd) connInfo = uri.connectionInfo() (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None) if success: QgsCredentials.instance().put(connInfo, user, passwd) geodb = GeoDB(host, int(port), database, user, passwd) schemas = geodb.list_schemas() for oid, name, owner, perms in schemas: item = QTreeWidgetItem() item.setText(0, name) item.setIcon(0, self.schemaIcon) self.addChild(item)
def setGdalBinPath(path): settings = QSettings() settings.setValue("/GdalTools/gdalPath", path)
def getGdalBinPath(): settings = QSettings() return settings.value("/GdalTools/gdalPath", u"", type=unicode)
def getLastUsedDir(): settings = QSettings() lastProjectDir = settings.value("/UI/lastProjectDir", u".", type=unicode) return settings.value("/GdalTools/lastUsedDir", lastProjectDir, type=unicode)