1 #----------------------------------------------------------------------------
3 # Authors: Jeff Childers, Will Sadkin
4 # Email: jchilders_98@yahoo.com, wsadkin@nameconnector.com
6 # Copyright: (c) 2003 by Jeff Childers, 2003
7 # Portions: (c) 2002 by Will Sadkin, 2002-2003
9 # License: wxWindows license
10 #----------------------------------------------------------------------------
12 # This was written way it is because of the lack of masked edit controls
13 # in wxWindows/wxPython.
15 # wxMaskedEdit controls are based on a suggestion made on [wxPython-Users] by
16 # Jason Hihn, and borrows liberally from Will Sadkin's original masked edit
17 # control for time entry, wxTimeCtrl (which is now rewritten using this
20 # wxMaskedEdit controls do not normally use validators, because they do
21 # careful manipulation of the cursor in the text window on each keystroke,
22 # and validation is cursor-position specific, so the control intercepts the
23 # key codes before the validator would fire. However, validators can be
24 # provided to do data transfer to the controls.
28 <b>Masked Edit Overview:
29 =====================</b>
30 <b>wxMaskedTextCtrl</b>
31 is a sublassed text control that can carefully control the user's input
32 based on a mask string you provide.
34 General usage example:
35 control = wxMaskedTextCtrl( win, -1, '', mask = '(###) ###-####')
37 The example above will create a text control that allows only numbers to be
38 entered and then only in the positions indicated in the mask by the # sign.
40 <b>wxMaskedComboBox</b>
41 is a similar subclass of wxComboBox that allows the same sort of masking,
42 but also can do auto-complete of values, and can require the value typed
43 to be in the list of choices to be colored appropriately.
46 is actually a factory function for several types of masked edit controls:
48 <b>wxMaskedTextCtrl</b> - standard masked edit text box
49 <b>wxMaskedComboBox</b> - adds combobox capabilities
50 <b>wxIpAddrCtrl</b> - adds special semantics for IP address entry
51 <b>wxTimeCtrl</b> - special subclass handling lots of types as values
52 <b>wxMaskedNumCtrl</b> - special subclass handling numeric values
54 It works by looking for a <b><i>controlType</i></b> parameter in the keyword
55 arguments of the control, to determine what kind of instance to return.
56 If not specified as a keyword argument, the default control type returned
57 will be wxMaskedTextCtrl.
59 Each of the above classes has its own set of arguments, but wxMaskedCtrl
60 provides a single "unified" interface for masked controls. Those for
61 wxMaskedTextCtrl, wxMaskedComboBox and wxIpAddrCtrl are all documented
62 below; the others have their own demo pages and interface descriptions.
63 (See end of following discussion for how to configure the wxMaskedCtrl()
64 to select the above control types.)
67 <b>INITILIZATION PARAMETERS
68 ========================
70 Allowed mask characters and function:
72 # Allow numeric only (0-9)
73 N Allow letters and numbers (0-9)
74 A Allow uppercase letters only
75 a Allow lowercase letters only
76 C Allow any letter, upper or lower
77 X Allow string.letters, string.punctuation, string.digits
78 & Allow string.punctuation only
81 These controls define these sets of characters using string.letters,
82 string.uppercase, etc. These sets are affected by the system locale
83 setting, so in order to have the masked controls accept characters
84 that are specific to your users' language, your application should
86 For example, to allow international characters to be used in the
87 above masks, you can place the following in your code as part of
88 your application's initialization code:
91 locale.setlocale(locale.LC_ALL, '')
94 Using these mask characters, a variety of template masks can be built. See
95 the demo for some other common examples include date+time, social security
96 number, etc. If any of these characters are needed as template rather
97 than mask characters, they can be escaped with \, ie. \N means "literal N".
98 (use \\ for literal backslash, as in: r'CCC\\NNN'.)
102 Masks containing only # characters and one optional decimal point
103 character are handled specially, as "numeric" controls. Such
104 controls have special handling for typing the '-' key, handling
105 the "decimal point" character as truncating the integer portion,
106 optionally allowing grouping characters and so forth.
107 There are several parameters and format codes that only make sense
108 when combined with such masks, eg. groupChar, decimalChar, and so
109 forth (see below). These allow you to construct reasonable
110 numeric entry controls.
113 Changing the mask for a control deletes any previous field classes
114 (and any associated validation or formatting constraints) for them.
116 <b>useFixedWidthFont=</b>
117 By default, masked edit controls use a fixed width font, so that
118 the mask characters are fixed within the control, regardless of
119 subsequent modifications to the value. Set to False if having
120 the control font be the same as other controls is required.
124 These other properties can be passed to the class when instantiating it:
125 Formatcodes are specified as a string of single character formatting
126 codes that modify behavior of the control:
130 R Right-align field(s)
131 r Right-insert in field(s) (implies R)
132 < Stay in field until explicit navigation out of it
134 > Allow insert/delete within partially filled fields (as
135 opposed to the default "overwrite" mode for fixed-width
136 masked edit controls.) This allows single-field controls
137 or each field within a multi-field control to optionally
138 behave more like standard text controls.
139 (See EMAIL or phone number autoformat examples.)
141 <i>Note: This also governs whether backspace/delete operations
142 shift contents of field to right of cursor, or just blank the
145 Also, when combined with 'r', this indicates that the field
146 or control allows right insert anywhere within the current
147 non-empty value in the field. (Otherwise right-insert behavior
148 is only performed to when the entire right-insertable field is
149 selected or the cursor is at the right edge of the field.</i>
152 , Allow grouping character in integer fields of numeric controls
153 and auto-group/regroup digits (if the result fits) when leaving
154 such a field. (If specified, .SetValue() will attempt to
156 ',' is also the default grouping character. To change the
157 grouping character and/or decimal character, use the groupChar
158 and decimalChar parameters, respectively.
159 Note: typing the "decimal point" character in such fields will
160 clip the value to that left of the cursor for integer
161 fields of controls with "integer" or "floating point" masks.
162 If the ',' format code is specified, this will also cause the
163 resulting digits to be regrouped properly, using the current
165 - Prepend and reserve leading space for sign to mask and allow
166 signed values (negative #s shown in red by default.) Can be
167 used with argument useParensForNegatives (see below.)
168 0 integer fields get leading zeros
171 F Auto-Fit: the control calulates its size from
172 the length of the template mask
173 V validate entered chars against validRegex before allowing them
174 to be entered vs. being allowed by basic mask and then having
175 the resulting value just colored as invalid.
176 (See USSTATE autoformat demo for how this can be used.)
177 S select entire field when navigating to new field
181 These controls have two options for the initial state of the control.
182 If a blank control with just the non-editable characters showing
183 is desired, simply leave the constructor variable fillChar as its
184 default (' '). If you want some other character there, simply
185 change the fillChar to that value. Note: changing the control's fillChar
186 will implicitly reset all of the fields' fillChars to this value.
188 If you need different default characters in each mask position,
189 you can specify a defaultValue parameter in the constructor, or
190 set them for each field individually.
191 This value must satisfy the non-editable characters of the mask,
192 but need not conform to the replaceable characters.
196 These parameters govern what character is used to group numbers
197 and is used to indicate the decimal point for numeric format controls.
198 The default groupChar is ',', the default decimalChar is '.'
199 By changing these, you can customize the presentation of numbers
201 eg: formatcodes = ',', groupChar="'" allows 12'345.34
202 formatcodes = ',', groupChar='.', decimalChar=',' allows 12.345,34
204 <b>shiftDecimalChar=</b>
205 The default "shiftDecimalChar" (used for "backwards-tabbing" until
206 shift-tab is fixed in wxPython) is '>' (for QUERTY keyboards.) for
207 other keyboards, you may want to customize this, eg '?' for shift ',' on
208 AZERTY keyboards, ':' or ';' for other European keyboards, etc.
210 <b>useParensForNegatives=False</b>
211 This option can be used with signed numeric format controls to
212 indicate signs via () rather than '-'.
214 <b>autoSelect=False</b>
215 This option can be used to have a field or the control try to
216 auto-complete on each keystroke if choices have been specified.
218 <b>autoCompleteKeycodes=[]</b>
219 By default, DownArrow, PageUp and PageDown will auto-complete a
220 partially entered field. Shift-DownArrow, Shift-UpArrow, PageUp
221 and PageDown will also auto-complete, but if the field already
222 contains a matched value, these keys will cycle through the list
223 of choices forward or backward as appropriate. Shift-Up and
224 Shift-Down also take you to the next/previous field after any
225 auto-complete action.
227 Additional auto-complete keys can be specified via this parameter.
228 Any keys so specified will act like PageDown.
232 <b>Validating User Input:
233 ======================</b>
234 There are a variety of initialization parameters that are used to validate
235 user input. These parameters can apply to the control as a whole, and/or
236 to individual fields:
238 excludeChars= A string of characters to exclude even if otherwise allowed
239 includeChars= A string of characters to allow even if otherwise disallowed
240 validRegex= Use a regular expression to validate the contents of the text box
241 validRange= Pass a rangeas list (low,high) to limit numeric fields/values
242 choices= A list of strings that are allowed choices for the control.
243 choiceRequired= value must be member of choices list
244 compareNoCase= Perform case-insensitive matching when validating against list
245 <i>Note: for wxMaskedComboBox, this defaults to True.</i>
246 emptyInvalid= Boolean indicating whether an empty value should be considered invalid
248 validFunc= A function to call of the form: bool = func(candidate_value)
249 which will return True if the candidate_value satisfies some
250 external criteria for the control in addition to the the
251 other validation, or False if not. (This validation is
252 applied last in the chain of validations.)
254 validRequired= Boolean indicating whether or not keys that are allowed by the
255 mask, but result in an invalid value are allowed to be entered
256 into the control. Setting this to True implies that a valid
257 default value is set for the control.
259 retainFieldValidation=
260 False by default; if True, this allows individual fields to
261 retain their own validation constraints independently of any
262 subsequent changes to the control's overall parameters.
264 validator= Validators are not normally needed for masked controls, because
265 of the nature of the validation and control of input. However,
266 you can supply one to provide data transfer routines for the
270 <b>Coloring Behavior:
271 ==================</b>
272 The following parameters have been provided to allow you to change the default
273 coloring behavior of the control. These can be set at construction, or via
274 the .SetCtrlParameters() function. Pass a color as string e.g. 'Yellow':
276 emptyBackgroundColour= Control Background color when identified as empty. Default=White
277 invalidBackgroundColour= Control Background color when identified as Not valid. Default=Yellow
278 validBackgroundColour= Control Background color when identified as Valid. Default=white
281 The following parameters control the default foreground color coloring behavior of the
282 control. Pass a color as string e.g. 'Yellow':
283 foregroundColour= Control foreground color when value is not negative. Default=Black
284 signedForegroundColour= Control foreground color when value is negative. Default=Red
289 Each part of the mask that allows user input is considered a field. The fields
290 are represented by their own class instances. You can specify field-specific
291 constraints by constructing or accessing the field instances for the control
292 and then specifying those constraints via parameters.
295 This parameter allows you to specify Field instances containing
296 constraints for the individual fields of a control, eg: local
297 choice lists, validation rules, functions, regexps, etc.
298 It can be either an ordered list or a dictionary. If a list,
299 the fields will be applied as fields 0, 1, 2, etc.
300 If a dictionary, it should be keyed by field index.
301 the values should be a instances of maskededit.Field.
303 Any field not represented by the list or dictionary will be
304 implicitly created by the control.
307 fields = [ Field(formatcodes='_r'), Field('choices=['a', 'b', 'c']) ]
310 1: ( Field(formatcodes='_R', choices=['a', 'b', 'c']),
311 3: ( Field(choices=['01', '02', '03'], choiceRequired=True)
314 The following parameters are available for individual fields, with the
315 same semantics as for the whole control but applied to the field in question:
317 fillChar # if set for a field, it will override the control's fillChar for that field
318 groupChar # if set for a field, it will override the control's default
319 defaultValue # sets field-specific default value; overrides any default from control
320 compareNoCase # overrides control's settings
321 emptyInvalid # determines whether field is required to be filled at all times
322 validRequired # if set, requires field to contain valid value
324 If any of the above parameters are subsequently specified for the control as a
325 whole, that new value will be propagated to each field, unless the
326 retainFieldValidation control-level parameter is set.
328 formatcodes # Augments control's settings
334 choiceRequired # ' ' '
339 <b>Control Class Functions:
340 ========================
341 .GetPlainValue(value=None)</b>
342 Returns the value specified (or the control's text value
343 not specified) without the formatting text.
344 In the example above, might return phone no='3522640075',
345 whereas control.GetValue() would return '(352) 264-0075'
347 Returns the control's value to its default, and places the
348 cursor at the beginning of the control.
350 Does "smart replacement" of passed value into the control, as does
351 the .Paste() method. As with other text entry controls, the
352 .SetValue() text replacement begins at left-edge of the control,
353 with missing mask characters inserted as appropriate.
354 .SetValue will also adjust integer, float or date mask entry values,
355 adding commas, auto-completing years, etc. as appropriate.
356 For "right-aligned" numeric controls, it will also now automatically
357 right-adjust any value whose length is less than the width of the
358 control before attempting to set the value.
359 If a value does not follow the format of the control's mask, or will
360 not fit into the control, a ValueError exception will be raised.
362 mask = '(###) ###-####'
363 .SetValue('1234567890') => '(123) 456-7890'
364 .SetValue('(123)4567890') => '(123) 456-7890'
365 .SetValue('(123)456-7890') => '(123) 456-7890'
366 .SetValue('123/4567-890') => illegal paste; ValueError
368 mask = '#{6}.#{2}', formatcodes = '_,-',
369 .SetValue('111') => ' 111 . '
370 .SetValue(' %9.2f' % -111.12345 ) => ' -111.12'
371 .SetValue(' %9.2f' % 1234.00 ) => ' 1,234.00'
372 .SetValue(' %9.2f' % -1234567.12345 ) => insufficient room; ValueError
374 mask = '#{6}.#{2}', formatcodes = '_,-R' # will right-adjust value for right-aligned control
375 .SetValue('111') => padded value misalignment ValueError: " 111" will not fit
376 .SetValue('%.2f' % 111 ) => ' 111.00'
377 .SetValue('%.2f' % -111.12345 ) => ' -111.12'
380 <b>.IsValid(value=None)</b>
381 Returns True if the value specified (or the value of the control
382 if not specified) passes validation tests
383 <b>.IsEmpty(value=None)</b>
384 Returns True if the value specified (or the value of the control
385 if not specified) is equal to an "empty value," ie. all
386 editable characters == the fillChar for their respective fields.
387 <b>.IsDefault(value=None)</b>
388 Returns True if the value specified (or the value of the control
389 if not specified) is equal to the initial value of the control.
392 Recolors the control as appropriate to its current settings.
394 <b>.SetCtrlParameters(**kwargs)</b>
395 This function allows you to set up and/or change the control parameters
396 after construction; it takes a list of key/value pairs as arguments,
397 where the keys can be any of the mask-specific parameters in the constructor.
399 ctl = wxMaskedTextCtrl( self, -1 )
400 ctl.SetCtrlParameters( mask='###-####',
401 defaultValue='555-1212',
404 <b>.GetCtrlParameter(parametername)</b>
405 This function allows you to retrieve the current value of a parameter
408 <b><i>Note:</i></b> Each of the control parameters can also be set using its
409 own Set and Get function. These functions follow a regular form:
410 All of the parameter names start with lower case; for their
411 corresponding Set/Get function, the parameter name is capitalized.
412 Eg: ctl.SetMask('###-####')
413 ctl.SetDefaultValue('555-1212')
414 ctl.GetChoiceRequired()
417 <b>.SetFieldParameters(field_index, **kwargs)</b>
418 This function allows you to specify change individual field
419 parameters after construction. (Indices are 0-based.)
421 <b>.GetFieldParameter(field_index, parametername)</b>
422 Allows the retrieval of field parameters after construction
425 The control detects certain common constructions. In order to use the signed feature
426 (negative numbers and coloring), the mask has to be all numbers with optionally one
427 decimal point. Without a decimal (e.g. '######', the control will treat it as an integer
428 value. With a decimal (e.g. '###.##'), the control will act as a floating point control
429 (i.e. press decimal to 'tab' to the decimal position). Pressing decimal in the
430 integer control truncates the value.
433 Check your controls by calling each control's .IsValid() function and the
434 .IsEmpty() function to determine which controls have been a) filled in and
435 b) filled in properly.
438 Regular expression validations can be used flexibly and creatively.
439 Take a look at the demo; the zip-code validation succeeds as long as the
440 first five numerals are entered. the last four are optional, but if
441 any are entered, there must be 4 to be valid.
443 <B>wxMaskedCtrl Configuration
444 ==========================</B>
445 wxMaskedCtrl works by looking for a special <b><i>controlType</i></b>
446 parameter in the variable arguments of the control, to determine
447 what kind of instance to return.
448 controlType can be one of:
450 controlTypes.MASKEDTEXT
451 controlTypes.MASKEDCOMBO
456 These constants are also available individually, ie, you can
457 use either of the following:
459 from wxPython.wx.lib.maskedctrl import wxMaskedCtrl, controlTypes
460 from wxPython.wx.lib.maskedctrl import wxMaskedCtrl, MASKEDCOMBO, MASKEDTEXT, NUMBER
462 If not specified as a keyword argument, the default controlType is
467 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
472 All methods of the Mixin that are not meant to be exposed to the external
473 interface are prefaced with '_'. Those functions that are primarily
474 intended to be internal subroutines subsequently start with a lower-case
475 letter; those that are primarily intended to be used and/or overridden
476 by derived subclasses start with a capital letter.
478 The following methods must be used and/or defined when deriving a control
479 from wxMaskedEditMixin. NOTE: if deriving from a *masked edit* control
480 (eg. class wxIpAddrCtrl(wxMaskedTextCtrl) ), then this is NOT necessary,
481 as it's already been done for you in the base class.
484 This function must be called after the associated base
485 control has been initialized in the subclass __init__
486 function. It sets the initial value of the control,
487 either to the value specified if non-empty, the
488 default value if specified, or the "template" for
489 the empty control as necessary. It will also set/reset
490 the font if necessary and apply formatting to the
491 control at this time.
495 Each class derived from wxMaskedEditMixin must define
496 the function for getting the start and end of the
497 current text selection. The reason for this is
498 that not all controls have the same function name for
499 doing this; eg. wxTextCtrl uses .GetSelection(),
500 whereas we had to write a .GetMark() function for
501 wxComboBox, because .GetSelection() for the control
502 gets the currently selected list item from the combo
503 box, and the control doesn't (yet) natively provide
504 a means of determining the text selection.
507 Similarly to _GetSelection, each class derived from
508 wxMaskedEditMixin must define the function for setting
509 the start and end of the current text selection.
510 (eg. .SetSelection() for wxMaskedTextCtrl, and .SetMark() for
513 ._GetInsertionPoint()
514 ._SetInsertionPoint()
516 For consistency, and because the mixin shouldn't rely
517 on fixed names for any manipulations it does of any of
518 the base controls, we require each class derived from
519 wxMaskedEditMixin to define these functions as well.
522 ._SetValue() REQUIRED
523 Each class derived from wxMaskedEditMixin must define
524 the functions used to get and set the raw value of the
526 This is necessary so that recursion doesn't take place
527 when setting the value, and so that the mixin can
528 call the appropriate function after doing all its
529 validation and manipulation without knowing what kind
530 of base control it was mixed in with. To handle undo
531 functionality, the ._SetValue() must record the current
532 selection prior to setting the value.
538 Each class derived from wxMaskedEditMixin must redefine
539 these functions to call the _Cut(), _Paste(), _Undo()
540 and _SetValue() methods, respectively for the control,
541 so as to prevent programmatic corruption of the control's
542 value. This must be done in each derivation, as the
543 mixin cannot itself override a member of a sibling class.
546 Each class derived from wxMaskedEditMixin must define
547 the function used to refresh the base control.
550 Each class derived from wxMaskedEditMixin must redefine
551 this function so that it checks the validity of the
552 control (via self._CheckValid) and then refreshes
553 control using the base class method.
555 ._IsEditable() REQUIRED
556 Each class derived from wxMaskedEditMixin must define
557 the function used to determine if the base control is
558 editable or not. (For wxMaskedComboBox, this has to
559 be done with code, rather than specifying the proper
560 function in the base control, as there isn't one...)
561 ._CalcSize() REQUIRED
562 Each class derived from wxMaskedEditMixin must define
563 the function used to determine how wide the control
564 should be given the mask. (The mixin function
565 ._calcSize() provides a baseline estimate.)
570 Event handlers are "chained", and wxMaskedEditMixin usually
571 swallows most of the events it sees, thereby preventing any other
572 handlers from firing in the chain. It is therefore required that
573 each class derivation using the mixin to have an option to hook up
574 the event handlers itself or forego this operation and let a
575 subclass of the masked control do so. For this reason, each
576 subclass should probably include the following code:
578 if setupEventHandling:
579 ## Setup event handlers
580 EVT_SET_FOCUS( self, self._OnFocus ) ## defeat automatic full selection
581 EVT_KILL_FOCUS( self, self._OnKillFocus ) ## run internal validator
582 EVT_LEFT_DCLICK(self, self._OnDoubleClick) ## select field under cursor on dclick
583 EVT_RIGHT_UP(self, self._OnContextMenu ) ## bring up an appropriate context menu
584 EVT_KEY_DOWN( self, self._OnKeyDown ) ## capture control events not normally seen, eg ctrl-tab.
585 EVT_CHAR( self, self._OnChar ) ## handle each keypress
586 EVT_TEXT( self, self.GetId(), self._OnTextChange ) ## color control appropriately & keep
587 ## track of previous value for undo
589 where setupEventHandling is an argument to its constructor.
591 These 5 handlers must be "wired up" for the wxMaskedEdit
592 control to provide default behavior. (The setupEventHandling
593 is an argument to wxMaskedTextCtrl and wxMaskedComboBox, so
594 that controls derived from *them* may replace one of these
595 handlers if they so choose.)
597 If your derived control wants to preprocess events before
598 taking action, it should then set up the event handling itself,
599 so it can be first in the event handler chain.
602 The following routines are available to facilitate changing
603 the default behavior of wxMaskedEdit controls:
605 ._SetKeycodeHandler(keycode, func)
606 ._SetKeyHandler(char, func)
607 Use to replace default handling for any given keycode.
608 func should take the key event as argument and return
609 False if no further action is required to handle the
611 self._SetKeycodeHandler(WXK_UP, self.IncrementValue)
612 self._SetKeyHandler('-', self._OnChangeSign)
614 "Navigation" keys are assumed to change the cursor position, and
615 therefore don't cause automatic motion of the cursor as insertable
618 ._AddNavKeycode(keycode, handler=None)
619 ._AddNavKey(char, handler=None)
620 Allows controls to specify other keys (and optional handlers)
621 to be treated as navigational characters. (eg. '.' in wxIpAddrCtrl)
623 ._GetNavKeycodes() Returns the current list of navigational keycodes.
625 ._SetNavKeycodes(key_func_tuples)
626 Allows replacement of the current list of keycode
627 processed as navigation keys, and bind associated
628 optional keyhandlers. argument is a list of key/handler
629 tuples. Passing a value of None for the handler in a
630 given tuple indicates that default processing for the key
633 ._FindField(pos) Returns the Field object associated with this position
636 ._FindFieldExtent(pos, getslice=False, value=None)
637 Returns edit_start, edit_end of the field corresponding
638 to the specified position within the control, and
639 optionally also returns the current contents of that field.
640 If value is specified, it will retrieve the slice the corresponding
641 slice from that value, rather than the current value of the
645 This is, the function that gets called for a given position
646 whenever the cursor is adjusted to leave a given field.
647 By default, it adjusts the year in date fields if mask is a date,
648 It can be overridden by a derived class to
649 adjust the value of the control at that time.
650 (eg. wxIpAddrCtrl reformats the address in this way.)
652 ._Change() Called by internal EVT_TEXT handler. Return False to force
653 skip of the normal class change event.
654 ._Keypress(key) Called by internal EVT_CHAR handler. Return False to force
655 skip of the normal class keypress event.
656 ._LostFocus() Called by internal EVT_KILL_FOCUS handler
659 This is the default EVT_KEY_DOWN routine; it just checks for
660 "navigation keys", and if event.ControlDown(), it fires the
661 mixin's _OnChar() routine, as such events are not always seen
662 by the "cooked" EVT_CHAR routine.
664 ._OnChar(event) This is the main EVT_CHAR handler for the
667 The following routines are used to handle standard actions
669 _OnArrow(event) used for arrow navigation events
670 _OnCtrl_A(event) 'select all'
671 _OnCtrl_C(event) 'copy' (uses base control function, as copy is non-destructive)
672 _OnCtrl_S(event) 'save' (does nothing)
673 _OnCtrl_V(event) 'paste' - calls _Paste() method, to do smart paste
674 _OnCtrl_X(event) 'cut' - calls _Cut() method, to "erase" selection
675 _OnCtrl_Z(event) 'undo' - resets value to previous value (if any)
677 _OnChangeField(event) primarily used for tab events, but can be
678 used for other keys (eg. '.' in wxIpAddrCtrl)
680 _OnErase(event) used for backspace and delete
686 from wxPython
.wx
import *
687 import string
, re
, copy
, difflib
, types
689 from wxPython
.tools
.dbg
import Logger
693 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
695 ## Constants for identifying control keys and classes of keys:
697 WXK_CTRL_A
= (ord('A')+1) - ord('A') ## These keys are not already defined in wx
698 WXK_CTRL_C
= (ord('C')+1) - ord('A')
699 WXK_CTRL_S
= (ord('S')+1) - ord('A')
700 WXK_CTRL_V
= (ord('V')+1) - ord('A')
701 WXK_CTRL_X
= (ord('X')+1) - ord('A')
702 WXK_CTRL_Z
= (ord('Z')+1) - ord('A')
704 nav
= (WXK_BACK
, WXK_LEFT
, WXK_RIGHT
, WXK_UP
, WXK_DOWN
, WXK_TAB
, WXK_HOME
, WXK_END
, WXK_RETURN
, WXK_PRIOR
, WXK_NEXT
)
705 control
= (WXK_BACK
, WXK_DELETE
, WXK_CTRL_A
, WXK_CTRL_C
, WXK_CTRL_S
, WXK_CTRL_V
, WXK_CTRL_X
, WXK_CTRL_Z
)
708 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
710 ## Constants for masking. This is where mask characters
712 ## maskchars used to identify valid mask characters from all others
713 ## #- allow numeric 0-9 only
714 ## A- allow uppercase only. Combine with forceupper to force lowercase to upper
715 ## a- allow lowercase only. Combine with forcelower to force upper to lowercase
716 ## X- allow any character (string.letters, string.punctuation, string.digits)
717 ## Note: locale settings affect what "uppercase", lowercase, etc comprise.
719 maskchars
= ("#","A","a","X","C","N", '&')
721 months
= '(01|02|03|04|05|06|07|08|09|10|11|12)'
722 charmonths
= '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)'
723 charmonths_dict
= {'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
724 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12}
726 days
= '(01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)'
727 hours
= '(0\d| \d|1[012])'
728 milhours
= '(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23)'
729 minutes
= """(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|\
730 16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|\
731 36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|\
734 am_pm_exclude
= 'BCDEFGHIJKLMNOQRSTUVWXYZ\x8a\x8c\x8e\x9f\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde'
736 states
= "AL,AK,AZ,AR,CA,CO,CT,DE,DC,FL,GA,GU,HI,ID,IL,IN,IA,KS,KY,LA,MA,ME,MD,MI,MN,MS,MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,OH,OK,OR,PA,PR,RI,SC,SD,TN,TX,UT,VA,VT,VI,WA,WV,WI,WY".split(',')
738 state_names
= ['Alabama','Alaska','Arizona','Arkansas',
739 'California','Colorado','Connecticut',
740 'Delaware','District of Columbia',
741 'Florida','Georgia','Hawaii',
742 'Idaho','Illinois','Indiana','Iowa',
743 'Kansas','Kentucky','Louisiana',
744 'Maine','Maryland','Massachusetts','Michigan',
745 'Minnesota','Mississippi','Missouri','Montana',
746 'Nebraska','Nevada','New Hampshire','New Jersey',
747 'New Mexico','New York','North Carolina','North Dakokta',
748 'Ohio','Oklahoma','Oregon',
749 'Pennsylvania','Puerto Rico','Rhode Island',
750 'South Carolina','South Dakota',
751 'Tennessee','Texas','Utah',
752 'Vermont','Virginia',
753 'Washington','West Virginia',
754 'Wisconsin','Wyoming']
756 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
758 ## The following dictionary defines the current set of autoformats:
762 'mask': "(###) ###-#### x:###",
763 'formatcodes': 'F^->',
764 'validRegex': "^\(\d{3}\) \d{3}-\d{4}",
765 'description': "Phone Number w/opt. ext"
768 'mask': "###-###-#### x:###",
769 'formatcodes': 'F^->',
770 'validRegex': "^\d{3}-\d{3}-\d{4}",
771 'description': "Phone Number\n (w/hyphens and opt. ext)"
774 'mask': "(###) ###-####",
775 'formatcodes': 'F^->',
776 'validRegex': "^\(\d{3}\) \d{3}-\d{4}",
777 'description': "Phone Number only"
780 'mask': "###-###-####",
781 'formatcodes': 'F^->',
782 'validRegex': "^\d{3}-\d{3}-\d{4}",
783 'description': "Phone Number\n(w/hyphens)"
787 'formatcodes': 'F!V',
788 'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string
.join(states
,'|'),
790 'choiceRequired': True,
791 'description': "US State Code"
794 'mask': "ACCCCCCCCCCCCCCCCCCC",
796 'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string
.join(state_names
,'|'),
797 'choices': state_names
,
798 'choiceRequired': True,
799 'description': "US State Name"
802 "USDATETIMEMMDDYYYY/HHMMSS": {
803 'mask': "##/##/#### ##:##:## AM",
804 'excludeChars': am_pm_exclude
,
805 'formatcodes': 'DF!',
806 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
807 'description': "US Date + Time"
809 "USDATETIMEMMDDYYYY-HHMMSS": {
810 'mask': "##-##-#### ##:##:## AM",
811 'excludeChars': am_pm_exclude
,
812 'formatcodes': 'DF!',
813 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
814 'description': "US Date + Time\n(w/hypens)"
816 "USDATEMILTIMEMMDDYYYY/HHMMSS": {
817 'mask': "##/##/#### ##:##:##",
819 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
820 'description': "US Date + Military Time"
822 "USDATEMILTIMEMMDDYYYY-HHMMSS": {
823 'mask': "##-##-#### ##:##:##",
825 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
826 'description': "US Date + Military Time\n(w/hypens)"
828 "USDATETIMEMMDDYYYY/HHMM": {
829 'mask': "##/##/#### ##:## AM",
830 'excludeChars': am_pm_exclude
,
831 'formatcodes': 'DF!',
832 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
833 'description': "US Date + Time\n(without seconds)"
835 "USDATEMILTIMEMMDDYYYY/HHMM": {
836 'mask': "##/##/#### ##:##",
838 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
,
839 'description': "US Date + Military Time\n(without seconds)"
841 "USDATETIMEMMDDYYYY-HHMM": {
842 'mask': "##-##-#### ##:## AM",
843 'excludeChars': am_pm_exclude
,
844 'formatcodes': 'DF!',
845 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
846 'description': "US Date + Time\n(w/hypens and w/o secs)"
848 "USDATEMILTIMEMMDDYYYY-HHMM": {
849 'mask': "##-##-#### ##:##",
851 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + milhours
+ ':' + minutes
,
852 'description': "US Date + Military Time\n(w/hyphens and w/o seconds)"
855 'mask': "##/##/####",
857 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4}',
858 'description': "US Date\n(MMDDYYYY)"
863 'validRegex': '^' + months
+ '/' + days
+ '/\d\d',
864 'description': "US Date\n(MMDDYY)"
867 'mask': "##-##-####",
869 'validRegex': '^' + months
+ '-' + days
+ '-' +'\d{4}',
870 'description': "MM-DD-YYYY"
874 'mask': "####/##/##",
876 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
,
877 'description': "YYYY/MM/DD"
880 'mask': "####.##.##",
882 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
,
883 'description': "YYYY.MM.DD"
886 'mask': "##/##/####",
888 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4}',
889 'description': "DD/MM/YYYY"
892 'mask': "##.##.####",
894 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4}',
895 'description': "DD.MM.YYYY"
897 "EUDATEDDMMMYYYY.": {
898 'mask': "##.CCC.####",
900 'validRegex': '^' + days
+ '.' + charmonths
+ '.' + '\d{4}',
901 'description': "DD.Month.YYYY"
903 "EUDATEDDMMMYYYY/": {
904 'mask': "##/CCC/####",
906 'validRegex': '^' + days
+ '/' + charmonths
+ '/' + '\d{4}',
907 'description': "DD/Month/YYYY"
910 "EUDATETIMEYYYYMMDD/HHMMSS": {
911 'mask': "####/##/## ##:##:## AM",
912 'excludeChars': am_pm_exclude
,
913 'formatcodes': 'DF!',
914 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
915 'description': "YYYY/MM/DD HH:MM:SS"
917 "EUDATETIMEYYYYMMDD.HHMMSS": {
918 'mask': "####.##.## ##:##:## AM",
919 'excludeChars': am_pm_exclude
,
920 'formatcodes': 'DF!',
921 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
922 'description': "YYYY.MM.DD HH:MM:SS"
924 "EUDATETIMEDDMMYYYY/HHMMSS": {
925 'mask': "##/##/#### ##:##:## AM",
926 'excludeChars': am_pm_exclude
,
927 'formatcodes': 'DF!',
928 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
929 'description': "DD/MM/YYYY HH:MM:SS"
931 "EUDATETIMEDDMMYYYY.HHMMSS": {
932 'mask': "##.##.#### ##:##:## AM",
933 'excludeChars': am_pm_exclude
,
934 'formatcodes': 'DF!',
935 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
936 'description': "DD.MM.YYYY HH:MM:SS"
939 "EUDATETIMEYYYYMMDD/HHMM": {
940 'mask': "####/##/## ##:## AM",
941 'excludeChars': am_pm_exclude
,
942 'formatcodes': 'DF!',
943 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + hours
+ ':' + minutes
+ ' (A|P)M',
944 'description': "YYYY/MM/DD HH:MM"
946 "EUDATETIMEYYYYMMDD.HHMM": {
947 'mask': "####.##.## ##:## AM",
948 'excludeChars': am_pm_exclude
,
949 'formatcodes': 'DF!',
950 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + hours
+ ':' + minutes
+ ' (A|P)M',
951 'description': "YYYY.MM.DD HH:MM"
953 "EUDATETIMEDDMMYYYY/HHMM": {
954 'mask': "##/##/#### ##:## AM",
955 'excludeChars': am_pm_exclude
,
956 'formatcodes': 'DF!',
957 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
958 'description': "DD/MM/YYYY HH:MM"
960 "EUDATETIMEDDMMYYYY.HHMM": {
961 'mask': "##.##.#### ##:## AM",
962 'excludeChars': am_pm_exclude
,
963 'formatcodes': 'DF!',
964 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
965 'description': "DD.MM.YYYY HH:MM"
968 "EUDATEMILTIMEYYYYMMDD/HHMMSS": {
969 'mask': "####/##/## ##:##:##",
971 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + milhours
+ ':' + minutes
+ ':' + seconds
,
972 'description': "YYYY/MM/DD Mil. Time"
974 "EUDATEMILTIMEYYYYMMDD.HHMMSS": {
975 'mask': "####.##.## ##:##:##",
977 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + milhours
+ ':' + minutes
+ ':' + seconds
,
978 'description': "YYYY.MM.DD Mil. Time"
980 "EUDATEMILTIMEDDMMYYYY/HHMMSS": {
981 'mask': "##/##/#### ##:##:##",
983 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
984 'description': "DD/MM/YYYY Mil. Time"
986 "EUDATEMILTIMEDDMMYYYY.HHMMSS": {
987 'mask': "##.##.#### ##:##:##",
989 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
990 'description': "DD.MM.YYYY Mil. Time"
992 "EUDATEMILTIMEYYYYMMDD/HHMM": {
993 'mask': "####/##/## ##:##",
994 'formatcodes': 'DF','validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + milhours
+ ':' + minutes
,
995 'description': "YYYY/MM/DD Mil. Time\n(w/o seconds)"
997 "EUDATEMILTIMEYYYYMMDD.HHMM": {
998 'mask': "####.##.## ##:##",
1000 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + milhours
+ ':' + minutes
,
1001 'description': "YYYY.MM.DD Mil. Time\n(w/o seconds)"
1003 "EUDATEMILTIMEDDMMYYYY/HHMM": {
1004 'mask': "##/##/#### ##:##",
1005 'formatcodes': 'DF',
1006 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
,
1007 'description': "DD/MM/YYYY Mil. Time\n(w/o seconds)"
1009 "EUDATEMILTIMEDDMMYYYY.HHMM": {
1010 'mask': "##.##.#### ##:##",
1011 'formatcodes': 'DF',
1012 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + milhours
+ ':' + minutes
,
1013 'description': "DD.MM.YYYY Mil. Time\n(w/o seconds)"
1017 'mask': "##:##:## AM",
1018 'excludeChars': am_pm_exclude
,
1019 'formatcodes': 'TF!',
1020 'validRegex': '^' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
1021 'description': "HH:MM:SS (A|P)M\n(see wxTimeCtrl)"
1025 'excludeChars': am_pm_exclude
,
1026 'formatcodes': 'TF!',
1027 'validRegex': '^' + hours
+ ':' + minutes
+ ' (A|P)M',
1028 'description': "HH:MM (A|P)M\n(see wxTimeCtrl)"
1032 'formatcodes': 'TF',
1033 'validRegex': '^' + milhours
+ ':' + minutes
+ ':' + seconds
,
1034 'description': "Military HH:MM:SS\n(see wxTimeCtrl)"
1038 'formatcodes': 'TF',
1039 'validRegex': '^' + milhours
+ ':' + minutes
,
1040 'description': "Military HH:MM\n(see wxTimeCtrl)"
1043 'mask': "###-##-####",
1045 'validRegex': "\d{3}-\d{2}-\d{4}",
1046 'description': "Social Sec#"
1049 'mask': "####-####-####-####",
1051 'validRegex': "\d{4}-\d{4}-\d{4}-\d{4}",
1052 'description': "Credit Card"
1057 'validRegex': "^" + months
+ "/\d\d",
1058 'description': "Expiration MM/YY"
1063 'validRegex': "^\d{5}",
1064 'description': "US 5-digit zip code"
1067 'mask': "#####-####",
1069 'validRegex': "\d{5}-(\s{4}|\d{4})",
1070 'description': "US zip+4 code"
1075 'validRegex': "^0.\d\d",
1076 'description': "Percentage"
1081 'validRegex': "^[1-9]{1} |[1-9][0-9] |1[0|1|2][0-9]",
1082 'description': "Age"
1085 'mask': "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
1086 'excludeChars': " \\/*&%$#!+='\"",
1087 'formatcodes': "F>",
1088 'validRegex': "^\w+([\-\.]\w+)*@((([a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*\.)+)[a-zA-Z]{2,4}|\[(\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}\]) *$",
1089 'description': "Email address"
1092 'mask': "###.###.###.###",
1093 'formatcodes': 'F_Sr',
1094 '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}",
1095 'description': "IP Address\n(see wxIpAddrCtrl)"
1099 # build demo-friendly dictionary of descriptions of autoformats
1101 for key
, value
in masktags
.items():
1102 autoformats
.append((key
, value
['description']))
1105 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
1109 'index': None, ## which field of mask; set by parent control.
1110 'mask': "", ## mask chars for this field
1111 'extent': (), ## (edit start, edit_end) of field; set by parent control.
1112 'formatcodes': "", ## codes indicating formatting options for the control
1113 'fillChar': ' ', ## used as initial value for each mask position if initial value is not given
1114 'groupChar': ',', ## used with numeric fields; indicates what char groups 3-tuple digits
1115 'decimalChar': '.', ## used with numeric fields; indicates what char separates integer from fraction
1116 'shiftDecimalChar': '>', ## used with numeric fields, indicates what is above the decimal point char on keyboard
1117 'useParensForNegatives': False, ## used with numeric fields, indicates that () should be used vs. - to show negative numbers.
1118 'defaultValue': "", ## use if you want different positional defaults vs. all the same fillChar
1119 'excludeChars': "", ## optional string of chars to exclude even if main mask type does
1120 'includeChars': "", ## optional string of chars to allow even if main mask type doesn't
1121 'validRegex': "", ## optional regular expression to use to validate the control
1122 'validRange': (), ## Optional hi-low range for numerics
1123 'choices': [], ## Optional list for character expressions
1124 'choiceRequired': False, ## If choices supplied this specifies if valid value must be in the list
1125 'compareNoCase': False, ## Optional flag to indicate whether or not to use case-insensitive list search
1126 'autoSelect': False, ## Set to True to try auto-completion on each keystroke:
1127 'validFunc': None, ## Optional function for defining additional, possibly dynamic validation constraints on contrl
1128 'validRequired': False, ## Set to True to disallow input that results in an invalid value
1129 'emptyInvalid': False, ## Set to True to make EMPTY = INVALID
1130 'description': "", ## primarily for autoformats, but could be useful elsewhere
1133 # This list contains all parameters that when set at the control level should
1134 # propagate down to each field:
1135 propagating_params
= ('fillChar', 'groupChar', 'decimalChar','useParensForNegatives',
1136 'compareNoCase', 'emptyInvalid', 'validRequired')
1138 def __init__(self
, **kwargs
):
1140 This is the "constructor" for setting up parameters for fields.
1141 a field_index of -1 is used to indicate "the entire control."
1143 ## dbg('Field::Field', indent=1)
1144 # Validate legitimate set of parameters:
1145 for key
in kwargs
.keys():
1146 if key
not in Field
.valid_params
.keys():
1148 raise TypeError('invalid parameter "%s"' % (key
))
1150 # Set defaults for each parameter for this instance, and fully
1151 # populate initial parameter list for configuration:
1152 for key
, value
in Field
.valid_params
.items():
1153 setattr(self
, '_' + key
, copy
.copy(value
))
1154 if not kwargs
.has_key(key
):
1155 kwargs
[key
] = copy
.copy(value
)
1157 self
._autoCompleteIndex
= -1
1158 self
._SetParameters
(**kwargs
)
1159 self
._ValidateParameters
(**kwargs
)
1164 def _SetParameters(self
, **kwargs
):
1166 This function can be used to set individual or multiple parameters for
1167 a masked edit field parameter after construction.
1170 dbg('maskededit.Field::_SetParameters', indent
=1)
1171 # Validate keyword arguments:
1172 for key
in kwargs
.keys():
1173 if key
not in Field
.valid_params
.keys():
1174 dbg(indent
=0, suspend
=0)
1175 raise AttributeError('invalid keyword argument "%s"' % key
)
1177 if self
._index
is not None: dbg('field index:', self
._index
)
1178 dbg('parameters:', indent
=1)
1179 for key
, value
in kwargs
.items():
1180 dbg('%s:' % key
, value
)
1183 old_fillChar
= self
._fillChar
# store so we can change choice lists accordingly if it changes
1185 # First, Assign all parameters specified:
1186 for key
in Field
.valid_params
.keys():
1187 if kwargs
.has_key(key
):
1188 setattr(self
, '_' + key
, kwargs
[key
] )
1190 if kwargs
.has_key('formatcodes'): # (set/changed)
1191 self
._forceupper
= '!' in self
._formatcodes
1192 self
._forcelower
= '^' in self
._formatcodes
1193 self
._groupdigits
= ',' in self
._formatcodes
1194 self
._okSpaces
= '_' in self
._formatcodes
1195 self
._padZero
= '0' in self
._formatcodes
1196 self
._autofit
= 'F' in self
._formatcodes
1197 self
._insertRight
= 'r' in self
._formatcodes
1198 self
._allowInsert
= '>' in self
._formatcodes
1199 self
._alignRight
= 'R' in self
._formatcodes
or 'r' in self
._formatcodes
1200 self
._moveOnFieldFull
= not '<' in self
._formatcodes
1201 self
._selectOnFieldEntry
= 'S' in self
._formatcodes
1203 if kwargs
.has_key('groupChar'):
1204 self
._groupChar
= kwargs
['groupChar']
1205 if kwargs
.has_key('decimalChar'):
1206 self
._decimalChar
= kwargs
['decimalChar']
1207 if kwargs
.has_key('shiftDecimalChar'):
1208 self
._shiftDecimalChar
= kwargs
['shiftDecimalChar']
1210 if kwargs
.has_key('formatcodes') or kwargs
.has_key('validRegex'):
1211 self
._regexMask
= 'V' in self
._formatcodes
and self
._validRegex
1213 if kwargs
.has_key('fillChar'):
1214 self
._old
_fillChar
= old_fillChar
1215 ## dbg("self._old_fillChar: '%s'" % self._old_fillChar)
1217 if kwargs
.has_key('mask') or kwargs
.has_key('validRegex'): # (set/changed)
1218 self
._isInt
= isInteger(self
._mask
)
1219 dbg('isInt?', self
._isInt
, 'self._mask:"%s"' % self
._mask
)
1221 dbg(indent
=0, suspend
=0)
1224 def _ValidateParameters(self
, **kwargs
):
1226 This function can be used to validate individual or multiple parameters for
1227 a masked edit field parameter after construction.
1230 dbg('maskededit.Field::_ValidateParameters', indent
=1)
1231 if self
._index
is not None: dbg('field index:', self
._index
)
1232 ## dbg('parameters:', indent=1)
1233 ## for key, value in kwargs.items():
1234 ## dbg('%s:' % key, value)
1236 ## dbg("self._old_fillChar: '%s'" % self._old_fillChar)
1238 # Verify proper numeric format params:
1239 if self
._groupdigits
and self
._groupChar
== self
._decimalChar
:
1240 dbg(indent
=0, suspend
=0)
1241 raise AttributeError("groupChar '%s' cannot be the same as decimalChar '%s'" % (self
._groupChar
, self
._decimalChar
))
1244 # Now go do validation, semantic and inter-dependency parameter processing:
1245 if kwargs
.has_key('choices') or kwargs
.has_key('compareNoCase') or kwargs
.has_key('choiceRequired'): # (set/changed)
1247 self
._compareChoices
= [choice
.strip() for choice
in self
._choices
]
1249 if self
._compareNoCase
and self
._choices
:
1250 self
._compareChoices
= [item
.lower() for item
in self
._compareChoices
]
1252 if kwargs
.has_key('choices'):
1253 self
._autoCompleteIndex
= -1
1256 if kwargs
.has_key('validRegex'): # (set/changed)
1257 if self
._validRegex
:
1259 if self
._compareNoCase
:
1260 self
._filter
= re
.compile(self
._validRegex
, re
.IGNORECASE
)
1262 self
._filter
= re
.compile(self
._validRegex
)
1264 dbg(indent
=0, suspend
=0)
1265 raise TypeError('%s: validRegex "%s" not a legal regular expression' % (str(self
._index
), self
._validRegex
))
1269 if kwargs
.has_key('validRange'): # (set/changed)
1270 self
._hasRange
= False
1273 if self
._validRange
:
1274 if type(self
._validRange
) != types
.TupleType
or len( self
._validRange
)!= 2 or self
._validRange
[0] > self
._validRange
[1]:
1275 dbg(indent
=0, suspend
=0)
1276 raise TypeError('%s: validRange %s parameter must be tuple of form (a,b) where a <= b'
1277 % (str(self
._index
), repr(self
._validRange
)) )
1279 self
._hasRange
= True
1280 self
._rangeLow
= self
._validRange
[0]
1281 self
._rangeHigh
= self
._validRange
[1]
1283 if kwargs
.has_key('choices') or (len(self
._choices
) and len(self
._choices
[0]) != len(self
._mask
)): # (set/changed)
1284 self
._hasList
= False
1285 if self
._choices
and type(self
._choices
) not in (types
.TupleType
, types
.ListType
):
1286 dbg(indent
=0, suspend
=0)
1287 raise TypeError('%s: choices must be a sequence of strings' % str(self
._index
))
1288 elif len( self
._choices
) > 0:
1289 for choice
in self
._choices
:
1290 if type(choice
) not in (types
.StringType
, types
.UnicodeType
):
1291 dbg(indent
=0, suspend
=0)
1292 raise TypeError('%s: choices must be a sequence of strings' % str(self
._index
))
1294 length
= len(self
._mask
)
1295 dbg('len(%s)' % self
._mask
, length
, 'len(self._choices):', len(self
._choices
), 'length:', length
, 'self._alignRight?', self
._alignRight
)
1296 if len(self
._choices
) and length
:
1297 if len(self
._choices
[0]) > length
:
1298 # changed mask without respecifying choices; readjust the width as appropriate:
1299 self
._choices
= [choice
.strip() for choice
in self
._choices
]
1300 if self
._alignRight
:
1301 self
._choices
= [choice
.rjust( length
) for choice
in self
._choices
]
1303 self
._choices
= [choice
.ljust( length
) for choice
in self
._choices
]
1304 dbg('aligned choices:', self
._choices
)
1306 if hasattr(self
, '_template'):
1307 # Verify each choice specified is valid:
1308 for choice
in self
._choices
:
1309 if self
.IsEmpty(choice
) and not self
._validRequired
:
1310 # allow empty values even if invalid, (just colored differently)
1312 if not self
.IsValid(choice
):
1313 dbg(indent
=0, suspend
=0)
1314 raise ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self
._index
), choice
))
1315 self
._hasList
= True
1317 ## dbg("kwargs.has_key('fillChar')?", kwargs.has_key('fillChar'), "len(self._choices) > 0?", len(self._choices) > 0)
1318 ## dbg("self._old_fillChar:'%s'" % self._old_fillChar, "self._fillChar: '%s'" % self._fillChar)
1319 if kwargs
.has_key('fillChar') and len(self
._choices
) > 0:
1320 if kwargs
['fillChar'] != ' ':
1321 self
._choices
= [choice
.replace(' ', self
._fillChar
) for choice
in self
._choices
]
1323 self
._choices
= [choice
.replace(self
._old
_fillChar
, self
._fillChar
) for choice
in self
._choices
]
1324 dbg('updated choices:', self
._choices
)
1327 if kwargs
.has_key('autoSelect') and kwargs
['autoSelect']:
1328 if not self
._hasList
:
1329 dbg('no list to auto complete; ignoring "autoSelect=True"')
1330 self
._autoSelect
= False
1332 # reset field validity assumption:
1334 dbg(indent
=0, suspend
=0)
1337 def _GetParameter(self
, paramname
):
1339 Routine for retrieving the value of any given parameter
1341 if Field
.valid_params
.has_key(paramname
):
1342 return getattr(self
, '_' + paramname
)
1344 TypeError('Field._GetParameter: invalid parameter "%s"' % key
)
1347 def IsEmpty(self
, slice):
1349 Indicates whether the specified slice is considered empty for the
1352 dbg('Field::IsEmpty("%s")' % slice, indent
=1)
1353 if not hasattr(self
, '_template'):
1355 raise AttributeError('_template')
1357 dbg('self._template: "%s"' % self
._template
)
1358 dbg('self._defaultValue: "%s"' % str(self
._defaultValue
))
1359 if slice == self
._template
and not self
._defaultValue
:
1363 elif slice == self
._template
:
1365 for pos
in range(len(self
._template
)):
1366 ## dbg('slice[%(pos)d] != self._fillChar?' %locals(), slice[pos] != self._fillChar[pos])
1367 if slice[pos
] not in (' ', self
._fillChar
):
1370 dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals(), indent
=0)
1373 dbg("IsEmpty? 0 (slice doesn't match template)", indent
=0)
1377 def IsValid(self
, slice):
1379 Indicates whether the specified slice is considered a valid value for the
1383 dbg('Field[%s]::IsValid("%s")' % (str(self
._index
), slice), indent
=1)
1384 valid
= True # assume true to start
1386 if self
.IsEmpty(slice):
1387 dbg(indent
=0, suspend
=0)
1388 if self
._emptyInvalid
:
1393 elif self
._hasList
and self
._choiceRequired
:
1394 dbg("(member of list required)")
1395 # do case-insensitive match on list; strip surrounding whitespace from slice (already done for choices):
1396 if self
._fillChar
!= ' ':
1397 slice = slice.replace(self
._fillChar
, ' ')
1398 dbg('updated slice:"%s"' % slice)
1399 compareStr
= slice.strip()
1401 if self
._compareNoCase
:
1402 compareStr
= compareStr
.lower()
1403 valid
= compareStr
in self
._compareChoices
1405 elif self
._hasRange
and not self
.IsEmpty(slice):
1406 dbg('validating against range')
1408 # allow float as well as int ranges (int comparisons for free.)
1409 valid
= self
._rangeLow
<= float(slice) <= self
._rangeHigh
1413 elif self
._validRegex
and self
._filter
:
1414 dbg('validating against regex')
1415 valid
= (re
.match( self
._filter
, slice) is not None)
1417 if valid
and self
._validFunc
:
1418 dbg('validating against supplied function')
1419 valid
= self
._validFunc
(slice)
1420 dbg('valid?', valid
, indent
=0, suspend
=0)
1424 def _AdjustField(self
, slice):
1425 """ 'Fixes' an integer field. Right or left-justifies, as required."""
1426 dbg('Field::_AdjustField("%s")' % slice, indent
=1)
1427 length
= len(self
._mask
)
1428 ## dbg('length(self._mask):', length)
1429 ## dbg('self._useParensForNegatives?', self._useParensForNegatives)
1431 if self
._useParensForNegatives
:
1432 signpos
= slice.find('(')
1433 right_signpos
= slice.find(')')
1434 intStr
= slice.replace('(', '').replace(')', '') # drop sign, if any
1436 signpos
= slice.find('-')
1437 intStr
= slice.replace( '-', '' ) # drop sign, if any
1440 intStr
= intStr
.replace(' ', '') # drop extra spaces
1441 intStr
= string
.replace(intStr
,self
._fillChar
,"") # drop extra fillchars
1442 intStr
= string
.replace(intStr
,"-","") # drop sign, if any
1443 intStr
= string
.replace(intStr
, self
._groupChar
, "") # lose commas/dots
1444 ## dbg('intStr:"%s"' % intStr)
1445 start
, end
= self
._extent
1446 field_len
= end
- start
1447 if not self
._padZero
and len(intStr
) != field_len
and intStr
.strip():
1448 intStr
= str(long(intStr
))
1449 ## dbg('raw int str: "%s"' % intStr)
1450 ## dbg('self._groupdigits:', self._groupdigits, 'self._formatcodes:', self._formatcodes)
1451 if self
._groupdigits
:
1454 for i
in range(len(intStr
)-1, -1, -1):
1455 new
= intStr
[i
] + new
1457 new
= self
._groupChar
+ new
1459 if new
and new
[0] == self
._groupChar
:
1461 if len(new
) <= length
:
1462 # expanded string will still fit and leave room for sign:
1464 # else... leave it without the commas...
1466 dbg('padzero?', self
._padZero
)
1467 dbg('len(intStr):', len(intStr
), 'field length:', length
)
1468 if self
._padZero
and len(intStr
) < length
:
1469 intStr
= '0' * (length
- len(intStr
)) + intStr
1470 if signpos
!= -1: # we had a sign before; restore it
1471 if self
._useParensForNegatives
:
1472 intStr
= '(' + intStr
[1:]
1473 if right_signpos
!= -1:
1476 intStr
= '-' + intStr
[1:]
1477 elif signpos
!= -1 and slice[0:signpos
].strip() == '': # - was before digits
1478 if self
._useParensForNegatives
:
1479 intStr
= '(' + intStr
1480 if right_signpos
!= -1:
1483 intStr
= '-' + intStr
1484 elif right_signpos
!= -1:
1485 # must have had ')' but '(' was before field; re-add ')'
1489 slice = slice.strip() # drop extra spaces
1491 if self
._alignRight
: ## Only if right-alignment is enabled
1492 slice = slice.rjust( length
)
1494 slice = slice.ljust( length
)
1495 if self
._fillChar
!= ' ':
1496 slice = slice.replace(' ', self
._fillChar
)
1497 dbg('adjusted slice: "%s"' % slice, indent
=0)
1501 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
1503 class wxMaskedEditMixin
:
1505 This class allows us to abstract the masked edit functionality that could
1506 be associated with any text entry control. (eg. wxTextCtrl, wxComboBox, etc.)
1508 valid_ctrl_params
= {
1509 'mask': 'XXXXXXXXXXXXX', ## mask string for formatting this control
1510 'autoformat': "", ## optional auto-format code to set format from masktags dictionary
1511 'fields': {}, ## optional list/dictionary of maskededit.Field class instances, indexed by position in mask
1512 'datestyle': 'MDY', ## optional date style for date-type values. Can trigger autocomplete year
1513 'autoCompleteKeycodes': [], ## Optional list of additional keycodes which will invoke field-auto-complete
1514 'useFixedWidthFont': True, ## Use fixed-width font instead of default for base control
1515 'retainFieldValidation': False, ## Set this to true if setting control-level parameters independently,
1516 ## from field validation constraints
1517 'emptyBackgroundColour': "White",
1518 'validBackgroundColour': "White",
1519 'invalidBackgroundColour': "Yellow",
1520 'foregroundColour': "Black",
1521 'signedForegroundColour': "Red",
1525 def __init__(self
, name
= 'wxMaskedEdit', **kwargs
):
1527 This is the "constructor" for setting up the mixin variable parameters for the composite class.
1532 # set up flag for doing optional things to base control if possible
1533 if not hasattr(self
, 'controlInitialized'):
1534 self
.controlInitialized
= False
1536 # Set internal state var for keeping track of whether or not a character
1537 # action results in a modification of the control, since .SetValue()
1538 # doesn't modify the base control's internal state:
1539 self
.modified
= False
1540 self
._previous
_mask
= None
1542 # Validate legitimate set of parameters:
1543 for key
in kwargs
.keys():
1544 if key
.replace('Color', 'Colour') not in wxMaskedEditMixin
.valid_ctrl_params
.keys() + Field
.valid_params
.keys():
1545 raise TypeError('%s: invalid parameter "%s"' % (name
, key
))
1547 ## Set up dictionary that can be used by subclasses to override or add to default
1548 ## behavior for individual characters. Derived subclasses needing to change
1549 ## default behavior for keys can either redefine the default functions for the
1550 ## common keys or add functions for specific keys to this list. Each function
1551 ## added should take the key event as argument, and return False if the key
1552 ## requires no further processing.
1554 ## Initially populated with navigation and function control keys:
1555 self
._keyhandlers
= {
1556 # default navigation keys and handlers:
1557 WXK_BACK
: self
._OnErase
,
1558 WXK_LEFT
: self
._OnArrow
,
1559 WXK_RIGHT
: self
._OnArrow
,
1560 WXK_UP
: self
._OnAutoCompleteField
,
1561 WXK_DOWN
: self
._OnAutoCompleteField
,
1562 WXK_TAB
: self
._OnChangeField
,
1563 WXK_HOME
: self
._OnHome
,
1564 WXK_END
: self
._OnEnd
,
1565 WXK_RETURN
: self
._OnReturn
,
1566 WXK_PRIOR
: self
._OnAutoCompleteField
,
1567 WXK_NEXT
: self
._OnAutoCompleteField
,
1569 # default function control keys and handlers:
1570 WXK_DELETE
: self
._OnErase
,
1571 WXK_CTRL_A
: self
._OnCtrl
_A
,
1572 WXK_CTRL_C
: self
._OnCtrl
_C
,
1573 WXK_CTRL_S
: self
._OnCtrl
_S
,
1574 WXK_CTRL_V
: self
._OnCtrl
_V
,
1575 WXK_CTRL_X
: self
._OnCtrl
_X
,
1576 WXK_CTRL_Z
: self
._OnCtrl
_Z
,
1579 ## bind standard navigational and control keycodes to this instance,
1580 ## so that they can be augmented and/or changed in derived classes:
1581 self
._nav
= list(nav
)
1582 self
._control
= list(control
)
1584 ## Dynamically evaluate and store string constants for mask chars
1585 ## so that locale settings can be made after this module is imported
1586 ## and the controls created after that is done can allow the
1587 ## appropriate characters:
1588 self
.maskchardict
= {
1590 'A': string
.uppercase
,
1591 'a': string
.lowercase
,
1592 'X': string
.letters
+ string
.punctuation
+ string
.digits
,
1593 'C': string
.letters
,
1594 'N': string
.letters
+ string
.digits
,
1595 '&': string
.punctuation
1598 ## self._ignoreChange is used by wxMaskedComboBox, because
1599 ## of the hack necessary to determine the selection; it causes
1600 ## EVT_TEXT messages from the combobox to be ignored if set.
1601 self
._ignoreChange
= False
1603 # These are used to keep track of previous value, for undo functionality:
1604 self
._curValue
= None
1605 self
._prevValue
= None
1609 # Set defaults for each parameter for this instance, and fully
1610 # populate initial parameter list for configuration:
1611 for key
, value
in wxMaskedEditMixin
.valid_ctrl_params
.items():
1612 setattr(self
, '_' + key
, copy
.copy(value
))
1613 if not kwargs
.has_key(key
):
1614 ## dbg('%s: "%s"' % (key, repr(value)))
1615 kwargs
[key
] = copy
.copy(value
)
1617 # Create a "field" that holds global parameters for control constraints
1618 self
._ctrl
_constraints
= self
._fields
[-1] = Field(index
=-1)
1619 self
.SetCtrlParameters(**kwargs
)
1623 def SetCtrlParameters(self
, **kwargs
):
1625 This public function can be used to set individual or multiple masked edit
1626 parameters after construction.
1629 dbg('wxMaskedEditMixin::SetCtrlParameters', indent
=1)
1630 ## dbg('kwargs:', indent=1)
1631 ## for key, value in kwargs.items():
1632 ## dbg(key, '=', value)
1635 # Validate keyword arguments:
1636 constraint_kwargs
= {}
1638 for key
, value
in kwargs
.items():
1639 key
= key
.replace('Color', 'Colour') # for b-c, and standard wxPython spelling
1640 if key
not in wxMaskedEditMixin
.valid_ctrl_params
.keys() + Field
.valid_params
.keys():
1641 dbg(indent
=0, suspend
=0)
1642 raise TypeError('Invalid keyword argument "%s" for control "%s"' % (key
, self
.name
))
1643 elif key
in Field
.valid_params
.keys():
1644 constraint_kwargs
[key
] = value
1646 ctrl_kwargs
[key
] = value
1651 if ctrl_kwargs
.has_key('autoformat'):
1652 autoformat
= ctrl_kwargs
['autoformat']
1656 if autoformat
!= self
._autoformat
and autoformat
in masktags
.keys():
1657 dbg('autoformat:', autoformat
)
1658 self
._autoformat
= autoformat
1659 mask
= masktags
[self
._autoformat
]['mask']
1660 # gather rest of any autoformat parameters:
1661 for param
, value
in masktags
[self
._autoformat
].items():
1662 if param
== 'mask': continue # (must be present; already accounted for)
1663 constraint_kwargs
[param
] = value
1665 elif autoformat
and not autoformat
in masktags
.keys():
1666 raise AttributeError('invalid value for autoformat parameter: %s' % repr(autoformat
))
1668 dbg('autoformat not selected')
1669 if kwargs
.has_key('mask'):
1670 mask
= kwargs
['mask']
1673 ## Assign style flags
1675 dbg('preserving previous mask')
1676 mask
= self
._previous
_mask
# preserve previous mask
1679 reset_args
['reset_mask'] = mask
1680 constraint_kwargs
['mask'] = mask
1682 # wipe out previous fields; preserve new control-level constraints
1683 self
._fields
= {-1: self._ctrl_constraints}
1686 if ctrl_kwargs
.has_key('fields'):
1687 # do field parameter type validation, and conversion to internal dictionary
1689 fields
= ctrl_kwargs
['fields']
1690 if type(fields
) in (types
.ListType
, types
.TupleType
):
1691 for i
in range(len(fields
)):
1693 if not isinstance(field
, Field
):
1694 dbg(indent
=0, suspend
=0)
1695 raise AttributeError('invalid type for field parameter: %s' % repr(field
))
1696 self
._fields
[i
] = field
1698 elif type(fields
) == types
.DictionaryType
:
1699 for index
, field
in fields
.items():
1700 if not isinstance(field
, Field
):
1701 dbg(indent
=0, suspend
=0)
1702 raise AttributeError('invalid type for field parameter: %s' % repr(field
))
1703 self
._fields
[index
] = field
1705 dbg(indent
=0, suspend
=0)
1706 raise AttributeError('fields parameter must be a list or dictionary; not %s' % repr(fields
))
1708 # Assign constraint parameters for entire control:
1709 ## dbg('control constraints:', indent=1)
1710 ## for key, value in constraint_kwargs.items():
1711 ## dbg('%s:' % key, value)
1714 # determine if changing parameters that should affect the entire control:
1715 for key
in wxMaskedEditMixin
.valid_ctrl_params
.keys():
1716 if key
in ( 'mask', 'fields' ): continue # (processed separately)
1717 if ctrl_kwargs
.has_key(key
):
1718 setattr(self
, '_' + key
, ctrl_kwargs
[key
])
1720 # Validate color parameters, converting strings to named colors and validating
1721 # result if appropriate:
1722 for key
in ('emptyBackgroundColour', 'invalidBackgroundColour', 'validBackgroundColour',
1723 'foregroundColour', 'signedForegroundColour'):
1724 if ctrl_kwargs
.has_key(key
):
1725 if type(ctrl_kwargs
[key
]) in (types
.StringType
, types
.UnicodeType
):
1726 c
= wxNamedColour(ctrl_kwargs
[key
])
1727 if c
.Get() == (-1, -1, -1):
1728 raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs
[key
]), key
))
1730 # replace attribute with wxColour object:
1731 setattr(self
, '_' + key
, c
)
1732 # attach a python dynamic attribute to wxColour for debug printouts
1733 c
._name
= ctrl_kwargs
[key
]
1735 elif type(ctrl_kwargs
[key
]) != type(wxBLACK
):
1736 raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs
[key
]), key
))
1739 dbg('self._retainFieldValidation:', self
._retainFieldValidation
)
1740 if not self
._retainFieldValidation
:
1741 # Build dictionary of any changing parameters which should be propagated to the
1743 for arg
in Field
.propagating_params
:
1744 ## dbg('kwargs.has_key(%s)?' % arg, kwargs.has_key(arg))
1745 ## dbg('getattr(self._ctrl_constraints, _%s)?' % arg, getattr(self._ctrl_constraints, '_'+arg))
1746 reset_args
[arg
] = kwargs
.has_key(arg
) and kwargs
[arg
] != getattr(self
._ctrl
_constraints
, '_'+arg
)
1747 ## dbg('reset_args[%s]?' % arg, reset_args[arg])
1749 # Set the control-level constraints:
1750 self
._ctrl
_constraints
._SetParameters
(**constraint_kwargs
)
1752 # This routine does the bulk of the interdependent parameter processing, determining
1753 # the field extents of the mask if changed, resetting parameters as appropriate,
1754 # determining the overall template value for the control, etc.
1755 self
._configure
(mask
, **reset_args
)
1757 # now that we've propagated the field constraints and mask portions to the
1758 # various fields, validate the constraints
1759 self
._ctrl
_constraints
._ValidateParameters
(**constraint_kwargs
)
1761 # Validate that all choices for given fields are at least of the
1762 # necessary length, and that they all would be valid pastes if pasted
1763 # into their respective fields:
1764 ## dbg('validating choices')
1765 self
._validateChoices
()
1768 self
._autofit
= self
._ctrl
_constraints
._autofit
1771 self
._isDate
= 'D' in self
._ctrl
_constraints
._formatcodes
and isDateType(mask
)
1772 self
._isTime
= 'T' in self
._ctrl
_constraints
._formatcodes
and isTimeType(mask
)
1774 # Set _dateExtent, used in date validation to locate date in string;
1775 # always set as though year will be 4 digits, even if mask only has
1776 # 2 digits, so we can always properly process the intended year for
1777 # date validation (leap years, etc.)
1778 if self
._mask
.find('CCC') != -1: self
._dateExtent
= 11
1779 else: self
._dateExtent
= 10
1781 self
._4digityear
= len(self
._mask
) > 8 and self
._mask
[9] == '#'
1783 if self
._isDate
and self
._autoformat
:
1784 # Auto-decide datestyle:
1785 if self
._autoformat
.find('MDDY') != -1: self
._datestyle
= 'MDY'
1786 elif self
._autoformat
.find('YMMD') != -1: self
._datestyle
= 'YMD'
1787 elif self
._autoformat
.find('YMMMD') != -1: self
._datestyle
= 'YMD'
1788 elif self
._autoformat
.find('DMMY') != -1: self
._datestyle
= 'DMY'
1789 elif self
._autoformat
.find('DMMMY') != -1: self
._datestyle
= 'DMY'
1792 if self
.controlInitialized
:
1793 # Then the base control is available for configuration;
1794 # take action on base control based on new settings, as appropriate.
1795 if kwargs
.has_key('useFixedWidthFont'):
1796 # Set control font - fixed width by default
1799 if reset_args
.has_key('reset_mask'):
1801 curvalue
= self
._GetValue
()
1802 if curvalue
.strip():
1804 dbg('attempting to _SetInitialValue(%s)' % self
._GetValue
())
1805 self
._SetInitialValue
(self
._GetValue
())
1806 except Exception, e
:
1807 dbg('exception caught:', e
)
1808 dbg("current value doesn't work; attempting to reset to template")
1809 self
._SetInitialValue
()
1811 dbg('attempting to _SetInitialValue() with template')
1812 self
._SetInitialValue
()
1814 elif kwargs
.has_key('useParensForNegatives'):
1815 newvalue
= self
._getSignedValue
()[0]
1817 if newvalue
is not None:
1818 # Adjust for new mask:
1819 if len(newvalue
) < len(self
._mask
):
1821 elif len(newvalue
) > len(self
._mask
):
1822 if newvalue
[-1] in (' ', ')'):
1823 newvalue
= newvalue
[:-1]
1825 dbg('reconfiguring value for parens:"%s"' % newvalue
)
1826 self
._SetValue
(newvalue
)
1828 if self
._prevValue
!= newvalue
:
1829 self
._prevValue
= newvalue
# disallow undo of sign type
1832 dbg('setting client size to:', self
._CalcSize
())
1833 self
.SetClientSize(self
._CalcSize
())
1835 # Set value/type-specific formatting
1836 self
._applyFormatting
()
1837 dbg(indent
=0, suspend
=0)
1839 def SetMaskParameters(self
, **kwargs
):
1840 """ old name for this function """
1841 return self
.SetCtrlParameters(**kwargs
)
1844 def GetCtrlParameter(self
, paramname
):
1846 Routine for retrieving the value of any given parameter
1848 if wxMaskedEditMixin
.valid_ctrl_params
.has_key(paramname
.replace('Color','Colour')):
1849 return getattr(self
, '_' + paramname
.replace('Color', 'Colour'))
1850 elif Field
.valid_params
.has_key(paramname
):
1851 return self
._ctrl
_constraints
._GetParameter
(paramname
)
1853 TypeError('"%s".GetCtrlParameter: invalid parameter "%s"' % (self
.name
, paramname
))
1855 def GetMaskParameter(self
, paramname
):
1856 """ old name for this function """
1857 return self
.GetCtrlParameter(paramname
)
1860 # ## TRICKY BIT: to avoid a ton of boiler-plate, and to
1861 # ## automate the getter/setter generation for each valid
1862 # ## control parameter so we never forget to add the
1863 # ## functions when adding parameters, this loop
1864 # ## programmatically adds them to the class:
1865 # ## (This makes it easier for Designers like Boa to
1866 # ## deal with masked controls.)
1868 for param
in valid_ctrl_params
.keys() + Field
.valid_params
.keys():
1869 propname
= param
[0].upper() + param
[1:]
1870 exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname
, param
))
1871 exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
1872 if param.find('Colour
') != -1:
1873 # add non-british spellings, for backward-compatibility
1874 propname.replace('Colour
', 'Color
')
1875 exec('def Set
%s(self
, value
): self
.SetCtrlParameters(%s=value
)' % (propname, param))
1876 exec('def Get
%s(self
): return self
.GetCtrlParameter("%s")''' % (propname, param))
1879 def SetFieldParameters(self, field_index, **kwargs):
1881 Routine provided to modify the parameters of a given field.
1882 Because changes to fields can affect the overall control,
1883 direct access to the fields is prevented, and the control
1884 is always "reconfigured" after setting a field parameter.
1886 if field_index not in self._field_indices:
1887 raise IndexError('%s is not a valid field for control "%s".' % (str(field_index), self.name))
1888 # set parameters as requested:
1889 self._fields[field_index]._SetParameters(**kwargs)
1891 # Possibly reprogram control template due to resulting changes, and ensure
1892 # control-level params are still propagated to fields:
1893 self._configure(self._previous_mask)
1894 self._fields[field_index]._ValidateParameters(**kwargs)
1896 if self.controlInitialized:
1897 if kwargs.has_key('fillChar') or kwargs.has_key('defaultValue'):
1898 self._SetInitialValue()
1901 self.SetClientSize(self._CalcSize())
1903 # Set value/type-specific formatting
1904 self._applyFormatting()
1907 def GetFieldParameter(self, field_index, paramname):
1909 Routine provided for getting a parameter of an individual field.
1911 if field_index not in self._field_indices:
1912 raise IndexError('%s is not a valid field for control "%s".' % (str(field_index), self.name))
1913 elif Field.valid_params.has_key(paramname):
1914 return self._fields[field_index]._GetParameter(paramname)
1916 TypeError('"%s".GetFieldParameter: invalid parameter "%s"' % (self.name, paramname))
1919 def _SetKeycodeHandler(self, keycode, func):
1921 This function adds and/or replaces key event handling functions
1922 used by the control. <func> should take the event as argument
1923 and return False if no further action on the key is necessary.
1925 self._keyhandlers[keycode] = func
1928 def _SetKeyHandler(self, char, func):
1930 This function adds and/or replaces key event handling functions
1931 for ascii characters. <func> should take the event as argument
1932 and return False if no further action on the key is necessary.
1934 self._SetKeycodeHandler(ord(char), func)
1937 def _AddNavKeycode(self, keycode, handler=None):
1939 This function allows a derived subclass to augment the list of
1940 keycodes that are considered "navigational" keys.
1942 self._nav.append(keycode)
1944 self._keyhandlers[keycode] = handler
1947 def _AddNavKey(self, char, handler=None):
1949 This function is a convenience function so you don't have to
1950 remember to call ord() for ascii chars to be used for navigation.
1952 self._AddNavKeycode(ord(char), handler)
1955 def _GetNavKeycodes(self):
1957 This function retrieves the current list of navigational keycodes for
1963 def _SetNavKeycodes(self, keycode_func_tuples):
1965 This function allows you to replace the current list of keycode processed
1966 as navigation keys, and bind associated optional keyhandlers.
1969 for keycode, func in keycode_func_tuples:
1970 self._nav.append(keycode)
1972 self._keyhandlers[keycode] = func
1975 def _processMask(self, mask):
1977 This subroutine expands {n} syntax in mask strings, and looks for escaped
1978 special characters and returns the expanded mask, and an dictionary
1979 of booleans indicating whether or not a given position in the mask is
1980 a mask character or not.
1982 dbg('_processMask: mask', mask, indent=1)
1983 # regular expression for parsing c{n} syntax:
1984 rex = re.compile('([' +string.join(maskchars,"") + '])\{(\d+)\}')
1986 match = rex.search(s)
1987 while match: # found an(other) occurrence
1988 maskchr = s[match.start(1):match.end(1)] # char to be repeated
1989 repcount = int(s[match.start(2):match.end(2)]) # the number of times
1990 replacement = string.join( maskchr * repcount, "") # the resulting substr
1991 s = s[:match.start(1)] + replacement + s[match.end(2)+1:] #account for trailing '}'
1992 match = rex.search(s) # look for another such entry in mask
1994 self._decimalChar = self._ctrl_constraints._decimalChar
1995 self._shiftDecimalChar = self._ctrl_constraints._shiftDecimalChar
1997 self._isFloat = isFloatingPoint(s) and not self._ctrl_constraints._validRegex
1998 self._isInt = isInteger(s) and not self._ctrl_constraints._validRegex
1999 self._signOk = '-' in self._ctrl_constraints._formatcodes and (self._isFloat or self._isInt)
2000 self._useParens = self._ctrl_constraints._useParensForNegatives
2002 ## dbg('self._signOk?', self._signOk, 'self._useParens?', self._useParens)
2003 ## dbg('isFloatingPoint(%s)?' % (s), isFloatingPoint(s),
2004 ## 'ctrl regex:', self._ctrl_constraints._validRegex)
2006 if self._signOk and s[0] != ' ':
2008 if self._ctrl_constraints._defaultValue and self._ctrl_constraints._defaultValue[0] != ' ':
2009 self._ctrl_constraints._defaultValue = ' ' + self._ctrl_constraints._defaultValue
2014 self._ctrl_constraints._defaultValue += ' '
2016 # Now, go build up a dictionary of booleans, indexed by position,
2017 # indicating whether or not a given position is masked or not
2021 if s[i] == '\\': # if escaped character:
2022 ismasked[i] = False # mark position as not a mask char
2023 if i+1 < len(s): # if another char follows...
2024 s = s[:i] + s[i+1:] # elide the '\'
2025 if i+2 < len(s) and s[i+1] == '\\':
2026 # if next char also a '\', char is a literal '\'
2027 s = s[:i] + s[i+1:] # elide the 2nd '\' as well
2028 else: # else if special char, mark position accordingly
2029 ismasked[i] = s[i] in maskchars
2030 ## dbg('ismasked[%d]:' % i, ismasked[i], s)
2031 i += 1 # increment to next char
2032 ## dbg('ismasked:', ismasked)
2033 dbg('new mask: "%s"' % s, indent=0)
2038 def _calcFieldExtents(self):
2040 Subroutine responsible for establishing/configuring field instances with
2041 indices and editable extents appropriate to the specified mask, and building
2042 the lookup table mapping each position to the corresponding field.
2044 self._lookupField = {}
2047 ## Create dictionary of positions,characters in mask
2049 for charnum in range( len( self._mask)):
2050 self.maskdict[charnum] = self._mask[charnum:charnum+1]
2052 # For the current mask, create an ordered list of field extents
2053 # and a dictionary of positions that map to field indices:
2055 if self._signOk: start = 1
2059 # Skip field "discovery", and just construct a 2-field control with appropriate
2060 # constraints for a floating-point entry.
2062 # .setdefault always constructs 2nd argument even if not needed, so we do this
2063 # the old-fashioned way...
2064 if not self._fields.has_key(0):
2065 self._fields[0] = Field()
2066 if not self._fields.has_key(1):
2067 self._fields[1] = Field()
2069 self._decimalpos = string.find( self._mask, '.')
2070 dbg('decimal pos =', self._decimalpos)
2072 formatcodes = self._fields[0]._GetParameter('formatcodes')
2073 if 'R' not in formatcodes: formatcodes += 'R'
2074 self._fields[0]._SetParameters(index=0, extent=(start, self._decimalpos),
2075 mask=self._mask[start:self._decimalpos], formatcodes=formatcodes)
2076 end = len(self._mask)
2077 if self._signOk and self._useParens:
2079 self._fields[1]._SetParameters(index=1, extent=(self._decimalpos+1, end),
2080 mask=self._mask[self._decimalpos+1:end])
2082 for i in range(self._decimalpos+1):
2083 self._lookupField[i] = 0
2085 for i in range(self._decimalpos+1, len(self._mask)+1):
2086 self._lookupField[i] = 1
2089 # Skip field "discovery", and just construct a 1-field control with appropriate
2090 # constraints for a integer entry.
2091 if not self._fields.has_key(0):
2092 self._fields[0] = Field(index=0)
2093 end = len(self._mask)
2094 if self._signOk and self._useParens:
2096 self._fields[0]._SetParameters(index=0, extent=(start, end),
2097 mask=self._mask[start:end])
2098 for i in range(len(self._mask)+1):
2099 self._lookupField[i] = 0
2101 # generic control; parse mask to figure out where the fields are:
2104 i = self._findNextEntry(pos,adjustInsert=False) # go to 1st entry point:
2105 if i < len(self._mask): # no editable chars!
2106 for j in range(pos, i+1):
2107 self._lookupField[j] = field_index
2108 pos = i # figure out field for 1st editable space:
2110 while i <= len(self._mask):
2111 ## dbg('searching: outer field loop: i = ', i)
2112 if self._isMaskChar(i):
2113 ## dbg('1st char is mask char; recording edit_start=', i)
2115 # Skip to end of editable part of current field:
2116 while i < len(self._mask) and self._isMaskChar(i):
2117 self._lookupField[i] = field_index
2119 ## dbg('edit_end =', i)
2121 self._lookupField[i] = field_index
2122 ## dbg('self._fields.has_key(%d)?' % field_index, self._fields.has_key(field_index))
2123 if not self._fields.has_key(field_index):
2124 kwargs = Field.valid_params.copy()
2125 kwargs['index'] = field_index
2126 kwargs['extent'] = (edit_start, edit_end)
2127 kwargs['mask'] = self._mask[edit_start:edit_end]
2128 self._fields[field_index] = Field(**kwargs)
2130 self._fields[field_index]._SetParameters(
2132 extent=(edit_start, edit_end),
2133 mask=self._mask[edit_start:edit_end])
2135 i = self._findNextEntry(pos, adjustInsert=False) # go to next field:
2137 for j in range(pos, i+1):
2138 self._lookupField[j] = field_index
2139 if i >= len(self._mask):
2140 break # if past end, we're done
2143 ## dbg('next field:', field_index)
2145 indices = self._fields.keys()
2147 self._field_indices = indices[1:]
2148 ## dbg('lookupField map:', indent=1)
2149 ## for i in range(len(self._mask)):
2150 ## dbg('pos %d:' % i, self._lookupField[i])
2153 # Verify that all field indices specified are valid for mask:
2154 for index in self._fields.keys():
2155 if index not in [-1] + self._lookupField.values():
2156 raise IndexError('field %d is not a valid field for mask "%s"' % (index, self._mask))
2159 def _calcTemplate(self, reset_fillchar, reset_default):
2161 Subroutine for processing current fillchars and default values for
2162 whole control and individual fields, constructing the resulting
2163 overall template, and adjusting the current value as necessary.
2166 if self._ctrl_constraints._defaultValue:
2169 for field in self._fields.values():
2170 if field._defaultValue and not reset_default:
2172 dbg('default set?', default_set)
2174 # Determine overall new template for control, and keep track of previous
2175 # values, so that current control value can be modified as appropriate:
2176 if self.controlInitialized: curvalue = list(self._GetValue())
2177 else: curvalue = None
2179 if hasattr(self, '_fillChar'): old_fillchars = self._fillChar
2180 else: old_fillchars = None
2182 if hasattr(self, '_template'): old_template = self._template
2183 else: old_template = None
2190 for field in self._fields.values():
2191 field._template = ""
2193 for pos in range(len(self._mask)):
2195 field = self._FindField(pos)
2196 ## dbg('field:', field._index)
2197 start, end = field._extent
2199 if pos == 0 and self._signOk:
2200 self._template = ' ' # always make 1st 1st position blank, regardless of fillchar
2201 elif self._isFloat and pos == self._decimalpos:
2202 self._template += self._decimalChar
2203 elif self._isMaskChar(pos):
2204 if field._fillChar != self._ctrl_constraints._fillChar and not reset_fillchar:
2205 fillChar = field._fillChar
2207 fillChar = self._ctrl_constraints._fillChar
2208 self._fillChar[pos] = fillChar
2210 # Replace any current old fillchar with new one in current value;
2211 # if action required, set reset_value flag so we can take that action
2212 # after we're all done
2213 if self.controlInitialized and old_fillchars and old_fillchars.has_key(pos) and curvalue:
2214 if curvalue[pos] == old_fillchars[pos] and old_fillchars[pos] != fillChar:
2216 curvalue[pos] = fillChar
2218 if not field._defaultValue and not self._ctrl_constraints._defaultValue:
2219 ## dbg('no default value')
2220 self._template += fillChar
2221 field._template += fillChar
2223 elif field._defaultValue and not reset_default:
2224 ## dbg('len(field._defaultValue):', len(field._defaultValue))
2225 ## dbg('pos-start:', pos-start)
2226 if len(field._defaultValue) > pos-start:
2227 ## dbg('field._defaultValue[pos-start]: "%s"' % field._defaultValue[pos-start])
2228 self._template += field._defaultValue[pos-start]
2229 field._template += field._defaultValue[pos-start]
2231 ## dbg('field default not long enough; using fillChar')
2232 self._template += fillChar
2233 field._template += fillChar
2235 if len(self._ctrl_constraints._defaultValue) > pos:
2236 ## dbg('using control default')
2237 self._template += self._ctrl_constraints._defaultValue[pos]
2238 field._template += self._ctrl_constraints._defaultValue[pos]
2240 ## dbg('ctrl default not long enough; using fillChar')
2241 self._template += fillChar
2242 field._template += fillChar
2243 ## dbg('field[%d]._template now "%s"' % (field._index, field._template))
2244 ## dbg('self._template now "%s"' % self._template)
2246 self._template += self._mask[pos]
2248 self._fields[-1]._template = self._template # (for consistency)
2250 if curvalue: # had an old value, put new one back together
2251 newvalue = string.join(curvalue, "")
2256 self._defaultValue = self._template
2257 dbg('self._defaultValue:', self._defaultValue)
2258 if not self.IsEmpty(self._defaultValue) and not self.IsValid(self._defaultValue):
2260 raise ValueError('Default value of "%s" is not a valid value for control "%s"' % (self._defaultValue, self.name))
2262 # if no fillchar change, but old value == old template, replace it:
2263 if newvalue == old_template:
2264 newvalue = self._template
2267 self._defaultValue = None
2270 dbg('resetting value to: "%s"' % newvalue)
2271 pos = self._GetInsertionPoint()
2272 sel_start, sel_to = self._GetSelection()
2273 self._SetValue(newvalue)
2274 self._SetInsertionPoint(pos)
2275 self._SetSelection(sel_start, sel_to)
2278 def _propagateConstraints(self, **reset_args):
2280 Subroutine for propagating changes to control-level constraints and
2281 formatting to the individual fields as appropriate.
2283 parent_codes = self._ctrl_constraints._formatcodes
2284 parent_includes = self._ctrl_constraints._includeChars
2285 parent_excludes = self._ctrl_constraints._excludeChars
2286 for i in self._field_indices:
2287 field = self._fields[i]
2289 if len(self._field_indices) == 1:
2290 inherit_args['formatcodes'] = parent_codes
2291 inherit_args['includeChars'] = parent_includes
2292 inherit_args['excludeChars'] = parent_excludes
2294 field_codes = current_codes = field._GetParameter('formatcodes')
2295 for c in parent_codes:
2296 if c not in field_codes: field_codes += c
2297 if field_codes != current_codes:
2298 inherit_args['formatcodes'] = field_codes
2300 include_chars = current_includes = field._GetParameter('includeChars')
2301 for c in parent_includes:
2302 if not c in include_chars: include_chars += c
2303 if include_chars != current_includes:
2304 inherit_args['includeChars'] = include_chars
2306 exclude_chars = current_excludes = field._GetParameter('excludeChars')
2307 for c in parent_excludes:
2308 if not c in exclude_chars: exclude_chars += c
2309 if exclude_chars != current_excludes:
2310 inherit_args['excludeChars'] = exclude_chars
2312 if reset_args.has_key('defaultValue') and reset_args['defaultValue']:
2313 inherit_args['defaultValue'] = "" # (reset for field)
2315 for param in Field.propagating_params:
2316 ## dbg('reset_args.has_key(%s)?' % param, reset_args.has_key(param))
2317 ## dbg('reset_args.has_key(%(param)s) and reset_args[%(param)s]?' % locals(), reset_args.has_key(param) and reset_args[param])
2318 if reset_args.has_key(param):
2319 inherit_args[param] = self.GetCtrlParameter(param)
2320 ## dbg('inherit_args[%s]' % param, inherit_args[param])
2323 field._SetParameters(**inherit_args)
2324 field._ValidateParameters(**inherit_args)
2327 def _validateChoices(self):
2329 Subroutine that validates that all choices for given fields are at
2330 least of the necessary length, and that they all would be valid pastes
2331 if pasted into their respective fields.
2333 for field in self._fields.values():
2335 index = field._index
2336 if len(self._field_indices) == 1 and index == 0 and field._choices == self._ctrl_constraints._choices:
2337 dbg('skipping (duplicate) choice validation of field 0')
2339 ## dbg('checking for choices for field', field._index)
2340 start, end = field._extent
2341 field_length = end - start
2342 ## dbg('start, end, length:', start, end, field_length)
2343 for choice in field._choices:
2344 ## dbg('testing "%s"' % choice)
2345 valid_paste, ignore, replace_to = self._validatePaste(choice, start, end)
2348 raise ValueError('"%s" could not be entered into field %d of control "%s"' % (choice, index, self.name))
2349 elif replace_to > end:
2351 raise ValueError('"%s" will not fit into field %d of control "%s"' (choice, index, self.name))
2352 ## dbg(choice, 'valid in field', index)
2355 def _configure(self, mask, **reset_args):
2357 This function sets flags for automatic styling options. It is
2358 called whenever a control or field-level parameter is set/changed.
2360 This routine does the bulk of the interdependent parameter processing, determining
2361 the field extents of the mask if changed, resetting parameters as appropriate,
2362 determining the overall template value for the control, etc.
2364 reset_args is supplied if called from control's .SetCtrlParameters()
2365 routine, and indicates which if any parameters which can be
2366 overridden by individual fields have been reset by request for the
2371 dbg('wxMaskedEditMixin::_configure("%s")' % mask, indent=1)
2373 # Preprocess specified mask to expand {n} syntax, handle escaped
2374 # mask characters, etc and build the resulting positionally keyed
2375 # dictionary for which positions are mask vs. template characters:
2376 self._mask, self.ismasked = self._processMask(mask)
2377 self._masklength = len(self._mask)
2378 ## dbg('processed mask:', self._mask)
2380 # Preserve original mask specified, for subsequent reprocessing
2381 # if parameters change.
2382 dbg('mask: "%s"' % self._mask, 'previous mask: "%s"' % self._previous_mask)
2383 self._previous_mask = mask # save unexpanded mask for next time
2384 # Set expanded mask and extent of field -1 to width of entire control:
2385 self._ctrl_constraints._SetParameters(mask = self._mask, extent=(0,self._masklength))
2387 # Go parse mask to determine where each field is, construct field
2388 # instances as necessary, configure them with those extents, and
2389 # build lookup table mapping each position for control to its corresponding
2391 ## dbg('calculating field extents')
2393 self._calcFieldExtents()
2396 # Go process defaultValues and fillchars to construct the overall
2397 # template, and adjust the current value as necessary:
2398 reset_fillchar = reset_args.has_key('fillChar') and reset_args['fillChar']
2399 reset_default = reset_args.has_key('defaultValue') and reset_args['defaultValue']
2401 ## dbg('calculating template')
2402 self._calcTemplate(reset_fillchar, reset_default)
2404 # Propagate control-level formatting and character constraints to each
2405 # field if they don't already have them; if only one field, propagate
2406 # control-level validation constraints to field as well:
2407 ## dbg('propagating constraints')
2408 self._propagateConstraints(**reset_args)
2411 if self._isFloat and self._fields[0]._groupChar == self._decimalChar:
2412 raise AttributeError('groupChar (%s) and decimalChar (%s) must be distinct.' %
2413 (self._fields[0]._groupChar, self._decimalChar) )
2415 ## dbg('fields:', indent=1)
2416 ## for i in [-1] + self._field_indices:
2417 ## dbg('field %d:' % i, self._fields[i].__dict__)
2420 # Set up special parameters for numeric control, if appropriate:
2422 self._signpos = 0 # assume it starts here, but it will move around on floats
2423 signkeys = ['-', '+', ' ']
2425 signkeys += ['(', ')']
2426 for key in signkeys:
2428 if not self._keyhandlers.has_key(keycode):
2429 self._SetKeyHandler(key, self._OnChangeSign)
2433 if self._isFloat or self._isInt:
2434 if self.controlInitialized:
2435 value = self._GetValue()
2436 ## dbg('value: "%s"' % value, 'len(value):', len(value),
2437 ## 'len(self._ctrl_constraints._mask):',len(self._ctrl_constraints._mask))
2438 if len(value) < len(self._ctrl_constraints._mask):
2440 if self._useParens and len(newvalue) < len(self._ctrl_constraints._mask) and newvalue.find('(') == -1:
2442 if self._signOk and len(newvalue) < len(self._ctrl_constraints._mask) and newvalue.find(')') == -1:
2443 newvalue = ' ' + newvalue
2444 if len(newvalue) < len(self._ctrl_constraints._mask):
2445 if self._ctrl_constraints._alignRight:
2446 newvalue = newvalue.rjust(len(self._ctrl_constraints._mask))
2448 newvalue = newvalue.ljust(len(self._ctrl_constraints._mask))
2449 dbg('old value: "%s"' % value)
2450 dbg('new value: "%s"' % newvalue)
2452 self._SetValue(newvalue)
2453 except Exception, e:
2454 dbg('exception raised:', e, 'resetting to initial value')
2455 self._SetInitialValue()
2457 elif len(value) > len(self._ctrl_constraints._mask):
2459 if not self._useParens and newvalue[-1] == ' ':
2460 newvalue = newvalue[:-1]
2461 if not self._signOk and len(newvalue) > len(self._ctrl_constraints._mask):
2462 newvalue = newvalue[1:]
2463 if not self._signOk:
2464 newvalue, signpos, right_signpos = self._getSignedValue(newvalue)
2466 dbg('old value: "%s"' % value)
2467 dbg('new value: "%s"' % newvalue)
2469 self._SetValue(newvalue)
2470 except Exception, e:
2471 dbg('exception raised:', e, 'resetting to initial value')
2472 self._SetInitialValue()
2473 elif not self._signOk and ('(' in value or '-' in value):
2474 newvalue, signpos, right_signpos = self._getSignedValue(value)
2475 dbg('old value: "%s"' % value)
2476 dbg('new value: "%s"' % newvalue)
2478 self._SetValue(newvalue)
2480 dbg('exception raised:', e, 'resetting to initial value')
2481 self._SetInitialValue()
2483 # Replace up/down arrow default handling:
2484 # make down act like tab, up act like shift-tab:
2486 ## dbg('Registering numeric navigation and control handlers (if not already set)')
2487 if not self._keyhandlers.has_key(WXK_DOWN):
2488 self._SetKeycodeHandler(WXK_DOWN, self._OnChangeField)
2489 if not self._keyhandlers.has_key(WXK_UP):
2490 self._SetKeycodeHandler(WXK_UP, self._OnUpNumeric) # (adds "shift" to up arrow, and calls _OnChangeField)
2492 # On ., truncate contents right of cursor to decimal point (if any)
2493 # leaves cusor after decimal point if floating point, otherwise at 0.
2494 if not self._keyhandlers.has_key(ord(self._decimalChar)):
2495 self._SetKeyHandler(self._decimalChar, self._OnDecimalPoint)
2496 if not self._keyhandlers.has_key(ord(self._shiftDecimalChar)):
2497 self._SetKeyHandler(self._shiftDecimalChar, self._OnChangeField) # (Shift-'.' == '>' on US keyboards)
2499 # Allow selective insert of groupchar in numbers:
2500 if not self._keyhandlers.has_key(ord(self._fields[0]._groupChar)):
2501 self._SetKeyHandler(self._fields[0]._groupChar, self._OnGroupChar)
2503 dbg(indent=0, suspend=0)
2506 def _SetInitialValue(self, value=""):
2508 fills the control with the generated or supplied default value.
2509 It will also set/reset the font if necessary and apply
2510 formatting to the control at this time.
2512 dbg('wxMaskedEditMixin::_SetInitialValue("%s")' % value, indent=1)
2514 self._prevValue = self._curValue = self._template
2515 # don't apply external validation rules in this case, as template may
2516 # not coincide with "legal" value...
2518 self._SetValue(self._curValue) # note the use of "raw" ._SetValue()...
2519 except Exception, e:
2520 dbg('exception thrown:', e, indent=0)
2523 # Otherwise apply validation as appropriate to passed value:
2524 ## dbg('value = "%s", length:' % value, len(value))
2525 self._prevValue = self._curValue = value
2527 self.SetValue(value) # use public (validating) .SetValue()
2528 except Exception, e:
2529 dbg('exception thrown:', e, indent=0)
2533 # Set value/type-specific formatting
2534 self._applyFormatting()
2538 def _calcSize(self, size=None):
2539 """ Calculate automatic size if allowed; must be called after the base control is instantiated"""
2540 ## dbg('wxMaskedEditMixin::_calcSize', indent=1)
2541 cont = (size is None or size == wxDefaultSize)
2543 if cont and self._autofit:
2544 sizing_text = 'M' * self._masklength
2545 if wxPlatform != "__WXMSW__": # give it a little extra space
2547 if wxPlatform == "__WXMAC__": # give it even a little more...
2549 ## dbg('len(sizing_text):', len(sizing_text), 'sizing_text: "%s"' % sizing_text)
2550 w, h = self.GetTextExtent(sizing_text)
2551 size = (w+4, self.GetClientSize().height)
2552 ## dbg('size:', size, indent=0)
2557 """ Set the control's font typeface -- pass the font name as str."""
2558 ## dbg('wxMaskedEditMixin::_setFont', indent=1)
2559 if not self._useFixedWidthFont:
2560 self._font = wxSystemSettings_GetFont(wxSYS_DEFAULT_GUI_FONT)
2562 font = self.GetFont() # get size, weight, etc from current font
2564 # Set to teletype font (guaranteed to be mappable to all wxWindows
2566 self._font = wxFont( font.GetPointSize(), wxTELETYPE, font.GetStyle(),
2567 font.GetWeight(), font.GetUnderlined())
2568 ## dbg('font string: "%s"' % font.GetNativeFontInfo().ToString())
2570 self.SetFont(self._font)
2574 def _OnTextChange(self, event):
2576 Handler for EVT_TEXT event.
2577 self._Change() is provided for subclasses, and may return False to
2578 skip this method logic. This function returns True if the event
2579 detected was a legitimate event, or False if it was a "bogus"
2580 EVT_TEXT event. (NOTE: There is currently an issue with calling
2581 .SetValue from within the EVT_CHAR handler that causes duplicate
2582 EVT_TEXT events for the same change.)
2584 newvalue = self._GetValue()
2585 dbg('wxMaskedEditMixin::_OnTextChange: value: "%s"' % newvalue, indent=1)
2587 if self._ignoreChange: # ie. if an "intermediate text change event"
2591 ##! WS: For some inexplicable reason, every wxTextCtrl.SetValue
2592 ## call is generating two (2) EVT_TEXT events.
2593 ## This is the only mechanism I can find to mask this problem:
2594 if newvalue == self._curValue:
2595 dbg('ignoring bogus text change event', indent=0)
2597 dbg('curvalue: "%s", newvalue: "%s"' % (self._curValue, newvalue))
2599 if self._signOk and self._isNeg and newvalue.find('-') == -1 and newvalue.find('(') == -1:
2600 dbg('clearing self._isNeg')
2602 text, self._signpos, self._right_signpos = self._getSignedValue()
2603 self._CheckValid() # Recolor control as appropriate
2604 dbg('calling event.Skip()')
2607 self._prevValue = self._curValue # save for undo
2608 self._curValue = newvalue # Save last seen value for next iteration
2613 def _OnKeyDown(self, event):
2615 This function allows the control to capture Ctrl-events like Ctrl-tab,
2616 that are not normally seen by the "cooked" EVT_CHAR routine.
2618 # Get keypress value, adjusted by control options (e.g. convert to upper etc)
2619 key = event.GetKeyCode()
2620 if key in self._nav and event.ControlDown():
2621 # then this is the only place we will likely see these events;
2623 dbg('wxMaskedEditMixin::OnKeyDown: calling _OnChar')
2626 # else allow regular EVT_CHAR key processing
2630 def _OnChar(self, event):
2632 This is the engine of wxMaskedEdit controls. It examines each keystroke,
2633 decides if it's allowed, where it should go or what action to take.
2635 dbg('wxMaskedEditMixin::_OnChar', indent=1)
2637 # Get keypress value, adjusted by control options (e.g. convert to upper etc)
2638 key = event.GetKeyCode()
2639 orig_pos = self._GetInsertionPoint()
2640 orig_value = self._GetValue()
2641 dbg('keycode = ', key)
2642 dbg('current pos = ', orig_pos)
2643 dbg('current selection = ', self._GetSelection())
2645 if not self._Keypress(key):
2649 # If no format string for this control, or the control is marked as "read-only",
2650 # skip the rest of the special processing, and just "do the standard thing:"
2651 if not self._mask or not self._IsEditable():
2656 # Process navigation and control keys first, with
2657 # position/selection unadulterated:
2658 if key in self._nav + self._control:
2659 if self._keyhandlers.has_key(key):
2660 keep_processing = self._keyhandlers[key](event)
2661 if self._GetValue() != orig_value:
2662 self.modified = True
2663 if not keep_processing:
2666 self._applyFormatting()
2670 # Else... adjust the position as necessary for next input key,
2671 # and determine resulting selection:
2672 pos = self._adjustPos( orig_pos, key ) ## get insertion position, adjusted as needed
2673 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
2674 dbg("pos, sel_start, sel_to:", pos, sel_start, sel_to)
2676 keep_processing = True
2677 # Capture user past end of format field
2678 if pos > len(self.maskdict):
2679 dbg("field length exceeded:",pos)
2680 keep_processing = False
2683 if self._isMaskChar(pos): ## Get string of allowed characters for validation
2684 okchars = self._getAllowedChars(pos)
2686 dbg('Not a valid position: pos = ', pos,"chars=",maskchars)
2689 key = self._adjustKey(pos, key) # apply formatting constraints to key:
2691 if self._keyhandlers.has_key(key):
2692 # there's an override for default behavior; use override function instead
2693 dbg('using supplied key handler:', self._keyhandlers[key])
2694 keep_processing = self._keyhandlers[key](event)
2695 if self._GetValue() != orig_value:
2696 self.modified = True
2697 if not keep_processing:
2700 # else skip default processing, but do final formatting
2701 if key < WXK_SPACE or key > 255:
2702 dbg('key < WXK_SPACE or key > 255')
2703 event.Skip() # non alphanumeric
2704 keep_processing = False
2706 field = self._FindField(pos)
2707 dbg("key ='%s'" % chr(key))
2709 dbg('okSpaces?', field._okSpaces)
2713 if chr(key) in field._excludeChars + self._ctrl_constraints._excludeChars:
2714 keep_processing = False
2716 if keep_processing and self._isCharAllowed( chr(key), pos, checkRegex = True ):
2717 dbg("key allowed by mask")
2718 # insert key into candidate new value, but don't change control yet:
2719 oldstr = self._GetValue()
2720 newstr, newpos, new_select_to, match_field, match_index = self._insertKey(
2721 chr(key), pos, sel_start, sel_to, self._GetValue(), allowAutoSelect = True)
2722 dbg("str with '%s' inserted:" % chr(key), '"%s"' % newstr)
2723 if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
2724 dbg('not valid; checking to see if adjusted string is:')
2725 keep_processing = False
2726 if self._isFloat and newstr != self._template:
2727 newstr = self._adjustFloat(newstr)
2728 dbg('adjusted str:', newstr)
2729 if self.IsValid(newstr):
2731 keep_processing = True
2732 wxCallAfter(self._SetInsertionPoint, self._decimalpos)
2733 if not keep_processing:
2734 dbg("key disallowed by validation")
2735 if not wxValidator_IsSilent() and orig_pos == pos:
2741 # special case: adjust date value as necessary:
2742 if self._isDate and newstr != self._template:
2743 newstr = self._adjustDate(newstr)
2744 dbg('adjusted newstr:', newstr)
2746 if newstr != orig_value:
2747 self.modified = True
2749 wxCallAfter(self._SetValue, newstr)
2751 # Adjust insertion point on date if just entered 2 digit year, and there are now 4 digits:
2752 if not self.IsDefault() and self._isDate and self._4digityear:
2753 year2dig = self._dateExtent - 2
2754 if pos == year2dig and unadjusted[year2dig] != newstr[year2dig]:
2757 wxCallAfter(self._SetInsertionPoint, newpos)
2759 if match_field is not None:
2760 dbg('matched field')
2761 self._OnAutoSelect(match_field, match_index)
2763 if new_select_to != newpos:
2764 dbg('queuing selection: (%d, %d)' % (newpos, new_select_to))
2765 wxCallAfter(self._SetSelection, newpos, new_select_to)
2767 newfield = self._FindField(newpos)
2768 if newfield != field and newfield._selectOnFieldEntry:
2769 dbg('queuing selection: (%d, %d)' % (newfield._extent[0], newfield._extent[1]))
2770 wxCallAfter(self._SetSelection, newfield._extent[0], newfield._extent[1])
2771 keep_processing = False
2773 elif keep_processing:
2774 dbg('char not allowed')
2775 keep_processing = False
2776 if (not wxValidator_IsSilent()) and orig_pos == pos:
2779 self._applyFormatting()
2781 # Move to next insertion point
2782 if keep_processing and key not in self._nav:
2783 pos = self._GetInsertionPoint()
2784 next_entry = self._findNextEntry( pos )
2785 if pos != next_entry:
2786 dbg("moving from %(pos)d to next valid entry: %(next_entry)d" % locals())
2787 wxCallAfter(self._SetInsertionPoint, next_entry )
2789 if self._isTemplateChar(pos):
2790 self._AdjustField(pos)
2794 def _FindFieldExtent(self, pos=None, getslice=False, value=None):
2795 """ returns editable extent of field corresponding to
2796 position pos, and, optionally, the contents of that field
2797 in the control or the value specified.
2798 Template chars are bound to the preceding field.
2799 For masks beginning with template chars, these chars are ignored
2800 when calculating the current field.
2802 Eg: with template (###) ###-####,
2803 >>> self._FindFieldExtent(pos=0)
2805 >>> self._FindFieldExtent(pos=1)
2807 >>> self._FindFieldExtent(pos=5)
2809 >>> self._FindFieldExtent(pos=6)
2811 >>> self._FindFieldExtent(pos=10)
2815 dbg('wxMaskedEditMixin::_FindFieldExtent(pos=%s, getslice=%s)' % (
2816 str(pos), str(getslice)) ,indent=1)
2818 field = self._FindField(pos)
2821 return None, None, ""
2824 edit_start, edit_end = field._extent
2826 if value is None: value = self._GetValue()
2827 slice = value[edit_start:edit_end]
2828 dbg('edit_start:', edit_start, 'edit_end:', edit_end, 'slice: "%s"' % slice)
2830 return edit_start, edit_end, slice
2832 dbg('edit_start:', edit_start, 'edit_end:', edit_end)
2834 return edit_start, edit_end
2837 def _FindField(self, pos=None):
2839 Returns the field instance in which pos resides.
2840 Template chars are bound to the preceding field.
2841 For masks beginning with template chars, these chars are ignored
2842 when calculating the current field.
2845 ## dbg('wxMaskedEditMixin::_FindField(pos=%s)' % str(pos) ,indent=1)
2846 if pos is None: pos = self._GetInsertionPoint()
2847 elif pos < 0 or pos > self._masklength:
2848 raise IndexError('position %s out of range of control' % str(pos))
2850 if len(self._fields) == 0:
2856 return self._fields[self._lookupField[pos]]
2859 def ClearValue(self):
2860 """ Blanks the current control value by replacing it with the default value."""
2861 dbg("wxMaskedEditMixin::ClearValue - value reset to default value (template)")
2862 self._SetValue( self._template )
2863 self._SetInsertionPoint(0)
2867 def _baseCtrlEventHandler(self, event):
2869 This function is used whenever a key should be handled by the base control.
2875 def _OnUpNumeric(self, event):
2877 Makes up-arrow act like shift-tab should; ie. take you to start of
2880 dbg('wxMaskedEditMixin::_OnUpNumeric', indent=1)
2881 event.m_shiftDown = 1
2882 dbg('event.ShiftDown()?', event.ShiftDown())
2883 self._OnChangeField(event)
2887 def _OnArrow(self, event):
2889 Used in response to left/right navigation keys; makes these actions skip
2890 over mask template chars.
2892 dbg("wxMaskedEditMixin::_OnArrow", indent=1)
2893 pos = self._GetInsertionPoint()
2894 keycode = event.GetKeyCode()
2895 sel_start, sel_to = self._GetSelection()
2896 entry_end = self._goEnd(getPosOnly=True)
2897 if keycode in (WXK_RIGHT, WXK_DOWN):
2898 if( ( not self._isTemplateChar(pos) and pos+1 > entry_end)
2899 or ( self._isTemplateChar(pos) and pos >= entry_end) ):
2900 dbg("can't advance", indent=0)
2902 elif self._isTemplateChar(pos):
2903 self._AdjustField(pos)
2904 elif keycode in (WXK_LEFT,WXK_UP) and sel_start == sel_to and pos > 0 and self._isTemplateChar(pos-1):
2905 dbg('adjusting field')
2906 self._AdjustField(pos)
2908 # treat as shifted up/down arrows as tab/reverse tab:
2909 if event.ShiftDown() and keycode in (WXK_UP, WXK_DOWN):
2910 # remove "shifting" and treat as (forward) tab:
2911 event.m_shiftDown = False
2912 keep_processing = self._OnChangeField(event)
2914 elif self._FindField(pos)._selectOnFieldEntry:
2915 if( keycode in (WXK_UP, WXK_LEFT)
2917 and self._isTemplateChar(sel_start-1)
2918 and sel_start != self._masklength
2919 and not self._signOk and not self._useParens):
2921 # call _OnChangeField to handle "ctrl-shifted event"
2922 # (which moves to previous field and selects it.)
2923 event.m_shiftDown = True
2924 event.m_ControlDown = True
2925 keep_processing = self._OnChangeField(event)
2926 elif( keycode in (WXK_DOWN, WXK_RIGHT)
2927 and sel_to != self._masklength
2928 and self._isTemplateChar(sel_to)):
2930 # when changing field to the right, ensure don't accidentally go left instead
2931 event.m_shiftDown = False
2932 keep_processing = self._OnChangeField(event)
2934 # treat arrows as normal, allowing selection
2936 dbg('using base ctrl event processing')
2939 if( (sel_to == self._fields[0]._extent[0] and keycode == WXK_LEFT)
2940 or (sel_to == self._masklength and keycode == WXK_RIGHT) ):
2941 if not wxValidator_IsSilent():
2944 # treat arrows as normal, allowing selection
2946 dbg('using base event processing')
2949 keep_processing = False
2951 return keep_processing
2954 def _OnCtrl_S(self, event):
2955 """ Default Ctrl-S handler; prints value information if demo enabled. """
2956 dbg("wxMaskedEditMixin::_OnCtrl_S")
2958 print 'wxMaskedEditMixin.GetValue() = "%s"\nwxMaskedEditMixin.GetPlainValue() = "%s"' % (self.GetValue(), self.GetPlainValue())
2959 print "Valid? => " + str(self.IsValid())
2960 print "Current field, start, end, value =", str( self._FindFieldExtent(getslice=True))
2964 def _OnCtrl_X(self, event=None):
2965 """ Handles ctrl-x keypress in control and Cut operation on context menu.
2966 Should return False to skip other processing. """
2967 dbg("wxMaskedEditMixin::_OnCtrl_X", indent=1)
2972 def _OnCtrl_C(self, event=None):
2973 """ Handles ctrl-C keypress in control and Copy operation on context menu.
2974 Uses base control handling. Should return False to skip other processing."""
2978 def _OnCtrl_V(self, event=None):
2979 """ Handles ctrl-V keypress in control and Paste operation on context menu.
2980 Should return False to skip other processing. """
2981 dbg("wxMaskedEditMixin::_OnCtrl_V", indent=1)
2986 def _OnCtrl_Z(self, event=None):
2987 """ Handles ctrl-Z keypress in control and Undo operation on context menu.
2988 Should return False to skip other processing. """
2989 dbg("wxMaskedEditMixin::_OnCtrl_Z", indent=1)
2994 def _OnCtrl_A(self,event=None):
2995 """ Handles ctrl-a keypress in control. Should return False to skip other processing. """
2996 end = self._goEnd(getPosOnly=True)
2997 if not event or event.ShiftDown():
2998 wxCallAfter(self._SetInsertionPoint, 0)
2999 wxCallAfter(self._SetSelection, 0, self._masklength)
3001 wxCallAfter(self._SetInsertionPoint, 0)
3002 wxCallAfter(self._SetSelection, 0, end)
3006 def _OnErase(self, event=None):
3007 """ Handles backspace and delete keypress in control. Should return False to skip other processing."""
3008 dbg("wxMaskedEditMixin::_OnErase", indent=1)
3009 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
3011 if event is None: # called as action routine from Cut() operation.
3014 key = event.GetKeyCode()
3016 field = self._FindField(sel_to)
3017 start, end = field._extent
3018 value = self._GetValue()
3019 oldstart = sel_start
3021 # If trying to erase beyond "legal" bounds, disallow operation:
3022 if( (sel_to == 0 and key == WXK_BACK)
3023 or (self._signOk and sel_to == 1 and value[0] == ' ' and key == WXK_BACK)
3024 or (sel_to == self._masklength and sel_start == sel_to and key == WXK_DELETE and not field._insertRight)
3025 or (self._signOk and self._useParens
3026 and sel_start == sel_to
3027 and sel_to == self._masklength - 1
3028 and value[sel_to] == ' ' and key == WXK_DELETE and not field._insertRight) ):
3029 if not wxValidator_IsSilent():
3035 if( field._insertRight # an insert-right field
3036 and value[start:end] != self._template[start:end] # and field not empty
3037 and sel_start >= start # and selection starts in field
3038 and ((sel_to == sel_start # and no selection
3039 and sel_to == end # and cursor at right edge
3040 and key in (WXK_BACK, WXK_DELETE)) # and either delete or backspace key
3042 (key == WXK_BACK # backspacing
3043 and (sel_to == end # and selection ends at right edge
3044 or sel_to < end and field._allowInsert)) ) ): # or allow right insert at any point in field
3047 # if backspace but left of cursor is empty, adjust cursor right before deleting
3048 while( key == WXK_BACK
3049 and sel_start == sel_to
3051 and value[start:sel_start] == self._template[start:sel_start]):
3055 dbg('sel_start, start:', sel_start, start)
3057 if sel_start == sel_to:
3061 newfield = value[start:keep] + value[sel_to:end]
3063 # handle sign char moving from outside field into the field:
3064 move_sign_into_field = False
3065 if not field._padZero and self._signOk and self._isNeg and value[0] in ('-', '('):
3067 newfield = signchar + newfield
3068 move_sign_into_field = True
3069 dbg('cut newfield: "%s"' % newfield)
3071 # handle what should fill in from the left:
3073 for i in range(start, end - len(newfield)):
3076 elif( self._signOk and self._isNeg and i == 1
3077 and ((self._useParens and newfield.find('(') == -1)
3078 or (not self._useParens and newfield.find('-') == -1)) ):
3081 left += self._template[i] # this can produce strange results in combination with default values...
3082 newfield = left + newfield
3083 dbg('filled newfield: "%s"' % newfield)
3085 newstr = value[:start] + newfield + value[end:]
3087 # (handle sign located in "mask position" in front of field prior to delete)
3088 if move_sign_into_field:
3089 newstr = ' ' + newstr[1:]
3092 # handle erasure of (left) sign, moving selection accordingly...
3093 if self._signOk and sel_start == 0:
3094 newstr = value = ' ' + value[1:]
3097 if field._allowInsert and sel_start >= start:
3098 # selection (if any) falls within current insert-capable field:
3099 select_len = sel_to - sel_start
3100 # determine where cursor should end up:
3103 newpos = sel_start -1
3109 if sel_to == sel_start:
3110 erase_to = sel_to + 1
3114 if self._isTemplateChar(newpos) and select_len == 0:
3116 if value[newpos] in ('(', '-'):
3117 newpos += 1 # don't move cusor
3118 newstr = ' ' + value[newpos:]
3119 elif value[newpos] == ')':
3120 # erase right sign, but don't move cursor; (matching left sign handled later)
3121 newstr = value[:newpos] + ' '
3123 # no deletion; just move cursor
3126 # no deletion; just move cursor
3129 if erase_to > end: erase_to = end
3130 erase_len = erase_to - newpos
3132 left = value[start:newpos]
3133 dbg("retained ='%s'" % value[erase_to:end], 'sel_to:', sel_to, "fill: '%s'" % self._template[end - erase_len:end])
3134 right = value[erase_to:end] + self._template[end-erase_len:end]
3136 if field._alignRight:
3137 rstripped = right.rstrip()
3138 if rstripped != right:
3139 pos_adjust = len(right) - len(rstripped)
3142 if not field._insertRight and value[-1] == ')' and end == self._masklength - 1:
3143 # need to shift ) into the field:
3144 right = right[:-1] + ')'
3145 value = value[:-1] + ' '
3147 newfield = left+right
3149 newfield = newfield.rjust(end-start)
3150 newpos += pos_adjust
3151 dbg("left='%s', right ='%s', newfield='%s'" %(left, right, newfield))
3152 newstr = value[:start] + newfield + value[end:]
3157 if sel_start == sel_to:
3158 dbg("current sel_start, sel_to:", sel_start, sel_to)
3160 sel_start, sel_to = sel_to-1, sel_to-1
3161 dbg("new sel_start, sel_to:", sel_start, sel_to)
3163 if field._padZero and not value[start:sel_to].replace('0', '').replace(' ','').replace(field._fillChar, ''):
3164 # preceding chars (if any) are zeros, blanks or fillchar; new char should be 0:
3167 newchar = self._template[sel_to] ## get an original template character to "clear" the current char
3168 dbg('value = "%s"' % value, 'value[%d] = "%s"' %(sel_start, value[sel_start]))
3170 if self._isTemplateChar(sel_to):
3171 if sel_to == 0 and self._signOk and value[sel_to] == '-': # erasing "template" sign char
3172 newstr = ' ' + value[1:]
3174 elif self._signOk and self._useParens and (value[sel_to] == ')' or value[sel_to] == '('):
3175 # allow "change sign" by removing both parens:
3176 newstr = value[:self._signpos] + ' ' + value[self._signpos+1:-1] + ' '
3181 if field._insertRight and sel_start == sel_to:
3182 # force non-insert-right behavior, by selecting char to be replaced:
3184 newstr, ignore = self._insertKey(newchar, sel_start, sel_start, sel_to, value)
3188 newstr = self._eraseSelection(value, sel_start, sel_to)
3190 pos = sel_start # put cursor back at beginning of selection
3192 if self._signOk and self._useParens:
3193 # account for resultant unbalanced parentheses:
3194 left_signpos = newstr.find('(')
3195 right_signpos = newstr.find(')')
3197 if left_signpos == -1 and right_signpos != -1:
3198 # erased left-sign marker; get rid of right sign marker:
3199 newstr = newstr[:right_signpos] + ' ' + newstr[right_signpos+1:]
3201 elif left_signpos != -1 and right_signpos == -1:
3202 # erased right-sign marker; get rid of left-sign marker:
3203 newstr = newstr[:left_signpos] + ' ' + newstr[left_signpos+1:]
3205 dbg("oldstr:'%s'" % value, 'oldpos:', oldstart)
3206 dbg("newstr:'%s'" % newstr, 'pos:', pos)
3208 # if erasure results in an invalid field, disallow it:
3209 dbg('field._validRequired?', field._validRequired)
3210 dbg('field.IsValid("%s")?' % newstr[start:end], field.IsValid(newstr[start:end]))
3211 if field._validRequired and not field.IsValid(newstr[start:end]):
3212 if not wxValidator_IsSilent():
3217 # if erasure results in an invalid value, disallow it:
3218 if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
3219 if not wxValidator_IsSilent():
3224 dbg('setting value (later) to', newstr)
3225 wxCallAfter(self._SetValue, newstr)
3226 dbg('setting insertion point (later) to', pos)
3227 wxCallAfter(self._SetInsertionPoint, pos)
3232 def _OnEnd(self,event):
3233 """ Handles End keypress in control. Should return False to skip other processing. """
3234 dbg("wxMaskedEditMixin::_OnEnd", indent=1)
3235 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3236 if not event.ControlDown():
3237 end = self._masklength # go to end of control
3238 if self._signOk and self._useParens:
3239 end = end - 1 # account for reserved char at end
3241 end_of_input = self._goEnd(getPosOnly=True)
3242 sel_start, sel_to = self._GetSelection()
3243 if sel_to < pos: sel_to = pos
3244 field = self._FindField(sel_to)
3245 field_end = self._FindField(end_of_input)
3247 # pick different end point if either:
3248 # - cursor not in same field
3249 # - or at or past last input already
3250 # - or current selection = end of current field:
3251 ## dbg('field != field_end?', field != field_end)
3252 ## dbg('sel_to >= end_of_input?', sel_to >= end_of_input)
3253 if field != field_end or sel_to >= end_of_input:
3254 edit_start, edit_end = field._extent
3255 ## dbg('edit_end:', edit_end)
3256 ## dbg('sel_to:', sel_to)
3257 ## dbg('sel_to == edit_end?', sel_to == edit_end)
3258 ## dbg('field._index < self._field_indices[-1]?', field._index < self._field_indices[-1])
3260 if sel_to == edit_end and field._index < self._field_indices[-1]:
3261 edit_start, edit_end = self._FindFieldExtent(self._findNextEntry(edit_end)) # go to end of next field:
3263 dbg('end moved to', end)
3265 elif sel_to == edit_end and field._index == self._field_indices[-1]:
3266 # already at edit end of last field; select to end of control:
3267 end = self._masklength
3268 dbg('end moved to', end)
3270 end = edit_end # select to end of current field
3271 dbg('end moved to ', end)
3273 # select to current end of input
3277 ## dbg('pos:', pos, 'end:', end)
3279 if event.ShiftDown():
3280 if not event.ControlDown():
3281 dbg("shift-end; select to end of control")
3283 dbg("shift-ctrl-end; select to end of non-whitespace")
3284 wxCallAfter(self._SetInsertionPoint, pos)
3285 wxCallAfter(self._SetSelection, pos, end)
3287 if not event.ControlDown():
3288 dbg('go to end of control:')
3289 wxCallAfter(self._SetInsertionPoint, end)
3290 wxCallAfter(self._SetSelection, end, end)
3296 def _OnReturn(self, event):
3298 Changes the event to look like a tab event, so we can then call
3299 event.Skip() on it, and have the parent form "do the right thing."
3301 dbg('wxMaskedEditMixin::OnReturn')
3302 event.m_keyCode = WXK_TAB
3306 def _OnHome(self,event):
3307 """ Handles Home keypress in control. Should return False to skip other processing."""
3308 dbg("wxMaskedEditMixin::_OnHome", indent=1)
3309 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3310 sel_start, sel_to = self._GetSelection()
3312 # There are 5 cases here:
3314 # 1) shift: select from start of control to end of current
3316 if event.ShiftDown() and not event.ControlDown():
3317 dbg("shift-home; select to start of control")
3321 # 2) no shift, no control: move cursor to beginning of control.
3322 elif not event.ControlDown():
3323 dbg("home; move to start of control")
3327 # 3) No shift, control: move cursor back to beginning of field; if
3328 # there already, go to beginning of previous field.
3329 # 4) shift, control, start of selection not at beginning of control:
3330 # move sel_start back to start of field; if already there, go to
3331 # start of previous field.
3332 elif( event.ControlDown()
3333 and (not event.ShiftDown()
3334 or (event.ShiftDown() and sel_start > 0) ) ):
3335 if len(self._field_indices) > 1:
3336 field = self._FindField(sel_start)
3337 start, ignore = field._extent
3338 if sel_start == start and field._index != self._field_indices[0]: # go to start of previous field:
3339 start, ignore = self._FindFieldExtent(sel_start-1)
3340 elif sel_start == start:
3341 start = 0 # go to literal beginning if edit start
3348 if not event.ShiftDown():
3349 dbg("ctrl-home; move to beginning of field")
3352 dbg("shift-ctrl-home; select to beginning of field")
3356 # 5) shift, control, start of selection at beginning of control:
3357 # unselect by moving sel_to backward to beginning of current field;
3358 # if already there, move to start of previous field.
3360 if len(self._field_indices) > 1:
3361 # find end of previous field:
3362 field = self._FindField(sel_to)
3363 if sel_to > start and field._index != self._field_indices[0]:
3364 ignore, end = self._FindFieldExtent(field._extent[0]-1)
3370 end_of_field = False
3371 dbg("shift-ctrl-home; unselect to beginning of field")
3373 dbg('queuing new sel_start, sel_to:', (start, end))
3374 wxCallAfter(self._SetInsertionPoint, start)
3375 wxCallAfter(self._SetSelection, start, end)
3380 def _OnChangeField(self, event):
3382 Primarily handles TAB events, but can be used for any key that
3383 designer wants to change fields within a masked edit control.
3384 NOTE: at the moment, although coded to handle shift-TAB and
3385 control-shift-TAB, these events are not sent to the controls
3388 dbg('wxMaskedEditMixin::_OnChangeField', indent = 1)
3389 # determine end of current field:
3390 pos = self._GetInsertionPoint()
3391 dbg('current pos:', pos)
3392 sel_start, sel_to = self._GetSelection()
3394 if self._masklength < 0: # no fields; process tab normally
3395 self._AdjustField(pos)
3396 if event.GetKeyCode() == WXK_TAB:
3397 dbg('tab to next ctrl')
3404 if event.ShiftDown():
3408 # NOTE: doesn't yet work with SHIFT-tab under wx; the control
3409 # never sees this event! (But I've coded for it should it ever work,
3410 # and it *does* work for '.' in wxIpAddrCtrl.)
3411 field = self._FindField(pos)
3412 index = field._index
3413 field_start = field._extent[0]
3414 if pos < field_start:
3415 dbg('cursor before 1st field; cannot change to a previous field')
3416 if not wxValidator_IsSilent():
3420 if event.ControlDown():
3421 dbg('queuing select to beginning of field:', field_start, pos)
3422 wxCallAfter(self._SetInsertionPoint, field_start)
3423 wxCallAfter(self._SetSelection, field_start, pos)
3428 # We're already in the 1st field; process shift-tab normally:
3429 self._AdjustField(pos)
3430 if event.GetKeyCode() == WXK_TAB:
3431 dbg('tab to previous ctrl')
3434 dbg('position at beginning')
3435 wxCallAfter(self._SetInsertionPoint, field_start)
3439 # find beginning of previous field:
3440 begin_prev = self._FindField(field_start-1)._extent[0]
3441 self._AdjustField(pos)
3442 dbg('repositioning to', begin_prev)
3443 wxCallAfter(self._SetInsertionPoint, begin_prev)
3444 if self._FindField(begin_prev)._selectOnFieldEntry:
3445 edit_start, edit_end = self._FindFieldExtent(begin_prev)
3446 dbg('queuing selection to (%d, %d)' % (edit_start, edit_end))
3447 wxCallAfter(self._SetInsertionPoint, edit_start)
3448 wxCallAfter(self._SetSelection, edit_start, edit_end)
3454 field = self._FindField(sel_to)
3455 field_start, field_end = field._extent
3456 if event.ControlDown():
3457 dbg('queuing select to end of field:', pos, field_end)
3458 wxCallAfter(self._SetInsertionPoint, pos)
3459 wxCallAfter(self._SetSelection, pos, field_end)
3463 if pos < field_start:
3464 dbg('cursor before 1st field; go to start of field')
3465 wxCallAfter(self._SetInsertionPoint, field_start)
3466 if field._selectOnFieldEntry:
3467 wxCallAfter(self._SetSelection, field_start, field_end)
3469 wxCallAfter(self._SetSelection, field_start, field_start)
3472 dbg('end of current field:', field_end)
3473 dbg('go to next field')
3474 if field_end == self._fields[self._field_indices[-1]]._extent[1]:
3475 self._AdjustField(pos)
3476 if event.GetKeyCode() == WXK_TAB:
3477 dbg('tab to next ctrl')
3480 dbg('position at end')
3481 wxCallAfter(self._SetInsertionPoint, field_end)
3485 # we have to find the start of the next field
3486 next_pos = self._findNextEntry(field_end)
3487 if next_pos == field_end:
3488 dbg('already in last field')
3489 self._AdjustField(pos)
3490 if event.GetKeyCode() == WXK_TAB:
3491 dbg('tab to next ctrl')
3497 self._AdjustField( pos )
3499 # move cursor to appropriate point in the next field and select as necessary:
3500 field = self._FindField(next_pos)
3501 edit_start, edit_end = field._extent
3502 if field._selectOnFieldEntry:
3503 dbg('move to ', next_pos)
3504 wxCallAfter(self._SetInsertionPoint, next_pos)
3505 edit_start, edit_end = self._FindFieldExtent(next_pos)
3506 dbg('queuing select', edit_start, edit_end)
3507 wxCallAfter(self._SetSelection, edit_start, edit_end)
3509 if field._insertRight:
3510 next_pos = field._extent[1]
3511 dbg('move to ', next_pos)
3512 wxCallAfter(self._SetInsertionPoint, next_pos)
3517 def _OnDecimalPoint(self, event):
3518 dbg('wxMaskedEditMixin::_OnDecimalPoint', indent=1)
3520 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3522 if self._isFloat: ## handle float value, move to decimal place
3523 dbg('key == Decimal tab; decimal pos:', self._decimalpos)
3524 value = self._GetValue()
3525 if pos < self._decimalpos:
3526 clipped_text = value[0:pos] + self._decimalChar + value[self._decimalpos+1:]
3527 dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text)
3528 newstr = self._adjustFloat(clipped_text)
3530 newstr = self._adjustFloat(value)
3531 wxCallAfter(self._SetValue, newstr)
3532 fraction = self._fields[1]
3533 start, end = fraction._extent
3534 wxCallAfter(self._SetInsertionPoint, start)
3535 if fraction._selectOnFieldEntry:
3536 dbg('queuing selection after decimal point to:', (start, end))
3537 wxCallAfter(self._SetSelection, start, end)
3538 keep_processing = False
3540 if self._isInt: ## handle integer value, truncate from current position
3541 dbg('key == Integer decimal event')
3542 value = self._GetValue()
3543 clipped_text = value[0:pos]
3544 dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text)
3545 newstr = self._adjustInt(clipped_text)
3546 dbg('newstr: "%s"' % newstr)
3547 wxCallAfter(self._SetValue, newstr)
3548 newpos = len(newstr.rstrip())
3549 if newstr.find(')') != -1:
3550 newpos -= 1 # (don't move past right paren)
3551 wxCallAfter(self._SetInsertionPoint, newpos)
3552 keep_processing = False
3556 def _OnChangeSign(self, event):
3557 dbg('wxMaskedEditMixin::_OnChangeSign', indent=1)
3558 key = event.GetKeyCode()
3559 pos = self._adjustPos(self._GetInsertionPoint(), key)
3560 value = self._eraseSelection()
3561 integer = self._fields[0]
3562 start, end = integer._extent
3564 ## dbg('adjusted pos:', pos)
3565 if chr(key) in ('-','+','(', ')') or (chr(key) == " " and pos == self._signpos):
3566 cursign = self._isNeg
3567 dbg('cursign:', cursign)
3568 if chr(key) in ('-','(', ')'):
3569 self._isNeg = (not self._isNeg) ## flip value
3572 dbg('isNeg?', self._isNeg)
3574 text, self._signpos, self._right_signpos = self._getSignedValue(candidate=value)
3575 dbg('text:"%s"' % text, 'signpos:', self._signpos, 'right_signpos:', self._right_signpos)
3579 if self._isNeg and self._signpos is not None and self._signpos != -1:
3580 if self._useParens and self._right_signpos is not None:
3581 text = text[:self._signpos] + '(' + text[self._signpos+1:self._right_signpos] + ')' + text[self._right_signpos+1:]
3583 text = text[:self._signpos] + '-' + text[self._signpos+1:]
3585 ## dbg('self._isNeg?', self._isNeg, 'self.IsValid(%s)' % text, self.IsValid(text))
3587 text = text[:self._signpos] + ' ' + text[self._signpos+1:self._right_signpos] + ' ' + text[self._right_signpos+1:]
3589 text = text[:self._signpos] + ' ' + text[self._signpos+1:]
3590 dbg('clearing self._isNeg')
3593 wxCallAfter(self._SetValue, text)
3594 wxCallAfter(self._applyFormatting)
3595 dbg('pos:', pos, 'signpos:', self._signpos)
3596 if pos == self._signpos or integer.IsEmpty(text[start:end]):
3597 wxCallAfter(self._SetInsertionPoint, self._signpos+1)
3599 wxCallAfter(self._SetInsertionPoint, pos)
3601 keep_processing = False
3603 keep_processing = True
3605 return keep_processing
3608 def _OnGroupChar(self, event):
3610 This handler is only registered if the mask is a numeric mask.
3611 It allows the insertion of ',' or '.' if appropriate.
3613 dbg('wxMaskedEditMixin::_OnGroupChar', indent=1)
3614 keep_processing = True
3615 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3616 sel_start, sel_to = self._GetSelection()
3617 groupchar = self._fields[0]._groupChar
3618 if not self._isCharAllowed(groupchar, pos, checkRegex=True):
3619 keep_processing = False
3620 if not wxValidator_IsSilent():
3624 newstr, newpos = self._insertKey(groupchar, pos, sel_start, sel_to, self._GetValue() )
3625 dbg("str with '%s' inserted:" % groupchar, '"%s"' % newstr)
3626 if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
3627 keep_processing = False
3628 if not wxValidator_IsSilent():
3632 wxCallAfter(self._SetValue, newstr)
3633 wxCallAfter(self._SetInsertionPoint, newpos)
3634 keep_processing = False
3636 return keep_processing
3639 def _findNextEntry(self,pos, adjustInsert=True):
3640 """ Find the insertion point for the next valid entry character position."""
3641 if self._isTemplateChar(pos): # if changing fields, pay attn to flag
3642 adjustInsert = adjustInsert
3643 else: # else within a field; flag not relevant
3644 adjustInsert = False
3646 while self._isTemplateChar(pos) and pos < self._masklength:
3649 # if changing fields, and we've been told to adjust insert point,
3650 # look at new field; if empty and right-insert field,
3651 # adjust to right edge:
3652 if adjustInsert and pos < self._masklength:
3653 field = self._FindField(pos)
3654 start, end = field._extent
3655 slice = self._GetValue()[start:end]
3656 if field._insertRight and field.IsEmpty(slice):
3661 def _findNextTemplateChar(self, pos):
3662 """ Find the position of the next non-editable character in the mask."""
3663 while not self._isTemplateChar(pos) and pos < self._masklength:
3668 def _OnAutoCompleteField(self, event):
3669 dbg('wxMaskedEditMixin::_OnAutoCompleteField', indent =1)
3670 pos = self._GetInsertionPoint()
3671 field = self._FindField(pos)
3672 edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
3675 keycode = event.GetKeyCode()
3677 if field._fillChar != ' ':
3678 text = slice.replace(field._fillChar, '')
3682 keep_processing = True # (assume True to start)
3683 dbg('field._hasList?', field._hasList)
3685 dbg('choices:', field._choices)
3686 dbg('compareChoices:', field._compareChoices)
3687 choices, choice_required = field._compareChoices, field._choiceRequired
3688 if keycode in (WXK_PRIOR, WXK_UP):
3692 match_index, partial_match = self._autoComplete(direction, choices, text, compareNoCase=field._compareNoCase, current_index = field._autoCompleteIndex)
3693 if( match_index is None
3694 and (keycode in self._autoCompleteKeycodes + [WXK_PRIOR, WXK_NEXT]
3695 or (keycode in [WXK_UP, WXK_DOWN] and event.ShiftDown() ) ) ):
3696 # Select the 1st thing from the list:
3699 if( match_index is not None
3700 and ( keycode in self._autoCompleteKeycodes + [WXK_PRIOR, WXK_NEXT]
3701 or (keycode in [WXK_UP, WXK_DOWN] and event.ShiftDown())
3702 or (keycode == WXK_DOWN and partial_match) ) ):
3704 # We're allowed to auto-complete:
3706 value = self._GetValue()
3707 newvalue = value[:edit_start] + field._choices[match_index] + value[edit_end:]
3708 dbg('setting value to "%s"' % newvalue)
3709 self._SetValue(newvalue)
3710 self._SetInsertionPoint(min(edit_end, len(newvalue.rstrip())))
3711 self._OnAutoSelect(field, match_index)
3712 self._CheckValid() # recolor as appopriate
3715 if keycode in (WXK_UP, WXK_DOWN, WXK_LEFT, WXK_RIGHT):
3716 # treat as left right arrow if unshifted, tab/shift tab if shifted.
3717 if event.ShiftDown():
3718 if keycode in (WXK_DOWN, WXK_RIGHT):
3719 # remove "shifting" and treat as (forward) tab:
3720 event.m_shiftDown = False
3721 keep_processing = self._OnChangeField(event)
3723 keep_processing = self._OnArrow(event)
3724 # else some other key; keep processing the key
3726 dbg('keep processing?', keep_processing, indent=0)
3727 return keep_processing
3730 def _OnAutoSelect(self, field, match_index = None):
3732 Function called if autoselect feature is enabled and entire control
3735 dbg('wxMaskedEditMixin::OnAutoSelect', field._index)
3736 if match_index is not None:
3737 field._autoCompleteIndex = match_index
3740 def _autoComplete(self, direction, choices, value, compareNoCase, current_index):
3742 This function gets called in response to Auto-complete events.
3743 It attempts to find a match to the specified value against the
3744 list of choices; if exact match, the index of then next
3745 appropriate value in the list, based on the given direction.
3746 If not an exact match, it will return the index of the 1st value from
3747 the choice list for which the partial value can be extended to match.
3748 If no match found, it will return None.
3749 The function returns a 2-tuple, with the 2nd element being a boolean
3750 that indicates if partial match was necessary.
3752 dbg('autoComplete(direction=', direction, 'choices=',choices, 'value=',value,'compareNoCase?', compareNoCase, 'current_index:', current_index, indent=1)
3754 dbg('nothing to match against', indent=0)
3755 return (None, False)
3757 partial_match = False
3760 value = value.lower()
3762 last_index = len(choices) - 1
3763 if value in choices:
3764 dbg('"%s" in', choices)
3765 if current_index is not None and choices[current_index] == value:
3766 index = current_index
3768 index = choices.index(value)
3770 dbg('matched "%s" (%d)' % (choices[index], index))
3772 dbg('going to previous')
3773 if index == 0: index = len(choices) - 1
3776 if index == len(choices) - 1: index = 0
3778 dbg('change value to "%s" (%d)' % (choices[index], index))
3781 partial_match = True
3782 value = value.strip()
3783 dbg('no match; try to auto-complete:')
3785 dbg('searching for "%s"' % value)
3786 if current_index is None:
3787 indices = range(len(choices))
3792 indices = range(current_index +1, len(choices)) + range(current_index+1)
3793 dbg('range(current_index+1 (%d), len(choices) (%d)) + range(%d):' % (current_index+1, len(choices), current_index+1), indices)
3795 indices = range(current_index-1, -1, -1) + range(len(choices)-1, current_index-1, -1)
3796 dbg('range(current_index-1 (%d), -1) + range(len(choices)-1 (%d)), current_index-1 (%d):' % (current_index-1, len(choices)-1, current_index-1), indices)
3797 ## dbg('indices:', indices)
3798 for index in indices:
3799 choice = choices[index]
3800 if choice.find(value, 0) == 0:
3801 dbg('match found:', choice)
3804 else: dbg('choice: "%s" - no match' % choice)
3805 if match is not None:
3806 dbg('matched', match)
3808 dbg('no match found')
3810 return (match, partial_match)
3813 def _AdjustField(self, pos):
3815 This function gets called by default whenever the cursor leaves a field.
3816 The pos argument given is the char position before leaving that field.
3817 By default, floating point, integer and date values are adjusted to be
3818 legal in this function. Derived classes may override this function
3819 to modify the value of the control in a different way when changing fields.
3821 NOTE: these change the value immediately, and restore the cursor to
3822 the passed location, so that any subsequent code can then move it
3823 based on the operation being performed.
3825 newvalue = value = self._GetValue()
3826 field = self._FindField(pos)
3827 start, end, slice = self._FindFieldExtent(getslice=True)
3828 newfield = field._AdjustField(slice)
3829 newvalue = value[:start] + newfield + value[end:]
3831 if self._isFloat and newvalue != self._template:
3832 newvalue = self._adjustFloat(newvalue)
3834 if self._ctrl_constraints._isInt and value != self._template:
3835 newvalue = self._adjustInt(value)
3837 if self._isDate and value != self._template:
3838 newvalue = self._adjustDate(value, fixcentury=True)
3839 if self._4digityear:
3840 year2dig = self._dateExtent - 2
3841 if pos == year2dig and value[year2dig] != newvalue[year2dig]:
3844 if newvalue != value:
3845 self._SetValue(newvalue)
3846 self._SetInsertionPoint(pos)
3849 def _adjustKey(self, pos, key):
3850 """ Apply control formatting to the key (e.g. convert to upper etc). """
3851 field = self._FindField(pos)
3852 if field._forceupper and key in range(97,123):
3853 key = ord( chr(key).upper())
3855 if field._forcelower and key in range(97,123):
3856 key = ord( chr(key).lower())
3861 def _adjustPos(self, pos, key):
3863 Checks the current insertion point position and adjusts it if
3864 necessary to skip over non-editable characters.
3866 dbg('_adjustPos', pos, key, indent=1)
3867 sel_start, sel_to = self._GetSelection()
3868 # If a numeric or decimal mask, and negatives allowed, reserve the
3869 # first space for sign, and last one if using parens.
3871 and ((pos == self._signpos and key in (ord('-'), ord('+'), ord(' ')) )
3872 or self._useParens and pos == self._masklength -1)):
3873 dbg('adjusted pos:', pos, indent=0)
3876 if key not in self._nav:
3877 field = self._FindField(pos)
3879 dbg('field._insertRight?', field._insertRight)
3880 if field._insertRight: # if allow right-insert
3881 start, end = field._extent
3882 slice = self._GetValue()[start:end].strip()
3883 field_len = end - start
3884 if pos == end: # if cursor at right edge of field
3885 # if not filled or supposed to stay in field, keep current position
3887 ## dbg('len (slice):', len(slice))
3888 ## dbg('field_len?', field_len)
3889 ## dbg('pos==end; len (slice) < field_len?', len(slice) < field_len)
3890 ## dbg('not field._moveOnFieldFull?', not field._moveOnFieldFull)
3891 if len(slice) == field_len and field._moveOnFieldFull:
3892 # move cursor to next field:
3893 pos = self._findNextEntry(pos)
3894 self._SetInsertionPoint(pos)
3896 self._SetSelection(pos, sel_to) # restore selection
3898 self._SetSelection(pos, pos) # remove selection
3899 else: # leave cursor alone
3902 # if at start of control, move to right edge
3903 if sel_to == sel_start and self._isTemplateChar(pos) and pos != end:
3904 pos = end # move to right edge
3905 ## elif sel_start <= start and sel_to == end:
3906 ## # select to right edge of field - 1 (to replace char)
3908 ## self._SetInsertionPoint(pos)
3909 ## # restore selection
3910 ## self._SetSelection(sel_start, pos)
3912 elif self._signOk and sel_start == 0: # if selected to beginning and signed,
3913 # adjust to past reserved sign position:
3914 pos = self._fields[0]._extent[0]
3915 self._SetInsertionPoint(pos)
3917 self._SetSelection(pos, sel_to)
3919 pass # leave position/selection alone
3921 # else make sure the user is not trying to type over a template character
3922 # If they are, move them to the next valid entry position
3923 elif self._isTemplateChar(pos):
3924 if( not field._moveOnFieldFull
3925 and (not self._signOk
3927 and field._index == 0
3928 and pos > 0) ) ): # don't move to next field without explicit cursor movement
3931 # find next valid position
3932 pos = self._findNextEntry(pos)
3933 self._SetInsertionPoint(pos)
3934 if pos < sel_to: # restore selection
3935 self._SetSelection(pos, sel_to)
3936 dbg('adjusted pos:', pos, indent=0)
3940 def _adjustFloat(self, candidate=None):
3942 'Fixes' an floating point control. Collapses spaces, right-justifies, etc.
3944 dbg('wxMaskedEditMixin::_adjustFloat, candidate = "%s"' % candidate, indent=1)
3945 lenInt,lenFraction = [len(s) for s in self._mask.split('.')] ## Get integer, fraction lengths
3947 if candidate is None: value = self._GetValue()
3948 else: value = candidate
3949 dbg('value = "%(value)s"' % locals(), 'len(value):', len(value))
3950 intStr, fracStr = value.split(self._decimalChar)
3952 intStr = self._fields[0]._AdjustField(intStr)
3953 dbg('adjusted intStr: "%s"' % intStr)
3954 lenInt = len(intStr)
3955 fracStr = fracStr + ('0'*(lenFraction-len(fracStr))) # add trailing spaces to decimal
3957 dbg('intStr "%(intStr)s"' % locals())
3958 dbg('lenInt:', lenInt)
3960 intStr = string.rjust( intStr[-lenInt:], lenInt)
3961 dbg('right-justifed intStr = "%(intStr)s"' % locals())
3962 newvalue = intStr + self._decimalChar + fracStr
3965 if len(newvalue) < self._masklength:
3966 newvalue = ' ' + newvalue
3967 signedvalue = self._getSignedValue(newvalue)[0]
3968 if signedvalue is not None: newvalue = signedvalue
3970 # Finally, align string with decimal position, left-padding with
3972 newdecpos = newvalue.find(self._decimalChar)
3973 if newdecpos < self._decimalpos:
3974 padlen = self._decimalpos - newdecpos
3975 newvalue = string.join([' ' * padlen] + [newvalue] ,'')
3977 if self._signOk and self._useParens:
3978 if newvalue.find('(') != -1:
3979 newvalue = newvalue[:-1] + ')'
3981 newvalue = newvalue[:-1] + ' '
3983 dbg('newvalue = "%s"' % newvalue)
3984 if candidate is None:
3985 wxCallAfter(self._SetValue, newvalue)
3990 def _adjustInt(self, candidate=None):
3991 """ 'Fixes' an integer control. Collapses spaces, right or left-justifies."""
3992 dbg("wxMaskedEditMixin::_adjustInt", candidate)
3993 lenInt = self._masklength
3994 if candidate is None: value = self._GetValue()
3995 else: value = candidate
3997 intStr = self._fields[0]._AdjustField(value)
3998 intStr = intStr.strip() # drop extra spaces
3999 dbg('adjusted field: "%s"' % intStr)
4001 if self._isNeg and intStr.find('-') == -1 and intStr.find('(') == -1:
4003 intStr = '(' + intStr + ')'
4005 intStr = '-' + intStr
4006 elif self._isNeg and intStr.find('-') != -1 and self._useParens:
4007 intStr = intStr.replace('-', '(')
4009 if( self._signOk and ((self._useParens and intStr.find('(') == -1)
4010 or (not self._useParens and intStr.find('-') == -1))):
4011 intStr = ' ' + intStr
4013 intStr += ' ' # space for right paren position
4015 elif self._signOk and self._useParens and intStr.find('(') != -1 and intStr.find(')') == -1:
4016 # ensure closing right paren:
4019 if self._fields[0]._alignRight: ## Only if right-alignment is enabled
4020 intStr = intStr.rjust( lenInt )
4022 intStr = intStr.ljust( lenInt )
4024 if candidate is None:
4025 wxCallAfter(self._SetValue, intStr )
4029 def _adjustDate(self, candidate=None, fixcentury=False, force4digit_year=False):
4031 'Fixes' a date control, expanding the year if it can.
4032 Applies various self-formatting options.
4034 dbg("wxMaskedEditMixin::_adjustDate", indent=1)
4035 if candidate is None: text = self._GetValue()
4036 else: text = candidate
4038 if self._datestyle == "YMD":
4043 dbg('getYear: "%s"' % getYear(text, self._datestyle))
4044 year = string.replace( getYear( text, self._datestyle),self._fields[year_field]._fillChar,"") # drop extra fillChars
4045 month = getMonth( text, self._datestyle)
4046 day = getDay( text, self._datestyle)
4047 dbg('self._datestyle:', self._datestyle, 'year:', year, 'Month', month, 'day:', day)
4050 yearstart = self._dateExtent - 4
4054 or (self._GetInsertionPoint() > yearstart+1 and text[yearstart+2] == ' ')
4055 or (self._GetInsertionPoint() > yearstart+2 and text[yearstart+3] == ' ') ) ):
4056 ## user entered less than four digits and changing fields or past point where we could
4057 ## enter another digit:
4061 dbg('bad year=', year)
4062 year = text[yearstart:self._dateExtent]
4064 if len(year) < 4 and yearVal:
4066 # Fix year adjustment to be less "20th century" :-) and to adjust heuristic as the
4068 now = wxDateTime_Now()
4069 century = (now.GetYear() /100) * 100 # "this century"
4070 twodig_year = now.GetYear() - century # "this year" (2 digits)
4071 # if separation between today's 2-digit year and typed value > 50,
4072 # assume last century,
4073 # else assume this century.
4075 # Eg: if 2003 and yearVal == 30, => 2030
4076 # if 2055 and yearVal == 80, => 2080
4077 # if 2010 and yearVal == 96, => 1996
4079 if abs(yearVal - twodig_year) > 50:
4080 yearVal = (century - 100) + yearVal
4082 yearVal = century + yearVal
4083 year = str( yearVal )
4084 else: # pad with 0's to make a 4-digit year
4085 year = "%04d" % yearVal
4086 if self._4digityear or force4digit_year:
4087 text = makeDate(year, month, day, self._datestyle, text) + text[self._dateExtent:]
4088 dbg('newdate: "%s"' % text, indent=0)
4092 def _goEnd(self, getPosOnly=False):
4093 """ Moves the insertion point to the end of user-entry """
4094 dbg("wxMaskedEditMixin::_goEnd; getPosOnly:", getPosOnly, indent=1)
4095 text = self._GetValue()
4096 ## dbg('text: "%s"' % text)
4098 if len(text.rstrip()):
4099 for i in range( min( self._masklength-1, len(text.rstrip())), -1, -1):
4100 ## dbg('i:', i, 'self._isMaskChar(%d)' % i, self._isMaskChar(i))
4101 if self._isMaskChar(i):
4103 ## dbg("text[%d]: '%s'" % (i, char))
4109 pos = self._goHome(getPosOnly=True)
4111 pos = min(i,self._masklength)
4113 field = self._FindField(pos)
4114 start, end = field._extent
4115 if field._insertRight and pos < end:
4117 dbg('next pos:', pos)
4122 self._SetInsertionPoint(pos)
4125 def _goHome(self, getPosOnly=False):
4126 """ Moves the insertion point to the beginning of user-entry """
4127 dbg("wxMaskedEditMixin::_goHome; getPosOnly:", getPosOnly, indent=1)
4128 text = self._GetValue()
4129 for i in range(self._masklength):
4130 if self._isMaskChar(i):
4137 self._SetInsertionPoint(max(i,0))
4141 def _getAllowedChars(self, pos):
4142 """ Returns a string of all allowed user input characters for the provided
4143 mask character plus control options
4145 maskChar = self.maskdict[pos]
4146 okchars = self.maskchardict[maskChar] ## entry, get mask approved characters
4147 field = self._FindField(pos)
4148 if okchars and field._okSpaces: ## Allow spaces?
4150 if okchars and field._includeChars: ## any additional included characters?
4151 okchars += field._includeChars
4152 ## dbg('okchars[%d]:' % pos, okchars)
4156 def _isMaskChar(self, pos):
4157 """ Returns True if the char at position pos is a special mask character (e.g. NCXaA#)
4159 if pos < self._masklength:
4160 return self.ismasked[pos]
4165 def _isTemplateChar(self,Pos):
4166 """ Returns True if the char at position pos is a template character (e.g. -not- NCXaA#)
4168 if Pos < self._masklength:
4169 return not self._isMaskChar(Pos)
4174 def _isCharAllowed(self, char, pos, checkRegex=False, allowAutoSelect=True, ignoreInsertRight=False):
4175 """ Returns True if character is allowed at the specific position, otherwise False."""
4176 dbg('_isCharAllowed', char, pos, checkRegex, indent=1)
4177 field = self._FindField(pos)
4178 right_insert = False
4180 if self.controlInitialized:
4181 sel_start, sel_to = self._GetSelection()
4183 sel_start, sel_to = pos, pos
4185 if (field._insertRight or self._ctrl_constraints._insertRight) and not ignoreInsertRight:
4186 start, end = field._extent
4187 field_len = end - start
4188 if self.controlInitialized:
4189 value = self._GetValue()
4190 fstr = value[start:end].strip()
4192 while fstr and fstr[0] == '0':
4194 input_len = len(fstr)
4195 if self._signOk and '-' in fstr or '(' in fstr:
4196 input_len -= 1 # sign can move out of field, so don't consider it in length
4198 value = self._template
4199 input_len = 0 # can't get the current "value", so use 0
4202 # if entire field is selected or position is at end and field is not full,
4203 # or if allowed to right-insert at any point in field and field is not full and cursor is not at a fillChar:
4204 if( (sel_start, sel_to) == field._extent
4205 or (pos == end and input_len < field_len)):
4207 dbg('pos = end - 1 = ', pos, 'right_insert? 1')
4209 elif( field._allowInsert and sel_start == sel_to
4210 and (sel_to == end or (sel_to < self._masklength and value[sel_start] != field._fillChar))
4211 and input_len < field_len ):
4212 pos = sel_to - 1 # where character will go
4213 dbg('pos = sel_to - 1 = ', pos, 'right_insert? 1')
4215 # else leave pos alone...
4217 dbg('pos stays ', pos, 'right_insert? 0')
4220 if self._isTemplateChar( pos ): ## if a template character, return empty
4221 dbg('%d is a template character; returning False' % pos, indent=0)
4224 if self._isMaskChar( pos ):
4225 okChars = self._getAllowedChars(pos)
4227 if self._fields[0]._groupdigits and (self._isInt or (self._isFloat and pos < self._decimalpos)):
4228 okChars += self._fields[0]._groupChar
4231 if self._isInt or (self._isFloat and pos < self._decimalpos):
4235 elif self._useParens and (self._isInt or (self._isFloat and pos > self._decimalpos)):
4238 ## dbg('%s in %s?' % (char, okChars), char in okChars)
4239 approved = char in okChars
4241 if approved and checkRegex:
4242 dbg("checking appropriate regex's")
4243 value = self._eraseSelection(self._GetValue())
4249 newvalue, ignore, ignore, ignore, ignore = self._insertKey(char, at, sel_start, sel_to, value, allowAutoSelect=True)
4251 newvalue, ignore = self._insertKey(char, at, sel_start, sel_to, value)
4252 dbg('newvalue: "%s"' % newvalue)
4254 fields = [self._FindField(pos)] + [self._ctrl_constraints]
4255 for field in fields: # includes fields[-1] == "ctrl_constraints"
4256 if field._regexMask and field._filter:
4257 dbg('checking vs. regex')
4258 start, end = field._extent
4259 slice = newvalue[start:end]
4260 approved = (re.match( field._filter, slice) is not None)
4261 dbg('approved?', approved)
4262 if not approved: break
4266 dbg('%d is a !???! character; returning False', indent=0)
4270 def _applyFormatting(self):
4271 """ Apply formatting depending on the control's state.
4272 Need to find a way to call this whenever the value changes, in case the control's
4273 value has been changed or set programatically.
4276 dbg('wxMaskedEditMixin::_applyFormatting', indent=1)
4278 # Handle negative numbers
4280 text, signpos, right_signpos = self._getSignedValue()
4281 dbg('text: "%s", signpos:' % text, signpos)
4282 if not text or text[signpos] not in ('-','('):
4284 dbg('no valid sign found; new sign:', self._isNeg)
4285 if text and signpos != self._signpos:
4286 self._signpos = signpos
4287 elif text and self._valid and not self._isNeg and text[signpos] in ('-', '('):
4288 dbg('setting _isNeg to True')
4290 dbg('self._isNeg:', self._isNeg)
4292 if self._signOk and self._isNeg:
4293 fc = self._signedForegroundColour
4295 fc = self._foregroundColour
4297 if hasattr(fc, '_name'):
4301 dbg('setting foreground to', c)
4302 self.SetForegroundColour(fc)
4307 bc = self._emptyBackgroundColour
4309 bc = self._validBackgroundColour
4312 bc = self._invalidBackgroundColour
4313 if hasattr(bc, '_name'):
4317 dbg('setting background to', c)
4318 self.SetBackgroundColour(bc)
4320 dbg(indent=0, suspend=0)
4323 def _getAbsValue(self, candidate=None):
4324 """ Return an unsigned value (i.e. strip the '-' prefix if any), and sign position(s).
4326 dbg('wxMaskedEditMixin::_getAbsValue; candidate="%s"' % candidate, indent=1)
4327 if candidate is None: text = self._GetValue()
4328 else: text = candidate
4329 right_signpos = text.find(')')
4332 if self._ctrl_constraints._alignRight and self._fields[0]._fillChar == ' ':
4333 signpos = text.find('-')
4335 dbg('no - found; searching for (')
4336 signpos = text.find('(')
4338 dbg('- found at', signpos)
4341 dbg('signpos still -1')
4342 dbg('len(%s) (%d) < len(%s) (%d)?' % (text, len(text), self._mask, self._masklength), len(text) < self._masklength)
4343 if len(text) < self._masklength:
4345 if len(text) < self._masklength:
4347 if len(text) > self._masklength and text[-1] in (')', ' '):
4350 dbg('len(%s) (%d), len(%s) (%d)' % (text, len(text), self._mask, self._masklength))
4351 dbg('len(%s) - (len(%s) + 1):' % (text, text.lstrip()) , len(text) - (len(text.lstrip()) + 1))
4352 signpos = len(text) - (len(text.lstrip()) + 1)
4354 if self._useParens and not text.strip():
4355 signpos -= 1 # empty value; use penultimate space
4356 dbg('signpos:', signpos)
4358 text = text[:signpos] + ' ' + text[signpos+1:]
4363 text = self._template[0] + text[1:]
4367 if right_signpos != -1:
4369 text = text[:right_signpos] + ' ' + text[right_signpos+1:]
4370 elif len(text) > self._masklength:
4371 text = text[:right_signpos] + text[right_signpos+1:]
4375 elif self._useParens and self._signOk:
4376 # figure out where it ought to go:
4377 right_signpos = self._masklength - 1 # initial guess
4378 if not self._ctrl_constraints._alignRight:
4379 dbg('not right-aligned')
4380 if len(text.strip()) == 0:
4381 right_signpos = signpos + 1
4382 elif len(text.strip()) < self._masklength:
4383 right_signpos = len(text.rstrip())
4384 dbg('right_signpos:', right_signpos)
4386 groupchar = self._fields[0]._groupChar
4388 value = long(text.replace(groupchar,'').replace('(','-').replace(')','').replace(' ', ''))
4390 dbg('invalid number', indent=0)
4391 return None, signpos, right_signpos
4395 groupchar = self._fields[0]._groupChar
4396 value = float(text.replace(groupchar,'').replace(self._decimalChar, '.').replace('(', '-').replace(')','').replace(' ', ''))
4397 dbg('value:', value)
4401 if value < 0 and value is not None:
4402 signpos = text.find('-')
4404 signpos = text.find('(')
4406 text = text[:signpos] + self._template[signpos] + text[signpos+1:]
4408 # look forwards up to the decimal point for the 1st non-digit
4409 dbg('decimal pos:', self._decimalpos)
4410 dbg('text: "%s"' % text)
4412 signpos = self._decimalpos - (len(text[:self._decimalpos].lstrip()) + 1)
4413 if text[signpos+1] in ('-','('):
4417 dbg('signpos:', signpos)
4421 right_signpos = self._masklength - 1
4422 text = text[:right_signpos] + ' '
4423 if text[signpos] == '(':
4424 text = text[:signpos] + ' ' + text[signpos+1:]
4426 right_signpos = text.find(')')
4427 if right_signpos != -1:
4432 dbg('invalid number')
4435 dbg('abstext = "%s"' % text, 'signpos:', signpos, 'right_signpos:', right_signpos)
4437 return text, signpos, right_signpos
4440 def _getSignedValue(self, candidate=None):
4441 """ Return a signed value by adding a "-" prefix if the value
4442 is set to negative, or a space if positive.
4444 dbg('wxMaskedEditMixin::_getSignedValue; candidate="%s"' % candidate, indent=1)
4445 if candidate is None: text = self._GetValue()
4446 else: text = candidate
4449 abstext, signpos, right_signpos = self._getAbsValue(text)
4453 return abstext, signpos, right_signpos
4455 if self._isNeg or text[signpos] in ('-', '('):
4462 if abstext[signpos] not in string.digits:
4463 text = abstext[:signpos] + sign + abstext[signpos+1:]
4465 # this can happen if value passed is too big; sign assumed to be
4466 # in position 0, but if already filled with a digit, prepend sign...
4467 text = sign + abstext
4468 if self._useParens and text.find('(') != -1:
4469 text = text[:right_signpos] + ')' + text[right_signpos+1:]
4472 dbg('signedtext = "%s"' % text, 'signpos:', signpos, 'right_signpos', right_signpos)
4474 return text, signpos, right_signpos
4477 def GetPlainValue(self, candidate=None):
4478 """ Returns control's value stripped of the template text.
4479 plainvalue = wxMaskedEditMixin.GetPlainValue()
4481 dbg('wxMaskedEditMixin::GetPlainValue; candidate="%s"' % candidate, indent=1)
4483 if candidate is None: text = self._GetValue()
4484 else: text = candidate
4487 dbg('returned ""', indent=0)
4491 for idx in range( min(len(self._template), len(text)) ):
4492 if self._mask[idx] in maskchars:
4495 if self._isFloat or self._isInt:
4496 dbg('plain so far: "%s"' % plain)
4497 plain = plain.replace('(', '-').replace(')', ' ')
4498 dbg('plain after sign regularization: "%s"' % plain)
4500 if self._signOk and self._isNeg and plain.count('-') == 0:
4501 # must be in reserved position; add to "plain value"
4502 plain = '-' + plain.strip()
4504 if self._fields[0]._alignRight:
4505 lpad = plain.count(',')
4506 plain = ' ' * lpad + plain.replace(',','')
4508 plain = plain.replace(',','')
4509 dbg('plain after pad and group:"%s"' % plain)
4511 dbg('returned "%s"' % plain.rstrip(), indent=0)
4512 return plain.rstrip()
4515 def IsEmpty(self, value=None):
4517 Returns True if control is equal to an empty value.
4518 (Empty means all editable positions in the template == fillChar.)
4520 if value is None: value = self._GetValue()
4521 if value == self._template and not self._defaultValue:
4522 ## dbg("IsEmpty? 1 (value == self._template and not self._defaultValue)")
4523 return True # (all mask chars == fillChar by defn)
4524 elif value == self._template:
4526 for pos in range(len(self._template)):
4527 ## dbg('isMaskChar(%(pos)d)?' % locals(), self._isMaskChar(pos))
4528 ## dbg('value[%(pos)d] != self._fillChar?' %locals(), value[pos] != self._fillChar[pos])
4529 if self._isMaskChar(pos) and value[pos] not in (' ', self._fillChar[pos]):
4531 ## dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals())
4534 ## dbg("IsEmpty? 0 (value doesn't match template)")
4538 def IsDefault(self, value=None):
4540 Returns True if the value specified (or the value of the control if not specified)
4541 is equal to the default value.
4543 if value is None: value = self._GetValue()
4544 return value == self._template
4547 def IsValid(self, value=None):
4548 """ Indicates whether the value specified (or the current value of the control
4549 if not specified) is considered valid."""
4550 ## dbg('wxMaskedEditMixin::IsValid("%s")' % value, indent=1)
4551 if value is None: value = self._GetValue()
4552 ret = self._CheckValid(value)
4557 def _eraseSelection(self, value=None, sel_start=None, sel_to=None):
4558 """ Used to blank the selection when inserting a new character. """
4559 dbg("wxMaskedEditMixin::_eraseSelection", indent=1)
4560 if value is None: value = self._GetValue()
4561 if sel_start is None or sel_to is None:
4562 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
4563 dbg('value: "%s"' % value)
4564 dbg("current sel_start, sel_to:", sel_start, sel_to)
4566 newvalue = list(value)
4567 for i in range(sel_start, sel_to):
4568 if self._signOk and newvalue[i] in ('-', '(', ')'):
4569 dbg('found sign (%s) at' % newvalue[i], i)
4571 # balance parentheses:
4572 if newvalue[i] == '(':
4573 right_signpos = value.find(')')
4574 if right_signpos != -1:
4575 newvalue[right_signpos] = ' '
4577 elif newvalue[i] == ')':
4578 left_signpos = value.find('(')
4579 if left_signpos != -1:
4580 newvalue[left_signpos] = ' '
4584 elif self._isMaskChar(i):
4585 field = self._FindField(i)
4589 newvalue[i] = self._template[i]
4591 value = string.join(newvalue,"")
4592 dbg('new value: "%s"' % value)
4597 def _insertKey(self, char, pos, sel_start, sel_to, value, allowAutoSelect=False):
4598 """ Handles replacement of the character at the current insertion point."""
4599 dbg('wxMaskedEditMixin::_insertKey', "\'" + char + "\'", pos, sel_start, sel_to, '"%s"' % value, indent=1)
4601 text = self._eraseSelection(value)
4602 field = self._FindField(pos)
4603 start, end = field._extent
4607 if pos != sel_start and sel_start == sel_to:
4608 # adjustpos must have moved the position; make selection match:
4609 sel_start = sel_to = pos
4611 dbg('field._insertRight?', field._insertRight)
4612 if( field._insertRight # field allows right insert
4613 and ((sel_start, sel_to) == field._extent # and whole field selected
4614 or (sel_start == sel_to # or nothing selected
4615 and (sel_start == end # and cursor at right edge
4616 or (field._allowInsert # or field allows right-insert
4617 and sel_start < end # next to other char in field:
4618 and text[sel_start] != field._fillChar) ) ) ) ):
4620 fstr = text[start:end]
4621 erasable_chars = [field._fillChar, ' ']
4624 erasable_chars.append('0')
4627 ## dbg("fstr[0]:'%s'" % fstr[0])
4628 ## dbg('field_index:', field._index)
4629 ## dbg("fstr[0] in erasable_chars?", fstr[0] in erasable_chars)
4630 ## dbg("self._signOk and field._index == 0 and fstr[0] in ('-','(')?",
4631 ## self._signOk and field._index == 0 and fstr[0] in ('-','('))
4632 if fstr[0] in erasable_chars or (self._signOk and field._index == 0 and fstr[0] in ('-','(')):
4634 ## dbg('value: "%s"' % text)
4635 ## dbg('fstr: "%s"' % fstr)
4636 ## dbg("erased: '%s'" % erased)
4637 field_sel_start = sel_start - start
4638 field_sel_to = sel_to - start
4639 dbg('left fstr: "%s"' % fstr[1:field_sel_start])
4640 dbg('right fstr: "%s"' % fstr[field_sel_to:end])
4641 fstr = fstr[1:field_sel_start] + char + fstr[field_sel_to:end]
4642 if field._alignRight and sel_start != sel_to:
4643 field_len = end - start
4644 ## pos += (field_len - len(fstr)) # move cursor right by deleted amount
4646 dbg('setting pos to:', pos)
4648 fstr = '0' * (field_len - len(fstr)) + fstr
4650 fstr = fstr.rjust(field_len) # adjust the field accordingly
4651 dbg('field str: "%s"' % fstr)
4653 newtext = text[:start] + fstr + text[end:]
4654 if erased in ('-', '(') and self._signOk:
4655 newtext = erased + newtext[1:]
4656 dbg('newtext: "%s"' % newtext)
4658 if self._signOk and field._index == 0:
4659 start -= 1 # account for sign position
4661 ## dbg('field._moveOnFieldFull?', field._moveOnFieldFull)
4662 ## dbg('len(fstr.lstrip()) == end-start?', len(fstr.lstrip()) == end-start)
4663 if( field._moveOnFieldFull and pos == end
4664 and len(fstr.lstrip()) == end-start): # if field now full
4665 newpos = self._findNextEntry(end) # go to next field
4667 newpos = pos # else keep cursor at current position
4672 dbg('newpos:', newpos)
4673 if self._signOk and self._useParens:
4674 old_right_signpos = text.find(')')
4676 if field._allowInsert and not field._insertRight and sel_to <= end and sel_start >= start:
4677 # inserting within a left-insert-capable field
4678 field_len = end - start
4679 before = text[start:sel_start]
4680 after = text[sel_to:end].strip()
4681 ## dbg("current field:'%s'" % text[start:end])
4682 ## dbg("before:'%s'" % before, "after:'%s'" % after)
4683 new_len = len(before) + len(after) + 1 # (for inserted char)
4684 ## dbg('new_len:', new_len)
4686 if new_len < field_len:
4687 retained = after + self._template[end-(field_len-new_len):end]
4688 elif new_len > end-start:
4689 retained = after[1:]
4693 left = text[0:start] + before
4694 ## dbg("left:'%s'" % left, "retained:'%s'" % retained)
4695 right = retained + text[end:]
4698 right = text[pos+1:]
4700 newtext = left + char + right
4702 if self._signOk and self._useParens:
4703 # Balance parentheses:
4704 left_signpos = newtext.find('(')
4706 if left_signpos == -1: # erased '('; remove ')'
4707 right_signpos = newtext.find(')')
4708 if right_signpos != -1:
4709 newtext = newtext[:right_signpos] + ' ' + newtext[right_signpos+1:]
4711 elif old_right_signpos != -1:
4712 right_signpos = newtext.find(')')
4714 if right_signpos == -1: # just replaced right-paren
4715 if newtext[pos] == ' ': # we just erased '); erase '('
4716 newtext = newtext[:left_signpos] + ' ' + newtext[left_signpos+1:]
4717 else: # replaced with digit; move ') over
4718 if self._ctrl_constraints._alignRight or self._isFloat:
4719 newtext = newtext[:-1] + ')'
4721 rstripped_text = newtext.rstrip()
4722 right_signpos = len(rstripped_text)
4723 dbg('old_right_signpos:', old_right_signpos, 'right signpos now:', right_signpos)
4724 newtext = newtext[:right_signpos] + ')' + newtext[right_signpos+1:]
4726 if( field._insertRight # if insert-right field (but we didn't start at right edge)
4727 and field._moveOnFieldFull # and should move cursor when full
4728 and len(newtext[start:end].strip()) == end-start): # and field now full
4729 newpos = self._findNextEntry(end) # go to next field
4730 dbg('newpos = nextentry =', newpos)
4732 dbg('pos:', pos, 'newpos:', pos+1)
4737 new_select_to = newpos # (default return values)
4741 if field._autoSelect:
4742 match_index, partial_match = self._autoComplete(1, # (always forward)
4743 field._compareChoices,
4745 compareNoCase=field._compareNoCase,
4746 current_index = field._autoCompleteIndex-1)
4747 if match_index is not None and partial_match:
4748 matched_str = newtext[start:end]
4749 newtext = newtext[:start] + field._choices[match_index] + newtext[end:]
4752 if field._insertRight:
4753 # adjust position to just after partial match in field
4754 newpos = end - (len(field._choices[match_index].strip()) - len(matched_str.strip()))
4756 elif self._ctrl_constraints._autoSelect:
4757 match_index, partial_match = self._autoComplete(
4758 1, # (always forward)
4759 self._ctrl_constraints._compareChoices,
4761 self._ctrl_constraints._compareNoCase,
4762 current_index = self._ctrl_constraints._autoCompleteIndex - 1)
4763 if match_index is not None and partial_match:
4764 matched_str = newtext
4765 newtext = self._ctrl_constraints._choices[match_index]
4766 new_select_to = self._ctrl_constraints._extent[1]
4767 match_field = self._ctrl_constraints
4768 if self._ctrl_constraints._insertRight:
4769 # adjust position to just after partial match in control:
4770 newpos = self._masklength - (len(self._ctrl_constraints._choices[match_index].strip()) - len(matched_str.strip()))
4772 dbg('newtext: "%s"' % newtext, 'newpos:', newpos, 'new_select_to:', new_select_to)
4774 return newtext, newpos, new_select_to, match_field, match_index
4776 dbg('newtext: "%s"' % newtext, 'newpos:', newpos)
4778 return newtext, newpos
4781 def _OnFocus(self,event):
4783 This event handler is currently necessary to work around new default
4784 behavior as of wxPython2.3.3;
4785 The TAB key auto selects the entire contents of the wxTextCtrl *after*
4786 the EVT_SET_FOCUS event occurs; therefore we can't query/adjust the selection
4787 *here*, because it hasn't happened yet. So to prevent this behavior, and
4788 preserve the correct selection when the focus event is not due to tab,
4789 we need to pull the following trick:
4791 dbg('wxMaskedEditMixin::_OnFocus')
4792 wxCallAfter(self._fixSelection)
4797 def _CheckValid(self, candidate=None):
4799 This is the default validation checking routine; It verifies that the
4800 current value of the control is a "valid value," and has the side
4801 effect of coloring the control appropriately.
4804 dbg('wxMaskedEditMixin::_CheckValid: candidate="%s"' % candidate, indent=1)
4805 oldValid = self._valid
4806 if candidate is None: value = self._GetValue()
4807 else: value = candidate
4808 dbg('value: "%s"' % value)
4810 valid = True # assume True
4812 if not self.IsDefault(value) and self._isDate: ## Date type validation
4813 valid = self._validateDate(value)
4814 dbg("valid date?", valid)
4816 elif not self.IsDefault(value) and self._isTime:
4817 valid = self._validateTime(value)
4818 dbg("valid time?", valid)
4820 elif not self.IsDefault(value) and (self._isInt or self._isFloat): ## Numeric type
4821 valid = self._validateNumeric(value)
4822 dbg("valid Number?", valid)
4824 if valid: # and not self.IsDefault(value): ## generic validation accounts for IsDefault()
4825 ## valid so far; ensure also allowed by any list or regex provided:
4826 valid = self._validateGeneric(value)
4827 dbg("valid value?", valid)
4829 dbg('valid?', valid)
4833 self._applyFormatting()
4834 if self._valid != oldValid:
4835 dbg('validity changed: oldValid =',oldValid,'newvalid =', self._valid)
4836 dbg('oldvalue: "%s"' % oldvalue, 'newvalue: "%s"' % self._GetValue())
4837 dbg(indent=0, suspend=0)
4841 def _validateGeneric(self, candidate=None):
4842 """ Validate the current value using the provided list or Regex filter (if any).
4844 if candidate is None:
4845 text = self._GetValue()
4849 valid = True # assume True
4850 for i in [-1] + self._field_indices: # process global constraints first:
4851 field = self._fields[i]
4852 start, end = field._extent
4853 slice = text[start:end]
4854 valid = field.IsValid(slice)
4861 def _validateNumeric(self, candidate=None):
4862 """ Validate that the value is within the specified range (if specified.)"""
4863 if candidate is None: value = self._GetValue()
4864 else: value = candidate
4866 groupchar = self._fields[0]._groupChar
4868 number = float(value.replace(groupchar, '').replace(self._decimalChar, '.').replace('(', '-').replace(')', ''))
4870 number = long( value.replace(groupchar, '').replace('(', '-').replace(')', ''))
4872 if self._fields[0]._alignRight:
4873 require_digit_at = self._fields[0]._extent[1]-1
4875 require_digit_at = self._fields[0]._extent[0]
4876 dbg('require_digit_at:', require_digit_at)
4877 dbg("value[rda]: '%s'" % value[require_digit_at])
4878 if value[require_digit_at] not in list(string.digits):
4882 dbg('number:', number)
4883 if self._ctrl_constraints._hasRange:
4884 valid = self._ctrl_constraints._rangeLow <= number <= self._ctrl_constraints._rangeHigh
4887 groupcharpos = value.rfind(groupchar)
4888 if groupcharpos != -1: # group char present
4889 dbg('groupchar found at', groupcharpos)
4890 if self._isFloat and groupcharpos > self._decimalpos:
4891 # 1st one found on right-hand side is past decimal point
4892 dbg('groupchar in fraction; illegal')
4895 integer = value[:self._decimalpos].strip()
4897 integer = value.strip()
4898 dbg("integer:'%s'" % integer)
4899 if integer[0] in ('-', '('):
4900 integer = integer[1:]
4901 if integer[-1] == ')':
4902 integer = integer[:-1]
4904 parts = integer.split(groupchar)
4905 dbg('parts:', parts)
4906 for i in range(len(parts)):
4907 if i == 0 and abs(int(parts[0])) > 999:
4908 dbg('group 0 too long; illegal')
4911 elif i > 0 and (len(parts[i]) != 3 or ' ' in parts[i]):
4912 dbg('group %i (%s) not right size; illegal' % (i, parts[i]))
4916 dbg('value not a valid number')
4921 def _validateDate(self, candidate=None):
4922 """ Validate the current date value using the provided Regex filter.
4923 Generally used for character types.BufferType
4925 dbg('wxMaskedEditMixin::_validateDate', indent=1)
4926 if candidate is None: value = self._GetValue()
4927 else: value = candidate
4928 dbg('value = "%s"' % value)
4929 text = self._adjustDate(value, force4digit_year=True) ## Fix the date up before validating it
4931 valid = True # assume True until proven otherwise
4934 # replace fillChar in each field with space:
4935 datestr = text[0:self._dateExtent]
4937 field = self._fields[i]
4938 start, end = field._extent
4939 fstr = datestr[start:end]
4940 fstr.replace(field._fillChar, ' ')
4941 datestr = datestr[:start] + fstr + datestr[end:]
4943 year, month, day = getDateParts( datestr, self._datestyle)
4945 dbg('self._dateExtent:', self._dateExtent)
4946 if self._dateExtent == 11:
4947 month = charmonths_dict[month.lower()]
4951 dbg('year, month, day:', year, month, day)
4954 dbg('cannot convert string to integer parts')
4957 dbg('cannot convert string to integer month')
4961 # use wxDateTime to unambiguously try to parse the date:
4962 # ### Note: because wxDateTime is *brain-dead* and expects months 0-11,
4963 # rather than 1-12, so handle accordingly:
4969 dbg("trying to create date from values day=%d, month=%d, year=%d" % (day,month,year))
4970 dateHandler = wxDateTimeFromDMY(day,month,year)
4974 dbg('cannot convert string to valid date')
4980 # wxDateTime doesn't take kindly to leading/trailing spaces when parsing,
4981 # so we eliminate them here:
4982 timeStr = text[self._dateExtent+1:].strip() ## time portion of the string
4984 dbg('timeStr: "%s"' % timeStr)
4986 checkTime = dateHandler.ParseTime(timeStr)
4987 valid = checkTime == len(timeStr)
4991 dbg('cannot convert string to valid time')
4992 if valid: dbg('valid date')
4997 def _validateTime(self, candidate=None):
4998 """ Validate the current time value using the provided Regex filter.
4999 Generally used for character types.BufferType
5001 dbg('wxMaskedEditMixin::_validateTime', indent=1)
5002 # wxDateTime doesn't take kindly to leading/trailing spaces when parsing,
5003 # so we eliminate them here:
5004 if candidate is None: value = self._GetValue().strip()
5005 else: value = candidate.strip()
5006 dbg('value = "%s"' % value)
5007 valid = True # assume True until proven otherwise
5009 dateHandler = wxDateTime_Today()
5011 checkTime = dateHandler.ParseTime(value)
5012 dbg('checkTime:', checkTime, 'len(value)', len(value))
5013 valid = checkTime == len(value)
5018 dbg('cannot convert string to valid time')
5019 if valid: dbg('valid time')
5024 def _OnKillFocus(self,event):
5025 """ Handler for EVT_KILL_FOCUS event.
5027 dbg('wxMaskedEditMixin::_OnKillFocus', 'isDate=',self._isDate, indent=1)
5028 if self._mask and self._IsEditable():
5029 self._AdjustField(self._GetInsertionPoint())
5030 self._CheckValid() ## Call valid handler
5032 self._LostFocus() ## Provided for subclass use
5037 def _fixSelection(self):
5039 This gets called after the TAB traversal selection is made, if the
5040 focus event was due to this, but before the EVT_LEFT_* events if
5041 the focus shift was due to a mouse event.
5043 The trouble is that, a priori, there's no explicit notification of
5044 why the focus event we received. However, the whole reason we need to
5045 do this is because the default behavior on TAB traveral in a wxTextCtrl is
5046 now to select the entire contents of the window, something we don't want.
5047 So we can *now* test the selection range, and if it's "the whole text"
5048 we can assume the cause, change the insertion point to the start of
5049 the control, and deselect.
5051 dbg('wxMaskedEditMixin::_fixSelection', indent=1)
5052 if not self._mask or not self._IsEditable():
5056 sel_start, sel_to = self._GetSelection()
5057 dbg('sel_start, sel_to:', sel_start, sel_to, 'self.IsEmpty()?', self.IsEmpty())
5059 if( sel_start == 0 and sel_to >= len( self._mask ) #(can be greater in numeric controls because of reserved space)
5060 and (not self._ctrl_constraints._autoSelect or self.IsEmpty() or self.IsDefault() ) ):
5061 # This isn't normally allowed, and so assume we got here by the new
5062 # "tab traversal" behavior, so we need to reset the selection
5063 # and insertion point:
5064 dbg('entire text selected; resetting selection to start of control')
5066 field = self._FindField(self._GetInsertionPoint())
5067 edit_start, edit_end = field._extent
5068 if field._selectOnFieldEntry:
5069 self._SetInsertionPoint(edit_start)
5070 self._SetSelection(edit_start, edit_end)
5072 elif field._insertRight:
5073 self._SetInsertionPoint(edit_end)
5074 self._SetSelection(edit_end, edit_end)
5076 elif (self._isFloat or self._isInt):
5078 text, signpos, right_signpos = self._getAbsValue()
5079 if text is None or text == self._template:
5080 integer = self._fields[0]
5081 edit_start, edit_end = integer._extent
5083 if integer._selectOnFieldEntry:
5084 dbg('select on field entry:')
5085 self._SetInsertionPoint(edit_start)
5086 self._SetSelection(edit_start, edit_end)
5088 elif integer._insertRight:
5089 dbg('moving insertion point to end')
5090 self._SetInsertionPoint(edit_end)
5091 self._SetSelection(edit_end, edit_end)
5093 dbg('numeric ctrl is empty; start at beginning after sign')
5094 self._SetInsertionPoint(signpos+1) ## Move past minus sign space if signed
5095 self._SetSelection(signpos+1, signpos+1)
5097 elif sel_start > self._goEnd(getPosOnly=True):
5098 dbg('cursor beyond the end of the user input; go to end of it')
5101 dbg('sel_start, sel_to:', sel_start, sel_to, 'self._masklength:', self._masklength)
5105 def _Keypress(self,key):
5106 """ Method provided to override OnChar routine. Return False to force
5107 a skip of the 'normal' OnChar process. Called before class OnChar.
5112 def _LostFocus(self):
5113 """ Method provided for subclasses. _LostFocus() is called after
5114 the class processes its EVT_KILL_FOCUS event code.
5119 def _OnDoubleClick(self, event):
5120 """ selects field under cursor on dclick."""
5121 pos = self._GetInsertionPoint()
5122 field = self._FindField(pos)
5123 start, end = field._extent
5124 self._SetInsertionPoint(start)
5125 self._SetSelection(start, end)
5129 """ Method provided for subclasses. Called by internal EVT_TEXT
5130 handler. Return False to override the class handler, True otherwise.
5137 Used to override the default Cut() method in base controls, instead
5138 copying the selection to the clipboard and then blanking the selection,
5139 leaving only the mask in the selected area behind.
5140 Note: _Cut (read "undercut" ;-) must be called from a Cut() override in the
5141 derived control because the mixin functions can't override a method of
5144 dbg("wxMaskedEditMixin::_Cut", indent=1)
5145 value = self._GetValue()
5146 dbg('current value: "%s"' % value)
5147 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
5148 dbg('selected text: "%s"' % value[sel_start:sel_to].strip())
5149 do = wxTextDataObject()
5150 do.SetText(value[sel_start:sel_to].strip())
5151 wxTheClipboard.Open()
5152 wxTheClipboard.SetData(do)
5153 wxTheClipboard.Close()
5155 if sel_to - sel_start != 0:
5160 # WS Note: overriding Copy is no longer necessary given that you
5161 # can no longer select beyond the last non-empty char in the control.
5163 ## def _Copy( self ):
5165 ## Override the wxTextCtrl's .Copy function, with our own
5166 ## that does validation. Need to strip trailing spaces.
5168 ## sel_start, sel_to = self._GetSelection()
5169 ## select_len = sel_to - sel_start
5170 ## textval = wxTextCtrl._GetValue(self)
5172 ## do = wxTextDataObject()
5173 ## do.SetText(textval[sel_start:sel_to].strip())
5174 ## wxTheClipboard.Open()
5175 ## wxTheClipboard.SetData(do)
5176 ## wxTheClipboard.Close()
5179 def _getClipboardContents( self ):
5180 """ Subroutine for getting the current contents of the clipboard.
5182 do = wxTextDataObject()
5183 wxTheClipboard.Open()
5184 success = wxTheClipboard.GetData(do)
5185 wxTheClipboard.Close()
5190 # Remove leading and trailing spaces before evaluating contents
5191 return do.GetText().strip()
5194 def _validatePaste(self, paste_text, sel_start, sel_to, raise_on_invalid=False):
5196 Used by paste routine and field choice validation to see
5197 if a given slice of paste text is legal for the area in question:
5198 returns validity, replacement text, and extent of paste in
5202 dbg('wxMaskedEditMixin::_validatePaste("%(paste_text)s", %(sel_start)d, %(sel_to)d), raise_on_invalid? %(raise_on_invalid)d' % locals(), indent=1)
5203 select_length = sel_to - sel_start
5204 maxlength = select_length
5205 dbg('sel_to - sel_start:', maxlength)
5207 maxlength = self._masklength - sel_start
5211 dbg('maxlength:', maxlength)
5212 length_considered = len(paste_text)
5213 if length_considered > maxlength:
5214 dbg('paste text will not fit into the %s:' % item, indent=0)
5215 if raise_on_invalid:
5216 dbg(indent=0, suspend=0)
5217 if item == 'control':
5218 raise ValueError('"%s" will not fit into the control "%s"' % (paste_text, self.name))
5220 raise ValueError('"%s" will not fit into the selection' % paste_text)
5222 dbg(indent=0, suspend=0)
5223 return False, None, None
5225 text = self._template
5226 dbg('length_considered:', length_considered)
5229 replacement_text = ""
5230 replace_to = sel_start
5232 while valid_paste and i < length_considered and replace_to < self._masklength:
5233 if paste_text[i:] == self._template[replace_to:length_considered]:
5234 # remainder of paste matches template; skip char-by-char analysis
5235 dbg('remainder paste_text[%d:] (%s) matches template[%d:%d]' % (i, paste_text[i:], replace_to, length_considered))
5236 replacement_text += paste_text[i:]
5237 replace_to = i = length_considered
5240 char = paste_text[i]
5241 field = self._FindField(replace_to)
5242 if not field._compareNoCase:
5243 if field._forceupper: char = char.upper()
5244 elif field._forcelower: char = char.lower()
5246 dbg('char:', "'"+char+"'", 'i =', i, 'replace_to =', replace_to)
5247 dbg('self._isTemplateChar(%d)?' % replace_to, self._isTemplateChar(replace_to))
5248 if not self._isTemplateChar(replace_to) and self._isCharAllowed( char, replace_to, allowAutoSelect=False, ignoreInsertRight=True):
5249 replacement_text += char
5250 dbg("not template(%(replace_to)d) and charAllowed('%(char)s',%(replace_to)d)" % locals())
5251 dbg("replacement_text:", '"'+replacement_text+'"')
5254 elif( char == self._template[replace_to]
5255 or (self._signOk and
5256 ( (i == 0 and (char == '-' or (self._useParens and char == '(')))
5257 or (i == self._masklength - 1 and self._useParens and char == ')') ) ) ):
5258 replacement_text += char
5259 dbg("'%(char)s' == template(%(replace_to)d)" % locals())
5260 dbg("replacement_text:", '"'+replacement_text+'"')
5264 next_entry = self._findNextEntry(replace_to, adjustInsert=False)
5265 if next_entry == replace_to:
5268 replacement_text += self._template[replace_to:next_entry]
5269 dbg("skipping template; next_entry =", next_entry)
5270 dbg("replacement_text:", '"'+replacement_text+'"')
5271 replace_to = next_entry # so next_entry will be considered on next loop
5273 if not valid_paste and raise_on_invalid:
5274 dbg('raising exception', indent=0, suspend=0)
5275 raise ValueError('"%s" cannot be inserted into the control "%s"' % (paste_text, self.name))
5277 elif i < len(paste_text):
5279 if raise_on_invalid:
5280 dbg('raising exception', indent=0, suspend=0)
5281 raise ValueError('"%s" will not fit into the control "%s"' % (paste_text, self.name))
5283 dbg('valid_paste?', valid_paste)
5285 dbg('replacement_text: "%s"' % replacement_text, 'replace to:', replace_to)
5286 dbg(indent=0, suspend=0)
5287 return valid_paste, replacement_text, replace_to
5290 def _Paste( self, value=None, raise_on_invalid=False, just_return_value=False ):
5292 Used to override the base control's .Paste() function,
5293 with our own that does validation.
5294 Note: _Paste must be called from a Paste() override in the
5295 derived control because the mixin functions can't override a
5296 method of a sibling class.
5298 dbg('wxMaskedEditMixin::_Paste (value = "%s")' % value, indent=1)
5300 paste_text = self._getClipboardContents()
5304 if paste_text is not None:
5305 dbg('paste text: "%s"' % paste_text)
5306 # (conversion will raise ValueError if paste isn't legal)
5307 sel_start, sel_to = self._GetSelection()
5308 dbg('selection:', (sel_start, sel_to))
5310 # special case: handle allowInsert fields properly
5311 field = self._FindField(sel_start)
5312 edit_start, edit_end = field._extent
5314 if field._allowInsert and sel_to <= edit_end and sel_start + len(paste_text) < edit_end:
5315 new_pos = sel_start + len(paste_text) # store for subsequent positioning
5316 paste_text = paste_text + self._GetValue()[sel_to:edit_end].rstrip()
5317 dbg('paste within insertable field; adjusted paste_text: "%s"' % paste_text, 'end:', edit_end)
5318 sel_to = sel_start + len(paste_text)
5320 # Another special case: paste won't fit, but it's a right-insert field where entire
5321 # non-empty value is selected, and there's room if the selection is expanded leftward:
5322 if( len(paste_text) > sel_to - sel_start
5323 and field._insertRight
5324 and sel_start > edit_start
5325 and sel_to >= edit_end
5326 and not self._GetValue()[edit_start:sel_start].strip() ):
5327 # text won't fit within selection, but left of selection is empty;
5328 # check to see if we can expand selection to accomodate the value:
5329 empty_space = sel_start - edit_start
5330 amount_needed = len(paste_text) - (sel_to - sel_start)
5331 if amount_needed <= empty_space:
5332 sel_start -= amount_needed
5333 dbg('expanded selection to:', (sel_start, sel_to))
5336 # another special case: deal with signed values properly:
5338 signedvalue, signpos, right_signpos = self._getSignedValue()
5339 paste_signpos = paste_text.find('-')
5340 if paste_signpos == -1:
5341 paste_signpos = paste_text.find('(')
5343 # if paste text will result in signed value:
5344 ## dbg('paste_signpos != -1?', paste_signpos != -1)
5345 ## dbg('sel_start:', sel_start, 'signpos:', signpos)
5346 ## dbg('field._insertRight?', field._insertRight)
5347 ## dbg('sel_start - len(paste_text) >= signpos?', sel_start - len(paste_text) <= signpos)
5348 if paste_signpos != -1 and (sel_start <= signpos
5349 or (field._insertRight and sel_start - len(paste_text) <= signpos)):
5353 # remove "sign" from paste text, so we can auto-adjust for sign type after paste:
5354 paste_text = paste_text.replace('-', ' ').replace('(',' ').replace(')','')
5355 dbg('unsigned paste text: "%s"' % paste_text)
5359 # another special case: deal with insert-right fields when selection is empty and
5360 # cursor is at end of field:
5361 ## dbg('field._insertRight?', field._insertRight)
5362 ## dbg('sel_start == edit_end?', sel_start == edit_end)
5363 ## dbg('sel_start', sel_start, 'sel_to', sel_to)
5364 if field._insertRight and sel_start == edit_end and sel_start == sel_to:
5365 sel_start -= len(paste_text)
5368 dbg('adjusted selection:', (sel_start, sel_to))
5371 valid_paste, replacement_text, replace_to = self._validatePaste(paste_text, sel_start, sel_to, raise_on_invalid)
5373 dbg('exception thrown', indent=0)
5377 dbg('paste text not legal for the selection or portion of the control following the cursor;')
5378 if not wxValidator_IsSilent():
5383 text = self._eraseSelection()
5385 new_text = text[:sel_start] + replacement_text + text[replace_to:]
5387 new_text = string.ljust(new_text,self._masklength)
5389 new_text, signpos, right_signpos = self._getSignedValue(candidate=new_text)
5392 new_text = new_text[:signpos] + '(' + new_text[signpos+1:right_signpos] + ')' + new_text[right_signpos+1:]
5394 new_text = new_text[:signpos] + '-' + new_text[signpos+1:]
5398 dbg("new_text:", '"'+new_text+'"')
5400 if not just_return_value:
5404 wxCallAfter(self._SetValue, new_text)
5406 new_pos = sel_start + len(replacement_text)
5407 wxCallAfter(self._SetInsertionPoint, new_pos)
5411 elif just_return_value:
5413 return self._GetValue()
5417 """ Provides an Undo() method in base controls. """
5418 dbg("wxMaskedEditMixin::_Undo", indent=1)
5419 value = self._GetValue()
5420 prev = self._prevValue
5421 dbg('current value: "%s"' % value)
5422 dbg('previous value: "%s"' % prev)
5424 dbg('no previous value', indent=0)
5428 # Determine what to select: (relies on fixed-length strings)
5429 # (This is a lot harder than it would first appear, because
5430 # of mask chars that stay fixed, and so break up the "diff"...)
5432 # Determine where they start to differ:
5434 length = len(value) # (both are same length in masked control)
5436 while( value[:i] == prev[:i] ):
5441 # handle signed values carefully, so undo from signed to unsigned or vice-versa
5444 text, signpos, right_signpos = self._getSignedValue(candidate=prev)
5446 if prev[signpos] == '(' and prev[right_signpos] == ')':
5450 # eliminate source of "far-end" undo difference if using balanced parens:
5451 value = value.replace(')', ' ')
5452 prev = prev.replace(')', ' ')
5453 elif prev[signpos] == '-':
5458 # Determine where they stop differing in "undo" result:
5459 sm = difflib.SequenceMatcher(None, a=value, b=prev)
5460 i, j, k = sm.find_longest_match(sel_start, length, sel_start, length)
5461 dbg('i,j,k = ', (i,j,k), 'value[i:i+k] = "%s"' % value[i:i+k], 'prev[j:j+k] = "%s"' % prev[j:j+k] )
5463 if k == 0: # no match found; select to end
5466 code_5tuples = sm.get_opcodes()
5467 for op, i1, i2, j1, j2 in code_5tuples:
5468 dbg("%7s value[%d:%d] (%s) prev[%d:%d] (%s)" %
5469 (op, i1, i2, value[i1:i2], j1, j2, prev[j1:j2]))
5472 # look backward through operations needed to produce "previous" value;
5473 # first change wins:
5474 for next_op in range(len(code_5tuples)-1, -1, -1):
5475 op, i1, i2, j1, j2 = code_5tuples[next_op]
5476 dbg('value[i1:i2]: "%s"' % value[i1:i2], 'template[i1:i2] "%s"' % self._template[i1:i2])
5477 if op == 'insert' and prev[j1:j2] != self._template[j1:j2]:
5478 dbg('insert found: selection =>', (j1, j2))
5483 elif op == 'delete' and value[i1:i2] != self._template[i1:i2]:
5484 field = self._FindField(i2)
5485 edit_start, edit_end = field._extent
5486 if field._insertRight and i2 == edit_end:
5492 dbg('delete found: selection =>', (sel_start, sel_to))
5495 elif op == 'replace':
5496 dbg('replace found: selection =>', (j1, j2))
5504 # now go forwards, looking for earlier changes:
5505 for next_op in range(len(code_5tuples)):
5506 op, i1, i2, j1, j2 = code_5tuples[next_op]
5507 field = self._FindField(i1)
5510 elif op == 'replace':
5511 dbg('setting sel_start to', i1)
5514 elif op == 'insert' and not value[i1:i2]:
5515 dbg('forward %s found' % op)
5516 if prev[j1:j2].strip():
5517 dbg('item to insert non-empty; setting sel_start to', j1)
5520 elif not field._insertRight:
5521 dbg('setting sel_start to inserted space:', j1)
5524 elif op == 'delete' and field._insertRight and not value[i1:i2].lstrip():
5527 # we've got what we need
5532 dbg('no insert,delete or replace found (!)')
5533 # do "left-insert"-centric processing of difference based on l.c.s.:
5534 if i == j and j != sel_start: # match starts after start of selection
5535 sel_to = sel_start + (j-sel_start) # select to start of match
5537 sel_to = j # (change ends at j)
5540 # There are several situations where the calculated difference is
5541 # not what we want to select. If changing sign, or just adding
5542 # group characters, we really don't want to highlight the characters
5543 # changed, but instead leave the cursor where it is.
5544 # Also, there a situations in which the difference can be ambiguous;
5547 # current value: 11234
5548 # previous value: 1111234
5550 # Where did the cursor actually lie and which 1s were selected on the delete
5553 # Also, difflib can "get it wrong;" Consider:
5555 # current value: " 128.66"
5556 # previous value: " 121.86"
5558 # difflib produces the following opcodes, which are sub-optimal:
5559 # equal value[0:9] ( 12) prev[0:9] ( 12)
5560 # insert value[9:9] () prev[9:11] (1.)
5561 # equal value[9:10] (8) prev[11:12] (8)
5562 # delete value[10:11] (.) prev[12:12] ()
5563 # equal value[11:12] (6) prev[12:13] (6)
5564 # delete value[12:13] (6) prev[13:13] ()
5566 # This should have been:
5567 # equal value[0:9] ( 12) prev[0:9] ( 12)
5568 # replace value[9:11] (8.6) prev[9:11] (1.8)
5569 # equal value[12:13] (6) prev[12:13] (6)
5571 # But it didn't figure this out!
5573 # To get all this right, we use the previous selection recorded to help us...
5575 if (sel_start, sel_to) != self._prevSelection:
5576 dbg('calculated selection', (sel_start, sel_to), "doesn't match previous", self._prevSelection)
5578 prev_sel_start, prev_sel_to = self._prevSelection
5579 field = self._FindField(sel_start)
5581 if self._signOk and (self._prevValue[sel_start] in ('-', '(', ')')
5582 or self._curValue[sel_start] in ('-', '(', ')')):
5583 # change of sign; leave cursor alone...
5584 sel_start, sel_to = self._prevSelection
5586 elif field._groupdigits and (self._curValue[sel_start:sel_to] == field._groupChar
5587 or self._prevValue[sel_start:sel_to] == field._groupChar):
5588 # do not highlight grouping changes
5589 sel_start, sel_to = self._prevSelection
5592 calc_select_len = sel_to - sel_start
5593 prev_select_len = prev_sel_to - prev_sel_start
5595 dbg('sel_start == prev_sel_start', sel_start == prev_sel_start)
5596 dbg('sel_to > prev_sel_to', sel_to > prev_sel_to)
5598 if prev_select_len >= calc_select_len:
5599 # old selection was bigger; trust it:
5600 sel_start, sel_to = self._prevSelection
5602 elif( sel_to > prev_sel_to # calculated select past last selection
5603 and prev_sel_to < len(self._template) # and prev_sel_to not at end of control
5604 and sel_to == len(self._template) ): # and calculated selection goes to end of control
5606 i, j, k = sm.find_longest_match(prev_sel_to, length, prev_sel_to, length)
5607 dbg('i,j,k = ', (i,j,k), 'value[i:i+k] = "%s"' % value[i:i+k], 'prev[j:j+k] = "%s"' % prev[j:j+k] )
5609 # difflib must not have optimized opcodes properly;
5613 # look for possible ambiguous diff:
5615 # if last change resulted in no selection, test from resulting cursor position:
5616 if prev_sel_start == prev_sel_to:
5617 calc_select_len = sel_to - sel_start
5618 field = self._FindField(prev_sel_start)
5620 # determine which way to search from last cursor position for ambiguous change:
5621 if field._insertRight:
5622 test_sel_start = prev_sel_start
5623 test_sel_to = prev_sel_start + calc_select_len
5625 test_sel_start = prev_sel_start - calc_select_len
5626 test_sel_to = prev_sel_start
5628 test_sel_start, test_sel_to = prev_sel_start, prev_sel_to
5630 dbg('test selection:', (test_sel_start, test_sel_to))
5631 dbg('calc change: "%s"' % self._prevValue[sel_start:sel_to])
5632 dbg('test change: "%s"' % self._prevValue[test_sel_start:test_sel_to])
5634 # if calculated selection spans characters, and same characters
5635 # "before" the previous insertion point are present there as well,
5636 # select the ones related to the last known selection instead.
5637 if( sel_start != sel_to
5638 and test_sel_to < len(self._template)
5639 and self._prevValue[test_sel_start:test_sel_to] == self._prevValue[sel_start:sel_to] ):
5641 sel_start, sel_to = test_sel_start, test_sel_to
5643 dbg('sel_start, sel_to:', sel_start, sel_to)
5644 dbg('previous value: "%s"' % self._prevValue)
5645 self._SetValue(self._prevValue)
5646 self._SetInsertionPoint(sel_start)
5647 self._SetSelection(sel_start, sel_to)
5649 dbg('no difference between previous value')
5653 def _OnClear(self, event):
5654 """ Provides an action for context menu delete operation """
5658 def _OnContextMenu(self, event):
5659 dbg('wxMaskedEditMixin::OnContextMenu()', indent=1)
5661 menu.Append(wxID_UNDO, "Undo", "")
5662 menu.AppendSeparator()
5663 menu.Append(wxID_CUT, "Cut", "")
5664 menu.Append(wxID_COPY, "Copy", "")
5665 menu.Append(wxID_PASTE, "Paste", "")
5666 menu.Append(wxID_CLEAR, "Delete", "")
5667 menu.AppendSeparator()
5668 menu.Append(wxID_SELECTALL, "Select All", "")
5670 EVT_MENU(menu, wxID_UNDO, self._OnCtrl_Z)
5671 EVT_MENU(menu, wxID_CUT, self._OnCtrl_X)
5672 EVT_MENU(menu, wxID_COPY, self._OnCtrl_C)
5673 EVT_MENU(menu, wxID_PASTE, self._OnCtrl_V)
5674 EVT_MENU(menu, wxID_CLEAR, self._OnClear)
5675 EVT_MENU(menu, wxID_SELECTALL, self._OnCtrl_A)
5677 # ## WSS: The base control apparently handles
5678 # enable/disable of wID_CUT, wxID_COPY, wxID_PASTE
5679 # and wxID_CLEAR menu items even if the menu is one
5680 # we created. However, it doesn't do undo properly,
5681 # so we're keeping track of previous values ourselves.
5682 # Therefore, we have to override the default update for
5683 # that item on the menu:
5684 EVT_UPDATE_UI(self, wxID_UNDO, self._UndoUpdateUI)
5685 self._contextMenu = menu
5687 self.PopupMenu(menu, event.GetPosition())
5689 self._contextMenu = None
5692 def _UndoUpdateUI(self, event):
5693 if self._prevValue is None or self._prevValue == self._curValue:
5694 self._contextMenu.Enable(wxID_UNDO, False)
5696 self._contextMenu.Enable(wxID_UNDO, True)
5699 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
5701 class wxMaskedTextCtrl( wxTextCtrl, wxMaskedEditMixin ):
5703 This is the primary derivation from wxMaskedEditMixin. It provides
5704 a general masked text control that can be configured with different
5708 def __init__( self, parent, id=-1, value = '',
5709 pos = wxDefaultPosition,
5710 size = wxDefaultSize,
5711 style = wxTE_PROCESS_TAB,
5712 validator=wxDefaultValidator, ## placeholder provided for data-transfer logic
5713 name = 'maskedTextCtrl',
5714 setupEventHandling = True, ## setup event handling by default
5717 wxTextCtrl.__init__(self, parent, id, value='',
5718 pos=pos, size = size,
5719 style=style, validator=validator,
5722 self.controlInitialized = True
5723 wxMaskedEditMixin.__init__( self, name, **kwargs )
5724 self._SetInitialValue(value)
5726 if setupEventHandling:
5727 ## Setup event handlers
5728 EVT_SET_FOCUS( self, self._OnFocus ) ## defeat automatic full selection
5729 EVT_KILL_FOCUS( self, self._OnKillFocus ) ## run internal validator
5730 EVT_LEFT_DCLICK(self, self._OnDoubleClick) ## select field under cursor on dclick
5731 EVT_RIGHT_UP(self, self._OnContextMenu ) ## bring up an appropriate context menu
5732 EVT_KEY_DOWN( self, self._OnKeyDown ) ## capture control events not normally seen, eg ctrl-tab.
5733 EVT_CHAR( self, self._OnChar ) ## handle each keypress
5734 EVT_TEXT( self, self.GetId(), self._OnTextChange ) ## color control appropriately & keep
5735 ## track of previous value for undo
5739 return "<wxMaskedTextCtrl: %s>" % self.GetValue()
5742 def _GetSelection(self):
5744 Allow mixin to get the text selection of this control.
5745 REQUIRED by any class derived from wxMaskedEditMixin.
5747 return self.GetSelection()
5749 def _SetSelection(self, sel_start, sel_to):
5751 Allow mixin to set the text selection of this control.
5752 REQUIRED by any class derived from wxMaskedEditMixin.
5754 ## dbg("wxMaskedTextCtrl::_SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
5755 return self.SetSelection( sel_start, sel_to )
5757 def SetSelection(self, sel_start, sel_to):
5759 This is just for debugging...
5761 dbg("wxMaskedTextCtrl::SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
5762 wxTextCtrl.SetSelection(self, sel_start, sel_to)
5765 def _GetInsertionPoint(self):
5766 return self.GetInsertionPoint()
5768 def _SetInsertionPoint(self, pos):
5769 ## dbg("wxMaskedTextCtrl::_SetInsertionPoint(%(pos)d)" % locals())
5770 self.SetInsertionPoint(pos)
5772 def SetInsertionPoint(self, pos):
5774 This is just for debugging...
5776 dbg("wxMaskedTextCtrl::SetInsertionPoint(%(pos)d)" % locals())
5777 wxTextCtrl.SetInsertionPoint(self, pos)
5780 def _GetValue(self):
5782 Allow mixin to get the raw value of the control with this function.
5783 REQUIRED by any class derived from wxMaskedEditMixin.
5785 return self.GetValue()
5787 def _SetValue(self, value):
5789 Allow mixin to set the raw value of the control with this function.
5790 REQUIRED by any class derived from wxMaskedEditMixin.
5792 dbg('wxMaskedTextCtrl::_SetValue("%(value)s")' % locals(), indent=1)
5793 # Record current selection and insertion point, for undo
5794 self._prevSelection = self._GetSelection()
5795 self._prevInsertionPoint = self._GetInsertionPoint()
5796 wxTextCtrl.SetValue(self, value)
5799 def SetValue(self, value):
5801 This function redefines the externally accessible .SetValue to be
5802 a smart "paste" of the text in question, so as not to corrupt the
5803 masked control. NOTE: this must be done in the class derived
5804 from the base wx control.
5806 dbg('wxMaskedTextCtrl::SetValue = "%s"' % value, indent=1)
5809 wxTextCtrl.SetValue(self, value) # revert to base control behavior
5812 # empty previous contents, replacing entire value:
5813 self._SetInsertionPoint(0)
5814 self._SetSelection(0, self._masklength)
5815 if self._signOk and self._useParens:
5816 signpos = value.find('-')
5818 value = value[:signpos] + '(' + value[signpos+1:].strip() + ')'
5819 elif value.find(')') == -1 and len(value) < self._masklength:
5820 value += ' ' # add place holder for reserved space for right paren
5822 if( len(value) < self._masklength # value shorter than control
5823 and (self._isFloat or self._isInt) # and it's a numeric control
5824 and self._ctrl_constraints._alignRight ): # and it's a right-aligned control
5826 dbg('len(value)', len(value), ' < self._masklength', self._masklength)
5827 # try to intelligently "pad out" the value to the right size:
5828 value = self._template[0:self._masklength - len(value)] + value
5829 if self._isFloat and value.find('.') == -1:
5831 dbg('padded value = "%s"' % value)
5833 # make SetValue behave the same as if you had typed the value in:
5835 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
5837 self._isNeg = False # (clear current assumptions)
5838 value = self._adjustFloat(value)
5840 self._isNeg = False # (clear current assumptions)
5841 value = self._adjustInt(value)
5842 elif self._isDate and not self.IsValid(value) and self._4digityear:
5843 value = self._adjustDate(value, fixcentury=True)
5845 # If date, year might be 2 digits vs. 4; try adjusting it:
5846 if self._isDate and self._4digityear:
5847 dateparts = value.split(' ')
5848 dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
5849 value = string.join(dateparts, ' ')
5850 dbg('adjusted value: "%s"' % value)
5851 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
5853 dbg('exception thrown', indent=0)
5856 self._SetValue(value)
5857 ## dbg('queuing insertion after .SetValue', self._masklength)
5858 wxCallAfter(self._SetInsertionPoint, self._masklength)
5859 wxCallAfter(self._SetSelection, self._masklength, self._masklength)
5864 """ Blanks the current control value by replacing it with the default value."""
5865 dbg("wxMaskedTextCtrl::Clear - value reset to default value (template)")
5869 wxTextCtrl.Clear(self) # else revert to base control behavior
5874 Allow mixin to refresh the base control with this function.
5875 REQUIRED by any class derived from wxMaskedEditMixin.
5877 dbg('wxMaskedTextCtrl::_Refresh', indent=1)
5878 wxTextCtrl.Refresh(self)
5884 This function redefines the externally accessible .Refresh() to
5885 validate the contents of the masked control as it refreshes.
5886 NOTE: this must be done in the class derived from the base wx control.
5888 dbg('wxMaskedTextCtrl::Refresh', indent=1)
5894 def _IsEditable(self):
5896 Allow mixin to determine if the base control is editable with this function.
5897 REQUIRED by any class derived from wxMaskedEditMixin.
5899 return wxTextCtrl.IsEditable(self)
5904 This function redefines the externally accessible .Cut to be
5905 a smart "erase" of the text in question, so as not to corrupt the
5906 masked control. NOTE: this must be done in the class derived
5907 from the base wx control.
5910 self._Cut() # call the mixin's Cut method
5912 wxTextCtrl.Cut(self) # else revert to base control behavior
5917 This function redefines the externally accessible .Paste to be
5918 a smart "paste" of the text in question, so as not to corrupt the
5919 masked control. NOTE: this must be done in the class derived
5920 from the base wx control.
5923 self._Paste() # call the mixin's Paste method
5925 wxTextCtrl.Paste(self, value) # else revert to base control behavior
5930 This function defines the undo operation for the control. (The default
5936 wxTextCtrl.Undo(self) # else revert to base control behavior
5939 def IsModified(self):
5941 This function overrides the raw wxTextCtrl method, because the
5942 masked edit mixin uses SetValue to change the value, which doesn't
5943 modify the state of this attribute. So, we keep track on each
5944 keystroke to see if the value changes, and if so, it's been
5947 return wxTextCtrl.IsModified(self) or self.modified
5950 def _CalcSize(self, size=None):
5952 Calculate automatic size if allowed; use base mixin function.
5954 return self._calcSize(size)
5957 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
5958 ## Because calling SetSelection programmatically does not fire EVT_COMBOBOX
5959 ## events, we have to do it ourselves when we auto-complete.
5960 class wxMaskedComboBoxSelectEvent(wxPyCommandEvent):
5961 def __init__(self, id, selection = 0, object=None):
5962 wxPyCommandEvent.__init__(self, wxEVT_COMMAND_COMBOBOX_SELECTED, id)
5964 self.__selection = selection
5965 self.SetEventObject(object)
5967 def GetSelection(self):
5968 """Retrieve the value of the control at the time
5969 this event was generated."""
5970 return self.__selection
5973 class wxMaskedComboBox( wxComboBox, wxMaskedEditMixin ):
5975 This masked edit control adds the ability to use a masked input
5976 on a combobox, and do auto-complete of such values.
5978 def __init__( self, parent, id=-1, value = '',
5979 pos = wxDefaultPosition,
5980 size = wxDefaultSize,
5982 style = wxCB_DROPDOWN,
5983 validator = wxDefaultValidator,
5984 name = "maskedComboBox",
5985 setupEventHandling = True, ## setup event handling by default):
5989 # This is necessary, because wxComboBox currently provides no
5990 # method for determining later if this was specified in the
5991 # constructor for the control...
5992 self.__readonly = style & wxCB_READONLY == wxCB_READONLY
5994 kwargs['choices'] = choices ## set up maskededit to work with choice list too
5996 ## Since combobox completion is case-insensitive, always validate same way
5997 if not kwargs.has_key('compareNoCase'):
5998 kwargs['compareNoCase'] = True
6000 wxMaskedEditMixin.__init__( self, name, **kwargs )
6001 self._choices = self._ctrl_constraints._choices
6002 dbg('self._choices:', self._choices)
6004 if self._ctrl_constraints._alignRight:
6005 choices = [choice.rjust(self._masklength) for choice in choices]
6007 choices = [choice.ljust(self._masklength) for choice in choices]
6009 wxComboBox.__init__(self, parent, id, value='',
6010 pos=pos, size = size,
6011 choices=choices, style=style|wxWANTS_CHARS,
6012 validator=validator,
6015 self.controlInitialized = True
6017 # Set control font - fixed width by default
6021 self.SetClientSize(self._CalcSize())
6024 # ensure value is width of the mask of the control:
6025 if self._ctrl_constraints._alignRight:
6026 value = value.rjust(self._masklength)
6028 value = value.ljust(self._masklength)
6031 self.SetStringSelection(value)
6033 self._SetInitialValue(value)
6036 self._SetKeycodeHandler(WXK_UP, self.OnSelectChoice)
6037 self._SetKeycodeHandler(WXK_DOWN, self.OnSelectChoice)
6039 if setupEventHandling:
6040 ## Setup event handlers
6041 EVT_SET_FOCUS( self, self._OnFocus ) ## defeat automatic full selection
6042 EVT_KILL_FOCUS( self, self._OnKillFocus ) ## run internal validator
6043 EVT_LEFT_DCLICK(self, self._OnDoubleClick) ## select field under cursor on dclick
6044 EVT_RIGHT_UP(self, self._OnContextMenu ) ## bring up an appropriate context menu
6045 EVT_CHAR( self, self._OnChar ) ## handle each keypress
6046 EVT_KEY_DOWN( self, self.OnKeyDown ) ## for special processing of up/down keys
6047 EVT_KEY_DOWN( self, self._OnKeyDown ) ## for processing the rest of the control keys
6048 ## (next in evt chain)
6049 EVT_TEXT( self, self.GetId(), self._OnTextChange ) ## color control appropriately & keep
6050 ## track of previous value for undo
6055 return "<wxMaskedComboBox: %s>" % self.GetValue()
6058 def _CalcSize(self, size=None):
6060 Calculate automatic size if allowed; augment base mixin function
6061 to account for the selector button.
6063 size = self._calcSize(size)
6064 return (size[0]+20, size[1])
6067 def _GetSelection(self):
6069 Allow mixin to get the text selection of this control.
6070 REQUIRED by any class derived from wxMaskedEditMixin.
6072 return self.GetMark()
6074 def _SetSelection(self, sel_start, sel_to):
6076 Allow mixin to set the text selection of this control.
6077 REQUIRED by any class derived from wxMaskedEditMixin.
6079 return self.SetMark( sel_start, sel_to )
6082 def _GetInsertionPoint(self):
6083 return self.GetInsertionPoint()
6085 def _SetInsertionPoint(self, pos):
6086 self.SetInsertionPoint(pos)
6089 def _GetValue(self):
6091 Allow mixin to get the raw value of the control with this function.
6092 REQUIRED by any class derived from wxMaskedEditMixin.
6094 return self.GetValue()
6096 def _SetValue(self, value):
6098 Allow mixin to set the raw value of the control with this function.
6099 REQUIRED by any class derived from wxMaskedEditMixin.
6101 # For wxComboBox, ensure that values are properly padded so that
6102 # if varying length choices are supplied, they always show up
6103 # in the window properly, and will be the appropriate length
6104 # to match the mask:
6105 if self._ctrl_constraints._alignRight:
6106 value = value.rjust(self._masklength)
6108 value = value.ljust(self._masklength)
6110 # Record current selection and insertion point, for undo
6111 self._prevSelection = self._GetSelection()
6112 self._prevInsertionPoint = self._GetInsertionPoint()
6113 wxComboBox.SetValue(self, value)
6114 # text change events don't always fire, so we check validity here
6115 # to make certain formatting is applied:
6118 def SetValue(self, value):
6120 This function redefines the externally accessible .SetValue to be
6121 a smart "paste" of the text in question, so as not to corrupt the
6122 masked control. NOTE: this must be done in the class derived
6123 from the base wx control.
6126 wxComboBox.SetValue(value) # revert to base control behavior
6129 # empty previous contents, replacing entire value:
6130 self._SetInsertionPoint(0)
6131 self._SetSelection(0, self._masklength)
6133 if( len(value) < self._masklength # value shorter than control
6134 and (self._isFloat or self._isInt) # and it's a numeric control
6135 and self._ctrl_constraints._alignRight ): # and it's a right-aligned control
6136 # try to intelligently "pad out" the value to the right size:
6137 value = self._template[0:self._masklength - len(value)] + value
6138 dbg('padded value = "%s"' % value)
6140 # For wxComboBox, ensure that values are properly padded so that
6141 # if varying length choices are supplied, they always show up
6142 # in the window properly, and will be the appropriate length
6143 # to match the mask:
6144 elif self._ctrl_constraints._alignRight:
6145 value = value.rjust(self._masklength)
6147 value = value.ljust(self._masklength)
6150 # make SetValue behave the same as if you had typed the value in:
6152 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
6154 self._isNeg = False # (clear current assumptions)
6155 value = self._adjustFloat(value)
6157 self._isNeg = False # (clear current assumptions)
6158 value = self._adjustInt(value)
6159 elif self._isDate and not self.IsValid(value) and self._4digityear:
6160 value = self._adjustDate(value, fixcentury=True)
6162 # If date, year might be 2 digits vs. 4; try adjusting it:
6163 if self._isDate and self._4digityear:
6164 dateparts = value.split(' ')
6165 dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
6166 value = string.join(dateparts, ' ')
6167 dbg('adjusted value: "%s"' % value)
6168 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
6172 self._SetValue(value)
6173 ## dbg('queuing insertion after .SetValue', self._masklength)
6174 wxCallAfter(self._SetInsertionPoint, self._masklength)
6175 wxCallAfter(self._SetSelection, self._masklength, self._masklength)
6180 Allow mixin to refresh the base control with this function.
6181 REQUIRED by any class derived from wxMaskedEditMixin.
6183 wxComboBox.Refresh(self)
6187 This function redefines the externally accessible .Refresh() to
6188 validate the contents of the masked control as it refreshes.
6189 NOTE: this must be done in the class derived from the base wx control.
6195 def _IsEditable(self):
6197 Allow mixin to determine if the base control is editable with this function.
6198 REQUIRED by any class derived from wxMaskedEditMixin.
6200 return not self.__readonly
6205 This function redefines the externally accessible .Cut to be
6206 a smart "erase" of the text in question, so as not to corrupt the
6207 masked control. NOTE: this must be done in the class derived
6208 from the base wx control.
6211 self._Cut() # call the mixin's Cut method
6213 wxComboBox.Cut(self) # else revert to base control behavior
6218 This function redefines the externally accessible .Paste to be
6219 a smart "paste" of the text in question, so as not to corrupt the
6220 masked control. NOTE: this must be done in the class derived
6221 from the base wx control.
6224 self._Paste() # call the mixin's Paste method
6226 wxComboBox.Paste(self) # else revert to base control behavior
6231 This function defines the undo operation for the control. (The default
6237 wxComboBox.Undo() # else revert to base control behavior
6240 def Append( self, choice, clientData=None ):
6242 This function override is necessary so we can keep track of any additions to the list
6243 of choices, because wxComboBox doesn't have an accessor for the choice list.
6244 The code here is the same as in the SetParameters() mixin function, but is
6245 done for the individual value as appended, so the list can be built incrementally
6246 without speed penalty.
6249 if type(choice) not in (types.StringType, types.UnicodeType):
6250 raise TypeError('%s: choices must be a sequence of strings' % str(self._index))
6251 elif not self.IsValid(choice):
6252 raise ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self._index), choice))
6254 if not self._ctrl_constraints._choices:
6255 self._ctrl_constraints._compareChoices = []
6256 self._ctrl_constraints._choices = []
6257 self._hasList = True
6259 compareChoice = choice.strip()
6261 if self._ctrl_constraints._compareNoCase:
6262 compareChoice = compareChoice.lower()
6264 if self._ctrl_constraints._alignRight:
6265 choice = choice.rjust(self._masklength)
6267 choice = choice.ljust(self._masklength)
6268 if self._ctrl_constraints._fillChar != ' ':
6269 choice = choice.replace(' ', self._fillChar)
6270 dbg('updated choice:', choice)
6273 self._ctrl_constraints._compareChoices.append(compareChoice)
6274 self._ctrl_constraints._choices.append(choice)
6275 self._choices = self._ctrl_constraints._choices # (for shorthand)
6277 if( not self.IsValid(choice) and
6278 (not self._ctrl_constraints.IsEmpty(choice) or
6279 (self._ctrl_constraints.IsEmpty(choice) and self._ctrl_constraints._validRequired) ) ):
6280 raise ValueError('"%s" is not a valid value for the control "%s" as specified.' % (choice, self.name))
6282 wxComboBox.Append(self, choice, clientData)
6288 This function override is necessary so we can keep track of any additions to the list
6289 of choices, because wxComboBox doesn't have an accessor for the choice list.
6293 self._ctrl_constraints._autoCompleteIndex = -1
6294 if self._ctrl_constraints._choices:
6295 self.SetCtrlParameters(choices=[])
6296 wxComboBox.Clear(self)
6299 def SetCtrlParameters( self, **kwargs ):
6301 Override mixin's default SetCtrlParameters to detect changes in choice list, so
6302 we can update the base control:
6304 wxMaskedEditMixin.SetCtrlParameters(self, **kwargs )
6305 if( self.controlInitialized
6306 and (kwargs.has_key('choices') or self._choices != self._ctrl_constraints._choices) ):
6307 wxComboBox.Clear(self)
6308 self._choices = self._ctrl_constraints._choices
6309 for choice in self._choices:
6310 wxComboBox.Append( self, choice )
6315 This function is a hack to make up for the fact that wxComboBox has no
6316 method for returning the selected portion of its edit control. It
6317 works, but has the nasty side effect of generating lots of intermediate
6320 dbg(suspend=1) # turn off debugging around this function
6321 dbg('wxMaskedComboBox::GetMark', indent=1)
6324 return 0, 0 # no selection possible for editing
6325 ## sel_start, sel_to = wxComboBox.GetMark(self) # what I'd *like* to have!
6326 sel_start = sel_to = self.GetInsertionPoint()
6327 dbg("current sel_start:", sel_start)
6328 value = self.GetValue()
6329 dbg('value: "%s"' % value)
6331 self._ignoreChange = True # tell _OnTextChange() to ignore next event (if any)
6333 wxComboBox.Cut(self)
6334 newvalue = self.GetValue()
6335 dbg("value after Cut operation:", newvalue)
6337 if newvalue != value: # something was selected; calculate extent
6338 dbg("something selected")
6339 sel_to = sel_start + len(value) - len(newvalue)
6340 wxComboBox.SetValue(self, value) # restore original value and selection (still ignoring change)
6341 wxComboBox.SetInsertionPoint(self, sel_start)
6342 wxComboBox.SetMark(self, sel_start, sel_to)
6344 self._ignoreChange = False # tell _OnTextChange() to pay attn again
6346 dbg('computed selection:', sel_start, sel_to, indent=0, suspend=0)
6347 return sel_start, sel_to
6350 def SetSelection(self, index):
6352 Necessary for bookkeeping on choice selection, to keep current value
6355 dbg('wxMaskedComboBox::SetSelection(%d)' % index)
6357 self._prevValue = self._curValue
6358 self._curValue = self._choices[index]
6359 self._ctrl_constraints._autoCompleteIndex = index
6360 wxComboBox.SetSelection(self, index)
6363 def OnKeyDown(self, event):
6365 This function is necessary because navigation and control key
6366 events do not seem to normally be seen by the wxComboBox's
6367 EVT_CHAR routine. (Tabs don't seem to be visible no matter
6370 if event.GetKeyCode() in self._nav + self._control:
6374 event.Skip() # let mixin default KeyDown behavior occur
6377 def OnSelectChoice(self, event):
6379 This function appears to be necessary, because the processing done
6380 on the text of the control somehow interferes with the combobox's
6381 selection mechanism for the arrow keys.
6383 dbg('wxMaskedComboBox::OnSelectChoice', indent=1)
6389 value = self.GetValue().strip()
6391 if self._ctrl_constraints._compareNoCase:
6392 value = value.lower()
6394 if event.GetKeyCode() == WXK_UP:
6398 match_index, partial_match = self._autoComplete(
6400 self._ctrl_constraints._compareChoices,
6402 self._ctrl_constraints._compareNoCase,
6403 current_index = self._ctrl_constraints._autoCompleteIndex)
6404 if match_index is not None:
6405 dbg('setting selection to', match_index)
6406 # issue appropriate event to outside:
6407 self._OnAutoSelect(self._ctrl_constraints, match_index=match_index)
6409 keep_processing = False
6411 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
6412 field = self._FindField(pos)
6413 if self.IsEmpty() or not field._hasList:
6414 dbg('selecting 1st value in list')
6415 self._OnAutoSelect(self._ctrl_constraints, match_index=0)
6417 keep_processing = False
6419 # attempt field-level auto-complete
6421 keep_processing = self._OnAutoCompleteField(event)
6422 dbg('keep processing?', keep_processing, indent=0)
6423 return keep_processing
6426 def _OnAutoSelect(self, field, match_index):
6428 Override mixin (empty) autocomplete handler, so that autocompletion causes
6429 combobox to update appropriately.
6431 dbg('wxMaskedComboBox::OnAutoSelect', field._index, indent=1)
6432 ## field._autoCompleteIndex = match_index
6433 if field == self._ctrl_constraints:
6434 self.SetSelection(match_index)
6435 dbg('issuing combo selection event')
6436 self.GetEventHandler().ProcessEvent(
6437 wxMaskedComboBoxSelectEvent( self.GetId(), match_index, self ) )
6439 dbg('field._autoCompleteIndex:', match_index)
6440 dbg('self.GetSelection():', self.GetSelection())
6444 def _OnReturn(self, event):
6446 For wxComboBox, it seems that if you hit return when the dropdown is
6447 dropped, the event that dismisses the dropdown will also blank the
6448 control, because of the implementation of wxComboBox. So here,
6449 we look and if the selection is -1, and the value according to
6450 (the base control!) is a value in the list, then we schedule a
6451 programmatic wxComboBox.SetSelection() call to pick the appropriate
6452 item in the list. (and then do the usual OnReturn bit.)
6454 dbg('wxMaskedComboBox::OnReturn', indent=1)
6455 dbg('current value: "%s"' % self.GetValue(), 'current index:', self.GetSelection())
6456 if self.GetSelection() == -1 and self.GetValue().lower().strip() in self._ctrl_constraints._compareChoices:
6457 wxCallAfter(self.SetSelection, self._ctrl_constraints._autoCompleteIndex)
6459 event.m_keyCode = WXK_TAB
6464 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6466 class wxIpAddrCtrl( wxMaskedTextCtrl ):
6468 This class is a particular type of wxMaskedTextCtrl that accepts
6469 and understands the semantics of IP addresses, reformats input
6470 as you move from field to field, and accepts '.' as a navigation
6471 character, so that typing an IP address can be done naturally.
6473 def __init__( self, parent, id=-1, value = '',
6474 pos = wxDefaultPosition,
6475 size = wxDefaultSize,
6476 style = wxTE_PROCESS_TAB,
6477 validator = wxDefaultValidator,
6478 name = 'wxIpAddrCtrl',
6479 setupEventHandling = True, ## setup event handling by default
6482 if not kwargs.has_key('mask'):
6483 kwargs['mask'] = mask = "###.###.###.###"
6484 if not kwargs.has_key('formatcodes'):
6485 kwargs['formatcodes'] = 'F_Sr<'
6486 if not kwargs.has_key('validRegex'):
6487 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}"
6490 wxMaskedTextCtrl.__init__(
6491 self, parent, id=id, value = value,
6494 validator = validator,
6496 setupEventHandling = setupEventHandling,
6499 # set up individual field parameters as well:
6501 field_params['validRegex'] = "( | \d| \d |\d | \d\d|\d\d |\d \d|(1\d\d|2[0-4]\d|25[0-5]))"
6503 # require "valid" string; this prevents entry of any value > 255, but allows
6504 # intermediate constructions; overall control validation requires well-formatted value.
6505 field_params['formatcodes'] = 'V'
6508 for i in self._field_indices:
6509 self.SetFieldParameters(i, **field_params)
6511 # This makes '.' act like tab:
6512 self._AddNavKey('.', handler=self.OnDot)
6513 self._AddNavKey('>', handler=self.OnDot) # for "shift-."
6516 def OnDot(self, event):
6517 dbg('wxIpAddrCtrl::OnDot', indent=1)
6518 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
6519 oldvalue = self.GetValue()
6520 edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
6521 if not event.ShiftDown():
6522 if pos > edit_start and pos < edit_end:
6523 # clip data in field to the right of pos, if adjusting fields
6524 # when not at delimeter; (assumption == they hit '.')
6525 newvalue = oldvalue[:pos] + ' ' * (edit_end - pos) + oldvalue[edit_end:]
6526 self._SetValue(newvalue)
6527 self._SetInsertionPoint(pos)
6529 return self._OnChangeField(event)
6533 def GetAddress(self):
6534 value = wxMaskedTextCtrl.GetValue(self)
6535 return value.replace(' ','') # remove spaces from the value
6538 def _OnCtrl_S(self, event):
6539 dbg("wxIpAddrCtrl::_OnCtrl_S")
6541 print "value:", self.GetAddress()
6544 def SetValue(self, value):
6545 dbg('wxIpAddrCtrl::SetValue(%s)' % str(value), indent=1)
6546 if type(value) not in (types.StringType, types.UnicodeType):
6548 raise ValueError('%s must be a string', str(value))
6550 bValid = True # assume True
6551 parts = value.split('.')
6557 if not 0 <= len(part) <= 3:
6560 elif part.strip(): # non-empty part
6562 j = string.atoi(part)
6563 if not 0 <= j <= 255:
6567 parts[i] = '%3d' % j
6572 # allow empty sections for SetValue (will result in "invalid" value,
6573 # but this may be useful for initializing the control:
6574 parts[i] = ' ' # convert empty field to 3-char length
6578 raise ValueError('value (%s) must be a string of form n.n.n.n where n is empty or in range 0-255' % str(value))
6580 dbg('parts:', parts)
6581 value = string.join(parts, '.')
6582 wxMaskedTextCtrl.SetValue(self, value)
6586 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6587 ## these are helper subroutines:
6589 def movetofloat( origvalue, fmtstring, neg, addseparators=False, sepchar = ',',fillchar=' '):
6590 """ addseparators = add separator character every three numerals if True
6592 fmt0 = fmtstring.split('.')
6595 val = origvalue.split('.')[0].strip()
6596 ret = fillchar * (len(fmt1)-len(val)) + val + "." + "0" * len(fmt2)
6599 return (ret,len(fmt1))
6602 def isDateType( fmtstring ):
6603 """ Checks the mask and returns True if it fits an allowed
6604 date or datetime format.
6606 dateMasks = ("^##/##/####",
6618 reString = "|".join(dateMasks)
6619 filter = re.compile( reString)
6620 if re.match(filter,fmtstring): return True
6623 def isTimeType( fmtstring ):
6624 """ Checks the mask and returns True if it fits an allowed
6627 reTimeMask = "^##:##(:##)?( (AM|PM))?"
6628 filter = re.compile( reTimeMask )
6629 if re.match(filter,fmtstring): return True
6633 def isFloatingPoint( fmtstring):
6634 filter = re.compile("[ ]?[#]+\.[#]+\n")
6635 if re.match(filter,fmtstring+"\n"): return True
6639 def isInteger( fmtstring ):
6640 filter = re.compile("[#]+\n")
6641 if re.match(filter,fmtstring+"\n"): return True
6645 def getDateParts( dateStr, dateFmt ):
6646 if len(dateStr) > 11: clip = dateStr[0:11]
6647 else: clip = dateStr
6648 if clip[-2] not in string.digits:
6649 clip = clip[:-1] # (got part of time; drop it)
6651 dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.')
6652 slices = clip.split(dateSep)
6653 if dateFmt == "MDY":
6654 y,m,d = (slices[2],slices[0],slices[1]) ## year, month, date parts
6655 elif dateFmt == "DMY":
6656 y,m,d = (slices[2],slices[1],slices[0]) ## year, month, date parts
6657 elif dateFmt == "YMD":
6658 y,m,d = (slices[0],slices[1],slices[2]) ## year, month, date parts
6660 y,m,d = None, None, None
6667 def getDateSepChar(dateStr):
6668 clip = dateStr[0:10]
6669 dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.')
6673 def makeDate( year, month, day, dateFmt, dateStr):
6674 sep = getDateSepChar( dateStr)
6675 if dateFmt == "MDY":
6676 return "%s%s%s%s%s" % (month,sep,day,sep,year) ## year, month, date parts
6677 elif dateFmt == "DMY":
6678 return "%s%s%s%s%s" % (day,sep,month,sep,year) ## year, month, date parts
6679 elif dateFmt == "YMD":
6680 return "%s%s%s%s%s" % (year,sep,month,sep,day) ## year, month, date parts
6685 def getYear(dateStr,dateFmt):
6686 parts = getDateParts( dateStr, dateFmt)
6689 def getMonth(dateStr,dateFmt):
6690 parts = getDateParts( dateStr, dateFmt)
6693 def getDay(dateStr,dateFmt):
6694 parts = getDateParts( dateStr, dateFmt)
6697 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6698 class test(wxPySimpleApp):
6700 from wxPython.lib.rcsizer import RowColSizer
6701 self.frame = wxFrame( NULL, -1, "wxMaskedEditMixin 0.0.7 Demo Page #1", size = (700,600))
6702 self.panel = wxPanel( self.frame, -1)
6703 self.sizer = RowColSizer()
6708 id, id1 = wxNewId(), wxNewId()
6709 self.command1 = wxButton( self.panel, id, "&Close" )
6710 self.command2 = wxButton( self.panel, id1, "&AutoFormats" )
6711 self.sizer.Add(self.command1, row=0, col=0, flag=wxALL, border = 5)
6712 self.sizer.Add(self.command2, row=0, col=1, colspan=2, flag=wxALL, border = 5)
6713 EVT_BUTTON( self.panel, id, self.onClick )
6714 ## self.panel.SetDefaultItem(self.command1 )
6715 EVT_BUTTON( self.panel, id1, self.onClickPage )
6717 self.check1 = wxCheckBox( self.panel, -1, "Disallow Empty" )
6718 self.check2 = wxCheckBox( self.panel, -1, "Highlight Empty" )
6719 self.sizer.Add( self.check1, row=0,col=3, flag=wxALL,border=5 )
6720 self.sizer.Add( self.check2, row=0,col=4, flag=wxALL,border=5 )
6721 EVT_CHECKBOX( self.panel, self.check1.GetId(), self._onCheck1 )
6722 EVT_CHECKBOX( self.panel, self.check2.GetId(), self._onCheck2 )
6725 label = """Press ctrl-s in any field to output the value and plain value. Press ctrl-x to clear and re-set any field.
6726 Note that all controls have been auto-sized by including F in the format code.
6727 Try entering nonsensical or partial values in validated fields to see what happens (use ctrl-s to test the valid status)."""
6728 label2 = "\nNote that the State and Last Name fields are list-limited (Name:Smith,Jones,Williams)."
6730 self.label1 = wxStaticText( self.panel, -1, label)
6731 self.label2 = wxStaticText( self.panel, -1, "Description")
6732 self.label3 = wxStaticText( self.panel, -1, "Mask Value")
6733 self.label4 = wxStaticText( self.panel, -1, "Format")
6734 self.label5 = wxStaticText( self.panel, -1, "Reg Expr Val. (opt)")
6735 self.label6 = wxStaticText( self.panel, -1, "wxMaskedEdit Ctrl")
6736 self.label7 = wxStaticText( self.panel, -1, label2)
6737 self.label7.SetForegroundColour("Blue")
6738 self.label1.SetForegroundColour("Blue")
6739 self.label2.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
6740 self.label3.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
6741 self.label4.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
6742 self.label5.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
6743 self.label6.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
6745 self.sizer.Add( self.label1, row=1,col=0,colspan=7, flag=wxALL,border=5)
6746 self.sizer.Add( self.label7, row=2,col=0,colspan=7, flag=wxALL,border=5)
6747 self.sizer.Add( self.label2, row=3,col=0, flag=wxALL,border=5)
6748 self.sizer.Add( self.label3, row=3,col=1, flag=wxALL,border=5)
6749 self.sizer.Add( self.label4, row=3,col=2, flag=wxALL,border=5)
6750 self.sizer.Add( self.label5, row=3,col=3, flag=wxALL,border=5)
6751 self.sizer.Add( self.label6, row=3,col=4, flag=wxALL,border=5)
6753 # The following list is of the controls for the demo. Feel free to play around with
6756 #description mask excl format regexp range,list,initial
6757 ("Phone No", "(###) ###-#### x:###", "", 'F!^-R', "^\(\d\d\d\) \d\d\d-\d\d\d\d", (),[],''),
6758 ("Last Name Only", "C{14}", "", 'F {list}', '^[A-Z][a-zA-Z]+', (),('Smith','Jones','Williams'),''),
6759 ("Full Name", "C{14}", "", 'F_', '^[A-Z][a-zA-Z]+ [A-Z][a-zA-Z]+', (),[],''),
6760 ("Social Sec#", "###-##-####", "", 'F', "\d{3}-\d{2}-\d{4}", (),[],''),
6761 ("U.S. Zip+4", "#{5}-#{4}", "", 'F', "\d{5}-(\s{4}|\d{4})",(),[],''),
6762 ("U.S. State (2 char)\n(with default)","AA", "", 'F!', "[A-Z]{2}", (),states, 'AZ'),
6763 ("Customer No", "\CAA-###", "", 'F!', "C[A-Z]{2}-\d{3}", (),[],''),
6764 ("Date (MDY) + Time\n(with default)", "##/##/#### ##:## AM", 'BCDEFGHIJKLMNOQRSTUVWXYZ','DFR!',"", (),[], r'03/05/2003 12:00 AM'),
6765 ("Invoice Total", "#{9}.##", "", 'F-R,', "", (),[], ''),
6766 ("Integer (signed)\n(with default)", "#{6}", "", 'F-R', "", (),[], '0 '),
6767 ("Integer (unsigned)\n(with default), 1-399", "######", "", 'F', "", (1,399),[], '1 '),
6768 ("Month selector", "XXX", "", 'F', "", (),
6769 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],""),
6770 ("fraction selector","#/##", "", 'F', "^\d\/\d\d?", (),
6771 ['2/3', '3/4', '1/2', '1/4', '1/8', '1/16', '1/32', '1/64'], "")
6774 for control in controls:
6775 self.sizer.Add( wxStaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wxALL)
6776 self.sizer.Add( wxStaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wxALL)
6777 self.sizer.Add( wxStaticText( self.panel, -1, control[3]),row=rowcount, col=2,border=5, flag=wxALL)
6778 self.sizer.Add( wxStaticText( self.panel, -1, control[4][:20]),row=rowcount, col=3,border=5, flag=wxALL)
6780 if control in controls[:]:#-2]:
6781 newControl = wxMaskedTextCtrl( self.panel, -1, "",
6783 excludeChars = control[2],
6784 formatcodes = control[3],
6786 validRegex = control[4],
6787 validRange = control[5],
6788 choices = control[6],
6789 defaultValue = control[7],
6791 if control[6]: newControl.SetCtrlParameters(choiceRequired = True)
6793 newControl = wxMaskedComboBox( self.panel, -1, "",
6794 choices = control[7],
6795 choiceRequired = True,
6797 formatcodes = control[3],
6798 excludeChars = control[2],
6800 validRegex = control[4],
6801 validRange = control[5],
6803 self.editList.append( newControl )
6805 self.sizer.Add( newControl, row=rowcount,col=4,flag=wxALL,border=5)
6808 self.sizer.AddGrowableCol(4)
6810 self.panel.SetSizer(self.sizer)
6811 self.panel.SetAutoLayout(1)
6818 def onClick(self, event):
6821 def onClickPage(self, event):
6822 self.page2 = test2(self.frame,-1,"")
6823 self.page2.Show(True)
6825 def _onCheck1(self,event):
6826 """ Set required value on/off """
6827 value = event.Checked()
6829 for control in self.editList:
6830 control.SetCtrlParameters(emptyInvalid=True)
6833 for control in self.editList:
6834 control.SetCtrlParameters(emptyInvalid=False)
6836 self.panel.Refresh()
6838 def _onCheck2(self,event):
6839 """ Highlight empty values"""
6840 value = event.Checked()
6842 for control in self.editList:
6843 control.SetCtrlParameters( emptyBackgroundColour = 'Aquamarine')
6846 for control in self.editList:
6847 control.SetCtrlParameters( emptyBackgroundColour = 'White')
6849 self.panel.Refresh()
6852 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6854 class test2(wxFrame):
6855 def __init__(self, parent, id, caption):
6856 wxFrame.__init__( self, parent, id, "wxMaskedEdit control 0.0.7 Demo Page #2 -- AutoFormats", size = (550,600))
6857 from wxPython.lib.rcsizer import RowColSizer
6858 self.panel = wxPanel( self, -1)
6859 self.sizer = RowColSizer()
6865 All these controls have been created by passing a single parameter, the AutoFormat code.
6866 The class contains an internal dictionary of types and formats (autoformats).
6867 To see a great example of validations in action, try entering a bad email address, then tab out."""
6869 self.label1 = wxStaticText( self.panel, -1, label)
6870 self.label2 = wxStaticText( self.panel, -1, "Description")
6871 self.label3 = wxStaticText( self.panel, -1, "AutoFormat Code")
6872 self.label4 = wxStaticText( self.panel, -1, "wxMaskedEdit Control")
6873 self.label1.SetForegroundColour("Blue")
6874 self.label2.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
6875 self.label3.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
6876 self.label4.SetFont(wxFont(9,wxSWISS,wxNORMAL,wxBOLD))
6878 self.sizer.Add( self.label1, row=1,col=0,colspan=3, flag=wxALL,border=5)
6879 self.sizer.Add( self.label2, row=3,col=0, flag=wxALL,border=5)
6880 self.sizer.Add( self.label3, row=3,col=1, flag=wxALL,border=5)
6881 self.sizer.Add( self.label4, row=3,col=2, flag=wxALL,border=5)
6883 id, id1 = wxNewId(), wxNewId()
6884 self.command1 = wxButton( self.panel, id, "&Close")
6885 self.command2 = wxButton( self.panel, id1, "&Print Formats")
6886 EVT_BUTTON( self.panel, id, self.onClick)
6887 self.panel.SetDefaultItem(self.command1)
6888 EVT_BUTTON( self.panel, id1, self.onClickPrint)
6890 # The following list is of the controls for the demo. Feel free to play around with
6893 ("Phone No","USPHONEFULLEXT"),
6894 ("US Date + Time","USDATETIMEMMDDYYYY/HHMM"),
6895 ("US Date MMDDYYYY","USDATEMMDDYYYY/"),
6896 ("Time (with seconds)","TIMEHHMMSS"),
6897 ("Military Time\n(without seconds)","MILTIMEHHMM"),
6898 ("Social Sec#","USSOCIALSEC"),
6899 ("Credit Card","CREDITCARD"),
6900 ("Expiration MM/YY","EXPDATEMMYY"),
6901 ("Percentage","PERCENT"),
6902 ("Person's Age","AGE"),
6903 ("US Zip Code","USZIP"),
6904 ("US Zip+4","USZIPPLUS4"),
6905 ("Email Address","EMAIL"),
6906 ("IP Address", "(derived control wxIpAddrCtrl)")
6909 for control in controls:
6910 self.sizer.Add( wxStaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wxALL)
6911 self.sizer.Add( wxStaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wxALL)
6912 if control in controls[:-1]:
6913 self.sizer.Add( wxMaskedTextCtrl( self.panel, -1, "",
6914 autoformat = control[1],
6916 row=rowcount,col=2,flag=wxALL,border=5)
6918 self.sizer.Add( wxIpAddrCtrl( self.panel, -1, "", demo=True ),
6919 row=rowcount,col=2,flag=wxALL,border=5)
6922 self.sizer.Add(self.command1, row=0, col=0, flag=wxALL, border = 5)
6923 self.sizer.Add(self.command2, row=0, col=1, flag=wxALL, border = 5)
6924 self.sizer.AddGrowableCol(3)
6926 self.panel.SetSizer(self.sizer)
6927 self.panel.SetAutoLayout(1)
6929 def onClick(self, event):
6932 def onClickPrint(self, event):
6933 for format in masktags.keys():
6934 sep = "+------------------------+"
6935 print "%s\n%s \n Mask: %s \n RE Validation string: %s\n" % (sep,format, masktags[format]['mask'], masktags[format]['validRegex'])
6937 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6939 if __name__ == "__main__":
6945 ## ===================================
6947 ## 1. WS: For some reason I don't understand, the control is generating two (2)
6948 ## EVT_TEXT events for every one (1) .SetValue() of the underlying control.
6949 ## I've been unsuccessful in determining why or in my efforts to make just one
6950 ## occur. So, I've added a hack to save the last seen value from the
6951 ## control in the EVT_TEXT handler, and if *different*, call event.Skip()
6952 ## to propagate it down the event chain, and let the application see it.
6954 ## 2. WS: wxMaskedComboBox is deficient in several areas, all having to do with the
6955 ## behavior of the underlying control that I can't fix. The problems are:
6956 ## a) The background coloring doesn't work in the text field of the control;
6957 ## instead, there's a only border around it that assumes the correct color.
6958 ## b) The control will not pass WXK_TAB to the event handler, no matter what
6959 ## I do, and there's no style wxCB_PROCESS_TAB like wxTE_PROCESS_TAB to
6960 ## indicate that we want these events. As a result, wxMaskedComboBox
6961 ## doesn't do the nice field-tabbing that wxMaskedTextCtrl does.
6962 ## c) Auto-complete had to be reimplemented for the control because programmatic
6963 ## setting of the value of the text field does not set up the auto complete
6964 ## the way that the control processing keystrokes does. (But I think I've
6965 ## implemented a fairly decent approximation.) Because of this the control
6966 ## also won't auto-complete on dropdown, and there's no event I can catch
6967 ## to work around this problem.
6968 ## d) There is no method provided for getting the selection; the hack I've
6969 ## implemented has its flaws, not the least of which is that due to the
6970 ## strategy that I'm using, the paste buffer is always replaced by the
6971 ## contents of the control's selection when in focus, on each keystroke;
6972 ## this makes it impossible to paste anything into a wxMaskedComboBox
6973 ## at the moment... :-(
6974 ## e) The other deficient behavior, likely induced by the workaround for (d),
6975 ## is that you can can't shift-left to select more than one character
6979 ## 3. WS: Controls on wxPanels don't seem to pass Shift-WXK_TAB to their
6980 ## EVT_KEY_DOWN or EVT_CHAR event handlers. Until this is fixed in
6981 ## wxWindows, shift-tab won't take you backwards through the fields of
6982 ## a wxMaskedTextCtrl like it should. Until then Shifted arrow keys will
6983 ## work like shift-tab and tab ought to.
6987 ## =============================##
6988 ## 1. Add Popup list for auto-completable fields that simulates combobox on individual
6989 ## fields. Example: City validates against list of cities, or zip vs zip code list.
6990 ## 2. Allow optional monetary symbols (eg. $, pounds, etc.) at front of a "decimal"
6992 ## 3. Fix shift-left selection for wxMaskedComboBox.
6993 ## 5. Transform notion of "decimal control" to be less "entire control"-centric,
6994 ## so that monetary symbols can be included and still have the appropriate
6995 ## semantics. (Big job, as currently written, but would make control even
6996 ## more useful for business applications.)
7000 ## ====================
7002 ## (Reported) bugs fixed:
7003 ## 1. Right-click menu allowed "cut" operation that destroyed mask
7004 ## (was implemented by base control)
7005 ## 2. wxMaskedComboBox didn't allow .Append() of mixed-case values; all
7006 ## got converted to lower case.
7007 ## 3. wxMaskedComboBox selection didn't deal with spaces in values
7008 ## properly when autocompleting, and didn't have a concept of "next"
7009 ## match for handling choice list duplicates.
7010 ## 4. Size of wxMaskedComboBox was always default.
7011 ## 5. Email address regexp allowed some "non-standard" things, and wasn't
7013 ## 6. Couldn't easily reset wxMaskedComboBox contents programmatically.
7014 ## 7. Couldn't set emptyInvalid during construction.
7015 ## 8. Under some versions of wxPython, readonly comboboxes can apparently
7016 ## return a GetInsertionPoint() result (655535), causing masked control
7018 ## 9. Specifying an empty mask caused the controls to traceback.
7019 ## 10. Can't specify float ranges for validRange.
7020 ## 11. '.' from within a the static portion of a restricted IP address
7021 ## destroyed the mask from that point rightward; tab when cursor is
7022 ## before 1st field takes cursor past that field.
7025 ## 12. Added Ctrl-Z/Undo handling, (and implemented context-menu properly.)
7026 ## 13. Added auto-select option on char input for masked controls with
7028 ## 14. Added '>' formatcode, allowing insert within a given or each field
7029 ## as appropriate, rather than requiring "overwrite". This makes single
7030 ## field controls that just have validation rules (eg. EMAIL) much more
7031 ## friendly. The same flag controls left shift when deleting vs just
7032 ## blanking the value, and for right-insert fields, allows right-insert
7033 ## at any non-blank (non-sign) position in the field.
7034 ## 15. Added option to use to indicate negative values for numeric controls.
7035 ## 16. Improved OnFocus handling of numeric controls.
7036 ## 17. Enhanced Home/End processing to allow operation on a field level,
7038 ## 18. Added individual Get/Set functions for control parameters, for
7039 ## simplified integration with Boa Constructor.
7040 ## 19. Standardized "Colour" parameter names to match wxPython, with
7041 ## non-british spellings still supported for backward-compatibility.
7042 ## 20. Added '&' mask specification character for punctuation only (no letters
7044 ## 21. Added (in a separate file) wxMaskedCtrl() factory function to provide
7045 ## unified interface to the masked edit subclasses.
7049 ## 1. Made it possible to configure grouping, decimal and shift-decimal characters,
7050 ## to make controls more usable internationally.
7051 ## 2. Added code to smart "adjust" value strings presented to .SetValue()
7052 ## for right-aligned numeric format controls if they are shorter than
7053 ## than the control width, prepending the missing portion, prepending control
7054 ## template left substring for the missing characters, so that setting
7055 ## numeric values is easier.
7056 ## 3. Renamed SetMaskParameters SetCtrlParameters() (with old name preserved
7057 ## for b-c), as this makes more sense.
7060 ## 1. Fixed .SetValue() to replace the current value, rather than the current
7061 ## selection. Also changed it to generate ValueError if presented with
7062 ## either a value which doesn't follow the format or won't fit. Also made
7063 ## set value adjust numeric and date controls as if user entered the value.
7064 ## Expanded doc explaining how SetValue() works.
7065 ## 2. Fixed EUDATE* autoformats, fixed IsDateType mask list, and added ability to
7066 ## use 3-char months for dates, and EUDATETIME, and EUDATEMILTIME autoformats.
7067 ## 3. Made all date autoformats automatically pick implied "datestyle".
7068 ## 4. Added IsModified override, since base wxTextCtrl never reports modified if
7069 ## .SetValue used to change the value, which is what the masked edit controls
7071 ## 5. Fixed bug in date position adjustment on 2 to 4 digit date conversion when
7072 ## using tab to "leave field" and auto-adjust.
7073 ## 6. Fixed bug in _isCharAllowed() for negative number insertion on pastes,
7074 ## and bug in ._Paste() that didn't account for signs in signed masks either.
7075 ## 7. Fixed issues with _adjustPos for right-insert fields causing improper
7076 ## selection/replacement of values
7077 ## 8. Fixed _OnHome handler to properly handle extending current selection to
7078 ## beginning of control.
7079 ## 9. Exposed all (valid) autoformats to demo, binding descriptions to
7081 ## 10. Fixed a couple of bugs in email regexp.
7082 ## 11. Made maskchardict an instance var, to make mask chars to be more
7083 ## amenable to international use.
7084 ## 12. Clarified meaning of '-' formatcode in doc.
7085 ## 13. Fixed a couple of coding bugs being flagged by Python2.1.
7086 ## 14. Fixed several issues with sign positioning, erasure and validity
7087 ## checking for "numeric" masked controls.
7088 ## 15. Added validation to wxIpAddrCtrl.SetValue().
7091 ## 1. Changed calling interface to use boolean "useFixedWidthFont" (True by default)
7092 ## vs. literal font facename, and use wxTELETYPE as the font family
7094 ## 2. Switched to use of dbg module vs. locally defined version.
7095 ## 3. Revamped entire control structure to use Field classes to hold constraint
7096 ## and formatting data, to make code more hierarchical, allow for more
7097 ## sophisticated masked edit construction.
7098 ## 4. Better strategy for managing options, and better validation on keywords.
7099 ## 5. Added 'V' format code, which requires that in order for a character
7100 ## to be accepted, it must result in a string that passes the validRegex.
7101 ## 6. Added 'S' format code which means "select entire field when navigating
7103 ## 7. Added 'r' format code to allow "right-insert" fields. (implies 'R'--right-alignment)
7104 ## 8. Added '<' format code to allow fields to require explicit cursor movement
7106 ## 9. Added validFunc option to other validation mechanisms, that allows derived
7107 ## classes to add dynamic validation constraints to the control.
7108 ## 10. Fixed bug in validatePaste code causing possible IndexErrors, and also
7109 ## fixed failure to obey case conversion codes when pasting.
7110 ## 11. Implemented '0' (zero-pad) formatting code, as it wasn't being done anywhere...
7111 ## 12. Removed condition from OnDecimalPoint, so that it always truncates right on '.'
7112 ## 13. Enhanced wxIpAddrCtrl to use right-insert fields, selection on field traversal,
7113 ## individual field validation to prevent field values > 255, and require explicit
7114 ## tab/. to change fields.
7115 ## 14. Added handler for left double-click to select field under cursor.
7116 ## 15. Fixed handling for "Read-only" styles.
7117 ## 16. Separated signedForegroundColor from 'R' style, and added foregroundColor
7118 ## attribute, for more consistent and controllable coloring.
7119 ## 17. Added retainFieldValidation parameter, allowing top-level constraints
7120 ## such as "validRequired" to be set independently of field-level equivalent.
7121 ## (needed in wxTimeCtrl for bounds constraints.)
7122 ## 18. Refactored code a bit, cleaned up and commented code more heavily, fixed
7123 ## some of the logic for setting/resetting parameters, eg. fillChar, defaultValue,
7125 ## 19. Fixed maskchar setting for upper/lowercase, to work in all locales.
7129 ## 1. Decimal point behavior restored for decimal and integer type controls:
7130 ## decimal point now trucates the portion > 0.
7131 ## 2. Return key now works like the tab character and moves to the next field,
7132 ## provided no default button is set for the form panel on which the control
7134 ## 3. Support added in _FindField() for subclasses controls (like timecontrol)
7135 ## to determine where the current insertion point is within the mask (i.e.
7136 ## which sub-'field'). See method documentation for more info and examples.
7137 ## 4. Added Field class and support for all constraints to be field-specific
7138 ## in addition to being globally settable for the control.
7139 ## Choices for each field are validated for length and pastability into
7140 ## the field in question, raising ValueError if not appropriate for the control.
7141 ## Also added selective additional validation based on individual field constraints.
7142 ## By default, SHIFT-WXK_DOWN, SHIFT-WXK_UP, WXK_PRIOR and WXK_NEXT all
7143 ## auto-complete fields with choice lists, supplying the 1st entry in
7144 ## the choice list if the field is empty, and cycling through the list in
7145 ## the appropriate direction if already a match. WXK_DOWN will also auto-
7146 ## complete if the field is partially completed and a match can be made.
7147 ## SHIFT-WXK_UP/DOWN will also take you to the next field after any
7148 ## auto-completion performed.
7149 ## 5. Added autoCompleteKeycodes=[] parameters for allowing further
7150 ## customization of the control. Any keycode supplied as a member
7151 ## of the _autoCompleteKeycodes list will be treated like WXK_NEXT. If
7152 ## requireFieldChoice is set, then a valid value from each non-empty
7153 ## choice list will be required for the value of the control to validate.
7154 ## 6. Fixed "auto-sizing" to be relative to the font actually used, rather
7155 ## than making assumptions about character width.
7156 ## 7. Fixed GetMaskParameter(), which was non-functional in previous version.
7157 ## 8. Fixed exceptions raised to provide info on which control had the error.
7158 ## 9. Fixed bug in choice management of wxMaskedComboBox.
7159 ## 10. Fixed bug in wxIpAddrCtrl causing traceback if field value was of
7160 ## the form '# #'. Modified control code for wxIpAddrCtrl so that '.'
7161 ## in the middle of a field clips the rest of that field, similar to
7162 ## decimal and integer controls.
7166 ## 1. "-" is a toggle for sign; "+" now changes - signed numerics to positive.
7167 ## 2. ',' in formatcodes now causes numeric values to be comma-delimited (e.g.333,333).
7168 ## 3. New support for selecting text within the control.(thanks Will Sadkin!)
7169 ## Shift-End and Shift-Home now select text as you would expect
7170 ## Control-Shift-End selects to the end of the mask string, even if value not entered.
7171 ## Control-A selects all *entered* text, Shift-Control-A selects everything in the control.
7172 ## 4. event.Skip() added to onKillFocus to correct remnants when running in Linux (contributed-
7173 ## for some reason I couldn't find the original email but thanks!!!)
7174 ## 5. All major key-handling code moved to their own methods for easier subclassing: OnHome,
7175 ## OnErase, OnEnd, OnCtrl_X, OnCtrl_A, etc.
7176 ## 6. Email and autoformat validations corrected using regex provided by Will Sadkin (thanks!).
7177 ## (The rest of the changes in this version were done by Will Sadkin with permission from Jeff...)
7178 ## 7. New mechanism for replacing default behavior for any given key, using
7179 ## ._SetKeycodeHandler(keycode, func) and ._SetKeyHandler(char, func) now available
7180 ## for easier subclassing of the control.
7181 ## 8. Reworked the delete logic, cut, paste and select/replace logic, as well as some bugs
7182 ## with insertion point/selection modification. Changed Ctrl-X to use standard "cut"
7183 ## semantics, erasing the selection, rather than erasing the entire control.
7184 ## 9. Added option for an "default value" (ie. the template) for use when a single fillChar
7185 ## is not desired in every position. Added IsDefault() function to mean "does the value
7186 ## equal the template?" and modified .IsEmpty() to mean "do all of the editable
7187 ## positions in the template == the fillChar?"
7188 ## 10. Extracted mask logic into mixin, so we can have both wxMaskedTextCtrl and wxMaskedComboBox,
7190 ## 11. wxMaskedComboBox now adds the capability to validate from list of valid values.
7191 ## Example: City validates against list of cities, or zip vs zip code list.
7192 ## 12. Fixed oversight in EVT_TEXT handler that prevented the events from being
7193 ## passed to the next handler in the event chain, causing updates to the
7194 ## control to be invisible to the parent code.
7195 ## 13. Added IPADDR autoformat code, and subclass wxIpAddrCtrl for controlling tabbing within
7196 ## the control, that auto-reformats as you move between cells.
7197 ## 14. Mask characters [A,a,X,#] can now appear in the format string as literals, by using '\'.
7198 ## 15. It is now possible to specify repeating masks, e.g. #{3}-#{3}-#{14}
7199 ## 16. Fixed major bugs in date validation, due to the fact that
7200 ## wxDateTime.ParseDate is too liberal, and will accept any form that
7201 ## makes any kind of sense, regardless of the datestyle you specified
7202 ## for the control. Unfortunately, the strategy used to fix it only
7203 ## works for versions of wxPython post 2.3.3.1, as a C++ assert box
7204 ## seems to show up on an invalid date otherwise, instead of a catchable
7206 ## 17. Enhanced date adjustment to automatically adjust heuristic based on
7207 ## current year, making last century/this century determination on
7208 ## 2-digit year based on distance between today's year and value;
7209 ## if > 50 year separation, assume last century (and don't assume last
7210 ## century is 20th.)
7211 ## 18. Added autoformats and support for including HHMMSS as well as HHMM for
7212 ## date times, and added similar time, and militaray time autoformats.
7213 ## 19. Enhanced tabbing logic so that tab takes you to the next field if the
7214 ## control is a multi-field control.
7215 ## 20. Added stub method called whenever the control "changes fields", that
7216 ## can be overridden by subclasses (eg. wxIpAddrCtrl.)
7217 ## 21. Changed a lot of code to be more functionally-oriented so side-effects
7218 ## aren't as problematic when maintaining code and/or adding features.
7219 ## Eg: IsValid() now does not have side-effects; it merely reflects the
7220 ## validity of the value of the control; to determine validity AND recolor
7221 ## the control, _CheckValid() should be used with a value argument of None.
7222 ## Similarly, made most reformatting function take an optional candidate value
7223 ## rather than just using the current value of the control, and only
7224 ## have them change the value of the control if a candidate is not specified.
7225 ## In this way, you can do validation *before* changing the control.
7226 ## 22. Changed validRequired to mean "disallow chars that result in invalid
7227 ## value." (Old meaning now represented by emptyInvalid.) (This was
7228 ## possible once I'd made the changes in (19) above.)
7229 ## 23. Added .SetMaskParameters and .GetMaskParameter methods, so they
7230 ## can be set/modified/retrieved after construction. Removed individual
7231 ## parameter setting functions, in favor of this mechanism, so that
7232 ## all adjustment of the control based on changing parameter values can
7233 ## be handled in one place with unified mechanism.
7234 ## 24. Did a *lot* of testing and fixing re: numeric values. Added ability
7235 ## to type "grouping char" (ie. ',') and validate as appropriate.
7236 ## 25. Fixed ZIPPLUS4 to allow either 5 or 4, but if > 5 must be 9.
7237 ## 26. Fixed assumption about "decimal or integer" masks so that they're only
7238 ## made iff there's no validRegex associated with the field. (This
7239 ## is so things like zipcodes which look like integers can have more
7240 ## restrictive validation (ie. must be 5 digits.)
7241 ## 27. Added a ton more doc strings to explain use and derivation requirements
7242 ## and did regularization of the naming conventions.
7243 ## 28. Fixed a range bug in _adjustKey preventing z from being handled properly.
7244 ## 29. Changed behavior of '.' (and shift-.) in numeric controls to move to
7245 ## reformat the value and move the next field as appropriate. (shift-'.',
7246 ## ie. '>' moves to the previous field.
7249 ## 1. Fixed regex bug that caused autoformat AGE to invalidate any age ending
7251 ## 2. New format character 'D' to trigger date type. If the user enters 2 digits in the
7252 ## year position, the control will expand the value to four digits, using numerals below
7253 ## 50 as 21st century (20+nn) and less than 50 as 20th century (19+nn).
7254 ## Also, new optional parameter datestyle = set to one of {MDY|DMY|YDM}
7255 ## 3. revalid parameter renamed validRegex to conform to standard for all validation
7256 ## parameters (see 2 new ones below).
7257 ## 4. New optional init parameter = validRange. Used only for int/dec (numeric) types.
7258 ## Allows the developer to specify a valid low/high range of values.
7259 ## 5. New optional init parameter = validList. Used for character types. Allows developer
7260 ## to send a list of values to the control to be used for specific validation.
7261 ## See the Last Name Only example - it is list restricted to Smith/Jones/Williams.
7262 ## 6. Date type fields now use wxDateTime's parser to validate the date and time.
7263 ## This works MUCH better than my kludgy regex!! Thanks to Robin Dunn for pointing
7264 ## me toward this solution!
7265 ## 7. Date fields now automatically expand 2-digit years when it can. For example,
7266 ## if the user types "03/10/67", then "67" will auto-expand to "1967". If a two-year
7267 ## date is entered it will be expanded in any case when the user tabs out of the
7269 ## 8. New class functions: SetValidBackgroundColor, SetInvalidBackgroundColor, SetEmptyBackgroundColor,
7270 ## SetSignedForeColor allow accessto override default class coloring behavior.
7271 ## 9. Documentation updated and improved.
7272 ## 10. Demo - page 2 is now a wxFrame class instead of a wxPyApp class. Works better.
7273 ## Two new options (checkboxes) - test highlight empty and disallow empty.
7274 ## 11. Home and End now work more intuitively, moving to the first and last user-entry
7275 ## value, respectively.
7276 ## 12. New class function: SetRequired(bool). Sets the control's entry required flag
7277 ## (i.e. disallow empty values if True).
7280 ## 1. get_plainValue method renamed to GetPlainValue following the wxWindows
7281 ## StudlyCaps(tm) standard (thanks Paul Moore). ;)
7282 ## 2. New format code 'F' causes the control to auto-fit (auto-size) itself
7283 ## based on the length of the mask template.
7284 ## 3. Class now supports "autoformat" codes. These can be passed to the class
7285 ## on instantiation using the parameter autoformat="code". If the code is in
7286 ## the dictionary, it will self set the mask, formatting, and validation string.
7287 ## I have included a number of samples, but I am hoping that someone out there
7288 ## can help me to define a whole bunch more.
7289 ## 4. I have added a second page to the demo (as well as a second demo class, test2)
7290 ## to showcase how autoformats work. The way they self-format and self-size is,
7291 ## I must say, pretty cool.
7292 ## 5. Comments added and some internal cosmetic revisions re: matching the code
7293 ## standards for class submission.
7294 ## 6. Regex validation is now done in real time - field turns yellow immediately
7295 ## and stays yellow until the entered value is valid
7296 ## 7. Cursor now skips over template characters in a more intuitive way (before the
7298 ## 8. Change, Keypress and LostFocus methods added for convenience of subclasses.
7299 ## Developer may use these methods which will be called after EVT_TEXT, EVT_CHAR,
7300 ## and EVT_KILL_FOCUS, respectively.
7301 ## 9. Decimal and numeric handlers have been rewritten and now work more intuitively.
7304 ## 1. New .IsEmpty() method returns True if the control's value is equal to the
7305 ## blank template string
7306 ## 2. Control now supports a new init parameter: revalid. Pass a regular expression
7307 ## that the value will have to match when the control loses focus. If invalid,
7308 ## the control's BackgroundColor will turn yellow, and an internal flag is set (see next).
7309 ## 3. Demo now shows revalid functionality. Try entering a partial value, such as a
7310 ## partial social security number.
7311 ## 4. New .IsValid() value returns True if the control is empty, or if the value matches
7312 ## the revalid expression. If not, .IsValid() returns False.
7313 ## 5. Decimal values now collapse to decimal with '.00' on losefocus if the user never
7314 ## presses the decimal point.
7315 ## 6. Cursor now goes to the beginning of the field if the user clicks in an
7316 ## "empty" field intead of leaving the insertion point in the middle of the
7318 ## 7. New "N" mask type includes upper and lower chars plus digits. a-zA-Z0-9.
7319 ## 8. New formatcodes init parameter replaces other init params and adds functions.
7320 ## String passed to control on init controls:
7324 ## R Show negative #s in red
7326 ## - Signed numerals
7327 ## 0 Numeric fields get leading zeros
7328 ## 9. Ctrl-X in any field clears the current value.
7329 ## 10. Code refactored and made more modular (esp in OnChar method). Should be more
7330 ## easy to read and understand.
7331 ## 11. Demo enhanced.
7332 ## 12. Now has _doc_.
7335 ## 1. GetPlainValue() now returns the value without the template characters;
7336 ## so, for example, a social security number (123-33-1212) would return as
7337 ## 123331212; also removes white spaces from numeric/decimal values, so
7338 ## "- 955.32" is returned "-955.32". Press ctrl-S to see the plain value.
7339 ## 2. Press '.' in an integer style masked control and truncate any trailing digits.
7340 ## 3. Code moderately refactored. Internal names improved for clarity. Additional
7341 ## internal documentation.
7342 ## 4. Home and End keys now supported to move cursor to beginning or end of field.
7343 ## 5. Un-signed integers and decimals now supported.
7344 ## 6. Cosmetic improvements to the demo.
7345 ## 7. Class renamed to wxMaskedTextCtrl.
7346 ## 8. Can now specify include characters that will override the basic
7347 ## controls: for example, includeChars = "@." for email addresses
7348 ## 9. Added mask character 'C' -> allow any upper or lowercase character
7349 ## 10. .SetSignColor(str:color) sets the foreground color for negative values
7350 ## in signed controls (defaults to red)
7351 ## 11. Overview documentation written.
7354 ## 1. Tab now works properly when pressed in last position
7355 ## 2. Decimal types now work (e.g. #####.##)
7356 ## 3. Signed decimal or numeric values supported (i.e. negative numbers)
7357 ## 4. Negative decimal or numeric values now can show in red.
7358 ## 5. Can now specify an "exclude list" with the excludeChars parameter.
7359 ## See date/time formatted example - you can only enter A or P in the
7360 ## character mask space (i.e. AM/PM).
7361 ## 6. Backspace now works properly, including clearing data from a selected
7362 ## region but leaving template characters intact. Also delete key.
7363 ## 7. Left/right arrows now work properly.
7364 ## 8. Removed EventManager call from test so demo should work with wxPython 2.3.3