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 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 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 load(self): """ populate the mRepositories dict""" self.mRepositories = {} settings = QSettings() settings.beginGroup(reposGroup) # first, update repositories in QSettings if needed officialRepoPresent = False for key in settings.childGroups(): url = settings.value(key + "/url", "", type=unicode) if url == officialRepo[1]: officialRepoPresent = True if url == officialRepo[2]: settings.setValue(key + "/url", officialRepo[1]) # correct a depreciated url officialRepoPresent = True if not officialRepoPresent: settings.setValue(officialRepo[0] + "/url", officialRepo[1]) for key in settings.childGroups(): self.mRepositories[key] = {} self.mRepositories[key]["url"] = settings.value(key + "/url", "", type=unicode) self.mRepositories[key]["authcfg"] = settings.value(key + "/authcfg", "", type=unicode) self.mRepositories[key]["enabled"] = settings.value(key + "/enabled", True, type=bool) self.mRepositories[key]["valid"] = settings.value(key + "/valid", True, type=bool) self.mRepositories[key]["Relay"] = Relay(key) self.mRepositories[key]["xmlData"] = None self.mRepositories[key]["state"] = 0 self.mRepositories[key]["error"] = "" settings.endGroup()
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 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 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 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 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 __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 __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 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 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 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 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 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 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 showSelectionDialog(self): # Find the file dialog's working directory settings = QSettings() text = self.leText.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 = settings.value('/Processing/LastInputPath') else: path = '' if self.isFolder: folder = QFileDialog.getExistingDirectory(self, self.tr('Select folder'), path) if folder: self.leText.setText(folder) settings.setValue('/Processing/LastInputPath', os.path.dirname(folder)) else: filenames = QFileDialog.getOpenFileNames(self, self.tr('Select file'), path, '*.' + self.ext) if filenames: self.leText.setText(u';'.join(filenames)) settings.setValue('/Processing/LastInputPath', os.path.dirname(filenames[0]))
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 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 execute(self): settings = QSettings() lastDir = settings.value('Processing/lastScriptsDir', '') filename = QFileDialog.getOpenFileName( self.toolbox, self.tr('Script files', 'AddScriptFromFileAction'), lastDir, self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction')) if filename: try: settings.setValue( 'Processing/lastScriptsDir', QFileInfo(filename).absoluteDir().absolutePath()) script = ScriptAlgorithm(filename) except WrongScriptException: QMessageBox.warning( self.toolbox, self.tr('Error reading script', 'AddScriptFromFileAction'), self.tr( 'The selected file does not contain a valid script', 'AddScriptFromFileAction')) return destFilename = os.path.join(ScriptUtils.scriptsFolder(), os.path.basename(filename)) with open(destFilename, 'w') as f: f.write(script.script) self.toolbox.updateProvider('script')
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 __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 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 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 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 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 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 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 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 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 __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 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 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 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 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 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 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 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 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 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 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)