Ejemplo n.º 1
0
    def __createSimpleGridOptions(self) -> BoxSizer:

        szrSimple: BoxSizer = BoxSizer(VERTICAL)

        cbEnableBackgroundGrid: CheckBox = CheckBox(
            self, self.enableBackgroundGridID, _('Enable Background Grid'))
        cbSnapToGrid: CheckBox = CheckBox(self, self.snapToGridID,
                                          _('Snap to Grid'))

        box: StaticBox = StaticBox(self, ID_ANY, _("Grid Interval"))
        szrGridInterval: StaticBoxSizer = StaticBoxSizer(
            box, HORIZONTAL | ALIGN_LEFT)

        scGridInterval: SpinCtrl = SpinCtrl(self, self.scGridIntervalID, "")

        szrGridInterval.Add(scGridInterval, 0, LEFT | RIGHT,
                            BackgroundPreferences.HORIZONTAL_GAP)

        szrSimple.Add(cbEnableBackgroundGrid, 0, LEFT | RIGHT,
                      BackgroundPreferences.VERTICAL_GAP)
        szrSimple.Add(cbSnapToGrid, 0, LEFT | BOTTOM,
                      BackgroundPreferences.VERTICAL_GAP)

        szrSimple.AddSpacer(BackgroundPreferences.VERTICAL_GAP)
        szrSimple.Add(szrGridInterval, 0, LEFT | RIGHT | TOP,
                      BackgroundPreferences.VERTICAL_GAP)

        self._cbEnableBackgroundGrid: CheckBox = cbEnableBackgroundGrid
        self._cbSnapToGrid: CheckBox = cbSnapToGrid
        self._scGridInterval: SpinCtrl = scGridInterval

        return szrSimple
Ejemplo n.º 2
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()
Ejemplo n.º 3
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)
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
    def doAction(self, umlObjects: List[OglObject],
                 selectedObjects: List[OglObject], umlFrame: UmlFrame):
        """

        Args:
            umlObjects: list of the uml objects of the diagram
            selectedObjects:  list of the selected objects
            umlFrame: the frame of the diagram

        """
        if len(selectedObjects) != 1:
            dlg = MessageDialog(None,
                                _("You must select at most a single class"),
                                _("Warning"), OK | ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()

            return
        filename: str = ToFastEdit.FAST_EDIT_TEMP_FILE

        file: TextIO = open(filename, "w")
        self.write(selectedObjects[0], file)
        file.close()

        if sysPlatform == PyutConstants.THE_GREAT_MAC_PLATFORM:
            osSystem(f'open -W -a {self._editor} {filename}')
        else:
            osSystem(f'{self._editor} {filename}')
        file = open(filename, "r")
        self.read(selectedObjects[0], file)
        file.close()

        self._setProjectModified()
        self._cleanupTempFile()
Ejemplo n.º 6
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()
Ejemplo n.º 7
0
    def __init__(self, parent: Window, dialogIdentifier, pyutNote: PyutNote):
        """

        Args:
            parent:             parent window to center on
            dialogIdentifier:   An identifier for the dialog
            pyutNote:           Model object we are editing
        """
        super().__init__(parent, dialogIdentifier, _("Note Edit"))

        self._pyutNote: PyutNote = pyutNote

        label: StaticText = StaticText(self, ID_ANY, _("Note text"))
        self._txtCtrl: TextCtrl = TextCtrl(self,
                                           TXT_NOTE,
                                           self._pyutNote.content,
                                           size=(400, 180),
                                           style=TE_MULTILINE)
        self._txtCtrl.SetFocus()

        self._setupMainDialogLayout(self._txtCtrl, label)

        self.Bind(EVT_TEXT, self._onTxtNoteChange, id=TXT_NOTE)

        self.Centre()
Ejemplo n.º 8
0
    def __initCtrl(self):
        """
        Initialize the controls.
        """
        # IDs
        [self.__editorID] = PyutUtils.assignID(1)

        sizer = BoxSizer(VERTICAL)

        self.__lblEditor = StaticText(self, -1, _("Editor"))
        self.__txtEditor = TextCtrl(self, -1, size=(100, 20))
        sizer.Add(self.__lblEditor, 0, ALL, DlgFastEditOptions.GAP)
        sizer.Add(self.__txtEditor, 0, ALL, DlgFastEditOptions.GAP)

        hs = BoxSizer(HORIZONTAL)
        btnOk = Button(self, ID_OK, _("&OK"))
        hs.Add(btnOk, 0, ALL, DlgFastEditOptions.GAP)
        sizer.Add(hs, 0, CENTER)

        self.SetAutoLayout(True)
        self.SetSizer(sizer)
        sizer.Fit(self)
        sizer.SetSizeHints(self)

        btnOk.SetDefault()

        self.Bind(EVT_TEXT, self.__OnText, id=self.__editorID)

        self.__setValues()
        self.Center()

        self.__changed: bool = False
Ejemplo n.º 9
0
    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}"))
Ejemplo n.º 10
0
    def doAction(self, umlObjects: List[OglObject],
                 selectedObjects: List[OglClass], umlFrame: UmlFrame):
        """

        Args:
            umlObjects: list of the uml objects of the diagram
            selectedObjects:  list of the selected objects
            umlFrame: the frame of the diagram
        """
        if len(selectedObjects) != 1:
            dlg: MessageDialog = MessageDialog(
                None, _("You must select at most a single class"),
                _("Warning"), OK | ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return
        oglClass: OglClass = selectedObjects[0]

        if isinstance(oglClass, OglClass) is False:
            dlg = MessageDialog(None, _('Must be a UML Class'),
                                _('Bad Selection'), OK | ICON_ERROR | CENTER)
            dlg.ShowModal()
            dlg.Destroy()
            return

        filename: str = ToFastEdit.FAST_EDIT_TEMP_FILE

        self._writeTempTextFileForEditor(filename, oglClass)
        self._launchAppropriateEditor(filename)
        self._readTheModifiedTextFile(filename, oglClass)

        self._setProjectModified()
        self._cleanupTempFile()
Ejemplo n.º 11
0
 def OnLeftDClick(self, event):
     """
     """
     dlg = TextEntryDialog(None, _("Message"), _("Enter message"), self._pyutObject.getInstanceName(), OK | CANCEL | CENTRE)
     if dlg.ShowModal() == ID_OK:
         self._pyutObject.setInstanceName(dlg.GetValue())
     dlg.Destroy()
Ejemplo n.º 12
0
 def __init__(self):
     """
     """
     super().__init__(None,
                      _("Are you sure you want to remove this link ?"),
                      _("Remove link confirmation"),
                      style=YES_NO | ICON_QUESTION | NO_DEFAULT)
Ejemplo n.º 13
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()
Ejemplo n.º 14
0
    def __init__(self, parent: Window, dialogIdentifier,
                 document: PyutDocument):
        """

        Args:
            parent:             The parent window
            dialogIdentifier    An identifier for the dialog
            document:           The UML document we want to edit
        """
        super().__init__(parent, dialogIdentifier, _("Document Edit"))

        self.logger: Logger = getLogger(__name__)
        self._document: PyutDocument = document

        label: StaticText = StaticText(self, ID_ANY, _("Document Name"))
        self._nameEntry: TextCtrl = TextCtrl(parent=self,
                                             id=TXT_DOCUMENT_NAME,
                                             value=document.title)
        self._nameEntry.SetFocus()

        self._setupMainDialogLayout(self._nameEntry, label)

        self.Bind(EVT_TEXT, self._onDocumentNameChange, id=TXT_DOCUMENT_NAME)

        self.Centre()
        self.ShowModal()
Ejemplo n.º 15
0
    def _createMethodInformation(self) -> FlexGridSizer:

        # Txt Ctrl Name
        lblName: StaticText = StaticText(self, ID_ANY, _("Name"))
        self._txtName: TextCtrl = TextCtrl(self,
                                           ID_TXT_METHOD_NAME,
                                           "",
                                           size=(125, -1))
        self.Bind(EVT_TEXT, self._evtMethodText, id=ID_TXT_METHOD_NAME)

        # Txt Ctrl Modifiers
        lblModifiers: StaticText = StaticText(self, ID_ANY, _("Modifiers"))
        self._txtModifiers: TextCtrl = TextCtrl(self,
                                                ID_ANY,
                                                "",
                                                size=(125, -1))

        # Txt Ctrl Return Type
        lblReturn: StaticText = StaticText(self, ID_ANY, _("Return type"))
        self._txtReturn: TextCtrl = TextCtrl(self, ID_ANY, "", size=(125, -1))

        methodInfoContainer: FlexGridSizer = FlexGridSizer(cols=3,
                                                           hgap=6,
                                                           vgap=6)

        methodInfoContainer.AddMany([
            lblName, lblModifiers, lblReturn, self._txtName,
            self._txtModifiers, self._txtReturn
        ])

        return methodInfoContainer
Ejemplo n.º 16
0
    def _createDialogButtonsContainer(self, buttons=OK) -> BoxSizer:
        """
        Override base class with our custom version
        Args:
            buttons:    Unused in our implementation.

        Returns: The container
        """
        self._btnMethodCode: Button = Button(self, ID_BTN_METHOD_CODE,
                                             _('C&ode'))
        self._btnMethodOk: Button = Button(self, ID_BTN_METHOD_OK, _('&Ok'))
        self._btnMethodCancel: Button = Button(self, ID_BTN_METHOD_CANCEL,
                                               _('&Cancel'))

        self.Bind(EVT_BUTTON, self._onMethodCode, id=ID_BTN_METHOD_CODE)
        self.Bind(EVT_BUTTON, self._onMethodOk, id=ID_BTN_METHOD_OK)
        self.Bind(EVT_BUTTON, self._onMethodCancel, id=ID_BTN_METHOD_CANCEL)

        self._btnMethodOk.SetDefault()

        szrButtons: BoxSizer = BoxSizer(HORIZONTAL)
        szrButtons.Add(self._btnMethodCode, 0, ALL, 5)
        szrButtons.Add(self._btnMethodOk, 0, ALL, 5)
        szrButtons.Add(self._btnMethodCancel, 0, ALL, 5)

        return szrButtons
Ejemplo n.º 17
0
    def _createParameterButtonsContainer(self) -> BoxSizer:

        self._btnParamAdd: Button = Button(self, ID_BTN_PARAM_ADD, _("&Add"))
        self._btnParamEdit: Button = Button(self, ID_BTN_PARAM_EDIT,
                                            _("&Edit"))
        self._btnParamRemove: Button = Button(self, ID_BTN_PARAM_REMOVE,
                                              _("&Remove"))
        self._btnParamUp: Button = Button(self, ID_BTN_PARAM_UP, _("&Up"))
        self._btnParamDown: Button = Button(self, ID_BTN_PARAM_DOWN,
                                            _("&Down"))

        self.Bind(EVT_BUTTON, self._onParamAdd, id=ID_BTN_PARAM_ADD)
        self.Bind(EVT_BUTTON, self._onParamEdit, id=ID_BTN_PARAM_EDIT)
        self.Bind(EVT_BUTTON, self._onParamRemove, id=ID_BTN_PARAM_REMOVE)
        self.Bind(EVT_BUTTON, self._onParamUp, id=ID_BTN_PARAM_UP)
        self.Bind(EVT_BUTTON, self._onParamDown, id=ID_BTN_PARAM_DOWN)

        szrParamButtons: BoxSizer = BoxSizer(HORIZONTAL)

        szrParamButtons.Add(self._btnParamAdd, 0, ALL, 5)
        szrParamButtons.Add(self._btnParamEdit, 0, ALL, 5)
        szrParamButtons.Add(self._btnParamRemove, 0, ALL, 5)
        szrParamButtons.Add(self._btnParamUp, 0, ALL, 5)
        szrParamButtons.Add(self._btnParamDown, 0, ALL, 5)

        return szrParamButtons
Ejemplo n.º 18
0
    def __OnCheckBox(self, event: CommandEvent):
        """
        """
        self.__changed = True
        eventID = event.GetId()
        val = event.IsChecked()
        if eventID == self.__autoResizeID:
            self.__prefs[PyutPreferences.AUTO_RESIZE_SHAPE_ON_EDIT] = val
        elif eventID == self.__showParamsID:
            self.__ctrl.showParams(val)
            self.__prefs[PyutPreferences.SHOW_PARAMETERS] = val
        elif eventID == self.__maximizeID:
            self.__prefs[PyutPreferences.FULL_SCREEN] = val
        elif eventID == self.__showTipsID:
            self.__prefs[PyutPreferences.SHOW_TIPS_ON_STARTUP] = val
        elif eventID == self.__centerDiagramID:
            self.__prefs.centerAppOnStartup = val
            self.__setPositionControls()
            dlg = MessageDialog(
                self, _("You must restart Pyut for position changes"),
                _("Warning"), OK | ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()

        else:
            self.logger.warning(f'Unknown combo box ID: {eventID}')
Ejemplo n.º 19
0
    def removeDocument(self, document, confirmation=True):
        """
        Remove a given document from the project.

        Args:
            document: PyutDocument to remove from this project
            confirmation:  If `True` ask for confirmation
        """
        frame = document.getFrame()

        if confirmation:
            self._mediator.getFileHandling().showFrame(frame)

            dlg = MessageDialog(self._mediator.getUmlFrame(), _("Are you sure to remove the document ?"),
                                _("Remove a document from a project"), YES_NO)
            if dlg.ShowModal() == ID_NO:
                dlg.Destroy()
                return
            dlg.Destroy()

        # Remove references

        fileHandling = self._mediator.getFileHandling()
        fileHandling.removeAllReferencesToUmlFrame(frame)

        document.removeFromTree()

        # Remove document from documents list
        self._documents.remove(document)
Ejemplo n.º 20
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
Ejemplo n.º 21
0
    def __init__(self, parent, ID, pyutUseCase):
        """
        Constructor.

        @since 1.0
        @author Philippe Waelti <*****@*****.**>
        """
        super().__init__(parent,
                         ID,
                         _("Use Case Edit"),
                         style=RESIZE_BORDER | CAPTION)

        # Associated PyutUseCase
        self._pyutUseCase = pyutUseCase

        self.SetAutoLayout(True)

        self._text = self._pyutUseCase.getName()
        self._returnAction = -1  # describe how the user exited the dialog box

        label = StaticText(self, -1, _("Use case text"))

        self._txtCtrl = TextCtrl(self,
                                 TXT_USECASE,
                                 self._text,
                                 size=(400, 180),
                                 style=TE_MULTILINE)
        self._txtCtrl.SetFocus()

        # text events
        self.Bind(EVT_TEXT, self._onTxtChange, id=TXT_USECASE)

        btnOk = Button(self, OK, _("&Ok"))
        btnOk.SetDefault()
        btnCancel = Button(self, CANCEL, _("&Cancel"))

        self.Bind(EVT_BUTTON, self._onCmdOk, id=OK)
        self.Bind(EVT_BUTTON, self._onCmdCancel, id=CANCEL)

        szrButtons = BoxSizer(HORIZONTAL)
        szrButtons.Add(btnOk, 0, RIGHT, 10)
        szrButtons.Add(btnCancel, 0, ALL)

        szrMain = BoxSizer(VERTICAL)
        szrMain.Add(label, 0, BOTTOM, 5)
        szrMain.Add(self._txtCtrl, 1, EXPAND | BOTTOM, 10)
        szrMain.Add(szrButtons, 0, ALIGN_CENTER_HORIZONTAL)
        # Border
        szrBorder = BoxSizer(VERTICAL)
        szrBorder.Add(szrMain, 1, EXPAND | ALL, 10)
        self.SetSizer(szrBorder)
        szrBorder.Fit(self)

        self.Centre()
        self.ShowModal()
Ejemplo n.º 22
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()
Ejemplo n.º 23
0
    def OnLeftDClick(self, event):
        """
        Callback for left double clicks.

        """
        dlg = TextEntryDialog(None, _("Message"), _("Enter message"),
                              self._pyutSDMessage.getMessage(),
                              OK | CANCEL | CENTRE)
        if dlg.ShowModal() == ID_OK:
            self._pyutSDMessage.setMessage(dlg.GetValue())
        dlg.Destroy()
Ejemplo n.º 24
0
    def _initializeAddHierarchySubMenu(self, mnuEdit: Menu) -> Menu:

        sub: Menu = Menu()
        sub.Append(SharedIdentifiers.ID_MNU_ADD_PYUT_HIERARCHY, _("&Pyut"),
                   _("Add the UML Diagram of Pyut"))
        sub.Append(SharedIdentifiers.ID_MNU_ADD_OGL_HIERARCHY, _("&Ogl"),
                   _("Add the UML Diagram of Pyut - Ogl"))

        mnuEdit.Append(NewIdRef(), _('Add Hierarchy'), sub)

        return mnuEdit
Ejemplo n.º 25
0
    def write(self, oglObjects: List[OglClass]):
        """

        Args:
            oglObjects:
        """
        directory = self._askForDirectoryExport()
        if directory == "":
            return False

        self.logger.info("IoPython Saving...")

        classes: Dict[str, List[str]] = {}
        generatedClassDoc: List[str] = self._pyutToPython.generateTopCode()

        # Create classes code for each object
        for oglClass in [oglObject for oglObject in oglObjects if isinstance(oglObject, OglClass)]:

            oglClass:  OglClass  = cast(OglClass, oglClass)
            pyutClass: PyutClass = oglClass.getPyutObject()

            generatedStanza:    str       = self._pyutToPython.generateClassStanza(pyutClass)
            generatedClassCode: List[str] = [generatedStanza]

            clsMethods: PyutToPython.MethodsCodeType = self._pyutToPython.generateMethodsCode(pyutClass)

            # Add __init__ Method
            if PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR in clsMethods:
                methodCode = clsMethods[PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR]
                generatedClassCode += methodCode
                del clsMethods[PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR]

            # Add others methods in order
            for pyutMethod in pyutClass.methods:
                methodName: str = pyutMethod.getName()
                if methodName != PyutToPython.SPECIAL_PYTHON_CONSTRUCTOR:
                    try:
                        methodCode: List[str] = clsMethods[methodName]
                        generatedClassCode += methodCode
                    except (ValueError, Exception, KeyError) as e:
                        self.logger.warning(f'{e}')

            generatedClassCode.append("\n\n")
            # Save to classes dictionary
            classes[pyutClass.getName()] = generatedClassCode

        # Write class code to a file
        for (className, classCode) in list(classes.items()):
            self._writeClassToFile(classCode, className, directory, generatedClassDoc)

        self.logger.info("IoPython done !")

        MessageBox(_("Done !"), _("Python code generation"), style=CENTRE | OK | ICON_INFORMATION)
Ejemplo n.º 26
0
    def shapeSelected(self, shape, position=None):
        """
        Do action when a shape is selected.
        TODO : support each link type
        """
        umlFrame = self._fileHandling.getCurrentFrame()
        if umlFrame is None:
            return

        # do the right action
        if self._currentAction in SOURCE_ACTIONS:
            self.logger.debug(f'Current action in source actions')
            # get the next action needed to complete the whole action
            if self._currentActionPersistent:
                self._oldAction = self._currentAction
            self._currentAction = NEXT_ACTION[self._currentAction]

            # if no source, cancel action
            if shape is None:
                self.logger.info("Action cancelled (no source)")
                self._currentAction = ACTION_SELECTOR
                self.selectTool(self._tools[0])
                self.setStatusText(_("Action cancelled"))
            else:  # store source
                self.logger.debug(
                    f'Store source - shape {shape}  position: {position}')
                self._src = shape
                self._srcPos = position
        elif self._currentAction in DEST_ACTIONS:
            self.logger.debug(f'Current action in destination actions')
            # store the destination object
            self._dst = shape
            self._dstPos = position
            # if no destination, cancel action
            if self._dst is None:
                self._currentAction = ACTION_SELECTOR
                self.selectTool(self._tools[0])
                self.setStatusText(_("Action cancelled"))
                return
            self._createLink(umlFrame)

            if self._currentActionPersistent:
                self._currentAction = self._oldAction
                del self._oldAction
            else:
                self._currentAction = ACTION_SELECTOR
                self.selectTool(self._tools[0])
        else:
            self.setStatusText(
                _("Error : Action not supported by the mediator"))
            return
        self.setStatusText(MESSAGES[self._currentAction])
Ejemplo n.º 27
0
    def __init__(self, parent, ID, title):
        """
        Constructor.

        @since 1.0
        @author C.Dutoit
        """
        # dialog box
        super().__init__(parent, ID, title, DefaultPosition, Size(720, 520))

        self.Center(BOTH)

        self.html = HtmlWindow(self, -1, DefaultPosition, Size(720, 520))

        htmlFileName = resource_filename(DlgHelp.HELP_PKG_NAME, 'index.html')
        self.html.LoadPage(htmlFileName)

        self.printer = HtmlEasyPrinting()

        self.box = BoxSizer(VERTICAL)
        self.box.Add(self.html, 1, GROW)
        subbox = BoxSizer(HORIZONTAL)

        btn = Button(self, ID_BACK, _("Back"))
        self.Bind(EVT_BUTTON, self.__OnBack, id=ID_BACK)
        subbox.Add(btn, 1, GROW | ALL, 2)

        btn = Button(self, ID_FORWARD, _("Forward"))
        self.Bind(EVT_BUTTON, self.__OnForward, id=ID_FORWARD)
        subbox.Add(btn, 1, GROW | ALL, 2)

        btn = Button(self, ID_PRINT, _("Print"))
        self.Bind(EVT_BUTTON, self.__OnPrint, id=ID_PRINT)
        subbox.Add(btn, 1, GROW | ALL, 2)

        btn = Button(self, ID_VIEW_SOURCE, _("View Source"))
        self.Bind(EVT_BUTTON, self.__OnViewSource, id=ID_VIEW_SOURCE)
        subbox.Add(btn, 1, GROW | ALL, 2)

        btn = Button(self, ID_OK, _("Exit"))
        subbox.Add(btn, 1, GROW | ALL, 2)

        self.box.Add(subbox, 0, GROW | BOTTOM)
        self.SetSizer(self.box)
        self.SetAutoLayout(True)
        subbox.Fit(self)
        self.box.Fit(self)

        self.OnShowDefault(None)

        self.Show(True)
Ejemplo n.º 28
0
    def onClose(self) -> bool:
        """
        Close all files

        Returns:
            True if everything is ok
        """
        # 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 projects and ask for unsaved but modified projects
        if not self._mediator.isInScriptMode():
            for project in self._projects:
                if project.getModified() is True:
                    frames = project.getFrames()
                    if len(frames) > 0:
                        frame = frames[0]
                        frame.SetFocus()
                        wxYield()
                        self.showFrame(frame)
                    dlg = MessageDialog(
                        self.__parent,
                        _("Your diagram has not been saved! Would you like to save it?"
                          ), _("Save changes?"), YES_NO | ICON_QUESTION)
                    if dlg.ShowModal() == ID_YES:
                        # save
                        if self.saveFile() is False:
                            return False
                    dlg.Destroy()

        from org.pyut.ui.frame.PyutApplicationFrame import PyutApplicationFrame  # Prevent recursion import problem
        from org.pyut.ui.Mediator import Mediator

        # dereference all
        self.__notebook.DeleteAllPages()
        self.__notebook = None

        self.__parent = cast(PyutApplicationFrame, None)
        self._projects = cast(List[PyutProject], None)
        self._mediator = cast(Mediator, None)
        self._currentProject = cast(PyutProject, None)
        self._currentFrame = cast(UmlDiagramsFrame, None)

        self.__splitter = None
        self.__projectTree = None
        self.__splitter = None

        return True
Ejemplo n.º 29
0
    def _createMenu(self) -> Menu:

        menu: Menu = Menu()

        increaseItem: MenuItem = menu.Append(
            ID_MENU_INCREASE_SIZE, _('Increase Size'),
            _('Increase Text Size by 2 points'))
        decreaseItem: MenuItem = menu.Append(
            ID_MENU_DECREASE_SIZE, _('Decrease Size'),
            _('Decrease Text Size by 2 points'))

        incBmp: Bitmap = IncreaseTextSize.GetBitmap()
        increaseItem.SetBitmap(incBmp)
        decBmp: Bitmap = DecreaseTextSize.GetBitmap()
        decreaseItem.SetBitmap(decBmp)

        boldItem: MenuItem = menu.AppendCheckItem(ID_MENU_BOLD_TEXT,
                                                  item=_('Bold Text'),
                                                  help=_('Set text to bold'))
        italicizedItem: MenuItem = menu.AppendCheckItem(
            ID_MENU_ITALIC_TEXT,
            item=_('Italicize Text'),
            help=_('Set text to italics'))

        if self.pyutText.isBold is True:
            boldItem.Check(check=True)
        if self.pyutText.isItalicized is True:
            italicizedItem.Check(check=True)

        menu.Bind(EVT_MENU, self._onChangeTextSize, id=ID_MENU_INCREASE_SIZE)
        menu.Bind(EVT_MENU, self._onChangeTextSize, id=ID_MENU_DECREASE_SIZE)
        menu.Bind(EVT_MENU, self._onToggleBold, id=ID_MENU_BOLD_TEXT)
        menu.Bind(EVT_MENU, self._onToggleItalicize, id=ID_MENU_ITALIC_TEXT)

        return menu
Ejemplo n.º 30
0
    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