def copyToResources(self, name, folder): resourcesFolder = os.path.join(folder, "resources") if not QDir(resourcesFolder).exists(): QDir().mkpath(resourcesFolder) f = os.path.join(os.path.dirname(inspect.getfile(self.__class__)), name) if os.path.exists(f): shutil.copy2(f, resourcesFolder)
def writeHelpFiles(self, appdef, folder): helpFolder = os.path.join(folder, "help") if not QDir(helpFolder).exists(): QDir().mkpath(helpFolder) content = "" sections = "" for widget in appdef["Widgets"].values(): helpContent = widget.widgetHelp() if helpContent is not None: helpImageFiles = widget.widgetHelpFiles() content += '<a name="%s"></a>' % widget.name() content += '<h2>%s</h2>' % widget.description() content += helpContent sections += '<li><a href="#%s">%s</a></li>' % ( widget.name(), widget.description()) for f in helpImageFiles: shutil.copy2(f, helpFolder) values = { "@SECTIONS@": sections, "@TITLE@": appdef["Settings"]["Title"], "@CONTENT@": content } templatePath = os.path.join(os.path.dirname(__file__), "base.html") html = replaceInTemplate(templatePath, values) with codecs.open(os.path.join(helpFolder, "help.html"), "w", encoding="utf-8") as f: f.write(html)
def writeLegendFiles(self, appdef, app, folder): layers = appdef["Layers"] legend = {} legendFolder = os.path.join(folder, "resources", "legend") if not QDir(legendFolder).exists(): QDir().mkpath(legendFolder) for ilayer, applayer in enumerate(layers): if applayer.showInControls: layer = applayer.layer symbols = self.getLegendSymbols(layer, ilayer, legendFolder) if symbols: legend[layer.id()] = symbols app.variables.append("var legendData = %s;" % json.dumps(legend))
def get_library_path(parent=None): library_path = prefs['library_path'] if library_path is None: # Need to migrate to new database layout base = os.path.expanduser('~') if iswindows: base = winutil.special_folder_path(winutil.CSIDL_PERSONAL) if not base or not os.path.exists(base): from PyQt4.Qt import QDir base = unicode(QDir.homePath()).replace('/', os.sep) candidate = choose_dir( None, 'choose calibre library', _('Choose a location for your calibre e-book library'), default_dir=base) if not candidate: candidate = os.path.join(base, 'Calibre Library') library_path = os.path.abspath(candidate) if not os.path.exists(library_path): try: os.makedirs(library_path) except: error_dialog(parent, _('Failed to create library'), _('Failed to create calibre library at: %r.') % library_path, det_msg=traceback.format_exc(), show=True) library_path = choose_dir( parent, 'choose calibre library', _('Choose a location for your new calibre e-book library'), default_dir=get_default_library_path()) return library_path
def __init__(self, parent, name=None): QTreeWidgetItem.__init__(self) self.filterList = ('mmp', 'MMP') if isinstance(parent, QListView): self.p = None if name: self.f = name else: self.f = '/' else: self.p = parent self.f = name self.readable = QDir(self.fullName()).isReadable() if not self.readable: self.setIcon(0, folderLockedIcon) else: self.setIcon(0, folderClosedIcon) if name is not None: self.setText(1, name) if isinstance(parent, QTreeWidget): parent.addTopLevelItem(self) else: parent.addChild(self)
def get_library_path(parent=None): library_path = prefs['library_path'] if library_path is None: # Need to migrate to new database layout base = os.path.expanduser('~') if iswindows: base = winutil.special_folder_path(winutil.CSIDL_PERSONAL) if not base or not os.path.exists(base): from PyQt4.Qt import QDir base = unicode(QDir.homePath()).replace('/', os.sep) candidate = choose_dir(None, 'choose calibre library', _('Choose a location for your calibre e-book library'), default_dir=base) if not candidate: candidate = os.path.join(base, 'Calibre Library') library_path = os.path.abspath(candidate) if not os.path.exists(library_path): try: os.makedirs(library_path) except: error_dialog(parent, _('Failed to create library'), _('Failed to create calibre library at: %r.')%library_path, det_msg=traceback.format_exc(), show=True) library_path = choose_dir(parent, 'choose calibre library', _('Choose a location for your new calibre e-book library'), default_dir=get_default_library_path()) return library_path
def ensure_QDir(arg): if type(arg) == type(""): arg = QString(arg) if isinstance(arg, QString): arg = QDir(arg) assert isinstance(arg, QDir) # fails if caller passes the wrong thing return arg
def __create_backup_file(self, orig_layer): file_name = self.backup_path + QDir.separator() + self.layer_id error = QgsVectorFileWriter.writeAsVectorFormat(orig_layer, file_name, "utf-8", None, "ESRI Shapefile", False, None, list(), list(), True) if error == QgsVectorFileWriter.NoError: QgsMessageLog.logMessage(self.plugin.tr('Backup created.'), self.plugin.tr('Vertex Tools'), QgsMessageLog.INFO)
def setOpen(self, o): if o: self.setIcon(0, folderOpenIcon) else: self.setIcon(0, folderClosedIcon) if o and not self.childCount(): s = self.fullName() thisDir = QDir(s) if not thisDir.isReadable(): self.readable = 0 return files = thisDir.entryInfoList() if files: for f in files: # f is a QFileInfo # f.fileName is '.' or '..' or 'bearings' or... fileName = str(f.fileName()) if fileName == '.' or fileName == '..': continue elif f.isSymLink(): d = QTreeWidgetItem(self, fileName) #, 'Symbolic Link') d.setIcon(0, fileIcon) elif f.isDir(): if fileName == 'CVS': #bruce 060319 skip CVS directories, so developers see same set of directories as end-users # (implements NFR I recently reported) # WARNING: this is only legitimate for some applications of this module. # For now that's ok (we only use it in MMKit). Later this feature should be turned on # by an optional argument to __init__, and generalized to a list of files to not show # or to a filter function. continue d = Directory(self, fileName) else: if f.isFile(): s = 'File' else: s = 'Special' if not fileName[-3:] in self.filterList: continue d = FileItem(self, f.absFilePath(), fileName) d.setIcon(0, fileIcon) qt4todo('QTreeWidgetItem.setOpen(self, o)')
def setOpen(self, o): if o: self.setIcon(0, folderOpenIcon) else: self.setIcon(0, folderClosedIcon) if o and not self.childCount(): s = self.fullName() thisDir = QDir(s) if not thisDir.isReadable(): self.readable = 0 return files = thisDir.entryInfoList() if files: for f in files: # f is a QFileInfo # f.fileName is '.' or '..' or 'bearings' or... fileName = str(f.fileName()) if fileName == '.' or fileName == '..': continue elif f.isSymLink(): d = QTreeWidgetItem(self, fileName)#, 'Symbolic Link') d.setIcon(0, fileIcon) elif f.isDir(): if fileName == 'CVS': #bruce 060319 skip CVS directories, so developers see same set of directories as end-users # (implements NFR I recently reported) # WARNING: this is only legitimate for some applications of this module. # For now that's ok (we only use it in MMKit). Later this feature should be turned on # by an optional argument to __init__, and generalized to a list of files to not show # or to a filter function. continue d = Directory(self, fileName) else: if f.isFile(): s = 'File' else: s = 'Special' if not fileName[-3:] in self.filterList: continue d = FileItem(self, f.absFilePath(), fileName) d.setIcon(0, fileIcon) qt4todo('QTreeWidgetItem.setOpen(self, o)')
def setThemeFromGtk(): f = QFile(QDir.homePath() + "/.gtkrc-2.0"); if not f.open(QIODevice.ReadOnly | QIODevice.Text): return while not f.atEnd(): l = f.readLine().trimmed(); if l.startsWith("gtk-icon-theme-name="): s = QString(l.split('=')[-1]); syslog.syslog( syslog.LOG_DEBUG, "DEBUG setting gtk theme %s" % str(s)); QIcon.setThemeName(s.remove('"')); break
def run_command(self, program, args): if debug_run(): print "will run this command:", program, args from PyQt4.Qt import QStringList, QProcess, QObject, SIGNAL, QDir # modified from runSim.py arguments = QStringList() if sys.platform == 'win32': program = "\"%s\"" % program # Double quotes needed by Windows. ###@@@ test this ### try it with blanks in output file name and in program name, once it works ###@@@ for arg in [program] + args: if arg: arguments.append(arg) self.simProcess = simProcess = QProcess() simProcess.setArguments(arguments) simProcess.setWorkingDirectory(QDir(self.working_directory)) # in case it writes random files if 1: # report stdout/stderr def blabout(): print "stdout:", simProcess.readStdout() ##e should also mention its existence in history, but don't copy it all there in case a lot def blaberr(): text = str(simProcess.readStderr()) # str since it's QString (i hope it can't be unicode) print "stderr:", text env.history.message(redmsg("%s stderr: " % self.plugin_name + quote_html(text))) # examples from CoNTub/bin/HJ: # stderr: BAD INPUT # stderr: Error: Indices of both tubes coincide QObject.connect(simProcess, SIGNAL("readyReadStdout()"), blabout) QObject.connect(simProcess, SIGNAL("readyReadStderr()"), blaberr) started = simProcess.start() ###k what is this code? i forget if true means ok or error if debug_run(): print "qprocess started:",started while 1: ###e need to make it abortable! from which abort button? ideally, one on the dialog; maybe cancel button?? # on exception: simProcess.kill() if simProcess.isRunning(): if debug_run(): print "still running" time.sleep(1) else: time.sleep(0.1) else: break if debug_run(): print "process done i guess: normalExit = %r, (if normal) exitStatus = %r" % \ (simProcess.normalExit(), simProcess.exitStatus()) if 1: QObject.disconnect(simProcess, SIGNAL("readyReadStdout()"), blabout) QObject.disconnect(simProcess, SIGNAL("readyReadStderr()"), blaberr) if simProcess.normalExit(): return simProcess.exitStatus() else: return -1
def __restore_geometries(self): src_file_name = self.backup_path + QDir.separator() + self.layer_id + '.shp' if not QFile.exists(src_file_name): self.report_message.emit(self.layer_id, 'no backup file') self.completed = True return self.report_message.emit(self.layer_id, 'preparing ...') orig_layer = QgsMapLayerRegistry.instance().mapLayer(self.layer_id) # create a copy of the layer just for editing layer = QgsVectorLayer(orig_layer.source(), orig_layer.name(), orig_layer.providerType()) layer.startEditing() src_layer = QgsVectorLayer(src_file_name, layer.name(), 'ogr') total_features = src_layer.featureCount() QgsMessageLog.logMessage(self.plugin.tr('Features to be restored in layer <{0}>: {1}'). format(orig_layer.name(), total_features), self.plugin.tr('Vertex Tools'), QgsMessageLog.INFO) if total_features == 0: self.report_message.emit(self.layer_id, 'no features to restore') count = 0 for feature in src_layer.getFeatures(): with QMutexLocker(self.mutex): if self.stopped: layer.rollBack() return layer.changeGeometry(feature.id(), feature.geometry()) count += 1 self.run_progressed.emit(self.layer_id, count, total_features) layer.commitChanges() self.completed = True
tree.setWindowTitle(tree.tr("Dir View")) tree.resize(250, 480) tree.show() for i in range(1,4): tree.hideColumn(i) sys.exit(app.exec_()) if False and __name__ == '__main__': a = QApplication(sys.argv) if 1: mw = DirView() a.setMainWidget(mw) mw.setCaption('PyQt Example - Directory Browser') mw.resize(400, 400) #mw.setSelectionMode(QTreeWidget.Extended) root = Directory(mw)#, '/huaicai') root.setOpen(1) mw.show() a.exec_() else: roots = QDir("/download") fiList = roots.entryInfoList() for drv in fiList: print "The file path is: ", str(drv.absFilePath()) a.exec_() # end
def writePrintFiles(self, appdef, folder, app, progress): progress.setText("Writing print layout files") progress.setProgress(0) printFolder = os.path.join(folder, "resources", "print") if not QDir(printFolder).exists(): QDir().mkpath(printFolder) dpis = [72, 150, 300] layoutDefs = [] def getBasicInfo(item): coords = {} pos = item.pos() coords["x"] = pos.x() coords["y"] = pos.y() rect = item.rect() coords["width"] = rect.width() coords["height"] = rect.height() coords["id"] = str(uuid.uuid4()) return coords composers = iface.activeComposers() for i, composer in enumerate(composers): name = composer.composerWindow().windowTitle() layoutSafeName = safeName(name) layoutDef = {} composition = composer.composition() img = composition.printPageAsRaster(0) img = img.scaledToHeight(100, Qt.SmoothTransformation) img.save(os.path.join(printFolder, "%s_thumbnail.png" % layoutSafeName)) layoutDef["width"] = composition.paperWidth() layoutDef["height"] = composition.paperHeight() elements = [] layoutDef["thumbnail"] = "%s_thumbnail.png" % layoutSafeName layoutDef["name"] = name layoutDef["elements"] = elements for item in composition.items(): element = None if isinstance(item, (QgsComposerLegend, QgsComposerShape, QgsComposerScaleBar, QgsComposerArrow)): element = getBasicInfo(item) for dpi in dpis: dpmm = dpi / 25.4 s = QSize(item.rect().width() * dpmm, item.rect().height() * dpmm) img = QImage(s, QImage.Format_ARGB32_Premultiplied) img.fill(Qt.transparent) painter = QPainter(img) painter.scale(dpmm, dpmm) item.paint(painter, None, None) painter.end() img.save(os.path.join(printFolder, "%s_%s_%s.png" % (layoutSafeName, element["id"], str(dpi)))) elif isinstance(item, QgsComposerLabel): element = getBasicInfo(item) element["name"] = item.text() element["size"] = item.font().pointSize() element["font"] = item.font().rawName() elif isinstance(item, QgsComposerMap): element = getBasicInfo(item) grid = item.grid() if grid is not None: element["grid"] = {} element["grid"]["intervalX"] = grid.intervalX() element["grid"]["intervalY"] = grid.intervalY() element["grid"]["crs"] = grid.crs().authid() element["grid"]["annotationEnabled"] = grid.annotationEnabled() elif isinstance(item, QgsComposerPicture): filename = os.path.basename(item.picturePath()) if os.path.exists(filename): element = getBasicInfo(item) shutil.copy(item.pictureFile(), os.path.join(printFolder, filename)) element["file"] = filename if element is not None: element["type"] = item.__class__.__name__[11:].lower() elements.append(element) layoutDefs.append(layoutDef) progress.setProgress(int((i+1)*100.0/len(composers))) app.variables.append("var printLayouts = %s;" % json.dumps(layoutDefs))
class QTouTvSettings(Qt.QObject): _DEFAULT_DOWNLOAD_DIR = QDir.home().absoluteFilePath('TOU.TV Downloads') _settings_types = { SettingsKeys.FILES_DOWNLOAD_DIR: str, SettingsKeys.NETWORK_HTTP_PROXY: str, SettingsKeys.DL_DOWNLOAD_SLOTS: int, SettingsKeys.DL_ALWAYS_MAX_QUALITY: bool, SettingsKeys.DL_REMOVE_FINISHED: bool, } setting_item_changed = QtCore.pyqtSignal(str, object) def __init__(self): super().__init__() self._fill_defaults() self._settings_dict = {} def _fill_defaults(self): """Fills defaults with sensible default values.""" self.defaults = {} def_dl_dir = QTouTvSettings._DEFAULT_DOWNLOAD_DIR self.defaults[SettingsKeys.FILES_DOWNLOAD_DIR] = def_dl_dir self.defaults[SettingsKeys.NETWORK_HTTP_PROXY] = "" self.defaults[SettingsKeys.DL_DOWNLOAD_SLOTS] = 5 self.defaults[SettingsKeys.DL_ALWAYS_MAX_QUALITY] = False self.defaults[SettingsKeys.DL_REMOVE_FINISHED] = False def write_settings(self): logging.debug('Writing settings') settings = QSettings() settings.clear() for k in self._settings_dict: if k in self.defaults: if self._settings_dict[k] != self.defaults[k]: settings.setValue(k, self._settings_dict[k]) else: msg = 'Setting key {} not found in defaults'.format(k) logging.warning(msg) settings.setValue(k, self._settings_dict[k]) def read_settings(self): logging.debug('Reading settings') settings = QSettings() read_settings = self.defaults.copy() keys = settings.allKeys() for k in keys: setting_type = QTouTvSettings._settings_types[k] read_settings[k] = settings.value(k, type=setting_type) self.apply_settings(read_settings) def _apply_settings(self, key, new_value): """Apply the new value. Return whether the value changed.""" # If the key did not exist, it "changed". if key not in self._settings_dict: self._settings_dict[key] = new_value return True cur_value = self._settings_dict[key] if cur_value == new_value: return False self._settings_dict[key] = new_value return True def apply_settings(self, new_settings): logging.debug('Applying settings') for key in new_settings: new_value = new_settings[key] if self._apply_settings(key, new_value): self.setting_item_changed.emit(key, new_value) self.write_settings() def get_download_directory(self): return self._settings_dict[SettingsKeys.FILES_DOWNLOAD_DIR] def get_http_proxy(self): return self._settings_dict[SettingsKeys.NETWORK_HTTP_PROXY] def get_download_slots(self): return int(self._settings_dict[SettingsKeys.DL_DOWNLOAD_SLOTS]) def get_always_max_quality(self): return self._settings_dict[SettingsKeys.DL_ALWAYS_MAX_QUALITY] def get_remove_finished(self): return self._settings_dict[SettingsKeys.DL_REMOVE_FINISHED] def debug_print_settings(self): print(self._settings_dict)
tree.setWindowTitle(tree.tr("Dir View")) tree.resize(250, 480) tree.show() for i in range(1, 4): tree.hideColumn(i) sys.exit(app.exec_()) if False and __name__ == '__main__': a = QApplication(sys.argv) if 1: mw = DirView() a.setMainWidget(mw) mw.setCaption('PyQt Example - Directory Browser') mw.resize(400, 400) #mw.setSelectionMode(QTreeWidget.Extended) root = Directory(mw) #, '/huaicai') root.setOpen(1) mw.show() a.exec_() else: roots = QDir("/download") fiList = roots.entryInfoList() for drv in fiList: print "The file path is: ", str(drv.absFilePath()) a.exec_() # end