def open_files(title, directory=None, filters=''): """Creates an Open File dialog and returns a list of filenames.""" result = compat.getopenfilenames(parent=active_window(), caption=title, basedir=directory, filters=filters) return result[0]
def open_file_dialog(self): """ Given a list of filters, prompts the user to select an existing file and returns the file path and filter. Returns ------- file_name : str Path to the selected file. selected_filter : str The chosen filter (this indicates which custom loader from the registry to use). """ filters = ["Auto (*)"] + [x for x in io_registry.get_formats( Spectrum1DRef)['Format']] file_names, self._file_filter = compat.getopenfilenames(basedir=self._directory, filters=";;".join(filters), selectedfilter=self._file_filter) if len(file_names) == 0: return None, None self._directory = file_names[0] return file_names[0], self._file_filter
def _click_addFilesButton(self): # dialog = QFileDialog(self) files = getopenfilenames( self, "Choose Time Series Files", '', self.tr('tseries (*.dat *.neu *.tseries *.pos)'), None, QFileDialog.DontUseNativeDialog)[0] self._add_files_to_fileListWidget(files)
def open_notebook(self, filenames=None): """Open a notebook from file.""" if not filenames: filenames, _selfilter = getopenfilenames(self, _("Open notebook"), '', FILES_FILTER) if filenames: for filename in filenames: self.create_new_client(filename=filename)
def slotOnImportFiles(self): files = getopenfilenames(self, _("Choose Time Series Files"), '', _('tseries (*.dat *.neu *.tseries *.pos)'), None, QFileDialog.DontUseNativeDialog)[0] self.addFiles(files) if len(files) == 1: item = self._files[files[0]] self.filesWidget.setCurrentItem(item) # ind = self.files.index(files[0]) # self.filesWidget.setCurrentRow(self.files.index(files[0])) self.slotOnLoadFile()
def _click_addFilesButton(self): files = getopenfilenames(None, "Choose Time Series Files", '', 'tseries (*.*)', None, QFileDialog.DontUseNativeDialog)[0] files = [i for i in files] items = [] for index in range(self.filesListWidget.count()): items.append(self.filesListWidget.item(index).text()) items = list(set(items + list(files))) self.filesListWidget.clear() self.filesListWidget.addItems(items) self.cont = self.filesListWidget.count()
def on_selectButton_clicked(self): # files = self.dialog.getOpenFileNames( # self, "Choose Time Series Files", '', # self.tr('tseries (*.neu *.tseries *.pos *dat)'), # None, QFileDialog.DontUseNativeDialog) files = getopenfilenames( self, "Choose Time Series Files", '', self.tr('tseries (*.neu *.tseries *.pos *dat)'), None, QFileDialog.DontUseNativeDialog)[0] items = [] for index in range(self.listWidget.count()): items.append(self.listWidget.item(index).text()) items = list(set(items + list(files))) self.listWidget.clear() self.listWidget.addItems(items) self.countLabel.setText("Total: %d" % len(items))
def open_notebook(self, filenames=None): """ Open a notebook from file. Parameters ---------- filenames : list of str or None, optional List of file names of notebooks to open. The default is None, meaning that the user should be asked. """ if not filenames: filenames, _selfilter = getopenfilenames(self, _('Open notebook'), '', FILES_FILTER) if filenames: for filename in filenames: self.create_new_client(filename=filename)
def load_model(self, model_dict=None): if model_dict is None: global _model_directory fname = compat.getopenfilenames( parent=self, caption='Read model file', basedir=_model_directory, filters=yaml_model_io.MODEL_FILE_FILTER) # File dialog returns a tuple with a list of file names. # We get the first name from the first tuple element. if len(fname[0]) < 1: return fname = fname[0][0] compound_model, formula, roi_bounds = yaml_model_io.buildModelFromFile( fname) else: compound_model, formula, roi_bounds = yaml_model_io.build_model_from_dict( model_dict) # Put new model in its own sub-layer under current layer. current_layer = self.current_layer if current_layer is None: return # Create new model layer using current ROI masks, if they exist mask = self.active_window.get_roi_mask(layer=current_layer) current_window = self.active_window # If there already is a model layer, just edit its model if hasattr(current_layer, '_model'): current_layer.model = compound_model self.update_model_list(layer=current_layer) dispatch.on_update_model.emit(layer=current_layer) else: layer = self.add_model_layer(compound_model) dispatch.on_update_model.emit(layer=layer) dispatch.on_add_model.emit(layer=layer) # dispatch.on_remove_model.emit(layer=layer) for bound in roi_bounds: current_window.add_roi(bounds=bound)
def _open_linelist_file(self, file_name=None): if file_name is None: filters = ['Line list (*.yaml *.ecsv)'] file_name, _file_filter = compat.getopenfilenames(filters=";;".join(filters)) # For now, lets assume both the line list itself, and its # associated YAML descriptor file, live in the same directory. # Not an issue for self-contained ecsv files. if file_name is not None and len(file_name) > 0: name = file_name[0] line_list = linelist.get_from_file(os.path.dirname(name), name) if line_list: self._get_waverange_from_dialog(line_list) if self.wave_range[0] and self.wave_range[1]: line_list = self._build_view(line_list, 0, waverange=self.wave_range) self.plot_window.linelists.append(line_list)
def _open_linelist_file(self, file_name=None): if file_name is None: filters = ['Line list (*.yaml *.ecsv)'] file_name, _file_filter = compat.getopenfilenames(filters=";;".join(filters)) # For now, lets assume both the line list itself, and its # associated YAML descriptor file, live in the same directory. # Not an issue for self-contained ecsv files. if file_name is not None and len(file_name) > 0: name = file_name[0] line_list = linelist.get_from_file(os.path.dirname(name), name) if line_list: self._get_waverange_from_dialog(line_list) if self.wave_range[0] and self.wave_range[1]: line_list = self._build_view(line_list, 0, waverange=self.wave_range) if not hasattr(self.plot_window, 'linelists'): self.plot_window.linelists = [] self.plot_window.linelists.append(line_list)
def exec_images_open_dialog(parent, basedir="", app_name=None, to_grayscale=True, dtype=None): """ Executes an image*s* open dialog box (QFileDialog.getOpenFileNames) * parent: parent widget (None means no parent) * basedir: base directory ('' means current directory) * app_name (opt.): application name (used as a title for an eventual error message box in case something goes wrong when saving image) * to_grayscale (default=True): convert image to grayscale Yields (filename, data) tuples if dialog is accepted, None otherwise """ saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr sys.stdout = None filenames, _filter = getopenfilenames( parent, _("Open"), basedir, io.iohandler.get_filters("load", dtype=dtype)) sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err filenames = [to_text_string(fname) for fname in list(filenames)] for filename in filenames: try: data = io.imread(filename, to_grayscale=to_grayscale) except Exception as msg: import traceback traceback.print_exc() QMessageBox.critical( parent, _("Error") if app_name is None else app_name, (_("%s could not be opened:") % osp.basename(filename)) + "\n" + str(msg), ) return yield filename, data
def run_opensbml(self, filenames=None, goto=None, word='', editorwindow=None, processevents=True): """Prompt the user to load a SBML file, translate to antimony, and display in a new window""" editor = self.main.editor editor0 = editor.get_current_editor() if editor0 is not None: position0 = editor0.get_position('cursor') filename0 = editor.get_current_filename() else: position0, filename0 = None, None if not filenames: # Recent files action action = editor.sender() if isinstance(action, QAction): filenames = from_qvariant(action.data(), to_text_string) if not filenames: basedir = getcwd() if editor.edit_filetypes is None: editor.edit_filetypes = get_edit_filetypes() if editor.edit_filters is None: editor.edit_filters = get_edit_filters() c_fname = editor.get_current_filename() if c_fname is not None and c_fname != editor.TEMPFILE_PATH: basedir = os.path.dirname(c_fname) editor.redirect_stdio.emit(False) parent_widget = editor.get_current_editorstack() if filename0 is not None: selectedfilter = get_filter(editor.edit_filetypes, os.path.splitext(filename0)[1]) else: selectedfilter = '' if not running_under_pytest(): customfilters = 'SBML files (*.sbml *.xml);;All files (*.*)' filenames, _sf = getopenfilenames( parent_widget, _("Open SBML file"), basedir, customfilters, selectedfilter=selectedfilter, options=QFileDialog.HideNameFilterDetails) else: # Use a Qt (i.e. scriptable) dialog for pytest dialog = QFileDialog(parent_widget, _("Open SBML file"), options=QFileDialog.DontUseNativeDialog) if dialog.exec_(): filenames = dialog.selectedFiles() editor.redirect_stdio.emit(True) if filenames: filenames = [os.path.normpath(fname) for fname in filenames] else: return focus_widget = QApplication.focusWidget() if editor.dockwidget and\ (not editor.dockwidget.isAncestorOf(focus_widget)\ and not isinstance(focus_widget, CodeEditor)): editor.dockwidget.setVisible(True) editor.dockwidget.setFocus() editor.dockwidget.raise_() def _convert(fname): fname = os.path.abspath(encoding.to_unicode_from_fs(fname)) if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':': fname = fname[0].upper() + fname[1:] return fname if hasattr(filenames, 'replaceInStrings'): # This is a QStringList instance (PyQt API #1), converting to list: filenames = list(filenames) if not isinstance(filenames, list): filenames = [_convert(filenames)] else: filenames = [_convert(fname) for fname in list(filenames)] if isinstance(goto, int): goto = [goto] elif goto is not None and len(goto) != len(filenames): goto = None for index, filename in enumerate(filenames): p = re.compile('(.xml$|.sbml$)') pythonfile = p.sub('_antimony.py', filename) if (pythonfile == filename): pythonfile = filename + "_antimony.py" # -- Do not open an already opened file current_editor = editor.set_current_filename( pythonfile, editorwindow) if current_editor is None: # -- Not a valid filename: if not os.path.isfile(filename): continue # -- current_es = editor.get_current_editorstack(editorwindow) # Creating the editor widget in the first editorstack (the one # that can't be destroyed), then cloning this editor widget in # all other editorstacks: finfo, newname = self.load_and_translate( filename, pythonfile, editor) finfo.path = editor.main.get_spyder_pythonpath() editor._clone_file_everywhere(finfo) current_editor = current_es.set_current_filename(newname) current_es.analyze_script() if goto is not None: # 'word' is assumed to be None as well current_editor.go_to_line(goto[index], word=word) position = current_editor.get_position('cursor') editor.cursor_moved(filename0, position0, filename, position) if (current_editor is not None): current_editor.clearFocus() current_editor.setFocus() current_editor.window().raise_() if processevents: QApplication.processEvents()
def import_data(self, filenames=None): """Import data from text file.""" title = _("Import data") if filenames is None: if self.filename is None: basedir = getcwd_or_home() else: basedir = osp.dirname(self.filename) filenames, _selfilter = getopenfilenames(self, title, basedir, iofunctions.load_filters) if not filenames: return elif is_text_string(filenames): filenames = [filenames] for filename in filenames: self.filename = to_text_string(filename) if os.name == "nt": self.filename = remove_backslashes(self.filename) ext = osp.splitext(self.filename)[1].lower() if ext not in iofunctions.load_funcs: buttons = QMessageBox.Yes | QMessageBox.Cancel answer = QMessageBox.question( self, title, _("<b>Unsupported file extension '%s'</b><br><br>" "Would you like to import it anyway " "(by selecting a known file format)?") % ext, buttons) if answer == QMessageBox.Cancel: return formats = list(iofunctions.load_extensions.keys()) item, ok = QInputDialog.getItem(self, title, _('Open file as:'), formats, 0, False) if ok: ext = iofunctions.load_extensions[to_text_string(item)] else: return load_func = iofunctions.load_funcs[ext] # 'import_wizard' (self.setup_io) if is_text_string(load_func): # Import data with import wizard error_message = None try: text, _encoding = encoding.read(self.filename) base_name = osp.basename(self.filename) editor = ImportWizard( self, text, title=base_name, varname=fix_reference_name(base_name)) if editor.exec_(): var_name, clip_data = editor.get_data() self.editor.new_value(var_name, clip_data) except Exception as error: error_message = str(error) else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() error_message = self.shellwidget.load_data(self.filename, ext) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical( self, title, _("<b>Unable to load '%s'</b>" "<br><br>" "The error message was:<br>%s") % (self.filename, error_message)) self.refresh_table()
def import_data(self, filenames=None): """Import data from text file""" title = _("Import data") if filenames is None: if self.filename is None: basedir = getcwd() else: basedir = osp.dirname(self.filename) filenames, _selfilter = getopenfilenames(self, title, basedir, iofunctions.load_filters) if not filenames: return elif is_text_string(filenames): filenames = [filenames] for filename in filenames: self.filename = to_text_string(filename) ext = osp.splitext(self.filename)[1].lower() if ext not in iofunctions.load_funcs: buttons = QMessageBox.Yes | QMessageBox.Cancel answer = QMessageBox.question(self, title, _("<b>Unsupported file extension '%s'</b><br><br>" "Would you like to import it anyway " "(by selecting a known file format)?" ) % ext, buttons) if answer == QMessageBox.Cancel: return formats = list(iofunctions.load_extensions.keys()) item, ok = QInputDialog.getItem(self, title, _('Open file as:'), formats, 0, False) if ok: ext = iofunctions.load_extensions[to_text_string(item)] else: return load_func = iofunctions.load_funcs[ext] # 'import_wizard' (self.setup_io) if is_text_string(load_func): # Import data with import wizard error_message = None try: text, _encoding = encoding.read(self.filename) if self.is_internal_shell: self.editor.import_from_string(text) else: base_name = osp.basename(self.filename) editor = ImportWizard(self, text, title=base_name, varname=fix_reference_name(base_name)) if editor.exec_(): var_name, clip_data = editor.get_data() monitor_set_global(self._get_sock(), var_name, clip_data) except Exception as error: error_message = str(error) else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() if self.is_internal_shell: namespace, error_message = load_func(self.filename) interpreter = self.shellwidget.interpreter for key in list(namespace.keys()): new_key = fix_reference_name(key, blacklist=list(interpreter.namespace.keys())) if new_key != key: namespace[new_key] = namespace.pop(key) if error_message is None: interpreter.namespace.update(namespace) else: error_message = monitor_load_globals(self._get_sock(), self.filename, ext) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical(self, title, _("<b>Unable to load '%s'</b>" "<br><br>Error message:<br>%s" ) % (self.filename, error_message)) self.refresh_table()
def import_data(self, filenames=None): """Import data from text file""" title = _("Import data") if filenames is None: if self.filename is None: basedir = getcwd() else: basedir = osp.dirname(self.filename) filenames, _selfilter = getopenfilenames(self, title, basedir, iofunctions.load_filters) if not filenames: return elif is_text_string(filenames): filenames = [filenames] for filename in filenames: self.filename = to_text_string(filename) ext = osp.splitext(self.filename)[1].lower() if ext not in iofunctions.load_funcs: buttons = QMessageBox.Yes | QMessageBox.Cancel answer = QMessageBox.question( self, title, _("<b>Unsupported file extension '%s'</b><br><br>" "Would you like to import it anyway " "(by selecting a known file format)?") % ext, buttons) if answer == QMessageBox.Cancel: return formats = list(iofunctions.load_extensions.keys()) item, ok = QInputDialog.getItem(self, title, _('Open file as:'), formats, 0, False) if ok: ext = iofunctions.load_extensions[to_text_string(item)] else: return load_func = iofunctions.load_funcs[ext] # 'import_wizard' (self.setup_io) if is_text_string(load_func): # Import data with import wizard error_message = None try: text, _encoding = encoding.read(self.filename) if self.is_internal_shell: self.editor.import_from_string(text) else: base_name = osp.basename(self.filename) editor = ImportWizard( self, text, title=base_name, varname=fix_reference_name(base_name)) if editor.exec_(): var_name, clip_data = editor.get_data() monitor_set_global(self._get_sock(), var_name, clip_data) except Exception as error: error_message = str(error) else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() if self.is_internal_shell: namespace, error_message = load_func(self.filename) interpreter = self.shellwidget.interpreter for key in list(namespace.keys()): new_key = fix_reference_name( key, blacklist=list(interpreter.namespace.keys())) if new_key != key: namespace[new_key] = namespace.pop(key) if error_message is None: interpreter.namespace.update(namespace) else: error_message = monitor_load_globals( self._get_sock(), self.filename, ext) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical( self, title, _("<b>Unable to load '%s'</b>" "<br><br>Error message:<br>%s") % (self.filename, error_message)) self.refresh_table()
def run_opensbml(self, filenames=None, goto=None, word='', editorwindow=None, processevents=True): """Prompt the user to load a SBML file, translate to antimony, and display in a new window""" editorwindow = None #Used in editor.load processevents = True #Used in editor.load editor = self.main.editor basedir = getcwd() if CONF.get('workingdir', 'editor/open/browse_scriptdir'): c_fname = editor.get_current_filename() if c_fname is not None and c_fname != editor.TEMPFILE_PATH: basedir = os.path.dirname(c_fname) editor.redirect_stdio.emit(False) parent_widget = editor.get_current_editorstack() selectedfilter = '' filters = 'SBML files (*.sbml *.xml);;All files (*.*)' filenames, _selfilter = getopenfilenames(parent_widget, _("Open SBML file"), basedir, filters, selectedfilter=selectedfilter) editor.redirect_stdio.emit(True) if filenames: filenames = [os.path.normpath(fname) for fname in filenames] if CONF.get('workingdir', 'editor/open/auto_set_to_basedir'): directory = os.path.dirname(filenames[0]) editor.emit(Signal("open_dir(QString)"), directory) else: #The file dialog box was closed without selecting a file. return focus_widget = QApplication.focusWidget() if editor.dockwidget and not editor.ismaximized and\ (not editor.dockwidget.isAncestorOf(focus_widget)\ and not isinstance(focus_widget, CodeEditor)): editor.dockwidget.setVisible(True) editor.dockwidget.setFocus() editor.dockwidget.raise_() def _convert(fname): fname = os.path.abspath(encoding.to_unicode_from_fs(fname)) if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':': fname = fname[0].upper() + fname[1:] return fname if hasattr(filenames, 'replaceInStrings'): # This is a QStringList instance (PyQt API #1), converting to list: filenames = list(filenames) if not isinstance(filenames, list): filenames = [_convert(filenames)] else: filenames = [_convert(fname) for fname in list(filenames)] for index, filename in enumerate(filenames): p = re.compile('(.xml$|.sbml$)') pythonfile = p.sub('_antimony.py', filename) if (pythonfile == filename): pythonfile = filename + "_antimony.py" current_editor = editor.set_current_filename( pythonfile, editorwindow) if current_editor is not None: # -- TODO: Do not open an already opened file pass else: # -- Not an existing opened file: if not os.path.isfile(filename): continue # -- current_es = editor.get_current_editorstack(editorwindow) # Creating the editor widget in the first editorstack (the one # that can't be destroyed), then cloning this editor widget in # all other editorstacks: finfo, newname = self.load_and_translate( filename, pythonfile, editor) finfo.path = editor.main.get_spyder_pythonpath() editor._clone_file_everywhere(finfo) current_editor = current_es.set_current_filename(newname) #if (current_editor is not None): # editor.register_widget_shortcuts("Editor", current_editor) current_es.analyze_script() if (current_editor is not None): current_editor.clearFocus() current_editor.setFocus() current_editor.window().raise_() if processevents: QApplication.processEvents()
def run_Import(self, action): """Prompt user to load a COMBINE archive or SED-ML file and translates it""" if action == 'c2p' or action == 'c2pwp' or action == 's2p' or action == 's2pwp': editorwindow = None #Used in editor.load processevents = True #Used in editor.load goto = None word = '' editor = self.main.editor editor0 = editor.get_current_editor() if editor0 is not None: position0 = editor0.get_position('cursor') filename0 = editor.get_current_filename() else: position0, filename0 = None, None # Recent files action raction = editor.sender() if isinstance(raction, QAction): filenames = from_qvariant(raction.data(), to_text_string) if not filenames: basedir = getcwd() if editor.edit_filetypes is None: editor.edit_filetypes = get_edit_filetypes() if editor.edit_filters is None: editor.edit_filters = get_edit_filters() c_fname = editor.get_current_filename() if c_fname is not None and c_fname != editor.TEMPFILE_PATH: basedir = os.path.dirname(c_fname) editor.redirect_stdio.emit(False) parent_widget = editor.get_current_editorstack() if filename0 is not None: selectedfilter = get_filter(editor.edit_filetypes, os.path.splitext(filename0)[1]) else: selectedfilter = '' if action == 'c2p' or action == 'c2pwp': filters = 'Combine archives (*.zip *.omex);;All files (*.*)' filenames, _selfilter = getopenfilenames( parent_widget, _("Open combine archive"), basedir, filters, selectedfilter=selectedfilter) else: filters = 'SED-ML files (*.sedml *.xml);;All files (*.*)' filenames, _selfilter = getopenfilenames( parent_widget, _("Open SED-ML file"), basedir, filters, selectedfilter=selectedfilter) editor.redirect_stdio.emit(True) if filenames: filenames = [ os.path.normpath(fname) for fname in filenames ] else: return focus_widget = QApplication.focusWidget() if editor.dockwidget and\ (not editor.dockwidget.isAncestorOf(focus_widget)\ and not isinstance(focus_widget, CodeEditor)): editor.dockwidget.setVisible(True) editor.dockwidget.setFocus() editor.dockwidget.raise_() def _convert(fname): fname = os.path.abspath(encoding.to_unicode_from_fs(fname)) if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':': fname = fname[0].upper() + fname[1:] return fname if hasattr(filenames, 'replaceInStrings'): # This is a QStringList instance (PyQt API #1), converting to list: filenames = list(filenames) if not isinstance(filenames, list): filenames = [_convert(filenames)] else: filenames = [_convert(fname) for fname in list(filenames)] if isinstance(goto, int): goto = [goto] elif goto is not None and len(goto) != len(filenames): goto = None for index, filename in enumerate(filenames): if action == 'c2p' or action == 'c2pwp': p = re.compile('(.zip$|.omex$)') pythonfile = p.sub('.py', filename) if (pythonfile == filename): pythonfile = filename + ".py" else: p = re.compile('(.xml$|.sedml$)') if action == 's2p': pythonfile = p.sub('_sedml.py', filename) if (pythonfile == filename): pythonfile = filename + "_sedml.py" else: pythonfile = p.sub('_phrasedml.py', filename) if (pythonfile == filename): pythonfile = filename + "_phrasedml.py" current_editor = editor.set_current_filename( pythonfile, editorwindow) if current_editor is None: # -- Not a valid filename: if not os.path.isfile(filename): continue # -- current_es = editor.get_current_editorstack(editorwindow) # Creating the editor widget in the first editorstack (the one # that can't be destroyed), then cloning this editor widget in # all other editorstacks: finfo, newname = self.load_and_translate( filename, pythonfile, editor, action) finfo.path = editor.main.get_spyder_pythonpath() editor._clone_file_everywhere(finfo) current_editor = current_es.set_current_filename(newname) current_es.analyze_script() if goto is not None: # 'word' is assumed to be None as well current_editor.go_to_line(goto[index], word=word) position = current_editor.get_position('cursor') editor.cursor_moved(filename0, position0, filename, position) if (current_editor is not None): current_editor.clearFocus() current_editor.setFocus() current_editor.window().raise_() if processevents: QApplication.processEvents()