Esempio n. 1
0
    def _handle_buttons(self, event: wx.CommandEvent) -> None:
        """
        Handle button clicks, run seo check on the new values and display results. Prevent closing on ok if seo failed.
        :param event: The button event
        :return: None
        """
        if event.GetId() == wx.ID_DELETE:
            # Only OK and Cancel button close the dialog by default.
            event.Skip()
            self.EndModal(wx.ID_DELETE)
        elif event.GetId() == wx.ID_OK:
            self._run_spellcheck(
                ((self._field_link_title, Strings.label_link_title),
                 (self._field_link_text, Strings.label_text)))
            # Save new information into image and rerun seo test.
            self._link.set_text(self._field_link_text.GetValue())
            self._link.set_title(self._field_link_title.GetValue())
            self._link.set_url(self._field_url.GetValue())

            # Run seo test in thread and show a testing dialog.
            self._seo_test(return_value=wx.ID_OK)
        else:
            # Restore original values
            self._link.set_url(self._original_url)
            self._link.set_title(self._original_title)
            self._link.set_text(self._original_text)
            self._link.set_modified(False)
            self._seo_test(return_value=wx.ID_CANCEL)
    def _handle_buttons(self, event: wx.CommandEvent) -> None:
        """
        Handle button clicks, run seo check on the new values and display results. Prevent closing if seo failed.
        :param event: The button event.
        :return: None
        """
        if event.GetId() == wx.ID_OPEN:
            new_path, new_name = self._ask_for_image()
            if not new_path:
                # No image was selected
                event.Skip()
                return
            else:
                self._change_image(new_path, new_name)
                self._ok_button.SetDefault()
        elif event.GetId() == wx.ID_OK:
            # Save new information into image and rerun seo test.
            self._run_spellcheck(
                ((self._field_item_name, Strings.label_menu_item_name),
                 (self._field_image_link_title, Strings.label_link_title),
                 (self._field_image_alt, Strings.label_alt_description)))
            self._item_copy.set_article_name(self._field_item_name.GetValue())
            self._item_copy.set_link_title(
                self._field_image_link_title.GetValue())
            self._item_copy.set_image_alt(self._field_image_alt.GetValue())

            if self._item_copy.test_self():
                self._original_item.set_article_name(
                    self._item_copy.get_article_name()[0])
                self._original_item.set_link_title(
                    self._item_copy.get_link_title()[0])
                self._original_item.set_image_alt(
                    self._item_copy.get_image_alt()[0])
                self._original_item.set_href(self._item_copy.get_link_href())
                self._original_item.set_image_path(
                    self._item_copy.get_image_path())
                self._original_item.set_filename(
                    self._item_copy.get_filename())
                self._original_item.test_self()
                event.Skip()
                return
            else:
                self.display_dialog_contents()
        elif event.GetId() == wx.ID_ADD:
            dlg = AddLogoDialog(self, self._work_dir)
            saved = dlg.ShowModal()
            if saved == wx.ID_OK:
                result = wx.MessageBox(Strings.label_use_image,
                                       Strings.label_image,
                                       wx.YES_NO | wx.ICON_QUESTION)
                if result == wx.YES:
                    # This function must be used only when the add image dialog is confirmed.
                    # Parameter expansion, expands tuple into the two arguments needed by the function.
                    self._change_image(*dlg.get_logo_location())
            dlg.Destroy()
        else:
            # Leave the original item as it is.
            event.Skip()
 def _handle_image_buttons(self, event: wx.CommandEvent) -> None:
     """
     Handle image button clicks.
     :param event: The button event, used to distinguish between buttons.
     :return: None
     """
     event.Skip()
     if event.GetId() == wx.ID_FILE1:
         # Create menu item.
         if not self._menu_item:
             menu_item: MenuItem = MenuItem(
                 name='',
                 title='',
                 image_alt='',
                 href=self._field_name.GetValue() + Strings.extension_html,
                 disk_path='',
                 img_filename=Strings.label_none)
             menu_item.test_self()
         else:
             menu_item = self._menu_item
         edit_dialog = EditMenuItemDialog(
             self, menu_item, self._config_manager.get_working_dir())
         # We first need to show the dialog so that the name label can calculate it's size and then switch to modal.
         edit_dialog.Show()
         edit_dialog.display_dialog_contents()
         result = edit_dialog.ShowModal()
         edit_dialog.Destroy()
         if result == wx.ID_OK:
             # Display the image. Disable section and name fields and enable main image button.
             self._menu_logo_button.SetBitmap(
                 wx.Bitmap(menu_item.get_image()))
             self._field_name.Disable()
             self._box_menu.Disable()
             self._main_image_button.Enable()
             self._menu_item = menu_item
     elif event.GetId() == wx.ID_FILE2:
         # Create article image.
         if not self._article_image:
             image = AsideImage(caption='',
                                title='',
                                image_alt='',
                                original_image_path='',
                                thumbnail_path='',
                                full_filename=Strings.label_none,
                                thumbnail_filename=Strings.label_none)
             image.test_self()
         else:
             image = self._article_image
         edit_dialog = EditAsideImageDialog(
             self, image, self._config_manager.get_working_dir())
         result = edit_dialog.ShowModal()
         edit_dialog.Destroy()
         if result == wx.ID_OK:
             self._main_image_button.SetBitmap(wx.Bitmap(image.get_image()))
             self._ok_button.Enable()
             self._article_image = image
Esempio n. 4
0
    def OnMenuClicked(self, event: CommandEvent):
        handlers = {
            self.menuItemExit.GetId():
            self.Exit,
            self.menuItemAbout.GetId():
            self.ShowAboutDialog,
            self.menuItemHelpDoc.GetId():
            lambda: LaunchDefaultBrowser("https://hefang.link/url/mhosts-doc"),
            self.menuItemNew.GetId():
            lambda: self.ShowEditDialog(None),
            self.menuItemCheckUpdate.GetId():
            self.CheckUpdate,
            TrayIcon.ID_EXIT:
            self.Exit,
            TrayIcon.ID_TOGGLE:
            self.ToggleWindow,
            TrayIcon.ID_REFRESH_DNS:
            MainWindow.DoRefreshDNS,
            TrayIcon.ID_NEW:
            lambda: self.ShowEditDialog(None),
            TrayIcon.ID_ABOUT:
            lambda: self.aboutDialog.Show(),
            TrayIcon.ID_IMPORT:
            None,
            TrayIcon.ID_LUNCH_CHROME:
            lambda: MainWindow.LunchChrome(),
            TrayIcon.ID_LUNCH_CHROME_CROS:
            lambda: MainWindow.LunchChrome(
                "--disable-web-security --user-data-dir=%(temp)s%(sep)smHostsChromeTempDir%(sep)s%(time)d"
                % {
                    'temp': os.environ['TEMP'],
                    'sep': os.sep,
                    'time': time.time()
                }),
            TrayIcon.ID_LUNCH_CHROME_NO_PLUGINS:
            lambda: MainWindow.LunchChrome(
                "--disable-plugins --disable-extensions"),
            TrayIcon.ID_TREE_MENU_EDIT:
            lambda: self.ShowEditDialog(self.__currentSelectHost),
            TrayIcon.ID_TREE_MENU_SET_ACTIVE:
            lambda: self.ApplyHosts(self.__currentSelectHost["id"]),
            TrayIcon.ID_TREE_MENU_DELETE:
            lambda: self.DeleteHosts(self.__currentSelectHost)
        }

        if event.GetId() in handlers:
            callback = handlers[event.GetId()]
            if callable(callback):
                callback()
            else:
                MessagePanel.Send("该菜单绑定的事件不可用",
                                  "菜单点击",
                                  dpi=(self.dpiX, self.dpiY))
        else:
            MessagePanel.Send("该菜单没有绑定事件", "菜单点击", dpi=(self.dpiX, self.dpiY))
Esempio n. 5
0
    def _onNewAction(self, event: CommandEvent):
        """
        Call the mediator to specify the current action.

        Args:
            event:
        """
        currentAction: int = SharedIdentifiers.ACTIONS[event.GetId()]

        self._mediator.setCurrentAction(currentAction)
        self._mediator.selectTool(event.GetId())
        self._treeNotebookHandler.setModified(True)
        self._mediator.updateTitle()
Esempio n. 6
0
    def _OnNewAction(self, event: CommandEvent):
        """
        Call the mediator to specify the current action.

        Args:
            event:
        """
        currentAction: int = SharedIdentifiers.ACTIONS[event.GetId()]

        self._ctrl.setCurrentAction(currentAction)
        self._ctrl.selectTool(event.GetId())
        self._mainFileHandlingUI.setModified(True)
        self._ctrl.updateTitle()
 def _lock_fields(self, event: wx.CommandEvent) -> None:
     """
     Prevents automatic copying of text to other fields when they are edited manually.
     :param event:
     :return: None
     """
     if event.GetId() == wx.ID_FILE1:
         if self._field_image_alt.GetValue(
         ) != self._field_item_name.GetValue():
             self._alt_lock = True
     elif event.GetId() == wx.ID_FILE2:
         if self._field_image_link_title.GetValue(
         ) != self._field_item_name.GetValue():
             self._title_lock = True
Esempio n. 8
0
 def _handle_buttons(self, event: wx.CommandEvent) -> None:
     """
     Handle button clicks, run seo check on the new values and display results. Prevent closing if seo failed.
     :param event: The button event
     :return: None
     """
     event.Skip()
     if event.GetId() == wx.ID_OK:
         self._save()
     elif event.GetId() == wx.ID_SPELL_CHECK:
         self._run_spellcheck(
             ((self._field_page_name, Strings.label_menu_name),
              (self._field_meta_keywords, Strings.label_menu_meta_keywords),
              (self._field_meta_description,
               Strings.label_menu_meta_description)))
Esempio n. 9
0
    def _handle_buttons(self, event: wx.CommandEvent) -> None:
        """
        Handle button clicks, run seo check on the new values and display results. Prevent closing if seo failed.
        :param event: The button event
        :return: None
        """
        if event.GetId() == wx.ID_OPEN:
            new_path, new_name = self._ask_for_image()
            if not new_path:
                # No image was selected
                event.Skip()
                return
            else:
                self._change_image(new_path, new_name)
        elif event.GetId() == wx.ID_ADD:
            dlg = AddImageDialog(self, self._work_dir)
            saved = dlg.ShowModal()
            if saved == wx.ID_OK:
                result = wx.MessageBox(Strings.label_use_image, Strings.label_image, wx.YES_NO | wx.ICON_QUESTION)
                if result == wx.YES:
                    # This function must be used only when the add image dialog is confirmed.
                    # Parameter expansion, expands tuple into the two arguments needed by the function.
                    self._change_image(*dlg.get_thumbnail_location())
            dlg.Destroy()
        elif event.GetId() == wx.ID_OK:
            self._run_spellcheck(((self._field_image_link_title, Strings.label_link_title),
                                  (self._field_image_alt, Strings.label_alt_description)))
            # Save new information into the copy of the image and rerun seo test.
            self._image_copy.set_link_title(self._field_image_link_title.GetValue())
            self._image_copy.set_alt(self._field_image_alt.GetValue())

            if self._image_copy.test_self():
                # If the seo test is good, transfer all information into the original image.
                self._original_image.set_link_title(self._image_copy.get_link_title()[0])
                self._original_image.set_alt(self._image_copy.get_image_alt()[0])
                self._original_image.set_original_image_path(self._image_copy.get_original_image_path())
                self._original_image.set_thumbnail_image_path(self._image_copy.get_thumbnail_image_path())
                self._original_image.set_full_filename(self._image_copy.get_full_filename())
                self._original_image.set_thumbnail_filename(self._image_copy.get_thumbnail_filename())
                # Reinitialize internal variables after changes, this should never fail as the test was done on the copy
                self._original_image.test_self()
                event.Skip()
                return
            else:
                self._display_dialog_contents()
        else:
            # Leave the old image as it is and do not do anything.
            event.Skip()
    def _on_image_modify(self, event: wx.CommandEvent):
        """
        Move image up/down one position, remove or edit them.
        :param event: Used to distinguish between up/down buttons. And contains reference to the image that is being
        moved.
        :return: None
        """
        self._img_index = self._images.index(event.GetClientData())
        # Rearrange the images in the list
        if event.GetId() == wx.ID_UP:
            if self._img_index == 0:
                return
            self._images[self._img_index], self._images[self._img_index - 1] = \
                self._images[self._img_index - 1], self._images[self._img_index]
            set_modified = True
        elif event.GetId() == wx.ID_DOWN:
            if self._img_index + 1 == len(self._images):
                return
            self._images[self._img_index], self._images[self._img_index + 1] = \
                self._images[self._img_index + 1], self._images[self._img_index]
            set_modified = True
        # Remove image from list
        elif event.GetId() == wx.ID_DELETE:
            result = wx.MessageBox(Strings.text_remove_image,
                                   Strings.status_warning,
                                   wx.YES_NO | wx.ICON_WARNING)
            if result == wx.YES:
                del self._images[self._img_index]
            set_modified = True
        else:
            # Modify image data
            edit_dialog = EditAsideImageDialog(
                self, self._images[self._img_index],
                self._doc.get_working_directory())
            edit_dialog.ShowModal()
            set_modified = edit_dialog.was_modified()
            edit_dialog.Destroy()
        self.show_images()

        # Pass the event into the main frame to change document color in the file list. Always send the event because
        # that runs spellcheck on the rest of the frame in case we learned new words, but indicate whether we made
        # any changes to set the document modified.
        color_evt = Events.SidepanelChangedEvent(self.GetId())
        if set_modified:
            color_evt.SetInt(1)
        else:
            color_evt.SetInt(0)
        wx.PostEvent(self.GetEventHandler(), color_evt)
Esempio n. 11
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()
Esempio n. 12
0
    def OnMenuClick(self, event: CommandEvent):
        """
        Callback for popup menu on class

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

        pyutObject: PyutClass = self.getPyutObject()
        eventId:    int       = event.GetId()
        if eventId == MENU_TOGGLE_STEREOTYPE:
            pyutObject.setShowStereotype(not pyutObject.getShowStereotype())
            self.autoResize()
        elif eventId == MENU_TOGGLE_METHODS:
            pyutObject.showMethods = not pyutObject.showMethods     # flip it!!  too cute
            self.autoResize()
        elif eventId == MENU_TOGGLE_FIELDS:
            pyutObject.showFields = not pyutObject.showFields       # flip it!! too cute
            self.autoResize()
        elif eventId == MENU_FIT_FIELDS:
            self.autoResize()
        elif eventId == MENU_CUT_SHAPE:
            ctrl = getMediator()
            ctrl.deselectAllShapes()
            self.SetSelected(True)
            ctrl.cutSelectedShapes()
        elif eventId == MENU_IMPLEMENT_INTERFACE:
            ctrl = getMediator()
            ctrl.requestLollipopLocation(self)
        else:
            event.Skip()
Esempio n. 13
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}')
Esempio n. 14
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()
Esempio n. 15
0
    def __OnCheckBox(self, event: CommandEvent):
        """
        """
        self.__changed = True
        eventID: int = event.GetId()
        val:     bool = event.IsChecked()
        if eventID == self.__autoResizeID:
            self._prefs.autoResizeShapesOnEdit = val
        elif eventID == self.__showParamsID:
            self._mediator.showParams(val)
            self._prefs.showParameters = val
        elif eventID == self.__maximizeID:
            self._prefs.fullScreen = val
        elif eventID == self.__showTipsID:
            self._prefs.showTipsOnStartup = val
        elif eventID == self.__toolBarIconSizeID:
            if val is True:
                self._prefs.toolBarIconSize = ToolBarIconSize.SIZE_32
            else:
                self._prefs.toolBarIconSize = ToolBarIconSize.SIZE_16
            dlg: MessageDialog = MessageDialog(self, _("Icons will change size on next restart"), _("Warning"), OK | ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()

        else:
            self.clsLogger.warning(f'Unknown combo box ID: {eventID}')
Esempio n. 16
0
 def OnRaiseToTop(self, event: wx.CommandEvent) -> None:
     window = self._id_to_window[event.GetId()]
     # At least on Mac we need to call Show before Raise in case
     # the window is hidden (see issue #599).  It is not yet clear
     # what is wx expected behaviour.  See upstream issue
     # https://trac.wxwidgets.org/ticket/18762
     window.Show()
     window.Raise()
Esempio n. 17
0
    def _handle_buttons(self, event: wx.CommandEvent) -> None:
        """
        Handle button clicks, run seo check on the new values and display results. Prevent closing if seo failed.
        :param event: The button event
        :return: None
        """
        if event.GetId() == wx.ID_OK:
            # Run spellcheck then run seo test, then save if ok.
            self._run_spellcheck(
                ((self._field_global_title, Strings.label_global_title),
                 (self._field_author, Strings.label_author),
                 (self._field_meta_keywords, Strings.label_default_keywords),
                 (self._field_meta_description,
                  Strings.label_main_meta_description),
                 (self._field_black_text, Strings.label_main_page_text),
                 (self._field_red_text, Strings.label_main_page_warning)))
            if self._seo_test():
                # In these cases all documents must be re-exported to reflect the change.
                result = self._config_manager.store_global_title(
                    self._field_global_title.GetValue())
                self._save_all = self._save_all or result
                result = self._config_manager.store_author(
                    self._field_author.GetValue())
                self._save_all = self._save_all or result
                result = self._config_manager.store_script(
                    self._field_script.GetValue())
                self._save_all = self._save_all or result

                # Keywords can be individual for each page. The global value is for new articles.
                self._config_manager.store_url(self._field_url.GetValue())
                self._config_manager.store_global_keywords(
                    self._field_meta_keywords.GetValue())
                self._config_manager.store_contact(
                    self._field_contact.GetValue())
                self._config_manager.store_main_page_description(
                    self._field_meta_description.GetValue())
                self._config_manager.store_black_text(
                    self._field_black_text.GetValue())
                self._config_manager.store_red_text(
                    self._field_red_text.GetValue())
                self._config_manager.store_number_of_news(
                    self._news_spinner.GetValue())
                event.Skip()
        elif event.GetId() == wx.ID_CANCEL:
            event.Skip()
 def _handle_buttons(self, event: wx.CommandEvent) -> None:
     """
     Handle button clicks, save the file.
     :param event: The button event
     :return: None
     """
     event.Skip()
     if event.GetId() == wx.ID_OK:
         self._field_text.SaveFile(str(self._file_name))
Esempio n. 19
0
    def OnWindowDestroy_(self, wxEvent: wx.CommandEvent) -> None:
        if wxEvent.GetId() != self.wxId_:
            print("WARNING: Received EVT_WINDOW_DESTROY for another window!")
            return

        wxEvent.Skip()

        for tube in self.tubes_:
            tube.DisconnectAll()
Esempio n. 20
0
    def _onMenuItemSelected(self, event: CommandEvent, data):

        eventId: int = event.GetId()
        if eventId == MENU_ADD_BEND:
            self._addBend(data)
        elif eventId == MENU_REMOVE_BEND:
            self._removeBend(data)
        elif eventId == MENU_TOGGLE_SPLINE:
            self._toggleSpline()
Esempio n. 21
0
 def OnShowOrHide(self, event: wx.CommandEvent) -> None:
     window = self._id_to_window[event.GetId()]
     # The window might be hidden but maybe it's just iconized
     # (minimized) or maybe it's both.  If it's iconized we need to
     # restore it first
     if window.IsIconized():
         window.Restore()
         window.Show()
     else:
         window.Show(not window.IsShown())
Esempio n. 22
0
 def _handle_buttons(self, event: wx.CommandEvent) -> None:
     """
     Handle button clicks, run seo check on the new values and display results. Prevent closing if seo failed.
     :param event: The button event
     :return: None
     """
     if event.GetId() == wx.ID_OPEN:
         self._save_button.Disable()
         self._image_path, self._image_name = self._ask_for_image()
         if self._image_path and self._image_name:
             self._load_image()
             self._field_image_name.SetFocus()
         if self._menu_image:
             self._save_button.Enable()
     elif event.GetId() == wx.ID_OK:
         if self._save():
             event.Skip()
     elif event.GetId() == wx.ID_CANCEL:
         event.Skip()
Esempio n. 23
0
 def _handle_buttons(self, event: wx.CommandEvent) -> None:
     """
     Handle button clicks, run seo check on the new values and display results. Prevent closing if seo failed.
     :param event: The button event
     :return: None
     """
     if event.GetId() == wx.ID_OK:
         self._config_manager.store_spelling_language(self._language_list.GetValue())
         event.Skip()
     elif event.GetId() == wx.ID_EDIT:
         dlg = PlainTextEditDialog(self, self._user_dict)
         dlg.ShowModal()
         self._rerun_spellchecks = True
         dlg.Destroy()
     elif event.GetId() == wx.ID_IGNORE:
         dlg = PlainTextEditDialog(self, self._user_exclusion_list)
         dlg.ShowModal()
         self._rerun_spellchecks = True
         dlg.Destroy()
     elif event.GetId() == wx.ID_CANCEL:
         event.Skip()
Esempio n. 24
0
    def OnExport(self, event: CommandEvent):
        """
        Callback.

        Args:
            event: wxEvent event
        """
        # Create a plugin instance
        cl = self.plugins[event.GetId()]
        umlObjects: List[OglClass] = self._ctrl.getUmlObjects()
        umlFrame: UmlClassDiagramsFrame = self._ctrl.getUmlFrame()
        obj = cl(umlObjects, umlFrame)
        # Do plugin functionality
        # BeginBusyCursor()
        obj.doExport()
Esempio n. 25
0
    def _OnMnuLOF(self, event: CommandEvent):
        """
        Open a file from the last opened files list

        Args:
            event:
        """
        for index in range(self._prefs.getNbLOF()):
            if event.GetId() == self.lastOpenedFilesID[index]:
                try:
                    lst = self._prefs.getLastOpenedFilesList()
                    self._loadFile(lst[index])
                    self._prefs.addNewLastOpenedFilesEntry(lst[index])
                    self.__setLastOpenedFilesItems()
                except (ValueError, Exception) as e:
                    self.logger.error(f'{e}')
Esempio n. 26
0
    def onExport(self, event: CommandEvent):
        """
        Callback.

        Args:
            event: A command event
        """
        # Create a plugin instance
        cl = self._exportPlugins[event.GetId()]
        umlObjects: List[OglClass]      = self._mediator.getUmlObjects()
        umlFrame: UmlClassDiagramsFrame = self._mediator.getUmlFrame()
        obj = cl(umlObjects, umlFrame)
        try:
            wxYield()
            obj.doExport()
        except (ValueError, Exception) as e:
            PyutUtils.displayError(_("An error occurred while executing the selected plugin"), _("Error..."))
            self.logger.error(f'{e}')
Esempio n. 27
0
    def _onChangeTextSize(self, event: CommandEvent):
        """
        Callback for popup menu on class

        Args:
            event:
        """
        pyutText: PyutText = self.pyutText
        eventId: int = event.GetId()

        if eventId == ID_MENU_INCREASE_SIZE:
            pyutText.textSize += TEXT_SIZE_INCREMENT
        elif eventId == ID_MENU_DECREASE_SIZE:
            pyutText.textSize -= TEXT_SIZE_DECREMENT
        else:
            assert False, f'Unhandled text size event: {eventId}'

        self._textFont.SetPointSize(pyutText.textSize)
        self.__updateDisplay()
Esempio n. 28
0
    def onImport(self, event: CommandEvent):

        self._treeNotebookHandler.newProject()
        self._treeNotebookHandler.newDocument(DiagramType.CLASS_DIAGRAM)
        self._mediator.updateTitle()
        cl = self._importPlugins[event.GetId()]

        obj = cl(self._mediator.getUmlObjects(), self._mediator.getUmlFrame())

        # Do plugin functionality
        try:
            wxYield()
            obj.doImport()
        except (ValueError, Exception) as e:
            PyutUtils.displayError(_("An error occurred while executing the selected plugin"), _("Error..."))
            self.logger.error(f'{e}')

        parent: Window = self._menu.GetWindow()

        parent.Refresh()
Esempio n. 29
0
    def menuHandler(self, event: wx.CommandEvent) -> None:
        """Handles menu events.
		
		Take action(s) based on the id contained in the event. Passes the event on to
		the next handler when finished.
		
		Args:
			event (wx.CommandEvent): The event which called this function.
			"""
        id = event.GetId()
        logging.debug(f"Handling menu event {id}")
        if id == wx.ID_EXIT:
            self.GetParent().onExit(event)
        elif id == wx.ID_ABOUT:
            wx.MessageBox("Typing Test by Thomas Stivers")
        elif id == wx.ID_CLEAR:
            pass
        elif id == self._ADD_SENTENCES_FROM_FILE_ID:
            directory_name = os.path.abspath(".")
            file_name = ""
            with wx.FileDialog(self, "Import sentences from text file.",
                               directory_name, file_name, "*.txt",
                               wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as dlg:
                if dlg.ShowModal() == wx.ID_OK:
                    file_name = dlg.GetFilename()
                    directory_name = dlg.GetDirectory()
                    path = os.path.join(directory_name, file_name)
                    Sentences.fillSentences(filename=path)
        elif id == self._ADD_SENTENCE_ID:
            self.GetParent().tests_panel.onAddSentence(None)
        elif id == wx.ID_DELETE:
            self.GetParent().results_panel.onRemoveResult(event)
        elif id == self._EDIT_SENTENCE_ID:
            self.GetParent().tests_panel.onEditSentence(event)
        elif id == self._VIEW_RESULTS_ID:
            self.GetParent().notebook.ChangeSelection(0)
        elif id == self._VIEW_TESTS_ID:
            self.GetParent().notebook.ChangeSelection(1)
        elif id == self._VIEW_USERS_ID:
            self.GetParent().notebook.ChangeSelection(2)
        event.Skip()
Esempio n. 30
0
    def OnWindowTitle(self, event: wx.CommandEvent) -> None:
        """Action when user selects the menu item with the window title."""
        window = self._id_to_window[event.GetId()]
        # Don't just call Restore() without checking if the window is
        # really iconized otherwise it might unmaximize a maximized
        # window when the user only wanted to bring it to the front.
        if window.IsIconized():
            window.Restore()
        # On GTK3 calling Raise() would be enough since it also calls
        # Show(), but on other platforms we do need to call Show()
        # first (see issue #599).  It's unclear what is the expected
        # wx behaviour (see https://trac.wxwidgets.org/ticket/18762)
        window.Show()
        window.Raise()

        # On Windows and OSX, when adding/removing displays, it is
        # possible that a window is at a position that no longer
        # exists.  So ensure that the window is shown at valid
        # coordinates.
        if wx.Display.GetFromWindow(window) == wx.NOT_FOUND:
            window.SetPosition(wx.GetMousePosition())