Example #1
0
    def OnMenuClick(self, event: CommandEvent):
        """
        Callback for popup menu on class

        Args:
            event:
        """
        from org.pyut.general.Mediator import getMediator   # avoid circular import

        pyutObject: PyutClass = self.getPyutObject()
        eventId:    int       = event.GetId()
        if eventId == MENU_TOGGLE_STEREOTYPE:
            pyutObject.setShowStereotype(not pyutObject.getShowStereotype())
            self.autoResize()
        elif eventId == MENU_TOGGLE_METHODS:
            pyutObject.showMethods = not pyutObject.showMethods     # flip it!!  too cute
            self.autoResize()
        elif eventId == MENU_TOGGLE_FIELDS:
            pyutObject.showFields = not pyutObject.showFields       # flip it!! too cute
            self.autoResize()
        elif eventId == MENU_FIT_FIELDS:
            self.autoResize()
        elif eventId == MENU_CUT_SHAPE:
            ctrl = getMediator()
            ctrl.deselectAllShapes()
            self.SetSelected(True)
            ctrl.cutSelectedShapes()
        elif eventId == MENU_IMPLEMENT_INTERFACE:
            ctrl = getMediator()
            ctrl.requestLollipopLocation(self)
        else:
            event.Skip()
Example #2
0
    def OnLeftDown(self, event: MouseEvent):
        """
        Callback for left clicks.

        Args:
            event: The mouse event
        """

        from org.pyut.general.Mediator import getMediator   # avoid circular import

        print(f'SelectAnchorPoint: {self._attachmentPoint}')

        getMediator().createLollipopInterface(implementor=self.GetParent(), attachmentAnchor=self)
Example #3
0
    def __showAppropriateUmlFrame(self, document) -> UmlDiagramsFrame:

        umlFrame: UmlDiagramsFrame = document.getFrame()
        ctrl = getMediator()
        ctrl.getFileHandling().showFrame(umlFrame)

        return umlFrame
Example #4
0
    def doExport(self):
        """
        Called by Pyut to begin the export process.
        """
        if self._umlFrame is None:
            self.displayNoUmlFrame()
            return

        outputFormat: Tuple[str, str, str] = self.getOutputFormat()
        if outputFormat is not None:
            if not self.setExportOptions():
                return None

            mediator = getMediator()
            prefs: PyutPreferences = PyutPreferences()
            if prefs.pyutIoPluginAutoSelectAll is True:
                mediator.selectAllShapes()
            self.__oglObjects = mediator.getSelectedShapes()
            if len(self.__oglObjects) == 0:
                self.displayNoSelectedUmlObjects()
            else:
                # write the file
                self.write(self.__oglObjects)
                mediator.deselectAllShapes()
        else:
            PyutIoPlugin.clsLogger.info(f'Output format is: {outputFormat}')
Example #5
0
    def _createNewClass(self, x, y):
        """
        Add a new class at (x, y).

        @return PyutClass : the newly created PyutClass
        @since 1.4
        @author L. Burgbacher <*****@*****.**>
        """
        from org.pyut.general.Mediator import getMediator
        from org.pyut.model.PyutClass import PyutClass
        from org.pyut.ogl.OglClass import OglClass

        med = getMediator()
        umlFrame = med.getFileHandling().getCurrentFrame()

        pyutClass = PyutClass(_("NoName"))
        oglClass = OglClass(pyutClass)
        med.classEditor(pyutClass)
        # med.autoResize(pyutClass)

        umlFrame.addShape(oglClass, x, y, withModelUpdate=True)
        med.autoResize(pyutClass)
        umlFrame.Refresh()

        return oglClass
Example #6
0
    def SetSelected(self, state=True):

        from org.pyut.general.Mediator import getMediator  # avoid circular import
        from org.pyut.general.Mediator import ACTION_ZOOM_OUT  # avoid circular import

        if getMediator().getCurrentAction() != ACTION_ZOOM_OUT:
            RectangleShape.SetSelected(self, state)
Example #7
0
    def __init__(self, parent: Window, frame):
        """

        Args:
            parent: The parent window
            frame:  The uml frame
        """
        super().__init__(parent)

        self.logger: Logger = getLogger(__name__)

        self._ctrl = getMediator()
        self.maxWidth = DEFAULT_WIDTH
        self.maxHeight = int(self.maxWidth /
                             A4_FACTOR)  # 1.41 is for A4 support

        nbrUnitsX: int = int(self.maxWidth / UmlFrame.PIXELS_PER_UNIT_X)
        nbrUnitsY: int = int(self.maxHeight / UmlFrame.PIXELS_PER_UNIT_Y)
        initPosX: int = 0
        initPosY: int = 0
        self.SetScrollbars(UmlFrame.PIXELS_PER_UNIT_X,
                           UmlFrame.PIXELS_PER_UNIT_Y, nbrUnitsX, nbrUnitsY,
                           initPosX, initPosY, False)

        self._frame = frame
        self._history = HistoryManager(self)

        # Close event
        self.Bind(EVT_CLOSE, self.evtClose)
        self.Bind(EVT_PAINT, self.OnPaint)
        self.Bind(EVT_CHAR, self._ctrl.processChar)

        self.SetInfinite(True)

        self._defaultCursor = self.GetCursor()
Example #8
0
    def __init__(self, oglObjects, umlFrame):
        """
        Constructor.

        @param oglObjects : list of ogl objects
        @param umlFrame : the UML Frame of pyut
        @author Laurent Burgbacher <*****@*****.**>
        @since 1.0
        """
        super().__init__(umlFrame, getMediator())
        self.__oglObjects = oglObjects
Example #9
0
    def OnLeftDown(self, event: MouseEvent):
        """
        Handle event on left click.

        Args:
            event:
        """
        self.logger.debug(f'OnLeftDown - event - {event}')

        from org.pyut.general.Mediator import getMediator  # avoid circular import

        med = getMediator()
        if med.actionWaiting():
            position: Point = event.GetPosition()
            med.shapeSelected(self, position)
            return
        event.Skip()
Example #10
0
    def _createLollipopInterface(self, pyutInterface: PyutInterface,
                                 attachmentAnchor: SelectAnchorPoint):

        from org.pyut.general.Mediator import getMediator
        from org.pyut.general.Mediator import Mediator

        oglInterface: OglInterface2 = OglInterface2(pyutInterface,
                                                    attachmentAnchor)

        anchorPosition: Tuple[float, float] = attachmentAnchor.GetPosition()
        self.logger.info(f'anchorPosition: {anchorPosition}')
        x = anchorPosition[0]
        y = anchorPosition[1]

        med: Mediator = getMediator()
        umlFrame: UmlClassDiagramsFrame = med.getFileHandling(
        ).getCurrentFrame()

        umlFrame.addShape(oglInterface, x, y, withModelUpdate=True)
        umlFrame.Refresh()
Example #11
0
    def __init__(self, filename: str, parentFrame: Notebook, tree: TreeCtrl, treeRoot: TreeItemId):
        """

        Args:
            filename:       The project file name
            parentFrame:
            tree:           The tree control
            treeRoot:       Where to root the tree
        """

        self._parentFrame   = parentFrame   # Parent frame
        self._ctrl          = getMediator()

        self._documents: List[PyutDocument] = []            # List of documents

        self._filename: str     = filename      # Project filename
        self._modified: bool    = False         # Was the project modified ?
        self._codePath: str     = ""
        self._treeRootParent: TreeItemId = treeRoot                 # Parent of the project root entry
        self._treeRoot:       TreeItemId = cast(TreeItemId, None)   # Root of the project entry in the tree
        self._tree:           TreeCtrl   = tree                     # Tree I belong to
        self.addToTree()
Example #12
0
    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)
Example #13
0
    def __init__(self, parent: Window, wxID: int, title: str):
        """

        Args:
            parent:     parent window
            wxID:       wx ID of this frame
            title:      Title to display
        """
        self._prefs: PyutPreferences = PyutPreferences()

        appSize: Size = Size(self._prefs.startupWidth,
                             self._prefs.startupHeight)

        super().__init__(parent=parent,
                         id=wxID,
                         title=title,
                         size=appSize,
                         style=DEFAULT_FRAME_STYLE | FRAME_EX_METAL)

        self.logger: Logger = getLogger(__name__)
        # Create the application's icon
        if sysPlatform != PyutConstants.THE_GREAT_MAC_PLATFORM:

            fileName: str = PyutUtils.getResourcePath(
                packageName=IMAGE_RESOURCES_PACKAGE, fileName='pyut.ico')
            icon: Icon = Icon(fileName, BITMAP_TYPE_ICO)
            self.SetIcon(icon)

        self.SetThemeEnabled(True)

        if self._prefs.centerAppOnStartUp is True:
            self.Center(BOTH)  # Center on the screen
        else:
            appPosition: Tuple[int, int] = self._prefs.appStartupPosition
            self.SetPosition(pt=appPosition)

        self.CreateStatusBar()

        # Properties
        from org.pyut.plugins.PluginManager import PluginManager  # Plugin Manager should not be in plugins directory

        self.plugMgr: PluginManager = PluginManager()
        self.plugins: SharedTypes.PluginMap = cast(SharedTypes.PluginMap,
                                                   {})  # To store the plugins
        self._toolboxIds: SharedTypes.ToolboxIdMap = cast(
            SharedTypes.ToolboxIdMap, {})  # Association toolbox id -> category
        self.mnuFile: Menu = cast(Menu, None)

        self._clipboard = []
        self._currentDirectory = getcwd()

        self._lastDir = self._prefs["LastDirectory"]
        if self._lastDir is None:  # Assert that the path is present
            self._lastDir = getcwd()

        self._ctrl = getMediator()
        self._ctrl.registerStatusBar(self.GetStatusBar())
        self._ctrl.resetStatusText()
        self._ctrl.registerAppFrame(self)

        # Last opened Files IDs
        self.lastOpenedFilesID = []
        for index in range(self._prefs.getNbLOF()):
            self.lastOpenedFilesID.append(PyutUtils.assignID(1)[0])

        self._mainFileHandlingUI: MainUI = MainUI(self, self._ctrl)
        self._ctrl.registerFileHandling(self._mainFileHandlingUI)

        # Initialization
        self._initPyutTools()  # Toolboxes, toolbar
        self._initMenu()  # Menu
        self._initPrinting()  # Printing data

        # Accelerators init. (=Keyboards shortcuts)
        acc = self._createAcceleratorTable()
        accel_table = AcceleratorTable(acc)
        self.SetAcceleratorTable(accel_table)

        self._ctrl.registerAppPath(self._currentDirectory)

        # set application title
        self._mainFileHandlingUI.newProject()
        self._ctrl.updateTitle()

        # Init tips frame
        self._alreadyDisplayedTipsFrame = False
        self.Bind(EVT_ACTIVATE, self._onActivate)
Example #14
0
    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)
Example #15
0
    def open(self, dom, project):
        """
        Open a file and create a diagram.
        """
        dlgGauge = None
        umlFrame = None  # avoid Pycharm warning
        try:
            root = dom.getElementsByTagName("PyutProject")[0]
            if root.hasAttribute('version'):
                version = int(root.getAttribute("version"))
            else:
                version = 1
            if version != self._this_version:
                self.logger.error("Wrong version of the file loader")
                eMsg: str = f'This is version {self._this_version} and the file version is {version}'
                self.logger.error(eMsg)
                raise Exception(f'VERSION_ERROR:  {eMsg}')
            project.setCodePath(root.getAttribute("CodePath"))

            # Create and init gauge
            dlgGauge = Dialog(None, -1, "Loading...", style=STAY_ON_TOP | ICON_INFORMATION | RESIZE_BORDER, size=Size(207, 70))
            gauge    = Gauge(dlgGauge, -1, 5, pos=Point(2, 5), size=Size(200, 30))
            dlgGauge.Show(True)

            # for all elements il xml file
            dlgGauge.SetTitle("Reading file...")
            gauge.SetValue(1)

            for documentNode in dom.getElementsByTagName("PyutDocument"):

                dicoOglObjects = {}     # format {id/name : oglClass}
                dicoLink       = {}     # format [id/name : PyutLink}
                dicoFather     = {}     # format {id child oglClass : [id fathers]}

                docType = documentNode.getAttribute("type")     # Python 3 update

                document = project.newDocument(PyutConstants.diagramTypeFromString(docType))
                umlFrame = document.getFrame()

                ctrl = getMediator()
                ctrl.getFileHandling().showFrame(umlFrame)

                self._getOglClasses(documentNode.getElementsByTagName('GraphicClass'),    dicoOglObjects, dicoLink, dicoFather, umlFrame)
                self._getOglNotes(documentNode.getElementsByTagName('GraphicNote'),       dicoOglObjects, dicoLink, dicoFather, umlFrame)
                self._getOglActors(documentNode.getElementsByTagName('GraphicActor'),     dicoOglObjects, dicoLink, dicoFather, umlFrame)
                self._getOglUseCases(documentNode.getElementsByTagName('GraphicUseCase'), dicoOglObjects, dicoLink, dicoFather, umlFrame)
                self._getOglLinks(documentNode.getElementsByTagName("GraphicLink"),       dicoOglObjects, dicoLink, dicoFather, umlFrame)
                self._getOglSDInstances(documentNode.getElementsByTagName("GraphicSDInstance"), dicoOglObjects, dicoLink, dicoFather, umlFrame)
                self._getOglSDMessages(documentNode.getElementsByTagName("GraphicSDMessage"),   dicoOglObjects, dicoLink, dicoFather, umlFrame)

                # fix the link's destination field
                gauge.SetValue(2)
                dlgGauge.SetTitle("Fixing link's destination...")
                for links in list(dicoLink.values()):
                    for link in links:
                        link[1].setDestination(dicoOglObjects[link[0]].getPyutObject())
                # adding fathers
                dlgGauge.SetTitle("Adding fathers...")
                gauge.SetValue(3)
                for child, fathers in list(dicoFather.items()):
                    for father in fathers:
                        umlFrame.createInheritanceLink(dicoOglObjects[child], dicoOglObjects[father])

                # adding links to this OGL object
                dlgGauge.SetTitle("Adding Links...")
                gauge.SetValue(4)
                for src, links in list(dicoLink.items()):
                    for link in links:
                        createdLink = umlFrame.createNewLink(dicoOglObjects[src], dicoOglObjects[link[1].getDestination().getId()])

                        # fix link with the loaded information
                        pyutLink = createdLink.getPyutObject()
                        traversalLink: PyutLink = link[1]
                        pyutLink.setBidir(traversalLink.getBidir())

                        # pyutLink.setDestinationCardinality(link[1].getDestinationCardinality())
                        # pyutLink.setSourceCardinality(link[1].getSrcCard())
                        pyutLink.destinationCardinality = traversalLink.destinationCardinality
                        pyutLink.sourceCardinality      = traversalLink.sourceCardinality

                        pyutLink.setName(link[1].getName())
        except (ValueError, Exception) as e:
            if dlgGauge is not None:
                dlgGauge.Destroy()
            PyutUtils.displayError(_(f"Can't load file {e}"))
            umlFrame.Refresh()
            return

        # to draw diagram
        umlFrame.Refresh()
        gauge.SetValue(5)

        if dlgGauge is not None:
            dlgGauge.Destroy()