# This was written way it is because of the lack of masked edit controls
# in wxWindows/wxPython.
#
-# wxMaskedEdit controls are based on a suggestion made on [wxPython-Users] by
+# MaskedEdit controls are based on a suggestion made on [wxPython-Users] by
# Jason Hihn, and borrows liberally from Will Sadkin's original masked edit
-# control for time entry, wxTimeCtrl (which is now rewritten using this
+# control for time entry, TimeCtrl (which is now rewritten using this
# control!).
#
-# wxMaskedEdit controls do not normally use validators, because they do
+# MaskedEdit controls do not normally use validators, because they do
# careful manipulation of the cursor in the text window on each keystroke,
# and validation is cursor-position specific, so the control intercepts the
# key codes before the validator would fire. However, validators can be
# provided to do data transfer to the controls.
-##
+#
+#----------------------------------------------------------------------------
+#
+# 12/09/2003 - Jeff Grimmett (grimmtooth@softhome.net)
+#
+# o Updated for wx namespace. No guarantees. This is one huge file.
+#
+# 12/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
+#
+# o Missed wx.DateTime stuff earlier.
+#
+# 12/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
+#
+# o wxMaskedEditMixin -> MaskedEditMixin
+# o wxMaskedTextCtrl -> MaskedTextCtrl
+# o wxMaskedComboBoxSelectEvent -> MaskedComboBoxSelectEvent
+# o wxMaskedComboBox -> MaskedComboBox
+# o wxIpAddrCtrl -> IpAddrCtrl
+# o wxTimeCtrl -> TimeCtrl
+#
"""\
<b>Masked Edit Overview:
=====================</b>
-<b>wxMaskedTextCtrl</b>
+<b>MaskedTextCtrl</b>
is a sublassed text control that can carefully control the user's input
based on a mask string you provide.
General usage example:
- control = wxMaskedTextCtrl( win, -1, '', mask = '(###) ###-####')
+ control = MaskedTextCtrl( win, -1, '', mask = '(###) ###-####')
The example above will create a text control that allows only numbers to be
entered and then only in the positions indicated in the mask by the # sign.
-<b>wxMaskedComboBox</b>
+<b>MaskedComboBox</b>
is a similar subclass of wxComboBox that allows the same sort of masking,
but also can do auto-complete of values, and can require the value typed
to be in the list of choices to be colored appropriately.
<b>wxMaskedCtrl</b>
is actually a factory function for several types of masked edit controls:
- <b>wxMaskedTextCtrl</b> - standard masked edit text box
- <b>wxMaskedComboBox</b> - adds combobox capabilities
- <b>wxIpAddrCtrl</b> - adds special semantics for IP address entry
- <b>wxTimeCtrl</b> - special subclass handling lots of types as values
+ <b>MaskedTextCtrl</b> - standard masked edit text box
+ <b>MaskedComboBox</b> - adds combobox capabilities
+ <b>IpAddrCtrl</b> - adds special semantics for IP address entry
+ <b>TimeCtrl</b> - special subclass handling lots of types as values
<b>wxMaskedNumCtrl</b> - special subclass handling numeric values
It works by looking for a <b><i>controlType</i></b> parameter in the keyword
arguments of the control, to determine what kind of instance to return.
If not specified as a keyword argument, the default control type returned
- will be wxMaskedTextCtrl.
+ will be MaskedTextCtrl.
Each of the above classes has its own set of arguments, but wxMaskedCtrl
provides a single "unified" interface for masked controls. Those for
- wxMaskedTextCtrl, wxMaskedComboBox and wxIpAddrCtrl are all documented
+ MaskedTextCtrl, MaskedComboBox and IpAddrCtrl are all documented
below; the others have their own demo pages and interface descriptions.
(See end of following discussion for how to configure the wxMaskedCtrl()
to select the above control types.)
choices= A list of strings that are allowed choices for the control.
choiceRequired= value must be member of choices list
compareNoCase= Perform case-insensitive matching when validating against list
- <i>Note: for wxMaskedComboBox, this defaults to True.</i>
+ <i>Note: for MaskedComboBox, this defaults to True.</i>
emptyInvalid= Boolean indicating whether an empty value should be considered invalid
validFunc= A function to call of the form: bool = func(candidate_value)
after construction; it takes a list of key/value pairs as arguments,
where the keys can be any of the mask-specific parameters in the constructor.
Eg:
- ctl = wxMaskedTextCtrl( self, -1 )
+ ctl = MaskedTextCtrl( self, -1 )
ctl.SetCtrlParameters( mask='###-####',
defaultValue='555-1212',
formatcodes='F')
The following methods must be used and/or defined when deriving a control
from wxMaskedEditMixin. NOTE: if deriving from a *masked edit* control
- (eg. class wxIpAddrCtrl(wxMaskedTextCtrl) ), then this is NOT necessary,
+ (eg. class IpAddrCtrl(MaskedTextCtrl) ), then this is NOT necessary,
as it's already been done for you in the base class.
._SetInitialValue()
Similarly to _GetSelection, each class derived from
wxMaskedEditMixin must define the function for setting
the start and end of the current text selection.
- (eg. .SetSelection() for wxMaskedTextCtrl, and .SetMark() for
- wxMaskedComboBox.
+ (eg. .SetSelection() for MaskedTextCtrl, and .SetMark() for
+ MaskedComboBox.
._GetInsertionPoint()
._SetInsertionPoint()
._IsEditable() REQUIRED
Each class derived from wxMaskedEditMixin must define
the function used to determine if the base control is
- editable or not. (For wxMaskedComboBox, this has to
+ editable or not. (For MaskedComboBox, this has to
be done with code, rather than specifying the proper
function in the base control, as there isn't one...)
._CalcSize() REQUIRED
These 5 handlers must be "wired up" for the wxMaskedEdit
control to provide default behavior. (The setupEventHandling
- is an argument to wxMaskedTextCtrl and wxMaskedComboBox, so
+ is an argument to MaskedTextCtrl and MaskedComboBox, so
that controls derived from *them* may replace one of these
handlers if they so choose.)
._AddNavKeycode(keycode, handler=None)
._AddNavKey(char, handler=None)
Allows controls to specify other keys (and optional handlers)
- to be treated as navigational characters. (eg. '.' in wxIpAddrCtrl)
+ to be treated as navigational characters. (eg. '.' in IpAddrCtrl)
._GetNavKeycodes() Returns the current list of navigational keycodes.
By default, it adjusts the year in date fields if mask is a date,
It can be overridden by a derived class to
adjust the value of the control at that time.
- (eg. wxIpAddrCtrl reformats the address in this way.)
+ (eg. IpAddrCtrl reformats the address in this way.)
._Change() Called by internal EVT_TEXT handler. Return False to force
skip of the normal class change event.
_OnCtrl_Z(event) 'undo' - resets value to previous value (if any)
_OnChangeField(event) primarily used for tab events, but can be
- used for other keys (eg. '.' in wxIpAddrCtrl)
+ used for other keys (eg. '.' in IpAddrCtrl)
_OnErase(event) used for backspace and delete
_OnHome(event)
"""
-from wxPython.wx import *
-import string, re, copy, difflib, types
+import copy
+import difflib
+import re
+import string
+import types
+
+import wx
+
+# jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would
+# be a good place to implement the 2.3 logger class
+from wx.tools.dbg import Logger
-from wxPython.tools.dbg import Logger
dbg = Logger()
dbg(enable=0)
WXK_CTRL_X = (ord('X')+1) - ord('A')
WXK_CTRL_Z = (ord('Z')+1) - ord('A')
-nav = (WXK_BACK, WXK_LEFT, WXK_RIGHT, WXK_UP, WXK_DOWN, WXK_TAB, WXK_HOME, WXK_END, WXK_RETURN, WXK_PRIOR, WXK_NEXT)
-control = (WXK_BACK, WXK_DELETE, WXK_CTRL_A, WXK_CTRL_C, WXK_CTRL_S, WXK_CTRL_V, WXK_CTRL_X, WXK_CTRL_Z)
+nav = (
+ wx.WXK_BACK, wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_UP, wx.WXK_DOWN, wx.WXK_TAB,
+ wx.WXK_HOME, wx.WXK_END, wx.WXK_RETURN, wx.WXK_PRIOR, wx.WXK_NEXT
+ )
+
+control = (
+ wx.WXK_BACK, wx.WXK_DELETE, WXK_CTRL_A, WXK_CTRL_C, WXK_CTRL_S, WXK_CTRL_V,
+ WXK_CTRL_X, WXK_CTRL_Z
+ )
## ---------- ---------- ---------- ---------- ---------- ---------- ----------
'excludeChars': am_pm_exclude,
'formatcodes': 'TF!',
'validRegex': '^' + hours + ':' + minutes + ':' + seconds + ' (A|P)M',
- 'description': "HH:MM:SS (A|P)M\n(see wxTimeCtrl)"
+ 'description': "HH:MM:SS (A|P)M\n(see TimeCtrl)"
},
"TIMEHHMM": {
'mask': "##:## AM",
'excludeChars': am_pm_exclude,
'formatcodes': 'TF!',
'validRegex': '^' + hours + ':' + minutes + ' (A|P)M',
- 'description': "HH:MM (A|P)M\n(see wxTimeCtrl)"
+ 'description': "HH:MM (A|P)M\n(see TimeCtrl)"
},
"MILTIMEHHMMSS": {
'mask': "##:##:##",
'formatcodes': 'TF',
'validRegex': '^' + milhours + ':' + minutes + ':' + seconds,
- 'description': "Military HH:MM:SS\n(see wxTimeCtrl)"
+ 'description': "Military HH:MM:SS\n(see TimeCtrl)"
},
"MILTIMEHHMM": {
'mask': "##:##",
'formatcodes': 'TF',
'validRegex': '^' + milhours + ':' + minutes,
- 'description': "Military HH:MM\n(see wxTimeCtrl)"
+ 'description': "Military HH:MM\n(see TimeCtrl)"
},
"USSOCIALSEC": {
'mask': "###-##-####",
'mask': "###.###.###.###",
'formatcodes': 'F_Sr',
'validRegex': "( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))(\.( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))){3}",
- 'description': "IP Address\n(see wxIpAddrCtrl)"
+ 'description': "IP Address\n(see IpAddrCtrl)"
}
}
## ---------- ---------- ---------- ---------- ---------- ---------- ----------
-class wxMaskedEditMixin:
+class MaskedEditMixin:
"""
This class allows us to abstract the masked edit functionality that could
be associated with any text entry control. (eg. wxTextCtrl, wxComboBox, etc.)
# Validate legitimate set of parameters:
for key in kwargs.keys():
- if key.replace('Color', 'Colour') not in wxMaskedEditMixin.valid_ctrl_params.keys() + Field.valid_params.keys():
+ if key.replace('Color', 'Colour') not in MaskedEditMixin.valid_ctrl_params.keys() + Field.valid_params.keys():
raise TypeError('%s: invalid parameter "%s"' % (name, key))
## Set up dictionary that can be used by subclasses to override or add to default
## Initially populated with navigation and function control keys:
self._keyhandlers = {
# default navigation keys and handlers:
- WXK_BACK: self._OnErase,
- WXK_LEFT: self._OnArrow,
- WXK_RIGHT: self._OnArrow,
- WXK_UP: self._OnAutoCompleteField,
- WXK_DOWN: self._OnAutoCompleteField,
- WXK_TAB: self._OnChangeField,
- WXK_HOME: self._OnHome,
- WXK_END: self._OnEnd,
- WXK_RETURN: self._OnReturn,
- WXK_PRIOR: self._OnAutoCompleteField,
- WXK_NEXT: self._OnAutoCompleteField,
+ wx.WXK_BACK: self._OnErase,
+ wx.WXK_LEFT: self._OnArrow,
+ wx.WXK_RIGHT: self._OnArrow,
+ wx.WXK_UP: self._OnAutoCompleteField,
+ wx.WXK_DOWN: self._OnAutoCompleteField,
+ wx.WXK_TAB: self._OnChangeField,
+ wx.WXK_HOME: self._OnHome,
+ wx.WXK_END: self._OnEnd,
+ wx.WXK_RETURN: self._OnReturn,
+ wx.WXK_PRIOR: self._OnAutoCompleteField,
+ wx.WXK_NEXT: self._OnAutoCompleteField,
# default function control keys and handlers:
- WXK_DELETE: self._OnErase,
+ wx.WXK_DELETE: self._OnErase,
WXK_CTRL_A: self._OnCtrl_A,
WXK_CTRL_C: self._OnCtrl_C,
WXK_CTRL_S: self._OnCtrl_S,
'&': string.punctuation
}
- ## self._ignoreChange is used by wxMaskedComboBox, because
+ ## self._ignoreChange is used by MaskedComboBox, because
## of the hack necessary to determine the selection; it causes
## EVT_TEXT messages from the combobox to be ignored if set.
self._ignoreChange = False
# Set defaults for each parameter for this instance, and fully
# populate initial parameter list for configuration:
- for key, value in wxMaskedEditMixin.valid_ctrl_params.items():
+ for key, value in MaskedEditMixin.valid_ctrl_params.items():
setattr(self, '_' + key, copy.copy(value))
if not kwargs.has_key(key):
## dbg('%s: "%s"' % (key, repr(value)))
parameters after construction.
"""
dbg(suspend=1)
- dbg('wxMaskedEditMixin::SetCtrlParameters', indent=1)
+ dbg('MaskedEditMixin::SetCtrlParameters', indent=1)
## dbg('kwargs:', indent=1)
## for key, value in kwargs.items():
## dbg(key, '=', value)
ctrl_kwargs = {}
for key, value in kwargs.items():
key = key.replace('Color', 'Colour') # for b-c, and standard wxPython spelling
- if key not in wxMaskedEditMixin.valid_ctrl_params.keys() + Field.valid_params.keys():
+ if key not in MaskedEditMixin.valid_ctrl_params.keys() + Field.valid_params.keys():
dbg(indent=0, suspend=0)
raise TypeError('Invalid keyword argument "%s" for control "%s"' % (key, self.name))
elif key in Field.valid_params.keys():
## dbg(indent=0)
# determine if changing parameters that should affect the entire control:
- for key in wxMaskedEditMixin.valid_ctrl_params.keys():
+ for key in MaskedEditMixin.valid_ctrl_params.keys():
if key in ( 'mask', 'fields' ): continue # (processed separately)
if ctrl_kwargs.has_key(key):
setattr(self, '_' + key, ctrl_kwargs[key])
'foregroundColour', 'signedForegroundColour'):
if ctrl_kwargs.has_key(key):
if type(ctrl_kwargs[key]) in (types.StringType, types.UnicodeType):
- c = wxNamedColor(ctrl_kwargs[key])
+ c = wx.NamedColour(ctrl_kwargs[key])
if c.Get() == (-1, -1, -1):
raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs[key]), key))
else:
# attach a python dynamic attribute to wxColour for debug printouts
c._name = ctrl_kwargs[key]
- elif type(ctrl_kwargs[key]) != type(wxBLACK):
+ elif type(ctrl_kwargs[key]) != type(wx.BLACK):
raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs[key]), key))
"""
Routine for retrieving the value of any given parameter
"""
- if wxMaskedEditMixin.valid_ctrl_params.has_key(paramname.replace('Color','Colour')):
+ if MaskedEditMixin.valid_ctrl_params.has_key(paramname.replace('Color','Colour')):
return getattr(self, '_' + paramname.replace('Color', 'Colour'))
elif Field.valid_params.has_key(paramname):
return self._ctrl_constraints._GetParameter(paramname)
# if no fillchar change, but old value == old template, replace it:
if newvalue == old_template:
newvalue = self._template
- reset_value = true
+ reset_value = True
else:
self._defaultValue = None
"""
dbg(suspend=1)
- dbg('wxMaskedEditMixin::_configure("%s")' % mask, indent=1)
+ dbg('MaskedEditMixin::_configure("%s")' % mask, indent=1)
# Preprocess specified mask to expand {n} syntax, handle escaped
# mask characters, etc and build the resulting positionally keyed
# make down act like tab, up act like shift-tab:
## dbg('Registering numeric navigation and control handlers (if not already set)')
- if not self._keyhandlers.has_key(WXK_DOWN):
- self._SetKeycodeHandler(WXK_DOWN, self._OnChangeField)
- if not self._keyhandlers.has_key(WXK_UP):
- self._SetKeycodeHandler(WXK_UP, self._OnUpNumeric) # (adds "shift" to up arrow, and calls _OnChangeField)
+ if not self._keyhandlers.has_key(wx.WXK_DOWN):
+ self._SetKeycodeHandler(wx.WXK_DOWN, self._OnChangeField)
+ if not self._keyhandlers.has_key(wx.WXK_UP):
+ self._SetKeycodeHandler(wx.WXK_UP, self._OnUpNumeric) # (adds "shift" to up arrow, and calls _OnChangeField)
# On ., truncate contents right of cursor to decimal point (if any)
# leaves cusor after decimal point if floating point, otherwise at 0.
It will also set/reset the font if necessary and apply
formatting to the control at this time.
"""
- dbg('wxMaskedEditMixin::_SetInitialValue("%s")' % value, indent=1)
+ dbg('MaskedEditMixin::_SetInitialValue("%s")' % value, indent=1)
if not value:
self._prevValue = self._curValue = self._template
# don't apply external validation rules in this case, as template may
def _calcSize(self, size=None):
""" Calculate automatic size if allowed; must be called after the base control is instantiated"""
-## dbg('wxMaskedEditMixin::_calcSize', indent=1)
- cont = (size is None or size == wxDefaultSize)
+## dbg('MaskedEditMixin::_calcSize', indent=1)
+ cont = (size is None or size == wx.DefaultSize)
if cont and self._autofit:
sizing_text = 'M' * self._masklength
- if wxPlatform != "__WXMSW__": # give it a little extra space
+ if wx.Platform != "__WXMSW__": # give it a little extra space
sizing_text += 'M'
- if wxPlatform == "__WXMAC__": # give it even a little more...
+ if wx.Platform == "__WXMAC__": # give it even a little more...
sizing_text += 'M'
## dbg('len(sizing_text):', len(sizing_text), 'sizing_text: "%s"' % sizing_text)
w, h = self.GetTextExtent(sizing_text)
def _setFont(self):
""" Set the control's font typeface -- pass the font name as str."""
-## dbg('wxMaskedEditMixin::_setFont', indent=1)
+## dbg('MaskedEditMixin::_setFont', indent=1)
if not self._useFixedWidthFont:
- self._font = wxSystemSettings_GetFont(wxSYS_DEFAULT_GUI_FONT)
+ self._font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
else:
font = self.GetFont() # get size, weight, etc from current font
# Set to teletype font (guaranteed to be mappable to all wxWindows
# platforms:
- self._font = wxFont( font.GetPointSize(), wxTELETYPE, font.GetStyle(),
+ self._font = wx.Font( font.GetPointSize(), wx.TELETYPE, font.GetStyle(),
font.GetWeight(), font.GetUnderlined())
## dbg('font string: "%s"' % font.GetNativeFontInfo().ToString())
EVT_TEXT events for the same change.)
"""
newvalue = self._GetValue()
- dbg('wxMaskedEditMixin::_OnTextChange: value: "%s"' % newvalue, indent=1)
+ dbg('MaskedEditMixin::_OnTextChange: value: "%s"' % newvalue, indent=1)
bValid = False
if self._ignoreChange: # ie. if an "intermediate text change event"
dbg(indent=0)
if key in self._nav and event.ControlDown():
# then this is the only place we will likely see these events;
# process them now:
- dbg('wxMaskedEditMixin::OnKeyDown: calling _OnChar')
+ dbg('MaskedEditMixin::OnKeyDown: calling _OnChar')
self._OnChar(event)
return
# else allow regular EVT_CHAR key processing
This is the engine of wxMaskedEdit controls. It examines each keystroke,
decides if it's allowed, where it should go or what action to take.
"""
- dbg('wxMaskedEditMixin::_OnChar', indent=1)
+ dbg('MaskedEditMixin::_OnChar', indent=1)
# Get keypress value, adjusted by control options (e.g. convert to upper etc)
key = event.GetKeyCode()
dbg(indent=0)
return
# else skip default processing, but do final formatting
- if key < WXK_SPACE or key > 255:
+ if key < wx.WXK_SPACE or key > 255:
dbg('key < WXK_SPACE or key > 255')
event.Skip() # non alphanumeric
keep_processing = False
if self.IsValid(newstr):
dbg("it is!")
keep_processing = True
- wxCallAfter(self._SetInsertionPoint, self._decimalpos)
+ wx.CallAfter(self._SetInsertionPoint, self._decimalpos)
if not keep_processing:
dbg("key disallowed by validation")
- if not wxValidator_IsSilent() and orig_pos == pos:
- wxBell()
+ if not wx.Validator_IsSilent() and orig_pos == pos:
+ wx.Bell()
if keep_processing:
unadjusted = newstr
if newstr != orig_value:
self.modified = True
- wxCallAfter(self._SetValue, newstr)
+ wx.CallAfter(self._SetValue, newstr)
# Adjust insertion point on date if just entered 2 digit year, and there are now 4 digits:
if not self.IsDefault() and self._isDate and self._4digityear:
if pos == year2dig and unadjusted[year2dig] != newstr[year2dig]:
newpos = pos+2
- wxCallAfter(self._SetInsertionPoint, newpos)
+ wx.CallAfter(self._SetInsertionPoint, newpos)
if match_field is not None:
dbg('matched field')
if new_select_to != newpos:
dbg('queuing selection: (%d, %d)' % (newpos, new_select_to))
- wxCallAfter(self._SetSelection, newpos, new_select_to)
+ wx.CallAfter(self._SetSelection, newpos, new_select_to)
else:
newfield = self._FindField(newpos)
if newfield != field and newfield._selectOnFieldEntry:
dbg('queuing selection: (%d, %d)' % (newfield._extent[0], newfield._extent[1]))
- wxCallAfter(self._SetSelection, newfield._extent[0], newfield._extent[1])
- keep_processing = false
+ wx.CallAfter(self._SetSelection, newfield._extent[0], newfield._extent[1])
+ keep_processing = False
elif keep_processing:
dbg('char not allowed')
keep_processing = False
- if (not wxValidator_IsSilent()) and orig_pos == pos:
- wxBell()
+ if (not wx.Validator_IsSilent()) and orig_pos == pos:
+ wx.Bell()
self._applyFormatting()
next_entry = self._findNextEntry( pos )
if pos != next_entry:
dbg("moving from %(pos)d to next valid entry: %(next_entry)d" % locals())
- wxCallAfter(self._SetInsertionPoint, next_entry )
+ wx.CallAfter(self._SetInsertionPoint, next_entry )
if self._isTemplateChar(pos):
self._AdjustField(pos)
10, 14
etc.
"""
- dbg('wxMaskedEditMixin::_FindFieldExtent(pos=%s, getslice=%s)' % (
+ dbg('MaskedEditMixin::_FindFieldExtent(pos=%s, getslice=%s)' % (
str(pos), str(getslice)) ,indent=1)
field = self._FindField(pos)
when calculating the current field.
"""
-## dbg('wxMaskedEditMixin::_FindField(pos=%s)' % str(pos) ,indent=1)
+## dbg('MaskedEditMixin::_FindField(pos=%s)' % str(pos) ,indent=1)
if pos is None: pos = self._GetInsertionPoint()
elif pos < 0 or pos > self._masklength:
raise IndexError('position %s out of range of control' % str(pos))
def ClearValue(self):
""" Blanks the current control value by replacing it with the default value."""
- dbg("wxMaskedEditMixin::ClearValue - value reset to default value (template)")
+ dbg("MaskedEditMixin::ClearValue - value reset to default value (template)")
self._SetValue( self._template )
self._SetInsertionPoint(0)
self.Refresh()
Makes up-arrow act like shift-tab should; ie. take you to start of
previous field.
"""
- dbg('wxMaskedEditMixin::_OnUpNumeric', indent=1)
+ dbg('MaskedEditMixin::_OnUpNumeric', indent=1)
event.m_shiftDown = 1
dbg('event.ShiftDown()?', event.ShiftDown())
self._OnChangeField(event)
Used in response to left/right navigation keys; makes these actions skip
over mask template chars.
"""
- dbg("wxMaskedEditMixin::_OnArrow", indent=1)
+ dbg("MaskedEditMixin::_OnArrow", indent=1)
pos = self._GetInsertionPoint()
keycode = event.GetKeyCode()
sel_start, sel_to = self._GetSelection()
entry_end = self._goEnd(getPosOnly=True)
- if keycode in (WXK_RIGHT, WXK_DOWN):
+ if keycode in (wx.WXK_RIGHT, wx.WXK_DOWN):
if( ( not self._isTemplateChar(pos) and pos+1 > entry_end)
or ( self._isTemplateChar(pos) and pos >= entry_end) ):
dbg("can't advance", indent=0)
return False
elif self._isTemplateChar(pos):
self._AdjustField(pos)
- elif keycode in (WXK_LEFT,WXK_UP) and sel_start == sel_to and pos > 0 and self._isTemplateChar(pos-1):
+ elif keycode in (wx.WXK_LEFT,wx.WXK_UP) and sel_start == sel_to and pos > 0 and self._isTemplateChar(pos-1):
dbg('adjusting field')
self._AdjustField(pos)
# treat as shifted up/down arrows as tab/reverse tab:
- if event.ShiftDown() and keycode in (WXK_UP, WXK_DOWN):
+ if event.ShiftDown() and keycode in (wx.WXK_UP, wx.WXK_DOWN):
# remove "shifting" and treat as (forward) tab:
event.m_shiftDown = False
keep_processing = self._OnChangeField(event)
elif self._FindField(pos)._selectOnFieldEntry:
- if( keycode in (WXK_UP, WXK_LEFT)
+ if( keycode in (wx.WXK_UP, wx.WXK_LEFT)
and sel_start != 0
and self._isTemplateChar(sel_start-1)
and sel_start != self._masklength
event.m_shiftDown = True
event.m_ControlDown = True
keep_processing = self._OnChangeField(event)
- elif( keycode in (WXK_DOWN, WXK_RIGHT)
+ elif( keycode in (wx.WXK_DOWN, wx.WXK_RIGHT)
and sel_to != self._masklength
and self._isTemplateChar(sel_to)):
dbg('using base ctrl event processing')
event.Skip()
else:
- if( (sel_to == self._fields[0]._extent[0] and keycode == WXK_LEFT)
- or (sel_to == self._masklength and keycode == WXK_RIGHT) ):
- if not wxValidator_IsSilent():
- wxBell()
+ if( (sel_to == self._fields[0]._extent[0] and keycode == wx.WXK_LEFT)
+ or (sel_to == self._masklength and keycode == wx.WXK_RIGHT) ):
+ if not wx.Validator_IsSilent():
+ wx.Bell()
else:
# treat arrows as normal, allowing selection
# as appropriate:
def _OnCtrl_S(self, event):
""" Default Ctrl-S handler; prints value information if demo enabled. """
- dbg("wxMaskedEditMixin::_OnCtrl_S")
+ dbg("MaskedEditMixin::_OnCtrl_S")
if self._demo:
- print 'wxMaskedEditMixin.GetValue() = "%s"\nwxMaskedEditMixin.GetPlainValue() = "%s"' % (self.GetValue(), self.GetPlainValue())
+ print 'MaskedEditMixin.GetValue() = "%s"\nMaskedEditMixin.GetPlainValue() = "%s"' % (self.GetValue(), self.GetPlainValue())
print "Valid? => " + str(self.IsValid())
print "Current field, start, end, value =", str( self._FindFieldExtent(getslice=True))
return False
def _OnCtrl_X(self, event=None):
""" Handles ctrl-x keypress in control and Cut operation on context menu.
Should return False to skip other processing. """
- dbg("wxMaskedEditMixin::_OnCtrl_X", indent=1)
+ dbg("MaskedEditMixin::_OnCtrl_X", indent=1)
self.Cut()
dbg(indent=0)
return False
def _OnCtrl_V(self, event=None):
""" Handles ctrl-V keypress in control and Paste operation on context menu.
Should return False to skip other processing. """
- dbg("wxMaskedEditMixin::_OnCtrl_V", indent=1)
+ dbg("MaskedEditMixin::_OnCtrl_V", indent=1)
self.Paste()
dbg(indent=0)
return False
def _OnCtrl_Z(self, event=None):
""" Handles ctrl-Z keypress in control and Undo operation on context menu.
- Should return false to skip other processing. """
- dbg("wxMaskedEditMixin::_OnCtrl_Z", indent=1)
+ Should return False to skip other processing. """
+ dbg("MaskedEditMixin::_OnCtrl_Z", indent=1)
self.Undo()
dbg(indent=0)
return False
""" Handles ctrl-a keypress in control. Should return False to skip other processing. """
end = self._goEnd(getPosOnly=True)
if not event or event.ShiftDown():
- wxCallAfter(self._SetInsertionPoint, 0)
- wxCallAfter(self._SetSelection, 0, self._masklength)
+ wx.CallAfter(self._SetInsertionPoint, 0)
+ wx.CallAfter(self._SetSelection, 0, self._masklength)
else:
- wxCallAfter(self._SetInsertionPoint, 0)
- wxCallAfter(self._SetSelection, 0, end)
+ wx.CallAfter(self._SetInsertionPoint, 0)
+ wx.CallAfter(self._SetSelection, 0, end)
return False
def _OnErase(self, event=None):
""" Handles backspace and delete keypress in control. Should return False to skip other processing."""
- dbg("wxMaskedEditMixin::_OnErase", indent=1)
+ dbg("MaskedEditMixin::_OnErase", indent=1)
sel_start, sel_to = self._GetSelection() ## check for a range of selected text
if event is None: # called as action routine from Cut() operation.
- key = WXK_DELETE
+ key = wx.WXK_DELETE
else:
key = event.GetKeyCode()
oldstart = sel_start
# If trying to erase beyond "legal" bounds, disallow operation:
- if( (sel_to == 0 and key == WXK_BACK)
- or (self._signOk and sel_to == 1 and value[0] == ' ' and key == WXK_BACK)
- or (sel_to == self._masklength and sel_start == sel_to and key == WXK_DELETE and not field._insertRight)
+ if( (sel_to == 0 and key == wx.WXK_BACK)
+ or (self._signOk and sel_to == 1 and value[0] == ' ' and key == wx.WXK_BACK)
+ or (sel_to == self._masklength and sel_start == sel_to and key == wx.WXK_DELETE and not field._insertRight)
or (self._signOk and self._useParens
and sel_start == sel_to
and sel_to == self._masklength - 1
- and value[sel_to] == ' ' and key == WXK_DELETE and not field._insertRight) ):
- if not wxValidator_IsSilent():
- wxBell()
+ and value[sel_to] == ' ' and key == wx.WXK_DELETE and not field._insertRight) ):
+ if not wx.Validator_IsSilent():
+ wx.Bell()
dbg(indent=0)
return False
and sel_start >= start # and selection starts in field
and ((sel_to == sel_start # and no selection
and sel_to == end # and cursor at right edge
- and key in (WXK_BACK, WXK_DELETE)) # and either delete or backspace key
+ and key in (wx.WXK_BACK, wx.WXK_DELETE)) # and either delete or backspace key
or # or
- (key == WXK_BACK # backspacing
+ (key == wx.WXK_BACK # backspacing
and (sel_to == end # and selection ends at right edge
or sel_to < end and field._allowInsert)) ) ): # or allow right insert at any point in field
dbg('delete left')
# if backspace but left of cursor is empty, adjust cursor right before deleting
- while( key == WXK_BACK
+ while( key == wx.WXK_BACK
and sel_start == sel_to
and sel_start < end
and value[start:sel_start] == self._template[start:sel_start]):
# selection (if any) falls within current insert-capable field:
select_len = sel_to - sel_start
# determine where cursor should end up:
- if key == WXK_BACK:
+ if key == wx.WXK_BACK:
if select_len == 0:
newpos = sel_start -1
else:
else:
if sel_start == sel_to:
dbg("current sel_start, sel_to:", sel_start, sel_to)
- if key == WXK_BACK:
+ if key == wx.WXK_BACK:
sel_start, sel_to = sel_to-1, sel_to-1
dbg("new sel_start, sel_to:", sel_start, sel_to)
dbg('field._validRequired?', field._validRequired)
dbg('field.IsValid("%s")?' % newstr[start:end], field.IsValid(newstr[start:end]))
if field._validRequired and not field.IsValid(newstr[start:end]):
- if not wxValidator_IsSilent():
- wxBell()
+ if not wx.Validator_IsSilent():
+ wx.Bell()
dbg(indent=0)
return False
# if erasure results in an invalid value, disallow it:
if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
- if not wxValidator_IsSilent():
- wxBell()
+ if not wx.Validator_IsSilent():
+ wx.Bell()
dbg(indent=0)
return False
dbg('setting value (later) to', newstr)
- wxCallAfter(self._SetValue, newstr)
+ wx.CallAfter(self._SetValue, newstr)
dbg('setting insertion point (later) to', pos)
- wxCallAfter(self._SetInsertionPoint, pos)
+ wx.CallAfter(self._SetInsertionPoint, pos)
dbg(indent=0)
return False
def _OnEnd(self,event):
""" Handles End keypress in control. Should return False to skip other processing. """
- dbg("wxMaskedEditMixin::_OnEnd", indent=1)
+ dbg("MaskedEditMixin::_OnEnd", indent=1)
pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
if not event.ControlDown():
end = self._masklength # go to end of control
dbg("shift-end; select to end of control")
else:
dbg("shift-ctrl-end; select to end of non-whitespace")
- wxCallAfter(self._SetInsertionPoint, pos)
- wxCallAfter(self._SetSelection, pos, end)
+ wx.CallAfter(self._SetInsertionPoint, pos)
+ wx.CallAfter(self._SetSelection, pos, end)
else:
if not event.ControlDown():
dbg('go to end of control:')
- wxCallAfter(self._SetInsertionPoint, end)
- wxCallAfter(self._SetSelection, end, end)
+ wx.CallAfter(self._SetInsertionPoint, end)
+ wx.CallAfter(self._SetSelection, end, end)
dbg(indent=0)
return False
Changes the event to look like a tab event, so we can then call
event.Skip() on it, and have the parent form "do the right thing."
"""
- dbg('wxMaskedEditMixin::OnReturn')
- event.m_keyCode = WXK_TAB
+ dbg('MaskedEditMixin::OnReturn')
+ event.m_keyCode = wx.WXK_TAB
event.Skip()
def _OnHome(self,event):
""" Handles Home keypress in control. Should return False to skip other processing."""
- dbg("wxMaskedEditMixin::_OnHome", indent=1)
+ dbg("MaskedEditMixin::_OnHome", indent=1)
pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
sel_start, sel_to = self._GetSelection()
dbg("shift-ctrl-home; unselect to beginning of field")
dbg('queuing new sel_start, sel_to:', (start, end))
- wxCallAfter(self._SetInsertionPoint, start)
- wxCallAfter(self._SetSelection, start, end)
+ wx.CallAfter(self._SetInsertionPoint, start)
+ wx.CallAfter(self._SetSelection, start, end)
dbg(indent=0)
return False
control-shift-TAB, these events are not sent to the controls
by the framework.
"""
- dbg('wxMaskedEditMixin::_OnChangeField', indent = 1)
+ dbg('MaskedEditMixin::_OnChangeField', indent = 1)
# determine end of current field:
pos = self._GetInsertionPoint()
dbg('current pos:', pos)
if self._masklength < 0: # no fields; process tab normally
self._AdjustField(pos)
- if event.GetKeyCode() == WXK_TAB:
+ if event.GetKeyCode() == wx.WXK_TAB:
dbg('tab to next ctrl')
event.Skip()
#else: do nothing
# NOTE: doesn't yet work with SHIFT-tab under wx; the control
# never sees this event! (But I've coded for it should it ever work,
- # and it *does* work for '.' in wxIpAddrCtrl.)
+ # and it *does* work for '.' in IpAddrCtrl.)
field = self._FindField(pos)
index = field._index
field_start = field._extent[0]
if pos < field_start:
dbg('cursor before 1st field; cannot change to a previous field')
- if not wxValidator_IsSilent():
- wxBell()
- return false
+ if not wx.Validator_IsSilent():
+ wx.Bell()
+ return False
if event.ControlDown():
dbg('queuing select to beginning of field:', field_start, pos)
- wxCallAfter(self._SetInsertionPoint, field_start)
- wxCallAfter(self._SetSelection, field_start, pos)
+ wx.CallAfter(self._SetInsertionPoint, field_start)
+ wx.CallAfter(self._SetSelection, field_start, pos)
dbg(indent=0)
return False
elif index == 0:
# We're already in the 1st field; process shift-tab normally:
self._AdjustField(pos)
- if event.GetKeyCode() == WXK_TAB:
+ if event.GetKeyCode() == wx.WXK_TAB:
dbg('tab to previous ctrl')
event.Skip()
else:
dbg('position at beginning')
- wxCallAfter(self._SetInsertionPoint, field_start)
+ wx.CallAfter(self._SetInsertionPoint, field_start)
dbg(indent=0)
return False
else:
begin_prev = self._FindField(field_start-1)._extent[0]
self._AdjustField(pos)
dbg('repositioning to', begin_prev)
- wxCallAfter(self._SetInsertionPoint, begin_prev)
+ wx.CallAfter(self._SetInsertionPoint, begin_prev)
if self._FindField(begin_prev)._selectOnFieldEntry:
edit_start, edit_end = self._FindFieldExtent(begin_prev)
dbg('queuing selection to (%d, %d)' % (edit_start, edit_end))
- wxCallAfter(self._SetInsertionPoint, edit_start)
- wxCallAfter(self._SetSelection, edit_start, edit_end)
+ wx.CallAfter(self._SetInsertionPoint, edit_start)
+ wx.CallAfter(self._SetSelection, edit_start, edit_end)
dbg(indent=0)
return False
field_start, field_end = field._extent
if event.ControlDown():
dbg('queuing select to end of field:', pos, field_end)
- wxCallAfter(self._SetInsertionPoint, pos)
- wxCallAfter(self._SetSelection, pos, field_end)
+ wx.CallAfter(self._SetInsertionPoint, pos)
+ wx.CallAfter(self._SetSelection, pos, field_end)
dbg(indent=0)
return False
else:
if pos < field_start:
dbg('cursor before 1st field; go to start of field')
- wxCallAfter(self._SetInsertionPoint, field_start)
+ wx.CallAfter(self._SetInsertionPoint, field_start)
if field._selectOnFieldEntry:
- wxCallAfter(self._SetSelection, field_start, field_end)
+ wx.CallAfter(self._SetSelection, field_start, field_end)
else:
- wxCallAfter(self._SetSelection, field_start, field_start)
+ wx.CallAfter(self._SetSelection, field_start, field_start)
return False
# else...
dbg('end of current field:', field_end)
dbg('go to next field')
if field_end == self._fields[self._field_indices[-1]]._extent[1]:
self._AdjustField(pos)
- if event.GetKeyCode() == WXK_TAB:
+ if event.GetKeyCode() == wx.WXK_TAB:
dbg('tab to next ctrl')
event.Skip()
else:
dbg('position at end')
- wxCallAfter(self._SetInsertionPoint, field_end)
+ wx.CallAfter(self._SetInsertionPoint, field_end)
dbg(indent=0)
return False
else:
if next_pos == field_end:
dbg('already in last field')
self._AdjustField(pos)
- if event.GetKeyCode() == WXK_TAB:
+ if event.GetKeyCode() == wx.WXK_TAB:
dbg('tab to next ctrl')
event.Skip()
#else: do nothing
edit_start, edit_end = field._extent
if field._selectOnFieldEntry:
dbg('move to ', next_pos)
- wxCallAfter(self._SetInsertionPoint, next_pos)
+ wx.CallAfter(self._SetInsertionPoint, next_pos)
edit_start, edit_end = self._FindFieldExtent(next_pos)
dbg('queuing select', edit_start, edit_end)
- wxCallAfter(self._SetSelection, edit_start, edit_end)
+ wx.CallAfter(self._SetSelection, edit_start, edit_end)
else:
if field._insertRight:
next_pos = field._extent[1]
dbg('move to ', next_pos)
- wxCallAfter(self._SetInsertionPoint, next_pos)
+ wx.CallAfter(self._SetInsertionPoint, next_pos)
dbg(indent=0)
return False
def _OnDecimalPoint(self, event):
- dbg('wxMaskedEditMixin::_OnDecimalPoint', indent=1)
+ dbg('MaskedEditMixin::_OnDecimalPoint', indent=1)
pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
newstr = self._adjustFloat(clipped_text)
else:
newstr = self._adjustFloat(value)
- wxCallAfter(self._SetValue, newstr)
+ wx.CallAfter(self._SetValue, newstr)
fraction = self._fields[1]
start, end = fraction._extent
- wxCallAfter(self._SetInsertionPoint, start)
+ wx.CallAfter(self._SetInsertionPoint, start)
if fraction._selectOnFieldEntry:
dbg('queuing selection after decimal point to:', (start, end))
- wxCallAfter(self._SetSelection, start, end)
+ wx.CallAfter(self._SetSelection, start, end)
keep_processing = False
if self._isInt: ## handle integer value, truncate from current position
dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text)
newstr = self._adjustInt(clipped_text)
dbg('newstr: "%s"' % newstr)
- wxCallAfter(self._SetValue, newstr)
+ wx.CallAfter(self._SetValue, newstr)
newpos = len(newstr.rstrip())
if newstr.find(')') != -1:
newpos -= 1 # (don't move past right paren)
- wxCallAfter(self._SetInsertionPoint, newpos)
+ wx.CallAfter(self._SetInsertionPoint, newpos)
keep_processing = False
dbg(indent=0)
def _OnChangeSign(self, event):
- dbg('wxMaskedEditMixin::_OnChangeSign', indent=1)
+ dbg('MaskedEditMixin::_OnChangeSign', indent=1)
key = event.GetKeyCode()
pos = self._adjustPos(self._GetInsertionPoint(), key)
value = self._eraseSelection()
dbg('clearing self._isNeg')
self._isNeg = False
- wxCallAfter(self._SetValue, text)
- wxCallAfter(self._applyFormatting)
+ wx.CallAfter(self._SetValue, text)
+ wx.CallAfter(self._applyFormatting)
dbg('pos:', pos, 'signpos:', self._signpos)
if pos == self._signpos or integer.IsEmpty(text[start:end]):
- wxCallAfter(self._SetInsertionPoint, self._signpos+1)
+ wx.CallAfter(self._SetInsertionPoint, self._signpos+1)
else:
- wxCallAfter(self._SetInsertionPoint, pos)
+ wx.CallAfter(self._SetInsertionPoint, pos)
keep_processing = False
else:
This handler is only registered if the mask is a numeric mask.
It allows the insertion of ',' or '.' if appropriate.
"""
- dbg('wxMaskedEditMixin::_OnGroupChar', indent=1)
+ dbg('MaskedEditMixin::_OnGroupChar', indent=1)
keep_processing = True
pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
sel_start, sel_to = self._GetSelection()
groupchar = self._fields[0]._groupChar
if not self._isCharAllowed(groupchar, pos, checkRegex=True):
keep_processing = False
- if not wxValidator_IsSilent():
- wxBell()
+ if not wx.Validator_IsSilent():
+ wx.Bell()
if keep_processing:
newstr, newpos = self._insertKey(groupchar, pos, sel_start, sel_to, self._GetValue() )
dbg("str with '%s' inserted:" % groupchar, '"%s"' % newstr)
if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
keep_processing = False
- if not wxValidator_IsSilent():
- wxBell()
+ if not wx.Validator_IsSilent():
+ wx.Bell()
if keep_processing:
- wxCallAfter(self._SetValue, newstr)
- wxCallAfter(self._SetInsertionPoint, newpos)
+ wx.CallAfter(self._SetValue, newstr)
+ wx.CallAfter(self._SetInsertionPoint, newpos)
keep_processing = False
dbg(indent=0)
return keep_processing
def _OnAutoCompleteField(self, event):
- dbg('wxMaskedEditMixin::_OnAutoCompleteField', indent =1)
+ dbg('MaskedEditMixin::_OnAutoCompleteField', indent =1)
pos = self._GetInsertionPoint()
field = self._FindField(pos)
edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
dbg('choices:', field._choices)
dbg('compareChoices:', field._compareChoices)
choices, choice_required = field._compareChoices, field._choiceRequired
- if keycode in (WXK_PRIOR, WXK_UP):
+ if keycode in (wx.WXK_PRIOR, wx.WXK_UP):
direction = -1
else:
direction = 1
match_index, partial_match = self._autoComplete(direction, choices, text, compareNoCase=field._compareNoCase, current_index = field._autoCompleteIndex)
if( match_index is None
- and (keycode in self._autoCompleteKeycodes + [WXK_PRIOR, WXK_NEXT]
- or (keycode in [WXK_UP, WXK_DOWN] and event.ShiftDown() ) ) ):
+ and (keycode in self._autoCompleteKeycodes + [wx.WXK_PRIOR, wx.WXK_NEXT]
+ or (keycode in [wx.WXK_UP, wx.WXK_DOWN] and event.ShiftDown() ) ) ):
# Select the 1st thing from the list:
match_index = 0
if( match_index is not None
- and ( keycode in self._autoCompleteKeycodes + [WXK_PRIOR, WXK_NEXT]
- or (keycode in [WXK_UP, WXK_DOWN] and event.ShiftDown())
- or (keycode == WXK_DOWN and partial_match) ) ):
+ and ( keycode in self._autoCompleteKeycodes + [wx.WXK_PRIOR, wx.WXK_NEXT]
+ or (keycode in [wx.WXK_UP, wx.WXK_DOWN] and event.ShiftDown())
+ or (keycode == wx.WXK_DOWN and partial_match) ) ):
# We're allowed to auto-complete:
dbg('match found')
self._CheckValid() # recolor as appopriate
- if keycode in (WXK_UP, WXK_DOWN, WXK_LEFT, WXK_RIGHT):
+ if keycode in (wx.WXK_UP, wx.WXK_DOWN, wx.WXK_LEFT, wx.WXK_RIGHT):
# treat as left right arrow if unshifted, tab/shift tab if shifted.
if event.ShiftDown():
- if keycode in (WXK_DOWN, WXK_RIGHT):
+ if keycode in (wx.WXK_DOWN, wx.WXK_RIGHT):
# remove "shifting" and treat as (forward) tab:
event.m_shiftDown = False
keep_processing = self._OnChangeField(event)
Function called if autoselect feature is enabled and entire control
is selected:
"""
- dbg('wxMaskedEditMixin::OnAutoSelect', field._index)
+ dbg('MaskedEditMixin::OnAutoSelect', field._index)
if match_index is not None:
field._autoCompleteIndex = match_index
"""
'Fixes' an floating point control. Collapses spaces, right-justifies, etc.
"""
- dbg('wxMaskedEditMixin::_adjustFloat, candidate = "%s"' % candidate, indent=1)
+ dbg('MaskedEditMixin::_adjustFloat, candidate = "%s"' % candidate, indent=1)
lenInt,lenFraction = [len(s) for s in self._mask.split('.')] ## Get integer, fraction lengths
if candidate is None: value = self._GetValue()
dbg('newvalue = "%s"' % newvalue)
if candidate is None:
- wxCallAfter(self._SetValue, newvalue)
+ wx.CallAfter(self._SetValue, newvalue)
dbg(indent=0)
return newvalue
def _adjustInt(self, candidate=None):
""" 'Fixes' an integer control. Collapses spaces, right or left-justifies."""
- dbg("wxMaskedEditMixin::_adjustInt", candidate)
+ dbg("MaskedEditMixin::_adjustInt", candidate)
lenInt = self._masklength
if candidate is None: value = self._GetValue()
else: value = candidate
intStr = intStr.ljust( lenInt )
if candidate is None:
- wxCallAfter(self._SetValue, intStr )
+ wx.CallAfter(self._SetValue, intStr )
return intStr
'Fixes' a date control, expanding the year if it can.
Applies various self-formatting options.
"""
- dbg("wxMaskedEditMixin::_adjustDate", indent=1)
+ dbg("MaskedEditMixin::_adjustDate", indent=1)
if candidate is None: text = self._GetValue()
else: text = candidate
dbg('text=', text)
if len(year) == 2:
# Fix year adjustment to be less "20th century" :-) and to adjust heuristic as the
# years pass...
- now = wxDateTime_Now()
+ now = wx.DateTime_Now()
century = (now.GetYear() /100) * 100 # "this century"
twodig_year = now.GetYear() - century # "this year" (2 digits)
# if separation between today's 2-digit year and typed value > 50,
def _goEnd(self, getPosOnly=False):
""" Moves the insertion point to the end of user-entry """
- dbg("wxMaskedEditMixin::_goEnd; getPosOnly:", getPosOnly, indent=1)
+ dbg("MaskedEditMixin::_goEnd; getPosOnly:", getPosOnly, indent=1)
text = self._GetValue()
## dbg('text: "%s"' % text)
i = 0
def _goHome(self, getPosOnly=False):
""" Moves the insertion point to the beginning of user-entry """
- dbg("wxMaskedEditMixin::_goHome; getPosOnly:", getPosOnly, indent=1)
+ dbg("MaskedEditMixin::_goHome; getPosOnly:", getPosOnly, indent=1)
text = self._GetValue()
for i in range(self._masklength):
if self._isMaskChar(i):
if self._isTemplateChar( pos ): ## if a template character, return empty
- dbg('%d is a template character; returning false' % pos, indent=0)
+ dbg('%d is a template character; returning False' % pos, indent=0)
return False
if self._isMaskChar( pos ):
dbg(indent=0)
return approved
else:
- dbg('%d is a !???! character; returning false', indent=0)
+ dbg('%d is a !???! character; returning False', indent=0)
return False
value has been changed or set programatically.
"""
dbg(suspend=1)
- dbg('wxMaskedEditMixin::_applyFormatting', indent=1)
+ dbg('MaskedEditMixin::_applyFormatting', indent=1)
# Handle negative numbers
if self._signOk:
def _getAbsValue(self, candidate=None):
""" Return an unsigned value (i.e. strip the '-' prefix if any), and sign position(s).
"""
- dbg('wxMaskedEditMixin::_getAbsValue; candidate="%s"' % candidate, indent=1)
+ dbg('MaskedEditMixin::_getAbsValue; candidate="%s"' % candidate, indent=1)
if candidate is None: text = self._GetValue()
else: text = candidate
right_signpos = text.find(')')
dbg('text: "%s"' % text)
if self._signOk:
signpos = self._decimalpos - (len(text[:self._decimalpos].lstrip()) + 1)
- if text[signpos+1] in ('-','('):
+ # prevent checking for empty string - Tomo - Wed 14 Jan 2004 03:19:09 PM CET
+ if len(text) >= signpos+1 and text[signpos+1] in ('-','('):
signpos += 1
else:
signpos = -1
""" Return a signed value by adding a "-" prefix if the value
is set to negative, or a space if positive.
"""
- dbg('wxMaskedEditMixin::_getSignedValue; candidate="%s"' % candidate, indent=1)
+ dbg('MaskedEditMixin::_getSignedValue; candidate="%s"' % candidate, indent=1)
if candidate is None: text = self._GetValue()
else: text = candidate
def GetPlainValue(self, candidate=None):
""" Returns control's value stripped of the template text.
- plainvalue = wxMaskedEditMixin.GetPlainValue()
+ plainvalue = MaskedEditMixin.GetPlainValue()
"""
- dbg('wxMaskedEditMixin::GetPlainValue; candidate="%s"' % candidate, indent=1)
+ dbg('MaskedEditMixin::GetPlainValue; candidate="%s"' % candidate, indent=1)
if candidate is None: text = self._GetValue()
else: text = candidate
def IsValid(self, value=None):
""" Indicates whether the value specified (or the current value of the control
if not specified) is considered valid."""
-## dbg('wxMaskedEditMixin::IsValid("%s")' % value, indent=1)
+## dbg('MaskedEditMixin::IsValid("%s")' % value, indent=1)
if value is None: value = self._GetValue()
ret = self._CheckValid(value)
## dbg(indent=0)
def _eraseSelection(self, value=None, sel_start=None, sel_to=None):
""" Used to blank the selection when inserting a new character. """
- dbg("wxMaskedEditMixin::_eraseSelection", indent=1)
+ dbg("MaskedEditMixin::_eraseSelection", indent=1)
if value is None: value = self._GetValue()
if sel_start is None or sel_to is None:
sel_start, sel_to = self._GetSelection() ## check for a range of selected text
def _insertKey(self, char, pos, sel_start, sel_to, value, allowAutoSelect=False):
""" Handles replacement of the character at the current insertion point."""
- dbg('wxMaskedEditMixin::_insertKey', "\'" + char + "\'", pos, sel_start, sel_to, '"%s"' % value, indent=1)
+ dbg('MaskedEditMixin::_insertKey', "\'" + char + "\'", pos, sel_start, sel_to, '"%s"' % value, indent=1)
text = self._eraseSelection(value)
field = self._FindField(pos)
preserve the correct selection when the focus event is not due to tab,
we need to pull the following trick:
"""
- dbg('wxMaskedEditMixin::_OnFocus')
- wxCallAfter(self._fixSelection)
+ dbg('MaskedEditMixin::_OnFocus')
+ wx.CallAfter(self._fixSelection)
event.Skip()
self.Refresh()
effect of coloring the control appropriately.
"""
dbg(suspend=1)
- dbg('wxMaskedEditMixin::_CheckValid: candidate="%s"' % candidate, indent=1)
+ dbg('MaskedEditMixin::_CheckValid: candidate="%s"' % candidate, indent=1)
oldValid = self._valid
if candidate is None: value = self._GetValue()
else: value = candidate
else:
text = candidate
- valid = True # assume true
+ valid = True # assume True
for i in [-1] + self._field_indices: # process global constraints first:
field = self._fields[i]
start, end = field._extent
""" Validate the current date value using the provided Regex filter.
Generally used for character types.BufferType
"""
- dbg('wxMaskedEditMixin::_validateDate', indent=1)
+ dbg('MaskedEditMixin::_validateDate', indent=1)
if candidate is None: value = self._GetValue()
else: value = candidate
dbg('value = "%s"' % value)
month -= 1
try:
dbg("trying to create date from values day=%d, month=%d, year=%d" % (day,month,year))
- dateHandler = wxDateTimeFromDMY(day,month,year)
+ dateHandler = wx.DateTimeFromDMY(day,month,year)
dbg("succeeded")
dateOk = True
except:
""" Validate the current time value using the provided Regex filter.
Generally used for character types.BufferType
"""
- dbg('wxMaskedEditMixin::_validateTime', indent=1)
+ dbg('MaskedEditMixin::_validateTime', indent=1)
# wxDateTime doesn't take kindly to leading/trailing spaces when parsing,
# so we eliminate them here:
if candidate is None: value = self._GetValue().strip()
dbg('value = "%s"' % value)
valid = True # assume True until proven otherwise
- dateHandler = wxDateTime_Today()
+ dateHandler = wx.DateTime_Today()
try:
checkTime = dateHandler.ParseTime(value)
dbg('checkTime:', checkTime, 'len(value)', len(value))
def _OnKillFocus(self,event):
""" Handler for EVT_KILL_FOCUS event.
"""
- dbg('wxMaskedEditMixin::_OnKillFocus', 'isDate=',self._isDate, indent=1)
+ dbg('MaskedEditMixin::_OnKillFocus', 'isDate=',self._isDate, indent=1)
if self._mask and self._IsEditable():
self._AdjustField(self._GetInsertionPoint())
self._CheckValid() ## Call valid handler
we can assume the cause, change the insertion point to the start of
the control, and deselect.
"""
- dbg('wxMaskedEditMixin::_fixSelection', indent=1)
+ dbg('MaskedEditMixin::_fixSelection', indent=1)
if not self._mask or not self._IsEditable():
dbg(indent=0)
return
derived control because the mixin functions can't override a method of
a sibling class.
"""
- dbg("wxMaskedEditMixin::_Cut", indent=1)
+ dbg("MaskedEditMixin::_Cut", indent=1)
value = self._GetValue()
dbg('current value: "%s"' % value)
sel_start, sel_to = self._GetSelection() ## check for a range of selected text
template.
"""
dbg(suspend=1)
- dbg('wxMaskedEditMixin::_validatePaste("%(paste_text)s", %(sel_start)d, %(sel_to)d), raise_on_invalid? %(raise_on_invalid)d' % locals(), indent=1)
+ dbg('MaskedEditMixin::_validatePaste("%(paste_text)s", %(sel_start)d, %(sel_to)d), raise_on_invalid? %(raise_on_invalid)d' % locals(), indent=1)
select_length = sel_to - sel_start
maxlength = select_length
dbg('sel_to - sel_start:', maxlength)
derived control because the mixin functions can't override a
method of a sibling class.
"""
- dbg('wxMaskedEditMixin::_Paste (value = "%s")' % value, indent=1)
+ dbg('MaskedEditMixin::_Paste (value = "%s")' % value, indent=1)
if value is None:
paste_text = self._getClipboardContents()
else:
if not valid_paste:
dbg('paste text not legal for the selection or portion of the control following the cursor;')
- if not wxValidator_IsSilent():
- wxBell()
+ if not wx.Validator_IsSilent():
+ wx.Bell()
dbg(indent=0)
return False
# else...
if new_text == '':
self.ClearValue()
else:
- wxCallAfter(self._SetValue, new_text)
+ wx.CallAfter(self._SetValue, new_text)
if new_pos is None:
new_pos = sel_start + len(replacement_text)
- wxCallAfter(self._SetInsertionPoint, new_pos)
+ wx.CallAfter(self._SetInsertionPoint, new_pos)
else:
dbg(indent=0)
return new_text
def _Undo(self):
""" Provides an Undo() method in base controls. """
- dbg("wxMaskedEditMixin::_Undo", indent=1)
+ dbg("MaskedEditMixin::_Undo", indent=1)
value = self._GetValue()
prev = self._prevValue
dbg('current value: "%s"' % value)
def _OnContextMenu(self, event):
- dbg('wxMaskedEditMixin::OnContextMenu()', indent=1)
+ dbg('MaskedEditMixin::OnContextMenu()', indent=1)
menu = wxMenu()
menu.Append(wxID_UNDO, "Undo", "")
menu.AppendSeparator()
## ---------- ---------- ---------- ---------- ---------- ---------- ----------
-class wxMaskedTextCtrl( wxTextCtrl, wxMaskedEditMixin ):
+class MaskedTextCtrl( wx.TextCtrl, MaskedEditMixin ):
"""
- This is the primary derivation from wxMaskedEditMixin. It provides
+ This is the primary derivation from MaskedEditMixin. It provides
a general masked text control that can be configured with different
masks.
"""
def __init__( self, parent, id=-1, value = '',
- pos = wxDefaultPosition,
- size = wxDefaultSize,
- style = wxTE_PROCESS_TAB,
- validator=wxDefaultValidator, ## placeholder provided for data-transfer logic
+ pos = wx.DefaultPosition,
+ size = wx.DefaultSize,
+ style = wx.TE_PROCESS_TAB,
+ validator=wx.DefaultValidator, ## placeholder provided for data-transfer logic
name = 'maskedTextCtrl',
setupEventHandling = True, ## setup event handling by default
**kwargs):
- wxTextCtrl.__init__(self, parent, id, value='',
+ wx.TextCtrl.__init__(self, parent, id, value='',
pos=pos, size = size,
style=style, validator=validator,
name=name)
self.controlInitialized = True
- wxMaskedEditMixin.__init__( self, name, **kwargs )
+ MaskedEditMixin.__init__( self, name, **kwargs )
self._SetInitialValue(value)
if setupEventHandling:
## Setup event handlers
- EVT_SET_FOCUS( self, self._OnFocus ) ## defeat automatic full selection
- EVT_KILL_FOCUS( self, self._OnKillFocus ) ## run internal validator
- EVT_LEFT_DCLICK(self, self._OnDoubleClick) ## select field under cursor on dclick
- EVT_RIGHT_UP(self, self._OnContextMenu ) ## bring up an appropriate context menu
- EVT_KEY_DOWN( self, self._OnKeyDown ) ## capture control events not normally seen, eg ctrl-tab.
- EVT_CHAR( self, self._OnChar ) ## handle each keypress
- EVT_TEXT( self, self.GetId(), self._OnTextChange ) ## color control appropriately & keep
+ self.Bind(wx.EVT_SET_FOCUS, self._OnFocus ) ## defeat automatic full selection
+ self.Bind(wx.EVT_KILL_FOCUS, self._OnKillFocus ) ## run internal validator
+ self.Bind(wx.EVT_LEFT_DCLICK, self._OnDoubleClick) ## select field under cursor on dclick
+ self.Bind(wx.EVT_RIGHT_UP, self._OnContextMenu ) ## bring up an appropriate context menu
+ self.Bind(wx.EVT_KEY_DOWN, self._OnKeyDown ) ## capture control events not normally seen, eg ctrl-tab.
+ self.Bind(wx.EVT_CHAR, self._OnChar ) ## handle each keypress
+ self.Bind(wx.EVT_TEXT, self._OnTextChange ) ## color control appropriately & keep
## track of previous value for undo
def __repr__(self):
- return "<wxMaskedTextCtrl: %s>" % self.GetValue()
+ return "<MaskedTextCtrl: %s>" % self.GetValue()
def _GetSelection(self):
"""
Allow mixin to get the text selection of this control.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
return self.GetSelection()
def _SetSelection(self, sel_start, sel_to):
"""
Allow mixin to set the text selection of this control.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
-## dbg("wxMaskedTextCtrl::_SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
+## dbg("MaskedTextCtrl::_SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
return self.SetSelection( sel_start, sel_to )
def SetSelection(self, sel_start, sel_to):
"""
This is just for debugging...
"""
- dbg("wxMaskedTextCtrl::SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
- wxTextCtrl.SetSelection(self, sel_start, sel_to)
+ dbg("MaskedTextCtrl::SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
+ wx.TextCtrl.SetSelection(self, sel_start, sel_to)
def _GetInsertionPoint(self):
return self.GetInsertionPoint()
def _SetInsertionPoint(self, pos):
-## dbg("wxMaskedTextCtrl::_SetInsertionPoint(%(pos)d)" % locals())
+## dbg("MaskedTextCtrl::_SetInsertionPoint(%(pos)d)" % locals())
self.SetInsertionPoint(pos)
def SetInsertionPoint(self, pos):
"""
This is just for debugging...
"""
- dbg("wxMaskedTextCtrl::SetInsertionPoint(%(pos)d)" % locals())
- wxTextCtrl.SetInsertionPoint(self, pos)
+ dbg("MaskedTextCtrl::SetInsertionPoint(%(pos)d)" % locals())
+ wx.TextCtrl.SetInsertionPoint(self, pos)
def _GetValue(self):
"""
Allow mixin to get the raw value of the control with this function.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
return self.GetValue()
def _SetValue(self, value):
"""
Allow mixin to set the raw value of the control with this function.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
- dbg('wxMaskedTextCtrl::_SetValue("%(value)s")' % locals(), indent=1)
+ dbg('MaskedTextCtrl::_SetValue("%(value)s")' % locals(), indent=1)
# Record current selection and insertion point, for undo
self._prevSelection = self._GetSelection()
self._prevInsertionPoint = self._GetInsertionPoint()
- wxTextCtrl.SetValue(self, value)
+ wx.TextCtrl.SetValue(self, value)
dbg(indent=0)
def SetValue(self, value):
masked control. NOTE: this must be done in the class derived
from the base wx control.
"""
- dbg('wxMaskedTextCtrl::SetValue = "%s"' % value, indent=1)
+ dbg('MaskedTextCtrl::SetValue = "%s"' % value, indent=1)
if not self._mask:
- wxTextCtrl.SetValue(self, value) # revert to base control behavior
+ wx.TextCtrl.SetValue(self, value) # revert to base control behavior
return
# empty previous contents, replacing entire value:
self._isNeg = False # (clear current assumptions)
value = self._adjustInt(value)
elif self._isDate and not self.IsValid(value) and self._4digityear:
- value = self._adjustDate(value, fixcentury=true)
+ value = self._adjustDate(value, fixcentury=True)
except ValueError:
# If date, year might be 2 digits vs. 4; try adjusting it:
if self._isDate and self._4digityear:
dateparts = value.split(' ')
- dateparts[0] = self._adjustDate(dateparts[0], fixcentury=true)
+ dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
value = string.join(dateparts, ' ')
dbg('adjusted value: "%s"' % value)
value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
self._SetValue(value)
## dbg('queuing insertion after .SetValue', self._masklength)
- wxCallAfter(self._SetInsertionPoint, self._masklength)
- wxCallAfter(self._SetSelection, self._masklength, self._masklength)
+ wx.CallAfter(self._SetInsertionPoint, self._masklength)
+ wx.CallAfter(self._SetSelection, self._masklength, self._masklength)
dbg(indent=0)
def Clear(self):
""" Blanks the current control value by replacing it with the default value."""
- dbg("wxMaskedTextCtrl::Clear - value reset to default value (template)")
+ dbg("MaskedTextCtrl::Clear - value reset to default value (template)")
if self._mask:
self.ClearValue()
else:
- wxTextCtrl.Clear(self) # else revert to base control behavior
+ wx.TextCtrl.Clear(self) # else revert to base control behavior
def _Refresh(self):
"""
Allow mixin to refresh the base control with this function.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
- dbg('wxMaskedTextCtrl::_Refresh', indent=1)
- wxTextCtrl.Refresh(self)
+ dbg('MaskedTextCtrl::_Refresh', indent=1)
+ wx.TextCtrl.Refresh(self)
dbg(indent=0)
validate the contents of the masked control as it refreshes.
NOTE: this must be done in the class derived from the base wx control.
"""
- dbg('wxMaskedTextCtrl::Refresh', indent=1)
+ dbg('MaskedTextCtrl::Refresh', indent=1)
self._CheckValid()
self._Refresh()
dbg(indent=0)
def _IsEditable(self):
"""
Allow mixin to determine if the base control is editable with this function.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
- return wxTextCtrl.IsEditable(self)
+ return wx.TextCtrl.IsEditable(self)
def Cut(self):
if self._mask:
self._Cut() # call the mixin's Cut method
else:
- wxTextCtrl.Cut(self) # else revert to base control behavior
+ wx.TextCtrl.Cut(self) # else revert to base control behavior
def Paste(self):
if self._mask:
self._Paste() # call the mixin's Paste method
else:
- wxTextCtrl.Paste(self, value) # else revert to base control behavior
+ wx.TextCtrl.Paste(self, value) # else revert to base control behavior
def Undo(self):
if self._mask:
self._Undo()
else:
- wxTextCtrl.Undo(self) # else revert to base control behavior
+ wx.TextCtrl.Undo(self) # else revert to base control behavior
def IsModified(self):
keystroke to see if the value changes, and if so, it's been
modified.
"""
- return wxTextCtrl.IsModified(self) or self.modified
+ return wx.TextCtrl.IsModified(self) or self.modified
def _CalcSize(self, size=None):
## ---------- ---------- ---------- ---------- ---------- ---------- ----------
## Because calling SetSelection programmatically does not fire EVT_COMBOBOX
## events, we have to do it ourselves when we auto-complete.
-class wxMaskedComboBoxSelectEvent(wxPyCommandEvent):
+class MaskedComboBoxSelectEvent(wx.PyCommandEvent):
def __init__(self, id, selection = 0, object=None):
- wxPyCommandEvent.__init__(self, wxEVT_COMMAND_COMBOBOX_SELECTED, id)
+ wx.PyCommandEvent.__init__(self, wx.wxEVT_COMMAND_COMBOBOX_SELECTED, id)
self.__selection = selection
self.SetEventObject(object)
return self.__selection
-class wxMaskedComboBox( wxComboBox, wxMaskedEditMixin ):
+class MaskedComboBox( wx.ComboBox, MaskedEditMixin ):
"""
This masked edit control adds the ability to use a masked input
on a combobox, and do auto-complete of such values.
"""
def __init__( self, parent, id=-1, value = '',
- pos = wxDefaultPosition,
- size = wxDefaultSize,
+ pos = wx.DefaultPosition,
+ size = wx.DefaultSize,
choices = [],
- style = wxCB_DROPDOWN,
- validator = wxDefaultValidator,
+ style = wx.CB_DROPDOWN,
+ validator = wx.DefaultValidator,
name = "maskedComboBox",
setupEventHandling = True, ## setup event handling by default):
**kwargs):
# This is necessary, because wxComboBox currently provides no
# method for determining later if this was specified in the
# constructor for the control...
- self.__readonly = style & wxCB_READONLY == wxCB_READONLY
+ self.__readonly = style & wx.CB_READONLY == wx.CB_READONLY
kwargs['choices'] = choices ## set up maskededit to work with choice list too
if not kwargs.has_key('compareNoCase'):
kwargs['compareNoCase'] = True
- wxMaskedEditMixin.__init__( self, name, **kwargs )
+ MaskedEditMixin.__init__( self, name, **kwargs )
self._choices = self._ctrl_constraints._choices
dbg('self._choices:', self._choices)
else:
choices = [choice.ljust(self._masklength) for choice in choices]
- wxComboBox.__init__(self, parent, id, value='',
+ wx.ComboBox.__init__(self, parent, id, value='',
pos=pos, size = size,
- choices=choices, style=style|wxWANTS_CHARS,
+ choices=choices, style=style|wx.WANTS_CHARS,
validator=validator,
name=name)
self._SetInitialValue(value)
- self._SetKeycodeHandler(WXK_UP, self.OnSelectChoice)
- self._SetKeycodeHandler(WXK_DOWN, self.OnSelectChoice)
+ self._SetKeycodeHandler(wx.WXK_UP, self.OnSelectChoice)
+ self._SetKeycodeHandler(wx.WXK_DOWN, self.OnSelectChoice)
if setupEventHandling:
## Setup event handlers
- EVT_SET_FOCUS( self, self._OnFocus ) ## defeat automatic full selection
- EVT_KILL_FOCUS( self, self._OnKillFocus ) ## run internal validator
- EVT_LEFT_DCLICK(self, self._OnDoubleClick) ## select field under cursor on dclick
- EVT_RIGHT_UP(self, self._OnContextMenu ) ## bring up an appropriate context menu
- EVT_CHAR( self, self._OnChar ) ## handle each keypress
- EVT_KEY_DOWN( self, self.OnKeyDown ) ## for special processing of up/down keys
- EVT_KEY_DOWN( self, self._OnKeyDown ) ## for processing the rest of the control keys
- ## (next in evt chain)
- EVT_TEXT( self, self.GetId(), self._OnTextChange ) ## color control appropriately & keep
+ self.Bind(wx.EVT_SET_FOCUS, self._OnFocus ) ## defeat automatic full selection
+ self.Bind(wx.EVT_KILL_FOCUS, self._OnKillFocus ) ## run internal validator
+ self.Bind(wx.EVT_LEFT_DCLICK, self._OnDoubleClick) ## select field under cursor on dclick
+ self.Bind(wx.EVT_RIGHT_UP, self._OnContextMenu ) ## bring up an appropriate context menu
+ self.Bind(wx.EVT_CHAR, self._OnChar ) ## handle each keypress
+ self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown ) ## for special processing of up/down keys
+ self.Bind(wx.EVT_KEY_DOWN, self._OnKeyDown ) ## for processing the rest of the control keys
+ ## (next in evt chain)
+ self.Bind(wx.EVT_TEXT, self._OnTextChange ) ## color control appropriately & keep
## track of previous value for undo
def __repr__(self):
- return "<wxMaskedComboBox: %s>" % self.GetValue()
+ return "<MaskedComboBox: %s>" % self.GetValue()
def _CalcSize(self, size=None):
def _GetSelection(self):
"""
Allow mixin to get the text selection of this control.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
return self.GetMark()
def _SetSelection(self, sel_start, sel_to):
"""
Allow mixin to set the text selection of this control.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
return self.SetMark( sel_start, sel_to )
def _GetValue(self):
"""
Allow mixin to get the raw value of the control with this function.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
return self.GetValue()
def _SetValue(self, value):
"""
Allow mixin to set the raw value of the control with this function.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
# For wxComboBox, ensure that values are properly padded so that
# if varying length choices are supplied, they always show up
# Record current selection and insertion point, for undo
self._prevSelection = self._GetSelection()
self._prevInsertionPoint = self._GetInsertionPoint()
- wxComboBox.SetValue(self, value)
+ wx.ComboBox.SetValue(self, value)
# text change events don't always fire, so we check validity here
# to make certain formatting is applied:
self._CheckValid()
from the base wx control.
"""
if not self._mask:
- wxComboBox.SetValue(value) # revert to base control behavior
+ wx.ComboBox.SetValue(value) # revert to base control behavior
return
# else...
# empty previous contents, replacing entire value:
self._isNeg = False # (clear current assumptions)
value = self._adjustInt(value)
elif self._isDate and not self.IsValid(value) and self._4digityear:
- value = self._adjustDate(value, fixcentury=true)
+ value = self._adjustDate(value, fixcentury=True)
except ValueError:
# If date, year might be 2 digits vs. 4; try adjusting it:
if self._isDate and self._4digityear:
dateparts = value.split(' ')
- dateparts[0] = self._adjustDate(dateparts[0], fixcentury=true)
+ dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
value = string.join(dateparts, ' ')
dbg('adjusted value: "%s"' % value)
value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
self._SetValue(value)
## dbg('queuing insertion after .SetValue', self._masklength)
- wxCallAfter(self._SetInsertionPoint, self._masklength)
- wxCallAfter(self._SetSelection, self._masklength, self._masklength)
+ wx.CallAfter(self._SetInsertionPoint, self._masklength)
+ wx.CallAfter(self._SetSelection, self._masklength, self._masklength)
def _Refresh(self):
"""
Allow mixin to refresh the base control with this function.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
- wxComboBox.Refresh(self)
+ wx.ComboBox.Refresh(self)
def Refresh(self):
"""
def _IsEditable(self):
"""
Allow mixin to determine if the base control is editable with this function.
- REQUIRED by any class derived from wxMaskedEditMixin.
+ REQUIRED by any class derived from MaskedEditMixin.
"""
return not self.__readonly
if self._mask:
self._Cut() # call the mixin's Cut method
else:
- wxComboBox.Cut(self) # else revert to base control behavior
+ wx.ComboBox.Cut(self) # else revert to base control behavior
def Paste(self):
if self._mask:
self._Paste() # call the mixin's Paste method
else:
- wxComboBox.Paste(self) # else revert to base control behavior
+ wx.ComboBox.Paste(self) # else revert to base control behavior
def Undo(self):
if self._mask:
self._Undo()
else:
- wxComboBox.Undo() # else revert to base control behavior
+ wx.ComboBox.Undo() # else revert to base control behavior
def Append( self, choice, clientData=None ):
(self._ctrl_constraints.IsEmpty(choice) and self._ctrl_constraints._validRequired) ) ):
raise ValueError('"%s" is not a valid value for the control "%s" as specified.' % (choice, self.name))
- wxComboBox.Append(self, choice, clientData)
+ wx.ComboBox.Append(self, choice, clientData)
self._ctrl_constraints._autoCompleteIndex = -1
if self._ctrl_constraints._choices:
self.SetCtrlParameters(choices=[])
- wxComboBox.Clear(self)
+ wx.ComboBox.Clear(self)
def SetCtrlParameters( self, **kwargs ):
Override mixin's default SetCtrlParameters to detect changes in choice list, so
we can update the base control:
"""
- wxMaskedEditMixin.SetCtrlParameters(self, **kwargs )
+ MaskedEditMixin.SetCtrlParameters(self, **kwargs )
if( self.controlInitialized
and (kwargs.has_key('choices') or self._choices != self._ctrl_constraints._choices) ):
- wxComboBox.Clear(self)
+ wx.ComboBox.Clear(self)
self._choices = self._ctrl_constraints._choices
for choice in self._choices:
- wxComboBox.Append( self, choice )
+ wx.ComboBox.Append( self, choice )
def GetMark(self):
events.
"""
dbg(suspend=1) # turn off debugging around this function
- dbg('wxMaskedComboBox::GetMark', indent=1)
+ dbg('MaskedComboBox::GetMark', indent=1)
if self.__readonly:
dbg(indent=0)
return 0, 0 # no selection possible for editing
self._ignoreChange = True # tell _OnTextChange() to ignore next event (if any)
- wxComboBox.Cut(self)
+ wx.ComboBox.Cut(self)
newvalue = self.GetValue()
dbg("value after Cut operation:", newvalue)
if newvalue != value: # something was selected; calculate extent
dbg("something selected")
sel_to = sel_start + len(value) - len(newvalue)
- wxComboBox.SetValue(self, value) # restore original value and selection (still ignoring change)
- wxComboBox.SetInsertionPoint(self, sel_start)
- wxComboBox.SetMark(self, sel_start, sel_to)
+ wx.ComboBox.SetValue(self, value) # restore original value and selection (still ignoring change)
+ wx.ComboBox.SetInsertionPoint(self, sel_start)
+ wx.ComboBox.SetMark(self, sel_start, sel_to)
self._ignoreChange = False # tell _OnTextChange() to pay attn again
Necessary for bookkeeping on choice selection, to keep current value
current.
"""
- dbg('wxMaskedComboBox::SetSelection(%d)' % index)
+ dbg('MaskedComboBox::SetSelection(%d)' % index)
if self._mask:
self._prevValue = self._curValue
self._curValue = self._choices[index]
self._ctrl_constraints._autoCompleteIndex = index
- wxComboBox.SetSelection(self, index)
+ wx.ComboBox.SetSelection(self, index)
def OnKeyDown(self, event):
on the text of the control somehow interferes with the combobox's
selection mechanism for the arrow keys.
"""
- dbg('wxMaskedComboBox::OnSelectChoice', indent=1)
+ dbg('MaskedComboBox::OnSelectChoice', indent=1)
if not self._mask:
event.Skip()
if self._ctrl_constraints._compareNoCase:
value = value.lower()
- if event.GetKeyCode() == WXK_UP:
+ if event.GetKeyCode() == wx.WXK_UP:
direction = -1
else:
direction = 1
Override mixin (empty) autocomplete handler, so that autocompletion causes
combobox to update appropriately.
"""
- dbg('wxMaskedComboBox::OnAutoSelect', field._index, indent=1)
+ dbg('MaskedComboBox::OnAutoSelect', field._index, indent=1)
## field._autoCompleteIndex = match_index
if field == self._ctrl_constraints:
self.SetSelection(match_index)
dbg('issuing combo selection event')
self.GetEventHandler().ProcessEvent(
- wxMaskedComboBoxSelectEvent( self.GetId(), match_index, self ) )
+ MaskedComboBoxSelectEvent( self.GetId(), match_index, self ) )
self._CheckValid()
dbg('field._autoCompleteIndex:', match_index)
dbg('self.GetSelection():', self.GetSelection())
programmatic wxComboBox.SetSelection() call to pick the appropriate
item in the list. (and then do the usual OnReturn bit.)
"""
- dbg('wxMaskedComboBox::OnReturn', indent=1)
+ dbg('MaskedComboBox::OnReturn', indent=1)
dbg('current value: "%s"' % self.GetValue(), 'current index:', self.GetSelection())
if self.GetSelection() == -1 and self.GetValue().lower().strip() in self._ctrl_constraints._compareChoices:
- wxCallAfter(self.SetSelection, self._ctrl_constraints._autoCompleteIndex)
+ wx.CallAfter(self.SetSelection, self._ctrl_constraints._autoCompleteIndex)
- event.m_keyCode = WXK_TAB
+ event.m_keyCode = wx.WXK_TAB
event.Skip()
dbg(indent=0)
## ---------- ---------- ---------- ---------- ---------- ---------- ----------
-class wxIpAddrCtrl( wxMaskedTextCtrl ):
+class IpAddrCtrl( MaskedTextCtrl ):
"""
- This class is a particular type of wxMaskedTextCtrl that accepts
+ This class is a particular type of MaskedTextCtrl that accepts
and understands the semantics of IP addresses, reformats input
as you move from field to field, and accepts '.' as a navigation
character, so that typing an IP address can be done naturally.
"""
def __init__( self, parent, id=-1, value = '',
- pos = wxDefaultPosition,
- size = wxDefaultSize,
- style = wxTE_PROCESS_TAB,
- validator = wxDefaultValidator,
- name = 'wxIpAddrCtrl',
+ pos = wx.DefaultPosition,
+ size = wx.DefaultSize,
+ style = wx.TE_PROCESS_TAB,
+ validator = wx.DefaultValidator,
+ name = 'IpAddrCtrl',
setupEventHandling = True, ## setup event handling by default
**kwargs):
kwargs['validRegex'] = "( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))(\.( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))){3}"
- wxMaskedTextCtrl.__init__(
+ MaskedTextCtrl.__init__(
self, parent, id=id, value = value,
pos=pos, size=size,
style = style,
def OnDot(self, event):
- dbg('wxIpAddrCtrl::OnDot', indent=1)
+ dbg('IpAddrCtrl::OnDot', indent=1)
pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
oldvalue = self.GetValue()
edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
def GetAddress(self):
- value = wxMaskedTextCtrl.GetValue(self)
+ value = MaskedTextCtrl.GetValue(self)
return value.replace(' ','') # remove spaces from the value
def _OnCtrl_S(self, event):
- dbg("wxIpAddrCtrl::_OnCtrl_S")
+ dbg("IpAddrCtrl::_OnCtrl_S")
if self._demo:
print "value:", self.GetAddress()
return False
def SetValue(self, value):
- dbg('wxIpAddrCtrl::SetValue(%s)' % str(value), indent=1)
+ dbg('IpAddrCtrl::SetValue(%s)' % str(value), indent=1)
if type(value) not in (types.StringType, types.UnicodeType):
dbg(indent=0)
raise ValueError('%s must be a string', str(value))
- bValid = True # assume true
+ bValid = True # assume True
parts = value.split('.')
if len(parts) != 4:
bValid = False
else:
dbg('parts:', parts)
value = string.join(parts, '.')
- wxMaskedTextCtrl.SetValue(self, value)
+ MaskedTextCtrl.SetValue(self, value)
dbg(indent=0)
return parts[2]
## ---------- ---------- ---------- ---------- ---------- ---------- ----------
-class test(wxPySimpleApp):
+class test(wx.PySimpleApp):
def OnInit(self):
- from wxPython.lib.rcsizer import RowColSizer
- self.frame = wxFrame( NULL, -1, "wxMaskedEditMixin 0.0.7 Demo Page #1", size = (700,600))
- self.panel = wxPanel( self.frame, -1)
+ from wx.lib.rcsizer import RowColSizer
+ self.frame = wx.Frame( None, -1, "MaskedEditMixin 0.0.7 Demo Page #1", size = (700,600))
+ self.panel = wx.Panel( self.frame, -1)
self.sizer = RowColSizer()
self.labels = []
self.editList = []
rowcount = 4
- id, id1 = wxNewId(), wxNewId()
- self.command1 = wxButton( self.panel, id, "&Close" )
- self.command2 = wxButton( self.panel, id1, "&AutoFormats" )
- self.sizer.Add(self.command1, row=0, col=0, flag=wxALL, border = 5)
- self.sizer.Add(self.command2, row=0, col=1, colspan=2, flag=wxALL, border = 5)
- EVT_BUTTON( self.panel, id, self.onClick )
+ id, id1 = wx.NewId(), wx.NewId()
+ self.command1 = wx.Button( self.panel, id, "&Close" )
+ self.command2 = wx.Button( self.panel, id1, "&AutoFormats" )
+ self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5)
+ self.sizer.Add(self.command2, row=0, col=1, colspan=2, flag=wx.ALL, border = 5)
+ self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1 )
## self.panel.SetDefaultItem(self.command1 )
- EVT_BUTTON( self.panel, id1, self.onClickPage )
+ self.panel.Bind(wx.EVT_BUTTON, self.onClickPage, self.command2)
- self.check1 = wxCheckBox( self.panel, -1, "Disallow Empty" )
- self.check2 = wxCheckBox( self.panel, -1, "Highlight Empty" )
- self.sizer.Add( self.check1, row=0,col=3, flag=wxALL,border=5 )
- self.sizer.Add( self.check2, row=0,col=4, flag=wxALL,border=5 )
- EVT_CHECKBOX( self.panel, self.check1.GetId(), self._onCheck1 )
- EVT_CHECKBOX( self.panel, self.check2.GetId(), self._onCheck2 )
+ self.check1 = wx.CheckBox( self.panel, -1, "Disallow Empty" )
+ self.check2 = wx.CheckBox( self.panel, -1, "Highlight Empty" )
+ self.sizer.Add( self.check1, row=0,col=3, flag=wx.ALL,border=5 )
+ self.sizer.Add( self.check2, row=0,col=4, flag=wx.ALL,border=5 )
+ self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck1, self.check1 )
+ self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck2, self.check2 )
label = """Press ctrl-s in any field to output the value and plain value. Press ctrl-x to clear and re-set any field.
Try entering nonsensical or partial values in validated fields to see what happens (use ctrl-s to test the valid status)."""
label2 = "\nNote that the State and Last Name fields are list-limited (Name:Smith,Jones,Williams)."
- self.label1 = wxStaticText( self.panel, -1, label)
- self.label2 = wxStaticText( self.panel, -1, "Description")
- self.label3 = wxStaticText( self.panel, -1, "Mask Value")
- self.label4 = wxStaticText( self.panel, -1, "Format")
- self.label5 = wxStaticText( self.panel, -1, "Reg Expr Val. (opt)")
- self.label6 = wxStaticText( self.panel, -1, "wxMaskedEdit Ctrl")
- self.label7 = wxStaticText( self.panel, -1, label2)
+ self.label1 = wx.StaticText( self.panel, -1, label)
+ self.label2 = wx.StaticText( self.panel, -1, "Description")
+ self.label3 = wx.StaticText( self.panel, -1, "Mask Value")
+ self.label4 = wx.StaticText( self.panel, -1, "Format")
+ self.label5 = wx.StaticText( self.panel, -1, "Reg Expr Val. (opt)")
+ self.label6 = wx.StaticText( self.panel, -1, "wxMaskedEdit Ctrl")
+ self.label7 = wx.StaticText( self.panel, -1, label2)
self.label7.SetForegroundColour("Blue")
self.label1.SetForegroundColour("Blue")
- self.label2.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
- self.label3.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
- self.label4.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
- self.label5.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
- self.label6.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
-
- self.sizer.Add( self.label1, row=1,col=0,colspan=7, flag=wxALL,border=5)
- self.sizer.Add( self.label7, row=2,col=0,colspan=7, flag=wxALL,border=5)
- self.sizer.Add( self.label2, row=3,col=0, flag=wxALL,border=5)
- self.sizer.Add( self.label3, row=3,col=1, flag=wxALL,border=5)
- self.sizer.Add( self.label4, row=3,col=2, flag=wxALL,border=5)
- self.sizer.Add( self.label5, row=3,col=3, flag=wxALL,border=5)
- self.sizer.Add( self.label6, row=3,col=4, flag=wxALL,border=5)
+ self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
+ self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
+ self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
+ self.label5.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
+ self.label6.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
+
+ self.sizer.Add( self.label1, row=1,col=0,colspan=7, flag=wx.ALL,border=5)
+ self.sizer.Add( self.label7, row=2,col=0,colspan=7, flag=wx.ALL,border=5)
+ self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5)
+ self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5)
+ self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5)
+ self.sizer.Add( self.label5, row=3,col=3, flag=wx.ALL,border=5)
+ self.sizer.Add( self.label6, row=3,col=4, flag=wx.ALL,border=5)
# The following list is of the controls for the demo. Feel free to play around with
# the options!
]
for control in controls:
- self.sizer.Add( wxStaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wxALL)
- self.sizer.Add( wxStaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wxALL)
- self.sizer.Add( wxStaticText( self.panel, -1, control[3]),row=rowcount, col=2,border=5, flag=wxALL)
- self.sizer.Add( wxStaticText( self.panel, -1, control[4][:20]),row=rowcount, col=3,border=5, flag=wxALL)
+ self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL)
+ self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL)
+ self.sizer.Add( wx.StaticText( self.panel, -1, control[3]),row=rowcount, col=2,border=5, flag=wx.ALL)
+ self.sizer.Add( wx.StaticText( self.panel, -1, control[4][:20]),row=rowcount, col=3,border=5, flag=wx.ALL)
if control in controls[:]:#-2]:
- newControl = wxMaskedTextCtrl( self.panel, -1, "",
+ newControl = MaskedTextCtrl( self.panel, -1, "",
mask = control[1],
excludeChars = control[2],
formatcodes = control[3],
demo = True)
if control[6]: newControl.SetCtrlParameters(choiceRequired = True)
else:
- newControl = wxMaskedComboBox( self.panel, -1, "",
+ newControl = MaskedComboBox( self.panel, -1, "",
choices = control[7],
choiceRequired = True,
mask = control[1],
demo = True)
self.editList.append( newControl )
- self.sizer.Add( newControl, row=rowcount,col=4,flag=wxALL,border=5)
+ self.sizer.Add( newControl, row=rowcount,col=4,flag=wx.ALL,border=5)
rowcount += 1
self.sizer.AddGrowableCol(4)
def _onCheck1(self,event):
""" Set required value on/off """
- value = event.Checked()
+ value = event.IsChecked()
if value:
for control in self.editList:
control.SetCtrlParameters(emptyInvalid=True)
def _onCheck2(self,event):
""" Highlight empty values"""
- value = event.Checked()
+ value = event.IsChecked()
if value:
for control in self.editList:
control.SetCtrlParameters( emptyBackgroundColour = 'Aquamarine')
## ---------- ---------- ---------- ---------- ---------- ---------- ----------
-class test2(wxFrame):
+class test2(wx.Frame):
def __init__(self, parent, id, caption):
- wxFrame.__init__( self, parent, id, "wxMaskedEdit control 0.0.7 Demo Page #2 -- AutoFormats", size = (550,600))
- from wxPython.lib.rcsizer import RowColSizer
- self.panel = wxPanel( self, -1)
+ wx.Frame.__init__( self, parent, id, "wxMaskedEdit control 0.0.7 Demo Page #2 -- AutoFormats", size = (550,600))
+ from wx.lib.rcsizer import RowColSizer
+ self.panel = wx.Panel( self, -1)
self.sizer = RowColSizer()
self.labels = []
self.texts = []
The class contains an internal dictionary of types and formats (autoformats).
To see a great example of validations in action, try entering a bad email address, then tab out."""
- self.label1 = wxStaticText( self.panel, -1, label)
- self.label2 = wxStaticText( self.panel, -1, "Description")
- self.label3 = wxStaticText( self.panel, -1, "AutoFormat Code")
- self.label4 = wxStaticText( self.panel, -1, "wxMaskedEdit Control")
+ self.label1 = wx.StaticText( self.panel, -1, label)
+ self.label2 = wx.StaticText( self.panel, -1, "Description")
+ self.label3 = wx.StaticText( self.panel, -1, "AutoFormat Code")
+ self.label4 = wx.StaticText( self.panel, -1, "wxMaskedEdit Control")
self.label1.SetForegroundColour("Blue")
- self.label2.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
- self.label3.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
- self.label4.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
-
- self.sizer.Add( self.label1, row=1,col=0,colspan=3, flag=wxALL,border=5)
- self.sizer.Add( self.label2, row=3,col=0, flag=wxALL,border=5)
- self.sizer.Add( self.label3, row=3,col=1, flag=wxALL,border=5)
- self.sizer.Add( self.label4, row=3,col=2, flag=wxALL,border=5)
-
- id, id1 = wxNewId(), wxNewId()
- self.command1 = wxButton( self.panel, id, "&Close")
- self.command2 = wxButton( self.panel, id1, "&Print Formats")
- EVT_BUTTON( self.panel, id, self.onClick)
+ self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
+ self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
+ self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
+
+ self.sizer.Add( self.label1, row=1,col=0,colspan=3, flag=wx.ALL,border=5)
+ self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5)
+ self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5)
+ self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5)
+
+ id, id1 = wx.NewId(), wx.NewId()
+ self.command1 = wx.Button( self.panel, id, "&Close")
+ self.command2 = wx.Button( self.panel, id1, "&Print Formats")
+ self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1)
self.panel.SetDefaultItem(self.command1)
- EVT_BUTTON( self.panel, id1, self.onClickPrint)
+ self.panel.Bind(wx.EVT_BUTTON, self.onClickPrint, self.command2)
# The following list is of the controls for the demo. Feel free to play around with
# the options!
("US Zip Code","USZIP"),
("US Zip+4","USZIPPLUS4"),
("Email Address","EMAIL"),
- ("IP Address", "(derived control wxIpAddrCtrl)")
+ ("IP Address", "(derived control IpAddrCtrl)")
]
for control in controls:
- self.sizer.Add( wxStaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wxALL)
- self.sizer.Add( wxStaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wxALL)
+ self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL)
+ self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL)
if control in controls[:-1]:
- self.sizer.Add( wxMaskedTextCtrl( self.panel, -1, "",
+ self.sizer.Add( MaskedTextCtrl( self.panel, -1, "",
autoformat = control[1],
demo = True),
- row=rowcount,col=2,flag=wxALL,border=5)
+ row=rowcount,col=2,flag=wx.ALL,border=5)
else:
- self.sizer.Add( wxIpAddrCtrl( self.panel, -1, "", demo=True ),
- row=rowcount,col=2,flag=wxALL,border=5)
+ self.sizer.Add( IpAddrCtrl( self.panel, -1, "", demo=True ),
+ row=rowcount,col=2,flag=wx.ALL,border=5)
rowcount += 1
- self.sizer.Add(self.command1, row=0, col=0, flag=wxALL, border = 5)
- self.sizer.Add(self.command2, row=0, col=1, flag=wxALL, border = 5)
+ self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5)
+ self.sizer.Add(self.command2, row=0, col=1, flag=wx.ALL, border = 5)
self.sizer.AddGrowableCol(3)
self.panel.SetSizer(self.sizer)
## ---------- ---------- ---------- ---------- ---------- ---------- ----------
if __name__ == "__main__":
- app = test()
+ app = test(False)
i=1
##
## control in the EVT_TEXT handler, and if *different*, call event.Skip()
## to propagate it down the event chain, and let the application see it.
##
-## 2. WS: wxMaskedComboBox is deficient in several areas, all having to do with the
+## 2. WS: MaskedComboBox is deficient in several areas, all having to do with the
## behavior of the underlying control that I can't fix. The problems are:
## a) The background coloring doesn't work in the text field of the control;
## instead, there's a only border around it that assumes the correct color.
## b) The control will not pass WXK_TAB to the event handler, no matter what
## I do, and there's no style wxCB_PROCESS_TAB like wxTE_PROCESS_TAB to
-## indicate that we want these events. As a result, wxMaskedComboBox
-## doesn't do the nice field-tabbing that wxMaskedTextCtrl does.
+## indicate that we want these events. As a result, MaskedComboBox
+## doesn't do the nice field-tabbing that MaskedTextCtrl does.
## c) Auto-complete had to be reimplemented for the control because programmatic
## setting of the value of the text field does not set up the auto complete
## the way that the control processing keystrokes does. (But I think I've
## implemented has its flaws, not the least of which is that due to the
## strategy that I'm using, the paste buffer is always replaced by the
## contents of the control's selection when in focus, on each keystroke;
-## this makes it impossible to paste anything into a wxMaskedComboBox
+## this makes it impossible to paste anything into a MaskedComboBox
## at the moment... :-(
## e) The other deficient behavior, likely induced by the workaround for (d),
## is that you can can't shift-left to select more than one character
## 3. WS: Controls on wxPanels don't seem to pass Shift-WXK_TAB to their
## EVT_KEY_DOWN or EVT_CHAR event handlers. Until this is fixed in
## wxWindows, shift-tab won't take you backwards through the fields of
-## a wxMaskedTextCtrl like it should. Until then Shifted arrow keys will
+## a MaskedTextCtrl like it should. Until then Shifted arrow keys will
## work like shift-tab and tab ought to.
##
## fields. Example: City validates against list of cities, or zip vs zip code list.
## 2. Allow optional monetary symbols (eg. $, pounds, etc.) at front of a "decimal"
## control.
-## 3. Fix shift-left selection for wxMaskedComboBox.
+## 3. Fix shift-left selection for MaskedComboBox.
## 5. Transform notion of "decimal control" to be less "entire control"-centric,
## so that monetary symbols can be included and still have the appropriate
## semantics. (Big job, as currently written, but would make control even
## (Reported) bugs fixed:
## 1. Right-click menu allowed "cut" operation that destroyed mask
## (was implemented by base control)
-## 2. wxMaskedComboBox didn't allow .Append() of mixed-case values; all
+## 2. MaskedComboBox didn't allow .Append() of mixed-case values; all
## got converted to lower case.
-## 3. wxMaskedComboBox selection didn't deal with spaces in values
+## 3. MaskedComboBox selection didn't deal with spaces in values
## properly when autocompleting, and didn't have a concept of "next"
## match for handling choice list duplicates.
-## 4. Size of wxMaskedComboBox was always default.
+## 4. Size of MaskedComboBox was always default.
## 5. Email address regexp allowed some "non-standard" things, and wasn't
## general enough.
-## 6. Couldn't easily reset wxMaskedComboBox contents programmatically.
+## 6. Couldn't easily reset MaskedComboBox contents programmatically.
## 7. Couldn't set emptyInvalid during construction.
## 8. Under some versions of wxPython, readonly comboboxes can apparently
## return a GetInsertionPoint() result (655535), causing masked control
## 13. Fixed a couple of coding bugs being flagged by Python2.1.
## 14. Fixed several issues with sign positioning, erasure and validity
## checking for "numeric" masked controls.
-## 15. Added validation to wxIpAddrCtrl.SetValue().
+## 15. Added validation to IpAddrCtrl.SetValue().
##
## Version 1.1
## 1. Changed calling interface to use boolean "useFixedWidthFont" (True by default)
## fixed failure to obey case conversion codes when pasting.
## 11. Implemented '0' (zero-pad) formatting code, as it wasn't being done anywhere...
## 12. Removed condition from OnDecimalPoint, so that it always truncates right on '.'
-## 13. Enhanced wxIpAddrCtrl to use right-insert fields, selection on field traversal,
+## 13. Enhanced IpAddrCtrl to use right-insert fields, selection on field traversal,
## individual field validation to prevent field values > 255, and require explicit
## tab/. to change fields.
## 14. Added handler for left double-click to select field under cursor.
## attribute, for more consistent and controllable coloring.
## 17. Added retainFieldValidation parameter, allowing top-level constraints
## such as "validRequired" to be set independently of field-level equivalent.
-## (needed in wxTimeCtrl for bounds constraints.)
+## (needed in TimeCtrl for bounds constraints.)
## 18. Refactored code a bit, cleaned up and commented code more heavily, fixed
## some of the logic for setting/resetting parameters, eg. fillChar, defaultValue,
## etc.
## than making assumptions about character width.
## 7. Fixed GetMaskParameter(), which was non-functional in previous version.
## 8. Fixed exceptions raised to provide info on which control had the error.
-## 9. Fixed bug in choice management of wxMaskedComboBox.
-## 10. Fixed bug in wxIpAddrCtrl causing traceback if field value was of
-## the form '# #'. Modified control code for wxIpAddrCtrl so that '.'
+## 9. Fixed bug in choice management of MaskedComboBox.
+## 10. Fixed bug in IpAddrCtrl causing traceback if field value was of
+## the form '# #'. Modified control code for IpAddrCtrl so that '.'
## in the middle of a field clips the rest of that field, similar to
## decimal and integer controls.
##
## is not desired in every position. Added IsDefault() function to mean "does the value
## equal the template?" and modified .IsEmpty() to mean "do all of the editable
## positions in the template == the fillChar?"
-## 10. Extracted mask logic into mixin, so we can have both wxMaskedTextCtrl and wxMaskedComboBox,
+## 10. Extracted mask logic into mixin, so we can have both MaskedTextCtrl and MaskedComboBox,
## now included.
-## 11. wxMaskedComboBox now adds the capability to validate from list of valid values.
+## 11. MaskedComboBox now adds the capability to validate from list of valid values.
## Example: City validates against list of cities, or zip vs zip code list.
## 12. Fixed oversight in EVT_TEXT handler that prevented the events from being
## passed to the next handler in the event chain, causing updates to the
## control to be invisible to the parent code.
-## 13. Added IPADDR autoformat code, and subclass wxIpAddrCtrl for controlling tabbing within
+## 13. Added IPADDR autoformat code, and subclass IpAddrCtrl for controlling tabbing within
## the control, that auto-reformats as you move between cells.
## 14. Mask characters [A,a,X,#] can now appear in the format string as literals, by using '\'.
## 15. It is now possible to specify repeating masks, e.g. #{3}-#{3}-#{14}
## 19. Enhanced tabbing logic so that tab takes you to the next field if the
## control is a multi-field control.
## 20. Added stub method called whenever the control "changes fields", that
-## can be overridden by subclasses (eg. wxIpAddrCtrl.)
+## can be overridden by subclasses (eg. IpAddrCtrl.)
## 21. Changed a lot of code to be more functionally-oriented so side-effects
## aren't as problematic when maintaining code and/or adding features.
## Eg: IsValid() now does not have side-effects; it merely reflects the
## 4. Home and End keys now supported to move cursor to beginning or end of field.
## 5. Un-signed integers and decimals now supported.
## 6. Cosmetic improvements to the demo.
-## 7. Class renamed to wxMaskedTextCtrl.
+## 7. Class renamed to MaskedTextCtrl.
## 8. Can now specify include characters that will override the basic
## controls: for example, includeChars = "@." for email addresses
## 9. Added mask character 'C' -> allow any upper or lowercase character