def readAllApps(self): self.allapps.clear() directoryLocal = QDir(self.folderlist.DirpathLocal) directoryLocal.setFilter(QDir.Files | QDir.Hidden); directoryLocal.setNameFilters(QStringList("*.desktop")) directoryGlobal = QDir(self.folderlist.DirpathGlobal) directoryGlobal.setFilter(QDir.Files | QDir.Hidden); directoryGlobal.setNameFilters(QStringList("*.desktop")) for file in directoryGlobal.entryList(): if not self.getAppIsNoDisplay(self.folderlist.DirpathGlobal + file): part = self.folderlist.getNameFromDirFile(self.folderlist.DirpathGlobal + file) icon = self.folderlist.getIconFromDirFile(self.folderlist.DirpathGlobal + file) self.allapps[part] = {} self.allapps[part]["path"] = self.folderlist.DirpathGlobal + file self.allapps[part]["icon"] = icon for file in directoryLocal.entryList(): if not self.getAppIsNoDisplay(self.folderlist.DirpathLocal + file): part = self.folderlist.getNameFromDirFile(self.folderlist.DirpathLocal + file) icon = self.folderlist.getIconFromDirFile(self.folderlist.DirpathLocal + file) self.allapps[part] = {} self.allapps[part]["path"] = self.folderlist.DirpathLocal + file self.allapps[part]["icon"] = icon
def updateImageRegistries(self): self.imageRegistry = [] self.hiResRegistry = [] self.imageEntryList = self.imageDir.entryList(['??????????'], QDir.Dirs) for i in self.imageEntryList: if self.killed is True: # kill request received, exit loop early break iDir = QDir(self.imageDir.path() + '\\' + i) #FIXME implement solution for not just jpg but values from ini iEntryList = iDir.entryList([i + '_???.jpg'], QDir.Files) self.imageRegistry = self.imageRegistry + iEntryList hiResEntryList = iDir.entryList(["highres*", "mrsid", "raw"], QDir.Dirs) hiResFilters = [i + '_???.' + ext for ext in self.hiResFormats] for hr in hiResEntryList: if self.killed is True: # kill request received, exit loop early break hrDir = QDir(iDir.path() + '\\' + hr) hrEntryList = hrDir.entryList(hiResFilters, QDir.Files) self.hiResRegistry = self.hiResRegistry + hrEntryList if self.killed is False: self.imageRegistryNE = [img[:14].replace('_','.') for img in self.imageRegistry] self.hiResRegistryNE = [img[:14].replace('_','.') for img in self.hiResRegistry]
def getRasterFiles(path, recursive=False): rasters = [] if not QFileInfo(path).exists(): return rasters # TODO remove *.aux.xml _filter = getRasterExtensions() workDir = QDir( path ) workDir.setFilter( QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot ) workDir.setNameFilters( _filter ) files = workDir.entryList() for f in files: rasters.append( path + "/" + f ) if recursive: for myRoot, myDirs, myFiles in os.walk( unicode(path) ): for dir in myDirs: workDir = QDir( myRoot + "/" + dir ) workDir.setFilter( QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot ) workDir.setNameFilters( _filter ) workFiles = workDir.entryList() for f in workFiles: rasters.append( myRoot + "/" + dir + "/" + f ) return rasters
def getFilesDirectory(self, globalPath, localPath): directoryLocal = QDir(localPath) directoryLocal.setFilter(QDir.Files | QDir.Hidden | QDir.NoSymLinks); directoryLocal.setNameFilters(QStringList("*.directory")) directoryGlobal = QDir(globalPath) directoryGlobal.setFilter(QDir.Files | QDir.Hidden | QDir.NoSymLinks); directoryGlobal.setNameFilters(QStringList("*.directory")) return directoryGlobal.entryList() + directoryLocal.entryList()
def clearTempFiles(self): """ Clear the directories created for each recording added to the queue and the files they contain. """ settingsQDir = QDir(self.settingsDir) settingsQDir.setFilter(QDir.Dirs | QDir.NoDotAndDotDot) for dir in settingsQDir.entryList(): tempQDir = QDir(self.settingsDir + '/' + dir) tempQDir.setFilter(QDir.Files) for tempFile in tempQDir.entryList(): tempQDir.remove(tempFile) settingsQDir.rmdir(self.settingsDir + '/' + dir)
def fillInputDir(self): inputDir = Utils.FileDialog.getExistingDirectory(self, self.tr("Select the input directory with files to Warp")) if not inputDir: return self.inSelector.setFilename(inputDir) filter = Utils.getRasterExtensions() workDir = QDir(inputDir) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) workDir.setNameFilters(filter) if len(workDir.entryList()) > 0: fl = inputDir + "/" + workDir.entryList()[0] self.sourceSRSEdit.setText(Utils.getRasterSRS(self, fl))
def fillInputDir(self): inputDir = Utils.FileDialog.getExistingDirectory( self, self.tr("Select the input directory with files to Warp")) if not inputDir: return self.inSelector.setFilename(inputDir) filter = Utils.getRasterExtensions() workDir = QDir(inputDir) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) workDir.setNameFilters(filter) if len(workDir.entryList()) > 0: fl = inputDir + "/" + workDir.entryList()[0] self.sourceSRSEdit.setText(Utils.getRasterSRS(self, fl))
def batchRun(self): exts = re.sub('\).*$', '', re.sub('^.*\(', '', self.formatCombo.currentText())).split(" ") if len(exts) > 0 and exts[0] != "*" and exts[0] != "*.*": outExt = exts[0].replace( "*", "" ) else: outExt = ".tif" self.base.enableRun( False ) self.base.setCursor( Qt.WaitCursor ) inDir = self.getInputFileName() outDir = self.getOutputFileName() extensions = Utils.getRasterExtensions() workDir = QDir( inDir ) workDir.setFilter( QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot ) workDir.setNameFilters( extensions ) files = workDir.entryList() self.inFiles = [] self.outFiles = [] for f in files: self.inFiles.append( inDir + "/" + f ) if outDir is not None: outFile = re.sub( "\.[a-zA-Z0-9]{2,4}", outExt, f ) self.outFiles.append( outDir + "/" + outFile ) self.errors = [] self.batchIndex = 0 self.batchTotal = len( self.inFiles ) self.setProgressRange( self.batchTotal ) self.runItem( self.batchIndex, self.batchTotal )
def on_upload_multiple_files(self): """ Browse and select multiple supporting documents. """ last_doc_path = last_document_path() if not last_doc_path: last_doc_path = '~/' docs_dir = QFileDialog.getExistingDirectory( self, 'Browse Supporting Documents Source Directory', last_doc_path) if not docs_dir: return # Check if there are files in the selected directory dir = QDir(docs_dir) els = dir.entryList(QDir.NoDot | QDir.NoDotDot | QDir.Files) if len(els) == 0: QMessageBox.warning( self, 'Supporting Documents', self.tr('There are no files in the selected directory.')) return doc_types = self.tbw_documents.document_types() dir_doc_dlg = DirDocumentTypeSelector(docs_dir, doc_types, self) res = dir_doc_dlg.exec_() if res == QDialog.Accepted: # Get document types selected by the user selected_doc_types = dir_doc_dlg.selected_document_types self.tbw_documents.upload_document(selected_doc_types)
def accept(self): if self.inputFiles is None: workDir = QDir(self.leInputDir.text()) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) nameFilter = ["*.shp", "*.SHP"] workDir.setNameFilters(nameFilter) self.inputFiles = workDir.entryList() if len(self.inputFiles) == 0: QMessageBox.warning( self, self.tr("No shapefiles found"), self.tr("There are no shapefiles in this directory. Please select another one.")) self.inputFiles = None return if self.outFileName is None: QMessageBox.warning( self, self.tr("No output file"), self.tr("Please specify output file.")) return if self.chkListMode.isChecked(): files = self.leInputDir.text().split(";") baseDir = QFileInfo(files[0]).absolutePath() else: baseDir = self.leInputDir.text() # look for shapes with specified geometry type self.inputFiles = ftools_utils.getShapesByGeometryType(baseDir, self.inputFiles, self.cmbGeometry.currentIndex()) if self.inputFiles is None: QMessageBox.warning( self, self.tr("No shapefiles found"), self.tr("There are no shapefiles with the given geometry type. Please select an available geometry type.")) return self.progressFiles.setRange(0, len(self.inputFiles)) outFile = QFile(self.outFileName) if outFile.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.outFileName): QMessageBox.warning(self, self.tr("Delete error"), self.tr("Can't delete file %s") % (self.outFileName)) return if self.inEncoding is None: self.inEncoding = "System" self.btnOk.setEnabled(False) self.mergeThread = ShapeMergeThread(baseDir, self.inputFiles, self.inEncoding, self.outFileName, self.encoding) QObject.connect(self.mergeThread, SIGNAL("rangeChanged( PyQt_PyObject )"), self.setFeatureProgressRange) QObject.connect(self.mergeThread, SIGNAL("checkStarted()"), self.setFeatureProgressFormat) QObject.connect(self.mergeThread, SIGNAL("checkFinished()"), self.resetFeatureProgressFormat) QObject.connect(self.mergeThread, SIGNAL("fileNameChanged( PyQt_PyObject )"), self.setShapeProgressFormat) QObject.connect(self.mergeThread, SIGNAL("featureProcessed()"), self.featureProcessed) QObject.connect(self.mergeThread, SIGNAL("shapeProcessed()"), self.shapeProcessed) QObject.connect(self.mergeThread, SIGNAL("processingFinished()"), self.processingFinished) QObject.connect(self.mergeThread, SIGNAL("processingInterrupted()"), self.processingInterrupted) self.btnClose.setText(self.tr("Cancel")) QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject) QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing) self.mergeThread.start()
def getAllInstalled(self, testLoad=True): """ Build the localCache """ self.localCache = {} # reversed list of the plugin paths: first system plugins -> then user plugins -> finally custom path(s) pluginPaths = list(plugin_paths) pluginPaths.reverse() for pluginsPath in pluginPaths: isTheSystemDir = (pluginPaths.index(pluginsPath)==0) # The curent dir is the system plugins dir if isTheSystemDir: # temporarily add the system path as the first element to force loading the readonly plugins, even if masked by user ones. sys.path = [pluginsPath] + sys.path try: pluginDir = QDir(pluginsPath) pluginDir.setFilter(QDir.AllDirs) for key in pluginDir.entryList(): if key not in [".",".."]: path = QDir.convertSeparators( pluginsPath + "/" + key ) # readOnly = not QFileInfo(pluginsPath).isWritable() # On windows testing the writable status isn't reliable. readOnly = isTheSystemDir # Assume only the system plugins are not writable. # only test those not yet loaded. Loaded plugins already proved they're o.k. testLoadThis = testLoad and key not in qgis.utils.plugins plugin = self.getInstalledPlugin(key, path=path, readOnly=readOnly, testLoad=testLoadThis) self.localCache[key] = plugin if key in self.localCache.keys() and compareVersions(self.localCache[key]["version_installed"],plugin["version_installed"]) == 1: # An obsolete plugin in the "user" location is masking a newer one in the "system" location! self.obsoletePlugins += [key] except: # it's not necessary to stop if one of the dirs is inaccessible pass if isTheSystemDir: # remove the temporarily added path sys.path.remove(pluginsPath)
def initTemplateList(self): cbox = self.ui.comboBox_Template cbox.clear() templateDir = QDir(tools.templateDir()) for i, entry in enumerate(templateDir.entryList(["*.html", "*.htm"])): cbox.addItem(entry) config = tools.getTemplateConfig(entry) # get template type templateType = config.get("type", "plain") cbox.setItemData(i, templateType, Qt.UserRole) # set tool tip text desc = config.get("description", "") if desc: cbox.setItemData(i, desc, Qt.ToolTipRole) # select the template of the settings templatePath = self._settings.get("Template") # if no template setting, select the last used template if not templatePath: templatePath = QSettings().value("/Qgis2threejs/lastTemplate", def_vals.template, type=unicode) if templatePath: index = cbox.findText(templatePath) if index != -1: cbox.setCurrentIndex(index) return index return -1
def inputDir(self): settings = QSettings() lastDir = settings.value("/fTools/lastShapeDir", ".") inDir = QFileDialog.getExistingDirectory( self, self.tr("Select directory with shapefiles to merge"), lastDir ) if not inDir: return workDir = QDir(inDir) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) nameFilter = ["*.shp", "*.SHP"] workDir.setNameFilters(nameFilter) self.inputFiles = workDir.entryList() if len(self.inputFiles) == 0: QMessageBox.warning( self, self.tr("No shapefiles found"), self.tr("There are no shapefiles in this directory. Please select another one.")) self.inputFiles = None return settings.setValue("/fTools/lastShapeDir", inDir) self.progressFiles.setRange(0, len(self.inputFiles)) self.leInputDir.setText(inDir)
def reloadPlugins(self): self.modules = [] self.plugins = [] if self.allPlugins: plugin_dir = QDir( os.path.join(os.path.dirname(QFile.decodeName(__file__)), "plugins")) plugins = plugin_dir.entryList(QDir.Dirs | QDir.NoSymLinks | QDir.NoDotAndDotDot) else: p = QSettings().value("/PhyloGeoRec/plugins", "", type=unicode) plugins = p.split(",") if p else [] import importlib for name in plugins: try: modname = "PhyloGeoRec.plugins." + str(name) module = reload( sys.modules[modname] ) if modname in sys.modules else importlib.import_module( modname) self.modules.append(module) self.plugins.append(getattr(module, "plugin_class")) except ImportError: logMessage("Failed to load plugin: " + str(name))
def batchRun(self): exts = re.sub('\).*$', '', re.sub('^.*\(', '', self.formatCombo.currentText())).split(" ") if len(exts) > 0 and exts[0] != "*" and exts[0] != "*.*": outExt = exts[0].replace( "*", "" ) else: outExt = ".tif" self.base.enableRun( False ) self.base.setCursor( Qt.WaitCursor ) inDir = self.getInputFileName() outDir = self.getOutputFileName() filter = Utils.getRasterExtensions() workDir = QDir( inDir ) workDir.setFilter( QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot ) workDir.setNameFilters( filter ) files = workDir.entryList() self.inFiles = [] self.outFiles = [] for f in files: self.inFiles.append( inDir + "/" + f ) if outDir is not None: outFile = re.sub( "\.[a-zA-Z0-9]{2,4}", outExt, f ) self.outFiles.append( outDir + "/" + outFile ) self.errors = [] self.batchIndex = 0 self.batchTotal = len( self.inFiles ) self.setProgressRange( self.batchTotal ) self.runItem( self.batchIndex, self.batchTotal )
def selectIcon(self, parent = None): dialog = DialogSelectFile(self) dialog.setWindowTitle("Select Icon") progress = QtGui.QProgressDialog("Please wait while loading icons", "Hide", 0, 100, parent) progress.setWindowModality(QtCore.Qt.WindowModal) progress.setAutoReset(True) progress.setAutoClose(True) progress.setMinimum(0) progress.setMaximum(100) progress.setWindowTitle("Loading...") progress.show() progress.setValue(0) directoryLocal = QDir(self.IconpathLocal) directoryLocal.setFilter(QDir.Files | QDir.Hidden | QDir.NoSymLinks); directoryLocal.setNameFilters(QStringList("*.png")) directoryGlobal = QDir(self.IconpathGlobal) directoryGlobal.setFilter(QDir.Files | QDir.Hidden | QDir.NoSymLinks); directoryGlobal.setNameFilters(QStringList("*.png")) for file in directoryLocal.entryList(): icon = QIcon(self.IconpathLocal + file) part = string.split(file, '.png')[0] listItem = QListWidgetItem(icon, part, dialog.listFile, QListWidgetItem.UserType) progress.setValue(50) for file in directoryGlobal.entryList(): icon = QIcon(self.IconpathGlobal + file) part = string.split(file, '.png')[0] listItem = QListWidgetItem(icon, part, dialog.listFile, QListWidgetItem.UserType) dialog.listFile.sortItems() progress.setValue(100) # progress.hide() dialog.show() dialog.exec_() selected = self.selFile self.selFile = "" return selected
def readFilenames(self): self.nameref.clear() directoryLocal = QDir(self.DirpathLocal) directoryLocal.setFilter(QDir.Files | QDir.Hidden | QDir.NoSymLinks); directoryLocal.setNameFilters(QStringList("*.directory")) directoryGlobal = QDir(self.DirpathGlobal) directoryGlobal.setFilter(QDir.Files | QDir.Hidden | QDir.NoSymLinks); directoryGlobal.setNameFilters(QStringList("*.directory")) for file in directoryGlobal.entryList(): part = self.getNameFromDirFile(self.DirpathGlobal + file) self.nameref[part] = self.DirpathGlobal + file for file in directoryLocal.entryList(): part = self.getNameFromDirFile(self.DirpathLocal + file) self.nameref[part] = self.DirpathLocal + file
def getThemeList(self): dir = QDir("/usr/share/enlightenment/data/themes") dir.setFilter( QDir.NoSymLinks | QDir.Files ) a = QStringList() a.append("*.edj") dir.setNameFilters(a) return dir.entryList()
def tearDown(self): del self.settings del self.metadata['dir'] del self.app outputDir = QDir(self.outputPath) outputDir.setFilter(QDir.Files) for file in outputDir.entryList(): filePath = unicode(self.outputPath + '/' + file) os.unlink(filePath)
def getThemeList(self): dir = QDir("/usr/share/themes") lst =dir.entryList() lst2=[] for previews in lst: if not previews == "HighContrast" and not previews == "HighContrastInverse": lst2.append(previews) return lst2
def getThemeList(self): dir =QDir("/usr/share/themes") lst= dir.entryList() lst2=[] for previews in lst: if not previews=="Crux": lst2.append(previews) return lst2
def paintEvent(self, event): # Create layout d = QDir(idahome) files = d.entryList(QDir.Files) self.filer = files self.comboList = QtGui.QComboBox(self) self.comboList.addItems(files) self.comboList.setCurrentIndex(-1) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.comboList) self.comboList.activated[str].connect(self.pass_Net_Adap)
def __init__(self, parent): QDialog.__init__(self, parent) # Set up the user interface from Designer. self.ui = ui = Ui_SettingsDialog() ui.setupUi(self) ui.lineEdit_BrowserPath.setPlaceholderText( "Leave this empty to use your default browser") ui.toolButton_Browse.clicked.connect(self.browseClicked) # load settings settings = QSettings() ui.lineEdit_BrowserPath.setText( settings.value("/Qgis2threejs/browser", "", type=unicode)) enabled_plugins = QSettings().value("/Qgis2threejs/plugins", "", type=unicode).split(",") # initialize plugin table widget plugin_dir = QDir( os.path.join(os.path.dirname(QFile.decodeName(__file__)), "plugins")) plugins = plugin_dir.entryList(QDir.Dirs | QDir.NoSymLinks | QDir.NoDotAndDotDot) tableWidget = ui.tableWidget_Plugins tableWidget.setRowCount(len(plugins)) tableWidget.setColumnCount(1) tableWidget.setHorizontalHeaderLabels(["Name"]) tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) headerView = tableWidget.horizontalHeader() headerView.setResizeMode(0, QHeaderView.Stretch) self.plugin_metadata = [] for i, name in enumerate(plugins): parser = ConfigParser.SafeConfigParser() with codecs.open( os.path.join(plugin_dir.absoluteFilePath(name), "metadata.txt"), "r", "UTF-8") as f: parser.readfp(f) metadata = dict(parser.items("general")) self.plugin_metadata.append(metadata) item = QTableWidgetItem(metadata.get("name", name)) item.setCheckState(Qt.Checked if name in enabled_plugins else Qt.Unchecked) tableWidget.setItem(i, 0, item) tableWidget.selectionModel().currentRowChanged.connect( self.pluginSelectionChanged)
def __init__(self, parent, dirName): """ Constructor @param parent parent widget (QWidget) @param dirName name of directory to show """ QDialog.__init__(self, parent) self.setupUi(self) dir = QDir(dirName) for icon in dir.entryList(QStringList() << "*.png"): QListWidgetItem(QIcon(os.path.join(unicode(dirName), unicode(icon))), icon, self.iconView)
def get_list_of_symbol_paths(symbolTopLevelPaths): """ Given a list of top level paths to directories containting sconcho kitting symbols returns a QStringList of all paths to individual sconcho patterns. """ symbolPaths = [] for path in symbolTopLevelPaths: aDir = QDir(path) for entry in aDir.entryList(QDir.AllDirs | QDir.NoDotAndDotDot): symbolPaths.append(aDir.absolutePath() + "/" + entry) return symbolPaths
def updateOrthoRegistry(self): import glob, os self.orthoRegistryNE = [] self.orthoRegistry = [] self.orthoEntryList = self.orthoDir.entryList(['??????????'], QDir.Dirs) for o in self.orthoEntryList: if self.killed is True: # kill request received, exit loop early break orthoFilters = [o + '_???_op*.' + ext for ext in self.orthoFormats] oDir = QDir(self.orthoDir.path() +'\\' + o) oEntryList = oDir.entryList(orthoFilters, QDir.Files) self.orthoRegistry = self.orthoRegistry + oEntryList if self.killed is False: self.orthoRegistryNE = [img[:14].replace('_','.') for img in self.orthoRegistry]
class MenuDiretorioConsole(MatrizConsole): arquivoSelecionado = pyqtSignal(str) def __init__(self, initDir='.', parent=None): super().__init__(parent=parent) self._dir = QDir(initDir) self._dir.setSorting(QDir.Name) self._addItensDir() def _addItensDir(self): self.clear() di = self._dir.entryList() try: di.remove('.') except ValueError: pass self.addItens([LabelConsole(i) for i in di]) def atualizarListaArquivos(self): self.cd('.') def cd(self, diret): if self._dir.cd(diret): self._addItensDir() return True return False def onEnter(self): if not self.cd(self.getItemSelecionado().getTexto()): self.arquivoSelecionado.emit(self.pathArquivoSelecionado()) def path(self): return self._dir.absolutePath() def pathArquivoSelecionado(self): return self.path() + '/' + self.getItemSelecionado().getTexto() def desenhoTela(self, tam): s = '|{0:-<{1}}|\n'.format('',tam-2) s += '|Path: {0:<{1}}{2}|\n'.format(LabelConsole(self._dir.absolutePath()).desenhoTelaConsole(tam-9), tam-9, [' ','*'][self.hasFocus()]) s += '|{0:-<{1}}|\n'.format('',tam-2) for i in super().desenhoTela(tam-2).split('\n'): s += '|{0:<{1}}|\n'.format(i, tam-2) s += '|{0:-<{1}}|'.format('',tam-2) return s
def handleWatchUpdate(self,path): myDir = QDir(path) myDir.setNameFilters(self.supportedExtensions) allFilesNow = myDir.entryList() allFilesNow = list(allFilesNow) allFilesNow = [str(item) for item in allFilesNow] differentFiles = list(set(allFilesNow) ^ set(self.fileNames)) if differentFiles != []: for aFile in differentFiles: if self.fileNames.__contains__(aFile): #TODO: delete the file from the table self.ui.statusbar.showMessage('Removed' + aFile,2500) else: #process the new file self.processFile(os.path.join(self.workingDirectory,aFile))
def getFiles(pattern, directory): files = [] d = QDir(directory) for f in d.entryList(): if f=="." or f=="..": continue fi = QFileInfo(d, f) if fi.isDir(): files.extend( getFiles( pattern, unicode( fi.filePath() ) ) ) elif re.search( pattern, f): files.append( os.path.abspath( unicode( fi.filePath() ) ) ) return files
def getFiles(pattern, directory): files = [] d = QDir(directory) for f in d.entryList(): if f == "." or f == "..": continue fi = QFileInfo(d, f) if fi.isDir(): files.extend(getFiles(pattern, unicode(fi.filePath()))) elif re.search(pattern, f): files.append(os.path.abspath(unicode(fi.filePath()))) return files
def scan_for_scripts(): """ Find python files (*.py) inside the scripts directory. """ addons = [] scripts = [] qdir = QDir(scripts_dirpath) qdir.setFilter(QDir.Files) qdir.setNameFilters(['*.py']) for py_filename in qdir.entryList(): py_filepath = path.join(str(scripts_dirpath), str(py_filename)) # or unicode? what = _is_script(py_filepath) if what == IS_SCRIPT: scripts.append(py_filepath) if what == IS_ADDON: addons.append(py_filepath) return scripts, addons
def testStatistics(self): """Test zonal stats""" sep = os.sep TEST_DATA_DIR = unitTestDataPath() + sep + "zonalstatistics" + sep myTempPath = QDir.tempPath() + sep testDir = QDir(TEST_DATA_DIR) for f in testDir.entryList(QDir.Files): QFile.remove(myTempPath + f) QFile.copy(TEST_DATA_DIR + f, myTempPath + f) myVector = QgsVectorLayer(myTempPath + "polys.shp", "poly", "ogr") myRasterPath = myTempPath + "edge_problem.asc" zs = QgsZonalStatistics(myVector, myRasterPath, "", 1) zs.calculateStatistics(None) feat = QgsFeature() # validate statistics for each feature request = QgsFeatureRequest().setFilterFid(0) feat = myVector.getFeatures(request).next() myMessage = ('Expected: %f\nGot: %f\n' % (12.0, feat[1])) assert feat[1] == 12.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (8.0, feat[2])) assert feat[2] == 8.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.666666666666667, feat[3])) assert abs(feat[3] - 0.666666666666667) < 0.00001, myMessage request.setFilterFid(1) feat = myVector.getFeatures(request).next() myMessage = ('Expected: %f\nGot: %f\n' % (9.0, feat[1])) assert feat[1] == 9.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2])) assert feat[2] == 5.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.555555555555556, feat[3])) assert abs(feat[3] - 0.555555555555556) < 0.00001, myMessage request.setFilterFid(2) feat = myVector.getFeatures(request).next() myMessage = ('Expected: %f\nGot: %f\n' % (6.0, feat[1])) assert feat[1] == 6.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (5.0, feat[2])) assert feat[2] == 5.0, myMessage myMessage = ('Expected: %f\nGot: %f\n' % (0.833333333333333, feat[3])) assert abs(feat[3] - 0.833333333333333) < 0.00001, myMessage
def fillInputDir( self ): inputDir = Utils.FileDialog.getExistingDirectory( self, self.tr( "Select the input directory with files to Translate" )) if not inputDir: return self.inSelector.setFilename( inputDir ) filter = Utils.getRasterExtensions() workDir = QDir( inputDir ) workDir.setFilter( QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot ) workDir.setNameFilters( filter ) # search for a valid SRS, then use it as default target SRS srs = '' for fname in workDir.entryList(): fl = inputDir + "/" + fname srs = Utils.getRasterSRS( self, fl ) if srs: break self.targetSRSEdit.setText( srs )
def fillInputDir(self): inputDir = Utils.FileDialog.getExistingDirectory( self, self.tr("Select the input directory with files to Translate")) if not inputDir: return self.inSelector.setFilename(inputDir) filter = Utils.getRasterExtensions() workDir = QDir(inputDir) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) workDir.setNameFilters(filter) # search for a valid SRS, then use it as default target SRS srs = '' for fname in workDir.entryList(): fl = inputDir + "/" + fname srs = Utils.getRasterSRS(self, fl) if srs: break self.targetSRSEdit.setText(srs)
def reloadPlugins(self): self.modules = [] self.plugins = [] allPlugins = False if allPlugins: plugin_dir = QDir(os.path.join(os.path.dirname(QFile.decodeName(__file__)), "plugins")) plugins = plugin_dir.entryList(QDir.Dirs | QDir.NoSymLinks | QDir.NoDotAndDotDot) else: p = QSettings().value("/Qgis2threejs/plugins", "", type=unicode) plugins = p.split(",") if p else [] import importlib for name in plugins: try: modname = "Qgis2threejs.plugins." + str(name) module = reload(sys.modules[modname]) if modname in sys.modules else importlib.import_module(modname) self.modules.append(module) self.plugins.append(getattr(module, "plugin_class")) except ImportError: logMessage("Failed to load plugin: " + str(name))
def getWallpaperSettings(self): dir = QDir("/usr/share/wallpapers/Pardus_Mood/contents") dir.setFilter( QDir.NoSymLinks | QDir.Files ) a = QStringList() a.append ("*.jpeg") a.append("*.jpg") a.append("*.png") dir.setNameFilters(a) lst = dir.entryList() items = [] for desktopFile in lst: wallpaper = {} try: wallpaper["wallpaperTitle"] = "picture" except: wallpaper["wallpaperTitle"] = "picture1" try: wallpaper["wallpaperDesc"] = "description" except: wallpaper["wallpaperDesc"] = "description1" # Get all files in the wallpaper's directory thumbFolder = desktopFile # """ # Appearantly the thumbnail names doesn't have a standart. # So we get the file list from the contents folder and # choose the file which has a name that starts with "scre". # File names I've seen so far; # screenshot.jpg, screnshot.jpg, screenshot.png, screnshot.png # """ wallpaper["wallpaperThumb"] = "/usr/share/wallpapers/Pardus_Mood/contents/%s"%desktopFile wallpaper["wallpaperFile"] = desktopFile items.append(wallpaper) CONFIG_KAPTANRC.setValue("Wallpaper/Source","/usr/share/wallpapers/Pardus_Mood/contents/%s" %desktopFile) self.getWallpaper(desktopFile) return items
def __init__(self, parent): QDialog.__init__(self, parent) # Set up the user interface from Designer. self.ui = ui = Ui_SettingsDialog() ui.setupUi(self) ui.lineEdit_BrowserPath.setPlaceholderText("Leave this empty to use your default browser") ui.toolButton_Browse.clicked.connect(self.browseClicked) # load settings settings = QSettings() ui.lineEdit_BrowserPath.setText(settings.value("/Qgis2threejs/browser", "", type=unicode)) enabled_plugins = QSettings().value("/Qgis2threejs/plugins", "", type=unicode).split(",") # initialize plugin table widget plugin_dir = QDir(os.path.join(os.path.dirname(QFile.decodeName(__file__)), "plugins")) plugins = plugin_dir.entryList(QDir.Dirs | QDir.NoSymLinks | QDir.NoDotAndDotDot) tableWidget = ui.tableWidget_Plugins tableWidget.setRowCount(len(plugins)) tableWidget.setColumnCount(1) tableWidget.setHorizontalHeaderLabels(["Name"]) tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) headerView = tableWidget.horizontalHeader() headerView.setResizeMode(0, QHeaderView.Stretch) self.plugin_metadata = [] for i, name in enumerate(plugins): parser = ConfigParser.SafeConfigParser() with codecs.open(os.path.join(plugin_dir.absoluteFilePath(name), "metadata.txt"), "r", "UTF-8") as f: parser.readfp(f) metadata = dict(parser.items("general")) self.plugin_metadata.append(metadata) item = QTableWidgetItem(metadata.get("name", name)) item.setCheckState(Qt.Checked if name in enabled_plugins else Qt.Unchecked) tableWidget.setItem(i, 0, item) tableWidget.selectionModel().currentRowChanged.connect(self.pluginSelectionChanged)
def getThemeList(self): dir = QDir("/usr/share/fluxbox/styles") return dir.entryList()
def __init__(self, notebooks): # Index directory of whoosh, located in notebookPath. self.schema = fields.Schema( path = fields.TEXT(stored=True), title = fields.TEXT(stored=True), content = fields.TEXT(stored=True), tags = fields.KEYWORD(commas=True)) self.notebookName = notebooks[0][0] self.notebookPath = notebooks[0][1] self.notePath = os.path.join(self.notebookPath, "notes").replace(os.sep, '/') self.htmlPath = os.path.join(self.notebookPath, "html", "notes").replace(os.sep, '/') self.indexdir = os.path.join(self.notePath, ".indexdir").replace(os.sep, '/') self.attachmentPath = os.path.join(self.notebookPath, "attachments").replace(os.sep, '/') self.configfile = os.path.join(self.notebookPath, "notebook.conf").replace(os.sep, '/') cssPath = os.path.join(self.notebookPath, "css").replace(os.sep, '/') self.cssfile = os.path.join(cssPath, "notebook.css").replace(os.sep, '/') self.searchcssfile = os.path.join(cssPath, "search-window.css").replace(os.sep, '/') self.qsettings = QSettings(self.configfile, QSettings.IniFormat) if os.path.exists(self.configfile): self.extensions = readListFromSettings(self.qsettings, "extensions") self.fileExt = self.qsettings.value("fileExt") self.attachmentImage = self.qsettings.value("attachmentImage") self.attachmentDocument = self.qsettings.value("attachmentDocument") self.version = self.qsettings.value("version") self.geometry = self.qsettings.value("geometry") self.windowstate = self.qsettings.value("windowstate") self.mathjax = self.qsettings.value('mathJax') if 'extensionsConfig' not in set(self.qsettings.childGroups()): self.extcfg = self.qsettings.value('extensionsConfig', defaultValue={}) writeDictToSettings(self.qsettings, 'extensionsConfig', self.extcfg) else: self.extcfg = readDictFromSettings(self.qsettings, 'extensionsConfig') else: self.extensions = [] self.fileExt = "" self.attachmentImage = [] self.attachmentDocument = [] self.version = None self.geometry = None self.windowstate = None self.mathjax = '' self.extcfg = {} self.faulty_exts=[] # Default enabled python-markdown extensions. # http://pythonhosted.org/Markdown/extensions/index.html if not self.extensions: self.extensions = [ 'nl2br' # newline to break , 'strkundr' # bold-italics-underline-delete style , 'codehilite' # code syntax highlight , 'fenced_code' # code block , 'headerid' # add id to headers , 'headerlink' # add anchor to headers , 'footnotes' , 'asciimathml' ] writeListToSettings(self.qsettings, "extensions", self.extensions) while True: print(self.extensions) try: markdown.markdown("",extensions=self.extensions) except AttributeError as e: remove_this = NOT_EXT.findall(e.args[0])[0] if remove_this in self.extensions: print("Found invalid markdown extension",remove_this,". Please consider removing it.") print('If you want to permanently disable this, just hit OK in the Notebook Settings dialog') self.extensions.remove(remove_this) self.faulty_exts.append(remove_this) except ImportError as e: if e.name.startswith('mdx_') and e.name[4:] in self.extensions: print('Found missing markdown extension', e.name[4:], ', temporarily disabling.') print('If you want to permanently disable this, just hit OK in the Notebook Settings dialog') self.extensions.remove(e.name[4:]) self.faulty_exts.append(e.name[4:]) elif e.name in self.extensions: print('Found missing markdown extension', e.name, ', temporarily disabling.') print('If you want to permanently disable this, just hit OK in the Notebook Settings dialog') self.extensions.remove(e.name) self.faulty_exts.append(e.name) else: self.md = markdown.Markdown(self.extensions, extension_configs=self.extcfg) break # Default file extension name if not self.fileExt: self.fileExt = ".md" self.qsettings.setValue("fileExt", self.fileExt) # Image file types that will be copied to attachmentDir # Inserted as image link if not self.attachmentImage: self.attachmentImage = [".jpg", ".jpeg", ".png", ".gif", ".svg"] self.qsettings.setValue("attachmentImage", self.attachmentImage) # Document file types that will be copied to attachmentDir # Inserted as link if not self.attachmentDocument: self.attachmentDocument = [".pdf", ".doc", ".odt"] self.qsettings.setValue("attachmentDocument", self.attachmentDocument) # Migrate notebookPath to v0.3.0 folder structure if not self.version: notebookDir = QDir(self.notebookPath) # move all markdown files to notes/ dirList = notebookDir.entryList(QDir.Dirs | QDir.NoDotAndDotDot) if 'css' in dirList: dirList.remove('css') fileList = notebookDir.entryList(['*.md', '*.mkd', '*.markdown']) notebookDir.mkdir('notes') for d in dirList + fileList: notebookDir.rename(d, os.path.join('notes', d).replace(os.sep, '/')) # remove .indexdir folder oldIndexDir = QDir(os.path.join(self.notebookPath, '.indexdir'.replace(os.sep, '/'))) indexFileList = oldIndexDir.entryList() for f in indexFileList: oldIndexDir.remove(f) notebookDir.rmdir('.indexdir') # rename notes.css to css/notebook.css oldCssFile = os.path.join(self.notebookPath, 'notes.css').replace(os.sep, '/') QDir().mkpath(cssPath) if os.path.exists(oldCssFile): QFile.rename(oldCssFile, self.cssfile) self.version = '0' if not self.mathjax: self.mathjax = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' self.qsettings.setValue('mathJax', self.mathjax)
class EasyImport: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'EasyImport_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = EasyImportDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&EasyImport') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'EasyImport') self.toolbar.setObjectName(u'EasyImport') # Root folder where shape files are stored self.shapeDirectory = QDir() # XML Config file self.configXML = QtXml.QDomDocument() # XML current Config self.currentConfigXML = QtXml.QDomElement() # XML Config path self.configFileName = 'config.xml' # Shape file dictionnary # shapeFiles[shape filename] = shapefile absolute path self.shapeFiles = {} # Shape file dictionnary # pointsLayersConfig[shape filename] = Import rules XML nodes self.pointsLayersConfig = {} # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('EasyImport', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/EasyImport/icon.png' self.add_action( icon_path, text=self.tr(u'EasyImport'), callback=self.run, parent=self.iface.mainWindow()) # Load settings from XML self.loadConfig() # Set event handlers self.dlg.btnBrowse.clicked.connect(self.setShapeDirectory) self.dlg.btnImport.clicked.connect(self.runImport) self.dlg.cbxConfig.currentIndexChanged.connect(self.cbxConfigChanged) self.dlg.txtDirectory.textEdited.connect(self.txtDirectoryChanged) def txtDirectoryChanged(self, text): self.shapeDirectory = QDir(text) self.getShapeFiles() def setShapeDirectory(self): """Display folder browser dialog.""" file = QFileDialog.getExistingDirectory(None, 'Select gps/shape file directory.') self.dlg.txtDirectory.setText(file) self.shapeDirectory = QDir(file) def cbxConfigChanged(self, id): """Reset config on configuration combox box changes.""" self.pointsLayersConfig.clear() self.setCurrentConfig(self.dlg.cbxConfig.itemData(id)) def getShapeFiles(self): """Get each shapefile in defined folder.""" self.shapeFiles.clear() shapefiles = self.shapeDirectory.entryList(['*.shp'],QDir.Files,QDir.Name) for file in shapefiles: # Populate the shape dictionnary self.shapeFiles[file.split('.',1)[0]] = file # print self.shapeFiles.keys() def removeShapeFiles(self, shapeFiles): """Removes generated shapefiles""" for code in shapeFiles.keys(): paths = str(self.shapeDirectory.absolutePath() + '/' + code + '.*') files = glob(paths) # print paths for file in files: os.remove(file) def getAsciiFiles(self): """Get each asciifile in defined folder.""" # self.asciiFiles.clear() asciifiles = self.shapeDirectory.entryList(['*.asc'],QDir.Files,QDir.Name) for file in asciifiles: # Convert into shapefile self.ascii2shape(file) def ascii2shape(self, file): """Convert every input from the ascii file to the corresponding shapefile and creates it if it does not exists yet. :param file: ascii file to be converted""" # Read ascii with open(self.shapeDirectory.absolutePath() + '/' + file,'r') as f: content = f.readlines() ind = 0 # Set spatial ref and driver driver = ogr.GetDriverByName('ESRI Shapefile') srs = osr.SpatialReference() epsg21781wkt = 'PROJCS["CH1903 / LV03",GEOGCS["CH1903",DATUM["CH1903",SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],TOWGS84[674.374,15.056,405.346,0,0,0,0],AUTHORITY["EPSG","6149"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4149"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Hotine_Oblique_Mercator"],PARAMETER["latitude_of_center",46.95240555555556],PARAMETER["longitude_of_center",7.439583333333333],PARAMETER["azimuth",90],PARAMETER["rectified_grid_angle",90],PARAMETER["scale_factor",1],PARAMETER["false_easting",600000],PARAMETER["false_northing",200000],AUTHORITY["EPSG","21781"],AXIS["Y",EAST],AXIS["X",NORTH]]' srs.ImportFromWkt(epsg21781wkt) # Start iteration on features for line in content: # Remove undesirables tabs and double spaces removedTabs = re.sub(r"\s+", " ", content[ind]) # split fields values line_fields = removedTabs.split(' ') # Avoid uncompleted lines if (len(line_fields)>4): # Create the dictionnary featureDict = ['GPSID','TYPE', 'CODE', 'Y', 'X', 'Z', 'DELTA', 'COMMENT'] # Extract the information featureDict[0] = str(line_fields[0]) # featureDict[0] = int(re.findall(r'\d+', line_fields[0])[0]) featureDict[1] = str(re.findall('[a-zA-Z]+', line_fields[0])[0]) try: featureDict[2] = int(line_fields[5]) except ValueError: featureDict[2] = 999 featureDict[3] = str(line_fields[1]) featureDict[4] = str(line_fields[2]) featureDict[5] = str(line_fields[3]) featureDict[6] = float(line_fields[4]) featureDict[7] = ' '.join(line_fields[6:]) ofilepath = self.shapeDirectory.absolutePath() + '/' + str(featureDict[2]) + '.shp' if not os.path.exists(ofilepath): dataSource = driver.CreateDataSource(ofilepath) olayer = dataSource.CreateLayer("points", srs, geom_type=ogr.wkbPoint25D) olayer.CreateField(ogr.FieldDefn("Point_ID", ogr.OFTString)) olayer.CreateField(ogr.FieldDefn("Ortho_Heig", ogr.OFTReal)) else: dataSource = driver.Open(ofilepath,1) olayer = dataSource.GetLayer() # print ofilepath # Set feature fields feature = ogr.Feature(olayer.GetLayerDefn()) feature.SetField("Point_ID", featureDict[0]) feature.SetField("Ortho_Heig", featureDict[5]) # Set geometry geom_wkt = 'POINT (' + featureDict[3] + ' ' + featureDict[4] + ' ' + featureDict[5] + ')' point = ogr.CreateGeometryFromWkt(geom_wkt) feature.SetGeometry(point) # Create feature olayer.CreateFeature(feature) # remove feature and datasource from memory feature.Destroy() dataSource.Destroy() # else: #additional behaviour in case of uncompleted line # increment ind+=1 def setCurrentConfig(self, idConfig): """Load configuration from XML based on configuration id. :param idConfig: configuration id's stored in XML. :type text: str """ # Get config node childrens if config id = idConfig root = self.configXML.documentElement() configs = root.elementsByTagName('config') for index in range(configs.count()): if configs.at(index).hasAttributes(): nodeAttributes = configs.at(index).attributes() if nodeAttributes.namedItem('id').nodeValue() == idConfig: self.currentConfigXML = configs.at(index) # Get all pointlayer nodes layerspoints = self.currentConfigXML.toElement().elementsByTagName('pointlayer') # Populate import rules (pointsLayersConfig) for index in range(layerspoints.count()): if layerspoints.at(index).hasAttributes(): self.pointsLayersConfig[layerspoints.at(index).toElement().attributeNode('code').value()] = layerspoints.at(index).toElement() def loadConfig(self): """Load configuration combobox with configurations stored in XML configuration file.""" XMLFile = QFile(self.plugin_dir + '/' + self.configFileName) if not XMLFile.open(QFile.ReadOnly | QFile.Text): QMessageBox.warning(self.iface.mainWindow(), "XML Configuration","Cannot read file %s:\n%s." % (self.plugin_dir + '/' + self.configFileName, XMLFile.errorString()),QMessageBox.Ok) return False ok, errorStr, errorLine, errorColumn = self.configXML.setContent(XMLFile, True) if not ok: QMessageBox.information(self.iface.mainWindow(), "XML Configuration","Parse error at line %d, column %d:\n%s" % (errorLine, errorColumn, errorStr)) return False root = self.configXML.documentElement() configs = root.elementsByTagName('config') for index in range(configs.count()): if configs.at(index).hasAttributes(): nodeAttributes = configs.at(index).attributes() self.dlg.cbxConfig.addItem(nodeAttributes.namedItem('name').nodeValue(), nodeAttributes.namedItem('id').nodeValue()) self.setCurrentConfig(self.dlg.cbxConfig.itemData(self.dlg.cbxConfig.currentIndex())) return True def runImport(self): self.getAsciiFiles() self.getShapeFiles() if len(self.shapeFiles) <= 0: QMessageBox.warning(self.iface.mainWindow(), "Shape import","No shape file found.") return #Shapefiles that match the config code codes = set(self.shapeFiles.keys()) & set(self.pointsLayersConfig.keys()) # Maximum value of progress bar is the number of shapefile self.dlg.pgbImport.setMaximum(len(codes)) # For each Shapefiles that match the config code for k in codes: # Import data based on config self.importData(self.shapeDirectory.absolutePath() + "/" + self.shapeFiles[k], k) # Increment progress bar self.dlg.pgbImport.setValue(self.dlg.pgbImport.value() + 1) self.removeShapeFiles(self.shapeFiles) def importData(self, filename, code): """Import data from shapefile to an specified layer in project. :param filename: shapefile filename. :type text: str :param code: shapefile name. :type text: str """ driver = ogr.GetDriverByName('ESRI Shapefile') layers = QgsMapLayerRegistry.instance().mapLayers() destinationlayer = None colunmMappingDict = {} staticMappingDict = {} regexMappingDict = {} destinationLayerName = self.pointsLayersConfig[code].elementsByTagName('destinationlayer').item(0).toElement().text() columnMappings = self.pointsLayersConfig[code].elementsByTagName('columnmapping') staticMappings = self.pointsLayersConfig[code].elementsByTagName('staticmapping') # No destination layer found in XML if destinationLayerName is None: return for k in layers.keys(): if layers[k].name() == destinationLayerName: destinationlayer = layers[k] # No destination layer found in QGis Project if destinationlayer is None: return dataSource = driver.Open(filename, 0) if dataSource is None: self.dlg.txtOut.appendPlainText('Could not open %s \n' % (filename)) else: self.dlg.txtOut.appendPlainText('Opened %s' % (filename)) layer = dataSource.GetLayer() featureCount = layer.GetFeatureCount() # Get import rules with column mappings for index in range(columnMappings.count()): sourcecolumnname = columnMappings.at(index).toElement().elementsByTagName('source').item(0).toElement().text() destinationcolumnname = columnMappings.at(index).toElement().elementsByTagName('destination').item(0).toElement().text() regex = columnMappings.at(index).toElement().elementsByTagName('regex') if not (regex is None): regexMappingDict[sourcecolumnname] = regex.item(0).toElement().text() colunmMappingDict[sourcecolumnname] = destinationcolumnname # Get import rules with static value mappings for index in range(staticMappings.count()): staticValue = staticMappings.at(index).toElement().elementsByTagName('value').item(0).toElement().text() destinationcolumnname = staticMappings.at(index).toElement().elementsByTagName('destination').item(0).toElement().text() staticMappingDict[destinationcolumnname] = staticValue # Enable edit mode on destination layer destinationlayer.startEditing() # Retrieve all column off destination layer fields = destinationlayer.pendingFields() # For each data in shapefile for feature in layer: #Create new feature in destination layer and get geometry from shapefile newFeature = QgsFeature(fields) newFeature.setGeometry(QgsGeometry.fromWkt(str(feature.GetGeometryRef()))) # For each column mapping for k in colunmMappingDict.keys(): # print "source %s -> destination %s" % (k,colunmMappingDict[k]) # With regex if regexMappingDict[k]: regexp = re.compile(regexMappingDict[k]) # print str(k) # print feature.GetField(str(k)) m = regexp.match(feature.GetField(str(k))) if not (m is None): # print 'Regex : %s --> Value : %s' % (regexMappingDict[k], m.group('group')) newFeature.setAttribute(fields.fieldNameIndex(colunmMappingDict[k]), m.group('group')) # Without regex else: newFeature.setAttribute(fields.fieldNameIndex(colunmMappingDict[k]), feature.GetField(str(k))) # For each static value mapping for k in staticMappingDict.keys(): #print "destination %s -> value %s" % (k,staticMappingDict[k]) newFeature.setAttribute(fields.fieldNameIndex(k), staticMappingDict[k]) # Add new feature in destination layer destinationlayer.addFeature(newFeature, True) self.dlg.txtOut.appendPlainText('Shape %s : %s features imported \n' % (code, featureCount)) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&EasyImport'), action) self.iface.removeToolBarIcon(action) def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # Reset progress bar value self.dlg.pgbImport.setValue(0) # Reset output text box self.dlg.txtOut.clear() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
def tearDown(self): outputDir = QDir(self.testPath + '/output') outputDir.setNameFilters(['*.m4a']) for outputFile in outputDir.entryList(): outputDir.remove(outputFile)
def populateUi(self): """ Die Graphische Oberfläche wird bevölkert. """ ## Die Icons werden hier definiert, da der Pfad zur ressourcen-DAtei nicht stimmt, wenn pyside-uic über die ui-Datei marschiert ist. self.ui.pushButton_previous.setIcon( QIcon(":/icons/images/actions/1leftarrow.png")) self.ui.pushButton_next.setIcon( QIcon(":/icons/images/actions/1rightarrow.png")) self.ui.actionNew.setIcon(QIcon(":/icons/images/actions/filenew.png")) self.ui.actionOpen.setIcon( QIcon(":/icons/images/actions/fileopen.png")) self.ui.actionSave.setIcon( QIcon(":/icons/images/actions/filesave.png")) self.ui.actionExport.setIcon( QIcon(":/icons/images/actions/fileexport.png")) self.ui.actionPrint.setIcon( QIcon(":/icons/images/actions/agt_print.png")) self.ui.actionSettings.setIcon( QIcon(":/icons/images/actions/exec.png")) self.ui.actionQuit.setIcon(QIcon(":/icons/images/actions/exit.png")) self.info = InfoWidget(self.__storage, self.__character, self) self.ui.layout_info.addWidget(self.info) attributes = AttributeWidget(self.__storage, self.__character, self) self.ui.layout_attributes.addWidget(attributes) skills = SkillWidget(self.__storage, self.__character, self) self.ui.layout_skills.addWidget(skills) #specialties = Specialties( self.__storage.traits["Skill"], self ) specialties = SpecialtiesWidget(self.__storage.traits["Skill"], self) self.ui.layout_specialties.addWidget(specialties) merits = MeritWidget(self.__storage, self.__character, self) self.ui.layout_merits.addWidget(merits) morality = MoralityWidget(self.__storage, self.__character, self) self.ui.layout_morality.addWidget(morality) self.template = TemplateWidget(self.__storage, self.__character, self) self.ui.layout_template.addWidget(self.template) if "Power" in self.__storage.traits.keys(): powers = PowerWidget(self.__storage, self.__character, self) self.ui.layout_powers.addWidget(powers) subPowers = SubPowerWidget(self.__storage, self.__character, self) self.ui.layout_subPowers.addWidget(subPowers) flaws = FlawWidget(self.__storage, self.__character, self) self.ui.layout_flaws.addWidget(flaws) self.__advantages = AdvantagesWidget(self.__storage, self.__character, self) self.ui.layout_advantages.addWidget(self.__advantages) items = ItemWidget(self.__storage, self.__character, self) self.ui.layout_items.addWidget(items) speciesSpecials = SpecialsWidget(self.__storage, self.__character, self) self.ui.layout_specials.addWidget(speciesSpecials) ## Wenn sich der Name im InfoWidget ändert, soll sich auch die Titelzeile des Programms ändern self.info.nameChanged.connect(self.setTitle) ### Wird eine neue Seite angewählt, muß das Info-Widget den Beschreibungstext speichern. #self.pageChanged.connect(self.info.saveDescription) # Die Spezialisierungen einer Fertigkeit sollen angezeigt werden. skills.specialtiesActivated.connect(specialties.showSpecialties) # Menschen haben keine übernatürlichen Kräfte, also zeige ich sie auch nicht an. self.__character.speciesChanged.connect( self.ui.selectWidget_select.disableItems) # Hintergrundbild ändert sich je nach Spezies self.__character.speciesChanged.connect(self.showBackround) ## Sämtliche Schriften in das System laden, damit ich sie auch benutzen kann. resourceFontDir = QDir(":/fonts/fonts") fontsList = resourceFontDir.entryList() for font in fontsList: QFontDatabase.addApplicationFont(resourceFontDir.filePath(font))
class EkdSaveDialog(QDialog): ''' EkdSaveDialog : Classe représentant la boite de dialogue utiliser lors de l'enregistrement des modification sur un fichier donné attributs : suffix - Suffix utilisé en filtre filter - Filtre (déduit à partir du suffix) chemin - Chemin du dernier fichier enregistré multiple - va-t-on enregistrer plus d'un fichier ? (ex: extraction d'image d'une vidéo) méthodes : getFile - Invoque la boite de dialogue et retourne le fichier saisi ''' ### Pourquoi avoir réimplémenté cette classe au lieu de passer par ### QFileDialog ? ## Correction du bug de consommation mémoire ## ## Explication du problème : ## Par défaut un QFileDialog utilise un QFileSystemModel qui lui ## crée un QWatchFileSystem ## Hors QWatchFileSystem scan régulièrement les changement ## dans le répertoire courant ## Ce phénomène provoque une réaction en chaine : ## 1 - je choisi mon répertoire de destination d'enregistrement ## de mes images ## 2 - ffmpeg se lance ## 3 - ffmpeg crée un fichier dans l'arborescence ## 4 - QWatchFileSystem (est toujours dans le répertoire courant) ## détecte un changement ## et recharge l'ensemble du contenue du répertoire ## 5 - goto 3 jusqu'à plus de mémoire ou fin du process ffmpeg ## ## def __init__(self, parent, path = None, suffix = '', title = u"Sauver", multiple = False, mode = None): if type(suffix) == tuple or type(suffix) == list : sfilter="" for s in suffix : sfilter += "*"+s+" " self.filter=sfilter[:-1] # Si on a plusieur suffix, on prend le premier par défaut pour # la sauvegarde self.suffix = suffix[0] else : self.suffix = suffix self.filter = "*" + self.suffix QDialog.__init__(self, parent) self.setWindowTitle(title) self.multiple = multiple self.mode = mode if not path: if self.mode == "image" : path = EkdConfig.get("general", "image_output_path") elif self.mode == "video" : path = EkdConfig.get("general", "video_output_path") elif self.mode == "audio" : path = EkdConfig.get("general", "sound_output_path") else : path = unicode(QDir.homePath()) # Nom du répertoire courant self.location = QLabel("<b>%s</b>" % path) # Variable permettant de savoir à tout moment le répertoire courant. self.currentDir = path self.mkdirButton = QPushButton(u" Créer un répertoire") self.mkdirButton.setIcon(QIcon("Icones" + os.sep + "add_sub_task.png")) if int(EkdConfig.get("general", "show_hidden_files")) : #print "hidden shown" EkdPrint(u"hidden shown") shf = QDir.Hidden else : shf = QDir.Readable # Liste des fichiers self.dirList = QListView() sorting = QDir.DirsFirst if int(EkdConfig.get("general", "ignore_case")): sorting |= QDir.IgnoreCase self.sorting = sorting self.flags = QDir.Files | QDir.Readable | shf self.dirModel = QStandardItemModel() self.dirList.setModel(self.dirModel) self.updateDir(path) self.dirList.setWrapping(True) #panneau latéral self.dirTree = QTreeView() self.dirModelLight = QDirModel(QStringList(""), QDir.AllDirs | QDir.NoDotAndDotDot | shf, QDir.DirsFirst | QDir.Name | QDir.IgnoreCase) self.dirTree.setModel(self.dirModelLight) self.dirTree.setColumnHidden(1,True) self.dirTree.setColumnHidden(2,True) self.dirTree.setColumnHidden(3,True) self.dirTree.setMaximumWidth(200) self.dirTree.setMinimumWidth(150) self.dirTree.setCurrentIndex(self.dirModelLight.index(path)) self.dirTree.resizeColumnToContents(0) self.connect(self.dirTree, SIGNAL("pressed(QModelIndex)"), self.updateLatDir) self.connect(self.dirTree, SIGNAL("expanded(QModelIndex)"), self.treeMAJ) self.connect(self.dirTree, SIGNAL("collapsed(QModelIndex)"), self.treeMAJ) # Nom du fichier self.fileField = QLineEdit() # Nom du filtre self.filterField = QComboBox() self.filterField.addItems(QStringList(self.filter)) # Bouton de sauvegarde et d'annulation self.saveButton = QPushButton(_(u" Enregistrer")) self.saveButton.setIcon(QIcon("Icones" + os.sep + "action.png")) self.cancelButton = QPushButton(_(u" Annuler")) self.cancelButton.setIcon(QIcon("Icones" + os.sep + "annuler.png")) # Organisation des différents objets de la boite de dialogue self.layout = QHBoxLayout(self) self.layout.addWidget(self.dirTree) self.filelinelayout = QGridLayout() self.filelinelayout.addWidget(self.location, 0, 0, 1, 0) self.filelinelayout.addWidget(self.mkdirButton, 0, 2) self.filelinelayout.addWidget(self.dirList, 1, 0, 1, 0) self.filelinelayout.addWidget(QLabel(_("Nom de fichier : ")), 2, 0) self.filelinelayout.addWidget(self.fileField, 2, 1) self.filelinelayout.addWidget(self.saveButton, 2, 2) self.filelinelayout.addWidget(QLabel(_("Filtre extension : ")), 3, 0) self.filelinelayout.addWidget(self.filterField, 3, 1) self.filelinelayout.addWidget(self.cancelButton, 3, 2) self.layout.addLayout(self.filelinelayout) # Connexion des différents objets self.connect(self.dirList, SIGNAL("clicked(QModelIndex)"), self.updateFile) self.connect(self.saveButton, SIGNAL("clicked()"), self.accept) self.connect(self.cancelButton, SIGNAL("clicked()"), self.reject) self.connect(self.mkdirButton, SIGNAL("clicked()"), self.mkdir) self.connect(self.dirList, SIGNAL("indexesMoved (const QModelIndexList&)"), self.updateFile) self.connect(self.fileField, SIGNAL("textChanged (const QString&)"), self.activate) self.connect(self.fileField, SIGNAL("returnPressed()"), self.accept) # Taille minimum self.setMinimumSize(700, 480) # Par défaut, on désactive self.deactivate() # Completion des fichiers self.completion = QCompleter(self.dirModel, self.dirList) def updateLatDir(self, item) : """ Fonction permettant de naviguer dans la listes des répertoires """ self.updateDir(self.dirModelLight.filePath(item)) def treeMAJ(self, item) : self.dirTree.resizeColumnToContents(0) def activate(self, filename=None): """ Activation des boutton de sauvegarde """ self.dirList.clearSelection() if filename != "": self.saveButton.setEnabled(True) else: self.saveButton.setEnabled(False) def deactivate(self): """ Désactivation des boutton de sauvegarde """ self.saveButton.setEnabled(False) def updateDir(self, path = None): """ Fonction permettant de naviguer dans la listes des répertoires """ if path : self.currentDir = path self.location.setText("<b>%s</b>" % path) self.dirModel.clear() self.tmpdir = QDir() self.tmpdir.setPath(self.currentDir) self.tmpdir.setNameFilters(QStringList(self.filter)) # Une icône pour les images, un autre icône pour les vidéos, et # une pour audio if self.mode == "image" : icone = QIcon("Icones" + os.sep + "image_image.png") elif self.mode == "video" : icone = QIcon("Icones" + os.sep + "image_video.png") elif self.mode == "audio" : icone = QIcon("Icones" + os.sep + "image_audio.png") else: icone = QIcon("Icones" + os.sep + "image_default.png") for wlfile in self.tmpdir.entryList(QDir.Files): if self.mode == "image" : icone = QIcon(EkdPreview("Icones" + os.sep + "image_default.png").get_preview()) item = QStandardItem(icone, QString(wlfile)) item.setToolTip(wlfile) item.setData(QVariant(self.tmpdir.absolutePath() + os.sep + wlfile), Qt.UserRole + 2) item.setData(QVariant(wlfile), Qt.UserRole + 3) self.dirModel.appendRow(item) def updateFile(self, item): """ Fonction appelée par la listView lors d'un changement de repertoire""" # On récupère le QModel parent du QModelItem path = "%s" % item.data(Qt.UserRole + 2).toString() name = os.path.basename(path) self.fileField.selectAll() self.fileField.setFocus() self.fileField.setText(name) self.activate(name) def selectedFile(self): """ Renvoi le fichier selectionné pour la sauvegarde""" # Récupération du fichier selectionné fichier = self.fileField.text() output = "%s%s%s" % (self.currentDir, os.sep, fichier) info = QFileInfo(output) # Si l'utilisateur n'a pas spécifié de suffix, on l'ajoute if info.suffix() != self.suffix[1:]: output = "%s%s" % (output, self.suffix) return output def mkdir(self): """ Crée un répertoire dans le répertoire courant """ (dirname, ok) = QInputDialog.getText(self, _(u"Nouveau répertoire"), _(u"Nom du répertoire"), QLineEdit.Normal, _(u"Nouveau répertoire")) if ok : try : os.mkdir("%s%s%s" % (self.currentDir, os.sep,dirname)) #print u"Création de : %s%s%s" % (self.currentDir, os.sep, dirname) EkdPrint(u"Création de : %s%s%s" % (self.currentDir, os.sep, dirname)) self.updateDir() self.dirModelLight.refresh() except Exception, e: #print _(u"Impossible de crée un nouveau répertoire : %s" % e) EkdPrint(_(u"Impossible de crée un nouveau répertoire : %s" % e))
class EasyImport: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'EasyImport_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = EasyImportDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&EasyImport') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'EasyImport') self.toolbar.setObjectName(u'EasyImport') # Root folder where shape files are stored self.shapeDirectory = QDir() # XML Config file self.configXML = QtXml.QDomDocument() # XML current Config self.currentConfigXML = QtXml.QDomElement() # XML Config path self.configFileName = 'config.xml' # Shape file dictionnary # shapeFiles[shape filename] = shapefile absolute path self.shapeFiles = {} # Shape file dictionnary # pointsLayersConfig[shape filename] = Import rules XML nodes self.pointsLayersConfig = {} # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('EasyImport', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/EasyImport/icon.png' self.add_action(icon_path, text=self.tr(u'EasyImport'), callback=self.run, parent=self.iface.mainWindow()) # Load settings from XML self.loadConfig() # Set event handlers self.dlg.btnBrowse.clicked.connect(self.setShapeDirectory) self.dlg.btnImport.clicked.connect(self.runImport) self.dlg.cbxConfig.currentIndexChanged.connect(self.cbxConfigChanged) self.dlg.txtDirectory.textEdited.connect(self.txtDirectoryChanged) def txtDirectoryChanged(self, text): self.shapeDirectory = QDir(text) self.getShapeFiles() def setShapeDirectory(self): """Display folder browser dialog.""" file = QFileDialog.getExistingDirectory( None, 'Select gps/shape file directory.') self.dlg.txtDirectory.setText(file) self.shapeDirectory = QDir(file) def cbxConfigChanged(self, id): """Reset config on configuration combox box changes.""" self.pointsLayersConfig.clear() self.setCurrentConfig(self.dlg.cbxConfig.itemData(id)) def getShapeFiles(self): """Get each shapefile in defined folder.""" self.shapeFiles.clear() shapefiles = self.shapeDirectory.entryList(['*.shp'], QDir.Files, QDir.Name) for file in shapefiles: # Populate the shape dictionnary self.shapeFiles[file.split('.', 1)[0]] = file # print self.shapeFiles.keys() def removeShapeFiles(self, shapeFiles): """Removes generated shapefiles""" for code in shapeFiles.keys(): paths = str(self.shapeDirectory.absolutePath() + '/' + code + '.*') files = glob(paths) # print paths for file in files: os.remove(file) def getAsciiFiles(self): """Get each asciifile in defined folder.""" # self.asciiFiles.clear() asciifiles = self.shapeDirectory.entryList(['*.asc'], QDir.Files, QDir.Name) for file in asciifiles: # Convert into shapefile self.ascii2shape(file) def ascii2shape(self, file): """Convert every input from the ascii file to the corresponding shapefile and creates it if it does not exists yet. :param file: ascii file to be converted""" # Read ascii with open(self.shapeDirectory.absolutePath() + '/' + file, 'r') as f: content = f.readlines() ind = 0 # Set spatial ref and driver driver = ogr.GetDriverByName('ESRI Shapefile') srs = osr.SpatialReference() epsg21781wkt = 'PROJCS["CH1903 / LV03",GEOGCS["CH1903",DATUM["CH1903",SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],TOWGS84[674.374,15.056,405.346,0,0,0,0],AUTHORITY["EPSG","6149"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4149"]],UNIT["metre",1,AUTHORITY["EPSG","9001"]],PROJECTION["Hotine_Oblique_Mercator"],PARAMETER["latitude_of_center",46.95240555555556],PARAMETER["longitude_of_center",7.439583333333333],PARAMETER["azimuth",90],PARAMETER["rectified_grid_angle",90],PARAMETER["scale_factor",1],PARAMETER["false_easting",600000],PARAMETER["false_northing",200000],AUTHORITY["EPSG","21781"],AXIS["Y",EAST],AXIS["X",NORTH]]' srs.ImportFromWkt(epsg21781wkt) # Start iteration on features for line in content: # Remove undesirables tabs and double spaces removedTabs = re.sub(r"\s+", " ", content[ind]) # split fields values line_fields = removedTabs.split(' ') # Avoid uncompleted lines if (len(line_fields) > 4): # Create the dictionnary featureDict = [ 'GPSID', 'TYPE', 'CODE', 'Y', 'X', 'Z', 'DELTA', 'COMMENT' ] # Extract the information featureDict[0] = str(line_fields[0]) # featureDict[0] = int(re.findall(r'\d+', line_fields[0])[0]) featureDict[1] = str( re.findall('[a-zA-Z]+', line_fields[0])[0]) try: featureDict[2] = int(line_fields[5]) except ValueError: featureDict[2] = 999 featureDict[3] = str(line_fields[1]) featureDict[4] = str(line_fields[2]) featureDict[5] = str(line_fields[3]) featureDict[6] = float(line_fields[4]) featureDict[7] = ' '.join(line_fields[6:]) ofilepath = self.shapeDirectory.absolutePath() + '/' + str( featureDict[2]) + '.shp' if not os.path.exists(ofilepath): dataSource = driver.CreateDataSource(ofilepath) olayer = dataSource.CreateLayer("points", srs, geom_type=ogr.wkbPoint25D) olayer.CreateField(ogr.FieldDefn("Point_ID", ogr.OFTString)) olayer.CreateField(ogr.FieldDefn("Ortho_Heig", ogr.OFTReal)) else: dataSource = driver.Open(ofilepath, 1) olayer = dataSource.GetLayer() # print ofilepath # Set feature fields feature = ogr.Feature(olayer.GetLayerDefn()) feature.SetField("Point_ID", featureDict[0]) feature.SetField("Ortho_Heig", featureDict[5]) # Set geometry geom_wkt = 'POINT (' + featureDict[3] + ' ' + featureDict[ 4] + ' ' + featureDict[5] + ')' point = ogr.CreateGeometryFromWkt(geom_wkt) feature.SetGeometry(point) # Create feature olayer.CreateFeature(feature) # remove feature and datasource from memory feature.Destroy() dataSource.Destroy() # else: #additional behaviour in case of uncompleted line # increment ind += 1 def setCurrentConfig(self, idConfig): """Load configuration from XML based on configuration id. :param idConfig: configuration id's stored in XML. :type text: str """ # Get config node childrens if config id = idConfig root = self.configXML.documentElement() configs = root.elementsByTagName('config') for index in range(configs.count()): if configs.at(index).hasAttributes(): nodeAttributes = configs.at(index).attributes() if nodeAttributes.namedItem('id').nodeValue() == idConfig: self.currentConfigXML = configs.at(index) # Get all pointlayer nodes layerspoints = self.currentConfigXML.toElement().elementsByTagName( 'pointlayer') # Populate import rules (pointsLayersConfig) for index in range(layerspoints.count()): if layerspoints.at(index).hasAttributes(): self.pointsLayersConfig[layerspoints.at( index).toElement().attributeNode( 'code').value()] = layerspoints.at(index).toElement() def loadConfig(self): """Load configuration combobox with configurations stored in XML configuration file.""" XMLFile = QFile(self.plugin_dir + '/' + self.configFileName) if not XMLFile.open(QFile.ReadOnly | QFile.Text): QMessageBox.warning( self.iface.mainWindow(), "XML Configuration", "Cannot read file %s:\n%s." % (self.plugin_dir + '/' + self.configFileName, XMLFile.errorString()), QMessageBox.Ok) return False ok, errorStr, errorLine, errorColumn = self.configXML.setContent( XMLFile, True) if not ok: QMessageBox.information( self.iface.mainWindow(), "XML Configuration", "Parse error at line %d, column %d:\n%s" % (errorLine, errorColumn, errorStr)) return False root = self.configXML.documentElement() configs = root.elementsByTagName('config') for index in range(configs.count()): if configs.at(index).hasAttributes(): nodeAttributes = configs.at(index).attributes() self.dlg.cbxConfig.addItem( nodeAttributes.namedItem('name').nodeValue(), nodeAttributes.namedItem('id').nodeValue()) self.setCurrentConfig( self.dlg.cbxConfig.itemData(self.dlg.cbxConfig.currentIndex())) return True def runImport(self): self.getAsciiFiles() self.getShapeFiles() if len(self.shapeFiles) <= 0: QMessageBox.warning(self.iface.mainWindow(), "Shape import", "No shape file found.") return #Shapefiles that match the config code codes = set(self.shapeFiles.keys()) & set( self.pointsLayersConfig.keys()) # Maximum value of progress bar is the number of shapefile self.dlg.pgbImport.setMaximum(len(codes)) # For each Shapefiles that match the config code for k in codes: # Import data based on config self.importData( self.shapeDirectory.absolutePath() + "/" + self.shapeFiles[k], k) # Increment progress bar self.dlg.pgbImport.setValue(self.dlg.pgbImport.value() + 1) self.removeShapeFiles(self.shapeFiles) def importData(self, filename, code): """Import data from shapefile to an specified layer in project. :param filename: shapefile filename. :type text: str :param code: shapefile name. :type text: str """ driver = ogr.GetDriverByName('ESRI Shapefile') layers = QgsMapLayerRegistry.instance().mapLayers() destinationlayer = None colunmMappingDict = {} staticMappingDict = {} regexMappingDict = {} destinationLayerName = self.pointsLayersConfig[code].elementsByTagName( 'destinationlayer').item(0).toElement().text() columnMappings = self.pointsLayersConfig[code].elementsByTagName( 'columnmapping') staticMappings = self.pointsLayersConfig[code].elementsByTagName( 'staticmapping') # No destination layer found in XML if destinationLayerName is None: return for k in layers.keys(): if layers[k].name() == destinationLayerName: destinationlayer = layers[k] # No destination layer found in QGis Project if destinationlayer is None: return dataSource = driver.Open(filename, 0) if dataSource is None: self.dlg.txtOut.appendPlainText('Could not open %s \n' % (filename)) else: self.dlg.txtOut.appendPlainText('Opened %s' % (filename)) layer = dataSource.GetLayer() featureCount = layer.GetFeatureCount() # Get import rules with column mappings for index in range(columnMappings.count()): sourcecolumnname = columnMappings.at(index).toElement( ).elementsByTagName('source').item(0).toElement().text() destinationcolumnname = columnMappings.at(index).toElement( ).elementsByTagName('destination').item(0).toElement().text() regex = columnMappings.at(index).toElement().elementsByTagName( 'regex') if not (regex is None): regexMappingDict[sourcecolumnname] = regex.item( 0).toElement().text() colunmMappingDict[sourcecolumnname] = destinationcolumnname # Get import rules with static value mappings for index in range(staticMappings.count()): staticValue = staticMappings.at(index).toElement( ).elementsByTagName('value').item(0).toElement().text() destinationcolumnname = staticMappings.at(index).toElement( ).elementsByTagName('destination').item(0).toElement().text() staticMappingDict[destinationcolumnname] = staticValue # Enable edit mode on destination layer destinationlayer.startEditing() # Retrieve all column off destination layer fields = destinationlayer.pendingFields() # For each data in shapefile for feature in layer: #Create new feature in destination layer and get geometry from shapefile newFeature = QgsFeature(fields) newFeature.setGeometry( QgsGeometry.fromWkt(str(feature.GetGeometryRef()))) # For each column mapping for k in colunmMappingDict.keys(): # print "source %s -> destination %s" % (k,colunmMappingDict[k]) # With regex if regexMappingDict[k]: regexp = re.compile(regexMappingDict[k]) # print str(k) # print feature.GetField(str(k)) m = regexp.match(feature.GetField(str(k))) if not (m is None): # print 'Regex : %s --> Value : %s' % (regexMappingDict[k], m.group('group')) newFeature.setAttribute( fields.fieldNameIndex(colunmMappingDict[k]), m.group('group')) # Without regex else: newFeature.setAttribute( fields.fieldNameIndex(colunmMappingDict[k]), feature.GetField(str(k))) # For each static value mapping for k in staticMappingDict.keys(): #print "destination %s -> value %s" % (k,staticMappingDict[k]) newFeature.setAttribute(fields.fieldNameIndex(k), staticMappingDict[k]) # Add new feature in destination layer destinationlayer.addFeature(newFeature, True) self.dlg.txtOut.appendPlainText('Shape %s : %s features imported \n' % (code, featureCount)) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(self.tr(u'&EasyImport'), action) self.iface.removeToolBarIcon(action) def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # Reset progress bar value self.dlg.pgbImport.setValue(0) # Reset output text box self.dlg.txtOut.clear() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass