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 InvokeSingleSelectionDirectoryDialog(self): """ Prompts the user to select a single directory from a directory dialog window. """ dialog = QFileDialog() dialog.setFileMode(QFileDialog.DirectoryOnly) DirectoryName = dialog.getExistingDirectory() if len(DirectoryName) == 0: DirectoryName = None return DirectoryName
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 _create_file_dialog ( self ): """ Creates the correct type of file dialog. """ dlg = QFileDialog( self.control.parentWidget() ) dlg.selectFile( self._file_name.value ) dlg.setFileMode( QFileDialog.Directory ) return dlg
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 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 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 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 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 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 destination_chooser(self): """Show folder chooser dialog and update lblDestPath with path selected. Input: None Output: None""" dialog = QFileDialog() dialog.setFileMode(QFileDialog.Directory) dialog.setOption(QFileDialog.ShowDirsOnly) dialog.exec_() self.lblDestPath.setEnabled(True) self.lblDestPath.setText(os.path.abspath(dialog.directory().absolutePath())) self.update_table_view() self.copyButton.setEnabled(True)
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 destination_chooser(self): """Show folder chooser dialog and update lblDestPath with path selected. Input: None Output: None""" dialog = QFileDialog() dialog.setFileMode(QFileDialog.Directory) dialog.setOption(QFileDialog.ShowDirsOnly) dialog.exec_() self.lblDestPath.setEnabled(True) self.lblDestPath.setText( os.path.abspath(dialog.directory().absolutePath())) self.update_table_view() self.copyButton.setEnabled(True)
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 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 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()
def _create_control ( self, parent ): # If the caller provided a default path instead of a default directory # and filename, split the path into it directory and filename # components. if ((len( self.default_path ) != 0) and (len( self.default_directory ) == 0) and (len( self.default_filename ) == 0)): default_directory, default_filename = \ os.path.split( self.default_path ) else: default_directory = self.default_directory default_filename = self.default_filename # Convert the filter: keep = True filters = [] for f in self.wildcard.split( '|' ): if keep and f: filters.append( f ) keep = not keep # Set the default directory: if not default_directory: default_directory = QDir.currentPath() dlg = QFileDialog( parent, self.title, default_directory ) dlg.setViewMode( QFileDialog.Detail ) dlg.selectFile( default_filename ) dlg.setFilters( filters ) if self.wildcard_index < filters.count(): dlg.selectFilter( filters[ self.wildcard_index ] ) if self.action == 'open': dlg.setAcceptMode( QFileDialog.AcceptOpen ) dlg.setFileMode( QFileDialog.ExistingFile ) elif self.action == 'open files': dlg.setAcceptMode( QFileDialog.AcceptOpen ) dlg.setFileMode( QFileDialog.ExistingFiles ) else: dlg.setAcceptMode( QFileDialog.AcceptSave ) dlg.setFileMode( QFileDialog.AnyFile ) return dlg
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 !")
class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Cobaya input generator for Cosmology") self.setGeometry(0, 0, 1500, 1000) self.move( QApplication.desktop().screen().rect().center() - self.rect().center()) self.show() # Main layout self.layout = QHBoxLayout() self.setLayout(self.layout) self.layout_left = QVBoxLayout() self.layout.addLayout(self.layout_left) self.layout_output = QVBoxLayout() self.layout.addLayout(self.layout_output) # LEFT: Options self.options = QWidget() self.layout_options = QVBoxLayout() self.options.setLayout(self.layout_options) self.options_scroll = QScrollArea() self.options_scroll.setWidget(self.options) self.options_scroll.setWidgetResizable(True) self.layout_left.addWidget(self.options_scroll) self.atoms = odict() titles = odict([ ["preset", "Presets"], ["theory", "Theory code"], ["primordial", "Primordial perturbations"], ["geometry", "Geometry"], ["hubble", "Constaint on hubble parameter"], ["baryons", "Baryon sector"], ["dark_matter", "Dark matter"], ["dark_energy", "Lambda / Dark energy"], ["neutrinos", "Neutrinos and other extra matter"], ["bbn", "BBN"], ["reionization", "Reionization history"], ["cmb_lensing", "CMB lensing"], ["cmb", "CMB experiments"], ["sampler", "Samplers"]]) for a in titles: self.atoms[a] = { "group": QGroupBox(titles[a]), "combo": QComboBox()} self.layout_options.addWidget(self.atoms[a]["group"]) self.atoms[a]["layout"] = QVBoxLayout(self.atoms[a]["group"]) self.atoms[a]["layout"].addWidget(self.atoms[a]["combo"]) self.atoms[a]["combo"].addItems( [text(k,v) for k,v in getattr(input_database, a).items()]) # Connect to refreshers -- needs to be after adding all elements for a in self.atoms: if a == "preset": self.atoms["preset"]["combo"].currentIndexChanged.connect( self.refresh_preset) continue self.atoms[a]["combo"].currentIndexChanged.connect(self.refresh) # Add Planck-naming checkbox and connect to refresher too self.planck_names = QCheckBox("Keep common names") self.atoms["theory"]["layout"].addWidget(self.planck_names) self.planck_names.stateChanged.connect(self.refresh) # RIGHT: Output + buttons self.display_tabs = QTabWidget() self.display = {} for k in ["yaml", "python"]: self.display[k] = QTextEdit() self.display[k].setLineWrapMode(QTextEdit.NoWrap) self.display[k].setFontFamily("mono") self.display[k].setCursorWidth(0) self.display[k].setReadOnly(True) self.display_tabs.addTab(self.display[k], k) self.layout_output.addWidget(self.display_tabs) # Buttons self.buttons = QHBoxLayout() self.save_button = QPushButton('Save', self) self.copy_button = QPushButton('Copy to clipboard', self) self.buttons.addWidget(self.save_button) self.buttons.addWidget(self.copy_button) self.save_button.released.connect(self.save_file) self.copy_button.released.connect(self.copy_clipb) self.layout_output.addLayout(self.buttons) self.save_dialog = QFileDialog() self.save_dialog.setFileMode(QFileDialog.AnyFile) self.save_dialog.setAcceptMode(QFileDialog.AcceptSave) # Select first preset, by default # print(self.atoms["preset"]["combo"].itemText(0)) @Slot() def refresh(self): info = create_input(planck_names=self.planck_names.isChecked(), **{ k:str(self.atoms[k]["combo"].currentText().split(_separator)[0]) for k in self.atoms if k is not "preset"}) self.refresh_display(info) @Slot() def refresh_preset(self): preset = self.atoms["preset"]["combo"].currentText().split(_separator)[0] info = create_input(preset=preset) self.refresh_display(info) # Update combo boxes to reflect the preset values, without triggering update for k,v in input_database.preset[preset].items(): if k in [input_database._desc, "derived"]: continue self.atoms[k]["combo"].blockSignals(True) self.atoms[k]["combo"].setCurrentIndex( self.atoms[k]["combo"].findText( text(v,getattr(input_database, k).get(v)))) self.atoms[k]["combo"].blockSignals(False) def refresh_display(self, info): self.display["python"].setText( "from collections import OrderedDict\n\ninfo = " + pformat(info)) self.display["yaml"].setText(yaml_dump(info)) @Slot() def save_file(self): ftype = next(k for k,w in self.display.items() if w is self.display_tabs.currentWidget()) ffilter = {"yaml": "Yaml files (*.yaml *.yml)", "python": "(*.py)"}[ftype] fsuffix = {"yaml": ".yaml", "python": ".py"}[ftype] fname, path = self.save_dialog.getSaveFileName( self.save_dialog, "Save input file", fsuffix, ffilter, os.getcwd()) if not fname.endswith(fsuffix): fname += fsuffix with open(fname, "w+") as f: f.write(self.display_tabs.currentWidget().toPlainText()) @Slot() def copy_clipb(self): self.clipboard.setText(self.display_tabs.currentWidget().toPlainText())
class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Cobaya input generator for Cosmology") self.setGeometry(0, 0, 1500, 1000) self.move( QApplication.desktop().screenGeometry().center() - self.rect().center()) self.show() # Main layout self.layout = QHBoxLayout() self.setLayout(self.layout) self.layout_left = QVBoxLayout() self.layout.addLayout(self.layout_left) self.layout_output = QVBoxLayout() self.layout.addLayout(self.layout_output) # LEFT: Options self.options = QWidget() self.layout_options = QVBoxLayout() self.options.setLayout(self.layout_options) self.options_scroll = QScrollArea() self.options_scroll.setWidget(self.options) self.options_scroll.setWidgetResizable(True) self.layout_left.addWidget(self.options_scroll) titles = odict([ ["Presets", odict([["preset", "Presets"]])], ["Cosmological Model", odict([ ["theory", "Theory code"], ["primordial", "Primordial perturbations"], ["geometry", "Geometry"], ["hubble", "Hubble parameter constraint"], ["matter", "Matter sector"], ["neutrinos", "Neutrinos and other extra matter"], ["dark_energy", "Lambda / Dark energy"], ["bbn", "BBN"], ["reionization", "Reionization history"]])], ["Data sets", odict([ ["like_cmb", "CMB experiments"], ["like_bao", "BAO experiments"], ["like_sn", "SN experiments"], ["like_H0", "Local H0 measurements"]])], ["Sampler", odict([["sampler", "Samplers"]])]]) self.combos = odict() for group, fields in titles.items(): group_box = QGroupBox(group) self.layout_options.addWidget(group_box) group_layout = QVBoxLayout(group_box) for a, desc in fields.items(): self.combos[a] = QComboBox() if len(fields) > 1: label = QLabel(desc) group_layout.addWidget(label) group_layout.addWidget(self.combos[a]) self.combos[a].addItems( [text(k, v) for k, v in getattr(input_database, a).items()]) # PLANCK NAMES CHECKBOX TEMPORARILY DISABLED # if a == "theory": # # Add Planck-naming checkbox # self.planck_names = QCheckBox( # "Keep common parameter names " # "(useful for fast CLASS/CAMB switching)") # group_layout.addWidget(self.planck_names) # Connect to refreshers -- needs to be after adding all elements for field, combo in self.combos.items(): if field == "preset": combo.currentIndexChanged.connect(self.refresh_preset) else: combo.currentIndexChanged.connect(self.refresh) # self.planck_names.stateChanged.connect(self.refresh_keep_preset) # RIGHT: Output + buttons self.display_tabs = QTabWidget() self.display = {} for k in ["yaml", "python", "citations"]: self.display[k] = QTextEdit() self.display[k].setLineWrapMode(QTextEdit.NoWrap) self.display[k].setFontFamily("mono") self.display[k].setCursorWidth(0) self.display[k].setReadOnly(True) self.display_tabs.addTab(self.display[k], k) self.layout_output.addWidget(self.display_tabs) # Buttons self.buttons = QHBoxLayout() self.save_button = QPushButton('Save', self) self.copy_button = QPushButton('Copy to clipboard', self) self.buttons.addWidget(self.save_button) self.buttons.addWidget(self.copy_button) self.save_button.released.connect(self.save_file) self.copy_button.released.connect(self.copy_clipb) self.layout_output.addLayout(self.buttons) self.save_dialog = QFileDialog() self.save_dialog.setFileMode(QFileDialog.AnyFile) self.save_dialog.setAcceptMode(QFileDialog.AcceptSave) def create_input(self): return create_input( get_comments=True, # planck_names=self.planck_names.isChecked(), **{field: list(getattr(input_database, field).keys())[combo.currentIndex()] for field, combo in self.combos.items() if field is not "preset"}) @Slot() def refresh_keep_preset(self): self.refresh_display(self.create_input()) @Slot() def refresh(self): self.combos["preset"].blockSignals(True) self.combos["preset"].setCurrentIndex(0) self.combos["preset"].blockSignals(False) self.refresh_display(self.create_input()) @Slot() def refresh_preset(self): preset = list(getattr(input_database, "preset").keys())[ self.combos["preset"].currentIndex()] info = create_input( get_comments=True, # planck_names=self.planck_names.isChecked(), preset=preset) self.refresh_display(info) # Update combo boxes to reflect the preset values, without triggering update for k, v in input_database.preset[preset].items(): if k in [input_database._desc]: continue self.combos[k].blockSignals(True) self.combos[k].setCurrentIndex( self.combos[k].findText( text(v, getattr(input_database, k).get(v)))) self.combos[k].blockSignals(False) def refresh_display(self, info): try: comments = info.pop(input_database._comment, None) comments_text = "\n# " + "\n# ".join(comments) except (TypeError, # No comments AttributeError): # Failed to generate info (returned str instead) comments_text = "" self.display["python"].setText( "from collections import OrderedDict\n\ninfo = " + pformat(info) + comments_text) self.display["yaml"].setText(yaml_dump(info) + comments_text) self.display["citations"].setText(prettyprint_citation(citation(info))) @Slot() def save_file(self): ftype = next(k for k, w in self.display.items() if w is self.display_tabs.currentWidget()) ffilter = {"yaml": "Yaml files (*.yaml *.yml)", "python": "(*.py)", "citations": "(*.txt)"}[ftype] fsuffix = {"yaml": ".yaml", "python": ".py", "citations": ".txt"}[ftype] fname, path = self.save_dialog.getSaveFileName( self.save_dialog, "Save input file", fsuffix, ffilter, os.getcwd()) if not fname.endswith(fsuffix): fname += fsuffix with open(fname, "w+") as f: f.write(self.display_tabs.currentWidget().toPlainText()) @Slot() def copy_clipb(self): self.clipboard.setText(self.display_tabs.currentWidget().toPlainText())