def build_details_social(self, sizer, row): types = ("alerts", "feed", "indicators") hsz = BoxSizer(wx.HORIZONTAL) d = self.details add = lambda c, s, *a: (d.add(c), s.Add(c, *a)) for i, key in enumerate(types): checks = self.checks.get(key, ()) if not checks: continue sz = BoxSizer(wx.VERTICAL) tx = StaticText( self, -1, _("{show_topic}:").format(show_topic=self.protocolinfo["show_%s_label" % key]), style=wx.ALIGN_LEFT, ) from gui.textutil import CopyFont tx.Font = CopyFont(tx.Font, weight=wx.BOLD) add(tx, sz, 0, wx.BOTTOM, tx.GetDefaultBorder()) for chk in checks: add(chk, sz, 0, ALL, chk.GetDefaultBorder()) hsz.Add(sz, 0) # if i != len(types)-1: hsz.AddSpacer(15) self.Sizer.Add(hsz, 0, wx.BOTTOM | wx.LEFT, 10) self.build_details_default(sizer, row)
def field_from_value(self, window, value, field): item = None if isinstance(value, basestring): item = TextCtrl(window, value=value) field.text_type = basestring elif isinstance(value, list): item = TextCtrl(window, value=", ".join(value)) field.text_type = list elif isinstance(value, bool): item = CheckBox(window, -1, '', (120, 75)) item.SetValue(value) elif isinstance(value, int): item = TextCtrl(window, value=str(value)) field.text_type = int elif isinstance(value, dict): subpage = Panel(window) vbox = BoxSizer(VERTICAL) alpha = value.keys() alpha.sort() for lbl in alpha: hbox = BoxSizer(HORIZONTAL) value2 = value[lbl] label = StaticText(subpage, label=lbl) hbox.Add(label, flag=RIGHT, border=8) subfield = Field(None, lbl) item = self.field_from_value(subpage, value2, subfield) field.add_child(subfield) if item!=None: hbox.Add(item, proportion=1) vbox.Add(hbox, flag=EXPAND|LEFT|RIGHT|TOP, border=5) vbox.Add((-1, 5)) subpage.SetSizer(vbox) subpage.Show() item = subpage field.wx_field = item return item
class DlgEditLink(Dialog): """ Dialog for the link (between classes) editting. to use it : dlg=DlgEditLink(...) dlg.setValues(...) dlg.ShowModal() to see if the user clicked on Ok or Cancel : x=dlg.getReturnAction() to get new values : x=dlg.getCardinality() x=dlg.getRoles() x=dlg.getRelationship() don't forget : dlg.Destroy() :version: $Revision: 1.9 $ :author: C.Dutoit :contact: [email protected] """ def __init__(self, parent, ID, pyutLink: PyutLink): """ """ super().__init__(parent, ID, _("Link Edit"), style=RESIZE_BORDER | CAPTION) self.logger: Logger = getLogger(__name__) # Associated PyutLink self._pyutLink: PyutLink = pyutLink self._relationship = self._pyutLink.getName() self._aRoleInB = "" self._bRoleInA = "" # self._cardinalityA = self._pyutLink.getSourceCardinality() # self._cardinalityB = self._pyutLink.getDestinationCardinality() self._cardinalityA = self._pyutLink.sourceCardinality self._cardinalityB = self._pyutLink.destinationCardinality self._returnAction = CANCEL # #describe how user exited dialog box # labels lblCardA = StaticText(self, -1, _("Cardinality"), style=ALIGN_LEFT) lblRela = StaticText(self, -1, _("Relationship"), style=ALIGN_CENTRE) lblCardB = StaticText(self, -1, _("Cardinality"), style=ALIGN_RIGHT) lblA = StaticText(self, -1, "A", style=ALIGN_LEFT) self._lblArrow = StaticText(self, -1, "", style=ALIGN_CENTRE) self.updateLblArrow() lblB = StaticText(self, -1, "B", style=ALIGN_RIGHT) lblAinB = StaticText(self, -1, _("A's role in B"), style=ALIGN_LEFT) lblBinA = StaticText(self, -1, _("B's role in A"), style=ALIGN_RIGHT) # text self._txtCardinalityA = TextCtrl(self, TXT_CARDINALITY_A, "", size=Size(50, 20)) self._txtRelationship = TextCtrl(self, TXT_RELATIONSHIP, "", size=Size(100, 20)) self._txtCardinalityB = TextCtrl(self, TXT_CARDINALITY_B, "", size=Size(50, 20)) self._txtARoleB = TextCtrl(self, A_ROLE_IN_B, "") self._txtBRoleA = TextCtrl(self, B_ROLE_IN_A, "") self.setValues(self._relationship, self._aRoleInB, self._bRoleInA, self._cardinalityA, self._cardinalityB) self._txtARoleB.Enable(False) self._txtBRoleA.Enable(False) # text events self.Bind(EVT_TEXT, self._onTxtCardinalityAChange, id=TXT_CARDINALITY_A) self.Bind(EVT_TEXT, self._onTxtCardinalityBChange, id=TXT_CARDINALITY_B) self.Bind(EVT_TEXT, self._onTxtRelationshipChange, id=TXT_RELATIONSHIP) self.Bind(EVT_TEXT, self._onTxtARoleBChange, id=A_ROLE_IN_B) self.Bind(EVT_TEXT, self._onTxtBRoleAChange, id=B_ROLE_IN_A) # Ok/Cancel btnOk = Button(self, OK, _("&Ok")) btnCancel = Button(self, CANCEL, _("&Cancel")) btnRemove = Button(self, BTN_REMOVE, _("&Remove")) btnOk.SetDefault() # button events self.Bind(EVT_BUTTON, self._onCmdOk, id=OK) self.Bind(EVT_BUTTON, self._onCmdCancel, id=CANCEL) self.Bind(EVT_BUTTON, self._onRemove, id=BTN_REMOVE) szr1 = FlexGridSizer(cols=3, hgap=30, vgap=5) szr1.AddMany([(lblCardA, 0, ALIGN_LEFT), (lblRela, 0, ALIGN_CENTER_HORIZONTAL), (lblCardB, 0, ALIGN_RIGHT), (self._txtCardinalityA, 0, ALIGN_LEFT), (self._txtRelationship, 0, ALIGN_CENTER_HORIZONTAL), (self._txtCardinalityB, 0, ALIGN_RIGHT)]) szr1.AddGrowableCol(0) szr1.AddGrowableCol(1) szr1.AddGrowableCol(2) szr2 = BoxSizer(HORIZONTAL) szr2.Add(lblA, 1, GROW | RIGHT, 10) szr2.Add(self._lblArrow, 1, GROW, 10) szr2.Add(lblB, 1, GROW) # szr3 : # lblAinB, lblBinA # self._txtARoleB, self._txtBRoleA szr3 = FlexGridSizer(cols=2, hgap=30, vgap=5) szr3.AddMany([(lblAinB, 0), (lblBinA, 0, ALIGN_RIGHT), (self._txtARoleB, 0), (self._txtBRoleA, 0, ALIGN_RIGHT | BOTTOM, 20)]) szr3.AddGrowableCol(0) szr3.AddGrowableCol(1) # szr4 : # btnRemove, btnOk, btnCancel szr4 = BoxSizer(HORIZONTAL) szr4.Add(btnRemove, 0, RIGHT, 10) szr4.Add(btnOk, 0, RIGHT, 10) szr4.Add(btnCancel, 0) # szr5 : # szr1 # szr2 # szr3 # szr4 szr5 = BoxSizer(VERTICAL) szr5.Add(szr1, 0, GROW | ALL, 10) szr5.Add(szr2, 0, GROW | ALL, 10) szr5.Add(szr3, 0, GROW | ALL, 10) szr5.Add(szr4, 0, ALIGN_RIGHT | ALL, 10) self.SetSizer(szr5) self.SetAutoLayout(True) szr5.Fit(self) def updateLblArrow(self): """ Draw an example arrow in lblArrow @since 1.1.1.2 @author C.Dutoit <*****@*****.**> """ dic = {PyutLink: "Pyut Link"} self.logger.info( f"DlgEditLink-updateLblArrow: {self._pyutLink.__class__}") if self._pyutLink.__class__ in dic.keys(): self._lblArrow.SetLabel(dic[self._pyutLink.__class__]) else: # self._lblArrow.SetLabel("Unknown link class : " + self._pyutLink.__class__) self._lblArrow.SetLabel( f'Unknown link class : {self._pyutLink.__class__}') def _copyLink(self): """ Copy the datas from _pyutLink to _pyutLinkCopy. @since 1.4 @author P. Waelti <*****@*****.**> """ self._pyutLinkCopy = deepcopy(self._pyutLink) def _onTxtCardinalityAChange(self, event): """ Event occuring when TXT_CARDINALITY_A change @since 1.2 @author C.Dutoit<*****@*****.**> """ self._cardinalityA = event.GetString() def _onTxtCardinalityBChange(self, event): """ Event occuring when TXT_CARDINALITY_B change @since 1.2 @author C.Dutoit<*****@*****.**> """ self._cardinalityB = event.GetString() def _onTxtRelationshipChange(self, event): """ Event occuring when TXT_RELATIONSHIP change @since 1.2 @author C.Dutoit<*****@*****.**> """ self._relationship = event.GetString() def _onTxtARoleBChange(self, event): """ Event occuring when TXT_A_ROLE_IN_B change @since 1.2 @author C.Dutoit<*****@*****.**> """ self._aRoleInB = event.GetString() def _onTxtBRoleAChange(self, event): """ Event occuring when TXT_B_ROLE_IN_A change @since 1.2 @author C.Dutoit<*****@*****.**> """ self._bRoleInA = event.GetString() # noinspection PyUnusedLocal def _onCmdOk(self, event: CommandEvent): """ Handle click on "Ok" button Args: event: """ self._pyutLink.setName(self._relationship) self._pyutLink.sourceCardinality = self._cardinalityA self._pyutLink.destinationCardinality = self._cardinalityB # Should perhaps take roles, not yet implemented in PyutLink TODO self._returnAction = OK self.Close() # noinspection PyUnusedLocal def _onCmdCancel(self, event): """ Handle click on "Cancel" button @since 1.2 @author C.Dutoit<*****@*****.**> """ self._returnAction = CANCEL self.Close() # noinspection PyUnusedLocal def _onRemove(self, event): """ Handle click on "Remove" button @since 1.2 @author Laurent Burgbacher <*****@*****.**> """ self._returnAction = -1 self.Close() def getCardinality(self): """ return a tuple composed by the two Cardinality (CA, CB) @since 1.2 @author C.Dutoit<*****@*****.**> """ return self._cardinalityA, self._cardinalityB def getRoles(self): """ return a tuple composed by the two Roles (A's role in B, B's role in a) @since 1.2 @author C.Dutoit<*****@*****.**> """ return self._aRoleInB, self._bRoleInA def getRelationship(self): """ return the relationship @since 1.2 @author C.Dutoit<*****@*****.**> """ return self._relationship def setValues(self, relationship, aRoleInB, bRoleInA, cardinalityA, cardinalityB): """ set all link's values @param text relationship : the relationship between the two entities @param text aRoleInB : the role of source entity in target entity @param text bRoleInA : the role of target entity in source entity @param text cardinalityA : the source cardinality @param text cardinalityB : the target cardinality @since 1.2 @author C.Dutoit<*****@*****.**> """ self._txtRelationship.SetValue(relationship) self._txtARoleB.SetValue(aRoleInB) self._txtBRoleA.SetValue(bRoleInA) self._txtCardinalityA.SetValue(cardinalityA) self._txtCardinalityB.SetValue(cardinalityB) def getReturnAction(self): """ Return an info on how the user exited the dialog box @return : Ok = click on Ok button; Cancel = click on Cancel button @since 1.2 @author C.Dutoit<*****@*****.**> """ return self._returnAction
class TestPanel(BaseWindowPanel): def __init__(self, parent): BaseWindowPanel.__init__(self, parent, bg_color=Colour.BLACK, fg_color=Colour.WHITE) self._caption_label = StaticText(self, pos=(70, 5), size=(20, 0), label=u"This month, we spent") self._caption_label.SetFont( Font(13, FONTFAMILY_DEFAULT, FONTSTYLE_NORMAL, FONTWEIGHT_NORMAL)) self._display = LEDNumberCtrl(self, pos=(0, 30), size=(320, 90), style=LED_ALIGN_RIGHT) self._display.SetValue("0.00") self._date_display = LEDNumberCtrl(self, pos=(110, 150), size=(210, 40), style=LED_ALIGN_RIGHT) self._date_display.SetValue("--.--.--") self._clock_display = LEDNumberCtrl(self, pos=(110, 190), size=(210, 50), style=LED_ALIGN_RIGHT) self._clock_display.SetValue("--.--.--") self.open_button = Button(self, -1, "Add", pos=(10, 125), size=(70, 35)) self.open_button.SetBackgroundColour(Colour.DARK_GREEN) self.open_button.SetForegroundColour(Colour.WHITE) self.list_button = Button(self, -1, "List", pos=(10, 160), size=(70, 35)) self.list_button.SetBackgroundColour(get_colour(0x333333)) self.list_button.SetForegroundColour(Colour.WHITE) self.close_button = Button(self, -1, "Close", pos=(10, 195), size=(70, 35)) self.close_button.SetBackgroundColour(Colour.DARK_RED) self.close_button.SetForegroundColour(Colour.WHITE) self._timer = Timer(self) self._timer.Start(100) self.Bind(EVT_TIMER, self.on_clock_update, self._timer) def set_display(self, value): """ :param float value: """ self._display.SetValue("{:.2f}".format(value)) def on_clock_update(self, e): self._clock_display.SetValue(datetime.now().strftime("%H:%M:%S")) self._date_display.SetValue(datetime.now().strftime("%d-%m-%Y"))
class TwitterAccountPanel(wx.Panel): ''' Selects update frequencies for different Twitter update types. Shows in the account dialog when editing Twitter accounts. ''' def __init__(self, parent, account): wx.Panel.__init__(self, parent) self.construct() self.layout() self.Bind(wx.EVT_CHOICE, self.SelectionChanged) # force an initial update self.set_values(account) self.SelectionChanged() @property def show_server_options(self): return getattr(sys, 'DEV', False) def set_values(self, account): # set initial values based on information from a Twitter Account defaults = deepcopy(protocolinfo().defaults) defaults.update(getattr(account, 'update_frequencies', {})) self.auto_throttle.Value = getattr(account, 'auto_throttle', defaults.get('auto_throttle')) for name, _ in UPDATE_TYPES: self.choices[name].Selection = UPDATE_VALUES.get( defaults.get(name), 4) if self.show_server_options: api_server = getattr(account, 'api_server', None) if api_server is not None: self.server.Value = api_server def construct(self): 'Construct GUI components.' self.header = StaticText(self, -1, _('Update Frequency:')) self.header.SetBold() self.desc = AutoHeightStaticText(self, -1, UPDATE_DESC_TEXT) self.desc.MinSize = wx.Size(40, -1) self.update_texts = {} # "Tweets every" self.choices = {} # "0 - 10 minutes" # Build StaticText, Choice for each update option. for i, (name, guistring) in enumerate(UPDATE_TYPES): self.update_texts[name] = StaticText(self, -1, guistring) self.choices[name] = Choice(self, choices=UPDATE_GUI_STRINGS) self.total = StaticText(self, style=ALIGN_CENTER) self.total.SetBold() self.auto_throttle = CheckBox( self, label=_('Auto-throttle when Twitter lowers the rate limit.'), name='auto_throttle') if self.show_server_options: self.server_text = StaticText(self, -1, _('Server')) self.server = wx.TextCtrl(self, -1) def info(self): """ Returns a mapping for this dialog's info. This looks like {'friends_timeline': 4, 'replies': 4, 'directs': 4} """ d = dict((name, UPDATE_CHOICES[self.choices[name].Selection][1]) for name, _gui in UPDATE_TYPES) d['auto_throttle'] = self.auto_throttle.Value if self.show_server_options: d['api_server'] = self.server.Value.strip() or None return d def layout(self): 'Layout GUI components.' gb = wx.GridBagSizer(hgap=3, vgap=3) for i, (name, guistring) in enumerate(UPDATE_TYPES): gb.Add(self.update_texts[name], (i, 0), flag=ALIGN_CENTER_VERTICAL) gb.Add(self.choices[name], (i, 1)) gb_h = wx.BoxSizer(HORIZONTAL) gb_h.Add(gb, 0, EXPAND) t_v = wx.BoxSizer(VERTICAL) t_v.AddStretchSpacer(1) t_v.Add(self.total, 0, EXPAND | ALIGN_CENTER) t_v.AddStretchSpacer(1) gb_h.Add(t_v, 1, EXPAND | ALIGN_CENTER) inner_sz = wx.BoxSizer(VERTICAL) if self.show_server_options: hsz = wx.BoxSizer(HORIZONTAL) hsz.Add(self.server_text, 0, EXPAND | wx.RIGHT, 7) hsz.Add(self.server, 1, EXPAND | wx.BOTTOM, 7) inner_sz.Add(hsz, 0, EXPAND) inner_sz.AddMany([ (self.header, 0, EXPAND), (self.desc, 1, EXPAND | TOP, 5), (gb_h, 0, EXPAND | TOP, 7), (self.auto_throttle, 0, EXPAND | TOP, 7), ]) sz = self.Sizer = wx.BoxSizer(VERTICAL) sz.Add(inner_sz, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 7) self.Fit() def SelectionChanged(self, e=None): 'Invoked when the user changes an update frequence Choice control.' # sum up 60/minutes for each choice to find how many updates # per hour we will request. mins = [ UPDATE_CHOICES[c.Selection][1] for name, c in self.choices.items() if adds_to_total(name) ] total_updates = sum(((60. / min) if min else 0) for min in mins) # the function color_for_total will use color to warn the user # if there is going to be too many updates. total_txt = self.total total_txt.SetLabel( _('{total_updates} / hour').format( total_updates=int(total_updates))) total_txt.ForegroundColour = color_for_total(total_updates) self.Layout()
def __init__(self, parent, windowId, parameterToEdit: PyutParam, mediator=None): """ The Dialog for parameter editing Args: parent: windowId: parameterToEdit: The parameter that is being edited mediator: """ super().__init__(parent, windowId, _("Parameter Edit"), theStyle=RESIZE_BORDER | CAPTION | STAY_ON_TOP, theMediator=mediator) self._parameterToEdit: PyutParam = parameterToEdit # ---------------- # Design of dialog # ---------------- self.SetAutoLayout(True) # Txt Ctrl Name lblName: StaticText = StaticText(self, ID_ANY, _("Name")) self._txtName: TextCtrl = TextCtrl(self, ID_TXT_PARAM_NAME, "", size=(125, -1)) self.Bind(EVT_TEXT, self._evtParamText, id=ID_TXT_PARAM_NAME) # Txt Ctrl Type lblType: StaticText = StaticText(self, ID_ANY, _("Type")) self._txtType: TextCtrl = TextCtrl(self, ID_ANY, "", size=(125, -1)) # Txt Ctrl Default lblDefault: StaticText = StaticText(self, ID_ANY, _("Default Value")) self._txtDefault: TextCtrl = TextCtrl(self, ID_ANY, "", size=(125, -1)) # --------------------- # Buttons OK and cancel self._btnOk: Button = Button(self, ID_BTN_PARAM_OK, _("&Ok")) self.Bind(EVT_BUTTON, self._onParamOk, id=ID_BTN_PARAM_OK) self._btnOk.SetDefault() self._btnCancel: Button = Button(self, ID_BTN_PARAM_CANCEL, _("&Cancel")) self.Bind(EVT_BUTTON, self._onParamCancel, id=ID_BTN_PARAM_CANCEL) szrButtons: BoxSizer = BoxSizer(HORIZONTAL) szrButtons.Add(self._btnOk, 0, ALL, 5) szrButtons.Add(self._btnCancel, 0, ALL, 5) szr1: FlexGridSizer = FlexGridSizer(cols=3, hgap=6, vgap=6) szr1.AddMany([ lblName, lblType, lblDefault, self._txtName, self._txtType, self._txtDefault ]) szr2: BoxSizer = BoxSizer(VERTICAL) szr2.Add(szr1, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) szr2.Add(szrButtons, 0, ALL | ALIGN_RIGHT, 5) self.SetSizer(szr2) self.SetAutoLayout(True) szr2.Fit(self) # Fill the text controls with PyutParam data self._txtName.SetValue(self._parameterToEdit.getName()) paramType: PyutType = self._parameterToEdit.getType() self._txtType.SetValue(paramType.value) self._txtDefault.SetValue( self._convertNone(self._parameterToEdit.getDefaultValue())) # Fix state of buttons (enabled or not) self._fixBtnDlgParams() # Set the focus self._txtName.SetFocus() self.Centre()
def __init__(self, parent: Window, wxID: int, title: str): """ Args: parent: parent window wxID: wx ID of this frame title: Title to display """ super().__init__(parent, wxID, title, DefaultPosition, Size(FrameWidth, FrameHeight)) self.logger: Logger = getLogger(__name__) # iconFileName: str = resource_filename(IMAGE_RESOURCES_PACKAGE, 'pyut.ico') # icon: Icon = Icon(iconFileName, BITMAP_TYPE_ICO) # # self.SetIcon(icon) if sysPlatform != PyutConstants.THE_GREAT_MAC_PLATFORM: fileName: str = PyutUtils.getResourcePath( packageName=IMAGE_RESOURCES_PACKAGE, fileName='pyut.ico') icon: Icon = Icon(fileName, BITMAP_TYPE_ICO) self.SetIcon(icon) self.Center(BOTH) longTextStr: str = PyutUtils.retrieveResourceText( ResourceTextType.KUDOS_TEXT_TYPE) self._textToShow: List[str] = longTextStr.split('\n') # Animation panel self._panel: Panel = Panel(self, ID_ANY, size=(FrameWidth, FrameHeight)) # Picture and text # bmp = Bitmap("img" + os.sep + "pyut.bmp", BITMAP_TYPE_BMP) # fileName = resource_filename(IMAGE_RESOURCES_PACKAGE, 'pyut.bmp') fileName: str = PyutUtils.getResourcePath(IMAGE_RESOURCES_PACKAGE, 'pyut.png') # bmp = Bitmap(fileName, BITMAP_TYPE_PNG) self._picture: StaticBitmap = StaticBitmap( self, ID_ANY, ImgPyut.embeddedImage.GetBitmap()) summaryText: str = "2020 The PyUt team and Humberto Sanchez II.\nPublished under the GNU General Public License" self._label: StaticText = StaticText(self, ID_ANY, summaryText, style=CAPTION) # Main sizer self.SetAutoLayout(True) sizer = BoxSizer(VERTICAL) sizer.Add(self._picture, 0, ALL | ALIGN_CENTER, 5) sizer.Add(self._panel, 1, ALL | ALIGN_CENTER, 5) sizer.Add(self._label, 0, ALL | ALIGN_CENTER, 5) btnOk: Button = Button(self, ID_OK, "&Ok") sizer.Add(btnOk, 0, ALL | ALIGN_CENTER, 5) self.SetSizer(sizer) sizer.Fit(self) self._textPosition = 0.0 # Current position self._timer: Timer = Timer(self) self.Bind(EVT_TIMER, self._onTimer, self._timer) self.Bind(EVT_BUTTON, self._onOk, btnOk) self._panel.Bind(EVT_PAINT, self.OnRefreshPanel) self.Bind(EVT_CLOSE, self._onOk)
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 __init__(self, *args, **kwargs): Panel.__init__(self, *args, **kwargs) sizer = GridBagSizer(5, 5) row = 0 col = 0 self.cb_html_output = CheckBox(self, label=u'Report in HTML') self.cb_html_output.Bind(EVT_CHECKBOX, self.__on_check) sizer.Add(self.cb_html_output, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.txt_html_report = TextCtrl(self, style=TE_READONLY) self.txt_html_report.Disable() sizer.Add(self.txt_html_report, pos=(row, col), span=(1, 3), flag=FLAG_ALL_AND_EXPAND) col += 3 self.btn_select_html = Button(self, label=u'Select HTML file') self.btn_select_html.Disable() self.btn_select_html.Bind(EVT_BUTTON, self.__on_select_file) sizer.Add(self.btn_select_html, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 self.cb_xml_output = CheckBox(self, label=u'Report in XML') self.cb_xml_output.Bind(EVT_CHECKBOX, self.__on_check) sizer.Add(self.cb_xml_output, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.txt_xml_report = TextCtrl(self, style=TE_READONLY) self.txt_xml_report.Disable() sizer.Add(self.txt_xml_report, pos=(row, col), span=(1, 3), flag=FLAG_ALL_AND_EXPAND) col += 3 self.btn_select_xml = Button(self, label=u'Select XML file') self.btn_select_xml.Disable() self.btn_select_xml.Bind(EVT_BUTTON, self.__on_select_file) sizer.Add(self.btn_select_xml, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 self.cb_options = CheckBox(self, label=u'Additional options') self.cb_options.Bind(EVT_CHECKBOX, self.__on_check) sizer.Add(self.cb_options, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.txt_options = TextCtrl(self) self.txt_options.Disable() sizer.Add(self.txt_options, pos=(row, col), span=(1, 3), flag=FLAG_ALL_AND_EXPAND) col += 3 self.btn_nose_help = Button(self, label=u'Show help') self.btn_nose_help.Bind(EVT_BUTTON, self.__on_show_help) sizer.Add(self.btn_nose_help, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 self.btn_load_tests_from_files = Button(self, label=u'Load tests from files') self.btn_load_tests_from_files.Bind(EVT_BUTTON, self.__load_tests_from_files) sizer.Add(self.btn_load_tests_from_files, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.btn_load_tests_from_dir = Button( self, label=u'Load tests from directory') self.btn_load_tests_from_dir.Bind(EVT_BUTTON, self.__load_tests_from_directory) sizer.Add(self.btn_load_tests_from_dir, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 dummy_label = StaticText(self) sizer.Add(dummy_label, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.cb_browser = Choice(self, choices=Browser.get_supported_browsers()) self.cb_browser.Select(0) sizer.Add(self.cb_browser, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.btn_run = Button(self, label=u'Run test cases') self.btn_run.Bind(EVT_BUTTON, self.__run_tests) sizer.Add(self.btn_run, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 window = SplitterWindow(self, style=SP_3D | SP_LIVE_UPDATE) self.tree_ctrl = CustomTreeCtrl( window, style=TR_SINGLE | TR_HAS_BUTTONS | TR_AUTO_CHECK_CHILD | TR_AUTO_CHECK_PARENT | TR_AUTO_TOGGLE_CHILD) self.tree_ctrl.SetBackgroundColour(self.GetBackgroundColour()) self.tree_ctrl.SetForegroundColour(self.GetForegroundColour()) self.tree_ctrl.Bind(EVT_TREE_ITEM_CHECKED, self.__on_tree_check) self.txt_ctrl = TextCtrl(window, style=TE_MULTILINE | TE_READONLY | HSCROLL | VSCROLL) font_size = self.txt_ctrl.GetFont().GetPointSize() self.txt_ctrl.SetFont( Font(font_size, FONTFAMILY_TELETYPE, NORMAL, NORMAL)) window.SplitVertically(self.tree_ctrl, self.txt_ctrl) sizer.Add(window, pos=(row, col), span=(1, 5), flag=FLAG_ALL_AND_EXPAND) sizer.AddGrowableCol(2, 1) sizer.AddGrowableRow(row, 1) self.SetSizerAndFit(sizer)
class AccountPrefsDialog(wx.Dialog): 'Small dialog window for editing and creating accounts.' # Use the following two methods to create and edit accounts. @classmethod def create_new(cls, parent, protocol_name): ''' Make a dialog box that can create a new account. ''' return cls(parent, protocol_name = protocol_name) @classmethod def edit_account(cls, parent, account): ''' Make a dialog box that can edit an existing Account. ''' return cls(parent, account = account) # def __init__(self, parent, account = None, protocol_name = None): "Please do not call directly. See classmethods create_new and edit_account." # Editing an existing account if account is not None: self.new = False assert protocol_name is None protocolinfo = account.protocol_info() self.protocol_name = account.protocol title = '%s - %s Settings' % (account.name, protocolinfo.name) # Creating a new account if account is None: self.new = True protocolinfo = protocols[protocol_name] self.protocol_name = protocol_name title = '%s Account' % protocolinfo.name # What to call the username (screenname, username, Jabber ID, etc.) self.screenname_name = protocolinfo.username_desc wx.Dialog.__init__(self, parent, title=title, size=(400,300)) self.account = account if account is not None else emptystringer(getattr(protocolinfo, 'defaults', None)) self.new = account is None self.protocolinfo = protocolinfo # Set the account type icon from gui import skin self.SetFrameIcon(skin.get('serviceicons.%s' % self.protocol_name)) self.formtype = getattr(protocolinfo, 'form', 'default') self.info_callbacks = Delegate() if self.new: self._allaccts = [acctid(a.protocol, a.name) for a in profile.account_manager] self.construct(account is None) self.layout() # enable or disable the save button as necessary. self.check_warnings() self.Fit() # focus the first enabled text control. for c in self.Children: if isinstance(c, TextCtrl) and c.IsEnabled() and c.IsEditable(): if c is get(self, 'password', None): c.SetSelection(-1, -1) # only makes sense to select all on a password field :) wx.CallAfter(c.SetFocus) break def info(self): 'Returns a Storage containing the attributes edited by this dialog.' info = Storage(name = self.name.Value, protocol = self.protocol_name) info.protocol, info.name = strip_acct_id(info.protocol, info.name) if hasattr(self, 'password'): info.password_len = len(self.password.Value) try: info.password = profile.crypt_pw(self.password.Value) except UnicodeEncodeError: # the database has corrupted the password. log.warning('corrupted password') info.password = '' self.password.Value = '' import hub hub.get_instance().on_error('This account\'s password has been corrupted somehow. Please report it immediately.') if hasattr(self, 'host'): info.server = (self.host.Value, int(self.port.Value) if self.port.Value else '') if hasattr(self, 'remote_alias'): info.remote_alias = self.remote_alias.Value if hasattr(self, 'autologin'): info.autologin = bool(self.autologin.Value) if hasattr(self, 'resource'): info.update(resource = self.resource.Value, priority = try_this(lambda: int(self.priority.Value), DEFAULT_JABBER_PRIORITY)) # , # confserver = self.confserver.Value if hasattr(self, 'dataproxy'): info.update(dataproxy = self.dataproxy.Value) for d in getattr(self.protocolinfo, 'more_details', []): attr = d['store'] ctrl = getattr(self, attr) info[attr] = ctrl.Value getattr(self, 'info_' + self.formtype, lambda *a: {})(info) for info_cb in self.info_callbacks: info_cb(info) defaults = self.protocolinfo.get('defaults', {}) for k in defaults: if k not in info: info[k] = getattr(self.account, k, defaults.get(k)) return info def info_email(self, info): info.update(Storage(updatefreq = int(self.updatefreq.Value)*60)) if hasattr(self, 'mailclient'): assert isinstance(self.mailclient, basestring) info.update(dict(mailclient = self.mailclient, custom_inbox_url = self.custom_inbox_url, custom_compose_url = self.custom_compose_url)) if hasattr(self, 'emailserver'): # email server information servertype = self.protocolinfo.needs_server.lower() info.update({servertype + 'server': self.emailserver.Value, servertype + 'port' : int(self.emailport.Value) \ if self.emailport.Value else '', 'require_ssl': self.require_ssl.Value}) if hasattr(self, 'smtp_server'): info.update(email_address = self.email_address.Value, smtp_server = self.smtp_server.Value, smtp_port = int(self.smtp_port.Value) if self.smtp_port.Value else '', smtp_require_ssl = self.smtp_require_ssl.Value) if self.smtp_same.Value: info.update(smtp_username = self.name.Value, smtp_password = self.password.Value) else: info.update(smtp_username = self.smtp_username.Value, smtp_password = self.smtp_password.Value) def info_social(self, info): for d in ((self.new and getattr(self.protocolinfo, 'new_details', []) or []) + getattr(self.protocolinfo, 'basic_details', [])): type_ = d['type'] if type_ in ['bool']: attr = d['store'] ctrl = getattr(self, attr) info[attr] = ctrl.Value elif type_ == 'meta': key = d['store'] val = d['value'] info[key] = val elif type_ == 'label': pass else: raise AssertionError("This mechanism needs to be completed!") filters = {} for key in self.checks: filters[key] = [] for chk in self.checks[key]: t, i = chk.Name.split('/') assert len(filters[key]) == int(i), (key, len(filters), int(i)) filters[t].append(chk.Value) info['filters'] = filters def on_expand(self, e): isshown = self.expanded self.details.Show(not isshown) self.FitInScreen() self.expanded = not isshown wx.CallAfter(self.Refresh) def construct(self, is_new): self.construct_common(is_new) getattr(self, 'construct_' + self.formtype, getattr(self, 'construct_default'))() # after all textboxes have been constructed, bind to their KeyEvents so # that we can disable the Save button when necessary # Make sure textboxes have values. txts = [self.name] for textbox in self.get_required_textboxes(all = True): textbox.Bind(wx.EVT_TEXT, lambda e: self.check_warnings()) if self.protocolinfo.get('needs_smtp', False): self.Bind(wx.EVT_RADIOBUTTON, lambda e: (e.Skip(), self.check_warnings())) # A small arrow for expanding the dialog to show advanced options. from gui.chevron import Chevron self.expand = Chevron(self, 'Advanced') self.expand.Bind(wx.EVT_CHECKBOX, self.on_expand) self.expanded = False self.AffirmativeId = wx.ID_SAVE self.save = wx.Button(self, wx.ID_SAVE, _('&Save')) self.save.Bind(wx.EVT_BUTTON, self.on_save) self.save.SetDefault() if is_new or try_this(lambda: self.password.Value, None) == '': self.save.Enable(False) self.cancel = wx.Button(self, wx.ID_CANCEL, _('&Cancel')) self.cancel.Bind(wx.EVT_BUTTON, self.on_cancel) def check_warnings(self): warnings = list(getattr(self.protocolinfo, 'warnings', ())) warnings.append(dict(checker = self.check_account_unique, critical = True, text = _('That account already exists.'))) warnings.append(dict(checker = self.filled_in, critical = True)) warn_texts = [] enable_save = True info = self.info() if self.protocolinfo.get('needs_password', True): info['plain_password'] = self.password.Value for warning in warnings: checker = warning.get('checker', None) check_passed = True if checker is not None: check_passed = checker(info) if not check_passed: text = warning.get('text', None) if text is not None: warn_texts.append(text) if warning.get('critical', False): enable_save = False self.set_warnings(warn_texts) self.save.Enable(enable_save) def construct_default(self): acct = self.account # Auto login checkbox: shown by default, turn off with show_autologin = False if getattr(self.protocolinfo, 'show_autologin', True): self.autologin = wx.CheckBox(self, -1, _('&Auto login')) self.autologin.SetToolTipString(_('If checked, this account will automatically sign in when Digsby starts.')) self.autologin.Value = bool(getattr(self.account, 'autologin', False)) # Register new account checkbox: off by default. shows only on when this # is a new account dialog, and when needs_register = True if self.new and getattr(self.protocolinfo, 'needs_register', False): self.register = wx.CheckBox(self, -1, _('&Register New Account')) self.register.Bind(wx.EVT_CHECKBOX, self.on_register) if getattr(self.protocolinfo, 'needs_remotealias', False): self.remote_alias = TextCtrl(self, -1, value = getattr(acct, 'remote_alias', ''), validator = LengthLimit(120)) if getattr(self.protocolinfo, 'needs_resourcepriority', False): # Length limit is according to rfc self.resource = TextCtrl(self, value = getattr(acct, 'resource') or 'Digsby', validator = LengthLimit(1023)) priority = getattr(acct, 'priority', DEFAULT_JABBER_PRIORITY) if priority == '': priority = DEFAULT_JABBER_PRIORITY self.priority = TextCtrl(self, value = str(priority), validator = NumericLimit(-127,128)) self.priority.MinSize = wx.Size(1, -1) if getattr(self.protocolinfo, 'needs_dataproxy', False): self.dataproxy = TextCtrl(self, value = getattr(acct, 'dataproxy', ''), validator = LengthLimit(1024)) if getattr(self.protocolinfo, 'hostport', True): server = getattr(self.account, 'server') if server: host, port = server else: host, port = '', '' self.host = TextCtrl(self, size = (110, -1), value=host, validator = LengthLimit(1023)) self.port = TextCtrl(self, value = str(port), validator = PortValidator()) self.port.MinSize = wx.Size(1, -1) def on_register(self, event): checked = self.register.IsChecked() self.save.Label = _(u"&Register") if checked else _(u"&Save") def add_warning(self, text): lbl = self.label_warnings.Label if lbl: newlbl = lbl + u'\n' + text else: newlbl = text self.set_warning(newlbl) def set_warnings(self, texts): self.set_warning('\n'.join(texts)) def set_warning(self, text): self.label_warnings.Label = text # FIXME: this throws the sizing on Mac all out of whack. Perhaps some native API gets # messed up when called on a hidden control? if not platformName == "mac": if not text: self.label_warnings.Show(False) else: self.label_warnings.Show(True) self.Layout() self.Fit() self.Refresh() def clear_warning(self): self.set_warning(u'') def construct_common(self, is_new): self.label_warnings = StaticText(self, -1, '', style = wx.ALIGN_CENTER) self.label_warnings.SetForegroundColour(wx.Colour(224, 0, 0)) self.clear_warning() needs_password = self.protocolinfo.get('needs_password', True) self.label_screenname = StaticText(self, -1, self.screenname_name + ':', style = ALIGN_RIGHT) if needs_password: self.label_password = StaticText(self, -1, 'Password:'******'' and hasattr(self.protocolinfo, 'newuser_url'): sn = self.url_screenname = wx.HyperlinkCtrl(self, -1, 'New User?', getattr(self.protocolinfo, 'newuser_url')) sn.HoverColour = sn.VisitedColour = sn.NormalColour if needs_password and hasattr(self.protocolinfo, 'password_url'): password = self.url_password = wx.HyperlinkCtrl(self, -1, 'Forgot Password?', getattr(self.protocolinfo, 'password_url')) password.HoverColour = password.VisitedColour = password.NormalColour if self.protocolinfo.get('needs_smtp', False): self.email_address = TextCtrl(self, -1, value = getattr(self.account, 'email_address', ''), size = txtSize, validator=LengthLimit(1024)) self.name = TextCtrl(self, -1, value=self.account.name, size=txtSize, validator=LengthLimit(1024)) # disable editing of username if this account is not new if not self.new: self.name.SetEditable(False) self.name.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_SCROLLBAR)) # self.name.Enable(self.new) if needs_password: password = self.account._decryptedpw() f = lambda p: TextCtrl(self, -1, value = p, size = txtSize, style = wx.TE_PASSWORD, validator = LengthLimit(128)) try: self.password = f(password) except UnicodeDecodeError: self.password = f('') def on_cancel(self, e): self.EndModal(self.EscapeId) def on_save(self, e): # Do some simple protocol dependent validation. c = get(self.account, 'connection', None) if c is not None: for updatee in get(c, 'needs_update', []): try: attr, fname = updatee f = getattr(c, fname) except: attr = updatee f = lambda _v: setattr(c, attr, _v) f(getattr(self, attr).Value) for attr, validator, message in getattr(self.protocolinfo, 'validators', []): if not validator(getattr(self, attr).Value): return wx.MessageBox(message, 'Account Information Error') if hasattr(self, 'register') and self.register.IsChecked(): self.save.Enabled = False info = self.info() log.info_s('adding account: %r', info) profile.register_account( on_success = lambda: wx.CallAfter(self.on_success_register), on_fail = lambda error: wx.CallAfter(self.on_fail_register, error), **info) else: self.EndModal(wx.ID_SAVE) def on_success_register(self): self.EndModal(wx.ID_SAVE) def on_fail_register(self, error): textcode, text, kind, codenum = error wx.MessageBox("Error %(codenum)d: %(text)s" % locals(), textcode) self.EndModal(wx.ID_CANCEL) def EndModal(self, return_code): if self.formtype == 'social' and hasattr(self, '_origfilters') and return_code != self.AffirmativeId and self.account: if self.account.filters != self._origfilters: self.account.filters = self._origfilters self.account.notify('alerts') wx.Dialog.EndModal(self, return_code) def get_required_textboxes(self, all = False): tb = [self.name] pinfo = self.protocolinfo if pinfo.get('needs_password', True): tb += [self.password] if pinfo.get('needs_smtp', False): tb += [self.email_address, self.emailserver, self.emailport, self.smtp_port, self.smtp_server] # when the "same" radio is not checked, the extra SMTP user/pass boxes # are required as well. if all or not self.smtp_same.Value: tb += [self.smtp_username, self.smtp_password] if pinfo.get('needs_remotealias', False) and all: tb += [self.remote_alias] return tb def check_account_unique(self, i): if self.new: return not (acctid(self.protocol_name, i.name) in self._allaccts) or self.protocol_name in ('imap', 'pop') else: return True def filled_in(self, _i): return all(tb.Value != '' for tb in self.get_required_textboxes()) def SwapDefaultPorts(self, event, srv, ssl, portfield): stdport = unicode(self.protocolinfo.defaults[srv + 'port']) sslport = unicode(self.protocolinfo.defaults[srv + 'port_ssl']) rightport, wrongport = (sslport, stdport) if ssl else (stdport, sslport) if portfield.Value == wrongport: portfield.Value = rightport event.Skip() def construct_email(self): srv = self.protocolinfo.get('needs_server', None) if srv is not None: srv = srv.lower() self.emailserver = TextCtrl(self, -1, size = txtSize, value = unicode(getattr(self.account, srv + 'server')), validator=LengthLimit(1024)) self.emailport = TextCtrl(self, -1, size = (60, -1), value = unicode(getattr(self.account, srv + 'port')), validator = PortValidator()) reqssl = self.require_ssl = CheckBox(self, '&This server requires SSL', value = bool(self.account.require_ssl)) reqssl.Bind(wx.EVT_CHECKBOX, lambda e: self.SwapDefaultPorts(e, srv, reqssl.Value, self.emailport)) smtp = self.protocolinfo.get('needs_smtp', False) if smtp: self.construct_smtp() updatetext = _('Check for new mail every {n} minutes').split(' {n} ') self.updatetext1 = StaticText(self, -1, updatetext[0]) self.updatetext2 = StaticText(self, -1, updatetext[1]) # email update frequency self.updatefreq = TextCtrl(self, -1, size=(30, -1), validator = NumericLimit(1, 999)) def update_changed(e): e.Skip(True) import gettext newval = gettext.ngettext(u'minute', u'minutes', int(self.updatefreq.Value or 0)) if newval != self.updatetext2.Label: self.updatetext2.Label = newval self.updatefreq.Bind(wx.EVT_TEXT, update_changed) minutes = str(self.account.updatefreq/60) self.updatefreq.Value = minutes if self.protocolinfo.get('needs_webclient', True): self.mailclient = self.account.mailclient or 'sysdefault' self.custom_inbox_url = self.account.custom_inbox_url self.custom_compose_url = self.account.custom_compose_url self.mailclienttext = StaticText(self, -1, _('Mail Client:')) self.mailclient_choice = wx.Choice(self) self.update_mailclient() self.mailclient_choice.Bind(wx.EVT_CHOICE, self.on_mailclient_choice) def construct_smtp(self): self.smtp_server = TextCtrl(self, -1, size = txtSize, value = unicode(getattr(self.account, 'smtp_server', '')), validator = LengthLimit(1024), ) self.smtp_port = TextCtrl(self, -1, size = (60, -1), value = unicode(getattr(self.account, 'smtp_port', '')), validator = PortValidator()) reqssl = self.smtp_require_ssl = CheckBox(self, '&This server requires SSL', value = bool(getattr(self.account, 'smtp_require_ssl', False))) reqssl.Bind(wx.EVT_CHECKBOX, lambda e: self.SwapDefaultPorts(e, 'smtp_', reqssl.Value, self.smtp_port)) servertype = self.protocolinfo.get('needs_server') self.smtp_same = RadioButton(self, -1, _('SMTP username/password are the same as {servertype}').format(servertype=servertype), style = wx.RB_GROUP) self.smtp_different = RadioButton(self, -1, _('Log on using:')) u = self.smtp_username = TextCtrl(self, -1, size = (110, -1), validator=LengthLimit(1024)) p = self.smtp_password = TextCtrl(self, -1, size = (110, -1), style = wx.TE_PASSWORD, validator=LengthLimit(1024)) smtpuser, smtppass = getattr(self.account, 'smtp_username', ''), getattr(self.account, 'smtp_password', '') if (not smtpuser and not smtppass) or smtpuser == self.name.Value and smtppass == self.password.Value: self.smtp_same.SetValue(True) u.Enable(False) p.Enable(False) else: self.smtp_different.SetValue(True) u.Enable(True) p.Enable(True) u.Value = smtpuser p.Value = smtppass def on_radio(e = None, val = False): # when a radio is clicked enabled = val if e is None else e.EventObject is not self.smtp_same u.Enable(enabled) p.Enable(enabled) self.Bind(wx.EVT_RADIOBUTTON, on_radio) def construct_social(self): types = ('alerts','feed', 'indicators') self.checks = {} if self.account.filters: from copy import deepcopy as copy self._origfilters = copy(self.account.filters) def set_filter(e): _t,_i = e.EventObject.Name.split('/') keylist = get(self.account,'%s_keys' % _t) _k = get(keylist, int(_i)) self.account.filters[_t][_k] = e.IsChecked() if _t == 'alerts': self.account.notify(_t) for typ in types: if getattr(self.protocolinfo, 'needs_%s' % typ, False): self.checks[typ] = [] for i, nicename in enumerate(self.protocolinfo[typ]): key = get(get(self.account,'%s_keys' % typ), i, None) if key is not None: val = self.account.filters[typ][key] else: val = True chk = wx.CheckBox(self, label=nicename, name='%s/%s' % (typ,i)) chk.Value = val if self.account: chk.Bind(wx.EVT_CHECKBOX, set_filter) self.checks[typ].append(chk) def layout_social(self, sizer, row): sizer, row = self.layout_top(sizer, row) self.layout_bottom(sizer,row) def layout_top(self, sizer, row): add = sizer.Add for d in ((self.new and getattr(self.protocolinfo, 'new_details', []) or []) + getattr(self.protocolinfo, 'basic_details', [])): type_ = d['type'] if type_ == 'bool': attr = d['store'] desc = d['label'] default = d['default'] ctrl = wx.CheckBox(self, -1, desc) setattr(self, attr, ctrl) s = wx.BoxSizer(wx.HORIZONTAL) ctrl.SetValue(getattr(self.account, attr, default) if self.account else default) s.Add(ctrl, 0, wx.EXPAND) # allow checkboxes to have [?] links next to them help_url = d.get('help', None) if help_url is not None: from gui.toolbox import HelpLink s.Add(HelpLink(self, help_url), 0, wx.EXPAND) add(s, (row,1), (1,3), flag = ALL, border = ctrl.GetDefaultBorder()) row += 1 elif type_ == 'label': desc = d['label'] ctrl = wx.StaticText(self, -1, desc) add(ctrl, (row,1), (1,3), flag = ALL, border = ctrl.GetDefaultBorder()) row += 1 elif type_ == 'meta': pass else: raise AssertionError("This mechanism needs to be completed!") return sizer, row def build_details_social(self,sizer,row): types = ('alerts','feed', 'indicators') hsz = BoxSizer(wx.HORIZONTAL) d = self.details add = lambda c,s,*a: (d.add(c),s.Add(c,*a)) for i, key in enumerate(types): checks = self.checks.get(key,()) if not checks: continue sz = BoxSizer(wx.VERTICAL) tx = StaticText(self, -1, _('{show_topic}:').format(show_topic = self.protocolinfo['show_%s_label' % key]), style = wx.ALIGN_LEFT) from gui.textutil import CopyFont tx.Font = CopyFont(tx.Font, weight = wx.BOLD) add(tx, sz, 0, wx.BOTTOM, tx.GetDefaultBorder()) for chk in checks: add(chk, sz, 0, ALL, chk.GetDefaultBorder()) hsz.Add(sz,0) # if i != len(types)-1: hsz.AddSpacer(15) self.Sizer.Add(hsz,0,wx.BOTTOM | wx.LEFT,10) self.build_details_default(sizer, row) def update_mailclient(self, mc = None): if mc is None: mc = self.account.mailclient or '' ch = self.mailclient_choice with ch.Frozen(): ch.Clear() choices = [MAIL_CLIENT_SYSDEFAULT] file_entry = 0 if mc.startswith('file:'): import os.path if not os.path.exists(mc[5:]): mc == 'sysdefault' else: choices += [_('Custom ({mailclient_name})').format(mailclient_name=mc[5:])] file_entry = len(choices) - 1 choices += [MAIL_CLIENT_OTHER, MAIL_CLIENT_URL] do(ch.Append(s) for s in choices) if mc == 'sysdefault': selection = 0 elif mc == '__urls__': selection = ch.Count - 1 else: selection = file_entry ch.SetSelection(selection) ch.Layout() def on_mailclient_choice(self, e): # TODO: don't use StringSelection, that's dumb. val = self.mailclient_choice.StringSelection if val.startswith(MAIL_CLIENT_SYSDEFAULT): self.mailclient = 'sysdefault' elif val == MAIL_CLIENT_OTHER: import os, sys defaultDir = os.environ.get('ProgramFiles', '') wildcard = '*.exe' if sys.platform == 'win32' else '*.*' filediag = wx.FileDialog(self, _('Please choose a mail client'), defaultDir = defaultDir, wildcard = wildcard, style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if filediag.ShowModal() == wx.ID_OK: self.mailclient = 'file:' + filediag.Path elif val == MAIL_CLIENT_URL: diag = LaunchURLDialog(self, self.custom_inbox_url, self.custom_compose_url) try: if wx.ID_OK == diag.ShowModal(): self.mailclient = '__urls__' self.custom_inbox_url = diag.InboxURL self.custom_compose_url = diag.ComposeURL finally: diag.Destroy() else: self.mailclient = val self.update_mailclient(getattr(self, 'mailclient', 'sysdefault')) def build_details_email(self,sizer,row): v = BoxSizer(wx.VERTICAL) d = self.details add = lambda c,s,*a,**k: (d.add(c),s.Add(c,*a,**k)) # text, update frequency textbox, text h = BoxSizer(wx.HORIZONTAL) add(self.updatetext1, h, 0, wx.ALIGN_CENTER_VERTICAL | ALL, self.updatetext1.GetDefaultBorder()) add(self.updatefreq, h, 0, ALL, self.updatefreq.GetDefaultBorder()) add(self.updatetext2, h, 0, wx.ALIGN_CENTER_VERTICAL | ALL, self.updatetext2.GetDefaultBorder()) v.Add(h, 0, EXPAND) # text, mail client choice if hasattr(self, 'mailclient_choice'): h2 = BoxSizer(wx.HORIZONTAL) add(self.mailclienttext, h2, 0, ALIGN_CENTER_VERTICAL | ALL, self.mailclienttext.GetDefaultBorder()) add(self.mailclient_choice, h2, 1, ALL, self.mailclient_choice.GetDefaultBorder()) # h2.Add((30,0)) v.Add(h2, 0, EXPAND | ALL, 3) add(wx.StaticLine(self),v,0,EXPAND|wx.TOP|wx.BOTTOM,3) if hasattr(self, 'smtp_same'): add(self.smtp_same, v, 0, EXPAND | ALL, self.GetDefaultBorder()) add(self.smtp_different, v, 0, EXPAND | ALL, self.GetDefaultBorder()) # v.AddSpacer(3) v2 = wx.GridBagSizer(8, 8); v2.SetEmptyCellSize((0,0)) add(StaticText(self, -1, _('Username:'******'Password:'******'label_warnings'): warn_sz = BoxSizer(wx.HORIZONTAL) warn_sz.Add(self.label_warnings, 1, flag = wx.EXPAND | wx.ALIGN_CENTER) s.Add(warn_sz, flag = wx.EXPAND | wx.TOP, border = self.GetDefaultBorder()) # Top Sizer: username, password, autologin[, register new] fx = wx.GridBagSizer(0,0) s.Add(fx, 1, EXPAND|ALL, self.GetDialogBorder()) # screenname: label, textfield, hyperlink row = 0 fx.SetEmptyCellSize((0,0)) if self.protocolinfo.get('needs_smtp', False): # email address label = StaticText(self, -1, _('Email Address')) fx.Add(label, (row, 0), flag = centerright | ALL, border = label.GetDefaultBorder()) fx.Add(self.email_address, (row, 1), flag = ALL, border = self.email_address.GetDefaultBorder()) row += 1 # username fx.Add(self.label_screenname, (row,0), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | ALL, border = self.label_screenname.GetDefaultBorder()) fx.Add(self.name, (row,1), flag = ALL, border = self.name.GetDefaultBorder()) if hasattr(self, 'url_screenname'): fx.Add(self.url_screenname, (row,2), (1,2), flag=ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | ALL, border = self.url_screenname.GetDefaultBorder()) row += 1 # password: label, textfield, hyperlink if self.protocolinfo.get('needs_password', True): fx.Add(self.label_password, (row,0), flag=ALIGN_CENTER_VERTICAL | ALIGN_RIGHT | ALL, border = self.label_password.GetDefaultBorder()) fx.Add(self.password, (row,1), flag = ALL, border = self.password.GetDefaultBorder()) if hasattr(self, 'url_password'): fx.Add(self.url_password, (row,2), (1,2), flag=ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | ALL, border = self.url_password.GetDefaultBorder()) fx.AddGrowableCol(1,1) row += 1 getattr(self, 'layout_' + self.formtype, getattr(self, 'layout_default'))(fx, row) row += 1 def layout_default(self, sizer, row): add = sizer.Add if hasattr(self, 'remote_alias'): add(StaticText(self, -1, _('&Display Name:')), (row,0), flag = ALIGN_RIGHT|ALIGN_CENTER_VERTICAL|ALL, border=self.GetDefaultBorder()) add(self.remote_alias, (row,1),flag = EXPAND | ALL, border = self.remote_alias.GetDefaultBorder()) row += 1 # autologin and register new account if hasattr(self, 'autologin') or hasattr(self, 'register'): checks = BoxSizer(wx.HORIZONTAL) if hasattr(self, 'autologin'): checks.Add(self.autologin, 0, EXPAND | ALL, self.autologin.GetDefaultBorder()) if hasattr(self, 'register'): #checks.AddSpacer(10) checks.Add(self.register, 0, EXPAND | ALL, self.register.GetDefaultBorder()) sizer.Add(checks, (row,1), (1,3)) row += 1 self.layout_bottom(sizer,row) def layout_bottom(self, sizer, row): s = self.Sizer sizer.Add(self.expand, (row, 0), (1,3)) row+=1 self.details = Clique() account_gui = getattr(self.protocolinfo, 'account_gui', None) if account_gui is not None: # Protocolmeta can specify a lazy import path to separate # GUI components. with traceguard: self.add_account_gui(account_gui) else: getattr(self, 'build_details_' + self.formtype, getattr(self, 'build_details_default'))(sizer,row) self.expand.Show(bool(self.details)) self.details.Show(False) s.Add(build_button_sizer(self.save, self.cancel, border=self.save.GetDefaultBorder()), 0, EXPAND | ALL, self.GetDefaultBorder()) def add_account_gui(self, account_gui): ''' Adds account specific GUI to the "extended" section. account_gui must be a dotted string import path to a function which returns a GUI component, and will be called with two arguments: this dialog, and the account we're editing/creating. ''' log.info('loading account GUI from %r', account_gui) self.details_panel = import_function(account_gui)(self, self.account) self.details.add(self.details_panel) self.info_callbacks += lambda info: info.update(self.details_panel.info()) self.Sizer.Add(self.details_panel, 0, EXPAND | ALL, self.GetDefaultBorder()) def layout_email(self, gridbag, row): add = gridbag.Add # email Server, Port servertype = getattr(self.protocolinfo, 'needs_server', None) if servertype is not None: add(wx.StaticLine(self),(row,0),(1,4),flag = EXPAND) row +=1 add(StaticText(self, -1, '&%s Server:' % _(servertype), style = ALIGN_RIGHT), (row, 0), flag = centerright | ALL, border = self.GetDefaultBorder()) add(self.emailserver, (row, 1), flag = ALL, border = self.emailserver.GetDefaultBorder()) add(StaticText(self, -1, 'P&ort:', style = ALIGN_RIGHT), (row, 2), flag = centerright | ALL, border = self.GetDefaultBorder()) add(self.emailport, (row, 3), flag = ALL, border = self.emailport.GetDefaultBorder()) row += 1 # This server requires SSL add(self.require_ssl, (row, 1), flag = ALL, border = self.require_ssl.GetDefaultBorder()) row += 1 if getattr(self.protocolinfo, 'needs_smtp', False): add(StaticText(self, -1, _('SMTP Server:'), style = ALIGN_RIGHT), (row, 0), flag = centerright | ALL, border = self.GetDefaultBorder()) add(self.smtp_server, (row, 1), flag = ALL, border = self.smtp_server.GetDefaultBorder()) add(StaticText(self, -1, _('Port:'), style = ALIGN_RIGHT), (row, 2), flag = centerright | ALL, border = self.GetDefaultBorder()) add(self.smtp_port, (row, 3), flag = ALL, border = self.smtp_port.GetDefaultBorder()) row += 1 add(self.smtp_require_ssl, (row, 1), flag = ALL, border = self.smtp_require_ssl.GetDefaultBorder()) row += 1 self.layout_default(gridbag, row) def build_details_default(self,sizer,row): Txt = lambda s: StaticText(self, -1, _(s)) details = self.details add = lambda i, *a, **k: (sizer.Add(i, *a, **k),details.add(i)) # position span if hasattr(self, 'host'): add(Txt(_('Host:')), (row, 0), flag = ALIGN_RIGHT|ALIGN_CENTER_VERTICAL|ALL, border = self.GetDefaultBorder()) add( self.host, (row, 1), flag = EXPAND|ALL, border = self.host.GetDefaultBorder()) add(Txt(_('Port:')), (row, 2), flag = ALIGN_RIGHT|ALIGN_CENTER_VERTICAL|ALL, border = self.GetDefaultBorder()) add( self.port, (row, 3), flag = EXPAND|ALL, border = self.port.GetDefaultBorder()) row += 1 if hasattr(self, 'resource'): add(Txt(_('Resource:')), (row, 0), flag = ALIGN_RIGHT|ALIGN_CENTER_VERTICAL|ALL, border = self.GetDefaultBorder()) add( self.resource, (row, 1), flag = EXPAND|ALL, border = self.resource.GetDefaultBorder()) add(Txt(_('Priority:')), (row, 2), flag = ALIGN_RIGHT|ALIGN_CENTER_VERTICAL|ALL, border = self.GetDefaultBorder()) add( self.priority, (row, 3), flag = EXPAND|ALL, border = self.priority.GetDefaultBorder()) row += 1 if hasattr(self, 'dataproxy'): add(Txt(_('Data Proxy:')), (row, 0), flag = ALIGN_RIGHT|ALIGN_CENTER_VERTICAL|ALL, border = self.GetDefaultBorder()) add( self.dataproxy, (row, 1), (1, 3), flag = EXPAND|ALL, border = self.dataproxy.GetDefaultBorder()) row += 1 sub2 = BoxSizer(wx.HORIZONTAL) col1 = BoxSizer(wx.VERTICAL) col2 = BoxSizer(wx.VERTICAL) # add = lambda c,r,f,p,s: (details.add(c),s.Add(c,r,f,p)) for d in getattr(self.protocolinfo, 'more_details', []): type_ = d['type'] name = d['store'] if type_ == 'bool': ctrl = wx.CheckBox(self, -1, d['label']) setattr(self, name, ctrl) ctrl.SetValue(bool(getattr(self.account, name))) details.add(ctrl) col2.Add(ctrl, 0, ALL, ctrl.GetDefaultBorder()) elif type_ == 'enum': ctrl = RadioPanel(self, d['elements'], details) setattr(self, name, ctrl) ctrl.SetValue(getattr(self.account, name)) col1.Add(ctrl, 0, ALL, self.GetDefaultBorder()) sub2.Add(col1,0,wx.RIGHT) sub2.Add(col2,0,wx.LEFT) self.Sizer.Add(sub2, 0, wx.ALIGN_CENTER_HORIZONTAL)
class LaunchURLDialog(OKCancelDialog): ''' email accounts let you specify custom URLs for inbox and compose actions. this dialog lets you enter those URLs. ''' MINSIZE = (350, 1) inbox_tooltip = _('Enter the URL that will be launched when you click "Inbox" for this email account.') compose_tooltip = _('Enter the URL that will be launched when you click "Compose" for this email account.') def __init__(self, parent, inbox_url = None, compose_url = None): OKCancelDialog.__init__(self, parent, title=_('Launch URL')) self.construct(inbox_url, compose_url) self.layout() @property def InboxURL(self): return self.inbox_text.Value @property def ComposeURL(self): return self.compose_text.Value def construct(self, inbox_url = None, compose_url = None): # construct GUI self.inbox_label = StaticText(self, -1, _('Enter a URL for the Inbox')) self.inbox_text = TextCtrl(self, -1, inbox_url or '') self.compose_label = StaticText(self, -1, _('Enter a URL for the Compose window')) self.compose_text = TextCtrl(self, -1, compose_url or '') # add tooltips self.inbox_label.SetToolTipString(self.inbox_tooltip) self.inbox_text.SetToolTipString(self.inbox_tooltip) self.compose_label.SetToolTipString(self.compose_tooltip) self.compose_text.SetToolTipString(self.compose_tooltip) # connect event handlers for disabling OK when there is missing # content. self.inbox_text.Bind(wx.EVT_TEXT, self.on_text) self.compose_text.Bind(wx.EVT_TEXT, self.on_text) self.on_text() def on_text(self, e = None): if e is not None: e.Skip() self.OKButton.Enable(bool(self.inbox_text.Value and self.compose_text.Value)) def layout(self): sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddMany([ (self.inbox_label, 0, EXPAND | BOTTOM | TOP, 5), (self.inbox_text, 0, EXPAND | LEFT, 7), (self.compose_label, 0, EXPAND | BOTTOM | TOP, 5), (self.compose_text, 0, EXPAND | LEFT, 7), self.MINSIZE, ]) self.set_component(sizer) self.Fit()
def __init__(self, parent): """ """ # Check import sys if sys.platform == "win32": return # Initialize the dialog box super().__init__( parent, -1, _("Tips"), DefaultPosition, Size(DEFAULT_WIDTH, DEFAULT_HEIGHT), RESIZE_BORDER | SYSTEM_MENU | CAPTION | FRAME_FLOAT_ON_PARENT | STAY_ON_TOP) # Normalize tips from org.pyut.general.LineSplitter import LineSplitter ls = LineSplitter() dc = ClientDC(self) for i in range(len(Tips)): tip = ls.split(Tips[i], dc, int(DEFAULT_WIDTH * 0.8)) Tips[i] = "" for line in tip: Tips[i] += line + "\n" # tip = "" # for line in Tips[i].split("\n"): # newLine = "" # for word in line.split(" "): # if len(newLine) + len(word) > 59: # tip += newLine + "\n" # newLine = "" # newLine += word + " " # tip += newLine # Tips[i] = tip # Set current tips self._prefs = PyutPreferences() self._currentTip = self._prefs[PyutPreferences.CURRENT_TIP] if self._currentTip is None: self._currentTip = 0 else: self._currentTip = int(self._currentTip) # Add icon # fileName = resource_filename(IMG_PKG, 'TipsLogo.bmp') # icon = Icon(fileName, BITMAP_TYPE_BMP) # self.SetIcon(icon) # self.Center(BOTH) # Center on the screen self.Center(dir=VERTICAL) self.AcceptsFocus() # Create controls # bmp: Bitmap = org.pyut.resources.img.ImgTipsFrameTipsLogo.embeddedImage.GetBitmap() bmp: Bitmap = TipsLogo.GetBitmap() self._picture = StaticBitmap(self, -1, bmp) tip = Tips[self._currentTip] self._label = StaticText(self, -1, tip, size=Size(DEFAULT_WIDTH * 0.8, DEFAULT_HEIGHT * 0.8), style=ST_NO_AUTORESIZE) nextTipButton = Button(self, ID_SET_NEXT_TIP, _("&Next tip")) previousTipButton = Button(self, ID_SET_PREVIOUS_TIP, _("&Previous tip")) self._chkShowTips = CheckBox(self, ID_CHK_SHOW_TIPS, _("&Show tips at startup")) showTips: bool = self._prefs.showTipsOnStartup() self._chkShowTips.SetValue(showTips) # Upper sizer upSizer = BoxSizer(HORIZONTAL) upSizer.Add(self._picture, 0, ALL | ALIGN_CENTER, 5) upSizer.Add(self._label, 1, ALL | ALIGN_CENTER, 5) # Lower sizer loSizer = BoxSizer(HORIZONTAL) loSizer.Add(previousTipButton, 0, ALL | ALIGN_CENTER, 5) loSizer.Add(nextTipButton, 0, ALL | ALIGN_CENTER, 5) loSizer.Add(Button(self, ID_OK, "&Ok"), 0, ALL | ALIGN_CENTER, 5) # Main sizer self.SetAutoLayout(True) mainSizer = BoxSizer(VERTICAL) mainSizer.Add(upSizer, 0, ALL | ALIGN_CENTER, 5) mainSizer.Add(self._chkShowTips, 0, ALL | ALIGN_CENTER, 5) mainSizer.Add(loSizer, 0, ALL | ALIGN_CENTER, 5) self.SetSizer(mainSizer) mainSizer.Fit(self) # Events self.Bind(EVT_BUTTON, self._onOk, id=ID_OK) self.Bind(EVT_CLOSE, self._onClose) self.Bind(EVT_BUTTON, self._onNextTip, id=ID_SET_NEXT_TIP) self.Bind(EVT_BUTTON, self._onPreviousTip, id=ID_SET_PREVIOUS_TIP)
def __init__(self, parent, flag): wiz.Wizard.__init__(self, parent, -1, "Configuration Wizard", myimages.PyDLWiz.GetBitmap()) self.SetPageSize((600,800)) page1 = titledPage.TitledPage(self, "Page 1") page2 = titledPage.TitledPage(self, "Page 2") page3 = titledPage.TitledPage(self, "Page 3") page4 = titledPage.TitledPage(self, "Page 4") page5 = titledPage.TitledPage(self, "Page 5") self.page1 = page1 self.page2 = page2 self.page3 = page3 self.page4 = page4 self.page5 = page5 self.flag = flag if flag == "new": page1.sizer.Add(wx.StaticText(page1, -1, """This wizard will lead you to set up a configuration for importing data to Salesforce.com.""")) self.FitToPage(page1) elif flag == "exists": btn_selectExists = wx.Button(page1, -1, "Browse...", size=(80,23), pos=(515,90)) page1.Bind(wx.EVT_BUTTON, self.OnSelectExists, btn_selectExists) st = StaticText(page1, -1, "Choose JSON file", size=(100, 20), pos=(10,60)) self.tc_exists = wx.TextCtrl(page1, -1, "", size=(500, -1), pos=(10,90)) btn_browse = wx.Button(page2, -1, "Browse...", size=(80,23), pos=(515,90)) page2.Bind(wx.EVT_BUTTON, self.OnBrowseButton, btn_browse) st = StaticText(page2, -1, "Choose CSV file", size=(100, 20), pos=(10,60)) self.t1_source = wx.TextCtrl(page2, -1, "", size=(500, -1), pos=(10,90)) # below is the information for page3 st3_cn = StaticText(page3, -1, "ConfigName:", size=(80,20), pos=(10,60)) self.tc3_cn = wx.TextCtrl(page3, -1, "", size=(200,-1), pos=(90,57)) st3_lt = StaticText(page3, -1, "LoadType:", size=(80,20), pos=(10,90)) #self.tc3_lt = wx.TextCtrl(page3, -1, "", size=(200,-1), pos=(90,87)) self.choice3_lt = wx.Choice(page3, -1, size=(200,-1), pos=(90,87), choices = iLoadTools.LoadTypeList) page3.Bind(wx.EVT_CHOICE, self.OnLoadTypeSelected, self.choice3_lt) st3_url = StaticText(page3, -1, "URL:", size=(80,20), pos=(10,120)) self.choice3_url = wx.Choice(page3, -1, size=(200,-1), pos=(90,117), choices = []) st3_un = StaticText(page3, -1, "UserName:"******"", size=(200,-1), pos=(90,147)) st3_pwd = StaticText(page3, -1, "Password:"******"", size=(200,-1), pos=(90,177), style=wx.TE_PASSWORD) st3_tt = StaticText(page3, -1, "TargetTable:", size=(80,20), pos=(10,210)) self.tc3_tt = wx.TextCtrl(page3, -1, "", size=(200,-1), pos=(90,207)) # above is the information for page3 # below is the information for page4 b_p4_newMap = wx.Button(page4, -1, "New Mapping", size=(100,23), pos=(10,60)) page4.Bind(wx.EVT_BUTTON, self.OnButtonNewMap, b_p4_newMap) tIDmap = wx.NewId() self.listmap = simpleListCtrl.SimpleListCtrl(page4, tIDmap, style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_EDIT_LABELS, size=(580,280), pos=(10,90) ) self.PopulateHeaderListMap() self.listmap.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClickMap) line4page4_1 = wx.StaticLine(page4, -1, size=(670,-1), pos=(10,390), style=wx.LI_HORIZONTAL) b_p4_newRule = wx.Button(page4, -1, "New Rule", size=(100,23), pos=(10,405)) page4.Bind(wx.EVT_BUTTON, self.OnButtonNewRule, b_p4_newRule) tIDrule = wx.NewId() self.listrule = simpleListCtrl.SimpleListCtrl(page4, tIDrule, style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_EDIT_LABELS, size=(580,280), pos=(10,435) ) self.PopulateHeaderListRule() self.listrule.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClickRule) line4page4_2 = wx.StaticLine(page4, -1, size=(670,-1), pos=(10,730), style=wx.LI_HORIZONTAL) btn_p4_execute = wx.Button(page4, -1, "Execute", size=(150,40), pos=(10,750)) btn_p4_execute.SetToolTipString("You can click this button to execute import.") page4.Bind(wx.EVT_BUTTON, self.OnClickExecute, btn_p4_execute) btn_p4_execute.SetBitmap(myimages.Mondrian.Bitmap, wx.LEFT) btn_p4_execute.SetBitmapMargins((2,2)) btn_p4_schedule = wx.Button(page4, -1, "Schedule", size=(150,40), pos=(180,750)) btn_p4_schedule.SetToolTipString("You can click this button to set schedule execute import.") page4.Bind(wx.EVT_BUTTON, self.OnClickSchedule, btn_p4_schedule) btn_p4_schedule.SetBitmap(myimages.Mondrian.Bitmap, wx.LEFT) btn_p4_schedule.SetBitmapMargins((2,2)) # above is the information for page4 # Use the convenience Chain function to connect the pages wiz.WizardPageSimple.Chain(page1, page2) wiz.WizardPageSimple.Chain(page2, page3) wiz.WizardPageSimple.Chain(page3, page4) #wiz.WizardPageSimple.Chain(page4, page5) self.GetPageAreaSizer().Add(page1) self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnWizPageChanged) self.Bind(wiz.EVT_WIZARD_PAGE_CHANGING, self.OnWizPageChanging) self.Bind(wiz.EVT_WIZARD_CANCEL, self.OnWizCancel) self.Bind(wiz.EVT_WIZARD_FINISHED, self.OnWizFinish) if self.RunWizard(page1): wx.MessageBox("Save configuration successfully") else: wx.MessageBox("You cancelled this wizard")
class MainDialog(Dialog): """ Main window. Hit a button to profile the system, then another to scan what was plugged in """ def __init__(self): """Constructor""" Dialog.__init__(self, None, title="Bad Cop", size=Size(500, 100)) ico = Icon('logo.ico', BITMAP_TYPE_ICO) self.SetIcon(ico) self.message = StaticText( self, label="Click Profile, then insert device and click Test") self.profile = Button(self, label="Profile") self.test = Button(self, label="Test") self.test.Disable() self.profile.Bind(EVT_BUTTON, self.profileusb) self.test.Bind(EVT_BUTTON, self.testusb) self.Bind(EVT_CLOSE, self.onclose) main_sizer = BoxSizer(VERTICAL) t_sizer = BoxSizer(HORIZONTAL) p_sizer = BoxSizer(HORIZONTAL) t_sizer.Add(self.message, 0, ALL | CENTER, 5) p_sizer.Add(self.profile, 0, ALL | CENTER, 5) p_sizer.Add(self.test, 0, ALL | CENTER, 5) main_sizer.Add(p_sizer, 0, ALL | CENTER, 5) main_sizer.Add(t_sizer, 0, ALL | EXPAND | CENTER, 5) self.SetSizer(main_sizer) def profileusb(self, other): del other dev = find(find_all=True) devices = [] for cfg in dev: devclass = str(cfg.bDeviceClass) product = str(cfg.iProduct) vid = hex(cfg.idVendor) pid = hex(cfg.idProduct) for line in Configuration(find(idVendor=cfg.idVendor)): line = str(line) linestrip = line.strip() linesplit = linestrip.split('\n') linesplit = [x.split(':') for x in linesplit] lines = [] for w in linesplit: lines.append([y.strip(' ') for y in w]) for e in lines: if 'bInterfaceClass' in e[0]: intclass = e[1] devices.append([devclass, product, vid, pid, intclass]) with open('devices.pkl', 'wb') as f: dump(devices, f) self.profile.SetLabel("Done!") self.profile.Disable() self.test.Enable() def testusb(self, other): del other with open('devices.pkl', 'rb') as f: benchmark = load(f) dev = find(find_all=True) devices = [] for cfg in dev: devclass = str(cfg.bDeviceClass) product = str(cfg.iProduct) vid = hex(cfg.idVendor) pid = hex(cfg.idProduct) for line in Configuration(find(idVendor=cfg.idVendor)): line = str(line) linestrip = line.strip() linesplit = linestrip.split('\n') linesplit = [x.split(':') for x in linesplit] lines = [] for w in linesplit: lines.append([y.strip(' ') for y in w]) for e in lines: if 'bInterfaceClass' in e[0]: intclass = e[1] devices.append([devclass, product, vid, pid, intclass]) first_tuple_list = [tuple(lst) for lst in benchmark] secnd_tuple_list = [tuple(lst) for lst in devices] first_set = set(first_tuple_list) secnd_set = set(secnd_tuple_list) output = "" height = 100 first = 0 for devclass, product, vid, pid, usbtype in first_set.symmetric_difference( secnd_set): if usbtype == "0xa CDC Data": devicedesc = "Virtual Data Port (Network)" elif usbtype == "0xe0 Wireless Controller": devicedesc = "Wireless Internet Or Bluetooth" elif usbtype == "0x8 Mass Storage": devicedesc = "Data Storage Device" elif usbtype == "0x9 Hub": devicedesc = "USB Hub" elif usbtype == "0x3 Human Interface Device": devicedesc = "Keyboard, Mouse, or Other Input Device" elif usbtype == "0x2 CDC Communication": devicedesc = "Vitual Communications Port (Network)" else: devicedesc = usbtype + " device " if first == 0: output += "This appears to be a: \n " + devicedesc + " \n" else: output += " " + devicedesc + " \n" height = height + 30 first = 1 self.SetSize((500, height)) self.message.SetLabel(output) def onclose(self, event): del event try: remove('devices.pkl') except: print('file missing') self.Destroy() exit("Application Exited")
def __init__(self, parent, windowId, pyutClass: PyutClass): """ Args: parent: dialog parent windowId: dialog identity pyutClass: Class modified by dialog """ super().__init__(parent=parent, windowId=windowId, dlgTitle=_("Class Edit"), pyutModel=pyutClass) self.logger: Logger = getLogger(__name__) lblStereotype: StaticText = StaticText(self, -1, _("Stereotype")) self._txtStereotype: TextCtrl = TextCtrl(self, ID_TXT_STEREO_TYPE, "", size=(125, -1)) self._szrNameStereotype.Add(lblStereotype, 0, ALL, 5) self._szrNameStereotype.Add(self._txtStereotype, 1, ALIGN_CENTER) # Label Fields lblField = StaticText(self, -1, _("Fields :")) # ListBox List self._lstFieldList = ListBox(self, ID_LST_FIELD_LIST, choices=[], style=LB_SINGLE) self.Bind(EVT_LISTBOX, self._evtFieldList, id=ID_LST_FIELD_LIST) self.Bind(EVT_LISTBOX_DCLICK, self._evtFieldListDClick, id=ID_LST_FIELD_LIST) # Button Add self._btnFieldAdd = Button(self, ID_BTN_FIELD_ADD, _("&Add")) self.Bind(EVT_BUTTON, self._onFieldAdd, id=ID_BTN_FIELD_ADD) # Button Edit self._btnFieldEdit = Button(self, ID_BTN_FIELD_EDIT, _("&Edit")) self.Bind(EVT_BUTTON, self._onFieldEdit, id=ID_BTN_FIELD_EDIT) # Button Remove self._btnFieldRemove = Button(self, ID_BTN_FIELD_REMOVE, _("&Remove")) self.Bind(EVT_BUTTON, self._onFieldRemove, id=ID_BTN_FIELD_REMOVE) # Button Up self._btnFieldUp = Button(self, ID_BTN_FIELD_UP, _("&Up")) self.Bind(EVT_BUTTON, self._onFieldUp, id=ID_BTN_FIELD_UP) # Button Down self._btnFieldDown = Button(self, ID_BTN_FIELD_DOWN, _("&Down")) self.Bind(EVT_BUTTON, self._onFieldDown, id=ID_BTN_FIELD_DOWN) # Sizer for Fields buttons szrFieldButtons = BoxSizer(HORIZONTAL) szrFieldButtons.Add(self._btnFieldAdd, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldEdit, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldRemove, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldUp, 0, ALL, 5) szrFieldButtons.Add(self._btnFieldDown, 0, ALL, 5) szrMethodButtons: BoxSizer = self._createMethodsUIArtifacts() # Show stereotype checkbox self._chkShowStereotype = CheckBox(self, -1, _("Show stereotype")) # Show fields checkbox self._chkShowFields = CheckBox(self, -1, _("Show fields")) # Show methods checkbox self._chkShowMethods = CheckBox(self, -1, _("Show methods")) # Sizer for display properties szrDisplayProperties = BoxSizer(VERTICAL) szrDisplayProperties.Add(self._chkShowStereotype, 0, ALL, 5) szrDisplayProperties.Add(self._chkShowFields, 0, ALL, 5) szrDisplayProperties.Add(self._chkShowMethods, 0, ALL, 5) self._szrMain.Add(lblField, 0, ALL, 5) self._szrMain.Add(self._lstFieldList, 1, ALL | EXPAND, 5) self._szrMain.Add(szrFieldButtons, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) self._szrMain.Add(self._lblMethod, 0, ALL, 5) self._szrMain.Add(self._lstMethodList, 1, ALL | EXPAND, 5) self._szrMain.Add(szrMethodButtons, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) self._szrMain.Add(szrDisplayProperties, 0, ALL | ALIGN_CENTER_HORIZONTAL, 5) self._szrMain.Add( self._szrButtons, 0, ALL | ALIGN_RIGHT, 5 ) # wxPython 4.1.0 Vertical alignment flags are ignored in vertical sizers # Fill the txt control with class data self._fillAllControls() # Fix buttons (enable or not) self._fixBtnFields() self._fixBtnMethod() # Set the focus and selection self._txtName.SetFocus() self._txtName.SetSelection(0, len(self._txtName.GetValue())) # Help Pycharm self._dlgMethod = cast(Dialog, None) self._szrMain.Fit(self) # subclasses need to do this self.Centre() self.ShowModal()
def __init__(self, parent, ID, pyutLink: PyutLink): """ """ super().__init__(parent, ID, _("Link Edit"), style=RESIZE_BORDER | CAPTION) self.logger: Logger = getLogger(__name__) # Associated PyutLink self._pyutLink: PyutLink = pyutLink self._relationship = self._pyutLink.getName() self._aRoleInB = "" self._bRoleInA = "" # self._cardinalityA = self._pyutLink.getSourceCardinality() # self._cardinalityB = self._pyutLink.getDestinationCardinality() self._cardinalityA = self._pyutLink.sourceCardinality self._cardinalityB = self._pyutLink.destinationCardinality self._returnAction = CANCEL # #describe how user exited dialog box # labels lblCardA = StaticText(self, -1, _("Cardinality"), style=ALIGN_LEFT) lblRela = StaticText(self, -1, _("Relationship"), style=ALIGN_CENTRE) lblCardB = StaticText(self, -1, _("Cardinality"), style=ALIGN_RIGHT) lblA = StaticText(self, -1, "A", style=ALIGN_LEFT) self._lblArrow = StaticText(self, -1, "", style=ALIGN_CENTRE) self.updateLblArrow() lblB = StaticText(self, -1, "B", style=ALIGN_RIGHT) lblAinB = StaticText(self, -1, _("A's role in B"), style=ALIGN_LEFT) lblBinA = StaticText(self, -1, _("B's role in A"), style=ALIGN_RIGHT) # text self._txtCardinalityA = TextCtrl(self, TXT_CARDINALITY_A, "", size=Size(50, 20)) self._txtRelationship = TextCtrl(self, TXT_RELATIONSHIP, "", size=Size(100, 20)) self._txtCardinalityB = TextCtrl(self, TXT_CARDINALITY_B, "", size=Size(50, 20)) self._txtARoleB = TextCtrl(self, A_ROLE_IN_B, "") self._txtBRoleA = TextCtrl(self, B_ROLE_IN_A, "") self.setValues(self._relationship, self._aRoleInB, self._bRoleInA, self._cardinalityA, self._cardinalityB) self._txtARoleB.Enable(False) self._txtBRoleA.Enable(False) # text events self.Bind(EVT_TEXT, self._onTxtCardinalityAChange, id=TXT_CARDINALITY_A) self.Bind(EVT_TEXT, self._onTxtCardinalityBChange, id=TXT_CARDINALITY_B) self.Bind(EVT_TEXT, self._onTxtRelationshipChange, id=TXT_RELATIONSHIP) self.Bind(EVT_TEXT, self._onTxtARoleBChange, id=A_ROLE_IN_B) self.Bind(EVT_TEXT, self._onTxtBRoleAChange, id=B_ROLE_IN_A) # Ok/Cancel btnOk = Button(self, OK, _("&Ok")) btnCancel = Button(self, CANCEL, _("&Cancel")) btnRemove = Button(self, BTN_REMOVE, _("&Remove")) btnOk.SetDefault() # button events self.Bind(EVT_BUTTON, self._onCmdOk, id=OK) self.Bind(EVT_BUTTON, self._onCmdCancel, id=CANCEL) self.Bind(EVT_BUTTON, self._onRemove, id=BTN_REMOVE) szr1 = FlexGridSizer(cols=3, hgap=30, vgap=5) szr1.AddMany([(lblCardA, 0, ALIGN_LEFT), (lblRela, 0, ALIGN_CENTER_HORIZONTAL), (lblCardB, 0, ALIGN_RIGHT), (self._txtCardinalityA, 0, ALIGN_LEFT), (self._txtRelationship, 0, ALIGN_CENTER_HORIZONTAL), (self._txtCardinalityB, 0, ALIGN_RIGHT)]) szr1.AddGrowableCol(0) szr1.AddGrowableCol(1) szr1.AddGrowableCol(2) szr2 = BoxSizer(HORIZONTAL) szr2.Add(lblA, 1, GROW | RIGHT, 10) szr2.Add(self._lblArrow, 1, GROW, 10) szr2.Add(lblB, 1, GROW) # szr3 : # lblAinB, lblBinA # self._txtARoleB, self._txtBRoleA szr3 = FlexGridSizer(cols=2, hgap=30, vgap=5) szr3.AddMany([(lblAinB, 0), (lblBinA, 0, ALIGN_RIGHT), (self._txtARoleB, 0), (self._txtBRoleA, 0, ALIGN_RIGHT | BOTTOM, 20)]) szr3.AddGrowableCol(0) szr3.AddGrowableCol(1) # szr4 : # btnRemove, btnOk, btnCancel szr4 = BoxSizer(HORIZONTAL) szr4.Add(btnRemove, 0, RIGHT, 10) szr4.Add(btnOk, 0, RIGHT, 10) szr4.Add(btnCancel, 0) # szr5 : # szr1 # szr2 # szr3 # szr4 szr5 = BoxSizer(VERTICAL) szr5.Add(szr1, 0, GROW | ALL, 10) szr5.Add(szr2, 0, GROW | ALL, 10) szr5.Add(szr3, 0, GROW | ALL, 10) szr5.Add(szr4, 0, ALIGN_RIGHT | ALL, 10) self.SetSizer(szr5) self.SetAutoLayout(True) szr5.Fit(self)
def Text(*a, **k): txt = StaticText(self, -1, *a, **k) txt.Wrap(520) return txt
def __init__(self, master, saveDirVal = None, backupDirVal = None): self.master = master saveDirSizer = BoxSizer(HORIZONTAL) self.saveDir = TextCtrl(master, size = (600, -1) ) if saveDirVal: self.saveDir.SetValue(saveDirVal) saveDirSizer.Add(StaticText(master, label = "Save directory"), 0, EXPAND ) saveDirSizer.Add(self.saveDir, 1, EXPAND) selectSaveDir = Button(master, -1, "Select") saveDirSizer.Add(selectSaveDir, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_select_save_dir, selectSaveDir) openSave = Button(master, label = "Open") saveDirSizer.Add(openSave, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_open_save_dir, openSave) hide = Button(master, label = "Hide") saveDirSizer.Add(hide, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_hide, hide) backupDirSizer = BoxSizer(HORIZONTAL) self.backupDir = TextCtrl(master) if backupDirVal: self.backupDir.SetValue(backupDirVal) backupDirSizer.Add(StaticText(master, label = "Backup directory"), 0, EXPAND ) backupDirSizer.Add(self.backupDir, 1, EXPAND) switch = Button(master, label = "Switch") master.Bind(EVT_BUTTON, self._on_switch, switch) backupDirSizer.Add(switch, 0, EXPAND) override = Button(master, label = "Overwrite") master.Bind(EVT_BUTTON, self._on_overwrite, override) backupDirSizer.Add(override, 0, EXPAND) selectBackupDir = Button(master, -1, "Select") master.Bind(EVT_BUTTON, self._on_select_backup_dir, selectBackupDir) backupDirSizer.Add(selectBackupDir, 0, EXPAND) openBackup = Button(master, label = "Open") backupDirSizer.Add(openBackup, 0, EXPAND) master.Bind(EVT_BUTTON, self._on_open_backup_dir, openBackup) filterOutSizer = BoxSizer(HORIZONTAL) filterOutSizer.Add(StaticText(master, label = "Filter Out"), 0, EXPAND) self.filterOut = TextCtrl(master) filterOutSizer.Add(self.filterOut, 1, EXPAND) self.cbMonitor = CheckBox(master, label = "Monitor") master.Bind(EVT_CHECKBOX, self._on_monitor, self.cbMonitor) self.sizer = sizer = BoxSizer(VERTICAL) sizer.Add(saveDirSizer, 0, EXPAND) sizer.Add(backupDirSizer, 0, EXPAND) sizer.Add(filterOutSizer, 0, EXPAND) sizer.Add(self.cbMonitor, 0, EXPAND) self.settingsWidgets = [ selectSaveDir, self.saveDir, self.backupDir, switch, selectBackupDir, self.filterOut ]
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())
def __create_widgets(self): panel = Panel(self) sizer = GridBagSizer(5, 5) row = 0 col = 0 label = StaticText(panel, label=u'Root folder:') sizer.Add(label, pos=(row, col)) col += 1 col_width = 4 self.__txt_root_path = TextCtrl(panel) sizer.Add(self.__txt_root_path, pos=(row, col), span=(1, col_width), flag=FLAG_ALL_AND_EXPAND) col += col_width self.__btn_set_root = Button(panel, label=u'Set root folder') self.__btn_set_root.Bind(EVT_BUTTON, self.__set_root_folder) sizer.Add(self.__btn_set_root, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 label = StaticText(panel, label=u'Url:') sizer.Add(label, pos=(row, col)) col += 1 self.__txt_url = TextCtrl( panel, value=u'https://www.google.com/') # TODO: remove url sizer.Add(self.__txt_url, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 label = StaticText(panel, label=u'Browser:') sizer.Add(label, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.__cb_browser = Choice(panel, choices=Browser.get_supported_browsers()) self.__cb_browser.Select(0) sizer.Add(self.__cb_browser, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.bth_open_url = Button(panel, label=u'Open url') self.bth_open_url.Bind(EVT_BUTTON, self.__open_url) sizer.Add(self.bth_open_url, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) col += 1 self.bth_close_url = Button(panel, label=u'Close browser') self.bth_close_url.Bind(EVT_BUTTON, self.__close_browser) sizer.Add(self.bth_close_url, pos=(row, col), flag=FLAG_ALL_AND_EXPAND) row += 1 col = 0 tabs = Tabs(panel, [(GeneratorTab, "Generator"), (EditorTab, "Editor"), (TestRunnerTab, "Test runner"), (SelectorFinderTab, "Selector finder")]) sizer.Add(tabs, pos=(row, col), span=(1, 6), flag=FLAG_ALL_AND_EXPAND) sizer.AddGrowableCol(1, 1) sizer.AddGrowableRow(2, 1) panel.SetSizer(sizer) self.Layout()
def __init__(self, theParent, theWindowId, fieldToEdit: PyutField, theMediator=None): super().__init__(theParent, theWindowId, _("Field Edit"), theStyle=RESIZE_BORDER | CAPTION | STAY_ON_TOP, theMediator=theMediator) self._fieldToEdit: PyutField = fieldToEdit # ---------------- # Design of dialog # ---------------- self.SetAutoLayout(True) # RadioBox Visibility self._rdbFieldVisibility: RadioBox = RadioBox(self, ID_ANY, "", Point(35, 30), DefaultSize, ["+", "-", "#"], style=RA_SPECIFY_ROWS) # Txt Ctrl Name lblFieldName = StaticText (self, ID_ANY, _("Name")) self._txtFieldName = TextCtrl(self, ID_TXT_FIELD_NAME, "", size=(125, -1)) self.Bind(EVT_TEXT, self._evtFieldText, id=ID_TXT_FIELD_NAME) # Txt Ctrl Type lblFieldType: StaticText = StaticText (self, ID_ANY, _("Type")) self._txtFieldType: TextCtrl = TextCtrl(self, ID_ANY, "", size=(125, -1)) # Txt Ctrl Default lblFieldDefault: StaticText = StaticText (self, ID_ANY, _("Default Value")) self._txtFieldDefault: TextCtrl = TextCtrl(self, ID_ANY, "", size=(125, -1)) # --------------------- # Buttons OK and Cancel # --------------------- self._btnFieldOk: Button = Button(self, ID_BTN_FIELD_OK, _("&Ok")) self.Bind(EVT_BUTTON, self._onFieldOk, id=ID_BTN_FIELD_OK) self._btnFieldOk.SetDefault() self._btnFieldCancel = Button(self, ID_BTN_FIELD_CANCEL, _("&Cancel")) self.Bind(EVT_BUTTON, self._onFieldCancel, id=ID_BTN_FIELD_CANCEL) szrButtons = BoxSizer (HORIZONTAL) szrButtons.Add(self._btnFieldOk, 0, ALL, 5) szrButtons.Add(self._btnFieldCancel, 0, ALL, 5) szrField1: FlexGridSizer = FlexGridSizer(cols=3, hgap=6, vgap=6) szrField1.AddMany([lblFieldName, lblFieldType, lblFieldDefault, self._txtFieldName, self._txtFieldType, self._txtFieldDefault]) szrField2 = BoxSizer(HORIZONTAL) szrField2.Add(self._rdbFieldVisibility, 0, ALL, 5) szrField2.Add(szrField1, 0, ALIGN_CENTER_VERTICAL | ALL, 5) szrField3 = BoxSizer(VERTICAL) szrField3.Add(szrField2, 0, ALL, 5) szrField3.Add(szrButtons, 0, ALL | ALIGN_RIGHT, 5) self.SetSizer(szrField3) self.SetAutoLayout(True) szrField3.Fit(self) # Fill the text controls with PyutField data self._txtFieldName.SetValue(self._fieldToEdit.getName()) self._txtFieldType.SetValue(str(self._fieldToEdit.getType())) self._txtFieldDefault.SetValue(self._convertNone(self._fieldToEdit.getDefaultValue())) self._rdbFieldVisibility.SetStringSelection(str(self._fieldToEdit.visibility)) # Fix state of buttons (enabled or not) self._fixBtnDlgFields() # Set the focus self._txtFieldName.SetFocus() self.Centre()
def __init__(self, parent): Panel.__init__(self, parent) t = StaticText(self, -1, "This is a PageTddhree object", (60, 200))
def _createVersionsContainer(self) -> BoxSizer: """ The noinspection is set for the StaticText.SetFont() methods Returns: The container """ version: Version = self._version pyVersionText: str = f'Python Version: {version.pythonVersion}' wxVersionText: str = f'WxPython Version: {version.wxPythonVersion}' pyGithubText: str = f'PyGithub Version: {version.pyGithubVersion}' todoistVersionText: str = f'Todoist Version: {version.todoistVersion}' appNameVersionText: str = f'{version.applicationName} - {version.applicationVersion}' appNameVersion: StaticText = StaticText(self, ID_ANY, appNameVersionText, style=CAPTION) longVersion: StaticText = StaticText(self, ID_ANY, version.applicationLongVersion, style=CAPTION) appSeparator: StaticLine = StaticLine(self, ID_ANY, style=LI_HORIZONTAL) pyVersion: StaticText = StaticText(self, ID_ANY, pyVersionText, style=CAPTION) wxVersion: StaticText = StaticText(self, ID_ANY, wxVersionText, style=CAPTION) pyGithubVersion: StaticText = StaticText(self, ID_ANY, pyGithubText, style=CAPTION) todoistVersion: StaticText = StaticText(self, ID_ANY, todoistVersionText, style=CAPTION) versionSizer: BoxSizer = BoxSizer(VERTICAL) appNameVersion.SetFont(self._versionFont) longVersion.SetFont(self._versionFont) pyVersion.SetFont(self._versionFont) wxVersion.SetFont(self._versionFont) pyGithubVersion.SetFont(self._versionFont) todoistVersion.SetFont(self._versionFont) versionSizer.Add(appNameVersion, 0, ALL | ALIGN_LEFT, 1) versionSizer.Add(longVersion, 0, ALL | ALIGN_LEFT, 1) versionSizer.Add(appSeparator, 0, ALL | ALIGN_LEFT, 1) versionSizer.Add(pyVersion, 0, ALL | ALIGN_LEFT, 1) versionSizer.Add(wxVersion, 0, ALL | ALIGN_LEFT, 1) versionSizer.Add(pyGithubVersion, 0, ALL | ALIGN_LEFT, 1) versionSizer.Add(todoistVersion, 0, ALL | ALIGN_LEFT, 1) return versionSizer
def SText(parent, text): if not isinstance(parent, WindowClass): raise TypeError('first arg to SText must be a wx.Window') return StaticText(parent, -1, text)