Ejemplo n.º 1
0
    def OnMenuClick(self, event: CommandEvent):
        """
        Callback for popup menu on class

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

        pyutObject: PyutClass = cast(PyutClass, self.pyutObject)
        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: Mediator = Mediator()
            ctrl.deselectAllShapes()
            self.SetSelected(True)
            ctrl.cutSelectedShapes()
        elif eventId == MENU_IMPLEMENT_INTERFACE:
            ctrl = Mediator()
            ctrl.requestLollipopLocation(self)
        else:
            event.Skip()
Ejemplo n.º 2
0
class TestIoFile(TestBase):
    """
    PyutClasses (data model) and OglClasses UI are intermixed in the PyutXml code;  Extremely, hard to unit
    test that the data model has been built correctly
    But, I did learn a bit about Python mocking !!
    """
    clsLogger: Logger = None

    @classmethod
    def setUpClass(cls):
        TestBase.setUpLogging()
        TestIoFile.clsLogger = getLogger(__name__)

    def setUp(self):
        self.logger: Logger = TestIoFile.clsLogger
        self.ioFile: IoFile = IoFile()

        self.mockFrame: MagicMock = MagicMock()
        self.mockTree: MagicMock = MagicMock()
        self.mockTreeRoot: MagicMock = MagicMock()
        self.fileHandling: TreeNotebookHandler = MagicMock()

        oldPath: str = getcwd()
        # Assume we are at src/tests
        chdir('../../../../..')
        newAppPath: str = getcwd()
        chdir(oldPath)

        self.mediator = Mediator()  # It's a Singleton, I can do this
        self.mediator.registerAppPath(newAppPath)
        self.mediator.registerFileHandling(self.fileHandling)

    def tearDown(self):
        pass

    # noinspection PyUnusedLocal
    @patch('wx.Dialog')
    @patch('wx.Gauge')
    @patch('org.pyut.general.Mediator')
    @patch('org.pyut.ui.TreeNotebookHandler.TreeNotebookHandler')
    def testIoFileOpenV8(self, mockFileHandling, mockMediator, wxGauge,
                         wxDialog):

        with patch('org.pyut.ui.PyutProject.PyutProject') as mockPyutProject:
            self.ioFile.open(filename='testdata/BaseSave_V8.put',
                             project=mockPyutProject)

    def testName2(self):
        pass
Ejemplo n.º 3
0
    def __init__(self, parent: Notebook, frame):
        """

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

        self.logger: Logger = getLogger(__name__)

        self._ctrl: Mediator = Mediator()

        self.maxWidth:  int  = DEFAULT_WIDTH
        self.maxHeight: int = 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 = 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()
Ejemplo n.º 4
0
    def __showAppropriateUmlFrame(self, document) -> UmlDiagramsFrame:

        umlFrame: UmlDiagramsFrame = document.getFrame()
        mediator: Mediator = Mediator()
        mediator.getFileHandling().showFrame(umlFrame)

        return umlFrame
Ejemplo n.º 5
0
    def _placeShapeOnFrame(self, ):
        """
        Place self._shape on the UML frame

        """
        from org.pyut.ui.Mediator import Mediator

        med: Mediator = Mediator()
        oglClass: OglClass = self._shape
        pyutClass: PyutClass = cast(PyutClass, oglClass.getPyutObject())
        umlFrame = med.getFileHandling().getCurrentFrame()
        if self._invokeEditDialog is True:
            med.classEditor(pyutClass)

        if self._prefs.snapToGrid is True:
            snappedX, snappedY = PyutUtils.snapCoordinatesToGrid(
                self._classX, self._classY, self._prefs.backgroundGridInterval)
            umlFrame.addShape(oglClass,
                              snappedX,
                              snappedY,
                              withModelUpdate=True)
        else:
            umlFrame.addShape(oglClass,
                              self._classX,
                              self._classY,
                              withModelUpdate=True)

        med.autoResize(pyutClass)
        umlFrame.Refresh()
Ejemplo n.º 6
0
    def read(self, oglObjects, umlFrame):
        """
        Read data from filename.

        Args:
            oglObjects:
            umlFrame: Pyut's UmlFrame

        Returns: True if read succeeds, False if error or canceled
        """
        # Ask the user which destination file he wants
        filename = self._askForFileImport()
        if filename == "":
            return False

        # Open file
        from org.pyut.ui.Mediator import Mediator

        mediator: Mediator = Mediator()

        fileHandling = mediator.getFileHandling()
        project = fileHandling.getCurrentProject()
        for document in project.getDocuments():
            project.removeDocument(document, False)
        fileHandling.openFile(filename, project)
Ejemplo n.º 7
0
    def __init__(self, parent):
        """

        Args:
            parent:     An PyutApplicationFrame
        """
        self.logger: Logger = getLogger(__name__)

        from org.pyut.ui.frame.PyutApplicationFrame import PyutApplicationFrame  # Prevent recursion import problem
        from org.pyut.ui.Mediator import Mediator
        self.__parent: PyutApplicationFrame = parent
        self._mediator: Mediator = Mediator()

        self._projects: List[PyutProject] = []
        self._currentProject: PyutProject = cast(PyutProject, None)
        self._currentFrame: UmlDiagramsFrame = cast(UmlDiagramsFrame, None)

        if not self._mediator.isInScriptMode():

            self.__splitter: SplitterWindow = cast(SplitterWindow, None)
            self.__projectTree: TreeCtrl = cast(TreeCtrl, None)
            self.__projectTreeRoot: TreeItemId = cast(TreeItemId, None)
            self.__notebook: Notebook = cast(Notebook, None)
            self.__projectPopupMenu: Menu = cast(Menu, None)
            self.__documentPopupMenu: Menu = cast(Menu, None)

            self._initializeUIElements()
Ejemplo n.º 8
0
    def SetSelected(self, state=True):

        from org.pyut.ui.Mediator import Mediator  # avoid circular import
        from org.pyut.ui.Mediator import ACTION_ZOOM_OUT  # avoid circular import

        mediator: Mediator = Mediator()
        if mediator.getCurrentAction() != ACTION_ZOOM_OUT:
            RectangleShape.SetSelected(self, state)
Ejemplo n.º 9
0
    def setUp(self):
        self.logger: Logger = TestIoFile.clsLogger
        self.ioFile: IoFile = IoFile()

        self.mockFrame: MagicMock = MagicMock()
        self.mockTree: MagicMock = MagicMock()
        self.mockTreeRoot: MagicMock = MagicMock()
        self.fileHandling: TreeNotebookHandler = MagicMock()

        oldPath: str = getcwd()
        # Assume we are at src/tests
        chdir('../../../../..')
        newAppPath: str = getcwd()
        chdir(oldPath)

        self.mediator = Mediator()  # It's a Singleton, I can do this
        self.mediator.registerAppPath(newAppPath)
        self.mediator.registerFileHandling(self.fileHandling)
Ejemplo n.º 10
0
    def __init__(self, umlObjects: OglClasses, umlFrame: UmlFrame):
        """

        Args:
            umlObjects:  list of ogl objects
            umlFrame:    Pyut's UML Frame
        """
        super().__init__(umlFrame=umlFrame, ctrl=Mediator())
        self._umlObjects = umlObjects
        self._umlFrame = umlFrame
Ejemplo n.º 11
0
    def OnLeftDown(self, event: MouseEvent):
        """
        Callback for left clicks.

        Args:
            event: The mouse event
        """

        from org.pyut.ui.Mediator import Mediator   # avoid circular import

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

        mediator: Mediator = Mediator()
        mediator.createLollipopInterface(implementor=self.GetParent(), attachmentAnchor=self)
Ejemplo n.º 12
0
    def __init__(self,
                 parent,
                 windowId,
                 dlgTitle: str,
                 pyutModel: Union[PyutClass, PyutInterface],
                 editInterface: bool = False):

        super().__init__(parent,
                         windowId,
                         dlgTitle,
                         style=RESIZE_BORDER | CAPTION)

        self._parent = parent  # TODO  Do I really need to stash this

        from org.pyut.ui.Mediator import Mediator

        self.logger: Logger = DlgEditClassCommon.clsLogger
        self._editInterface: bool = editInterface
        self._mediator: Mediator = Mediator()

        self._pyutModel: CommonClassType = pyutModel
        self._pyutModelCopy: CommonClassType = deepcopy(pyutModel)

        self.SetAutoLayout(True)

        if editInterface is True:
            lbl: str = _('Interface Name')
        else:
            lbl = _('Class Name')

        lblName: StaticText = StaticText(self, ID_ANY, lbl)
        self._txtName: TextCtrl = TextCtrl(self,
                                           ID_TEXT_NAME,
                                           "",
                                           size=(125, -1))

        # Name and Stereotype sizer
        self._szrNameStereotype: BoxSizer = BoxSizer(HORIZONTAL)

        self._szrNameStereotype.Add(lblName, 0, ALL | ALIGN_CENTER, 5)
        self._szrNameStereotype.Add(self._txtName, 1, ALIGN_CENTER)

        self._szrButtons: BoxSizer = self.createButtonContainer()

        self._szrMain: BoxSizer = BoxSizer(VERTICAL)

        self._szrMain.Add(self._szrNameStereotype, 0,
                          ALL | ALIGN_CENTER_HORIZONTAL, 5)

        self.SetSizer(self._szrMain)
Ejemplo n.º 13
0
    def SetPosition(self, x, y):
        """
        Define new position for the object

        Args:
            x:  The new abscissa
            y:  The new ordinate
        """
        from org.pyut.ui.Mediator import Mediator
        mediator: Mediator = Mediator()  # TODO:
        fileHandling = mediator.getFileHandling()  #
        if fileHandling is not None:  # Send an event to the mediator for this
            fileHandling.setModified(True)  # BAD BAD BAD
        RectangleShape.SetPosition(self, x, y)
Ejemplo n.º 14
0
    def OnLeftDown(self, event: MouseEvent):
        """
        Handle event on left click.

        Args:
            event:
        """
        OglObject.clsLogger.debug(f'OnLeftDown - event - {event}')

        from org.pyut.ui.Mediator import Mediator  # avoid circular import

        med: Mediator = Mediator()
        if med.actionWaiting():
            position: Point = event.GetPosition()
            med.shapeSelected(self, position)
            return
        event.Skip()
Ejemplo n.º 15
0
    def setUp(self):
        """
        """
        # Initialize mediator and error manager
        mediator: Mediator = Mediator()
        mediator.setScriptMode()

        fileHandling: TreeNotebookHandler = TreeNotebookHandler(None)
        mediator.registerFileHandling(fileHandling)

        errorManager: ErrorManager = mediator.getErrorManager()
        errorManager.changeType(ErrorViewTypes.RAISE_ERROR_VIEW)

        whereWeAre: str = getcwd()
        PyutUtils.setBasePath(whereWeAre)

        self.app = TestUmlFrame.clsApp
        self._umlFrame: UmlFrame = TestUmlFrame.clsFrame
Ejemplo n.º 16
0
    def __init__(self, frame: Frame, fileMenuHandler: FileMenuHandler,
                 editMenuHandler: EditMenuHandler,
                 newActionCallback: Callable):

        self._containingFrame: Frame = frame

        self._fileMenuHandler: FileMenuHandler = fileMenuHandler
        self._editMenuHandler: EditMenuHandler = editMenuHandler
        self._newActionCallback: Callable = newActionCallback

        self.logger: Logger = getLogger(__name__)
        self._mediator: Mediator = Mediator()
        self._tb: ToolBar = frame.CreateToolBar(TB_HORIZONTAL | NO_BORDER
                                                | TB_FLAT)

        frame.SetToolBar(self._tb)

        self._toolIconOwner: ToolIconOwner = ToolIconOwner()
        self._toolIconOwner.initializeIcons()
Ejemplo n.º 17
0
    def isIDUsed(self, idToCheck) -> bool:
        """
        Determine if an ID is in use

        Args:
            idToCheck:

        Returns:
            `True` if `idToCheck` is in use, else `False`
        """
        from org.pyut.ui.Mediator import Mediator
        mediator: Mediator = Mediator()
        #
        # TODO:  This seems compute heavy;  I wonder if we should have a lookup map
        for obj in [
                el for el in mediator.getUmlObjects()
                if isinstance(el, PyutObject)
        ]:
            if obj.getId() == idToCheck:
                return True
        return False
Ejemplo n.º 18
0
    def _makeToolboxesMenu(self):
        """
        Make the Toolboxes submenu.
        """
        mediator: Mediator = Mediator()
        # Get categories
        categories = mediator.getToolboxesCategories()
        nb = len(categories)
        if nb == 0:
            return None
        sub: Menu = Menu()

        for category in categories:

            categoryId = self.__getWxId(category)
            sub.Append(categoryId, category)
            self._containingFrame.Bind(
                EVT_MENU,
                self._toolsMenuHandler.onToolboxMenuClick,
                id=categoryId)
        return sub
Ejemplo n.º 19
0
    def write(self, oglObjects) -> bool:
        """
        Write data to filename.

        Args:
            oglObjects:

        Returns: True if we succeeded with the write, Returns False if error occurred or if the operation was cancelled
        """
        oldPath = getcwd()
        # Ask the user which destination file he wants
        filename: str = self._askForFileExport()
        if filename == "":
            return False

        lastVersion: str = PyutXmlFinder.getLatestXmlVersion()
        myXml = PyutXmlFinder.getPyutXmlClass(theVersion=lastVersion)
        file = open(filename, "w")

        if int(lastVersion) >= 5:
            from org.pyut.ui.Mediator import Mediator

            mediator: Mediator = Mediator()

            fileHandling = mediator.getFileHandling()
            project      = fileHandling.getProjectFromOglObjects(oglObjects)
            doc          = myXml.save(project)
        else:
            doc = myXml.save(oglObjects)

        if self.pretty:
            text = doc.toprettyxml()
        else:
            text = doc.toxml()
        updatedXml: str = PyutXmlFinder.setAsISOLatin(text)

        file.write(updatedXml)
        file.close()
        chdir(oldPath)
        return True
Ejemplo n.º 20
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.logger:       Logger   = getLogger(__name__)
        self._parentFrame: Notebook = parentFrame   # Parent frame
        self._mediator:    Mediator = Mediator()

        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()
Ejemplo n.º 21
0
    def OnInit(self):

        PyutPreferences.determinePreferencesLocation()

        frameTop: Frame = Frame(parent=None,
                                id=TestToolboxFrame.FRAME_ID,
                                title="Test Toolbox Version 2",
                                size=(TestToolboxFrame.WINDOW_WIDTH,
                                      TestToolboxFrame.WINDOW_HEIGHT),
                                style=DEFAULT_FRAME_STYLE)
        frameTop.Show(True)

        TestBase.setUpLogging()

        self.logger: Logger = getLogger(__name__)
        diagramFrame: DiagramFrame = DiagramFrame(frameTop)
        diagramFrame.SetSize(
            (TestToolboxFrame.WINDOW_WIDTH, TestToolboxFrame.WINDOW_HEIGHT))
        diagramFrame.SetScrollbars(10, 10, 100, 100)

        diagramFrame.Show(True)

        self.SetTopWindow(diagramFrame)

        self._diagramFrame: DiagramFrame = diagramFrame

        self._mediator: Mediator = Mediator()

        self._mediator.registerAppFrame(frameTop)

        self._toolIconOwner: ToolIconOwner = ToolIconOwner()
        self._toolIconOwner.initializeIcons()

        frameTop.Bind(EVT_CLOSE, self.__onCloseFrame)

        self.initTest()

        return True
Ejemplo n.º 22
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()

                mediator: Mediator = Mediator()
                mediator.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()
Ejemplo n.º 23
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.startupSize.width,
                             self._prefs.startupSize.height)

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

        self.logger: Logger = getLogger(__name__)
        self._createApplicationIcon()
        self._plugMgr: PluginManager = PluginManager()

        self.CreateStatusBar()

        self._treeNotebookHandler: TreeNotebookHandler = TreeNotebookHandler(
            self)

        self._mediator: Mediator = Mediator()
        self._mediator.registerStatusBar(self.GetStatusBar())
        self._mediator.resetStatusText()
        self._mediator.registerAppFrame(self)
        self._mediator.registerFileHandling(self._treeNotebookHandler)
        self._mediator.registerAppPath(getcwd())

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

        self._toolPlugins: PluginMap = self._plugMgr.mapWxIdsToToolPlugins()
        self._importPlugins: PluginMap = self._plugMgr.mapWxIdsToImportPlugins(
        )
        self._exportPlugins: PluginMap = self._plugMgr.mapWxIdsToExportPlugins(
        )

        # Initialization
        fileMenu: Menu = Menu()
        editMenu: Menu = Menu()
        toolsMenu: Menu = Menu()
        helpMenu: Menu = Menu()
        self._fileMenuHandler: FileMenuHandler = FileMenuHandler(
            fileMenu=fileMenu, lastOpenFilesIDs=self.lastOpenedFilesID)
        self._editMenuHandler: EditMenuHandler = EditMenuHandler(
            editMenu=editMenu)

        self._initializePyutTools()

        self._toolboxIds: ToolboxIdMap = self._createToolboxIdMap()

        self._toolsMenuHandler: ToolsMenuHandler = ToolsMenuHandler(
            toolsMenu=toolsMenu,
            toolPluginsMap=self._toolPlugins,
            toolboxIds=self._toolboxIds)
        self._helpMenuHandler: HelpMenuHandler = HelpMenuHandler(
            helpMenu=helpMenu)

        self._menuCreator: MenuCreator = MenuCreator(
            frame=self, lastOpenFilesID=self.lastOpenedFilesID)
        self._menuCreator.fileMenu = fileMenu
        self._menuCreator.editMenu = editMenu
        self._menuCreator.toolsMenu = toolsMenu
        self._menuCreator.helpMenu = helpMenu
        self._menuCreator.fileMenuHandler = self._fileMenuHandler
        self._menuCreator.editMenuHandler = self._editMenuHandler
        self._menuCreator.toolsMenuHandler = self._toolsMenuHandler
        self._menuCreator.helpMenuHandler = self._helpMenuHandler
        self._menuCreator.toolPlugins = self._toolPlugins
        self._menuCreator.exportPlugins = self._exportPlugins
        self._menuCreator.importPlugins = self._importPlugins
        self._menuCreator.toolboxIds = self._toolboxIds

        self._menuCreator.initializeMenus()

        self.__setupKeyboardShortcuts()

        # set application title
        self._treeNotebookHandler.newProject()
        self._mediator.updateTitle()

        if self._prefs.centerAppOnStartUp is True:
            self.Center(BOTH)  # Center on the screen
        else:
            appPosition: Position = self._prefs.startupPosition
            self.SetPosition(pt=Point(x=appPosition.x, y=appPosition.y))

        # Initialize the tips frame
        self._alreadyDisplayedTipsFrame = False

        self.SetDropTarget(
            PyutFileDropTarget(treeNotebookHandler=self._treeNotebookHandler))

        if self.GetThemeEnabled() is True:
            self.SetThemeEnabled(True)

        self.Bind(EVT_ACTIVATE, self._onActivate)
        self.Bind(EVT_CLOSE, self.Close)
Ejemplo n.º 24
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()
        mediator: Mediator = Mediator()
        path:     str      = mediator.getAppPath()
        chdir(path)

        Lang.importLanguage()
        xmlString: str = ""
        suffix:    str = filename[-4:]
        if suffix == PyutConstants.PYUT_EXTENSION:
            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 suffix == PyutConstants.XML_EXTENSION:
            xmlString = open(filename, "r").read()
        else:
            PyutUtils.displayError(_(f"This is an unsupported file type: {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;
            #  I don't think this is used by the Python3 version of this Pyut
            self.logger.warning('***********************************')
            self.logger.warning('Using old code !!!')
            self.logger.warning('***********************************')
            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)
Ejemplo n.º 25
0
    def __init__(self, parent: Window):

        super().__init__(parent=parent, style=BORDER_SUNKEN)

        self._prefs: PyutPreferences = PyutPreferences()
        self._mediator: Mediator = Mediator()
Ejemplo n.º 26
0
    def __init__(self, menu: Menu):

        self._menu:     Menu     = menu
        self._mediator: Mediator = Mediator()
        self._parent:   Window   = self._menu.GetWindow()   # TODO this does not work at init