1 #----------------------------------------------------------------------------
3 # Authors: Jeff Childers, Will Sadkin
4 # Email: jchilders_98@yahoo.com, wsadkin@parlancecorp.com
6 # Copyright: (c) 2003 by Jeff Childers, Will Sadkin, 2003
7 # Portions: (c) 2002 by Will Sadkin, 2002-2006
9 # License: wxWindows license
10 #----------------------------------------------------------------------------
12 # MaskedEdit controls are based on a suggestion made on [wxPython-Users] by
13 # Jason Hihn, and borrows liberally from Will Sadkin's original masked edit
14 # control for time entry, TimeCtrl (which is now rewritten using this
17 # MaskedEdit controls do not normally use validators, because they do
18 # careful manipulation of the cursor in the text window on each keystroke,
19 # and validation is cursor-position specific, so the control intercepts the
20 # key codes before the validator would fire. However, validators can be
21 # provided to do data transfer to the controls.
23 #----------------------------------------------------------------------------
25 # This file now contains the bulk of the logic behind all masked controls,
26 # the MaskedEditMixin class, the Field class, and the autoformat codes.
28 #----------------------------------------------------------------------------
30 # 03/30/2004 - Will Sadkin (wsadkin@nameconnector.com)
32 # o Split out TextCtrl, ComboBox and IpAddrCtrl into their own files,
33 # o Reorganized code into masked package
35 # 12/09/2003 - Jeff Grimmett (grimmtooth@softhome.net)
37 # o Updated for wx namespace. No guarantees. This is one huge file.
39 # 12/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
41 # o Missed wx.DateTime stuff earlier.
43 # 12/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
45 # o MaskedEditMixin -> MaskedEditMixin
46 # o wxMaskedTextCtrl -> maskedTextCtrl
47 # o wxMaskedComboBoxSelectEvent -> MaskedComboBoxSelectEvent
48 # o wxMaskedComboBox -> MaskedComboBox
49 # o wxIpAddrCtrl -> IpAddrCtrl
50 # o wxTimeCtrl -> TimeCtrl
54 contains MaskedEditMixin class that drives all the other masked controls.
61 is a sublassed text control that can carefully control the user's input
62 based on a mask string you provide.
64 General usage example::
66 control = masked.TextCtrl( win, -1, '', mask = '(###) ###-####')
68 The example above will create a text control that allows only numbers to be
69 entered and then only in the positions indicated in the mask by the # sign.
72 is a similar subclass of wxComboBox that allows the same sort of masking,
73 but also can do auto-complete of values, and can require the value typed
74 to be in the list of choices to be colored appropriately.
77 is actually a factory function for several types of masked edit controls:
79 ================= ==================================================
80 masked.TextCtrl standard masked edit text box
81 masked.ComboBox adds combobox capabilities
82 masked.IpAddrCtrl adds special semantics for IP address entry
83 masked.TimeCtrl special subclass handling lots of types as values
84 masked.NumCtrl special subclass handling numeric values
85 ================= ==================================================
87 It works by looking for a *controlType* parameter in the keyword
88 arguments of the control, to determine what kind of instance to return.
89 If not specified as a keyword argument, the default control type returned
90 will be masked.TextCtrl.
92 Each of the above classes has its own set of arguments, but masked.Ctrl
93 provides a single "unified" interface for masked controls.
95 What follows is a description of how to configure the generic masked.TextCtrl
96 and masked.ComboBox; masked.NumCtrl and masked.TimeCtrl have their own demo
97 pages and interface descriptions.
99 =========================
101 Initialization Parameters
102 -------------------------
104 Allowed mask characters and function:
106 ========= ==========================================================
108 ========= ==========================================================
109 # Allow numeric only (0-9)
110 N Allow letters and numbers (0-9)
111 A Allow uppercase letters only
112 a Allow lowercase letters only
113 C Allow any letter, upper or lower
114 X Allow string.letters, string.punctuation, string.digits
115 & Allow string.punctuation only (doesn't include all unicode symbols)
116 \* Allow any visible character
117 | explicit field boundary (takes no space in the control; allows mix
118 of adjacent mask characters to be treated as separate fields,
119 eg: '&|###' means "field 0 = '&', field 1 = '###'", but there's
120 no fixed characters in between.
121 ========= ==========================================================
124 These controls define these sets of characters using string.letters,
125 string.uppercase, etc. These sets are affected by the system locale
126 setting, so in order to have the masked controls accept characters
127 that are specific to your users' language, your application should
129 For example, to allow international characters to be used in the
130 above masks, you can place the following in your code as part of
131 your application's initialization code::
134 locale.setlocale(locale.LC_ALL, '')
136 The controls now also support (by popular demand) all "visible" characters,
137 by use of the * mask character, including unicode characters above
138 the standard ANSI keycode range.
139 Note: As string.punctuation doesn't typically include all unicode
140 symbols, you will have to use includechars to get some of these into
141 otherwise restricted positions in your control, such as those specified
144 Using these mask characters, a variety of template masks can be built. See
145 the demo for some other common examples include date+time, social security
146 number, etc. If any of these characters are needed as template rather
147 than mask characters, they can be escaped with \, ie. \N means "literal N".
148 (use \\ for literal backslash, as in: r'CCC\\NNN'.)
152 Masks containing only # characters and one optional decimal point
153 character are handled specially, as "numeric" controls. Such
154 controls have special handling for typing the '-' key, handling
155 the "decimal point" character as truncating the integer portion,
156 optionally allowing grouping characters and so forth.
157 There are several parameters and format codes that only make sense
158 when combined with such masks, eg. groupChar, decimalChar, and so
159 forth (see below). These allow you to construct reasonable
160 numeric entry controls.
163 Changing the mask for a control deletes any previous field classes
164 (and any associated validation or formatting constraints) for them.
167 By default, masked edit controls use a fixed width font, so that
168 the mask characters are fixed within the control, regardless of
169 subsequent modifications to the value. Set to False if having
170 the control font be the same as other controls is required. (This is
171 a control-level parameter.)
174 (Applies to unicode systems only) By default, the default unicode encoding
175 used is latin1, or iso-8859-1. If necessary, you can set this control-level
176 parameter to govern the codec used to decode your keyboard inputs.
177 (This is a control-level parameter.)
180 These other properties can be passed to the class when instantiating it:
181 Formatcodes are specified as a string of single character formatting
182 codes that modify behavior of the control::
187 R Right-align field(s)
188 r Right-insert in field(s) (implies R)
189 < Stay in field until explicit navigation out of it
191 > Allow insert/delete within partially filled fields (as
192 opposed to the default "overwrite" mode for fixed-width
193 masked edit controls.) This allows single-field controls
194 or each field within a multi-field control to optionally
195 behave more like standard text controls.
196 (See EMAIL or phone number autoformat examples.)
198 *Note: This also governs whether backspace/delete operations
199 shift contents of field to right of cursor, or just blank the
202 Also, when combined with 'r', this indicates that the field
203 or control allows right insert anywhere within the current
204 non-empty value in the field. (Otherwise right-insert behavior
205 is only performed to when the entire right-insertable field is
206 selected or the cursor is at the right edge of the field.*
209 , Allow grouping character in integer fields of numeric controls
210 and auto-group/regroup digits (if the result fits) when leaving
211 such a field. (If specified, .SetValue() will attempt to
213 ',' is also the default grouping character. To change the
214 grouping character and/or decimal character, use the groupChar
215 and decimalChar parameters, respectively.
216 Note: typing the "decimal point" character in such fields will
217 clip the value to that left of the cursor for integer
218 fields of controls with "integer" or "floating point" masks.
219 If the ',' format code is specified, this will also cause the
220 resulting digits to be regrouped properly, using the current
222 - Prepend and reserve leading space for sign to mask and allow
223 signed values (negative #s shown in red by default.) Can be
224 used with argument useParensForNegatives (see below.)
225 0 integer fields get leading zeros
228 F Auto-Fit: the control calulates its size from
229 the length of the template mask
230 V validate entered chars against validRegex before allowing them
231 to be entered vs. being allowed by basic mask and then having
232 the resulting value just colored as invalid.
233 (See USSTATE autoformat demo for how this can be used.)
234 S select entire field when navigating to new field
239 These controls have two options for the initial state of the control.
240 If a blank control with just the non-editable characters showing
241 is desired, simply leave the constructor variable fillChar as its
242 default (' '). If you want some other character there, simply
243 change the fillChar to that value. Note: changing the control's fillChar
244 will implicitly reset all of the fields' fillChars to this value.
246 If you need different default characters in each mask position,
247 you can specify a defaultValue parameter in the constructor, or
248 set them for each field individually.
249 This value must satisfy the non-editable characters of the mask,
250 but need not conform to the replaceable characters.
255 These parameters govern what character is used to group numbers
256 and is used to indicate the decimal point for numeric format controls.
257 The default groupChar is ',', the default decimalChar is '.'
258 By changing these, you can customize the presentation of numbers
263 formatcodes = ',', groupChar='\'' allows 12'345.34
264 formatcodes = ',', groupChar='.', decimalChar=',' allows 12.345,34
266 (These are control-level parameters.)
269 The default "shiftDecimalChar" (used for "backwards-tabbing" until
270 shift-tab is fixed in wxPython) is '>' (for QUERTY keyboards.) for
271 other keyboards, you may want to customize this, eg '?' for shift ',' on
272 AZERTY keyboards, ':' or ';' for other European keyboards, etc.
273 (This is a control-level parameter.)
275 useParensForNegatives=False
276 This option can be used with signed numeric format controls to
277 indicate signs via () rather than '-'.
278 (This is a control-level parameter.)
281 This option can be used to have a field or the control try to
282 auto-complete on each keystroke if choices have been specified.
284 autoCompleteKeycodes=[]
285 By default, DownArrow, PageUp and PageDown will auto-complete a
286 partially entered field. Shift-DownArrow, Shift-UpArrow, PageUp
287 and PageDown will also auto-complete, but if the field already
288 contains a matched value, these keys will cycle through the list
289 of choices forward or backward as appropriate. Shift-Up and
290 Shift-Down also take you to the next/previous field after any
291 auto-complete action.
293 Additional auto-complete keys can be specified via this parameter.
294 Any keys so specified will act like PageDown.
295 (This is a control-level parameter.)
299 Validating User Input
300 =====================
301 There are a variety of initialization parameters that are used to validate
302 user input. These parameters can apply to the control as a whole, and/or
303 to individual fields:
305 ===================== ==================================================================
306 excludeChars A string of characters to exclude even if otherwise allowed
307 includeChars A string of characters to allow even if otherwise disallowed
308 validRegex Use a regular expression to validate the contents of the text box
309 validRange Pass a rangeas list (low,high) to limit numeric fields/values
310 choices A list of strings that are allowed choices for the control.
311 choiceRequired value must be member of choices list
312 compareNoCase Perform case-insensitive matching when validating against list
313 *Note: for masked.ComboBox, this defaults to True.*
314 emptyInvalid Boolean indicating whether an empty value should be considered
317 validFunc A function to call of the form: bool = func(candidate_value)
318 which will return True if the candidate_value satisfies some
319 external criteria for the control in addition to the the
320 other validation, or False if not. (This validation is
321 applied last in the chain of validations.)
323 validRequired Boolean indicating whether or not keys that are allowed by the
324 mask, but result in an invalid value are allowed to be entered
325 into the control. Setting this to True implies that a valid
326 default value is set for the control.
328 retainFieldValidation False by default; if True, this allows individual fields to
329 retain their own validation constraints independently of any
330 subsequent changes to the control's overall parameters.
331 (This is a control-level parameter.)
333 validator Validators are not normally needed for masked controls, because
334 of the nature of the validation and control of input. However,
335 you can supply one to provide data transfer routines for the
337 raiseOnInvalidPaste False by default; normally a bad paste simply is ignored with a bell;
338 if True, this will cause a ValueError exception to be thrown,
339 with the .value attribute of the exception containing the bad value.
340 ===================== ==================================================================
345 The following parameters have been provided to allow you to change the default
346 coloring behavior of the control. These can be set at construction, or via
347 the .SetCtrlParameters() function. Pass a color as string e.g. 'Yellow':
349 ======================== =======================================================================
350 emptyBackgroundColour Control Background color when identified as empty. Default=White
351 invalidBackgroundColour Control Background color when identified as Not valid. Default=Yellow
352 validBackgroundColour Control Background color when identified as Valid. Default=white
353 ======================== =======================================================================
356 The following parameters control the default foreground color coloring behavior of the
357 control. Pass a color as string e.g. 'Yellow':
359 ======================== ======================================================================
360 foregroundColour Control foreground color when value is not negative. Default=Black
361 signedForegroundColour Control foreground color when value is negative. Default=Red
362 ======================== ======================================================================
367 Each part of the mask that allows user input is considered a field. The fields
368 are represented by their own class instances. You can specify field-specific
369 constraints by constructing or accessing the field instances for the control
370 and then specifying those constraints via parameters.
373 This parameter allows you to specify Field instances containing
374 constraints for the individual fields of a control, eg: local
375 choice lists, validation rules, functions, regexps, etc.
376 It can be either an ordered list or a dictionary. If a list,
377 the fields will be applied as fields 0, 1, 2, etc.
378 If a dictionary, it should be keyed by field index.
379 the values should be a instances of maskededit.Field.
381 Any field not represented by the list or dictionary will be
382 implicitly created by the control.
386 fields = [ Field(formatcodes='_r'), Field('choices=['a', 'b', 'c']) ]
391 1: ( Field(formatcodes='_R', choices=['a', 'b', 'c']),
392 3: ( Field(choices=['01', '02', '03'], choiceRequired=True)
395 The following parameters are available for individual fields, with the
396 same semantics as for the whole control but applied to the field in question:
398 ============== =============================================================================
399 fillChar if set for a field, it will override the control's fillChar for that field
400 groupChar if set for a field, it will override the control's default
401 defaultValue sets field-specific default value; overrides any default from control
402 compareNoCase overrides control's settings
403 emptyInvalid determines whether field is required to be filled at all times
404 validRequired if set, requires field to contain valid value
405 ============== =============================================================================
407 If any of the above parameters are subsequently specified for the control as a
408 whole, that new value will be propagated to each field, unless the
409 retainFieldValidation control-level parameter is set.
411 ============== ==============================
412 formatcodes Augments control's settings
420 ============== ==============================
424 Control Class Functions
425 =======================
426 .GetPlainValue(value=None)
427 Returns the value specified (or the control's text value
428 not specified) without the formatting text.
429 In the example above, might return phone no='3522640075',
430 whereas control.GetValue() would return '(352) 264-0075'
432 Returns the control's value to its default, and places the
433 cursor at the beginning of the control.
435 Does "smart replacement" of passed value into the control, as does
436 the .Paste() method. As with other text entry controls, the
437 .SetValue() text replacement begins at left-edge of the control,
438 with missing mask characters inserted as appropriate.
439 .SetValue will also adjust integer, float or date mask entry values,
440 adding commas, auto-completing years, etc. as appropriate.
441 For "right-aligned" numeric controls, it will also now automatically
442 right-adjust any value whose length is less than the width of the
443 control before attempting to set the value.
444 If a value does not follow the format of the control's mask, or will
445 not fit into the control, a ValueError exception will be raised.
449 mask = '(###) ###-####'
450 .SetValue('1234567890') => '(123) 456-7890'
451 .SetValue('(123)4567890') => '(123) 456-7890'
452 .SetValue('(123)456-7890') => '(123) 456-7890'
453 .SetValue('123/4567-890') => illegal paste; ValueError
455 mask = '#{6}.#{2}', formatcodes = '_,-',
456 .SetValue('111') => ' 111 . '
457 .SetValue(' %9.2f' % -111.12345 ) => ' -111.12'
458 .SetValue(' %9.2f' % 1234.00 ) => ' 1,234.00'
459 .SetValue(' %9.2f' % -1234567.12345 ) => insufficient room; ValueError
461 mask = '#{6}.#{2}', formatcodes = '_,-R' # will right-adjust value for right-aligned control
462 .SetValue('111') => padded value misalignment ValueError: " 111" will not fit
463 .SetValue('%.2f' % 111 ) => ' 111.00'
464 .SetValue('%.2f' % -111.12345 ) => ' -111.12'
468 Returns True if the value specified (or the value of the control
469 if not specified) passes validation tests
471 Returns True if the value specified (or the value of the control
472 if not specified) is equal to an "empty value," ie. all
473 editable characters == the fillChar for their respective fields.
474 .IsDefault(value=None)
475 Returns True if the value specified (or the value of the control
476 if not specified) is equal to the initial value of the control.
479 Recolors the control as appropriate to its current settings.
481 .SetCtrlParameters(\*\*kwargs)
482 This function allows you to set up and/or change the control parameters
483 after construction; it takes a list of key/value pairs as arguments,
484 where the keys can be any of the mask-specific parameters in the constructor.
488 ctl = masked.TextCtrl( self, -1 )
489 ctl.SetCtrlParameters( mask='###-####',
490 defaultValue='555-1212',
493 .GetCtrlParameter(parametername)
494 This function allows you to retrieve the current value of a parameter
497 *Note:* Each of the control parameters can also be set using its
498 own Set and Get function. These functions follow a regular form:
499 All of the parameter names start with lower case; for their
500 corresponding Set/Get function, the parameter name is capitalized.
504 ctl.SetMask('###-####')
505 ctl.SetDefaultValue('555-1212')
506 ctl.GetChoiceRequired()
509 *Note:* After any change in parameters, the choices for the
510 control are reevaluated to ensure that they are still legal. If you
511 have large choice lists, it is therefore more efficient to set parameters
512 before setting the choices available.
514 .SetFieldParameters(field_index, \*\*kwargs)
515 This function allows you to specify change individual field
516 parameters after construction. (Indices are 0-based.)
518 .GetFieldParameter(field_index, parametername)
519 Allows the retrieval of field parameters after construction
522 The control detects certain common constructions. In order to use the signed feature
523 (negative numbers and coloring), the mask has to be all numbers with optionally one
524 decimal point. Without a decimal (e.g. '######', the control will treat it as an integer
525 value. With a decimal (e.g. '###.##'), the control will act as a floating point control
526 (i.e. press decimal to 'tab' to the decimal position). Pressing decimal in the
527 integer control truncates the value. However, for a true numeric control,
528 masked.NumCtrl provides all this, and true numeric input/output support as well.
531 Check your controls by calling each control's .IsValid() function and the
532 .IsEmpty() function to determine which controls have been a) filled in and
533 b) filled in properly.
536 Regular expression validations can be used flexibly and creatively.
537 Take a look at the demo; the zip-code validation succeeds as long as the
538 first five numerals are entered. the last four are optional, but if
539 any are entered, there must be 4 to be valid.
541 masked.Ctrl Configuration
542 =========================
543 masked.Ctrl works by looking for a special *controlType*
544 parameter in the variable arguments of the control, to determine
545 what kind of instance to return.
546 controlType can be one of::
554 These constants are also available individually, ie, you can
555 use either of the following::
557 from wxPython.wx.lib.masked import MaskedCtrl, controlTypes
558 from wxPython.wx.lib.masked import MaskedCtrl, COMBO, TEXT, NUMBER, IPADDR
560 If not specified as a keyword argument, the default controlType is
566 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
571 All methods of the Mixin that are not meant to be exposed to the external
572 interface are prefaced with '_'. Those functions that are primarily
573 intended to be internal subroutines subsequently start with a lower-case
574 letter; those that are primarily intended to be used and/or overridden
575 by derived subclasses start with a capital letter.
577 The following methods must be used and/or defined when deriving a control
578 from MaskedEditMixin. NOTE: if deriving from a *masked edit* control
579 (eg. class IpAddrCtrl(masked.TextCtrl) ), then this is NOT necessary,
580 as it's already been done for you in the base class.
583 This function must be called after the associated base
584 control has been initialized in the subclass __init__
585 function. It sets the initial value of the control,
586 either to the value specified if non-empty, the
587 default value if specified, or the "template" for
588 the empty control as necessary. It will also set/reset
589 the font if necessary and apply formatting to the
590 control at this time.
594 Each class derived from MaskedEditMixin must define
595 the function for getting the start and end of the
596 current text selection. The reason for this is
597 that not all controls have the same function name for
598 doing this; eg. wx.TextCtrl uses .GetSelection(),
599 whereas we had to write a .GetMark() function for
600 wxComboBox, because .GetSelection() for the control
601 gets the currently selected list item from the combo
602 box, and the control doesn't (yet) natively provide
603 a means of determining the text selection.
606 Similarly to _GetSelection, each class derived from
607 MaskedEditMixin must define the function for setting
608 the start and end of the current text selection.
609 (eg. .SetSelection() for masked.TextCtrl, and .SetMark() for
612 ._GetInsertionPoint()
613 ._SetInsertionPoint()
615 For consistency, and because the mixin shouldn't rely
616 on fixed names for any manipulations it does of any of
617 the base controls, we require each class derived from
618 MaskedEditMixin to define these functions as well.
621 ._SetValue() REQUIRED
622 Each class derived from MaskedEditMixin must define
623 the functions used to get and set the raw value of the
625 This is necessary so that recursion doesn't take place
626 when setting the value, and so that the mixin can
627 call the appropriate function after doing all its
628 validation and manipulation without knowing what kind
629 of base control it was mixed in with. To handle undo
630 functionality, the ._SetValue() must record the current
631 selection prior to setting the value.
637 Each class derived from MaskedEditMixin must redefine
638 these functions to call the _Cut(), _Paste(), _Undo()
639 and _SetValue() methods, respectively for the control,
640 so as to prevent programmatic corruption of the control's
641 value. This must be done in each derivation, as the
642 mixin cannot itself override a member of a sibling class.
645 Each class derived from MaskedEditMixin must define
646 the function used to refresh the base control.
649 Each class derived from MaskedEditMixin must redefine
650 this function so that it checks the validity of the
651 control (via self._CheckValid) and then refreshes
652 control using the base class method.
654 ._IsEditable() REQUIRED
655 Each class derived from MaskedEditMixin must define
656 the function used to determine if the base control is
657 editable or not. (For masked.ComboBox, this has to
658 be done with code, rather than specifying the proper
659 function in the base control, as there isn't one...)
660 ._CalcSize() REQUIRED
661 Each class derived from MaskedEditMixin must define
662 the function used to determine how wide the control
663 should be given the mask. (The mixin function
664 ._calcSize() provides a baseline estimate.)
669 Event handlers are "chained", and MaskedEditMixin usually
670 swallows most of the events it sees, thereby preventing any other
671 handlers from firing in the chain. It is therefore required that
672 each class derivation using the mixin to have an option to hook up
673 the event handlers itself or forego this operation and let a
674 subclass of the masked control do so. For this reason, each
675 subclass should probably include the following code:
677 if setupEventHandling:
678 ## Setup event handlers
679 EVT_SET_FOCUS( self, self._OnFocus ) ## defeat automatic full selection
680 EVT_KILL_FOCUS( self, self._OnKillFocus ) ## run internal validator
681 EVT_LEFT_DCLICK(self, self._OnDoubleClick) ## select field under cursor on dclick
682 EVT_RIGHT_UP(self, self._OnContextMenu ) ## bring up an appropriate context menu
683 EVT_KEY_DOWN( self, self._OnKeyDown ) ## capture control events not normally seen, eg ctrl-tab.
684 EVT_CHAR( self, self._OnChar ) ## handle each keypress
685 EVT_TEXT( self, self.GetId(), self._OnTextChange ) ## color control appropriately & keep
686 ## track of previous value for undo
688 where setupEventHandling is an argument to its constructor.
690 These 5 handlers must be "wired up" for the masked edit
691 controls to provide default behavior. (The setupEventHandling
692 is an argument to masked.TextCtrl and masked.ComboBox, so
693 that controls derived from *them* may replace one of these
694 handlers if they so choose.)
696 If your derived control wants to preprocess events before
697 taking action, it should then set up the event handling itself,
698 so it can be first in the event handler chain.
701 The following routines are available to facilitate changing
702 the default behavior of masked edit controls:
704 ._SetKeycodeHandler(keycode, func)
705 ._SetKeyHandler(char, func)
706 Use to replace default handling for any given keycode.
707 func should take the key event as argument and return
708 False if no further action is required to handle the
710 self._SetKeycodeHandler(WXK_UP, self.IncrementValue)
711 self._SetKeyHandler('-', self._OnChangeSign)
713 (Setting a func of None removes any keyhandler for the given key.)
715 "Navigation" keys are assumed to change the cursor position, and
716 therefore don't cause automatic motion of the cursor as insertable
719 ._AddNavKeycode(keycode, handler=None)
720 ._AddNavKey(char, handler=None)
721 Allows controls to specify other keys (and optional handlers)
722 to be treated as navigational characters. (eg. '.' in IpAddrCtrl)
724 ._GetNavKeycodes() Returns the current list of navigational keycodes.
726 ._SetNavKeycodes(key_func_tuples)
727 Allows replacement of the current list of keycode
728 processed as navigation keys, and bind associated
729 optional keyhandlers. argument is a list of key/handler
730 tuples. Passing a value of None for the handler in a
731 given tuple indicates that default processing for the key
734 ._FindField(pos) Returns the Field object associated with this position
737 ._FindFieldExtent(pos, getslice=False, value=None)
738 Returns edit_start, edit_end of the field corresponding
739 to the specified position within the control, and
740 optionally also returns the current contents of that field.
741 If value is specified, it will retrieve the slice the corresponding
742 slice from that value, rather than the current value of the
746 This is, the function that gets called for a given position
747 whenever the cursor is adjusted to leave a given field.
748 By default, it adjusts the year in date fields if mask is a date,
749 It can be overridden by a derived class to
750 adjust the value of the control at that time.
751 (eg. IpAddrCtrl reformats the address in this way.)
753 ._Change() Called by internal EVT_TEXT handler. Return False to force
754 skip of the normal class change event.
755 ._Keypress(key) Called by internal EVT_CHAR handler. Return False to force
756 skip of the normal class keypress event.
757 ._LostFocus() Called by internal EVT_KILL_FOCUS handler
760 This is the default EVT_KEY_DOWN routine; it just checks for
761 "navigation keys", and if event.ControlDown(), it fires the
762 mixin's _OnChar() routine, as such events are not always seen
763 by the "cooked" EVT_CHAR routine.
765 ._OnChar(event) This is the main EVT_CHAR handler for the
768 The following routines are used to handle standard actions
770 _OnArrow(event) used for arrow navigation events
771 _OnCtrl_A(event) 'select all'
772 _OnCtrl_C(event) 'copy' (uses base control function, as copy is non-destructive)
773 _OnCtrl_S(event) 'save' (does nothing)
774 _OnCtrl_V(event) 'paste' - calls _Paste() method, to do smart paste
775 _OnCtrl_X(event) 'cut' - calls _Cut() method, to "erase" selection
776 _OnCtrl_Z(event) 'undo' - resets value to previous value (if any)
778 _OnChangeField(event) primarily used for tab events, but can be
779 used for other keys (eg. '.' in IpAddrCtrl)
781 _OnErase(event) used for backspace and delete
785 The following routine provides a hook back to any class derivations, so that
786 they can react to parameter changes before any value is set/reset as a result of
787 those changes. (eg. masked.ComboBox needs to detect when the choices list is
788 modified, either implicitly or explicitly, so it can reset the base control
789 to have the appropriate choice list *before* the initial value is reset to match.)
791 _OnCtrlParametersChanged()
795 For convenience, each class derived from MaskedEditMixin should
796 define an accessors mixin, so that it exposes only those parameters
797 that make sense for the derivation. This is done with an intermediate
798 level of inheritance, ie:
800 class BaseMaskedTextCtrl( TextCtrl, MaskedEditMixin ):
802 class TextCtrl( BaseMaskedTextCtrl, MaskedEditAccessorsMixin ):
803 class ComboBox( BaseMaskedComboBox, MaskedEditAccessorsMixin ):
804 class NumCtrl( BaseMaskedTextCtrl, MaskedNumCtrlAccessorsMixin ):
805 class IpAddrCtrl( BaseMaskedTextCtrl, IpAddrCtrlAccessorsMixin ):
806 class TimeCtrl( BaseMaskedTextCtrl, TimeCtrlAccessorsMixin ):
810 Each accessors mixin defines Get/Set functions for the base class parameters
811 that are appropriate for that derivation.
812 This allows the base classes to be "more generic," exposing the widest
813 set of options, while not requiring derived classes to be so general.
824 # jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would
825 # be a good place to implement the 2.3 logger class
826 from wx
.tools
.dbg
import Logger
831 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
833 ## Constants for identifying control keys and classes of keys:
835 WXK_CTRL_A
= (ord('A')+1) - ord('A') ## These keys are not already defined in wx
836 WXK_CTRL_C
= (ord('C')+1) - ord('A')
837 WXK_CTRL_S
= (ord('S')+1) - ord('A')
838 WXK_CTRL_V
= (ord('V')+1) - ord('A')
839 WXK_CTRL_X
= (ord('X')+1) - ord('A')
840 WXK_CTRL_Z
= (ord('Z')+1) - ord('A')
843 wx
.WXK_BACK
, wx
.WXK_LEFT
, wx
.WXK_RIGHT
, wx
.WXK_UP
, wx
.WXK_DOWN
, wx
.WXK_TAB
,
844 wx
.WXK_HOME
, wx
.WXK_END
, wx
.WXK_RETURN
, wx
.WXK_PRIOR
, wx
.WXK_NEXT
,
845 wx
.WXK_NUMPAD_LEFT
, wx
.WXK_NUMPAD_RIGHT
, wx
.WXK_NUMPAD_UP
, wx
.WXK_NUMPAD_DOWN
,
846 wx
.WXK_NUMPAD_HOME
, wx
.WXK_NUMPAD_END
, wx
.WXK_NUMPAD_ENTER
, wx
.WXK_NUMPAD_PRIOR
, wx
.WXK_NUMPAD_NEXT
850 wx
.WXK_BACK
, wx
.WXK_DELETE
, wx
.WXK_INSERT
,
851 wx
.WXK_NUMPAD_DELETE
, wx
.WXK_NUMPAD_INSERT
,
852 WXK_CTRL_A
, WXK_CTRL_C
, WXK_CTRL_S
, WXK_CTRL_V
,
853 WXK_CTRL_X
, WXK_CTRL_Z
856 # Because unicode can go over the ansi character range, we need to explicitly test
857 # for all non-visible keystrokes, rather than just assuming a particular range for
858 # visible characters:
859 wx_control_keycodes
= range(32) + list(nav
) + list(control
) + [
860 wx
.WXK_START
, wx
.WXK_LBUTTON
, wx
.WXK_RBUTTON
, wx
.WXK_CANCEL
, wx
.WXK_MBUTTON
,
861 wx
.WXK_CLEAR
, wx
.WXK_SHIFT
, wx
.WXK_CONTROL
, wx
.WXK_MENU
, wx
.WXK_PAUSE
,
862 wx
.WXK_CAPITAL
, wx
.WXK_SELECT
, wx
.WXK_PRINT
, wx
.WXK_EXECUTE
, wx
.WXK_SNAPSHOT
,
863 wx
.WXK_HELP
, wx
.WXK_NUMPAD0
, wx
.WXK_NUMPAD1
, wx
.WXK_NUMPAD2
, wx
.WXK_NUMPAD3
,
864 wx
.WXK_NUMPAD4
, wx
.WXK_NUMPAD5
, wx
.WXK_NUMPAD6
, wx
.WXK_NUMPAD7
, wx
.WXK_NUMPAD8
,
865 wx
.WXK_NUMPAD9
, wx
.WXK_MULTIPLY
, wx
.WXK_ADD
, wx
.WXK_SEPARATOR
, wx
.WXK_SUBTRACT
,
866 wx
.WXK_DECIMAL
, wx
.WXK_DIVIDE
, wx
.WXK_F1
, wx
.WXK_F2
, wx
.WXK_F3
, wx
.WXK_F4
,
867 wx
.WXK_F5
, wx
.WXK_F6
, wx
.WXK_F7
, wx
.WXK_F8
, wx
.WXK_F9
, wx
.WXK_F10
, wx
.WXK_F11
,
868 wx
.WXK_F12
, wx
.WXK_F13
, wx
.WXK_F14
, wx
.WXK_F15
, wx
.WXK_F16
, wx
.WXK_F17
,
869 wx
.WXK_F18
, wx
.WXK_F19
, wx
.WXK_F20
, wx
.WXK_F21
, wx
.WXK_F22
, wx
.WXK_F23
,
870 wx
.WXK_F24
, wx
.WXK_NUMLOCK
, wx
.WXK_SCROLL
, wx
.WXK_PAGEUP
, wx
.WXK_PAGEDOWN
,
871 wx
.WXK_NUMPAD_SPACE
, wx
.WXK_NUMPAD_TAB
, wx
.WXK_NUMPAD_ENTER
, wx
.WXK_NUMPAD_F1
,
872 wx
.WXK_NUMPAD_F2
, wx
.WXK_NUMPAD_F3
, wx
.WXK_NUMPAD_F4
, wx
.WXK_NUMPAD_HOME
,
873 wx
.WXK_NUMPAD_LEFT
, wx
.WXK_NUMPAD_UP
, wx
.WXK_NUMPAD_RIGHT
, wx
.WXK_NUMPAD_DOWN
,
874 wx
.WXK_NUMPAD_PRIOR
, wx
.WXK_NUMPAD_PAGEUP
, wx
.WXK_NUMPAD_NEXT
, wx
.WXK_NUMPAD_PAGEDOWN
,
875 wx
.WXK_NUMPAD_END
, wx
.WXK_NUMPAD_BEGIN
, wx
.WXK_NUMPAD_INSERT
, wx
.WXK_NUMPAD_DELETE
,
876 wx
.WXK_NUMPAD_EQUAL
, wx
.WXK_NUMPAD_MULTIPLY
, wx
.WXK_NUMPAD_ADD
, wx
.WXK_NUMPAD_SEPARATOR
,
877 wx
.WXK_NUMPAD_SUBTRACT
, wx
.WXK_NUMPAD_DECIMAL
, wx
.WXK_NUMPAD_DIVIDE
, wx
.WXK_WINDOWS_LEFT
,
878 wx
.WXK_WINDOWS_RIGHT
, wx
.WXK_WINDOWS_MENU
, wx
.WXK_COMMAND
,
879 # Hardware-specific buttons
880 wx
.WXK_SPECIAL1
, wx
.WXK_SPECIAL2
, wx
.WXK_SPECIAL3
, wx
.WXK_SPECIAL4
, wx
.WXK_SPECIAL5
,
881 wx
.WXK_SPECIAL6
, wx
.WXK_SPECIAL7
, wx
.WXK_SPECIAL8
, wx
.WXK_SPECIAL9
, wx
.WXK_SPECIAL10
,
882 wx
.WXK_SPECIAL11
, wx
.WXK_SPECIAL12
, wx
.WXK_SPECIAL13
, wx
.WXK_SPECIAL14
, wx
.WXK_SPECIAL15
,
883 wx
.WXK_SPECIAL16
, wx
.WXK_SPECIAL17
, wx
.WXK_SPECIAL18
, wx
.WXK_SPECIAL19
, wx
.WXK_SPECIAL20
887 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
889 ## Constants for masking. This is where mask characters
891 ## maskchars used to identify valid mask characters from all others
892 ## # - allow numeric 0-9 only
893 ## A - allow uppercase only. Combine with forceupper to force lowercase to upper
894 ## a - allow lowercase only. Combine with forcelower to force upper to lowercase
895 ## C - allow any letter, upper or lower
896 ## X - allow string.letters, string.punctuation, string.digits
897 ## & - allow string.punctuation only (doesn't include all unicode symbols)
898 ## * - allow any visible character
900 ## Note: locale settings affect what "uppercase", lowercase, etc comprise.
901 ## Note: '|' is not a maskchar, in that it is a mask processing directive, and so
902 ## does not appear here.
904 maskchars
= ("#","A","a","X","C","N",'*','&')
906 for i
in xrange(32, 256):
909 months
= '(01|02|03|04|05|06|07|08|09|10|11|12)'
910 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)'
911 charmonths_dict
= {'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
912 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12}
914 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)'
915 hours
= '(0\d| \d|1[012])'
916 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)'
917 minutes
= """(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|\
918 16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|\
919 36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|\
922 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'
924 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(',')
926 state_names
= ['Alabama','Alaska','Arizona','Arkansas',
927 'California','Colorado','Connecticut',
928 'Delaware','District of Columbia',
929 'Florida','Georgia','Hawaii',
930 'Idaho','Illinois','Indiana','Iowa',
931 'Kansas','Kentucky','Louisiana',
932 'Maine','Maryland','Massachusetts','Michigan',
933 'Minnesota','Mississippi','Missouri','Montana',
934 'Nebraska','Nevada','New Hampshire','New Jersey',
935 'New Mexico','New York','North Carolina','North Dakokta',
936 'Ohio','Oklahoma','Oregon',
937 'Pennsylvania','Puerto Rico','Rhode Island',
938 'South Carolina','South Dakota',
939 'Tennessee','Texas','Utah',
940 'Vermont','Virginia',
941 'Washington','West Virginia',
942 'Wisconsin','Wyoming']
944 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
946 ## The following dictionary defines the current set of autoformats:
950 'mask': "(###) ###-#### x:###",
951 'formatcodes': 'F^->',
952 'validRegex': "^\(\d{3}\) \d{3}-\d{4}",
953 'description': "Phone Number w/opt. ext"
956 'mask': "###-###-#### x:###",
957 'formatcodes': 'F^->',
958 'validRegex': "^\d{3}-\d{3}-\d{4}",
959 'description': "Phone Number\n (w/hyphens and opt. ext)"
962 'mask': "(###) ###-####",
963 'formatcodes': 'F^->',
964 'validRegex': "^\(\d{3}\) \d{3}-\d{4}",
965 'description': "Phone Number only"
968 'mask': "###-###-####",
969 'formatcodes': 'F^->',
970 'validRegex': "^\d{3}-\d{3}-\d{4}",
971 'description': "Phone Number\n(w/hyphens)"
975 'formatcodes': 'F!V',
976 'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string
.join(states
,'|'),
978 'choiceRequired': True,
979 'description': "US State Code"
982 'mask': "ACCCCCCCCCCCCCCCCCCC",
984 'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string
.join(state_names
,'|'),
985 'choices': state_names
,
986 'choiceRequired': True,
987 'description': "US State Name"
990 "USDATETIMEMMDDYYYY/HHMMSS": {
991 'mask': "##/##/#### ##:##:## AM",
992 'excludeChars': am_pm_exclude
,
993 'formatcodes': 'DF!',
994 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
995 'description': "US Date + Time"
997 "USDATETIMEMMDDYYYY-HHMMSS": {
998 'mask': "##-##-#### ##:##:## AM",
999 'excludeChars': am_pm_exclude
,
1000 'formatcodes': 'DF!',
1001 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
1002 'description': "US Date + Time\n(w/hypens)"
1004 "USDATE24HRTIMEMMDDYYYY/HHMMSS": {
1005 'mask': "##/##/#### ##:##:##",
1006 'formatcodes': 'DF',
1007 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1008 'description': "US Date + 24Hr (Military) Time"
1010 "USDATE24HRTIMEMMDDYYYY-HHMMSS": {
1011 'mask': "##-##-#### ##:##:##",
1012 'formatcodes': 'DF',
1013 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1014 'description': "US Date + 24Hr Time\n(w/hypens)"
1016 "USDATETIMEMMDDYYYY/HHMM": {
1017 'mask': "##/##/#### ##:## AM",
1018 'excludeChars': am_pm_exclude
,
1019 'formatcodes': 'DF!',
1020 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
1021 'description': "US Date + Time\n(without seconds)"
1023 "USDATE24HRTIMEMMDDYYYY/HHMM": {
1024 'mask': "##/##/#### ##:##",
1025 'formatcodes': 'DF',
1026 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
,
1027 'description': "US Date + 24Hr Time\n(without seconds)"
1029 "USDATETIMEMMDDYYYY-HHMM": {
1030 'mask': "##-##-#### ##:## AM",
1031 'excludeChars': am_pm_exclude
,
1032 'formatcodes': 'DF!',
1033 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
1034 'description': "US Date + Time\n(w/hypens and w/o secs)"
1036 "USDATE24HRTIMEMMDDYYYY-HHMM": {
1037 'mask': "##-##-#### ##:##",
1038 'formatcodes': 'DF',
1039 'validRegex': '^' + months
+ '-' + days
+ '-' + '\d{4} ' + milhours
+ ':' + minutes
,
1040 'description': "US Date + 24Hr Time\n(w/hyphens and w/o seconds)"
1042 "USDATEMMDDYYYY/": {
1043 'mask': "##/##/####",
1044 'formatcodes': 'DF',
1045 'validRegex': '^' + months
+ '/' + days
+ '/' + '\d{4}',
1046 'description': "US Date\n(MMDDYYYY)"
1050 'formatcodes': 'DF',
1051 'validRegex': '^' + months
+ '/' + days
+ '/\d\d',
1052 'description': "US Date\n(MMDDYY)"
1054 "USDATEMMDDYYYY-": {
1055 'mask': "##-##-####",
1056 'formatcodes': 'DF',
1057 'validRegex': '^' + months
+ '-' + days
+ '-' +'\d{4}',
1058 'description': "MM-DD-YYYY"
1061 "EUDATEYYYYMMDD/": {
1062 'mask': "####/##/##",
1063 'formatcodes': 'DF',
1064 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
,
1065 'description': "YYYY/MM/DD"
1067 "EUDATEYYYYMMDD.": {
1068 'mask': "####.##.##",
1069 'formatcodes': 'DF',
1070 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
,
1071 'description': "YYYY.MM.DD"
1073 "EUDATEDDMMYYYY/": {
1074 'mask': "##/##/####",
1075 'formatcodes': 'DF',
1076 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4}',
1077 'description': "DD/MM/YYYY"
1079 "EUDATEDDMMYYYY.": {
1080 'mask': "##.##.####",
1081 'formatcodes': 'DF',
1082 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4}',
1083 'description': "DD.MM.YYYY"
1085 "EUDATEDDMMMYYYY.": {
1086 'mask': "##.CCC.####",
1087 'formatcodes': 'DF',
1088 'validRegex': '^' + days
+ '.' + charmonths
+ '.' + '\d{4}',
1089 'description': "DD.Month.YYYY"
1091 "EUDATEDDMMMYYYY/": {
1092 'mask': "##/CCC/####",
1093 'formatcodes': 'DF',
1094 'validRegex': '^' + days
+ '/' + charmonths
+ '/' + '\d{4}',
1095 'description': "DD/Month/YYYY"
1098 "EUDATETIMEYYYYMMDD/HHMMSS": {
1099 'mask': "####/##/## ##:##:## AM",
1100 'excludeChars': am_pm_exclude
,
1101 'formatcodes': 'DF!',
1102 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
1103 'description': "YYYY/MM/DD HH:MM:SS"
1105 "EUDATETIMEYYYYMMDD.HHMMSS": {
1106 'mask': "####.##.## ##:##:## AM",
1107 'excludeChars': am_pm_exclude
,
1108 'formatcodes': 'DF!',
1109 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
1110 'description': "YYYY.MM.DD HH:MM:SS"
1112 "EUDATETIMEDDMMYYYY/HHMMSS": {
1113 'mask': "##/##/#### ##:##:## AM",
1114 'excludeChars': am_pm_exclude
,
1115 'formatcodes': 'DF!',
1116 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
1117 'description': "DD/MM/YYYY HH:MM:SS"
1119 "EUDATETIMEDDMMYYYY.HHMMSS": {
1120 'mask': "##.##.#### ##:##:## AM",
1121 'excludeChars': am_pm_exclude
,
1122 'formatcodes': 'DF!',
1123 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
1124 'description': "DD.MM.YYYY HH:MM:SS"
1127 "EUDATETIMEYYYYMMDD/HHMM": {
1128 'mask': "####/##/## ##:## AM",
1129 'excludeChars': am_pm_exclude
,
1130 'formatcodes': 'DF!',
1131 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + hours
+ ':' + minutes
+ ' (A|P)M',
1132 'description': "YYYY/MM/DD HH:MM"
1134 "EUDATETIMEYYYYMMDD.HHMM": {
1135 'mask': "####.##.## ##:## AM",
1136 'excludeChars': am_pm_exclude
,
1137 'formatcodes': 'DF!',
1138 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + hours
+ ':' + minutes
+ ' (A|P)M',
1139 'description': "YYYY.MM.DD HH:MM"
1141 "EUDATETIMEDDMMYYYY/HHMM": {
1142 'mask': "##/##/#### ##:## AM",
1143 'excludeChars': am_pm_exclude
,
1144 'formatcodes': 'DF!',
1145 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
1146 'description': "DD/MM/YYYY HH:MM"
1148 "EUDATETIMEDDMMYYYY.HHMM": {
1149 'mask': "##.##.#### ##:## AM",
1150 'excludeChars': am_pm_exclude
,
1151 'formatcodes': 'DF!',
1152 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + hours
+ ':' + minutes
+ ' (A|P)M',
1153 'description': "DD.MM.YYYY HH:MM"
1156 "EUDATE24HRTIMEYYYYMMDD/HHMMSS": {
1157 'mask': "####/##/## ##:##:##",
1158 'formatcodes': 'DF',
1159 'validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1160 'description': "YYYY/MM/DD 24Hr Time"
1162 "EUDATE24HRTIMEYYYYMMDD.HHMMSS": {
1163 'mask': "####.##.## ##:##:##",
1164 'formatcodes': 'DF',
1165 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1166 'description': "YYYY.MM.DD 24Hr Time"
1168 "EUDATE24HRTIMEDDMMYYYY/HHMMSS": {
1169 'mask': "##/##/#### ##:##:##",
1170 'formatcodes': 'DF',
1171 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1172 'description': "DD/MM/YYYY 24Hr Time"
1174 "EUDATE24HRTIMEDDMMYYYY.HHMMSS": {
1175 'mask': "##.##.#### ##:##:##",
1176 'formatcodes': 'DF',
1177 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + milhours
+ ':' + minutes
+ ':' + seconds
,
1178 'description': "DD.MM.YYYY 24Hr Time"
1180 "EUDATE24HRTIMEYYYYMMDD/HHMM": {
1181 'mask': "####/##/## ##:##",
1182 'formatcodes': 'DF','validRegex': '^' + '\d{4}'+ '/' + months
+ '/' + days
+ ' ' + milhours
+ ':' + minutes
,
1183 'description': "YYYY/MM/DD 24Hr Time\n(w/o seconds)"
1185 "EUDATE24HRTIMEYYYYMMDD.HHMM": {
1186 'mask': "####.##.## ##:##",
1187 'formatcodes': 'DF',
1188 'validRegex': '^' + '\d{4}'+ '.' + months
+ '.' + days
+ ' ' + milhours
+ ':' + minutes
,
1189 'description': "YYYY.MM.DD 24Hr Time\n(w/o seconds)"
1191 "EUDATE24HRTIMEDDMMYYYY/HHMM": {
1192 'mask': "##/##/#### ##:##",
1193 'formatcodes': 'DF',
1194 'validRegex': '^' + days
+ '/' + months
+ '/' + '\d{4} ' + milhours
+ ':' + minutes
,
1195 'description': "DD/MM/YYYY 24Hr Time\n(w/o seconds)"
1197 "EUDATE24HRTIMEDDMMYYYY.HHMM": {
1198 'mask': "##.##.#### ##:##",
1199 'formatcodes': 'DF',
1200 'validRegex': '^' + days
+ '.' + months
+ '.' + '\d{4} ' + milhours
+ ':' + minutes
,
1201 'description': "DD.MM.YYYY 24Hr Time\n(w/o seconds)"
1205 'mask': "##:##:## AM",
1206 'excludeChars': am_pm_exclude
,
1207 'formatcodes': 'TF!',
1208 'validRegex': '^' + hours
+ ':' + minutes
+ ':' + seconds
+ ' (A|P)M',
1209 'description': "HH:MM:SS (A|P)M\n(see TimeCtrl)"
1213 'excludeChars': am_pm_exclude
,
1214 'formatcodes': 'TF!',
1215 'validRegex': '^' + hours
+ ':' + minutes
+ ' (A|P)M',
1216 'description': "HH:MM (A|P)M\n(see TimeCtrl)"
1220 'formatcodes': 'TF',
1221 'validRegex': '^' + milhours
+ ':' + minutes
+ ':' + seconds
,
1222 'description': "24Hr HH:MM:SS\n(see TimeCtrl)"
1226 'formatcodes': 'TF',
1227 'validRegex': '^' + milhours
+ ':' + minutes
,
1228 'description': "24Hr HH:MM\n(see TimeCtrl)"
1231 'mask': "###-##-####",
1233 'validRegex': "\d{3}-\d{2}-\d{4}",
1234 'description': "Social Sec#"
1237 'mask': "####-####-####-####",
1239 'validRegex': "\d{4}-\d{4}-\d{4}-\d{4}",
1240 'description': "Credit Card"
1245 'validRegex': "^" + months
+ "/\d\d",
1246 'description': "Expiration MM/YY"
1251 'validRegex': "^\d{5}",
1252 'description': "US 5-digit zip code"
1255 'mask': "#####-####",
1257 'validRegex': "\d{5}-(\s{4}|\d{4})",
1258 'description': "US zip+4 code"
1263 'validRegex': "^0.\d\d",
1264 'description': "Percentage"
1269 'validRegex': "^[1-9]{1} |[1-9][0-9] |1[0|1|2][0-9]",
1270 'description': "Age"
1273 'mask': "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
1274 'excludeChars': " \\/*&%$#!+='\"",
1275 'formatcodes': "F>",
1276 '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}\]) *$",
1277 'description': "Email address"
1280 'mask': "###.###.###.###",
1281 'formatcodes': 'F_Sr',
1282 '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}",
1283 'description': "IP Address\n(see IpAddrCtrl)"
1287 # build demo-friendly dictionary of descriptions of autoformats
1289 for key
, value
in masktags
.items():
1290 autoformats
.append((key
, value
['description']))
1293 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
1297 This class manages the individual fields in a masked edit control.
1298 Each field has a zero-based index, indicating its position in the
1299 control, an extent, an associated mask, and a plethora of optional
1300 parameters. Fields can be instantiated and then associated with
1301 parent masked controls, in order to provide field-specific configuration.
1302 Alternatively, fields will be implicitly created by the parent control
1303 if not provided at construction, at which point, the fields can then
1304 manipulated by the controls .SetFieldParameters() method.
1307 'index': None, ## which field of mask; set by parent control.
1308 'mask': "", ## mask chars for this field
1309 'extent': (), ## (edit start, edit_end) of field; set by parent control.
1310 'formatcodes': "", ## codes indicating formatting options for the control
1311 'fillChar': ' ', ## used as initial value for each mask position if initial value is not given
1312 'groupChar': ',', ## used with numeric fields; indicates what char groups 3-tuple digits
1313 'decimalChar': '.', ## used with numeric fields; indicates what char separates integer from fraction
1314 'shiftDecimalChar': '>', ## used with numeric fields, indicates what is above the decimal point char on keyboard
1315 'useParensForNegatives': False, ## used with numeric fields, indicates that () should be used vs. - to show negative numbers.
1316 'defaultValue': "", ## use if you want different positional defaults vs. all the same fillChar
1317 'excludeChars': "", ## optional string of chars to exclude even if main mask type does
1318 'includeChars': "", ## optional string of chars to allow even if main mask type doesn't
1319 'validRegex': "", ## optional regular expression to use to validate the control
1320 'validRange': (), ## Optional hi-low range for numerics
1321 'choices': [], ## Optional list for character expressions
1322 'choiceRequired': False, ## If choices supplied this specifies if valid value must be in the list
1323 'compareNoCase': False, ## Optional flag to indicate whether or not to use case-insensitive list search
1324 'autoSelect': False, ## Set to True to try auto-completion on each keystroke:
1325 'validFunc': None, ## Optional function for defining additional, possibly dynamic validation constraints on contrl
1326 'validRequired': False, ## Set to True to disallow input that results in an invalid value
1327 'emptyInvalid': False, ## Set to True to make EMPTY = INVALID
1328 'description': "", ## primarily for autoformats, but could be useful elsewhere
1329 'raiseOnInvalidPaste': False, ## if True, paste into field will cause ValueError
1332 # This list contains all parameters that when set at the control level should
1333 # propagate down to each field:
1334 propagating_params
= ('fillChar', 'groupChar', 'decimalChar','useParensForNegatives',
1335 'compareNoCase', 'emptyInvalid', 'validRequired', 'raiseOnInvalidPaste')
1337 def __init__(self
, **kwargs
):
1339 This is the "constructor" for setting up parameters for fields.
1340 a field_index of -1 is used to indicate "the entire control."
1342 #### dbg('Field::Field', indent=1)
1343 # Validate legitimate set of parameters:
1344 for key
in kwargs
.keys():
1345 if key
not in Field
.valid_params
.keys():
1347 ae
= AttributeError('invalid parameter "%s"' % (key
))
1351 # Set defaults for each parameter for this instance, and fully
1352 # populate initial parameter list for configuration:
1353 for key
, value
in Field
.valid_params
.items():
1354 setattr(self
, '_' + key
, copy
.copy(value
))
1355 if not kwargs
.has_key(key
):
1356 kwargs
[key
] = copy
.copy(value
)
1358 self
._autoCompleteIndex
= -1
1359 self
._SetParameters
(**kwargs
)
1360 self
._ValidateParameters
(**kwargs
)
1365 def _SetParameters(self
, **kwargs
):
1367 This function can be used to set individual or multiple parameters for
1368 a masked edit field parameter after construction.
1371 ## dbg('maskededit.Field::_SetParameters', indent=1)
1372 # Validate keyword arguments:
1373 for key
in kwargs
.keys():
1374 if key
not in Field
.valid_params
.keys():
1375 ## dbg(indent=0, suspend=0)
1376 ae
= AttributeError('invalid keyword argument "%s"' % key
)
1380 ## if self._index is not None: dbg('field index:', self._index)
1381 ## dbg('parameters:', indent=1)
1382 for key
, value
in kwargs
.items():
1383 ## dbg('%s:' % key, value)
1388 old_fillChar
= self
._fillChar
# store so we can change choice lists accordingly if it changes
1390 # First, Assign all parameters specified:
1391 for key
in Field
.valid_params
.keys():
1392 if kwargs
.has_key(key
):
1393 setattr(self
, '_' + key
, kwargs
[key
] )
1395 if kwargs
.has_key('formatcodes'): # (set/changed)
1396 self
._forceupper
= '!' in self
._formatcodes
1397 self
._forcelower
= '^' in self
._formatcodes
1398 self
._groupdigits
= ',' in self
._formatcodes
1399 self
._okSpaces
= '_' in self
._formatcodes
1400 self
._padZero
= '0' in self
._formatcodes
1401 self
._autofit
= 'F' in self
._formatcodes
1402 self
._insertRight
= 'r' in self
._formatcodes
1403 self
._allowInsert
= '>' in self
._formatcodes
1404 self
._alignRight
= 'R' in self
._formatcodes
or 'r' in self
._formatcodes
1405 self
._moveOnFieldFull
= not '<' in self
._formatcodes
1406 self
._selectOnFieldEntry
= 'S' in self
._formatcodes
1408 if kwargs
.has_key('groupChar'):
1409 self
._groupChar
= kwargs
['groupChar']
1410 if kwargs
.has_key('decimalChar'):
1411 self
._decimalChar
= kwargs
['decimalChar']
1412 if kwargs
.has_key('shiftDecimalChar'):
1413 self
._shiftDecimalChar
= kwargs
['shiftDecimalChar']
1415 if kwargs
.has_key('formatcodes') or kwargs
.has_key('validRegex'):
1416 self
._regexMask
= 'V' in self
._formatcodes
and self
._validRegex
1418 if kwargs
.has_key('fillChar'):
1419 self
._old
_fillChar
= old_fillChar
1420 #### dbg("self._old_fillChar: '%s'" % self._old_fillChar)
1422 if kwargs
.has_key('mask') or kwargs
.has_key('validRegex'): # (set/changed)
1423 self
._isInt
= _isInteger(self
._mask
)
1424 ## dbg('isInt?', self._isInt, 'self._mask:"%s"' % self._mask)
1426 ## dbg(indent=0, suspend=0)
1429 def _ValidateParameters(self
, **kwargs
):
1431 This function can be used to validate individual or multiple parameters for
1432 a masked edit field parameter after construction.
1435 ## dbg('maskededit.Field::_ValidateParameters', indent=1)
1436 ## if self._index is not None: dbg('field index:', self._index)
1437 #### dbg('parameters:', indent=1)
1438 ## for key, value in kwargs.items():
1439 #### dbg('%s:' % key, value)
1441 #### dbg("self._old_fillChar: '%s'" % self._old_fillChar)
1443 # Verify proper numeric format params:
1444 if self
._groupdigits
and self
._groupChar
== self
._decimalChar
:
1445 ## dbg(indent=0, suspend=0)
1446 ae
= AttributeError("groupChar '%s' cannot be the same as decimalChar '%s'" % (self
._groupChar
, self
._decimalChar
))
1447 ae
.attribute
= self
._groupChar
1451 # Now go do validation, semantic and inter-dependency parameter processing:
1452 if kwargs
.has_key('choices') or kwargs
.has_key('compareNoCase') or kwargs
.has_key('choiceRequired'): # (set/changed)
1454 self
._compareChoices
= [choice
.strip() for choice
in self
._choices
]
1456 if self
._compareNoCase
and self
._choices
:
1457 self
._compareChoices
= [item
.lower() for item
in self
._compareChoices
]
1459 if kwargs
.has_key('choices'):
1460 self
._autoCompleteIndex
= -1
1463 if kwargs
.has_key('validRegex'): # (set/changed)
1464 if self
._validRegex
:
1466 if self
._compareNoCase
:
1467 self
._filter
= re
.compile(self
._validRegex
, re
.IGNORECASE
)
1469 self
._filter
= re
.compile(self
._validRegex
)
1471 ## dbg(indent=0, suspend=0)
1472 raise TypeError('%s: validRegex "%s" not a legal regular expression' % (str(self
._index
), self
._validRegex
))
1476 if kwargs
.has_key('validRange'): # (set/changed)
1477 self
._hasRange
= False
1480 if self
._validRange
:
1481 if type(self
._validRange
) != types
.TupleType
or len( self
._validRange
)!= 2 or self
._validRange
[0] > self
._validRange
[1]:
1482 ## dbg(indent=0, suspend=0)
1483 raise TypeError('%s: validRange %s parameter must be tuple of form (a,b) where a <= b'
1484 % (str(self
._index
), repr(self
._validRange
)) )
1486 self
._hasRange
= True
1487 self
._rangeLow
= self
._validRange
[0]
1488 self
._rangeHigh
= self
._validRange
[1]
1490 if kwargs
.has_key('choices') or (len(self
._choices
) and len(self
._choices
[0]) != len(self
._mask
)): # (set/changed)
1491 self
._hasList
= False
1492 if self
._choices
and type(self
._choices
) not in (types
.TupleType
, types
.ListType
):
1493 ## dbg(indent=0, suspend=0)
1494 raise TypeError('%s: choices must be a sequence of strings' % str(self
._index
))
1495 elif len( self
._choices
) > 0:
1496 for choice
in self
._choices
:
1497 if type(choice
) not in (types
.StringType
, types
.UnicodeType
):
1498 ## dbg(indent=0, suspend=0)
1499 raise TypeError('%s: choices must be a sequence of strings' % str(self
._index
))
1501 length
= len(self
._mask
)
1502 ## dbg('len(%s)' % self._mask, length, 'len(self._choices):', len(self._choices), 'length:', length, 'self._alignRight?', self._alignRight)
1503 if len(self
._choices
) and length
:
1504 if len(self
._choices
[0]) > length
:
1505 # changed mask without respecifying choices; readjust the width as appropriate:
1506 self
._choices
= [choice
.strip() for choice
in self
._choices
]
1507 if self
._alignRight
:
1508 self
._choices
= [choice
.rjust( length
) for choice
in self
._choices
]
1510 self
._choices
= [choice
.ljust( length
) for choice
in self
._choices
]
1511 ## dbg('aligned choices:', self._choices)
1513 if hasattr(self
, '_template'):
1514 # Verify each choice specified is valid:
1515 for choice
in self
._choices
:
1516 if self
.IsEmpty(choice
) and not self
._validRequired
:
1517 # allow empty values even if invalid, (just colored differently)
1519 if not self
.IsValid(choice
):
1520 ## dbg(indent=0, suspend=0)
1521 ve
= ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self
._index
), choice
))
1524 self
._hasList
= True
1526 #### dbg("kwargs.has_key('fillChar')?", kwargs.has_key('fillChar'), "len(self._choices) > 0?", len(self._choices) > 0)
1527 #### dbg("self._old_fillChar:'%s'" % self._old_fillChar, "self._fillChar: '%s'" % self._fillChar)
1528 if kwargs
.has_key('fillChar') and len(self
._choices
) > 0:
1529 if kwargs
['fillChar'] != ' ':
1530 self
._choices
= [choice
.replace(' ', self
._fillChar
) for choice
in self
._choices
]
1532 self
._choices
= [choice
.replace(self
._old
_fillChar
, self
._fillChar
) for choice
in self
._choices
]
1533 ## dbg('updated choices:', self._choices)
1536 if kwargs
.has_key('autoSelect') and kwargs
['autoSelect']:
1537 if not self
._hasList
:
1538 ## dbg('no list to auto complete; ignoring "autoSelect=True"')
1539 self
._autoSelect
= False
1541 # reset field validity assumption:
1543 ## dbg(indent=0, suspend=0)
1546 def _GetParameter(self
, paramname
):
1548 Routine for retrieving the value of any given parameter
1550 if Field
.valid_params
.has_key(paramname
):
1551 return getattr(self
, '_' + paramname
)
1553 TypeError('Field._GetParameter: invalid parameter "%s"' % key
)
1556 def IsEmpty(self
, slice):
1558 Indicates whether the specified slice is considered empty for the
1561 ## dbg('Field::IsEmpty("%s")' % slice, indent=1)
1562 if not hasattr(self
, '_template'):
1564 raise AttributeError('_template')
1566 ## dbg('self._template: "%s"' % self._template)
1567 ## dbg('self._defaultValue: "%s"' % str(self._defaultValue))
1568 if slice == self
._template
and not self
._defaultValue
:
1572 elif slice == self
._template
:
1574 for pos
in range(len(self
._template
)):
1575 #### dbg('slice[%(pos)d] != self._fillChar?' %locals(), slice[pos] != self._fillChar[pos])
1576 if slice[pos
] not in (' ', self
._fillChar
):
1579 ## dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals(), indent=0)
1582 ## dbg("IsEmpty? 0 (slice doesn't match template)", indent=0)
1586 def IsValid(self
, slice):
1588 Indicates whether the specified slice is considered a valid value for the
1592 ## dbg('Field[%s]::IsValid("%s")' % (str(self._index), slice), indent=1)
1593 valid
= True # assume true to start
1595 if self
.IsEmpty(slice):
1596 ## dbg(indent=0, suspend=0)
1597 if self
._emptyInvalid
:
1602 elif self
._hasList
and self
._choiceRequired
:
1603 ## dbg("(member of list required)")
1604 # do case-insensitive match on list; strip surrounding whitespace from slice (already done for choices):
1605 if self
._fillChar
!= ' ':
1606 slice = slice.replace(self
._fillChar
, ' ')
1607 ## dbg('updated slice:"%s"' % slice)
1608 compareStr
= slice.strip()
1610 if self
._compareNoCase
:
1611 compareStr
= compareStr
.lower()
1612 valid
= compareStr
in self
._compareChoices
1614 elif self
._hasRange
and not self
.IsEmpty(slice):
1615 ## dbg('validating against range')
1617 # allow float as well as int ranges (int comparisons for free.)
1618 valid
= self
._rangeLow
<= float(slice) <= self
._rangeHigh
1622 elif self
._validRegex
and self
._filter
:
1623 ## dbg('validating against regex')
1624 valid
= (re
.match( self
._filter
, slice) is not None)
1626 if valid
and self
._validFunc
:
1627 ## dbg('validating against supplied function')
1628 valid
= self
._validFunc
(slice)
1629 ## dbg('valid?', valid, indent=0, suspend=0)
1633 def _AdjustField(self
, slice):
1634 """ 'Fixes' an integer field. Right or left-justifies, as required."""
1635 ## dbg('Field::_AdjustField("%s")' % slice, indent=1)
1636 length
= len(self
._mask
)
1637 #### dbg('length(self._mask):', length)
1638 #### dbg('self._useParensForNegatives?', self._useParensForNegatives)
1640 if self
._useParensForNegatives
:
1641 signpos
= slice.find('(')
1642 right_signpos
= slice.find(')')
1643 intStr
= slice.replace('(', '').replace(')', '') # drop sign, if any
1645 signpos
= slice.find('-')
1646 intStr
= slice.replace( '-', '' ) # drop sign, if any
1649 intStr
= intStr
.replace(' ', '') # drop extra spaces
1650 intStr
= string
.replace(intStr
,self
._fillChar
,"") # drop extra fillchars
1651 intStr
= string
.replace(intStr
,"-","") # drop sign, if any
1652 intStr
= string
.replace(intStr
, self
._groupChar
, "") # lose commas/dots
1653 #### dbg('intStr:"%s"' % intStr)
1654 start
, end
= self
._extent
1655 field_len
= end
- start
1656 if not self
._padZero
and len(intStr
) != field_len
and intStr
.strip():
1657 intStr
= str(long(intStr
))
1658 #### dbg('raw int str: "%s"' % intStr)
1659 #### dbg('self._groupdigits:', self._groupdigits, 'self._formatcodes:', self._formatcodes)
1660 if self
._groupdigits
:
1663 for i
in range(len(intStr
)-1, -1, -1):
1664 new
= intStr
[i
] + new
1666 new
= self
._groupChar
+ new
1668 if new
and new
[0] == self
._groupChar
:
1670 if len(new
) <= length
:
1671 # expanded string will still fit and leave room for sign:
1673 # else... leave it without the commas...
1675 ## dbg('padzero?', self._padZero)
1676 ## dbg('len(intStr):', len(intStr), 'field length:', length)
1677 if self
._padZero
and len(intStr
) < length
:
1678 intStr
= '0' * (length
- len(intStr
)) + intStr
1679 if signpos
!= -1: # we had a sign before; restore it
1680 if self
._useParensForNegatives
:
1681 intStr
= '(' + intStr
[1:]
1682 if right_signpos
!= -1:
1685 intStr
= '-' + intStr
[1:]
1686 elif signpos
!= -1 and slice[0:signpos
].strip() == '': # - was before digits
1687 if self
._useParensForNegatives
:
1688 intStr
= '(' + intStr
1689 if right_signpos
!= -1:
1692 intStr
= '-' + intStr
1693 elif right_signpos
!= -1:
1694 # must have had ')' but '(' was before field; re-add ')'
1698 slice = slice.strip() # drop extra spaces
1700 if self
._alignRight
: ## Only if right-alignment is enabled
1701 slice = slice.rjust( length
)
1703 slice = slice.ljust( length
)
1704 if self
._fillChar
!= ' ':
1705 slice = slice.replace(' ', self
._fillChar
)
1706 ## dbg('adjusted slice: "%s"' % slice, indent=0)
1710 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
1712 class MaskedEditMixin
:
1714 This class allows us to abstract the masked edit functionality that could
1715 be associated with any text entry control. (eg. wx.TextCtrl, wx.ComboBox, etc.)
1716 It forms the basis for all of the lib.masked controls.
1718 valid_ctrl_params
= {
1719 'mask': 'XXXXXXXXXXXXX', ## mask string for formatting this control
1720 'autoformat': "", ## optional auto-format code to set format from masktags dictionary
1721 'fields': {}, ## optional list/dictionary of maskededit.Field class instances, indexed by position in mask
1722 'datestyle': 'MDY', ## optional date style for date-type values. Can trigger autocomplete year
1723 'autoCompleteKeycodes': [], ## Optional list of additional keycodes which will invoke field-auto-complete
1724 'useFixedWidthFont': True, ## Use fixed-width font instead of default for base control
1725 'defaultEncoding': 'latin1', ## optional argument to indicate unicode codec to use (unicode ctrls only)
1726 'retainFieldValidation': False, ## Set this to true if setting control-level parameters independently,
1727 ## from field validation constraints
1728 'emptyBackgroundColour': "White",
1729 'validBackgroundColour': "White",
1730 'invalidBackgroundColour': "Yellow",
1731 'foregroundColour': "Black",
1732 'signedForegroundColour': "Red",
1736 def __init__(self
, name
= 'MaskedEdit', **kwargs
):
1738 This is the "constructor" for setting up the mixin variable parameters for the composite class.
1743 # set up flag for doing optional things to base control if possible
1744 if not hasattr(self
, 'controlInitialized'):
1745 self
.controlInitialized
= False
1747 # Set internal state var for keeping track of whether or not a character
1748 # action results in a modification of the control, since .SetValue()
1749 # doesn't modify the base control's internal state:
1750 self
.modified
= False
1751 self
._previous
_mask
= None
1753 # Validate legitimate set of parameters:
1754 for key
in kwargs
.keys():
1755 if key
.replace('Color', 'Colour') not in MaskedEditMixin
.valid_ctrl_params
.keys() + Field
.valid_params
.keys():
1756 raise TypeError('%s: invalid parameter "%s"' % (name
, key
))
1758 ## Set up dictionary that can be used by subclasses to override or add to default
1759 ## behavior for individual characters. Derived subclasses needing to change
1760 ## default behavior for keys can either redefine the default functions for the
1761 ## common keys or add functions for specific keys to this list. Each function
1762 ## added should take the key event as argument, and return False if the key
1763 ## requires no further processing.
1765 ## Initially populated with navigation and function control keys:
1766 self
._keyhandlers
= {
1767 # default navigation keys and handlers:
1768 wx
.WXK_BACK
: self
._OnErase
,
1769 wx
.WXK_LEFT
: self
._OnArrow
,
1770 wx
.WXK_NUMPAD_LEFT
: self
._OnArrow
,
1771 wx
.WXK_RIGHT
: self
._OnArrow
,
1772 wx
.WXK_NUMPAD_RIGHT
: self
._OnArrow
,
1773 wx
.WXK_UP
: self
._OnAutoCompleteField
,
1774 wx
.WXK_NUMPAD_UP
: self
._OnAutoCompleteField
,
1775 wx
.WXK_DOWN
: self
._OnAutoCompleteField
,
1776 wx
.WXK_NUMPAD_DOWN
: self
._OnAutoCompleteField
,
1777 wx
.WXK_TAB
: self
._OnChangeField
,
1778 wx
.WXK_HOME
: self
._OnHome
,
1779 wx
.WXK_NUMPAD_HOME
: self
._OnHome
,
1780 wx
.WXK_END
: self
._OnEnd
,
1781 wx
.WXK_NUMPAD_END
: self
._OnEnd
,
1782 wx
.WXK_RETURN
: self
._OnReturn
,
1783 wx
.WXK_NUMPAD_ENTER
: self
._OnReturn
,
1784 wx
.WXK_PRIOR
: self
._OnAutoCompleteField
,
1785 wx
.WXK_NUMPAD_PRIOR
: self
._OnAutoCompleteField
,
1786 wx
.WXK_NEXT
: self
._OnAutoCompleteField
,
1787 wx
.WXK_NUMPAD_NEXT
: self
._OnAutoCompleteField
,
1789 # default function control keys and handlers:
1790 wx
.WXK_DELETE
: self
._OnDelete
,
1791 wx
.WXK_NUMPAD_DELETE
: self
._OnDelete
,
1792 wx
.WXK_INSERT
: self
._OnInsert
,
1793 wx
.WXK_NUMPAD_INSERT
: self
._OnInsert
,
1795 WXK_CTRL_A
: self
._OnCtrl
_A
,
1796 WXK_CTRL_C
: self
._OnCtrl
_C
,
1797 WXK_CTRL_S
: self
._OnCtrl
_S
,
1798 WXK_CTRL_V
: self
._OnCtrl
_V
,
1799 WXK_CTRL_X
: self
._OnCtrl
_X
,
1800 WXK_CTRL_Z
: self
._OnCtrl
_Z
,
1803 ## bind standard navigational and control keycodes to this instance,
1804 ## so that they can be augmented and/or changed in derived classes:
1805 self
._nav
= list(nav
)
1806 self
._control
= list(control
)
1808 ## Dynamically evaluate and store string constants for mask chars
1809 ## so that locale settings can be made after this module is imported
1810 ## and the controls created after that is done can allow the
1811 ## appropriate characters:
1812 self
.maskchardict
= {
1814 'A': string
.uppercase
,
1815 'a': string
.lowercase
,
1816 'X': string
.letters
+ string
.punctuation
+ string
.digits
,
1817 'C': string
.letters
,
1818 'N': string
.letters
+ string
.digits
,
1819 '&': string
.punctuation
,
1820 '*': ansichars
# to give it a value, but now allows any non-wxcontrol character
1823 ## self._ignoreChange is used by MaskedComboBox, because
1824 ## of the hack necessary to determine the selection; it causes
1825 ## EVT_TEXT messages from the combobox to be ignored if set.
1826 self
._ignoreChange
= False
1828 # These are used to keep track of previous value, for undo functionality:
1829 self
._curValue
= None
1830 self
._prevValue
= None
1834 # Set defaults for each parameter for this instance, and fully
1835 # populate initial parameter list for configuration:
1836 for key
, value
in MaskedEditMixin
.valid_ctrl_params
.items():
1837 setattr(self
, '_' + key
, copy
.copy(value
))
1838 if not kwargs
.has_key(key
):
1839 #### dbg('%s: "%s"' % (key, repr(value)))
1840 kwargs
[key
] = copy
.copy(value
)
1842 # Create a "field" that holds global parameters for control constraints
1843 self
._ctrl
_constraints
= self
._fields
[-1] = Field(index
=-1)
1844 self
.SetCtrlParameters(**kwargs
)
1848 def SetCtrlParameters(self
, **kwargs
):
1850 This public function can be used to set individual or multiple masked edit
1851 parameters after construction. (See maskededit module overview for the list
1852 of valid parameters.)
1855 ## dbg('MaskedEditMixin::SetCtrlParameters', indent=1)
1856 #### dbg('kwargs:', indent=1)
1857 ## for key, value in kwargs.items():
1858 #### dbg(key, '=', value)
1861 # Validate keyword arguments:
1862 constraint_kwargs
= {}
1864 for key
, value
in kwargs
.items():
1865 key
= key
.replace('Color', 'Colour') # for b-c, and standard wxPython spelling
1866 if key
not in MaskedEditMixin
.valid_ctrl_params
.keys() + Field
.valid_params
.keys():
1867 ## dbg(indent=0, suspend=0)
1868 ae
= AttributeError('Invalid keyword argument "%s" for control "%s"' % (key
, self
.name
))
1871 elif key
in Field
.valid_params
.keys():
1872 constraint_kwargs
[key
] = value
1874 ctrl_kwargs
[key
] = value
1879 if ctrl_kwargs
.has_key('autoformat'):
1880 autoformat
= ctrl_kwargs
['autoformat']
1884 # handle "parochial name" backward compatibility:
1885 if autoformat
and autoformat
.find('MILTIME') != -1 and autoformat
not in masktags
.keys():
1886 autoformat
= autoformat
.replace('MILTIME', '24HRTIME')
1888 if autoformat
!= self
._autoformat
and autoformat
in masktags
.keys():
1889 ## dbg('autoformat:', autoformat)
1890 self
._autoformat
= autoformat
1891 mask
= masktags
[self
._autoformat
]['mask']
1892 # gather rest of any autoformat parameters:
1893 for param
, value
in masktags
[self
._autoformat
].items():
1894 if param
== 'mask': continue # (must be present; already accounted for)
1895 constraint_kwargs
[param
] = value
1897 elif autoformat
and not autoformat
in masktags
.keys():
1898 ae
= AttributeError('invalid value for autoformat parameter: %s' % repr(autoformat
))
1899 ae
.attribute
= autoformat
1902 ## dbg('autoformat not selected')
1903 if kwargs
.has_key('mask'):
1904 mask
= kwargs
['mask']
1905 ## dbg('mask:', mask)
1907 ## Assign style flags
1909 ## dbg('preserving previous mask')
1910 mask
= self
._previous
_mask
# preserve previous mask
1912 ## dbg('mask (re)set')
1913 reset_args
['reset_mask'] = mask
1914 constraint_kwargs
['mask'] = mask
1916 # wipe out previous fields; preserve new control-level constraints
1917 self
._fields
= {-1: self._ctrl_constraints}
1920 if ctrl_kwargs
.has_key('fields'):
1921 # do field parameter type validation, and conversion to internal dictionary
1923 fields
= ctrl_kwargs
['fields']
1924 if type(fields
) in (types
.ListType
, types
.TupleType
):
1925 for i
in range(len(fields
)):
1927 if not isinstance(field
, Field
):
1928 ## dbg(indent=0, suspend=0)
1929 raise TypeError('invalid type for field parameter: %s' % repr(field
))
1930 self
._fields
[i
] = field
1932 elif type(fields
) == types
.DictionaryType
:
1933 for index
, field
in fields
.items():
1934 if not isinstance(field
, Field
):
1935 ## dbg(indent=0, suspend=0)
1936 raise TypeError('invalid type for field parameter: %s' % repr(field
))
1937 self
._fields
[index
] = field
1939 ## dbg(indent=0, suspend=0)
1940 raise TypeError('fields parameter must be a list or dictionary; not %s' % repr(fields
))
1942 # Assign constraint parameters for entire control:
1943 #### dbg('control constraints:', indent=1)
1944 ## for key, value in constraint_kwargs.items():
1945 #### dbg('%s:' % key, value)
1948 # determine if changing parameters that should affect the entire control:
1949 for key
in MaskedEditMixin
.valid_ctrl_params
.keys():
1950 if key
in ( 'mask', 'fields' ): continue # (processed separately)
1951 if ctrl_kwargs
.has_key(key
):
1952 setattr(self
, '_' + key
, ctrl_kwargs
[key
])
1954 # Validate color parameters, converting strings to named colors and validating
1955 # result if appropriate:
1956 for key
in ('emptyBackgroundColour', 'invalidBackgroundColour', 'validBackgroundColour',
1957 'foregroundColour', 'signedForegroundColour'):
1958 if ctrl_kwargs
.has_key(key
):
1959 if type(ctrl_kwargs
[key
]) in (types
.StringType
, types
.UnicodeType
):
1960 c
= wx
.NamedColour(ctrl_kwargs
[key
])
1961 if c
.Get() == (-1, -1, -1):
1962 raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs
[key
]), key
))
1964 # replace attribute with wxColour object:
1965 setattr(self
, '_' + key
, c
)
1966 # attach a python dynamic attribute to wxColour for debug printouts
1967 c
._name
= ctrl_kwargs
[key
]
1969 elif type(ctrl_kwargs
[key
]) != type(wx
.BLACK
):
1970 raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs
[key
]), key
))
1973 ## dbg('self._retainFieldValidation:', self._retainFieldValidation)
1974 if not self
._retainFieldValidation
:
1975 # Build dictionary of any changing parameters which should be propagated to the
1977 for arg
in Field
.propagating_params
:
1978 #### dbg('kwargs.has_key(%s)?' % arg, kwargs.has_key(arg))
1979 #### dbg('getattr(self._ctrl_constraints, _%s)?' % arg, getattr(self._ctrl_constraints, '_'+arg))
1980 reset_args
[arg
] = kwargs
.has_key(arg
) and kwargs
[arg
] != getattr(self
._ctrl
_constraints
, '_'+arg
)
1981 #### dbg('reset_args[%s]?' % arg, reset_args[arg])
1983 # Set the control-level constraints:
1984 self
._ctrl
_constraints
._SetParameters
(**constraint_kwargs
)
1986 # This routine does the bulk of the interdependent parameter processing, determining
1987 # the field extents of the mask if changed, resetting parameters as appropriate,
1988 # determining the overall template value for the control, etc.
1989 self
._configure
(mask
, **reset_args
)
1991 # now that we've propagated the field constraints and mask portions to the
1992 # various fields, validate the constraints
1993 self
._ctrl
_constraints
._ValidateParameters
(**constraint_kwargs
)
1995 # Validate that all choices for given fields are at least of the
1996 # necessary length, and that they all would be valid pastes if pasted
1997 # into their respective fields:
1998 #### dbg('validating choices')
1999 self
._validateChoices
()
2002 self
._autofit
= self
._ctrl
_constraints
._autofit
2005 self
._isDate
= 'D' in self
._ctrl
_constraints
._formatcodes
and _isDateType(mask
)
2006 self
._isTime
= 'T' in self
._ctrl
_constraints
._formatcodes
and _isTimeType(mask
)
2008 # Set _dateExtent, used in date validation to locate date in string;
2009 # always set as though year will be 4 digits, even if mask only has
2010 # 2 digits, so we can always properly process the intended year for
2011 # date validation (leap years, etc.)
2012 if self
._mask
.find('CCC') != -1: self
._dateExtent
= 11
2013 else: self
._dateExtent
= 10
2015 self
._4digityear
= len(self
._mask
) > 8 and self
._mask
[9] == '#'
2017 if self
._isDate
and self
._autoformat
:
2018 # Auto-decide datestyle:
2019 if self
._autoformat
.find('MDDY') != -1: self
._datestyle
= 'MDY'
2020 elif self
._autoformat
.find('YMMD') != -1: self
._datestyle
= 'YMD'
2021 elif self
._autoformat
.find('YMMMD') != -1: self
._datestyle
= 'YMD'
2022 elif self
._autoformat
.find('DMMY') != -1: self
._datestyle
= 'DMY'
2023 elif self
._autoformat
.find('DMMMY') != -1: self
._datestyle
= 'DMY'
2025 # Give derived controls a chance to react to parameter changes before
2026 # potentially changing current value of the control.
2027 self
._OnCtrlParametersChanged
()
2029 if self
.controlInitialized
:
2030 # Then the base control is available for configuration;
2031 # take action on base control based on new settings, as appropriate.
2032 if kwargs
.has_key('useFixedWidthFont'):
2033 # Set control font - fixed width by default
2036 if reset_args
.has_key('reset_mask'):
2037 ## dbg('reset mask')
2038 curvalue
= self
._GetValue
()
2039 if curvalue
.strip():
2041 ## dbg('attempting to _SetInitialValue(%s)' % self._GetValue())
2042 self
._SetInitialValue
(self
._GetValue
())
2043 except Exception, e
:
2044 ## dbg('exception caught:', e)
2045 ## dbg("current value doesn't work; attempting to reset to template")
2046 self
._SetInitialValue
()
2048 ## dbg('attempting to _SetInitialValue() with template')
2049 self
._SetInitialValue
()
2051 elif kwargs
.has_key('useParensForNegatives'):
2052 newvalue
= self
._getSignedValue
()[0]
2054 if newvalue
is not None:
2055 # Adjust for new mask:
2056 if len(newvalue
) < len(self
._mask
):
2058 elif len(newvalue
) > len(self
._mask
):
2059 if newvalue
[-1] in (' ', ')'):
2060 newvalue
= newvalue
[:-1]
2062 ## dbg('reconfiguring value for parens:"%s"' % newvalue)
2063 self
._SetValue
(newvalue
)
2065 if self
._prevValue
!= newvalue
:
2066 self
._prevValue
= newvalue
# disallow undo of sign type
2069 ## dbg('calculated size:', self._CalcSize())
2070 self
.SetClientSize(self
._CalcSize
())
2071 width
= self
.GetSize().width
2072 height
= self
.GetBestSize().height
2073 ## dbg('setting client size to:', (width, height))
2074 self
.SetInitialSize((width
, height
))
2076 # Set value/type-specific formatting
2077 self
._applyFormatting
()
2078 ## dbg(indent=0, suspend=0)
2080 def SetMaskParameters(self
, **kwargs
):
2081 """ old name for the SetCtrlParameters function (DEPRECATED)"""
2082 return self
.SetCtrlParameters(**kwargs
)
2085 def GetCtrlParameter(self
, paramname
):
2087 Routine for retrieving the value of any given parameter
2089 if MaskedEditMixin
.valid_ctrl_params
.has_key(paramname
.replace('Color','Colour')):
2090 return getattr(self
, '_' + paramname
.replace('Color', 'Colour'))
2091 elif Field
.valid_params
.has_key(paramname
):
2092 return self
._ctrl
_constraints
._GetParameter
(paramname
)
2094 TypeError('"%s".GetCtrlParameter: invalid parameter "%s"' % (self
.name
, paramname
))
2096 def GetMaskParameter(self
, paramname
):
2097 """ old name for the GetCtrlParameters function (DEPRECATED)"""
2098 return self
.GetCtrlParameter(paramname
)
2101 ## This idea worked, but Boa was unable to use this solution...
2102 ## def _attachMethod(self, func):
2104 ## setattr(self, func.__name__, new.instancemethod(func, self, self.__class__))
2107 ## def _DefinePropertyFunctions(exposed_params):
2108 ## for param in exposed_params:
2109 ## propname = param[0].upper() + param[1:]
2111 ## exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))
2112 ## exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
2113 ## self._attachMethod(locals()['Set%s' % propname])
2114 ## self._attachMethod(locals()['Get%s' % propname])
2116 ## if param.find('Colour') != -1:
2117 ## # add non-british spellings, for backward-compatibility
2118 ## propname.replace('Colour', 'Color')
2120 ## exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))
2121 ## exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
2122 ## self._attachMethod(locals()['Set%s' % propname])
2123 ## self._attachMethod(locals()['Get%s' % propname])
2127 def SetFieldParameters(self
, field_index
, **kwargs
):
2129 Routine provided to modify the parameters of a given field.
2130 Because changes to fields can affect the overall control,
2131 direct access to the fields is prevented, and the control
2132 is always "reconfigured" after setting a field parameter.
2133 (See maskededit module overview for the list of valid field-level
2136 if field_index
not in self
._field
_indices
:
2137 ie
= IndexError('%s is not a valid field for control "%s".' % (str(field_index
), self
.name
))
2138 ie
.index
= field_index
2140 # set parameters as requested:
2141 self
._fields
[field_index
]._SetParameters
(**kwargs
)
2143 # Possibly reprogram control template due to resulting changes, and ensure
2144 # control-level params are still propagated to fields:
2145 self
._configure
(self
._previous
_mask
)
2146 self
._fields
[field_index
]._ValidateParameters
(**kwargs
)
2148 if self
.controlInitialized
:
2149 if kwargs
.has_key('fillChar') or kwargs
.has_key('defaultValue'):
2150 self
._SetInitialValue
()
2153 # this is tricky, because, as Robin explains:
2154 # "Basically there are two sizes to deal with, that are potentially
2155 # different. The client size is the inside size and may, depending
2156 # on platform, exclude the borders and such. The normal size is
2157 # the outside size that does include the borders. What you are
2158 # calculating (in _CalcSize) is the client size, but the sizers
2159 # deal with the full size and so that is the minimum size that
2160 # we need to set with SetInitialSize. The root of the problem is
2161 # that in _calcSize the current client size height is returned,
2162 # instead of a height based on the current font. So I suggest using
2163 # _calcSize to just get the width, and then use GetBestSize to
2165 self
.SetClientSize(self
._CalcSize
())
2166 width
= self
.GetSize().width
2167 height
= self
.GetBestSize().height
2168 self
.SetInitialSize((width
, height
))
2171 # Set value/type-specific formatting
2172 self
._applyFormatting
()
2175 def GetFieldParameter(self
, field_index
, paramname
):
2177 Routine provided for getting a parameter of an individual field.
2179 if field_index
not in self
._field
_indices
:
2180 ie
= IndexError('%s is not a valid field for control "%s".' % (str(field_index
), self
.name
))
2181 ie
.index
= field_index
2183 elif Field
.valid_params
.has_key(paramname
):
2184 return self
._fields
[field_index
]._GetParameter
(paramname
)
2186 ae
= AttributeError('"%s".GetFieldParameter: invalid parameter "%s"' % (self
.name
, paramname
))
2187 ae
.attribute
= paramname
2191 def _SetKeycodeHandler(self
, keycode
, func
):
2193 This function adds and/or replaces key event handling functions
2194 used by the control. <func> should take the event as argument
2195 and return False if no further action on the key is necessary.
2198 self
._keyhandlers
[keycode
] = func
2199 elif self
._keyhandlers
.has_key(keycode
):
2200 del self
._keyhandlers
[keycode
]
2203 def _SetKeyHandler(self
, char
, func
):
2205 This function adds and/or replaces key event handling functions
2206 for ascii characters. <func> should take the event as argument
2207 and return False if no further action on the key is necessary.
2209 self
._SetKeycodeHandler
(ord(char
), func
)
2212 def _AddNavKeycode(self
, keycode
, handler
=None):
2214 This function allows a derived subclass to augment the list of
2215 keycodes that are considered "navigational" keys.
2217 self
._nav
.append(keycode
)
2219 self
._keyhandlers
[keycode
] = handler
2220 elif self
.keyhandlers
.has_key(keycode
):
2221 del self
._keyhandlers
[keycode
]
2225 def _AddNavKey(self
, char
, handler
=None):
2227 This function is a convenience function so you don't have to
2228 remember to call ord() for ascii chars to be used for navigation.
2230 self
._AddNavKeycode
(ord(char
), handler
)
2233 def _GetNavKeycodes(self
):
2235 This function retrieves the current list of navigational keycodes for
2241 def _SetNavKeycodes(self
, keycode_func_tuples
):
2243 This function allows you to replace the current list of keycode processed
2244 as navigation keys, and bind associated optional keyhandlers.
2247 for keycode
, func
in keycode_func_tuples
:
2248 self
._nav
.append(keycode
)
2250 self
._keyhandlers
[keycode
] = func
2251 elif self
.keyhandlers
.has_key(keycode
):
2252 del self
._keyhandlers
[keycode
]
2255 def _processMask(self
, mask
):
2257 This subroutine expands {n} syntax in mask strings, and looks for escaped
2258 special characters and returns the expanded mask, and an dictionary
2259 of booleans indicating whether or not a given position in the mask is
2260 a mask character or not.
2262 ## dbg('_processMask: mask', mask, indent=1)
2263 # regular expression for parsing c{n} syntax:
2264 rex
= re
.compile('([' +string
.join(maskchars
,"") + '])\{(\d+)\}')
2266 match
= rex
.search(s
)
2267 while match
: # found an(other) occurrence
2268 maskchr
= s
[match
.start(1):match
.end(1)] # char to be repeated
2269 repcount
= int(s
[match
.start(2):match
.end(2)]) # the number of times
2270 replacement
= string
.join( maskchr
* repcount
, "") # the resulting substr
2271 s
= s
[:match
.start(1)] + replacement
+ s
[match
.end(2)+1:] #account for trailing '}'
2272 match
= rex
.search(s
) # look for another such entry in mask
2274 self
._decimalChar
= self
._ctrl
_constraints
._decimalChar
2275 self
._shiftDecimalChar
= self
._ctrl
_constraints
._shiftDecimalChar
2277 self
._isFloat
= _isFloatingPoint(s
) and not self
._ctrl
_constraints
._validRegex
2278 self
._isInt
= _isInteger(s
) and not self
._ctrl
_constraints
._validRegex
2279 self
._signOk
= '-' in self
._ctrl
_constraints
._formatcodes
and (self
._isFloat
or self
._isInt
)
2280 self
._useParens
= self
._ctrl
_constraints
._useParensForNegatives
2282 #### dbg('self._signOk?', self._signOk, 'self._useParens?', self._useParens)
2283 #### dbg('isFloatingPoint(%s)?' % (s), _isFloatingPoint(s),
2284 ## 'ctrl regex:', self._ctrl_constraints._validRegex)
2286 if self
._signOk
and s
[0] != ' ':
2288 if self
._ctrl
_constraints
._defaultValue
and self
._ctrl
_constraints
._defaultValue
[0] != ' ':
2289 self
._ctrl
_constraints
._defaultValue
= ' ' + self
._ctrl
_constraints
._defaultValue
2294 self
._ctrl
_constraints
._defaultValue
+= ' '
2297 # Now, go build up a dictionary of booleans, indexed by position,
2298 # indicating whether or not a given position is masked or not.
2299 # Also, strip out any '|' chars, adjusting the mask as necessary,
2300 # marking the appropriate positions for field boundaries:
2302 explicit_field_boundaries
= []
2305 if s
[i
] == '\\': # if escaped character:
2306 ismasked
[i
] = False # mark position as not a mask char
2307 if i
+1 < len(s
): # if another char follows...
2308 s
= s
[:i
] + s
[i
+1:] # elide the '\'
2309 if i
+2 < len(s
) and s
[i
+1] == '\\':
2310 # if next char also a '\', char is a literal '\'
2311 s
= s
[:i
] + s
[i
+1:] # elide the 2nd '\' as well
2312 i
+= 1 # increment to next char
2314 s
= s
[:i
] + s
[i
+1:] # elide the '|'
2315 explicit_field_boundaries
.append(i
)
2316 # keep index where it is:
2317 else: # else if special char, mark position accordingly
2318 ismasked
[i
] = s
[i
] in maskchars
2319 #### dbg('ismasked[%d]:' % i, ismasked[i], s)
2320 i
+= 1 # increment to next char
2321 #### dbg('ismasked:', ismasked)
2322 ## dbg('new mask: "%s"' % s, indent=0)
2324 return s
, ismasked
, explicit_field_boundaries
2327 def _calcFieldExtents(self
):
2329 Subroutine responsible for establishing/configuring field instances with
2330 indices and editable extents appropriate to the specified mask, and building
2331 the lookup table mapping each position to the corresponding field.
2333 self
._lookupField
= {}
2336 ## Create dictionary of positions,characters in mask
2338 for charnum
in range( len( self
._mask
)):
2339 self
.maskdict
[charnum
] = self
._mask
[charnum
:charnum
+1]
2341 # For the current mask, create an ordered list of field extents
2342 # and a dictionary of positions that map to field indices:
2344 if self
._signOk
: start
= 1
2348 # Skip field "discovery", and just construct a 2-field control with appropriate
2349 # constraints for a floating-point entry.
2351 # .setdefault always constructs 2nd argument even if not needed, so we do this
2352 # the old-fashioned way...
2353 if not self
._fields
.has_key(0):
2354 self
._fields
[0] = Field()
2355 if not self
._fields
.has_key(1):
2356 self
._fields
[1] = Field()
2358 self
._decimalpos
= string
.find( self
._mask
, '.')
2359 ## dbg('decimal pos =', self._decimalpos)
2361 formatcodes
= self
._fields
[0]._GetParameter
('formatcodes')
2362 if 'R' not in formatcodes
: formatcodes
+= 'R'
2363 self
._fields
[0]._SetParameters
(index
=0, extent
=(start
, self
._decimalpos
),
2364 mask
=self
._mask
[start
:self
._decimalpos
], formatcodes
=formatcodes
)
2365 end
= len(self
._mask
)
2366 if self
._signOk
and self
._useParens
:
2368 self
._fields
[1]._SetParameters
(index
=1, extent
=(self
._decimalpos
+1, end
),
2369 mask
=self
._mask
[self
._decimalpos
+1:end
])
2371 for i
in range(self
._decimalpos
+1):
2372 self
._lookupField
[i
] = 0
2374 for i
in range(self
._decimalpos
+1, len(self
._mask
)+1):
2375 self
._lookupField
[i
] = 1
2378 # Skip field "discovery", and just construct a 1-field control with appropriate
2379 # constraints for a integer entry.
2380 if not self
._fields
.has_key(0):
2381 self
._fields
[0] = Field(index
=0)
2382 end
= len(self
._mask
)
2383 if self
._signOk
and self
._useParens
:
2385 self
._fields
[0]._SetParameters
(index
=0, extent
=(start
, end
),
2386 mask
=self
._mask
[start
:end
])
2387 for i
in range(len(self
._mask
)+1):
2388 self
._lookupField
[i
] = 0
2390 # generic control; parse mask to figure out where the fields are:
2393 i
= self
._findNextEntry
(pos
,adjustInsert
=False) # go to 1st entry point:
2394 if i
< len(self
._mask
): # no editable chars!
2395 for j
in range(pos
, i
+1):
2396 self
._lookupField
[j
] = field_index
2397 pos
= i
# figure out field for 1st editable space:
2399 while i
<= len(self
._mask
):
2400 #### dbg('searching: outer field loop: i = ', i)
2401 if self
._isMaskChar
(i
):
2402 #### dbg('1st char is mask char; recording edit_start=', i)
2404 # Skip to end of editable part of current field:
2405 while i
< len(self
._mask
) and self
._isMaskChar
(i
):
2406 self
._lookupField
[i
] = field_index
2408 if i
in self
._explicit
_field
_boundaries
:
2410 #### dbg('edit_end =', i)
2412 self
._lookupField
[i
] = field_index
2413 #### dbg('self._fields.has_key(%d)?' % field_index, self._fields.has_key(field_index))
2414 if not self
._fields
.has_key(field_index
):
2415 kwargs
= Field
.valid_params
.copy()
2416 kwargs
['index'] = field_index
2417 kwargs
['extent'] = (edit_start
, edit_end
)
2418 kwargs
['mask'] = self
._mask
[edit_start
:edit_end
]
2419 self
._fields
[field_index
] = Field(**kwargs
)
2421 self
._fields
[field_index
]._SetParameters
(
2423 extent
=(edit_start
, edit_end
),
2424 mask
=self
._mask
[edit_start
:edit_end
])
2426 i
= self
._findNextEntry
(pos
, adjustInsert
=False) # go to next field:
2427 #### dbg('next entry:', i)
2429 for j
in range(pos
, i
+1):
2430 self
._lookupField
[j
] = field_index
2431 if i
>= len(self
._mask
):
2432 break # if past end, we're done
2435 #### dbg('next field:', field_index)
2437 indices
= self
._fields
.keys()
2439 self
._field
_indices
= indices
[1:]
2440 #### dbg('lookupField map:', indent=1)
2441 ## for i in range(len(self._mask)):
2442 #### dbg('pos %d:' % i, self._lookupField[i])
2445 # Verify that all field indices specified are valid for mask:
2446 for index
in self
._fields
.keys():
2447 if index
not in [-1] + self
._lookupField
.values():
2448 ie
= IndexError('field %d is not a valid field for mask "%s"' % (index
, self
._mask
))
2454 def _calcTemplate(self
, reset_fillchar
, reset_default
):
2456 Subroutine for processing current fillchars and default values for
2457 whole control and individual fields, constructing the resulting
2458 overall template, and adjusting the current value as necessary.
2461 if self
._ctrl
_constraints
._defaultValue
:
2464 for field
in self
._fields
.values():
2465 if field
._defaultValue
and not reset_default
:
2467 ## dbg('default set?', default_set)
2469 # Determine overall new template for control, and keep track of previous
2470 # values, so that current control value can be modified as appropriate:
2471 if self
.controlInitialized
: curvalue
= list(self
._GetValue
())
2472 else: curvalue
= None
2474 if hasattr(self
, '_fillChar'): old_fillchars
= self
._fillChar
2475 else: old_fillchars
= None
2477 if hasattr(self
, '_template'): old_template
= self
._template
2478 else: old_template
= None
2485 for field
in self
._fields
.values():
2486 field
._template
= ""
2488 for pos
in range(len(self
._mask
)):
2489 #### dbg('pos:', pos)
2490 field
= self
._FindField
(pos
)
2491 #### dbg('field:', field._index)
2492 start
, end
= field
._extent
2494 if pos
== 0 and self
._signOk
:
2495 self
._template
= ' ' # always make 1st 1st position blank, regardless of fillchar
2496 elif self
._isFloat
and pos
== self
._decimalpos
:
2497 self
._template
+= self
._decimalChar
2498 elif self
._isMaskChar
(pos
):
2499 if field
._fillChar
!= self
._ctrl
_constraints
._fillChar
and not reset_fillchar
:
2500 fillChar
= field
._fillChar
2502 fillChar
= self
._ctrl
_constraints
._fillChar
2503 self
._fillChar
[pos
] = fillChar
2505 # Replace any current old fillchar with new one in current value;
2506 # if action required, set reset_value flag so we can take that action
2507 # after we're all done
2508 if self
.controlInitialized
and old_fillchars
and old_fillchars
.has_key(pos
) and curvalue
:
2509 if curvalue
[pos
] == old_fillchars
[pos
] and old_fillchars
[pos
] != fillChar
:
2511 curvalue
[pos
] = fillChar
2513 if not field
._defaultValue
and not self
._ctrl
_constraints
._defaultValue
:
2514 #### dbg('no default value')
2515 self
._template
+= fillChar
2516 field
._template
+= fillChar
2518 elif field
._defaultValue
and not reset_default
:
2519 #### dbg('len(field._defaultValue):', len(field._defaultValue))
2520 #### dbg('pos-start:', pos-start)
2521 if len(field
._defaultValue
) > pos
-start
:
2522 #### dbg('field._defaultValue[pos-start]: "%s"' % field._defaultValue[pos-start])
2523 self
._template
+= field
._defaultValue
[pos
-start
]
2524 field
._template
+= field
._defaultValue
[pos
-start
]
2526 #### dbg('field default not long enough; using fillChar')
2527 self
._template
+= fillChar
2528 field
._template
+= fillChar
2530 if len(self
._ctrl
_constraints
._defaultValue
) > pos
:
2531 #### dbg('using control default')
2532 self
._template
+= self
._ctrl
_constraints
._defaultValue
[pos
]
2533 field
._template
+= self
._ctrl
_constraints
._defaultValue
[pos
]
2535 #### dbg('ctrl default not long enough; using fillChar')
2536 self
._template
+= fillChar
2537 field
._template
+= fillChar
2538 #### dbg('field[%d]._template now "%s"' % (field._index, field._template))
2539 #### dbg('self._template now "%s"' % self._template)
2541 self
._template
+= self
._mask
[pos
]
2543 self
._fields
[-1]._template
= self
._template
# (for consistency)
2545 if curvalue
: # had an old value, put new one back together
2546 newvalue
= string
.join(curvalue
, "")
2551 self
._defaultValue
= self
._template
2552 ## dbg('self._defaultValue:', self._defaultValue)
2553 if not self
.IsEmpty(self
._defaultValue
) and not self
.IsValid(self
._defaultValue
):
2555 ve
= ValueError('Default value of "%s" is not a valid value for control "%s"' % (self
._defaultValue
, self
.name
))
2556 ve
.value
= self
._defaultValue
2559 # if no fillchar change, but old value == old template, replace it:
2560 if newvalue
== old_template
:
2561 newvalue
= self
._template
2564 self
._defaultValue
= None
2567 ## dbg('resetting value to: "%s"' % newvalue)
2568 pos
= self
._GetInsertionPoint
()
2569 sel_start
, sel_to
= self
._GetSelection
()
2570 self
._SetValue
(newvalue
)
2571 self
._SetInsertionPoint
(pos
)
2572 self
._SetSelection
(sel_start
, sel_to
)
2575 def _propagateConstraints(self
, **reset_args
):
2577 Subroutine for propagating changes to control-level constraints and
2578 formatting to the individual fields as appropriate.
2580 parent_codes
= self
._ctrl
_constraints
._formatcodes
2581 parent_includes
= self
._ctrl
_constraints
._includeChars
2582 parent_excludes
= self
._ctrl
_constraints
._excludeChars
2583 for i
in self
._field
_indices
:
2584 field
= self
._fields
[i
]
2586 if len(self
._field
_indices
) == 1:
2587 inherit_args
['formatcodes'] = parent_codes
2588 inherit_args
['includeChars'] = parent_includes
2589 inherit_args
['excludeChars'] = parent_excludes
2591 field_codes
= current_codes
= field
._GetParameter
('formatcodes')
2592 for c
in parent_codes
:
2593 if c
not in field_codes
: field_codes
+= c
2594 if field_codes
!= current_codes
:
2595 inherit_args
['formatcodes'] = field_codes
2597 include_chars
= current_includes
= field
._GetParameter
('includeChars')
2598 for c
in parent_includes
:
2599 if not c
in include_chars
: include_chars
+= c
2600 if include_chars
!= current_includes
:
2601 inherit_args
['includeChars'] = include_chars
2603 exclude_chars
= current_excludes
= field
._GetParameter
('excludeChars')
2604 for c
in parent_excludes
:
2605 if not c
in exclude_chars
: exclude_chars
+= c
2606 if exclude_chars
!= current_excludes
:
2607 inherit_args
['excludeChars'] = exclude_chars
2609 if reset_args
.has_key('defaultValue') and reset_args
['defaultValue']:
2610 inherit_args
['defaultValue'] = "" # (reset for field)
2612 for param
in Field
.propagating_params
:
2613 #### dbg('reset_args.has_key(%s)?' % param, reset_args.has_key(param))
2614 #### dbg('reset_args.has_key(%(param)s) and reset_args[%(param)s]?' % locals(), reset_args.has_key(param) and reset_args[param])
2615 if reset_args
.has_key(param
):
2616 inherit_args
[param
] = self
.GetCtrlParameter(param
)
2617 #### dbg('inherit_args[%s]' % param, inherit_args[param])
2620 field
._SetParameters
(**inherit_args
)
2621 field
._ValidateParameters
(**inherit_args
)
2624 def _validateChoices(self
):
2626 Subroutine that validates that all choices for given fields are at
2627 least of the necessary length, and that they all would be valid pastes
2628 if pasted into their respective fields.
2630 for field
in self
._fields
.values():
2632 index
= field
._index
2633 if len(self
._field
_indices
) == 1 and index
== 0 and field
._choices
== self
._ctrl
_constraints
._choices
:
2634 ## dbg('skipping (duplicate) choice validation of field 0')
2636 #### dbg('checking for choices for field', field._index)
2637 start
, end
= field
._extent
2638 field_length
= end
- start
2639 #### dbg('start, end, length:', start, end, field_length)
2640 for choice
in field
._choices
:
2641 #### dbg('testing "%s"' % choice)
2642 valid_paste
, ignore
, replace_to
= self
._validatePaste
(choice
, start
, end
)
2645 ve
= ValueError('"%s" could not be entered into field %d of control "%s"' % (choice
, index
, self
.name
))
2649 elif replace_to
> end
:
2651 ve
= ValueError('"%s" will not fit into field %d of control "%s"' (choice
, index
, self
.name
))
2656 #### dbg(choice, 'valid in field', index)
2659 def _configure(self
, mask
, **reset_args
):
2661 This function sets flags for automatic styling options. It is
2662 called whenever a control or field-level parameter is set/changed.
2664 This routine does the bulk of the interdependent parameter processing, determining
2665 the field extents of the mask if changed, resetting parameters as appropriate,
2666 determining the overall template value for the control, etc.
2668 reset_args is supplied if called from control's .SetCtrlParameters()
2669 routine, and indicates which if any parameters which can be
2670 overridden by individual fields have been reset by request for the
2675 ## dbg('MaskedEditMixin::_configure("%s")' % mask, indent=1)
2677 # Preprocess specified mask to expand {n} syntax, handle escaped
2678 # mask characters, etc and build the resulting positionally keyed
2679 # dictionary for which positions are mask vs. template characters:
2680 self
._mask
, self
._ismasked
, self
._explicit
_field
_boundaries
= self
._processMask
(mask
)
2681 self
._masklength
= len(self
._mask
)
2682 #### dbg('processed mask:', self._mask)
2684 # Preserve original mask specified, for subsequent reprocessing
2685 # if parameters change.
2686 ## dbg('mask: "%s"' % self._mask, 'previous mask: "%s"' % self._previous_mask)
2687 self
._previous
_mask
= mask
# save unexpanded mask for next time
2688 # Set expanded mask and extent of field -1 to width of entire control:
2689 self
._ctrl
_constraints
._SetParameters
(mask
= self
._mask
, extent
=(0,self
._masklength
))
2691 # Go parse mask to determine where each field is, construct field
2692 # instances as necessary, configure them with those extents, and
2693 # build lookup table mapping each position for control to its corresponding
2695 #### dbg('calculating field extents')
2697 self
._calcFieldExtents
()
2700 # Go process defaultValues and fillchars to construct the overall
2701 # template, and adjust the current value as necessary:
2702 reset_fillchar
= reset_args
.has_key('fillChar') and reset_args
['fillChar']
2703 reset_default
= reset_args
.has_key('defaultValue') and reset_args
['defaultValue']
2705 #### dbg('calculating template')
2706 self
._calcTemplate
(reset_fillchar
, reset_default
)
2708 # Propagate control-level formatting and character constraints to each
2709 # field if they don't already have them; if only one field, propagate
2710 # control-level validation constraints to field as well:
2711 #### dbg('propagating constraints')
2712 self
._propagateConstraints
(**reset_args
)
2715 if self
._isFloat
and self
._fields
[0]._groupChar
== self
._decimalChar
:
2716 raise AttributeError('groupChar (%s) and decimalChar (%s) must be distinct.' %
2717 (self
._fields
[0]._groupChar
, self
._decimalChar
) )
2719 #### dbg('fields:', indent=1)
2720 ## for i in [-1] + self._field_indices:
2721 #### dbg('field %d:' % i, self._fields[i].__dict__)
2724 # Set up special parameters for numeric control, if appropriate:
2726 self
._signpos
= 0 # assume it starts here, but it will move around on floats
2727 signkeys
= ['-', '+', ' ']
2729 signkeys
+= ['(', ')']
2730 for key
in signkeys
:
2732 if not self
._keyhandlers
.has_key(keycode
):
2733 self
._SetKeyHandler
(key
, self
._OnChangeSign
)
2734 elif self
._isInt
or self
._isFloat
:
2735 signkeys
= ['-', '+', ' ', '(', ')']
2736 for key
in signkeys
:
2738 if self
._keyhandlers
.has_key(keycode
) and self
._keyhandlers
[keycode
] == self
._OnChangeSign
:
2739 self
._SetKeyHandler
(key
, None)
2743 if self
._isFloat
or self
._isInt
:
2744 if self
.controlInitialized
:
2745 value
= self
._GetValue
()
2746 #### dbg('value: "%s"' % value, 'len(value):', len(value),
2747 ## 'len(self._ctrl_constraints._mask):',len(self._ctrl_constraints._mask))
2748 if len(value
) < len(self
._ctrl
_constraints
._mask
):
2750 if self
._useParens
and len(newvalue
) < len(self
._ctrl
_constraints
._mask
) and newvalue
.find('(') == -1:
2752 if self
._signOk
and len(newvalue
) < len(self
._ctrl
_constraints
._mask
) and newvalue
.find(')') == -1:
2753 newvalue
= ' ' + newvalue
2754 if len(newvalue
) < len(self
._ctrl
_constraints
._mask
):
2755 if self
._ctrl
_constraints
._alignRight
:
2756 newvalue
= newvalue
.rjust(len(self
._ctrl
_constraints
._mask
))
2758 newvalue
= newvalue
.ljust(len(self
._ctrl
_constraints
._mask
))
2759 ## dbg('old value: "%s"' % value)
2760 ## dbg('new value: "%s"' % newvalue)
2762 self
._SetValue
(newvalue
)
2763 except Exception, e
:
2764 ## dbg('exception raised:', e, 'resetting to initial value')
2765 self
._SetInitialValue
()
2767 elif len(value
) > len(self
._ctrl
_constraints
._mask
):
2769 if not self
._useParens
and newvalue
[-1] == ' ':
2770 newvalue
= newvalue
[:-1]
2771 if not self
._signOk
and len(newvalue
) > len(self
._ctrl
_constraints
._mask
):
2772 newvalue
= newvalue
[1:]
2773 if not self
._signOk
:
2774 newvalue
, signpos
, right_signpos
= self
._getSignedValue
(newvalue
)
2776 ## dbg('old value: "%s"' % value)
2777 ## dbg('new value: "%s"' % newvalue)
2779 self
._SetValue
(newvalue
)
2780 except Exception, e
:
2781 ## dbg('exception raised:', e, 'resetting to initial value')
2782 self
._SetInitialValue
()
2783 elif not self
._signOk
and ('(' in value
or '-' in value
):
2784 newvalue
, signpos
, right_signpos
= self
._getSignedValue
(value
)
2785 ## dbg('old value: "%s"' % value)
2786 ## dbg('new value: "%s"' % newvalue)
2788 self
._SetValue
(newvalue
)
2790 ## dbg('exception raised:', e, 'resetting to initial value')
2791 self
._SetInitialValue
()
2793 # Replace up/down arrow default handling:
2794 # make down act like tab, up act like shift-tab:
2796 #### dbg('Registering numeric navigation and control handlers (if not already set)')
2797 if not self
._keyhandlers
.has_key(wx
.WXK_DOWN
):
2798 self
._SetKeycodeHandler
(wx
.WXK_DOWN
, self
._OnChangeField
)
2799 if not self
._keyhandlers
.has_key(wx
.WXK_NUMPAD_DOWN
):
2800 self
._SetKeycodeHandler
(wx
.WXK_DOWN
, self
._OnChangeField
)
2801 if not self
._keyhandlers
.has_key(wx
.WXK_UP
):
2802 self
._SetKeycodeHandler
(wx
.WXK_UP
, self
._OnUpNumeric
) # (adds "shift" to up arrow, and calls _OnChangeField)
2803 if not self
._keyhandlers
.has_key(wx
.WXK_NUMPAD_UP
):
2804 self
._SetKeycodeHandler
(wx
.WXK_UP
, self
._OnUpNumeric
) # (adds "shift" to up arrow, and calls _OnChangeField)
2806 # On ., truncate contents right of cursor to decimal point (if any)
2807 # leaves cursor after decimal point if floating point, otherwise at 0.
2808 if not self
._keyhandlers
.has_key(ord(self
._decimalChar
)) or self
._keyhandlers
[ord(self
._decimalChar
)] != self
._OnDecimalPoint
:
2809 self
._SetKeyHandler
(self
._decimalChar
, self
._OnDecimalPoint
)
2811 if not self
._keyhandlers
.has_key(ord(self
._shiftDecimalChar
)) or self
._keyhandlers
[ord(self
._shiftDecimalChar
)] != self
._OnChangeField
:
2812 self
._SetKeyHandler
(self
._shiftDecimalChar
, self
._OnChangeField
) # (Shift-'.' == '>' on US keyboards)
2814 # Allow selective insert of groupchar in numbers:
2815 if not self
._keyhandlers
.has_key(ord(self
._fields
[0]._groupChar
)) or self
._keyhandlers
[ord(self
._fields
[0]._groupChar
)] != self
._OnGroupChar
:
2816 self
._SetKeyHandler
(self
._fields
[0]._groupChar
, self
._OnGroupChar
)
2818 ## dbg(indent=0, suspend=0)
2821 def _SetInitialValue(self
, value
=""):
2823 fills the control with the generated or supplied default value.
2824 It will also set/reset the font if necessary and apply
2825 formatting to the control at this time.
2827 ## dbg('MaskedEditMixin::_SetInitialValue("%s")' % value, indent=1)
2829 self
._prevValue
= self
._curValue
= self
._template
2830 # don't apply external validation rules in this case, as template may
2831 # not coincide with "legal" value...
2833 self
._SetValue
(self
._curValue
) # note the use of "raw" ._SetValue()...
2834 except Exception, e
:
2835 ## dbg('exception thrown:', e, indent=0)
2838 # Otherwise apply validation as appropriate to passed value:
2839 #### dbg('value = "%s", length:' % value, len(value))
2840 self
._prevValue
= self
._curValue
= value
2842 self
.SetValue(value
) # use public (validating) .SetValue()
2843 except Exception, e
:
2844 ## dbg('exception thrown:', e, indent=0)
2848 # Set value/type-specific formatting
2849 self
._applyFormatting
()
2853 def _calcSize(self
, size
=None):
2854 """ Calculate automatic size if allowed; must be called after the base control is instantiated"""
2855 #### dbg('MaskedEditMixin::_calcSize', indent=1)
2856 cont
= (size
is None or size
== wx
.DefaultSize
)
2858 if cont
and self
._autofit
:
2859 sizing_text
= 'M' * self
._masklength
2860 if wx
.Platform
!= "__WXMSW__": # give it a little extra space
2862 if wx
.Platform
== "__WXMAC__": # give it even a little more...
2864 #### dbg('len(sizing_text):', len(sizing_text), 'sizing_text: "%s"' % sizing_text)
2865 w
, h
= self
.GetTextExtent(sizing_text
)
2866 size
= (w
+4, self
.GetSize().height
)
2867 #### dbg('size:', size, indent=0)
2872 """ Set the control's font typeface -- pass the font name as str."""
2873 #### dbg('MaskedEditMixin::_setFont', indent=1)
2874 if not self
._useFixedWidthFont
:
2875 self
._font
= wx
.SystemSettings_GetFont(wx
.SYS_DEFAULT_GUI_FONT
)
2877 font
= self
.GetFont() # get size, weight, etc from current font
2879 # Set to teletype font (guaranteed to be mappable to all wxWindows
2881 self
._font
= wx
.Font( font
.GetPointSize(), wx
.TELETYPE
, font
.GetStyle(),
2882 font
.GetWeight(), font
.GetUnderlined())
2883 #### dbg('font string: "%s"' % font.GetNativeFontInfo().ToString())
2885 self
.SetFont(self
._font
)
2889 def _OnTextChange(self
, event
):
2891 Handler for EVT_TEXT event.
2892 self._Change() is provided for subclasses, and may return False to
2893 skip this method logic. This function returns True if the event
2894 detected was a legitimate event, or False if it was a "bogus"
2895 EVT_TEXT event. (NOTE: There is currently an issue with calling
2896 .SetValue from within the EVT_CHAR handler that causes duplicate
2897 EVT_TEXT events for the same change.)
2899 newvalue
= self
._GetValue
()
2900 ## dbg('MaskedEditMixin::_OnTextChange: value: "%s"' % newvalue, indent=1)
2902 if self
._ignoreChange
: # ie. if an "intermediate text change event"
2906 ##! WS: For some inexplicable reason, every wx.TextCtrl.SetValue
2907 ## call is generating two (2) EVT_TEXT events. On certain platforms,
2908 ## (eg. linux/GTK) the 1st is an empty string value.
2909 ## This is the only mechanism I can find to mask this problem:
2910 if newvalue
== self
._curValue
or len(newvalue
) == 0:
2911 ## dbg('ignoring bogus text change event', indent=0)
2914 ## dbg('curvalue: "%s", newvalue: "%s", len(newvalue): %d' % (self._curValue, newvalue, len(newvalue)))
2916 if self
._signOk
and self
._isNeg
and newvalue
.find('-') == -1 and newvalue
.find('(') == -1:
2917 ## dbg('clearing self._isNeg')
2919 text
, self
._signpos
, self
._right
_signpos
= self
._getSignedValue
()
2920 self
._CheckValid
() # Recolor control as appropriate
2921 ## dbg('calling event.Skip()')
2924 self
._prevValue
= self
._curValue
# save for undo
2925 self
._curValue
= newvalue
# Save last seen value for next iteration
2930 def _OnKeyDown(self
, event
):
2932 This function allows the control to capture Ctrl-events like Ctrl-tab,
2933 that are not normally seen by the "cooked" EVT_CHAR routine.
2935 # Get keypress value, adjusted by control options (e.g. convert to upper etc)
2936 key
= event
.GetKeyCode()
2937 if key
in self
._nav
and event
.ControlDown():
2938 # then this is the only place we will likely see these events;
2940 ## dbg('MaskedEditMixin::OnKeyDown: calling _OnChar')
2943 # else allow regular EVT_CHAR key processing
2947 def _OnChar(self
, event
):
2949 This is the engine of MaskedEdit controls. It examines each keystroke,
2950 decides if it's allowed, where it should go or what action to take.
2952 ## dbg('MaskedEditMixin::_OnChar', indent=1)
2954 # Get keypress value, adjusted by control options (e.g. convert to upper etc)
2955 key
= event
.GetKeyCode()
2956 orig_pos
= self
._GetInsertionPoint
()
2957 orig_value
= self
._GetValue
()
2958 ## dbg('keycode = ', key)
2959 ## dbg('current pos = ', orig_pos)
2960 ## dbg('current selection = ', self._GetSelection())
2962 if not self
._Keypress
(key
):
2966 # If no format string for this control, or the control is marked as "read-only",
2967 # skip the rest of the special processing, and just "do the standard thing:"
2968 if not self
._mask
or not self
._IsEditable
():
2973 # Process navigation and control keys first, with
2974 # position/selection unadulterated:
2975 if key
in self
._nav
+ self
._control
:
2976 if self
._keyhandlers
.has_key(key
):
2977 keep_processing
= self
._keyhandlers
[key
](event
)
2978 if self
._GetValue
() != orig_value
:
2979 self
.modified
= True
2980 if not keep_processing
:
2983 self
._applyFormatting
()
2987 # Else... adjust the position as necessary for next input key,
2988 # and determine resulting selection:
2989 pos
= self
._adjustPos
( orig_pos
, key
) ## get insertion position, adjusted as needed
2990 sel_start
, sel_to
= self
._GetSelection
() ## check for a range of selected text
2991 ## dbg("pos, sel_start, sel_to:", pos, sel_start, sel_to)
2993 keep_processing
= True
2994 # Capture user past end of format field
2995 if pos
> len(self
.maskdict
):
2996 ## dbg("field length exceeded:",pos)
2997 keep_processing
= False
2999 key
= self
._adjustKey
(pos
, key
) # apply formatting constraints to key:
3001 if self
._keyhandlers
.has_key(key
):
3002 # there's an override for default behavior; use override function instead
3003 ## dbg('using supplied key handler:', self._keyhandlers[key])
3004 keep_processing
= self
._keyhandlers
[key
](event
)
3005 if self
._GetValue
() != orig_value
:
3006 self
.modified
= True
3007 if not keep_processing
:
3010 # else skip default processing, but do final formatting
3011 if key
in wx_control_keycodes
:
3012 ## dbg('key in wx_control_keycodes')
3013 event
.Skip() # non-printable; let base control handle it
3014 keep_processing
= False
3016 field
= self
._FindField
(pos
)
3018 if 'unicode' in wx
.PlatformInfo
:
3020 char
= chr(key
) # (must work if we got this far)
3021 char
= char
.decode(self
._defaultEncoding
)
3023 char
= unichr(event
.GetUnicodeKey())
3024 dbg('unicode char:', char
)
3026 if type(field
._excludeChars
) != types
.UnicodeType
:
3027 excludes
+= field
._excludeChars
.decode(self
._defaultEncoding
)
3028 if type(self
._ctrl
_constraints
) != types
.UnicodeType
:
3029 excludes
+= self
._ctrl
_constraints
._excludeChars
.decode(self
._defaultEncoding
)
3031 char
= chr(key
) # (must work if we got this far)
3032 excludes
= field
._excludeChars
+ self
._ctrl
_constraints
._excludeChars
3034 ## dbg("key ='%s'" % chr(key))
3036 ## dbg('okSpaces?', field._okSpaces)
3040 if char
in excludes
:
3041 keep_processing
= False
3043 if keep_processing
and self
._isCharAllowed
( char
, pos
, checkRegex
= True ):
3044 ## dbg("key allowed by mask")
3045 # insert key into candidate new value, but don't change control yet:
3046 oldstr
= self
._GetValue
()
3047 newstr
, newpos
, new_select_to
, match_field
, match_index
= self
._insertKey
(
3048 char
, pos
, sel_start
, sel_to
, self
._GetValue
(), allowAutoSelect
= True)
3049 ## dbg("str with '%s' inserted:" % char, '"%s"' % newstr)
3050 if self
._ctrl
_constraints
._validRequired
and not self
.IsValid(newstr
):
3051 ## dbg('not valid; checking to see if adjusted string is:')
3052 keep_processing
= False
3053 if self
._isFloat
and newstr
!= self
._template
:
3054 newstr
= self
._adjustFloat
(newstr
)
3055 ## dbg('adjusted str:', newstr)
3056 if self
.IsValid(newstr
):
3058 keep_processing
= True
3059 wx
.CallAfter(self
._SetInsertionPoint
, self
._decimalpos
)
3060 if not keep_processing
:
3061 ## dbg("key disallowed by validation")
3062 if not wx
.Validator_IsSilent() and orig_pos
== pos
:
3068 # special case: adjust date value as necessary:
3069 if self
._isDate
and newstr
!= self
._template
:
3070 newstr
= self
._adjustDate
(newstr
)
3071 ## dbg('adjusted newstr:', newstr)
3073 if newstr
!= orig_value
:
3074 self
.modified
= True
3076 wx
.CallAfter(self
._SetValue
, newstr
)
3078 # Adjust insertion point on date if just entered 2 digit year, and there are now 4 digits:
3079 if not self
.IsDefault() and self
._isDate
and self
._4digityear
:
3080 year2dig
= self
._dateExtent
- 2
3081 if pos
== year2dig
and unadjusted
[year2dig
] != newstr
[year2dig
]:
3084 ## dbg('queuing insertion point: (%d)' % newpos)
3085 wx
.CallAfter(self
._SetInsertionPoint
, newpos
)
3087 if match_field
is not None:
3088 ## dbg('matched field')
3089 self
._OnAutoSelect
(match_field
, match_index
)
3091 if new_select_to
!= newpos
:
3092 ## dbg('queuing selection: (%d, %d)' % (newpos, new_select_to))
3093 wx
.CallAfter(self
._SetSelection
, newpos
, new_select_to
)
3095 newfield
= self
._FindField
(newpos
)
3096 if newfield
!= field
and newfield
._selectOnFieldEntry
:
3097 ## dbg('queuing insertion point: (%d)' % newfield._extent[0])
3098 wx
.CallAfter(self
._SetInsertionPoint
, newfield
._extent
[0])
3099 ## dbg('queuing selection: (%d, %d)' % (newfield._extent[0], newfield._extent[1]))
3100 wx
.CallAfter(self
._SetSelection
, newfield
._extent
[0], newfield
._extent
[1])
3102 wx
.CallAfter(self
._SetSelection
, newpos
, new_select_to
)
3103 keep_processing
= False
3105 elif keep_processing
:
3106 ## dbg('char not allowed')
3107 keep_processing
= False
3108 if (not wx
.Validator_IsSilent()) and orig_pos
== pos
:
3111 self
._applyFormatting
()
3113 # Move to next insertion point
3114 if keep_processing
and key
not in self
._nav
:
3115 pos
= self
._GetInsertionPoint
()
3116 next_entry
= self
._findNextEntry
( pos
)
3117 if pos
!= next_entry
:
3118 ## dbg("moving from %(pos)d to next valid entry: %(next_entry)d" % locals())
3119 wx
.CallAfter(self
._SetInsertionPoint
, next_entry
)
3121 if self
._isTemplateChar
(pos
):
3122 self
._AdjustField
(pos
)
3126 def _FindFieldExtent(self
, pos
=None, getslice
=False, value
=None):
3127 """ returns editable extent of field corresponding to
3128 position pos, and, optionally, the contents of that field
3129 in the control or the value specified.
3130 Template chars are bound to the preceding field.
3131 For masks beginning with template chars, these chars are ignored
3132 when calculating the current field.
3134 Eg: with template (###) ###-####,
3135 >>> self._FindFieldExtent(pos=0)
3137 >>> self._FindFieldExtent(pos=1)
3139 >>> self._FindFieldExtent(pos=5)
3141 >>> self._FindFieldExtent(pos=6)
3143 >>> self._FindFieldExtent(pos=10)
3147 ## dbg('MaskedEditMixin::_FindFieldExtent(pos=%s, getslice=%s)' % (str(pos), str(getslice)) ,indent=1)
3149 field
= self
._FindField
(pos
)
3152 return None, None, ""
3155 edit_start
, edit_end
= field
._extent
3157 if value
is None: value
= self
._GetValue
()
3158 slice = value
[edit_start
:edit_end
]
3159 ## dbg('edit_start:', edit_start, 'edit_end:', edit_end, 'slice: "%s"' % slice)
3161 return edit_start
, edit_end
, slice
3163 ## dbg('edit_start:', edit_start, 'edit_end:', edit_end)
3165 return edit_start
, edit_end
3168 def _FindField(self
, pos
=None):
3170 Returns the field instance in which pos resides.
3171 Template chars are bound to the preceding field.
3172 For masks beginning with template chars, these chars are ignored
3173 when calculating the current field.
3176 #### dbg('MaskedEditMixin::_FindField(pos=%s)' % str(pos) ,indent=1)
3177 if pos
is None: pos
= self
._GetInsertionPoint
()
3178 elif pos
< 0 or pos
> self
._masklength
:
3179 raise IndexError('position %s out of range of control' % str(pos
))
3181 if len(self
._fields
) == 0:
3187 return self
._fields
[self
._lookupField
[pos
]]
3190 def ClearValue(self
):
3191 """ Blanks the current control value by replacing it with the default value."""
3192 ## dbg("MaskedEditMixin::ClearValue - value reset to default value (template)")
3193 self
._SetValue
( self
._template
)
3194 self
._SetInsertionPoint
(0)
3198 def _baseCtrlEventHandler(self
, event
):
3200 This function is used whenever a key should be handled by the base control.
3206 def _OnUpNumeric(self
, event
):
3208 Makes up-arrow act like shift-tab should; ie. take you to start of
3211 ## dbg('MaskedEditMixin::_OnUpNumeric', indent=1)
3212 event
.m_shiftDown
= 1
3213 ## dbg('event.ShiftDown()?', event.ShiftDown())
3214 self
._OnChangeField
(event
)
3218 def _OnArrow(self
, event
):
3220 Used in response to left/right navigation keys; makes these actions skip
3221 over mask template chars.
3223 ## dbg("MaskedEditMixin::_OnArrow", indent=1)
3224 pos
= self
._GetInsertionPoint
()
3225 keycode
= event
.GetKeyCode()
3226 sel_start
, sel_to
= self
._GetSelection
()
3227 entry_end
= self
._goEnd
(getPosOnly
=True)
3228 if keycode
in (wx
.WXK_RIGHT
, wx
.WXK_DOWN
, wx
.WXK_NUMPAD_RIGHT
, wx
.WXK_NUMPAD_DOWN
):
3229 if( ( not self
._isTemplateChar
(pos
) and pos
+1 > entry_end
)
3230 or ( self
._isTemplateChar
(pos
) and pos
>= entry_end
) ):
3231 ## dbg("can't advance", indent=0)
3233 elif self
._isTemplateChar
(pos
):
3234 self
._AdjustField
(pos
)
3235 elif keycode
in (wx
.WXK_LEFT
, wx
.WXK_UP
, wx
.WXK_NUMPAD_LEFT
, wx
.WXK_NUMPAD_UP
) and sel_start
== sel_to
and pos
> 0 and self
._isTemplateChar
(pos
-1):
3236 ## dbg('adjusting field')
3237 self
._AdjustField
(pos
)
3239 # treat as shifted up/down arrows as tab/reverse tab:
3240 if event
.ShiftDown() and keycode
in (wx
.WXK_UP
, wx
.WXK_DOWN
, wx
.WXK_NUMPAD_UP
, wx
.WXK_NUMPAD_DOWN
):
3241 # remove "shifting" and treat as (forward) tab:
3242 event
.m_shiftDown
= False
3243 keep_processing
= self
._OnChangeField
(event
)
3245 elif self
._FindField
(pos
)._selectOnFieldEntry
:
3246 if( keycode
in (wx
.WXK_UP
, wx
.WXK_LEFT
, wx
.WXK_NUMPAD_UP
, wx
.WXK_NUMPAD_LEFT
)
3248 and self
._isTemplateChar
(sel_start
-1)
3249 and sel_start
!= self
._masklength
3250 and not self
._signOk
and not self
._useParens
):
3252 # call _OnChangeField to handle "ctrl-shifted event"
3253 # (which moves to previous field and selects it.)
3254 event
.m_shiftDown
= True
3255 event
.m_ControlDown
= True
3256 keep_processing
= self
._OnChangeField
(event
)
3257 elif( keycode
in (wx
.WXK_DOWN
, wx
.WXK_RIGHT
, wx
.WXK_NUMPAD_DOWN
, wx
.WXK_NUMPAD_RIGHT
)
3258 and sel_to
!= self
._masklength
3259 and self
._isTemplateChar
(sel_to
)):
3261 # when changing field to the right, ensure don't accidentally go left instead
3262 event
.m_shiftDown
= False
3263 keep_processing
= self
._OnChangeField
(event
)
3265 # treat arrows as normal, allowing selection
3267 ## dbg('using base ctrl event processing')
3270 if( (sel_to
== self
._fields
[0]._extent
[0] and keycode
in (wx
.WXK_LEFT
, wx
.WXK_NUMPAD_LEFT
) )
3271 or (sel_to
== self
._masklength
and keycode
in (wx
.WXK_RIGHT
, wx
.WXK_NUMPAD_RIGHT
) ) ):
3272 if not wx
.Validator_IsSilent():
3275 # treat arrows as normal, allowing selection
3277 ## dbg('using base event processing')
3280 keep_processing
= False
3282 return keep_processing
3285 def _OnCtrl_S(self
, event
):
3286 """ Default Ctrl-S handler; prints value information if demo enabled. """
3287 ## dbg("MaskedEditMixin::_OnCtrl_S")
3289 print 'MaskedEditMixin.GetValue() = "%s"\nMaskedEditMixin.GetPlainValue() = "%s"' % (self
.GetValue(), self
.GetPlainValue())
3290 print "Valid? => " + str(self
.IsValid())
3291 print "Current field, start, end, value =", str( self
._FindFieldExtent
(getslice
=True))
3295 def _OnCtrl_X(self
, event
=None):
3296 """ Handles ctrl-x keypress in control and Cut operation on context menu.
3297 Should return False to skip other processing. """
3298 ## dbg("MaskedEditMixin::_OnCtrl_X", indent=1)
3303 def _OnCtrl_C(self
, event
=None):
3304 """ Handles ctrl-C keypress in control and Copy operation on context menu.
3305 Uses base control handling. Should return False to skip other processing."""
3309 def _OnCtrl_V(self
, event
=None):
3310 """ Handles ctrl-V keypress in control and Paste operation on context menu.
3311 Should return False to skip other processing. """
3312 ## dbg("MaskedEditMixin::_OnCtrl_V", indent=1)
3317 def _OnInsert(self
, event
=None):
3318 """ Handles shift-insert and control-insert operations (paste and copy, respectively)"""
3319 ## dbg("MaskedEditMixin::_OnInsert", indent=1)
3320 if event
and isinstance(event
, wx
.KeyEvent
):
3321 if event
.ShiftDown():
3323 elif event
.ControlDown():
3330 def _OnDelete(self
, event
=None):
3331 """ Handles shift-delete and delete operations (cut and erase, respectively)"""
3332 ## dbg("MaskedEditMixin::_OnDelete", indent=1)
3333 if event
and isinstance(event
, wx
.KeyEvent
):
3334 if event
.ShiftDown():
3337 self
._OnErase
(event
)
3339 self
._OnErase
(event
)
3343 def _OnCtrl_Z(self
, event
=None):
3344 """ Handles ctrl-Z keypress in control and Undo operation on context menu.
3345 Should return False to skip other processing. """
3346 ## dbg("MaskedEditMixin::_OnCtrl_Z", indent=1)
3351 def _OnCtrl_A(self
,event
=None):
3352 """ Handles ctrl-a keypress in control. Should return False to skip other processing. """
3353 end
= self
._goEnd
(getPosOnly
=True)
3354 if not event
or (isinstance(event
, wx
.KeyEvent
) and event
.ShiftDown()):
3355 wx
.CallAfter(self
._SetInsertionPoint
, 0)
3356 wx
.CallAfter(self
._SetSelection
, 0, self
._masklength
)
3358 wx
.CallAfter(self
._SetInsertionPoint
, 0)
3359 wx
.CallAfter(self
._SetSelection
, 0, end
)
3363 def _OnErase(self
, event
=None, just_return_value
=False):
3364 """ Handles backspace and delete keypress in control. Should return False to skip other processing."""
3365 ## dbg("MaskedEditMixin::_OnErase", indent=1)
3366 sel_start
, sel_to
= self
._GetSelection
() ## check for a range of selected text
3368 if event
is None: # called as action routine from Cut() operation.
3371 key
= event
.GetKeyCode()
3373 field
= self
._FindField
(sel_to
)
3374 start
, end
= field
._extent
3375 value
= self
._GetValue
()
3376 oldstart
= sel_start
3378 # If trying to erase beyond "legal" bounds, disallow operation:
3379 if( (sel_to
== 0 and key
== wx
.WXK_BACK
)
3380 or (self
._signOk
and sel_to
== 1 and value
[0] == ' ' and key
== wx
.WXK_BACK
)
3381 or (sel_to
== self
._masklength
and sel_start
== sel_to
and key
in (wx
.WXK_DELETE
, wx
.WXK_NUMPAD_DELETE
) and not field
._insertRight
)
3382 or (self
._signOk
and self
._useParens
3383 and sel_start
== sel_to
3384 and sel_to
== self
._masklength
- 1
3385 and value
[sel_to
] == ' ' and key
in (wx
.WXK_DELETE
, wx
.WXK_NUMPAD_DELETE
) and not field
._insertRight
) ):
3386 if not wx
.Validator_IsSilent():
3392 if( field
._insertRight
# an insert-right field
3393 and value
[start
:end
] != self
._template
[start
:end
] # and field not empty
3394 and sel_start
>= start
# and selection starts in field
3395 and ((sel_to
== sel_start
# and no selection
3396 and sel_to
== end
# and cursor at right edge
3397 and key
in (wx
.WXK_BACK
, wx
.WXK_DELETE
, wx
.WXK_NUMPAD_DELETE
)) # and either delete or backspace key
3399 (key
== wx
.WXK_BACK
# backspacing
3400 and (sel_to
== end
# and selection ends at right edge
3401 or sel_to
< end
and field
._allowInsert
)) ) ): # or allow right insert at any point in field
3403 ## dbg('delete left')
3404 # if backspace but left of cursor is empty, adjust cursor right before deleting
3405 while( key
== wx
.WXK_BACK
3406 and sel_start
== sel_to
3408 and value
[start
:sel_start
] == self
._template
[start
:sel_start
]):
3412 ## dbg('sel_start, start:', sel_start, start)
3414 if sel_start
== sel_to
:
3418 newfield
= value
[start
:keep
] + value
[sel_to
:end
]
3420 # handle sign char moving from outside field into the field:
3421 move_sign_into_field
= False
3422 if not field
._padZero
and self
._signOk
and self
._isNeg
and value
[0] in ('-', '('):
3424 newfield
= signchar
+ newfield
3425 move_sign_into_field
= True
3426 ## dbg('cut newfield: "%s"' % newfield)
3428 # handle what should fill in from the left:
3430 for i
in range(start
, end
- len(newfield
)):
3433 elif( self
._signOk
and self
._isNeg
and i
== 1
3434 and ((self
._useParens
and newfield
.find('(') == -1)
3435 or (not self
._useParens
and newfield
.find('-') == -1)) ):
3438 left
+= self
._template
[i
] # this can produce strange results in combination with default values...
3439 newfield
= left
+ newfield
3440 ## dbg('filled newfield: "%s"' % newfield)
3442 newstr
= value
[:start
] + newfield
+ value
[end
:]
3444 # (handle sign located in "mask position" in front of field prior to delete)
3445 if move_sign_into_field
:
3446 newstr
= ' ' + newstr
[1:]
3449 # handle erasure of (left) sign, moving selection accordingly...
3450 if self
._signOk
and sel_start
== 0:
3451 newstr
= value
= ' ' + value
[1:]
3454 if field
._allowInsert
and sel_start
>= start
:
3455 # selection (if any) falls within current insert-capable field:
3456 select_len
= sel_to
- sel_start
3457 # determine where cursor should end up:
3458 if key
== wx
.WXK_BACK
:
3460 newpos
= sel_start
-1
3466 if sel_to
== sel_start
:
3467 erase_to
= sel_to
+ 1
3471 if self
._isTemplateChar
(newpos
) and select_len
== 0:
3473 if value
[newpos
] in ('(', '-'):
3474 newpos
+= 1 # don't move cusor
3475 newstr
= ' ' + value
[newpos
:]
3476 elif value
[newpos
] == ')':
3477 # erase right sign, but don't move cursor; (matching left sign handled later)
3478 newstr
= value
[:newpos
] + ' '
3480 # no deletion; just move cursor
3483 # no deletion; just move cursor
3486 if erase_to
> end
: erase_to
= end
3487 erase_len
= erase_to
- newpos
3489 left
= value
[start
:newpos
]
3490 ## dbg("retained ='%s'" % value[erase_to:end], 'sel_to:', sel_to, "fill: '%s'" % self._template[end - erase_len:end])
3491 right
= value
[erase_to
:end
] + self
._template
[end
-erase_len
:end
]
3493 if field
._alignRight
:
3494 rstripped
= right
.rstrip()
3495 if rstripped
!= right
:
3496 pos_adjust
= len(right
) - len(rstripped
)
3499 if not field
._insertRight
and value
[-1] == ')' and end
== self
._masklength
- 1:
3500 # need to shift ) into the field:
3501 right
= right
[:-1] + ')'
3502 value
= value
[:-1] + ' '
3504 newfield
= left
+right
3506 newfield
= newfield
.rjust(end
-start
)
3507 newpos
+= pos_adjust
3508 ## dbg("left='%s', right ='%s', newfield='%s'" %(left, right, newfield))
3509 newstr
= value
[:start
] + newfield
+ value
[end
:]
3514 if sel_start
== sel_to
:
3515 ## dbg("current sel_start, sel_to:", sel_start, sel_to)
3516 if key
== wx
.WXK_BACK
:
3517 sel_start
, sel_to
= sel_to
-1, sel_to
-1
3518 ## dbg("new sel_start, sel_to:", sel_start, sel_to)
3520 if field
._padZero
and not value
[start
:sel_to
].replace('0', '').replace(' ','').replace(field
._fillChar
, ''):
3521 # preceding chars (if any) are zeros, blanks or fillchar; new char should be 0:
3524 newchar
= self
._template
[sel_to
] ## get an original template character to "clear" the current char
3525 ## dbg('value = "%s"' % value, 'value[%d] = "%s"' %(sel_start, value[sel_start]))
3527 if self
._isTemplateChar
(sel_to
):
3528 if sel_to
== 0 and self
._signOk
and value
[sel_to
] == '-': # erasing "template" sign char
3529 newstr
= ' ' + value
[1:]
3531 elif self
._signOk
and self
._useParens
and (value
[sel_to
] == ')' or value
[sel_to
] == '('):
3532 # allow "change sign" by removing both parens:
3533 newstr
= value
[:self
._signpos
] + ' ' + value
[self
._signpos
+1:-1] + ' '
3538 if field
._insertRight
and sel_start
== sel_to
:
3539 # force non-insert-right behavior, by selecting char to be replaced:
3541 newstr
, ignore
= self
._insertKey
(newchar
, sel_start
, sel_start
, sel_to
, value
)
3545 newstr
= self
._eraseSelection
(value
, sel_start
, sel_to
)
3547 pos
= sel_start
# put cursor back at beginning of selection
3549 if self
._signOk
and self
._useParens
:
3550 # account for resultant unbalanced parentheses:
3551 left_signpos
= newstr
.find('(')
3552 right_signpos
= newstr
.find(')')
3554 if left_signpos
== -1 and right_signpos
!= -1:
3555 # erased left-sign marker; get rid of right sign marker:
3556 newstr
= newstr
[:right_signpos
] + ' ' + newstr
[right_signpos
+1:]
3558 elif left_signpos
!= -1 and right_signpos
== -1:
3559 # erased right-sign marker; get rid of left-sign marker:
3560 newstr
= newstr
[:left_signpos
] + ' ' + newstr
[left_signpos
+1:]
3562 ## dbg("oldstr:'%s'" % value, 'oldpos:', oldstart)
3563 ## dbg("newstr:'%s'" % newstr, 'pos:', pos)
3565 # if erasure results in an invalid field, disallow it:
3566 ## dbg('field._validRequired?', field._validRequired)
3567 ## dbg('field.IsValid("%s")?' % newstr[start:end], field.IsValid(newstr[start:end]))
3568 if field
._validRequired
and not field
.IsValid(newstr
[start
:end
]):
3569 if not wx
.Validator_IsSilent():
3574 # if erasure results in an invalid value, disallow it:
3575 if self
._ctrl
_constraints
._validRequired
and not self
.IsValid(newstr
):
3576 if not wx
.Validator_IsSilent():
3581 if just_return_value
:
3586 ## dbg('setting value (later) to', newstr)
3587 wx
.CallAfter(self
._SetValue
, newstr
)
3588 ## dbg('setting insertion point (later) to', pos)
3589 wx
.CallAfter(self
._SetInsertionPoint
, pos
)
3592 self
.modified
= True
3596 def _OnEnd(self
,event
):
3597 """ Handles End keypress in control. Should return False to skip other processing. """
3598 ## dbg("MaskedEditMixin::_OnEnd", indent=1)
3599 pos
= self
._adjustPos
(self
._GetInsertionPoint
(), event
.GetKeyCode())
3600 if not event
.ControlDown():
3601 end
= self
._masklength
# go to end of control
3602 if self
._signOk
and self
._useParens
:
3603 end
= end
- 1 # account for reserved char at end
3605 end_of_input
= self
._goEnd
(getPosOnly
=True)
3606 sel_start
, sel_to
= self
._GetSelection
()
3607 if sel_to
< pos
: sel_to
= pos
3608 field
= self
._FindField
(sel_to
)
3609 field_end
= self
._FindField
(end_of_input
)
3611 # pick different end point if either:
3612 # - cursor not in same field
3613 # - or at or past last input already
3614 # - or current selection = end of current field:
3615 #### dbg('field != field_end?', field != field_end)
3616 #### dbg('sel_to >= end_of_input?', sel_to >= end_of_input)
3617 if field
!= field_end
or sel_to
>= end_of_input
:
3618 edit_start
, edit_end
= field
._extent
3619 #### dbg('edit_end:', edit_end)
3620 #### dbg('sel_to:', sel_to)
3621 #### dbg('sel_to == edit_end?', sel_to == edit_end)
3622 #### dbg('field._index < self._field_indices[-1]?', field._index < self._field_indices[-1])
3624 if sel_to
== edit_end
and field
._index
< self
._field
_indices
[-1]:
3625 edit_start
, edit_end
= self
._FindFieldExtent
(self
._findNextEntry
(edit_end
)) # go to end of next field:
3627 ## dbg('end moved to', end)
3629 elif sel_to
== edit_end
and field
._index
== self
._field
_indices
[-1]:
3630 # already at edit end of last field; select to end of control:
3631 end
= self
._masklength
3632 ## dbg('end moved to', end)
3634 end
= edit_end
# select to end of current field
3635 ## dbg('end moved to ', end)
3637 # select to current end of input
3641 #### dbg('pos:', pos, 'end:', end)
3643 if event
.ShiftDown():
3644 if not event
.ControlDown():
3645 ## dbg("shift-end; select to end of control")
3648 ## dbg("shift-ctrl-end; select to end of non-whitespace")
3650 wx
.CallAfter(self
._SetInsertionPoint
, pos
)
3651 wx
.CallAfter(self
._SetSelection
, pos
, end
)
3653 if not event
.ControlDown():
3654 ## dbg('go to end of control:')
3656 wx
.CallAfter(self
._SetInsertionPoint
, end
)
3657 wx
.CallAfter(self
._SetSelection
, end
, end
)
3663 def _OnReturn(self
, event
):
3665 Swallows the return, issues a Navigate event instead, since
3666 masked controls are "single line" by defn.
3668 ## dbg('MaskedEditMixin::OnReturn')
3673 def _OnHome(self
,event
):
3674 """ Handles Home keypress in control. Should return False to skip other processing."""
3675 ## dbg("MaskedEditMixin::_OnHome", indent=1)
3676 pos
= self
._adjustPos
(self
._GetInsertionPoint
(), event
.GetKeyCode())
3677 sel_start
, sel_to
= self
._GetSelection
()
3679 # There are 5 cases here:
3681 # 1) shift: select from start of control to end of current
3683 if event
.ShiftDown() and not event
.ControlDown():
3684 ## dbg("shift-home; select to start of control")
3688 # 2) no shift, no control: move cursor to beginning of control.
3689 elif not event
.ControlDown():
3690 ## dbg("home; move to start of control")
3694 # 3) No shift, control: move cursor back to beginning of field; if
3695 # there already, go to beginning of previous field.
3696 # 4) shift, control, start of selection not at beginning of control:
3697 # move sel_start back to start of field; if already there, go to
3698 # start of previous field.
3699 elif( event
.ControlDown()
3700 and (not event
.ShiftDown()
3701 or (event
.ShiftDown() and sel_start
> 0) ) ):
3702 if len(self
._field
_indices
) > 1:
3703 field
= self
._FindField
(sel_start
)
3704 start
, ignore
= field
._extent
3705 if sel_start
== start
and field
._index
!= self
._field
_indices
[0]: # go to start of previous field:
3706 start
, ignore
= self
._FindFieldExtent
(sel_start
-1)
3707 elif sel_start
== start
:
3708 start
= 0 # go to literal beginning if edit start
3715 if not event
.ShiftDown():
3716 ## dbg("ctrl-home; move to beginning of field")
3719 ## dbg("shift-ctrl-home; select to beginning of field")
3723 # 5) shift, control, start of selection at beginning of control:
3724 # unselect by moving sel_to backward to beginning of current field;
3725 # if already there, move to start of previous field.
3727 if len(self
._field
_indices
) > 1:
3728 # find end of previous field:
3729 field
= self
._FindField
(sel_to
)
3730 if sel_to
> start
and field
._index
!= self
._field
_indices
[0]:
3731 ignore
, end
= self
._FindFieldExtent
(field
._extent
[0]-1)
3737 end_of_field
= False
3738 ## dbg("shift-ctrl-home; unselect to beginning of field")
3740 ## dbg('queuing new sel_start, sel_to:', (start, end))
3741 wx
.CallAfter(self
._SetInsertionPoint
, start
)
3742 wx
.CallAfter(self
._SetSelection
, start
, end
)
3747 def _OnChangeField(self
, event
):
3749 Primarily handles TAB events, but can be used for any key that
3750 designer wants to change fields within a masked edit control.
3752 ## dbg('MaskedEditMixin::_OnChangeField', indent = 1)
3753 # determine end of current field:
3754 pos
= self
._GetInsertionPoint
()
3755 ## dbg('current pos:', pos)
3756 sel_start
, sel_to
= self
._GetSelection
()
3758 if self
._masklength
< 0: # no fields; process tab normally
3759 self
._AdjustField
(pos
)
3760 if event
.GetKeyCode() == wx
.WXK_TAB
:
3761 ## dbg('tab to next ctrl')
3762 # As of 2.5.2, you don't call event.Skip() to do
3763 # this, but instead force explicit navigation, if
3764 # wx.TE_PROCESS_TAB is used (like in the masked edits)
3771 if event
.ShiftDown():
3775 # NOTE: doesn't yet work with SHIFT-tab under wx; the control
3776 # never sees this event! (But I've coded for it should it ever work,
3777 # and it *does* work for '.' in IpAddrCtrl.)
3778 field
= self
._FindField
(pos
)
3779 index
= field
._index
3780 field_start
= field
._extent
[0]
3781 if pos
< field_start
:
3782 ## dbg('cursor before 1st field; cannot change to a previous field')
3783 if not wx
.Validator_IsSilent():
3787 if event
.ControlDown():
3788 ## dbg('queuing select to beginning of field:', field_start, pos)
3789 wx
.CallAfter(self
._SetInsertionPoint
, field_start
)
3790 wx
.CallAfter(self
._SetSelection
, field_start
, pos
)
3795 # We're already in the 1st field; process shift-tab normally:
3796 self
._AdjustField
(pos
)
3797 if event
.GetKeyCode() == wx
.WXK_TAB
:
3798 ## dbg('tab to previous ctrl')
3799 # As of 2.5.2, you don't call event.Skip() to do
3800 # this, but instead force explicit navigation, if
3801 # wx.TE_PROCESS_TAB is used (like in the masked edits)
3802 self
.Navigate(False)
3804 ## dbg('position at beginning')
3805 wx
.CallAfter(self
._SetInsertionPoint
, field_start
)
3809 # find beginning of previous field:
3810 begin_prev
= self
._FindField
(field_start
-1)._extent
[0]
3811 self
._AdjustField
(pos
)
3812 ## dbg('repositioning to', begin_prev)
3813 wx
.CallAfter(self
._SetInsertionPoint
, begin_prev
)
3814 if self
._FindField
(begin_prev
)._selectOnFieldEntry
:
3815 edit_start
, edit_end
= self
._FindFieldExtent
(begin_prev
)
3816 ## dbg('queuing selection to (%d, %d)' % (edit_start, edit_end))
3817 wx
.CallAfter(self
._SetInsertionPoint
, edit_start
)
3818 wx
.CallAfter(self
._SetSelection
, edit_start
, edit_end
)
3824 field
= self
._FindField
(sel_to
)
3825 field_start
, field_end
= field
._extent
3826 if event
.ControlDown():
3827 ## dbg('queuing select to end of field:', pos, field_end)
3828 wx
.CallAfter(self
._SetInsertionPoint
, pos
)
3829 wx
.CallAfter(self
._SetSelection
, pos
, field_end
)
3833 if pos
< field_start
:
3834 ## dbg('cursor before 1st field; go to start of field')
3835 wx
.CallAfter(self
._SetInsertionPoint
, field_start
)
3836 if field
._selectOnFieldEntry
:
3837 wx
.CallAfter(self
._SetSelection
, field_start
, field_end
)
3839 wx
.CallAfter(self
._SetSelection
, field_start
, field_start
)
3842 ## dbg('end of current field:', field_end)
3843 ## dbg('go to next field')
3844 if field_end
== self
._fields
[self
._field
_indices
[-1]]._extent
[1]:
3845 self
._AdjustField
(pos
)
3846 if event
.GetKeyCode() == wx
.WXK_TAB
:
3847 ## dbg('tab to next ctrl')
3848 # As of 2.5.2, you don't call event.Skip() to do
3849 # this, but instead force explicit navigation, if
3850 # wx.TE_PROCESS_TAB is used (like in the masked edits)
3853 ## dbg('position at end')
3854 wx
.CallAfter(self
._SetInsertionPoint
, field_end
)
3858 # we have to find the start of the next field
3859 next_pos
= self
._findNextEntry
(field_end
)
3860 if next_pos
== field_end
:
3861 ## dbg('already in last field')
3862 self
._AdjustField
(pos
)
3863 if event
.GetKeyCode() == wx
.WXK_TAB
:
3864 ## dbg('tab to next ctrl')
3865 # As of 2.5.2, you don't call event.Skip() to do
3866 # this, but instead force explicit navigation, if
3867 # wx.TE_PROCESS_TAB is used (like in the masked edits)
3873 self
._AdjustField
( pos
)
3875 # move cursor to appropriate point in the next field and select as necessary:
3876 field
= self
._FindField
(next_pos
)
3877 edit_start
, edit_end
= field
._extent
3878 if field
._selectOnFieldEntry
:
3879 ## dbg('move to ', next_pos)
3880 wx
.CallAfter(self
._SetInsertionPoint
, next_pos
)
3881 edit_start
, edit_end
= self
._FindFieldExtent
(next_pos
)
3882 ## dbg('queuing select', edit_start, edit_end)
3883 wx
.CallAfter(self
._SetSelection
, edit_start
, edit_end
)
3885 if field
._insertRight
:
3886 next_pos
= field
._extent
[1]
3887 ## dbg('move to ', next_pos)
3888 wx
.CallAfter(self
._SetInsertionPoint
, next_pos
)
3893 def _OnDecimalPoint(self
, event
):
3894 ## dbg('MaskedEditMixin::_OnDecimalPoint', indent=1)
3896 pos
= self
._adjustPos
(self
._GetInsertionPoint
(), event
.GetKeyCode())
3898 if self
._isFloat
: ## handle float value, move to decimal place
3899 ## dbg('key == Decimal tab; decimal pos:', self._decimalpos)
3900 value
= self
._GetValue
()
3901 if pos
< self
._decimalpos
:
3902 clipped_text
= value
[0:pos
] + self
._decimalChar
+ value
[self
._decimalpos
+1:]
3903 ## dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text)
3904 newstr
= self
._adjustFloat
(clipped_text
)
3906 newstr
= self
._adjustFloat
(value
)
3907 wx
.CallAfter(self
._SetValue
, newstr
)
3908 fraction
= self
._fields
[1]
3909 start
, end
= fraction
._extent
3910 wx
.CallAfter(self
._SetInsertionPoint
, start
)
3911 if fraction
._selectOnFieldEntry
:
3912 ## dbg('queuing selection after decimal point to:', (start, end))
3913 wx
.CallAfter(self
._SetSelection
, start
, end
)
3915 wx
.CallAfter(self
._SetSelection
, start
, start
)
3916 keep_processing
= False
3918 if self
._isInt
: ## handle integer value, truncate from current position
3919 ## dbg('key == Integer decimal event')
3920 value
= self
._GetValue
()
3921 clipped_text
= value
[0:pos
]
3922 ## dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text)
3923 newstr
= self
._adjustInt
(clipped_text
)
3924 ## dbg('newstr: "%s"' % newstr)
3925 wx
.CallAfter(self
._SetValue
, newstr
)
3926 newpos
= len(newstr
.rstrip())
3927 if newstr
.find(')') != -1:
3928 newpos
-= 1 # (don't move past right paren)
3929 wx
.CallAfter(self
._SetInsertionPoint
, newpos
)
3930 wx
.CallAfter(self
._SetSelection
, newpos
, newpos
)
3931 keep_processing
= False
3935 def _OnChangeSign(self
, event
):
3936 ## dbg('MaskedEditMixin::_OnChangeSign', indent=1)
3937 key
= event
.GetKeyCode()
3938 pos
= self
._adjustPos
(self
._GetInsertionPoint
(), key
)
3939 value
= self
._eraseSelection
()
3940 integer
= self
._fields
[0]
3941 start
, end
= integer
._extent
3942 sel_start
, sel_to
= self
._GetSelection
()
3944 #### dbg('adjusted pos:', pos)
3945 if chr(key
) in ('-','+','(', ')') or (chr(key
) == " " and pos
== self
._signpos
):
3946 cursign
= self
._isNeg
3947 ## dbg('cursign:', cursign)
3948 if chr(key
) in ('-','(', ')'):
3949 if sel_start
<= self
._signpos
:
3952 self
._isNeg
= (not self
._isNeg
) ## flip value
3955 ## dbg('isNeg?', self._isNeg)
3957 text
, self
._signpos
, self
._right
_signpos
= self
._getSignedValue
(candidate
=value
)
3958 ## dbg('text:"%s"' % text, 'signpos:', self._signpos, 'right_signpos:', self._right_signpos)
3962 if self
._isNeg
and self
._signpos
is not None and self
._signpos
!= -1:
3963 if self
._useParens
and self
._right
_signpos
is not None:
3964 text
= text
[:self
._signpos
] + '(' + text
[self
._signpos
+1:self
._right
_signpos
] + ')' + text
[self
._right
_signpos
+1:]
3966 text
= text
[:self
._signpos
] + '-' + text
[self
._signpos
+1:]
3968 #### dbg('self._isNeg?', self._isNeg, 'self.IsValid(%s)' % text, self.IsValid(text))
3970 text
= text
[:self
._signpos
] + ' ' + text
[self
._signpos
+1:self
._right
_signpos
] + ' ' + text
[self
._right
_signpos
+1:]
3972 text
= text
[:self
._signpos
] + ' ' + text
[self
._signpos
+1:]
3973 ## dbg('clearing self._isNeg')
3976 wx
.CallAfter(self
._SetValue
, text
)
3977 wx
.CallAfter(self
._applyFormatting
)
3978 ## dbg('pos:', pos, 'signpos:', self._signpos)
3979 if pos
== self
._signpos
or integer
.IsEmpty(text
[start
:end
]):
3980 wx
.CallAfter(self
._SetInsertionPoint
, self
._signpos
+1)
3982 wx
.CallAfter(self
._SetInsertionPoint
, pos
)
3984 keep_processing
= False
3986 keep_processing
= True
3988 return keep_processing
3991 def _OnGroupChar(self
, event
):
3993 This handler is only registered if the mask is a numeric mask.
3994 It allows the insertion of ',' or '.' if appropriate.
3996 ## dbg('MaskedEditMixin::_OnGroupChar', indent=1)
3997 keep_processing
= True
3998 pos
= self
._adjustPos
(self
._GetInsertionPoint
(), event
.GetKeyCode())
3999 sel_start
, sel_to
= self
._GetSelection
()
4000 groupchar
= self
._fields
[0]._groupChar
4001 if not self
._isCharAllowed
(groupchar
, pos
, checkRegex
=True):
4002 keep_processing
= False
4003 if not wx
.Validator_IsSilent():
4007 newstr
, newpos
= self
._insertKey
(groupchar
, pos
, sel_start
, sel_to
, self
._GetValue
() )
4008 ## dbg("str with '%s' inserted:" % groupchar, '"%s"' % newstr)
4009 if self
._ctrl
_constraints
._validRequired
and not self
.IsValid(newstr
):
4010 keep_processing
= False
4011 if not wx
.Validator_IsSilent():
4015 wx
.CallAfter(self
._SetValue
, newstr
)
4016 wx
.CallAfter(self
._SetInsertionPoint
, newpos
)
4017 keep_processing
= False
4019 return keep_processing
4022 def _findNextEntry(self
,pos
, adjustInsert
=True):
4023 """ Find the insertion point for the next valid entry character position."""
4024 ## dbg('MaskedEditMixin::_findNextEntry', indent=1)
4025 if self
._isTemplateChar
(pos
) or pos
in self
._explicit
_field
_boundaries
: # if changing fields, pay attn to flag
4026 adjustInsert
= adjustInsert
4027 else: # else within a field; flag not relevant
4028 adjustInsert
= False
4030 while self
._isTemplateChar
(pos
) and pos
< self
._masklength
:
4033 # if changing fields, and we've been told to adjust insert point,
4034 # look at new field; if empty and right-insert field,
4035 # adjust to right edge:
4036 if adjustInsert
and pos
< self
._masklength
:
4037 field
= self
._FindField
(pos
)
4038 start
, end
= field
._extent
4039 slice = self
._GetValue
()[start
:end
]
4040 if field
._insertRight
and field
.IsEmpty(slice):
4042 ## dbg('final pos:', pos, indent=0)
4046 def _findNextTemplateChar(self
, pos
):
4047 """ Find the position of the next non-editable character in the mask."""
4048 while not self
._isTemplateChar
(pos
) and pos
< self
._masklength
:
4053 def _OnAutoCompleteField(self
, event
):
4054 ## dbg('MaskedEditMixin::_OnAutoCompleteField', indent =1)
4055 pos
= self
._GetInsertionPoint
()
4056 field
= self
._FindField
(pos
)
4057 edit_start
, edit_end
, slice = self
._FindFieldExtent
(pos
, getslice
=True)
4060 keycode
= event
.GetKeyCode()
4062 if field
._fillChar
!= ' ':
4063 text
= slice.replace(field
._fillChar
, '')
4067 keep_processing
= True # (assume True to start)
4068 ## dbg('field._hasList?', field._hasList)
4070 ## dbg('choices:', field._choices)
4071 ## dbg('compareChoices:', field._compareChoices)
4072 choices
, choice_required
= field
._compareChoices
, field
._choiceRequired
4073 if keycode
in (wx
.WXK_PRIOR
, wx
.WXK_UP
, wx
.WXK_NUMPAD_PRIOR
, wx
.WXK_NUMPAD_UP
):
4077 match_index
, partial_match
= self
._autoComplete
(direction
, choices
, text
, compareNoCase
=field
._compareNoCase
, current_index
= field
._autoCompleteIndex
)
4078 if( match_index
is None
4079 and (keycode
in self
._autoCompleteKeycodes
+ [wx
.WXK_PRIOR
, wx
.WXK_NEXT
, wx
.WXK_NUMPAD_PRIOR
, wx
.WXK_NUMPAD_NEXT
]
4080 or (keycode
in [wx
.WXK_UP
, wx
.WXK_DOWN
, wx
.WXK_NUMPAD_UP
, wx
.WXK_NUMPAD_DOWN
] and event
.ShiftDown() ) ) ):
4081 # Select the 1st thing from the list:
4084 if( match_index
is not None
4085 and ( keycode
in self
._autoCompleteKeycodes
+ [wx
.WXK_PRIOR
, wx
.WXK_NEXT
, wx
.WXK_NUMPAD_PRIOR
, wx
.WXK_NUMPAD_NEXT
]
4086 or (keycode
in [wx
.WXK_UP
, wx
.WXK_DOWN
, wx
.WXK_NUMPAD_UP
, wx
.WXK_NUMPAD_DOWN
] and event
.ShiftDown())
4087 or (keycode
in [wx
.WXK_DOWN
, wx
.WXK_NUMPAD_DOWN
] and partial_match
) ) ):
4089 # We're allowed to auto-complete:
4090 ## dbg('match found')
4091 value
= self
._GetValue
()
4092 newvalue
= value
[:edit_start
] + field
._choices
[match_index
] + value
[edit_end
:]
4093 ## dbg('setting value to "%s"' % newvalue)
4094 self
._SetValue
(newvalue
)
4095 self
._SetInsertionPoint
(min(edit_end
, len(newvalue
.rstrip())))
4096 self
._OnAutoSelect
(field
, match_index
)
4097 self
._CheckValid
() # recolor as appopriate
4100 if keycode
in (wx
.WXK_UP
, wx
.WXK_DOWN
, wx
.WXK_LEFT
, wx
.WXK_RIGHT
,
4101 wx
.WXK_NUMPAD_UP
, wx
.WXK_NUMPAD_DOWN
, wx
.WXK_NUMPAD_LEFT
, wx
.WXK_NUMPAD_RIGHT
):
4102 # treat as left right arrow if unshifted, tab/shift tab if shifted.
4103 if event
.ShiftDown():
4104 if keycode
in (wx
.WXK_DOWN
, wx
.WXK_RIGHT
, wx
.WXK_NUMPAD_DOWN
, wx
.WXK_NUMPAD_RIGHT
):
4105 # remove "shifting" and treat as (forward) tab:
4106 event
.m_shiftDown
= False
4107 keep_processing
= self
._OnChangeField
(event
)
4109 keep_processing
= self
._OnArrow
(event
)
4110 # else some other key; keep processing the key
4112 ## dbg('keep processing?', keep_processing, indent=0)
4113 return keep_processing
4116 def _OnAutoSelect(self
, field
, match_index
= None):
4118 Function called if autoselect feature is enabled and entire control
4121 ## dbg('MaskedEditMixin::OnAutoSelect', field._index)
4122 if match_index
is not None:
4123 field
._autoCompleteIndex
= match_index
4126 def _autoComplete(self
, direction
, choices
, value
, compareNoCase
, current_index
):
4128 This function gets called in response to Auto-complete events.
4129 It attempts to find a match to the specified value against the
4130 list of choices; if exact match, the index of then next
4131 appropriate value in the list, based on the given direction.
4132 If not an exact match, it will return the index of the 1st value from
4133 the choice list for which the partial value can be extended to match.
4134 If no match found, it will return None.
4135 The function returns a 2-tuple, with the 2nd element being a boolean
4136 that indicates if partial match was necessary.
4138 ## dbg('autoComplete(direction=', direction, 'choices=',choices, 'value=',value,'compareNoCase?', compareNoCase, 'current_index:', current_index, indent=1)
4140 ## dbg('nothing to match against', indent=0)
4141 return (None, False)
4143 partial_match
= False
4146 value
= value
.lower()
4148 last_index
= len(choices
) - 1
4149 if value
in choices
:
4150 ## dbg('"%s" in', choices)
4151 if current_index
is not None and choices
[current_index
] == value
:
4152 index
= current_index
4154 index
= choices
.index(value
)
4156 ## dbg('matched "%s" (%d)' % (choices[index], index))
4158 ## dbg('going to previous')
4159 if index
== 0: index
= len(choices
) - 1
4162 if index
== len(choices
) - 1: index
= 0
4164 ## dbg('change value to "%s" (%d)' % (choices[index], index))
4167 partial_match
= True
4168 value
= value
.strip()
4169 ## dbg('no match; try to auto-complete:')
4171 ## dbg('searching for "%s"' % value)
4172 if current_index
is None:
4173 indices
= range(len(choices
))
4178 indices
= range(current_index
+1, len(choices
)) + range(current_index
+1)
4179 ## dbg('range(current_index+1 (%d), len(choices) (%d)) + range(%d):' % (current_index+1, len(choices), current_index+1), indices)
4181 indices
= range(current_index
-1, -1, -1) + range(len(choices
)-1, current_index
-1, -1)
4182 ## 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)
4183 #### dbg('indices:', indices)
4184 for index
in indices
:
4185 choice
= choices
[index
]
4186 if choice
.find(value
, 0) == 0:
4187 ## dbg('match found:', choice)
4191 ## dbg('choice: "%s" - no match' % choice)
4193 if match
is not None:
4194 ## dbg('matched', match)
4197 ## dbg('no match found')
4200 return (match
, partial_match
)
4203 def _AdjustField(self
, pos
):
4205 This function gets called by default whenever the cursor leaves a field.
4206 The pos argument given is the char position before leaving that field.
4207 By default, floating point, integer and date values are adjusted to be
4208 legal in this function. Derived classes may override this function
4209 to modify the value of the control in a different way when changing fields.
4211 NOTE: these change the value immediately, and restore the cursor to
4212 the passed location, so that any subsequent code can then move it
4213 based on the operation being performed.
4215 newvalue
= value
= self
._GetValue
()
4216 field
= self
._FindField
(pos
)
4217 start
, end
, slice = self
._FindFieldExtent
(getslice
=True)
4218 newfield
= field
._AdjustField
(slice)
4219 newvalue
= value
[:start
] + newfield
+ value
[end
:]
4221 if self
._isFloat
and newvalue
!= self
._template
:
4222 newvalue
= self
._adjustFloat
(newvalue
)
4224 if self
._ctrl
_constraints
._isInt
and value
!= self
._template
:
4225 newvalue
= self
._adjustInt
(value
)
4227 if self
._isDate
and value
!= self
._template
:
4228 newvalue
= self
._adjustDate
(value
, fixcentury
=True)
4229 if self
._4digityear
:
4230 year2dig
= self
._dateExtent
- 2
4231 if pos
== year2dig
and value
[year2dig
] != newvalue
[year2dig
]:
4234 if newvalue
!= value
:
4235 ## dbg('old value: "%s"\nnew value: "%s"' % (value, newvalue))
4236 self
._SetValue
(newvalue
)
4237 self
._SetInsertionPoint
(pos
)
4240 def _adjustKey(self
, pos
, key
):
4241 """ Apply control formatting to the key (e.g. convert to upper etc). """
4242 field
= self
._FindField
(pos
)
4243 if field
._forceupper
and key
in range(97,123):
4244 key
= ord( chr(key
).upper())
4246 if field
._forcelower
and key
in range(97,123):
4247 key
= ord( chr(key
).lower())
4252 def _adjustPos(self
, pos
, key
):
4254 Checks the current insertion point position and adjusts it if
4255 necessary to skip over non-editable characters.
4257 ## dbg('_adjustPos', pos, key, indent=1)
4258 sel_start
, sel_to
= self
._GetSelection
()
4259 # If a numeric or decimal mask, and negatives allowed, reserve the
4260 # first space for sign, and last one if using parens.
4262 and ((pos
== self
._signpos
and key
in (ord('-'), ord('+'), ord(' ')) )
4263 or (self
._useParens
and pos
== self
._masklength
-1))):
4264 ## dbg('adjusted pos:', pos, indent=0)
4267 if key
not in self
._nav
:
4268 field
= self
._FindField
(pos
)
4270 ## dbg('field._insertRight?', field._insertRight)
4271 ## if self._signOk: dbg('self._signpos:', self._signpos)
4272 if field
._insertRight
: # if allow right-insert
4273 start
, end
= field
._extent
4274 slice = self
._GetValue
()[start
:end
].strip()
4275 field_len
= end
- start
4276 if pos
== end
: # if cursor at right edge of field
4277 # if not filled or supposed to stay in field, keep current position
4278 #### dbg('pos==end')
4279 #### dbg('len (slice):', len(slice))
4280 #### dbg('field_len?', field_len)
4281 #### dbg('pos==end; len (slice) < field_len?', len(slice) < field_len)
4282 #### dbg('not field._moveOnFieldFull?', not field._moveOnFieldFull)
4283 if len(slice) == field_len
and field
._moveOnFieldFull
:
4284 # move cursor to next field:
4285 pos
= self
._findNextEntry
(pos
)
4286 self
._SetInsertionPoint
(pos
)
4288 self
._SetSelection
(pos
, sel_to
) # restore selection
4290 self
._SetSelection
(pos
, pos
) # remove selection
4291 else: # leave cursor alone
4294 # if at start of control, move to right edge
4295 if (sel_to
== sel_start
4296 and (self
._isTemplateChar
(pos
) or (pos
== start
and len(slice)+ 1 < field_len
))
4298 pos
= end
# move to right edge
4299 ## elif sel_start <= start and sel_to == end:
4300 ## # select to right edge of field - 1 (to replace char)
4302 ## self._SetInsertionPoint(pos)
4303 ## # restore selection
4304 ## self._SetSelection(sel_start, pos)
4306 # if selected to beginning and signed, and not changing sign explicitly:
4307 elif self
._signOk
and sel_start
== 0 and key
not in (ord('-'), ord('+'), ord(' ')):
4308 # adjust to past reserved sign position:
4309 pos
= self
._fields
[0]._extent
[0]
4310 ## dbg('adjusting field to ', pos)
4311 self
._SetInsertionPoint
(pos
)
4312 # but keep original selection, to allow replacement of any sign:
4313 self
._SetSelection
(0, sel_to
)
4315 pass # leave position/selection alone
4317 # else make sure the user is not trying to type over a template character
4318 # If they are, move them to the next valid entry position
4319 elif self
._isTemplateChar
(pos
):
4320 if( not field
._moveOnFieldFull
4321 and (not self
._signOk
4323 and field
._index
== 0
4324 and pos
> 0) ) ): # don't move to next field without explicit cursor movement
4327 # find next valid position
4328 pos
= self
._findNextEntry
(pos
)
4329 self
._SetInsertionPoint
(pos
)
4330 if pos
< sel_to
: # restore selection
4331 self
._SetSelection
(pos
, sel_to
)
4333 self
._SetSelection
(pos
, pos
)
4334 ## dbg('adjusted pos:', pos, indent=0)
4338 def _adjustFloat(self
, candidate
=None):
4340 'Fixes' an floating point control. Collapses spaces, right-justifies, etc.
4342 ## dbg('MaskedEditMixin::_adjustFloat, candidate = "%s"' % candidate, indent=1)
4343 lenInt
,lenFraction
= [len(s
) for s
in self
._mask
.split('.')] ## Get integer, fraction lengths
4345 if candidate
is None: value
= self
._GetValue
()
4346 else: value
= candidate
4347 ## dbg('value = "%(value)s"' % locals(), 'len(value):', len(value))
4348 intStr
, fracStr
= value
.split(self
._decimalChar
)
4350 intStr
= self
._fields
[0]._AdjustField
(intStr
)
4351 ## dbg('adjusted intStr: "%s"' % intStr)
4352 lenInt
= len(intStr
)
4353 fracStr
= fracStr
+ ('0'*(lenFraction
-len(fracStr
))) # add trailing spaces to decimal
4355 ## dbg('intStr "%(intStr)s"' % locals())
4356 ## dbg('lenInt:', lenInt)
4358 intStr
= string
.rjust( intStr
[-lenInt
:], lenInt
)
4359 ## dbg('right-justifed intStr = "%(intStr)s"' % locals())
4360 newvalue
= intStr
+ self
._decimalChar
+ fracStr
4363 if len(newvalue
) < self
._masklength
:
4364 newvalue
= ' ' + newvalue
4365 signedvalue
= self
._getSignedValue
(newvalue
)[0]
4366 if signedvalue
is not None: newvalue
= signedvalue
4368 # Finally, align string with decimal position, left-padding with
4370 newdecpos
= newvalue
.find(self
._decimalChar
)
4371 if newdecpos
< self
._decimalpos
:
4372 padlen
= self
._decimalpos
- newdecpos
4373 newvalue
= string
.join([' ' * padlen
] + [newvalue
] ,'')
4375 if self
._signOk
and self
._useParens
:
4376 if newvalue
.find('(') != -1:
4377 newvalue
= newvalue
[:-1] + ')'
4379 newvalue
= newvalue
[:-1] + ' '
4381 ## dbg('newvalue = "%s"' % newvalue)
4382 if candidate
is None:
4383 wx
.CallAfter(self
._SetValue
, newvalue
)
4388 def _adjustInt(self
, candidate
=None):
4389 """ 'Fixes' an integer control. Collapses spaces, right or left-justifies."""
4390 ## dbg("MaskedEditMixin::_adjustInt", candidate)
4391 lenInt
= self
._masklength
4392 if candidate
is None: value
= self
._GetValue
()
4393 else: value
= candidate
4395 intStr
= self
._fields
[0]._AdjustField
(value
)
4396 intStr
= intStr
.strip() # drop extra spaces
4397 ## dbg('adjusted field: "%s"' % intStr)
4399 if self
._isNeg
and intStr
.find('-') == -1 and intStr
.find('(') == -1:
4401 intStr
= '(' + intStr
+ ')'
4403 intStr
= '-' + intStr
4404 elif self
._isNeg
and intStr
.find('-') != -1 and self
._useParens
:
4405 intStr
= intStr
.replace('-', '(')
4407 if( self
._signOk
and ((self
._useParens
and intStr
.find('(') == -1)
4408 or (not self
._useParens
and intStr
.find('-') == -1))):
4409 intStr
= ' ' + intStr
4411 intStr
+= ' ' # space for right paren position
4413 elif self
._signOk
and self
._useParens
and intStr
.find('(') != -1 and intStr
.find(')') == -1:
4414 # ensure closing right paren:
4417 if self
._fields
[0]._alignRight
: ## Only if right-alignment is enabled
4418 intStr
= intStr
.rjust( lenInt
)
4420 intStr
= intStr
.ljust( lenInt
)
4422 if candidate
is None:
4423 wx
.CallAfter(self
._SetValue
, intStr
)
4427 def _adjustDate(self
, candidate
=None, fixcentury
=False, force4digit_year
=False):
4429 'Fixes' a date control, expanding the year if it can.
4430 Applies various self-formatting options.
4432 ## dbg("MaskedEditMixin::_adjustDate", indent=1)
4433 if candidate
is None: text
= self
._GetValue
()
4434 else: text
= candidate
4435 ## dbg('text=', text)
4436 if self
._datestyle
== "YMD":
4441 ## dbg('getYear: "%s"' % _getYear(text, self._datestyle))
4442 year
= string
.replace( _getYear( text
, self
._datestyle
),self
._fields
[year_field
]._fillChar
,"") # drop extra fillChars
4443 month
= _getMonth( text
, self
._datestyle
)
4444 day
= _getDay( text
, self
._datestyle
)
4445 ## dbg('self._datestyle:', self._datestyle, 'year:', year, 'Month', month, 'day:', day)
4448 yearstart
= self
._dateExtent
- 4
4452 or (self
._GetInsertionPoint
() > yearstart
+1 and text
[yearstart
+2] == ' ')
4453 or (self
._GetInsertionPoint
() > yearstart
+2 and text
[yearstart
+3] == ' ') ) ):
4454 ## user entered less than four digits and changing fields or past point where we could
4455 ## enter another digit:
4459 ## dbg('bad year=', year)
4460 year
= text
[yearstart
:self
._dateExtent
]
4462 if len(year
) < 4 and yearVal
:
4464 # Fix year adjustment to be less "20th century" :-) and to adjust heuristic as the
4466 now
= wx
.DateTime_Now()
4467 century
= (now
.GetYear() /100) * 100 # "this century"
4468 twodig_year
= now
.GetYear() - century
# "this year" (2 digits)
4469 # if separation between today's 2-digit year and typed value > 50,
4470 # assume last century,
4471 # else assume this century.
4473 # Eg: if 2003 and yearVal == 30, => 2030
4474 # if 2055 and yearVal == 80, => 2080
4475 # if 2010 and yearVal == 96, => 1996
4477 if abs(yearVal
- twodig_year
) > 50:
4478 yearVal
= (century
- 100) + yearVal
4480 yearVal
= century
+ yearVal
4481 year
= str( yearVal
)
4482 else: # pad with 0's to make a 4-digit year
4483 year
= "%04d" % yearVal
4484 if self
._4digityear
or force4digit_year
:
4485 text
= _makeDate(year
, month
, day
, self
._datestyle
, text
) + text
[self
._dateExtent
:]
4486 ## dbg('newdate: "%s"' % text, indent=0)
4490 def _goEnd(self
, getPosOnly
=False):
4491 """ Moves the insertion point to the end of user-entry """
4492 ## dbg("MaskedEditMixin::_goEnd; getPosOnly:", getPosOnly, indent=1)
4493 text
= self
._GetValue
()
4494 #### dbg('text: "%s"' % text)
4496 if len(text
.rstrip()):
4497 for i
in range( min( self
._masklength
-1, len(text
.rstrip())), -1, -1):
4498 #### dbg('i:', i, 'self._isMaskChar(%d)' % i, self._isMaskChar(i))
4499 if self
._isMaskChar
(i
):
4501 #### dbg("text[%d]: '%s'" % (i, char))
4507 pos
= self
._goHome
(getPosOnly
=True)
4509 pos
= min(i
,self
._masklength
)
4511 field
= self
._FindField
(pos
)
4512 start
, end
= field
._extent
4513 if field
._insertRight
and pos
< end
:
4515 ## dbg('next pos:', pos)
4520 self
._SetInsertionPoint
(pos
)
4523 def _goHome(self
, getPosOnly
=False):
4524 """ Moves the insertion point to the beginning of user-entry """
4525 ## dbg("MaskedEditMixin::_goHome; getPosOnly:", getPosOnly, indent=1)
4526 text
= self
._GetValue
()
4527 for i
in range(self
._masklength
):
4528 if self
._isMaskChar
(i
):
4535 self
._SetInsertionPoint
(max(i
,0))
4539 def _getAllowedChars(self
, pos
):
4540 """ Returns a string of all allowed user input characters for the provided
4541 mask character plus control options
4543 maskChar
= self
.maskdict
[pos
]
4544 okchars
= self
.maskchardict
[maskChar
] ## entry, get mask approved characters
4546 # convert okchars to unicode if required; will force subsequent appendings to
4547 # result in unicode strings
4548 if 'unicode' in wx
.PlatformInfo
and type(okchars
) != types
.UnicodeType
:
4549 okchars
= okchars
.decode(self
._defaultEncoding
)
4551 field
= self
._FindField
(pos
)
4552 if okchars
and field
._okSpaces
: ## Allow spaces?
4554 if okchars
and field
._includeChars
: ## any additional included characters?
4555 okchars
+= field
._includeChars
4556 #### dbg('okchars[%d]:' % pos, okchars)
4560 def _isMaskChar(self
, pos
):
4561 """ Returns True if the char at position pos is a special mask character (e.g. NCXaA#)
4563 if pos
< self
._masklength
:
4564 return self
._ismasked
[pos
]
4569 def _isTemplateChar(self
,Pos
):
4570 """ Returns True if the char at position pos is a template character (e.g. -not- NCXaA#)
4572 if Pos
< self
._masklength
:
4573 return not self
._isMaskChar
(Pos
)
4578 def _isCharAllowed(self
, char
, pos
, checkRegex
=False, allowAutoSelect
=True, ignoreInsertRight
=False):
4579 """ Returns True if character is allowed at the specific position, otherwise False."""
4580 ## dbg('_isCharAllowed', char, pos, checkRegex, indent=1)
4581 field
= self
._FindField
(pos
)
4582 right_insert
= False
4584 if self
.controlInitialized
:
4585 sel_start
, sel_to
= self
._GetSelection
()
4587 sel_start
, sel_to
= pos
, pos
4589 if (field
._insertRight
or self
._ctrl
_constraints
._insertRight
) and not ignoreInsertRight
:
4590 start
, end
= field
._extent
4591 field_len
= end
- start
4592 if self
.controlInitialized
:
4593 value
= self
._GetValue
()
4594 fstr
= value
[start
:end
].strip()
4596 while fstr
and fstr
[0] == '0':
4598 input_len
= len(fstr
)
4599 if self
._signOk
and '-' in fstr
or '(' in fstr
:
4600 input_len
-= 1 # sign can move out of field, so don't consider it in length
4602 value
= self
._template
4603 input_len
= 0 # can't get the current "value", so use 0
4606 # if entire field is selected or position is at end and field is not full,
4607 # or if allowed to right-insert at any point in field and field is not full and cursor is not at a fillChar
4608 # or the field is a singleton integer field and is currently 0 and we're at the end:
4609 if( (sel_start
, sel_to
) == field
._extent
4610 or (pos
== end
and ((input_len
< field_len
)
4612 and input_len
== field_len
4614 and value
[end
-1] == '0'
4618 ## dbg('pos = end - 1 = ', pos, 'right_insert? 1')
4620 elif( field
._allowInsert
and sel_start
== sel_to
4621 and (sel_to
== end
or (sel_to
< self
._masklength
and value
[sel_start
] != field
._fillChar
))
4622 and input_len
< field_len
):
4623 pos
= sel_to
- 1 # where character will go
4624 ## dbg('pos = sel_to - 1 = ', pos, 'right_insert? 1')
4626 # else leave pos alone...
4628 ## dbg('pos stays ', pos, 'right_insert? 0')
4631 if self
._isTemplateChar
( pos
): ## if a template character, return empty
4632 ## dbg('%d is a template character; returning False' % pos, indent=0)
4635 if self
._isMaskChar
( pos
):
4636 okChars
= self
._getAllowedChars
(pos
)
4638 if self
._fields
[0]._groupdigits
and (self
._isInt
or (self
._isFloat
and pos
< self
._decimalpos
)):
4639 okChars
+= self
._fields
[0]._groupChar
4642 if self
._isInt
or (self
._isFloat
and pos
< self
._decimalpos
):
4646 elif self
._useParens
and (self
._isInt
or (self
._isFloat
and pos
> self
._decimalpos
)):
4649 #### dbg('%s in %s?' % (char, okChars), char in okChars)
4650 approved
= (self
.maskdict
[pos
] == '*' or char
in okChars
)
4652 if approved
and checkRegex
:
4653 ## dbg("checking appropriate regex's")
4654 value
= self
._eraseSelection
(self
._GetValue
())
4656 # move the position to the right side of the insertion:
4661 newvalue
, ignore
, ignore
, ignore
, ignore
= self
._insertKey
(char
, at
, sel_start
, sel_to
, value
, allowAutoSelect
=True)
4663 newvalue
, ignore
= self
._insertKey
(char
, at
, sel_start
, sel_to
, value
)
4664 ## dbg('newvalue: "%s"' % newvalue)
4666 fields
= [self
._FindField
(pos
)] + [self
._ctrl
_constraints
]
4667 for field
in fields
: # includes fields[-1] == "ctrl_constraints"
4668 if field
._regexMask
and field
._filter
:
4669 ## dbg('checking vs. regex')
4670 start
, end
= field
._extent
4671 slice = newvalue
[start
:end
]
4672 approved
= (re
.match( field
._filter
, slice) is not None)
4673 ## dbg('approved?', approved)
4674 if not approved
: break
4678 ## dbg('%d is a !???! character; returning False', indent=0)
4682 def _applyFormatting(self
):
4683 """ Apply formatting depending on the control's state.
4684 Need to find a way to call this whenever the value changes, in case the control's
4685 value has been changed or set programatically.
4688 ## dbg('MaskedEditMixin::_applyFormatting', indent=1)
4690 # Handle negative numbers
4692 text
, signpos
, right_signpos
= self
._getSignedValue
()
4693 ## dbg('text: "%s", signpos:' % text, signpos)
4694 if text
and signpos
!= self
._signpos
:
4695 self
._signpos
= signpos
4696 if not text
or text
[signpos
] not in ('-','('):
4698 ## dbg('no valid sign found; new sign:', self._isNeg)
4699 elif text
and self
._valid
and not self
._isNeg
and text
[signpos
] in ('-', '('):
4700 ## dbg('setting _isNeg to True')
4702 ## dbg('self._isNeg:', self._isNeg)
4704 if self
._signOk
and self
._isNeg
:
4705 fc
= self
._signedForegroundColour
4707 fc
= self
._foregroundColour
4709 if hasattr(fc
, '_name'):
4713 ## dbg('setting foreground to', c)
4714 self
.SetForegroundColour(fc
)
4719 bc
= self
._emptyBackgroundColour
4721 bc
= self
._validBackgroundColour
4724 bc
= self
._invalidBackgroundColour
4725 if hasattr(bc
, '_name'):
4729 ## dbg('setting background to', c)
4730 self
.SetBackgroundColour(bc
)
4732 ## dbg(indent=0, suspend=0)
4735 def _getAbsValue(self
, candidate
=None):
4736 """ Return an unsigned value (i.e. strip the '-' prefix if any), and sign position(s).
4738 ## dbg('MaskedEditMixin::_getAbsValue; candidate="%s"' % candidate, indent=1)
4739 if candidate
is None: text
= self
._GetValue
()
4740 else: text
= candidate
4741 right_signpos
= text
.find(')')
4744 if self
._ctrl
_constraints
._alignRight
and self
._fields
[0]._fillChar
== ' ':
4745 signpos
= text
.find('-')
4747 ## dbg('no - found; searching for (')
4748 signpos
= text
.find('(')
4750 ## dbg('- found at', signpos)
4754 ## dbg('signpos still -1')
4755 ## dbg('len(%s) (%d) < len(%s) (%d)?' % (text, len(text), self._mask, self._masklength), len(text) < self._masklength)
4756 if len(text
) < self
._masklength
:
4758 if len(text
) < self
._masklength
:
4760 if len(text
) > self
._masklength
and text
[-1] in (')', ' '):
4763 ## dbg('len(%s) (%d), len(%s) (%d)' % (text, len(text), self._mask, self._masklength))
4764 ## dbg('len(%s) - (len(%s) + 1):' % (text, text.lstrip()) , len(text) - (len(text.lstrip()) + 1))
4765 signpos
= len(text
) - (len(text
.lstrip()) + 1)
4767 if self
._useParens
and not text
.strip():
4768 signpos
-= 1 # empty value; use penultimate space
4769 ## dbg('signpos:', signpos)
4771 text
= text
[:signpos
] + ' ' + text
[signpos
+1:]
4776 text
= self
._template
[0] + text
[1:]
4780 if right_signpos
!= -1:
4782 text
= text
[:right_signpos
] + ' ' + text
[right_signpos
+1:]
4783 elif len(text
) > self
._masklength
:
4784 text
= text
[:right_signpos
] + text
[right_signpos
+1:]
4788 elif self
._useParens
and self
._signOk
:
4789 # figure out where it ought to go:
4790 right_signpos
= self
._masklength
- 1 # initial guess
4791 if not self
._ctrl
_constraints
._alignRight
:
4792 ## dbg('not right-aligned')
4793 if len(text
.strip()) == 0:
4794 right_signpos
= signpos
+ 1
4795 elif len(text
.strip()) < self
._masklength
:
4796 right_signpos
= len(text
.rstrip())
4797 ## dbg('right_signpos:', right_signpos)
4799 groupchar
= self
._fields
[0]._groupChar
4801 value
= long(text
.replace(groupchar
,'').replace('(','-').replace(')','').replace(' ', ''))
4803 ## dbg('invalid number', indent=0)
4804 return None, signpos
, right_signpos
4808 groupchar
= self
._fields
[0]._groupChar
4809 value
= float(text
.replace(groupchar
,'').replace(self
._decimalChar
, '.').replace('(', '-').replace(')','').replace(' ', ''))
4810 ## dbg('value:', value)
4814 if value
< 0 and value
is not None:
4815 signpos
= text
.find('-')
4817 signpos
= text
.find('(')
4819 text
= text
[:signpos
] + self
._template
[signpos
] + text
[signpos
+1:]
4821 # look forwards up to the decimal point for the 1st non-digit
4822 ## dbg('decimal pos:', self._decimalpos)
4823 ## dbg('text: "%s"' % text)
4825 signpos
= self
._decimalpos
- (len(text
[:self
._decimalpos
].lstrip()) + 1)
4826 # prevent checking for empty string - Tomo - Wed 14 Jan 2004 03:19:09 PM CET
4827 if len(text
) >= signpos
+1 and text
[signpos
+1] in ('-','('):
4831 ## dbg('signpos:', signpos)
4835 right_signpos
= self
._masklength
- 1
4836 text
= text
[:right_signpos
] + ' '
4837 if text
[signpos
] == '(':
4838 text
= text
[:signpos
] + ' ' + text
[signpos
+1:]
4840 right_signpos
= text
.find(')')
4841 if right_signpos
!= -1:
4846 ## dbg('invalid number')
4849 ## dbg('abstext = "%s"' % text, 'signpos:', signpos, 'right_signpos:', right_signpos)
4851 return text
, signpos
, right_signpos
4854 def _getSignedValue(self
, candidate
=None):
4855 """ Return a signed value by adding a "-" prefix if the value
4856 is set to negative, or a space if positive.
4858 ## dbg('MaskedEditMixin::_getSignedValue; candidate="%s"' % candidate, indent=1)
4859 if candidate
is None: text
= self
._GetValue
()
4860 else: text
= candidate
4863 abstext
, signpos
, right_signpos
= self
._getAbsValue
(text
)
4867 return abstext
, signpos
, right_signpos
4869 if self
._isNeg
or text
[signpos
] in ('-', '('):
4876 if abstext
[signpos
] not in string
.digits
:
4877 text
= abstext
[:signpos
] + sign
+ abstext
[signpos
+1:]
4879 # this can happen if value passed is too big; sign assumed to be
4880 # in position 0, but if already filled with a digit, prepend sign...
4881 text
= sign
+ abstext
4882 if self
._useParens
and text
.find('(') != -1:
4883 text
= text
[:right_signpos
] + ')' + text
[right_signpos
+1:]
4886 ## dbg('signedtext = "%s"' % text, 'signpos:', signpos, 'right_signpos', right_signpos)
4888 return text
, signpos
, right_signpos
4891 def GetPlainValue(self
, candidate
=None):
4892 """ Returns control's value stripped of the template text.
4893 plainvalue = MaskedEditMixin.GetPlainValue()
4895 ## dbg('MaskedEditMixin::GetPlainValue; candidate="%s"' % candidate, indent=1)
4897 if candidate
is None: text
= self
._GetValue
()
4898 else: text
= candidate
4901 ## dbg('returned ""', indent=0)
4905 for idx
in range( min(len(self
._template
), len(text
)) ):
4906 if self
._mask
[idx
] in maskchars
:
4909 if self
._isFloat
or self
._isInt
:
4910 ## dbg('plain so far: "%s"' % plain)
4911 plain
= plain
.replace('(', '-').replace(')', ' ')
4912 ## dbg('plain after sign regularization: "%s"' % plain)
4914 if self
._signOk
and self
._isNeg
and plain
.count('-') == 0:
4915 # must be in reserved position; add to "plain value"
4916 plain
= '-' + plain
.strip()
4918 if self
._fields
[0]._alignRight
:
4919 lpad
= plain
.count(',')
4920 plain
= ' ' * lpad
+ plain
.replace(',','')
4922 plain
= plain
.replace(',','')
4923 ## dbg('plain after pad and group:"%s"' % plain)
4925 ## dbg('returned "%s"' % plain.rstrip(), indent=0)
4926 return plain
.rstrip()
4929 def IsEmpty(self
, value
=None):
4931 Returns True if control is equal to an empty value.
4932 (Empty means all editable positions in the template == fillChar.)
4934 if value
is None: value
= self
._GetValue
()
4935 if value
== self
._template
and not self
._defaultValue
:
4936 #### dbg("IsEmpty? 1 (value == self._template and not self._defaultValue)")
4937 return True # (all mask chars == fillChar by defn)
4938 elif value
== self
._template
:
4940 for pos
in range(len(self
._template
)):
4941 #### dbg('isMaskChar(%(pos)d)?' % locals(), self._isMaskChar(pos))
4942 #### dbg('value[%(pos)d] != self._fillChar?' %locals(), value[pos] != self._fillChar[pos])
4943 if self
._isMaskChar
(pos
) and value
[pos
] not in (' ', self
._fillChar
[pos
]):
4945 #### dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals())
4948 #### dbg("IsEmpty? 0 (value doesn't match template)")
4952 def IsDefault(self
, value
=None):
4954 Returns True if the value specified (or the value of the control if not specified)
4955 is equal to the default value.
4957 if value
is None: value
= self
._GetValue
()
4958 return value
== self
._template
4961 def IsValid(self
, value
=None):
4962 """ Indicates whether the value specified (or the current value of the control
4963 if not specified) is considered valid."""
4964 #### dbg('MaskedEditMixin::IsValid("%s")' % value, indent=1)
4965 if value
is None: value
= self
._GetValue
()
4966 ret
= self
._CheckValid
(value
)
4971 def _eraseSelection(self
, value
=None, sel_start
=None, sel_to
=None):
4972 """ Used to blank the selection when inserting a new character. """
4973 ## dbg("MaskedEditMixin::_eraseSelection", indent=1)
4974 if value
is None: value
= self
._GetValue
()
4975 if sel_start
is None or sel_to
is None:
4976 sel_start
, sel_to
= self
._GetSelection
() ## check for a range of selected text
4977 ## dbg('value: "%s"' % value)
4978 ## dbg("current sel_start, sel_to:", sel_start, sel_to)
4980 newvalue
= list(value
)
4981 for i
in range(sel_start
, sel_to
):
4982 if self
._signOk
and newvalue
[i
] in ('-', '(', ')'):
4983 ## dbg('found sign (%s) at' % newvalue[i], i)
4985 # balance parentheses:
4986 if newvalue
[i
] == '(':
4987 right_signpos
= value
.find(')')
4988 if right_signpos
!= -1:
4989 newvalue
[right_signpos
] = ' '
4991 elif newvalue
[i
] == ')':
4992 left_signpos
= value
.find('(')
4993 if left_signpos
!= -1:
4994 newvalue
[left_signpos
] = ' '
4998 elif self
._isMaskChar
(i
):
4999 field
= self
._FindField
(i
)
5003 newvalue
[i
] = self
._template
[i
]
5005 value
= string
.join(newvalue
,"")
5006 ## dbg('new value: "%s"' % value)
5011 def _insertKey(self
, char
, pos
, sel_start
, sel_to
, value
, allowAutoSelect
=False):
5012 """ Handles replacement of the character at the current insertion point."""
5013 ## dbg('MaskedEditMixin::_insertKey', "\'" + char + "\'", pos, sel_start, sel_to, '"%s"' % value, indent=1)
5015 text
= self
._eraseSelection
(value
)
5016 field
= self
._FindField
(pos
)
5017 start
, end
= field
._extent
5021 # if >= 2 chars selected in a right-insert field, do appropriate erase on field,
5022 # then set selection to end, and do usual right insert.
5023 if sel_start
!= sel_to
and sel_to
>= sel_start
+2:
5024 field
= self
._FindField
(sel_start
)
5025 if( field
._insertRight
# if right-insert
5026 and field
._allowInsert
# and allow insert at any point in field
5027 and field
== self
._FindField
(sel_to
) ): # and selection all in same field
5028 text
= self
._OnErase
(just_return_value
=True) # remove selection before insert
5029 ## dbg('text after (left)erase: "%s"' % text)
5030 pos
= sel_start
= sel_to
5032 if pos
!= sel_start
and sel_start
== sel_to
:
5033 # adjustpos must have moved the position; make selection match:
5034 sel_start
= sel_to
= pos
5036 ## dbg('field._insertRight?', field._insertRight)
5037 ## dbg('field._allowInsert?', field._allowInsert)
5038 ## dbg('sel_start, end', sel_start, end)
5040 ## dbg('text[sel_start] != field._fillChar?', text[sel_start] != field._fillChar)
5043 if( field
._insertRight
# field allows right insert
5044 and ((sel_start
, sel_to
) == field
._extent
# and whole field selected
5045 or (sel_start
== sel_to
# or nothing selected
5046 and (sel_start
== end
# and cursor at right edge
5047 or (field
._allowInsert
# or field allows right-insert
5048 and sel_start
< end
# next to other char in field:
5049 and text
[sel_start
] != field
._fillChar
) ) ) ) ):
5050 ## dbg('insertRight')
5051 fstr
= text
[start
:end
]
5052 erasable_chars
= [field
._fillChar
, ' ']
5054 # if zero padding field, or a single digit, and currently a value of 0, allow erasure of 0:
5055 if field
._padZero
or (field
._isInt
and (end
- start
== 1) and fstr
[0] == '0'):
5056 erasable_chars
.append('0')
5059 #### dbg("fstr[0]:'%s'" % fstr[0])
5060 #### dbg('field_index:', field._index)
5061 #### dbg("fstr[0] in erasable_chars?", fstr[0] in erasable_chars)
5062 #### dbg("self._signOk and field._index == 0 and fstr[0] in ('-','(')?", self._signOk and field._index == 0 and fstr[0] in ('-','('))
5063 if fstr
[0] in erasable_chars
or (self
._signOk
and field
._index
== 0 and fstr
[0] in ('-','(')):
5065 #### dbg('value: "%s"' % text)
5066 #### dbg('fstr: "%s"' % fstr)
5067 #### dbg("erased: '%s'" % erased)
5068 field_sel_start
= sel_start
- start
5069 field_sel_to
= sel_to
- start
5070 ## dbg('left fstr: "%s"' % fstr[1:field_sel_start])
5071 ## dbg('right fstr: "%s"' % fstr[field_sel_to:end])
5072 fstr
= fstr
[1:field_sel_start
] + char
+ fstr
[field_sel_to
:end
]
5073 if field
._alignRight
and sel_start
!= sel_to
:
5074 field_len
= end
- start
5075 ## pos += (field_len - len(fstr)) # move cursor right by deleted amount
5077 ## dbg('setting pos to:', pos)
5079 fstr
= '0' * (field_len
- len(fstr
)) + fstr
5081 fstr
= fstr
.rjust(field_len
) # adjust the field accordingly
5082 ## dbg('field str: "%s"' % fstr)
5084 newtext
= text
[:start
] + fstr
+ text
[end
:]
5085 if erased
in ('-', '(') and self
._signOk
:
5086 newtext
= erased
+ newtext
[1:]
5087 ## dbg('newtext: "%s"' % newtext)
5089 if self
._signOk
and field
._index
== 0:
5090 start
-= 1 # account for sign position
5092 #### dbg('field._moveOnFieldFull?', field._moveOnFieldFull)
5093 #### dbg('len(fstr.lstrip()) == end-start?', len(fstr.lstrip()) == end-start)
5094 if( field
._moveOnFieldFull
and pos
== end
5095 and len(fstr
.lstrip()) == end
-start
): # if field now full
5096 newpos
= self
._findNextEntry
(end
) # go to next field
5098 newpos
= pos
# else keep cursor at current position
5101 ## dbg('not newtext')
5103 ## dbg('newpos:', newpos)
5105 if self
._signOk
and self
._useParens
:
5106 old_right_signpos
= text
.find(')')
5108 if field
._allowInsert
and not field
._insertRight
and sel_to
<= end
and sel_start
>= start
:
5109 ## dbg('inserting within a left-insert-capable field')
5110 field_len
= end
- start
5111 before
= text
[start
:sel_start
]
5112 after
= text
[sel_to
:end
].strip()
5113 #### dbg("current field:'%s'" % text[start:end])
5114 #### dbg("before:'%s'" % before, "after:'%s'" % after)
5115 new_len
= len(before
) + len(after
) + 1 # (for inserted char)
5116 #### dbg('new_len:', new_len)
5118 if new_len
< field_len
:
5119 retained
= after
+ self
._template
[end
-(field_len
-new_len
):end
]
5120 elif new_len
> end
-start
:
5121 retained
= after
[1:]
5125 left
= text
[0:start
] + before
5126 #### dbg("left:'%s'" % left, "retained:'%s'" % retained)
5127 right
= retained
+ text
[end
:]
5130 right
= text
[pos
+1:]
5132 if 'unicode' in wx
.PlatformInfo
and type(char
) != types
.UnicodeType
:
5133 # convert the keyboard constant to a unicode value, to
5134 # ensure it can be concatenated into the control value:
5135 char
= char
.decode(self
._defaultEncoding
)
5137 newtext
= left
+ char
+ right
5138 #### dbg('left: "%s"' % left)
5139 #### dbg('right: "%s"' % right)
5140 #### dbg('newtext: "%s"' % newtext)
5142 if self
._signOk
and self
._useParens
:
5143 # Balance parentheses:
5144 left_signpos
= newtext
.find('(')
5146 if left_signpos
== -1: # erased '('; remove ')'
5147 right_signpos
= newtext
.find(')')
5148 if right_signpos
!= -1:
5149 newtext
= newtext
[:right_signpos
] + ' ' + newtext
[right_signpos
+1:]
5151 elif old_right_signpos
!= -1:
5152 right_signpos
= newtext
.find(')')
5154 if right_signpos
== -1: # just replaced right-paren
5155 if newtext
[pos
] == ' ': # we just erased '); erase '('
5156 newtext
= newtext
[:left_signpos
] + ' ' + newtext
[left_signpos
+1:]
5157 else: # replaced with digit; move ') over
5158 if self
._ctrl
_constraints
._alignRight
or self
._isFloat
:
5159 newtext
= newtext
[:-1] + ')'
5161 rstripped_text
= newtext
.rstrip()
5162 right_signpos
= len(rstripped_text
)
5163 ## dbg('old_right_signpos:', old_right_signpos, 'right signpos now:', right_signpos)
5164 newtext
= newtext
[:right_signpos
] + ')' + newtext
[right_signpos
+1:]
5166 if( field
._insertRight
# if insert-right field (but we didn't start at right edge)
5167 and field
._moveOnFieldFull
# and should move cursor when full
5168 and len(newtext
[start
:end
].strip()) == end
-start
): # and field now full
5169 newpos
= self
._findNextEntry
(end
) # go to next field
5170 ## dbg('newpos = nextentry =', newpos)
5172 ## dbg('pos:', pos, 'newpos:', pos+1)
5177 new_select_to
= newpos
# (default return values)
5181 if field
._autoSelect
:
5182 match_index
, partial_match
= self
._autoComplete
(1, # (always forward)
5183 field
._compareChoices
,
5185 compareNoCase
=field
._compareNoCase
,
5186 current_index
= field
._autoCompleteIndex
-1)
5187 if match_index
is not None and partial_match
:
5188 matched_str
= newtext
[start
:end
]
5189 newtext
= newtext
[:start
] + field
._choices
[match_index
] + newtext
[end
:]
5192 if field
._insertRight
:
5193 # adjust position to just after partial match in field
5194 newpos
= end
- (len(field
._choices
[match_index
].strip()) - len(matched_str
.strip()))
5196 elif self
._ctrl
_constraints
._autoSelect
:
5197 match_index
, partial_match
= self
._autoComplete
(
5198 1, # (always forward)
5199 self
._ctrl
_constraints
._compareChoices
,
5201 self
._ctrl
_constraints
._compareNoCase
,
5202 current_index
= self
._ctrl
_constraints
._autoCompleteIndex
- 1)
5203 if match_index
is not None and partial_match
:
5204 matched_str
= newtext
5205 newtext
= self
._ctrl
_constraints
._choices
[match_index
]
5206 edit_end
= self
._ctrl
_constraints
._extent
[1]
5207 new_select_to
= min(edit_end
, len(newtext
.rstrip()))
5208 match_field
= self
._ctrl
_constraints
5209 if self
._ctrl
_constraints
._insertRight
:
5210 # adjust position to just after partial match in control:
5211 newpos
= self
._masklength
- (len(self
._ctrl
_constraints
._choices
[match_index
].strip()) - len(matched_str
.strip()))
5213 ## dbg('newtext: "%s"' % newtext, 'newpos:', newpos, 'new_select_to:', new_select_to)
5215 return newtext
, newpos
, new_select_to
, match_field
, match_index
5217 ## dbg('newtext: "%s"' % newtext, 'newpos:', newpos)
5219 return newtext
, newpos
5222 def _OnFocus(self
,event
):
5224 This event handler is currently necessary to work around new default
5225 behavior as of wxPython2.3.3;
5226 The TAB key auto selects the entire contents of the wx.TextCtrl *after*
5227 the EVT_SET_FOCUS event occurs; therefore we can't query/adjust the selection
5228 *here*, because it hasn't happened yet. So to prevent this behavior, and
5229 preserve the correct selection when the focus event is not due to tab,
5230 we need to pull the following trick:
5232 ## dbg('MaskedEditMixin::_OnFocus')
5233 if self
.IsBeingDeleted() or self
.GetParent().IsBeingDeleted():
5235 wx
.CallAfter(self
._fixSelection
)
5240 def _CheckValid(self
, candidate
=None):
5242 This is the default validation checking routine; It verifies that the
5243 current value of the control is a "valid value," and has the side
5244 effect of coloring the control appropriately.
5247 ## dbg('MaskedEditMixin::_CheckValid: candidate="%s"' % candidate, indent=1)
5248 oldValid
= self
._valid
5249 if candidate
is None: value
= self
._GetValue
()
5250 else: value
= candidate
5251 ## dbg('value: "%s"' % value)
5253 valid
= True # assume True
5255 if not self
.IsDefault(value
) and self
._isDate
: ## Date type validation
5256 valid
= self
._validateDate
(value
)
5257 ## dbg("valid date?", valid)
5259 elif not self
.IsDefault(value
) and self
._isTime
:
5260 valid
= self
._validateTime
(value
)
5261 ## dbg("valid time?", valid)
5263 elif not self
.IsDefault(value
) and (self
._isInt
or self
._isFloat
): ## Numeric type
5264 valid
= self
._validateNumeric
(value
)
5265 ## dbg("valid Number?", valid)
5267 if valid
: # and not self.IsDefault(value): ## generic validation accounts for IsDefault()
5268 ## valid so far; ensure also allowed by any list or regex provided:
5269 valid
= self
._validateGeneric
(value
)
5270 ## dbg("valid value?", valid)
5272 ## dbg('valid?', valid)
5276 self
._applyFormatting
()
5277 if self
._valid
!= oldValid
:
5278 ## dbg('validity changed: oldValid =',oldValid,'newvalid =', self._valid)
5279 ## dbg('oldvalue: "%s"' % oldvalue, 'newvalue: "%s"' % self._GetValue())
5281 ## dbg(indent=0, suspend=0)
5285 def _validateGeneric(self
, candidate
=None):
5286 """ Validate the current value using the provided list or Regex filter (if any).
5288 if candidate
is None:
5289 text
= self
._GetValue
()
5293 valid
= True # assume True
5294 for i
in [-1] + self
._field
_indices
: # process global constraints first:
5295 field
= self
._fields
[i
]
5296 start
, end
= field
._extent
5297 slice = text
[start
:end
]
5298 valid
= field
.IsValid(slice)
5305 def _validateNumeric(self
, candidate
=None):
5306 """ Validate that the value is within the specified range (if specified.)"""
5307 if candidate
is None: value
= self
._GetValue
()
5308 else: value
= candidate
5310 groupchar
= self
._fields
[0]._groupChar
5312 number
= float(value
.replace(groupchar
, '').replace(self
._decimalChar
, '.').replace('(', '-').replace(')', ''))
5314 number
= long( value
.replace(groupchar
, '').replace('(', '-').replace(')', ''))
5316 if self
._fields
[0]._alignRight
:
5317 require_digit_at
= self
._fields
[0]._extent
[1]-1
5319 require_digit_at
= self
._fields
[0]._extent
[0]
5320 ## dbg('require_digit_at:', require_digit_at)
5321 ## dbg("value[rda]: '%s'" % value[require_digit_at])
5322 if value
[require_digit_at
] not in list(string
.digits
):
5326 ## dbg('number:', number)
5327 if self
._ctrl
_constraints
._hasRange
:
5328 valid
= self
._ctrl
_constraints
._rangeLow
<= number
<= self
._ctrl
_constraints
._rangeHigh
5331 groupcharpos
= value
.rfind(groupchar
)
5332 if groupcharpos
!= -1: # group char present
5333 ## dbg('groupchar found at', groupcharpos)
5334 if self
._isFloat
and groupcharpos
> self
._decimalpos
:
5335 # 1st one found on right-hand side is past decimal point
5336 ## dbg('groupchar in fraction; illegal')
5339 integer
= value
[:self
._decimalpos
].strip()
5341 integer
= value
.strip()
5342 ## dbg("integer:'%s'" % integer)
5343 if integer
[0] in ('-', '('):
5344 integer
= integer
[1:]
5345 if integer
[-1] == ')':
5346 integer
= integer
[:-1]
5348 parts
= integer
.split(groupchar
)
5349 ## dbg('parts:', parts)
5350 for i
in range(len(parts
)):
5351 if i
== 0 and abs(int(parts
[0])) > 999:
5352 ## dbg('group 0 too long; illegal')
5355 elif i
> 0 and (len(parts
[i
]) != 3 or ' ' in parts
[i
]):
5356 ## dbg('group %i (%s) not right size; illegal' % (i, parts[i]))
5360 ## dbg('value not a valid number')
5365 def _validateDate(self
, candidate
=None):
5366 """ Validate the current date value using the provided Regex filter.
5367 Generally used for character types.BufferType
5369 ## dbg('MaskedEditMixin::_validateDate', indent=1)
5370 if candidate
is None: value
= self
._GetValue
()
5371 else: value
= candidate
5372 ## dbg('value = "%s"' % value)
5373 text
= self
._adjustDate
(value
, force4digit_year
=True) ## Fix the date up before validating it
5374 ## dbg('text =', text)
5375 valid
= True # assume True until proven otherwise
5378 # replace fillChar in each field with space:
5379 datestr
= text
[0:self
._dateExtent
]
5381 field
= self
._fields
[i
]
5382 start
, end
= field
._extent
5383 fstr
= datestr
[start
:end
]
5384 fstr
.replace(field
._fillChar
, ' ')
5385 datestr
= datestr
[:start
] + fstr
+ datestr
[end
:]
5387 year
, month
, day
= _getDateParts( datestr
, self
._datestyle
)
5389 ## dbg('self._dateExtent:', self._dateExtent)
5390 if self
._dateExtent
== 11:
5391 month
= charmonths_dict
[month
.lower()]
5395 ## dbg('year, month, day:', year, month, day)
5398 ## dbg('cannot convert string to integer parts')
5401 ## dbg('cannot convert string to integer month')
5405 # use wxDateTime to unambiguously try to parse the date:
5406 # ### Note: because wxDateTime is *brain-dead* and expects months 0-11,
5407 # rather than 1-12, so handle accordingly:
5413 ## dbg("trying to create date from values day=%d, month=%d, year=%d" % (day,month,year))
5414 dateHandler
= wx
.DateTimeFromDMY(day
,month
,year
)
5418 ## dbg('cannot convert string to valid date')
5424 # wxDateTime doesn't take kindly to leading/trailing spaces when parsing,
5425 # so we eliminate them here:
5426 timeStr
= text
[self
._dateExtent
+1:].strip() ## time portion of the string
5428 ## dbg('timeStr: "%s"' % timeStr)
5430 checkTime
= dateHandler
.ParseTime(timeStr
)
5431 valid
= checkTime
== len(timeStr
)
5435 ## dbg('cannot convert string to valid time')
5437 ## if valid: dbg('valid date')
5442 def _validateTime(self
, candidate
=None):
5443 """ Validate the current time value using the provided Regex filter.
5444 Generally used for character types.BufferType
5446 ## dbg('MaskedEditMixin::_validateTime', indent=1)
5447 # wxDateTime doesn't take kindly to leading/trailing spaces when parsing,
5448 # so we eliminate them here:
5449 if candidate
is None: value
= self
._GetValue
().strip()
5450 else: value
= candidate
.strip()
5451 ## dbg('value = "%s"' % value)
5452 valid
= True # assume True until proven otherwise
5454 dateHandler
= wx
.DateTime_Today()
5456 checkTime
= dateHandler
.ParseTime(value
)
5457 ## dbg('checkTime:', checkTime, 'len(value)', len(value))
5458 valid
= checkTime
== len(value
)
5463 ## dbg('cannot convert string to valid time')
5465 ## if valid: dbg('valid time')
5470 def _OnKillFocus(self
,event
):
5471 """ Handler for EVT_KILL_FOCUS event.
5473 ## dbg('MaskedEditMixin::_OnKillFocus', 'isDate=',self._isDate, indent=1)
5474 if self
.IsBeingDeleted() or self
.GetParent().IsBeingDeleted():
5476 if self
._mask
and self
._IsEditable
():
5477 self
._AdjustField
(self
._GetInsertionPoint
())
5478 self
._CheckValid
() ## Call valid handler
5480 self
._LostFocus
() ## Provided for subclass use
5485 def _fixSelection(self
):
5487 This gets called after the TAB traversal selection is made, if the
5488 focus event was due to this, but before the EVT_LEFT_* events if
5489 the focus shift was due to a mouse event.
5491 The trouble is that, a priori, there's no explicit notification of
5492 why the focus event we received. However, the whole reason we need to
5493 do this is because the default behavior on TAB traveral in a wx.TextCtrl is
5494 now to select the entire contents of the window, something we don't want.
5495 So we can *now* test the selection range, and if it's "the whole text"
5496 we can assume the cause, change the insertion point to the start of
5497 the control, and deselect.
5499 ## dbg('MaskedEditMixin::_fixSelection', indent=1)
5500 # can get here if called with wx.CallAfter after underlying
5501 # control has been destroyed on close, but after focus
5503 if not self
or not self
._mask
or not self
._IsEditable
():
5507 sel_start
, sel_to
= self
._GetSelection
()
5508 ## dbg('sel_start, sel_to:', sel_start, sel_to, 'self.IsEmpty()?', self.IsEmpty())
5510 if( sel_start
== 0 and sel_to
>= len( self
._mask
) #(can be greater in numeric controls because of reserved space)
5511 and (not self
._ctrl
_constraints
._autoSelect
or self
.IsEmpty() or self
.IsDefault() ) ):
5512 # This isn't normally allowed, and so assume we got here by the new
5513 # "tab traversal" behavior, so we need to reset the selection
5514 # and insertion point:
5515 ## dbg('entire text selected; resetting selection to start of control')
5517 field
= self
._FindField
(self
._GetInsertionPoint
())
5518 edit_start
, edit_end
= field
._extent
5519 if field
._selectOnFieldEntry
:
5520 if self
._isFloat
or self
._isInt
and field
== self
._fields
[0]:
5522 self
._SetInsertionPoint
(edit_start
)
5523 self
._SetSelection
(edit_start
, edit_end
)
5525 elif field
._insertRight
:
5526 self
._SetInsertionPoint
(edit_end
)
5527 self
._SetSelection
(edit_end
, edit_end
)
5529 elif (self
._isFloat
or self
._isInt
):
5531 text
, signpos
, right_signpos
= self
._getAbsValue
()
5532 if text
is None or text
== self
._template
:
5533 integer
= self
._fields
[0]
5534 edit_start
, edit_end
= integer
._extent
5536 if integer
._selectOnFieldEntry
:
5537 ## dbg('select on field entry:')
5538 self
._SetInsertionPoint
(0)
5539 self
._SetSelection
(0, edit_end
)
5541 elif integer
._insertRight
:
5542 ## dbg('moving insertion point to end')
5543 self
._SetInsertionPoint
(edit_end
)
5544 self
._SetSelection
(edit_end
, edit_end
)
5546 ## dbg('numeric ctrl is empty; start at beginning after sign')
5547 self
._SetInsertionPoint
(signpos
+1) ## Move past minus sign space if signed
5548 self
._SetSelection
(signpos
+1, signpos
+1)
5550 elif sel_start
> self
._goEnd
(getPosOnly
=True):
5551 ## dbg('cursor beyond the end of the user input; go to end of it')
5554 ## dbg('sel_start, sel_to:', sel_start, sel_to, 'self._masklength:', self._masklength)
5559 def _Keypress(self
,key
):
5560 """ Method provided to override OnChar routine. Return False to force
5561 a skip of the 'normal' OnChar process. Called before class OnChar.
5566 def _LostFocus(self
):
5567 """ Method provided for subclasses. _LostFocus() is called after
5568 the class processes its EVT_KILL_FOCUS event code.
5573 def _OnDoubleClick(self
, event
):
5574 """ selects field under cursor on dclick."""
5575 pos
= self
._GetInsertionPoint
()
5576 field
= self
._FindField
(pos
)
5577 start
, end
= field
._extent
5578 self
._SetInsertionPoint
(start
)
5579 self
._SetSelection
(start
, end
)
5583 """ Method provided for subclasses. Called by internal EVT_TEXT
5584 handler. Return False to override the class handler, True otherwise.
5591 Used to override the default Cut() method in base controls, instead
5592 copying the selection to the clipboard and then blanking the selection,
5593 leaving only the mask in the selected area behind.
5594 Note: _Cut (read "undercut" ;-) must be called from a Cut() override in the
5595 derived control because the mixin functions can't override a method of
5598 ## dbg("MaskedEditMixin::_Cut", indent=1)
5599 value
= self
._GetValue
()
5600 ## dbg('current value: "%s"' % value)
5601 sel_start
, sel_to
= self
._GetSelection
() ## check for a range of selected text
5602 ## dbg('selected text: "%s"' % value[sel_start:sel_to].strip())
5603 do
= wx
.TextDataObject()
5604 do
.SetText(value
[sel_start
:sel_to
].strip())
5605 wx
.TheClipboard
.Open()
5606 wx
.TheClipboard
.SetData(do
)
5607 wx
.TheClipboard
.Close()
5609 if sel_to
- sel_start
!= 0:
5614 # WS Note: overriding Copy is no longer necessary given that you
5615 # can no longer select beyond the last non-empty char in the control.
5617 ## def _Copy( self ):
5619 ## Override the wx.TextCtrl's .Copy function, with our own
5620 ## that does validation. Need to strip trailing spaces.
5622 ## sel_start, sel_to = self._GetSelection()
5623 ## select_len = sel_to - sel_start
5624 ## textval = wx.TextCtrl._GetValue(self)
5626 ## do = wx.TextDataObject()
5627 ## do.SetText(textval[sel_start:sel_to].strip())
5628 ## wx.TheClipboard.Open()
5629 ## wx.TheClipboard.SetData(do)
5630 ## wx.TheClipboard.Close()
5633 def _getClipboardContents( self
):
5634 """ Subroutine for getting the current contents of the clipboard.
5636 do
= wx
.TextDataObject()
5637 wx
.TheClipboard
.Open()
5638 success
= wx
.TheClipboard
.GetData(do
)
5639 wx
.TheClipboard
.Close()
5644 # Remove leading and trailing spaces before evaluating contents
5645 return do
.GetText().strip()
5648 def _validatePaste(self
, paste_text
, sel_start
, sel_to
, raise_on_invalid
=False):
5650 Used by paste routine and field choice validation to see
5651 if a given slice of paste text is legal for the area in question:
5652 returns validity, replacement text, and extent of paste in
5656 ## dbg('MaskedEditMixin::_validatePaste("%(paste_text)s", %(sel_start)d, %(sel_to)d), raise_on_invalid? %(raise_on_invalid)d' % locals(), indent=1)
5657 select_length
= sel_to
- sel_start
5658 maxlength
= select_length
5659 ## dbg('sel_to - sel_start:', maxlength)
5661 maxlength
= self
._masklength
- sel_start
5665 ## dbg('maxlength:', maxlength)
5666 if 'unicode' in wx
.PlatformInfo
and type(paste_text
) != types
.UnicodeType
:
5667 paste_text
= paste_text
.decode(self
._defaultEncoding
)
5669 length_considered
= len(paste_text
)
5670 if length_considered
> maxlength
:
5671 ## dbg('paste text will not fit into the %s:' % item, indent=0)
5672 if raise_on_invalid
:
5673 ## dbg(indent=0, suspend=0)
5674 if item
== 'control':
5675 ve
= ValueError('"%s" will not fit into the control "%s"' % (paste_text
, self
.name
))
5676 ve
.value
= paste_text
5679 ve
= ValueError('"%s" will not fit into the selection' % paste_text
)
5680 ve
.value
= paste_text
5683 ## dbg(indent=0, suspend=0)
5684 return False, None, None
5686 text
= self
._template
5687 ## dbg('length_considered:', length_considered)
5690 replacement_text
= ""
5691 replace_to
= sel_start
5693 while valid_paste
and i
< length_considered
and replace_to
< self
._masklength
:
5694 if paste_text
[i
:] == self
._template
[replace_to
:length_considered
]:
5695 # remainder of paste matches template; skip char-by-char analysis
5696 ## dbg('remainder paste_text[%d:] (%s) matches template[%d:%d]' % (i, paste_text[i:], replace_to, length_considered))
5697 replacement_text
+= paste_text
[i
:]
5698 replace_to
= i
= length_considered
5701 char
= paste_text
[i
]
5702 field
= self
._FindField
(replace_to
)
5703 if not field
._compareNoCase
:
5704 if field
._forceupper
: char
= char
.upper()
5705 elif field
._forcelower
: char
= char
.lower()
5707 ## dbg('char:', "'"+char+"'", 'i =', i, 'replace_to =', replace_to)
5708 ## dbg('self._isTemplateChar(%d)?' % replace_to, self._isTemplateChar(replace_to))
5709 if not self
._isTemplateChar
(replace_to
) and self
._isCharAllowed
( char
, replace_to
, allowAutoSelect
=False, ignoreInsertRight
=True):
5710 replacement_text
+= char
5711 ## dbg("not template(%(replace_to)d) and charAllowed('%(char)s',%(replace_to)d)" % locals())
5712 ## dbg("replacement_text:", '"'+replacement_text+'"')
5715 elif( char
== self
._template
[replace_to
]
5716 or (self
._signOk
and
5717 ( (i
== 0 and (char
== '-' or (self
._useParens
and char
== '(')))
5718 or (i
== self
._masklength
- 1 and self
._useParens
and char
== ')') ) ) ):
5719 replacement_text
+= char
5720 ## dbg("'%(char)s' == template(%(replace_to)d)" % locals())
5721 ## dbg("replacement_text:", '"'+replacement_text+'"')
5725 next_entry
= self
._findNextEntry
(replace_to
, adjustInsert
=False)
5726 if next_entry
== replace_to
:
5729 replacement_text
+= self
._template
[replace_to
:next_entry
]
5730 ## dbg("skipping template; next_entry =", next_entry)
5731 ## dbg("replacement_text:", '"'+replacement_text+'"')
5732 replace_to
= next_entry
# so next_entry will be considered on next loop
5734 if not valid_paste
and raise_on_invalid
:
5735 ## dbg('raising exception', indent=0, suspend=0)
5736 ve
= ValueError('"%s" cannot be inserted into the control "%s"' % (paste_text
, self
.name
))
5737 ve
.value
= paste_text
5741 elif i
< len(paste_text
):
5743 if raise_on_invalid
:
5744 ## dbg('raising exception', indent=0, suspend=0)
5745 ve
= ValueError('"%s" will not fit into the control "%s"' % (paste_text
, self
.name
))
5746 ve
.value
= paste_text
5749 ## dbg('valid_paste?', valid_paste)
5751 ## dbg('replacement_text: "%s"' % replacement_text, 'replace to:', replace_to)
5753 ## dbg(indent=0, suspend=0)
5754 return valid_paste
, replacement_text
, replace_to
5757 def _Paste( self
, value
=None, raise_on_invalid
=False, just_return_value
=False ):
5759 Used to override the base control's .Paste() function,
5760 with our own that does validation.
5761 Note: _Paste must be called from a Paste() override in the
5762 derived control because the mixin functions can't override a
5763 method of a sibling class.
5765 ## dbg('MaskedEditMixin::_Paste (value = "%s")' % value, indent=1)
5767 paste_text
= self
._getClipboardContents
()
5771 if paste_text
is not None:
5773 if 'unicode' in wx
.PlatformInfo
and type(paste_text
) != types
.UnicodeType
:
5774 paste_text
= paste_text
.decode(self
._defaultEncoding
)
5776 ## dbg('paste text: "%s"' % paste_text)
5777 # (conversion will raise ValueError if paste isn't legal)
5778 sel_start
, sel_to
= self
._GetSelection
()
5779 ## dbg('selection:', (sel_start, sel_to))
5781 # special case: handle allowInsert fields properly
5782 field
= self
._FindField
(sel_start
)
5783 edit_start
, edit_end
= field
._extent
5785 if field
._allowInsert
and sel_to
<= edit_end
and (sel_start
+ len(paste_text
) < edit_end
or field
._insertRight
):
5786 if field
._insertRight
:
5787 # want to paste to the left; see if it will fit:
5788 left_text
= self
._GetValue
()[edit_start
:sel_start
].lstrip()
5789 ## dbg('len(left_text):', len(left_text))
5790 ## dbg('len(paste_text):', len(paste_text))
5791 ## dbg('sel_start - (len(left_text) + len(paste_text)) >= edit_start?', sel_start - (len(left_text) + len(paste_text)) >= edit_start)
5792 if sel_start
- (len(left_text
) - (sel_to
- sel_start
) + len(paste_text
)) >= edit_start
:
5793 # will fit! create effective paste text, and move cursor back to do so:
5794 paste_text
= left_text
+ paste_text
5795 sel_start
-= len(left_text
)
5796 paste_text
= paste_text
.rjust(sel_to
- sel_start
)
5797 ## dbg('modified paste_text to be: "%s"' % paste_text)
5798 ## dbg('modified selection to:', (sel_start, sel_to))
5800 ## dbg("won't fit left;", 'paste text remains: "%s"' % paste_text)
5803 paste_text
= paste_text
+ self
._GetValue
()[sel_to
:edit_end
].rstrip()
5804 ## dbg("allow insert, but not insert right;", 'paste text set to: "%s"' % paste_text)
5807 new_pos
= sel_start
+ len(paste_text
) # store for subsequent positioning
5808 ## dbg('paste within insertable field; adjusted paste_text: "%s"' % paste_text, 'end:', edit_end)
5809 ## dbg('expanded selection to:', (sel_start, sel_to))
5811 # Another special case: paste won't fit, but it's a right-insert field where entire
5812 # non-empty value is selected, and there's room if the selection is expanded leftward:
5813 if( len(paste_text
) > sel_to
- sel_start
5814 and field
._insertRight
5815 and sel_start
> edit_start
5816 and sel_to
>= edit_end
5817 and not self
._GetValue
()[edit_start
:sel_start
].strip() ):
5818 # text won't fit within selection, but left of selection is empty;
5819 # check to see if we can expand selection to accommodate the value:
5820 empty_space
= sel_start
- edit_start
5821 amount_needed
= len(paste_text
) - (sel_to
- sel_start
)
5822 if amount_needed
<= empty_space
:
5823 sel_start
-= amount_needed
5824 ## dbg('expanded selection to:', (sel_start, sel_to))
5827 # another special case: deal with signed values properly:
5829 signedvalue
, signpos
, right_signpos
= self
._getSignedValue
()
5830 paste_signpos
= paste_text
.find('-')
5831 if paste_signpos
== -1:
5832 paste_signpos
= paste_text
.find('(')
5834 # if paste text will result in signed value:
5835 #### dbg('paste_signpos != -1?', paste_signpos != -1)
5836 #### dbg('sel_start:', sel_start, 'signpos:', signpos)
5837 #### dbg('field._insertRight?', field._insertRight)
5838 #### dbg('sel_start - len(paste_text) >= signpos?', sel_start - len(paste_text) <= signpos)
5839 if paste_signpos
!= -1 and (sel_start
<= signpos
5840 or (field
._insertRight
and sel_start
- len(paste_text
) <= signpos
)):
5844 # remove "sign" from paste text, so we can auto-adjust for sign type after paste:
5845 paste_text
= paste_text
.replace('-', ' ').replace('(',' ').replace(')','')
5846 ## dbg('unsigned paste text: "%s"' % paste_text)
5850 # another special case: deal with insert-right fields when selection is empty and
5851 # cursor is at end of field:
5852 #### dbg('field._insertRight?', field._insertRight)
5853 #### dbg('sel_start == edit_end?', sel_start == edit_end)
5854 #### dbg('sel_start', sel_start, 'sel_to', sel_to)
5855 if field
._insertRight
and sel_start
== edit_end
and sel_start
== sel_to
:
5856 sel_start
-= len(paste_text
)
5859 ## dbg('adjusted selection:', (sel_start, sel_to))
5861 raise_on_invalid
= raise_on_invalid
or field
._raiseOnInvalidPaste
5863 valid_paste
, replacement_text
, replace_to
= self
._validatePaste
(paste_text
, sel_start
, sel_to
, raise_on_invalid
)
5865 ## dbg('exception thrown', indent=0)
5869 ## dbg('paste text not legal for the selection or portion of the control following the cursor;')
5870 if not wx
.Validator_IsSilent():
5875 text
= self
._eraseSelection
()
5877 new_text
= text
[:sel_start
] + replacement_text
+ text
[replace_to
:]
5879 new_text
= string
.ljust(new_text
,self
._masklength
)
5881 new_text
, signpos
, right_signpos
= self
._getSignedValue
(candidate
=new_text
)
5884 new_text
= new_text
[:signpos
] + '(' + new_text
[signpos
+1:right_signpos
] + ')' + new_text
[right_signpos
+1:]
5886 new_text
= new_text
[:signpos
] + '-' + new_text
[signpos
+1:]
5890 ## dbg("new_text:", '"'+new_text+'"')
5892 if not just_return_value
:
5893 if new_text
!= self
._GetValue
():
5894 self
.modified
= True
5898 wx
.CallAfter(self
._SetValue
, new_text
)
5900 new_pos
= sel_start
+ len(replacement_text
)
5901 wx
.CallAfter(self
._SetInsertionPoint
, new_pos
)
5904 return new_text
, replace_to
5905 elif just_return_value
:
5907 return self
._GetValue
(), sel_to
5910 def _Undo(self
, value
=None, prev
=None, just_return_results
=False):
5911 """ Provides an Undo() method in base controls. """
5912 ## dbg("MaskedEditMixin::_Undo", indent=1)
5914 value
= self
._GetValue
()
5916 prev
= self
._prevValue
5917 ## dbg('current value: "%s"' % value)
5918 ## dbg('previous value: "%s"' % prev)
5920 ## dbg('no previous value', indent=0)
5924 # Determine what to select: (relies on fixed-length strings)
5925 # (This is a lot harder than it would first appear, because
5926 # of mask chars that stay fixed, and so break up the "diff"...)
5928 # Determine where they start to differ:
5930 length
= len(value
) # (both are same length in masked control)
5932 while( value
[:i
] == prev
[:i
] ):
5937 # handle signed values carefully, so undo from signed to unsigned or vice-versa
5940 text
, signpos
, right_signpos
= self
._getSignedValue
(candidate
=prev
)
5942 if prev
[signpos
] == '(' and prev
[right_signpos
] == ')':
5946 # eliminate source of "far-end" undo difference if using balanced parens:
5947 value
= value
.replace(')', ' ')
5948 prev
= prev
.replace(')', ' ')
5949 elif prev
[signpos
] == '-':
5954 # Determine where they stop differing in "undo" result:
5955 sm
= difflib
.SequenceMatcher(None, a
=value
, b
=prev
)
5956 i
, j
, k
= sm
.find_longest_match(sel_start
, length
, sel_start
, length
)
5957 ## 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] )
5959 if k
== 0: # no match found; select to end
5962 code_5tuples
= sm
.get_opcodes()
5963 for op
, i1
, i2
, j1
, j2
in code_5tuples
:
5964 ## dbg("%7s value[%d:%d] (%s) prev[%d:%d] (%s)" % (op, i1, i2, value[i1:i2], j1, j2, prev[j1:j2]))
5968 # look backward through operations needed to produce "previous" value;
5969 # first change wins:
5970 for next_op
in range(len(code_5tuples
)-1, -1, -1):
5971 op
, i1
, i2
, j1
, j2
= code_5tuples
[next_op
]
5972 ## dbg('value[i1:i2]: "%s"' % value[i1:i2], 'template[i1:i2] "%s"' % self._template[i1:i2])
5973 field
= self
._FindField
(i2
)
5974 if op
== 'insert' and prev
[j1
:j2
] != self
._template
[j1
:j2
]:
5975 ## dbg('insert found: selection =>', (j1, j2))
5980 elif op
== 'delete' and value
[i1
:i2
] != self
._template
[i1
:i2
]:
5981 edit_start
, edit_end
= field
._extent
5982 if field
._insertRight
and (field
._allowInsert
or i2
== edit_end
):
5988 ## dbg('delete found: selection =>', (sel_start, sel_to))
5991 elif op
== 'replace':
5992 if not prev
[i1
:i2
].strip() and field
._insertRight
:
5993 sel_start
= sel_to
= j2
5997 ## dbg('replace found: selection =>', (sel_start, sel_to))
6003 # now go forwards, looking for earlier changes:
6004 ## dbg('searching forward...')
6005 for next_op
in range(len(code_5tuples
)):
6006 op
, i1
, i2
, j1
, j2
= code_5tuples
[next_op
]
6007 field
= self
._FindField
(i1
)
6010 elif op
== 'replace':
6011 if field
._insertRight
:
6012 # if replace with spaces in an insert-right control, ignore "forward" replace
6013 if not prev
[i1
:i2
].strip():
6016 ## dbg('setting sel_start to', j1)
6019 ## dbg('setting sel_start to', i1)
6022 ## dbg('setting sel_start to', i1)
6024 ## dbg('saw replace; breaking')
6026 elif op
== 'insert' and not value
[i1
:i2
]:
6027 ## dbg('forward %s found' % op)
6028 if prev
[j1
:j2
].strip():
6029 ## dbg('item to insert non-empty; setting sel_start to', j1)
6032 elif not field
._insertRight
:
6033 ## dbg('setting sel_start to inserted space:', j1)
6036 elif op
== 'delete':
6037 ## dbg('delete; field._insertRight?', field._insertRight, 'value[%d:%d].lstrip: "%s"' % (i1,i2,value[i1:i2].lstrip()))
6038 if field
._insertRight
:
6039 if value
[i1
:i2
].lstrip():
6040 ## dbg('setting sel_start to ', j1)
6042 ## dbg('breaking loop')
6047 ## dbg('saw delete; breaking')
6050 ## dbg('unknown code!')
6051 # we've got what we need
6056 ## dbg('no insert,delete or replace found (!)')
6057 # do "left-insert"-centric processing of difference based on l.c.s.:
6058 if i
== j
and j
!= sel_start
: # match starts after start of selection
6059 sel_to
= sel_start
+ (j
-sel_start
) # select to start of match
6061 sel_to
= j
# (change ends at j)
6064 # There are several situations where the calculated difference is
6065 # not what we want to select. If changing sign, or just adding
6066 # group characters, we really don't want to highlight the characters
6067 # changed, but instead leave the cursor where it is.
6068 # Also, there a situations in which the difference can be ambiguous;
6071 # current value: 11234
6072 # previous value: 1111234
6074 # Where did the cursor actually lie and which 1s were selected on the delete
6077 # Also, difflib can "get it wrong;" Consider:
6079 # current value: " 128.66"
6080 # previous value: " 121.86"
6082 # difflib produces the following opcodes, which are sub-optimal:
6083 # equal value[0:9] ( 12) prev[0:9] ( 12)
6084 # insert value[9:9] () prev[9:11] (1.)
6085 # equal value[9:10] (8) prev[11:12] (8)
6086 # delete value[10:11] (.) prev[12:12] ()
6087 # equal value[11:12] (6) prev[12:13] (6)
6088 # delete value[12:13] (6) prev[13:13] ()
6090 # This should have been:
6091 # equal value[0:9] ( 12) prev[0:9] ( 12)
6092 # replace value[9:11] (8.6) prev[9:11] (1.8)
6093 # equal value[12:13] (6) prev[12:13] (6)
6095 # But it didn't figure this out!
6097 # To get all this right, we use the previous selection recorded to help us...
6099 if (sel_start
, sel_to
) != self
._prevSelection
:
6100 ## dbg('calculated selection', (sel_start, sel_to), "doesn't match previous", self._prevSelection)
6102 prev_sel_start
, prev_sel_to
= self
._prevSelection
6103 field
= self
._FindField
(sel_start
)
6105 and sel_start
< self
._masklength
6106 and (prev
[sel_start
] in ('-', '(', ')')
6107 or value
[sel_start
] in ('-', '(', ')')) ):
6108 # change of sign; leave cursor alone...
6109 ## dbg("prev[sel_start] in ('-', '(', ')')?", prev[sel_start] in ('-', '(', ')'))
6110 ## dbg("value[sel_start] in ('-', '(', ')')?", value[sel_start] in ('-', '(', ')'))
6111 ## dbg('setting selection to previous one')
6112 sel_start
, sel_to
= self
._prevSelection
6114 elif field
._groupdigits
and (value
[sel_start
:sel_to
] == field
._groupChar
6115 or prev
[sel_start
:sel_to
] == field
._groupChar
):
6116 # do not highlight grouping changes
6117 ## dbg('value[sel_start:sel_to] == field._groupChar?', value[sel_start:sel_to] == field._groupChar)
6118 ## dbg('prev[sel_start:sel_to] == field._groupChar?', prev[sel_start:sel_to] == field._groupChar)
6119 ## dbg('setting selection to previous one')
6120 sel_start
, sel_to
= self
._prevSelection
6123 calc_select_len
= sel_to
- sel_start
6124 prev_select_len
= prev_sel_to
- prev_sel_start
6126 ## dbg('sel_start == prev_sel_start', sel_start == prev_sel_start)
6127 ## dbg('sel_to > prev_sel_to', sel_to > prev_sel_to)
6129 if prev_select_len
>= calc_select_len
:
6130 # old selection was bigger; trust it:
6131 ## dbg('prev_select_len >= calc_select_len?', prev_select_len >= calc_select_len)
6132 if not field
._insertRight
:
6133 ## dbg('setting selection to previous one')
6134 sel_start
, sel_to
= self
._prevSelection
6136 sel_to
= self
._prevSelection
[1]
6137 ## dbg('setting selection to', (sel_start, sel_to))
6139 elif( sel_to
> prev_sel_to
# calculated select past last selection
6140 and prev_sel_to
< len(self
._template
) # and prev_sel_to not at end of control
6141 and sel_to
== len(self
._template
) ): # and calculated selection goes to end of control
6143 i
, j
, k
= sm
.find_longest_match(prev_sel_to
, length
, prev_sel_to
, length
)
6144 ## 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] )
6146 # difflib must not have optimized opcodes properly;
6150 # look for possible ambiguous diff:
6152 # if last change resulted in no selection, test from resulting cursor position:
6153 if prev_sel_start
== prev_sel_to
:
6154 calc_select_len
= sel_to
- sel_start
6155 field
= self
._FindField
(prev_sel_start
)
6157 # determine which way to search from last cursor position for ambiguous change:
6158 if field
._insertRight
:
6159 test_sel_start
= prev_sel_start
6160 test_sel_to
= prev_sel_start
+ calc_select_len
6162 test_sel_start
= prev_sel_start
- calc_select_len
6163 test_sel_to
= prev_sel_start
6165 test_sel_start
, test_sel_to
= prev_sel_start
, prev_sel_to
6167 ## dbg('test selection:', (test_sel_start, test_sel_to))
6168 ## dbg('calc change: "%s"' % prev[sel_start:sel_to])
6169 ## dbg('test change: "%s"' % prev[test_sel_start:test_sel_to])
6171 # if calculated selection spans characters, and same characters
6172 # "before" the previous insertion point are present there as well,
6173 # select the ones related to the last known selection instead.
6174 if( sel_start
!= sel_to
6175 and test_sel_to
< len(self
._template
)
6176 and prev
[test_sel_start
:test_sel_to
] == prev
[sel_start
:sel_to
] ):
6178 sel_start
, sel_to
= test_sel_start
, test_sel_to
6180 # finally, make sure that the old and new values are
6181 # different where we say they're different:
6182 while( sel_to
- 1 > 0
6183 and sel_to
> sel_start
6184 and value
[sel_to
-1:] == prev
[sel_to
-1:]):
6186 while( sel_start
+ 1 < self
._masklength
6187 and sel_start
< sel_to
6188 and value
[:sel_start
+1] == prev
[:sel_start
+1]):
6191 ## dbg('sel_start, sel_to:', sel_start, sel_to)
6192 ## dbg('previous value: "%s"' % prev)
6194 if just_return_results
:
6195 return prev
, (sel_start
, sel_to
)
6197 self
._SetValue
(prev
)
6198 self
._SetInsertionPoint
(sel_start
)
6199 self
._SetSelection
(sel_start
, sel_to
)
6202 ## dbg('no difference between previous value')
6204 if just_return_results
:
6205 return prev
, self
._GetSelection
()
6208 def _OnClear(self
, event
):
6209 """ Provides an action for context menu delete operation """
6213 def _OnContextMenu(self
, event
):
6214 ## dbg('MaskedEditMixin::OnContextMenu()', indent=1)
6216 menu
.Append(wx
.ID_UNDO
, "Undo", "")
6217 menu
.AppendSeparator()
6218 menu
.Append(wx
.ID_CUT
, "Cut", "")
6219 menu
.Append(wx
.ID_COPY
, "Copy", "")
6220 menu
.Append(wx
.ID_PASTE
, "Paste", "")
6221 menu
.Append(wx
.ID_CLEAR
, "Delete", "")
6222 menu
.AppendSeparator()
6223 menu
.Append(wx
.ID_SELECTALL
, "Select All", "")
6225 wx
.EVT_MENU(menu
, wx
.ID_UNDO
, self
._OnCtrl
_Z
)
6226 wx
.EVT_MENU(menu
, wx
.ID_CUT
, self
._OnCtrl
_X
)
6227 wx
.EVT_MENU(menu
, wx
.ID_COPY
, self
._OnCtrl
_C
)
6228 wx
.EVT_MENU(menu
, wx
.ID_PASTE
, self
._OnCtrl
_V
)
6229 wx
.EVT_MENU(menu
, wx
.ID_CLEAR
, self
._OnClear
)
6230 wx
.EVT_MENU(menu
, wx
.ID_SELECTALL
, self
._OnCtrl
_A
)
6232 # ## WSS: The base control apparently handles
6233 # enable/disable of wx.ID_CUT, wx.ID_COPY, wx.ID_PASTE
6234 # and wx.ID_CLEAR menu items even if the menu is one
6235 # we created. However, it doesn't do undo properly,
6236 # so we're keeping track of previous values ourselves.
6237 # Therefore, we have to override the default update for
6238 # that item on the menu:
6239 wx
.EVT_UPDATE_UI(self
, wx
.ID_UNDO
, self
._UndoUpdateUI
)
6240 self
._contextMenu
= menu
6242 self
.PopupMenu(menu
, event
.GetPosition())
6244 self
._contextMenu
= None
6247 def _UndoUpdateUI(self
, event
):
6248 if self
._prevValue
is None or self
._prevValue
== self
._curValue
:
6249 self
._contextMenu
.Enable(wx
.ID_UNDO
, False)
6251 self
._contextMenu
.Enable(wx
.ID_UNDO
, True)
6254 def _OnCtrlParametersChanged(self
):
6256 Overridable function to allow derived classes to take action as a
6257 result of parameter changes prior to possibly changing the value
6262 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6263 class MaskedEditAccessorsMixin
:
6265 To avoid a ton of boiler-plate, and to automate the getter/setter generation
6266 for each valid control parameter so we never forget to add the functions when
6267 adding parameters, this class programmatically adds the masked edit mixin
6268 parameters to itself.
6269 (This makes it easier for Designers like Boa to deal with masked controls.)
6271 To further complicate matters, this is done with an extra level of inheritance,
6272 so that "general" classes like masked.TextCtrl can have all possible attributes,
6273 while derived classes, like masked.TimeCtrl and masked.NumCtrl can prevent
6274 exposure of those optional attributes of their base class that do not make
6275 sense for their derivation.
6277 Therefore, we define:
6278 BaseMaskedTextCtrl(TextCtrl, MaskedEditMixin)
6280 masked.TextCtrl(BaseMaskedTextCtrl, MaskedEditAccessorsMixin).
6282 This allows us to then derive:
6283 masked.NumCtrl( BaseMaskedTextCtrl )
6285 and not have to expose all the same accessor functions for the
6286 derived control when they don't all make sense for it.
6290 # Define the default set of attributes exposed by the most generic masked controls:
6291 exposed_basectrl_params
= MaskedEditMixin
.valid_ctrl_params
.keys() + Field
.valid_params
.keys()
6292 exposed_basectrl_params
.remove('index')
6293 exposed_basectrl_params
.remove('extent')
6294 exposed_basectrl_params
.remove('foregroundColour') # (base class already has this)
6296 for param
in exposed_basectrl_params
:
6297 propname
= param
[0].upper() + param
[1:]
6298 exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname
, param
))
6299 exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
6301 if param.find('Colour
') != -1:
6302 # add non-british spellings, for backward-compatibility
6303 propname.replace('Colour
', 'Color
')
6305 exec('def Set
%s(self
, value
): self
.SetCtrlParameters(%s=value
)' % (propname, param))
6306 exec('def Get
%s(self
): return self
.GetCtrlParameter("%s")''' % (propname, param))
6311 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6312 ## these are helper subroutines:
6314 def _movetofloat( origvalue, fmtstring, neg, addseparators=False, sepchar = ',',fillchar=' '):
6315 """ addseparators = add separator character every three numerals if True
6317 fmt0 = fmtstring.split('.')
6320 val = origvalue.split('.')[0].strip()
6321 ret = fillchar * (len(fmt1)-len(val)) + val + "." + "0" * len(fmt2)
6324 return (ret,len(fmt1))
6327 def _isDateType( fmtstring ):
6328 """ Checks the mask and returns True if it fits an allowed
6329 date or datetime format.
6331 dateMasks = ("^##/##/####",
6343 reString = "|".join(dateMasks)
6344 filter = re.compile( reString)
6345 if re.match(filter,fmtstring): return True
6348 def _isTimeType( fmtstring ):
6349 """ Checks the mask and returns True if it fits an allowed
6352 reTimeMask = "^##:##(:##)?( (AM|PM))?"
6353 filter = re.compile( reTimeMask )
6354 if re.match(filter,fmtstring): return True
6358 def _isFloatingPoint( fmtstring):
6359 filter = re.compile("[ ]?[#]+\.[#]+\n")
6360 if re.match(filter,fmtstring+"\n"): return True
6364 def _isInteger( fmtstring ):
6365 filter = re.compile("[#]+\n")
6366 if re.match(filter,fmtstring+"\n"): return True
6370 def _getDateParts( dateStr, dateFmt ):
6371 if len(dateStr) > 11: clip = dateStr[0:11]
6372 else: clip = dateStr
6373 if clip[-2] not in string.digits:
6374 clip = clip[:-1] # (got part of time; drop it)
6376 dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.')
6377 slices = clip.split(dateSep)
6378 if dateFmt == "MDY":
6379 y,m,d = (slices[2],slices[0],slices[1]) ## year, month, date parts
6380 elif dateFmt == "DMY":
6381 y,m,d = (slices[2],slices[1],slices[0]) ## year, month, date parts
6382 elif dateFmt == "YMD":
6383 y,m,d = (slices[0],slices[1],slices[2]) ## year, month, date parts
6385 y,m,d = None, None, None
6392 def _getDateSepChar(dateStr):
6393 clip = dateStr[0:10]
6394 dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.')
6398 def _makeDate( year, month, day, dateFmt, dateStr):
6399 sep = _getDateSepChar( dateStr)
6400 if dateFmt == "MDY":
6401 return "%s%s%s%s%s" % (month,sep,day,sep,year) ## year, month, date parts
6402 elif dateFmt == "DMY":
6403 return "%s%s%s%s%s" % (day,sep,month,sep,year) ## year, month, date parts
6404 elif dateFmt == "YMD":
6405 return "%s%s%s%s%s" % (year,sep,month,sep,day) ## year, month, date parts
6410 def _getYear(dateStr,dateFmt):
6411 parts = _getDateParts( dateStr, dateFmt)
6414 def _getMonth(dateStr,dateFmt):
6415 parts = _getDateParts( dateStr, dateFmt)
6418 def _getDay(dateStr,dateFmt):
6419 parts = _getDateParts( dateStr, dateFmt)
6422 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6423 class __test(wx.PySimpleApp):
6425 from wx.lib.rcsizer import RowColSizer
6426 self.frame = wx.Frame( None, -1, "MaskedEditMixin 0.0.7 Demo Page #1", size = (700,600))
6427 self.panel = wx.Panel( self.frame, -1)
6428 self.sizer = RowColSizer()
6433 id, id1 = wx.NewId(), wx.NewId()
6434 self.command1 = wx.Button( self.panel, id, "&Close" )
6435 self.command2 = wx.Button( self.panel, id1, "&AutoFormats" )
6436 self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5)
6437 self.sizer.Add(self.command2, row=0, col=1, colspan=2, flag=wx.ALL, border = 5)
6438 self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1 )
6439 ## self.panel.SetDefaultItem(self.command1 )
6440 self.panel.Bind(wx.EVT_BUTTON, self.onClickPage, self.command2)
6442 self.check1 = wx.CheckBox( self.panel, -1, "Disallow Empty" )
6443 self.check2 = wx.CheckBox( self.panel, -1, "Highlight Empty" )
6444 self.sizer.Add( self.check1, row=0,col=3, flag=wx.ALL,border=5 )
6445 self.sizer.Add( self.check2, row=0,col=4, flag=wx.ALL,border=5 )
6446 self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck1, self.check1 )
6447 self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck2, self.check2 )
6450 label = """Press ctrl-s in any field to output the value and plain value. Press ctrl-x to clear and re-set any field.
6451 Note that all controls have been auto-sized by including F in the format code.
6452 Try entering nonsensical or partial values in validated fields to see what happens (use ctrl-s to test the valid status)."""
6453 label2 = "\nNote that the State and Last Name fields are list-limited (Name:Smith,Jones,Williams)."
6455 self.label1 = wx.StaticText( self.panel, -1, label)
6456 self.label2 = wx.StaticText( self.panel, -1, "Description")
6457 self.label3 = wx.StaticText( self.panel, -1, "Mask Value")
6458 self.label4 = wx.StaticText( self.panel, -1, "Format")
6459 self.label5 = wx.StaticText( self.panel, -1, "Reg Expr Val. (opt)")
6460 self.label6 = wx.StaticText( self.panel, -1, "MaskedEdit Ctrl")
6461 self.label7 = wx.StaticText( self.panel, -1, label2)
6462 self.label7.SetForegroundColour("Blue")
6463 self.label1.SetForegroundColour("Blue")
6464 self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6465 self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6466 self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6467 self.label5.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6468 self.label6.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6470 self.sizer.Add( self.label1, row=1,col=0,colspan=7, flag=wx.ALL,border=5)
6471 self.sizer.Add( self.label7, row=2,col=0,colspan=7, flag=wx.ALL,border=5)
6472 self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5)
6473 self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5)
6474 self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5)
6475 self.sizer.Add( self.label5, row=3,col=3, flag=wx.ALL,border=5)
6476 self.sizer.Add( self.label6, row=3,col=4, flag=wx.ALL,border=5)
6478 # The following list is of the controls for the demo. Feel free to play around with
6481 #description mask excl format regexp range,list,initial
6482 ("Phone No", "(###) ###-#### x:###", "", 'F!^-R', "^\(\d\d\d\) \d\d\d-\d\d\d\d", (),[],''),
6483 ("Last Name Only", "C{14}", "", 'F {list}', '^[A-Z][a-zA-Z]+', (),('Smith','Jones','Williams'),''),
6484 ("Full Name", "C{14}", "", 'F_', '^[A-Z][a-zA-Z]+ [A-Z][a-zA-Z]+', (),[],''),
6485 ("Social Sec#", "###-##-####", "", 'F', "\d{3}-\d{2}-\d{4}", (),[],''),
6486 ("U.S. Zip+4", "#{5}-#{4}", "", 'F', "\d{5}-(\s{4}|\d{4})",(),[],''),
6487 ("U.S. State (2 char)\n(with default)","AA", "", 'F!', "[A-Z]{2}", (),states, 'AZ'),
6488 ("Customer No", "\CAA-###", "", 'F!', "C[A-Z]{2}-\d{3}", (),[],''),
6489 ("Date (MDY) + Time\n(with default)", "##/##/#### ##:## AM", 'BCDEFGHIJKLMNOQRSTUVWXYZ','DFR!',"", (),[], r'03/05/2003 12:00 AM'),
6490 ("Invoice Total", "#{9}.##", "", 'F-R,', "", (),[], ''),
6491 ("Integer (signed)\n(with default)", "#{6}", "", 'F-R', "", (),[], '0 '),
6492 ("Integer (unsigned)\n(with default), 1-399", "######", "", 'F', "", (1,399),[], '1 '),
6493 ("Month selector", "XXX", "", 'F', "", (),
6494 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],""),
6495 ("fraction selector","#/##", "", 'F', "^\d\/\d\d?", (),
6496 ['2/3', '3/4', '1/2', '1/4', '1/8', '1/16', '1/32', '1/64'], "")
6499 for control in controls:
6500 self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL)
6501 self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL)
6502 self.sizer.Add( wx.StaticText( self.panel, -1, control[3]),row=rowcount, col=2,border=5, flag=wx.ALL)
6503 self.sizer.Add( wx.StaticText( self.panel, -1, control[4][:20]),row=rowcount, col=3,border=5, flag=wx.ALL)
6505 if control in controls[:]:#-2]:
6506 newControl = MaskedTextCtrl( self.panel, -1, "",
6508 excludeChars = control[2],
6509 formatcodes = control[3],
6511 validRegex = control[4],
6512 validRange = control[5],
6513 choices = control[6],
6514 defaultValue = control[7],
6516 if control[6]: newControl.SetCtrlParameters(choiceRequired = True)
6518 newControl = MaskedComboBox( self.panel, -1, "",
6519 choices = control[7],
6520 choiceRequired = True,
6522 formatcodes = control[3],
6523 excludeChars = control[2],
6525 validRegex = control[4],
6526 validRange = control[5],
6528 self.editList.append( newControl )
6530 self.sizer.Add( newControl, row=rowcount,col=4,flag=wx.ALL,border=5)
6533 self.sizer.AddGrowableCol(4)
6535 self.panel.SetSizer(self.sizer)
6536 self.panel.SetAutoLayout(1)
6543 def onClick(self, event):
6546 def onClickPage(self, event):
6547 self.page2 = __test2(self.frame,-1,"")
6548 self.page2.Show(True)
6550 def _onCheck1(self,event):
6551 """ Set required value on/off """
6552 value = event.IsChecked()
6554 for control in self.editList:
6555 control.SetCtrlParameters(emptyInvalid=True)
6558 for control in self.editList:
6559 control.SetCtrlParameters(emptyInvalid=False)
6561 self.panel.Refresh()
6563 def _onCheck2(self,event):
6564 """ Highlight empty values"""
6565 value = event.IsChecked()
6567 for control in self.editList:
6568 control.SetCtrlParameters( emptyBackgroundColour = 'Aquamarine')
6571 for control in self.editList:
6572 control.SetCtrlParameters( emptyBackgroundColour = 'White')
6574 self.panel.Refresh()
6577 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6579 class __test2(wx.Frame):
6580 def __init__(self, parent, id, caption):
6581 wx.Frame.__init__( self, parent, id, "MaskedEdit control 0.0.7 Demo Page #2 -- AutoFormats", size = (550,600))
6582 from wx.lib.rcsizer import RowColSizer
6583 self.panel = wx.Panel( self, -1)
6584 self.sizer = RowColSizer()
6590 All these controls have been created by passing a single parameter, the AutoFormat code.
6591 The class contains an internal dictionary of types and formats (autoformats).
6592 To see a great example of validations in action, try entering a bad email address, then tab out."""
6594 self.label1 = wx.StaticText( self.panel, -1, label)
6595 self.label2 = wx.StaticText( self.panel, -1, "Description")
6596 self.label3 = wx.StaticText( self.panel, -1, "AutoFormat Code")
6597 self.label4 = wx.StaticText( self.panel, -1, "MaskedEdit Control")
6598 self.label1.SetForegroundColour("Blue")
6599 self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6600 self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6601 self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6603 self.sizer.Add( self.label1, row=1,col=0,colspan=3, flag=wx.ALL,border=5)
6604 self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5)
6605 self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5)
6606 self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5)
6608 id, id1 = wx.NewId(), wx.NewId()
6609 self.command1 = wx.Button( self.panel, id, "&Close")
6610 self.command2 = wx.Button( self.panel, id1, "&Print Formats")
6611 self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1)
6612 self.panel.SetDefaultItem(self.command1)
6613 self.panel.Bind(wx.EVT_BUTTON, self.onClickPrint, self.command2)
6615 # The following list is of the controls for the demo. Feel free to play around with
6618 ("Phone No","USPHONEFULLEXT"),
6619 ("US Date + Time","USDATETIMEMMDDYYYY/HHMM"),
6620 ("US Date MMDDYYYY","USDATEMMDDYYYY/"),
6621 ("Time (with seconds)","TIMEHHMMSS"),
6622 ("Military Time\n(without seconds)","24HRTIMEHHMM"),
6623 ("Social Sec#","USSOCIALSEC"),
6624 ("Credit Card","CREDITCARD"),
6625 ("Expiration MM/YY","EXPDATEMMYY"),
6626 ("Percentage","PERCENT"),
6627 ("Person's Age","AGE"),
6628 ("US Zip Code","USZIP"),
6629 ("US Zip+4","USZIPPLUS4"),
6630 ("Email Address","EMAIL"),
6631 ("IP Address", "(derived control IpAddrCtrl)")
6634 for control in controls:
6635 self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL)
6636 self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL)
6637 if control in controls[:-1]:
6638 self.sizer.Add( MaskedTextCtrl( self.panel, -1, "",
6639 autoformat = control[1],
6641 row=rowcount,col=2,flag=wx.ALL,border=5)
6643 self.sizer.Add( IpAddrCtrl( self.panel, -1, "", demo=True ),
6644 row=rowcount,col=2,flag=wx.ALL,border=5)
6647 self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5)
6648 self.sizer.Add(self.command2, row=0, col=1, flag=wx.ALL, border = 5)
6649 self.sizer.AddGrowableCol(3)
6651 self.panel.SetSizer(self.sizer)
6652 self.panel.SetAutoLayout(1)
6654 def onClick(self, event):
6657 def onClickPrint(self, event):
6658 for format in masktags.keys():
6659 sep = "+------------------------+"
6660 print "%s\n%s \n Mask: %s \n RE Validation string: %s\n" % (sep,format, masktags[format]['mask'], masktags[format]['validRegex'])
6662 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6664 if __name__ == "__main__":
6670 ## ===================================
6672 ## 1. WS: For some reason I don't understand, the control is generating two (2)
6673 ## EVT_TEXT events for every one (1) .SetValue() of the underlying control.
6674 ## I've been unsuccessful in determining why or in my efforts to make just one
6675 ## occur. So, I've added a hack to save the last seen value from the
6676 ## control in the EVT_TEXT handler, and if *different*, call event.Skip()
6677 ## to propagate it down the event chain, and let the application see it.
6679 ## 2. WS: MaskedComboBox is deficient in several areas, all having to do with the
6680 ## behavior of the underlying control that I can't fix. The problems are:
6681 ## a) The background coloring doesn't work in the text field of the control;
6682 ## instead, there's a only border around it that assumes the correct color.
6683 ## b) The control will not pass WXK_TAB to the event handler, no matter what
6684 ## I do, and there's no style wxCB_PROCESS_TAB like wxTE_PROCESS_TAB to
6685 ## indicate that we want these events. As a result, MaskedComboBox
6686 ## doesn't do the nice field-tabbing that MaskedTextCtrl does.
6687 ## c) Auto-complete had to be reimplemented for the control because programmatic
6688 ## setting of the value of the text field does not set up the auto complete
6689 ## the way that the control processing keystrokes does. (But I think I've
6690 ## implemented a fairly decent approximation.) Because of this the control
6691 ## also won't auto-complete on dropdown, and there's no event I can catch
6692 ## to work around this problem.
6693 ## d) There is no method provided for getting the selection; the hack I've
6694 ## implemented has its flaws, not the least of which is that due to the
6695 ## strategy that I'm using, the paste buffer is always replaced by the
6696 ## contents of the control's selection when in focus, on each keystroke;
6697 ## this makes it impossible to paste anything into a MaskedComboBox
6698 ## at the moment... :-(
6699 ## e) The other deficient behavior, likely induced by the workaround for (d),
6700 ## is that you can can't shift-left to select more than one character
6704 ## 3. WS: Controls on wxPanels don't seem to pass Shift-WXK_TAB to their
6705 ## EVT_KEY_DOWN or EVT_CHAR event handlers. Until this is fixed in
6706 ## wxWindows, shift-tab won't take you backwards through the fields of
6707 ## a MaskedTextCtrl like it should. Until then Shifted arrow keys will
6708 ## work like shift-tab and tab ought to.
6712 ## =============================##
6713 ## 1. Add Popup list for auto-completable fields that simulates combobox on individual
6714 ## fields. Example: City validates against list of cities, or zip vs zip code list.
6715 ## 2. Allow optional monetary symbols (eg. $, pounds, etc.) at front of a "decimal"
6717 ## 3. Fix shift-left selection for MaskedComboBox.
6718 ## 5. Transform notion of "decimal control" to be less "entire control"-centric,
6719 ## so that monetary symbols can be included and still have the appropriate
6720 ## semantics. (Big job, as currently written, but would make control even
6721 ## more useful for business applications.)
6725 ## ====================
6727 ## 1. Added proper support for NUMPAD keypad keycodes for navigation and control.
6730 ## 1. Added value member to ValueError exceptions, so that people can catch them
6731 ## and then display their own errors, and added attribute raiseOnInvalidPaste,
6732 ## so one doesn't have to subclass the controls simply to force generation of
6733 ## a ValueError on a bad paste operation.
6734 ## 2. Fixed handling of unicode charsets by converting to explicit control char
6735 ## set testing for passing those keystrokes to the base control, and then
6736 ## changing the semantics of the * maskchar to indicate any visible char.
6737 ## 3. Added '|' mask specification character, which allows splitting of contiguous
6738 ## mask characters into separate fields, allowing finer control of behavior
6743 ## 1. Added handling for WXK_DELETE and WXK_INSERT, such that shift-delete
6744 ## cuts, shift-insert pastes, and ctrl-insert copies.
6747 ## 1. Now ignores kill focus events when being destroyed.
6748 ## 2. Added missing call to set insertion point on changing fields.
6749 ## 3. Modified SetKeyHandler() to accept None as means of removing one.
6750 ## 4. Fixed keyhandler processing for group and decimal character changes.
6751 ## 5. Fixed a problem that prevented input into the integer digit of a
6752 ## integerwidth=1 numctrl, if the current value was 0.
6753 ## 6. Fixed logic involving processing of "_signOk" flag, to remove default
6754 ## sign key handlers if false, so that SetAllowNegative(False) in the
6755 ## NumCtrl works properly.
6756 ## 7. Fixed selection logic for numeric controls so that if selectOnFieldEntry
6757 ## is true, and the integer portion of an integer format control is selected
6758 ## and the sign position is selected, the sign keys will always result in a
6759 ## negative value, rather than toggling the previous sign.
6763 ## 1. Fixed bug involving incorrect variable name, causing combobox autocomplete to fail.
6764 ## 2. Added proper support for unicode version of wxPython
6765 ## 3. Added * as mask char meaning "all ansi chars" (ordinals 32-255).
6766 ## 4. Converted doc strings to use reST format, for ePyDoc documentation.
6767 ## 5. Renamed helper functions, classes, etc. not intended to be visible in public
6768 ## interface to code.
6771 ## 1. Fixed intra-right-insert-field erase, such that it doesn't leave a hole, but instead
6772 ## shifts the text to the left accordingly.
6773 ## 2. Fixed _SetValue() to place cursor after last character inserted, rather than end of
6775 ## 3. Fixed some incorrect undo behavior for right-insert fields, and allowed derived classes
6776 ## (eg. numctrl) to pass modified values for undo processing (to handle/ignore grouping
6778 ## 4. Fixed autoselect behavior to work similarly to (2) above, so that combobox
6779 ## selection will only select the non-empty text, as per request.
6780 ## 5. Fixed tabbing to work with 2.5.2 semantics.
6781 ## 6. Fixed size calculation to handle changing fonts
6784 ## 1. Reorganized masked controls into separate package, renamed things accordingly
6785 ## 2. Split actual controls out of this file into their own files.
6787 ## (Reported) bugs fixed:
6788 ## 1. Crash ensues if you attempt to change the mask of a read-only
6789 ## MaskedComboBox after initial construction.
6790 ## 2. Changed strategy of defining Get/Set property functions so that
6791 ## these are now generated dynamically at runtime, rather than as
6792 ## part of the class definition. (This makes it possible to have
6793 ## more general base classes that have many more options for configuration
6794 ## without requiring that derivations support the same options.)
6795 ## 3. Fixed IsModified for _Paste() and _OnErase().
6798 ## 1. Fixed "attribute function inheritance," since base control is more
6799 ## generic than subsequent derivations, not all property functions of a
6800 ## generic control should be exposed in those derivations. New strategy
6801 ## uses base control classes (eg. BaseMaskedTextCtrl) that should be
6802 ## used to derive new class types, and mixed with their own mixins to
6803 ## only expose those attributes from the generic masked controls that
6804 ## make sense for the derivation. (This makes Boa happier.)
6805 ## 2. Renamed (with b-c) MILTIME autoformats to 24HRTIME, so as to be less
6809 ## (Reported) bugs fixed:
6810 ## 1. Right-click menu allowed "cut" operation that destroyed mask
6811 ## (was implemented by base control)
6812 ## 2. MaskedComboBox didn't allow .Append() of mixed-case values; all
6813 ## got converted to lower case.
6814 ## 3. MaskedComboBox selection didn't deal with spaces in values
6815 ## properly when autocompleting, and didn't have a concept of "next"
6816 ## match for handling choice list duplicates.
6817 ## 4. Size of MaskedComboBox was always default.
6818 ## 5. Email address regexp allowed some "non-standard" things, and wasn't
6820 ## 6. Couldn't easily reset MaskedComboBox contents programmatically.
6821 ## 7. Couldn't set emptyInvalid during construction.
6822 ## 8. Under some versions of wxPython, readonly comboboxes can apparently
6823 ## return a GetInsertionPoint() result (655535), causing masked control
6825 ## 9. Specifying an empty mask caused the controls to traceback.
6826 ## 10. Can't specify float ranges for validRange.
6827 ## 11. '.' from within a the static portion of a restricted IP address
6828 ## destroyed the mask from that point rightward; tab when cursor is
6829 ## before 1st field takes cursor past that field.
6832 ## 12. Added Ctrl-Z/Undo handling, (and implemented context-menu properly.)
6833 ## 13. Added auto-select option on char input for masked controls with
6835 ## 14. Added '>' formatcode, allowing insert within a given or each field
6836 ## as appropriate, rather than requiring "overwrite". This makes single
6837 ## field controls that just have validation rules (eg. EMAIL) much more
6838 ## friendly. The same flag controls left shift when deleting vs just
6839 ## blanking the value, and for right-insert fields, allows right-insert
6840 ## at any non-blank (non-sign) position in the field.
6841 ## 15. Added option to use to indicate negative values for numeric controls.
6842 ## 16. Improved OnFocus handling of numeric controls.
6843 ## 17. Enhanced Home/End processing to allow operation on a field level,
6845 ## 18. Added individual Get/Set functions for control parameters, for
6846 ## simplified integration with Boa Constructor.
6847 ## 19. Standardized "Colour" parameter names to match wxPython, with
6848 ## non-british spellings still supported for backward-compatibility.
6849 ## 20. Added '&' mask specification character for punctuation only (no letters
6851 ## 21. Added (in a separate file) wx.MaskedCtrl() factory function to provide
6852 ## unified interface to the masked edit subclasses.
6856 ## 1. Made it possible to configure grouping, decimal and shift-decimal characters,
6857 ## to make controls more usable internationally.
6858 ## 2. Added code to smart "adjust" value strings presented to .SetValue()
6859 ## for right-aligned numeric format controls if they are shorter than
6860 ## than the control width, prepending the missing portion, prepending control
6861 ## template left substring for the missing characters, so that setting
6862 ## numeric values is easier.
6863 ## 3. Renamed SetMaskParameters SetCtrlParameters() (with old name preserved
6864 ## for b-c), as this makes more sense.
6867 ## 1. Fixed .SetValue() to replace the current value, rather than the current
6868 ## selection. Also changed it to generate ValueError if presented with
6869 ## either a value which doesn't follow the format or won't fit. Also made
6870 ## set value adjust numeric and date controls as if user entered the value.
6871 ## Expanded doc explaining how SetValue() works.
6872 ## 2. Fixed EUDATE* autoformats, fixed IsDateType mask list, and added ability to
6873 ## use 3-char months for dates, and EUDATETIME, and EUDATEMILTIME autoformats.
6874 ## 3. Made all date autoformats automatically pick implied "datestyle".
6875 ## 4. Added IsModified override, since base wx.TextCtrl never reports modified if
6876 ## .SetValue used to change the value, which is what the masked edit controls
6878 ## 5. Fixed bug in date position adjustment on 2 to 4 digit date conversion when
6879 ## using tab to "leave field" and auto-adjust.
6880 ## 6. Fixed bug in _isCharAllowed() for negative number insertion on pastes,
6881 ## and bug in ._Paste() that didn't account for signs in signed masks either.
6882 ## 7. Fixed issues with _adjustPos for right-insert fields causing improper
6883 ## selection/replacement of values
6884 ## 8. Fixed _OnHome handler to properly handle extending current selection to
6885 ## beginning of control.
6886 ## 9. Exposed all (valid) autoformats to demo, binding descriptions to
6888 ## 10. Fixed a couple of bugs in email regexp.
6889 ## 11. Made maskchardict an instance var, to make mask chars to be more
6890 ## amenable to international use.
6891 ## 12. Clarified meaning of '-' formatcode in doc.
6892 ## 13. Fixed a couple of coding bugs being flagged by Python2.1.
6893 ## 14. Fixed several issues with sign positioning, erasure and validity
6894 ## checking for "numeric" masked controls.
6895 ## 15. Added validation to IpAddrCtrl.SetValue().
6898 ## 1. Changed calling interface to use boolean "useFixedWidthFont" (True by default)
6899 ## vs. literal font facename, and use wxTELETYPE as the font family
6901 ## 2. Switched to use of dbg module vs. locally defined version.
6902 ## 3. Revamped entire control structure to use Field classes to hold constraint
6903 ## and formatting data, to make code more hierarchical, allow for more
6904 ## sophisticated masked edit construction.
6905 ## 4. Better strategy for managing options, and better validation on keywords.
6906 ## 5. Added 'V' format code, which requires that in order for a character
6907 ## to be accepted, it must result in a string that passes the validRegex.
6908 ## 6. Added 'S' format code which means "select entire field when navigating
6910 ## 7. Added 'r' format code to allow "right-insert" fields. (implies 'R'--right-alignment)
6911 ## 8. Added '<' format code to allow fields to require explicit cursor movement
6913 ## 9. Added validFunc option to other validation mechanisms, that allows derived
6914 ## classes to add dynamic validation constraints to the control.
6915 ## 10. Fixed bug in validatePaste code causing possible IndexErrors, and also
6916 ## fixed failure to obey case conversion codes when pasting.
6917 ## 11. Implemented '0' (zero-pad) formatting code, as it wasn't being done anywhere...
6918 ## 12. Removed condition from OnDecimalPoint, so that it always truncates right on '.'
6919 ## 13. Enhanced IpAddrCtrl to use right-insert fields, selection on field traversal,
6920 ## individual field validation to prevent field values > 255, and require explicit
6921 ## tab/. to change fields.
6922 ## 14. Added handler for left double-click to select field under cursor.
6923 ## 15. Fixed handling for "Read-only" styles.
6924 ## 16. Separated signedForegroundColor from 'R' style, and added foregroundColor
6925 ## attribute, for more consistent and controllable coloring.
6926 ## 17. Added retainFieldValidation parameter, allowing top-level constraints
6927 ## such as "validRequired" to be set independently of field-level equivalent.
6928 ## (needed in TimeCtrl for bounds constraints.)
6929 ## 18. Refactored code a bit, cleaned up and commented code more heavily, fixed
6930 ## some of the logic for setting/resetting parameters, eg. fillChar, defaultValue,
6932 ## 19. Fixed maskchar setting for upper/lowercase, to work in all locales.
6936 ## 1. Decimal point behavior restored for decimal and integer type controls:
6937 ## decimal point now trucates the portion > 0.
6938 ## 2. Return key now works like the tab character and moves to the next field,
6939 ## provided no default button is set for the form panel on which the control
6941 ## 3. Support added in _FindField() for subclasses controls (like timecontrol)
6942 ## to determine where the current insertion point is within the mask (i.e.
6943 ## which sub-'field'). See method documentation for more info and examples.
6944 ## 4. Added Field class and support for all constraints to be field-specific
6945 ## in addition to being globally settable for the control.
6946 ## Choices for each field are validated for length and pastability into
6947 ## the field in question, raising ValueError if not appropriate for the control.
6948 ## Also added selective additional validation based on individual field constraints.
6949 ## By default, SHIFT-WXK_DOWN, SHIFT-WXK_UP, WXK_PRIOR and WXK_NEXT all
6950 ## auto-complete fields with choice lists, supplying the 1st entry in
6951 ## the choice list if the field is empty, and cycling through the list in
6952 ## the appropriate direction if already a match. WXK_DOWN will also auto-
6953 ## complete if the field is partially completed and a match can be made.
6954 ## SHIFT-WXK_UP/DOWN will also take you to the next field after any
6955 ## auto-completion performed.
6956 ## 5. Added autoCompleteKeycodes=[] parameters for allowing further
6957 ## customization of the control. Any keycode supplied as a member
6958 ## of the _autoCompleteKeycodes list will be treated like WXK_NEXT. If
6959 ## requireFieldChoice is set, then a valid value from each non-empty
6960 ## choice list will be required for the value of the control to validate.
6961 ## 6. Fixed "auto-sizing" to be relative to the font actually used, rather
6962 ## than making assumptions about character width.
6963 ## 7. Fixed GetMaskParameter(), which was non-functional in previous version.
6964 ## 8. Fixed exceptions raised to provide info on which control had the error.
6965 ## 9. Fixed bug in choice management of MaskedComboBox.
6966 ## 10. Fixed bug in IpAddrCtrl causing traceback if field value was of
6967 ## the form '# #'. Modified control code for IpAddrCtrl so that '.'
6968 ## in the middle of a field clips the rest of that field, similar to
6969 ## decimal and integer controls.
6973 ## 1. "-" is a toggle for sign; "+" now changes - signed numerics to positive.
6974 ## 2. ',' in formatcodes now causes numeric values to be comma-delimited (e.g.333,333).
6975 ## 3. New support for selecting text within the control.(thanks Will Sadkin!)
6976 ## Shift-End and Shift-Home now select text as you would expect
6977 ## Control-Shift-End selects to the end of the mask string, even if value not entered.
6978 ## Control-A selects all *entered* text, Shift-Control-A selects everything in the control.
6979 ## 4. event.Skip() added to onKillFocus to correct remnants when running in Linux (contributed-
6980 ## for some reason I couldn't find the original email but thanks!!!)
6981 ## 5. All major key-handling code moved to their own methods for easier subclassing: OnHome,
6982 ## OnErase, OnEnd, OnCtrl_X, OnCtrl_A, etc.
6983 ## 6. Email and autoformat validations corrected using regex provided by Will Sadkin (thanks!).
6984 ## (The rest of the changes in this version were done by Will Sadkin with permission from Jeff...)
6985 ## 7. New mechanism for replacing default behavior for any given key, using
6986 ## ._SetKeycodeHandler(keycode, func) and ._SetKeyHandler(char, func) now available
6987 ## for easier subclassing of the control.
6988 ## 8. Reworked the delete logic, cut, paste and select/replace logic, as well as some bugs
6989 ## with insertion point/selection modification. Changed Ctrl-X to use standard "cut"
6990 ## semantics, erasing the selection, rather than erasing the entire control.
6991 ## 9. Added option for an "default value" (ie. the template) for use when a single fillChar
6992 ## is not desired in every position. Added IsDefault() function to mean "does the value
6993 ## equal the template?" and modified .IsEmpty() to mean "do all of the editable
6994 ## positions in the template == the fillChar?"
6995 ## 10. Extracted mask logic into mixin, so we can have both MaskedTextCtrl and MaskedComboBox,
6997 ## 11. MaskedComboBox now adds the capability to validate from list of valid values.
6998 ## Example: City validates against list of cities, or zip vs zip code list.
6999 ## 12. Fixed oversight in EVT_TEXT handler that prevented the events from being
7000 ## passed to the next handler in the event chain, causing updates to the
7001 ## control to be invisible to the parent code.
7002 ## 13. Added IPADDR autoformat code, and subclass IpAddrCtrl for controlling tabbing within
7003 ## the control, that auto-reformats as you move between cells.
7004 ## 14. Mask characters [A,a,X,#] can now appear in the format string as literals, by using '\'.
7005 ## 15. It is now possible to specify repeating masks, e.g. #{3}-#{3}-#{14}
7006 ## 16. Fixed major bugs in date validation, due to the fact that
7007 ## wxDateTime.ParseDate is too liberal, and will accept any form that
7008 ## makes any kind of sense, regardless of the datestyle you specified
7009 ## for the control. Unfortunately, the strategy used to fix it only
7010 ## works for versions of wxPython post 2.3.3.1, as a C++ assert box
7011 ## seems to show up on an invalid date otherwise, instead of a catchable
7013 ## 17. Enhanced date adjustment to automatically adjust heuristic based on
7014 ## current year, making last century/this century determination on
7015 ## 2-digit year based on distance between today's year and value;
7016 ## if > 50 year separation, assume last century (and don't assume last
7017 ## century is 20th.)
7018 ## 18. Added autoformats and support for including HHMMSS as well as HHMM for
7019 ## date times, and added similar time, and militaray time autoformats.
7020 ## 19. Enhanced tabbing logic so that tab takes you to the next field if the
7021 ## control is a multi-field control.
7022 ## 20. Added stub method called whenever the control "changes fields", that
7023 ## can be overridden by subclasses (eg. IpAddrCtrl.)
7024 ## 21. Changed a lot of code to be more functionally-oriented so side-effects
7025 ## aren't as problematic when maintaining code and/or adding features.
7026 ## Eg: IsValid() now does not have side-effects; it merely reflects the
7027 ## validity of the value of the control; to determine validity AND recolor
7028 ## the control, _CheckValid() should be used with a value argument of None.
7029 ## Similarly, made most reformatting function take an optional candidate value
7030 ## rather than just using the current value of the control, and only
7031 ## have them change the value of the control if a candidate is not specified.
7032 ## In this way, you can do validation *before* changing the control.
7033 ## 22. Changed validRequired to mean "disallow chars that result in invalid
7034 ## value." (Old meaning now represented by emptyInvalid.) (This was
7035 ## possible once I'd made the changes in (19) above.)
7036 ## 23. Added .SetMaskParameters and .GetMaskParameter methods, so they
7037 ## can be set/modified/retrieved after construction. Removed individual
7038 ## parameter setting functions, in favor of this mechanism, so that
7039 ## all adjustment of the control based on changing parameter values can
7040 ## be handled in one place with unified mechanism.
7041 ## 24. Did a *lot* of testing and fixing re: numeric values. Added ability
7042 ## to type "grouping char" (ie. ',') and validate as appropriate.
7043 ## 25. Fixed ZIPPLUS4 to allow either 5 or 4, but if > 5 must be 9.
7044 ## 26. Fixed assumption about "decimal or integer" masks so that they're only
7045 ## made iff there's no validRegex associated with the field. (This
7046 ## is so things like zipcodes which look like integers can have more
7047 ## restrictive validation (ie. must be 5 digits.)
7048 ## 27. Added a ton more doc strings to explain use and derivation requirements
7049 ## and did regularization of the naming conventions.
7050 ## 28. Fixed a range bug in _adjustKey preventing z from being handled properly.
7051 ## 29. Changed behavior of '.' (and shift-.) in numeric controls to move to
7052 ## reformat the value and move the next field as appropriate. (shift-'.',
7053 ## ie. '>' moves to the previous field.
7056 ## 1. Fixed regex bug that caused autoformat AGE to invalidate any age ending
7058 ## 2. New format character 'D' to trigger date type. If the user enters 2 digits in the
7059 ## year position, the control will expand the value to four digits, using numerals below
7060 ## 50 as 21st century (20+nn) and less than 50 as 20th century (19+nn).
7061 ## Also, new optional parameter datestyle = set to one of {MDY|DMY|YDM}
7062 ## 3. revalid parameter renamed validRegex to conform to standard for all validation
7063 ## parameters (see 2 new ones below).
7064 ## 4. New optional init parameter = validRange. Used only for int/dec (numeric) types.
7065 ## Allows the developer to specify a valid low/high range of values.
7066 ## 5. New optional init parameter = validList. Used for character types. Allows developer
7067 ## to send a list of values to the control to be used for specific validation.
7068 ## See the Last Name Only example - it is list restricted to Smith/Jones/Williams.
7069 ## 6. Date type fields now use wxDateTime's parser to validate the date and time.
7070 ## This works MUCH better than my kludgy regex!! Thanks to Robin Dunn for pointing
7071 ## me toward this solution!
7072 ## 7. Date fields now automatically expand 2-digit years when it can. For example,
7073 ## if the user types "03/10/67", then "67" will auto-expand to "1967". If a two-year
7074 ## date is entered it will be expanded in any case when the user tabs out of the
7076 ## 8. New class functions: SetValidBackgroundColor, SetInvalidBackgroundColor, SetEmptyBackgroundColor,
7077 ## SetSignedForeColor allow accessto override default class coloring behavior.
7078 ## 9. Documentation updated and improved.
7079 ## 10. Demo - page 2 is now a wxFrame class instead of a wxPyApp class. Works better.
7080 ## Two new options (checkboxes) - test highlight empty and disallow empty.
7081 ## 11. Home and End now work more intuitively, moving to the first and last user-entry
7082 ## value, respectively.
7083 ## 12. New class function: SetRequired(bool). Sets the control's entry required flag
7084 ## (i.e. disallow empty values if True).
7087 ## 1. get_plainValue method renamed to GetPlainValue following the wxWindows
7088 ## StudlyCaps(tm) standard (thanks Paul Moore). ;)
7089 ## 2. New format code 'F' causes the control to auto-fit (auto-size) itself
7090 ## based on the length of the mask template.
7091 ## 3. Class now supports "autoformat" codes. These can be passed to the class
7092 ## on instantiation using the parameter autoformat="code". If the code is in
7093 ## the dictionary, it will self set the mask, formatting, and validation string.
7094 ## I have included a number of samples, but I am hoping that someone out there
7095 ## can help me to define a whole bunch more.
7096 ## 4. I have added a second page to the demo (as well as a second demo class, test2)
7097 ## to showcase how autoformats work. The way they self-format and self-size is,
7098 ## I must say, pretty cool.
7099 ## 5. Comments added and some internal cosmetic revisions re: matching the code
7100 ## standards for class submission.
7101 ## 6. Regex validation is now done in real time - field turns yellow immediately
7102 ## and stays yellow until the entered value is valid
7103 ## 7. Cursor now skips over template characters in a more intuitive way (before the
7105 ## 8. Change, Keypress and LostFocus methods added for convenience of subclasses.
7106 ## Developer may use these methods which will be called after EVT_TEXT, EVT_CHAR,
7107 ## and EVT_KILL_FOCUS, respectively.
7108 ## 9. Decimal and numeric handlers have been rewritten and now work more intuitively.
7111 ## 1. New .IsEmpty() method returns True if the control's value is equal to the
7112 ## blank template string
7113 ## 2. Control now supports a new init parameter: revalid. Pass a regular expression
7114 ## that the value will have to match when the control loses focus. If invalid,
7115 ## the control's BackgroundColor will turn yellow, and an internal flag is set (see next).
7116 ## 3. Demo now shows revalid functionality. Try entering a partial value, such as a
7117 ## partial social security number.
7118 ## 4. New .IsValid() value returns True if the control is empty, or if the value matches
7119 ## the revalid expression. If not, .IsValid() returns False.
7120 ## 5. Decimal values now collapse to decimal with '.00' on losefocus if the user never
7121 ## presses the decimal point.
7122 ## 6. Cursor now goes to the beginning of the field if the user clicks in an
7123 ## "empty" field intead of leaving the insertion point in the middle of the
7125 ## 7. New "N" mask type includes upper and lower chars plus digits. a-zA-Z0-9.
7126 ## 8. New formatcodes init parameter replaces other init params and adds functions.
7127 ## String passed to control on init controls:
7131 ## R Show negative #s in red
7133 ## - Signed numerals
7134 ## 0 Numeric fields get leading zeros
7135 ## 9. Ctrl-X in any field clears the current value.
7136 ## 10. Code refactored and made more modular (esp in OnChar method). Should be more
7137 ## easy to read and understand.
7138 ## 11. Demo enhanced.
7139 ## 12. Now has _doc_.
7142 ## 1. GetPlainValue() now returns the value without the template characters;
7143 ## so, for example, a social security number (123-33-1212) would return as
7144 ## 123331212; also removes white spaces from numeric/decimal values, so
7145 ## "- 955.32" is returned "-955.32". Press ctrl-S to see the plain value.
7146 ## 2. Press '.' in an integer style masked control and truncate any trailing digits.
7147 ## 3. Code moderately refactored. Internal names improved for clarity. Additional
7148 ## internal documentation.
7149 ## 4. Home and End keys now supported to move cursor to beginning or end of field.
7150 ## 5. Un-signed integers and decimals now supported.
7151 ## 6. Cosmetic improvements to the demo.
7152 ## 7. Class renamed to MaskedTextCtrl.
7153 ## 8. Can now specify include characters that will override the basic
7154 ## controls: for example, includeChars = "@." for email addresses
7155 ## 9. Added mask character 'C' -> allow any upper or lowercase character
7156 ## 10. .SetSignColor(str:color) sets the foreground color for negative values
7157 ## in signed controls (defaults to red)
7158 ## 11. Overview documentation written.
7161 ## 1. Tab now works properly when pressed in last position
7162 ## 2. Decimal types now work (e.g. #####.##)
7163 ## 3. Signed decimal or numeric values supported (i.e. negative numbers)
7164 ## 4. Negative decimal or numeric values now can show in red.
7165 ## 5. Can now specify an "exclude list" with the excludeChars parameter.
7166 ## See date/time formatted example - you can only enter A or P in the
7167 ## character mask space (i.e. AM/PM).
7168 ## 6. Backspace now works properly, including clearing data from a selected
7169 ## region but leaving template characters intact. Also delete key.
7170 ## 7. Left/right arrows now work properly.
7171 ## 8. Removed EventManager call from test so demo should work with wxPython 2.3.3