Exemple #1
0
    def getOglActors(self, xmlOglActors: NodeList) -> OglActors:
        """
        Parse the XML elements given and build data layer for PyUt actors.

        Args:
            xmlOglActors:       XML 'GraphicActor' elements

        Returns:
            A dictionary of OglActor objects
        """
        oglActors: OglActors = cast(OglActors, {})

        for xmlOglActor in xmlOglActors:
            pyutActor: PyutActor = PyutActor()

            # Building OGL Actor
            height: int = PyutUtils.strFloatToInt(xmlOglActor.getAttribute(PyutXmlConstants.ATTR_HEIGHT))
            width:  int = PyutUtils.strFloatToInt(xmlOglActor.getAttribute(PyutXmlConstants.ATTR_WIDTH))
            oglActor: OglActor = OglActor(pyutActor, width, height)

            xmlActor: Element = xmlOglActor.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_ACTOR)[0]

            pyutActor.setId(int(xmlActor.getAttribute(PyutXmlConstants.ATTR_ID)))
            pyutActor.setName(xmlActor.getAttribute(PyutXmlConstants.ATTR_NAME))
            pyutActor.setFilename(xmlActor.getAttribute(PyutXmlConstants.ATTR_FILENAME))

            # Adding properties necessary to place shape on a diagram frame
            x = PyutUtils.strFloatToInt(xmlOglActor.getAttribute(PyutXmlConstants.ATTR_X))
            y = PyutUtils.strFloatToInt(xmlOglActor.getAttribute(PyutXmlConstants.ATTR_Y))
            oglActor.SetPosition(x, y)

            oglActors[pyutActor.getId()] = oglActor

        return oglActors
Exemple #2
0
    def setUp(self):
        """
        Initialize.
        @author C.Dutoit
        """
        # Initialize mediator and error manager
        ctrl = Mediator.getMediator()
        ctrl.setScriptMode()
        fileHandling = MainUI(None, ctrl)
        ctrl.registerFileHandling(fileHandling)
        errorManager = ctrl.getErrorManager()
        errorManager.changeType(ErrorViewTypes.RAISE_ERROR_VIEW)
        whereWeAre: str = getcwd()
        PyutUtils.setBasePath(whereWeAre)

        # Create wx application
        # For python 3 and wx 4.x we need to save it so it does not get GC'ed
        self.app = App()

        #  Create frame
        # baseFrame = wxFrame(None, -1, "", size=(10, 10))
        baseFrame = Frame(None, -1, "", size=(10, 10))
        umlFrame = UmlFrame(baseFrame, None)
        umlFrame.Show(True)
        self._umlFrame = umlFrame
Exemple #3
0
    def getOglUseCases(self, xmlOglUseCases: NodeList) -> OglUseCases:
        """
        Parse the XML elements given and build data layer for PyUt actors.

        Args:
            xmlOglUseCases:     XML 'GraphicUseCase' elements

        Returns:
            A dictionary of OglUseCase objects
        """
        oglUseCases: OglUseCases = cast(OglUseCases, {})

        for xmlOglUseCase in xmlOglUseCases:

            pyutUseCase: PyutUseCase = PyutUseCase()

            # Building OGL UseCase
            height: int = PyutUtils.strFloatToInt(xmlOglUseCase.getAttribute(PyutXmlConstants.ATTR_HEIGHT))
            width:  int = PyutUtils.strFloatToInt(xmlOglUseCase.getAttribute(PyutXmlConstants.ATTR_WIDTH))
            oglUseCase = OglUseCase(pyutUseCase, width, height)

            xmlUseCase: Element = xmlOglUseCase.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_USE_CASE)[0]

            pyutUseCase.setId(int(xmlUseCase.getAttribute(PyutXmlConstants.ATTR_ID)))
            pyutUseCase.setName(xmlUseCase.getAttribute(PyutXmlConstants.ATTR_NAME))
            pyutUseCase.setFilename(xmlUseCase.getAttribute(PyutXmlConstants.ATTR_FILENAME))

            x: int = PyutUtils.strFloatToInt(xmlOglUseCase.getAttribute(PyutXmlConstants.ATTR_X))
            y: int = PyutUtils.strFloatToInt(xmlOglUseCase.getAttribute(PyutXmlConstants.ATTR_Y))
            oglUseCase.SetPosition(x, y)

            oglUseCases[pyutUseCase.getId()] = oglUseCase

        return oglUseCases
Exemple #4
0
    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
Exemple #5
0
    def _OnMnuHelpVersion(self, event: CommandEvent):
        """
        Check for newer version.
        Args:
            event:
        """
        # Init
        FILE_TO_CHECK = "http://pyut.sourceforge.net/backdoors/lastversion"  # TODO FIXME  :-)

        # Get file  -- Python 3 update
        f = request.urlopen(FILE_TO_CHECK)
        lstFile = f.readlines()
        f.close()

        # Verify data coherence
        if lstFile[0][:15] != "Last version = " or lstFile[
                1][:15] != "Old versions = ":
            msg = "Incorrect file on server"
        else:
            latestVersion = lstFile[0][15:]
            oldestVersions = lstFile[1][15:].split()
            print(oldestVersions)

            from org.pyut.general.PyutVersion import PyutVersion
            v = PyutVersion.getPyUtVersion()
            if v in oldestVersions:
                msg = _("PyUt version ") + str(latestVersion) + _(
                    " is available on http://pyut.sf.net")
            else:
                msg = _("No newer version yet !")

        # Display dialog box
        PyutUtils.displayInformation(msg, _("Check for newer version"), self)
Exemple #6
0
    def __positionAndSetupDiagramFrame(
        self,
        umlFrame: UmlDiagramsFrame,
        documentNode: Element,
    ):

        xStr: str = documentNode.getAttribute(
            PyutXmlConstants.ATTR_SCROLL_POSITION_X)
        yStr: str = documentNode.getAttribute(
            PyutXmlConstants.ATTR_SCROLL_POSITION_Y)

        scrollPosX: int = PyutUtils.secureInteger(xStr)
        scrollPosY: int = PyutUtils.secureInteger(yStr)

        umlFrame.Scroll(scrollPosX, scrollPosY)

        xPerUnitStr: str = documentNode.getAttribute(
            PyutXmlConstants.ATTR_PIXELS_PER_UNIT_X)
        yPerUnitStr: str = documentNode.getAttribute(
            PyutXmlConstants.ATTR_PIXELS_PER_UNIT_Y)

        pixelsPerUnitX: int = PyutUtils.secureInteger(xPerUnitStr)
        pixelsPerUnitY: int = PyutUtils.secureInteger(yPerUnitStr)
        if pixelsPerUnitX != 0 and pixelsPerUnitY != 0:
            umlFrame.SetScrollRate(xstep=pixelsPerUnitX, ystep=pixelsPerUnitY)
Exemple #7
0
    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()
Exemple #8
0
    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()
Exemple #9
0
    def onHelpVersion(self, event: CommandEvent):
        """
        Check for newer version.
        Args:
            event:
        """
        from org.pyut.general.PyutVersion import PyutVersion
        from org.pyut.general.GithubAdapter import GithubAdapter
        from org.pyut.general.SemanticVersion import SemanticVersion

        wxBeginBusyCursor()
        githubAdapter: GithubAdapter = GithubAdapter()
        latestVersion: SemanticVersion = githubAdapter.getLatestVersionNumber()

        myVersion: SemanticVersion = SemanticVersion(
            PyutVersion.getPyUtVersion())
        if myVersion < latestVersion:
            msg = _("PyUt version ") + str(latestVersion) + _(
                " is available on https://github.com/hasii2011/PyUt/releases")
        else:
            msg = _("No newer version yet !")

        wxEndBusyCursor()
        wxYield()
        PyutUtils.displayInformation(msg, _("Check for newer version"),
                                     self._parent)
Exemple #10
0
    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
Exemple #11
0
    def testBasicBasePath(self):
        basicPath: str = TestPyutUtils.BASE_TEST_PATH
        PyutUtils.setBasePath(basicPath)

        actualPath: str = PyutUtils.getBasePath()
        self.assertEqual(TestPyutUtils.BASE_TEST_PATH, actualPath,
                         'Path should have not been modified')
Exemple #12
0
    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()
Exemple #13
0
    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)
Exemple #14
0
    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
Exemple #15
0
    def _OnMnuHelpWeb(self, event: CommandEvent):
        """

        Args:
            event:
        """
        PyutUtils.displayInformation(
            f"Please point your browser to {AppFrame.PYUT_WIKI}",
            "Pyut's new wiki", self)
Exemple #16
0
    def onHelpWeb(self, event: CommandEvent):
        """

        Args:
            event:
        """
        PyutUtils.displayInformation(
            f"Please point your browser to {HelpMenuHandler.PYUT_WIKI}",
            "Pyut's new wiki", self._parent)
Exemple #17
0
    def testGetTempFilePathDebug(self):

        PyutPreferences.useDebugTempFileLocation = True
        PyutUtils.setBasePath(TestPyutUtils.BASE_TEST_PATH)

        fqFileName: str = PyutUtils.getTempFilePath(
            TestPyutUtils.FAKE_TEST_FILENAME)
        self.assertEqual(
            f'{TestPyutUtils.BASE_TEST_PATH}/{TestPyutUtils.FAKE_TEST_FILENAME}',
            fqFileName, 'Should be local path')
Exemple #18
0
    def _generateControlPoints(self, link: Element) -> ControlPoints:

        controlPoints: ControlPoints = cast(ControlPoints, [])

        for controlPoint in link.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_CONTROL_POINT):
            x = PyutUtils.strFloatToInt(controlPoint.getAttribute(PyutXmlConstants.ATTR_X))
            y = PyutUtils.strFloatToInt(controlPoint.getAttribute(PyutXmlConstants.ATTR_Y))
            controlPoints.append(ControlPoint(x, y))

        return controlPoints
Exemple #19
0
    def setUp(self):
        self.logger: Logger = TestPluginManager.clsLogger

        # Assume we are in src
        savePath: str = getcwd()

        newBasePath: str = getcwd()
        PyutUtils.setBasePath(newBasePath)
        chdir(savePath)

        self.pluginManager: PluginManager = PluginManager()
Exemple #20
0
    def _OnMnuRedo(self, event: CommandEvent):
        """

        Args:
            event:
        """
        if (self._mainFileHandlingUI.getCurrentFrame()) is None:
            PyutUtils.displayWarning(msg=_('No selected frame'),
                                     title=_('Huh!'))
            return
        self._mainFileHandlingUI.getCurrentFrame().getHistory().redo()
Exemple #21
0
    def getOglClasses(self, xmlOglClasses: NodeList) -> OglClasses:
        """
        Loads to OGL objects
        Parse the XML elements given and build data model for the Pyut classes.

        Args:
            xmlOglClasses:   XML 'GraphicClass' elements

        Returns:
                The built dictionary uses an ID for the key and an OglClass for the value
        """
        oglObjects: OglClasses = cast(OglClasses, {})

        for xmlOglClass in xmlOglClasses:

            xmlOglClass: Element   = cast(Element, xmlOglClass)
            pyutClass:   PyutClass = PyutClass()

            height: float      = float(xmlOglClass.getAttribute(PyutXmlConstants.ATTR_HEIGHT))
            width:  float      = float(xmlOglClass.getAttribute(PyutXmlConstants.ATTR_WIDTH))
            oglClass: OglClass = OglClass(pyutClass, width, height)

            xmlClass: Element = xmlOglClass.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_CLASS)[0]

            pyutClass.setId(int(xmlClass.getAttribute(PyutXmlConstants.ATTR_ID)))
            pyutClass.setName(xmlClass.getAttribute(PyutXmlConstants.ATTR_NAME))
            pyutClass.description = xmlClass.getAttribute(PyutXmlConstants.ATTR_DESCRIPTION)
            if xmlClass.hasAttribute(PyutXmlConstants.ATTR_STEREOTYPE):
                pyutClass.setStereotype(getPyutStereotype(xmlClass.getAttribute(PyutXmlConstants.ATTR_STEREOTYPE)))

            # adding display properties (cd)
            value = PyutUtils.secureBoolean(xmlClass.getAttribute(PyutXmlConstants.ATTR_SHOW_STEREOTYPE))
            pyutClass.setShowStereotype(value)
            value = PyutUtils.secureBoolean(xmlClass.getAttribute(PyutXmlConstants.ATTR_SHOW_METHODS))
            pyutClass.showMethods = value
            value = PyutUtils.secureBoolean(xmlClass.getAttribute(PyutXmlConstants.ATTR_SHOW_FIELDS))
            pyutClass.showFields = value

            pyutClass.setFilename(xmlClass.getAttribute(PyutXmlConstants.ATTR_FILENAME))

            pyutClass.methods = self._getMethods(xmlClass)
            pyutClass.fields  = self._getFields(xmlClass)

            # Adding properties necessary to place shape on a diagram frame
            x = float(xmlOglClass.getAttribute(PyutXmlConstants.ATTR_X))
            y = float(xmlOglClass.getAttribute(PyutXmlConstants.ATTR_Y))

            oglClass.SetPosition(x, y)

            oglObjects[pyutClass.getId()] = oglClass

        return oglObjects
Exemple #22
0
    def _OnMnuFileRemoveDocument(self, event: CommandEvent):
        """
        Remove the current document from the current project

        Args:
            event:
        """
        project = self._mainFileHandlingUI.getCurrentProject()
        document = self._mainFileHandlingUI.getCurrentDocument()
        if project is not None and document is not None:
            project.removeDocument(document)
        else:
            PyutUtils.displayWarning(_("No document to remove"))
Exemple #23
0
    def onRemoveDocument(self, event: CommandEvent):
        """
        Remove the current document from the current project

        Args:
            event:
        """
        project  = self._treeNotebookHandler.getCurrentProject()
        document = self._treeNotebookHandler.getCurrentDocument()
        if project is not None and document is not None:
            project.removeDocument(document)
        else:
            PyutUtils.displayWarning(_("No document to remove"))
Exemple #24
0
 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 setUp(self):
        self.logger: Logger = TestCommandGroup.clsLogger
        self._cgGroup: CommandGroup = CommandGroup(
            comment='This is a test group')

        PyutUtils.setBasePath(newValue=osGetCwd())
        mockFrame: MagicMock = MagicMock()
        historyMgr: HistoryManager = HistoryManager(theFrame=mockFrame)
        self._cgGroup.setHistory(history=historyMgr)

        saveFile = open(
            f'{TEST_DIRECTORY}{osSep}testdata{osSep}DeleteShape-Link.txt', 'r')
        self._fileContent = saveFile.read()
        saveFile.close()
Exemple #26
0
    def testGetTempFilePathProduction(self):

        PyutPreferences.useDebugTempFileLocation = False
        PyutUtils.setBasePath(TestPyutUtils.BASE_TEST_PATH)

        fqFileName: str = PyutUtils.getTempFilePath(
            TestPyutUtils.FAKE_TEST_FILENAME)
        #
        # Going to be something like:
        # /var/folders/83/_dybkw8115vcgcybw433gs4h0000gn/T/hasiiTheGreat.doc
        #
        self.assertNotEqual(
            f'{TestPyutUtils.BASE_TEST_PATH}/{TestPyutUtils.FAKE_TEST_FILENAME}',
            fqFileName, 'Should be system temp')
        self.logger.info(f'temp file name {fqFileName}')
Exemple #27
0
    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()
Exemple #28
0
    def __init__(self, parent):
        """
        """
        dialogStyle: int = RESIZE_BORDER | SYSTEM_MENU | CAPTION | FRAME_FLOAT_ON_PARENT | STAY_ON_TOP
        dialogSize: Size = Size(DEFAULT_WIDTH, DEFAULT_HEIGHT)
        super().__init__(parent, ID_ANY, _("Tips"), DefaultPosition,
                         dialogSize, dialogStyle)

        self._prefs: PyutPreferences = PyutPreferences()
        self._tipsFileName: str = PyutUtils.retrieveResourcePath(
            f'{DlgTips.TIPS_FILENAME}')

        self._tipHandler = TipHandler(fqFileName=self._tipsFileName)

        upSizer: BoxSizer = self._buildUpperDialog(
            self._tipHandler.getCurrentTipText())
        loSizer: BoxSizer = self._buildLowerDialog()

        self.SetAutoLayout(True)

        mainSizer: BoxSizer = BoxSizer(VERTICAL)

        mainSizer.Add(upSizer, WX_SIZER_NOT_CHANGEABLE, ALL | ALIGN_CENTER, 5)
        mainSizer.Add(self._chkShowTips, WX_SIZER_NOT_CHANGEABLE,
                      ALL | ALIGN_CENTER, 5)
        mainSizer.Add(loSizer, WX_SIZER_NOT_CHANGEABLE, ALL | ALIGN_CENTER, 5)

        mainSizer.Fit(self)

        self.Center(dir=VERTICAL)
        self.AcceptsFocus()
        self.SetSizer(mainSizer)

        self._bindEventHandlers()
    def __init__(self, theParent, imageOptions: ImageOptions = ImageOptions()):

        [
            self.__selectedFileId, self.__imageWidthId, self.__imageHeightId,
            self.__horizontalGapId, self.__verticalGapId, self.__fileSelectBtn,
            self.__imageFormatChoiceId
        ] = PyutUtils.assignID(7)

        super().__init__(theParent, theTitle='UML Image Generation Options')

        self.logger: Logger = getLogger(__name__)
        self._imageOptions: ImageOptions = imageOptions

        fs: StaticBoxSizer = self.__layoutFileSelection()
        imgS: StaticBoxSizer = self.__layoutImageSizeControls()
        imgF: StaticBoxSizer = self.__layoutImageFormatChoice()
        imgP: StaticBoxSizer = self.__layoutImagePadding()

        hs: Sizer = self._createDialogButtonsContainer(buttons=OK | CANCEL)

        mainSizer: BoxSizer = BoxSizer(orient=VERTICAL)
        mainSizer.Add(fs, 0, ALL | EXPAND, 5)
        mainSizer.Add(imgS, 0, ALL, 5)
        mainSizer.Add(imgF, 0, ALL, 5)
        mainSizer.Add(imgP, 0, ALL, 5)
        mainSizer.Add(hs, 0, ALIGN_RIGHT)

        self.SetSizer(mainSizer)

        mainSizer.Fit(self)
        self._bindEventHandlers()

        self.Bind(EVT_BUTTON, self._OnCmdOk, id=ID_OK)
        self.Bind(EVT_CLOSE, self._OnClose, id=ID_CANCEL)
Exemple #30
0
    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()