Ejemplo n.º 1
0
    def __createLanguageControlContainer(self) -> BoxSizer:
        """
        Creates the language control inside a container

        Returns:
            The sizer that contains the language selection control
        """

        # Language
        self.__lblLanguage: StaticText = StaticText(self, ID_ANY,
                                                    _("Language"))
        self.logger.info(f'We are running on: {platform}')
        #
        # wx.CB_SORT not currently supported by wxOSX/Cocoa (True even as late as wx 4.0.7
        #
        if platform == PyutConstants.THE_GREAT_MAC_PLATFORM:
            self.__cmbLanguage = ComboBox(
                self,
                self.__languageID,
                choices=[el[0] for el in list(Lang.LANGUAGES.values())],
                style=CB_READONLY)
        else:
            self.__cmbLanguage = ComboBox(
                self,
                self.__languageID,
                choices=[el[0] for el in list(Lang.LANGUAGES.values())],
                style=CB_READONLY | CB_SORT)
        szrLanguage: BoxSizer = BoxSizer(HORIZONTAL)
        szrLanguage.Add(self.__lblLanguage, 0, ALL,
                        DlgPyutPreferences.HORIZONTAL_GAP)
        szrLanguage.Add(self.__cmbLanguage, 0, ALL,
                        DlgPyutPreferences.HORIZONTAL_GAP)

        return szrLanguage
Ejemplo n.º 2
0
    def crt_combobox(self, choices, size=(-1, -1), event_handler=None):
        combobox = ComboBox(self, choices=choices, size=size, style=wx.CB_READONLY)

        if event_handler is not None:
            combobox.Bind(wx.EVT_COMBOBOX, event_handler)

        return combobox
Ejemplo n.º 3
0
    def __createLanguageControlContainer(self) -> StaticBoxSizer:
        """
        Creates the language control inside a container

        Returns:
            The sizer that contains the language selection control
        """
        self.clsLogger.info(f'We are running on: {platform}')

        choices = [el[0] for el in list(LANGUAGES.values())]

        if platform == PyutConstants.THE_GREAT_MAC_PLATFORM:
            self.__cmbLanguage = ComboBox(self,
                                          self.__languageID,
                                          choices=choices,
                                          style=CB_READONLY | CB_SORT)
        else:
            self.__cmbLanguage = ComboBox(self,
                                          self.__languageID,
                                          choices=choices,
                                          style=CB_READONLY | CB_SORT)
        box: StaticBox = StaticBox(self, ID_ANY, _("Language"))
        szrGridStyle: StaticBoxSizer = StaticBoxSizer(box, HORIZONTAL)

        szrGridStyle.Add(self.__cmbLanguage, WX_SIZER_CHANGEABLE, ALL,
                         MiscellaneousPreferences.HORIZONTAL_GAP)

        return szrGridStyle
Ejemplo n.º 4
0
def combobox(element, instance: wx.ComboBox) -> wx.Object:
    props = exclude(element['props'], {'value'})
    # ComboBox is a textctrl and listbox linked together.
    # Updating one causes events to fire for the other, so
    # to avoid doubling up the events, we unhook everything,
    # perform the updates, and then re-add the handlers.
    instance.Unbind(wx.EVT_COMBOBOX)
    instance.Unbind(wx.EVT_TEXT)

    set_basic_props(instance, props)
    # we blanket delete/recreate the items for now, which
    # seems to be Good Enough. Child diffing could be benchmarked
    # to see if it's worth the effort.
    for _ in instance.GetItems():
        instance.Delete(0)
    instance.AppendItems(props.get('choices', []))
    if 'value' in props:
        instance.SetSelection(props['choices'].index(element['props'].get('value')))

    if props.get('on_change'):
        instance.Bind(wx.EVT_COMBOBOX, props['on_change'])
    if props.get('on_input'):
        instance.Bind(wx.EVT_TEXT, props['on_input'])

    return instance
Ejemplo n.º 5
0
    def __create_widgets(self):
        sizer = self.GetSizer()

        # Next row
        inner_sizer = BoxSizer(HORIZONTAL)
        label = StaticText(self, label=u'Class path:')
        inner_sizer.Add(label, flag=ALL)

        self.cb_class_path = ComboBox(self, style=CB_READONLY)
        self.cb_class_path.Bind(EVT_COMBOBOX, self.__on_load_po_class)
        inner_sizer.Add(self.cb_class_path, 1, flag=FLAG_ALL_AND_EXPAND)

        self.btn_reload = Button(self, label=u'Reload')
        self.btn_reload.Bind(EVT_BUTTON, self.__on_load_po_class)
        inner_sizer.Add(self.btn_reload, flag=ALL)

        self.btn_open_class = Button(self, label=u'Open class')
        self.btn_open_class.Bind(EVT_BUTTON, self.__open_class)
        inner_sizer.Add(self.btn_open_class, flag=ALL)

        row = 0
        sizer.Add(inner_sizer, pos=(row, 0), flag=FLAG_ALL_AND_EXPAND)

        # Next row
        row += 1
        splitter = SplitterWindow(self, style=SP_3D | SP_LIVE_UPDATE)

        self.image_panel = ImageWithElements(splitter)
        self.image_panel.static_bitmap.Bind(EVT_MOTION, self.__on_mouse_move)
        self.image_panel.static_bitmap.Bind(EVT_RIGHT_DOWN, self.__on_right_click)

        self.table_and_test_file_tabs = FieldsTableAndTestFilesTabs(splitter, self)

        splitter.SplitHorizontally(self.image_panel, self.table_and_test_file_tabs)
        sizer.Add(splitter, pos=(row, 0), flag=FLAG_ALL_AND_EXPAND)

        sizer.AddGrowableRow(row, 1)
        sizer.AddGrowableCol(0, 1)
Ejemplo n.º 6
0
    def __createTextSizeSelectorContainer(self,
                                          parent: Window) -> StaticBoxSizer:

        box: StaticBox = StaticBox(self, ID_ANY, _("Font Size"))
        szrFontSize: StaticBoxSizer = StaticBoxSizer(box, HORIZONTAL)

        fontSizes: List[str] = [
            '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18',
            '19', '20'
        ]
        self._cbxFontSizeSelector = ComboBox(parent,
                                             self._cbxFontSizeSelectorId,
                                             choices=fontSizes,
                                             style=CB_READONLY)

        szrFontSize.Add(self._cbxFontSizeSelector, 1, LEFT | RIGHT,
                        TextAttributesContainer.MINI_GAP)

        return szrFontSize
Ejemplo n.º 7
0
    def __createTextFontSelectorContainer(self,
                                          parent: Window) -> StaticBoxSizer:

        fontChoices = []
        for fontName in TextFontEnum:
            fontChoices.append(fontName.value)

        box: StaticBox = StaticBox(self, ID_ANY, _("Text Font"))
        szrFont: StaticBoxSizer = StaticBoxSizer(box, HORIZONTAL)

        self._cbxFontSelector = ComboBox(parent,
                                         self._cbxFontSelectorId,
                                         choices=fontChoices,
                                         style=CB_READONLY)

        szrFont.Add(self._cbxFontSelector, 1, LEFT | RIGHT,
                    TextAttributesContainer.MINI_GAP)

        return szrFont
Ejemplo n.º 8
0
    def _createRepositorySelection(self) -> StaticBoxSizer:

        repoSelectionWxId: int = wxNewIdRef()

        self._repositorySelection: ComboBox = ComboBox(self,
                                                       repoSelectionWxId,
                                                       style=CB_DROPDOWN
                                                       | CB_READONLY)

        sz = StaticBoxSizer(VERTICAL, self, "Repository List")
        sz.Add(self._repositorySelection, BasePanel.PROPORTION_NOT_CHANGEABLE,
               EXPAND)

        self.__populateRepositories()

        self.Bind(EVT_COMBOBOX,
                  self._onRepositorySelected,
                  id=repoSelectionWxId)

        return sz
Ejemplo n.º 9
0
    def __createGridLineColorContainer(self) -> StaticBoxSizer:
        """
        Creates the grid line selection control inside a container

        Returns:
            The sizer that contains the language selection control
        """
        colorChoices = []
        for cc in PyutColorEnum:
            colorChoices.append(cc.value)

        self._cmbGridLineColor: ComboBox = ComboBox(self,
                                                    self.colorID,
                                                    choices=colorChoices,
                                                    style=CB_READONLY)

        box: StaticBox = StaticBox(self, ID_ANY, _("Grid Line Color"))
        szrColor: StaticBoxSizer = StaticBoxSizer(box, HORIZONTAL)

        szrColor.Add(self._cmbGridLineColor, 1, LEFT | RIGHT,
                     BackgroundPreferences.MINI_GAP)

        return szrColor
Ejemplo n.º 10
0
    def __init__(self, parent, dpi=(1, 1)):
        Dialog.__init__(self,
                        parent,
                        id=ID_ANY,
                        title=u"编辑/添加Hosts",
                        pos=Point(600, 600),
                        size=Size(394 * dpi[0], 210 * dpi[1]),
                        style=DEFAULT_DIALOG_STYLE | FRAME_FLOAT_ON_PARENT)
        self.__window = parent
        self.SetSizeHints(DefaultSize, DefaultSize)

        font = Font(10, FONTFAMILY_DEFAULT, FONTSTYLE_NORMAL,
                    FONTWEIGHT_NORMAL, False, EmptyString)
        inputSize = Size(260 * dpi[0], -1)
        self.SetFont(font)
        fgSizer3 = FlexGridSizer(0, 2, 0, 0)
        fgSizer3.SetFlexibleDirection(BOTH)
        fgSizer3.SetNonFlexibleGrowMode(FLEX_GROWMODE_SPECIFIED)

        self.localRadio = RadioButton(self, ID_ANY, u"本地Hosts",
                                      DefaultPosition, DefaultSize, 0)
        self.localRadio.SetFont(font)
        fgSizer3.Add(self.localRadio, 0, ALL, 5)
        self.localRadio.Bind(EVT_RADIOBUTTON, self.OnRadioChange)

        self.onlineRadio = RadioButton(self, ID_ANY, u"在线Hosts",
                                       DefaultPosition, DefaultSize, 0)
        fgSizer3.Add(self.onlineRadio, 0, ALL, 5)
        self.onlineRadio.Bind(EVT_RADIOBUTTON, self.OnRadioChange)

        self.m_staticText4 = StaticText(self, ID_ANY, u"名称", DefaultPosition,
                                        DefaultSize, 0)
        self.m_staticText4.Wrap(-1)

        fgSizer3.Add(self.m_staticText4, 0, ALL, 5)

        self.nameInput = TextCtrl(self, ID_ANY, EmptyString, DefaultPosition,
                                  inputSize, 0)
        fgSizer3.Add(self.nameInput, 0, ALL, 5)

        self.m_staticText5 = StaticText(self, ID_ANY, u"地址", DefaultPosition,
                                        DefaultSize, 0)
        self.m_staticText5.Wrap(-1)

        fgSizer3.Add(self.m_staticText5, 0, ALL, 5)

        self.urlInput = TextCtrl(self, ID_ANY, u"http://", DefaultPosition,
                                 inputSize, 0)
        fgSizer3.Add(self.urlInput, 0, ALL, 5)

        self.m_staticText3 = StaticText(self, ID_ANY, u"图标", DefaultPosition,
                                        DefaultSize, 0)
        self.m_staticText3.Wrap(-1)

        fgSizer3.Add(self.m_staticText3, 0, ALL, 5)

        self.iconComboBox = ComboBox(self, ID_ANY, u"请选择图标", DefaultPosition,
                                     inputSize, list(GetIcons().keys()), 0)
        self.iconComboBox.SetFont(font)
        fgSizer3.Add(self.iconComboBox, 0, ALL, 5)

        self.cancelButton = Button(self, ID_ANY, u"取消", DefaultPosition,
                                   DefaultSize, 0)
        fgSizer3.Add(self.cancelButton, 0, ALL, 5)

        self.saveButton = Button(self, ID_ANY, u"保存", DefaultPosition,
                                 DefaultSize, 0)
        fgSizer3.Add(self.saveButton, 0, ALL, 5)

        self.SetSizer(fgSizer3)
        self.Layout()

        self.Centre(BOTH)

        self.cancelButton.Bind(EVT_BUTTON, self.OnButtonClicked)
        self.saveButton.Bind(EVT_BUTTON, self.OnButtonClicked)
        self.Bind(EVT_CLOSE, self.OnClose)
Ejemplo n.º 11
0
class EditDialog(Dialog):
    __hosts = None
    __window = None

    def __init__(self, parent, dpi=(1, 1)):
        Dialog.__init__(self,
                        parent,
                        id=ID_ANY,
                        title=u"编辑/添加Hosts",
                        pos=Point(600, 600),
                        size=Size(394 * dpi[0], 210 * dpi[1]),
                        style=DEFAULT_DIALOG_STYLE | FRAME_FLOAT_ON_PARENT)
        self.__window = parent
        self.SetSizeHints(DefaultSize, DefaultSize)

        font = Font(10, FONTFAMILY_DEFAULT, FONTSTYLE_NORMAL,
                    FONTWEIGHT_NORMAL, False, EmptyString)
        inputSize = Size(260 * dpi[0], -1)
        self.SetFont(font)
        fgSizer3 = FlexGridSizer(0, 2, 0, 0)
        fgSizer3.SetFlexibleDirection(BOTH)
        fgSizer3.SetNonFlexibleGrowMode(FLEX_GROWMODE_SPECIFIED)

        self.localRadio = RadioButton(self, ID_ANY, u"本地Hosts",
                                      DefaultPosition, DefaultSize, 0)
        self.localRadio.SetFont(font)
        fgSizer3.Add(self.localRadio, 0, ALL, 5)
        self.localRadio.Bind(EVT_RADIOBUTTON, self.OnRadioChange)

        self.onlineRadio = RadioButton(self, ID_ANY, u"在线Hosts",
                                       DefaultPosition, DefaultSize, 0)
        fgSizer3.Add(self.onlineRadio, 0, ALL, 5)
        self.onlineRadio.Bind(EVT_RADIOBUTTON, self.OnRadioChange)

        self.m_staticText4 = StaticText(self, ID_ANY, u"名称", DefaultPosition,
                                        DefaultSize, 0)
        self.m_staticText4.Wrap(-1)

        fgSizer3.Add(self.m_staticText4, 0, ALL, 5)

        self.nameInput = TextCtrl(self, ID_ANY, EmptyString, DefaultPosition,
                                  inputSize, 0)
        fgSizer3.Add(self.nameInput, 0, ALL, 5)

        self.m_staticText5 = StaticText(self, ID_ANY, u"地址", DefaultPosition,
                                        DefaultSize, 0)
        self.m_staticText5.Wrap(-1)

        fgSizer3.Add(self.m_staticText5, 0, ALL, 5)

        self.urlInput = TextCtrl(self, ID_ANY, u"http://", DefaultPosition,
                                 inputSize, 0)
        fgSizer3.Add(self.urlInput, 0, ALL, 5)

        self.m_staticText3 = StaticText(self, ID_ANY, u"图标", DefaultPosition,
                                        DefaultSize, 0)
        self.m_staticText3.Wrap(-1)

        fgSizer3.Add(self.m_staticText3, 0, ALL, 5)

        self.iconComboBox = ComboBox(self, ID_ANY, u"请选择图标", DefaultPosition,
                                     inputSize, list(GetIcons().keys()), 0)
        self.iconComboBox.SetFont(font)
        fgSizer3.Add(self.iconComboBox, 0, ALL, 5)

        self.cancelButton = Button(self, ID_ANY, u"取消", DefaultPosition,
                                   DefaultSize, 0)
        fgSizer3.Add(self.cancelButton, 0, ALL, 5)

        self.saveButton = Button(self, ID_ANY, u"保存", DefaultPosition,
                                 DefaultSize, 0)
        fgSizer3.Add(self.saveButton, 0, ALL, 5)

        self.SetSizer(fgSizer3)
        self.Layout()

        self.Centre(BOTH)

        self.cancelButton.Bind(EVT_BUTTON, self.OnButtonClicked)
        self.saveButton.Bind(EVT_BUTTON, self.OnButtonClicked)
        self.Bind(EVT_CLOSE, self.OnClose)

    def __del__(self):
        pass

    def OnClose(self, event):
        self.SetHosts(None)
        event.Skip()

    def SetHosts(self, hosts):
        self.__hosts = hosts
        if hosts:
            if hosts["url"] and len(hosts["url"] > 0):
                self.onlineRadio.SetValue(hosts["url"])
            self.localRadio.SetValue(not hosts["url"])
            self.nameInput.SetValue(hosts["name"])
            self.urlInput.SetValue(hosts["url"] or "")
            self.iconComboBox.SetValue(hosts["icon"])
            self.onlineRadio.Enable(False)
            self.localRadio.Enable(False)
        else:
            self.onlineRadio.Enable(False)
            self.localRadio.Enable(True)
            self.localRadio.SetValue(True)
            self.urlInput.SetValue("")
            self.iconComboBox.SetValue("logo")
            self.nameInput.SetValue("")

    def OnButtonClicked(self, event):
        if event.GetId() == self.cancelButton.GetId():
            self.Close()
            return
        name = self.nameInput.GetValue()
        url = self.urlInput.GetValue()
        isOnline = self.onlineRadio.GetValue()
        if not isOnline:
            url = None
        if not name or len(name) < 1:
            MessageBox("请输入Hosts名称", "提示", ICON_WARNING)
        elif isOnline and (not url or len(url) < 1):
            MessageBox("请输入在线Hosts地址", "提示", ICON_WARNING)
        else:
            if not self.iconComboBox.GetValue():
                self.iconComboBox.SetValue("logo")
            if self.__hosts:
                self.__hosts["name"] = name
                self.__hosts["url"] = url
                self.__hosts["lastUpdateTime"] = Now()
                self.__hosts["icon"] = self.iconComboBox.GetValue()
                hostsId = self.__hosts['id']
            else:
                hostsId = 0x1994 + len(Settings.settings["hosts"])
                Settings.settings["hosts"].append(
                    hostsDict(hostsId,
                              name,
                              url=url,
                              lastUpdateTime=Now(),
                              content="# Created by mHosts v%s, %s\n" %
                              (Settings.version(), Now()),
                              icon=self.iconComboBox.GetValue()))
            Settings.Save()
            self.__window.InitHostsTree(select=hostsId)
            self.Close()

    def OnRadioChange(self, event):
        self.urlInput.Enable(event.GetId() == self.onlineRadio.GetId())
Ejemplo n.º 12
0
class EditorTab(Panel):
    def __init__(self, parent):
        Panel.__init__(self, parent)
        sizer = GridBagSizer(5, 5)
        self.SetSizer(sizer)

        self.__cur_po_class = None
        self.__create_widgets()

    def __create_widgets(self):
        sizer = self.GetSizer()

        # Next row
        inner_sizer = BoxSizer(HORIZONTAL)
        label = StaticText(self, label=u'Class path:')
        inner_sizer.Add(label, flag=ALL)

        self.cb_class_path = ComboBox(self, style=CB_READONLY)
        self.cb_class_path.Bind(EVT_COMBOBOX, self.__on_load_po_class)
        inner_sizer.Add(self.cb_class_path, 1, flag=FLAG_ALL_AND_EXPAND)

        self.btn_reload = Button(self, label=u'Reload')
        self.btn_reload.Bind(EVT_BUTTON, self.__on_load_po_class)
        inner_sizer.Add(self.btn_reload, flag=ALL)

        self.btn_open_class = Button(self, label=u'Open class')
        self.btn_open_class.Bind(EVT_BUTTON, self.__open_class)
        inner_sizer.Add(self.btn_open_class, flag=ALL)

        row = 0
        sizer.Add(inner_sizer, pos=(row, 0), flag=FLAG_ALL_AND_EXPAND)

        # Next row
        row += 1
        splitter = SplitterWindow(self, style=SP_3D | SP_LIVE_UPDATE)

        self.image_panel = ImageWithElements(splitter)
        self.image_panel.static_bitmap.Bind(EVT_MOTION, self.__on_mouse_move)
        self.image_panel.static_bitmap.Bind(EVT_RIGHT_DOWN, self.__on_right_click)

        self.table_and_test_file_tabs = FieldsTableAndTestFilesTabs(splitter, self)

        splitter.SplitHorizontally(self.image_panel, self.table_and_test_file_tabs)
        sizer.Add(splitter, pos=(row, 0), flag=FLAG_ALL_AND_EXPAND)

        sizer.AddGrowableRow(row, 1)
        sizer.AddGrowableCol(0, 1)

    def __get_parsed_classes(self, field):
        classes = ParsedPageObjectClass.get_parsed_classes(self.__cur_po_class.file_path)
        if len(classes) > 0 and len(classes[0].methods) == 0:
            classes = []
        classes += [ParsedModule.get_parsed_module(tools)]
        if field:
            classes += ParsedMouseClass.get_parsed_classes()
            classes += ParsedBrowserClass.get_parsed_classes()
        return classes

    def show_content_menu(self, field):
        tabs = self.table_and_test_file_tabs.tabs
        count = tabs.GetPageCount()
        if count > 1:
            selected_tab = tabs.GetPage(tabs.GetSelection())
            if type(selected_tab) in (TestFileUI, PyFileUI):
                file_path = selected_tab.get_file_path()
                txt_ctrl_ui = tabs.GetPage(tabs.GetSelection())
                parsed_classes = self.__get_parsed_classes(field)
                context_menu = FieldContextMenu(field,
                                                parsed_classes,
                                                file_path,
                                                txt_ctrl_ui)
                self.PopupMenu(context_menu)
                context_menu.Destroy()
            else:
                show_dialog(self, u'Please select tab with test file.',
                            u'Tab with test file was not selected')
        else:
            show_dialog(self, u'Please create/open test file.',
                        u'Test file was not created/opened')

    def __on_load_po_class(self, evt):
        path = self.cb_class_path.GetValue()
        if len(path) > 0:
            self.__load_po_class(path)

    def __on_right_click(self, evt):
        field = self.__get_current_field(evt)
        self.show_content_menu(field)

    def __on_mouse_move(self, evt):
        if self.__cur_po_class:
            ImageAndTableHelper.select_field_on_mouse_move(
                evt,
                self.__cur_po_class.fields,
                self.image_panel,
                self.table_and_test_file_tabs.table
            )

    def __get_current_field(self, evt):
        return self.image_panel.get_field(evt.GetPosition())

    def __open_class(self, evt):
        folder = self.GetTopLevelParent().get_root_folder()
        if folder:
            if RootFolder.PO_FOLDER in os.listdir(folder):
                folder = os.path.join(folder, RootFolder.PO_FOLDER)
            dialog = FileDialog(self, defaultDir=folder, wildcard=u'*.py')
            if dialog.ShowModal() == ID_OK:
                self.__load_po_class(dialog.GetPath())
        else:
            show_dialog_path_doesnt_exist(self, folder)

    def __load_po_class(self, path):
        self.table_and_test_file_tabs.table.clear_table()

        if not os.path.exists(path):
            show_dialog_path_doesnt_exist(self, path)
        if not is_correct_python_file(path):
            show_dialog(self, u'File name is incorrect: %s' % path,
                        u'Bad file name')
        else:
            folder = os.path.dirname(path)
            files = [os.path.join(folder, p) for p in os.listdir(folder)
                     if is_correct_python_file(p)]
            self.cb_class_path.Clear()
            self.cb_class_path.AppendItems(files)
            self.cb_class_path.Select(files.index(path))
            try:
                self.__cur_po_class = PageObjectClass.parse_string_to_po_class(read_file(path))
                area = self.__cur_po_class.area
                self.image_panel.set_po_fields(self.__cur_po_class.fields)
                self.image_panel.load_image(self.__cur_po_class.img_path, area)

                self.cb_class_path.SetValue(self.__cur_po_class.file_path)

                self.table_and_test_file_tabs.load_po_class(self.__cur_po_class)
            except Exception:
                self.__cur_po_class = None
                show_error_dialog(self, traceback.format_exc(),
                                  u'Failed to open file %s' % path)
Ejemplo n.º 13
0
class DlgPyutPreferences(Dialog):

    VERTICAL_GAP: int = 5
    HORIZONTAL_GAP: int = 5
    """
    This is the preferences dialog for Pyut.

    Display current preferences and possible values, save modified values.
    
    This works just like preferences on OS X work.  They are changed
    immediately

    To use it from a wxFrame:
    ```python

        dlg = DlgProperties(self, wx.ID_ANY PyutPreferences(), Mediator())
        dlg.ShowModal()
        dlg.Destroy()
    ```
    """
    def __init__(self, parent, ID, ctrl, prefs: PyutPreferences):
        """

        Args:
            parent:
            ID:
            ctrl:
            prefs:   The PyutPreferences
        """
        super().__init__(parent, ID, _("Preferences"))

        self.logger: Logger = getLogger(__name__)

        self.__ctrl = ctrl
        self.__prefs: PyutPreferences = prefs

        self.__initializeTheControls()
        self.Bind(EVT_CLOSE, self.__OnClose)

    def __initializeTheControls(self):
        """
        Initialize the controls.
        """
        # IDs
        [
            self.__autoResizeID, self.__showParamsID, self.__languageID,
            self.__maximizeID, self.__fontSizeID, self.__showTipsID,
            self.__centerDiagramID, self.__resetTipsID, self.__scAppWidthID,
            self.__scAppHeightID, self.__scAppPosXID, self.__scAppPosYID
        ] = PyutUtils.assignID(12)

        self.__createBooleanControls()
        self.__createFontSizeControl()
        self.__cmbLanguage: ComboBox = cast(ComboBox, None)

        szrLanguage: BoxSizer = self.__createLanguageControlContainer()
        hs: BoxSizer = self.__createDialogButtonsContainer()

        box: StaticBox = StaticBox(self, ID_ANY, "")
        mainSizer: StaticBoxSizer = StaticBoxSizer(box, VERTICAL)

        # mainSizer.Add(window=self.__cbAutoResize, proportion=0, flag=ALL, border=DlgPyutPreferences.VERTICAL_GAP)
        mainSizer.Add(self.__cbAutoResize, 0, ALL,
                      DlgPyutPreferences.VERTICAL_GAP)
        mainSizer.Add(self.__cbShowParams, 0, ALL,
                      DlgPyutPreferences.VERTICAL_GAP)
        mainSizer.Add(self.__cbMaximize, 0, ALL,
                      DlgPyutPreferences.VERTICAL_GAP)
        mainSizer.Add(self.__cbShowTips, 0, ALL,
                      DlgPyutPreferences.VERTICAL_GAP)

        mainSizer.Add(self.__cbCenterDiagram, 0, ALL,
                      DlgPyutPreferences.VERTICAL_GAP)
        mainSizer.Add(self.__createAppPositionControls(), 0, ALL,
                      DlgPyutPreferences.VERTICAL_GAP)

        mainSizer.Add(self.__createAppSizeControls(), 0, ALL,
                      DlgPyutPreferences.VERTICAL_GAP)
        mainSizer.Add(self.__btnResetTips, 0, ALL,
                      DlgPyutPreferences.VERTICAL_GAP)

        mainSizer.Add(szrLanguage, 0, ALL, DlgPyutPreferences.VERTICAL_GAP)
        mainSizer.Add(hs, 0, CENTER)

        border: BoxSizer = BoxSizer()
        border.Add(mainSizer, 1, EXPAND | ALL, 3)

        self.SetAutoLayout(True)
        self.SetSizer(border)

        border.Fit(self)
        border.SetSizeHints(self)

        self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__autoResizeID)
        self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__showParamsID)
        self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__maximizeID)
        self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__showTipsID)
        self.Bind(EVT_CHECKBOX, self.__OnCheckBox, id=self.__centerDiagramID)

        self.Bind(EVT_SPINCTRL, self.__OnSizeChange, id=self.__scAppWidthID)
        self.Bind(EVT_SPINCTRL, self.__OnSizeChange, id=self.__scAppHeightID)

        self.Bind(EVT_BUTTON, self.__OnBtnResetTips, id=self.__resetTipsID)

        self.Bind(EVT_COMBOBOX, self.__OnLanguageChange, id=self.__languageID)
        self.Bind(EVT_BUTTON, self.__OnCmdOk, id=ID_OK)

        self.__changed: bool = False
        self.__setValues()

    def __createDialogButtonsContainer(self) -> BoxSizer:

        hs: BoxSizer = BoxSizer(HORIZONTAL)

        btnOk: Button = Button(self, ID_OK, _("&OK"))
        hs.Add(btnOk, 0, ALL, DlgPyutPreferences.HORIZONTAL_GAP)

        return hs

    def __createLanguageControlContainer(self) -> BoxSizer:
        """
        Creates the language control inside a container

        Returns:
            The sizer that contains the language selection control
        """

        # Language
        self.__lblLanguage: StaticText = StaticText(self, ID_ANY,
                                                    _("Language"))
        self.logger.info(f'We are running on: {platform}')
        #
        # wx.CB_SORT not currently supported by wxOSX/Cocoa (True even as late as wx 4.0.7
        #
        if platform == PyutConstants.THE_GREAT_MAC_PLATFORM:
            self.__cmbLanguage = ComboBox(
                self,
                self.__languageID,
                choices=[el[0] for el in list(Lang.LANGUAGES.values())],
                style=CB_READONLY)
        else:
            self.__cmbLanguage = ComboBox(
                self,
                self.__languageID,
                choices=[el[0] for el in list(Lang.LANGUAGES.values())],
                style=CB_READONLY | CB_SORT)
        szrLanguage: BoxSizer = BoxSizer(HORIZONTAL)
        szrLanguage.Add(self.__lblLanguage, 0, ALL,
                        DlgPyutPreferences.HORIZONTAL_GAP)
        szrLanguage.Add(self.__cmbLanguage, 0, ALL,
                        DlgPyutPreferences.HORIZONTAL_GAP)

        return szrLanguage

    def __createBooleanControls(self):
        """
        Creates the main control and stashes them as private instance variables
        """

        self.__cbMaximize: CheckBox = CheckBox(self, self.__maximizeID,
                                               _("&Full Screen on startup"))
        self.__cbAutoResize: CheckBox = CheckBox(
            self, self.__autoResizeID,
            _("&Auto resize classes to fit content"))
        self.__cbShowParams: CheckBox = CheckBox(self, self.__showParamsID,
                                                 _("&Show params in classes"))
        self.__cbShowTips: CheckBox = CheckBox(self, self.__showTipsID,
                                               _("Show &Tips on startup"))
        self.__cbCenterDiagram: CheckBox = CheckBox(self,
                                                    self.__centerDiagramID,
                                                    _('Center Diagram'))

        self.__btnResetTips: Button = Button(self, self.__resetTipsID,
                                             _('Reset Tips'))

    def __createAppSizeControls(self) -> StaticBoxSizer:

        scAppWidth = SpinCtrl(self, self.__scAppWidthID, "", (30, 50))
        scAppHeight = SpinCtrl(self, self.__scAppHeightID, "", (30, 50))

        scAppWidth.SetRange(960, 4096)
        scAppHeight.SetRange(480, 4096)

        box: StaticBox = StaticBox(self, ID_ANY, "Startup Width/Height")
        szrAppSize: StaticBoxSizer = StaticBoxSizer(box, HORIZONTAL)

        szrAppSize.Add(scAppWidth, 0, ALL, DlgPyutPreferences.HORIZONTAL_GAP)
        szrAppSize.Add(scAppHeight, 0, ALL, DlgPyutPreferences.HORIZONTAL_GAP)

        self.__scAppWidth = scAppWidth
        self.__scAppHeight = scAppHeight

        return szrAppSize

    def __createAppPositionControls(self) -> StaticBoxSizer:

        scAppPosX = SpinCtrl(self, self.__scAppPosXID, "", (30, 50))
        scAppPosY = SpinCtrl(self, self.__scAppPosYID, "", (30, 50))

        scAppPosX.SetRange(0, 4096)
        scAppPosY.SetRange(0, 4096)
        scAppPosX.SetValue(self.__prefs.appStartupPosition[0])
        scAppPosY.SetValue(self.__prefs.appStartupPosition[1])

        box: StaticBox = StaticBox(self, ID_ANY, "Startup Position")
        szrAppPosition: StaticBoxSizer = StaticBoxSizer(box, HORIZONTAL)

        szrAppPosition.Add(scAppPosX, 0, ALL,
                           DlgPyutPreferences.HORIZONTAL_GAP)
        szrAppPosition.Add(scAppPosY, 0, ALL,
                           DlgPyutPreferences.HORIZONTAL_GAP)

        self.__scAppPosX = scAppPosX
        self.__scAppPosY = scAppPosY

        self.__setPositionControls()
        return szrAppPosition

    def __createFontSizeControl(self):
        """
        TODO:  Need this later;  Inherited from legacy code
        """
        #        self.__lblFontSize = StaticText(self, -1, _("Font size"))
        #        self.__txtFontSize = TextCtrl(self, self.__fontSizeID)
        #        szrFont = wx.BoxSizer(HORIZONTAL)
        #        szrFont.Add(self.__lblFontSize, 0, ALL, HORIZONTAL_GAP)
        #        szrFont.Add(self.__txtFontSize, 0, ALL, HORIZONTAL_GAP)
        pass

    def __setValues(self):
        """
        Set the default values to the controls.
        """
        self.__cbAutoResize.SetValue(
            secureBool(
                self.__prefs[PyutPreferences.AUTO_RESIZE_SHAPE_ON_EDIT]))
        self.__cbShowParams.SetValue(
            secureBool(self.__prefs[PyutPreferences.SHOW_PARAMETERS]))
        self.__cbMaximize.SetValue(
            secureBool(self.__prefs[PyutPreferences.FULL_SCREEN]))
        self.__cbShowTips.SetValue(
            secureBool(self.__prefs[PyutPreferences.SHOW_TIPS_ON_STARTUP]))
        self.__cbCenterDiagram.SetValue(
            secureBool(self.__prefs[PyutPreferences.CENTER_DIAGRAM]))

        self.__scAppWidth.SetValue(self.__prefs.startupWidth)
        self.__scAppHeight.SetValue(self.__prefs.startupHeight)
        # i18n
        n = self.__prefs[PyutPreferences.I18N]
        if n not in Lang.LANGUAGES:
            n = Lang.DEFAULT_LANG
        self.__cmbLanguage.SetValue(Lang.LANGUAGES[n][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}')

    def __OnSizeChange(self, event: SpinEvent):

        self.__changed = True
        eventId: int = event.GetId()
        newValue: int = event.GetInt()
        if eventId == self.__scAppWidthID:
            self.__prefs.startupWidth = newValue
        elif eventId == self.__scAppHeightID:
            self.__prefs.startupHeight = newValue
        else:
            self.logger.error(f'Unknown onSizeChange event id: {eventId}')

        dlg = MessageDialog(self, _("You must restart Pyut for size changes"),
                            _("Warning"), OK | ICON_EXCLAMATION)
        dlg.ShowModal()
        dlg.Destroy()

    def __OnClose(self, event):
        event.Skip(skip=True)

    # noinspection PyUnusedLocal
    def __OnCmdOk(self, event: CommandEvent):
        """
        """
        if self.__changed is True:
            self.logger.info(f'Preferences have changed')
        event.Skip(skip=True)

    # noinspection PyUnusedLocal
    def __OnBtnResetTips(self, event: CommandEvent):
        self.__prefs[PyutPreferences.CURRENT_TIP] = '0'

    def __OnLanguageChange(self, event: CommandEvent):

        newLanguage: str = event.GetString()
        actualLanguage: str = self.__prefs[PyutPreferences.I18N]
        if actualLanguage not in Lang.LANGUAGES or newLanguage != Lang.LANGUAGES[
                actualLanguage][0]:
            # Search the key corresponding to the newLanguage
            for i in list(Lang.LANGUAGES.items()):
                if newLanguage == i[1][0]:
                    # Write the key in preferences file
                    self.__prefs[PyutPreferences.I18N] = i[0]

            dlg = MessageDialog(
                self, _("You must restart Pyut for language changes"),
                _("Warning"), OK | ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()

    def __setPositionControls(self):
        """
        Set the position controls based on the value of appropriate preference value

        """
        if self.__prefs.centerAppOnStartUp is True:
            self.__scAppPosX.Disable()
            self.__scAppPosY.Disable()
        else:
            self.__scAppPosX.Enable()
            self.__scAppPosY.Enable()
Ejemplo n.º 14
0
class MiscellaneousPreferences(PreferencesPanel):

    VERTICAL_GAP: int = 2
    HORIZONTAL_GAP: int = 2

    clsLogger: Logger = getLogger(__name__)

    def __init__(self, parent):

        super().__init__(parent=parent)

        [self.__languageID, self.__pdfFilenameID,
         self.__wxImageFileNameID] = PyutUtils.assignID(3)

        self._pdfFileNameContainer: TextContainer = cast(TextContainer, None)
        self._wxImageFileNameContainer: TextContainer = cast(
            TextContainer, None)
        self._fastEditEditorNameContainer: TextContainer = cast(
            TextContainer, None)

        self._createControls()
        self._setControlValues()

    def _createControls(self):

        mainSizer: BoxSizer = BoxSizer(VERTICAL)

        mainSizer.Add(self.__createExportToPdfDefaultFileNameContainer(), 0,
                      ALL, MiscellaneousPreferences.VERTICAL_GAP)
        mainSizer.Add(self.__createWxImageFileNameContainer(), 0, ALL,
                      MiscellaneousPreferences.VERTICAL_GAP)
        mainSizer.Add(self.__createFastEditEditorNameContainer(), 0, ALL,
                      MiscellaneousPreferences.VERTICAL_GAP)
        mainSizer.Add(self.__createLanguageControlContainer(), 0, ALL,
                      MiscellaneousPreferences.VERTICAL_GAP)

        self.SetAutoLayout(True)
        self.SetSizer(mainSizer)

        self.Bind(EVT_COMBOBOX, self.__OnLanguageChange, id=self.__languageID)

    def __createExportToPdfDefaultFileNameContainer(self) -> TextContainer:

        pdfFileNameContainer: TextContainer = TextContainer(
            parent=self,
            labelText=_('PDF Filename'),
            valueChangedCallback=self.__onPdfFileNameChange)

        self._pdfFileNameContainer = pdfFileNameContainer

        return pdfFileNameContainer

    def __createWxImageFileNameContainer(self) -> TextContainer:

        wxImageFileNameContainer: TextContainer = TextContainer(
            parent=self,
            labelText=_('Image Filename'),
            valueChangedCallback=self.__onWxImageFileNameChange)

        self._wxImageFileNameContainer = wxImageFileNameContainer

        return wxImageFileNameContainer

    def __createFastEditEditorNameContainer(self) -> TextContainer:

        editorNameContainer: TextContainer = TextContainer(
            parent=self,
            labelText=_('FastEdit Editor Name'),
            valueChangedCallback=self.__onFastEditEditorNameChange)

        self._fastEditEditorNameContainer = editorNameContainer

        return editorNameContainer

    def __createLanguageControlContainer(self) -> StaticBoxSizer:
        """
        Creates the language control inside a container

        Returns:
            The sizer that contains the language selection control
        """
        self.clsLogger.info(f'We are running on: {platform}')

        choices = [el[0] for el in list(LANGUAGES.values())]

        if platform == PyutConstants.THE_GREAT_MAC_PLATFORM:
            self.__cmbLanguage = ComboBox(self,
                                          self.__languageID,
                                          choices=choices,
                                          style=CB_READONLY | CB_SORT)
        else:
            self.__cmbLanguage = ComboBox(self,
                                          self.__languageID,
                                          choices=choices,
                                          style=CB_READONLY | CB_SORT)
        box: StaticBox = StaticBox(self, ID_ANY, _("Language"))
        szrGridStyle: StaticBoxSizer = StaticBoxSizer(box, HORIZONTAL)

        szrGridStyle.Add(self.__cmbLanguage, WX_SIZER_CHANGEABLE, ALL,
                         MiscellaneousPreferences.HORIZONTAL_GAP)

        return szrGridStyle

    def __createAFileNameContainer(
            self, fileNameLabelText: str,
            textCtrlID: int) -> Tuple[BoxSizer, TextCtrl]:

        lblFileName: StaticText = StaticText(self, ID_ANY, fileNameLabelText)

        textCtrl: TextCtrl = TextCtrl(self, textCtrlID)

        szrFilename: BoxSizer = BoxSizer(VERTICAL)

        szrFilename.Add(lblFileName, 1, ALL | EXPAND,
                        MiscellaneousPreferences.VERTICAL_GAP)
        szrFilename.Add(textCtrl, 1, ALL,
                        MiscellaneousPreferences.VERTICAL_GAP)

        return szrFilename, textCtrl

    def _setControlValues(self):

        n = self._prefs.i18n
        if n not in LANGUAGES:
            n = DEFAULT_LANG

        self.__cmbLanguage.SetValue(LANGUAGES[n][0])

        self._pdfFileNameContainer.textValue = self._prefs.pdfExportFileName
        self._wxImageFileNameContainer.textValue = self._prefs.wxImageFileName
        self._fastEditEditorNameContainer.textValue = self._prefs.editor

    def __OnLanguageChange(self, event: CommandEvent):

        newLanguage: str = event.GetString()
        actualLanguage: str = self._prefs.i18n
        if actualLanguage not in LANGUAGES or newLanguage != LANGUAGES[
                actualLanguage][0]:
            # Search the key corresponding to the newLanguage
            for i in list(LANGUAGES.items()):
                if newLanguage == i[1][0]:
                    # Write the key in preferences file
                    # self._prefs[PyutPreferences.I18N] = i[0]
                    self._prefs.i18n = i[0]

            dlg: MessageDialog = MessageDialog(
                self, _("You must restart Pyut for language changes"),
                _("Warning"), OK | ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()

    def __onPdfFileNameChange(self, newValue: str):

        self._prefs.pdfExportFileName = newValue

    def __onWxImageFileNameChange(self, newValue: str):

        self._prefs.wxImageFileName = newValue

    def __onFastEditEditorNameChange(self, newValue: str):
        self._prefs.editor = newValue