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 # MaskedEdit 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, TimeCtrl (which is now rewritten using this
20 # MaskedEdit 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.
26 #----------------------------------------------------------------------------
28 # 12/09/2003 - Jeff Grimmett (grimmtooth@softhome.net)
30 # o Updated for wx namespace. No guarantees. This is one huge file.
32 # 12/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
34 # o Missed wx.DateTime stuff earlier.
36 # 12/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
38 # o wxMaskedEditMixin -> MaskedEditMixin
39 # o wxMaskedTextCtrl -> MaskedTextCtrl
40 # o wxMaskedComboBoxSelectEvent -> MaskedComboBoxSelectEvent
41 # o wxMaskedComboBox -> MaskedComboBox
42 # o wxIpAddrCtrl -> IpAddrCtrl
43 # o wxTimeCtrl -> TimeCtrl
47 <b>Masked Edit Overview:
48 =====================</b>
50 is a sublassed text control that can carefully control the user's input
51 based on a mask string you provide.
53 General usage example:
54 control = MaskedTextCtrl( win, -1, '', mask = '(###) ###-####')
56 The example above will create a text control that allows only numbers to be
57 entered and then only in the positions indicated in the mask by the # sign.
60 is a similar subclass of wxComboBox that allows the same sort of masking,
61 but also can do auto-complete of values, and can require the value typed
62 to be in the list of choices to be colored appropriately.
65 is actually a factory function for several types of masked edit controls:
67 <b>MaskedTextCtrl</b> - standard masked edit text box
68 <b>MaskedComboBox</b> - adds combobox capabilities
69 <b>IpAddrCtrl</b> - adds special semantics for IP address entry
70 <b>TimeCtrl</b> - special subclass handling lots of types as values
71 <b>wxMaskedNumCtrl</b> - special subclass handling numeric values
73 It works by looking for a <b><i>controlType</i></b> parameter in the keyword
74 arguments of the control, to determine what kind of instance to return.
75 If not specified as a keyword argument, the default control type returned
76 will be MaskedTextCtrl.
78 Each of the above classes has its own set of arguments, but wxMaskedCtrl
79 provides a single "unified" interface for masked controls. Those for
80 MaskedTextCtrl, MaskedComboBox and IpAddrCtrl are all documented
81 below; the others have their own demo pages and interface descriptions.
82 (See end of following discussion for how to configure the wxMaskedCtrl()
83 to select the above control types.)
86 <b>INITILIZATION PARAMETERS
87 ========================
89 Allowed mask characters and function:
91 # Allow numeric only (0-9)
92 N Allow letters and numbers (0-9)
93 A Allow uppercase letters only
94 a Allow lowercase letters only
95 C Allow any letter, upper or lower
96 X Allow string.letters, string.punctuation, string.digits
97 & Allow string.punctuation only
100 These controls define these sets of characters using string.letters,
101 string.uppercase, etc. These sets are affected by the system locale
102 setting, so in order to have the masked controls accept characters
103 that are specific to your users' language, your application should
105 For example, to allow international characters to be used in the
106 above masks, you can place the following in your code as part of
107 your application's initialization code:
110 locale.setlocale(locale.LC_ALL, '')
113 Using these mask characters, a variety of template masks can be built. See
114 the demo for some other common examples include date+time, social security
115 number, etc. If any of these characters are needed as template rather
116 than mask characters, they can be escaped with \, ie. \N means "literal N".
117 (use \\ for literal backslash, as in: r'CCC\\NNN'.)
121 Masks containing only # characters and one optional decimal point
122 character are handled specially, as "numeric" controls. Such
123 controls have special handling for typing the '-' key, handling
124 the "decimal point" character as truncating the integer portion,
125 optionally allowing grouping characters and so forth.
126 There are several parameters and format codes that only make sense
127 when combined with such masks, eg. groupChar, decimalChar, and so
128 forth (see below). These allow you to construct reasonable
129 numeric entry controls.
132 Changing the mask for a control deletes any previous field classes
133 (and any associated validation or formatting constraints) for them.
135 <b>useFixedWidthFont=</b>
136 By default, masked edit controls use a fixed width font, so that
137 the mask characters are fixed within the control, regardless of
138 subsequent modifications to the value. Set to False if having
139 the control font be the same as other controls is required.
143 These other properties can be passed to the class when instantiating it:
144 Formatcodes are specified as a string of single character formatting
145 codes that modify behavior of the control:
149 R Right-align field(s)
150 r Right-insert in field(s) (implies R)
151 < Stay in field until explicit navigation out of it
153 > Allow insert/delete within partially filled fields (as
154 opposed to the default "overwrite" mode for fixed-width
155 masked edit controls.) This allows single-field controls
156 or each field within a multi-field control to optionally
157 behave more like standard text controls.
158 (See EMAIL or phone number autoformat examples.)
160 <i>Note: This also governs whether backspace/delete operations
161 shift contents of field to right of cursor, or just blank the
164 Also, when combined with 'r', this indicates that the field
165 or control allows right insert anywhere within the current
166 non-empty value in the field. (Otherwise right-insert behavior
167 is only performed to when the entire right-insertable field is
168 selected or the cursor is at the right edge of the field.</i>
171 , Allow grouping character in integer fields of numeric controls
172 and auto-group/regroup digits (if the result fits) when leaving
173 such a field. (If specified, .SetValue() will attempt to
175 ',' is also the default grouping character. To change the
176 grouping character and/or decimal character, use the groupChar
177 and decimalChar parameters, respectively.
178 Note: typing the "decimal point" character in such fields will
179 clip the value to that left of the cursor for integer
180 fields of controls with "integer" or "floating point" masks.
181 If the ',' format code is specified, this will also cause the
182 resulting digits to be regrouped properly, using the current
184 - Prepend and reserve leading space for sign to mask and allow
185 signed values (negative #s shown in red by default.) Can be
186 used with argument useParensForNegatives (see below.)
187 0 integer fields get leading zeros
190 F Auto-Fit: the control calulates its size from
191 the length of the template mask
192 V validate entered chars against validRegex before allowing them
193 to be entered vs. being allowed by basic mask and then having
194 the resulting value just colored as invalid.
195 (See USSTATE autoformat demo for how this can be used.)
196 S select entire field when navigating to new field
200 These controls have two options for the initial state of the control.
201 If a blank control with just the non-editable characters showing
202 is desired, simply leave the constructor variable fillChar as its
203 default (' '). If you want some other character there, simply
204 change the fillChar to that value. Note: changing the control's fillChar
205 will implicitly reset all of the fields' fillChars to this value.
207 If you need different default characters in each mask position,
208 you can specify a defaultValue parameter in the constructor, or
209 set them for each field individually.
210 This value must satisfy the non-editable characters of the mask,
211 but need not conform to the replaceable characters.
215 These parameters govern what character is used to group numbers
216 and is used to indicate the decimal point for numeric format controls.
217 The default groupChar is ',', the default decimalChar is '.'
218 By changing these, you can customize the presentation of numbers
220 eg: formatcodes = ',', groupChar="'" allows 12'345.34
221 formatcodes = ',', groupChar='.', decimalChar=',' allows 12.345,34
223 <b>shiftDecimalChar=</b>
224 The default "shiftDecimalChar" (used for "backwards-tabbing" until
225 shift-tab is fixed in wxPython) is '>' (for QUERTY keyboards.) for
226 other keyboards, you may want to customize this, eg '?' for shift ',' on
227 AZERTY keyboards, ':' or ';' for other European keyboards, etc.
229 <b>useParensForNegatives=False</b>
230 This option can be used with signed numeric format controls to
231 indicate signs via () rather than '-'.
233 <b>autoSelect=False</b>
234 This option can be used to have a field or the control try to
235 auto-complete on each keystroke if choices have been specified.
237 <b>autoCompleteKeycodes=[]</b>
238 By default, DownArrow, PageUp and PageDown will auto-complete a
239 partially entered field. Shift-DownArrow, Shift-UpArrow, PageUp
240 and PageDown will also auto-complete, but if the field already
241 contains a matched value, these keys will cycle through the list
242 of choices forward or backward as appropriate. Shift-Up and
243 Shift-Down also take you to the next/previous field after any
244 auto-complete action.
246 Additional auto-complete keys can be specified via this parameter.
247 Any keys so specified will act like PageDown.
251 <b>Validating User Input:
252 ======================</b>
253 There are a variety of initialization parameters that are used to validate
254 user input. These parameters can apply to the control as a whole, and/or
255 to individual fields:
257 excludeChars= A string of characters to exclude even if otherwise allowed
258 includeChars= A string of characters to allow even if otherwise disallowed
259 validRegex= Use a regular expression to validate the contents of the text box
260 validRange= Pass a rangeas list (low,high) to limit numeric fields/values
261 choices= A list of strings that are allowed choices for the control.
262 choiceRequired= value must be member of choices list
263 compareNoCase= Perform case-insensitive matching when validating against list
264 <i>Note: for MaskedComboBox, this defaults to True.</i>
265 emptyInvalid= Boolean indicating whether an empty value should be considered invalid
267 validFunc= A function to call of the form: bool = func(candidate_value)
268 which will return True if the candidate_value satisfies some
269 external criteria for the control in addition to the the
270 other validation, or False if not. (This validation is
271 applied last in the chain of validations.)
273 validRequired= Boolean indicating whether or not keys that are allowed by the
274 mask, but result in an invalid value are allowed to be entered
275 into the control. Setting this to True implies that a valid
276 default value is set for the control.
278 retainFieldValidation=
279 False by default; if True, this allows individual fields to
280 retain their own validation constraints independently of any
281 subsequent changes to the control's overall parameters.
283 validator= Validators are not normally needed for masked controls, because
284 of the nature of the validation and control of input. However,
285 you can supply one to provide data transfer routines for the
289 <b>Coloring Behavior:
290 ==================</b>
291 The following parameters have been provided to allow you to change the default
292 coloring behavior of the control. These can be set at construction, or via
293 the .SetCtrlParameters() function. Pass a color as string e.g. 'Yellow':
295 emptyBackgroundColour= Control Background color when identified as empty. Default=White
296 invalidBackgroundColour= Control Background color when identified as Not valid. Default=Yellow
297 validBackgroundColour= Control Background color when identified as Valid. Default=white
300 The following parameters control the default foreground color coloring behavior of the
301 control. Pass a color as string e.g. 'Yellow':
302 foregroundColour= Control foreground color when value is not negative. Default=Black
303 signedForegroundColour= Control foreground color when value is negative. Default=Red
308 Each part of the mask that allows user input is considered a field. The fields
309 are represented by their own class instances. You can specify field-specific
310 constraints by constructing or accessing the field instances for the control
311 and then specifying those constraints via parameters.
314 This parameter allows you to specify Field instances containing
315 constraints for the individual fields of a control, eg: local
316 choice lists, validation rules, functions, regexps, etc.
317 It can be either an ordered list or a dictionary. If a list,
318 the fields will be applied as fields 0, 1, 2, etc.
319 If a dictionary, it should be keyed by field index.
320 the values should be a instances of maskededit.Field.
322 Any field not represented by the list or dictionary will be
323 implicitly created by the control.
326 fields = [ Field(formatcodes='_r'), Field('choices=['a', 'b', 'c']) ]
329 1: ( Field(formatcodes='_R', choices=['a', 'b', 'c']),
330 3: ( Field(choices=['01', '02', '03'], choiceRequired=True)
333 The following parameters are available for individual fields, with the
334 same semantics as for the whole control but applied to the field in question:
336 fillChar # if set for a field, it will override the control's fillChar for that field
337 groupChar # if set for a field, it will override the control's default
338 defaultValue # sets field-specific default value; overrides any default from control
339 compareNoCase # overrides control's settings
340 emptyInvalid # determines whether field is required to be filled at all times
341 validRequired # if set, requires field to contain valid value
343 If any of the above parameters are subsequently specified for the control as a
344 whole, that new value will be propagated to each field, unless the
345 retainFieldValidation control-level parameter is set.
347 formatcodes # Augments control's settings
353 choiceRequired # ' ' '
358 <b>Control Class Functions:
359 ========================
360 .GetPlainValue(value=None)</b>
361 Returns the value specified (or the control's text value
362 not specified) without the formatting text.
363 In the example above, might return phone no='3522640075',
364 whereas control.GetValue() would return '(352) 264-0075'
366 Returns the control's value to its default, and places the
367 cursor at the beginning of the control.
369 Does "smart replacement" of passed value into the control, as does
370 the .Paste() method. As with other text entry controls, the
371 .SetValue() text replacement begins at left-edge of the control,
372 with missing mask characters inserted as appropriate.
373 .SetValue will also adjust integer, float or date mask entry values,
374 adding commas, auto-completing years, etc. as appropriate.
375 For "right-aligned" numeric controls, it will also now automatically
376 right-adjust any value whose length is less than the width of the
377 control before attempting to set the value.
378 If a value does not follow the format of the control's mask, or will
379 not fit into the control, a ValueError exception will be raised.
381 mask = '(###) ###-####'
382 .SetValue('1234567890') => '(123) 456-7890'
383 .SetValue('(123)4567890') => '(123) 456-7890'
384 .SetValue('(123)456-7890') => '(123) 456-7890'
385 .SetValue('123/4567-890') => illegal paste; ValueError
387 mask = '#{6}.#{2}', formatcodes = '_,-',
388 .SetValue('111') => ' 111 . '
389 .SetValue(' %9.2f' % -111.12345 ) => ' -111.12'
390 .SetValue(' %9.2f' % 1234.00 ) => ' 1,234.00'
391 .SetValue(' %9.2f' % -1234567.12345 ) => insufficient room; ValueError
393 mask = '#{6}.#{2}', formatcodes = '_,-R' # will right-adjust value for right-aligned control
394 .SetValue('111') => padded value misalignment ValueError: " 111" will not fit
395 .SetValue('%.2f' % 111 ) => ' 111.00'
396 .SetValue('%.2f' % -111.12345 ) => ' -111.12'
399 <b>.IsValid(value=None)</b>
400 Returns True if the value specified (or the value of the control
401 if not specified) passes validation tests
402 <b>.IsEmpty(value=None)</b>
403 Returns True if the value specified (or the value of the control
404 if not specified) is equal to an "empty value," ie. all
405 editable characters == the fillChar for their respective fields.
406 <b>.IsDefault(value=None)</b>
407 Returns True if the value specified (or the value of the control
408 if not specified) is equal to the initial value of the control.
411 Recolors the control as appropriate to its current settings.
413 <b>.SetCtrlParameters(**kwargs)</b>
414 This function allows you to set up and/or change the control parameters
415 after construction; it takes a list of key/value pairs as arguments,
416 where the keys can be any of the mask-specific parameters in the constructor.
418 ctl = MaskedTextCtrl( self, -1 )
419 ctl.SetCtrlParameters( mask='###-####',
420 defaultValue='555-1212',
423 <b>.GetCtrlParameter(parametername)</b>
424 This function allows you to retrieve the current value of a parameter
427 <b><i>Note:</i></b> Each of the control parameters can also be set using its
428 own Set and Get function. These functions follow a regular form:
429 All of the parameter names start with lower case; for their
430 corresponding Set/Get function, the parameter name is capitalized.
431 Eg: ctl.SetMask('###-####')
432 ctl.SetDefaultValue('555-1212')
433 ctl.GetChoiceRequired()
436 <b>.SetFieldParameters(field_index, **kwargs)</b>
437 This function allows you to specify change individual field
438 parameters after construction. (Indices are 0-based.)
440 <b>.GetFieldParameter(field_index, parametername)</b>
441 Allows the retrieval of field parameters after construction
444 The control detects certain common constructions. In order to use the signed feature
445 (negative numbers and coloring), the mask has to be all numbers with optionally one
446 decimal point. Without a decimal (e.g. '######', the control will treat it as an integer
447 value. With a decimal (e.g. '###.##'), the control will act as a floating point control
448 (i.e. press decimal to 'tab' to the decimal position). Pressing decimal in the
449 integer control truncates the value.
452 Check your controls by calling each control's .IsValid() function and the
453 .IsEmpty() function to determine which controls have been a) filled in and
454 b) filled in properly.
457 Regular expression validations can be used flexibly and creatively.
458 Take a look at the demo; the zip-code validation succeeds as long as the
459 first five numerals are entered. the last four are optional, but if
460 any are entered, there must be 4 to be valid.
462 <B>wxMaskedCtrl Configuration
463 ==========================</B>
464 wxMaskedCtrl works by looking for a special <b><i>controlType</i></b>
465 parameter in the variable arguments of the control, to determine
466 what kind of instance to return.
467 controlType can be one of:
469 controlTypes.MASKEDTEXT
470 controlTypes.MASKEDCOMBO
475 These constants are also available individually, ie, you can
476 use either of the following:
478 from wxPython.wx.lib.maskedctrl import wxMaskedCtrl, controlTypes
479 from wxPython.wx.lib.maskedctrl import wxMaskedCtrl, MASKEDCOMBO, MASKEDTEXT, NUMBER
481 If not specified as a keyword argument, the default controlType is
486 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
491 All methods of the Mixin that are not meant to be exposed to the external
492 interface are prefaced with '_'. Those functions that are primarily
493 intended to be internal subroutines subsequently start with a lower-case
494 letter; those that are primarily intended to be used and/or overridden
495 by derived subclasses start with a capital letter.
497 The following methods must be used and/or defined when deriving a control
498 from wxMaskedEditMixin. NOTE: if deriving from a *masked edit* control
499 (eg. class IpAddrCtrl(MaskedTextCtrl) ), then this is NOT necessary,
500 as it's already been done for you in the base class.
503 This function must be called after the associated base
504 control has been initialized in the subclass __init__
505 function. It sets the initial value of the control,
506 either to the value specified if non-empty, the
507 default value if specified, or the "template" for
508 the empty control as necessary. It will also set/reset
509 the font if necessary and apply formatting to the
510 control at this time.
514 Each class derived from wxMaskedEditMixin must define
515 the function for getting the start and end of the
516 current text selection. The reason for this is
517 that not all controls have the same function name for
518 doing this; eg. wxTextCtrl uses .GetSelection(),
519 whereas we had to write a .GetMark() function for
520 wxComboBox, because .GetSelection() for the control
521 gets the currently selected list item from the combo
522 box, and the control doesn't (yet) natively provide
523 a means of determining the text selection.
526 Similarly to _GetSelection, each class derived from
527 wxMaskedEditMixin must define the function for setting
528 the start and end of the current text selection.
529 (eg. .SetSelection() for MaskedTextCtrl, and .SetMark() for
532 ._GetInsertionPoint()
533 ._SetInsertionPoint()
535 For consistency, and because the mixin shouldn't rely
536 on fixed names for any manipulations it does of any of
537 the base controls, we require each class derived from
538 wxMaskedEditMixin to define these functions as well.
541 ._SetValue() REQUIRED
542 Each class derived from wxMaskedEditMixin must define
543 the functions used to get and set the raw value of the
545 This is necessary so that recursion doesn't take place
546 when setting the value, and so that the mixin can
547 call the appropriate function after doing all its
548 validation and manipulation without knowing what kind
549 of base control it was mixed in with. To handle undo
550 functionality, the ._SetValue() must record the current
551 selection prior to setting the value.
557 Each class derived from wxMaskedEditMixin must redefine
558 these functions to call the _Cut(), _Paste(), _Undo()
559 and _SetValue() methods, respectively for the control,
560 so as to prevent programmatic corruption of the control's
561 value. This must be done in each derivation, as the
562 mixin cannot itself override a member of a sibling class.
565 Each class derived from wxMaskedEditMixin must define
566 the function used to refresh the base control.
569 Each class derived from wxMaskedEditMixin must redefine
570 this function so that it checks the validity of the
571 control (via self._CheckValid) and then refreshes
572 control using the base class method.
574 ._IsEditable() REQUIRED
575 Each class derived from wxMaskedEditMixin must define
576 the function used to determine if the base control is
577 editable or not. (For MaskedComboBox, this has to
578 be done with code, rather than specifying the proper
579 function in the base control, as there isn't one...)
580 ._CalcSize() REQUIRED
581 Each class derived from wxMaskedEditMixin must define
582 the function used to determine how wide the control
583 should be given the mask. (The mixin function
584 ._calcSize() provides a baseline estimate.)
589 Event handlers are "chained", and wxMaskedEditMixin usually
590 swallows most of the events it sees, thereby preventing any other
591 handlers from firing in the chain. It is therefore required that
592 each class derivation using the mixin to have an option to hook up
593 the event handlers itself or forego this operation and let a
594 subclass of the masked control do so. For this reason, each
595 subclass should probably include the following code:
597 if setupEventHandling:
598 ## Setup event handlers
599 EVT_SET_FOCUS( self, self._OnFocus ) ## defeat automatic full selection
600 EVT_KILL_FOCUS( self, self._OnKillFocus ) ## run internal validator
601 EVT_LEFT_DCLICK(self, self._OnDoubleClick) ## select field under cursor on dclick
602 EVT_RIGHT_UP(self, self._OnContextMenu ) ## bring up an appropriate context menu
603 EVT_KEY_DOWN( self, self._OnKeyDown ) ## capture control events not normally seen, eg ctrl-tab.
604 EVT_CHAR( self, self._OnChar ) ## handle each keypress
605 EVT_TEXT( self, self.GetId(), self._OnTextChange ) ## color control appropriately & keep
606 ## track of previous value for undo
608 where setupEventHandling is an argument to its constructor.
610 These 5 handlers must be "wired up" for the wxMaskedEdit
611 control to provide default behavior. (The setupEventHandling
612 is an argument to MaskedTextCtrl and MaskedComboBox, so
613 that controls derived from *them* may replace one of these
614 handlers if they so choose.)
616 If your derived control wants to preprocess events before
617 taking action, it should then set up the event handling itself,
618 so it can be first in the event handler chain.
621 The following routines are available to facilitate changing
622 the default behavior of wxMaskedEdit controls:
624 ._SetKeycodeHandler(keycode, func)
625 ._SetKeyHandler(char, func)
626 Use to replace default handling for any given keycode.
627 func should take the key event as argument and return
628 False if no further action is required to handle the
630 self._SetKeycodeHandler(WXK_UP, self.IncrementValue)
631 self._SetKeyHandler('-', self._OnChangeSign)
633 "Navigation" keys are assumed to change the cursor position, and
634 therefore don't cause automatic motion of the cursor as insertable
637 ._AddNavKeycode(keycode, handler=None)
638 ._AddNavKey(char, handler=None)
639 Allows controls to specify other keys (and optional handlers)
640 to be treated as navigational characters. (eg. '.' in IpAddrCtrl)
642 ._GetNavKeycodes() Returns the current list of navigational keycodes.
644 ._SetNavKeycodes(key_func_tuples)
645 Allows replacement of the current list of keycode
646 processed as navigation keys, and bind associated
647 optional keyhandlers. argument is a list of key/handler
648 tuples. Passing a value of None for the handler in a
649 given tuple indicates that default processing for the key
652 ._FindField(pos) Returns the Field object associated with this position
655 ._FindFieldExtent(pos, getslice=False, value=None)
656 Returns edit_start, edit_end of the field corresponding
657 to the specified position within the control, and
658 optionally also returns the current contents of that field.
659 If value is specified, it will retrieve the slice the corresponding
660 slice from that value, rather than the current value of the
664 This is, the function that gets called for a given position
665 whenever the cursor is adjusted to leave a given field.
666 By default, it adjusts the year in date fields if mask is a date,
667 It can be overridden by a derived class to
668 adjust the value of the control at that time.
669 (eg. IpAddrCtrl reformats the address in this way.)
671 ._Change() Called by internal EVT_TEXT handler. Return False to force
672 skip of the normal class change event.
673 ._Keypress(key) Called by internal EVT_CHAR handler. Return False to force
674 skip of the normal class keypress event.
675 ._LostFocus() Called by internal EVT_KILL_FOCUS handler
678 This is the default EVT_KEY_DOWN routine; it just checks for
679 "navigation keys", and if event.ControlDown(), it fires the
680 mixin's _OnChar() routine, as such events are not always seen
681 by the "cooked" EVT_CHAR routine.
683 ._OnChar(event) This is the main EVT_CHAR handler for the
686 The following routines are used to handle standard actions
688 _OnArrow(event) used for arrow navigation events
689 _OnCtrl_A(event) 'select all'
690 _OnCtrl_C(event) 'copy' (uses base control function, as copy is non-destructive)
691 _OnCtrl_S(event) 'save' (does nothing)
692 _OnCtrl_V(event) 'paste' - calls _Paste() method, to do smart paste
693 _OnCtrl_X(event) 'cut' - calls _Cut() method, to "erase" selection
694 _OnCtrl_Z(event) 'undo' - resets value to previous value (if any)
696 _OnChangeField(event) primarily used for tab events, but can be
697 used for other keys (eg. '.' in IpAddrCtrl)
699 _OnErase(event) used for backspace and delete
713 # jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would
714 # be a good place to implement the 2.3 logger class
715 from wx
.tools
.dbg
import Logger
720 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
722 ## Constants for identifying control keys and classes of keys:
724 WXK_CTRL_A
= (ord('A')+1) - ord('A') ## These keys are not already defined in wx
725 WXK_CTRL_C
= (ord('C')+1) - ord('A')
726 WXK_CTRL_S
= (ord('S')+1) - ord('A')
727 WXK_CTRL_V
= (ord('V')+1) - ord('A')
728 WXK_CTRL_X
= (ord('X')+1) - ord('A')
729 WXK_CTRL_Z
= (ord('Z')+1) - ord('A')
732 wx
.WXK_BACK
, wx
.WXK_LEFT
, wx
.WXK_RIGHT
, wx
.WXK_UP
, wx
.WXK_DOWN
, wx
.WXK_TAB
,
733 wx
.WXK_HOME
, wx
.WXK_END
, wx
.WXK_RETURN
, wx
.WXK_PRIOR
, wx
.WXK_NEXT
737 wx
.WXK_BACK
, wx
.WXK_DELETE
, WXK_CTRL_A
, WXK_CTRL_C
, WXK_CTRL_S
, WXK_CTRL_V
,
738 WXK_CTRL_X
, WXK_CTRL_Z
742 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
744 ## Constants for masking. This is where mask characters
746 ## maskchars used to identify valid mask characters from all others
747 ## #- allow numeric 0-9 only
748 ## A- allow uppercase only. Combine with forceupper to force lowercase to upper
749 ## a- allow lowercase only. Combine with forcelower to force upper to lowercase
750 ## X- allow any character (string.letters, string.punctuation, string.digits)
751 ## Note: locale settings affect what "uppercase", lowercase, etc comprise.
753 maskchars
= ("#","A","a","X","C","N", '&')
755 months
= '(01|02|03|04|05|06|07|08|09|10|11|12)'
756 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)'
757 charmonths_dict
= {'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
758 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12}
760 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)'
761 hours
= '(0\d| \d|1[012])'
762 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)'
763 minutes
= """(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|\
764 16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|\
765 36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|\
768 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'
770 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(',')
772 state_names
= ['Alabama','Alaska','Arizona','Arkansas',
773 'California','Colorado','Connecticut',
774 'Delaware','District of Columbia',
775 'Florida','Georgia','Hawaii',
776 'Idaho','Illinois','Indiana','Iowa',
777 'Kansas','Kentucky','Louisiana',
778 'Maine','Maryland','Massachusetts','Michigan',
779 'Minnesota','Mississippi','Missouri','Montana',
780 'Nebraska','Nevada','New Hampshire','New Jersey',
781 'New Mexico','New York','North Carolina','North Dakokta',
782 'Ohio','Oklahoma','Oregon',
783 'Pennsylvania','Puerto Rico','Rhode Island',
784 'South Carolina','South Dakota',
785 'Tennessee','Texas','Utah',
786 'Vermont','Virginia',
787 'Washington','West Virginia',
788 'Wisconsin','Wyoming']
790 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
792 ## The following dictionary defines the current set of autoformats:
796 'mask': "(###) ###-#### x:###",
797 'formatcodes': 'F^->',
798 'validRegex': "^\(\d{3}\) \d{3}-\d{4}",
799 'description': "Phone Number w/opt. ext"
802 'mask': "###-###-#### x:###",
803 'formatcodes': 'F^->',
804 'validRegex': "^\d{3}-\d{3}-\d{4}",
805 'description': "Phone Number\n (w/hyphens and opt. ext)"
808 'mask': "(###) ###-####",
809 'formatcodes': 'F^->',
810 'validRegex': "^\(\d{3}\) \d{3}-\d{4}",
811 'description': "Phone Number only"
814 'mask': "###-###-####",
815 'formatcodes': 'F^->',
816 'validRegex': "^\d{3}-\d{3}-\d{4}",
817 'description': "Phone Number\n(w/hyphens)"
821 'formatcodes': 'F!V',
822 'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string
.join(states
,'|'),
824 'choiceRequired': True,
825 'description': "US State Code"
828 'mask': "ACCCCCCCCCCCCCCCCCCC",
830 'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string
.join(state_names
,'|'),
831 'choices': state_names
,
832 'choiceRequired': True,
833 'description': "US State Name"
836 "USDATETIMEMMDDYYYY/HHMMSS": {
837 'mask': "##/##/#### ##:##:## AM",
838 'excludeChars': am_pm_exclude
,
839 'formatcodes': 'DF!',
840 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
841 'description': "US Date + Time"
843 "USDATETIMEMMDDYYYY-HHMMSS": {
844 'mask': "##-##-#### ##:##:## AM",
845 'excludeChars': am_pm_exclude
,
846 'formatcodes': 'DF!',
847 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
848 'description': "US Date + Time\n(w/hypens)"
850 "USDATEMILTIMEMMDDYYYY/HHMMSS": {
851 'mask': "##/##/#### ##:##:##",
853 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
854 'description': "US Date + Military Time"
856 "USDATEMILTIMEMMDDYYYY-HHMMSS": {
857 'mask': "##-##-#### ##:##:##",
859 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
860 'description': "US Date + Military Time\n(w/hypens)"
862 "USDATETIMEMMDDYYYY/HHMM": {
863 'mask': "##/##/#### ##:## AM",
864 'excludeChars': am_pm_exclude
,
865 'formatcodes': 'DF!',
866 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
867 'description': "US Date + Time\n(without seconds)"
869 "USDATEMILTIMEMMDDYYYY/HHMM": {
870 'mask': "##/##/#### ##:##",
872 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
,
873 'description': "US Date + Military Time\n(without seconds)"
875 "USDATETIMEMMDDYYYY-HHMM": {
876 'mask': "##-##-#### ##:## AM",
877 'excludeChars': am_pm_exclude
,
878 'formatcodes': 'DF!',
879 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
880 'description': "US Date + Time\n(w/hypens and w/o secs)"
882 "USDATEMILTIMEMMDDYYYY-HHMM": {
883 'mask': "##-##-#### ##:##",
885 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + milhours
+ ':' + minutes
,
886 'description': "US Date + Military Time\n(w/hyphens and w/o seconds)"
889 'mask': "##/##/####",
891 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4}',
892 'description': "US Date\n(MMDDYYYY)"
897 'validRegex': '^' + months
+ '/' + days
+ '/\d\d',
898 'description': "US Date\n(MMDDYY)"
901 'mask': "##-##-####",
903 'validRegex': '^' + months
+ '-' + days
+ '-' +'\d{4}',
904 'description': "MM-DD-YYYY"
908 'mask': "####/##/##",
910 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
,
911 'description': "YYYY/MM/DD"
914 'mask': "####.##.##",
916 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
,
917 'description': "YYYY.MM.DD"
920 'mask': "##/##/####",
922 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4}',
923 'description': "DD/MM/YYYY"
926 'mask': "##.##.####",
928 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4}',
929 'description': "DD.MM.YYYY"
931 "EUDATEDDMMMYYYY.": {
932 'mask': "##.CCC.####",
934 'validRegex': '^' + days
+ '.' + charmonths
+ '.' + '\d{4}',
935 'description': "DD.Month.YYYY"
937 "EUDATEDDMMMYYYY/": {
938 'mask': "##/CCC/####",
940 'validRegex': '^' + days
+ '/' + charmonths
+ '/' + '\d{4}',
941 'description': "DD/Month/YYYY"
944 "EUDATETIMEYYYYMMDD/HHMMSS": {
945 'mask': "####/##/## ##:##:## AM",
946 'excludeChars': am_pm_exclude
,
947 'formatcodes': 'DF!',
948 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
949 'description': "YYYY/MM/DD HH:MM:SS"
951 "EUDATETIMEYYYYMMDD.HHMMSS": {
952 'mask': "####.##.## ##:##:## AM",
953 'excludeChars': am_pm_exclude
,
954 'formatcodes': 'DF!',
955 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
956 'description': "YYYY.MM.DD HH:MM:SS"
958 "EUDATETIMEDDMMYYYY/HHMMSS": {
959 'mask': "##/##/#### ##:##:## AM",
960 'excludeChars': am_pm_exclude
,
961 'formatcodes': 'DF!',
962 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
963 'description': "DD/MM/YYYY HH:MM:SS"
965 "EUDATETIMEDDMMYYYY.HHMMSS": {
966 'mask': "##.##.#### ##:##:## AM",
967 'excludeChars': am_pm_exclude
,
968 'formatcodes': 'DF!',
969 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
970 'description': "DD.MM.YYYY HH:MM:SS"
973 "EUDATETIMEYYYYMMDD/HHMM": {
974 'mask': "####/##/## ##:## AM",
975 'excludeChars': am_pm_exclude
,
976 'formatcodes': 'DF!',
977 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + hours
+ ':' + minutes
+ ' (A|P)M',
978 'description': "YYYY/MM/DD HH:MM"
980 "EUDATETIMEYYYYMMDD.HHMM": {
981 'mask': "####.##.## ##:## AM",
982 'excludeChars': am_pm_exclude
,
983 'formatcodes': 'DF!',
984 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + hours
+ ':' + minutes
+ ' (A|P)M',
985 'description': "YYYY.MM.DD HH:MM"
987 "EUDATETIMEDDMMYYYY/HHMM": {
988 'mask': "##/##/#### ##:## AM",
989 'excludeChars': am_pm_exclude
,
990 'formatcodes': 'DF!',
991 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
992 'description': "DD/MM/YYYY HH:MM"
994 "EUDATETIMEDDMMYYYY.HHMM": {
995 'mask': "##.##.#### ##:## AM",
996 'excludeChars': am_pm_exclude
,
997 'formatcodes': 'DF!',
998 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
999 'description': "DD.MM.YYYY HH:MM"
1002 "EUDATEMILTIMEYYYYMMDD/HHMMSS": {
1003 'mask': "####/##/## ##:##:##",
1004 'formatcodes': 'DF',
1005 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1006 'description': "YYYY/MM/DD Mil. Time"
1008 "EUDATEMILTIMEYYYYMMDD.HHMMSS": {
1009 'mask': "####.##.## ##:##:##",
1010 'formatcodes': 'DF',
1011 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1012 'description': "YYYY.MM.DD Mil. Time"
1014 "EUDATEMILTIMEDDMMYYYY/HHMMSS": {
1015 'mask': "##/##/#### ##:##:##",
1016 'formatcodes': 'DF',
1017 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1018 'description': "DD/MM/YYYY Mil. Time"
1020 "EUDATEMILTIMEDDMMYYYY.HHMMSS": {
1021 'mask': "##.##.#### ##:##:##",
1022 'formatcodes': 'DF',
1023 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1024 'description': "DD.MM.YYYY Mil. Time"
1026 "EUDATEMILTIMEYYYYMMDD/HHMM": {
1027 'mask': "####/##/## ##:##",
1028 'formatcodes': 'DF','validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + milhours
+ ':' + minutes
,
1029 'description': "YYYY/MM/DD Mil. Time\n(w/o seconds)"
1031 "EUDATEMILTIMEYYYYMMDD.HHMM": {
1032 'mask': "####.##.## ##:##",
1033 'formatcodes': 'DF',
1034 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + milhours
+ ':' + minutes
,
1035 'description': "YYYY.MM.DD Mil. Time\n(w/o seconds)"
1037 "EUDATEMILTIMEDDMMYYYY/HHMM": {
1038 'mask': "##/##/#### ##:##",
1039 'formatcodes': 'DF',
1040 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
,
1041 'description': "DD/MM/YYYY Mil. Time\n(w/o seconds)"
1043 "EUDATEMILTIMEDDMMYYYY.HHMM": {
1044 'mask': "##.##.#### ##:##",
1045 'formatcodes': 'DF',
1046 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + milhours
+ ':' + minutes
,
1047 'description': "DD.MM.YYYY Mil. Time\n(w/o seconds)"
1051 'mask': "##:##:## AM",
1052 'excludeChars': am_pm_exclude
,
1053 'formatcodes': 'TF!',
1054 'validRegex': '^' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
1055 'description': "HH:MM:SS (A|P)M\n(see TimeCtrl)"
1059 'excludeChars': am_pm_exclude
,
1060 'formatcodes': 'TF!',
1061 'validRegex': '^' + hours
+ ':' + minutes
+ ' (A|P)M',
1062 'description': "HH:MM (A|P)M\n(see TimeCtrl)"
1066 'formatcodes': 'TF',
1067 'validRegex': '^' + milhours
+ ':' + minutes
+ ':' + seconds
,
1068 'description': "Military HH:MM:SS\n(see TimeCtrl)"
1072 'formatcodes': 'TF',
1073 'validRegex': '^' + milhours
+ ':' + minutes
,
1074 'description': "Military HH:MM\n(see TimeCtrl)"
1077 'mask': "###-##-####",
1079 'validRegex': "\d{3}-\d{2}-\d{4}",
1080 'description': "Social Sec#"
1083 'mask': "####-####-####-####",
1085 'validRegex': "\d{4}-\d{4}-\d{4}-\d{4}",
1086 'description': "Credit Card"
1091 'validRegex': "^" + months
+ "/\d\d",
1092 'description': "Expiration MM/YY"
1097 'validRegex': "^\d{5}",
1098 'description': "US 5-digit zip code"
1101 'mask': "#####-####",
1103 'validRegex': "\d{5}-(\s{4}|\d{4})",
1104 'description': "US zip+4 code"
1109 'validRegex': "^0.\d\d",
1110 'description': "Percentage"
1115 'validRegex': "^[1-9]{1} |[1-9][0-9] |1[0|1|2][0-9]",
1116 'description': "Age"
1119 'mask': "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
1120 'excludeChars': " \\/*&%$#!+='\"",
1121 'formatcodes': "F>",
1122 '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}\]) *$",
1123 'description': "Email address"
1126 'mask': "###.###.###.###",
1127 'formatcodes': 'F_Sr',
1128 '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}",
1129 'description': "IP Address\n(see IpAddrCtrl)"
1133 # build demo-friendly dictionary of descriptions of autoformats
1135 for key
, value
in masktags
.items():
1136 autoformats
.append((key
, value
['description']))
1139 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
1143 'index': None, ## which field of mask; set by parent control.
1144 'mask': "", ## mask chars for this field
1145 'extent': (), ## (edit start, edit_end) of field; set by parent control.
1146 'formatcodes': "", ## codes indicating formatting options for the control
1147 'fillChar': ' ', ## used as initial value for each mask position if initial value is not given
1148 'groupChar': ',', ## used with numeric fields; indicates what char groups 3-tuple digits
1149 'decimalChar': '.', ## used with numeric fields; indicates what char separates integer from fraction
1150 'shiftDecimalChar': '>', ## used with numeric fields, indicates what is above the decimal point char on keyboard
1151 'useParensForNegatives': False, ## used with numeric fields, indicates that () should be used vs. - to show negative numbers.
1152 'defaultValue': "", ## use if you want different positional defaults vs. all the same fillChar
1153 'excludeChars': "", ## optional string of chars to exclude even if main mask type does
1154 'includeChars': "", ## optional string of chars to allow even if main mask type doesn't
1155 'validRegex': "", ## optional regular expression to use to validate the control
1156 'validRange': (), ## Optional hi-low range for numerics
1157 'choices': [], ## Optional list for character expressions
1158 'choiceRequired': False, ## If choices supplied this specifies if valid value must be in the list
1159 'compareNoCase': False, ## Optional flag to indicate whether or not to use case-insensitive list search
1160 'autoSelect': False, ## Set to True to try auto-completion on each keystroke:
1161 'validFunc': None, ## Optional function for defining additional, possibly dynamic validation constraints on contrl
1162 'validRequired': False, ## Set to True to disallow input that results in an invalid value
1163 'emptyInvalid': False, ## Set to True to make EMPTY = INVALID
1164 'description': "", ## primarily for autoformats, but could be useful elsewhere
1167 # This list contains all parameters that when set at the control level should
1168 # propagate down to each field:
1169 propagating_params
= ('fillChar', 'groupChar', 'decimalChar','useParensForNegatives',
1170 'compareNoCase', 'emptyInvalid', 'validRequired')
1172 def __init__(self
, **kwargs
):
1174 This is the "constructor" for setting up parameters for fields.
1175 a field_index of -1 is used to indicate "the entire control."
1177 ## dbg('Field::Field', indent=1)
1178 # Validate legitimate set of parameters:
1179 for key
in kwargs
.keys():
1180 if key
not in Field
.valid_params
.keys():
1182 raise TypeError('invalid parameter "%s"' % (key
))
1184 # Set defaults for each parameter for this instance, and fully
1185 # populate initial parameter list for configuration:
1186 for key
, value
in Field
.valid_params
.items():
1187 setattr(self
, '_' + key
, copy
.copy(value
))
1188 if not kwargs
.has_key(key
):
1189 kwargs
[key
] = copy
.copy(value
)
1191 self
._autoCompleteIndex
= -1
1192 self
._SetParameters
(**kwargs
)
1193 self
._ValidateParameters
(**kwargs
)
1198 def _SetParameters(self
, **kwargs
):
1200 This function can be used to set individual or multiple parameters for
1201 a masked edit field parameter after construction.
1204 dbg('maskededit.Field::_SetParameters', indent
=1)
1205 # Validate keyword arguments:
1206 for key
in kwargs
.keys():
1207 if key
not in Field
.valid_params
.keys():
1208 dbg(indent
=0, suspend
=0)
1209 raise AttributeError('invalid keyword argument "%s"' % key
)
1211 if self
._index
is not None: dbg('field index:', self
._index
)
1212 dbg('parameters:', indent
=1)
1213 for key
, value
in kwargs
.items():
1214 dbg('%s:' % key
, value
)
1217 old_fillChar
= self
._fillChar
# store so we can change choice lists accordingly if it changes
1219 # First, Assign all parameters specified:
1220 for key
in Field
.valid_params
.keys():
1221 if kwargs
.has_key(key
):
1222 setattr(self
, '_' + key
, kwargs
[key
] )
1224 if kwargs
.has_key('formatcodes'): # (set/changed)
1225 self
._forceupper
= '!' in self
._formatcodes
1226 self
._forcelower
= '^' in self
._formatcodes
1227 self
._groupdigits
= ',' in self
._formatcodes
1228 self
._okSpaces
= '_' in self
._formatcodes
1229 self
._padZero
= '0' in self
._formatcodes
1230 self
._autofit
= 'F' in self
._formatcodes
1231 self
._insertRight
= 'r' in self
._formatcodes
1232 self
._allowInsert
= '>' in self
._formatcodes
1233 self
._alignRight
= 'R' in self
._formatcodes
or 'r' in self
._formatcodes
1234 self
._moveOnFieldFull
= not '<' in self
._formatcodes
1235 self
._selectOnFieldEntry
= 'S' in self
._formatcodes
1237 if kwargs
.has_key('groupChar'):
1238 self
._groupChar
= kwargs
['groupChar']
1239 if kwargs
.has_key('decimalChar'):
1240 self
._decimalChar
= kwargs
['decimalChar']
1241 if kwargs
.has_key('shiftDecimalChar'):
1242 self
._shiftDecimalChar
= kwargs
['shiftDecimalChar']
1244 if kwargs
.has_key('formatcodes') or kwargs
.has_key('validRegex'):
1245 self
._regexMask
= 'V' in self
._formatcodes
and self
._validRegex
1247 if kwargs
.has_key('fillChar'):
1248 self
._old
_fillChar
= old_fillChar
1249 ## dbg("self._old_fillChar: '%s'" % self._old_fillChar)
1251 if kwargs
.has_key('mask') or kwargs
.has_key('validRegex'): # (set/changed)
1252 self
._isInt
= isInteger(self
._mask
)
1253 dbg('isInt?', self
._isInt
, 'self._mask:"%s"' % self
._mask
)
1255 dbg(indent
=0, suspend
=0)
1258 def _ValidateParameters(self
, **kwargs
):
1260 This function can be used to validate individual or multiple parameters for
1261 a masked edit field parameter after construction.
1264 dbg('maskededit.Field::_ValidateParameters', indent
=1)
1265 if self
._index
is not None: dbg('field index:', self
._index
)
1266 ## dbg('parameters:', indent=1)
1267 ## for key, value in kwargs.items():
1268 ## dbg('%s:' % key, value)
1270 ## dbg("self._old_fillChar: '%s'" % self._old_fillChar)
1272 # Verify proper numeric format params:
1273 if self
._groupdigits
and self
._groupChar
== self
._decimalChar
:
1274 dbg(indent
=0, suspend
=0)
1275 raise AttributeError("groupChar '%s' cannot be the same as decimalChar '%s'" % (self
._groupChar
, self
._decimalChar
))
1278 # Now go do validation, semantic and inter-dependency parameter processing:
1279 if kwargs
.has_key('choices') or kwargs
.has_key('compareNoCase') or kwargs
.has_key('choiceRequired'): # (set/changed)
1281 self
._compareChoices
= [choice
.strip() for choice
in self
._choices
]
1283 if self
._compareNoCase
and self
._choices
:
1284 self
._compareChoices
= [item
.lower() for item
in self
._compareChoices
]
1286 if kwargs
.has_key('choices'):
1287 self
._autoCompleteIndex
= -1
1290 if kwargs
.has_key('validRegex'): # (set/changed)
1291 if self
._validRegex
:
1293 if self
._compareNoCase
:
1294 self
._filter
= re
.compile(self
._validRegex
, re
.IGNORECASE
)
1296 self
._filter
= re
.compile(self
._validRegex
)
1298 dbg(indent
=0, suspend
=0)
1299 raise TypeError('%s: validRegex "%s" not a legal regular expression' % (str(self
._index
), self
._validRegex
))
1303 if kwargs
.has_key('validRange'): # (set/changed)
1304 self
._hasRange
= False
1307 if self
._validRange
:
1308 if type(self
._validRange
) != types
.TupleType
or len( self
._validRange
)!= 2 or self
._validRange
[0] > self
._validRange
[1]:
1309 dbg(indent
=0, suspend
=0)
1310 raise TypeError('%s: validRange %s parameter must be tuple of form (a,b) where a <= b'
1311 % (str(self
._index
), repr(self
._validRange
)) )
1313 self
._hasRange
= True
1314 self
._rangeLow
= self
._validRange
[0]
1315 self
._rangeHigh
= self
._validRange
[1]
1317 if kwargs
.has_key('choices') or (len(self
._choices
) and len(self
._choices
[0]) != len(self
._mask
)): # (set/changed)
1318 self
._hasList
= False
1319 if self
._choices
and type(self
._choices
) not in (types
.TupleType
, types
.ListType
):
1320 dbg(indent
=0, suspend
=0)
1321 raise TypeError('%s: choices must be a sequence of strings' % str(self
._index
))
1322 elif len( self
._choices
) > 0:
1323 for choice
in self
._choices
:
1324 if type(choice
) not in (types
.StringType
, types
.UnicodeType
):
1325 dbg(indent
=0, suspend
=0)
1326 raise TypeError('%s: choices must be a sequence of strings' % str(self
._index
))
1328 length
= len(self
._mask
)
1329 dbg('len(%s)' % self
._mask
, length
, 'len(self._choices):', len(self
._choices
), 'length:', length
, 'self._alignRight?', self
._alignRight
)
1330 if len(self
._choices
) and length
:
1331 if len(self
._choices
[0]) > length
:
1332 # changed mask without respecifying choices; readjust the width as appropriate:
1333 self
._choices
= [choice
.strip() for choice
in self
._choices
]
1334 if self
._alignRight
:
1335 self
._choices
= [choice
.rjust( length
) for choice
in self
._choices
]
1337 self
._choices
= [choice
.ljust( length
) for choice
in self
._choices
]
1338 dbg('aligned choices:', self
._choices
)
1340 if hasattr(self
, '_template'):
1341 # Verify each choice specified is valid:
1342 for choice
in self
._choices
:
1343 if self
.IsEmpty(choice
) and not self
._validRequired
:
1344 # allow empty values even if invalid, (just colored differently)
1346 if not self
.IsValid(choice
):
1347 dbg(indent
=0, suspend
=0)
1348 raise ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self
._index
), choice
))
1349 self
._hasList
= True
1351 ## dbg("kwargs.has_key('fillChar')?", kwargs.has_key('fillChar'), "len(self._choices) > 0?", len(self._choices) > 0)
1352 ## dbg("self._old_fillChar:'%s'" % self._old_fillChar, "self._fillChar: '%s'" % self._fillChar)
1353 if kwargs
.has_key('fillChar') and len(self
._choices
) > 0:
1354 if kwargs
['fillChar'] != ' ':
1355 self
._choices
= [choice
.replace(' ', self
._fillChar
) for choice
in self
._choices
]
1357 self
._choices
= [choice
.replace(self
._old
_fillChar
, self
._fillChar
) for choice
in self
._choices
]
1358 dbg('updated choices:', self
._choices
)
1361 if kwargs
.has_key('autoSelect') and kwargs
['autoSelect']:
1362 if not self
._hasList
:
1363 dbg('no list to auto complete; ignoring "autoSelect=True"')
1364 self
._autoSelect
= False
1366 # reset field validity assumption:
1368 dbg(indent
=0, suspend
=0)
1371 def _GetParameter(self
, paramname
):
1373 Routine for retrieving the value of any given parameter
1375 if Field
.valid_params
.has_key(paramname
):
1376 return getattr(self
, '_' + paramname
)
1378 TypeError('Field._GetParameter: invalid parameter "%s"' % key
)
1381 def IsEmpty(self
, slice):
1383 Indicates whether the specified slice is considered empty for the
1386 dbg('Field::IsEmpty("%s")' % slice, indent
=1)
1387 if not hasattr(self
, '_template'):
1389 raise AttributeError('_template')
1391 dbg('self._template: "%s"' % self
._template
)
1392 dbg('self._defaultValue: "%s"' % str(self
._defaultValue
))
1393 if slice == self
._template
and not self
._defaultValue
:
1397 elif slice == self
._template
:
1399 for pos
in range(len(self
._template
)):
1400 ## dbg('slice[%(pos)d] != self._fillChar?' %locals(), slice[pos] != self._fillChar[pos])
1401 if slice[pos
] not in (' ', self
._fillChar
):
1404 dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals(), indent
=0)
1407 dbg("IsEmpty? 0 (slice doesn't match template)", indent
=0)
1411 def IsValid(self
, slice):
1413 Indicates whether the specified slice is considered a valid value for the
1417 dbg('Field[%s]::IsValid("%s")' % (str(self
._index
), slice), indent
=1)
1418 valid
= True # assume true to start
1420 if self
.IsEmpty(slice):
1421 dbg(indent
=0, suspend
=0)
1422 if self
._emptyInvalid
:
1427 elif self
._hasList
and self
._choiceRequired
:
1428 dbg("(member of list required)")
1429 # do case-insensitive match on list; strip surrounding whitespace from slice (already done for choices):
1430 if self
._fillChar
!= ' ':
1431 slice = slice.replace(self
._fillChar
, ' ')
1432 dbg('updated slice:"%s"' % slice)
1433 compareStr
= slice.strip()
1435 if self
._compareNoCase
:
1436 compareStr
= compareStr
.lower()
1437 valid
= compareStr
in self
._compareChoices
1439 elif self
._hasRange
and not self
.IsEmpty(slice):
1440 dbg('validating against range')
1442 # allow float as well as int ranges (int comparisons for free.)
1443 valid
= self
._rangeLow
<= float(slice) <= self
._rangeHigh
1447 elif self
._validRegex
and self
._filter
:
1448 dbg('validating against regex')
1449 valid
= (re
.match( self
._filter
, slice) is not None)
1451 if valid
and self
._validFunc
:
1452 dbg('validating against supplied function')
1453 valid
= self
._validFunc
(slice)
1454 dbg('valid?', valid
, indent
=0, suspend
=0)
1458 def _AdjustField(self
, slice):
1459 """ 'Fixes' an integer field. Right or left-justifies, as required."""
1460 dbg('Field::_AdjustField("%s")' % slice, indent
=1)
1461 length
= len(self
._mask
)
1462 ## dbg('length(self._mask):', length)
1463 ## dbg('self._useParensForNegatives?', self._useParensForNegatives)
1465 if self
._useParensForNegatives
:
1466 signpos
= slice.find('(')
1467 right_signpos
= slice.find(')')
1468 intStr
= slice.replace('(', '').replace(')', '') # drop sign, if any
1470 signpos
= slice.find('-')
1471 intStr
= slice.replace( '-', '' ) # drop sign, if any
1474 intStr
= intStr
.replace(' ', '') # drop extra spaces
1475 intStr
= string
.replace(intStr
,self
._fillChar
,"") # drop extra fillchars
1476 intStr
= string
.replace(intStr
,"-","") # drop sign, if any
1477 intStr
= string
.replace(intStr
, self
._groupChar
, "") # lose commas/dots
1478 ## dbg('intStr:"%s"' % intStr)
1479 start
, end
= self
._extent
1480 field_len
= end
- start
1481 if not self
._padZero
and len(intStr
) != field_len
and intStr
.strip():
1482 intStr
= str(long(intStr
))
1483 ## dbg('raw int str: "%s"' % intStr)
1484 ## dbg('self._groupdigits:', self._groupdigits, 'self._formatcodes:', self._formatcodes)
1485 if self
._groupdigits
:
1488 for i
in range(len(intStr
)-1, -1, -1):
1489 new
= intStr
[i
] + new
1491 new
= self
._groupChar
+ new
1493 if new
and new
[0] == self
._groupChar
:
1495 if len(new
) <= length
:
1496 # expanded string will still fit and leave room for sign:
1498 # else... leave it without the commas...
1500 dbg('padzero?', self
._padZero
)
1501 dbg('len(intStr):', len(intStr
), 'field length:', length
)
1502 if self
._padZero
and len(intStr
) < length
:
1503 intStr
= '0' * (length
- len(intStr
)) + intStr
1504 if signpos
!= -1: # we had a sign before; restore it
1505 if self
._useParensForNegatives
:
1506 intStr
= '(' + intStr
[1:]
1507 if right_signpos
!= -1:
1510 intStr
= '-' + intStr
[1:]
1511 elif signpos
!= -1 and slice[0:signpos
].strip() == '': # - was before digits
1512 if self
._useParensForNegatives
:
1513 intStr
= '(' + intStr
1514 if right_signpos
!= -1:
1517 intStr
= '-' + intStr
1518 elif right_signpos
!= -1:
1519 # must have had ')' but '(' was before field; re-add ')'
1523 slice = slice.strip() # drop extra spaces
1525 if self
._alignRight
: ## Only if right-alignment is enabled
1526 slice = slice.rjust( length
)
1528 slice = slice.ljust( length
)
1529 if self
._fillChar
!= ' ':
1530 slice = slice.replace(' ', self
._fillChar
)
1531 dbg('adjusted slice: "%s"' % slice, indent
=0)
1535 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
1537 class MaskedEditMixin
:
1539 This class allows us to abstract the masked edit functionality that could
1540 be associated with any text entry control. (eg. wxTextCtrl, wxComboBox, etc.)
1542 valid_ctrl_params
= {
1543 'mask': 'XXXXXXXXXXXXX', ## mask string for formatting this control
1544 'autoformat': "", ## optional auto-format code to set format from masktags dictionary
1545 'fields': {}, ## optional list/dictionary of maskededit.Field class instances, indexed by position in mask
1546 'datestyle': 'MDY', ## optional date style for date-type values. Can trigger autocomplete year
1547 'autoCompleteKeycodes': [], ## Optional list of additional keycodes which will invoke field-auto-complete
1548 'useFixedWidthFont': True, ## Use fixed-width font instead of default for base control
1549 'retainFieldValidation': False, ## Set this to true if setting control-level parameters independently,
1550 ## from field validation constraints
1551 'emptyBackgroundColour': "White",
1552 'validBackgroundColour': "White",
1553 'invalidBackgroundColour': "Yellow",
1554 'foregroundColour': "Black",
1555 'signedForegroundColour': "Red",
1559 def __init__(self
, name
= 'wxMaskedEdit', **kwargs
):
1561 This is the "constructor" for setting up the mixin variable parameters for the composite class.
1566 # set up flag for doing optional things to base control if possible
1567 if not hasattr(self
, 'controlInitialized'):
1568 self
.controlInitialized
= False
1570 # Set internal state var for keeping track of whether or not a character
1571 # action results in a modification of the control, since .SetValue()
1572 # doesn't modify the base control's internal state:
1573 self
.modified
= False
1574 self
._previous
_mask
= None
1576 # Validate legitimate set of parameters:
1577 for key
in kwargs
.keys():
1578 if key
.replace('Color', 'Colour') not in MaskedEditMixin
.valid_ctrl_params
.keys() + Field
.valid_params
.keys():
1579 raise TypeError('%s: invalid parameter "%s"' % (name
, key
))
1581 ## Set up dictionary that can be used by subclasses to override or add to default
1582 ## behavior for individual characters. Derived subclasses needing to change
1583 ## default behavior for keys can either redefine the default functions for the
1584 ## common keys or add functions for specific keys to this list. Each function
1585 ## added should take the key event as argument, and return False if the key
1586 ## requires no further processing.
1588 ## Initially populated with navigation and function control keys:
1589 self
._keyhandlers
= {
1590 # default navigation keys and handlers:
1591 wx
.WXK_BACK
: self
._OnErase
,
1592 wx
.WXK_LEFT
: self
._OnArrow
,
1593 wx
.WXK_RIGHT
: self
._OnArrow
,
1594 wx
.WXK_UP
: self
._OnAutoCompleteField
,
1595 wx
.WXK_DOWN
: self
._OnAutoCompleteField
,
1596 wx
.WXK_TAB
: self
._OnChangeField
,
1597 wx
.WXK_HOME
: self
._OnHome
,
1598 wx
.WXK_END
: self
._OnEnd
,
1599 wx
.WXK_RETURN
: self
._OnReturn
,
1600 wx
.WXK_PRIOR
: self
._OnAutoCompleteField
,
1601 wx
.WXK_NEXT
: self
._OnAutoCompleteField
,
1603 # default function control keys and handlers:
1604 wx
.WXK_DELETE
: self
._OnErase
,
1605 WXK_CTRL_A
: self
._OnCtrl
_A
,
1606 WXK_CTRL_C
: self
._OnCtrl
_C
,
1607 WXK_CTRL_S
: self
._OnCtrl
_S
,
1608 WXK_CTRL_V
: self
._OnCtrl
_V
,
1609 WXK_CTRL_X
: self
._OnCtrl
_X
,
1610 WXK_CTRL_Z
: self
._OnCtrl
_Z
,
1613 ## bind standard navigational and control keycodes to this instance,
1614 ## so that they can be augmented and/or changed in derived classes:
1615 self
._nav
= list(nav
)
1616 self
._control
= list(control
)
1618 ## Dynamically evaluate and store string constants for mask chars
1619 ## so that locale settings can be made after this module is imported
1620 ## and the controls created after that is done can allow the
1621 ## appropriate characters:
1622 self
.maskchardict
= {
1624 'A': string
.uppercase
,
1625 'a': string
.lowercase
,
1626 'X': string
.letters
+ string
.punctuation
+ string
.digits
,
1627 'C': string
.letters
,
1628 'N': string
.letters
+ string
.digits
,
1629 '&': string
.punctuation
1632 ## self._ignoreChange is used by MaskedComboBox, because
1633 ## of the hack necessary to determine the selection; it causes
1634 ## EVT_TEXT messages from the combobox to be ignored if set.
1635 self
._ignoreChange
= False
1637 # These are used to keep track of previous value, for undo functionality:
1638 self
._curValue
= None
1639 self
._prevValue
= None
1643 # Set defaults for each parameter for this instance, and fully
1644 # populate initial parameter list for configuration:
1645 for key
, value
in MaskedEditMixin
.valid_ctrl_params
.items():
1646 setattr(self
, '_' + key
, copy
.copy(value
))
1647 if not kwargs
.has_key(key
):
1648 ## dbg('%s: "%s"' % (key, repr(value)))
1649 kwargs
[key
] = copy
.copy(value
)
1651 # Create a "field" that holds global parameters for control constraints
1652 self
._ctrl
_constraints
= self
._fields
[-1] = Field(index
=-1)
1653 self
.SetCtrlParameters(**kwargs
)
1657 def SetCtrlParameters(self
, **kwargs
):
1659 This public function can be used to set individual or multiple masked edit
1660 parameters after construction.
1663 dbg('MaskedEditMixin::SetCtrlParameters', indent
=1)
1664 ## dbg('kwargs:', indent=1)
1665 ## for key, value in kwargs.items():
1666 ## dbg(key, '=', value)
1669 # Validate keyword arguments:
1670 constraint_kwargs
= {}
1672 for key
, value
in kwargs
.items():
1673 key
= key
.replace('Color', 'Colour') # for b-c, and standard wxPython spelling
1674 if key
not in MaskedEditMixin
.valid_ctrl_params
.keys() + Field
.valid_params
.keys():
1675 dbg(indent
=0, suspend
=0)
1676 raise TypeError('Invalid keyword argument "%s" for control "%s"' % (key
, self
.name
))
1677 elif key
in Field
.valid_params
.keys():
1678 constraint_kwargs
[key
] = value
1680 ctrl_kwargs
[key
] = value
1685 if ctrl_kwargs
.has_key('autoformat'):
1686 autoformat
= ctrl_kwargs
['autoformat']
1690 if autoformat
!= self
._autoformat
and autoformat
in masktags
.keys():
1691 dbg('autoformat:', autoformat
)
1692 self
._autoformat
= autoformat
1693 mask
= masktags
[self
._autoformat
]['mask']
1694 # gather rest of any autoformat parameters:
1695 for param
, value
in masktags
[self
._autoformat
].items():
1696 if param
== 'mask': continue # (must be present; already accounted for)
1697 constraint_kwargs
[param
] = value
1699 elif autoformat
and not autoformat
in masktags
.keys():
1700 raise AttributeError('invalid value for autoformat parameter: %s' % repr(autoformat
))
1702 dbg('autoformat not selected')
1703 if kwargs
.has_key('mask'):
1704 mask
= kwargs
['mask']
1707 ## Assign style flags
1709 dbg('preserving previous mask')
1710 mask
= self
._previous
_mask
# preserve previous mask
1713 reset_args
['reset_mask'] = mask
1714 constraint_kwargs
['mask'] = mask
1716 # wipe out previous fields; preserve new control-level constraints
1717 self
._fields
= {-1: self._ctrl_constraints}
1720 if ctrl_kwargs
.has_key('fields'):
1721 # do field parameter type validation, and conversion to internal dictionary
1723 fields
= ctrl_kwargs
['fields']
1724 if type(fields
) in (types
.ListType
, types
.TupleType
):
1725 for i
in range(len(fields
)):
1727 if not isinstance(field
, Field
):
1728 dbg(indent
=0, suspend
=0)
1729 raise AttributeError('invalid type for field parameter: %s' % repr(field
))
1730 self
._fields
[i
] = field
1732 elif type(fields
) == types
.DictionaryType
:
1733 for index
, field
in fields
.items():
1734 if not isinstance(field
, Field
):
1735 dbg(indent
=0, suspend
=0)
1736 raise AttributeError('invalid type for field parameter: %s' % repr(field
))
1737 self
._fields
[index
] = field
1739 dbg(indent
=0, suspend
=0)
1740 raise AttributeError('fields parameter must be a list or dictionary; not %s' % repr(fields
))
1742 # Assign constraint parameters for entire control:
1743 ## dbg('control constraints:', indent=1)
1744 ## for key, value in constraint_kwargs.items():
1745 ## dbg('%s:' % key, value)
1748 # determine if changing parameters that should affect the entire control:
1749 for key
in MaskedEditMixin
.valid_ctrl_params
.keys():
1750 if key
in ( 'mask', 'fields' ): continue # (processed separately)
1751 if ctrl_kwargs
.has_key(key
):
1752 setattr(self
, '_' + key
, ctrl_kwargs
[key
])
1754 # Validate color parameters, converting strings to named colors and validating
1755 # result if appropriate:
1756 for key
in ('emptyBackgroundColour', 'invalidBackgroundColour', 'validBackgroundColour',
1757 'foregroundColour', 'signedForegroundColour'):
1758 if ctrl_kwargs
.has_key(key
):
1759 if type(ctrl_kwargs
[key
]) in (types
.StringType
, types
.UnicodeType
):
1760 c
= wx
.NamedColour(ctrl_kwargs
[key
])
1761 if c
.Get() == (-1, -1, -1):
1762 raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs
[key
]), key
))
1764 # replace attribute with wxColour object:
1765 setattr(self
, '_' + key
, c
)
1766 # attach a python dynamic attribute to wxColour for debug printouts
1767 c
._name
= ctrl_kwargs
[key
]
1769 elif type(ctrl_kwargs
[key
]) != type(wx
.BLACK
):
1770 raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs
[key
]), key
))
1773 dbg('self._retainFieldValidation:', self
._retainFieldValidation
)
1774 if not self
._retainFieldValidation
:
1775 # Build dictionary of any changing parameters which should be propagated to the
1777 for arg
in Field
.propagating_params
:
1778 ## dbg('kwargs.has_key(%s)?' % arg, kwargs.has_key(arg))
1779 ## dbg('getattr(self._ctrl_constraints, _%s)?' % arg, getattr(self._ctrl_constraints, '_'+arg))
1780 reset_args
[arg
] = kwargs
.has_key(arg
) and kwargs
[arg
] != getattr(self
._ctrl
_constraints
, '_'+arg
)
1781 ## dbg('reset_args[%s]?' % arg, reset_args[arg])
1783 # Set the control-level constraints:
1784 self
._ctrl
_constraints
._SetParameters
(**constraint_kwargs
)
1786 # This routine does the bulk of the interdependent parameter processing, determining
1787 # the field extents of the mask if changed, resetting parameters as appropriate,
1788 # determining the overall template value for the control, etc.
1789 self
._configure
(mask
, **reset_args
)
1791 # now that we've propagated the field constraints and mask portions to the
1792 # various fields, validate the constraints
1793 self
._ctrl
_constraints
._ValidateParameters
(**constraint_kwargs
)
1795 # Validate that all choices for given fields are at least of the
1796 # necessary length, and that they all would be valid pastes if pasted
1797 # into their respective fields:
1798 ## dbg('validating choices')
1799 self
._validateChoices
()
1802 self
._autofit
= self
._ctrl
_constraints
._autofit
1805 self
._isDate
= 'D' in self
._ctrl
_constraints
._formatcodes
and isDateType(mask
)
1806 self
._isTime
= 'T' in self
._ctrl
_constraints
._formatcodes
and isTimeType(mask
)
1808 # Set _dateExtent, used in date validation to locate date in string;
1809 # always set as though year will be 4 digits, even if mask only has
1810 # 2 digits, so we can always properly process the intended year for
1811 # date validation (leap years, etc.)
1812 if self
._mask
.find('CCC') != -1: self
._dateExtent
= 11
1813 else: self
._dateExtent
= 10
1815 self
._4digityear
= len(self
._mask
) > 8 and self
._mask
[9] == '#'
1817 if self
._isDate
and self
._autoformat
:
1818 # Auto-decide datestyle:
1819 if self
._autoformat
.find('MDDY') != -1: self
._datestyle
= 'MDY'
1820 elif self
._autoformat
.find('YMMD') != -1: self
._datestyle
= 'YMD'
1821 elif self
._autoformat
.find('YMMMD') != -1: self
._datestyle
= 'YMD'
1822 elif self
._autoformat
.find('DMMY') != -1: self
._datestyle
= 'DMY'
1823 elif self
._autoformat
.find('DMMMY') != -1: self
._datestyle
= 'DMY'
1826 if self
.controlInitialized
:
1827 # Then the base control is available for configuration;
1828 # take action on base control based on new settings, as appropriate.
1829 if kwargs
.has_key('useFixedWidthFont'):
1830 # Set control font - fixed width by default
1833 if reset_args
.has_key('reset_mask'):
1835 curvalue
= self
._GetValue
()
1836 if curvalue
.strip():
1838 dbg('attempting to _SetInitialValue(%s)' % self
._GetValue
())
1839 self
._SetInitialValue
(self
._GetValue
())
1840 except Exception, e
:
1841 dbg('exception caught:', e
)
1842 dbg("current value doesn't work; attempting to reset to template")
1843 self
._SetInitialValue
()
1845 dbg('attempting to _SetInitialValue() with template')
1846 self
._SetInitialValue
()
1848 elif kwargs
.has_key('useParensForNegatives'):
1849 newvalue
= self
._getSignedValue
()[0]
1851 if newvalue
is not None:
1852 # Adjust for new mask:
1853 if len(newvalue
) < len(self
._mask
):
1855 elif len(newvalue
) > len(self
._mask
):
1856 if newvalue
[-1] in (' ', ')'):
1857 newvalue
= newvalue
[:-1]
1859 dbg('reconfiguring value for parens:"%s"' % newvalue
)
1860 self
._SetValue
(newvalue
)
1862 if self
._prevValue
!= newvalue
:
1863 self
._prevValue
= newvalue
# disallow undo of sign type
1866 dbg('setting client size to:', self
._CalcSize
())
1867 self
.SetClientSize(self
._CalcSize
())
1869 # Set value/type-specific formatting
1870 self
._applyFormatting
()
1871 dbg(indent
=0, suspend
=0)
1873 def SetMaskParameters(self
, **kwargs
):
1874 """ old name for this function """
1875 return self
.SetCtrlParameters(**kwargs
)
1878 def GetCtrlParameter(self
, paramname
):
1880 Routine for retrieving the value of any given parameter
1882 if MaskedEditMixin
.valid_ctrl_params
.has_key(paramname
.replace('Color','Colour')):
1883 return getattr(self
, '_' + paramname
.replace('Color', 'Colour'))
1884 elif Field
.valid_params
.has_key(paramname
):
1885 return self
._ctrl
_constraints
._GetParameter
(paramname
)
1887 TypeError('"%s".GetCtrlParameter: invalid parameter "%s"' % (self
.name
, paramname
))
1889 def GetMaskParameter(self
, paramname
):
1890 """ old name for this function """
1891 return self
.GetCtrlParameter(paramname
)
1894 # ## TRICKY BIT: to avoid a ton of boiler-plate, and to
1895 # ## automate the getter/setter generation for each valid
1896 # ## control parameter so we never forget to add the
1897 # ## functions when adding parameters, this loop
1898 # ## programmatically adds them to the class:
1899 # ## (This makes it easier for Designers like Boa to
1900 # ## deal with masked controls.)
1902 for param
in valid_ctrl_params
.keys() + Field
.valid_params
.keys():
1903 propname
= param
[0].upper() + param
[1:]
1904 exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname
, param
))
1905 exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
1906 if param.find('Colour
') != -1:
1907 # add non-british spellings, for backward-compatibility
1908 propname.replace('Colour
', 'Color
')
1909 exec('def Set
%s(self
, value
): self
.SetCtrlParameters(%s=value
)' % (propname, param))
1910 exec('def Get
%s(self
): return self
.GetCtrlParameter("%s")''' % (propname, param))
1913 def SetFieldParameters(self, field_index, **kwargs):
1915 Routine provided to modify the parameters of a given field.
1916 Because changes to fields can affect the overall control,
1917 direct access to the fields is prevented, and the control
1918 is always "reconfigured" after setting a field parameter.
1920 if field_index not in self._field_indices:
1921 raise IndexError('%s is not a valid field for control "%s".' % (str(field_index), self.name))
1922 # set parameters as requested:
1923 self._fields[field_index]._SetParameters(**kwargs)
1925 # Possibly reprogram control template due to resulting changes, and ensure
1926 # control-level params are still propagated to fields:
1927 self._configure(self._previous_mask)
1928 self._fields[field_index]._ValidateParameters(**kwargs)
1930 if self.controlInitialized:
1931 if kwargs.has_key('fillChar') or kwargs.has_key('defaultValue'):
1932 self._SetInitialValue()
1935 self.SetClientSize(self._CalcSize())
1937 # Set value/type-specific formatting
1938 self._applyFormatting()
1941 def GetFieldParameter(self, field_index, paramname):
1943 Routine provided for getting a parameter of an individual field.
1945 if field_index not in self._field_indices:
1946 raise IndexError('%s is not a valid field for control "%s".' % (str(field_index), self.name))
1947 elif Field.valid_params.has_key(paramname):
1948 return self._fields[field_index]._GetParameter(paramname)
1950 TypeError('"%s".GetFieldParameter: invalid parameter "%s"' % (self.name, paramname))
1953 def _SetKeycodeHandler(self, keycode, func):
1955 This function adds and/or replaces key event handling functions
1956 used by the control. <func> should take the event as argument
1957 and return False if no further action on the key is necessary.
1959 self._keyhandlers[keycode] = func
1962 def _SetKeyHandler(self, char, func):
1964 This function adds and/or replaces key event handling functions
1965 for ascii characters. <func> should take the event as argument
1966 and return False if no further action on the key is necessary.
1968 self._SetKeycodeHandler(ord(char), func)
1971 def _AddNavKeycode(self, keycode, handler=None):
1973 This function allows a derived subclass to augment the list of
1974 keycodes that are considered "navigational" keys.
1976 self._nav.append(keycode)
1978 self._keyhandlers[keycode] = handler
1981 def _AddNavKey(self, char, handler=None):
1983 This function is a convenience function so you don't have to
1984 remember to call ord() for ascii chars to be used for navigation.
1986 self._AddNavKeycode(ord(char), handler)
1989 def _GetNavKeycodes(self):
1991 This function retrieves the current list of navigational keycodes for
1997 def _SetNavKeycodes(self, keycode_func_tuples):
1999 This function allows you to replace the current list of keycode processed
2000 as navigation keys, and bind associated optional keyhandlers.
2003 for keycode, func in keycode_func_tuples:
2004 self._nav.append(keycode)
2006 self._keyhandlers[keycode] = func
2009 def _processMask(self, mask):
2011 This subroutine expands {n} syntax in mask strings, and looks for escaped
2012 special characters and returns the expanded mask, and an dictionary
2013 of booleans indicating whether or not a given position in the mask is
2014 a mask character or not.
2016 dbg('_processMask: mask', mask, indent=1)
2017 # regular expression for parsing c{n} syntax:
2018 rex = re.compile('([' +string.join(maskchars,"") + '])\{(\d+)\}')
2020 match = rex.search(s)
2021 while match: # found an(other) occurrence
2022 maskchr = s[match.start(1):match.end(1)] # char to be repeated
2023 repcount = int(s[match.start(2):match.end(2)]) # the number of times
2024 replacement = string.join( maskchr * repcount, "") # the resulting substr
2025 s = s[:match.start(1)] + replacement + s[match.end(2)+1:] #account for trailing '}'
2026 match = rex.search(s) # look for another such entry in mask
2028 self._decimalChar = self._ctrl_constraints._decimalChar
2029 self._shiftDecimalChar = self._ctrl_constraints._shiftDecimalChar
2031 self._isFloat = isFloatingPoint(s) and not self._ctrl_constraints._validRegex
2032 self._isInt = isInteger(s) and not self._ctrl_constraints._validRegex
2033 self._signOk = '-' in self._ctrl_constraints._formatcodes and (self._isFloat or self._isInt)
2034 self._useParens = self._ctrl_constraints._useParensForNegatives
2036 ## dbg('self._signOk?', self._signOk, 'self._useParens?', self._useParens)
2037 ## dbg('isFloatingPoint(%s)?' % (s), isFloatingPoint(s),
2038 ## 'ctrl regex:', self._ctrl_constraints._validRegex)
2040 if self._signOk and s[0] != ' ':
2042 if self._ctrl_constraints._defaultValue and self._ctrl_constraints._defaultValue[0] != ' ':
2043 self._ctrl_constraints._defaultValue = ' ' + self._ctrl_constraints._defaultValue
2048 self._ctrl_constraints._defaultValue += ' '
2050 # Now, go build up a dictionary of booleans, indexed by position,
2051 # indicating whether or not a given position is masked or not
2055 if s[i] == '\\': # if escaped character:
2056 ismasked[i] = False # mark position as not a mask char
2057 if i+1 < len(s): # if another char follows...
2058 s = s[:i] + s[i+1:] # elide the '\'
2059 if i+2 < len(s) and s[i+1] == '\\':
2060 # if next char also a '\', char is a literal '\'
2061 s = s[:i] + s[i+1:] # elide the 2nd '\' as well
2062 else: # else if special char, mark position accordingly
2063 ismasked[i] = s[i] in maskchars
2064 ## dbg('ismasked[%d]:' % i, ismasked[i], s)
2065 i += 1 # increment to next char
2066 ## dbg('ismasked:', ismasked)
2067 dbg('new mask: "%s"' % s, indent=0)
2072 def _calcFieldExtents(self):
2074 Subroutine responsible for establishing/configuring field instances with
2075 indices and editable extents appropriate to the specified mask, and building
2076 the lookup table mapping each position to the corresponding field.
2078 self._lookupField = {}
2081 ## Create dictionary of positions,characters in mask
2083 for charnum in range( len( self._mask)):
2084 self.maskdict[charnum] = self._mask[charnum:charnum+1]
2086 # For the current mask, create an ordered list of field extents
2087 # and a dictionary of positions that map to field indices:
2089 if self._signOk: start = 1
2093 # Skip field "discovery", and just construct a 2-field control with appropriate
2094 # constraints for a floating-point entry.
2096 # .setdefault always constructs 2nd argument even if not needed, so we do this
2097 # the old-fashioned way...
2098 if not self._fields.has_key(0):
2099 self._fields[0] = Field()
2100 if not self._fields.has_key(1):
2101 self._fields[1] = Field()
2103 self._decimalpos = string.find( self._mask, '.')
2104 dbg('decimal pos =', self._decimalpos)
2106 formatcodes = self._fields[0]._GetParameter('formatcodes')
2107 if 'R' not in formatcodes: formatcodes += 'R'
2108 self._fields[0]._SetParameters(index=0, extent=(start, self._decimalpos),
2109 mask=self._mask[start:self._decimalpos], formatcodes=formatcodes)
2110 end = len(self._mask)
2111 if self._signOk and self._useParens:
2113 self._fields[1]._SetParameters(index=1, extent=(self._decimalpos+1, end),
2114 mask=self._mask[self._decimalpos+1:end])
2116 for i in range(self._decimalpos+1):
2117 self._lookupField[i] = 0
2119 for i in range(self._decimalpos+1, len(self._mask)+1):
2120 self._lookupField[i] = 1
2123 # Skip field "discovery", and just construct a 1-field control with appropriate
2124 # constraints for a integer entry.
2125 if not self._fields.has_key(0):
2126 self._fields[0] = Field(index=0)
2127 end = len(self._mask)
2128 if self._signOk and self._useParens:
2130 self._fields[0]._SetParameters(index=0, extent=(start, end),
2131 mask=self._mask[start:end])
2132 for i in range(len(self._mask)+1):
2133 self._lookupField[i] = 0
2135 # generic control; parse mask to figure out where the fields are:
2138 i = self._findNextEntry(pos,adjustInsert=False) # go to 1st entry point:
2139 if i < len(self._mask): # no editable chars!
2140 for j in range(pos, i+1):
2141 self._lookupField[j] = field_index
2142 pos = i # figure out field for 1st editable space:
2144 while i <= len(self._mask):
2145 ## dbg('searching: outer field loop: i = ', i)
2146 if self._isMaskChar(i):
2147 ## dbg('1st char is mask char; recording edit_start=', i)
2149 # Skip to end of editable part of current field:
2150 while i < len(self._mask) and self._isMaskChar(i):
2151 self._lookupField[i] = field_index
2153 ## dbg('edit_end =', i)
2155 self._lookupField[i] = field_index
2156 ## dbg('self._fields.has_key(%d)?' % field_index, self._fields.has_key(field_index))
2157 if not self._fields.has_key(field_index):
2158 kwargs = Field.valid_params.copy()
2159 kwargs['index'] = field_index
2160 kwargs['extent'] = (edit_start, edit_end)
2161 kwargs['mask'] = self._mask[edit_start:edit_end]
2162 self._fields[field_index] = Field(**kwargs)
2164 self._fields[field_index]._SetParameters(
2166 extent=(edit_start, edit_end),
2167 mask=self._mask[edit_start:edit_end])
2169 i = self._findNextEntry(pos, adjustInsert=False) # go to next field:
2171 for j in range(pos, i+1):
2172 self._lookupField[j] = field_index
2173 if i >= len(self._mask):
2174 break # if past end, we're done
2177 ## dbg('next field:', field_index)
2179 indices = self._fields.keys()
2181 self._field_indices = indices[1:]
2182 ## dbg('lookupField map:', indent=1)
2183 ## for i in range(len(self._mask)):
2184 ## dbg('pos %d:' % i, self._lookupField[i])
2187 # Verify that all field indices specified are valid for mask:
2188 for index in self._fields.keys():
2189 if index not in [-1] + self._lookupField.values():
2190 raise IndexError('field %d is not a valid field for mask "%s"' % (index, self._mask))
2193 def _calcTemplate(self, reset_fillchar, reset_default):
2195 Subroutine for processing current fillchars and default values for
2196 whole control and individual fields, constructing the resulting
2197 overall template, and adjusting the current value as necessary.
2200 if self._ctrl_constraints._defaultValue:
2203 for field in self._fields.values():
2204 if field._defaultValue and not reset_default:
2206 dbg('default set?', default_set)
2208 # Determine overall new template for control, and keep track of previous
2209 # values, so that current control value can be modified as appropriate:
2210 if self.controlInitialized: curvalue = list(self._GetValue())
2211 else: curvalue = None
2213 if hasattr(self, '_fillChar'): old_fillchars = self._fillChar
2214 else: old_fillchars = None
2216 if hasattr(self, '_template'): old_template = self._template
2217 else: old_template = None
2224 for field in self._fields.values():
2225 field._template = ""
2227 for pos in range(len(self._mask)):
2229 field = self._FindField(pos)
2230 ## dbg('field:', field._index)
2231 start, end = field._extent
2233 if pos == 0 and self._signOk:
2234 self._template = ' ' # always make 1st 1st position blank, regardless of fillchar
2235 elif self._isFloat and pos == self._decimalpos:
2236 self._template += self._decimalChar
2237 elif self._isMaskChar(pos):
2238 if field._fillChar != self._ctrl_constraints._fillChar and not reset_fillchar:
2239 fillChar = field._fillChar
2241 fillChar = self._ctrl_constraints._fillChar
2242 self._fillChar[pos] = fillChar
2244 # Replace any current old fillchar with new one in current value;
2245 # if action required, set reset_value flag so we can take that action
2246 # after we're all done
2247 if self.controlInitialized and old_fillchars and old_fillchars.has_key(pos) and curvalue:
2248 if curvalue[pos] == old_fillchars[pos] and old_fillchars[pos] != fillChar:
2250 curvalue[pos] = fillChar
2252 if not field._defaultValue and not self._ctrl_constraints._defaultValue:
2253 ## dbg('no default value')
2254 self._template += fillChar
2255 field._template += fillChar
2257 elif field._defaultValue and not reset_default:
2258 ## dbg('len(field._defaultValue):', len(field._defaultValue))
2259 ## dbg('pos-start:', pos-start)
2260 if len(field._defaultValue) > pos-start:
2261 ## dbg('field._defaultValue[pos-start]: "%s"' % field._defaultValue[pos-start])
2262 self._template += field._defaultValue[pos-start]
2263 field._template += field._defaultValue[pos-start]
2265 ## dbg('field default not long enough; using fillChar')
2266 self._template += fillChar
2267 field._template += fillChar
2269 if len(self._ctrl_constraints._defaultValue) > pos:
2270 ## dbg('using control default')
2271 self._template += self._ctrl_constraints._defaultValue[pos]
2272 field._template += self._ctrl_constraints._defaultValue[pos]
2274 ## dbg('ctrl default not long enough; using fillChar')
2275 self._template += fillChar
2276 field._template += fillChar
2277 ## dbg('field[%d]._template now "%s"' % (field._index, field._template))
2278 ## dbg('self._template now "%s"' % self._template)
2280 self._template += self._mask[pos]
2282 self._fields[-1]._template = self._template # (for consistency)
2284 if curvalue: # had an old value, put new one back together
2285 newvalue = string.join(curvalue, "")
2290 self._defaultValue = self._template
2291 dbg('self._defaultValue:', self._defaultValue)
2292 if not self.IsEmpty(self._defaultValue) and not self.IsValid(self._defaultValue):
2294 raise ValueError('Default value of "%s" is not a valid value for control "%s"' % (self._defaultValue, self.name))
2296 # if no fillchar change, but old value == old template, replace it:
2297 if newvalue == old_template:
2298 newvalue = self._template
2301 self._defaultValue = None
2304 dbg('resetting value to: "%s"' % newvalue)
2305 pos = self._GetInsertionPoint()
2306 sel_start, sel_to = self._GetSelection()
2307 self._SetValue(newvalue)
2308 self._SetInsertionPoint(pos)
2309 self._SetSelection(sel_start, sel_to)
2312 def _propagateConstraints(self, **reset_args):
2314 Subroutine for propagating changes to control-level constraints and
2315 formatting to the individual fields as appropriate.
2317 parent_codes = self._ctrl_constraints._formatcodes
2318 parent_includes = self._ctrl_constraints._includeChars
2319 parent_excludes = self._ctrl_constraints._excludeChars
2320 for i in self._field_indices:
2321 field = self._fields[i]
2323 if len(self._field_indices) == 1:
2324 inherit_args['formatcodes'] = parent_codes
2325 inherit_args['includeChars'] = parent_includes
2326 inherit_args['excludeChars'] = parent_excludes
2328 field_codes = current_codes = field._GetParameter('formatcodes')
2329 for c in parent_codes:
2330 if c not in field_codes: field_codes += c
2331 if field_codes != current_codes:
2332 inherit_args['formatcodes'] = field_codes
2334 include_chars = current_includes = field._GetParameter('includeChars')
2335 for c in parent_includes:
2336 if not c in include_chars: include_chars += c
2337 if include_chars != current_includes:
2338 inherit_args['includeChars'] = include_chars
2340 exclude_chars = current_excludes = field._GetParameter('excludeChars')
2341 for c in parent_excludes:
2342 if not c in exclude_chars: exclude_chars += c
2343 if exclude_chars != current_excludes:
2344 inherit_args['excludeChars'] = exclude_chars
2346 if reset_args.has_key('defaultValue') and reset_args['defaultValue']:
2347 inherit_args['defaultValue'] = "" # (reset for field)
2349 for param in Field.propagating_params:
2350 ## dbg('reset_args.has_key(%s)?' % param, reset_args.has_key(param))
2351 ## dbg('reset_args.has_key(%(param)s) and reset_args[%(param)s]?' % locals(), reset_args.has_key(param) and reset_args[param])
2352 if reset_args.has_key(param):
2353 inherit_args[param] = self.GetCtrlParameter(param)
2354 ## dbg('inherit_args[%s]' % param, inherit_args[param])
2357 field._SetParameters(**inherit_args)
2358 field._ValidateParameters(**inherit_args)
2361 def _validateChoices(self):
2363 Subroutine that validates that all choices for given fields are at
2364 least of the necessary length, and that they all would be valid pastes
2365 if pasted into their respective fields.
2367 for field in self._fields.values():
2369 index = field._index
2370 if len(self._field_indices) == 1 and index == 0 and field._choices == self._ctrl_constraints._choices:
2371 dbg('skipping (duplicate) choice validation of field 0')
2373 ## dbg('checking for choices for field', field._index)
2374 start, end = field._extent
2375 field_length = end - start
2376 ## dbg('start, end, length:', start, end, field_length)
2377 for choice in field._choices:
2378 ## dbg('testing "%s"' % choice)
2379 valid_paste, ignore, replace_to = self._validatePaste(choice, start, end)
2382 raise ValueError('"%s" could not be entered into field %d of control "%s"' % (choice, index, self.name))
2383 elif replace_to > end:
2385 raise ValueError('"%s" will not fit into field %d of control "%s"' (choice, index, self.name))
2386 ## dbg(choice, 'valid in field', index)
2389 def _configure(self, mask, **reset_args):
2391 This function sets flags for automatic styling options. It is
2392 called whenever a control or field-level parameter is set/changed.
2394 This routine does the bulk of the interdependent parameter processing, determining
2395 the field extents of the mask if changed, resetting parameters as appropriate,
2396 determining the overall template value for the control, etc.
2398 reset_args is supplied if called from control's .SetCtrlParameters()
2399 routine, and indicates which if any parameters which can be
2400 overridden by individual fields have been reset by request for the
2405 dbg('MaskedEditMixin::_configure("%s")' % mask, indent=1)
2407 # Preprocess specified mask to expand {n} syntax, handle escaped
2408 # mask characters, etc and build the resulting positionally keyed
2409 # dictionary for which positions are mask vs. template characters:
2410 self._mask, self.ismasked = self._processMask(mask)
2411 self._masklength = len(self._mask)
2412 ## dbg('processed mask:', self._mask)
2414 # Preserve original mask specified, for subsequent reprocessing
2415 # if parameters change.
2416 dbg('mask: "%s"' % self._mask, 'previous mask: "%s"' % self._previous_mask)
2417 self._previous_mask = mask # save unexpanded mask for next time
2418 # Set expanded mask and extent of field -1 to width of entire control:
2419 self._ctrl_constraints._SetParameters(mask = self._mask, extent=(0,self._masklength))
2421 # Go parse mask to determine where each field is, construct field
2422 # instances as necessary, configure them with those extents, and
2423 # build lookup table mapping each position for control to its corresponding
2425 ## dbg('calculating field extents')
2427 self._calcFieldExtents()
2430 # Go process defaultValues and fillchars to construct the overall
2431 # template, and adjust the current value as necessary:
2432 reset_fillchar = reset_args.has_key('fillChar') and reset_args['fillChar']
2433 reset_default = reset_args.has_key('defaultValue') and reset_args['defaultValue']
2435 ## dbg('calculating template')
2436 self._calcTemplate(reset_fillchar, reset_default)
2438 # Propagate control-level formatting and character constraints to each
2439 # field if they don't already have them; if only one field, propagate
2440 # control-level validation constraints to field as well:
2441 ## dbg('propagating constraints')
2442 self._propagateConstraints(**reset_args)
2445 if self._isFloat and self._fields[0]._groupChar == self._decimalChar:
2446 raise AttributeError('groupChar (%s) and decimalChar (%s) must be distinct.' %
2447 (self._fields[0]._groupChar, self._decimalChar) )
2449 ## dbg('fields:', indent=1)
2450 ## for i in [-1] + self._field_indices:
2451 ## dbg('field %d:' % i, self._fields[i].__dict__)
2454 # Set up special parameters for numeric control, if appropriate:
2456 self._signpos = 0 # assume it starts here, but it will move around on floats
2457 signkeys = ['-', '+', ' ']
2459 signkeys += ['(', ')']
2460 for key in signkeys:
2462 if not self._keyhandlers.has_key(keycode):
2463 self._SetKeyHandler(key, self._OnChangeSign)
2467 if self._isFloat or self._isInt:
2468 if self.controlInitialized:
2469 value = self._GetValue()
2470 ## dbg('value: "%s"' % value, 'len(value):', len(value),
2471 ## 'len(self._ctrl_constraints._mask):',len(self._ctrl_constraints._mask))
2472 if len(value) < len(self._ctrl_constraints._mask):
2474 if self._useParens and len(newvalue) < len(self._ctrl_constraints._mask) and newvalue.find('(') == -1:
2476 if self._signOk and len(newvalue) < len(self._ctrl_constraints._mask) and newvalue.find(')') == -1:
2477 newvalue = ' ' + newvalue
2478 if len(newvalue) < len(self._ctrl_constraints._mask):
2479 if self._ctrl_constraints._alignRight:
2480 newvalue = newvalue.rjust(len(self._ctrl_constraints._mask))
2482 newvalue = newvalue.ljust(len(self._ctrl_constraints._mask))
2483 dbg('old value: "%s"' % value)
2484 dbg('new value: "%s"' % newvalue)
2486 self._SetValue(newvalue)
2487 except Exception, e:
2488 dbg('exception raised:', e, 'resetting to initial value')
2489 self._SetInitialValue()
2491 elif len(value) > len(self._ctrl_constraints._mask):
2493 if not self._useParens and newvalue[-1] == ' ':
2494 newvalue = newvalue[:-1]
2495 if not self._signOk and len(newvalue) > len(self._ctrl_constraints._mask):
2496 newvalue = newvalue[1:]
2497 if not self._signOk:
2498 newvalue, signpos, right_signpos = self._getSignedValue(newvalue)
2500 dbg('old value: "%s"' % value)
2501 dbg('new value: "%s"' % newvalue)
2503 self._SetValue(newvalue)
2504 except Exception, e:
2505 dbg('exception raised:', e, 'resetting to initial value')
2506 self._SetInitialValue()
2507 elif not self._signOk and ('(' in value or '-' in value):
2508 newvalue, signpos, right_signpos = self._getSignedValue(value)
2509 dbg('old value: "%s"' % value)
2510 dbg('new value: "%s"' % newvalue)
2512 self._SetValue(newvalue)
2514 dbg('exception raised:', e, 'resetting to initial value')
2515 self._SetInitialValue()
2517 # Replace up/down arrow default handling:
2518 # make down act like tab, up act like shift-tab:
2520 ## dbg('Registering numeric navigation and control handlers (if not already set)')
2521 if not self._keyhandlers.has_key(wx.WXK_DOWN):
2522 self._SetKeycodeHandler(wx.WXK_DOWN, self._OnChangeField)
2523 if not self._keyhandlers.has_key(wx.WXK_UP):
2524 self._SetKeycodeHandler(wx.WXK_UP, self._OnUpNumeric) # (adds "shift" to up arrow, and calls _OnChangeField)
2526 # On ., truncate contents right of cursor to decimal point (if any)
2527 # leaves cusor after decimal point if floating point, otherwise at 0.
2528 if not self._keyhandlers.has_key(ord(self._decimalChar)):
2529 self._SetKeyHandler(self._decimalChar, self._OnDecimalPoint)
2530 if not self._keyhandlers.has_key(ord(self._shiftDecimalChar)):
2531 self._SetKeyHandler(self._shiftDecimalChar, self._OnChangeField) # (Shift-'.' == '>' on US keyboards)
2533 # Allow selective insert of groupchar in numbers:
2534 if not self._keyhandlers.has_key(ord(self._fields[0]._groupChar)):
2535 self._SetKeyHandler(self._fields[0]._groupChar, self._OnGroupChar)
2537 dbg(indent=0, suspend=0)
2540 def _SetInitialValue(self, value=""):
2542 fills the control with the generated or supplied default value.
2543 It will also set/reset the font if necessary and apply
2544 formatting to the control at this time.
2546 dbg('MaskedEditMixin::_SetInitialValue("%s")' % value, indent=1)
2548 self._prevValue = self._curValue = self._template
2549 # don't apply external validation rules in this case, as template may
2550 # not coincide with "legal" value...
2552 self._SetValue(self._curValue) # note the use of "raw" ._SetValue()...
2553 except Exception, e:
2554 dbg('exception thrown:', e, indent=0)
2557 # Otherwise apply validation as appropriate to passed value:
2558 ## dbg('value = "%s", length:' % value, len(value))
2559 self._prevValue = self._curValue = value
2561 self.SetValue(value) # use public (validating) .SetValue()
2562 except Exception, e:
2563 dbg('exception thrown:', e, indent=0)
2567 # Set value/type-specific formatting
2568 self._applyFormatting()
2572 def _calcSize(self, size=None):
2573 """ Calculate automatic size if allowed; must be called after the base control is instantiated"""
2574 ## dbg('MaskedEditMixin::_calcSize', indent=1)
2575 cont = (size is None or size == wx.DefaultSize)
2577 if cont and self._autofit:
2578 sizing_text = 'M' * self._masklength
2579 if wx.Platform != "__WXMSW__": # give it a little extra space
2581 if wx.Platform == "__WXMAC__": # give it even a little more...
2583 ## dbg('len(sizing_text):', len(sizing_text), 'sizing_text: "%s"' % sizing_text)
2584 w, h = self.GetTextExtent(sizing_text)
2585 size = (w+4, self.GetClientSize().height)
2586 ## dbg('size:', size, indent=0)
2591 """ Set the control's font typeface -- pass the font name as str."""
2592 ## dbg('MaskedEditMixin::_setFont', indent=1)
2593 if not self._useFixedWidthFont:
2594 self._font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
2596 font = self.GetFont() # get size, weight, etc from current font
2598 # Set to teletype font (guaranteed to be mappable to all wxWindows
2600 self._font = wx.Font( font.GetPointSize(), wx.TELETYPE, font.GetStyle(),
2601 font.GetWeight(), font.GetUnderlined())
2602 ## dbg('font string: "%s"' % font.GetNativeFontInfo().ToString())
2604 self.SetFont(self._font)
2608 def _OnTextChange(self, event):
2610 Handler for EVT_TEXT event.
2611 self._Change() is provided for subclasses, and may return False to
2612 skip this method logic. This function returns True if the event
2613 detected was a legitimate event, or False if it was a "bogus"
2614 EVT_TEXT event. (NOTE: There is currently an issue with calling
2615 .SetValue from within the EVT_CHAR handler that causes duplicate
2616 EVT_TEXT events for the same change.)
2618 newvalue = self._GetValue()
2619 dbg('MaskedEditMixin::_OnTextChange: value: "%s"' % newvalue, indent=1)
2621 if self._ignoreChange: # ie. if an "intermediate text change event"
2625 ##! WS: For some inexplicable reason, every wxTextCtrl.SetValue
2626 ## call is generating two (2) EVT_TEXT events.
2627 ## This is the only mechanism I can find to mask this problem:
2628 if newvalue == self._curValue:
2629 dbg('ignoring bogus text change event', indent=0)
2631 dbg('curvalue: "%s", newvalue: "%s"' % (self._curValue, newvalue))
2633 if self._signOk and self._isNeg and newvalue.find('-') == -1 and newvalue.find('(') == -1:
2634 dbg('clearing self._isNeg')
2636 text, self._signpos, self._right_signpos = self._getSignedValue()
2637 self._CheckValid() # Recolor control as appropriate
2638 dbg('calling event.Skip()')
2641 self._prevValue = self._curValue # save for undo
2642 self._curValue = newvalue # Save last seen value for next iteration
2647 def _OnKeyDown(self, event):
2649 This function allows the control to capture Ctrl-events like Ctrl-tab,
2650 that are not normally seen by the "cooked" EVT_CHAR routine.
2652 # Get keypress value, adjusted by control options (e.g. convert to upper etc)
2653 key = event.GetKeyCode()
2654 if key in self._nav and event.ControlDown():
2655 # then this is the only place we will likely see these events;
2657 dbg('MaskedEditMixin::OnKeyDown: calling _OnChar')
2660 # else allow regular EVT_CHAR key processing
2664 def _OnChar(self, event):
2666 This is the engine of wxMaskedEdit controls. It examines each keystroke,
2667 decides if it's allowed, where it should go or what action to take.
2669 dbg('MaskedEditMixin::_OnChar', indent=1)
2671 # Get keypress value, adjusted by control options (e.g. convert to upper etc)
2672 key = event.GetKeyCode()
2673 orig_pos = self._GetInsertionPoint()
2674 orig_value = self._GetValue()
2675 dbg('keycode = ', key)
2676 dbg('current pos = ', orig_pos)
2677 dbg('current selection = ', self._GetSelection())
2679 if not self._Keypress(key):
2683 # If no format string for this control, or the control is marked as "read-only",
2684 # skip the rest of the special processing, and just "do the standard thing:"
2685 if not self._mask or not self._IsEditable():
2690 # Process navigation and control keys first, with
2691 # position/selection unadulterated:
2692 if key in self._nav + self._control:
2693 if self._keyhandlers.has_key(key):
2694 keep_processing = self._keyhandlers[key](event)
2695 if self._GetValue() != orig_value:
2696 self.modified = True
2697 if not keep_processing:
2700 self._applyFormatting()
2704 # Else... adjust the position as necessary for next input key,
2705 # and determine resulting selection:
2706 pos = self._adjustPos( orig_pos, key ) ## get insertion position, adjusted as needed
2707 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
2708 dbg("pos, sel_start, sel_to:", pos, sel_start, sel_to)
2710 keep_processing = True
2711 # Capture user past end of format field
2712 if pos > len(self.maskdict):
2713 dbg("field length exceeded:",pos)
2714 keep_processing = False
2717 if self._isMaskChar(pos): ## Get string of allowed characters for validation
2718 okchars = self._getAllowedChars(pos)
2720 dbg('Not a valid position: pos = ', pos,"chars=",maskchars)
2723 key = self._adjustKey(pos, key) # apply formatting constraints to key:
2725 if self._keyhandlers.has_key(key):
2726 # there's an override for default behavior; use override function instead
2727 dbg('using supplied key handler:', self._keyhandlers[key])
2728 keep_processing = self._keyhandlers[key](event)
2729 if self._GetValue() != orig_value:
2730 self.modified = True
2731 if not keep_processing:
2734 # else skip default processing, but do final formatting
2735 if key < wx.WXK_SPACE or key > 255:
2736 dbg('key < WXK_SPACE or key > 255')
2737 event.Skip() # non alphanumeric
2738 keep_processing = False
2740 field = self._FindField(pos)
2741 dbg("key ='%s'" % chr(key))
2743 dbg('okSpaces?', field._okSpaces)
2747 if chr(key) in field._excludeChars + self._ctrl_constraints._excludeChars:
2748 keep_processing = False
2750 if keep_processing and self._isCharAllowed( chr(key), pos, checkRegex = True ):
2751 dbg("key allowed by mask")
2752 # insert key into candidate new value, but don't change control yet:
2753 oldstr = self._GetValue()
2754 newstr, newpos, new_select_to, match_field, match_index = self._insertKey(
2755 chr(key), pos, sel_start, sel_to, self._GetValue(), allowAutoSelect = True)
2756 dbg("str with '%s' inserted:" % chr(key), '"%s"' % newstr)
2757 if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
2758 dbg('not valid; checking to see if adjusted string is:')
2759 keep_processing = False
2760 if self._isFloat and newstr != self._template:
2761 newstr = self._adjustFloat(newstr)
2762 dbg('adjusted str:', newstr)
2763 if self.IsValid(newstr):
2765 keep_processing = True
2766 wx.CallAfter(self._SetInsertionPoint, self._decimalpos)
2767 if not keep_processing:
2768 dbg("key disallowed by validation")
2769 if not wx.Validator_IsSilent() and orig_pos == pos:
2775 # special case: adjust date value as necessary:
2776 if self._isDate and newstr != self._template:
2777 newstr = self._adjustDate(newstr)
2778 dbg('adjusted newstr:', newstr)
2780 if newstr != orig_value:
2781 self.modified = True
2783 wx.CallAfter(self._SetValue, newstr)
2785 # Adjust insertion point on date if just entered 2 digit year, and there are now 4 digits:
2786 if not self.IsDefault() and self._isDate and self._4digityear:
2787 year2dig = self._dateExtent - 2
2788 if pos == year2dig and unadjusted[year2dig] != newstr[year2dig]:
2791 wx.CallAfter(self._SetInsertionPoint, newpos)
2793 if match_field is not None:
2794 dbg('matched field')
2795 self._OnAutoSelect(match_field, match_index)
2797 if new_select_to != newpos:
2798 dbg('queuing selection: (%d, %d)' % (newpos, new_select_to))
2799 wx.CallAfter(self._SetSelection, newpos, new_select_to)
2801 newfield = self._FindField(newpos)
2802 if newfield != field and newfield._selectOnFieldEntry:
2803 dbg('queuing selection: (%d, %d)' % (newfield._extent[0], newfield._extent[1]))
2804 wx.CallAfter(self._SetSelection, newfield._extent[0], newfield._extent[1])
2805 keep_processing = False
2807 elif keep_processing:
2808 dbg('char not allowed')
2809 keep_processing = False
2810 if (not wx.Validator_IsSilent()) and orig_pos == pos:
2813 self._applyFormatting()
2815 # Move to next insertion point
2816 if keep_processing and key not in self._nav:
2817 pos = self._GetInsertionPoint()
2818 next_entry = self._findNextEntry( pos )
2819 if pos != next_entry:
2820 dbg("moving from %(pos)d to next valid entry: %(next_entry)d" % locals())
2821 wx.CallAfter(self._SetInsertionPoint, next_entry )
2823 if self._isTemplateChar(pos):
2824 self._AdjustField(pos)
2828 def _FindFieldExtent(self, pos=None, getslice=False, value=None):
2829 """ returns editable extent of field corresponding to
2830 position pos, and, optionally, the contents of that field
2831 in the control or the value specified.
2832 Template chars are bound to the preceding field.
2833 For masks beginning with template chars, these chars are ignored
2834 when calculating the current field.
2836 Eg: with template (###) ###-####,
2837 >>> self._FindFieldExtent(pos=0)
2839 >>> self._FindFieldExtent(pos=1)
2841 >>> self._FindFieldExtent(pos=5)
2843 >>> self._FindFieldExtent(pos=6)
2845 >>> self._FindFieldExtent(pos=10)
2849 dbg('MaskedEditMixin::_FindFieldExtent(pos=%s, getslice=%s)' % (
2850 str(pos), str(getslice)) ,indent=1)
2852 field = self._FindField(pos)
2855 return None, None, ""
2858 edit_start, edit_end = field._extent
2860 if value is None: value = self._GetValue()
2861 slice = value[edit_start:edit_end]
2862 dbg('edit_start:', edit_start, 'edit_end:', edit_end, 'slice: "%s"' % slice)
2864 return edit_start, edit_end, slice
2866 dbg('edit_start:', edit_start, 'edit_end:', edit_end)
2868 return edit_start, edit_end
2871 def _FindField(self, pos=None):
2873 Returns the field instance in which pos resides.
2874 Template chars are bound to the preceding field.
2875 For masks beginning with template chars, these chars are ignored
2876 when calculating the current field.
2879 ## dbg('MaskedEditMixin::_FindField(pos=%s)' % str(pos) ,indent=1)
2880 if pos is None: pos = self._GetInsertionPoint()
2881 elif pos < 0 or pos > self._masklength:
2882 raise IndexError('position %s out of range of control' % str(pos))
2884 if len(self._fields) == 0:
2890 return self._fields[self._lookupField[pos]]
2893 def ClearValue(self):
2894 """ Blanks the current control value by replacing it with the default value."""
2895 dbg("MaskedEditMixin::ClearValue - value reset to default value (template)")
2896 self._SetValue( self._template )
2897 self._SetInsertionPoint(0)
2901 def _baseCtrlEventHandler(self, event):
2903 This function is used whenever a key should be handled by the base control.
2909 def _OnUpNumeric(self, event):
2911 Makes up-arrow act like shift-tab should; ie. take you to start of
2914 dbg('MaskedEditMixin::_OnUpNumeric', indent=1)
2915 event.m_shiftDown = 1
2916 dbg('event.ShiftDown()?', event.ShiftDown())
2917 self._OnChangeField(event)
2921 def _OnArrow(self, event):
2923 Used in response to left/right navigation keys; makes these actions skip
2924 over mask template chars.
2926 dbg("MaskedEditMixin::_OnArrow", indent=1)
2927 pos = self._GetInsertionPoint()
2928 keycode = event.GetKeyCode()
2929 sel_start, sel_to = self._GetSelection()
2930 entry_end = self._goEnd(getPosOnly=True)
2931 if keycode in (wx.WXK_RIGHT, wx.WXK_DOWN):
2932 if( ( not self._isTemplateChar(pos) and pos+1 > entry_end)
2933 or ( self._isTemplateChar(pos) and pos >= entry_end) ):
2934 dbg("can't advance", indent=0)
2936 elif self._isTemplateChar(pos):
2937 self._AdjustField(pos)
2938 elif keycode in (wx.WXK_LEFT,wx.WXK_UP) and sel_start == sel_to and pos > 0 and self._isTemplateChar(pos-1):
2939 dbg('adjusting field')
2940 self._AdjustField(pos)
2942 # treat as shifted up/down arrows as tab/reverse tab:
2943 if event.ShiftDown() and keycode in (wx.WXK_UP, wx.WXK_DOWN):
2944 # remove "shifting" and treat as (forward) tab:
2945 event.m_shiftDown = False
2946 keep_processing = self._OnChangeField(event)
2948 elif self._FindField(pos)._selectOnFieldEntry:
2949 if( keycode in (wx.WXK_UP, wx.WXK_LEFT)
2951 and self._isTemplateChar(sel_start-1)
2952 and sel_start != self._masklength
2953 and not self._signOk and not self._useParens):
2955 # call _OnChangeField to handle "ctrl-shifted event"
2956 # (which moves to previous field and selects it.)
2957 event.m_shiftDown = True
2958 event.m_ControlDown = True
2959 keep_processing = self._OnChangeField(event)
2960 elif( keycode in (wx.WXK_DOWN, wx.WXK_RIGHT)
2961 and sel_to != self._masklength
2962 and self._isTemplateChar(sel_to)):
2964 # when changing field to the right, ensure don't accidentally go left instead
2965 event.m_shiftDown = False
2966 keep_processing = self._OnChangeField(event)
2968 # treat arrows as normal, allowing selection
2970 dbg('using base ctrl event processing')
2973 if( (sel_to == self._fields[0]._extent[0] and keycode == wx.WXK_LEFT)
2974 or (sel_to == self._masklength and keycode == wx.WXK_RIGHT) ):
2975 if not wx.Validator_IsSilent():
2978 # treat arrows as normal, allowing selection
2980 dbg('using base event processing')
2983 keep_processing = False
2985 return keep_processing
2988 def _OnCtrl_S(self, event):
2989 """ Default Ctrl-S handler; prints value information if demo enabled. """
2990 dbg("MaskedEditMixin::_OnCtrl_S")
2992 print 'MaskedEditMixin.GetValue() = "%s"\nMaskedEditMixin.GetPlainValue() = "%s"' % (self.GetValue(), self.GetPlainValue())
2993 print "Valid? => " + str(self.IsValid())
2994 print "Current field, start, end, value =", str( self._FindFieldExtent(getslice=True))
2998 def _OnCtrl_X(self, event=None):
2999 """ Handles ctrl-x keypress in control and Cut operation on context menu.
3000 Should return False to skip other processing. """
3001 dbg("MaskedEditMixin::_OnCtrl_X", indent=1)
3006 def _OnCtrl_C(self, event=None):
3007 """ Handles ctrl-C keypress in control and Copy operation on context menu.
3008 Uses base control handling. Should return False to skip other processing."""
3012 def _OnCtrl_V(self, event=None):
3013 """ Handles ctrl-V keypress in control and Paste operation on context menu.
3014 Should return False to skip other processing. """
3015 dbg("MaskedEditMixin::_OnCtrl_V", indent=1)
3020 def _OnCtrl_Z(self, event=None):
3021 """ Handles ctrl-Z keypress in control and Undo operation on context menu.
3022 Should return False to skip other processing. """
3023 dbg("MaskedEditMixin::_OnCtrl_Z", indent=1)
3028 def _OnCtrl_A(self,event=None):
3029 """ Handles ctrl-a keypress in control. Should return False to skip other processing. """
3030 end = self._goEnd(getPosOnly=True)
3031 if not event or event.ShiftDown():
3032 wx.CallAfter(self._SetInsertionPoint, 0)
3033 wx.CallAfter(self._SetSelection, 0, self._masklength)
3035 wx.CallAfter(self._SetInsertionPoint, 0)
3036 wx.CallAfter(self._SetSelection, 0, end)
3040 def _OnErase(self, event=None):
3041 """ Handles backspace and delete keypress in control. Should return False to skip other processing."""
3042 dbg("MaskedEditMixin::_OnErase", indent=1)
3043 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
3045 if event is None: # called as action routine from Cut() operation.
3048 key = event.GetKeyCode()
3050 field = self._FindField(sel_to)
3051 start, end = field._extent
3052 value = self._GetValue()
3053 oldstart = sel_start
3055 # If trying to erase beyond "legal" bounds, disallow operation:
3056 if( (sel_to == 0 and key == wx.WXK_BACK)
3057 or (self._signOk and sel_to == 1 and value[0] == ' ' and key == wx.WXK_BACK)
3058 or (sel_to == self._masklength and sel_start == sel_to and key == wx.WXK_DELETE and not field._insertRight)
3059 or (self._signOk and self._useParens
3060 and sel_start == sel_to
3061 and sel_to == self._masklength - 1
3062 and value[sel_to] == ' ' and key == wx.WXK_DELETE and not field._insertRight) ):
3063 if not wx.Validator_IsSilent():
3069 if( field._insertRight # an insert-right field
3070 and value[start:end] != self._template[start:end] # and field not empty
3071 and sel_start >= start # and selection starts in field
3072 and ((sel_to == sel_start # and no selection
3073 and sel_to == end # and cursor at right edge
3074 and key in (wx.WXK_BACK, wx.WXK_DELETE)) # and either delete or backspace key
3076 (key == wx.WXK_BACK # backspacing
3077 and (sel_to == end # and selection ends at right edge
3078 or sel_to < end and field._allowInsert)) ) ): # or allow right insert at any point in field
3081 # if backspace but left of cursor is empty, adjust cursor right before deleting
3082 while( key == wx.WXK_BACK
3083 and sel_start == sel_to
3085 and value[start:sel_start] == self._template[start:sel_start]):
3089 dbg('sel_start, start:', sel_start, start)
3091 if sel_start == sel_to:
3095 newfield = value[start:keep] + value[sel_to:end]
3097 # handle sign char moving from outside field into the field:
3098 move_sign_into_field = False
3099 if not field._padZero and self._signOk and self._isNeg and value[0] in ('-', '('):
3101 newfield = signchar + newfield
3102 move_sign_into_field = True
3103 dbg('cut newfield: "%s"' % newfield)
3105 # handle what should fill in from the left:
3107 for i in range(start, end - len(newfield)):
3110 elif( self._signOk and self._isNeg and i == 1
3111 and ((self._useParens and newfield.find('(') == -1)
3112 or (not self._useParens and newfield.find('-') == -1)) ):
3115 left += self._template[i] # this can produce strange results in combination with default values...
3116 newfield = left + newfield
3117 dbg('filled newfield: "%s"' % newfield)
3119 newstr = value[:start] + newfield + value[end:]
3121 # (handle sign located in "mask position" in front of field prior to delete)
3122 if move_sign_into_field:
3123 newstr = ' ' + newstr[1:]
3126 # handle erasure of (left) sign, moving selection accordingly...
3127 if self._signOk and sel_start == 0:
3128 newstr = value = ' ' + value[1:]
3131 if field._allowInsert and sel_start >= start:
3132 # selection (if any) falls within current insert-capable field:
3133 select_len = sel_to - sel_start
3134 # determine where cursor should end up:
3135 if key == wx.WXK_BACK:
3137 newpos = sel_start -1
3143 if sel_to == sel_start:
3144 erase_to = sel_to + 1
3148 if self._isTemplateChar(newpos) and select_len == 0:
3150 if value[newpos] in ('(', '-'):
3151 newpos += 1 # don't move cusor
3152 newstr = ' ' + value[newpos:]
3153 elif value[newpos] == ')':
3154 # erase right sign, but don't move cursor; (matching left sign handled later)
3155 newstr = value[:newpos] + ' '
3157 # no deletion; just move cursor
3160 # no deletion; just move cursor
3163 if erase_to > end: erase_to = end
3164 erase_len = erase_to - newpos
3166 left = value[start:newpos]
3167 dbg("retained ='%s'" % value[erase_to:end], 'sel_to:', sel_to, "fill: '%s'" % self._template[end - erase_len:end])
3168 right = value[erase_to:end] + self._template[end-erase_len:end]
3170 if field._alignRight:
3171 rstripped = right.rstrip()
3172 if rstripped != right:
3173 pos_adjust = len(right) - len(rstripped)
3176 if not field._insertRight and value[-1] == ')' and end == self._masklength - 1:
3177 # need to shift ) into the field:
3178 right = right[:-1] + ')'
3179 value = value[:-1] + ' '
3181 newfield = left+right
3183 newfield = newfield.rjust(end-start)
3184 newpos += pos_adjust
3185 dbg("left='%s', right ='%s', newfield='%s'" %(left, right, newfield))
3186 newstr = value[:start] + newfield + value[end:]
3191 if sel_start == sel_to:
3192 dbg("current sel_start, sel_to:", sel_start, sel_to)
3193 if key == wx.WXK_BACK:
3194 sel_start, sel_to = sel_to-1, sel_to-1
3195 dbg("new sel_start, sel_to:", sel_start, sel_to)
3197 if field._padZero and not value[start:sel_to].replace('0', '').replace(' ','').replace(field._fillChar, ''):
3198 # preceding chars (if any) are zeros, blanks or fillchar; new char should be 0:
3201 newchar = self._template[sel_to] ## get an original template character to "clear" the current char
3202 dbg('value = "%s"' % value, 'value[%d] = "%s"' %(sel_start, value[sel_start]))
3204 if self._isTemplateChar(sel_to):
3205 if sel_to == 0 and self._signOk and value[sel_to] == '-': # erasing "template" sign char
3206 newstr = ' ' + value[1:]
3208 elif self._signOk and self._useParens and (value[sel_to] == ')' or value[sel_to] == '('):
3209 # allow "change sign" by removing both parens:
3210 newstr = value[:self._signpos] + ' ' + value[self._signpos+1:-1] + ' '
3215 if field._insertRight and sel_start == sel_to:
3216 # force non-insert-right behavior, by selecting char to be replaced:
3218 newstr, ignore = self._insertKey(newchar, sel_start, sel_start, sel_to, value)
3222 newstr = self._eraseSelection(value, sel_start, sel_to)
3224 pos = sel_start # put cursor back at beginning of selection
3226 if self._signOk and self._useParens:
3227 # account for resultant unbalanced parentheses:
3228 left_signpos = newstr.find('(')
3229 right_signpos = newstr.find(')')
3231 if left_signpos == -1 and right_signpos != -1:
3232 # erased left-sign marker; get rid of right sign marker:
3233 newstr = newstr[:right_signpos] + ' ' + newstr[right_signpos+1:]
3235 elif left_signpos != -1 and right_signpos == -1:
3236 # erased right-sign marker; get rid of left-sign marker:
3237 newstr = newstr[:left_signpos] + ' ' + newstr[left_signpos+1:]
3239 dbg("oldstr:'%s'" % value, 'oldpos:', oldstart)
3240 dbg("newstr:'%s'" % newstr, 'pos:', pos)
3242 # if erasure results in an invalid field, disallow it:
3243 dbg('field._validRequired?', field._validRequired)
3244 dbg('field.IsValid("%s")?' % newstr[start:end], field.IsValid(newstr[start:end]))
3245 if field._validRequired and not field.IsValid(newstr[start:end]):
3246 if not wx.Validator_IsSilent():
3251 # if erasure results in an invalid value, disallow it:
3252 if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
3253 if not wx.Validator_IsSilent():
3258 dbg('setting value (later) to', newstr)
3259 wx.CallAfter(self._SetValue, newstr)
3260 dbg('setting insertion point (later) to', pos)
3261 wx.CallAfter(self._SetInsertionPoint, pos)
3266 def _OnEnd(self,event):
3267 """ Handles End keypress in control. Should return False to skip other processing. """
3268 dbg("MaskedEditMixin::_OnEnd", indent=1)
3269 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3270 if not event.ControlDown():
3271 end = self._masklength # go to end of control
3272 if self._signOk and self._useParens:
3273 end = end - 1 # account for reserved char at end
3275 end_of_input = self._goEnd(getPosOnly=True)
3276 sel_start, sel_to = self._GetSelection()
3277 if sel_to < pos: sel_to = pos
3278 field = self._FindField(sel_to)
3279 field_end = self._FindField(end_of_input)
3281 # pick different end point if either:
3282 # - cursor not in same field
3283 # - or at or past last input already
3284 # - or current selection = end of current field:
3285 ## dbg('field != field_end?', field != field_end)
3286 ## dbg('sel_to >= end_of_input?', sel_to >= end_of_input)
3287 if field != field_end or sel_to >= end_of_input:
3288 edit_start, edit_end = field._extent
3289 ## dbg('edit_end:', edit_end)
3290 ## dbg('sel_to:', sel_to)
3291 ## dbg('sel_to == edit_end?', sel_to == edit_end)
3292 ## dbg('field._index < self._field_indices[-1]?', field._index < self._field_indices[-1])
3294 if sel_to == edit_end and field._index < self._field_indices[-1]:
3295 edit_start, edit_end = self._FindFieldExtent(self._findNextEntry(edit_end)) # go to end of next field:
3297 dbg('end moved to', end)
3299 elif sel_to == edit_end and field._index == self._field_indices[-1]:
3300 # already at edit end of last field; select to end of control:
3301 end = self._masklength
3302 dbg('end moved to', end)
3304 end = edit_end # select to end of current field
3305 dbg('end moved to ', end)
3307 # select to current end of input
3311 ## dbg('pos:', pos, 'end:', end)
3313 if event.ShiftDown():
3314 if not event.ControlDown():
3315 dbg("shift-end; select to end of control")
3317 dbg("shift-ctrl-end; select to end of non-whitespace")
3318 wx.CallAfter(self._SetInsertionPoint, pos)
3319 wx.CallAfter(self._SetSelection, pos, end)
3321 if not event.ControlDown():
3322 dbg('go to end of control:')
3323 wx.CallAfter(self._SetInsertionPoint, end)
3324 wx.CallAfter(self._SetSelection, end, end)
3330 def _OnReturn(self, event):
3332 Changes the event to look like a tab event, so we can then call
3333 event.Skip() on it, and have the parent form "do the right thing."
3335 dbg('MaskedEditMixin::OnReturn')
3336 event.m_keyCode = wx.WXK_TAB
3340 def _OnHome(self,event):
3341 """ Handles Home keypress in control. Should return False to skip other processing."""
3342 dbg("MaskedEditMixin::_OnHome", indent=1)
3343 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3344 sel_start, sel_to = self._GetSelection()
3346 # There are 5 cases here:
3348 # 1) shift: select from start of control to end of current
3350 if event.ShiftDown() and not event.ControlDown():
3351 dbg("shift-home; select to start of control")
3355 # 2) no shift, no control: move cursor to beginning of control.
3356 elif not event.ControlDown():
3357 dbg("home; move to start of control")
3361 # 3) No shift, control: move cursor back to beginning of field; if
3362 # there already, go to beginning of previous field.
3363 # 4) shift, control, start of selection not at beginning of control:
3364 # move sel_start back to start of field; if already there, go to
3365 # start of previous field.
3366 elif( event.ControlDown()
3367 and (not event.ShiftDown()
3368 or (event.ShiftDown() and sel_start > 0) ) ):
3369 if len(self._field_indices) > 1:
3370 field = self._FindField(sel_start)
3371 start, ignore = field._extent
3372 if sel_start == start and field._index != self._field_indices[0]: # go to start of previous field:
3373 start, ignore = self._FindFieldExtent(sel_start-1)
3374 elif sel_start == start:
3375 start = 0 # go to literal beginning if edit start
3382 if not event.ShiftDown():
3383 dbg("ctrl-home; move to beginning of field")
3386 dbg("shift-ctrl-home; select to beginning of field")
3390 # 5) shift, control, start of selection at beginning of control:
3391 # unselect by moving sel_to backward to beginning of current field;
3392 # if already there, move to start of previous field.
3394 if len(self._field_indices) > 1:
3395 # find end of previous field:
3396 field = self._FindField(sel_to)
3397 if sel_to > start and field._index != self._field_indices[0]:
3398 ignore, end = self._FindFieldExtent(field._extent[0]-1)
3404 end_of_field = False
3405 dbg("shift-ctrl-home; unselect to beginning of field")
3407 dbg('queuing new sel_start, sel_to:', (start, end))
3408 wx.CallAfter(self._SetInsertionPoint, start)
3409 wx.CallAfter(self._SetSelection, start, end)
3414 def _OnChangeField(self, event):
3416 Primarily handles TAB events, but can be used for any key that
3417 designer wants to change fields within a masked edit control.
3418 NOTE: at the moment, although coded to handle shift-TAB and
3419 control-shift-TAB, these events are not sent to the controls
3422 dbg('MaskedEditMixin::_OnChangeField', indent = 1)
3423 # determine end of current field:
3424 pos = self._GetInsertionPoint()
3425 dbg('current pos:', pos)
3426 sel_start, sel_to = self._GetSelection()
3428 if self._masklength < 0: # no fields; process tab normally
3429 self._AdjustField(pos)
3430 if event.GetKeyCode() == wx.WXK_TAB:
3431 dbg('tab to next ctrl')
3438 if event.ShiftDown():
3442 # NOTE: doesn't yet work with SHIFT-tab under wx; the control
3443 # never sees this event! (But I've coded for it should it ever work,
3444 # and it *does* work for '.' in IpAddrCtrl.)
3445 field = self._FindField(pos)
3446 index = field._index
3447 field_start = field._extent[0]
3448 if pos < field_start:
3449 dbg('cursor before 1st field; cannot change to a previous field')
3450 if not wx.Validator_IsSilent():
3454 if event.ControlDown():
3455 dbg('queuing select to beginning of field:', field_start, pos)
3456 wx.CallAfter(self._SetInsertionPoint, field_start)
3457 wx.CallAfter(self._SetSelection, field_start, pos)
3462 # We're already in the 1st field; process shift-tab normally:
3463 self._AdjustField(pos)
3464 if event.GetKeyCode() == wx.WXK_TAB:
3465 dbg('tab to previous ctrl')
3468 dbg('position at beginning')
3469 wx.CallAfter(self._SetInsertionPoint, field_start)
3473 # find beginning of previous field:
3474 begin_prev = self._FindField(field_start-1)._extent[0]
3475 self._AdjustField(pos)
3476 dbg('repositioning to', begin_prev)
3477 wx.CallAfter(self._SetInsertionPoint, begin_prev)
3478 if self._FindField(begin_prev)._selectOnFieldEntry:
3479 edit_start, edit_end = self._FindFieldExtent(begin_prev)
3480 dbg('queuing selection to (%d, %d)' % (edit_start, edit_end))
3481 wx.CallAfter(self._SetInsertionPoint, edit_start)
3482 wx.CallAfter(self._SetSelection, edit_start, edit_end)
3488 field = self._FindField(sel_to)
3489 field_start, field_end = field._extent
3490 if event.ControlDown():
3491 dbg('queuing select to end of field:', pos, field_end)
3492 wx.CallAfter(self._SetInsertionPoint, pos)
3493 wx.CallAfter(self._SetSelection, pos, field_end)
3497 if pos < field_start:
3498 dbg('cursor before 1st field; go to start of field')
3499 wx.CallAfter(self._SetInsertionPoint, field_start)
3500 if field._selectOnFieldEntry:
3501 wx.CallAfter(self._SetSelection, field_start, field_end)
3503 wx.CallAfter(self._SetSelection, field_start, field_start)
3506 dbg('end of current field:', field_end)
3507 dbg('go to next field')
3508 if field_end == self._fields[self._field_indices[-1]]._extent[1]:
3509 self._AdjustField(pos)
3510 if event.GetKeyCode() == wx.WXK_TAB:
3511 dbg('tab to next ctrl')
3514 dbg('position at end')
3515 wx.CallAfter(self._SetInsertionPoint, field_end)
3519 # we have to find the start of the next field
3520 next_pos = self._findNextEntry(field_end)
3521 if next_pos == field_end:
3522 dbg('already in last field')
3523 self._AdjustField(pos)
3524 if event.GetKeyCode() == wx.WXK_TAB:
3525 dbg('tab to next ctrl')
3531 self._AdjustField( pos )
3533 # move cursor to appropriate point in the next field and select as necessary:
3534 field = self._FindField(next_pos)
3535 edit_start, edit_end = field._extent
3536 if field._selectOnFieldEntry:
3537 dbg('move to ', next_pos)
3538 wx.CallAfter(self._SetInsertionPoint, next_pos)
3539 edit_start, edit_end = self._FindFieldExtent(next_pos)
3540 dbg('queuing select', edit_start, edit_end)
3541 wx.CallAfter(self._SetSelection, edit_start, edit_end)
3543 if field._insertRight:
3544 next_pos = field._extent[1]
3545 dbg('move to ', next_pos)
3546 wx.CallAfter(self._SetInsertionPoint, next_pos)
3551 def _OnDecimalPoint(self, event):
3552 dbg('MaskedEditMixin::_OnDecimalPoint', indent=1)
3554 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3556 if self._isFloat: ## handle float value, move to decimal place
3557 dbg('key == Decimal tab; decimal pos:', self._decimalpos)
3558 value = self._GetValue()
3559 if pos < self._decimalpos:
3560 clipped_text = value[0:pos] + self._decimalChar + value[self._decimalpos+1:]
3561 dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text)
3562 newstr = self._adjustFloat(clipped_text)
3564 newstr = self._adjustFloat(value)
3565 wx.CallAfter(self._SetValue, newstr)
3566 fraction = self._fields[1]
3567 start, end = fraction._extent
3568 wx.CallAfter(self._SetInsertionPoint, start)
3569 if fraction._selectOnFieldEntry:
3570 dbg('queuing selection after decimal point to:', (start, end))
3571 wx.CallAfter(self._SetSelection, start, end)
3572 keep_processing = False
3574 if self._isInt: ## handle integer value, truncate from current position
3575 dbg('key == Integer decimal event')
3576 value = self._GetValue()
3577 clipped_text = value[0:pos]
3578 dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text)
3579 newstr = self._adjustInt(clipped_text)
3580 dbg('newstr: "%s"' % newstr)
3581 wx.CallAfter(self._SetValue, newstr)
3582 newpos = len(newstr.rstrip())
3583 if newstr.find(')') != -1:
3584 newpos -= 1 # (don't move past right paren)
3585 wx.CallAfter(self._SetInsertionPoint, newpos)
3586 keep_processing = False
3590 def _OnChangeSign(self, event):
3591 dbg('MaskedEditMixin::_OnChangeSign', indent=1)
3592 key = event.GetKeyCode()
3593 pos = self._adjustPos(self._GetInsertionPoint(), key)
3594 value = self._eraseSelection()
3595 integer = self._fields[0]
3596 start, end = integer._extent
3598 ## dbg('adjusted pos:', pos)
3599 if chr(key) in ('-','+','(', ')') or (chr(key) == " " and pos == self._signpos):
3600 cursign = self._isNeg
3601 dbg('cursign:', cursign)
3602 if chr(key) in ('-','(', ')'):
3603 self._isNeg = (not self._isNeg) ## flip value
3606 dbg('isNeg?', self._isNeg)
3608 text, self._signpos, self._right_signpos = self._getSignedValue(candidate=value)
3609 dbg('text:"%s"' % text, 'signpos:', self._signpos, 'right_signpos:', self._right_signpos)
3613 if self._isNeg and self._signpos is not None and self._signpos != -1:
3614 if self._useParens and self._right_signpos is not None:
3615 text = text[:self._signpos] + '(' + text[self._signpos+1:self._right_signpos] + ')' + text[self._right_signpos+1:]
3617 text = text[:self._signpos] + '-' + text[self._signpos+1:]
3619 ## dbg('self._isNeg?', self._isNeg, 'self.IsValid(%s)' % text, self.IsValid(text))
3621 text = text[:self._signpos] + ' ' + text[self._signpos+1:self._right_signpos] + ' ' + text[self._right_signpos+1:]
3623 text = text[:self._signpos] + ' ' + text[self._signpos+1:]
3624 dbg('clearing self._isNeg')
3627 wx.CallAfter(self._SetValue, text)
3628 wx.CallAfter(self._applyFormatting)
3629 dbg('pos:', pos, 'signpos:', self._signpos)
3630 if pos == self._signpos or integer.IsEmpty(text[start:end]):
3631 wx.CallAfter(self._SetInsertionPoint, self._signpos+1)
3633 wx.CallAfter(self._SetInsertionPoint, pos)
3635 keep_processing = False
3637 keep_processing = True
3639 return keep_processing
3642 def _OnGroupChar(self, event):
3644 This handler is only registered if the mask is a numeric mask.
3645 It allows the insertion of ',' or '.' if appropriate.
3647 dbg('MaskedEditMixin::_OnGroupChar', indent=1)
3648 keep_processing = True
3649 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3650 sel_start, sel_to = self._GetSelection()
3651 groupchar = self._fields[0]._groupChar
3652 if not self._isCharAllowed(groupchar, pos, checkRegex=True):
3653 keep_processing = False
3654 if not wx.Validator_IsSilent():
3658 newstr, newpos = self._insertKey(groupchar, pos, sel_start, sel_to, self._GetValue() )
3659 dbg("str with '%s' inserted:" % groupchar, '"%s"' % newstr)
3660 if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
3661 keep_processing = False
3662 if not wx.Validator_IsSilent():
3666 wx.CallAfter(self._SetValue, newstr)
3667 wx.CallAfter(self._SetInsertionPoint, newpos)
3668 keep_processing = False
3670 return keep_processing
3673 def _findNextEntry(self,pos, adjustInsert=True):
3674 """ Find the insertion point for the next valid entry character position."""
3675 if self._isTemplateChar(pos): # if changing fields, pay attn to flag
3676 adjustInsert = adjustInsert
3677 else: # else within a field; flag not relevant
3678 adjustInsert = False
3680 while self._isTemplateChar(pos) and pos < self._masklength:
3683 # if changing fields, and we've been told to adjust insert point,
3684 # look at new field; if empty and right-insert field,
3685 # adjust to right edge:
3686 if adjustInsert and pos < self._masklength:
3687 field = self._FindField(pos)
3688 start, end = field._extent
3689 slice = self._GetValue()[start:end]
3690 if field._insertRight and field.IsEmpty(slice):
3695 def _findNextTemplateChar(self, pos):
3696 """ Find the position of the next non-editable character in the mask."""
3697 while not self._isTemplateChar(pos) and pos < self._masklength:
3702 def _OnAutoCompleteField(self, event):
3703 dbg('MaskedEditMixin::_OnAutoCompleteField', indent =1)
3704 pos = self._GetInsertionPoint()
3705 field = self._FindField(pos)
3706 edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
3709 keycode = event.GetKeyCode()
3711 if field._fillChar != ' ':
3712 text = slice.replace(field._fillChar, '')
3716 keep_processing = True # (assume True to start)
3717 dbg('field._hasList?', field._hasList)
3719 dbg('choices:', field._choices)
3720 dbg('compareChoices:', field._compareChoices)
3721 choices, choice_required = field._compareChoices, field._choiceRequired
3722 if keycode in (wx.WXK_PRIOR, wx.WXK_UP):
3726 match_index, partial_match = self._autoComplete(direction, choices, text, compareNoCase=field._compareNoCase, current_index = field._autoCompleteIndex)
3727 if( match_index is None
3728 and (keycode in self._autoCompleteKeycodes + [wx.WXK_PRIOR, wx.WXK_NEXT]
3729 or (keycode in [wx.WXK_UP, wx.WXK_DOWN] and event.ShiftDown() ) ) ):
3730 # Select the 1st thing from the list:
3733 if( match_index is not None
3734 and ( keycode in self._autoCompleteKeycodes + [wx.WXK_PRIOR, wx.WXK_NEXT]
3735 or (keycode in [wx.WXK_UP, wx.WXK_DOWN] and event.ShiftDown())
3736 or (keycode == wx.WXK_DOWN and partial_match) ) ):
3738 # We're allowed to auto-complete:
3740 value = self._GetValue()
3741 newvalue = value[:edit_start] + field._choices[match_index] + value[edit_end:]
3742 dbg('setting value to "%s"' % newvalue)
3743 self._SetValue(newvalue)
3744 self._SetInsertionPoint(min(edit_end, len(newvalue.rstrip())))
3745 self._OnAutoSelect(field, match_index)
3746 self._CheckValid() # recolor as appopriate
3749 if keycode in (wx.WXK_UP, wx.WXK_DOWN, wx.WXK_LEFT, wx.WXK_RIGHT):
3750 # treat as left right arrow if unshifted, tab/shift tab if shifted.
3751 if event.ShiftDown():
3752 if keycode in (wx.WXK_DOWN, wx.WXK_RIGHT):
3753 # remove "shifting" and treat as (forward) tab:
3754 event.m_shiftDown = False
3755 keep_processing = self._OnChangeField(event)
3757 keep_processing = self._OnArrow(event)
3758 # else some other key; keep processing the key
3760 dbg('keep processing?', keep_processing, indent=0)
3761 return keep_processing
3764 def _OnAutoSelect(self, field, match_index = None):
3766 Function called if autoselect feature is enabled and entire control
3769 dbg('MaskedEditMixin::OnAutoSelect', field._index)
3770 if match_index is not None:
3771 field._autoCompleteIndex = match_index
3774 def _autoComplete(self, direction, choices, value, compareNoCase, current_index):
3776 This function gets called in response to Auto-complete events.
3777 It attempts to find a match to the specified value against the
3778 list of choices; if exact match, the index of then next
3779 appropriate value in the list, based on the given direction.
3780 If not an exact match, it will return the index of the 1st value from
3781 the choice list for which the partial value can be extended to match.
3782 If no match found, it will return None.
3783 The function returns a 2-tuple, with the 2nd element being a boolean
3784 that indicates if partial match was necessary.
3786 dbg('autoComplete(direction=', direction, 'choices=',choices, 'value=',value,'compareNoCase?', compareNoCase, 'current_index:', current_index, indent=1)
3788 dbg('nothing to match against', indent=0)
3789 return (None, False)
3791 partial_match = False
3794 value = value.lower()
3796 last_index = len(choices) - 1
3797 if value in choices:
3798 dbg('"%s" in', choices)
3799 if current_index is not None and choices[current_index] == value:
3800 index = current_index
3802 index = choices.index(value)
3804 dbg('matched "%s" (%d)' % (choices[index], index))
3806 dbg('going to previous')
3807 if index == 0: index = len(choices) - 1
3810 if index == len(choices) - 1: index = 0
3812 dbg('change value to "%s" (%d)' % (choices[index], index))
3815 partial_match = True
3816 value = value.strip()
3817 dbg('no match; try to auto-complete:')
3819 dbg('searching for "%s"' % value)
3820 if current_index is None:
3821 indices = range(len(choices))
3826 indices = range(current_index +1, len(choices)) + range(current_index+1)
3827 dbg('range(current_index+1 (%d), len(choices) (%d)) + range(%d):' % (current_index+1, len(choices), current_index+1), indices)
3829 indices = range(current_index-1, -1, -1) + range(len(choices)-1, current_index-1, -1)
3830 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)
3831 ## dbg('indices:', indices)
3832 for index in indices:
3833 choice = choices[index]
3834 if choice.find(value, 0) == 0:
3835 dbg('match found:', choice)
3838 else: dbg('choice: "%s" - no match' % choice)
3839 if match is not None:
3840 dbg('matched', match)
3842 dbg('no match found')
3844 return (match, partial_match)
3847 def _AdjustField(self, pos):
3849 This function gets called by default whenever the cursor leaves a field.
3850 The pos argument given is the char position before leaving that field.
3851 By default, floating point, integer and date values are adjusted to be
3852 legal in this function. Derived classes may override this function
3853 to modify the value of the control in a different way when changing fields.
3855 NOTE: these change the value immediately, and restore the cursor to
3856 the passed location, so that any subsequent code can then move it
3857 based on the operation being performed.
3859 newvalue = value = self._GetValue()
3860 field = self._FindField(pos)
3861 start, end, slice = self._FindFieldExtent(getslice=True)
3862 newfield = field._AdjustField(slice)
3863 newvalue = value[:start] + newfield + value[end:]
3865 if self._isFloat and newvalue != self._template:
3866 newvalue = self._adjustFloat(newvalue)
3868 if self._ctrl_constraints._isInt and value != self._template:
3869 newvalue = self._adjustInt(value)
3871 if self._isDate and value != self._template:
3872 newvalue = self._adjustDate(value, fixcentury=True)
3873 if self._4digityear:
3874 year2dig = self._dateExtent - 2
3875 if pos == year2dig and value[year2dig] != newvalue[year2dig]:
3878 if newvalue != value:
3879 self._SetValue(newvalue)
3880 self._SetInsertionPoint(pos)
3883 def _adjustKey(self, pos, key):
3884 """ Apply control formatting to the key (e.g. convert to upper etc). """
3885 field = self._FindField(pos)
3886 if field._forceupper and key in range(97,123):
3887 key = ord( chr(key).upper())
3889 if field._forcelower and key in range(97,123):
3890 key = ord( chr(key).lower())
3895 def _adjustPos(self, pos, key):
3897 Checks the current insertion point position and adjusts it if
3898 necessary to skip over non-editable characters.
3900 dbg('_adjustPos', pos, key, indent=1)
3901 sel_start, sel_to = self._GetSelection()
3902 # If a numeric or decimal mask, and negatives allowed, reserve the
3903 # first space for sign, and last one if using parens.
3905 and ((pos == self._signpos and key in (ord('-'), ord('+'), ord(' ')) )
3906 or self._useParens and pos == self._masklength -1)):
3907 dbg('adjusted pos:', pos, indent=0)
3910 if key not in self._nav:
3911 field = self._FindField(pos)
3913 dbg('field._insertRight?', field._insertRight)
3914 if field._insertRight: # if allow right-insert
3915 start, end = field._extent
3916 slice = self._GetValue()[start:end].strip()
3917 field_len = end - start
3918 if pos == end: # if cursor at right edge of field
3919 # if not filled or supposed to stay in field, keep current position
3921 ## dbg('len (slice):', len(slice))
3922 ## dbg('field_len?', field_len)
3923 ## dbg('pos==end; len (slice) < field_len?', len(slice) < field_len)
3924 ## dbg('not field._moveOnFieldFull?', not field._moveOnFieldFull)
3925 if len(slice) == field_len and field._moveOnFieldFull:
3926 # move cursor to next field:
3927 pos = self._findNextEntry(pos)
3928 self._SetInsertionPoint(pos)
3930 self._SetSelection(pos, sel_to) # restore selection
3932 self._SetSelection(pos, pos) # remove selection
3933 else: # leave cursor alone
3936 # if at start of control, move to right edge
3937 if sel_to == sel_start and self._isTemplateChar(pos) and pos != end:
3938 pos = end # move to right edge
3939 ## elif sel_start <= start and sel_to == end:
3940 ## # select to right edge of field - 1 (to replace char)
3942 ## self._SetInsertionPoint(pos)
3943 ## # restore selection
3944 ## self._SetSelection(sel_start, pos)
3946 elif self._signOk and sel_start == 0: # if selected to beginning and signed,
3947 # adjust to past reserved sign position:
3948 pos = self._fields[0]._extent[0]
3949 self._SetInsertionPoint(pos)
3951 self._SetSelection(pos, sel_to)
3953 pass # leave position/selection alone
3955 # else make sure the user is not trying to type over a template character
3956 # If they are, move them to the next valid entry position
3957 elif self._isTemplateChar(pos):
3958 if( not field._moveOnFieldFull
3959 and (not self._signOk
3961 and field._index == 0
3962 and pos > 0) ) ): # don't move to next field without explicit cursor movement
3965 # find next valid position
3966 pos = self._findNextEntry(pos)
3967 self._SetInsertionPoint(pos)
3968 if pos < sel_to: # restore selection
3969 self._SetSelection(pos, sel_to)
3970 dbg('adjusted pos:', pos, indent=0)
3974 def _adjustFloat(self, candidate=None):
3976 'Fixes' an floating point control. Collapses spaces, right-justifies, etc.
3978 dbg('MaskedEditMixin::_adjustFloat, candidate = "%s"' % candidate, indent=1)
3979 lenInt,lenFraction = [len(s) for s in self._mask.split('.')] ## Get integer, fraction lengths
3981 if candidate is None: value = self._GetValue()
3982 else: value = candidate
3983 dbg('value = "%(value)s"' % locals(), 'len(value):', len(value))
3984 intStr, fracStr = value.split(self._decimalChar)
3986 intStr = self._fields[0]._AdjustField(intStr)
3987 dbg('adjusted intStr: "%s"' % intStr)
3988 lenInt = len(intStr)
3989 fracStr = fracStr + ('0'*(lenFraction-len(fracStr))) # add trailing spaces to decimal
3991 dbg('intStr "%(intStr)s"' % locals())
3992 dbg('lenInt:', lenInt)
3994 intStr = string.rjust( intStr[-lenInt:], lenInt)
3995 dbg('right-justifed intStr = "%(intStr)s"' % locals())
3996 newvalue = intStr + self._decimalChar + fracStr
3999 if len(newvalue) < self._masklength:
4000 newvalue = ' ' + newvalue
4001 signedvalue = self._getSignedValue(newvalue)[0]
4002 if signedvalue is not None: newvalue = signedvalue
4004 # Finally, align string with decimal position, left-padding with
4006 newdecpos = newvalue.find(self._decimalChar)
4007 if newdecpos < self._decimalpos:
4008 padlen = self._decimalpos - newdecpos
4009 newvalue = string.join([' ' * padlen] + [newvalue] ,'')
4011 if self._signOk and self._useParens:
4012 if newvalue.find('(') != -1:
4013 newvalue = newvalue[:-1] + ')'
4015 newvalue = newvalue[:-1] + ' '
4017 dbg('newvalue = "%s"' % newvalue)
4018 if candidate is None:
4019 wx.CallAfter(self._SetValue, newvalue)
4024 def _adjustInt(self, candidate=None):
4025 """ 'Fixes' an integer control. Collapses spaces, right or left-justifies."""
4026 dbg("MaskedEditMixin::_adjustInt", candidate)
4027 lenInt = self._masklength
4028 if candidate is None: value = self._GetValue()
4029 else: value = candidate
4031 intStr = self._fields[0]._AdjustField(value)
4032 intStr = intStr.strip() # drop extra spaces
4033 dbg('adjusted field: "%s"' % intStr)
4035 if self._isNeg and intStr.find('-') == -1 and intStr.find('(') == -1:
4037 intStr = '(' + intStr + ')'
4039 intStr = '-' + intStr
4040 elif self._isNeg and intStr.find('-') != -1 and self._useParens:
4041 intStr = intStr.replace('-', '(')
4043 if( self._signOk and ((self._useParens and intStr.find('(') == -1)
4044 or (not self._useParens and intStr.find('-') == -1))):
4045 intStr = ' ' + intStr
4047 intStr += ' ' # space for right paren position
4049 elif self._signOk and self._useParens and intStr.find('(') != -1 and intStr.find(')') == -1:
4050 # ensure closing right paren:
4053 if self._fields[0]._alignRight: ## Only if right-alignment is enabled
4054 intStr = intStr.rjust( lenInt )
4056 intStr = intStr.ljust( lenInt )
4058 if candidate is None:
4059 wx.CallAfter(self._SetValue, intStr )
4063 def _adjustDate(self, candidate=None, fixcentury=False, force4digit_year=False):
4065 'Fixes' a date control, expanding the year if it can.
4066 Applies various self-formatting options.
4068 dbg("MaskedEditMixin::_adjustDate", indent=1)
4069 if candidate is None: text = self._GetValue()
4070 else: text = candidate
4072 if self._datestyle == "YMD":
4077 dbg('getYear: "%s"' % getYear(text, self._datestyle))
4078 year = string.replace( getYear( text, self._datestyle),self._fields[year_field]._fillChar,"") # drop extra fillChars
4079 month = getMonth( text, self._datestyle)
4080 day = getDay( text, self._datestyle)
4081 dbg('self._datestyle:', self._datestyle, 'year:', year, 'Month', month, 'day:', day)
4084 yearstart = self._dateExtent - 4
4088 or (self._GetInsertionPoint() > yearstart+1 and text[yearstart+2] == ' ')
4089 or (self._GetInsertionPoint() > yearstart+2 and text[yearstart+3] == ' ') ) ):
4090 ## user entered less than four digits and changing fields or past point where we could
4091 ## enter another digit:
4095 dbg('bad year=', year)
4096 year = text[yearstart:self._dateExtent]
4098 if len(year) < 4 and yearVal:
4100 # Fix year adjustment to be less "20th century" :-) and to adjust heuristic as the
4102 now = wx.DateTime_Now()
4103 century = (now.GetYear() /100) * 100 # "this century"
4104 twodig_year = now.GetYear() - century # "this year" (2 digits)
4105 # if separation between today's 2-digit year and typed value > 50,
4106 # assume last century,
4107 # else assume this century.
4109 # Eg: if 2003 and yearVal == 30, => 2030
4110 # if 2055 and yearVal == 80, => 2080
4111 # if 2010 and yearVal == 96, => 1996
4113 if abs(yearVal - twodig_year) > 50:
4114 yearVal = (century - 100) + yearVal
4116 yearVal = century + yearVal
4117 year = str( yearVal )
4118 else: # pad with 0's to make a 4-digit year
4119 year = "%04d" % yearVal
4120 if self._4digityear or force4digit_year:
4121 text = makeDate(year, month, day, self._datestyle, text) + text[self._dateExtent:]
4122 dbg('newdate: "%s"' % text, indent=0)
4126 def _goEnd(self, getPosOnly=False):
4127 """ Moves the insertion point to the end of user-entry """
4128 dbg("MaskedEditMixin::_goEnd; getPosOnly:", getPosOnly, indent=1)
4129 text = self._GetValue()
4130 ## dbg('text: "%s"' % text)
4132 if len(text.rstrip()):
4133 for i in range( min( self._masklength-1, len(text.rstrip())), -1, -1):
4134 ## dbg('i:', i, 'self._isMaskChar(%d)' % i, self._isMaskChar(i))
4135 if self._isMaskChar(i):
4137 ## dbg("text[%d]: '%s'" % (i, char))
4143 pos = self._goHome(getPosOnly=True)
4145 pos = min(i,self._masklength)
4147 field = self._FindField(pos)
4148 start, end = field._extent
4149 if field._insertRight and pos < end:
4151 dbg('next pos:', pos)
4156 self._SetInsertionPoint(pos)
4159 def _goHome(self, getPosOnly=False):
4160 """ Moves the insertion point to the beginning of user-entry """
4161 dbg("MaskedEditMixin::_goHome; getPosOnly:", getPosOnly, indent=1)
4162 text = self._GetValue()
4163 for i in range(self._masklength):
4164 if self._isMaskChar(i):
4171 self._SetInsertionPoint(max(i,0))
4175 def _getAllowedChars(self, pos):
4176 """ Returns a string of all allowed user input characters for the provided
4177 mask character plus control options
4179 maskChar = self.maskdict[pos]
4180 okchars = self.maskchardict[maskChar] ## entry, get mask approved characters
4181 field = self._FindField(pos)
4182 if okchars and field._okSpaces: ## Allow spaces?
4184 if okchars and field._includeChars: ## any additional included characters?
4185 okchars += field._includeChars
4186 ## dbg('okchars[%d]:' % pos, okchars)
4190 def _isMaskChar(self, pos):
4191 """ Returns True if the char at position pos is a special mask character (e.g. NCXaA#)
4193 if pos < self._masklength:
4194 return self.ismasked[pos]
4199 def _isTemplateChar(self,Pos):
4200 """ Returns True if the char at position pos is a template character (e.g. -not- NCXaA#)
4202 if Pos < self._masklength:
4203 return not self._isMaskChar(Pos)
4208 def _isCharAllowed(self, char, pos, checkRegex=False, allowAutoSelect=True, ignoreInsertRight=False):
4209 """ Returns True if character is allowed at the specific position, otherwise False."""
4210 dbg('_isCharAllowed', char, pos, checkRegex, indent=1)
4211 field = self._FindField(pos)
4212 right_insert = False
4214 if self.controlInitialized:
4215 sel_start, sel_to = self._GetSelection()
4217 sel_start, sel_to = pos, pos
4219 if (field._insertRight or self._ctrl_constraints._insertRight) and not ignoreInsertRight:
4220 start, end = field._extent
4221 field_len = end - start
4222 if self.controlInitialized:
4223 value = self._GetValue()
4224 fstr = value[start:end].strip()
4226 while fstr and fstr[0] == '0':
4228 input_len = len(fstr)
4229 if self._signOk and '-' in fstr or '(' in fstr:
4230 input_len -= 1 # sign can move out of field, so don't consider it in length
4232 value = self._template
4233 input_len = 0 # can't get the current "value", so use 0
4236 # if entire field is selected or position is at end and field is not full,
4237 # or if allowed to right-insert at any point in field and field is not full and cursor is not at a fillChar:
4238 if( (sel_start, sel_to) == field._extent
4239 or (pos == end and input_len < field_len)):
4241 dbg('pos = end - 1 = ', pos, 'right_insert? 1')
4243 elif( field._allowInsert and sel_start == sel_to
4244 and (sel_to == end or (sel_to < self._masklength and value[sel_start] != field._fillChar))
4245 and input_len < field_len ):
4246 pos = sel_to - 1 # where character will go
4247 dbg('pos = sel_to - 1 = ', pos, 'right_insert? 1')
4249 # else leave pos alone...
4251 dbg('pos stays ', pos, 'right_insert? 0')
4254 if self._isTemplateChar( pos ): ## if a template character, return empty
4255 dbg('%d is a template character; returning False' % pos, indent=0)
4258 if self._isMaskChar( pos ):
4259 okChars = self._getAllowedChars(pos)
4261 if self._fields[0]._groupdigits and (self._isInt or (self._isFloat and pos < self._decimalpos)):
4262 okChars += self._fields[0]._groupChar
4265 if self._isInt or (self._isFloat and pos < self._decimalpos):
4269 elif self._useParens and (self._isInt or (self._isFloat and pos > self._decimalpos)):
4272 ## dbg('%s in %s?' % (char, okChars), char in okChars)
4273 approved = char in okChars
4275 if approved and checkRegex:
4276 dbg("checking appropriate regex's")
4277 value = self._eraseSelection(self._GetValue())
4283 newvalue, ignore, ignore, ignore, ignore = self._insertKey(char, at, sel_start, sel_to, value, allowAutoSelect=True)
4285 newvalue, ignore = self._insertKey(char, at, sel_start, sel_to, value)
4286 dbg('newvalue: "%s"' % newvalue)
4288 fields = [self._FindField(pos)] + [self._ctrl_constraints]
4289 for field in fields: # includes fields[-1] == "ctrl_constraints"
4290 if field._regexMask and field._filter:
4291 dbg('checking vs. regex')
4292 start, end = field._extent
4293 slice = newvalue[start:end]
4294 approved = (re.match( field._filter, slice) is not None)
4295 dbg('approved?', approved)
4296 if not approved: break
4300 dbg('%d is a !???! character; returning False', indent=0)
4304 def _applyFormatting(self):
4305 """ Apply formatting depending on the control's state.
4306 Need to find a way to call this whenever the value changes, in case the control's
4307 value has been changed or set programatically.
4310 dbg('MaskedEditMixin::_applyFormatting', indent=1)
4312 # Handle negative numbers
4314 text, signpos, right_signpos = self._getSignedValue()
4315 dbg('text: "%s", signpos:' % text, signpos)
4316 if not text or text[signpos] not in ('-','('):
4318 dbg('no valid sign found; new sign:', self._isNeg)
4319 if text and signpos != self._signpos:
4320 self._signpos = signpos
4321 elif text and self._valid and not self._isNeg and text[signpos] in ('-', '('):
4322 dbg('setting _isNeg to True')
4324 dbg('self._isNeg:', self._isNeg)
4326 if self._signOk and self._isNeg:
4327 fc = self._signedForegroundColour
4329 fc = self._foregroundColour
4331 if hasattr(fc, '_name'):
4335 dbg('setting foreground to', c)
4336 self.SetForegroundColour(fc)
4341 bc = self._emptyBackgroundColour
4343 bc = self._validBackgroundColour
4346 bc = self._invalidBackgroundColour
4347 if hasattr(bc, '_name'):
4351 dbg('setting background to', c)
4352 self.SetBackgroundColour(bc)
4354 dbg(indent=0, suspend=0)
4357 def _getAbsValue(self, candidate=None):
4358 """ Return an unsigned value (i.e. strip the '-' prefix if any), and sign position(s).
4360 dbg('MaskedEditMixin::_getAbsValue; candidate="%s"' % candidate, indent=1)
4361 if candidate is None: text = self._GetValue()
4362 else: text = candidate
4363 right_signpos = text.find(')')
4366 if self._ctrl_constraints._alignRight and self._fields[0]._fillChar == ' ':
4367 signpos = text.find('-')
4369 dbg('no - found; searching for (')
4370 signpos = text.find('(')
4372 dbg('- found at', signpos)
4375 dbg('signpos still -1')
4376 dbg('len(%s) (%d) < len(%s) (%d)?' % (text, len(text), self._mask, self._masklength), len(text) < self._masklength)
4377 if len(text) < self._masklength:
4379 if len(text) < self._masklength:
4381 if len(text) > self._masklength and text[-1] in (')', ' '):
4384 dbg('len(%s) (%d), len(%s) (%d)' % (text, len(text), self._mask, self._masklength))
4385 dbg('len(%s) - (len(%s) + 1):' % (text, text.lstrip()) , len(text) - (len(text.lstrip()) + 1))
4386 signpos = len(text) - (len(text.lstrip()) + 1)
4388 if self._useParens and not text.strip():
4389 signpos -= 1 # empty value; use penultimate space
4390 dbg('signpos:', signpos)
4392 text = text[:signpos] + ' ' + text[signpos+1:]
4397 text = self._template[0] + text[1:]
4401 if right_signpos != -1:
4403 text = text[:right_signpos] + ' ' + text[right_signpos+1:]
4404 elif len(text) > self._masklength:
4405 text = text[:right_signpos] + text[right_signpos+1:]
4409 elif self._useParens and self._signOk:
4410 # figure out where it ought to go:
4411 right_signpos = self._masklength - 1 # initial guess
4412 if not self._ctrl_constraints._alignRight:
4413 dbg('not right-aligned')
4414 if len(text.strip()) == 0:
4415 right_signpos = signpos + 1
4416 elif len(text.strip()) < self._masklength:
4417 right_signpos = len(text.rstrip())
4418 dbg('right_signpos:', right_signpos)
4420 groupchar = self._fields[0]._groupChar
4422 value = long(text.replace(groupchar,'').replace('(','-').replace(')','').replace(' ', ''))
4424 dbg('invalid number', indent=0)
4425 return None, signpos, right_signpos
4429 groupchar = self._fields[0]._groupChar
4430 value = float(text.replace(groupchar,'').replace(self._decimalChar, '.').replace('(', '-').replace(')','').replace(' ', ''))
4431 dbg('value:', value)
4435 if value < 0 and value is not None:
4436 signpos = text.find('-')
4438 signpos = text.find('(')
4440 text = text[:signpos] + self._template[signpos] + text[signpos+1:]
4442 # look forwards up to the decimal point for the 1st non-digit
4443 dbg('decimal pos:', self._decimalpos)
4444 dbg('text: "%s"' % text)
4446 signpos = self._decimalpos - (len(text[:self._decimalpos].lstrip()) + 1)
4447 if text[signpos+1] in ('-','('):
4451 dbg('signpos:', signpos)
4455 right_signpos = self._masklength - 1
4456 text = text[:right_signpos] + ' '
4457 if text[signpos] == '(':
4458 text = text[:signpos] + ' ' + text[signpos+1:]
4460 right_signpos = text.find(')')
4461 if right_signpos != -1:
4466 dbg('invalid number')
4469 dbg('abstext = "%s"' % text, 'signpos:', signpos, 'right_signpos:', right_signpos)
4471 return text, signpos, right_signpos
4474 def _getSignedValue(self, candidate=None):
4475 """ Return a signed value by adding a "-" prefix if the value
4476 is set to negative, or a space if positive.
4478 dbg('MaskedEditMixin::_getSignedValue; candidate="%s"' % candidate, indent=1)
4479 if candidate is None: text = self._GetValue()
4480 else: text = candidate
4483 abstext, signpos, right_signpos = self._getAbsValue(text)
4487 return abstext, signpos, right_signpos
4489 if self._isNeg or text[signpos] in ('-', '('):
4496 if abstext[signpos] not in string.digits:
4497 text = abstext[:signpos] + sign + abstext[signpos+1:]
4499 # this can happen if value passed is too big; sign assumed to be
4500 # in position 0, but if already filled with a digit, prepend sign...
4501 text = sign + abstext
4502 if self._useParens and text.find('(') != -1:
4503 text = text[:right_signpos] + ')' + text[right_signpos+1:]
4506 dbg('signedtext = "%s"' % text, 'signpos:', signpos, 'right_signpos', right_signpos)
4508 return text, signpos, right_signpos
4511 def GetPlainValue(self, candidate=None):
4512 """ Returns control's value stripped of the template text.
4513 plainvalue = MaskedEditMixin.GetPlainValue()
4515 dbg('MaskedEditMixin::GetPlainValue; candidate="%s"' % candidate, indent=1)
4517 if candidate is None: text = self._GetValue()
4518 else: text = candidate
4521 dbg('returned ""', indent=0)
4525 for idx in range( min(len(self._template), len(text)) ):
4526 if self._mask[idx] in maskchars:
4529 if self._isFloat or self._isInt:
4530 dbg('plain so far: "%s"' % plain)
4531 plain = plain.replace('(', '-').replace(')', ' ')
4532 dbg('plain after sign regularization: "%s"' % plain)
4534 if self._signOk and self._isNeg and plain.count('-') == 0:
4535 # must be in reserved position; add to "plain value"
4536 plain = '-' + plain.strip()
4538 if self._fields[0]._alignRight:
4539 lpad = plain.count(',')
4540 plain = ' ' * lpad + plain.replace(',','')
4542 plain = plain.replace(',','')
4543 dbg('plain after pad and group:"%s"' % plain)
4545 dbg('returned "%s"' % plain.rstrip(), indent=0)
4546 return plain.rstrip()
4549 def IsEmpty(self, value=None):
4551 Returns True if control is equal to an empty value.
4552 (Empty means all editable positions in the template == fillChar.)
4554 if value is None: value = self._GetValue()
4555 if value == self._template and not self._defaultValue:
4556 ## dbg("IsEmpty? 1 (value == self._template and not self._defaultValue)")
4557 return True # (all mask chars == fillChar by defn)
4558 elif value == self._template:
4560 for pos in range(len(self._template)):
4561 ## dbg('isMaskChar(%(pos)d)?' % locals(), self._isMaskChar(pos))
4562 ## dbg('value[%(pos)d] != self._fillChar?' %locals(), value[pos] != self._fillChar[pos])
4563 if self._isMaskChar(pos) and value[pos] not in (' ', self._fillChar[pos]):
4565 ## dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals())
4568 ## dbg("IsEmpty? 0 (value doesn't match template)")
4572 def IsDefault(self, value=None):
4574 Returns True if the value specified (or the value of the control if not specified)
4575 is equal to the default value.
4577 if value is None: value = self._GetValue()
4578 return value == self._template
4581 def IsValid(self, value=None):
4582 """ Indicates whether the value specified (or the current value of the control
4583 if not specified) is considered valid."""
4584 ## dbg('MaskedEditMixin::IsValid("%s")' % value, indent=1)
4585 if value is None: value = self._GetValue()
4586 ret = self._CheckValid(value)
4591 def _eraseSelection(self, value=None, sel_start=None, sel_to=None):
4592 """ Used to blank the selection when inserting a new character. """
4593 dbg("MaskedEditMixin::_eraseSelection", indent=1)
4594 if value is None: value = self._GetValue()
4595 if sel_start is None or sel_to is None:
4596 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
4597 dbg('value: "%s"' % value)
4598 dbg("current sel_start, sel_to:", sel_start, sel_to)
4600 newvalue = list(value)
4601 for i in range(sel_start, sel_to):
4602 if self._signOk and newvalue[i] in ('-', '(', ')'):
4603 dbg('found sign (%s) at' % newvalue[i], i)
4605 # balance parentheses:
4606 if newvalue[i] == '(':
4607 right_signpos = value.find(')')
4608 if right_signpos != -1:
4609 newvalue[right_signpos] = ' '
4611 elif newvalue[i] == ')':
4612 left_signpos = value.find('(')
4613 if left_signpos != -1:
4614 newvalue[left_signpos] = ' '
4618 elif self._isMaskChar(i):
4619 field = self._FindField(i)
4623 newvalue[i] = self._template[i]
4625 value = string.join(newvalue,"")
4626 dbg('new value: "%s"' % value)
4631 def _insertKey(self, char, pos, sel_start, sel_to, value, allowAutoSelect=False):
4632 """ Handles replacement of the character at the current insertion point."""
4633 dbg('MaskedEditMixin::_insertKey', "\'" + char + "\'", pos, sel_start, sel_to, '"%s"' % value, indent=1)
4635 text = self._eraseSelection(value)
4636 field = self._FindField(pos)
4637 start, end = field._extent
4641 if pos != sel_start and sel_start == sel_to:
4642 # adjustpos must have moved the position; make selection match:
4643 sel_start = sel_to = pos
4645 dbg('field._insertRight?', field._insertRight)
4646 if( field._insertRight # field allows right insert
4647 and ((sel_start, sel_to) == field._extent # and whole field selected
4648 or (sel_start == sel_to # or nothing selected
4649 and (sel_start == end # and cursor at right edge
4650 or (field._allowInsert # or field allows right-insert
4651 and sel_start < end # next to other char in field:
4652 and text[sel_start] != field._fillChar) ) ) ) ):
4654 fstr = text[start:end]
4655 erasable_chars = [field._fillChar, ' ']
4658 erasable_chars.append('0')
4661 ## dbg("fstr[0]:'%s'" % fstr[0])
4662 ## dbg('field_index:', field._index)
4663 ## dbg("fstr[0] in erasable_chars?", fstr[0] in erasable_chars)
4664 ## dbg("self._signOk and field._index == 0 and fstr[0] in ('-','(')?",
4665 ## self._signOk and field._index == 0 and fstr[0] in ('-','('))
4666 if fstr[0] in erasable_chars or (self._signOk and field._index == 0 and fstr[0] in ('-','(')):
4668 ## dbg('value: "%s"' % text)
4669 ## dbg('fstr: "%s"' % fstr)
4670 ## dbg("erased: '%s'" % erased)
4671 field_sel_start = sel_start - start
4672 field_sel_to = sel_to - start
4673 dbg('left fstr: "%s"' % fstr[1:field_sel_start])
4674 dbg('right fstr: "%s"' % fstr[field_sel_to:end])
4675 fstr = fstr[1:field_sel_start] + char + fstr[field_sel_to:end]
4676 if field._alignRight and sel_start != sel_to:
4677 field_len = end - start
4678 ## pos += (field_len - len(fstr)) # move cursor right by deleted amount
4680 dbg('setting pos to:', pos)
4682 fstr = '0' * (field_len - len(fstr)) + fstr
4684 fstr = fstr.rjust(field_len) # adjust the field accordingly
4685 dbg('field str: "%s"' % fstr)
4687 newtext = text[:start] + fstr + text[end:]
4688 if erased in ('-', '(') and self._signOk:
4689 newtext = erased + newtext[1:]
4690 dbg('newtext: "%s"' % newtext)
4692 if self._signOk and field._index == 0:
4693 start -= 1 # account for sign position
4695 ## dbg('field._moveOnFieldFull?', field._moveOnFieldFull)
4696 ## dbg('len(fstr.lstrip()) == end-start?', len(fstr.lstrip()) == end-start)
4697 if( field._moveOnFieldFull and pos == end
4698 and len(fstr.lstrip()) == end-start): # if field now full
4699 newpos = self._findNextEntry(end) # go to next field
4701 newpos = pos # else keep cursor at current position
4706 dbg('newpos:', newpos)
4707 if self._signOk and self._useParens:
4708 old_right_signpos = text.find(')')
4710 if field._allowInsert and not field._insertRight and sel_to <= end and sel_start >= start:
4711 # inserting within a left-insert-capable field
4712 field_len = end - start
4713 before = text[start:sel_start]
4714 after = text[sel_to:end].strip()
4715 ## dbg("current field:'%s'" % text[start:end])
4716 ## dbg("before:'%s'" % before, "after:'%s'" % after)
4717 new_len = len(before) + len(after) + 1 # (for inserted char)
4718 ## dbg('new_len:', new_len)
4720 if new_len < field_len:
4721 retained = after + self._template[end-(field_len-new_len):end]
4722 elif new_len > end-start:
4723 retained = after[1:]
4727 left = text[0:start] + before
4728 ## dbg("left:'%s'" % left, "retained:'%s'" % retained)
4729 right = retained + text[end:]
4732 right = text[pos+1:]
4734 newtext = left + char + right
4736 if self._signOk and self._useParens:
4737 # Balance parentheses:
4738 left_signpos = newtext.find('(')
4740 if left_signpos == -1: # erased '('; remove ')'
4741 right_signpos = newtext.find(')')
4742 if right_signpos != -1:
4743 newtext = newtext[:right_signpos] + ' ' + newtext[right_signpos+1:]
4745 elif old_right_signpos != -1:
4746 right_signpos = newtext.find(')')
4748 if right_signpos == -1: # just replaced right-paren
4749 if newtext[pos] == ' ': # we just erased '); erase '('
4750 newtext = newtext[:left_signpos] + ' ' + newtext[left_signpos+1:]
4751 else: # replaced with digit; move ') over
4752 if self._ctrl_constraints._alignRight or self._isFloat:
4753 newtext = newtext[:-1] + ')'
4755 rstripped_text = newtext.rstrip()
4756 right_signpos = len(rstripped_text)
4757 dbg('old_right_signpos:', old_right_signpos, 'right signpos now:', right_signpos)
4758 newtext = newtext[:right_signpos] + ')' + newtext[right_signpos+1:]
4760 if( field._insertRight # if insert-right field (but we didn't start at right edge)
4761 and field._moveOnFieldFull # and should move cursor when full
4762 and len(newtext[start:end].strip()) == end-start): # and field now full
4763 newpos = self._findNextEntry(end) # go to next field
4764 dbg('newpos = nextentry =', newpos)
4766 dbg('pos:', pos, 'newpos:', pos+1)
4771 new_select_to = newpos # (default return values)
4775 if field._autoSelect:
4776 match_index, partial_match = self._autoComplete(1, # (always forward)
4777 field._compareChoices,
4779 compareNoCase=field._compareNoCase,
4780 current_index = field._autoCompleteIndex-1)
4781 if match_index is not None and partial_match:
4782 matched_str = newtext[start:end]
4783 newtext = newtext[:start] + field._choices[match_index] + newtext[end:]
4786 if field._insertRight:
4787 # adjust position to just after partial match in field
4788 newpos = end - (len(field._choices[match_index].strip()) - len(matched_str.strip()))
4790 elif self._ctrl_constraints._autoSelect:
4791 match_index, partial_match = self._autoComplete(
4792 1, # (always forward)
4793 self._ctrl_constraints._compareChoices,
4795 self._ctrl_constraints._compareNoCase,
4796 current_index = self._ctrl_constraints._autoCompleteIndex - 1)
4797 if match_index is not None and partial_match:
4798 matched_str = newtext
4799 newtext = self._ctrl_constraints._choices[match_index]
4800 new_select_to = self._ctrl_constraints._extent[1]
4801 match_field = self._ctrl_constraints
4802 if self._ctrl_constraints._insertRight:
4803 # adjust position to just after partial match in control:
4804 newpos = self._masklength - (len(self._ctrl_constraints._choices[match_index].strip()) - len(matched_str.strip()))
4806 dbg('newtext: "%s"' % newtext, 'newpos:', newpos, 'new_select_to:', new_select_to)
4808 return newtext, newpos, new_select_to, match_field, match_index
4810 dbg('newtext: "%s"' % newtext, 'newpos:', newpos)
4812 return newtext, newpos
4815 def _OnFocus(self,event):
4817 This event handler is currently necessary to work around new default
4818 behavior as of wxPython2.3.3;
4819 The TAB key auto selects the entire contents of the wxTextCtrl *after*
4820 the EVT_SET_FOCUS event occurs; therefore we can't query/adjust the selection
4821 *here*, because it hasn't happened yet. So to prevent this behavior, and
4822 preserve the correct selection when the focus event is not due to tab,
4823 we need to pull the following trick:
4825 dbg('MaskedEditMixin::_OnFocus')
4826 wx.CallAfter(self._fixSelection)
4831 def _CheckValid(self, candidate=None):
4833 This is the default validation checking routine; It verifies that the
4834 current value of the control is a "valid value," and has the side
4835 effect of coloring the control appropriately.
4838 dbg('MaskedEditMixin::_CheckValid: candidate="%s"' % candidate, indent=1)
4839 oldValid = self._valid
4840 if candidate is None: value = self._GetValue()
4841 else: value = candidate
4842 dbg('value: "%s"' % value)
4844 valid = True # assume True
4846 if not self.IsDefault(value) and self._isDate: ## Date type validation
4847 valid = self._validateDate(value)
4848 dbg("valid date?", valid)
4850 elif not self.IsDefault(value) and self._isTime:
4851 valid = self._validateTime(value)
4852 dbg("valid time?", valid)
4854 elif not self.IsDefault(value) and (self._isInt or self._isFloat): ## Numeric type
4855 valid = self._validateNumeric(value)
4856 dbg("valid Number?", valid)
4858 if valid: # and not self.IsDefault(value): ## generic validation accounts for IsDefault()
4859 ## valid so far; ensure also allowed by any list or regex provided:
4860 valid = self._validateGeneric(value)
4861 dbg("valid value?", valid)
4863 dbg('valid?', valid)
4867 self._applyFormatting()
4868 if self._valid != oldValid:
4869 dbg('validity changed: oldValid =',oldValid,'newvalid =', self._valid)
4870 dbg('oldvalue: "%s"' % oldvalue, 'newvalue: "%s"' % self._GetValue())
4871 dbg(indent=0, suspend=0)
4875 def _validateGeneric(self, candidate=None):
4876 """ Validate the current value using the provided list or Regex filter (if any).
4878 if candidate is None:
4879 text = self._GetValue()
4883 valid = True # assume True
4884 for i in [-1] + self._field_indices: # process global constraints first:
4885 field = self._fields[i]
4886 start, end = field._extent
4887 slice = text[start:end]
4888 valid = field.IsValid(slice)
4895 def _validateNumeric(self, candidate=None):
4896 """ Validate that the value is within the specified range (if specified.)"""
4897 if candidate is None: value = self._GetValue()
4898 else: value = candidate
4900 groupchar = self._fields[0]._groupChar
4902 number = float(value.replace(groupchar, '').replace(self._decimalChar, '.').replace('(', '-').replace(')', ''))
4904 number = long( value.replace(groupchar, '').replace('(', '-').replace(')', ''))
4906 if self._fields[0]._alignRight:
4907 require_digit_at = self._fields[0]._extent[1]-1
4909 require_digit_at = self._fields[0]._extent[0]
4910 dbg('require_digit_at:', require_digit_at)
4911 dbg("value[rda]: '%s'" % value[require_digit_at])
4912 if value[require_digit_at] not in list(string.digits):
4916 dbg('number:', number)
4917 if self._ctrl_constraints._hasRange:
4918 valid = self._ctrl_constraints._rangeLow <= number <= self._ctrl_constraints._rangeHigh
4921 groupcharpos = value.rfind(groupchar)
4922 if groupcharpos != -1: # group char present
4923 dbg('groupchar found at', groupcharpos)
4924 if self._isFloat and groupcharpos > self._decimalpos:
4925 # 1st one found on right-hand side is past decimal point
4926 dbg('groupchar in fraction; illegal')
4929 integer = value[:self._decimalpos].strip()
4931 integer = value.strip()
4932 dbg("integer:'%s'" % integer)
4933 if integer[0] in ('-', '('):
4934 integer = integer[1:]
4935 if integer[-1] == ')':
4936 integer = integer[:-1]
4938 parts = integer.split(groupchar)
4939 dbg('parts:', parts)
4940 for i in range(len(parts)):
4941 if i == 0 and abs(int(parts[0])) > 999:
4942 dbg('group 0 too long; illegal')
4945 elif i > 0 and (len(parts[i]) != 3 or ' ' in parts[i]):
4946 dbg('group %i (%s) not right size; illegal' % (i, parts[i]))
4950 dbg('value not a valid number')
4955 def _validateDate(self, candidate=None):
4956 """ Validate the current date value using the provided Regex filter.
4957 Generally used for character types.BufferType
4959 dbg('MaskedEditMixin::_validateDate', indent=1)
4960 if candidate is None: value = self._GetValue()
4961 else: value = candidate
4962 dbg('value = "%s"' % value)
4963 text = self._adjustDate(value, force4digit_year=True) ## Fix the date up before validating it
4965 valid = True # assume True until proven otherwise
4968 # replace fillChar in each field with space:
4969 datestr = text[0:self._dateExtent]
4971 field = self._fields[i]
4972 start, end = field._extent
4973 fstr = datestr[start:end]
4974 fstr.replace(field._fillChar, ' ')
4975 datestr = datestr[:start] + fstr + datestr[end:]
4977 year, month, day = getDateParts( datestr, self._datestyle)
4979 dbg('self._dateExtent:', self._dateExtent)
4980 if self._dateExtent == 11:
4981 month = charmonths_dict[month.lower()]
4985 dbg('year, month, day:', year, month, day)
4988 dbg('cannot convert string to integer parts')
4991 dbg('cannot convert string to integer month')
4995 # use wxDateTime to unambiguously try to parse the date:
4996 # ### Note: because wxDateTime is *brain-dead* and expects months 0-11,
4997 # rather than 1-12, so handle accordingly:
5003 dbg("trying to create date from values day=%d, month=%d, year=%d" % (day,month,year))
5004 dateHandler = wx.DateTimeFromDMY(day,month,year)
5008 dbg('cannot convert string to valid date')
5014 # wxDateTime doesn't take kindly to leading/trailing spaces when parsing,
5015 # so we eliminate them here:
5016 timeStr = text[self._dateExtent+1:].strip() ## time portion of the string
5018 dbg('timeStr: "%s"' % timeStr)
5020 checkTime = dateHandler.ParseTime(timeStr)
5021 valid = checkTime == len(timeStr)
5025 dbg('cannot convert string to valid time')
5026 if valid: dbg('valid date')
5031 def _validateTime(self, candidate=None):
5032 """ Validate the current time value using the provided Regex filter.
5033 Generally used for character types.BufferType
5035 dbg('MaskedEditMixin::_validateTime', indent=1)
5036 # wxDateTime doesn't take kindly to leading/trailing spaces when parsing,
5037 # so we eliminate them here:
5038 if candidate is None: value = self._GetValue().strip()
5039 else: value = candidate.strip()
5040 dbg('value = "%s"' % value)
5041 valid = True # assume True until proven otherwise
5043 dateHandler = wx.DateTime_Today()
5045 checkTime = dateHandler.ParseTime(value)
5046 dbg('checkTime:', checkTime, 'len(value)', len(value))
5047 valid = checkTime == len(value)
5052 dbg('cannot convert string to valid time')
5053 if valid: dbg('valid time')
5058 def _OnKillFocus(self,event):
5059 """ Handler for EVT_KILL_FOCUS event.
5061 dbg('MaskedEditMixin::_OnKillFocus', 'isDate=',self._isDate, indent=1)
5062 if self._mask and self._IsEditable():
5063 self._AdjustField(self._GetInsertionPoint())
5064 self._CheckValid() ## Call valid handler
5066 self._LostFocus() ## Provided for subclass use
5071 def _fixSelection(self):
5073 This gets called after the TAB traversal selection is made, if the
5074 focus event was due to this, but before the EVT_LEFT_* events if
5075 the focus shift was due to a mouse event.
5077 The trouble is that, a priori, there's no explicit notification of
5078 why the focus event we received. However, the whole reason we need to
5079 do this is because the default behavior on TAB traveral in a wxTextCtrl is
5080 now to select the entire contents of the window, something we don't want.
5081 So we can *now* test the selection range, and if it's "the whole text"
5082 we can assume the cause, change the insertion point to the start of
5083 the control, and deselect.
5085 dbg('MaskedEditMixin::_fixSelection', indent=1)
5086 if not self._mask or not self._IsEditable():
5090 sel_start, sel_to = self._GetSelection()
5091 dbg('sel_start, sel_to:', sel_start, sel_to, 'self.IsEmpty()?', self.IsEmpty())
5093 if( sel_start == 0 and sel_to >= len( self._mask ) #(can be greater in numeric controls because of reserved space)
5094 and (not self._ctrl_constraints._autoSelect or self.IsEmpty() or self.IsDefault() ) ):
5095 # This isn't normally allowed, and so assume we got here by the new
5096 # "tab traversal" behavior, so we need to reset the selection
5097 # and insertion point:
5098 dbg('entire text selected; resetting selection to start of control')
5100 field = self._FindField(self._GetInsertionPoint())
5101 edit_start, edit_end = field._extent
5102 if field._selectOnFieldEntry:
5103 self._SetInsertionPoint(edit_start)
5104 self._SetSelection(edit_start, edit_end)
5106 elif field._insertRight:
5107 self._SetInsertionPoint(edit_end)
5108 self._SetSelection(edit_end, edit_end)
5110 elif (self._isFloat or self._isInt):
5112 text, signpos, right_signpos = self._getAbsValue()
5113 if text is None or text == self._template:
5114 integer = self._fields[0]
5115 edit_start, edit_end = integer._extent
5117 if integer._selectOnFieldEntry:
5118 dbg('select on field entry:')
5119 self._SetInsertionPoint(edit_start)
5120 self._SetSelection(edit_start, edit_end)
5122 elif integer._insertRight:
5123 dbg('moving insertion point to end')
5124 self._SetInsertionPoint(edit_end)
5125 self._SetSelection(edit_end, edit_end)
5127 dbg('numeric ctrl is empty; start at beginning after sign')
5128 self._SetInsertionPoint(signpos+1) ## Move past minus sign space if signed
5129 self._SetSelection(signpos+1, signpos+1)
5131 elif sel_start > self._goEnd(getPosOnly=True):
5132 dbg('cursor beyond the end of the user input; go to end of it')
5135 dbg('sel_start, sel_to:', sel_start, sel_to, 'self._masklength:', self._masklength)
5139 def _Keypress(self,key):
5140 """ Method provided to override OnChar routine. Return False to force
5141 a skip of the 'normal' OnChar process. Called before class OnChar.
5146 def _LostFocus(self):
5147 """ Method provided for subclasses. _LostFocus() is called after
5148 the class processes its EVT_KILL_FOCUS event code.
5153 def _OnDoubleClick(self, event):
5154 """ selects field under cursor on dclick."""
5155 pos = self._GetInsertionPoint()
5156 field = self._FindField(pos)
5157 start, end = field._extent
5158 self._SetInsertionPoint(start)
5159 self._SetSelection(start, end)
5163 """ Method provided for subclasses. Called by internal EVT_TEXT
5164 handler. Return False to override the class handler, True otherwise.
5171 Used to override the default Cut() method in base controls, instead
5172 copying the selection to the clipboard and then blanking the selection,
5173 leaving only the mask in the selected area behind.
5174 Note: _Cut (read "undercut" ;-) must be called from a Cut() override in the
5175 derived control because the mixin functions can't override a method of
5178 dbg("MaskedEditMixin::_Cut", indent=1)
5179 value = self._GetValue()
5180 dbg('current value: "%s"' % value)
5181 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
5182 dbg('selected text: "%s"' % value[sel_start:sel_to].strip())
5183 do = wxTextDataObject()
5184 do.SetText(value[sel_start:sel_to].strip())
5185 wxTheClipboard.Open()
5186 wxTheClipboard.SetData(do)
5187 wxTheClipboard.Close()
5189 if sel_to - sel_start != 0:
5194 # WS Note: overriding Copy is no longer necessary given that you
5195 # can no longer select beyond the last non-empty char in the control.
5197 ## def _Copy( self ):
5199 ## Override the wxTextCtrl's .Copy function, with our own
5200 ## that does validation. Need to strip trailing spaces.
5202 ## sel_start, sel_to = self._GetSelection()
5203 ## select_len = sel_to - sel_start
5204 ## textval = wxTextCtrl._GetValue(self)
5206 ## do = wxTextDataObject()
5207 ## do.SetText(textval[sel_start:sel_to].strip())
5208 ## wxTheClipboard.Open()
5209 ## wxTheClipboard.SetData(do)
5210 ## wxTheClipboard.Close()
5213 def _getClipboardContents( self ):
5214 """ Subroutine for getting the current contents of the clipboard.
5216 do = wxTextDataObject()
5217 wxTheClipboard.Open()
5218 success = wxTheClipboard.GetData(do)
5219 wxTheClipboard.Close()
5224 # Remove leading and trailing spaces before evaluating contents
5225 return do.GetText().strip()
5228 def _validatePaste(self, paste_text, sel_start, sel_to, raise_on_invalid=False):
5230 Used by paste routine and field choice validation to see
5231 if a given slice of paste text is legal for the area in question:
5232 returns validity, replacement text, and extent of paste in
5236 dbg('MaskedEditMixin::_validatePaste("%(paste_text)s", %(sel_start)d, %(sel_to)d), raise_on_invalid? %(raise_on_invalid)d' % locals(), indent=1)
5237 select_length = sel_to - sel_start
5238 maxlength = select_length
5239 dbg('sel_to - sel_start:', maxlength)
5241 maxlength = self._masklength - sel_start
5245 dbg('maxlength:', maxlength)
5246 length_considered = len(paste_text)
5247 if length_considered > maxlength:
5248 dbg('paste text will not fit into the %s:' % item, indent=0)
5249 if raise_on_invalid:
5250 dbg(indent=0, suspend=0)
5251 if item == 'control':
5252 raise ValueError('"%s" will not fit into the control "%s"' % (paste_text, self.name))
5254 raise ValueError('"%s" will not fit into the selection' % paste_text)
5256 dbg(indent=0, suspend=0)
5257 return False, None, None
5259 text = self._template
5260 dbg('length_considered:', length_considered)
5263 replacement_text = ""
5264 replace_to = sel_start
5266 while valid_paste and i < length_considered and replace_to < self._masklength:
5267 if paste_text[i:] == self._template[replace_to:length_considered]:
5268 # remainder of paste matches template; skip char-by-char analysis
5269 dbg('remainder paste_text[%d:] (%s) matches template[%d:%d]' % (i, paste_text[i:], replace_to, length_considered))
5270 replacement_text += paste_text[i:]
5271 replace_to = i = length_considered
5274 char = paste_text[i]
5275 field = self._FindField(replace_to)
5276 if not field._compareNoCase:
5277 if field._forceupper: char = char.upper()
5278 elif field._forcelower: char = char.lower()
5280 dbg('char:', "'"+char+"'", 'i =', i, 'replace_to =', replace_to)
5281 dbg('self._isTemplateChar(%d)?' % replace_to, self._isTemplateChar(replace_to))
5282 if not self._isTemplateChar(replace_to) and self._isCharAllowed( char, replace_to, allowAutoSelect=False, ignoreInsertRight=True):
5283 replacement_text += char
5284 dbg("not template(%(replace_to)d) and charAllowed('%(char)s',%(replace_to)d)" % locals())
5285 dbg("replacement_text:", '"'+replacement_text+'"')
5288 elif( char == self._template[replace_to]
5289 or (self._signOk and
5290 ( (i == 0 and (char == '-' or (self._useParens and char == '(')))
5291 or (i == self._masklength - 1 and self._useParens and char == ')') ) ) ):
5292 replacement_text += char
5293 dbg("'%(char)s' == template(%(replace_to)d)" % locals())
5294 dbg("replacement_text:", '"'+replacement_text+'"')
5298 next_entry = self._findNextEntry(replace_to, adjustInsert=False)
5299 if next_entry == replace_to:
5302 replacement_text += self._template[replace_to:next_entry]
5303 dbg("skipping template; next_entry =", next_entry)
5304 dbg("replacement_text:", '"'+replacement_text+'"')
5305 replace_to = next_entry # so next_entry will be considered on next loop
5307 if not valid_paste and raise_on_invalid:
5308 dbg('raising exception', indent=0, suspend=0)
5309 raise ValueError('"%s" cannot be inserted into the control "%s"' % (paste_text, self.name))
5311 elif i < len(paste_text):
5313 if raise_on_invalid:
5314 dbg('raising exception', indent=0, suspend=0)
5315 raise ValueError('"%s" will not fit into the control "%s"' % (paste_text, self.name))
5317 dbg('valid_paste?', valid_paste)
5319 dbg('replacement_text: "%s"' % replacement_text, 'replace to:', replace_to)
5320 dbg(indent=0, suspend=0)
5321 return valid_paste, replacement_text, replace_to
5324 def _Paste( self, value=None, raise_on_invalid=False, just_return_value=False ):
5326 Used to override the base control's .Paste() function,
5327 with our own that does validation.
5328 Note: _Paste must be called from a Paste() override in the
5329 derived control because the mixin functions can't override a
5330 method of a sibling class.
5332 dbg('MaskedEditMixin::_Paste (value = "%s")' % value, indent=1)
5334 paste_text = self._getClipboardContents()
5338 if paste_text is not None:
5339 dbg('paste text: "%s"' % paste_text)
5340 # (conversion will raise ValueError if paste isn't legal)
5341 sel_start, sel_to = self._GetSelection()
5342 dbg('selection:', (sel_start, sel_to))
5344 # special case: handle allowInsert fields properly
5345 field = self._FindField(sel_start)
5346 edit_start, edit_end = field._extent
5348 if field._allowInsert and sel_to <= edit_end and sel_start + len(paste_text) < edit_end:
5349 new_pos = sel_start + len(paste_text) # store for subsequent positioning
5350 paste_text = paste_text + self._GetValue()[sel_to:edit_end].rstrip()
5351 dbg('paste within insertable field; adjusted paste_text: "%s"' % paste_text, 'end:', edit_end)
5352 sel_to = sel_start + len(paste_text)
5354 # Another special case: paste won't fit, but it's a right-insert field where entire
5355 # non-empty value is selected, and there's room if the selection is expanded leftward:
5356 if( len(paste_text) > sel_to - sel_start
5357 and field._insertRight
5358 and sel_start > edit_start
5359 and sel_to >= edit_end
5360 and not self._GetValue()[edit_start:sel_start].strip() ):
5361 # text won't fit within selection, but left of selection is empty;
5362 # check to see if we can expand selection to accomodate the value:
5363 empty_space = sel_start - edit_start
5364 amount_needed = len(paste_text) - (sel_to - sel_start)
5365 if amount_needed <= empty_space:
5366 sel_start -= amount_needed
5367 dbg('expanded selection to:', (sel_start, sel_to))
5370 # another special case: deal with signed values properly:
5372 signedvalue, signpos, right_signpos = self._getSignedValue()
5373 paste_signpos = paste_text.find('-')
5374 if paste_signpos == -1:
5375 paste_signpos = paste_text.find('(')
5377 # if paste text will result in signed value:
5378 ## dbg('paste_signpos != -1?', paste_signpos != -1)
5379 ## dbg('sel_start:', sel_start, 'signpos:', signpos)
5380 ## dbg('field._insertRight?', field._insertRight)
5381 ## dbg('sel_start - len(paste_text) >= signpos?', sel_start - len(paste_text) <= signpos)
5382 if paste_signpos != -1 and (sel_start <= signpos
5383 or (field._insertRight and sel_start - len(paste_text) <= signpos)):
5387 # remove "sign" from paste text, so we can auto-adjust for sign type after paste:
5388 paste_text = paste_text.replace('-', ' ').replace('(',' ').replace(')','')
5389 dbg('unsigned paste text: "%s"' % paste_text)
5393 # another special case: deal with insert-right fields when selection is empty and
5394 # cursor is at end of field:
5395 ## dbg('field._insertRight?', field._insertRight)
5396 ## dbg('sel_start == edit_end?', sel_start == edit_end)
5397 ## dbg('sel_start', sel_start, 'sel_to', sel_to)
5398 if field._insertRight and sel_start == edit_end and sel_start == sel_to:
5399 sel_start -= len(paste_text)
5402 dbg('adjusted selection:', (sel_start, sel_to))
5405 valid_paste, replacement_text, replace_to = self._validatePaste(paste_text, sel_start, sel_to, raise_on_invalid)
5407 dbg('exception thrown', indent=0)
5411 dbg('paste text not legal for the selection or portion of the control following the cursor;')
5412 if not wx.Validator_IsSilent():
5417 text = self._eraseSelection()
5419 new_text = text[:sel_start] + replacement_text + text[replace_to:]
5421 new_text = string.ljust(new_text,self._masklength)
5423 new_text, signpos, right_signpos = self._getSignedValue(candidate=new_text)
5426 new_text = new_text[:signpos] + '(' + new_text[signpos+1:right_signpos] + ')' + new_text[right_signpos+1:]
5428 new_text = new_text[:signpos] + '-' + new_text[signpos+1:]
5432 dbg("new_text:", '"'+new_text+'"')
5434 if not just_return_value:
5438 wx.CallAfter(self._SetValue, new_text)
5440 new_pos = sel_start + len(replacement_text)
5441 wx.CallAfter(self._SetInsertionPoint, new_pos)
5445 elif just_return_value:
5447 return self._GetValue()
5451 """ Provides an Undo() method in base controls. """
5452 dbg("MaskedEditMixin::_Undo", indent=1)
5453 value = self._GetValue()
5454 prev = self._prevValue
5455 dbg('current value: "%s"' % value)
5456 dbg('previous value: "%s"' % prev)
5458 dbg('no previous value', indent=0)
5462 # Determine what to select: (relies on fixed-length strings)
5463 # (This is a lot harder than it would first appear, because
5464 # of mask chars that stay fixed, and so break up the "diff"...)
5466 # Determine where they start to differ:
5468 length = len(value) # (both are same length in masked control)
5470 while( value[:i] == prev[:i] ):
5475 # handle signed values carefully, so undo from signed to unsigned or vice-versa
5478 text, signpos, right_signpos = self._getSignedValue(candidate=prev)
5480 if prev[signpos] == '(' and prev[right_signpos] == ')':
5484 # eliminate source of "far-end" undo difference if using balanced parens:
5485 value = value.replace(')', ' ')
5486 prev = prev.replace(')', ' ')
5487 elif prev[signpos] == '-':
5492 # Determine where they stop differing in "undo" result:
5493 sm = difflib.SequenceMatcher(None, a=value, b=prev)
5494 i, j, k = sm.find_longest_match(sel_start, length, sel_start, length)
5495 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] )
5497 if k == 0: # no match found; select to end
5500 code_5tuples = sm.get_opcodes()
5501 for op, i1, i2, j1, j2 in code_5tuples:
5502 dbg("%7s value[%d:%d] (%s) prev[%d:%d] (%s)" %
5503 (op, i1, i2, value[i1:i2], j1, j2, prev[j1:j2]))
5506 # look backward through operations needed to produce "previous" value;
5507 # first change wins:
5508 for next_op in range(len(code_5tuples)-1, -1, -1):
5509 op, i1, i2, j1, j2 = code_5tuples[next_op]
5510 dbg('value[i1:i2]: "%s"' % value[i1:i2], 'template[i1:i2] "%s"' % self._template[i1:i2])
5511 if op == 'insert' and prev[j1:j2] != self._template[j1:j2]:
5512 dbg('insert found: selection =>', (j1, j2))
5517 elif op == 'delete' and value[i1:i2] != self._template[i1:i2]:
5518 field = self._FindField(i2)
5519 edit_start, edit_end = field._extent
5520 if field._insertRight and i2 == edit_end:
5526 dbg('delete found: selection =>', (sel_start, sel_to))
5529 elif op == 'replace':
5530 dbg('replace found: selection =>', (j1, j2))
5538 # now go forwards, looking for earlier changes:
5539 for next_op in range(len(code_5tuples)):
5540 op, i1, i2, j1, j2 = code_5tuples[next_op]
5541 field = self._FindField(i1)
5544 elif op == 'replace':
5545 dbg('setting sel_start to', i1)
5548 elif op == 'insert' and not value[i1:i2]:
5549 dbg('forward %s found' % op)
5550 if prev[j1:j2].strip():
5551 dbg('item to insert non-empty; setting sel_start to', j1)
5554 elif not field._insertRight:
5555 dbg('setting sel_start to inserted space:', j1)
5558 elif op == 'delete' and field._insertRight and not value[i1:i2].lstrip():
5561 # we've got what we need
5566 dbg('no insert,delete or replace found (!)')
5567 # do "left-insert"-centric processing of difference based on l.c.s.:
5568 if i == j and j != sel_start: # match starts after start of selection
5569 sel_to = sel_start + (j-sel_start) # select to start of match
5571 sel_to = j # (change ends at j)
5574 # There are several situations where the calculated difference is
5575 # not what we want to select. If changing sign, or just adding
5576 # group characters, we really don't want to highlight the characters
5577 # changed, but instead leave the cursor where it is.
5578 # Also, there a situations in which the difference can be ambiguous;
5581 # current value: 11234
5582 # previous value: 1111234
5584 # Where did the cursor actually lie and which 1s were selected on the delete
5587 # Also, difflib can "get it wrong;" Consider:
5589 # current value: " 128.66"
5590 # previous value: " 121.86"
5592 # difflib produces the following opcodes, which are sub-optimal:
5593 # equal value[0:9] ( 12) prev[0:9] ( 12)
5594 # insert value[9:9] () prev[9:11] (1.)
5595 # equal value[9:10] (8) prev[11:12] (8)
5596 # delete value[10:11] (.) prev[12:12] ()
5597 # equal value[11:12] (6) prev[12:13] (6)
5598 # delete value[12:13] (6) prev[13:13] ()
5600 # This should have been:
5601 # equal value[0:9] ( 12) prev[0:9] ( 12)
5602 # replace value[9:11] (8.6) prev[9:11] (1.8)
5603 # equal value[12:13] (6) prev[12:13] (6)
5605 # But it didn't figure this out!
5607 # To get all this right, we use the previous selection recorded to help us...
5609 if (sel_start, sel_to) != self._prevSelection:
5610 dbg('calculated selection', (sel_start, sel_to), "doesn't match previous", self._prevSelection)
5612 prev_sel_start, prev_sel_to = self._prevSelection
5613 field = self._FindField(sel_start)
5615 if self._signOk and (self._prevValue[sel_start] in ('-', '(', ')')
5616 or self._curValue[sel_start] in ('-', '(', ')')):
5617 # change of sign; leave cursor alone...
5618 sel_start, sel_to = self._prevSelection
5620 elif field._groupdigits and (self._curValue[sel_start:sel_to] == field._groupChar
5621 or self._prevValue[sel_start:sel_to] == field._groupChar):
5622 # do not highlight grouping changes
5623 sel_start, sel_to = self._prevSelection
5626 calc_select_len = sel_to - sel_start
5627 prev_select_len = prev_sel_to - prev_sel_start
5629 dbg('sel_start == prev_sel_start', sel_start == prev_sel_start)
5630 dbg('sel_to > prev_sel_to', sel_to > prev_sel_to)
5632 if prev_select_len >= calc_select_len:
5633 # old selection was bigger; trust it:
5634 sel_start, sel_to = self._prevSelection
5636 elif( sel_to > prev_sel_to # calculated select past last selection
5637 and prev_sel_to < len(self._template) # and prev_sel_to not at end of control
5638 and sel_to == len(self._template) ): # and calculated selection goes to end of control
5640 i, j, k = sm.find_longest_match(prev_sel_to, length, prev_sel_to, length)
5641 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] )
5643 # difflib must not have optimized opcodes properly;
5647 # look for possible ambiguous diff:
5649 # if last change resulted in no selection, test from resulting cursor position:
5650 if prev_sel_start == prev_sel_to:
5651 calc_select_len = sel_to - sel_start
5652 field = self._FindField(prev_sel_start)
5654 # determine which way to search from last cursor position for ambiguous change:
5655 if field._insertRight:
5656 test_sel_start = prev_sel_start
5657 test_sel_to = prev_sel_start + calc_select_len
5659 test_sel_start = prev_sel_start - calc_select_len
5660 test_sel_to = prev_sel_start
5662 test_sel_start, test_sel_to = prev_sel_start, prev_sel_to
5664 dbg('test selection:', (test_sel_start, test_sel_to))
5665 dbg('calc change: "%s"' % self._prevValue[sel_start:sel_to])
5666 dbg('test change: "%s"' % self._prevValue[test_sel_start:test_sel_to])
5668 # if calculated selection spans characters, and same characters
5669 # "before" the previous insertion point are present there as well,
5670 # select the ones related to the last known selection instead.
5671 if( sel_start != sel_to
5672 and test_sel_to < len(self._template)
5673 and self._prevValue[test_sel_start:test_sel_to] == self._prevValue[sel_start:sel_to] ):
5675 sel_start, sel_to = test_sel_start, test_sel_to
5677 dbg('sel_start, sel_to:', sel_start, sel_to)
5678 dbg('previous value: "%s"' % self._prevValue)
5679 self._SetValue(self._prevValue)
5680 self._SetInsertionPoint(sel_start)
5681 self._SetSelection(sel_start, sel_to)
5683 dbg('no difference between previous value')
5687 def _OnClear(self, event):
5688 """ Provides an action for context menu delete operation """
5692 def _OnContextMenu(self, event):
5693 dbg('MaskedEditMixin::OnContextMenu()', indent=1)
5695 menu.Append(wxID_UNDO, "Undo", "")
5696 menu.AppendSeparator()
5697 menu.Append(wxID_CUT, "Cut", "")
5698 menu.Append(wxID_COPY, "Copy", "")
5699 menu.Append(wxID_PASTE, "Paste", "")
5700 menu.Append(wxID_CLEAR, "Delete", "")
5701 menu.AppendSeparator()
5702 menu.Append(wxID_SELECTALL, "Select All", "")
5704 EVT_MENU(menu, wxID_UNDO, self._OnCtrl_Z)
5705 EVT_MENU(menu, wxID_CUT, self._OnCtrl_X)
5706 EVT_MENU(menu, wxID_COPY, self._OnCtrl_C)
5707 EVT_MENU(menu, wxID_PASTE, self._OnCtrl_V)
5708 EVT_MENU(menu, wxID_CLEAR, self._OnClear)
5709 EVT_MENU(menu, wxID_SELECTALL, self._OnCtrl_A)
5711 # ## WSS: The base control apparently handles
5712 # enable/disable of wID_CUT, wxID_COPY, wxID_PASTE
5713 # and wxID_CLEAR menu items even if the menu is one
5714 # we created. However, it doesn't do undo properly,
5715 # so we're keeping track of previous values ourselves.
5716 # Therefore, we have to override the default update for
5717 # that item on the menu:
5718 EVT_UPDATE_UI(self, wxID_UNDO, self._UndoUpdateUI)
5719 self._contextMenu = menu
5721 self.PopupMenu(menu, event.GetPosition())
5723 self._contextMenu = None
5726 def _UndoUpdateUI(self, event):
5727 if self._prevValue is None or self._prevValue == self._curValue:
5728 self._contextMenu.Enable(wxID_UNDO, False)
5730 self._contextMenu.Enable(wxID_UNDO, True)
5733 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
5735 class MaskedTextCtrl( wx.TextCtrl, MaskedEditMixin ):
5737 This is the primary derivation from MaskedEditMixin. It provides
5738 a general masked text control that can be configured with different
5742 def __init__( self, parent, id=-1, value = '',
5743 pos = wx.DefaultPosition,
5744 size = wx.DefaultSize,
5745 style = wx.TE_PROCESS_TAB,
5746 validator=wx.DefaultValidator, ## placeholder provided for data-transfer logic
5747 name = 'maskedTextCtrl',
5748 setupEventHandling = True, ## setup event handling by default
5751 wx.TextCtrl.__init__(self, parent, id, value='',
5752 pos=pos, size = size,
5753 style=style, validator=validator,
5756 self.controlInitialized = True
5757 MaskedEditMixin.__init__( self, name, **kwargs )
5758 self._SetInitialValue(value)
5760 if setupEventHandling:
5761 ## Setup event handlers
5762 self.Bind(wx.EVT_SET_FOCUS, self._OnFocus ) ## defeat automatic full selection
5763 self.Bind(wx.EVT_KILL_FOCUS, self._OnKillFocus ) ## run internal validator
5764 self.Bind(wx.EVT_LEFT_DCLICK, self._OnDoubleClick) ## select field under cursor on dclick
5765 self.Bind(wx.EVT_RIGHT_UP, self._OnContextMenu ) ## bring up an appropriate context menu
5766 self.Bind(wx.EVT_KEY_DOWN, self._OnKeyDown ) ## capture control events not normally seen, eg ctrl-tab.
5767 self.Bind(wx.EVT_CHAR, self._OnChar ) ## handle each keypress
5768 self.Bind(wx.EVT_TEXT, self._OnTextChange ) ## color control appropriately & keep
5769 ## track of previous value for undo
5773 return "<MaskedTextCtrl: %s>" % self.GetValue()
5776 def _GetSelection(self):
5778 Allow mixin to get the text selection of this control.
5779 REQUIRED by any class derived from MaskedEditMixin.
5781 return self.GetSelection()
5783 def _SetSelection(self, sel_start, sel_to):
5785 Allow mixin to set the text selection of this control.
5786 REQUIRED by any class derived from MaskedEditMixin.
5788 ## dbg("MaskedTextCtrl::_SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
5789 return self.SetSelection( sel_start, sel_to )
5791 def SetSelection(self, sel_start, sel_to):
5793 This is just for debugging...
5795 dbg("MaskedTextCtrl::SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
5796 wx.TextCtrl.SetSelection(self, sel_start, sel_to)
5799 def _GetInsertionPoint(self):
5800 return self.GetInsertionPoint()
5802 def _SetInsertionPoint(self, pos):
5803 ## dbg("MaskedTextCtrl::_SetInsertionPoint(%(pos)d)" % locals())
5804 self.SetInsertionPoint(pos)
5806 def SetInsertionPoint(self, pos):
5808 This is just for debugging...
5810 dbg("MaskedTextCtrl::SetInsertionPoint(%(pos)d)" % locals())
5811 wx.TextCtrl.SetInsertionPoint(self, pos)
5814 def _GetValue(self):
5816 Allow mixin to get the raw value of the control with this function.
5817 REQUIRED by any class derived from MaskedEditMixin.
5819 return self.GetValue()
5821 def _SetValue(self, value):
5823 Allow mixin to set the raw value of the control with this function.
5824 REQUIRED by any class derived from MaskedEditMixin.
5826 dbg('MaskedTextCtrl::_SetValue("%(value)s")' % locals(), indent=1)
5827 # Record current selection and insertion point, for undo
5828 self._prevSelection = self._GetSelection()
5829 self._prevInsertionPoint = self._GetInsertionPoint()
5830 wx.TextCtrl.SetValue(self, value)
5833 def SetValue(self, value):
5835 This function redefines the externally accessible .SetValue to be
5836 a smart "paste" of the text in question, so as not to corrupt the
5837 masked control. NOTE: this must be done in the class derived
5838 from the base wx control.
5840 dbg('MaskedTextCtrl::SetValue = "%s"' % value, indent=1)
5843 wx.TextCtrl.SetValue(self, value) # revert to base control behavior
5846 # empty previous contents, replacing entire value:
5847 self._SetInsertionPoint(0)
5848 self._SetSelection(0, self._masklength)
5849 if self._signOk and self._useParens:
5850 signpos = value.find('-')
5852 value = value[:signpos] + '(' + value[signpos+1:].strip() + ')'
5853 elif value.find(')') == -1 and len(value) < self._masklength:
5854 value += ' ' # add place holder for reserved space for right paren
5856 if( len(value) < self._masklength # value shorter than control
5857 and (self._isFloat or self._isInt) # and it's a numeric control
5858 and self._ctrl_constraints._alignRight ): # and it's a right-aligned control
5860 dbg('len(value)', len(value), ' < self._masklength', self._masklength)
5861 # try to intelligently "pad out" the value to the right size:
5862 value = self._template[0:self._masklength - len(value)] + value
5863 if self._isFloat and value.find('.') == -1:
5865 dbg('padded value = "%s"' % value)
5867 # make SetValue behave the same as if you had typed the value in:
5869 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
5871 self._isNeg = False # (clear current assumptions)
5872 value = self._adjustFloat(value)
5874 self._isNeg = False # (clear current assumptions)
5875 value = self._adjustInt(value)
5876 elif self._isDate and not self.IsValid(value) and self._4digityear:
5877 value = self._adjustDate(value, fixcentury=True)
5879 # If date, year might be 2 digits vs. 4; try adjusting it:
5880 if self._isDate and self._4digityear:
5881 dateparts = value.split(' ')
5882 dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
5883 value = string.join(dateparts, ' ')
5884 dbg('adjusted value: "%s"' % value)
5885 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
5887 dbg('exception thrown', indent=0)
5890 self._SetValue(value)
5891 ## dbg('queuing insertion after .SetValue', self._masklength)
5892 wx.CallAfter(self._SetInsertionPoint, self._masklength)
5893 wx.CallAfter(self._SetSelection, self._masklength, self._masklength)
5898 """ Blanks the current control value by replacing it with the default value."""
5899 dbg("MaskedTextCtrl::Clear - value reset to default value (template)")
5903 wx.TextCtrl.Clear(self) # else revert to base control behavior
5908 Allow mixin to refresh the base control with this function.
5909 REQUIRED by any class derived from MaskedEditMixin.
5911 dbg('MaskedTextCtrl::_Refresh', indent=1)
5912 wx.TextCtrl.Refresh(self)
5918 This function redefines the externally accessible .Refresh() to
5919 validate the contents of the masked control as it refreshes.
5920 NOTE: this must be done in the class derived from the base wx control.
5922 dbg('MaskedTextCtrl::Refresh', indent=1)
5928 def _IsEditable(self):
5930 Allow mixin to determine if the base control is editable with this function.
5931 REQUIRED by any class derived from MaskedEditMixin.
5933 return wx.TextCtrl.IsEditable(self)
5938 This function redefines the externally accessible .Cut to be
5939 a smart "erase" of the text in question, so as not to corrupt the
5940 masked control. NOTE: this must be done in the class derived
5941 from the base wx control.
5944 self._Cut() # call the mixin's Cut method
5946 wx.TextCtrl.Cut(self) # else revert to base control behavior
5951 This function redefines the externally accessible .Paste to be
5952 a smart "paste" of the text in question, so as not to corrupt the
5953 masked control. NOTE: this must be done in the class derived
5954 from the base wx control.
5957 self._Paste() # call the mixin's Paste method
5959 wx.TextCtrl.Paste(self, value) # else revert to base control behavior
5964 This function defines the undo operation for the control. (The default
5970 wx.TextCtrl.Undo(self) # else revert to base control behavior
5973 def IsModified(self):
5975 This function overrides the raw wxTextCtrl method, because the
5976 masked edit mixin uses SetValue to change the value, which doesn't
5977 modify the state of this attribute. So, we keep track on each
5978 keystroke to see if the value changes, and if so, it's been
5981 return wx.TextCtrl.IsModified(self) or self.modified
5984 def _CalcSize(self, size=None):
5986 Calculate automatic size if allowed; use base mixin function.
5988 return self._calcSize(size)
5991 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
5992 ## Because calling SetSelection programmatically does not fire EVT_COMBOBOX
5993 ## events, we have to do it ourselves when we auto-complete.
5994 class MaskedComboBoxSelectEvent(wx.PyCommandEvent):
5995 def __init__(self, id, selection = 0, object=None):
5996 wx.PyCommandEvent.__init__(self, wx.EVT_COMMAND_COMBOBOX_SELECTED, id)
5998 self.__selection = selection
5999 self.SetEventObject(object)
6001 def GetSelection(self):
6002 """Retrieve the value of the control at the time
6003 this event was generated."""
6004 return self.__selection
6007 class MaskedComboBox( wx.ComboBox, MaskedEditMixin ):
6009 This masked edit control adds the ability to use a masked input
6010 on a combobox, and do auto-complete of such values.
6012 def __init__( self, parent, id=-1, value = '',
6013 pos = wx.DefaultPosition,
6014 size = wx.DefaultSize,
6016 style = wx.CB_DROPDOWN,
6017 validator = wx.DefaultValidator,
6018 name = "maskedComboBox",
6019 setupEventHandling = True, ## setup event handling by default):
6023 # This is necessary, because wxComboBox currently provides no
6024 # method for determining later if this was specified in the
6025 # constructor for the control...
6026 self.__readonly = style & wx.CB_READONLY == wx.CB_READONLY
6028 kwargs['choices'] = choices ## set up maskededit to work with choice list too
6030 ## Since combobox completion is case-insensitive, always validate same way
6031 if not kwargs.has_key('compareNoCase'):
6032 kwargs['compareNoCase'] = True
6034 MaskedEditMixin.__init__( self, name, **kwargs )
6035 self._choices = self._ctrl_constraints._choices
6036 dbg('self._choices:', self._choices)
6038 if self._ctrl_constraints._alignRight:
6039 choices = [choice.rjust(self._masklength) for choice in choices]
6041 choices = [choice.ljust(self._masklength) for choice in choices]
6043 wx.ComboBox.__init__(self, parent, id, value='',
6044 pos=pos, size = size,
6045 choices=choices, style=style|wx.WANTS_CHARS,
6046 validator=validator,
6049 self.controlInitialized = True
6051 # Set control font - fixed width by default
6055 self.SetClientSize(self._CalcSize())
6058 # ensure value is width of the mask of the control:
6059 if self._ctrl_constraints._alignRight:
6060 value = value.rjust(self._masklength)
6062 value = value.ljust(self._masklength)
6065 self.SetStringSelection(value)
6067 self._SetInitialValue(value)
6070 self._SetKeycodeHandler(wx.WXK_UP, self.OnSelectChoice)
6071 self._SetKeycodeHandler(wx.WXK_DOWN, self.OnSelectChoice)
6073 if setupEventHandling:
6074 ## Setup event handlers
6075 self.Bind(wx.EVT_SET_FOCUS, self._OnFocus ) ## defeat automatic full selection
6076 self.Bind(wx.EVT_KILL_FOCUS, self._OnKillFocus ) ## run internal validator
6077 self.Bind(wx.EVT_LEFT_DCLICK, self._OnDoubleClick) ## select field under cursor on dclick
6078 self.Bind(wx.EVT_RIGHT_UP, self._OnContextMenu ) ## bring up an appropriate context menu
6079 self.Bind(wx.EVT_CHAR, self._OnChar ) ## handle each keypress
6080 self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown ) ## for special processing of up/down keys
6081 self.Bind(wx.EVT_KEY_DOWN, self._OnKeyDown ) ## for processing the rest of the control keys
6082 ## (next in evt chain)
6083 self.Bind(wx.EVT_TEXT, self._OnTextChange ) ## color control appropriately & keep
6084 ## track of previous value for undo
6089 return "<MaskedComboBox: %s>" % self.GetValue()
6092 def _CalcSize(self, size=None):
6094 Calculate automatic size if allowed; augment base mixin function
6095 to account for the selector button.
6097 size = self._calcSize(size)
6098 return (size[0]+20, size[1])
6101 def _GetSelection(self):
6103 Allow mixin to get the text selection of this control.
6104 REQUIRED by any class derived from MaskedEditMixin.
6106 return self.GetMark()
6108 def _SetSelection(self, sel_start, sel_to):
6110 Allow mixin to set the text selection of this control.
6111 REQUIRED by any class derived from MaskedEditMixin.
6113 return self.SetMark( sel_start, sel_to )
6116 def _GetInsertionPoint(self):
6117 return self.GetInsertionPoint()
6119 def _SetInsertionPoint(self, pos):
6120 self.SetInsertionPoint(pos)
6123 def _GetValue(self):
6125 Allow mixin to get the raw value of the control with this function.
6126 REQUIRED by any class derived from MaskedEditMixin.
6128 return self.GetValue()
6130 def _SetValue(self, value):
6132 Allow mixin to set the raw value of the control with this function.
6133 REQUIRED by any class derived from MaskedEditMixin.
6135 # For wxComboBox, ensure that values are properly padded so that
6136 # if varying length choices are supplied, they always show up
6137 # in the window properly, and will be the appropriate length
6138 # to match the mask:
6139 if self._ctrl_constraints._alignRight:
6140 value = value.rjust(self._masklength)
6142 value = value.ljust(self._masklength)
6144 # Record current selection and insertion point, for undo
6145 self._prevSelection = self._GetSelection()
6146 self._prevInsertionPoint = self._GetInsertionPoint()
6147 wx.ComboBox.SetValue(self, value)
6148 # text change events don't always fire, so we check validity here
6149 # to make certain formatting is applied:
6152 def SetValue(self, value):
6154 This function redefines the externally accessible .SetValue to be
6155 a smart "paste" of the text in question, so as not to corrupt the
6156 masked control. NOTE: this must be done in the class derived
6157 from the base wx control.
6160 wx.ComboBox.SetValue(value) # revert to base control behavior
6163 # empty previous contents, replacing entire value:
6164 self._SetInsertionPoint(0)
6165 self._SetSelection(0, self._masklength)
6167 if( len(value) < self._masklength # value shorter than control
6168 and (self._isFloat or self._isInt) # and it's a numeric control
6169 and self._ctrl_constraints._alignRight ): # and it's a right-aligned control
6170 # try to intelligently "pad out" the value to the right size:
6171 value = self._template[0:self._masklength - len(value)] + value
6172 dbg('padded value = "%s"' % value)
6174 # For wxComboBox, ensure that values are properly padded so that
6175 # if varying length choices are supplied, they always show up
6176 # in the window properly, and will be the appropriate length
6177 # to match the mask:
6178 elif self._ctrl_constraints._alignRight:
6179 value = value.rjust(self._masklength)
6181 value = value.ljust(self._masklength)
6184 # make SetValue behave the same as if you had typed the value in:
6186 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
6188 self._isNeg = False # (clear current assumptions)
6189 value = self._adjustFloat(value)
6191 self._isNeg = False # (clear current assumptions)
6192 value = self._adjustInt(value)
6193 elif self._isDate and not self.IsValid(value) and self._4digityear:
6194 value = self._adjustDate(value, fixcentury=True)
6196 # If date, year might be 2 digits vs. 4; try adjusting it:
6197 if self._isDate and self._4digityear:
6198 dateparts = value.split(' ')
6199 dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
6200 value = string.join(dateparts, ' ')
6201 dbg('adjusted value: "%s"' % value)
6202 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
6206 self._SetValue(value)
6207 ## dbg('queuing insertion after .SetValue', self._masklength)
6208 wx.CallAfter(self._SetInsertionPoint, self._masklength)
6209 wx.CallAfter(self._SetSelection, self._masklength, self._masklength)
6214 Allow mixin to refresh the base control with this function.
6215 REQUIRED by any class derived from MaskedEditMixin.
6217 wx.ComboBox.Refresh(self)
6221 This function redefines the externally accessible .Refresh() to
6222 validate the contents of the masked control as it refreshes.
6223 NOTE: this must be done in the class derived from the base wx control.
6229 def _IsEditable(self):
6231 Allow mixin to determine if the base control is editable with this function.
6232 REQUIRED by any class derived from MaskedEditMixin.
6234 return not self.__readonly
6239 This function redefines the externally accessible .Cut to be
6240 a smart "erase" of the text in question, so as not to corrupt the
6241 masked control. NOTE: this must be done in the class derived
6242 from the base wx control.
6245 self._Cut() # call the mixin's Cut method
6247 wx.ComboBox.Cut(self) # else revert to base control behavior
6252 This function redefines the externally accessible .Paste to be
6253 a smart "paste" of the text in question, so as not to corrupt the
6254 masked control. NOTE: this must be done in the class derived
6255 from the base wx control.
6258 self._Paste() # call the mixin's Paste method
6260 wx.ComboBox.Paste(self) # else revert to base control behavior
6265 This function defines the undo operation for the control. (The default
6271 wx.ComboBox.Undo() # else revert to base control behavior
6274 def Append( self, choice, clientData=None ):
6276 This function override is necessary so we can keep track of any additions to the list
6277 of choices, because wxComboBox doesn't have an accessor for the choice list.
6278 The code here is the same as in the SetParameters() mixin function, but is
6279 done for the individual value as appended, so the list can be built incrementally
6280 without speed penalty.
6283 if type(choice) not in (types.StringType, types.UnicodeType):
6284 raise TypeError('%s: choices must be a sequence of strings' % str(self._index))
6285 elif not self.IsValid(choice):
6286 raise ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self._index), choice))
6288 if not self._ctrl_constraints._choices:
6289 self._ctrl_constraints._compareChoices = []
6290 self._ctrl_constraints._choices = []
6291 self._hasList = True
6293 compareChoice = choice.strip()
6295 if self._ctrl_constraints._compareNoCase:
6296 compareChoice = compareChoice.lower()
6298 if self._ctrl_constraints._alignRight:
6299 choice = choice.rjust(self._masklength)
6301 choice = choice.ljust(self._masklength)
6302 if self._ctrl_constraints._fillChar != ' ':
6303 choice = choice.replace(' ', self._fillChar)
6304 dbg('updated choice:', choice)
6307 self._ctrl_constraints._compareChoices.append(compareChoice)
6308 self._ctrl_constraints._choices.append(choice)
6309 self._choices = self._ctrl_constraints._choices # (for shorthand)
6311 if( not self.IsValid(choice) and
6312 (not self._ctrl_constraints.IsEmpty(choice) or
6313 (self._ctrl_constraints.IsEmpty(choice) and self._ctrl_constraints._validRequired) ) ):
6314 raise ValueError('"%s" is not a valid value for the control "%s" as specified.' % (choice, self.name))
6316 wx.ComboBox.Append(self, choice, clientData)
6322 This function override is necessary so we can keep track of any additions to the list
6323 of choices, because wxComboBox doesn't have an accessor for the choice list.
6327 self._ctrl_constraints._autoCompleteIndex = -1
6328 if self._ctrl_constraints._choices:
6329 self.SetCtrlParameters(choices=[])
6330 wx.ComboBox.Clear(self)
6333 def SetCtrlParameters( self, **kwargs ):
6335 Override mixin's default SetCtrlParameters to detect changes in choice list, so
6336 we can update the base control:
6338 MaskedEditMixin.SetCtrlParameters(self, **kwargs )
6339 if( self.controlInitialized
6340 and (kwargs.has_key('choices') or self._choices != self._ctrl_constraints._choices) ):
6341 wx.ComboBox.Clear(self)
6342 self._choices = self._ctrl_constraints._choices
6343 for choice in self._choices:
6344 wx.ComboBox.Append( self, choice )
6349 This function is a hack to make up for the fact that wxComboBox has no
6350 method for returning the selected portion of its edit control. It
6351 works, but has the nasty side effect of generating lots of intermediate
6354 dbg(suspend=1) # turn off debugging around this function
6355 dbg('MaskedComboBox::GetMark', indent=1)
6358 return 0, 0 # no selection possible for editing
6359 ## sel_start, sel_to = wxComboBox.GetMark(self) # what I'd *like* to have!
6360 sel_start = sel_to = self.GetInsertionPoint()
6361 dbg("current sel_start:", sel_start)
6362 value = self.GetValue()
6363 dbg('value: "%s"' % value)
6365 self._ignoreChange = True # tell _OnTextChange() to ignore next event (if any)
6367 wx.ComboBox.Cut(self)
6368 newvalue = self.GetValue()
6369 dbg("value after Cut operation:", newvalue)
6371 if newvalue != value: # something was selected; calculate extent
6372 dbg("something selected")
6373 sel_to = sel_start + len(value) - len(newvalue)
6374 wx.ComboBox.SetValue(self, value) # restore original value and selection (still ignoring change)
6375 wx.ComboBox.SetInsertionPoint(self, sel_start)
6376 wx.ComboBox.SetMark(self, sel_start, sel_to)
6378 self._ignoreChange = False # tell _OnTextChange() to pay attn again
6380 dbg('computed selection:', sel_start, sel_to, indent=0, suspend=0)
6381 return sel_start, sel_to
6384 def SetSelection(self, index):
6386 Necessary for bookkeeping on choice selection, to keep current value
6389 dbg('MaskedComboBox::SetSelection(%d)' % index)
6391 self._prevValue = self._curValue
6392 self._curValue = self._choices[index]
6393 self._ctrl_constraints._autoCompleteIndex = index
6394 wx.ComboBox.SetSelection(self, index)
6397 def OnKeyDown(self, event):
6399 This function is necessary because navigation and control key
6400 events do not seem to normally be seen by the wxComboBox's
6401 EVT_CHAR routine. (Tabs don't seem to be visible no matter
6404 if event.GetKeyCode() in self._nav + self._control:
6408 event.Skip() # let mixin default KeyDown behavior occur
6411 def OnSelectChoice(self, event):
6413 This function appears to be necessary, because the processing done
6414 on the text of the control somehow interferes with the combobox's
6415 selection mechanism for the arrow keys.
6417 dbg('MaskedComboBox::OnSelectChoice', indent=1)
6423 value = self.GetValue().strip()
6425 if self._ctrl_constraints._compareNoCase:
6426 value = value.lower()
6428 if event.GetKeyCode() == wx.WXK_UP:
6432 match_index, partial_match = self._autoComplete(
6434 self._ctrl_constraints._compareChoices,
6436 self._ctrl_constraints._compareNoCase,
6437 current_index = self._ctrl_constraints._autoCompleteIndex)
6438 if match_index is not None:
6439 dbg('setting selection to', match_index)
6440 # issue appropriate event to outside:
6441 self._OnAutoSelect(self._ctrl_constraints, match_index=match_index)
6443 keep_processing = False
6445 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
6446 field = self._FindField(pos)
6447 if self.IsEmpty() or not field._hasList:
6448 dbg('selecting 1st value in list')
6449 self._OnAutoSelect(self._ctrl_constraints, match_index=0)
6451 keep_processing = False
6453 # attempt field-level auto-complete
6455 keep_processing = self._OnAutoCompleteField(event)
6456 dbg('keep processing?', keep_processing, indent=0)
6457 return keep_processing
6460 def _OnAutoSelect(self, field, match_index):
6462 Override mixin (empty) autocomplete handler, so that autocompletion causes
6463 combobox to update appropriately.
6465 dbg('MaskedComboBox::OnAutoSelect', field._index, indent=1)
6466 ## field._autoCompleteIndex = match_index
6467 if field == self._ctrl_constraints:
6468 self.SetSelection(match_index)
6469 dbg('issuing combo selection event')
6470 self.GetEventHandler().ProcessEvent(
6471 MaskedComboBoxSelectEvent( self.GetId(), match_index, self ) )
6473 dbg('field._autoCompleteIndex:', match_index)
6474 dbg('self.GetSelection():', self.GetSelection())
6478 def _OnReturn(self, event):
6480 For wxComboBox, it seems that if you hit return when the dropdown is
6481 dropped, the event that dismisses the dropdown will also blank the
6482 control, because of the implementation of wxComboBox. So here,
6483 we look and if the selection is -1, and the value according to
6484 (the base control!) is a value in the list, then we schedule a
6485 programmatic wxComboBox.SetSelection() call to pick the appropriate
6486 item in the list. (and then do the usual OnReturn bit.)
6488 dbg('MaskedComboBox::OnReturn', indent=1)
6489 dbg('current value: "%s"' % self.GetValue(), 'current index:', self.GetSelection())
6490 if self.GetSelection() == -1 and self.GetValue().lower().strip() in self._ctrl_constraints._compareChoices:
6491 wx.CallAfter(self.SetSelection, self._ctrl_constraints._autoCompleteIndex)
6493 event.m_keyCode = wx.WXK_TAB
6498 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6500 class IpAddrCtrl( MaskedTextCtrl ):
6502 This class is a particular type of MaskedTextCtrl that accepts
6503 and understands the semantics of IP addresses, reformats input
6504 as you move from field to field, and accepts '.' as a navigation
6505 character, so that typing an IP address can be done naturally.
6507 def __init__( self, parent, id=-1, value = '',
6508 pos = wx.DefaultPosition,
6509 size = wx.DefaultSize,
6510 style = wx.TE_PROCESS_TAB,
6511 validator = wx.DefaultValidator,
6512 name = 'IpAddrCtrl',
6513 setupEventHandling = True, ## setup event handling by default
6516 if not kwargs.has_key('mask'):
6517 kwargs['mask'] = mask = "###.###.###.###"
6518 if not kwargs.has_key('formatcodes'):
6519 kwargs['formatcodes'] = 'F_Sr<'
6520 if not kwargs.has_key('validRegex'):
6521 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}"
6524 MaskedTextCtrl.__init__(
6525 self, parent, id=id, value = value,
6528 validator = validator,
6530 setupEventHandling = setupEventHandling,
6533 # set up individual field parameters as well:
6535 field_params['validRegex'] = "( | \d| \d |\d | \d\d|\d\d |\d \d|(1\d\d|2[0-4]\d|25[0-5]))"
6537 # require "valid" string; this prevents entry of any value > 255, but allows
6538 # intermediate constructions; overall control validation requires well-formatted value.
6539 field_params['formatcodes'] = 'V'
6542 for i in self._field_indices:
6543 self.SetFieldParameters(i, **field_params)
6545 # This makes '.' act like tab:
6546 self._AddNavKey('.', handler=self.OnDot)
6547 self._AddNavKey('>', handler=self.OnDot) # for "shift-."
6550 def OnDot(self, event):
6551 dbg('IpAddrCtrl::OnDot', indent=1)
6552 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
6553 oldvalue = self.GetValue()
6554 edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
6555 if not event.ShiftDown():
6556 if pos > edit_start and pos < edit_end:
6557 # clip data in field to the right of pos, if adjusting fields
6558 # when not at delimeter; (assumption == they hit '.')
6559 newvalue = oldvalue[:pos] + ' ' * (edit_end - pos) + oldvalue[edit_end:]
6560 self._SetValue(newvalue)
6561 self._SetInsertionPoint(pos)
6563 return self._OnChangeField(event)
6567 def GetAddress(self):
6568 value = MaskedTextCtrl.GetValue(self)
6569 return value.replace(' ','') # remove spaces from the value
6572 def _OnCtrl_S(self, event):
6573 dbg("IpAddrCtrl::_OnCtrl_S")
6575 print "value:", self.GetAddress()
6578 def SetValue(self, value):
6579 dbg('IpAddrCtrl::SetValue(%s)' % str(value), indent=1)
6580 if type(value) not in (types.StringType, types.UnicodeType):
6582 raise ValueError('%s must be a string', str(value))
6584 bValid = True # assume True
6585 parts = value.split('.')
6591 if not 0 <= len(part) <= 3:
6594 elif part.strip(): # non-empty part
6596 j = string.atoi(part)
6597 if not 0 <= j <= 255:
6601 parts[i] = '%3d' % j
6606 # allow empty sections for SetValue (will result in "invalid" value,
6607 # but this may be useful for initializing the control:
6608 parts[i] = ' ' # convert empty field to 3-char length
6612 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))
6614 dbg('parts:', parts)
6615 value = string.join(parts, '.')
6616 MaskedTextCtrl.SetValue(self, value)
6620 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6621 ## these are helper subroutines:
6623 def movetofloat( origvalue, fmtstring, neg, addseparators=False, sepchar = ',',fillchar=' '):
6624 """ addseparators = add separator character every three numerals if True
6626 fmt0 = fmtstring.split('.')
6629 val = origvalue.split('.')[0].strip()
6630 ret = fillchar * (len(fmt1)-len(val)) + val + "." + "0" * len(fmt2)
6633 return (ret,len(fmt1))
6636 def isDateType( fmtstring ):
6637 """ Checks the mask and returns True if it fits an allowed
6638 date or datetime format.
6640 dateMasks = ("^##/##/####",
6652 reString = "|".join(dateMasks)
6653 filter = re.compile( reString)
6654 if re.match(filter,fmtstring): return True
6657 def isTimeType( fmtstring ):
6658 """ Checks the mask and returns True if it fits an allowed
6661 reTimeMask = "^##:##(:##)?( (AM|PM))?"
6662 filter = re.compile( reTimeMask )
6663 if re.match(filter,fmtstring): return True
6667 def isFloatingPoint( fmtstring):
6668 filter = re.compile("[ ]?[#]+\.[#]+\n")
6669 if re.match(filter,fmtstring+"\n"): return True
6673 def isInteger( fmtstring ):
6674 filter = re.compile("[#]+\n")
6675 if re.match(filter,fmtstring+"\n"): return True
6679 def getDateParts( dateStr, dateFmt ):
6680 if len(dateStr) > 11: clip = dateStr[0:11]
6681 else: clip = dateStr
6682 if clip[-2] not in string.digits:
6683 clip = clip[:-1] # (got part of time; drop it)
6685 dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.')
6686 slices = clip.split(dateSep)
6687 if dateFmt == "MDY":
6688 y,m,d = (slices[2],slices[0],slices[1]) ## year, month, date parts
6689 elif dateFmt == "DMY":
6690 y,m,d = (slices[2],slices[1],slices[0]) ## year, month, date parts
6691 elif dateFmt == "YMD":
6692 y,m,d = (slices[0],slices[1],slices[2]) ## year, month, date parts
6694 y,m,d = None, None, None
6701 def getDateSepChar(dateStr):
6702 clip = dateStr[0:10]
6703 dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.')
6707 def makeDate( year, month, day, dateFmt, dateStr):
6708 sep = getDateSepChar( dateStr)
6709 if dateFmt == "MDY":
6710 return "%s%s%s%s%s" % (month,sep,day,sep,year) ## year, month, date parts
6711 elif dateFmt == "DMY":
6712 return "%s%s%s%s%s" % (day,sep,month,sep,year) ## year, month, date parts
6713 elif dateFmt == "YMD":
6714 return "%s%s%s%s%s" % (year,sep,month,sep,day) ## year, month, date parts
6719 def getYear(dateStr,dateFmt):
6720 parts = getDateParts( dateStr, dateFmt)
6723 def getMonth(dateStr,dateFmt):
6724 parts = getDateParts( dateStr, dateFmt)
6727 def getDay(dateStr,dateFmt):
6728 parts = getDateParts( dateStr, dateFmt)
6731 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6732 class test(wx.PySimpleApp):
6734 from wx.lib.rcsizer import RowColSizer
6735 self.frame = wx.Frame( None, -1, "MaskedEditMixin 0.0.7 Demo Page #1", size = (700,600))
6736 self.panel = wx.Panel( self.frame, -1)
6737 self.sizer = RowColSizer()
6742 id, id1 = wx.NewId(), wx.NewId()
6743 self.command1 = wx.Button( self.panel, id, "&Close" )
6744 self.command2 = wx.Button( self.panel, id1, "&AutoFormats" )
6745 self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5)
6746 self.sizer.Add(self.command2, row=0, col=1, colspan=2, flag=wx.ALL, border = 5)
6747 self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1 )
6748 ## self.panel.SetDefaultItem(self.command1 )
6749 self.panel.Bind(wx.EVT_BUTTON, self.onClickPage, self.command2)
6751 self.check1 = wx.CheckBox( self.panel, -1, "Disallow Empty" )
6752 self.check2 = wx.CheckBox( self.panel, -1, "Highlight Empty" )
6753 self.sizer.Add( self.check1, row=0,col=3, flag=wx.ALL,border=5 )
6754 self.sizer.Add( self.check2, row=0,col=4, flag=wx.ALL,border=5 )
6755 self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck1, self.check1 )
6756 self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck2, self.check2 )
6759 label = """Press ctrl-s in any field to output the value and plain value. Press ctrl-x to clear and re-set any field.
6760 Note that all controls have been auto-sized by including F in the format code.
6761 Try entering nonsensical or partial values in validated fields to see what happens (use ctrl-s to test the valid status)."""
6762 label2 = "\nNote that the State and Last Name fields are list-limited (Name:Smith,Jones,Williams)."
6764 self.label1 = wx.StaticText( self.panel, -1, label)
6765 self.label2 = wx.StaticText( self.panel, -1, "Description")
6766 self.label3 = wx.StaticText( self.panel, -1, "Mask Value")
6767 self.label4 = wx.StaticText( self.panel, -1, "Format")
6768 self.label5 = wx.StaticText( self.panel, -1, "Reg Expr Val. (opt)")
6769 self.label6 = wx.StaticText( self.panel, -1, "wxMaskedEdit Ctrl")
6770 self.label7 = wx.StaticText( self.panel, -1, label2)
6771 self.label7.SetForegroundColour("Blue")
6772 self.label1.SetForegroundColour("Blue")
6773 self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6774 self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6775 self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6776 self.label5.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6777 self.label6.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6779 self.sizer.Add( self.label1, row=1,col=0,colspan=7, flag=wx.ALL,border=5)
6780 self.sizer.Add( self.label7, row=2,col=0,colspan=7, flag=wx.ALL,border=5)
6781 self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5)
6782 self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5)
6783 self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5)
6784 self.sizer.Add( self.label5, row=3,col=3, flag=wx.ALL,border=5)
6785 self.sizer.Add( self.label6, row=3,col=4, flag=wx.ALL,border=5)
6787 # The following list is of the controls for the demo. Feel free to play around with
6790 #description mask excl format regexp range,list,initial
6791 ("Phone No", "(###) ###-#### x:###", "", 'F!^-R', "^\(\d\d\d\) \d\d\d-\d\d\d\d", (),[],''),
6792 ("Last Name Only", "C{14}", "", 'F {list}', '^[A-Z][a-zA-Z]+', (),('Smith','Jones','Williams'),''),
6793 ("Full Name", "C{14}", "", 'F_', '^[A-Z][a-zA-Z]+ [A-Z][a-zA-Z]+', (),[],''),
6794 ("Social Sec#", "###-##-####", "", 'F', "\d{3}-\d{2}-\d{4}", (),[],''),
6795 ("U.S. Zip+4", "#{5}-#{4}", "", 'F', "\d{5}-(\s{4}|\d{4})",(),[],''),
6796 ("U.S. State (2 char)\n(with default)","AA", "", 'F!', "[A-Z]{2}", (),states, 'AZ'),
6797 ("Customer No", "\CAA-###", "", 'F!', "C[A-Z]{2}-\d{3}", (),[],''),
6798 ("Date (MDY) + Time\n(with default)", "##/##/#### ##:## AM", 'BCDEFGHIJKLMNOQRSTUVWXYZ','DFR!',"", (),[], r'03/05/2003 12:00 AM'),
6799 ("Invoice Total", "#{9}.##", "", 'F-R,', "", (),[], ''),
6800 ("Integer (signed)\n(with default)", "#{6}", "", 'F-R', "", (),[], '0 '),
6801 ("Integer (unsigned)\n(with default), 1-399", "######", "", 'F', "", (1,399),[], '1 '),
6802 ("Month selector", "XXX", "", 'F', "", (),
6803 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],""),
6804 ("fraction selector","#/##", "", 'F', "^\d\/\d\d?", (),
6805 ['2/3', '3/4', '1/2', '1/4', '1/8', '1/16', '1/32', '1/64'], "")
6808 for control in controls:
6809 self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL)
6810 self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL)
6811 self.sizer.Add( wx.StaticText( self.panel, -1, control[3]),row=rowcount, col=2,border=5, flag=wx.ALL)
6812 self.sizer.Add( wx.StaticText( self.panel, -1, control[4][:20]),row=rowcount, col=3,border=5, flag=wx.ALL)
6814 if control in controls[:]:#-2]:
6815 newControl = MaskedTextCtrl( self.panel, -1, "",
6817 excludeChars = control[2],
6818 formatcodes = control[3],
6820 validRegex = control[4],
6821 validRange = control[5],
6822 choices = control[6],
6823 defaultValue = control[7],
6825 if control[6]: newControl.SetCtrlParameters(choiceRequired = True)
6827 newControl = MaskedComboBox( self.panel, -1, "",
6828 choices = control[7],
6829 choiceRequired = True,
6831 formatcodes = control[3],
6832 excludeChars = control[2],
6834 validRegex = control[4],
6835 validRange = control[5],
6837 self.editList.append( newControl )
6839 self.sizer.Add( newControl, row=rowcount,col=4,flag=wx.ALL,border=5)
6842 self.sizer.AddGrowableCol(4)
6844 self.panel.SetSizer(self.sizer)
6845 self.panel.SetAutoLayout(1)
6852 def onClick(self, event):
6855 def onClickPage(self, event):
6856 self.page2 = test2(self.frame,-1,"")
6857 self.page2.Show(True)
6859 def _onCheck1(self,event):
6860 """ Set required value on/off """
6861 value = event.IsChecked()
6863 for control in self.editList:
6864 control.SetCtrlParameters(emptyInvalid=True)
6867 for control in self.editList:
6868 control.SetCtrlParameters(emptyInvalid=False)
6870 self.panel.Refresh()
6872 def _onCheck2(self,event):
6873 """ Highlight empty values"""
6874 value = event.IsChecked()
6876 for control in self.editList:
6877 control.SetCtrlParameters( emptyBackgroundColour = 'Aquamarine')
6880 for control in self.editList:
6881 control.SetCtrlParameters( emptyBackgroundColour = 'White')
6883 self.panel.Refresh()
6886 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6888 class test2(wx.Frame):
6889 def __init__(self, parent, id, caption):
6890 wx.Frame.__init__( self, parent, id, "wxMaskedEdit control 0.0.7 Demo Page #2 -- AutoFormats", size = (550,600))
6891 from wx.lib.rcsizer import RowColSizer
6892 self.panel = wx.Panel( self, -1)
6893 self.sizer = RowColSizer()
6899 All these controls have been created by passing a single parameter, the AutoFormat code.
6900 The class contains an internal dictionary of types and formats (autoformats).
6901 To see a great example of validations in action, try entering a bad email address, then tab out."""
6903 self.label1 = wx.StaticText( self.panel, -1, label)
6904 self.label2 = wx.StaticText( self.panel, -1, "Description")
6905 self.label3 = wx.StaticText( self.panel, -1, "AutoFormat Code")
6906 self.label4 = wx.StaticText( self.panel, -1, "wxMaskedEdit Control")
6907 self.label1.SetForegroundColour("Blue")
6908 self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6909 self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6910 self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6912 self.sizer.Add( self.label1, row=1,col=0,colspan=3, flag=wx.ALL,border=5)
6913 self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5)
6914 self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5)
6915 self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5)
6917 id, id1 = wx.NewId(), wx.NewId()
6918 self.command1 = wx.Button( self.panel, id, "&Close")
6919 self.command2 = wx.Button( self.panel, id1, "&Print Formats")
6920 self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1)
6921 self.panel.SetDefaultItem(self.command1)
6922 self.panel.Bind(wx.EVT_BUTTON, self.onClickPrint, self.command2)
6924 # The following list is of the controls for the demo. Feel free to play around with
6927 ("Phone No","USPHONEFULLEXT"),
6928 ("US Date + Time","USDATETIMEMMDDYYYY/HHMM"),
6929 ("US Date MMDDYYYY","USDATEMMDDYYYY/"),
6930 ("Time (with seconds)","TIMEHHMMSS"),
6931 ("Military Time\n(without seconds)","MILTIMEHHMM"),
6932 ("Social Sec#","USSOCIALSEC"),
6933 ("Credit Card","CREDITCARD"),
6934 ("Expiration MM/YY","EXPDATEMMYY"),
6935 ("Percentage","PERCENT"),
6936 ("Person's Age","AGE"),
6937 ("US Zip Code","USZIP"),
6938 ("US Zip+4","USZIPPLUS4"),
6939 ("Email Address","EMAIL"),
6940 ("IP Address", "(derived control IpAddrCtrl)")
6943 for control in controls:
6944 self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL)
6945 self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL)
6946 if control in controls[:-1]:
6947 self.sizer.Add( MaskedTextCtrl( self.panel, -1, "",
6948 autoformat = control[1],
6950 row=rowcount,col=2,flag=wx.ALL,border=5)
6952 self.sizer.Add( IpAddrCtrl( self.panel, -1, "", demo=True ),
6953 row=rowcount,col=2,flag=wx.ALL,border=5)
6956 self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5)
6957 self.sizer.Add(self.command2, row=0, col=1, flag=wx.ALL, border = 5)
6958 self.sizer.AddGrowableCol(3)
6960 self.panel.SetSizer(self.sizer)
6961 self.panel.SetAutoLayout(1)
6963 def onClick(self, event):
6966 def onClickPrint(self, event):
6967 for format in masktags.keys():
6968 sep = "+------------------------+"
6969 print "%s\n%s \n Mask: %s \n RE Validation string: %s\n" % (sep,format, masktags[format]['mask'], masktags[format]['validRegex'])
6971 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6973 if __name__ == "__main__":
6979 ## ===================================
6981 ## 1. WS: For some reason I don't understand, the control is generating two (2)
6982 ## EVT_TEXT events for every one (1) .SetValue() of the underlying control.
6983 ## I've been unsuccessful in determining why or in my efforts to make just one
6984 ## occur. So, I've added a hack to save the last seen value from the
6985 ## control in the EVT_TEXT handler, and if *different*, call event.Skip()
6986 ## to propagate it down the event chain, and let the application see it.
6988 ## 2. WS: MaskedComboBox is deficient in several areas, all having to do with the
6989 ## behavior of the underlying control that I can't fix. The problems are:
6990 ## a) The background coloring doesn't work in the text field of the control;
6991 ## instead, there's a only border around it that assumes the correct color.
6992 ## b) The control will not pass WXK_TAB to the event handler, no matter what
6993 ## I do, and there's no style wxCB_PROCESS_TAB like wxTE_PROCESS_TAB to
6994 ## indicate that we want these events. As a result, MaskedComboBox
6995 ## doesn't do the nice field-tabbing that MaskedTextCtrl does.
6996 ## c) Auto-complete had to be reimplemented for the control because programmatic
6997 ## setting of the value of the text field does not set up the auto complete
6998 ## the way that the control processing keystrokes does. (But I think I've
6999 ## implemented a fairly decent approximation.) Because of this the control
7000 ## also won't auto-complete on dropdown, and there's no event I can catch
7001 ## to work around this problem.
7002 ## d) There is no method provided for getting the selection; the hack I've
7003 ## implemented has its flaws, not the least of which is that due to the
7004 ## strategy that I'm using, the paste buffer is always replaced by the
7005 ## contents of the control's selection when in focus, on each keystroke;
7006 ## this makes it impossible to paste anything into a MaskedComboBox
7007 ## at the moment... :-(
7008 ## e) The other deficient behavior, likely induced by the workaround for (d),
7009 ## is that you can can't shift-left to select more than one character
7013 ## 3. WS: Controls on wxPanels don't seem to pass Shift-WXK_TAB to their
7014 ## EVT_KEY_DOWN or EVT_CHAR event handlers. Until this is fixed in
7015 ## wxWindows, shift-tab won't take you backwards through the fields of
7016 ## a MaskedTextCtrl like it should. Until then Shifted arrow keys will
7017 ## work like shift-tab and tab ought to.
7021 ## =============================##
7022 ## 1. Add Popup list for auto-completable fields that simulates combobox on individual
7023 ## fields. Example: City validates against list of cities, or zip vs zip code list.
7024 ## 2. Allow optional monetary symbols (eg. $, pounds, etc.) at front of a "decimal"
7026 ## 3. Fix shift-left selection for MaskedComboBox.
7027 ## 5. Transform notion of "decimal control" to be less "entire control"-centric,
7028 ## so that monetary symbols can be included and still have the appropriate
7029 ## semantics. (Big job, as currently written, but would make control even
7030 ## more useful for business applications.)
7034 ## ====================
7036 ## (Reported) bugs fixed:
7037 ## 1. Right-click menu allowed "cut" operation that destroyed mask
7038 ## (was implemented by base control)
7039 ## 2. MaskedComboBox didn't allow .Append() of mixed-case values; all
7040 ## got converted to lower case.
7041 ## 3. MaskedComboBox selection didn't deal with spaces in values
7042 ## properly when autocompleting, and didn't have a concept of "next"
7043 ## match for handling choice list duplicates.
7044 ## 4. Size of MaskedComboBox was always default.
7045 ## 5. Email address regexp allowed some "non-standard" things, and wasn't
7047 ## 6. Couldn't easily reset MaskedComboBox contents programmatically.
7048 ## 7. Couldn't set emptyInvalid during construction.
7049 ## 8. Under some versions of wxPython, readonly comboboxes can apparently
7050 ## return a GetInsertionPoint() result (655535), causing masked control
7052 ## 9. Specifying an empty mask caused the controls to traceback.
7053 ## 10. Can't specify float ranges for validRange.
7054 ## 11. '.' from within a the static portion of a restricted IP address
7055 ## destroyed the mask from that point rightward; tab when cursor is
7056 ## before 1st field takes cursor past that field.
7059 ## 12. Added Ctrl-Z/Undo handling, (and implemented context-menu properly.)
7060 ## 13. Added auto-select option on char input for masked controls with
7062 ## 14. Added '>' formatcode, allowing insert within a given or each field
7063 ## as appropriate, rather than requiring "overwrite". This makes single
7064 ## field controls that just have validation rules (eg. EMAIL) much more
7065 ## friendly. The same flag controls left shift when deleting vs just
7066 ## blanking the value, and for right-insert fields, allows right-insert
7067 ## at any non-blank (non-sign) position in the field.
7068 ## 15. Added option to use to indicate negative values for numeric controls.
7069 ## 16. Improved OnFocus handling of numeric controls.
7070 ## 17. Enhanced Home/End processing to allow operation on a field level,
7072 ## 18. Added individual Get/Set functions for control parameters, for
7073 ## simplified integration with Boa Constructor.
7074 ## 19. Standardized "Colour" parameter names to match wxPython, with
7075 ## non-british spellings still supported for backward-compatibility.
7076 ## 20. Added '&' mask specification character for punctuation only (no letters
7078 ## 21. Added (in a separate file) wxMaskedCtrl() factory function to provide
7079 ## unified interface to the masked edit subclasses.
7083 ## 1. Made it possible to configure grouping, decimal and shift-decimal characters,
7084 ## to make controls more usable internationally.
7085 ## 2. Added code to smart "adjust" value strings presented to .SetValue()
7086 ## for right-aligned numeric format controls if they are shorter than
7087 ## than the control width, prepending the missing portion, prepending control
7088 ## template left substring for the missing characters, so that setting
7089 ## numeric values is easier.
7090 ## 3. Renamed SetMaskParameters SetCtrlParameters() (with old name preserved
7091 ## for b-c), as this makes more sense.
7094 ## 1. Fixed .SetValue() to replace the current value, rather than the current
7095 ## selection. Also changed it to generate ValueError if presented with
7096 ## either a value which doesn't follow the format or won't fit. Also made
7097 ## set value adjust numeric and date controls as if user entered the value.
7098 ## Expanded doc explaining how SetValue() works.
7099 ## 2. Fixed EUDATE* autoformats, fixed IsDateType mask list, and added ability to
7100 ## use 3-char months for dates, and EUDATETIME, and EUDATEMILTIME autoformats.
7101 ## 3. Made all date autoformats automatically pick implied "datestyle".
7102 ## 4. Added IsModified override, since base wxTextCtrl never reports modified if
7103 ## .SetValue used to change the value, which is what the masked edit controls
7105 ## 5. Fixed bug in date position adjustment on 2 to 4 digit date conversion when
7106 ## using tab to "leave field" and auto-adjust.
7107 ## 6. Fixed bug in _isCharAllowed() for negative number insertion on pastes,
7108 ## and bug in ._Paste() that didn't account for signs in signed masks either.
7109 ## 7. Fixed issues with _adjustPos for right-insert fields causing improper
7110 ## selection/replacement of values
7111 ## 8. Fixed _OnHome handler to properly handle extending current selection to
7112 ## beginning of control.
7113 ## 9. Exposed all (valid) autoformats to demo, binding descriptions to
7115 ## 10. Fixed a couple of bugs in email regexp.
7116 ## 11. Made maskchardict an instance var, to make mask chars to be more
7117 ## amenable to international use.
7118 ## 12. Clarified meaning of '-' formatcode in doc.
7119 ## 13. Fixed a couple of coding bugs being flagged by Python2.1.
7120 ## 14. Fixed several issues with sign positioning, erasure and validity
7121 ## checking for "numeric" masked controls.
7122 ## 15. Added validation to IpAddrCtrl.SetValue().
7125 ## 1. Changed calling interface to use boolean "useFixedWidthFont" (True by default)
7126 ## vs. literal font facename, and use wxTELETYPE as the font family
7128 ## 2. Switched to use of dbg module vs. locally defined version.
7129 ## 3. Revamped entire control structure to use Field classes to hold constraint
7130 ## and formatting data, to make code more hierarchical, allow for more
7131 ## sophisticated masked edit construction.
7132 ## 4. Better strategy for managing options, and better validation on keywords.
7133 ## 5. Added 'V' format code, which requires that in order for a character
7134 ## to be accepted, it must result in a string that passes the validRegex.
7135 ## 6. Added 'S' format code which means "select entire field when navigating
7137 ## 7. Added 'r' format code to allow "right-insert" fields. (implies 'R'--right-alignment)
7138 ## 8. Added '<' format code to allow fields to require explicit cursor movement
7140 ## 9. Added validFunc option to other validation mechanisms, that allows derived
7141 ## classes to add dynamic validation constraints to the control.
7142 ## 10. Fixed bug in validatePaste code causing possible IndexErrors, and also
7143 ## fixed failure to obey case conversion codes when pasting.
7144 ## 11. Implemented '0' (zero-pad) formatting code, as it wasn't being done anywhere...
7145 ## 12. Removed condition from OnDecimalPoint, so that it always truncates right on '.'
7146 ## 13. Enhanced IpAddrCtrl to use right-insert fields, selection on field traversal,
7147 ## individual field validation to prevent field values > 255, and require explicit
7148 ## tab/. to change fields.
7149 ## 14. Added handler for left double-click to select field under cursor.
7150 ## 15. Fixed handling for "Read-only" styles.
7151 ## 16. Separated signedForegroundColor from 'R' style, and added foregroundColor
7152 ## attribute, for more consistent and controllable coloring.
7153 ## 17. Added retainFieldValidation parameter, allowing top-level constraints
7154 ## such as "validRequired" to be set independently of field-level equivalent.
7155 ## (needed in TimeCtrl for bounds constraints.)
7156 ## 18. Refactored code a bit, cleaned up and commented code more heavily, fixed
7157 ## some of the logic for setting/resetting parameters, eg. fillChar, defaultValue,
7159 ## 19. Fixed maskchar setting for upper/lowercase, to work in all locales.
7163 ## 1. Decimal point behavior restored for decimal and integer type controls:
7164 ## decimal point now trucates the portion > 0.
7165 ## 2. Return key now works like the tab character and moves to the next field,
7166 ## provided no default button is set for the form panel on which the control
7168 ## 3. Support added in _FindField() for subclasses controls (like timecontrol)
7169 ## to determine where the current insertion point is within the mask (i.e.
7170 ## which sub-'field'). See method documentation for more info and examples.
7171 ## 4. Added Field class and support for all constraints to be field-specific
7172 ## in addition to being globally settable for the control.
7173 ## Choices for each field are validated for length and pastability into
7174 ## the field in question, raising ValueError if not appropriate for the control.
7175 ## Also added selective additional validation based on individual field constraints.
7176 ## By default, SHIFT-WXK_DOWN, SHIFT-WXK_UP, WXK_PRIOR and WXK_NEXT all
7177 ## auto-complete fields with choice lists, supplying the 1st entry in
7178 ## the choice list if the field is empty, and cycling through the list in
7179 ## the appropriate direction if already a match. WXK_DOWN will also auto-
7180 ## complete if the field is partially completed and a match can be made.
7181 ## SHIFT-WXK_UP/DOWN will also take you to the next field after any
7182 ## auto-completion performed.
7183 ## 5. Added autoCompleteKeycodes=[] parameters for allowing further
7184 ## customization of the control. Any keycode supplied as a member
7185 ## of the _autoCompleteKeycodes list will be treated like WXK_NEXT. If
7186 ## requireFieldChoice is set, then a valid value from each non-empty
7187 ## choice list will be required for the value of the control to validate.
7188 ## 6. Fixed "auto-sizing" to be relative to the font actually used, rather
7189 ## than making assumptions about character width.
7190 ## 7. Fixed GetMaskParameter(), which was non-functional in previous version.
7191 ## 8. Fixed exceptions raised to provide info on which control had the error.
7192 ## 9. Fixed bug in choice management of MaskedComboBox.
7193 ## 10. Fixed bug in IpAddrCtrl causing traceback if field value was of
7194 ## the form '# #'. Modified control code for IpAddrCtrl so that '.'
7195 ## in the middle of a field clips the rest of that field, similar to
7196 ## decimal and integer controls.
7200 ## 1. "-" is a toggle for sign; "+" now changes - signed numerics to positive.
7201 ## 2. ',' in formatcodes now causes numeric values to be comma-delimited (e.g.333,333).
7202 ## 3. New support for selecting text within the control.(thanks Will Sadkin!)
7203 ## Shift-End and Shift-Home now select text as you would expect
7204 ## Control-Shift-End selects to the end of the mask string, even if value not entered.
7205 ## Control-A selects all *entered* text, Shift-Control-A selects everything in the control.
7206 ## 4. event.Skip() added to onKillFocus to correct remnants when running in Linux (contributed-
7207 ## for some reason I couldn't find the original email but thanks!!!)
7208 ## 5. All major key-handling code moved to their own methods for easier subclassing: OnHome,
7209 ## OnErase, OnEnd, OnCtrl_X, OnCtrl_A, etc.
7210 ## 6. Email and autoformat validations corrected using regex provided by Will Sadkin (thanks!).
7211 ## (The rest of the changes in this version were done by Will Sadkin with permission from Jeff...)
7212 ## 7. New mechanism for replacing default behavior for any given key, using
7213 ## ._SetKeycodeHandler(keycode, func) and ._SetKeyHandler(char, func) now available
7214 ## for easier subclassing of the control.
7215 ## 8. Reworked the delete logic, cut, paste and select/replace logic, as well as some bugs
7216 ## with insertion point/selection modification. Changed Ctrl-X to use standard "cut"
7217 ## semantics, erasing the selection, rather than erasing the entire control.
7218 ## 9. Added option for an "default value" (ie. the template) for use when a single fillChar
7219 ## is not desired in every position. Added IsDefault() function to mean "does the value
7220 ## equal the template?" and modified .IsEmpty() to mean "do all of the editable
7221 ## positions in the template == the fillChar?"
7222 ## 10. Extracted mask logic into mixin, so we can have both MaskedTextCtrl and MaskedComboBox,
7224 ## 11. MaskedComboBox now adds the capability to validate from list of valid values.
7225 ## Example: City validates against list of cities, or zip vs zip code list.
7226 ## 12. Fixed oversight in EVT_TEXT handler that prevented the events from being
7227 ## passed to the next handler in the event chain, causing updates to the
7228 ## control to be invisible to the parent code.
7229 ## 13. Added IPADDR autoformat code, and subclass IpAddrCtrl for controlling tabbing within
7230 ## the control, that auto-reformats as you move between cells.
7231 ## 14. Mask characters [A,a,X,#] can now appear in the format string as literals, by using '\'.
7232 ## 15. It is now possible to specify repeating masks, e.g. #{3}-#{3}-#{14}
7233 ## 16. Fixed major bugs in date validation, due to the fact that
7234 ## wxDateTime.ParseDate is too liberal, and will accept any form that
7235 ## makes any kind of sense, regardless of the datestyle you specified
7236 ## for the control. Unfortunately, the strategy used to fix it only
7237 ## works for versions of wxPython post 2.3.3.1, as a C++ assert box
7238 ## seems to show up on an invalid date otherwise, instead of a catchable
7240 ## 17. Enhanced date adjustment to automatically adjust heuristic based on
7241 ## current year, making last century/this century determination on
7242 ## 2-digit year based on distance between today's year and value;
7243 ## if > 50 year separation, assume last century (and don't assume last
7244 ## century is 20th.)
7245 ## 18. Added autoformats and support for including HHMMSS as well as HHMM for
7246 ## date times, and added similar time, and militaray time autoformats.
7247 ## 19. Enhanced tabbing logic so that tab takes you to the next field if the
7248 ## control is a multi-field control.
7249 ## 20. Added stub method called whenever the control "changes fields", that
7250 ## can be overridden by subclasses (eg. IpAddrCtrl.)
7251 ## 21. Changed a lot of code to be more functionally-oriented so side-effects
7252 ## aren't as problematic when maintaining code and/or adding features.
7253 ## Eg: IsValid() now does not have side-effects; it merely reflects the
7254 ## validity of the value of the control; to determine validity AND recolor
7255 ## the control, _CheckValid() should be used with a value argument of None.
7256 ## Similarly, made most reformatting function take an optional candidate value
7257 ## rather than just using the current value of the control, and only
7258 ## have them change the value of the control if a candidate is not specified.
7259 ## In this way, you can do validation *before* changing the control.
7260 ## 22. Changed validRequired to mean "disallow chars that result in invalid
7261 ## value." (Old meaning now represented by emptyInvalid.) (This was
7262 ## possible once I'd made the changes in (19) above.)
7263 ## 23. Added .SetMaskParameters and .GetMaskParameter methods, so they
7264 ## can be set/modified/retrieved after construction. Removed individual
7265 ## parameter setting functions, in favor of this mechanism, so that
7266 ## all adjustment of the control based on changing parameter values can
7267 ## be handled in one place with unified mechanism.
7268 ## 24. Did a *lot* of testing and fixing re: numeric values. Added ability
7269 ## to type "grouping char" (ie. ',') and validate as appropriate.
7270 ## 25. Fixed ZIPPLUS4 to allow either 5 or 4, but if > 5 must be 9.
7271 ## 26. Fixed assumption about "decimal or integer" masks so that they're only
7272 ## made iff there's no validRegex associated with the field. (This
7273 ## is so things like zipcodes which look like integers can have more
7274 ## restrictive validation (ie. must be 5 digits.)
7275 ## 27. Added a ton more doc strings to explain use and derivation requirements
7276 ## and did regularization of the naming conventions.
7277 ## 28. Fixed a range bug in _adjustKey preventing z from being handled properly.
7278 ## 29. Changed behavior of '.' (and shift-.) in numeric controls to move to
7279 ## reformat the value and move the next field as appropriate. (shift-'.',
7280 ## ie. '>' moves to the previous field.
7283 ## 1. Fixed regex bug that caused autoformat AGE to invalidate any age ending
7285 ## 2. New format character 'D' to trigger date type. If the user enters 2 digits in the
7286 ## year position, the control will expand the value to four digits, using numerals below
7287 ## 50 as 21st century (20+nn) and less than 50 as 20th century (19+nn).
7288 ## Also, new optional parameter datestyle = set to one of {MDY|DMY|YDM}
7289 ## 3. revalid parameter renamed validRegex to conform to standard for all validation
7290 ## parameters (see 2 new ones below).
7291 ## 4. New optional init parameter = validRange. Used only for int/dec (numeric) types.
7292 ## Allows the developer to specify a valid low/high range of values.
7293 ## 5. New optional init parameter = validList. Used for character types. Allows developer
7294 ## to send a list of values to the control to be used for specific validation.
7295 ## See the Last Name Only example - it is list restricted to Smith/Jones/Williams.
7296 ## 6. Date type fields now use wxDateTime's parser to validate the date and time.
7297 ## This works MUCH better than my kludgy regex!! Thanks to Robin Dunn for pointing
7298 ## me toward this solution!
7299 ## 7. Date fields now automatically expand 2-digit years when it can. For example,
7300 ## if the user types "03/10/67", then "67" will auto-expand to "1967". If a two-year
7301 ## date is entered it will be expanded in any case when the user tabs out of the
7303 ## 8. New class functions: SetValidBackgroundColor, SetInvalidBackgroundColor, SetEmptyBackgroundColor,
7304 ## SetSignedForeColor allow accessto override default class coloring behavior.
7305 ## 9. Documentation updated and improved.
7306 ## 10. Demo - page 2 is now a wxFrame class instead of a wxPyApp class. Works better.
7307 ## Two new options (checkboxes) - test highlight empty and disallow empty.
7308 ## 11. Home and End now work more intuitively, moving to the first and last user-entry
7309 ## value, respectively.
7310 ## 12. New class function: SetRequired(bool). Sets the control's entry required flag
7311 ## (i.e. disallow empty values if True).
7314 ## 1. get_plainValue method renamed to GetPlainValue following the wxWindows
7315 ## StudlyCaps(tm) standard (thanks Paul Moore). ;)
7316 ## 2. New format code 'F' causes the control to auto-fit (auto-size) itself
7317 ## based on the length of the mask template.
7318 ## 3. Class now supports "autoformat" codes. These can be passed to the class
7319 ## on instantiation using the parameter autoformat="code". If the code is in
7320 ## the dictionary, it will self set the mask, formatting, and validation string.
7321 ## I have included a number of samples, but I am hoping that someone out there
7322 ## can help me to define a whole bunch more.
7323 ## 4. I have added a second page to the demo (as well as a second demo class, test2)
7324 ## to showcase how autoformats work. The way they self-format and self-size is,
7325 ## I must say, pretty cool.
7326 ## 5. Comments added and some internal cosmetic revisions re: matching the code
7327 ## standards for class submission.
7328 ## 6. Regex validation is now done in real time - field turns yellow immediately
7329 ## and stays yellow until the entered value is valid
7330 ## 7. Cursor now skips over template characters in a more intuitive way (before the
7332 ## 8. Change, Keypress and LostFocus methods added for convenience of subclasses.
7333 ## Developer may use these methods which will be called after EVT_TEXT, EVT_CHAR,
7334 ## and EVT_KILL_FOCUS, respectively.
7335 ## 9. Decimal and numeric handlers have been rewritten and now work more intuitively.
7338 ## 1. New .IsEmpty() method returns True if the control's value is equal to the
7339 ## blank template string
7340 ## 2. Control now supports a new init parameter: revalid. Pass a regular expression
7341 ## that the value will have to match when the control loses focus. If invalid,
7342 ## the control's BackgroundColor will turn yellow, and an internal flag is set (see next).
7343 ## 3. Demo now shows revalid functionality. Try entering a partial value, such as a
7344 ## partial social security number.
7345 ## 4. New .IsValid() value returns True if the control is empty, or if the value matches
7346 ## the revalid expression. If not, .IsValid() returns False.
7347 ## 5. Decimal values now collapse to decimal with '.00' on losefocus if the user never
7348 ## presses the decimal point.
7349 ## 6. Cursor now goes to the beginning of the field if the user clicks in an
7350 ## "empty" field intead of leaving the insertion point in the middle of the
7352 ## 7. New "N" mask type includes upper and lower chars plus digits. a-zA-Z0-9.
7353 ## 8. New formatcodes init parameter replaces other init params and adds functions.
7354 ## String passed to control on init controls:
7358 ## R Show negative #s in red
7360 ## - Signed numerals
7361 ## 0 Numeric fields get leading zeros
7362 ## 9. Ctrl-X in any field clears the current value.
7363 ## 10. Code refactored and made more modular (esp in OnChar method). Should be more
7364 ## easy to read and understand.
7365 ## 11. Demo enhanced.
7366 ## 12. Now has _doc_.
7369 ## 1. GetPlainValue() now returns the value without the template characters;
7370 ## so, for example, a social security number (123-33-1212) would return as
7371 ## 123331212; also removes white spaces from numeric/decimal values, so
7372 ## "- 955.32" is returned "-955.32". Press ctrl-S to see the plain value.
7373 ## 2. Press '.' in an integer style masked control and truncate any trailing digits.
7374 ## 3. Code moderately refactored. Internal names improved for clarity. Additional
7375 ## internal documentation.
7376 ## 4. Home and End keys now supported to move cursor to beginning or end of field.
7377 ## 5. Un-signed integers and decimals now supported.
7378 ## 6. Cosmetic improvements to the demo.
7379 ## 7. Class renamed to MaskedTextCtrl.
7380 ## 8. Can now specify include characters that will override the basic
7381 ## controls: for example, includeChars = "@." for email addresses
7382 ## 9. Added mask character 'C' -> allow any upper or lowercase character
7383 ## 10. .SetSignColor(str:color) sets the foreground color for negative values
7384 ## in signed controls (defaults to red)
7385 ## 11. Overview documentation written.
7388 ## 1. Tab now works properly when pressed in last position
7389 ## 2. Decimal types now work (e.g. #####.##)
7390 ## 3. Signed decimal or numeric values supported (i.e. negative numbers)
7391 ## 4. Negative decimal or numeric values now can show in red.
7392 ## 5. Can now specify an "exclude list" with the excludeChars parameter.
7393 ## See date/time formatted example - you can only enter A or P in the
7394 ## character mask space (i.e. AM/PM).
7395 ## 6. Backspace now works properly, including clearing data from a selected
7396 ## region but leaving template characters intact. Also delete key.
7397 ## 7. Left/right arrows now work properly.
7398 ## 8. Removed EventManager call from test so demo should work with wxPython 2.3.3