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 insertFile(self, filename): """ Insert a file in the current project Args: filename: filename of the project to insert """ # Get current project project = self._currentProject # Save number of initial documents nbInitialDocuments = len(project.getDocuments()) # Load data... if not project.insertProject(filename): PyutUtils.displayError(_("The specified file can't be loaded !")) return False # ... if not self._mediator.isInScriptMode(): try: for document in project.getDocuments()[nbInitialDocuments:]: self.__notebook.AddPage(document.getFrame(), document.getFullyQualifiedName()) self.__notebookCurrentPage = self.__notebook.GetPageCount()-1 self.__notebook.SetSelection(self.__notebookCurrentPage) except (ValueError, Exception) as e: PyutUtils.displayError(_(f"An error occurred while adding the project to the notebook {e}")) return False # Select first frame as current frame if len(project.getDocuments()) > nbInitialDocuments: self._frame = project.getDocuments()[nbInitialDocuments].getFrame()
def onToolPlugin(self, event: CommandEvent): """ Args: event: """ # Create a plugin instance wxId: int = event.GetId() self.logger.warning(f'{wxId=}') clazz: type = self._toolPluginsMap[wxId] pluginInstance: PyutToPlugin = clazz(self._mediator.getUmlObjects(), self._mediator.getUmlFrame()) # Do plugin functionality BeginBusyCursor() try: pluginInstance.callDoAction() self.logger.debug(f"After tool plugin do action") except (ValueError, Exception) as e: PyutUtils.displayError( _("An error occurred while executing the selected plugin"), _("Error...")) self.logger.error(f'{e}') EndBusyCursor() # Refresh screen umlFrame = self._mediator.getUmlFrame() if umlFrame is not None: umlFrame.Refresh()
def OnToolPlugin(self, event: CommandEvent): """ Args: event: """ # Create a plugin instance cl = self.plugins[event.GetId()] obj = cl(self._ctrl.getUmlObjects(), self._ctrl.getUmlFrame()) # Do plugin functionality BeginBusyCursor() try: obj.callDoAction() self.logger.debug(f"After tool plugin do action") except (ValueError, Exception) as e: PyutUtils.displayError( _("An error occurred while executing the selected plugin"), _("Error..."), self) self.logger.error(f'{e}') EndBusyCursor() # Refresh screen umlFrame = self._ctrl.getUmlFrame() if umlFrame is not None: umlFrame.Refresh()
def insertProject(self, filename: str) -> bool: """ Insert another project into this one Args: filename: filename to open Returns: `True` if the operation succeeded """ # Load the file from org.pyut.persistence import IoFile BeginBusyCursor() io = IoFile.IoFile() try: io.open(filename, self) self._modified = False except (ValueError, Exception) as e: PyutUtils.displayError(_(f"Error loading file {e}")) EndBusyCursor() return False EndBusyCursor() # Update text self.updateTreeText() # Register to mediator if len(self._documents) > 0: frame = self._documents[0].getFrame() self._mediator.getFileHandling().registerUmlFrame(frame) # Return return True
def open(self, dom: Document, project: PyutProject): """ Open a file and create a diagram. Args: dom: The minidom document project: The UI Project to fill out """ self.__setupProgressDialog() umlFrame: UmlDiagramsFrame = cast(UmlDiagramsFrame, None) # avoid Pycharm warning root = self.__validateXmlVersion(dom) try: project.setCodePath(root.getAttribute("CodePath")) self.__updateProgressDialog(newMessage='Reading elements...', newGaugeValue=1) wxYield() toOgl: MiniDomToOglV10 = MiniDomToOglV10() for documentNode in dom.getElementsByTagName( PyutXmlConstants.ELEMENT_DOCUMENT): documentNode: Element = cast(Element, documentNode) docTypeStr: str = documentNode.getAttribute( PyutXmlConstants.ATTR_TYPE) self.__updateProgressDialog( newMessage= f'Determine Title for document type: {docTypeStr}', newGaugeValue=2) wxYield() docType: DiagramType = PyutConstants.diagramTypeFromString( docTypeStr) document: PyutDocument = project.newDocument(docType) document.title = self.__determineDocumentTitle(documentNode) umlFrame: UmlDiagramsFrame = self.__showAppropriateUmlFrame( document) self.__positionAndSetupDiagramFrame(umlFrame=umlFrame, documentNode=documentNode) self.__updateProgressDialog(newMessage='Start Conversion...', newGaugeValue=3) if docType == DiagramType.CLASS_DIAGRAM: self.__renderClassDiagram(documentNode, toOgl, umlFrame) elif docType == DiagramType.USECASE_DIAGRAM: self.__renderUseCaseDiagram(documentNode, toOgl, umlFrame) elif docType == DiagramType.SEQUENCE_DIAGRAM: self.__renderSequenceDiagram(documentNode, toOgl, umlFrame) self.__updateProgressDialog( newMessage='Conversion Complete...', newGaugeValue=4) except (ValueError, Exception) as e: self._dlgGauge.Destroy() PyutUtils.displayError(_(f"Can not load file {e}")) umlFrame.Refresh() return self.__cleanupProgressDialog(umlFrame)
def save(self, project): """ Aave diagram in XML file. @param project @author Deve Roux @modified Laurent Burgbacher <*****@*****.**> : add version support @modified C.Dutoit 20021122 : added document container tag """ dlg: Dialog = Dialog(None, -1, "Saving...", style=STAY_ON_TOP | ICON_INFORMATION | RESIZE_BORDER, size=Size(207, 70)) xmlDoc: Document = Document() try: # xmlDoc: Document = Document() top = xmlDoc.createElement("PyutProject") top.setAttribute('version', str(self._this_version)) top.setAttribute('CodePath', project.getCodePath()) xmlDoc.appendChild(top) # dlg = Dialog(None, -1, "Saving...", style=STAY_ON_TOP | ICON_INFORMATION | RESIZE_BORDER, size=Size(207, 70)) gauge = Gauge(dlg, -1, 100, pos=Point(2, 5), size=Size(200, 30)) dlg.Show(True) # Save all documents in the project for document in project.getDocuments(): documentNode = xmlDoc.createElement("PyutDocument") documentNode.setAttribute('type', PyutConstants.diagramTypeAsString(document.getType())) top.appendChild(documentNode) oglObjects = document.getFrame().getUmlObjects() for i in range(len(oglObjects)): gauge.SetValue(i * 100 / len(oglObjects)) oglObject = oglObjects[i] if isinstance(oglObject, OglClass): documentNode.appendChild(self._OglClass2xml(oglObject, xmlDoc)) elif isinstance(oglObject, OglNote): documentNode.appendChild(self._OglNote2xml(oglObject, xmlDoc)) elif isinstance(oglObject, OglActor): documentNode.appendChild(self._OglActor2xml(oglObject, xmlDoc)) elif isinstance(oglObject, OglUseCase): documentNode.appendChild(self._OglUseCase2xml(oglObject, xmlDoc)) elif isinstance(oglObject, OglLink): documentNode.appendChild(self._OglLink2xml(oglObject, xmlDoc)) elif isinstance(oglObject, OglSDInstance): documentNode.appendChild(self._OglSDInstance2xml(oglObject, xmlDoc)) elif isinstance(oglObject, OglSDMessage): documentNode.appendChild(self._OglSDMessage2xml(oglObject, xmlDoc)) except (ValueError, Exception) as e: try: dlg.Destroy() self.logger.error(f'{e}') except (ValueError, Exception) as e: self.logger.error(f'{e}') PyutUtils.displayError(_("Can't save file")) return xmlDoc dlg.Destroy() return xmlDoc
def closeCurrentProject(self): """ Close the current project Returns: True if everything is ok """ if self._currentProject is None and self._currentFrame is not None: self._currentProject = self.getProjectFromFrame(self._currentFrame) if self._currentProject is None: PyutUtils.displayError(_("No frame to close !"), _("Error...")) return False # Display warning if we are in scripting mode if self._mediator.isInScriptMode(): self.logger.warning( "WARNING : in script mode, the non-saved projects are closed without warning" ) # Close the file if self._currentProject.getModified( ) is True and not self._mediator.isInScriptMode(): frame = self._currentProject.getFrames()[0] frame.SetFocus() self.showFrame(frame) dlg = MessageDialog( self.__parent, _("Your project has not been saved. " "Would you like to save it ?"), _("Save changes ?"), YES_NO | ICON_QUESTION) if dlg.ShowModal() == ID_YES: if self.saveFile() is False: return False # Remove the frame in the notebook if not self._mediator.isInScriptMode(): pages = list(range(self.__notebook.GetPageCount())) pages.reverse() for i in pages: pageFrame = self.__notebook.GetPage(i) if pageFrame in self._currentProject.getFrames(): self.__notebook.DeletePage(i) self._currentProject.removeFromTree() self._projects.remove(self._currentProject) self.logger.debug(f'{self._currentProject.getFilename()=}') self._currentProject = None self._currentFrame = None nbrProjects: int = len(self._projects) self.logger.debug(f'{nbrProjects=}') if nbrProjects > 0: self.__updateTreeNotebookIfPossible(project=self._projects[0]) self._mediator.updateTitle() return True
def saveXmlPyut(self): """ save the project """ from org.pyut.persistence.IoFile import IoFile io: IoFile = IoFile() BeginBusyCursor() try: io.save(self) self._modified = False self.updateTreeText() except (ValueError, Exception) as e: PyutUtils.displayError(_(f"An error occurred while saving project {e}")) EndBusyCursor()
def _OnMnuSelectAll(self, event: CommandEvent): """ Args: event: """ frame = self._ctrl.getUmlFrame() if frame is None: PyutUtils.displayError(_("No frame found !")) return diagram = frame.GetDiagram() shapes = diagram.GetShapes() for shape in shapes: shape.SetSelected(True) frame.Refresh()
def saveFile(self) -> bool: """ save to the current filename Returns: `True` if the save succeeds else `False` """ currentProject = self._currentProject if currentProject is None: PyutUtils.displayError(_("No diagram to save !"), _("Error")) return False if currentProject.getFilename() is None or currentProject.getFilename() == PyutConstants.DefaultFilename: return self.saveFileAs() else: return currentProject.saveXmlPyut()
def __init__(self, parentFrame, project, docType: DiagramType): """ Args: parentFrame: The containing UML or sequence diagram frame project: The project docType: The enumeration value for the diagram type """ self.logger: Logger = getLogger(__name__) self._parentFrame: UmlDiagramsFrame = cast(UmlDiagramsFrame, None) self._project = project self._type: DiagramType = docType """ This document's diagram type """ self._treeRoot: TreeItemId = cast(TreeItemId, None) """ Root of the project entry in the tree """ self._treeRootParent: TreeItemId = cast(TreeItemId, None) """ Parent of the project root entry """ self._tree: TreeCtrl = cast(TreeCtrl, None) """ Tree I belong to """ self.logger.debug( f'Project: {project} PyutDocument using type {docType}') if docType == DiagramType.CLASS_DIAGRAM: self._title = DiagramsLabels[docType] self._frame = UmlClassDiagramsFrame(parentFrame) elif docType == DiagramType.SEQUENCE_DIAGRAM: self._title = DiagramsLabels[docType] self._frame = UmlSequenceDiagramsFrame(parentFrame) elif docType == DiagramType.USECASE_DIAGRAM: self._title = DiagramsLabels[docType] self._frame = UmlClassDiagramsFrame(parentFrame) else: PyutUtils.displayError( f'Unsupported diagram type; replacing by class diagram: {docType}' ) self._title = DiagramsLabels[DiagramType.CLASS_DIAGRAM] self._frame = UmlClassDiagramsFrame(parentFrame)
def onExport(self, event: CommandEvent): """ Callback. Args: event: A command event """ # Create a plugin instance cl = self._exportPlugins[event.GetId()] umlObjects: List[OglClass] = self._mediator.getUmlObjects() umlFrame: UmlClassDiagramsFrame = self._mediator.getUmlFrame() obj = cl(umlObjects, umlFrame) try: wxYield() obj.doExport() except (ValueError, Exception) as e: PyutUtils.displayError(_("An error occurred while executing the selected plugin"), _("Error...")) self.logger.error(f'{e}')
def onSelectAll(self, event: CommandEvent): """ Args: event: """ frame: UmlClassDiagramsFrame = self._mediator.getUmlFrame() if frame is None: PyutUtils.displayError(_("No frame found !")) return diagram: Diagram = frame.GetDiagram() shapes: List[OglObject] = diagram.GetShapes() for oglShape in shapes: shape: OglObject = cast(OglObject, oglShape) shape.SetSelected(True) frame.Refresh()
def onPaste(self, event: CommandEvent): """ Args: event: """ if len(self._clipboard) == 0: return self.logger.info(f'Pasting {len(self._clipboard)} objects') frame = self._mediator.getUmlFrame() if frame == -1: PyutUtils.displayError(_("No frame to paste into")) return # put the objects in the clipboard and remove them from the diagram x, y = 100, 100 for clipboardObject in self._clipboard: obj: PyutObject = copy(clipboardObject) if isinstance(obj, PyutClass): po: OglObject = OglClass(obj) elif isinstance(obj, PyutNote): po = OglNote(obj) elif isinstance(obj, PyutActor): po = OglActor(obj) elif isinstance(obj, PyutUseCase): po = OglUseCase(obj) else: self.logger.error(f'Error when try to paste object: {obj}') return self.logger.info(f'Pasting: {po=}') self._mediator.getUmlFrame().addShape(po, x, y) x += 20 y += 20 canvas = po.GetDiagram().GetPanel() # the frame that contains the shape # specify the canvas on which we will paint dc: ClientDC = ClientDC(canvas) canvas.PrepareDC(dc) self._treeNotebookHandler.setModified(True) self._mediator.updateTitle() canvas.Refresh()
def openFile(self, filename, project=None) -> bool: """ Open a file Args: filename: project: Returns: `True` if operation succeeded """ self.logger.info(f'{filename=} {project=}') # Exit if the file is already loaded if not self.isDefaultFilename(filename) and self.isProjectLoaded( filename): PyutUtils.displayError(_("The selected file is already loaded !")) return False # Create a new project ? if project is None: project = PyutProject(PyutConstants.DEFAULT_FILENAME, self.__notebook, self.__projectTree, self.__projectTreeRoot) # Load the project and add it try: if not project.loadFromFilename(filename): eMsg: str = f'{_("The file cannot be loaded !")} - {filename}' PyutUtils.displayError(eMsg) return False self._projects.append(project) self._currentProject = project except (ValueError, Exception) as e: self.logger.error( f"An error occurred while loading the project ! {e}") return False success: bool = self.__addProjectToNotebook(project) self.logger.debug( f'{self.currentFrame=} {self.currentProject=} {self.notebook.GetSelection()=}' ) return success
def _OnMnuEditPaste(self, event: CommandEvent): """ Args: event: """ if len(self._clipboard) == 0: return frame = self._ctrl.getUmlFrame() if frame == -1: PyutUtils.displayError(_("No frame to paste into")) return # put the objects in the clipboard and remove them from the diagram x, y = 100, 100 for obj in self._clipboard: obj = copy(obj) # this is a PyutObject if isinstance(obj, PyutClass): po = OglClass(obj) elif isinstance(obj, PyutNote): po = OglNote(obj) elif isinstance(obj, PyutActor): po = OglActor(obj) elif isinstance(obj, PyutUseCase): po = OglUseCase(obj) else: self.logger.error("Error when try to paste object") return self._ctrl.getUmlFrame().addShape(po, x, y) x += 20 y += 20 canvas = po.GetDiagram().GetPanel() # the canvas that contain the shape # specify the canvas on which we will paint dc = ClientDC(canvas) canvas.PrepareDC(dc) self._mainFileHandlingUI.setModified(True) self._ctrl.updateTitle() canvas.Refresh()
def onImport(self, event: CommandEvent): self._treeNotebookHandler.newProject() self._treeNotebookHandler.newDocument(DiagramType.CLASS_DIAGRAM) self._mediator.updateTitle() cl = self._importPlugins[event.GetId()] obj = cl(self._mediator.getUmlObjects(), self._mediator.getUmlFrame()) # Do plugin functionality try: wxYield() obj.doImport() except (ValueError, Exception) as e: PyutUtils.displayError(_("An error occurred while executing the selected plugin"), _("Error...")) self.logger.error(f'{e}') parent: Window = self._menu.GetWindow() parent.Refresh()
def doImport(self): """ Import datas from file to uml frame @author C.Dutoit """ # Read XMI xmi = self._dom.getElementsByTagName("XMI") if len(xmi) == 0: PyutUtils.displayError( "Wrong XMI File format : XMI tag not found !") return else: xmi = xmi[0] # Read XMI.header self._readXMIHeader(xmi) # Read XMI content self._readXMIContent(xmi)
def onPrint(self, event: CommandEvent): """ Print the current diagram Args: event: """ if self._mediator.getDiagram() is None: PyutUtils.displayError(_("No diagram to print !"), _("Error")) return self._mediator.deselectAllShapes() printDialogData: PrintDialogData = PrintDialogData() printDialogData.SetPrintData(self._printData) printDialogData.SetMinPage(1) printDialogData.SetMaxPage(1) printer = Printer(printDialogData) printout = PyutPrintout(self._mediator.getUmlFrame()) if not printer.Print(self._parent, printout, True): PyutUtils.displayError(_("Cannot print"), _("Error"))
def OnImport(self, event): self._mainFileHandlingUI.newProject() self._mainFileHandlingUI.newDocument(DiagramType.CLASS_DIAGRAM) self._ctrl.updateTitle() cl = self.plugins[event.GetId()] obj = cl(self._ctrl.getUmlObjects(), self._ctrl.getUmlFrame()) # Do plugin functionality BeginBusyCursor() try: wxYield() # time to process the refresh in newDiagram obj.doImport() except (ValueError, Exception) as e: PyutUtils.displayError( _("An error occurred while executing the selected plugin"), _("Error..."), self) self.logger.error(f'{e}') EndBusyCursor() self.Refresh()
def openFile(self, filename, project=None) -> bool: """ Open a file Args: filename: project: Returns: `True` if operation succeeded """ # Exit if the file is already loaded if not self.isDefaultFilename(filename) and self.isProjectLoaded(filename): PyutUtils.displayError(_("The selected file is already loaded !")) return False # Create a new project ? if project is None: project = PyutProject(PyutConstants.DefaultFilename, self.__notebook, self.__projectTree, self.__projectTreeRoot) # print ">>>FileHandling-openFile-3" # Load the project and add it try: if not project.loadFromFilename(filename): PyutUtils.displayError(_("The specified file can't be loaded !")) return False self._projects.append(project) # self._ctrl.registerCurrentProject(project) self._currentProject = project except (ValueError, Exception) as e: PyutUtils.displayError(_(f"An error occurred while loading the project ! {e}")) return False try: if not self._mediator.isInScriptMode(): for document in project.getDocuments(): diagramTitle: str = document.getTitle() shortName: str = self.shortenNotebookPageFileName(diagramTitle) self.__notebook.AddPage(document.getFrame(), shortName) self.__notebookCurrentPage = self.__notebook.GetPageCount()-1 self.__notebook.SetSelection(self.__notebookCurrentPage) if len(project.getDocuments()) > 0: self._currentFrame = project.getDocuments()[0].getFrame() except (ValueError, Exception) as e: PyutUtils.displayError(_(f"An error occurred while adding the project to the notebook {e}")) return False return True
def loadFromFilename(self, filename: str) -> bool: """ Load a project from a file Args: filename: filename to open Returns: `True` if the operation succeeded """ # Load the file BeginBusyCursor() from org.pyut.persistence.IoFile import IoFile # Avoid Nuitka cyclical dependency io: IoFile = IoFile() wxYield() # to treat the uml frame refresh in newDiagram before loading # Load the file self._filename = filename try: io.open(filename, self) self._modified = False except (ValueError, Exception) as e: EndBusyCursor() PyutUtils.displayError(_(f"Error loading file: {e}")) return False EndBusyCursor() # Update text self.updateTreeText() # Register to mediator # if len(self._documents)>0: # self._ctrl.registerUMLFrame(self._documents[0].getFrame()) # print ">>>PyutProject-loadFromFilename-7" if len(self._documents) > 0: self._ctrl.getFileHandling().showFrame(self._documents[0].getFrame()) self._documents[0].getFrame().Refresh() return True else: return False
def _OnMnuFilePrintPreview(self, event: CommandEvent): """ Display the print preview frame; Preview before printing. Args: event: """ self._ctrl.deselectAllShapes() frame = self._ctrl.getUmlFrame() if frame == -1: PyutUtils.displayError(_("Can't print nonexistent frame..."), _("Error..."), self) return printout = PyutPrintout(frame) printout2 = PyutPrintout(frame) preview = PrintPreview(printout, printout2, self._printData) if not preview.IsOk(): PyutUtils.displayError( _("An unknown error occurred while previewing"), _("Error..."), self) return frame = PreviewFrame(preview, self, _("Diagram preview")) frame.Initialize() frame.Centre(BOTH) try: frame.Show(True) except (ValueError, Exception) as e: PyutUtils.displayError( _("An unknown error occurred while previewing"), _("Error..."), 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 __addProjectToNotebook(self, project: PyutProject) -> bool: success: bool = True try: if self._mediator.isInScriptMode() is False: for document in project.getDocuments(): diagramTitle: str = document.title shortName: str = self.__shortenNotebookPageFileName( diagramTitle) self.__notebook.AddPage(document.getFrame(), shortName) self.__notebookCurrentPage = self.__notebook.GetPageCount() - 1 self.__notebook.SetSelection(self.__notebookCurrentPage) self.__updateTreeNotebookIfPossible(project=project) except (ValueError, Exception) as e: PyutUtils.displayError( _(f"An error occurred while adding the project to the notebook {e}" )) success = False return success
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=""): """ 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 open(self, filename, project): """ To open a compressed file and create diagram. Args: filename: The file name project: The project """ oldPath: str = getcwd() path: str = getMediator().getAppPath() chdir(path) Lang.importLanguage() xmlString = "" if filename[-4:] == ".put": try: with open(filename, "rb") as dataFile: compressedData: bytes = dataFile.read() # noinspection PyUnresolvedReferences self.logger.info(f'zlib.__version__: {zlib.__version__}') xmlBytes = zlib.decompress( compressedData) # has b'....' around it xmlString: str = xmlBytes.decode() self.logger.info(f'Document read:\n{xmlString}') except (ValueError, Exception) as e: self.logger.error(f'open: {e}') elif filename[-4:] == ".xml": xmlString = open(filename, "r").read() else: PyutUtils.displayError( _(f"Can't open the unidentified file : {filename}")) return dom = parseString(xmlString) root = dom.getElementsByTagName("PyutProject") if len(root) > 0: root = root[0] if root.hasAttribute('version'): version = root.getAttribute("version") myXml = PyutXmlFinder.getPyutXmlClass(theVersion=version) else: from org.pyut.persistence.PyutXml import PyutXml myXml = PyutXml() myXml.open(dom, project) else: # TODO fix this code to use PyutXmlFinder root = dom.getElementsByTagName("Pyut")[0] if root.hasAttribute('version'): version = root.getAttribute("version") self.logger.info(f"Using version {version} of the importer") module = __import__("PyutXmlV" + str(version)) # noinspection PyUnresolvedReferences myXml = module.PyutXml() else: from org.pyut.persistence.PyutXml import PyutXml # don't like it here but at top of file not recognized -- hasii # version = 1 myXml = PyutXml() project.newDocument(DiagramType.CLASS_DIAGRAM) umlFrame = project.getDocuments()[0].getFrame() myXml.open(dom, umlFrame) chdir(oldPath)
def save(self, project: PyutProject) -> Document: """ Save diagram in XML file. Args: project: The project to write as XML Returns: A minidom XML Document """ assert project is not None, 'Oops someone sent me a bad project' dlg: Dialog = Dialog(None, ID_ANY, "Saving...", style=STAY_ON_TOP | ICON_INFORMATION | RESIZE_BORDER, size=Size(207, 70)) xmlDoc: Document = Document() try: top = xmlDoc.createElement(PyutXmlConstants.TOP_LEVEL_ELEMENT) top.setAttribute(PyutXmlConstants.ATTR_VERSION, str(PyutXml.VERSION)) codePath: str = project.getCodePath() if codePath is None: top.setAttribute(PyutXmlConstants.ATTR_CODE_PATH, '') else: top.setAttribute(PyutXmlConstants.ATTR_CODE_PATH, codePath) xmlDoc.appendChild(top) gauge = Gauge(dlg, ID_ANY, 100, pos=Point(2, 5), size=Size(200, 30)) dlg.Show(True) wxYield() toPyutXml: OglToMiniDomV10 = OglToMiniDomV10() # Save all documents in the project for pyutDocument in project.getDocuments(): document: PyutDocument = cast(PyutDocument, pyutDocument) documentNode: Element = self.__pyutDocumentToPyutXml( xmlDoc=xmlDoc, pyutDocument=document) top.appendChild(documentNode) from org.pyut.ui.UmlFrame import UmlObjects oglObjects: UmlObjects = document.getFrame().getUmlObjects() for i in range(len(oglObjects)): gauge.SetValue(i * 100 / len(oglObjects)) wxYield() oglObject = oglObjects[i] if isinstance(oglObject, OglClass): classElement: Element = toPyutXml.oglClassToXml( oglObject, xmlDoc) documentNode.appendChild(classElement) elif isinstance(oglObject, OglInterface2): classElement = toPyutXml.oglInterface2ToXml( oglObject, xmlDoc) documentNode.appendChild(classElement) elif isinstance(oglObject, OglNote): noteElement: Element = toPyutXml.oglNoteToXml( oglObject, xmlDoc) documentNode.appendChild(noteElement) elif isinstance(oglObject, OglText): textElement: Element = toPyutXml.oglTextToXml( oglObject, xmlDoc) documentNode.appendChild(textElement) elif isinstance(oglObject, OglActor): actorElement: Element = toPyutXml.oglActorToXml( oglObject, xmlDoc) documentNode.appendChild(actorElement) elif isinstance(oglObject, OglUseCase): useCaseElement: Element = toPyutXml.oglUseCaseToXml( oglObject, xmlDoc) documentNode.appendChild(useCaseElement) elif isinstance(oglObject, OglSDInstance): sdInstanceElement: Element = toPyutXml.oglSDInstanceToXml( oglObject, xmlDoc) documentNode.appendChild(sdInstanceElement) elif isinstance(oglObject, OglSDMessage): sdMessageElement: Element = toPyutXml.oglSDMessageToXml( oglObject, xmlDoc) documentNode.appendChild(sdMessageElement) # OglLink comes last because OglSDInstance is a subclass of OglLink # Now I know why OglLink used to double inherit from LineShape, ShapeEventHandler # I changed it to inherit from OglLink directly elif isinstance(oglObject, OglLink): linkElement: Element = toPyutXml.oglLinkToXml( oglObject, xmlDoc) documentNode.appendChild(linkElement) else: self.logger.warning( f'Unhandled OGL Object: {oglObject}') except (ValueError, Exception) as e: try: dlg.Destroy() self.logger.error(f'{e}') except (ValueError, Exception) as e: self.logger.error(f'{e}') PyutUtils.displayError(_("Can't save file")) return xmlDoc dlg.Destroy() return xmlDoc