Beispiel #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)
Beispiel #2
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()
    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}')
Beispiel #4
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}')
Beispiel #5
0
    def onSnapToGridChanged(self, event: CommandEvent):

        enabledValue: bool = event.IsChecked()
        BackgroundPreferences.clsLogger.info(
            f'onSnapToGridChanged - {enabledValue}')
        self._prefs.snapToGrid = enabledValue
        event.Skip(True)
 def checkbox_event(event: wx.CommandEvent):
     folder = event.GetEventObject().folder
     for node in folder.children:
         if hasattr(node, 'checkbox'):
             if not event.IsChecked():
                 node.checkbox.SetValue(False)
             node.checkbox.Enable(event.IsChecked())
     event.Skip()
Beispiel #7
0
    def onGridLineColorSelectionChanged(self, event: CommandEvent):

        colorValue: str = event.GetString()

        pyutColorEnum: PyutColorEnum = PyutColorEnum(colorValue)

        self._prefs.gridLineColor = pyutColorEnum

        event.Skip(True)
Beispiel #8
0
 def OnLevelChoice(self, evt: wx.CommandEvent):
     if evt.GetSelection() == 0:
         changeLevel('debug')
     elif evt.GetSelection() == 1:
         changeLevel('info')
     elif evt.GetSelection() == 2:
         changeLevel('warning')
     else:
         changeLevel('error')
Beispiel #9
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()
 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))
 def _on_menu_click(self, event: wx.CommandEvent) -> None:
     """
     When the image is moved, we add the AsideImage instance into the event so that the containing panel knows
     which image is being moved.
     :param event: The CommandEvent from the button.
     :return: None
     """
     event.SetClientData(self._image)
     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
Beispiel #13
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))
Beispiel #14
0
 def save(self, evt: wx.CommandEvent):
     if evt.GetEventObject().GetName() == 'BUWC':
         config.save(not evt.IsChecked(), 'showUninstallDialog')
     elif evt.GetEventObject().GetName() == 'VGFC':
         config.save(not evt.IsChecked(), 'showVerifyDialog')
     elif evt.GetEventObject().GetName() == 'SUCC':
         config.save(not evt.IsChecked(), 'startupUpdateCheck')
     elif evt.GetEventObject().GetName() == 'SSC':
         config.save(not evt.IsChecked(), 'showSplashScreen')
     elif evt.GetEventObject().GetName() == 'LDDL':
         config.save(self.LDDL.GetString(evt.GetSelection()), 'lang')
Beispiel #15
0
    def _OnObjectiveChanged(self, event: wx.CommandEvent) -> None:
        objective_name = event.GetString()
        self.crosshairBoxSize = 512 * wx.GetApp().Objectives.GetPixelSize()
        self.offset = wx.GetApp().Objectives.GetOffset()
        self.objectiveSelectedText.SetLabel(objective_name.center(15))
        colour = tuple(
            [int(x * 255) for x in wx.GetApp().Objectives.GetColour()])
        self.objectiveSelectedText.SetBackgroundColour(colour)

        #force a redraw so that the crosshairs are properly sized
        self.Refresh()
        event.Skip()
Beispiel #16
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()
Beispiel #17
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()
Beispiel #18
0
    def onEnableBackgroundGridChanged(self, event: CommandEvent):

        enabledValue: bool = event.IsChecked()
        BackgroundPreferences.clsLogger.warning(
            f'onEnableBackgroundGridChanged - {enabledValue}')
        self._prefs.backgroundGridEnabled = enabledValue
        if enabledValue is True:
            self._cbSnapToGrid.Enabled = True
        else:
            self._cbSnapToGrid.SetValue(False)
            self._cbSnapToGrid.Enabled = False
            self._prefs.snapToGrid = False
        event.Skip(True)
Beispiel #19
0
    def OnChar_(self, wxEvent: wx.CommandEvent) -> None:
        keyCode = wxEvent.GetKeyCode()

        if keyCode < wx.WXK_SPACE or keyCode == wx.WXK_DELETE or keyCode > 255:
            wxEvent.Skip()
            return

        if chr(keyCode) in string.digits or chr(keyCode) in ('.', '-'):
            # Allow this character to propagate
            wxEvent.Skip()
            return

        if not wx.Validator.IsSilent():
            wx.Bell()
 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
Beispiel #21
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)))
    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)
Beispiel #23
0
	def _onCheckEvent(self, evt: wx.CommandEvent):
		settingsStorage = self._getSettingsStorage()
		if evt.GetEventObject() is self._enabledCheckbox:
			isEnableAllChecked = evt.IsChecked()
			settingsStorage.highlightBrowseMode = isEnableAllChecked
			settingsStorage.highlightFocus = isEnableAllChecked
			settingsStorage.highlightNavigator = isEnableAllChecked
			if not self._ensureEnableState(isEnableAllChecked) and isEnableAllChecked:
				self._onEnableFailure()
			self.updateDriverSettings()
		else:
			self._updateEnabledState()

		providerInst: Optional[NVDAHighlighter] = self._providerControl.getProviderInstance()
		if providerInst:
			providerInst.refresh()
 def __OnCmdOk(self, event: CommandEvent):
     """
     """
     self._timer.Stop()
     event.Skip(skip=True)
     self.SetReturnCode(OK)
     self.EndModal(OK)
Beispiel #25
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()
Beispiel #26
0
    def OnImportChannels(self, event: wx.CommandEvent) -> None:
        """Add all channels in a file."""
        filepath = wx.LoadFileSelector('Select file to import',
                                       '',
                                       parent=self)
        if not filepath:
            return
        try:
            with open(filepath, 'r') as fh:
                new_channels = json.load(fh)
        except:
            cockpit.gui.ExceptionBox('Failed to read to \'%s\'' % filepath,
                                     parent=self)
        duplicated = [n for n in new_channels.keys() if n in self._channels]
        if duplicated:
            answer = wx.MessageBox(
                'The import will overwrite the following'
                ' channels: %s. Do you want to continue?' %
                ', '.join(duplicated),
                caption='Duplicated channels on loaded file',
                parent=self,
                style=wx.YES_NO)
            if answer != wx.YES:
                return

        menu = event.GetEventObject()
        for name, channel in new_channels.items():
            # Duplicated channels only need to update our dict but new
            # channels also need a new menu item.
            if name not in duplicated:
                self.Bind(wx.EVT_MENU, self.OnApplyChannel,
                          menu.Append(wx.ID_ANY, item=name))
            self._channels[name] = channel
Beispiel #27
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()
Beispiel #28
0
 def on_kill_focus(self, event: wx.CommandEvent) -> None:
     """On EVT_KILL_FOCUS, process the updated value."""
     if self._text_dirty:
         self.Undo()
         self._text_dirty = False
     self._selected_dirty = False
     event.Skip()
Beispiel #29
0
    def _onTxtNoteChange(self, event: CommandEvent):
        """
        Handle changes to the text in the widget identified by TXT_NOTE

        Args:
            event:
        """
        self._pyutNote.content = event.GetString()
Beispiel #30
0
    def __onTasksInParentProject(self, event: CommandEvent):

        if event.IsChecked() is True:
            self._preferences.singleTodoistProject = True
            self._parentProjectNameContainer.textControlEnabled(True)
        else:
            self._preferences.singleTodoistProject = False
            self._parentProjectNameContainer.textControlEnabled(False)