def __init__(self): folder = QStandardPaths.writableLocation( QStandardPaths.AppDataLocation) folder += "/" + Settings._filepath if not os.path.exists(folder): os.makedirs(folder) filepath = folder + "/" + Settings._filename if not os.path.exists(filepath): config = configparser.ConfigParser() config["Constants"] = { "styleSheetPath": "./ui/stylesheet.qss", "tailerRefreshTimeMs": "500", "spoolPath": "C:\\Users\\nicola\\Desktop\\Spool" } config["Configuration"] = { "styleButtonVisible": "0", "maxLogRowCount": "10" } config["Logging"] = { "path": QStandardPaths.writableLocation( QStandardPaths.AppLocalDataLocation) + "/DV/CSV2JSON/logs/", "filename": "CSV2JSON.txt", "levels": "CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET", "currentLevel": "DEBUG" } config["JsonConfiguration"] = {"StripWidthUm": "100000"} with open(filepath, 'w') as fp: config.write(fp) config = configparser.ConfigParser() config.read(filepath) self.styleSheetPath = config["Constants"]["styleSheetPath"] self.tailerRefreshTimeMs = config["Constants"]["tailerRefreshTimeMs"] self.styleButtonVisible = config["Configuration"]["styleButtonVisible"] self.maxLogRowCount = config["Configuration"]["maxLogRowCount"] self.spoolPath = config["Constants"]["spoolPath"] self.loggingPath = config["Logging"]["path"] self.loggingFilename = config["Logging"]["filename"] self.loggingLevels = config["Logging"]["levels"] self.loggingCurrentLevel = config["Logging"]["currentLevel"] self.jsonConfigurationStripWidthUm = config["JsonConfiguration"][ "StripWidthUm"]
def setup_menus(self): file_menu = self.menuBar().addMenu("&File") exit_action = file_menu.addAction("E&xit") exit_action.setShortcut(QKeySequence("Ctrl+Q")) character_menu = self.menuBar().addMenu("&Character") import_action = character_menu.addAction("&Import from PDF") import_action.triggered.connect( lambda: self.pdf_wizard_factory.create(self)) import_action = character_menu.addAction("&Create new Character") import_action.triggered.connect(self.create_new_player) export_menu = self.menuBar().addMenu("&Export") export_debug_action = export_menu.addAction("Export Debug") export_debug_action.triggered.connect( lambda: self.export_pdf_wizard_factory.create(self)) resource_menu = self.menuBar().addMenu("&Resources") open_app_data = resource_menu.addAction("Open Appdata Folder") dir_to_open = QStandardPaths.writableLocation( QStandardPaths.AppDataLocation) open_app_data.triggered.connect( lambda: QDesktopServices.openUrl(dir_to_open)) exit_action.triggered.connect(QApplication.instance().quit) logger.debug("Menus set-up")
def saveData(self): if not self.docModified: return if self.docPath is None: path, ftype = QFileDialog.getSaveFileName( self, '保存食谱', QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation), 'Excel 文件(*.xlsx)') if path == '': return if QDir(path) == QDir(self._library_file): QMessageBox.critical(self, G_APPNAME, '%s 是库文件,不能用于保存食谱' % path) return else: path = self.docPath wb = openpyxl.Workbook() ws = wb.active for k, v in self.data.items(): cell = ws.cell(row=k[0] + 1, column=k[1] + 1) cell.value = "\n".join(v) try: wb.save(path) wb.close() except: QMessageBox.critical(self, G_APPNAME, '%s 保存失败' % path) return self.docPath = path self.setDocModified(False)
def draw_index(self): if not self.graph: logger.warning("No graph to draw found!") width = self.contentsRect().width() height = self.contentsRect().height() pagewidth = int(width) - 10 pageheight = int(height) - 10 logger.info(f"{width}x{height}") html = importlib.resources.read_text(__package__, "index.thtml", encoding="utf-8-sig") html = (html.replace( "$graph", "'" + json.dumps(networkx.node_link_data(self.graph)) + "'" if self.graph else """'{"directed":true,"multigraph":true,"graph":[],"nodes":[],"links":[]}'""", ).replace("$width", str(pagewidth)).replace("$height", str(pageheight))) path = pathlib.Path( QStandardPaths.writableLocation( QStandardPaths.AppLocalDataLocation)) / "index.html" logger.info(f"""Saving html to {path.absolute()}""") path.write_text(html) self.index.setHtml(html) self.index.settings().setAttribute(QWebEngineSettings.ShowScrollBars, False) self.webview.setPage(self.index) self.webview.resize(width, height) self.webview.show() self.update()
def __init__(self, parent=None): """ :param parent: """ super(SlippyMap, self).__init__(parent) self._offset = QPoint() self._tiles_rectangle = QRect() self._tile_pixmaps = {} # Point(x, y) to QPixmap mapping self._manager = QNetworkAccessManager() self._url = QUrl() # public vars self.width = 400 self.height = 300 self.zoom = 4 self.latitude = 59.9138204 self.longitude = 10.7387413 self._emptyTile = QPixmap(TDIM, TDIM) self._emptyTile.fill(Qt.lightGray) self.request = QNetworkRequest() self.cache = QNetworkDiskCache() self.cache.setCacheDirectory( QStandardPaths.writableLocation(QStandardPaths.CacheLocation)) self._manager.setCache(self.cache) self._manager.finished.connect(self.handle_network_data)
def export(self): # TODO exporter should tell me what file to use dir_to_search = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) dir_to_search = os.path.join(dir_to_search, "exporters") file_to_export_to = os.path.join( dir_to_search, "Character Sheet_WARLOCK_FILLABLE.pdf" ) pdf_file = PDFFile(file_to_export_to) form_fields = pdf_file.get_forms_names() convertable_form_fields = [ field_name for field_name in form_fields if field_name in self.plugin.key_conversion.keys() ] for field in convertable_form_fields: ch_candidate = self.plugin.key_conversion[field] if not ch_candidate: logger.info(f"Value {ch_candidate} is not a valid CH") continue ch = CHProperty(ch_candidate) ch_property = self.player_controller.player_model.get_ch_property(ch) value = ch_property.value pdf_file.set_field(field, value) # TODO maybe go to a model where we do not keep track of set fields and check it at another place (plugin?) # form_fields = [ # # form for form in form_fields if form not in convertable_form_fields # # ] # TODO skills # forms = self.export_skills(form_fields, self.skill_keys) self.plugin.export_character_incremental_lists(pdf_file, self.player_controller) pdf_file.save(self.pdf_target)
def ask_for_filename_to_load(parent): dir_to_open = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) fname = QFileDialog.getOpenFileName(parent, "Open PDF", dir_to_open, "PDF Files (*.pdf)") return fname
def __get_sqlite_name(self) -> str: """Create the name for the SqliteDB. Therefor combine the Qt Application Defs: QStandardPaths.DataLocation + QtCoreApplication.applicationName + .sqlite3 * *on Mac is this* `~/Library/Application Support/io.jmuelbert.github/jmbde/jmbde.sqlite3` * *on Linux this* `~/.local/share/<APPNAME>/jmbde.sqlite3` * *on Windows is this* `C:/Users/<USER>/AppData/Local/<APPNAME>/jmbde.sqlite3` Returns: The connection string fot the sqlite database. """ db_data_path = QStandardPaths.writableLocation( QStandardPaths.DataLocation) self.log.info("The Database: {}".format(db_data_path)) write_dir = QDir(db_data_path) if not write_dir.mkpath("."): self.log.error("Failed to create writable directory") if not write_dir.exists(): write_dir.mkpath(db_data_path) # Ensure that we have a writable location on all devices. filename = "{}/{}.sqlite3".format(write_dir.absolutePath(), QCoreApplication.applicationName()) return filename
def ask_for_filename_to_save(parent): dir_to_open = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) fname = QFileDialog().getSaveFileName(parent, "Save as PDF", dir_to_open, "PDF Files (*.pdf)") return fname
def _onActionOpenTriggered(self): fileNames = QFileDialog.getOpenFileNames(self, self.tr("Open Document"), QStandardPaths.writableLocation(QStandardPaths.HomeLocation), self.tr("CSV Files (*.csv);;All Files (*.*)"))[0] for fileName in fileNames: self._openDocument(fileName)
def config_directory() -> str: """Returns the configuration directory (This is the root dir for dial)""" config_directory = ( QStandardPaths.writableLocation(QStandardPaths.ConfigLocation) + os.path.sep + "dial") if not os.path.isdir(config_directory): os.mkdir(config_directory) return config_directory
def open(self): fileDialog = QFileDialog(self) supportedMimeTypes = ["video/mp4", "*.*"] fileDialog.setMimeTypeFilters(supportedMimeTypes) moviesLocation = QStandardPaths.writableLocation( QStandardPaths.MoviesLocation) fileDialog.setDirectory(moviesLocation) if fileDialog.exec_() == QDialog.Accepted: self.playlist.addMedia(fileDialog.selectedUrls()[0]) self.player.play()
def selectTemplate(self): startLocation = self.ui.hyperthoughtTemplateLineEdit.text() if startLocation == "": startLocation = QStandardPaths.writableLocation( QStandardPaths.HomeLocation) templateFilePath = QFileDialog.getOpenFileName( self, self.tr("Select File"), startLocation, self.tr("Files (*.ez)"))[0] self.loadTemplateFile(templateFilePath)
def __init__(self): super().__init__() self.settings = QSettings(self) qt_write_base = Path( QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation)) qt_write_base.mkdir(parents=True, exist_ok=True) self.icon_write_dir = qt_write_base / "app_icons" self.icon_write_dir.mkdir(exist_ok=True)
def nextImageFileName(self): picturesLocation = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation) dateString = QDate.currentDate().toString("yyyyMMdd") pattern = picturesLocation + "/pyside2_camera_" + dateString + "_{:03d}.jpg" n = 1 while True: result = pattern.format(n) if not os.path.exists(result): return result n = n + 1 return None
def nextImageFileName(self): picturesLocation = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation) dateString = QDate.currentDate().toString("yyyyMMdd") pattern = picturesLocation + "/pyside2_camera_" + dateString + "_{:03d}.jpg" n = 1 while True: result = pattern.format(n) if not os.path.exists(result): return result n = n + 1 return None
def open(self): fileDialog = QFileDialog(self) supportedMimeTypes = QMediaPlayer.supportedMimeTypes() if not supportedMimeTypes: supportedMimeTypes.append("video/x-msvideo") # AVI fileDialog.setMimeTypeFilters(supportedMimeTypes) moviesLocation = QStandardPaths.writableLocation(QStandardPaths.MoviesLocation) fileDialog.setDirectory(moviesLocation) if fileDialog.exec_() == QDialog.Accepted: self.playlist.addMedia(fileDialog.selectedUrls()[0]) self.player.play()
def start_simple_tts(self, content: str, ui_config: str): if content == '': self.failed.emit() return out_file = os.path.join( QStandardPaths.writableLocation(QStandardPaths.DownloadLocation), 'tts.wav') self._do_tts(True, self._get_ssml_config_template(ui_config).format(content), out_file) self.allReady.emit()
def go_desktop(self, checked=False): """Slot for the 'Desktop' button. Scrolls the treeview to show and select the user's desktop directory.""" desktop = QStandardPaths.writableLocation(QStandardPaths.DesktopLocation) # Return a list if not desktop: return self.ui.comboBox_current_path.setCurrentIndex(-1) desktop_index = self.file_model.index(desktop) self.ui.treeView_file_system.collapseAll() self.ui.treeView_file_system.setCurrentIndex(desktop_index) self.ui.treeView_file_system.expand(desktop_index) self.ui.treeView_file_system.scrollTo(desktop_index, hint=QAbstractItemView.PositionAtTop)
def open(self): fileDialog = QFileDialog(self) supportedMimeTypes = QMediaPlayer.supportedMimeTypes() if not supportedMimeTypes: supportedMimeTypes.append("video/x-msvideo") # AVI fileDialog.setMimeTypeFilters(supportedMimeTypes) moviesLocation = QStandardPaths.writableLocation(QStandardPaths.MoviesLocation) fileDialog.setDirectory(moviesLocation) if fileDialog.exec_() == QDialog.Accepted: self.playlist.addMedia(fileDialog.selectedUrls()[0]) self.player.play()
def appDirectory(): directory = QStandardPaths.writableLocation( QStandardPaths.AppDataLocation) if AppInfo.isDevMode(): directory = directory.replace("python", "Spongo") if not QDir().exists(directory): QDir().mkdir(directory) return directory
def go_documents(self, checked=False): """Slot for the 'Documents' button. Scrolls the treeview to show and select the user's documents directory.""" docs = QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation) if not docs: return self.ui.comboBox_current_path.setCurrentIndex(-1) docs_index = self.file_model.index(docs) self.ui.treeView_file_system.collapseAll() self.ui.treeView_file_system.setCurrentIndex(docs_index) self.ui.treeView_file_system.expand(docs_index) self.ui.treeView_file_system.scrollTo(docs_index, hint=QAbstractItemView.PositionAtTop)
def load(self) -> None: settings = QSettings(self.settings_path) settings.beginGroup("Settings") self.input_link = settings.value("input_link", "") self.output_path = settings.value( "output_path", QStandardPaths.writableLocation(QStandardPaths.DownloadLocation)) self.file_format = settings.value("file_format", "webm") self.single_line = bool( settings.value("single_line", "True") == "True") self.theme_color = settings.value("theme_color", "#004d99") settings.endGroup()
def __init__(self, parent=None): super(SettingsDialog, self).__init__(parent) self.settings = QSettings( QStandardPaths.writableLocation(QStandardPaths.ConfigLocation) + "/settings.ini", QSettings.IniFormat) self.usernames = set() self.engines = set() self.newUsername = "" self.newEnginePath = "" self._loadSettings() self.mainLayout = QtWidgets.QFormLayout() self.usernameLineEdit = QtWidgets.QLineEdit(self.newUsername) self.usernameLineEdit.setPlaceholderText("Username (a-zA-Z0-9_)") self.usernameLineEdit.setMinimumHeight(35) self.usernameLineEdit.setValidator(self.validator) self.usernameLineEdit.textChanged.connect(self.validateFields) self.usernameLineEdit.selectAll() self.usernameLineEdit.setCompleter( QtWidgets.QCompleter(list(self.usernames), self)) self.engineEdit = _EngineEdit(self.newEnginePath) self.engineEdit.pathEdit.textChanged.connect(self.validateFields) self.engineEdit.pathEdit.selectAll() self.engineEdit.pathEdit.setCompleter( QtWidgets.QCompleter(list(self.engines), self)) self.resetButton = QtWidgets.QPushButton("Reset") self.resetButton.clicked.connect(self._reset) buttonBox = QtWidgets.QDialogButtonBox() self.okButton = buttonBox.addButton( "Ok", QtWidgets.QDialogButtonBox.AcceptRole) self.cancelButton = buttonBox.addButton( "Cancel", QtWidgets.QDialogButtonBox.RejectRole) self.okButton.clicked.connect(self._ok) self.cancelButton.clicked.connect(self.reject) self.mainLayout.setContentsMargins(0, 0, 0, 0) self.mainLayout.setAlignment(Qt.AlignBottom) self.mainLayout.addRow("Username", self.usernameLineEdit) self.mainLayout.addRow("Engine", self.engineEdit) self.mainLayout.addWidget(self.resetButton) self.mainLayout.addWidget(buttonBox) self.setLayout(self.mainLayout) self.validateFields()
def save_dictionary(file_name: str, dict_src: str, regex_map: Dict[str, Entry]): """Saves the dictionary if user modified it. Connected to aboutToQuit signal.""" if MainWindow.dict_modified: if dict_src == file_name: # TODO: change for deploy? check sig too app_data_loc: str = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) if app_data_loc: # Qt found a place we could save (may not exist) dir_exists = QDir().mkpath(app_data_loc) if dir_exists: # Exists / created abs_dir = QDir(app_data_loc) dict_src = abs_dir.filePath(file_name) with open(dict_src, 'w') as f: json.dump(regex_map, f)
def filepathBrowse(self): path = None if AppInfo.isDevMode(): path = "./data/images" else: img_dir = QStandardPaths.writableLocation( QStandardPaths.PicturesLocation) path = QFileDialog.getExistingDirectory(self, "Sélectionner un dossier", img_dir) self._filepath_text.setText(path)
def __init__(self): self.clips = [] self.clipboard_save_dir = _dir / "clip" self.app_settings_file = Path( QStandardPaths.writableLocation( QStandardPaths.GenericConfigLocation) ) / "network_clipboard_settings.json" if self.app_settings_file.exists(): self.clipboard_save_dir = Path( json.loads( self.app_settings_file.read_text())["clipboard_save_dir"]) self.hostname = socket.gethostname() self.clipboard_save_file = self.clipboard_save_dir / f"{self.hostname}.clips.json"
def __init__(self, settings_path=None): super(Settings, self).__init__(None) self.settings_path = Settings.CONFIG_PATH if settings_path == None else settings_path self.input_link = str() self.output_path = QStandardPaths.writableLocation( QStandardPaths.DownloadLocation) self.file_format = "webm" self.single_line = True self.theme_color = "#004d99" if os.path.isfile(Settings.CONFIG_PATH): self.load() atexit.register(self.save)
def save_text(self): frmat = '.txt' initial_path = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) if not initial_path: initial_path = QDir.currentPath() initial_path += '/Screenshot_Text-' + \ str(datetime.now()).replace(' ', '_') + frmat file_dialog = QFileDialog(self, "Save as", initial_path) file_dialog.setAcceptMode(QFileDialog.AcceptSave) file_dialog.setFileMode(QFileDialog.AnyFile) if file_dialog.exec() != QDialog.Accepted: return file_name = file_dialog.selectedFiles()[0] with open(file_name, 'w') as wf: wf.write(self.text_edit.toPlainText())
def toQImage(self, filepath): ibuf = ImageBuf(filepath) try: bufok = ibuf.read(subimage=0, miplevel=0, force=True, convert=oiio.UINT8) except Exception as ex: print(ex) return None if not bufok: return None spec = ibuf.spec() width = spec.width height = spec.height # Expect the channel to be RGB from the beginning. # It might not work if it is a format like ARGB. # qimage = QtGui.QImage(width, height, QtGui.QImage.Format_RGB888) roi = oiio.ROI(0, width, 0, height, 0, 1, 0, 3) try: orgimg = Image.fromarray(ibuf.get_pixels(oiio.UINT8, roi)) # for ImageQt source format error if orgimg.mode in self.mw.shot.NO_SUPPORT_IMAGEQT: orgimg = orgimg.convert('RGB') if self.mw.thumbnail_bright != self.mw.THUMB_DEFALUT_BRIGHT: eim = ImageEnhance.Brightness(orgimg) orgimg = eim.enhance(self.mw.thumbnail_bright) qimage = ImageQt(orgimg) # workaround https://bugreports.qt.io/browse/PYSIDE-884 # output QImage to a file and reRead qimage wksavepath = QStandardPaths.writableLocation( QStandardPaths.TempLocation) wksavepath = wksavepath + "/{0}/sequencegrab.jpg".format( self.mw.APPID) qimage.save(wksavepath, "jpg") wkqim = QImage(wksavepath) qimage = wkqim os.remove(wksavepath) except Exception as ex: print(ex) return None return (qimage)
def start_tts_by_srt_file(self, file_name: str, config_str: str): subs = [] with open(file_name, mode='r', encoding='utf-8') as file: subs = list(srt.parse(file.read())) # print(subs[0].start, subs[0]) ssml_template_str = self._get_ssml_config_template(config_str) (base_name, ext) = os.path.splitext(file_name) out_dir = os.path.join( QStandardPaths.writableLocation(QStandardPaths.DownloadLocation), base_name) print("Subtitles to tts results store in: ", out_dir) if not os.path.isdir(out_dir): os.mkdir(out_dir) for srt_obj in subs: text = srt_obj.content.replace('\u200e', '') out_file = os.path.join(out_dir, '{}.wav'.format(text)) self._do_tts(True, ssml_template_str.format(text), out_file)
def _set_filename(self): name = APPNAME.lower() + '.sbc' path = QStandardPaths.writableLocation( QStandardPaths.AppConfigLocation) if path: path = pathlib.Path(path) / name elif WIN: path = pathlib.Path.home() / name else: path = pathlib.Path.home() / '.config' if path.exists(): path /= name else: path = pathlib.Path.home() / f'.{name}' self._filename = str(path.resolve()) if path.exists(): self._update_on_open() else: self._make_default_sbc()
def open_download_directory(): path = QStandardPaths.writableLocation(QStandardPaths.DownloadLocation) DownloadWidget.open_file(path)