def __open_or_create_test_file(self, style): if self.__cur_po_class: folder = self.GetTopLevelParent().get_root_folder() if not folder: folder = os.path.dirname(self.__cur_po_class.file_path) elif RootFolder.TESTS_FOLDER in os.listdir(folder): folder = os.path.join(folder, RootFolder.TESTS_FOLDER) dialog = FileDialog(self, defaultDir=folder, style=style, wildcard='*.py') if dialog.ShowModal() == ID_OK: test_file = dialog.GetPath() load_file = style == FD_OPEN filename = os.path.basename(test_file) if StringUtils.is_test_file_name_correct(test_file): test_file_ui = TestFileUI(self.tabs, test_file, self.__cur_po_class, load_file) self.tabs.AddPage(test_file_ui, filename) self.tabs.SetSelection(self.tabs.GetPageCount() - 1) if style == FD_SAVE: test_file_ui.set_file_was_changed() else: show_dialog_bad_name(self, filename, 'my_first_test.py') else: show_dialog(self, u'Please select class file.', u'Class file was not opened')
def choose_file(parent, message, d=None): folder = FileDialog(parent, message=message, defaultFile='sample.txt', style=FD_SAVE) if folder.ShowModal() == ID_OK: return folder.GetPath()
def __open_class(self, evt): folder = self.GetTopLevelParent().get_root_folder() if folder: if RootFolder.PO_FOLDER in os.listdir(folder): folder = os.path.join(folder, RootFolder.PO_FOLDER) dialog = FileDialog(self, defaultDir=folder, wildcard=u'*.py') if dialog.ShowModal() == ID_OK: self.__load_po_class(dialog.GetPath()) else: show_dialog_path_doesnt_exist(self, folder)
def getFilePath(wildcard, title): app = App(None) style = FD_OPEN | FD_FILE_MUST_EXIST dialog = FileDialog(None, title, wildcard=wildcard, style=style) if dialog.ShowModal() == ID_OK: path = dialog.GetPath() else: path = None dialog.Destroy() return path
def __load_tests_from_files(self, evt): folder = self.__get_safe_path_from_root_folder(RootFolder.TESTS_FOLDER) if folder: dialog = FileDialog(self, defaultDir=folder, style=FD_OPEN | FD_FILE_MUST_EXIST | FD_MULTIPLE, wildcard=u'*.py') if dialog.ShowModal() == ID_OK: self.__load_tests_to_tree(file_paths=dialog.GetPaths()) else: show_dialog_path_doesnt_exist(self, folder)
def OnSave(self, event): file_choices = "PNG (*.png)|*.png" dlg = FileDialog(self, message="Zapisz wykres jako...", defaultDir=getcwd(), defaultFile="plot.png", wildcard=file_choices, style=SAVE) if dlg.ShowModal() == ID_OK: path = dlg.GetPath() self.canvas.print_figure(path, dpi=100)
class SaveAsMenuItem(CustomNormalMenuItemBase): """Menu item to save an unsaved project """ def __init__(self): """Default constructor """ super().__init__(SAVE_AS_MENU_ITEM, '') def Function(self) -> bool: """save an unsaved project :return: Whether the project has been saved or not. :rtype: bool """ project_mgr = self.Get(PROJECT_MANAGER) project = project_mgr.GetProject() if (path := project.GetPath()) == '': path = project_mgr.GetDefaultProjectPath() dir_path = project.GetDirectory() file_name = project.GetFileName() with FileDialog(parent=None, defaultDir=dir_path, defaultFile=file_name, wildcard=SAVEFILE_WILDCARD, style=FD_SAVE) as dialog: if dialog.ShowModal() == ID_CANCEL: return False path = dialog.GetPath() project.SetPath(path) project_mgr.SaveProject(project) return True
def onFileInsertProject(self, event: CommandEvent): """ Insert a project into this one Args: event: """ PyutUtils.displayWarning(_("The project insert is experimental, " "use it at your own risk.\n" "You risk a shapes ID duplicate with " "unexpected results !"), parent=self) if (self._treeNotebookHandler.getCurrentProject()) is None: PyutUtils.displayError(_("No project to insert this file into !")) return # Ask which project to insert defaultDirectory: str = self._currentDirectoryHandler.currentDirectory dlg = FileDialog(self._parent, _("Choose a project"), defaultDirectory, "", "*.put", FD_OPEN) if dlg.ShowModal() != ID_OK: dlg.Destroy() return False self._currentDirectoryHandler.currentDirectory = dlg.GetPath() filename = dlg.GetPath() dlg.Destroy() self.logger.warning(f'inserting file: {filename}') # Insert the specified files try: self._treeNotebookHandler.insertFile(filename) except (ValueError, Exception) as e: PyutUtils.displayError(_(f"An error occurred while loading the project! {e}"))
def __on_select_file(self, evt): folder = self.__get_safe_path_from_root_folder(RootFolder.REPORTS) obj = evt.GetEventObject() txt_ctrl = None if obj == self.btn_select_html: wildcard = u'*.html' txt_ctrl = self.txt_html_report elif obj == self.btn_select_xml: wildcard = u'*.xml' txt_ctrl = self.txt_xml_report else: wildcard = u'*.*' dialog = FileDialog(self, defaultDir=folder, style=FD_SAVE | FD_OVERWRITE_PROMPT, wildcard=wildcard) if dialog.ShowModal() == ID_OK and txt_ctrl: txt_ctrl.SetValue(dialog.GetPath())
def OnAdd(self, event): ''' dialog = AddDialog("Add Option", None) if dialog.ShowModal() == wx.ID_OK: print dialog.GetOption() self.listCtrl.AppendAndEnsureVisible(dialog.GetOption()) ''' wildcard = "All Files (*.*) | *.* |" \ "source (*.py) | *.py |" \ "Doc Files (*.doc) | *.doc" dialog = FileDialog(self, "Attach files", os.getcwd(), "", "*.*", FileDialog.OPEN | FileDialog.MULTIPLE) if dialog.ShowModal() == wx.ID_OK: fullList = dialog.GetPaths() self.attachments.copy(fullList) for item in self.attachments.GetFilenames(): self.listCtrl.Append(item) dialog.Destroy()
def Function(self): """loading an existing project """ with FileDialog(None, wildcard=SAVEFILE_WILDCARD, style=FD_OPEN | FD_FILE_MUST_EXIST) as dialog: if dialog.ShowModal() == ID_CANCEL: return path = dialog.GetPath() self.Get(PROJECT_MANAGER).OpenProject(path)
def file_dialog(self, style=None): """Opens a dialog to find a file""" with FileDialog( None, 'Choose a file', dirname(self.config.active_file), wildcard='Rasi files (*.rasi)|*.rasi|All Files (*.*)|*.*', style=style) as dialog: if ID_OK == dialog.ShowModal(): return dialog.GetPath() return None
def button_callback(self, event): """ Receive selection event after files are selected, and pass to callback function :param event: Event contains directory and files :return: None """ with FileDialog(self, self._text_title, "", "", wildcard=self._text_open_file + '(' + self._file_type + ')|' + self._file_type, style=FD_OPEN | FD_FILE_MUST_EXIST | FD_MULTIPLE) as dialog: if dialog.ShowModal() == ID_CANCEL: return # the user changed their mind path = dialog.Directory files = dialog.Filenames if self._reset: self._text_input.SetValue("") else: self._text_input.SetValue(path) self._callback(path=path, files=files)
def _onFileSelectClick(self, event: CommandEvent): self.logger.warning(f'File Select Click') wxYield() fmtSelIdx: int = self._imageFormatChoice.GetCurrentSelection() outputFormat: str = self._imageFormatChoice.GetString(fmtSelIdx) dlg: FileDialog = FileDialog(self, message='Choose the export file name', defaultFile='PyutExport', style=FD_SAVE | FD_OVERWRITE_PROMPT | FD_CHANGE_DIR) if dlg.ShowModal() == ID_OK: wxYield() path: str = dlg.GetPath() fileName: str = dlg.GetFilename() self._selectedFile.SetValue(fileName) # for simple viewing self._selectedFile.SetModified(True) self._imageOptions.outputFileName = path # for actual us dlg.Destroy()
def _loadFile(self, filename=""): """ Load the specified filename Args: filename: Its name """ # Make a list to be compatible with multi-files loading fileNames = [filename] # Ask which filename to load ? if filename == "": dlg = FileDialog(self, _("Choose a file"), self._lastDir, "", "*.put", FD_OPEN | FD_MULTIPLE) if dlg.ShowModal() != ID_OK: dlg.Destroy() return False self.updateCurrentDir(dlg.GetPath()) fileNames = dlg.GetPaths() dlg.Destroy() self.logger.info(f"loading file(s) {filename}") # Open the specified files for filename in fileNames: try: if self._mainFileHandlingUI.openFile(filename): # Add to last opened files list self._prefs.addNewLastOpenedFilesEntry(filename) self.__setLastOpenedFilesItems() self._ctrl.updateTitle() except (ValueError, Exception) as e: PyutUtils.displayError( _("An error occurred while loading the project !"), parent=self) self.logger.error(f'{e}')
def _askForFileImport(self, multiSelect: bool = False, startDirectory: str = None): """ Called by plugin to ask which file must be imported Args: multiSelect: True to allow multi-file selection Returns: filename or "" for multiple=False, fileNames[] or [] else "", [] indicates that the user pressed the cancel button """ inputFormat: PyutPlugin.INPUT_FORMAT_TYPE = self.getInputFormat() defaultDir: str = startDirectory if defaultDir is None: defaultDir = self._ctrl.getCurrentDir() if multiSelect: dlg = FileDialog(self._umlFrame, "Choose files to import", wildcard=inputFormat[0] + " (*." + inputFormat[1] + ")|*." + inputFormat[1], defaultDir=defaultDir, style=FD_OPEN | FD_FILE_MUST_EXIST | FD_MULTIPLE | FD_CHANGE_DIR) dlg.ShowModal() if dlg.GetReturnCode() == ID_CANCEL: return [], "" return dlg.GetFilenames(), dlg.GetDirectory() else: file = FileSelector("Choose a file to import", wildcard=inputFormat[0] + " (*." + inputFormat[1] + ")|*." + inputFormat[1], flags=FD_OPEN | FD_FILE_MUST_EXIST | FD_CHANGE_DIR) return file
def _OnMnuFileInsertProject(self, event: CommandEvent): """ Insert a project into this one Args: event: """ PyutUtils.displayWarning(_("The project insert is experimental, " "use it at your own risk.\n" "You risk a shapes ID duplicate with " "unexpected results !"), parent=self) if (self._mainFileHandlingUI.getCurrentProject()) is None: PyutUtils.displayError(_("No project to insert this file into !"), parent=self) return # Ask which project to insert dlg = FileDialog(self, _("Choose a file"), self._lastDir, "", "*.put", FD_OPEN) if dlg.ShowModal() != ID_OK: dlg.Destroy() return False self.updateCurrentDir(dlg.GetPath()) filename = dlg.GetPath() dlg.Destroy() print(("inserting file", str(filename))) # Insert the specified files try: self._mainFileHandlingUI.insertFile(filename) except (ValueError, Exception) as e: PyutUtils.displayError( _(f"An error occurred while loading the project! {e}"), parent=self)
def loadFile(self, filename: str = ""): """ Load the specified filename; This is externally available so that we can open a file from the command line Args: filename: Its name """ # Make a list to be compatible with multi-files loading fileNames = [filename] currentDir: str = self._mediator.getCurrentDir() # TODO This is bad practice to do something different based on input if filename == "": dlg = FileDialog(self._parent, _("Choose a file"), currentDir, "", "*.put", FD_OPEN | FD_MULTIPLE) if dlg.ShowModal() != ID_OK: dlg.Destroy() return False fileNames = dlg.GetPaths() self._currentDirectoryHandler.currentDirectory = fileNames[0] dlg.Destroy() self.logger.info(f"loading file(s) {filename}") # Open the specified files for filename in fileNames: try: if self._treeNotebookHandler.openFile(filename): # Add to last opened files list self._preferences.addNewLastOpenedFilesEntry(filename) self.setLastOpenedFilesItems() self._mediator.updateTitle() except (ValueError, Exception) as e: PyutUtils.displayError(_("An error occurred while loading the project !")) self.logger.error(f'{e}')
def doAction(self, umlObjects: List[OglClass], selectedObjects: List[OglClass], umlFrame: UmlFrame): """ Args: umlObjects: list of the uml objects of the diagram selectedObjects: list of the selected objects umlFrame: The diagram frame """ if umlFrame is None: self.displayNoUmlFrame() return ctrl = getMediator() project = ctrl.getFileHandling().getProjectFromFrame(umlFrame) if project.getCodePath() == "": dlg = DirDialog(None, _("Choose the root directory for the code"), getcwd()) if dlg.ShowModal() == ID_OK: codeDir = dlg.GetPath() self.logger.info(f"Chosen directory is {codeDir}") umlFrame.setCodePath(codeDir) dlg.Destroy() else: return oglClasses = [x for x in selectedObjects if isinstance(x, OglClass)] if len(oglClasses) == 0: self.logger.info("Nothing selected") return oldDir = getcwd() chdir(project.getCodePath()) sysPath.append(getcwd()) # plug = IoPython(None, None) plug = IoPython(cast(OglObject, None), cast(UmlFrame, None)) normalDir = getcwd() for oglClass in oglClasses: pyutClass = oglClass.getPyutObject() filename = pyutClass.getFilename() if filename == "": dlg = FileDialog(None, _("Choose the file for this UML class"), project.getCodePath(), "", "*.py", FD_OPEN) if dlg.ShowModal() != ID_OK: dlg.Destroy() continue filename = dlg.GetPaths()[0] self.logger.info(f"Chosen filename is {filename}") pyutClass.setFilename(filename) dlg.Destroy() modulename = filename[:-3] # remove ".py" try: # normalDir = getcwd() path, name = osPath.split(osPath.abspath(modulename)) chdir(path) module = __import__(name) importlib.reload(module) chdir(normalDir) except ImportError as ie: self.logger.error( f"Error while trying to import module '{str(modulename)}' --- '{ie}'" ) chdir(normalDir) continue orgClass = module.__dict__[pyutClass.getName()] plug.getPyutClass(orgClass, filename, pyutClass) oglClass.autoResize() chdir(oldDir)
def saveFileAs(self): """ Ask for a filename and save the diagram data Returns: `True` if the save succeeds else `False` """ if self._mediator.isInScriptMode(): PyutUtils.displayError(_("Save File As is not accessible in script mode !")) return # Test if no diagram exists if self._mediator.getDiagram() is None: PyutUtils.displayError(_("No diagram to save !"), _("Error")) return # Ask for filename filenameOK = False # TODO revisit this to figure out how to get rid of Pycharm warning 'dlg referenced before assignment' # Bad thing is dlg can be either a FileDialog or a MessageDialog dlg: DialogType = cast(DialogType, None) while not filenameOK: dlg = FileDialog(self.__parent, defaultDir=self.__parent.getCurrentDir(), wildcard=_("Pyut file (*.put)|*.put"), style=FD_SAVE | FD_OVERWRITE_PROMPT) # Return False if canceled if dlg.ShowModal() != ID_OK: dlg.Destroy() return False # Find if a specified filename is already opened filename = dlg.GetPath() if len([project for project in self._projects if project.getFilename() == filename]) > 0: dlg = MessageDialog(self.__parent, _("Error ! The filename '%s" + "' correspond to a project which is currently opened !" + " Please choose another filename !") % str(filename), _("Save change, filename error"), OK | ICON_ERROR) dlg.ShowModal() dlg.Destroy() return filenameOK = True project = self._currentProject project.setFilename(dlg.GetPath()) project.saveXmlPyut() # Modify notebook text for i in range(self.__notebook.GetPageCount()): frame = self.__notebook.GetPage(i) document = [document for document in project.getDocuments() if document.getFrame() is frame] if len(document) > 0: document = document[0] if frame in project.getFrames(): diagramTitle: str = document.getTitle() shortName: str = self.shortenNotebookPageFileName(diagramTitle) self.__notebook.SetPageText(i, shortName) else: self.logger.info("Not updating notebook in FileHandling") self.__parent.updateCurrentDir(dlg.GetPath()) project.setModified(False) dlg.Destroy() return True