def outputIndexAs(self): widget = QApplication.focusWidget() extensions = [] for extension, desc in EXPORT_EXTENSIONS.items(): extensions.append("{} (*{})".format(desc, extension)) with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True): form = QFileDialog( self.window, "Output As — {}".format(QApplication.applicationName())) form.setNameFilters(extensions) form.setAcceptMode(QFileDialog.AcceptSave) form.setDirectory(self.state.outputPath) form.selectFile(str(pathlib.Path(self.state.model.filename).stem)) if form.exec_(): filename = form.selectedFiles()[0] extension = form.selectedNameFilter() if filename: # Must have some extension if not re.match(r"^.*[.].+$", filename): if extension: filename += EXTENSION_EXTRACT_RX.sub( r"\1", extension) else: filename += ".rtf" self._outputIndex(filename, widget) Lib.restoreFocus(widget)
def import_wallet(self): dlg = QFileDialog(self.new_wallet_ui, "Select Import Wallet File") dlg.setFileMode(QFileDialog.ExistingFile) wallet_filename = None if dlg.exec_(): wallet_filename = dlg.selectedFiles()[0] else: return new_wallet_file = os.path.join(wallet_dir_path, self.get_new_wallet_file_name()) if wallet_filename: wallet_key_filename = wallet_filename + '.keys' if not os.path.exists(wallet_key_filename): QMessageBox.warning(self.new_wallet_ui, \ 'Import Wallet',\ """Error: Key file does not exist!<br> Are you sure to select correct wallet file?<br><br> Hint: Wallet file often ends with .bin""") return False try: copy2(wallet_filename, os.path.join(wallet_dir_path, new_wallet_file)) copy2(wallet_key_filename, os.path.join(wallet_dir_path, \ new_wallet_file + '.keys')) except IOError, err: self._detail_error_msg("Importing Wallet", "Error importing wallet!", str(err)) self.ui.reset_wallet() return False
def choosePackages(parent=None, caption="", directory="", selectMode="single"): dialog = QFileDialog(parent, caption, osp.normcase(directory)) dialog.setFileMode(QFileDialog.Directory) dialog.setFilter(QDir.NoDotAndDotDot | QDir.Dirs)# | QDir.Files) dialog.setNameFilters(["Packages ( pkg_* lyr_* )"]) dialog.setOption(QFileDialog.ReadOnly) bMultiSelect = (selectMode == "multi") treeView = dialog.findChild(QTreeView) if bMultiSelect: treeView.setSelectionMode(QAbstractItemView.ExtendedSelection) if bMultiSelect: listView = dialog.itemDelegate().parent() listView.setSelectionMode(QAbstractItemView.ExtendedSelection) treeView.model().setNameFilterDisables(True) proxyModel = PackSortProxyModel(dialog) dialog.setProxyModel(proxyModel) res = dialog.exec_() if res and treeView.selectionModel().hasSelection(): sDirList = dialog.selectedFiles() try: sDirList.remove(dialog.directory().absolutePath()) except ValueError: pass return sDirList if bMultiSelect else sDirList[0] return [] if bMultiSelect else ""
def on_browse(self): current_path = self.files_model.rootPath() file_dialog = QFileDialog(self, 'Select a Folder', current_path) file_dialog.setFileMode(QFileDialog.Directory) file_dialog.setOption(QFileDialog.ShowDirsOnly) if file_dialog.exec_(): self.on_change_root_path(file_dialog.selectedFiles()[0])
def on_browse(self, *_): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.DirectoryOnly) dialog.setViewMode(QFileDialog.Detail) dialog.setDirectory(self.le_output.text()) if dialog.exec_(): self.le_output.setText(dialog.selectedFiles()[0])
def on_browse(self): current_path = self.files_model.rootPath() file_dialog = QFileDialog(self, 'Select a Folder', current_path) file_dialog.setFileMode(QFileDialog.Directory) file_dialog.setOption(QFileDialog.ShowDirsOnly) if file_dialog.exec_(): self.on_change_root_path(file_dialog.selectedFiles()[0])
def seleccionarUI(self): dialogo = QFileDialog(None) dialogo.setFileMode(QFileDialog.ExistingFile) dialogo.setNameFilter('Interfaz(*.ui)') if dialogo.exec_(): global Ruta_archivoUI Ruta_archivoUI = dialogo.selectedFiles()[0] self.rutaEntrada_lineEdit.setText(Ruta_archivoUI)
def open_file(parent, filter): dialog = QFileDialog() dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setFilter(QDir.Files) dialog.setFileMode(QFileDialog.ExistingFile) dialog.setNameFilter(filter) res = dialog.exec() if res: return dialog.selectedFiles()[0]
def _add(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.ExistingFiles) dialog.setViewMode(QFileDialog.Detail) fileNames = dialog.selectedFiles() if dialog.exec_() else [] for fileName in fileNames: layer = Layer() layer.load_file(fileName, None) self.list.add_layer(layer)
def open_file(parent, filter): dialog = QFileDialog() dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setFilter(QDir.Files) dialog.setFileMode(QFileDialog.ExistingFile) dialog.setNameFilter(filter) res = dialog.exec() if res: return dialog.selectedFiles()[0]
def InvokeSingleSelectionFileDialog(self): """ Prompts the user to select a single file from a file dialog window. """ dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFile) dialog.setFilter(self.videoExtensionFileFilter) ret = dialog.exec_() FileNames = dialog.selectedFiles() if len(FileNames) == 0: FileNames.append(None) return FileNames[0]
def save(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setDefaultSuffix("avi") dialog.setDirectory(os.getcwd()) dialog.setNameFilter(self.tr("Video Files [.avi] (*.avi)")) if dialog.exec_(): output_file_name = dialog.selectedFiles()[0] correlate(self.clip_filename, self.audio_filename, output_file_name)
def seleccionarPY(self): dialogo = QFileDialog(None) dialogo.setFileMode(QFileDialog.AnyFile) dialogo.setNameFilter('Archivo Python(*.py)') dialogo.setAcceptMode(QFileDialog.AcceptSave) dialogo.setDefaultSuffix('py') if dialogo.exec_(): global Ruta_archivoPY Ruta_archivoPY = dialogo.selectedFiles()[0] self.rutaSalida_lineEdit.setText(Ruta_archivoPY)
def cmdSfoglia_click(self): """Evento che gestisce il tasto per sfogliare il percorso""" dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("SQLite db (*.db)") dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): fileNames = dialog.selectedFiles() self.myWidget.txtPercorso.setText(fileNames[0]) self.InitTable()
def save(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setDefaultSuffix("avi") dialog.setDirectory(os.getcwd()) dialog.setNameFilter(self.tr("Video Files [.avi] (*.avi)")) if dialog.exec_(): output_file_name = dialog.selectedFiles()[0] correlate(self.clip_filename, self.audio_filename, output_file_name)
def cmdSfoglia_click(self): """Evento che gestisce il tasto per sfogliare il percorso""" dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("SQLite db (*.db)") dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): fileNames = dialog.selectedFiles() self.myWidget.txtPercorso.setText( fileNames[0] ) self.InitTable()
def choose_save_dir(self): fname = QFileDialog(self, FILEBROWSER_SAVE_FOLDER_TITLE) fname.setFileMode(QFileDialog.Directory) looking_label = QFileDialog.DialogLabel(QFileDialog.LookIn) filename_label = QFileDialog.DialogLabel(QFileDialog.FileName) filetype_label = QFileDialog.DialogLabel(QFileDialog.FileType) fname.setLabelText(looking_label, FILEBROWSER_SAVE_FOLDER_LOOKIN) fname.setLabelText(filename_label, FILEBROWSER_SAVE_FOLDER_FOLDERNAME) fname.setLabelText(filetype_label, FILEBROWSER_SAVE_FOLDER_FOLDERTYPE) fname.setOption(QFileDialog.ShowDirsOnly) if fname.exec_(): filename = fname.selectedFiles()[0] self.save_folder_editline.setText(filename)
def loadGeo(self, *args): dialog = QFileDialog(self) #dialog.setFileMode(QFileDialog.AnyFile) if not self.fileName: dialog.setDirectory('meshes') else: dialog.setDirectory(os.path.dirname(self.fileName)) dialog.setNameFilter("Images (*.obj *.stl)") if dialog.exec_(): self.fileName = str(dialog.selectedFiles()[0]) self.refreshMesh()
def set_backup_directory(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.Directory) dialog.setOption(QFileDialog.ShowDirsOnly, True) dialog.setWindowTitle("Please select a backup directory") if configuration.get("Backup", "backup_directory"): dialog.setDirectory(configuration.get("Backup", "backup_directory")) if dialog.exec_(): mainlog.debug(dialog.selectedFiles()) directory = dialog.selectedFiles()[0] self._log("Testing the backup directory") try: f = open(os.path.join(directory, "test_file"), "w") f.write("TestBackup") f.close() except Exception as ex: box = QMessageBox( QMessageBox.Warning, "Unable to write into the backup directory", u"I can't write in the backup directory you selected. Have I the necessary permissions on that directory ({})? The error was : {}" .format(directory, str(ex))) box.exec_() return self.backup_directory_edit.setText(directory) configuration.set("Backup", "backup_directory", directory) self._log("Saving the backup directory in the configuration") configuration.save() dialog.close()
class ImportDirAction(QAction): def __init__(self, w): super(ImportDirAction, self).__init__( QIcon('exit.png'), u'&음악 폴더 지정', w) self.files = [] self.setShortcut('Ctrl+O') self.dialog = QFileDialog(w) self.dialog.setFileMode(QFileDialog.Directory) self.dialog.setOption(QFileDialog.ShowDirsOnly) self.triggered.connect(self.choose_dir) def choose_dir(self): if self.dialog.exec_(): config = NoisyConfig() for dir in self.dialog.selectedFiles(): config.dir = dir
def open_file(self): """ saves the file """ dialog = QFileDialog(self) dialog.setNameFilter("Image Files (*.png *.jpg *.bmp)") dialog.setStyleSheet('color:black;') name = '' if dialog.exec_(): name = dialog.selectedFiles() if name: self.image_data = open(name[0], 'rb').read() self.pixmap = QPixmap(name[0]) self.image_label.setPixmap( self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation))
def new_picture(self): dialog = QFileDialog() if (dialog.exec_()): filename = dialog.selectedFiles()[0] # print "ok {}".format(filename) f = open(filename,"rb") bytes = f.read(-1) f.close() image = QImage.fromData(QByteArray(bytes)) if image: # save as buffer(bytes) pixmap = QPixmap.fromImage(image.convertToFormat(QImage.Format_RGB16, Qt.MonoOnly).scaledToHeight(128)) self.set_pixmap_as_icon(pixmap)
def importF(self): fileBrowser = QFileDialog() fileBrowser.setFileMode(QFileDialog.Directory) fileBrowser.setViewMode(QFileDialog.Detail) fileBrowser.setOption(QFileDialog.ShowDirsOnly, True) if fileBrowser.exec_(): dir = fileBrowser.selectedFiles() else: print "Cancelled" return print "Copying data from " + str(dir[0]) files = os.listdir(str(dir[0])) copyOn = True print files for file in files: copyOn = True if file.endswith(".json"): if os.path.exists( os.path.join(json_reader.buildPath("data"), file)): if popup( "File " + file[:len(file) - 5] + " already exists. Overwrite?", "Warning"): os.remove(json_reader.buildPath("data/" + file)) else: copyOn = False if copyOn: print "Copying valid file " + file copy(os.path.join(str(dir[0]), file), json_reader.buildPath("data")) if "_link" not in file: try: #Ugly AF json_reader.readOne(file[:len(file) - 5]) json_reader.writeCharNames(file[:len(file) - 5]) except: print "Not a Character" try: json_reader.readP(file[:len(file) - 5]) json_reader.writePerNames(file[:len(file) - 5]) except Exception as e: print "Not a Persona" print e print "Successfully copied files" popup("Files imported successfully!", "Information")
def open_input_file_dialog(self): ''' Opens and input file dialog and sets the output based on that. The output file path will be the same as the input, but renamed .csv instead of .txt. ''' dialog = QFileDialog(self) # TODO - While testing anyway dialog.setDirectory('.') dialog.setFileMode(QFileDialog.ExistingFile) dialog.setNameFilter('Text files (*.txt)') if dialog.exec_(): input_files = dialog.selectedFiles() input_file = input_files[0] self.input_path.setText(input_file) out_path = generate_output_file(input_file) self.output_path.setText(out_path)
def export(self): fileBrowser = QFileDialog() fileBrowser.setFileMode(QFileDialog.Directory) fileBrowser.setViewMode(QFileDialog.Detail) fileBrowser.setOption(QFileDialog.ShowDirsOnly, True) if fileBrowser.exec_(): dir = fileBrowser.selectedFiles() else: print "Cancelled" return print "Copying data to " + str(dir[0]) + "/exportdata" try: copytree(json_reader.buildPath("data"), str(dir[0]) + "/exportdata") except Exception as e: print e popup( "Error in copying files. There is a file in the selected directory that has the same name as a Story Creator file.\n\nFiles are copied to " + str(dir[0]) + "/exportdata" + ". Please ensure this directory does not already exist.", "Critical") return print "Successfully copied files" popup("Files exported successfully!", "Information")
def open_existing_wallet(self): current_wallet_password, result = self._custom_input_dialog(self.ui, \ "Wallet Password", "Current wallet password:"******"Incorrect Wallet Password", "Wallet password is not correct!") return dlg = QFileDialog(self.ui, "Open Wallet File", wallet_dir_path, "Wallet files (*.bin)") dlg.setFileMode(QFileDialog.ExistingFile) wallet_filename = None if dlg.exec_(): wallet_filename = dlg.selectedFiles()[0] else: self.on_open_existing_wallet_complete_event.emit() return if not wallet_filename: return wallet_key_filename = wallet_filename + '.keys' if not os.path.exists(wallet_key_filename): QMessageBox.warning(self.ui, \ 'Open Wallet File',\ """Error: Key file does not exist!<br> Please make sure to select correct wallet file""") return if os.path.normpath(os.path.dirname( wallet_filename)) != os.path.normpath(wallet_dir_path): QMessageBox.warning(self.ui, \ 'Open Wallet File',\ """Error: Only wallet files at default location are available for opening.<br> You can import wallet via 'New... > Import' feature instead.""") return if os.path.basename(wallet_filename) == os.path.basename( self.ui.wallet_info.wallet_filepath): QMessageBox.warning(self.ui, \ 'Open Wallet File',\ """Error: Cannot open the same wallet!""") return while True: wallet_password, result = self._custom_input_dialog(self.ui, \ "Wallet Password", "Enter wallet password for opening:", QLineEdit.Password) if result: if not wallet_password: QMessageBox.warning(self.ui, \ 'Wallet Password',\ "You must provide password to open wallet") continue else: break else: return self.ui.stop_update_wallet_info_timer() self.on_open_existing_wallet_start_event.emit() current_wallet_filename = self.ui.wallet_info.wallet_filepath try: ret = self.ui.wallet_rpc_manager.rpc_request.stop_wallet() if ret['status'] == "ERROR": error_message = ret['message'] QMessageBox.critical(self.ui, \ 'Error Closing Current Wallet',\ "Error: %s" % error_message) raise Exception(error_message) self.ui.wallet_rpc_manager.set_ready(False) self.ui.run_wallet_rpc() while not self.ui.wallet_rpc_manager.is_ready(): self.app_process_events(0.1) ret = self.ui.wallet_rpc_manager.rpc_request.open_wallet( os.path.basename(wallet_filename), wallet_password) if ret['status'] == "ERROR": error_message = ret['message'] QMessageBox.critical(self.ui, 'Error Opening Wallet', error_message) raise Exception(error_message) self.ui.reset_wallet(False) self.ui.wallet_info.wallet_password = hashlib.sha256( wallet_password).hexdigest() self.ui.wallet_info.wallet_filepath = wallet_filename self.ui.wallet_info.is_loaded = True self.ui.wallet_info.save() while not self.ui.wallet_rpc_manager.is_ready(): self.app_process_events(0.1) except Exception, err: log(str(err), LEVEL_ERROR) ret = self.ui.wallet_rpc_manager.rpc_request.open_wallet( os.path.basename(current_wallet_filename), current_wallet_password) self.ui.wallet_info.wallet_password = hashlib.sha256( current_wallet_password).hexdigest() self.ui.wallet_info.wallet_filepath = current_wallet_filename self.ui.wallet_info.is_loaded = True self.ui.wallet_info.save() self.on_open_existing_wallet_complete_event.emit()
def restore_backup(self): self._clear_log() self._log("Restore procedure started") url = self.url_edit.text() psql_path = configuration.get("Commands", "psql") if not psql_path: self._log_error( "The Commands/psql path is not set in the server.cfg") self._log("Please fix the configuration file (on the right)") return if not configuration.get("Commands", "pg_restore"): self._log_error( "The Commands/pg_restore path is not set in the server.cfg") self._log("Please fix the configuration file (on the right)") return if not configuration.get("Backup", "backup_directory"): self._log( "The Backup/backup_directory path is not set in the server.cfg" ) self._log("I'm setting it myself.") configuration.set("Backup", "backup_directory", get_data_dir()) configuration.set("DocumentsDatabase", "documents_root", os.path.join(get_data_dir(), "documents")) configuration.save() self.edit_config.load_configuration() login_clt, password_clt, dummy, dummy, dummy = self._extract_db_params_from_url( configuration.get("Database", "url")) login_adm, password_adm, dbname, host, port = self._extract_db_params_from_url( configuration.get("Database", "admin_url")) self._log("{} / {}".format(login_adm, password_adm)) full_path_backup = None d = "" if configuration.get("Backup", "backup_directory"): d = configuration.get("Backup", "backup_directory") if platform.system() == "Windows": if configuration.get("Backup", "backup_directory"): d = configuration.get("Backup", "backup_directory") # Using the static method gives a more native FileDialog. # with support for network backup_file = QFileDialog.getOpenFileName( self, _("Please select a backup file"), d, "{} database backup (*.pgbackup)".format( configuration.get("Globals", "name")))[0] if not backup_file: self._log("Restore aborted") return full_path_backup = backup_file if not os.path.isdir(full_path_backup): self._log( "{} is not a directory, so I'll go up a level".format( full_path_backup)) full_path_backup = os.path.dirname(full_path_backup) if not os.path.isdir(full_path_backup): self._log_error( "{} is not a directory either. Aborting restore.". format(full_path_backup)) return elif platform.system() == "Linux": d = AskWindowsShare(None) d.exec_() if d.result() == QDialog.Accepted: # //192.168.0.6/postgresqlbackup script_path = "/tmp/horse_mount.sh" script = open(script_path, "w") script.write("""#!/bin/bash echo "Creating transfer directory" mkdir /tmp/backup_win echo "Unmounting previous transfer directory (can fail)" umount /tmp/backup_win echo "Mouting the backup directory" mount -t cifs -ousername={},password={} {} /tmp/backup_win """.format(d.user.text().strip(), d.password.text().strip(), d.address.text().strip())) script.close() import stat os.chmod(script_path, stat.S_IEXEC | stat.S_IWRITE | stat.S_IREAD) cmd = [ 'gksudo', '--sudo-mode', '--message', 'Allow Koi to connect to the backup server.', script_path ] # gksudo seems to like to have the DISPLAY set. So I basically copy # it from the calling environment. ret, dummy, dummy = self._run_shell( cmd, {'DISPLAY': os.environ.get('DISPLAY')}) if ret > 0: self._log_error( "The mount operation failed. Please review the parameters you've given." ) self._log_error( "Network address : {}, windows user name : {}".format( d.address.text() or "?", d.user.text() or "?")) return full_path_backup = "/tmp/backup_win" else: dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.Directory) dialog.setNameFilters(['Koi database backup (*.pgbackup)']) dialog.setWindowTitle("Please select a backup file") if configuration.get("Backup", "backup_directory"): dialog.setDirectory( configuration.get("Backup", "backup_directory")) if dialog.exec_(): full_path_backup = dialog.selectedFiles()[0] else: self._log_error( "Without proper source directory, I can't continue !") return else: self._log_error("Unsupported operating system") # At this poitn full_path_backup is the path to the backup # directory of Horse that we want to restore. # It is different than the current backup directory. if full_path_backup: full_restore(configuration, full_path_backup, backup_file, True, mainlog) self._log_success("Backup successfully restored !")