def getDataDir(): # Temporary fix for non-ascii usernames # If username has non-ascii characters, just store userdata # in the Pesterchum install directory (like before) # TODO: fix error if standardLocations is not what we expect try: if isOSX(): return os.path.join(str(QStandardPaths.standardLocations(QStandardPaths.DataLocation)[0]), "Pesterchum/") elif isLinux(): return os.path.join(str(QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0]), ".pesterchum/") else: return os.path.join(str(QStandardPaths.standardLocations(QStandardPaths.DataLocation)[0]), "pesterchum/") except UnicodeDecodeError: return ''
def test__app_local_data(self): if qt_version < (5, 4, 1): raise SkipTest paths = get_standard_paths(Location.app_local_data) path_strs = [] for path in paths: assert_is_instance(path, pathlib.Path) path_strs.append(path.as_posix()) qt_path_strs = QStandardPaths.standardLocations( QStandardPaths.AppLocalDataLocation, ) if platform.system() == 'Darwin': # Exclude bundle path on OS X. See comments in # `get_standard_paths` implementation for more information. if qt_path_strs[-1].rstrip('/').endswith('Python.app'): qt_path_strs = qt_path_strs[:-1] elif platform.system() == 'Windows': # Exclude paths relative to executable. See comments in # `get_standard_paths` implementation for more information. python_loc = (pathlib.Path(sys.executable) / '..').resolve() qt_path_strs = [ ps for ps in qt_path_strs if ps not in ( python_loc.as_posix(), (python_loc / 'data').as_posix(), ) ] eq_(path_strs, qt_path_strs)
def load_settings(cls, client_id: int, client_secret: str): """Carga las configuraciones y preferencias de la aplicación. Además incializa los archivos settings.ini y files_info.ini si no han sido creados. Este método debe ser llamado al menos una vez en el uso de la aplicación. Se recomienda que sea al principio. Args: client_id (int): ID del cliente en la API. client_secret (str): Secreto del cliente en la API. """ cls.client_id = client_id cls.client_secret = client_secret config_path = QStandardPaths.standardLocations( QStandardPaths.DataLocation)[0] cls.qsettings = QSettings("{}/settings.ini".format(config_path), QSettings.IniFormat) cls.qsettings_files = QSettings( "{}/files_info.ini".format(config_path), QSettings.IniFormat) #Se instancia un objeto Fernet con el secreto de la aplicación fernet = Fernet(cls.__secret) #Si el token está guardado se obtiene y se decodifica if cls.qsettings.value("tokens/access_token"): cls.access_token = cls.__get_setting( bytes.decode( fernet.decrypt( cls.qsettings.value("tokens/access_token")))) #Si el token está guardado se obtiene y se decodifica if cls.qsettings.value("tokens/refresh_token"): cls.refresh_token = cls.__get_setting( bytes.decode( fernet.decrypt( cls.qsettings.value("tokens/refresh_token")))) cls.access_token_expire = cls.qsettings.value( "tokens/access_token_expire") aux_file = cls.qsettings.value("paths/socios_file_path") if aux_file: cls.socios_file.update(aux_file) cls.socios_file["hash"] = cls.qsettings_files.value("socios/hash") cls.socios_file["last_sync"] = cls.qsettings_files.value( "socios/last_sync") aux_file = cls.qsettings.value("paths/prestamos_file_path") if aux_file: cls.prestamos_file.update(aux_file) cls.prestamos_file["hash"] = cls.qsettings_files.value( "prestamos/hash") cls.prestamos_file["last_sync"] = cls.qsettings_files.value( "prestamos/last_sync") cls.domain = cls.qsettings.value("urls/domain") cls.app_icon = QIcon(":res/icons/app_icon.ico") cls.sync_icon = QIcon(":res/icons/sync_icon.ico") cls.sync_error_icon = QIcon(":res/icons/sync_error_icon.ico") if cls.qsettings.value("misc/start_on_system"): cls.start_on_system = cls.qsettings.value("misc/start_on_system", type=bool) cls.set_start_on_system()
def __init__(self, filepath=None): QObject.__init__(self) QTimer.singleShot(0, self.__launchTimerTimedOut) self.prefs = Preferences() self.prefs.load() global APP_PREFS APP_PREFS = self.prefs locale = QLocale.system() dateFormat = self.prefs.dateFormat decimalSep = locale.decimalPoint() groupingSep = locale.groupSeparator() cachePath = QStandardPaths.standardLocations(QStandardPaths.CacheLocation)[0] DateEdit.DATE_FORMAT = dateFormat self.model = MoneyGuruModel( view=self, date_format=dateFormat, decimal_sep=decimalSep, grouping_sep=groupingSep, cache_path=cachePath ) self.mainWindow = MainWindow(app=self) self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self) self.aboutBox = AboutBox(self.mainWindow, self) self.initialFilePath = None if filepath and op.exists(filepath): self.initialFilePath = filepath elif self.prefs.recentDocuments: self.initialFilePath = self.prefs.recentDocuments[0] self.finishedLaunching.connect(self.applicationFinishedLaunching) QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
def open_scheme_on_new_window(self): """Open a new scheme. Return QDialog.Rejected if the user canceled the operation and QDialog.Accepted otherwise. """ document = self.current_document() if document.isModifiedStrict(): if self.ask_save_changes() == QDialog.Rejected: return QDialog.Rejected if self.last_scheme_dir is None: # Get user 'Documents' folder start_dir = QStandardPaths.standardLocations( QStandardPaths.DocumentsLocation)[0] else: start_dir = self.last_scheme_dir # TODO: Use a dialog instance and use 'addSidebarUrls' to # set one or more extra sidebar locations where Schemes are stored. # Also use setHistory filename = QFileDialog.getOpenFileName( self, self.tr("Open Orange Workflow File"), start_dir, self.tr("Orange Workflow (*.ows)"), )[0] if filename: return self.load_scheme_on_window(filename, self.instantiate_window()) else: return QDialog.Rejected
def logDir(self): dirPath = os.path.join( QStandardPaths.standardLocations(QStandardPaths.TempLocation)[0], appName) shutil.rmtree(dirPath, ignore_errors=True) os.makedirs(dirPath, exist_ok=True) return dirPath
def exportFile(self): fileFormats = [ (self.tr("PostScript OT font {}").format("(*.otf)")), (self.tr("TrueType OT font {}").format("(*.ttf)")), ] state = settings.exportFileDialogState() # TODO: font.path as default? # TODO: store per-font export path in lib directory = None if state else QStandardPaths.standardLocations( QStandardPaths.DocumentsLocation)[0] dialog = QFileDialog( self, self.tr("Export File"), directory, ";;".join(fileFormats)) if state: dialog.restoreState(state) dialog.setAcceptMode(QFileDialog.AcceptSave) ok = dialog.exec_() settings.setExportFileDialogState(dialog.saveState()) if ok: fmt = "ttf" if dialog.selectedNameFilter( ) == fileFormats[1] else "otf" path = dialog.selectedFiles()[0] try: self._font.export(path, fmt) except Exception as e: errorReports.showCriticalException(e)
def defaultDir(): dirs = QStandardPaths.standardLocations( QStandardPaths.DownloadLocation) if dirs: return dirs[0] else: return ''
def saveFileAs(self): fileFormats = OrderedDict([ (self.tr("UFO Font version 3 {}").format("(*.ufo)"), 3), (self.tr("UFO Font version 2 {}").format("(*.ufo)"), 2), ]) state = settings.saveFileDialogState() path = self._font.path or self._font.binaryPath if path: directory = os.path.dirname(path) else: directory = None if state else QStandardPaths.standardLocations( QStandardPaths.DocumentsLocation)[0] # TODO: switch to directory dlg on platforms that need it dialog = QFileDialog( self, self.tr("Save File"), directory, ";;".join(fileFormats.keys())) if state: dialog.restoreState(state) dialog.setAcceptMode(QFileDialog.AcceptSave) if directory: dialog.setDirectory(directory) ok = dialog.exec_() settings.setSaveFileDialogState(dialog.saveState()) if ok: nameFilter = dialog.selectedNameFilter() path = dialog.selectedFiles()[0] if not os.path.basename(path).endswith(".ufo"): path += ".ufo" self.saveFile(path, fileFormats[nameFilter]) app = QApplication.instance() app.setCurrentFile(self._font.path) self.setWindowTitle(self.fontTitle())
def saveFileAs(self): fileFormats = OrderedDict([ (self.tr("UFO Font version 3 {}").format("(*.ufo)"), 3), (self.tr("UFO Font version 2 {}").format("(*.ufo)"), 2), ]) state = settings.saveFileDialogState() path = self._font.path or self._font.binaryPath if path: directory = os.path.dirname(path) else: directory = None if state else QStandardPaths.standardLocations( QStandardPaths.DocumentsLocation)[0] # TODO: switch to directory dlg on platforms that need it dialog = QFileDialog( self, self.tr("Save File"), directory, ";;".join(fileFormats.keys())) if state: dialog.restoreState(state) dialog.setAcceptMode(QFileDialog.AcceptSave) if directory: dialog.setDirectory(directory) ok = dialog.exec_() settings.setSaveFileDialogState(dialog.saveState()) if ok: nameFilter = dialog.selectedNameFilter() path = dialog.selectedFiles()[0] self.saveFile(path, fileFormats[nameFilter]) self.setWindowTitle(self.fontTitle())
def _test_against_qt(self, location, qt_location): paths = get_standard_paths(location) path_strs = [] for path in paths: assert_is_instance(path, pathlib.Path) path_strs.append(path.as_posix()) eq_(path_strs, QStandardPaths.standardLocations(qt_location))
def main(): """ Main loop to run test """ home_dir = QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0] print('home_dir:', home_dir) stdPwlDict = home_dir + QDir.separator() + "my-dict.txt" print('stdPwlDict:', stdPwlDict)
def get(name): """ Retrieve setting and convert result """ home_dir = QStandardPaths.standardLocations(QStandardPaths.HomeLocation)[0] stdPwlDict = home_dir + QDir.separator() + "my-dict.txt" settings = QSettings("Davide Setti", "Lector") if name == 'scanner:height': return int(settings.value(name, 297)) elif name == 'scanner:width': return int(settings.value(name, 210)) elif name == 'scanner:resolution': return int(settings.value(name, 300)) elif name == 'scanner:mode': return str(settings.value(name, "Color")) elif name == 'scanner:device': return str(settings.value(name, "")) elif name == 'editor:font': return settings.value(name, QFont(QFont("Courier New", 10))) elif name == 'editor:symbols': return settings.value(name) elif name in ('editor:clear', 'editor:spell', 'editor:whiteSpace', 'spellchecker:pwlLang',): return str(settings.value(name, "true")).lower() == "true" elif name in ('log:errors'): return str(settings.value(name, "false")).lower() == "true" elif name == 'spellchecker:pwlDict': return str(settings.value(name, stdPwlDict)) else: return str(settings.value(name, ""))
def __init__(self, filepath=None): ApplicationBase.__init__(self) self.prefs = Preferences() self.prefs.load() global APP_PREFS APP_PREFS = self.prefs locale = QLocale.system() dateFormat = self.prefs.dateFormat decimalSep = locale.decimalPoint() groupingSep = locale.groupSeparator() cachePath = QStandardPaths.standardLocations(QStandardPaths.CacheLocation)[0] appdata = getAppData() DateEdit.DATE_FORMAT = dateFormat self.model = MoneyGuruModel( view=self, date_format=dateFormat, decimal_sep=decimalSep, grouping_sep=groupingSep, cache_path=cachePath, appdata_path=appdata, ) # on the Qt side, we're single document based, so it's one doc per app. self.doc = Document(app=self) self.doc.model.connect() self.mainWindow = MainWindow(doc=self.doc) self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self) self.aboutBox = AboutBox(self.mainWindow, self) self.initialFilePath = None if filepath and op.exists(filepath): self.initialFilePath = filepath elif self.prefs.recentDocuments: self.initialFilePath = self.prefs.recentDocuments[0] self.finishedLaunching.connect(self.applicationFinishedLaunching) QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
def createDesktopShortcut(self): """ Create a desktop shortcut to start the GUI """ import os from win32com.client import Dispatch import sys desktop_locations = QStandardPaths.standardLocations(QStandardPaths.DesktopLocation) path = os.path.join(desktop_locations[0], "FMPy GUI.lnk") python = sys.executable root, ext = os.path.splitext(python) pythonw = root + 'w' + ext if os.path.isfile(pythonw): target = pythonw else: target = python file_path = os.path.dirname(__file__) icon = os.path.join(file_path, 'icons', 'app_icon.ico') shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(path) shortcut.Targetpath = target shortcut.Arguments = '-m fmpy.gui' # shortcut.WorkingDirectory = ... shortcut.IconLocation = icon shortcut.save()
def validate(config_file): """ Check the pb_tool.cfg file for mandatory sections/files """ valid = True cfg = get_config(config_file) if not check_cfg(cfg, 'plugin', 'name'): valid = False if not check_cfg(cfg, 'files', 'python_files'): valid = False if not check_cfg(cfg, 'files', 'main_dialog'): valid = False if not check_cfg(cfg, 'files', 'resource_files'): valid = False if not check_cfg(cfg, 'files', 'extras'): valid = False if not check_cfg(cfg, 'help', 'dir'): valid = False if not check_cfg(cfg, 'help', 'target'): valid = False click.secho("Using Python {}".format(sys.version), fg='green') if valid: click.secho( "Your {0} file is valid and contains all mandatory items".format( config_file), fg='green') else: click.secho("Your {0} file is invalid".format(config_file), fg='red') try: from PyQt5.QtCore import QStandardPaths, QDir path = QStandardPaths.standardLocations( QStandardPaths.AppDataLocation)[0] plugin_path = os.path.join( QDir.homePath(), path, 'QGIS/QGIS3/profiles/default/python/plugins') click.secho("Plugin path: {}".format(plugin_path), fg='green') except: click.secho( """Unable to determine location of your QGIS Plugin directory. Make sure your QGIS environment is setup properly for development and Python has access to the PyQt4.QtCore module.""", fg='red') zipbin = find_zip() a7z = find_7z() if zipbin: zip_utility = zipbin elif a7z: zip_utility = a7z else: zip_utility = None if not zip_utility: click.secho('zip or 7z not found. Unable to package the plugin', fg='red') click.secho('Check your path or install a zip program', fg='red') else: click.secho('Found suitable zip utility: {}'.format(zip_utility), fg='green')
def new_pressed(self): start_dir = QStandardPaths.standardLocations( QStandardPaths.HomeLocation)[-1] file_dialog = QFileDialog(self) file_dialog.setDirectory(start_dir) if file_dialog.exec_(): # TODO: Implement File-adding logic using storage module self.add_button.setEnabled(True)
def open(self): if self.maybeSave(): documents = QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation)[0] fileName, _ = QFileDialog.getOpenFileName(self, "open File", documents, "Text Files (*.txt *.csv *.sh *.py) ;; all Files (*.*)") if fileName: self.loadFile(fileName) else: self.statusBar().showMessage("cancelled", 3000)
def _getCacheDir(self): local_data_dir = QStandardPaths.standardLocations(QStandardPaths.CacheLocation) path = os.path.abspath(local_data_dir[0]) try: # Apparently the cache location might not exist os.makedirs(path) except: pass return path
def getDataDirectory(): try: data_dir = QStandardPaths.standardLocations(QStandardPaths.AppLocalDataLocation)[0] if not os.path.exists(data_dir): os.makedirs(data_dir) return data_dir except Exception as e: config.logger.error("util: Exception in getDataDirectory() %s",e) return None
def chooselogfile(self): #选择单个待测Baseline的excel文件。如果使用的是QFileDialog.getOpenFileNames则可以同时选择多个文件 choosefilename, _ = QFileDialog.getOpenFileName( self, "选取log文件", QStandardPaths.standardLocations(0)[0], "Text Files (*.txt *.log);;All Files (*)") # print(choosefilename) if choosefilename: self.lineEdit_logpath.setText(choosefilename)
def _special_folder_path(special_folder, appname=None, portable=False): if special_folder == SpecialFolder.CACHE: if ISWINDOWS and portable: folder = op.join(executable_folder(), "cache") else: folder = QStandardPaths.standardLocations( QStandardPaths.CacheLocation)[0] else: folder = get_appdata(portable) return folder
def getConfigLocation(): configLocation = QStandardPaths.GenericConfigLocation root = QStandardPaths.standardLocations(configLocation)[0] if sys.platform in ('win32', 'darwin'): path = os.path.join(root, 'Crispy') else: path = os.path.join(root, 'crispy') return path
def main(): import sys app = QApplication(sys.argv) QQuickWindow.setDefaultAlphaBuffer(True) QCoreApplication.setApplicationName("Photosurface") QCoreApplication.setOrganizationName("QtProject") QCoreApplication.setApplicationVersion(QT_VERSION_STR) parser = QCommandLineParser() parser.setApplicationDescription("Qt Quick Demo - Photo Surface") parser.addHelpOption() parser.addVersionOption() parser.addPositionalArgument("directory", "The image directory or URL to show.") parser.process(app) initialUrl = QUrl() if parser.positionalArguments(): initialUrl = QUrl.fromUserInput(parser.positionalArguments()[0], QDir.currentPath(), QUrl.AssumeLocalFile) if not initialUrl.isValid(): print( 'Invalid argument: "', parser.positionalArguments()[0], '": ', initialUrl.errorString(), ) sys.exit(1) nameFilters = imageNameFilters() engine = QQmlApplicationEngine() context: QQmlContext = engine.rootContext() picturesLocationUrl = QUrl.fromLocalFile(QDir.homePath()) picturesLocations = QStandardPaths.standardLocations( QStandardPaths.PicturesLocation) if picturesLocations: picturesLocationUrl = QUrl.fromLocalFile(picturesLocations[0]) if not initialUrl and QDir(picturesLocations[0]).entryInfoList( nameFilters, QDir.Files): initialUrl = picturesLocationUrl context.setContextProperty("contextPicturesLocation", picturesLocationUrl) context.setContextProperty("contextInitialUrl", initialUrl) context.setContextProperty("contextImageNameFilters", nameFilters) engine.load(QUrl("qrc:///photosurface.qml")) if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_())
def main(): """Test module functionality """ print('starting tests...') home_dir = QStandardPaths.standardLocations(QStandardPaths.HomeLocation) print('Home dir is:', home_dir) print('configFile:', configFile()) print('Input durectory is: ', readSetting('images/input_dir')) print('Last used filename is: ', readSetting('images/last_filename')) print('language:', readSetting('language'), type(readSetting('language'))) print('tests ended...')
def _choose_place_to_save_data(self, dataframe): paths = QStandardPaths.standardLocations(0) if len(paths) > 0: path = paths[0] else: path = "" filename = QFileDialog.getSaveFileName( self, Messages.save_weatherdata_csv(), path + "/weather_data.csv", "Comma separated values CSV (*.csv);;All files (*)") if filename[0] != "": self._save_to_csv(dataframe, filename[0])
def get_fonts() -> list: """ Returns a list of tuples (font, path) of all fonts installed on the system. """ paths = [] for path in QStandardPaths.standardLocations(QStandardPaths.FontsLocation): if os.path.isdir(path): paths.append(path) if platform.system() == "Linux": unix_paths = QStandardPaths.standardLocations( QStandardPaths.AppDataLocation) for path in unix_paths: possible_path = os.path.dirname(path) + os.sep + "fonts" if os.path.isdir(possible_path): paths.append(possible_path) fonts = dict() for i, path in enumerate(paths): for dir_path, dir_names, file_names in os.walk(path): for filename in file_names: if filename.endswith(".ttf"): try: absolute_file_path = dir_path + os.sep + filename ttf = TTFontFile() ttf.getMetrics(absolute_file_path) font_name = ttf.fullName.replace("-", " ") font_name = " ".join( re.findall(r"[A-Z]?[^A-Z\s]+|[A-Z]+", font_name)) if font_name not in fonts: fonts[font_name] = absolute_file_path except RuntimeError: pass fonts = sorted(fonts.items()) return fonts
def brosebaselinedir(self): # fileName, path = QFileDialog.getOpenFileName(self, "Open File",QCoreApplication.applicationDirPath()) # print(QStandardPaths.standardLocations(0)) # print(QStandardPaths.standardLocations(0)[0]) #选择单个待测Baseline的excel文件。如果使用的是QFileDialog.getOpenFileNames则可以同时选择多个文件 choosefilename, _ = QFileDialog.getOpenFileName(self, "选取文件",QStandardPaths.standardLocations(0)[0], "Excel Files (*.xlsx *.xls);;All Files (*)") # print(choosefilename) if choosefilename: self.lineEdit_register_base_line_dir.setText(choosefilename) self.gen_filename=self.lineEdit_register_base_line_dir.text()
def removeOldFiles(self): configLocation = QStandardPaths.GenericConfigLocation root = QStandardPaths.standardLocations(configLocation)[0] path = os.path.join(root, self.name) if version < '0.7.0': try: os.remove(os.path.join(path, 'settings.json')) os.rmdir(path) except (IOError, OSError) as e: pass
def createQSettings(): # Create a QSettings instance with the correct arguments. # On windows use an ini file in the AppDataLocation instead of registry if possible as it # makes it easier for a user to clear it out when there are issues. if ISWINDOWS: Locations = QStandardPaths.standardLocations(QStandardPaths.AppDataLocation) if Locations: return QSettings(op.join(Locations[0], "settings.ini"), QSettings.IniFormat) else: return QSettings() else: return QSettings()
def display(self): dialog = QFileDialog( parent=self.__parentWidget, caption=self.__tr("Select location to save debugging information"), directory=QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation)[0], filter="ZIP files (*.zip)", ) dialog.selectFile(time.strftime("MO2_Debug_Info_%Y%m%d_%H%M%S.zip")) if(dialog.exec()): with ZipFile(dialog.selectedFiles()[0], 'w', ZIP_LZMA) as file_zip: self.getProcesses(file_zip) self.getServices(file_zip)
def saveAs(self): if not self.myeditor.toPlainText() == "": if self.curFile: fileName, _ = QFileDialog.getSaveFileName(self, "Save as...", self.curFile, "Text Files (*.txt)") else: documents = QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation)[0] fileName, _ = QFileDialog.getSaveFileName(self, "Save as...", documents + "/newDocument.txt", "Text Files (*.txt)" ) if fileName: return self.saveFile(fileName) return False else: self.statusBar().showMessage("no Text")
def show_box_file(self, text, f_name): r = QMessageBox.question(window, "File sending", text, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if r == QMessageBox.Yes: self.path_file = QFileDialog.getSaveFileName( self, "Open Image", QStandardPaths.standardLocations( QStandardPaths.HomeLocation)[0] + "/" + f_name, "All Files (*.*)") else: self.path_file = ("", "")
def loadPlugins(self): pluginpath = os.path.dirname(Flux.Plugins.__file__) if hasattr(sys, "frozen"): pluginpath = "lib/python3.8/flux/Plugins" pluginpath2 = os.path.join(QStandardPaths.standardLocations(QStandardPaths.AppDataLocation)[0], "Plugins") plugin_loaders = pkgutil.iter_modules([pluginpath, pluginpath2]) self.plugins = {} for loader, module_name, is_pkg in plugin_loaders: if is_pkg: continue _module = loader.find_module(module_name).load_module(module_name) _module.module_name = module_name self.plugins[module_name] = _module
def getDataDir(): # Temporary fix for non-ascii usernames # If username has non-ascii characters, just store userdata # in the Pesterchum install directory (like before) # TODO: fix error if standardLocations is not what we expect try: if isOSX(): return os.path.join( str( QStandardPaths.standardLocations( QStandardPaths.DataLocation)[0]), "Pesterchum/") elif isLinux(): return os.path.join( str( QStandardPaths.standardLocations( QStandardPaths.HomeLocation)[0]), ".pesterchum/") else: return os.path.join( str( QStandardPaths.standardLocations( QStandardPaths.DataLocation)[0]), "pesterchum/") except UnicodeDecodeError: return ''
def removeOldFiles(self): """Function that removes the settings from previous versions.""" root = QStandardPaths.standardLocations( QStandardPaths.GenericConfigLocation)[0] path = os.path.join(root, self.name) if version < "0.7.0": try: os.remove(os.path.join(path, "settings.json")) os.rmdir(path) logger.debug("Removed old configuration file.") except (IOError, OSError): pass
def storeQGISui(self,force =False): try: # store current QGIS ui # layout qgisAppDataPath = QStandardPaths.standardLocations(QStandardPaths.AppDataLocation)[0] file = os.path.join(qgisAppDataPath, 'qgis_ui.bin') if not os.path.isfile(file) or force: if self.debug: self.info.log("storeQGISui:", self.helper.shortDisplayText(file)) f = QSaveFile(file) f.open(QIODevice.WriteOnly) f.write(self.iface.mainWindow().saveState()) f.commit() except Exception as e: self.info.err(e)
def cache_dir(): """Return the application cache directory. If the directory path does not yet exists then create it. """ init() cachedir = QStandardPaths.standardLocations( QStandardPaths.CacheLocation)[0] cachedir = six.text_type(cachedir) version = six.text_type(QCoreApplication.applicationVersion()) cachedir = os.path.join(cachedir, version) if not os.path.exists(cachedir): os.makedirs(cachedir) return cachedir
def getScriptsDirectory(self): userPath = QSettings().value("scripting/path") if userPath and os.path.exists(userPath): return userPath appDataFolder = QStandardPaths.standardLocations(QStandardPaths.AppLocalDataLocation)[0] scriptsFolder = os.path.normpath(os.path.join(appDataFolder, "Scripts")) if not os.path.exists(scriptsFolder): try: os.makedirs(scriptsFolder) except OSError: return os.path.expanduser("~") return scriptsFolder
def data_dir(): """Return the application data directory. If the directory path does not yet exists then create it. """ init() # return default.data_dir() datadir = QStandardPaths.standardLocations(QStandardPaths.DataLocation)[0] datadir = six.text_type(datadir) version = six.text_type(QCoreApplication.applicationVersion()) datadir = os.path.join(datadir, version) if not os.path.exists(datadir): os.makedirs(datadir) return datadir
def __init__(self): QObject.__init__(self) self.reset() # On windows use an ini file in the AppDataLocation instead of registry if possible as it # makes it easier for a user to clear it out when there are issues. if ISWINDOWS: Locations = QStandardPaths.standardLocations( QStandardPaths.AppDataLocation) if Locations: self._settings = QSettings( op.join(Locations[0], "settings.ini"), QSettings.IniFormat) else: self._settings = QSettings() else: self._settings = QSettings()
def initializeDataDirs(): assert not datadirs if '__file__' in locals(): datadirs.append(dirname(dirname(__file__))) dataLocations = QStandardPaths.standardLocations(QStandardPaths.GenericDataLocation) datadirs.extend(join(d, 'retext') for d in dataLocations) if sys.platform == "win32": # Windows compatibility: Add "PythonXXX\share\" path datadirs.append(join(dirname(sys.executable), 'share', 'retext')) # For virtualenvs datadirs.append(join(dirname(dirname(sys.executable)), 'share', 'retext'))
def _getLocalDirectory(self, key, name): userPath = settings.value(key, type=str) if userPath and os.path.isdir(userPath): return userPath appDataFolder = QStandardPaths.standardLocations(QStandardPaths.AppLocalDataLocation)[0] subFolder = os.path.normpath(os.path.join(appDataFolder, name)) if not os.path.exists(subFolder): try: os.makedirs(subFolder) except OSError: subFolder = os.path.expanduser("~") settings.setValue(key, subFolder) return subFolder
def exportToPDF(self, path=None): if path is None: desktop = QStandardPaths.standardLocations( QStandardPaths.DesktopLocation) path = os.path.join(desktop[0], "metricsWindow.pdf") printer = QPrinter() # printer.setFullPage(True) printer.setOutputFileName(path) printer.setOutputFormat(QPrinter.PdfFormat) painter = QPainter() painter.begin(printer) painter.setRenderHint(QPainter.Antialiasing) if self._rightToLeft: self.paintRightToLeft(painter, self.geometry()) else: self.paintLeftToRight(painter, self.geometry()) painter.end()
def test__generic_config(self): paths = get_standard_paths(Location.generic_config) path_strs = [] for path in paths: assert_is_instance(path, pathlib.Path) path_strs.append(path.as_posix()) qt_path_strs = QStandardPaths.standardLocations( QStandardPaths.GenericConfigLocation, ) if platform.system() == 'Windows': # Exclude paths relative to executable. See comments in # `get_standard_paths` implementation for more information. python_loc = (pathlib.Path(sys.executable) / '..').resolve() qt_path_strs = [ ps for ps in qt_path_strs if ps not in ( python_loc.as_posix(), (python_loc / 'data').as_posix(), ) ] eq_(path_strs, qt_path_strs)
def readSetting(name): """Return stored setting value """ settings = QSettings(configFile(), QSettings.IniFormat) # ByteArray if name in ('geometry', 'state', 'splitter_1Sizes', 'splitter_2Sizes'): return settings.value(name) elif name == 'images/input_dir': return str(settings.value(name, QStandardPaths.standardLocations( QStandardPaths.DesktopLocation))) elif name == 'images/last_filename': return str(settings.value(name, r'images/phototest.tif')) elif name == 'images/zoom_factor': return float(settings.value(name, QVariant(1.0))) elif name == 'language': # default value 'eng' return str(settings.value(name, 'eng')) else: # Return name value as string or empty string if name does not exist return str(settings.value(name, ""))
settings.setValue(key, value) elif len(value) == 1: settings.setValue(key, value[0]) else: settings.remove(key) class ReTextSettings(object): def __init__(self): for option in configOptions: value = configOptions[option] object.__setattr__(self, option, readFromSettings( option, type(value), default=value)) def __setattr__(self, option, value): if not option in configOptions: raise AttributeError('Unknown attribute') object.__setattr__(self, option, value) writeToSettings(option, value, configOptions[option]) globalSettings = ReTextSettings() markups.common.PYGMENTS_STYLE = globalSettings.pygmentsStyle monofont = QFont() monofont.setFamily(globalSettings.editorFont) if globalSettings.editorFontSize: monofont.setPointSize(globalSettings.editorFontSize) datadirs = QStandardPaths.standardLocations(QStandardPaths.GenericDataLocation) datadirs = [abspath('.')] + [join(d, 'retext') for d in datadirs]
import os import sys from PyQt5.QtCore import QStandardPaths from OpenNumismat import version # Getting default path for storing user data HOME_PATH = '' if sys.platform in ('win32', 'darwin'): __location = QStandardPaths.DocumentsLocation else: __location = QStandardPaths.HomeLocation __docDirs = QStandardPaths.standardLocations(__location) if __docDirs: HOME_PATH = os.path.join(__docDirs[0], version.AppName) if not os.path.exists(HOME_PATH): HOME_PATH = __docDirs[0] __imgDirs = QStandardPaths.standardLocations(QStandardPaths.PicturesLocation) if __imgDirs: IMAGE_PATH = __imgDirs[0] else: IMAGE_PATH = HOME_PATH # Getting path where stored application data (icons, templates, etc) PRJ_PATH = os.path.abspath(os.path.dirname(__file__)) # sys.frozen is True when running from cx_Freeze executable if getattr(sys, 'frozen', False):
def _special_folder_path(special_folder, appname=None): if special_folder == SpecialFolder.Cache: qtfolder = QStandardPaths.CacheLocation else: qtfolder = QStandardPaths.DataLocation return QStandardPaths.standardLocations(qtfolder)[0]
def defaultDir(): dirs = QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation) if dirs: return dirs[0] else: return ''
def photosDir(self): return QStandardPaths.standardLocations(QStandardPaths.PicturesLocation)[0]
def _openFile(self, path=None, openFile=True, importFile=False): if not path: # formats fileFormats = [] supportedFiles = "" if openFile: packageAsFile = platformSpecific.treatPackageAsFile() if packageAsFile: ufoFormat = "*.ufo" tfExtFormat = "*.tfExt" else: ufoFormat = "metainfo.plist" tfExtFormat = "info.plist" fileFormats.extend([ self.tr("UFO Fonts {}").format("(%s)" % ufoFormat), self.tr("TruFont Extension {}").format( "(%s)" % tfExtFormat) ]) supportedFiles += "{} {} ".format(ufoFormat, tfExtFormat) if importFile: # TODO: systematize this fileFormats.extend([ self.tr("OpenType Font file {}").format("(*.otf *.ttf)"), self.tr("Type1 Font file {}").format("(*.pfa *.pfb)"), self.tr("ttx Font file {}").format("(*.ttx)"), self.tr("WOFF Font file {}").format("(*.woff)"), ]) supportedFiles += "*.otf *.pfa *.pfb *.ttf *.ttx *.woff" fileFormats.extend([ self.tr("All supported files {}").format( "(%s)" % supportedFiles.rstrip()), self.tr("All files {}").format("(*.*)"), ]) # dialog importKey = importFile and not openFile state = settings.openFileDialogState( ) if not importKey else settings.importFileDialogState() directory = None if state else QStandardPaths.standardLocations( QStandardPaths.DocumentsLocation)[0] title = self.tr( "Open File") if openFile else self.tr("Import File") dialog = QFileDialog( self.activeWindow(), title, directory, ";;".join(fileFormats)) if state: dialog.restoreState(state) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setFileMode(QFileDialog.ExistingFile) dialog.setNameFilter(fileFormats[-2]) ret = dialog.exec_() # save current directory # TODO: should open w/o file chooser also update current dir? state = dialog.saveState() if importKey: settings.setImportFileDialogState(directory) else: settings.setOpenFileDialogState(directory) # cancelled? if not ret: return path = dialog.selectedFiles()[0] # sanitize path = os.path.normpath(path) if ".plist" in path: path = os.path.dirname(path) ext = os.path.splitext(path)[1] if ext == ".ufo": self._loadUFO(path) elif ext == ".tfExt": self._loadExt(path) else: self._loadBinary(path)
import os import sys from PyQt5.QtCore import QStandardPaths from OpenNumismat import version # Getting default path for storing user data HOME_PATH = '' if sys.platform in ['win32', 'darwin']: __docDirs = QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation) if __docDirs: HOME_PATH = os.path.join(__docDirs[0], version.AppName) else: __homeDirs = QStandardPaths.standardLocations(QStandardPaths.HomeLocation) if __homeDirs: HOME_PATH = os.path.join(__homeDirs[0], version.AppName) __imgDirs = QStandardPaths.standardLocations(QStandardPaths.PicturesLocation) if __imgDirs: IMAGE_PATH = __imgDirs[0] else: IMAGE_PATH = HOME_PATH # Getting path where stored application data (icons, templates, etc) PRJ_PATH = os.path.abspath(os.path.dirname(__file__)) # sys.frozen is True when running from cx_Freeze executable if getattr(sys, 'frozen', False): PRJ_PATH = os.path.dirname(sys.executable)
def getAppData(): return QStandardPaths.standardLocations(QStandardPaths.DataLocation)[0]
def moviesDir(self): return QStandardPaths.standardLocations(QStandardPaths.MoviesLocation)[0]
def musicDir(self): return QStandardPaths.standardLocations(QStandardPaths.MusicLocation)[0]
{'action': 'add'}, {'action': 'add'}, {'action': 'add'}, ] SKIPPED_FIELDS = ('edgeimg', 'photo1', 'photo2', 'photo3', 'photo4', 'obversedesigner', 'reversedesigner', 'catalognum2', 'catalognum3', 'catalognum4', 'saledate', 'saleprice', 'totalsaleprice', 'buyer', 'saleplace', 'saleinfo', 'paydate', 'payprice', 'totalpayprice', 'saller', 'payplace', 'payinfo', 'url', 'obversedesigner', 'reversedesigner', 'barcode', 'quantity', 'features', 'storage', 'defect', 'note', 'status', 'createdat') app = QApplication(sys.argv) HOME_PATH = '' __docDirs = QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation) if __docDirs: HOME_PATH = os.path.join(__docDirs[0], "OpenNumismat") # Getting path where stored application data (icons, templates, etc) PRJ_PATH = os.path.abspath(os.path.join( os.path.dirname(__file__), "..", "OpenNumismat")) json_file_name, _selectedFilter = QFileDialog.getOpenFileName(None, "Open collection", HOME_PATH, "Collections (*.json)") if json_file_name: image_path = json_file_name.replace('.json', '_images') json_file = codecs.open(json_file_name, "r", "utf-8") data = json.load(json_file) is_obverse_enabled = False
def __getFileName(self): """ Private method to get the file name to save to from the user. """ if self.__gettingFileName: return import Helpviewer.HelpWindow downloadDirectory = Helpviewer.HelpWindow.HelpWindow\ .downloadManager().downloadDirectory() if self.__fileName: fileName = self.__fileName originalFileName = self.__originalFileName self.__toDownload = True ask = False else: defaultFileName, originalFileName = \ self.__saveFileName(downloadDirectory) fileName = defaultFileName self.__originalFileName = originalFileName ask = True self.__autoOpen = False if not self.__toDownload: from .DownloadAskActionDialog import DownloadAskActionDialog url = self.__reply.url() dlg = DownloadAskActionDialog( QFileInfo(originalFileName).fileName(), self.__reply.header(QNetworkRequest.ContentTypeHeader), "{0}://{1}".format(url.scheme(), url.authority()), self) if dlg.exec_() == QDialog.Rejected or dlg.getAction() == "cancel": self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return if dlg.getAction() == "scan": self.__mainWindow.requestVirusTotalScan(url) self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("VirusTotal scan scheduled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return self.__autoOpen = dlg.getAction() == "open" if PYQT_VERSION_STR >= "5.0.0": from PyQt5.QtCore import QStandardPaths tempLocation = QStandardPaths.standardLocations( QStandardPaths.TempLocation)[0] else: from PyQt5.QtGui import QDesktopServices tempLocation = QDesktopServices.storageLocation( QDesktopServices.TempLocation) fileName = tempLocation + '/' + \ QFileInfo(fileName).completeBaseName() if ask and not self.__autoOpen and self.__requestFilename: self.__gettingFileName = True fileName = E5FileDialog.getSaveFileName( None, self.tr("Save File"), defaultFileName, "") self.__gettingFileName = False if not fileName: self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}") .format(QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return fileInfo = QFileInfo(fileName) Helpviewer.HelpWindow.HelpWindow.downloadManager()\ .setDownloadDirectory(fileInfo.absoluteDir().absolutePath()) self.filenameLabel.setText(fileInfo.fileName()) self.__output.setFileName(fileName + ".part") self.__fileName = fileName # check file path for saving saveDirPath = QFileInfo(self.__fileName).dir() if not saveDirPath.exists(): if not saveDirPath.mkpath(saveDirPath.absolutePath()): self.progressBar.setVisible(False) self.on_stopButton_clicked() self.infoLabel.setText(self.tr( "Download directory ({0}) couldn't be created.") .format(saveDirPath.absolutePath())) return self.filenameLabel.setText(QFileInfo(self.__fileName).fileName()) if self.__requestFilename: self.__readyRead()