def __init__(self, parent, plugin): QDialog.__init__(self, parent) self.setupUi(self) self.plugin = plugin self.mResult = "" self.progressBar.setRange(0, 0) self.progressBar.setFormat("%p%") self.labelName.setText(plugin["name"]) self.buttonBox.clicked.connect(self.abort) url = QUrl(plugin["download_url"]) fileName = plugin["filename"] tmpDir = QDir.tempPath() tmpPath = QDir.cleanPath(tmpDir + "/" + fileName) self.file = QFile(tmpPath) self.request = QNetworkRequest(url) authcfg = repositories.all()[plugin["zip_repository"]]["authcfg"] if authcfg and isinstance(authcfg, basestring): if not QgsAuthManager.instance().updateNetworkRequest( self.request, authcfg.strip()): self.mResult = self.tr( "Update of network request with authentication " "credentials FAILED for configuration '{0}'").format(authcfg) self.request = None if self.request is not None: self.reply = QgsNetworkAccessManager.instance().get(self.request) self.reply.downloadProgress.connect(self.readProgress) self.reply.finished.connect(self.requestFinished) self.stateChanged(4)
def main(): pyqtRemoveInputHook() QDir(QDir.homePath()).mkdir(".ricodebug") app = QApplication(sys.argv) app.setApplicationName("ricodebug") Icons() # We use all kinds of loggers here: # * a CriticalLogHandler that will abort the program whenever a critical error is received # * a FileHandler writing to a log in the home directory (all messages, for debugging) # * a LogViewHandler to have the log available in the GUI # * a ErrorLabelHandler that visually notifies the user of an error or a warning logger = logging.getLogger() formatter = logging.Formatter('[%(levelname)-8s] : %(filename)15s:%(lineno)4d/%(funcName)-20s : %(message)s') filehandler = logging.FileHandler(filename='%s/.ricodebug/ricodebug.log' % str(QDir.homePath())) filehandler.setFormatter(formatter) logger.addHandler(filehandler) logger.setLevel(logging.DEBUG) logger.addHandler(criticalloghandler.CriticalLogHandler()) window = MainWindow() logger.addHandler(window.logviewhandler) logger.addHandler(window.notificationFrameHandler) if (len(sys.argv) > 1): window.debugController.openExecutable(sys.argv[1]) window.show() logging.shutdown() sys.exit(app.exec_())
def __init__(self, file, recurse = True, recursion_counter = None, namingregex = None): super(FileSystemItem, self).__init__() # Raise exception if root path has too many child elements if recursion_counter: recursion_counter.increment() if isinstance(file, QFileInfo): self.fileinfo = file else: self.fileinfo = QFileInfo(file) self.fullpath = self.fileinfo.absoluteFilePath() self.basename = self.fileinfo.completeBaseName() self.displayname = self.fileinfo.fileName() if self.fileinfo.isDir() else self.fileinfo.completeBaseName() if namingregex: self.displayname = namingregex.match(self.displayname).group(1) self.icon = FileSystemItem.iconProvider.icon(self.fileinfo) self.isdir = self.fileinfo.isDir() self.children = [] if self.isdir else None if self.isdir and recurse: qdir = QDir(self.fullpath) for finfo in qdir.entryInfoList( FileSystemItem.fileExtensions , QDir.Files | QDir.AllDirs | QDir.NoDotAndDotDot,QDir.Name): self.children.append(FileSystemItem(finfo, recurse, recursion_counter, namingregex)) else: # file # Populate this if and when needed self.searchablecontent = None
def __init__(self, parent=None): custom_dock.CustomDock.__init__(self) self.explorador = QTreeView() self.setWidget(self.explorador) self.explorador.header().setHidden(True) self.explorador.setAnimated(True) # Modelo self.modelo = QFileSystemModel(self.explorador) path = QDir.toNativeSeparators(QDir.homePath()) self.modelo.setRootPath(path) self.explorador.setModel(self.modelo) self.modelo.setNameFilters(["*.c", "*.h", "*.s"]) self.explorador.setRootIndex(QModelIndex(self.modelo.index(path))) self.modelo.setNameFilterDisables(False) # Se ocultan algunas columnas self.explorador.hideColumn(1) self.explorador.hideColumn(2) self.explorador.hideColumn(3) # Conexion self.explorador.doubleClicked.connect(self._abrir_archivo) EDIS.cargar_lateral("explorador", self)
def __init__(self, conversationId): super(ChatWidget, self).__init__() self._conversationId = conversationId self._windowTitle = Contacts.instance().getName(self._conversationId) self._ownJid = Contacts.instance().phoneToConversationId(getConfig('countryCode') + getConfig('phoneNumber')) self._defaultContactPicture = '/%s/im-user.png' % QDir.searchPaths('icons')[0] self._chatViewUrl = QUrl('file://%s/ChatView.html' % QDir.searchPaths('html')[0]) self._historyTimestamp = datetime.date.today() self._scrollTimer = QTimer() self._scrollTimer.setSingleShot(True) self._scrollTimer.timeout.connect(self.on_scrollToBottom) self.scroll_to_bottom_signal.connect(self.on_scrollToBottom, Qt.QueuedConnection) loadUi(os.path.join(QDir.searchPaths('ui')[0], 'ChatWidget.ui'), self) self.setWindowTitle(self._windowTitle) self.historyButton.setIcon(QIcon.fromTheme('clock')) self.visibilityChanged.connect(self.on_visibilityChanged) self.chatView.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) self.__on_messageText_keyPressEvent = self.messageText.keyPressEvent self.messageText.keyPressEvent = self.on_messageText_keyPressEvent self.show_message_signal.connect(self.showMessage) self.show_history_message_signal.connect(self.showMessage) self.show_history_since_signal.connect(self.showHistorySince) self.show_history_num_messages_signal.connect(self.showHistoryNumMessages) self.has_unread_message_signal.connect(self.unreadMessage) self.reloadChatView() self.showHistorySince(datetime.date.today(), minMessage=3, maxMessages=10)
def __locate_code_in_project(self, queue_folders, nproject): file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable while not self._cancel and not queue_folders.empty(): current_dir = QDir(queue_folders.get()) #Skip not readable dirs! if not current_dir.isReadable(): continue #Collect all sub dirs! current_sub_dirs = current_dir.entryInfoList(dir_filter) for one_dir in current_sub_dirs: queue_folders.put(one_dir.absoluteFilePath()) #all files in sub_dir first apply the filters current_files = current_dir.entryInfoList( ['*{0}'.format(x) for x in nproject.extensions], file_filter) #process all files in current dir! global files_paths for one_file in current_files: try: self._grep_file_symbols(one_file.absoluteFilePath(), one_file.fileName()) files_paths[nproject.path].append( one_file.absoluteFilePath()) except Exception as reason: logger.error( '__locate_code_in_project, error: %r' % reason) logger.error( '__locate_code_in_project fail for file: %r' % one_file.absoluteFilePath())
def locate_code(self): explorerContainer = explorer_container.ExplorerContainer() projects_obj = explorerContainer.get_opened_projects() projects = [p.path for p in projects_obj] if not projects: return queue = Queue.Queue() for project in projects: queue.put(project) file_filter = QDir.Files | QDir.NoDotAndDotDot | QDir.Readable dir_filter = QDir.Dirs | QDir.NoDotAndDotDot | QDir.Readable while not self._cancel and not queue.empty(): current_dir = QDir(queue.get()) #Skip not readable dirs! if not current_dir.isReadable(): continue #Collect all sub dirs! current_sub_dirs = current_dir.entryInfoList(dir_filter) for one_dir in current_sub_dirs: queue.put(one_dir.absoluteFilePath()) current_sub_dirs = current_dir.entryInfoList(dir_filter) #all files in sub_dir first apply the filters current_files = current_dir.entryInfoList( ['*{0}'.format(x) for x in settings.SUPPORTED_EXTENSIONS], file_filter) #process all files in current dir! for one_file in current_files: self._grep_file_locate(unicode(one_file.absoluteFilePath()), one_file.fileName()) self.dirty = True self.get_locations()
def linux(self): if not self.aBaslat.isChecked(): setting.setValue("ContextMenu/AcilistaBaslat", False) dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart", "Virux.desktop") if os.path.isfile(dosyaYolu): os.remove(dosyaYolu) else: setting.setValue("ContextMenu/AcilistaBaslat", True) dosyaYolu = os.path.join(str(QDir.homePath()), ".kde", "Autostart", "Virux.desktop") desktop = """[Desktop Entry] Comment[tr]=Platform bağımsız bir antivirüs uygulaması Comment=Platform bağımsız bir antivirüs uygulaması Exec=python %s/virux.py GenericName[tr]=Platform bağımsız bir antivirüs uygulaması GenericName=Platform bağımsız bir antivirüs uygulaması Icon=%s Type=Application Name[tr]=Virux Name=Virux Path= StartupNotify=true Terminal=false """ % ( mainPath, os.path.join(mainPath, "data", "logo.png"), ) yaz = open(dosyaYolu, "w") yaz.write(desktop) yaz.close()
def __init__(self, canvas, fileName="Unknown", parent=None): """ Initialize the dialog. """ super(ExportBitmapDialog, self).__init__(parent) self.setupUi(self) self._determine_image_formats() self._add_image_formats_to_gui() if fileName: self.fullPath = QDir.homePath() + "/" + QFileInfo(fileName).baseName() else: self.fullPath = QDir.homePath() + "/" extension = self.selected_file_extension() self.fileNameEdit.setText(self.fullPath + "." + extension) # NOTE: This has to come first since we rely on them # to syncronize the widgets self._set_up_connections() self.canvas = canvas self.currentUnit = 0 self.unitSelector.setCurrentIndex(self.currentUnit) self.defaultDPI = 300 self.update_dimensions() self.dpiSpinner.setValue(self.defaultDPI)
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 locate_code(self): explorerContainer = explorer_container.ExplorerContainer() projects_obj = explorerContainer.get_opened_projects() projects = [p.path for p in projects_obj] if not projects: return queue = Queue.Queue() for project in projects: queue.put(project) while not self._cancel and not queue.empty(): current_dir = QDir(queue.get()) #Skip not readable dirs! if not current_dir.isReadable(): continue project_data = project = json_manager.read_ninja_project( current_dir.path()) extensions = project_data.get('supported-extensions', settings.SUPPORTED_EXTENSIONS) queue_folders = Queue.Queue() queue_folders.put(current_dir) self.__locate_code_in_project(queue_folders, extensions) self.dirty = True self.get_locations()
def testComposition(self, page=0, pixelDiff=0 ): if self.mComposition is None: myMessage = "Composition not valid" return False, myMessage #load expected image self.setControlName("expected_"+self.mTestName) # get width/height, create image and render the composition to it outputImage = QImage( self.mSize, QImage.Format_RGB32 ) self.mComposition.setPlotStyle( QgsComposition.Print ) outputImage.setDotsPerMeterX( self.mDotsPerMeter ) outputImage.setDotsPerMeterY( self.mDotsPerMeter ) QgsMultiRenderChecker.drawBackground( outputImage ) p = QPainter( outputImage ) self.mComposition.renderPage( p, page ) p.end() renderedFilePath = QDir.tempPath() + QDir.separator() + QFileInfo(self.mTestName).baseName() + "_rendered.png" outputImage.save( renderedFilePath, "PNG" ) self.setRenderedImage( renderedFilePath ) testResult = self.runTest( self.mTestName, pixelDiff ) return testResult, self.report()
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 validate(self): """ :return: Return True if the source document directory exists, otherwise False. :rtype: bool """ source_doc_path = self.txtRootFolder.text() #Clear previous notifications self._notif_bar.clear() if not source_doc_path: msg = self.tr( 'Please set the root directory of source documents.' ) self._notif_bar.insertErrorNotification(msg) return False dir = QDir() if not dir.exists(source_doc_path): msg = self.tr(u"'{0}' directory does not exist.".format( source_doc_path)) self._notif_bar.insertErrorNotification(msg) return False return True
def parse_settings_from_ui(self): # Download settings download_data = {} download_default_folder = self.ui.lineedit_default_download_folder.text() dir_check = QDir(download_default_folder) if dir_check.exists(): download_data["default-folder"] = str(download_default_folder) else: download_data["default-folder"] = self.config_helper.datahandler.get_data_dir_path() self.ui.lineedit_default_download_folder.setText(download_data["default-folder"]) self.main_ui_handler.show_banner("Could not validate default download folder " + str(download_default_folder) + ", reseted to default") self.logger.warning("Default download folder invalid, reseted to default") download_data["no-dialog"] = self.ui.checkbox_no_dl_dialog.isChecked() # Authentication settings authentication_data = {} authentication_data["store-auth"] = self.ui.checkbox_enable_store_auth.isChecked() # Automated sync automate_sync_data = {} automate_sync_data["enabled"] = self.ui.checkbox_enable_sync.isChecked() automate_sync_data["only-sync-on-wlan"] = self.ui.checkbox_only_wlan_sync.isChecked() automate_sync_data["update-interval"] = self.ui.spinbox_sync_interval.value() automate_sync_data["sync-path"] = str(self.sync_path_button.valueText()) self.config_helper.write_settings(download_data, authentication_data, automate_sync_data)
def rename (self, songs): # TODO: parametrize the main music colleciton mainColl= self.collaggr.collections[0] base= mainColl.path d= QDir () for song in songs: dstPath= self.songPath (base, song) dstDir= os.path.dirname (dstPath) # TODO: QtDir is not net transp. try to make sub jobs creating the missing path if d.mkpath (dstDir): # HINT: KUrl because KIO.* use KUrl # src= KUrl (song.filepath) src= KUrl (utils.path2qurl (song.filepath)) # BUG: Renamer.rename() # PyQt4.QtCore.QUrl(u'file:///home/mdione/media/music/new/bandidos rurales/05 - uruguay, uruguay.mp3') -> # PyQt4.QtCore.QUrl(u'file:///home/mdione/media/music/Le\xf3n Gieco/2001 - Bandidos rurales/05 - Uruguay, Uruguay.mp3') # ^^^^ dst= KUrl (dstPath) logger.info ("Renamer.rename()", src, "->", dst) # TODO: do not launch them all in parallel job= KIO.file_move (src, dst) # TODO: emit a finished. # print "Renamer.rename()", job job.result.connect (self.jobFinished) # print "Renamer.rename(): connected" self.jobs.append (job) # print "Renamer.rename(): next!" else: logger.info ("Renamer.rename(): failed to create", dstDir, ", skipping", dstPath)
def _check_path_exists(self, path, text_box): #Validates if the specified folder exists dir = QDir() if not dir.exists(path): msg = self.tr(u"'{0}' directory does not exist.".format(path)) self.notif_bar.insertErrorNotification(msg) #Highlight textbox control text_box.setStyleSheet(INVALIDATESTYLESHEET) timer = QTimer(self) #Sync interval with that of the notification bar timer.setInterval(self.notif_bar.interval) timer.setSingleShot(True) #Remove previous connected slots (if any) receivers = timer.receivers(SIGNAL('timeout()')) if receivers > 0: self._timer.timeout.disconnect() timer.start() timer.timeout.connect(lambda:self._restore_stylesheet( text_box) ) return False return True
def setup_logger(): from stdm.settings.registryconfig import debug_logging logger = logging.getLogger('stdm') logger.setLevel(logging.ERROR) # Create log directory if it does not exist log_folder = QDir() if not log_folder.exists(LOG_DIR): status = log_folder.mkpath(LOG_DIR) # Log directory could not be created if not status: raise IOError('Log directory for STDM could not be created.') # File handler for logging debug messages file_handler = TimedRotatingFileHandler(LOG_FILE_PATH, when='D', interval=1, backupCount=14) file_handler.setLevel(logging.DEBUG) # Create formatter and add it to the handler formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) # Add handler to the logger logger.addHandler(file_handler) # Enable/disable debugging. Defaults to ERROR level. lvl = debug_logging() if lvl: file_handler.setLevel(logging.DEBUG) else: file_handler.setLevel(logging.ERROR)
def s_browse(self): directory = QFileDialog.getExistingDirectory(self,QDir.homePath(), QDir.homePath()) if directory!="": path = check_repository(directory) if path[0]: self.ui.Source_lineEdit.clear() self.ui.Source_lineEdit.insert(directory) else: QMessageBox.critical(self, "Error", "That directory is not a git repository", QMessageBox.Ok)
def mkdir(self, path): directory = QDir(path) SCJ.lock.lock() if not directory.exists() : if not directory.mkpath(path) : self.emit(SIGNAL("error(QString)"), QString(self.trUtf8("Cannot create %s" % path))) SCJ.lock.unlock()
def fromFile(cls, filename): QDir.setCurrent(os.path.dirname(filename)) fileinfo = QFileInfo(filename) QgsProject.instance().read(fileinfo) xml = open(filename).read() doc = QDomDocument() doc.setContent(xml) return cls(doc)
def get_music_storage_folder(): storage_path = "%s%s%s" % (QDesktopServices.storageLocation(QDesktopServices.DataLocation).replace("\\", "/"), Config.DataPrefix, Config.MusicPrefix) dir = QDir(storage_path) if dir.exists() != True: dir.mkpath('.') return storage_path
def fillGrid2(self,home): print (QDir.currentPath()) self.fileSystemModel.setRootPath(QDir.currentPath()) self.ui.treeView.setModel(self.fileSystemModel) self.ui.treeView.setRootIndex(self.fileSystemModel.index(QDir.currentPath())) self.ui.treeView.hideColumn(1) self.ui.treeView.hideColumn(2) self.ui.treeView.hideColumn(3)
def loadqgisproject(self, project, projectfile): QDir.setCurrent(os.path.dirname(project.projectfile)) fileinfo = QFileInfo(project.projectfile) # No idea why we have to set this each time. Maybe QGIS deletes it for # some reason. self.badLayerHandler = BadLayerHandler(callback=self.missing_layers) QgsProject.instance().setBadLayerHandler(self.badLayerHandler) QgsProject.instance().read(fileinfo)
def getWidgetStateIcons(cls): if not hasattr(cls, "_cached__widget_state_icons"): iconsDir = os.path.join(environ.canvas_install_dir, "icons") QDir.addSearchPath("canvasIcons", os.path.join(environ.canvas_install_dir, "icons/")) info = QPixmap("canvasIcons:information.png") warning = QPixmap("canvasIcons:warning.png") error = QPixmap("canvasIcons:error.png") cls._cached__widget_state_icons = {"Info": info, "Warning": warning, "Error": error} return cls._cached__widget_state_icons
def initialize(): """Initialize support for the icons. Called on app startup.""" QDir.setSearchPaths("icons", __path__) # use our icon theme (that builds on Tango) if there are no system icons if (not QIcon.themeName() or QIcon.themeName() == "hicolor" or not QSettings().value("system_icons", True, bool)): QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + __path__) QIcon.setThemeName("TangoExt")
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 index_path(): options = Configuration._read_options( config_file=Configuration.INDEXING_CONFIG_FILE, config_file_header=Configuration.INDEXING_CONFIG_FILE_HEADER ) if Configuration.INDEXING_CONFIG_PATH in options: return QDir.fromNativeSeparators(options[Configuration.INDEXING_CONFIG_PATH]) return QDir.fromNativeSeparators('%s/%s' % (QDir.homePath(), 'index_db'))
def importFromDirectory(self, path): d = QDir(path) d.setFilter(QDir.Files | QDir.Hidden) #d.setSorting(QDir.Size | QDir.Reversed) for fileInfo in d.entryInfoList(): if debug_mode == 0 and fileInfo.fileName() == "debug.tsv": continue if fileInfo.suffix().lower() == "tsv": self.importFromTsv(fileInfo.filePath())
def getfile(self): path=QFileDialog.getOpenFileName(self, 'Open file', self.lineEditvalue.text(),"text files (*.txt *.*)") self.lineEditvalue.setText(QDir.toNativeSeparators(path)) self.upconfig()
def runAndCreateLayer(parent): geomDialog = QgsNewVectorLayerDialog(parent) if (geomDialog.exec_() == QDialog.Rejected): return "" geometrytype = geomDialog.selectedType() fileformat = geomDialog.selectedFileFormat() enc = geomDialog.selectedFileEncoding() crsId = geomDialog.selectedCrsId() print(QString("New file format will be: %1").arg(fileformat)) attributes = dict() geomDialog.attributes(attributes) settings = QSettings() lastUsedDir = settings.value("/UI/lastVectorFileFilterDir", QDir.homePath()).toString() filterString = QgsVectorFileWriter.filterForDriver(fileformat) fileName = QFileDialog.getSaveFileName(parent, "Save layer as...", lastUsedDir, filterString) if (fileName.isNull()): return "" if (fileformat == "ESRI Shapefile" and not fileName.endsWith(".shp", Qt.CaseInsensitive)): fileName += ".shp" settings.setValue("/UI/lastVectorFileFilterDir", QFileInfo(fileName).absolutePath()) settings.setValue("/UI/encoding", enc) #try to create the new layer with OGRProvider instead of QgsVectorFileWriter pReg = QgsProviderRegistry.instance() ogrlib = pReg.library("ogr") # load the data provider myLib = QLibrary(ogrlib) loaded = myLib.load() constructionLineLayer = None mapUnits = define._canvas.mapUnits() layerName = String.QString2Str(fileName).split("\\")[-1] path = "memory" selectedCrs = geomDialog.selectedCrs() if geometrytype == QGis.Line: # if mapUnits == QGis.Meters: constructionLineLayer = QgsVectorLayer( "linestring?crs=%s" % selectedCrs.authid(), layerName, path) # else: # constructionLineLayer = QgsVectorLayer("linestring?crs=%s"%define._latLonCrs.authid (), layerName, path) elif geometrytype == QGis.Polygon: # if mapUnits == QGis.Meters: constructionLineLayer = QgsVectorLayer( "polygon?crs=%s" % selectedCrs.authid(), layerName, path) # else: # constructionLineLayer = QgsVectorLayer("polygon?crs=%s"%define._latLonCrs.authid (), layerName, path) elif geometrytype == QGis.Point: # if mapUnits == QGis.Meters: constructionLineLayer = QgsVectorLayer( "Point?crs=%s" % selectedCrs.authid(), layerName, path) # else: # constructionLineLayer = QgsVectorLayer("Point?crs=%s"%define._latLonCrs.authid (), layerName, path) fieldList = [] for key in attributes.iterkeys(): fieldList.append(QgsField(key, attributes[key][0])) constructionLineLayer.startEditing() constructionLineLayer.dataProvider().addAttributes(fieldList) constructionLineLayer.commitChanges() er = QgsVectorFileWriter.writeAsVectorFormat( constructionLineLayer, fileName, "utf-8", constructionLineLayer.crs()) constructionLineLayer = QgsVectorLayer(fileName, layerName, "ogr") QgisHelper.appendToCanvas(define._canvas, [constructionLineLayer], "NewLayers") # if ( loaded ): # print( "ogr provider loaded" ) # # typedef bool ( *createEmptyDataSourceProc )( const QString&, const QString&, const QString&, QGis::WkbType, # const QList< QPair<QString, QString> >&, const QgsCoordinateReferenceSystem * ) # createEmptyDataSourceProc createEmptyDataSource = ( createEmptyDataSourceProc ) cast_to_fptr( myLib.resolve( "createEmptyDataSource" ) ) # if ( createEmptyDataSource ) # { # if ( geometrytype not = QGis::WKBUnknown ) # { # QgsCoordinateReferenceSystem srs = QgsCRSCache::instance().crsBySrsId( crsId ) # if ( not createEmptyDataSource( fileName, fileformat, enc, geometrytype, attributes, &srs ) ) # { # return QString::null # } # } # else # { # QgsDebugMsg( "geometry type not recognised" ) # return QString::null # } # } # else # { # QgsDebugMsg( "Resolving newEmptyDataSource(...) failed" ) # return QString::null # } # } # # if ( pEnc ) # *pEnc = enc return fileName
def getProjectLocation(self): '''获取项目路径''' path = QFileDialog.getExistingDirectory() path = QDir.fromNativeSeparators(path) self.et_project_location.setText(path)
def loadqgisproject(self, project, projectfile): QDir.setCurrent(os.path.dirname(project.projectfile)) fileinfo = QFileInfo(project.projectfile) QgsProject.instance().read(fileinfo)
class Folder(DataStore): """ Folder DataStore A folder based data store is a collection of shape files and tiff images stored in a common folder. .. versionadded:: 4.0 """ def __init__(self, uri): """ Constructor for the folder DataStore. :param uri: A directory object or the path to the folder :type uri: QDir, str .. versionadded:: 4.0 """ super(Folder, self).__init__(uri) self._default_vector_format = 'shp' if isinstance(uri, QDir): self._uri = uri elif isinstance(uri, basestring): self._uri = QDir(uri) else: raise ErrorDataStore('Unknown type') @property def default_vector_format(self): """Default vector format for the folder datastore. :return: The default vector format. :rtype: str. """ return self._default_vector_format @default_vector_format.setter def default_vector_format(self, default_format): """Set the default vector format for the folder datastore. :param default_format: The default output format. It can be 'shp', 'geojson' or 'kml'. :param default_format: str """ if default_format in VECTOR_EXTENSIONS: self._default_vector_format = default_format @property def uri_path(self): """Return the URI of the datastore as a path. It's not a layer URI. :return: The URI. :rtype: str .. versionadded:: 4.0 """ return self.uri.absolutePath() def is_writable(self): """Check if the folder is writable. :return: If it's writable or not. :rtype: bool .. versionadded:: 4.0 """ return QFileInfo(self._uri.absolutePath()).isWritable() def supports_rasters(self): """Check if we can support raster in the datastore. :return: If it's writable or not. :rtype: bool .. versionadded:: 4.0 """ return True def layers(self): """Return a list of layers available. :return: List of layers available in the datastore. :rtype: list .. versionadded:: 4.0 """ extensions = ['*.%s' % f for f in EXTENSIONS] self.uri.setNameFilters(extensions) files = self.uri.entryList() self.uri.setNameFilters('') files = human_sorting([QFileInfo(f).baseName() for f in files]) return files def layer_uri(self, layer_name): """Get layer URI. :param layer_name: The name of the layer to fetch. :type layer_name: str :return: The URI to the layer. :rtype: str .. versionadded:: 4.0 """ layers = self.layers() for layer, extension in product(layers, EXTENSIONS): one_file = QFileInfo(self.uri.filePath(layer + '.' + extension)) if one_file.exists(): if one_file.baseName() == layer_name: return one_file.absoluteFilePath() else: return None def _add_tabular_layer(self, tabular_layer, layer_name): """Add a tabular layer to the folder. :param tabular_layer: The layer to add. :type tabular_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ output = QFileInfo(self.uri.filePath(layer_name + '.csv')) QgsVectorFileWriter.writeAsVectorFormat(tabular_layer, output.absoluteFilePath(), 'utf-8', None, 'CSV') assert output.exists() return True, output.baseName() def _add_vector_layer(self, vector_layer, layer_name): """Add a vector layer to the folder. :param vector_layer: The layer to add. :type vector_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ if not self.is_writable(): return False, 'The destination is not writable.' output = QFileInfo( self.uri.filePath(layer_name + '.' + self._default_vector_format)) driver_mapping = { 'shp': 'ESRI Shapefile', 'kml': 'KML', 'geojson': 'GeoJSON', } QgsVectorFileWriter.writeAsVectorFormat( vector_layer, output.absoluteFilePath(), 'utf-8', vector_layer.crs(), driver_mapping[self._default_vector_format]) assert output.exists() return True, output.baseName() def _add_raster_layer(self, raster_layer, layer_name): """Add a raster layer to the folder. :param raster_layer: The layer to add. :type raster_layer: QgsRasterLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ if not self.is_writable(): return False, 'The destination is not writable.' output = QFileInfo(self.uri.filePath(layer_name + '.tif')) source = QFileInfo(raster_layer.source()) if source.exists() and source.suffix() in ['tiff', 'tif']: # If it's tiff file based. QFile.copy(source.absoluteFilePath(), output.absoluteFilePath()) else: # If it's not file based. renderer = raster_layer.renderer() provider = raster_layer.dataProvider() crs = raster_layer.crs() pipe = QgsRasterPipe() pipe.set(provider.clone()) pipe.set(renderer.clone()) file_writer = QgsRasterFileWriter(output.absoluteFilePath()) file_writer.Mode(1) file_writer.writeRaster(pipe, provider.xSize(), provider.ySize(), provider.extent(), crs) del file_writer assert output.exists() return True, output.baseName()
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 temporaryOutputDir(): return QDir.tempPath() + "/Qgis2threejs"
def _create_plugin_directory(self): """Create the plugin directory using the class name.""" # remove spaces from the plugin name self.plugin_path = os.path.join(str(self.plugin_path), str(self.dialog.class_name.text())) QDir().mkdir(self.plugin_path)
def _open_config_folder(self): QDesktopServices.openUrl( QUrl("file:///" + QDir.toNativeSeparators(sys.path[1])))
from stdm.ui.wizard.custom_item_model import EntitiesModel from stdm.geoodk.importer import EntityImporter from stdm.settings.projectionSelector import ProjectionSelector from stdm.geoodk.importer import ImportLogger from stdm.geoodk.importer import Save2DB from stdm.third_party.sqlalchemy.exc import SQLAlchemyError from stdm import resources_rc #from stdm.geoodk.importer.geoodkserver import JSONEXTRACTOR from collections import OrderedDict FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'ui_geoodk_import.ui')) HOME = QDir.home().path() CONFIG_FILE = HOME + '/.stdm/geoodk/' MSG = 'Error creating log' GEOODK_FORM_HOME = CONFIG_FILE+'instances' class ProfileInstanceRecords(QDialog, FORM_CLASS): """ class constructor The class handles all the instances that the user has collected and saved in the folder and saved in a computer. The class will construct the path to the folder and enumerate all available instances and return the count. It will also rename all the file based on instance unique GUUID for easier management and future updates. """ def __init__(self, parent=None):
def _open_config_folder(self): QDesktopServices.openUrl( QUrl("file:///" + QDir.toNativeSeparators(cfclient.config_path)))
def get_qml_resource(qmlpath): path_qml = QDir.fromNativeSeparators( os.path.join(resources.QML_FILES, qmlpath)) path_qml = urlunparse(urlparse(path_qml)._replace(scheme='file')) return QUrl(path_qml)
from PyQt4.QtCore import Qt ############################################################################### # CHECK PYTHON VERSION ############################################################################### if sys.version_info.major == 3: IS_PYTHON3 = True else: IS_PYTHON3 = False ############################################################################### # PATHS ############################################################################### HOME_PATH = QDir.toNativeSeparators(QDir.homePath()) NINJA_EXECUTABLE = os.path.realpath(sys.argv[0]) PRJ_PATH = os.path.abspath(os.path.dirname(__file__)) if not IS_PYTHON3: PRJ_PATH = PRJ_PATH.decode('utf-8') #Only for py2exe frozen = getattr(sys, 'frozen', '') if frozen in ('dll', 'console_exe', 'windows_exe'): # py2exe: PRJ_PATH = os.path.abspath(os.path.dirname(sys.executable)) HOME_NINJA_PATH = os.path.join(HOME_PATH, ".ninja_ide") NINJA_KNOWLEDGE_PATH = os.path.join(HOME_NINJA_PATH, 'knowledge')
def __init__(self, file='settings'): """ @type file: string @param file: the prefix of the settings files used. Used for testing. """ userDir = QDir(os.path.expanduser('~')) userDir.cd('Application Data') or userDir.cd('AppData') or userDir.cd('Library') if not userDir.cd('BootTunes'): userDir.mkdir('BootTunes') userDir.cd('BootTunes') self.settingsDir = unicode(userDir.absolutePath()) basePath = unicode(userDir.absolutePath()) self.settingsPath = settingsPath = basePath + '/' + file + '-settings' self.defaultsPath = defaultsPath = basePath + '/' + file + '-defaults' self.namesPath = namesPath = basePath + '/' + file + '-names' self.completedPath = completedPath = basePath + '/' + file + '-completed' pathsAndProperties = [ (settingsPath, 'settings'), (defaultsPath, 'artistDefaults'), (namesPath, 'artistNames'), (completedPath, 'completed') ] for pathAndProperty in pathsAndProperties: filePath = pathAndProperty[0] property = pathAndProperty[1] setattr(self, property, {}) if os.path.exists(filePath): fileObj = codecs.open(filePath, 'r') try: setattr(self, property, cPickle.load(fileObj) or {}) except (cPickle.UnpicklingError, AttributeError, EOFError, ImportError, IndexError): pass fileObj.close()
## ############################################################################# import sys from PyQt4.QtCore import QDir, Qt from PyQt4.QtGui import * app = QApplication(sys.argv) background = QWidget() palette = QPalette() palette.setColor(QPalette.Window, QColor(Qt.white)) background.setPalette(palette) model = QFileSystemModel() model.setRootPath(QDir.currentPath()) treeView = QTreeView(background) treeView.setModel(model) treeView.setRootIndex(model.index(QDir.currentPath())) listView = QListView(background) listView.setModel(model) listView.setRootIndex(model.index(QDir.currentPath())) tableView = QTableView(background) tableView.setModel(model) tableView.setRootIndex(model.index(QDir.currentPath())) selection = QItemSelectionModel(model) treeView.setSelectionModel(selection)
def main(argv=None): if argv is None: argv = sys.argv usage = "usage: %prog [options] [scheme_file]" parser = optparse.OptionParser(usage=usage) parser.add_option("--no-discovery", action="store_true", help="Don't run widget discovery " "(use full cache instead)") parser.add_option("--force-discovery", action="store_true", help="Force full widget discovery " "(invalidate cache)") parser.add_option("--no-welcome", action="store_true", help="Don't show welcome dialog.") parser.add_option("--no-splash", action="store_true", help="Don't show splash screen.") parser.add_option("-l", "--log-level", help="Logging level (0, 1, 2, 3, 4)", type="int", default=1) parser.add_option("--no-redirect", action="store_true", help="Do not redirect stdout/err to canvas output view.") parser.add_option("--style", help="QStyle to use", type="str", default=None) parser.add_option("--stylesheet", help="Application level CSS style sheet to use", type="str", default="orange.qss") parser.add_option("--qt", help="Additional arguments for QApplication", type="str", default=None) (options, args) = parser.parse_args(argv[1:]) levels = [ logging.CRITICAL, logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG ] # Fix streams before configuring logging (otherwise it will store # and write to the old file descriptors) fix_win_pythonw_std_stream() # Try to fix fonts on OSX Mavericks fix_osx_10_9_private_font() # File handler should always be at least INFO level so we need # the application root level to be at least at INFO. root_level = min(levels[options.log_level], logging.INFO) rootlogger = logging.getLogger(OrangeCanvas.__name__) rootlogger.setLevel(root_level) # Standard output stream handler at the requested level stream_hander = logging.StreamHandler() stream_hander.setLevel(level=levels[options.log_level]) rootlogger.addHandler(stream_hander) log.info("Starting 'Orange Canvas' application.") qt_argv = argv[:1] if options.style is not None: qt_argv += ["-style", options.style] if options.qt is not None: qt_argv += shlex.split(options.qt) qt_argv += args log.debug("Starting CanvasApplicaiton with argv = %r.", qt_argv) app = CanvasApplication(qt_argv) # NOTE: config.init() must be called after the QApplication constructor config.init() file_handler = logging.FileHandler(filename=os.path.join( config.log_dir(), "canvas.log"), mode="w") file_handler.setLevel(root_level) rootlogger.addHandler(file_handler) # intercept any QFileOpenEvent requests until the main window is # fully initialized. # NOTE: The QApplication must have the executable ($0) and filename # arguments passed in argv otherwise the FileOpen events are # triggered for them (this is done by Cocoa, but QApplicaiton filters # them out if passed in argv) open_requests = [] def onrequest(url): log.info("Received an file open request %s", url) open_requests.append(url) app.fileOpenRequest.connect(onrequest) settings = QSettings() stylesheet = options.stylesheet stylesheet_string = None if stylesheet != "none": if os.path.isfile(stylesheet): stylesheet_string = open(stylesheet, "rb").read() else: if not os.path.splitext(stylesheet)[1]: # no extension stylesheet = os.path.extsep.join([stylesheet, "qss"]) pkg_name = OrangeCanvas.__name__ resource = "styles/" + stylesheet if pkg_resources.resource_exists(pkg_name, resource): stylesheet_string = \ pkg_resources.resource_string(pkg_name, resource) base = pkg_resources.resource_filename(pkg_name, "styles") pattern = re.compile( r"^\s@([a-zA-Z0-9_]+?)\s*:\s*([a-zA-Z0-9_/]+?);\s*$", flags=re.MULTILINE) matches = pattern.findall(stylesheet_string) for prefix, search_path in matches: QDir.addSearchPath(prefix, os.path.join(base, search_path)) log.info("Adding search path %r for prefix, %r", search_path, prefix) stylesheet_string = pattern.sub("", stylesheet_string) else: log.info("%r style sheet not found.", stylesheet) # Add the default canvas_icons search path dirpath = os.path.abspath(os.path.dirname(OrangeCanvas.__file__)) QDir.addSearchPath("canvas_icons", os.path.join(dirpath, "icons")) canvas_window = CanvasMainWindow() canvas_window.setWindowIcon(config.application_icon()) if stylesheet_string is not None: canvas_window.setStyleSheet(stylesheet_string) if not options.force_discovery: reg_cache = cache.registry_cache() else: reg_cache = None widget_discovery = qt.QtWidgetDiscovery(cached_descriptions=reg_cache) widget_registry = qt.QtWidgetRegistry() widget_discovery.found_category.connect(widget_registry.register_category) widget_discovery.found_widget.connect(widget_registry.register_widget) want_splash = \ settings.value("startup/show-splash-screen", True, type=bool) and \ not options.no_splash if want_splash: pm, rect = config.splash_screen() splash_screen = SplashScreen(pixmap=pm, textRect=rect) splash_screen.setFont(QFont("Helvetica", 12)) color = QColor("#FFD39F") def show_message(message): splash_screen.showMessage(message, color=color) widget_discovery.discovery_start.connect(splash_screen.show) widget_discovery.discovery_process.connect(show_message) widget_discovery.discovery_finished.connect(splash_screen.hide) log.info("Running widget discovery process.") cache_filename = os.path.join(cache_dir(), "widget-registry.pck") if options.no_discovery: widget_registry = cPickle.load(open(cache_filename, "rb")) widget_registry = qt.QtWidgetRegistry(widget_registry) else: widget_discovery.run(config.widgets_entry_points()) # Store cached descriptions cache.save_registry_cache(widget_discovery.cached_descriptions) cPickle.dump(WidgetRegistry(widget_registry), open(cache_filename, "wb")) set_global_registry(widget_registry) canvas_window.set_widget_registry(widget_registry) canvas_window.show() canvas_window.raise_() want_welcome = \ settings.value("startup/show-welcome-screen", True, type=bool) \ and not options.no_welcome # Process events to make sure the canvas_window layout has # a chance to activate (the welcome dialog is modal and will # block the event queue, plus we need a chance to receive open file # signals when running without a splash screen) app.processEvents() app.fileOpenRequest.connect(canvas_window.open_scheme_file) if want_welcome and not args and not open_requests: canvas_window.welcome_dialog() elif args: log.info("Loading a scheme from the command line argument %r", args[0]) canvas_window.load_scheme(args[0]) elif open_requests: log.info("Loading a scheme from an `QFileOpenEvent` for %r", open_requests[-1]) canvas_window.load_scheme(open_requests[-1].toLocalFile()) stdout_redirect = \ settings.value("output/redirect-stdout", True, type=bool) stderr_redirect = \ settings.value("output/redirect-stderr", True, type=bool) # cmd line option overrides settings / no redirect is possible # under ipython if options.no_redirect or running_in_ipython(): stderr_redirect = stdout_redirect = False output_view = canvas_window.output_view() if stdout_redirect: stdout = TextStream() stdout.stream.connect(output_view.write) # also connect to original fd stdout.stream.connect(sys.stdout.write) else: stdout = sys.stdout if stderr_redirect: error_writer = output_view.formated(color=Qt.red) stderr = TextStream() stderr.stream.connect(error_writer.write) # also connect to original fd stderr.stream.connect(sys.stderr.write) else: stderr = sys.stderr if stderr_redirect: sys.excepthook = ExceptHook() sys.excepthook.handledException.connect(output_view.parent().show) with nested(redirect_stdout(stdout), redirect_stderr(stderr)): log.info("Entering main event loop.") try: status = app.exec_() except BaseException: log.error("Error in main event loop.", exc_info=True) canvas_window.deleteLater() app.processEvents() app.flush() del canvas_window # Collect any cycles before deleting the QApplication instance gc.collect() del app return status
def tempFolder(): tempDir = os.path.join(unicode(QDir.tempPath()), 'processing') if not QDir(tempDir).exists(): QDir().mkpath(tempDir) return unicode(os.path.abspath(tempDir))
def run(self, *args, **kwargs): """ :param templatePath: The file path to the user-defined template. :param entityFieldName: The name of the column for the specified entity which must exist in the data source view or table. :param entityFieldValue: The value for filtering the records in the data source view or table. :param outputMode: Whether the output composition should be an image or PDF. :param filePath: The output file where the composition will be written to. Applies to single mode output generation. :param dataFields: List containing the field names whose values will be used to name the files. This is used in multiple mode configuration. :param fileExtension: The output file format. Used in multiple mode configuration. :param data_source: Name of the data source table or view whose row values will be used to name output files if the options has been specified by the user. """ templatePath = args[0] entityFieldName = args[1] entityFieldValue = args[2] outputMode = args[3] filePath = kwargs.get("filePath", None) dataFields = kwargs.get("dataFields", []) fileExtension = kwargs.get("fileExtension", "") data_source = kwargs.get("data_source", "") templateFile = QFile(templatePath) if not templateFile.open(QIODevice.ReadOnly): return False, QApplication.translate("DocumentGenerator", "Cannot read template file.") templateDoc = QDomDocument() if templateDoc.setContent(templateFile): composerDS = ComposerDataSource.create(templateDoc) spatialFieldsConfig = SpatialFieldsConfiguration.create( templateDoc) composerDS.setSpatialFieldsConfig(spatialFieldsConfig) #Check if data source exists and return if it doesn't if not self.data_source_exists(composerDS): msg = QApplication.translate( "DocumentGenerator", u"'{0}' data source does not exist in the database." u"\nPlease contact your database " u"administrator.".format(composerDS.name())) return False, msg #Set file name value formatter self._file_name_value_formatter = EntityValueFormatter( name=data_source) #Register field names to be used for file naming self._file_name_value_formatter.register_columns(dataFields) #TODO: Need to automatically register custom configuration collections #Photo config collection ph_config_collection = PhotoConfigurationCollection.create( templateDoc) #Table configuration collection table_config_collection = TableConfigurationCollection.create( templateDoc) #Create chart configuration collection object chart_config_collection = ChartConfigurationCollection.create( templateDoc) # Create QR code configuration collection object qrc_config_collection = QRCodeConfigurationCollection.create( templateDoc) #Load the layers required by the table composer items self._table_mem_layers = load_table_layers(table_config_collection) entityFieldName = self.format_entity_field_name( composerDS.name(), data_source) #Execute query dsTable, records = self._exec_query(composerDS.name(), entityFieldName, entityFieldValue) if records is None or len(records) == 0: return False, QApplication.translate( "DocumentGenerator", "No matching records in the database") """ Iterate through records where a single file output will be generated for each matching record. """ for rec in records: composition = QgsComposition(self._map_settings) composition.loadFromTemplate(templateDoc) ref_layer = None #Set value of composer items based on the corresponding db values for composerId in composerDS.dataFieldMappings().reverse: #Use composer item id since the uuid is stripped off composerItem = composition.getComposerItemById(composerId) if not composerItem is None: fieldName = composerDS.dataFieldName(composerId) fieldValue = getattr(rec, fieldName) self._composeritem_value_handler( composerItem, fieldValue) # Extract photo information self._extract_photo_info(composition, ph_config_collection, rec) # Set table item values based on configuration information self._set_table_data(composition, table_config_collection, rec) # Refresh non-custom map composer items self._refresh_composer_maps( composition, spatialFieldsConfig.spatialFieldsMapping().keys()) # Set use fixed scale to false i.e. relative zoom use_fixed_scale = False # Create memory layers for spatial features and add them to the map for mapId, spfmList in spatialFieldsConfig.spatialFieldsMapping( ).iteritems(): map_item = composition.getComposerItemById(mapId) if not map_item is None: # Clear any previous map memory layer # self.clear_temporary_map_layers() for spfm in spfmList: #Use the value of the label field to name the layer lbl_field = spfm.labelField() spatial_field = spfm.spatialField() if not spatial_field: continue if lbl_field: if hasattr(rec, spfm.labelField()): layerName = getattr(rec, spfm.labelField()) else: layerName = self._random_feature_layer_name( spatial_field) else: layerName = self._random_feature_layer_name( spatial_field) #Extract the geometry using geoalchemy spatial capabilities geom_value = getattr(rec, spatial_field) if geom_value is None: continue geom_func = geom_value.ST_AsText() geomWKT = self._dbSession.scalar(geom_func) #Get geometry type geom_type, srid = geometryType( composerDS.name(), spatial_field) #Create reference layer with feature ref_layer = self._build_vector_layer( layerName, geom_type, srid) if ref_layer is None or not ref_layer.isValid(): continue # Add feature bbox = self._add_feature_to_layer( ref_layer, geomWKT) zoom_type = spfm.zoom_type # Only scale the extents if zoom type is relative if zoom_type == 'RELATIVE': bbox.scale(spfm.zoomLevel()) #Workaround for zooming to single point extent if ref_layer.wkbType() == QGis.WKBPoint: canvas_extent = self._iface.mapCanvas( ).fullExtent() cnt_pnt = bbox.center() canvas_extent.scale(1.0 / 32, cnt_pnt) bbox = canvas_extent #Style layer based on the spatial field mapping symbol layer symbol_layer = spfm.symbolLayer() if not symbol_layer is None: ref_layer.rendererV2().symbols( )[0].changeSymbolLayer(0, spfm.symbolLayer()) ''' Add layer to map and ensure its always added at the top ''' self.map_registry.addMapLayer(ref_layer) self._iface.mapCanvas().setExtent(bbox) # Set scale if type is FIXED if zoom_type == 'FIXED': self._iface.mapCanvas().zoomScale( spfm.zoomLevel()) use_fixed_scale = True self._iface.mapCanvas().refresh() # Add layer to map memory layer list self._map_memory_layers.append(ref_layer.id()) self._hide_layer(ref_layer) ''' Use root layer tree to get the correct ordering of layers in the legend ''' self._refresh_map_item(map_item, use_fixed_scale) # Extract chart information and generate chart self._generate_charts(composition, chart_config_collection, rec) # Extract QR code information in order to generate QR codes self._generate_qr_codes(composition, qrc_config_collection, rec) #Build output path and generate composition if not filePath is None and len(dataFields) == 0: self._write_output(composition, outputMode, filePath) elif filePath is None and len(dataFields) > 0: entityFieldName = 'id' docFileName = self._build_file_name( data_source, entityFieldName, entityFieldValue, dataFields, fileExtension) # Replace unsupported characters in Windows file naming docFileName = docFileName.replace('/', '_').replace \ ('\\', '_').replace(':', '_').strip('*?"<>|') if not docFileName: return ( False, QApplication.translate( "DocumentGenerator", "File name could not be generated from the data fields." )) outputDir = self._composer_output_path() if outputDir is None: return ( False, QApplication.translate( "DocumentGenerator", "System could not read the location of the output directory in the registry." )) qDir = QDir() if not qDir.exists(outputDir): return (False, QApplication.translate( "DocumentGenerator", "Output directory does not exist")) absDocPath = u"{0}/{1}".format(outputDir, docFileName) self._write_output(composition, outputMode, absDocPath) return True, "Success" return False, "Document composition could not be generated"
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # See http://www.gnu.org/licenses/ for more information. """ Icons. """ from __future__ import unicode_literals import os from PyQt4.QtCore import QDir, QFile, QFileInfo, QSettings, QSize from PyQt4.QtGui import QFileIconProvider, QIcon _cache = {} QDir.setSearchPaths("icons", __path__) # use our icon theme (that builds on Tango) if there are no system icons if (not QIcon.themeName() or QIcon.themeName() == "hicolor" or not QSettings().value("system_icons", True, bool)): QIcon.setThemeSearchPaths(QIcon.themeSearchPaths() + __path__) QIcon.setThemeName("TangoExt") def get(name): """Returns an icon with the specified name.""" if QIcon.hasThemeIcon(name): return QIcon.fromTheme(name) try: return _cache[name] except KeyError:
def exportStyles(layers, folder, clustered): stylesFolder = os.path.join(folder, "styles") QDir().mkpath(stylesFolder) legendFolder = os.path.join(stylesFolder, "legend") QDir().mkpath(legendFolder) for count, (layer, cluster) in enumerate(zip(layers, clustered)): sln = safeName(layer.name()) + unicode(count) if layer.type() != layer.VectorLayer: continue labelsEnabled = unicode( layer.customProperty("labeling/enabled")).lower() == "true" if (labelsEnabled): labelField = layer.customProperty("labeling/fieldName") if labelField != "": if unicode(layer.customProperty( "labeling/isExpression")).lower() == "true": exprFilename = os.path.join(folder, "resources", "qgis2web_expressions.js") fieldName = layer.customProperty("labeling/fieldName") name = compile_to_file(fieldName, "label_%s" % sln, "OpenLayers3", exprFilename) js = "%s(context)" % (name) js = js.strip() labelText = js else: fieldIndex = layer.pendingFields().indexFromName( labelField) editFormConfig = layer.editFormConfig() editorWidget = editFormConfig.widgetType(fieldIndex) if (editorWidget == QgsVectorLayer.Hidden or editorWidget == 'Hidden'): labelField = "q2wHide_" + labelField labelText = ('feature.get("%s")' % labelField.replace('"', '\\"')) else: labelText = '""' else: labelText = '""' defs = "var size = 0;\n" try: renderer = layer.rendererV2() layer_alpha = layer.layerTransparency() if isinstance(renderer, QgsSingleSymbolRendererV2): symbol = renderer.symbol() style = "var style = " + getSymbolAsStyle( symbol, stylesFolder, layer_alpha, renderer) legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap( symbol, QSize(16, 16)) legendIcon.save(os.path.join(legendFolder, sln + ".png")) value = 'var value = ""' elif isinstance(renderer, QgsCategorizedSymbolRendererV2): cluster = False defs += """function categories_%s(feature, value, size) { switch(value.toString()) {""" % sln cats = [] for cnt, cat in enumerate(renderer.categories()): legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap( cat.symbol(), QSize(16, 16)) legendIcon.save( os.path.join(legendFolder, sln + "_" + unicode(cnt) + ".png")) if (cat.value() is not None and cat.value() != "" and not isinstance(cat.value(), QPyNullVariant)): categoryStr = "case '%s':" % unicode( cat.value()).replace("'", "\\'") else: categoryStr = "default:" categoryStr += ''' return %s; break;''' % (getSymbolAsStyle(cat.symbol(), stylesFolder, layer_alpha, renderer)) cats.append(categoryStr) defs += "\n".join(cats) + "}};" classAttr = renderer.classAttribute() fieldIndex = layer.pendingFields().indexFromName(classAttr) editFormConfig = layer.editFormConfig() editorWidget = editFormConfig.widgetType(fieldIndex) if (editorWidget == QgsVectorLayer.Hidden or editorWidget == 'Hidden'): classAttr = "q2wHide_" + classAttr value = ('var value = feature.get("%s");' % classAttr) style = ('var style = categories_%s(feature, value, size)' % sln) elif isinstance(renderer, QgsGraduatedSymbolRendererV2): cluster = False varName = "ranges_" + sln defs += "var %s = [" % varName ranges = [] for cnt, ran in enumerate(renderer.ranges()): legendIcon = QgsSymbolLayerV2Utils.symbolPreviewPixmap( ran.symbol(), QSize(16, 16)) legendIcon.save( os.path.join(legendFolder, sln + "_" + unicode(cnt) + ".png")) symbolstyle = getSymbolAsStyle(ran.symbol(), stylesFolder, layer_alpha, renderer) ranges.append( '[%f, %f, %s]' % (ran.lowerValue(), ran.upperValue(), symbolstyle)) defs += ",\n".join(ranges) + "];" classAttr = renderer.classAttribute() fieldIndex = layer.pendingFields().indexFromName(classAttr) editFormConfig = layer.editFormConfig() editorWidget = editFormConfig.widgetType(fieldIndex) if (editorWidget == QgsVectorLayer.Hidden or editorWidget == 'Hidden'): classAttr = "q2wHide_" + classAttr value = ('var value = feature.get("%s");' % classAttr) style = '''var style = %(v)s[0][2]; for (i = 0; i < %(v)s.length; i++){ var range = %(v)s[i]; if (value > range[0] && value<=range[1]){ style = range[2]; } }''' % { "v": varName } elif isinstance(renderer, QgsRuleBasedRendererV2): cluster = False template = """ function rules_%s(feature, value) { var context = { feature: feature, variables: {} }; // Start of if blocks and style check logic %s else { return %s; } } var style = rules_%s(feature, value); """ elsejs = "[]" js = "" root_rule = renderer.rootRule() rules = root_rule.children() expFile = os.path.join(folder, "resources", "qgis2web_expressions.js") ifelse = "if" for count, rule in enumerate(rules): symbol = rule.symbol() styleCode = getSymbolAsStyle(symbol, stylesFolder, layer_alpha, renderer) name = "".join((sln, "rule", unicode(count))) exp = rule.filterExpression() if rule.isElse(): elsejs = styleCode continue name = compile_to_file(exp, name, "OpenLayers3", expFile) js += """ %s (%s(context)) { return %s; } """ % (ifelse, name, styleCode) js = js.strip() ifelse = "else if" value = ("var value = '';") style = template % (sln, js, elsejs, sln) else: style = "" if layer.customProperty("labeling/fontSize"): size = float(layer.customProperty("labeling/fontSize")) * 1.3 else: size = 10 italic = layer.customProperty("labeling/fontItalic") bold = layer.customProperty("labeling/fontWeight") r = layer.customProperty("labeling/textColorR") g = layer.customProperty("labeling/textColorG") b = layer.customProperty("labeling/textColorB") if (r or g or b) is None: color = "rgba(0, 0, 0, 1)" else: color = "rgba(%s, %s, %s, 1)" % (r, g, b) face = layer.customProperty("labeling/fontFamily") if face is None: face = "," else: face = " \\'%s\\'," % face palyr = QgsPalLayerSettings() palyr.readFromLayer(layer) sv = palyr.scaleVisibility if sv: min = float(palyr.scaleMin) max = float(palyr.scaleMax) if min != 0: min = 1 / ((1 / min) * 39.37 * 90.7) max = 1 / ((1 / max) * 39.37 * 90.7) labelRes = " && resolution > %(min)d " % {"min": min} labelRes += "&& resolution < %(max)d" % {"max": max} else: labelRes = "" buffer = palyr.bufferDraw if buffer: bufferColor = palyr.bufferColor.name() bufferWidth = palyr.bufferSize stroke = """ stroke: new ol.style.Stroke({ color: "%s", width: %d }),""" % (bufferColor, bufferWidth) else: stroke = "" if style != "": style = getStyle(style, cluster, labelRes, labelText, sln, size, face, color, value) else: style = "''" except Exception, e: style = """{ /* """ + traceback.format_exc() + " */}" QgsMessageLog.logMessage(traceback.format_exc(), "qgis2web", level=QgsMessageLog.CRITICAL) path = os.path.join(stylesFolder, sln + "_style.js") with codecs.open(path, "w", "utf-8") as f: f.write('''%(defs)s var styleCache_%(name)s={} var style_%(name)s = %(style)s;''' % { "defs": defs, "name": sln, "style": style })
def insertDocumentFromFile(self, path, doc_type_id, entity, record_count=1): """ Insert a new document into one of the registered containers with the document type id. This document is registered :param path: The local user path of the document :type path: String :param doc_type_id: The entity document type id :type doc_type_id: Integer :param entity: The entity in which the document is inserted into. :type entity: Entity class :param record_count: The number of records for which a document is uploaded. Default is 1. For instance, more records could be used in STR wizard in multi-party. :type record_count: Integer :return: None :rtype: NoneType """ if len(self.containers) > 0: if doc_type_id in self.containers: container = self.containers[doc_type_id] #Check if the file exists if QFile.exists(path): network_location = network_document_path() if not network_location: self._doc_repository_error() return #Check if the directory exists doc_dir = QDir(network_location) if not doc_dir.exists(): msg = QApplication.translate( "sourceDocumentManager", u"The root document " u"repository '{0}' does " u"not exist.\nPlease " u"check the path settings." ) parent = self.parent() if not isinstance(parent, QWidget): parent = None QMessageBox.critical( parent, QApplication.translate( "sourceDocumentManager", "Document Manager" ), msg.format(network_location) ) return for i in range(record_count): # Use the default network file manager networkManager = NetworkFileManager( network_location, self.parent() ) # Add document widget docWidg = DocumentWidget( self.document_model, networkManager, parent=self.parent(), view_manager=self._doc_view_manager ) # Connect slot once the document # has been successfully uploaded. docWidg.fileUploadComplete.connect( lambda: self.onFileUploadComplete(doc_type_id) ) self._linkWidgetRemovedSignal(docWidg) doc_type_entity = entity.supporting_doc.document_type_entity doc_type_value = entity_id_to_attr( doc_type_entity, 'value', doc_type_id ) docWidg.setFile( path, entity.name, doc_type_value, doc_type_id ) container.addWidget(docWidg)
def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/SurveyingCalculation/icon.png' icon_dir = QDir.cleanPath(self.plugin_dir + QDir.separator() + 'icons') # build menu self.actions = [] self.menu = QMenu() self.menu.setTitle(tr(u'&SurveyingCalculation')) self.sc_coord = QAction( QIcon(QDir(icon_dir).absoluteFilePath('new_coord.png')), tr("New coordinate list ..."), self.iface.mainWindow()) self.sc_fb = QAction( QIcon(QDir(icon_dir).absoluteFilePath('new_fb.png')), tr("New fieldbook ..."), self.iface.mainWindow()) self.sc_load = QAction( QIcon(QDir(icon_dir).absoluteFilePath('import_fieldbook.png')), tr("Import fieldbook ..."), self.iface.mainWindow()) self.sc_addp = QAction( QIcon(QDir(icon_dir).absoluteFilePath('addp.png')), tr("Add new point ..."), self.iface.mainWindow()) self.sc_calc = QAction( QIcon(QDir(icon_dir).absoluteFilePath('single_calc.png')), tr("Single point calculations ..."), self.iface.mainWindow()) self.sc_trav = QAction( QIcon(QDir(icon_dir).absoluteFilePath('traverse_calc.png')), tr("Traverse calculations ..."), self.iface.mainWindow()) self.sc_netw = QAction( QIcon(QDir(icon_dir).absoluteFilePath('network_calc.png')), tr("Network adjustment ..."), self.iface.mainWindow()) self.sc_tran = QAction( QIcon(QDir(icon_dir).absoluteFilePath('coord_calc.png')), tr("Coordinate transformation ..."), self.iface.mainWindow()) self.sc_pdiv = QAction( QIcon(QDir(icon_dir).absoluteFilePath('poly_div.png')), tr("Polygon division ..."), self.iface.mainWindow()) self.sc_plot = QAction( QIcon(QDir(icon_dir).absoluteFilePath('plot.png')), tr("Plot by template ..."), self.iface.mainWindow()) self.sc_batchplot = QAction( QIcon(QDir(icon_dir).absoluteFilePath('batch_plot.png')), tr("Batch plotting ..."), self.iface.mainWindow()) self.sc_settings = QAction(tr("Settings ..."), self.iface.mainWindow()) self.sc_help = QAction(tr("Help"), self.iface.mainWindow()) self.sc_about = QAction(tr("About"), self.iface.mainWindow()) self.menu.addActions([ self.sc_coord, self.sc_fb, self.sc_load, self.sc_addp, self.sc_calc, self.sc_trav, self.sc_netw, self.sc_tran, self.sc_plot, self.sc_batchplot, self.sc_settings, self.sc_help, self.sc_about ]) self.menu.insertSeparator(self.sc_calc) self.menu.insertSeparator(self.sc_plot) self.menu.insertSeparator(self.sc_settings) self.menu.insertSeparator(self.sc_help) menu_bar = self.iface.mainWindow().menuBar() actions = menu_bar.actions() lastAction = actions[len(actions) - 1] menu_bar.insertMenu(lastAction, self.menu) self.sc_coord.triggered.connect(self.create_coordlist) self.sc_fb.triggered.connect(self.create_fb) self.sc_load.triggered.connect(self.load_fieldbook) self.sc_addp.triggered.connect(self.addp) self.sc_calc.triggered.connect(self.calculations) self.sc_trav.triggered.connect(self.traverses) self.sc_netw.triggered.connect(self.networks) self.sc_tran.triggered.connect(self.transformation) self.sc_pdiv.setCheckable(True) self.tool_pdiv = LineMapTool(self.iface) self.tool_pdiv.setAction(self.sc_pdiv) self.sc_pdiv.triggered.connect(self.polygon_division) self.sc_plot.triggered.connect(self.plot_by_temp) self.sc_batchplot.triggered.connect(self.batch_plotting) self.sc_settings.triggered.connect(self.settings) self.sc_about.triggered.connect(self.about) self.sc_help.triggered.connect(self.help) # add icons to toolbar self.toolbar = self.iface.addToolBar(u'SurveyingCalculation') self.toolbar.setObjectName(u'SurveyingCalculation') self.toolbar.addActions([ self.sc_load, self.sc_addp, self.sc_calc, self.sc_trav, self.sc_netw, self.sc_tran, self.sc_pdiv, self.sc_plot, self.sc_batchplot ]) self.toolbar.insertSeparator(self.sc_calc) self.toolbar.insertSeparator(self.sc_plot)
def exportLayers(iface, layers, folder, precision, optimize, popupField, json, restrictToExtent, extent): canvas = iface.mapCanvas() epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326") layersFolder = os.path.join(folder, "layers") QDir().mkpath(layersFolder) for count, (layer, encode2json, popup) in enumerate(zip(layers, json, popupField)): if (layer.type() == layer.VectorLayer and (layer.providerType() != "WFS" or encode2json)): cleanLayer = writeTmpLayer(layer, popup, restrictToExtent, iface, extent) fields = layer.pendingFields() for field in fields: exportImages(layer, field.name(), layersFolder + "/tmp.tmp") if is25d(layer, canvas, restrictToExtent, extent): provider = cleanLayer.dataProvider() provider.addAttributes([ QgsField("height", QVariant.Double), QgsField("wallColor", QVariant.String), QgsField("roofColor", QVariant.String) ]) cleanLayer.updateFields() fields = cleanLayer.pendingFields() renderer = layer.rendererV2() renderContext = QgsRenderContext.fromMapSettings( canvas.mapSettings()) feats = layer.getFeatures() context = QgsExpressionContext() context.appendScope( QgsExpressionContextUtils.layerScope(layer)) expression = QgsExpression('eval(@qgis_25d_height)') heightField = fields.indexFromName("height") wallField = fields.indexFromName("wallColor") roofField = fields.indexFromName("roofColor") renderer.startRender(renderContext, fields) cleanLayer.startEditing() for feat in feats: context.setFeature(feat) height = expression.evaluate(context) if isinstance(renderer, QgsCategorizedSymbolRendererV2): classAttribute = renderer.classAttribute() attrValue = feat.attribute(classAttribute) catIndex = renderer.categoryIndexForValue(attrValue) categories = renderer.categories() symbol = categories[catIndex].symbol() elif isinstance(renderer, QgsGraduatedSymbolRendererV2): classAttribute = renderer.classAttribute() attrValue = feat.attribute(classAttribute) ranges = renderer.ranges() for range in ranges: if (attrValue >= range.lowerValue() and attrValue <= range.upperValue()): symbol = range.symbol().clone() else: symbol = renderer.symbolForFeature2( feat, renderContext) sl1 = symbol.symbolLayer(1) sl2 = symbol.symbolLayer(2) wallColor = sl1.subSymbol().color().name() roofColor = sl2.subSymbol().color().name() provider.changeAttributeValues({ feat.id() + 1: { heightField: height, wallField: wallColor, roofField: roofColor } }) cleanLayer.commitChanges() renderer.stopRender(renderContext) sln = safeName(cleanLayer.name()) + unicode(count) tmpPath = os.path.join(layersFolder, sln + ".json") path = os.path.join(layersFolder, sln + ".js") options = [] if precision != "maintain": options.append("COORDINATE_PRECISION=" + unicode(precision)) QgsVectorFileWriter.writeAsVectorFormat(cleanLayer, tmpPath, "utf-8", epsg4326, 'GeoJson', 0, layerOptions=options) with open(path, "w") as f: f.write("var %s = " % ("geojson_" + sln)) with open(tmpPath, "r") as f2: for line in f2: if optimize: line = line.strip("\n\t ") line = removeSpaces(line) f.write(line) os.remove(tmpPath) elif (layer.type() == layer.RasterLayer and layer.providerType() != "wms"): name_ts = (safeName(layer.name()) + unicode(count) + unicode(int(time.time()))) # We need to create a new file to export style piped_file = os.path.join(tempfile.gettempdir(), name_ts + '_piped.tif') piped_extent = layer.extent() piped_width = layer.height() piped_height = layer.width() piped_crs = layer.crs() piped_renderer = layer.renderer() piped_provider = layer.dataProvider() pipe = QgsRasterPipe() pipe.set(piped_provider.clone()) pipe.set(piped_renderer.clone()) file_writer = QgsRasterFileWriter(piped_file) file_writer.writeRaster(pipe, piped_width, piped_height, piped_extent, piped_crs) # Extent of the layer in EPSG:3857 crsSrc = layer.crs() crsDest = QgsCoordinateReferenceSystem(3857) xform = QgsCoordinateTransform(crsSrc, crsDest) extentRep = xform.transform(layer.extent()) extentRepNew = ','.join([ unicode(extentRep.xMinimum()), unicode(extentRep.xMaximum()), unicode(extentRep.yMinimum()), unicode(extentRep.yMaximum()) ]) # Reproject in 3857 piped_3857 = os.path.join(tempfile.gettempdir(), name_ts + '_piped_3857.tif') # Export layer as PNG out_raster = os.path.join( layersFolder, safeName(layer.name()) + unicode(count) + ".png") qgis_version = QGis.QGIS_VERSION if int(qgis_version.split('.')[1]) < 15: processing.runalg("gdalogr:warpreproject", piped_file, layer.crs().authid(), "EPSG:3857", "", 0, 1, 0, -1, 75, 6, 1, False, 0, False, "", piped_3857) processing.runalg("gdalogr:translate", piped_3857, 100, True, "", 0, "", extentRepNew, False, 0, 0, 75, 6, 1, False, 0, False, "", out_raster) else: try: warpArgs = { "INPUT": piped_file, "SOURCE_SRS": layer.crs().authid(), "DEST_SRS": "EPSG:3857", "NO_DATA": "", "TR": 0, "METHOD": 2, "RAST_EXT": extentRepNew, "EXT_CRS": "EPSG:3857", "RTYPE": 0, "COMPRESS": 4, "JPEGCOMPRESSION": 75, "ZLEVEL": 6, "PREDICTOR": 1, "TILED": False, "BIGTIFF": 0, "TFW": False, "EXTRA": "", "OUTPUT": piped_3857 } procRtn = processing.runalg("gdalogr:warpreproject", warpArgs) # force exception on algorithm fail for val in procRtn: pass except: try: warpArgs = { "INPUT": piped_file, "SOURCE_SRS": layer.crs().authid(), "DEST_SRS": "EPSG:3857", "NO_DATA": "", "TR": 0, "METHOD": 2, "RAST_EXT": extentRepNew, "RTYPE": 0, "COMPRESS": 4, "JPEGCOMPRESSION": 75, "ZLEVEL": 6, "PREDICTOR": 1, "TILED": False, "BIGTIFF": 0, "TFW": False, "EXTRA": "", "OUTPUT": piped_3857 } procRtn = processing.runalg("gdalogr:warpreproject", warpArgs) # force exception on algorithm fail for val in procRtn: pass except: try: warpArgs = { "INPUT": piped_file, "SOURCE_SRS": layer.crs().authid(), "DEST_SRS": "EPSG:3857", "NO_DATA": "", "TR": 0, "METHOD": 2, "RTYPE": 0, "COMPRESS": 4, "JPEGCOMPRESSION": 75, "ZLEVEL": 6, "PREDICTOR": 1, "TILED": False, "BIGTIFF": 0, "TFW": False, "EXTRA": "", "OUTPUT": piped_3857 } procRtn = processing.runalg( "gdalogr:warpreproject", warpArgs) # force exception on algorithm fail for val in procRtn: pass except: shutil.copyfile(piped_file, piped_3857) try: processing.runalg("gdalogr:translate", piped_3857, 100, True, "", 0, "", extentRepNew, False, 5, 4, 75, 6, 1, False, 0, False, "", out_raster) except: shutil.copyfile(piped_3857, out_raster)
def _open_database(self, dbPath): """Opens a database. Checks if there are geometry_columns and spatial_ref_sys tables in the database, if not it creates and fills those tables. Checks if there are all PU columns in PAR table, if it it creates and fills those columns. Args: dbPath (str): A full path to the database. Raises: dw.puError: When SQLITE database driver is not available or when database connection fails. """ if not QSqlDatabase.isDriverAvailable('QSQLITE'): raise self.dW.puError( self.dW, self, u'SQLITE database driver is not available.', u'Databázový ovladač QSQLITE není dostupný.', u'Databázový ovladač QSQLITE není dostupný.') connectionName = QUuid.createUuid().toString() db = QSqlDatabase.addDatabase('QSQLITE', connectionName) db.setDatabaseName(dbPath) db.open() if not db.open(): raise self.dW.puError(self.dW, self, u'Database connection failed.', u'Nepodařilo se připojit k databázi.', u'Nepodařilo se připojit k databázi.') self.set_text_statusbar.emit(u'Kontroluji tabulky a sloupce...', 0, False) QgsApplication.processEvents() sqlQuery = QSqlQuery(db) sqlDir = QDir(self.pluginDir.path() + u'/data/sql') query = self._read_text_from_file(sqlDir.filePath(u'check_gc_srs.sql')) sqlQuery.exec_(query) QgsApplication.processEvents() checkGcSrsSize = 0 while sqlQuery.next(): checkGcSrsSize += 1 if checkGcSrsSize < 2: queries = self._read_text_from_file( sqlDir.filePath(u'create_fill_gc_srs.sql')).split(';') for query in queries: sqlQuery.exec_(query) QgsApplication.processEvents() query = self._read_text_from_file( sqlDir.filePath(u'check_pu_columns_PAR.sql')) sqlQuery.exec_(query) QgsApplication.processEvents() columns = [] while sqlQuery.next(): record = sqlQuery.record() name = str(record.value('name')) columns.append(name) if not all(column in columns for column in self.dW.allPuColumns): queries = self._read_text_from_file( sqlDir.filePath(u'add_pu_columns_PAR.sql')).split(';') for query in queries: sqlQuery.exec_(query) QgsApplication.processEvents() queries = self._read_text_from_file( sqlDir.filePath(u'create_sobr_spol.sql')).split(';') for query in queries: sqlQuery.exec_(query) db.close()
Variables set: :fontname: monospace font used in calculation results widgets :fontsize: font size used in calculation results widgets :homedir: start dir used for loading fieldbooks :template_dir: path to template files for batch plotting :log_path: path to log file :line_tolerance: snapping tolerance to line tool :area_tolerance: area tolerance for area division :max_iteration: maximal number of iterations for area division :gama_path: full path to gama-local, default plug-in dir """ from PyQt4.QtCore import QDir, QFileInfo # dialogs fontname = 'DejaVu Sans Mono' fontsize = 9 # homedir = QDir().cleanPath( QFileInfo(__file__).absolutePath() ) # plot template template_dir = QDir(homedir).absoluteFilePath("template") # logging log_path = '/tmp/log.log' # line tool line_tolerance = 1 # tolerance in layer units # area division area_tolerance = 0.5 # tolerance in layer unirs max_iteration = 100 # maximum number of iteration in area division # GNU Gama - full path to gama-local gama_path = '/home/siki/Downloads/gama-1.15/bin/gama-local'
def testWriteShapefileWithZ(self): """Check writing geometries with Z dimension to an ESRI shapefile.""" #start by saving a memory layer and forcing z ml = QgsVectorLayer(('Point?crs=epsg:4326&field=id:int'), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromWkt('PointZ (1 2 3)')) ft.setAttributes([1]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 # check with both a standard PointZ and 25d style Point25D type for t in [QgsWKBTypes.PointZ, QgsWKBTypes.Point25D]: dest_file_name = os.path.join( str(QDir.tempPath()), 'point_{}.shp'.format(QgsWKBTypes.displayString(t))) print(dest_file_name) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile', overrideGeometryType=t) self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer( u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') f = created_layer.getFeatures(QgsFeatureRequest()).next() g = f.geometry() wkt = g.exportToWkt() expWkt = 'PointZ (1 2 3)' assert compareWkt( expWkt, wkt ), "saving geometry with Z failed: mismatch Expected:\n%s\nGot:\n%s\n" % ( expWkt, wkt) #also try saving out the shapefile version again, as an extra test #this tests that saving a layer with z WITHOUT explicitly telling the writer to keep z values, #will stay retain the z values dest_file_name = os.path.join( str(QDir.tempPath()), 'point_{}_copy.shp'.format(QgsWKBTypes.displayString(t))) print(dest_file_name) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( created_layer, dest_file_name, 'utf-8', crs, 'ESRI Shapefile') self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer_from_shp = QgsVectorLayer( u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') f = created_layer_from_shp.getFeatures(QgsFeatureRequest()).next() g = f.geometry() wkt = g.exportToWkt() assert compareWkt( expWkt, wkt ), "saving geometry with Z failed: mismatch Expected:\n%s\nGot:\n%s\n" % ( expWkt, wkt)
def load_fieldbook(self): """ Import an electric fieldbook from file (GSI, JOB/ARE, ...) """ if get_coordlist() is None: QMessageBox.warning( self.iface.mainWindow(), tr("Warning"), tr("No coordinate list is opened, coordinates will be lost from the fieldbook" )) homedir = QSettings().value("SurveyingCalculation/homedir", config.homedir) fname = QFileDialog.getOpenFileName(self.iface.mainWindow(), \ tr('Electric fieldbook'), homedir, \ filter = tr('Leica GSI (*.gsi);;Leica IDX (*.idx);;Geodimeter JOB/ARE (*.job *.are);;Sokkia CRD (*.crd);;SurvCE RW5 (*.rw5);;STONEX DAT (*.dat);;Text dump (*.dmp)')) if fname: # file selected # make a copy of dbf template if not are is loaded if QRegExp('\.are$', Qt.CaseInsensitive).indexIn(fname) == -1: # ask for table name ofname = QFileDialog.getSaveFileName( self.iface.mainWindow(), tr('QGIS fieldbook'), QFileInfo(fname).absolutePath(), filter=tr('DBF file (*.dbf)')) if not ofname: return # remember last input dir QSettings().setValue("SurveyingCalculation/homedir", QFileInfo(fname).absolutePath()) QSettings().sync() # start with 'fb_'? if QRegExp('fb_').indexIn(QFileInfo(ofname).baseName()): ofname = QDir.cleanPath( QFileInfo(ofname).absolutePath() + QDir().separator() + 'fb_' + QFileInfo(ofname).fileName()) # extension is .dbf? if QRegExp('\.dbf$', Qt.CaseInsensitive).indexIn(ofname) == -1: ofname += '.dbf' tempname = QDir.cleanPath(self.plugin_dir + QDir().separator() + 'template' + QDir().separator() + 'fb_template.dbf') if not QFile(tempname).copy(ofname): QMessageBox.warning( self.iface.mainWindow(), tr('File warning'), tr('Error copying fieldbook template, target file exists?' ), tr('OK')) return fb_dbf = QgsVectorLayer(ofname, QFileInfo(ofname).baseName(), "ogr") if not fb_dbf or not fb_dbf.isValid(): QMessageBox.warning(self.iface.mainWindow(), tr('File warning'), tr('Fieldbook loading error'), tr('OK')) return QgsMapLayerRegistry.instance().addMapLayer(fb_dbf) if QRegExp('\.gsi$', Qt.CaseInsensitive).indexIn(fname) > -1: fb = LeicaGsi(fname) elif QRegExp('\.job$', Qt.CaseInsensitive).indexIn(fname) > -1 or \ QRegExp('\.are$', Qt.CaseInsensitive).indexIn(fname) > -1: fb = JobAre(fname) elif QRegExp('\.crd$', Qt.CaseInsensitive).indexIn(fname) > -1: fb = Sdr(fname) elif QRegExp('\.rw5$', Qt.CaseInsensitive).indexIn(fname) > -1: fb = SurvCE(fname) elif QRegExp('\.dat$', Qt.CaseInsensitive).indexIn(fname) > -1: fb = Stonex(fname) elif QRegExp('\.dmp$', Qt.CaseInsensitive).indexIn(fname) > -1: fb = Dump(fname) elif QRegExp('\.idx$', Qt.CaseInsensitive).indexIn(fname) > -1: fb = Idex(fname) else: QMessageBox.warning(self.iface.mainWindow(), tr('File warning'), tr('Unknown fieldbook type'), tr('OK')) return i = 10 # ordinal number for fieldbook records #fb_dbf.startEditing() fb.open() n_fb = 0 # fieldbook records stored n_co = 0 # points stored in coordinate list while True: # get next observation/station data from fieldbook r = fb.parse_next() if r is None: break # end of file if 'station' in r: # add row to fieldbook table record = QgsFeature() # add & initialize attributes record.setFields(fb_dbf.pendingFields(), True) j = fb_dbf.dataProvider().fieldNameIndex('id') if j != -1: record.setAttribute(j, i) for key in r: j = fb_dbf.dataProvider().fieldNameIndex(key) if j != -1: record.setAttribute(j, r[key]) (xxx, yyy) = fb_dbf.dataProvider().addFeatures([record]) if not xxx: QMessageBox.warning( self.iface.mainWindow(), tr('File warning'), tr('Fieldbook record creation error'), tr('OK')) return n_fb += 1 if 'station_e' in r or 'station_z' in r: # store station coordinates too dimension = 0 if 'station_z' in r: dimension += 1 else: r['station_z'] = None if 'station_e' in r and 'station_n' in r: dimension += 2 else: r['station_e'] = None r['station_n'] = None if not 'pc' in r: r['pc'] = None p = Point(r['point_id'], r['station_e'], r['station_n'], r['station_z'], r['pc']) qp = ScPoint(p) qp.store_coord(dimension) n_co += 1 if 'e' in r or 'z' in r: # store coordinates too dimension = 0 if 'z' in r: dimension += 1 else: r['z'] = None if 'e' in r and 'n' in r: dimension += 2 else: r['e'] = None r['n'] = None if not 'pc' in r: r['pc'] = None p = Point(r['point_id'], r['e'], r['n'], r['z'], r['pc']) qp = ScPoint(p) qp.store_coord(dimension) n_co += 1 i += 10 #fb_dbf.commitChanges() if QRegExp('\.are$', Qt.CaseInsensitive).indexIn(fname) == -1: if n_fb == 0: # no observations QgsMapLayerRegistry.instance().removeMapLayer(fb_dbf.id()) # remove empty file QFile(ofname).remove() if n_co == 0: # no coordinates QMessageBox.warning(self.iface.mainWindow(), tr("Warning"),\ tr("Neither coordinates nor observations found")) else: QMessageBox.warning(self.iface.mainWindow(), tr("Warning"),\ tr("No observations found")) self.log.write() self.log.write_log(tr("Fieldbook loaded: ") + fname) self.log.write(" %d observations, %d coordinates" % (n_fb, n_co)) return
def installPlugin(self, key, quiet=False): """ Install given plugin """ error = False infoString = ('', '') plugin = plugins.all()[key] previousStatus = plugin["status"] if not plugin: return if plugin["status"] == "newer" and not plugin[ "error"]: # ask for confirmation if user downgrades an usable plugin if QMessageBox.warning( iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self. tr("Are you sure you want to downgrade the plugin to the latest available version? The installed one is newer!" ), QMessageBox.Yes, QMessageBox.No) == QMessageBox.No: return dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(), plugin) dlg.exec_() if dlg.result(): error = True infoString = (self.tr("Plugin installation failed"), dlg.result()) elif not QDir(qgis.utils.home_plugin_path + "/" + key).exists(): error = True infoString = ( self.tr("Plugin has disappeared"), self. tr("The plugin seems to have been installed but I don't know where. Probably the plugin package contained a wrong named directory.\nPlease search the list of installed plugins. I'm nearly sure you'll find the plugin there, but I just can't determine which of them it is. It also means that I won't be able to determine if this plugin is installed and inform you about available updates. However the plugin may work. Please contact the plugin author and submit this issue." )) QApplication.setOverrideCursor(Qt.WaitCursor) plugins.getAllInstalled() plugins.rebuild() self.exportPluginsToManager() QApplication.restoreOverrideCursor() else: QApplication.setOverrideCursor(Qt.WaitCursor) # update the list of plugins in plugin handling routines updateAvailablePlugins() # try to load the plugin loadPlugin(plugin["id"]) plugins.getAllInstalled(testLoad=True) plugins.rebuild() plugin = plugins.all()[key] if not plugin["error"]: if previousStatus in ["not installed", "new"]: infoString = (self.tr("Plugin installed successfully"), "") if startPlugin(plugin["id"]): settings = QSettings() settings.setValue("/PythonPlugins/" + plugin["id"], True) else: settings = QSettings() if settings.value( "/PythonPlugins/" + key, False, type=bool ): # plugin will be reloaded on the fly only if currently loaded reloadPlugin( key) # unloadPlugin + loadPlugin + startPlugin infoString = ( self.tr("Plugin reinstalled successfully"), "") else: unloadPlugin( key ) # Just for a case. Will exit quietly if really not loaded loadPlugin(key) infoString = ( self.tr("Plugin reinstalled successfully"), self. tr("Python plugin reinstalled.\nYou need to restart QGIS in order to reload it." )) if quiet: infoString = (None, None) QApplication.restoreOverrideCursor() else: QApplication.restoreOverrideCursor() if plugin["error"] == "incompatible": message = self.tr( "The plugin is not compatible with this version of QGIS. It's designed for QGIS versions:" ) message += " <b>" + plugin["error_details"] + "</b>" elif plugin["error"] == "dependent": message = self.tr( "The plugin depends on some components missing on your system. You need to install the following Python module in order to enable it:" ) message += "<b> " + plugin["error_details"] + "</b>" else: message = self.tr("The plugin is broken. Python said:") message += "<br><b>" + plugin["error_details"] + "</b>" dlg = QgsPluginInstallerPluginErrorDialog( iface.mainWindow(), message) dlg.exec_() if dlg.result(): # revert installation pluginDir = qgis.utils.home_plugin_path + "/" + plugin["id"] result = removeDir(pluginDir) if QDir(pluginDir).exists(): error = True infoString = (self.tr("Plugin uninstall failed"), result) try: exec("sys.path_importer_cache.clear()") exec("import %s" % plugin["id"]) exec("reload (%s)" % plugin["id"]) except: pass else: try: exec("del sys.modules[%s]" % plugin["id"]) except: pass plugins.getAllInstalled() plugins.rebuild() self.exportPluginsToManager() if infoString[0]: level = error and QgsMessageBar.CRITICAL or QgsMessageBar.INFO msg = "<b>%s:</b>%s" % (infoString[0], infoString[1]) iface.pluginManagerInterface().pushMessage(msg, level)
def testDateTimeWriteShapefile(self): """Check writing date and time fields to an ESRI shapefile.""" ml = QgsVectorLayer( ('Point?crs=epsg:4326&field=id:int&' 'field=date_f:date&field=time_f:time&field=dt_f:datetime'), 'test', 'memory') assert ml is not None, 'Provider not initialized' assert ml.isValid(), 'Source layer not valid' provider = ml.dataProvider() assert provider is not None ft = QgsFeature() ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(10, 10))) ft.setAttributes([ 1, QDate(2014, 3, 5), QTime(13, 45, 22), QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22)) ]) res, features = provider.addFeatures([ft]) assert res assert len(features) > 0 dest_file_name = os.path.join(str(QDir.tempPath()), 'datetime.shp') print(dest_file_name) crs = QgsCoordinateReferenceSystem() crs.createFromId(4326, QgsCoordinateReferenceSystem.EpsgCrsId) write_result = QgsVectorFileWriter.writeAsVectorFormat( ml, dest_file_name, 'utf-8', crs, 'ESRI Shapefile') self.assertEqual(write_result, QgsVectorFileWriter.NoError) # Open result and check created_layer = QgsVectorLayer(u'{}|layerid=0'.format(dest_file_name), u'test', u'ogr') fields = created_layer.dataProvider().fields() self.assertEqual( fields.at(fields.indexFromName('date_f')).type(), QVariant.Date) #shapefiles do not support time types, result should be string self.assertEqual( fields.at(fields.indexFromName('time_f')).type(), QVariant.String) #shapefiles do not support datetime types, result should be string self.assertEqual( fields.at(fields.indexFromName('dt_f')).type(), QVariant.String) f = created_layer.getFeatures(QgsFeatureRequest()).next() date_idx = created_layer.fieldNameIndex('date_f') assert isinstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2014, 3, 5)) time_idx = created_layer.fieldNameIndex('time_f') #shapefiles do not support time types assert isinstance(f.attributes()[time_idx], basestring) self.assertEqual(f.attributes()[time_idx], '13:45:22') #shapefiles do not support datetime types datetime_idx = created_layer.fieldNameIndex('dt_f') assert isinstance(f.attributes()[datetime_idx], basestring) self.assertEqual( f.attributes()[datetime_idx], QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22)).toString("yyyy/MM/dd hh:mm:ss.zzz"))
def computeCache(self, fname=None, rep=''): from PyQt4.QtCore import QDir print 'compute cache' self.__cachedcariables = list(self.variations.iterkeys()) if not fname or not self.__use_cache: print 'no cache :', not self.__use_cache for i, maxp in self.__computeCache(): yield i, maxp else: from os.path import exists, join from os import mkdir, rmdir from shutil import rmtree tmpdir = str(QDir.tempPath()) cachedir = join(tmpdir, 'flowerdemo-cache') if '--re-cache' in sys.argv and exists(cachedir): print 'Remove cache dir :', repr(cachedir) try: rmtree(cachedir) except Exception, e: print e pass lcachedir = join(cachedir, rep) gfname = join(lcachedir, fname) outdated = False timestampfile = join(lcachedir, 'timestamp.txt') self.cache = {} if exists(timestampfile) and long( eval(file(timestampfile).readline())) < long( os.stat(self.lsystem_file).st_mtime): print 'Outdated cache for lsystem', self.lsystem_file outdated = True if not outdated and exists(gfname): print 'looking for cache files' cache = eval(file(gfname).readline()) maxp = len(cache) i = 0 for key, value in cache.iteritems(): valuepath = join(lcachedir, value) if exists(valuepath): self.cache[key] = Scene(valuepath) else: self.cache.clear() break i += 1 yield i, maxp print 'load cache ', fname if len(self.cache) == 0: print 'compute cache' for i, maxp in self.__computeCache(): yield i, maxp if not exists(cachedir): mkdir(cachedir) if not exists(lcachedir): mkdir(lcachedir) cache = {} for key, value in self.cache.iteritems(): lfname = '__' + ''.join( ['_' if not i.isalnum() else i for i in str(key)]) + '.bgeom' value.save(join(lcachedir, lfname)) cache[key] = lfname stream = file(gfname, 'w') stream.write(str(cache) + '\n') stream = file(timestampfile, 'w') stream.write( str(long(os.stat(self.lsystem_file).st_mtime)) + '\n') yield 1, 1 print 'save cache', repr(fname)