def _save_as(self): """ Present a file dialog to the user and saves the content of the UI in XML format. """ if self._filename is not None: fname = self._filename else: fname = self._instrument + '_' fname = QFileDialog.getSaveFileName(self, "Reduction settings - Save settings", self._last_directory + '/' + fname, "Settings files (*.xml)") if not fname: return if isinstance(fname, tuple): fname = fname[0] fname = str(QFileInfo(fname).filePath()) if not fname.endswith('.xml'): fname += ".xml" if fname in self._recent_files: self._recent_files.remove(fname) self._recent_files.insert(0, fname) while len(self._recent_files) > 10: self._recent_files.pop() self._last_directory = QFileInfo(fname).path() self._filename = fname self._save()
def data_browse_dialog(self, data_type=None, title=None, multi=False): """ Pop up a file dialog box. @param data_type: string used to filter the files @param title: string to use as title @param multi: multiselection is enabled if True """ if data_type is None: data_type = self._data_type if title is None: title = "Data file - Choose a data file" if hasattr(QFileDialog, 'getOpenFileNamesAndFilter'): getOpenFileNames = QFileDialog.getOpenFileNamesAndFilter else: getOpenFileNames = QFileDialog.getOpenFileNames flist, _ = getOpenFileNames(self, title, self._settings.data_path, data_type) if not flist: return None if multi: flist = [QFileInfo(item).filePath() for item in flist] self._settings.data_path = flist[-1] else: if isinstance(flist, (tuple, list)): flist = flist[0] flist = QFileInfo(flist).filePath() self._settings.data_path = flist return flist
def load_file(path: str, *args, **kwargs) -> dict: with h5py.File(path, 'r') as hf: vertices = hf['vertices'][()] indices = hf['indices'][()] # Properties properties = dict(hf.attrs) # Data data = { 'vertices': vertices, 'indices': indices, } # Metadata metadata = { 'name': QFileInfo(path).completeBaseName(), 'extension': QFileInfo(path).suffix(), } return { 'data': data, 'properties': properties, 'metadata': metadata, }
def load_file(path: str, *args, **kwargs) -> dict: assert path.lower().endswith('out') # Data with open(path, 'r') as f: try: header_count, headers = GSLibParser.get_header_info(path) data = pd.read_csv(f, sep=' ', header=None, names=headers, skiprows=header_count + 2) except Exception: # This "GSLib" file doesn't have headers print( f'*** WARNING: We can read {path}, but keep in mind that this not a real GSLib file. ***' ) data = pd.read_csv(f, sep=' ', header=None, prefix='col_') # Properties properties = {} # Metadata metadata = { 'name': QFileInfo(path).completeBaseName(), 'extension': QFileInfo(path).suffix() } return { 'data': data, 'properties': properties, 'metadata': metadata, }
def rename(self): """renames the selected file or folder""" index = self.selectionModel().currentIndex() path = self.model.filePath(index) if path: file_info = QFileInfo(path) if file_info.isFile(): filename = self.rename_dialog("file") if filename: q_file = QFile(path) file_info.absolutePath() new_path = os.path.join(file_info.absolutePath(), str(filename)) q_file.rename(new_path) elif file_info.isDir(): filename = self.rename_dialog("directory") if filename: directory = QDir(path) file_info.absolutePath() new_path = os.path.join(file_info.absolutePath(), str(filename)) directory.rename(path, new_path)
def __init__(self, parent: MainWindowBase): super(ProjectWidget, self).__init__(parent) self.setupUi(self) # Undo view self.command_stack = parent.command_stack undo_view = QUndoView(self.command_stack) undo_view.setEmptyLabel("~Start Pyslvs") w = QWidget(self) layout = QVBoxLayout(w) layout.addWidget(undo_view) history_icon = QIcon(QPixmap(":/icons/history.png")) self.history_tabs.addTab(w, history_icon, "Mechanism") # Settings self.prefer = parent.prefer # Check project saved function self.project_saved = parent.project_saved # Open file dialog self.input_from = parent.input_from # Parse function self.parse_expression = parent.parse_expression # Call to load inputs variables data self.load_inputs = parent.inputs_widget.add_inputs_variables # Clear function for main window self.main_clear = parent.clear # Environment path self.env_path = parent.env_path self.overview_button.clicked.connect(parent.show_overview) self.ex_expression_button.clicked.connect(parent.show_expr) self.ex_dxf_button.clicked.connect(parent.export_dxf) self.ex_slvs_button.clicked.connect(parent.export_slvs) self.ex_pmks_button.clicked.connect(parent.save_pmks) self.ex_py_button.clicked.connect(parent.py_script) self.ex_image_button.clicked.connect(parent.export_image) self.ex_capture_button.clicked.connect(parent.save_picture_clipboard) self.im_pmks_button.clicked.connect(parent.import_pmks_url) self.im_example_button.clicked.connect( lambda: self.load_example(is_import=True)) self.background_option.textChanged.connect( parent.main_canvas.set_background) self.background_opacity_option.valueChanged.connect( parent.main_canvas.set_background_opacity) self.background_x_option.valueChanged.connect( parent.main_canvas.set_background_offset_x) self.background_y_option.valueChanged.connect( parent.main_canvas.set_background_offset_y) self.background_scale_option.valueChanged.connect( parent.main_canvas.set_background_scale) # Editors self.yaml_editor = YamlEditor(self, parent) self.hdf5_editor = HDF5Editor(self, parent) self.pickle_editor = PickleEditor(self, parent) # Reset self.__file_name = QFileInfo() self.__changed = False self.reset()
def accept(self): path = self.selectedFiles()[0] stats = QFileInfo(path) if stats.isDir(): self.setDirectory(path) return if not stats.exists(): return loadProgram(path) self.hide()
def openLocation(self, index): path = self.model.filePath(self.rootIndex()) name = self.model.filePath(index) absolute_path = os.path.join(path, name) file_info = QFileInfo(absolute_path) if file_info.isDir(): self.model.setRootPath(absolute_path) self.setRootIndex(self.model.index(absolute_path)) self.rootChanged.emit(absolute_path)
def transferFile(self, src_path): dest_path = self.model.filePath(self.rootIndex()) src_file = QFile() src_file.setFileName(src_path) src_file_info = QFileInfo(src_path) dst_path = os.path.join(dest_path, src_file_info.fileName()) src_file.copy(dst_path)
def openModel(self, fileName): print(f'Otwieram: {fileName}') self.__m_vtkFboItem.addModel(fileName) localFilePath = QUrl(fileName).toLocalFile() currentDir = QFileInfo(localFilePath).absoluteDir() currentPath = currentDir.absolutePath() MySettings = QSettings() MySettings.setValue(CanvasHandler.DEFAULT_MODEL_DIR_KEY, currentPath) print(currentPath)
def set_background_config(self, config: Dict[str, Union[str, float]]) -> None: """Set background config by dict object.""" env = self.__file_name.absoluteDir() file = QFileInfo(env, config.get('background', "")) path = file.absoluteFilePath() self.background_option.setText(path if file.isFile() else "") self.background_x_option.setValue(config.get('background_x', 0.)) self.background_y_option.setValue(config.get('background_y', 0.)) self.background_scale_option.setValue( config.get('background_scale', 1.)) self.background_opacity_option.setValue( config.get('background_opacity', 1.))
def viewParentDirectory(self): """View the parent directory of the current view.""" path = self.model.filePath(self.rootIndex()) file_info = QFileInfo(path) directory = file_info.dir() new_path = directory.absolutePath() currentRoot = self.rootIndex() self.model.setRootPath(new_path) self.setRootIndex(currentRoot.parent()) self.rootChanged.emit(new_path)
def _save_result(self): """ Save the scaled output in one combined I(Q) file """ if self._stitcher is not None: if not os.path.isdir(self._output_dir): self._output_dir = os.path.expanduser("~") fname = QFileDialog.getSaveFileName(self, "Save combined I(Q)", self._output_dir, "Data Files (*.xml)") if not fname: return if isinstance(fname, tuple): fname = fname[0] fname = str(QFileInfo(fname).filePath()) if len(fname) > 0: if fname.endswith('.xml'): self._stitcher.save_combined(fname, as_canSAS=True) elif fname.endswith('.txt'): self._stitcher.save_combined(fname, as_canSAS=False) else: fname_tmp = fname + ".xml" self._stitcher.save_combined(fname_tmp, as_canSAS=True) fname_tmp = fname + ".txt" self._stitcher.save_combined(fname_tmp, as_canSAS=False)
def _file_open(self, *argv): """ File chooser for loading UI parameters """ fname = QFileDialog.getOpenFileName(self, "Reduction settings - Choose a settings file", self._last_directory, "Settings files (*.xml)") if not fname: return if isinstance(fname, tuple): fname = fname[0] fname = str(QFileInfo(fname).filePath()) # Store the location of the loaded file self._last_directory = str(QFileInfo(fname).path()) self.open_file(fname)
def __load_file(self, file_name: str = "") -> None: """Load a supported format in Pyslvs.""" if self.check_file_changed(): return if not file_name: file_name = self.input_from("project", [ "Pyslvs project (*.pyslvs)", "Solvespace 2.x-3.x (*.slvs)", ]) if not file_name: return suffix = QFileInfo(file_name).suffix().lower() if suffix == 'pyslvs': self.project_widget.read(file_name) elif suffix == 'slvs': self.__read_slvs(file_name) else: QMessageBox.warning(self, "Invalid file suffix", "Only support '*.pyslvs' or '*.slvs'.") return self.project_saved() self.main_canvas.zoom_to_fit()
def dropEvent(self, event, *args, **kwargs) -> None: for url in event.mimeData().urls(): path = url.toLocalFile() if QFileInfo(path).isDir(): self.load_folder(path, self.load_mesh) else: self.load_mesh(path)
def input_from(self, format_name: str, format_choose: Sequence[str]) -> str: """Get external file name.""" file_name, suffix = QFileDialog.getOpenFileName( self, f"Open {format_name}", self.env, ';;'.join(format_choose)) if file_name: self.set_locate(QFileInfo(file_name).absolutePath()) return file_name
def dropEvent(self, event: QDropEvent) -> None: """Drop file in to our window.""" file = event.mimeData().urls()[0].toLocalFile() if QFileInfo(file).suffix().lower() in set(qt_image_suffix): self.project_widget.set_background_config({'background': file}) else: self.__load_file(file) event.acceptProposedAction()
def save_reply_box(self, title: str, file_name: str) -> None: """Show message when successfully saved.""" size = size_format(QFileInfo(file_name).size()) QMessageBox.information( self, f"Initial Saved: {title}", f"Successfully saved:\n{file_name}\n" f"Size: {size}") logger.info(f"Saved: [\"{file_name}\"] ({size})")
def saveAs(self): file_name = self.save_as_dialog(self.filename) if file_name is False: return original_file = QFileInfo(self.filename) path = original_file.path() new_absolute_path = os.path.join(path, file_name) new_file = QFile(new_absolute_path) result = new_file.open(QFile.WriteOnly) if result: save_stream = QTextStream(new_file) save_stream << self.text() new_file.close()
def deleteItem(self): """Delete the selected item (either a file or folder).""" # ToDo: use Move2Trash, instead of deleting the file index = self.selectionModel().currentIndex() path = self.model.filePath(index) if path: file_info = QFileInfo(path) if file_info.isFile(): if not self.ask_dialog("Do you wan't to delete the selected file?"): return q_file = QFile(path) q_file.remove() elif file_info.isDir(): if not self.ask_dialog("Do you wan't to delete the selected directory?"): return directory = QDir(path) directory.removeRecursively()
def data_browse_dialog(self): """ Pop up a file dialog box. """ title = "Data file - Choose a reduced I(Q) file" if not os.path.isdir(str(self._output_dir)): self._output_dir = os.path.expanduser("~") FileName = QFileDialog.getOpenFileName(self, title, self._output_dir, "Reduced txt files (*.txt);; All files (*)") if isinstance(FileName,tuple): FileName = FileName[0] fname = QFileInfo(FileName).filePath() if fname: if isinstance(fname, tuple): fname = fname[0] # Store the location of the loaded file self._output_dir = str(QFileInfo(fname).path()) return str(fname)
def input_from_multiple(self, format_name: str, format_choose: Sequence[str]) -> List[str]: """Get external file names.""" file_names, suffix = QFileDialog.getOpenFileNames( self, f"Open {format_name} files ...", self.env, ';;'.join(format_choose)) if file_names: self.set_locate(QFileInfo(file_names[0]).absolutePath()) return file_names
def dragEnterEvent(self, event: QDragEnterEvent) -> None: """Drag file in to our window.""" mime_data: QMimeData = event.mimeData() if not mime_data.hasUrls(): return urls = mime_data.urls() if len(urls) == 1: suffix = QFileInfo(urls[0].toLocalFile()).suffix().lower() if suffix in {'yml', 'pyslvs', 'slvs'} | set(qt_image_suffix): event.acceptProposedAction()
def set_file_name(self, file_name: str, *, is_example: bool = False) -> None: """Set file name.""" self.__file_name = QFileInfo(file_name) self.file_name_label.setText(self.__file_name.fileName()) self.path_label.setText(self.__file_name.absolutePath()) self.owner_label.setText(self.__file_name.owner()) time: QDateTime = self.__file_name.lastModified() self.last_modified_label.setText(time.toString()) self.file_size_label.setText(size_format(self.__file_name.size())) if is_example: t = "Example (In memory)" elif self.file_exist(): t = f"File ({PROJECT_FORMAT[self.prefer.file_type_option]})" else: t = "In memory" self.type_label.setText(t)
def get_paths_from_directory(path: str) -> list: it = QDirIterator(path, QDirIterator.Subdirectories) path_list = [] while it.hasNext(): next_path = it.next() if QFileInfo(next_path).isFile(): path_list.append(next_path) return sorted(path_list)
def load_from_args(self) -> None: if not ARGUMENTS.filepath: return suffix = QFileInfo(ARGUMENTS.filepath).suffix().lower() if suffix == 'pyslvs': self.project_widget.read(ARGUMENTS.filepath) elif suffix == 'slvs': self.__read_slvs(ARGUMENTS.filepath) else: QMessageBox.warning(self, "Invalid file suffix", "Only support '*.pyslvs' or '*.slvs'.")
def load_file(path: str, *args, **kwargs) -> dict: assert path.lower().endswith('csv') # Data with open(path, 'r') as f: data = pd.read_csv(f) # Properties properties = {} # Metadata metadata = { 'name': QFileInfo(path).completeBaseName(), 'extension': QFileInfo(path).suffix() } return { 'data': data, 'properties': properties, 'metadata': metadata, }
def saveAs(self): file_name = self.save_as_dialog(self.filename) if file_name is False: print("saveAs file name error") return self.filename = str(STATUS.file) original_file = QFileInfo(self.filename) path = original_file.path() new_absolute_path = os.path.join(path, file_name) new_file = QFile(new_absolute_path) result = new_file.open(QFile.WriteOnly) if result: save_stream = QTextStream(new_file) save_stream << self.text() new_file.close() self.text_before_edit = '' self.somethingHasChanged.emit(False)
def input_from(self, format_name: str, format_choose: Sequence[str], multiple: bool = False) -> Union[str, List[str]]: """Get file name(s).""" if multiple: func = QFileDialog.getOpenFileNames else: func = QFileDialog.getOpenFileName file_names: Union[str, List[str]] file_names, suffix = func( self, f"Open {format_name} file{'s' if multiple else ''}...", self.env, ';;'.join(format_choose)) if file_names: if type(file_names) is str: self.set_locate(QFileInfo(file_names).absolutePath()) else: self.set_locate(QFileInfo(file_names[0]).absolutePath()) suffix = str_between(suffix, '(', ')').split('*')[-1] logger.debug(f"Format: {suffix}") return file_names
def _store_previous_directory(self, settings, path): previous_file = QFileInfo(path) settings.setValue("InPath", previous_file.absoluteDir().absolutePath())