def onOpenFile(self): qset = QSettings("BKR-LAB", "CueMol") qfdlg = QFileDialog(self) qset.beginGroup("fileopendlg") qfdlg.restoreState(qset.value("savestate", qfdlg.saveState())) qset.endGroup() qfdlg.setNameFilter(self.tr("CueMol Scene (*.qsc)")) res = qfdlg.exec_() qset.beginGroup("fileopendlg") qset.setValue("savestate", qfdlg.saveState()) qset.endGroup() if not res: return fname = qfdlg.selectedFiles() #fname = QFileDialog.getOpenFileName(self, 'Open file') print("get OFN: " + str(fname[0])) #self.loadPDBFile(fname[0]) self.loadQSCFile(fname[0])
def on_but(self): path_old = self.path qfdial = QFileDialog(directory=self.path) qfdial.setHistory([]) # clear history rsp = qfdial.restoreState(qfdial.saveState()) qfdial.setHistory(self.dirs) logger.debug('QFileDialog.history: %s' % str(qfdial.history())) resp = qfdial.getSaveFileName(parent=self, caption='Output file', filter=self.fltr)\ if self.mode == 'w' else \ qfdial.getOpenFileName(parent=self, caption='Input file', filter=self.fltr) logger.debug('response: %s len=%d' % (resp, len(resp))) self.path, filter = resp dname, fname = os.path.split(self.path) if self.mode == 'r' and not os.path.lexists(self.path): logger.debug('pass does not exist: %s' % self.path) return elif dname == '' or fname == '': logger.debug('input directiry name "%s" or file name "%s" is empty... use default values'%(dname, fname)) return elif self.path == path_old: logger.debug('path has not been changed: %s' % str(self.path)) return else: logger.debug('selected file: %s' % self.path) self.but.setText(self.but_text()) self.path_is_changed.emit(self.path) self.but.setStyleSheet(self.but_style_selected)
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 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 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 chooseExportDir(self, givenDir=None): state = settings.exportFileDialogState() dialog = QFileDialog(self) if state: dialog.restoreState(state) dialogDir = dialog.directory() if givenDir is not None: dialog.setDirectory(givenDir) elif dialogDir is None: dialog.setDirectory( QStandardPaths.standardLocations(QStandardPaths.DocumentsLocation)[0] ) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setFileMode(QFileDialog.Directory) ok = dialog.exec_() exportDir = QDir.toNativeSeparators(dialog.directory().absolutePath()) if givenDir is not None: dialog.setDirectory(dialogDir) settings.setExportFileDialogState(dialog.saveState()) if ok: self.exportDirectory = exportDir
def requestWrite(self, node, file_name = None, limit_mimetypes = None): if self._writing: raise OutputDeviceError.DeviceBusyError() dialog = QFileDialog() dialog.setWindowTitle(catalog.i18nc("@title:window", "Save to File")) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) # Ensure platform never ask for overwrite confirmation since we do this ourselves dialog.setOption(QFileDialog.DontConfirmOverwrite) if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ: dialog.setOption(QFileDialog.DontUseNativeDialog) filters = [] mime_types = [] selected_filter = None last_used_type = Preferences.getInstance().getValue("local_file/last_used_type") file_types = Application.getInstance().getMeshFileHandler().getSupportedFileTypesWrite() file_types.sort(key = lambda k: k["description"]) if limit_mimetypes: file_types = list(filter(lambda i: i["mime_type"] in limit_mimetypes, file_types)) if len(file_types) == 0: Logger.log("e", "There are no file types available to write with!") raise OutputDeviceError.WriteRequestFailedError() for item in file_types: type_filter = "{0} (*.{1})".format(item["description"], item["extension"]) filters.append(type_filter) mime_types.append(item["mime_type"]) if last_used_type == item["mime_type"]: selected_filter = type_filter if file_name: file_name += "." + item["extension"] dialog.setNameFilters(filters) if selected_filter != None: dialog.selectNameFilter(selected_filter) if file_name != None: dialog.selectFile(file_name) dialog.restoreState(Preferences.getInstance().getValue("local_file/dialog_state").encode()) if not dialog.exec_(): raise OutputDeviceError.UserCanceledError() Preferences.getInstance().setValue("local_file/dialog_state", str(dialog.saveState())) selected_type = file_types[filters.index(dialog.selectedNameFilter())] Preferences.getInstance().setValue("local_file/last_used_type", selected_type["mime_type"]) file_name = dialog.selectedFiles()[0] if os.path.exists(file_name): result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"), catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_name)) if result == QMessageBox.No: raise OutputDeviceError.UserCanceledError() self.writeStarted.emit(self) mesh_writer = Application.getInstance().getMeshFileHandler().getWriter(selected_type["id"]) try: mode = selected_type["mode"] if mode == MeshWriter.OutputMode.TextMode: Logger.log("d", "Writing to Local File %s in text mode", file_name) stream = open(file_name, "wt") elif mode == MeshWriter.OutputMode.BinaryMode: Logger.log("d", "Writing to Local File %s in binary mode", file_name) stream = open(file_name, "wb") job = WriteMeshJob(mesh_writer, stream, node, mode) job.setFileName(file_name) job.progress.connect(self._onJobProgress) job.finished.connect(self._onWriteJobFinished) message = Message(catalog.i18nc("@info:progress", "Saving to <filename>{0}</filename>").format(file_name), 0, False, -1) message.show() job._message = message self._writing = True job.start() except PermissionError as e: Logger.log("e", "Permission denied when trying to write to %s: %s", file_name, str(e)) raise OutputDeviceError.PermissionDeniedError(catalog.i18nc("@info:status", "Permission denied when trying to save <filename>{0}</filename>").format(file_name)) from e except OSError as e: Logger.log("e", "Operating system would not let us write to %s: %s", file_name, str(e)) raise OutputDeviceError.WriteRequestFailedError(catalog.i18nc("@info:status", "Could not save to <filename>{0}</filename>: <message>{1}</message>").format()) from e
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("SimpleFont 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 *.woff2)"), ]) 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 os.path.basename(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)
def saveState(widget: QFileDialog, key: str) -> None: key += "State" aqt.mw.pm.profile[key] = widget.saveState()
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)
def requestWrite(self, node, file_name=None): if self._writing: raise OutputDeviceError.DeviceBusyError() dialog = QFileDialog() dialog.setWindowTitle(catalog.i18nc("@title:window", "Save to File")) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) # Ensure platform never ask for overwrite confirmation since we do this ourselves dialog.setOption(QFileDialog.DontConfirmOverwrite) if sys.platform == "linux" and "KDE_FULL_SESSION" in os.environ: dialog.setOption(QFileDialog.DontUseNativeDialog) filters = [] mime_types = [] selected_filter = None last_used_type = Preferences.getInstance().getValue( "local_file/last_used_type") file_types = Application.getInstance().getMeshFileHandler( ).getSupportedFileTypesWrite() file_types.sort(key=lambda k: k["description"]) for item in file_types: type_filter = "{0} (*.{1})".format(item["description"], item["extension"]) filters.append(type_filter) mime_types.append(item["mime_type"]) if last_used_type == item["mime_type"]: selected_filter = type_filter file_name += "." + item["extension"] dialog.setNameFilters(filters) if selected_filter != None: dialog.selectNameFilter(selected_filter) if file_name != None: dialog.selectFile(file_name) dialog.restoreState(Preferences.getInstance().getValue( "local_file/dialog_state").encode()) if not dialog.exec_(): raise OutputDeviceError.UserCanceledError() Preferences.getInstance().setValue("local_file/dialog_state", str(dialog.saveState())) selected_type = file_types[filters.index(dialog.selectedNameFilter())] Preferences.getInstance().setValue("local_file/last_used_type", selected_type["mime_type"]) file_name = dialog.selectedFiles()[0] if os.path.exists(file_name): result = QMessageBox.question( None, catalog.i18nc("@title:window", "File Already Exists"), catalog.i18nc( "@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?" ).format(file_name)) if result == QMessageBox.No: raise OutputDeviceError.UserCanceledError() self.writeStarted.emit(self) mesh_writer = Application.getInstance().getMeshFileHandler().getWriter( selected_type["id"]) try: mode = selected_type["mode"] if mode == MeshWriter.OutputMode.TextMode: Logger.log("d", "Writing to Local File %s in text mode", file_name) stream = open(file_name, "wt") elif mode == MeshWriter.OutputMode.BinaryMode: Logger.log("d", "Writing to Local File %s in binary mode", file_name) stream = open(file_name, "wb") job = WriteMeshJob(mesh_writer, stream, node, mode) job.setFileName(file_name) job.progress.connect(self._onJobProgress) job.finished.connect(self._onWriteJobFinished) message = Message( catalog.i18nc( "@info:progress", "Saving to <filename>{0}</filename>").format(file_name), 0, False, -1) message.show() job._message = message self._writing = True job.start() except PermissionError as e: Logger.log("e", "Permission denied when trying to write to %s: %s", file_name, str(e)) raise OutputDeviceError.PermissionDeniedError( catalog.i18nc( "@info:status", "Permission denied when trying to save <filename>{0}</filename>" ).format(file_name)) from e except OSError as e: Logger.log("e", "Operating system would not let us write to %s: %s", file_name, str(e)) raise OutputDeviceError.WriteRequestFailedError( catalog.i18nc( "@info:status", "Could not save to <filename>{0}</filename>: <message>{1}</message>" ).format()) from e