]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wx/lib/maskededit.py
Fixed some wx prefix issues, changed the self test to use a sizer.
[wxWidgets.git] / wxPython / wx / lib / maskededit.py
1 #----------------------------------------------------------------------------
2 # Name: maskededit.py
3 # Authors: Jeff Childers, Will Sadkin
4 # Email: jchilders_98@yahoo.com, wsadkin@nameconnector.com
5 # Created: 02/11/2003
6 # Copyright: (c) 2003 by Jeff Childers, 2003
7 # Portions: (c) 2002 by Will Sadkin, 2002-2003
8 # RCS-ID: $Id$
9 # License: wxWindows license
10 #----------------------------------------------------------------------------
11 # NOTE:
12 # This was written way it is because of the lack of masked edit controls
13 # in wxWindows/wxPython.
14 #
15 # MaskedEdit controls are based on a suggestion made on [wxPython-Users] by
16 # Jason Hihn, and borrows liberally from Will Sadkin's original masked edit
17 # control for time entry, TimeCtrl (which is now rewritten using this
18 # control!).
19 #
20 # MaskedEdit controls do not normally use validators, because they do
21 # careful manipulation of the cursor in the text window on each keystroke,
22 # and validation is cursor-position specific, so the control intercepts the
23 # key codes before the validator would fire. However, validators can be
24 # provided to do data transfer to the controls.
25 #
26 #----------------------------------------------------------------------------
27 #
28 # 12/09/2003 - Jeff Grimmett (grimmtooth@softhome.net)
29 #
30 # o Updated for wx namespace. No guarantees. This is one huge file.
31 #
32 # 12/13/2003 - Jeff Grimmett (grimmtooth@softhome.net)
33 #
34 # o Missed wx.DateTime stuff earlier.
35 #
36 # 12/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
37 #
38 # o wxMaskedEditMixin -> MaskedEditMixin
39 # o wxMaskedTextCtrl -> MaskedTextCtrl
40 # o wxMaskedComboBoxSelectEvent -> MaskedComboBoxSelectEvent
41 # o wxMaskedComboBox -> MaskedComboBox
42 # o wxIpAddrCtrl -> IpAddrCtrl
43 # o wxTimeCtrl -> TimeCtrl
44 #
45
46 """\
47 <b>Masked Edit Overview:
48 =====================</b>
49 <b>MaskedTextCtrl</b>
50 is a sublassed text control that can carefully control the user's input
51 based on a mask string you provide.
52
53 General usage example:
54 control = MaskedTextCtrl( win, -1, '', mask = '(###) ###-####')
55
56 The example above will create a text control that allows only numbers to be
57 entered and then only in the positions indicated in the mask by the # sign.
58
59 <b>MaskedComboBox</b>
60 is a similar subclass of wxComboBox that allows the same sort of masking,
61 but also can do auto-complete of values, and can require the value typed
62 to be in the list of choices to be colored appropriately.
63
64 <b>wxMaskedCtrl</b>
65 is actually a factory function for several types of masked edit controls:
66
67 <b>MaskedTextCtrl</b> - standard masked edit text box
68 <b>MaskedComboBox</b> - adds combobox capabilities
69 <b>IpAddrCtrl</b> - adds special semantics for IP address entry
70 <b>TimeCtrl</b> - special subclass handling lots of types as values
71 <b>wxMaskedNumCtrl</b> - special subclass handling numeric values
72
73 It works by looking for a <b><i>controlType</i></b> parameter in the keyword
74 arguments of the control, to determine what kind of instance to return.
75 If not specified as a keyword argument, the default control type returned
76 will be MaskedTextCtrl.
77
78 Each of the above classes has its own set of arguments, but wxMaskedCtrl
79 provides a single "unified" interface for masked controls. Those for
80 MaskedTextCtrl, MaskedComboBox and IpAddrCtrl are all documented
81 below; the others have their own demo pages and interface descriptions.
82 (See end of following discussion for how to configure the wxMaskedCtrl()
83 to select the above control types.)
84
85
86 <b>INITILIZATION PARAMETERS
87 ========================
88 mask=</b>
89 Allowed mask characters and function:
90 Character Function
91 # Allow numeric only (0-9)
92 N Allow letters and numbers (0-9)
93 A Allow uppercase letters only
94 a Allow lowercase letters only
95 C Allow any letter, upper or lower
96 X Allow string.letters, string.punctuation, string.digits
97 &amp; Allow string.punctuation only
98
99
100 These controls define these sets of characters using string.letters,
101 string.uppercase, etc. These sets are affected by the system locale
102 setting, so in order to have the masked controls accept characters
103 that are specific to your users' language, your application should
104 set the locale.
105 For example, to allow international characters to be used in the
106 above masks, you can place the following in your code as part of
107 your application's initialization code:
108
109 import locale
110 locale.setlocale(locale.LC_ALL, '')
111
112
113 Using these mask characters, a variety of template masks can be built. See
114 the demo for some other common examples include date+time, social security
115 number, etc. If any of these characters are needed as template rather
116 than mask characters, they can be escaped with \, ie. \N means "literal N".
117 (use \\ for literal backslash, as in: r'CCC\\NNN'.)
118
119
120 <b>Note:</b>
121 Masks containing only # characters and one optional decimal point
122 character are handled specially, as "numeric" controls. Such
123 controls have special handling for typing the '-' key, handling
124 the "decimal point" character as truncating the integer portion,
125 optionally allowing grouping characters and so forth.
126 There are several parameters and format codes that only make sense
127 when combined with such masks, eg. groupChar, decimalChar, and so
128 forth (see below). These allow you to construct reasonable
129 numeric entry controls.
130
131 <b>Note:</b>
132 Changing the mask for a control deletes any previous field classes
133 (and any associated validation or formatting constraints) for them.
134
135 <b>useFixedWidthFont=</b>
136 By default, masked edit controls use a fixed width font, so that
137 the mask characters are fixed within the control, regardless of
138 subsequent modifications to the value. Set to False if having
139 the control font be the same as other controls is required.
140
141
142 <b>formatcodes=</b>
143 These other properties can be passed to the class when instantiating it:
144 Formatcodes are specified as a string of single character formatting
145 codes that modify behavior of the control:
146 _ Allow spaces
147 ! Force upper
148 ^ Force lower
149 R Right-align field(s)
150 r Right-insert in field(s) (implies R)
151 &lt; Stay in field until explicit navigation out of it
152
153 &gt; Allow insert/delete within partially filled fields (as
154 opposed to the default "overwrite" mode for fixed-width
155 masked edit controls.) This allows single-field controls
156 or each field within a multi-field control to optionally
157 behave more like standard text controls.
158 (See EMAIL or phone number autoformat examples.)
159
160 <i>Note: This also governs whether backspace/delete operations
161 shift contents of field to right of cursor, or just blank the
162 erased section.
163
164 Also, when combined with 'r', this indicates that the field
165 or control allows right insert anywhere within the current
166 non-empty value in the field. (Otherwise right-insert behavior
167 is only performed to when the entire right-insertable field is
168 selected or the cursor is at the right edge of the field.</i>
169
170
171 , Allow grouping character in integer fields of numeric controls
172 and auto-group/regroup digits (if the result fits) when leaving
173 such a field. (If specified, .SetValue() will attempt to
174 auto-group as well.)
175 ',' is also the default grouping character. To change the
176 grouping character and/or decimal character, use the groupChar
177 and decimalChar parameters, respectively.
178 Note: typing the "decimal point" character in such fields will
179 clip the value to that left of the cursor for integer
180 fields of controls with "integer" or "floating point" masks.
181 If the ',' format code is specified, this will also cause the
182 resulting digits to be regrouped properly, using the current
183 grouping character.
184 - Prepend and reserve leading space for sign to mask and allow
185 signed values (negative #s shown in red by default.) Can be
186 used with argument useParensForNegatives (see below.)
187 0 integer fields get leading zeros
188 D Date[/time] field
189 T Time field
190 F Auto-Fit: the control calulates its size from
191 the length of the template mask
192 V validate entered chars against validRegex before allowing them
193 to be entered vs. being allowed by basic mask and then having
194 the resulting value just colored as invalid.
195 (See USSTATE autoformat demo for how this can be used.)
196 S select entire field when navigating to new field
197
198 <b>fillChar=
199 defaultValue=</b>
200 These controls have two options for the initial state of the control.
201 If a blank control with just the non-editable characters showing
202 is desired, simply leave the constructor variable fillChar as its
203 default (' '). If you want some other character there, simply
204 change the fillChar to that value. Note: changing the control's fillChar
205 will implicitly reset all of the fields' fillChars to this value.
206
207 If you need different default characters in each mask position,
208 you can specify a defaultValue parameter in the constructor, or
209 set them for each field individually.
210 This value must satisfy the non-editable characters of the mask,
211 but need not conform to the replaceable characters.
212
213 <b>groupChar=
214 decimalChar=</b>
215 These parameters govern what character is used to group numbers
216 and is used to indicate the decimal point for numeric format controls.
217 The default groupChar is ',', the default decimalChar is '.'
218 By changing these, you can customize the presentation of numbers
219 for your location.
220 eg: formatcodes = ',', groupChar="'" allows 12'345.34
221 formatcodes = ',', groupChar='.', decimalChar=',' allows 12.345,34
222
223 <b>shiftDecimalChar=</b>
224 The default "shiftDecimalChar" (used for "backwards-tabbing" until
225 shift-tab is fixed in wxPython) is '>' (for QUERTY keyboards.) for
226 other keyboards, you may want to customize this, eg '?' for shift ',' on
227 AZERTY keyboards, ':' or ';' for other European keyboards, etc.
228
229 <b>useParensForNegatives=False</b>
230 This option can be used with signed numeric format controls to
231 indicate signs via () rather than '-'.
232
233 <b>autoSelect=False</b>
234 This option can be used to have a field or the control try to
235 auto-complete on each keystroke if choices have been specified.
236
237 <b>autoCompleteKeycodes=[]</b>
238 By default, DownArrow, PageUp and PageDown will auto-complete a
239 partially entered field. Shift-DownArrow, Shift-UpArrow, PageUp
240 and PageDown will also auto-complete, but if the field already
241 contains a matched value, these keys will cycle through the list
242 of choices forward or backward as appropriate. Shift-Up and
243 Shift-Down also take you to the next/previous field after any
244 auto-complete action.
245
246 Additional auto-complete keys can be specified via this parameter.
247 Any keys so specified will act like PageDown.
248
249
250
251 <b>Validating User Input:
252 ======================</b>
253 There are a variety of initialization parameters that are used to validate
254 user input. These parameters can apply to the control as a whole, and/or
255 to individual fields:
256
257 excludeChars= A string of characters to exclude even if otherwise allowed
258 includeChars= A string of characters to allow even if otherwise disallowed
259 validRegex= Use a regular expression to validate the contents of the text box
260 validRange= Pass a rangeas list (low,high) to limit numeric fields/values
261 choices= A list of strings that are allowed choices for the control.
262 choiceRequired= value must be member of choices list
263 compareNoCase= Perform case-insensitive matching when validating against list
264 <i>Note: for MaskedComboBox, this defaults to True.</i>
265 emptyInvalid= Boolean indicating whether an empty value should be considered invalid
266
267 validFunc= A function to call of the form: bool = func(candidate_value)
268 which will return True if the candidate_value satisfies some
269 external criteria for the control in addition to the the
270 other validation, or False if not. (This validation is
271 applied last in the chain of validations.)
272
273 validRequired= Boolean indicating whether or not keys that are allowed by the
274 mask, but result in an invalid value are allowed to be entered
275 into the control. Setting this to True implies that a valid
276 default value is set for the control.
277
278 retainFieldValidation=
279 False by default; if True, this allows individual fields to
280 retain their own validation constraints independently of any
281 subsequent changes to the control's overall parameters.
282
283 validator= Validators are not normally needed for masked controls, because
284 of the nature of the validation and control of input. However,
285 you can supply one to provide data transfer routines for the
286 controls.
287
288
289 <b>Coloring Behavior:
290 ==================</b>
291 The following parameters have been provided to allow you to change the default
292 coloring behavior of the control. These can be set at construction, or via
293 the .SetCtrlParameters() function. Pass a color as string e.g. 'Yellow':
294
295 emptyBackgroundColour= Control Background color when identified as empty. Default=White
296 invalidBackgroundColour= Control Background color when identified as Not valid. Default=Yellow
297 validBackgroundColour= Control Background color when identified as Valid. Default=white
298
299
300 The following parameters control the default foreground color coloring behavior of the
301 control. Pass a color as string e.g. 'Yellow':
302 foregroundColour= Control foreground color when value is not negative. Default=Black
303 signedForegroundColour= Control foreground color when value is negative. Default=Red
304
305
306 <b>Fields:
307 =======</b>
308 Each part of the mask that allows user input is considered a field. The fields
309 are represented by their own class instances. You can specify field-specific
310 constraints by constructing or accessing the field instances for the control
311 and then specifying those constraints via parameters.
312
313 <b>fields=</b>
314 This parameter allows you to specify Field instances containing
315 constraints for the individual fields of a control, eg: local
316 choice lists, validation rules, functions, regexps, etc.
317 It can be either an ordered list or a dictionary. If a list,
318 the fields will be applied as fields 0, 1, 2, etc.
319 If a dictionary, it should be keyed by field index.
320 the values should be a instances of maskededit.Field.
321
322 Any field not represented by the list or dictionary will be
323 implicitly created by the control.
324
325 eg:
326 fields = [ Field(formatcodes='_r'), Field('choices=['a', 'b', 'c']) ]
327 or
328 fields = {
329 1: ( Field(formatcodes='_R', choices=['a', 'b', 'c']),
330 3: ( Field(choices=['01', '02', '03'], choiceRequired=True)
331 }
332
333 The following parameters are available for individual fields, with the
334 same semantics as for the whole control but applied to the field in question:
335
336 fillChar # if set for a field, it will override the control's fillChar for that field
337 groupChar # if set for a field, it will override the control's default
338 defaultValue # sets field-specific default value; overrides any default from control
339 compareNoCase # overrides control's settings
340 emptyInvalid # determines whether field is required to be filled at all times
341 validRequired # if set, requires field to contain valid value
342
343 If any of the above parameters are subsequently specified for the control as a
344 whole, that new value will be propagated to each field, unless the
345 retainFieldValidation control-level parameter is set.
346
347 formatcodes # Augments control's settings
348 excludeChars # ' ' '
349 includeChars # ' ' '
350 validRegex # ' ' '
351 validRange # ' ' '
352 choices # ' ' '
353 choiceRequired # ' ' '
354 validFunc # ' ' '
355
356
357
358 <b>Control Class Functions:
359 ========================
360 .GetPlainValue(value=None)</b>
361 Returns the value specified (or the control's text value
362 not specified) without the formatting text.
363 In the example above, might return phone no='3522640075',
364 whereas control.GetValue() would return '(352) 264-0075'
365 <b>.ClearValue()</b>
366 Returns the control's value to its default, and places the
367 cursor at the beginning of the control.
368 <b>.SetValue()</b>
369 Does "smart replacement" of passed value into the control, as does
370 the .Paste() method. As with other text entry controls, the
371 .SetValue() text replacement begins at left-edge of the control,
372 with missing mask characters inserted as appropriate.
373 .SetValue will also adjust integer, float or date mask entry values,
374 adding commas, auto-completing years, etc. as appropriate.
375 For "right-aligned" numeric controls, it will also now automatically
376 right-adjust any value whose length is less than the width of the
377 control before attempting to set the value.
378 If a value does not follow the format of the control's mask, or will
379 not fit into the control, a ValueError exception will be raised.
380 Eg:
381 mask = '(###) ###-####'
382 .SetValue('1234567890') => '(123) 456-7890'
383 .SetValue('(123)4567890') => '(123) 456-7890'
384 .SetValue('(123)456-7890') => '(123) 456-7890'
385 .SetValue('123/4567-890') => illegal paste; ValueError
386
387 mask = '#{6}.#{2}', formatcodes = '_,-',
388 .SetValue('111') => ' 111 . '
389 .SetValue(' %9.2f' % -111.12345 ) => ' -111.12'
390 .SetValue(' %9.2f' % 1234.00 ) => ' 1,234.00'
391 .SetValue(' %9.2f' % -1234567.12345 ) => insufficient room; ValueError
392
393 mask = '#{6}.#{2}', formatcodes = '_,-R' # will right-adjust value for right-aligned control
394 .SetValue('111') => padded value misalignment ValueError: " 111" will not fit
395 .SetValue('%.2f' % 111 ) => ' 111.00'
396 .SetValue('%.2f' % -111.12345 ) => ' -111.12'
397
398
399 <b>.IsValid(value=None)</b>
400 Returns True if the value specified (or the value of the control
401 if not specified) passes validation tests
402 <b>.IsEmpty(value=None)</b>
403 Returns True if the value specified (or the value of the control
404 if not specified) is equal to an "empty value," ie. all
405 editable characters == the fillChar for their respective fields.
406 <b>.IsDefault(value=None)</b>
407 Returns True if the value specified (or the value of the control
408 if not specified) is equal to the initial value of the control.
409
410 <b>.Refresh()</b>
411 Recolors the control as appropriate to its current settings.
412
413 <b>.SetCtrlParameters(**kwargs)</b>
414 This function allows you to set up and/or change the control parameters
415 after construction; it takes a list of key/value pairs as arguments,
416 where the keys can be any of the mask-specific parameters in the constructor.
417 Eg:
418 ctl = MaskedTextCtrl( self, -1 )
419 ctl.SetCtrlParameters( mask='###-####',
420 defaultValue='555-1212',
421 formatcodes='F')
422
423 <b>.GetCtrlParameter(parametername)</b>
424 This function allows you to retrieve the current value of a parameter
425 from the control.
426
427 <b><i>Note:</i></b> Each of the control parameters can also be set using its
428 own Set and Get function. These functions follow a regular form:
429 All of the parameter names start with lower case; for their
430 corresponding Set/Get function, the parameter name is capitalized.
431 Eg: ctl.SetMask('###-####')
432 ctl.SetDefaultValue('555-1212')
433 ctl.GetChoiceRequired()
434 ctl.GetFormatcodes()
435
436 <b>.SetFieldParameters(field_index, **kwargs)</b>
437 This function allows you to specify change individual field
438 parameters after construction. (Indices are 0-based.)
439
440 <b>.GetFieldParameter(field_index, parametername)</b>
441 Allows the retrieval of field parameters after construction
442
443
444 The control detects certain common constructions. In order to use the signed feature
445 (negative numbers and coloring), the mask has to be all numbers with optionally one
446 decimal point. Without a decimal (e.g. '######', the control will treat it as an integer
447 value. With a decimal (e.g. '###.##'), the control will act as a floating point control
448 (i.e. press decimal to 'tab' to the decimal position). Pressing decimal in the
449 integer control truncates the value.
450
451
452 Check your controls by calling each control's .IsValid() function and the
453 .IsEmpty() function to determine which controls have been a) filled in and
454 b) filled in properly.
455
456
457 Regular expression validations can be used flexibly and creatively.
458 Take a look at the demo; the zip-code validation succeeds as long as the
459 first five numerals are entered. the last four are optional, but if
460 any are entered, there must be 4 to be valid.
461
462 <B>wxMaskedCtrl Configuration
463 ==========================</B>
464 wxMaskedCtrl works by looking for a special <b><i>controlType</i></b>
465 parameter in the variable arguments of the control, to determine
466 what kind of instance to return.
467 controlType can be one of:
468
469 controlTypes.MASKEDTEXT
470 controlTypes.MASKEDCOMBO
471 controlTypes.IPADDR
472 controlTypes.TIME
473 controlTypes.NUMBER
474
475 These constants are also available individually, ie, you can
476 use either of the following:
477
478 from wxPython.wx.lib.maskedctrl import wxMaskedCtrl, controlTypes
479 from wxPython.wx.lib.maskedctrl import wxMaskedCtrl, MASKEDCOMBO, MASKEDTEXT, NUMBER
480
481 If not specified as a keyword argument, the default controlType is
482 controlTypes.TEXT.
483 """
484
485 """
486 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
487 DEVELOPER COMMENTS:
488
489 Naming Conventions
490 ------------------
491 All methods of the Mixin that are not meant to be exposed to the external
492 interface are prefaced with '_'. Those functions that are primarily
493 intended to be internal subroutines subsequently start with a lower-case
494 letter; those that are primarily intended to be used and/or overridden
495 by derived subclasses start with a capital letter.
496
497 The following methods must be used and/or defined when deriving a control
498 from wxMaskedEditMixin. NOTE: if deriving from a *masked edit* control
499 (eg. class IpAddrCtrl(MaskedTextCtrl) ), then this is NOT necessary,
500 as it's already been done for you in the base class.
501
502 ._SetInitialValue()
503 This function must be called after the associated base
504 control has been initialized in the subclass __init__
505 function. It sets the initial value of the control,
506 either to the value specified if non-empty, the
507 default value if specified, or the "template" for
508 the empty control as necessary. It will also set/reset
509 the font if necessary and apply formatting to the
510 control at this time.
511
512 ._GetSelection()
513 REQUIRED
514 Each class derived from wxMaskedEditMixin must define
515 the function for getting the start and end of the
516 current text selection. The reason for this is
517 that not all controls have the same function name for
518 doing this; eg. wxTextCtrl uses .GetSelection(),
519 whereas we had to write a .GetMark() function for
520 wxComboBox, because .GetSelection() for the control
521 gets the currently selected list item from the combo
522 box, and the control doesn't (yet) natively provide
523 a means of determining the text selection.
524 ._SetSelection()
525 REQUIRED
526 Similarly to _GetSelection, each class derived from
527 wxMaskedEditMixin must define the function for setting
528 the start and end of the current text selection.
529 (eg. .SetSelection() for MaskedTextCtrl, and .SetMark() for
530 MaskedComboBox.
531
532 ._GetInsertionPoint()
533 ._SetInsertionPoint()
534 REQUIRED
535 For consistency, and because the mixin shouldn't rely
536 on fixed names for any manipulations it does of any of
537 the base controls, we require each class derived from
538 wxMaskedEditMixin to define these functions as well.
539
540 ._GetValue()
541 ._SetValue() REQUIRED
542 Each class derived from wxMaskedEditMixin must define
543 the functions used to get and set the raw value of the
544 control.
545 This is necessary so that recursion doesn't take place
546 when setting the value, and so that the mixin can
547 call the appropriate function after doing all its
548 validation and manipulation without knowing what kind
549 of base control it was mixed in with. To handle undo
550 functionality, the ._SetValue() must record the current
551 selection prior to setting the value.
552
553 .Cut()
554 .Paste()
555 .Undo()
556 .SetValue() REQUIRED
557 Each class derived from wxMaskedEditMixin must redefine
558 these functions to call the _Cut(), _Paste(), _Undo()
559 and _SetValue() methods, respectively for the control,
560 so as to prevent programmatic corruption of the control's
561 value. This must be done in each derivation, as the
562 mixin cannot itself override a member of a sibling class.
563
564 ._Refresh() REQUIRED
565 Each class derived from wxMaskedEditMixin must define
566 the function used to refresh the base control.
567
568 .Refresh() REQUIRED
569 Each class derived from wxMaskedEditMixin must redefine
570 this function so that it checks the validity of the
571 control (via self._CheckValid) and then refreshes
572 control using the base class method.
573
574 ._IsEditable() REQUIRED
575 Each class derived from wxMaskedEditMixin must define
576 the function used to determine if the base control is
577 editable or not. (For MaskedComboBox, this has to
578 be done with code, rather than specifying the proper
579 function in the base control, as there isn't one...)
580 ._CalcSize() REQUIRED
581 Each class derived from wxMaskedEditMixin must define
582 the function used to determine how wide the control
583 should be given the mask. (The mixin function
584 ._calcSize() provides a baseline estimate.)
585
586
587 Event Handling
588 --------------
589 Event handlers are "chained", and wxMaskedEditMixin usually
590 swallows most of the events it sees, thereby preventing any other
591 handlers from firing in the chain. It is therefore required that
592 each class derivation using the mixin to have an option to hook up
593 the event handlers itself or forego this operation and let a
594 subclass of the masked control do so. For this reason, each
595 subclass should probably include the following code:
596
597 if setupEventHandling:
598 ## Setup event handlers
599 EVT_SET_FOCUS( self, self._OnFocus ) ## defeat automatic full selection
600 EVT_KILL_FOCUS( self, self._OnKillFocus ) ## run internal validator
601 EVT_LEFT_DCLICK(self, self._OnDoubleClick) ## select field under cursor on dclick
602 EVT_RIGHT_UP(self, self._OnContextMenu ) ## bring up an appropriate context menu
603 EVT_KEY_DOWN( self, self._OnKeyDown ) ## capture control events not normally seen, eg ctrl-tab.
604 EVT_CHAR( self, self._OnChar ) ## handle each keypress
605 EVT_TEXT( self, self.GetId(), self._OnTextChange ) ## color control appropriately & keep
606 ## track of previous value for undo
607
608 where setupEventHandling is an argument to its constructor.
609
610 These 5 handlers must be "wired up" for the wxMaskedEdit
611 control to provide default behavior. (The setupEventHandling
612 is an argument to MaskedTextCtrl and MaskedComboBox, so
613 that controls derived from *them* may replace one of these
614 handlers if they so choose.)
615
616 If your derived control wants to preprocess events before
617 taking action, it should then set up the event handling itself,
618 so it can be first in the event handler chain.
619
620
621 The following routines are available to facilitate changing
622 the default behavior of wxMaskedEdit controls:
623
624 ._SetKeycodeHandler(keycode, func)
625 ._SetKeyHandler(char, func)
626 Use to replace default handling for any given keycode.
627 func should take the key event as argument and return
628 False if no further action is required to handle the
629 key. Eg:
630 self._SetKeycodeHandler(WXK_UP, self.IncrementValue)
631 self._SetKeyHandler('-', self._OnChangeSign)
632
633 "Navigation" keys are assumed to change the cursor position, and
634 therefore don't cause automatic motion of the cursor as insertable
635 characters do.
636
637 ._AddNavKeycode(keycode, handler=None)
638 ._AddNavKey(char, handler=None)
639 Allows controls to specify other keys (and optional handlers)
640 to be treated as navigational characters. (eg. '.' in IpAddrCtrl)
641
642 ._GetNavKeycodes() Returns the current list of navigational keycodes.
643
644 ._SetNavKeycodes(key_func_tuples)
645 Allows replacement of the current list of keycode
646 processed as navigation keys, and bind associated
647 optional keyhandlers. argument is a list of key/handler
648 tuples. Passing a value of None for the handler in a
649 given tuple indicates that default processing for the key
650 is desired.
651
652 ._FindField(pos) Returns the Field object associated with this position
653 in the control.
654
655 ._FindFieldExtent(pos, getslice=False, value=None)
656 Returns edit_start, edit_end of the field corresponding
657 to the specified position within the control, and
658 optionally also returns the current contents of that field.
659 If value is specified, it will retrieve the slice the corresponding
660 slice from that value, rather than the current value of the
661 control.
662
663 ._AdjustField(pos)
664 This is, the function that gets called for a given position
665 whenever the cursor is adjusted to leave a given field.
666 By default, it adjusts the year in date fields if mask is a date,
667 It can be overridden by a derived class to
668 adjust the value of the control at that time.
669 (eg. IpAddrCtrl reformats the address in this way.)
670
671 ._Change() Called by internal EVT_TEXT handler. Return False to force
672 skip of the normal class change event.
673 ._Keypress(key) Called by internal EVT_CHAR handler. Return False to force
674 skip of the normal class keypress event.
675 ._LostFocus() Called by internal EVT_KILL_FOCUS handler
676
677 ._OnKeyDown(event)
678 This is the default EVT_KEY_DOWN routine; it just checks for
679 "navigation keys", and if event.ControlDown(), it fires the
680 mixin's _OnChar() routine, as such events are not always seen
681 by the "cooked" EVT_CHAR routine.
682
683 ._OnChar(event) This is the main EVT_CHAR handler for the
684 wxMaskedEditMixin.
685
686 The following routines are used to handle standard actions
687 for control keys:
688 _OnArrow(event) used for arrow navigation events
689 _OnCtrl_A(event) 'select all'
690 _OnCtrl_C(event) 'copy' (uses base control function, as copy is non-destructive)
691 _OnCtrl_S(event) 'save' (does nothing)
692 _OnCtrl_V(event) 'paste' - calls _Paste() method, to do smart paste
693 _OnCtrl_X(event) 'cut' - calls _Cut() method, to "erase" selection
694 _OnCtrl_Z(event) 'undo' - resets value to previous value (if any)
695
696 _OnChangeField(event) primarily used for tab events, but can be
697 used for other keys (eg. '.' in IpAddrCtrl)
698
699 _OnErase(event) used for backspace and delete
700 _OnHome(event)
701 _OnEnd(event)
702
703 """
704
705 import copy
706 import difflib
707 import re
708 import string
709 import types
710
711 import wx
712
713 # jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would
714 # be a good place to implement the 2.3 logger class
715 from wx.tools.dbg import Logger
716
717 dbg = Logger()
718 dbg(enable=0)
719
720 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
721
722 ## Constants for identifying control keys and classes of keys:
723
724 WXK_CTRL_A = (ord('A')+1) - ord('A') ## These keys are not already defined in wx
725 WXK_CTRL_C = (ord('C')+1) - ord('A')
726 WXK_CTRL_S = (ord('S')+1) - ord('A')
727 WXK_CTRL_V = (ord('V')+1) - ord('A')
728 WXK_CTRL_X = (ord('X')+1) - ord('A')
729 WXK_CTRL_Z = (ord('Z')+1) - ord('A')
730
731 nav = (
732 wx.WXK_BACK, wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_UP, wx.WXK_DOWN, wx.WXK_TAB,
733 wx.WXK_HOME, wx.WXK_END, wx.WXK_RETURN, wx.WXK_PRIOR, wx.WXK_NEXT
734 )
735
736 control = (
737 wx.WXK_BACK, wx.WXK_DELETE, WXK_CTRL_A, WXK_CTRL_C, WXK_CTRL_S, WXK_CTRL_V,
738 WXK_CTRL_X, WXK_CTRL_Z
739 )
740
741
742 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
743
744 ## Constants for masking. This is where mask characters
745 ## are defined.
746 ## maskchars used to identify valid mask characters from all others
747 ## #- allow numeric 0-9 only
748 ## A- allow uppercase only. Combine with forceupper to force lowercase to upper
749 ## a- allow lowercase only. Combine with forcelower to force upper to lowercase
750 ## X- allow any character (string.letters, string.punctuation, string.digits)
751 ## Note: locale settings affect what "uppercase", lowercase, etc comprise.
752 ##
753 maskchars = ("#","A","a","X","C","N", '&')
754
755 months = '(01|02|03|04|05|06|07|08|09|10|11|12)'
756 charmonths = '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)'
757 charmonths_dict = {'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
758 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12}
759
760 days = '(01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)'
761 hours = '(0\d| \d|1[012])'
762 milhours = '(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23)'
763 minutes = """(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|\
764 16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|\
765 36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|\
766 56|57|58|59)"""
767 seconds = minutes
768 am_pm_exclude = 'BCDEFGHIJKLMNOQRSTUVWXYZ\x8a\x8c\x8e\x9f\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde'
769
770 states = "AL,AK,AZ,AR,CA,CO,CT,DE,DC,FL,GA,GU,HI,ID,IL,IN,IA,KS,KY,LA,MA,ME,MD,MI,MN,MS,MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,OH,OK,OR,PA,PR,RI,SC,SD,TN,TX,UT,VA,VT,VI,WA,WV,WI,WY".split(',')
771
772 state_names = ['Alabama','Alaska','Arizona','Arkansas',
773 'California','Colorado','Connecticut',
774 'Delaware','District of Columbia',
775 'Florida','Georgia','Hawaii',
776 'Idaho','Illinois','Indiana','Iowa',
777 'Kansas','Kentucky','Louisiana',
778 'Maine','Maryland','Massachusetts','Michigan',
779 'Minnesota','Mississippi','Missouri','Montana',
780 'Nebraska','Nevada','New Hampshire','New Jersey',
781 'New Mexico','New York','North Carolina','North Dakokta',
782 'Ohio','Oklahoma','Oregon',
783 'Pennsylvania','Puerto Rico','Rhode Island',
784 'South Carolina','South Dakota',
785 'Tennessee','Texas','Utah',
786 'Vermont','Virginia',
787 'Washington','West Virginia',
788 'Wisconsin','Wyoming']
789
790 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
791
792 ## The following dictionary defines the current set of autoformats:
793
794 masktags = {
795 "USPHONEFULLEXT": {
796 'mask': "(###) ###-#### x:###",
797 'formatcodes': 'F^->',
798 'validRegex': "^\(\d{3}\) \d{3}-\d{4}",
799 'description': "Phone Number w/opt. ext"
800 },
801 "USPHONETIGHTEXT": {
802 'mask': "###-###-#### x:###",
803 'formatcodes': 'F^->',
804 'validRegex': "^\d{3}-\d{3}-\d{4}",
805 'description': "Phone Number\n (w/hyphens and opt. ext)"
806 },
807 "USPHONEFULL": {
808 'mask': "(###) ###-####",
809 'formatcodes': 'F^->',
810 'validRegex': "^\(\d{3}\) \d{3}-\d{4}",
811 'description': "Phone Number only"
812 },
813 "USPHONETIGHT": {
814 'mask': "###-###-####",
815 'formatcodes': 'F^->',
816 'validRegex': "^\d{3}-\d{3}-\d{4}",
817 'description': "Phone Number\n(w/hyphens)"
818 },
819 "USSTATE": {
820 'mask': "AA",
821 'formatcodes': 'F!V',
822 'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string.join(states,'|'),
823 'choices': states,
824 'choiceRequired': True,
825 'description': "US State Code"
826 },
827 "USSTATENAME": {
828 'mask': "ACCCCCCCCCCCCCCCCCCC",
829 'formatcodes': 'F_',
830 'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string.join(state_names,'|'),
831 'choices': state_names,
832 'choiceRequired': True,
833 'description': "US State Name"
834 },
835
836 "USDATETIMEMMDDYYYY/HHMMSS": {
837 'mask': "##/##/#### ##:##:## AM",
838 'excludeChars': am_pm_exclude,
839 'formatcodes': 'DF!',
840 'validRegex': '^' + months + '/' + days + '/' + '\d{4} ' + hours + ':' + minutes + ':' + seconds + ' (A|P)M',
841 'description': "US Date + Time"
842 },
843 "USDATETIMEMMDDYYYY-HHMMSS": {
844 'mask': "##-##-#### ##:##:## AM",
845 'excludeChars': am_pm_exclude,
846 'formatcodes': 'DF!',
847 'validRegex': '^' + months + '-' + days + '-' + '\d{4} ' + hours + ':' + minutes + ':' + seconds + ' (A|P)M',
848 'description': "US Date + Time\n(w/hypens)"
849 },
850 "USDATEMILTIMEMMDDYYYY/HHMMSS": {
851 'mask': "##/##/#### ##:##:##",
852 'formatcodes': 'DF',
853 'validRegex': '^' + months + '/' + days + '/' + '\d{4} ' + milhours + ':' + minutes + ':' + seconds,
854 'description': "US Date + Military Time"
855 },
856 "USDATEMILTIMEMMDDYYYY-HHMMSS": {
857 'mask': "##-##-#### ##:##:##",
858 'formatcodes': 'DF',
859 'validRegex': '^' + months + '-' + days + '-' + '\d{4} ' + milhours + ':' + minutes + ':' + seconds,
860 'description': "US Date + Military Time\n(w/hypens)"
861 },
862 "USDATETIMEMMDDYYYY/HHMM": {
863 'mask': "##/##/#### ##:## AM",
864 'excludeChars': am_pm_exclude,
865 'formatcodes': 'DF!',
866 'validRegex': '^' + months + '/' + days + '/' + '\d{4} ' + hours + ':' + minutes + ' (A|P)M',
867 'description': "US Date + Time\n(without seconds)"
868 },
869 "USDATEMILTIMEMMDDYYYY/HHMM": {
870 'mask': "##/##/#### ##:##",
871 'formatcodes': 'DF',
872 'validRegex': '^' + months + '/' + days + '/' + '\d{4} ' + milhours + ':' + minutes,
873 'description': "US Date + Military Time\n(without seconds)"
874 },
875 "USDATETIMEMMDDYYYY-HHMM": {
876 'mask': "##-##-#### ##:## AM",
877 'excludeChars': am_pm_exclude,
878 'formatcodes': 'DF!',
879 'validRegex': '^' + months + '-' + days + '-' + '\d{4} ' + hours + ':' + minutes + ' (A|P)M',
880 'description': "US Date + Time\n(w/hypens and w/o secs)"
881 },
882 "USDATEMILTIMEMMDDYYYY-HHMM": {
883 'mask': "##-##-#### ##:##",
884 'formatcodes': 'DF',
885 'validRegex': '^' + months + '-' + days + '-' + '\d{4} ' + milhours + ':' + minutes,
886 'description': "US Date + Military Time\n(w/hyphens and w/o seconds)"
887 },
888 "USDATEMMDDYYYY/": {
889 'mask': "##/##/####",
890 'formatcodes': 'DF',
891 'validRegex': '^' + months + '/' + days + '/' + '\d{4}',
892 'description': "US Date\n(MMDDYYYY)"
893 },
894 "USDATEMMDDYY/": {
895 'mask': "##/##/##",
896 'formatcodes': 'DF',
897 'validRegex': '^' + months + '/' + days + '/\d\d',
898 'description': "US Date\n(MMDDYY)"
899 },
900 "USDATEMMDDYYYY-": {
901 'mask': "##-##-####",
902 'formatcodes': 'DF',
903 'validRegex': '^' + months + '-' + days + '-' +'\d{4}',
904 'description': "MM-DD-YYYY"
905 },
906
907 "EUDATEYYYYMMDD/": {
908 'mask': "####/##/##",
909 'formatcodes': 'DF',
910 'validRegex': '^' + '\d{4}'+ '/' + months + '/' + days,
911 'description': "YYYY/MM/DD"
912 },
913 "EUDATEYYYYMMDD.": {
914 'mask': "####.##.##",
915 'formatcodes': 'DF',
916 'validRegex': '^' + '\d{4}'+ '.' + months + '.' + days,
917 'description': "YYYY.MM.DD"
918 },
919 "EUDATEDDMMYYYY/": {
920 'mask': "##/##/####",
921 'formatcodes': 'DF',
922 'validRegex': '^' + days + '/' + months + '/' + '\d{4}',
923 'description': "DD/MM/YYYY"
924 },
925 "EUDATEDDMMYYYY.": {
926 'mask': "##.##.####",
927 'formatcodes': 'DF',
928 'validRegex': '^' + days + '.' + months + '.' + '\d{4}',
929 'description': "DD.MM.YYYY"
930 },
931 "EUDATEDDMMMYYYY.": {
932 'mask': "##.CCC.####",
933 'formatcodes': 'DF',
934 'validRegex': '^' + days + '.' + charmonths + '.' + '\d{4}',
935 'description': "DD.Month.YYYY"
936 },
937 "EUDATEDDMMMYYYY/": {
938 'mask': "##/CCC/####",
939 'formatcodes': 'DF',
940 'validRegex': '^' + days + '/' + charmonths + '/' + '\d{4}',
941 'description': "DD/Month/YYYY"
942 },
943
944 "EUDATETIMEYYYYMMDD/HHMMSS": {
945 'mask': "####/##/## ##:##:## AM",
946 'excludeChars': am_pm_exclude,
947 'formatcodes': 'DF!',
948 'validRegex': '^' + '\d{4}'+ '/' + months + '/' + days + ' ' + hours + ':' + minutes + ':' + seconds + ' (A|P)M',
949 'description': "YYYY/MM/DD HH:MM:SS"
950 },
951 "EUDATETIMEYYYYMMDD.HHMMSS": {
952 'mask': "####.##.## ##:##:## AM",
953 'excludeChars': am_pm_exclude,
954 'formatcodes': 'DF!',
955 'validRegex': '^' + '\d{4}'+ '.' + months + '.' + days + ' ' + hours + ':' + minutes + ':' + seconds + ' (A|P)M',
956 'description': "YYYY.MM.DD HH:MM:SS"
957 },
958 "EUDATETIMEDDMMYYYY/HHMMSS": {
959 'mask': "##/##/#### ##:##:## AM",
960 'excludeChars': am_pm_exclude,
961 'formatcodes': 'DF!',
962 'validRegex': '^' + days + '/' + months + '/' + '\d{4} ' + hours + ':' + minutes + ':' + seconds + ' (A|P)M',
963 'description': "DD/MM/YYYY HH:MM:SS"
964 },
965 "EUDATETIMEDDMMYYYY.HHMMSS": {
966 'mask': "##.##.#### ##:##:## AM",
967 'excludeChars': am_pm_exclude,
968 'formatcodes': 'DF!',
969 'validRegex': '^' + days + '.' + months + '.' + '\d{4} ' + hours + ':' + minutes + ':' + seconds + ' (A|P)M',
970 'description': "DD.MM.YYYY HH:MM:SS"
971 },
972
973 "EUDATETIMEYYYYMMDD/HHMM": {
974 'mask': "####/##/## ##:## AM",
975 'excludeChars': am_pm_exclude,
976 'formatcodes': 'DF!',
977 'validRegex': '^' + '\d{4}'+ '/' + months + '/' + days + ' ' + hours + ':' + minutes + ' (A|P)M',
978 'description': "YYYY/MM/DD HH:MM"
979 },
980 "EUDATETIMEYYYYMMDD.HHMM": {
981 'mask': "####.##.## ##:## AM",
982 'excludeChars': am_pm_exclude,
983 'formatcodes': 'DF!',
984 'validRegex': '^' + '\d{4}'+ '.' + months + '.' + days + ' ' + hours + ':' + minutes + ' (A|P)M',
985 'description': "YYYY.MM.DD HH:MM"
986 },
987 "EUDATETIMEDDMMYYYY/HHMM": {
988 'mask': "##/##/#### ##:## AM",
989 'excludeChars': am_pm_exclude,
990 'formatcodes': 'DF!',
991 'validRegex': '^' + days + '/' + months + '/' + '\d{4} ' + hours + ':' + minutes + ' (A|P)M',
992 'description': "DD/MM/YYYY HH:MM"
993 },
994 "EUDATETIMEDDMMYYYY.HHMM": {
995 'mask': "##.##.#### ##:## AM",
996 'excludeChars': am_pm_exclude,
997 'formatcodes': 'DF!',
998 'validRegex': '^' + days + '.' + months + '.' + '\d{4} ' + hours + ':' + minutes + ' (A|P)M',
999 'description': "DD.MM.YYYY HH:MM"
1000 },
1001
1002 "EUDATEMILTIMEYYYYMMDD/HHMMSS": {
1003 'mask': "####/##/## ##:##:##",
1004 'formatcodes': 'DF',
1005 'validRegex': '^' + '\d{4}'+ '/' + months + '/' + days + ' ' + milhours + ':' + minutes + ':' + seconds,
1006 'description': "YYYY/MM/DD Mil. Time"
1007 },
1008 "EUDATEMILTIMEYYYYMMDD.HHMMSS": {
1009 'mask': "####.##.## ##:##:##",
1010 'formatcodes': 'DF',
1011 'validRegex': '^' + '\d{4}'+ '.' + months + '.' + days + ' ' + milhours + ':' + minutes + ':' + seconds,
1012 'description': "YYYY.MM.DD Mil. Time"
1013 },
1014 "EUDATEMILTIMEDDMMYYYY/HHMMSS": {
1015 'mask': "##/##/#### ##:##:##",
1016 'formatcodes': 'DF',
1017 'validRegex': '^' + days + '/' + months + '/' + '\d{4} ' + milhours + ':' + minutes + ':' + seconds,
1018 'description': "DD/MM/YYYY Mil. Time"
1019 },
1020 "EUDATEMILTIMEDDMMYYYY.HHMMSS": {
1021 'mask': "##.##.#### ##:##:##",
1022 'formatcodes': 'DF',
1023 'validRegex': '^' + days + '.' + months + '.' + '\d{4} ' + milhours + ':' + minutes + ':' + seconds,
1024 'description': "DD.MM.YYYY Mil. Time"
1025 },
1026 "EUDATEMILTIMEYYYYMMDD/HHMM": {
1027 'mask': "####/##/## ##:##",
1028 'formatcodes': 'DF','validRegex': '^' + '\d{4}'+ '/' + months + '/' + days + ' ' + milhours + ':' + minutes,
1029 'description': "YYYY/MM/DD Mil. Time\n(w/o seconds)"
1030 },
1031 "EUDATEMILTIMEYYYYMMDD.HHMM": {
1032 'mask': "####.##.## ##:##",
1033 'formatcodes': 'DF',
1034 'validRegex': '^' + '\d{4}'+ '.' + months + '.' + days + ' ' + milhours + ':' + minutes,
1035 'description': "YYYY.MM.DD Mil. Time\n(w/o seconds)"
1036 },
1037 "EUDATEMILTIMEDDMMYYYY/HHMM": {
1038 'mask': "##/##/#### ##:##",
1039 'formatcodes': 'DF',
1040 'validRegex': '^' + days + '/' + months + '/' + '\d{4} ' + milhours + ':' + minutes,
1041 'description': "DD/MM/YYYY Mil. Time\n(w/o seconds)"
1042 },
1043 "EUDATEMILTIMEDDMMYYYY.HHMM": {
1044 'mask': "##.##.#### ##:##",
1045 'formatcodes': 'DF',
1046 'validRegex': '^' + days + '.' + months + '.' + '\d{4} ' + milhours + ':' + minutes,
1047 'description': "DD.MM.YYYY Mil. Time\n(w/o seconds)"
1048 },
1049
1050 "TIMEHHMMSS": {
1051 'mask': "##:##:## AM",
1052 'excludeChars': am_pm_exclude,
1053 'formatcodes': 'TF!',
1054 'validRegex': '^' + hours + ':' + minutes + ':' + seconds + ' (A|P)M',
1055 'description': "HH:MM:SS (A|P)M\n(see TimeCtrl)"
1056 },
1057 "TIMEHHMM": {
1058 'mask': "##:## AM",
1059 'excludeChars': am_pm_exclude,
1060 'formatcodes': 'TF!',
1061 'validRegex': '^' + hours + ':' + minutes + ' (A|P)M',
1062 'description': "HH:MM (A|P)M\n(see TimeCtrl)"
1063 },
1064 "MILTIMEHHMMSS": {
1065 'mask': "##:##:##",
1066 'formatcodes': 'TF',
1067 'validRegex': '^' + milhours + ':' + minutes + ':' + seconds,
1068 'description': "Military HH:MM:SS\n(see TimeCtrl)"
1069 },
1070 "MILTIMEHHMM": {
1071 'mask': "##:##",
1072 'formatcodes': 'TF',
1073 'validRegex': '^' + milhours + ':' + minutes,
1074 'description': "Military HH:MM\n(see TimeCtrl)"
1075 },
1076 "USSOCIALSEC": {
1077 'mask': "###-##-####",
1078 'formatcodes': 'F',
1079 'validRegex': "\d{3}-\d{2}-\d{4}",
1080 'description': "Social Sec#"
1081 },
1082 "CREDITCARD": {
1083 'mask': "####-####-####-####",
1084 'formatcodes': 'F',
1085 'validRegex': "\d{4}-\d{4}-\d{4}-\d{4}",
1086 'description': "Credit Card"
1087 },
1088 "EXPDATEMMYY": {
1089 'mask': "##/##",
1090 'formatcodes': "F",
1091 'validRegex': "^" + months + "/\d\d",
1092 'description': "Expiration MM/YY"
1093 },
1094 "USZIP": {
1095 'mask': "#####",
1096 'formatcodes': 'F',
1097 'validRegex': "^\d{5}",
1098 'description': "US 5-digit zip code"
1099 },
1100 "USZIPPLUS4": {
1101 'mask': "#####-####",
1102 'formatcodes': 'F',
1103 'validRegex': "\d{5}-(\s{4}|\d{4})",
1104 'description': "US zip+4 code"
1105 },
1106 "PERCENT": {
1107 'mask': "0.##",
1108 'formatcodes': 'F',
1109 'validRegex': "^0.\d\d",
1110 'description': "Percentage"
1111 },
1112 "AGE": {
1113 'mask': "###",
1114 'formatcodes': "F",
1115 'validRegex': "^[1-9]{1} |[1-9][0-9] |1[0|1|2][0-9]",
1116 'description': "Age"
1117 },
1118 "EMAIL": {
1119 'mask': "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
1120 'excludeChars': " \\/*&%$#!+='\"",
1121 'formatcodes': "F>",
1122 'validRegex': "^\w+([\-\.]\w+)*@((([a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*\.)+)[a-zA-Z]{2,4}|\[(\d|\d\d|(1\d\d|2[0-4]\d|25[0-5]))(\.(\d|\d\d|(1\d\d|2[0-4]\d|25[0-5]))){3}\]) *$",
1123 'description': "Email address"
1124 },
1125 "IPADDR": {
1126 'mask': "###.###.###.###",
1127 'formatcodes': 'F_Sr',
1128 'validRegex': "( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))(\.( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))){3}",
1129 'description': "IP Address\n(see IpAddrCtrl)"
1130 }
1131 }
1132
1133 # build demo-friendly dictionary of descriptions of autoformats
1134 autoformats = []
1135 for key, value in masktags.items():
1136 autoformats.append((key, value['description']))
1137 autoformats.sort()
1138
1139 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
1140
1141 class Field:
1142 valid_params = {
1143 'index': None, ## which field of mask; set by parent control.
1144 'mask': "", ## mask chars for this field
1145 'extent': (), ## (edit start, edit_end) of field; set by parent control.
1146 'formatcodes': "", ## codes indicating formatting options for the control
1147 'fillChar': ' ', ## used as initial value for each mask position if initial value is not given
1148 'groupChar': ',', ## used with numeric fields; indicates what char groups 3-tuple digits
1149 'decimalChar': '.', ## used with numeric fields; indicates what char separates integer from fraction
1150 'shiftDecimalChar': '>', ## used with numeric fields, indicates what is above the decimal point char on keyboard
1151 'useParensForNegatives': False, ## used with numeric fields, indicates that () should be used vs. - to show negative numbers.
1152 'defaultValue': "", ## use if you want different positional defaults vs. all the same fillChar
1153 'excludeChars': "", ## optional string of chars to exclude even if main mask type does
1154 'includeChars': "", ## optional string of chars to allow even if main mask type doesn't
1155 'validRegex': "", ## optional regular expression to use to validate the control
1156 'validRange': (), ## Optional hi-low range for numerics
1157 'choices': [], ## Optional list for character expressions
1158 'choiceRequired': False, ## If choices supplied this specifies if valid value must be in the list
1159 'compareNoCase': False, ## Optional flag to indicate whether or not to use case-insensitive list search
1160 'autoSelect': False, ## Set to True to try auto-completion on each keystroke:
1161 'validFunc': None, ## Optional function for defining additional, possibly dynamic validation constraints on contrl
1162 'validRequired': False, ## Set to True to disallow input that results in an invalid value
1163 'emptyInvalid': False, ## Set to True to make EMPTY = INVALID
1164 'description': "", ## primarily for autoformats, but could be useful elsewhere
1165 }
1166
1167 # This list contains all parameters that when set at the control level should
1168 # propagate down to each field:
1169 propagating_params = ('fillChar', 'groupChar', 'decimalChar','useParensForNegatives',
1170 'compareNoCase', 'emptyInvalid', 'validRequired')
1171
1172 def __init__(self, **kwargs):
1173 """
1174 This is the "constructor" for setting up parameters for fields.
1175 a field_index of -1 is used to indicate "the entire control."
1176 """
1177 ## dbg('Field::Field', indent=1)
1178 # Validate legitimate set of parameters:
1179 for key in kwargs.keys():
1180 if key not in Field.valid_params.keys():
1181 ## dbg(indent=0)
1182 raise TypeError('invalid parameter "%s"' % (key))
1183
1184 # Set defaults for each parameter for this instance, and fully
1185 # populate initial parameter list for configuration:
1186 for key, value in Field.valid_params.items():
1187 setattr(self, '_' + key, copy.copy(value))
1188 if not kwargs.has_key(key):
1189 kwargs[key] = copy.copy(value)
1190
1191 self._autoCompleteIndex = -1
1192 self._SetParameters(**kwargs)
1193 self._ValidateParameters(**kwargs)
1194
1195 ## dbg(indent=0)
1196
1197
1198 def _SetParameters(self, **kwargs):
1199 """
1200 This function can be used to set individual or multiple parameters for
1201 a masked edit field parameter after construction.
1202 """
1203 dbg(suspend=1)
1204 dbg('maskededit.Field::_SetParameters', indent=1)
1205 # Validate keyword arguments:
1206 for key in kwargs.keys():
1207 if key not in Field.valid_params.keys():
1208 dbg(indent=0, suspend=0)
1209 raise AttributeError('invalid keyword argument "%s"' % key)
1210
1211 if self._index is not None: dbg('field index:', self._index)
1212 dbg('parameters:', indent=1)
1213 for key, value in kwargs.items():
1214 dbg('%s:' % key, value)
1215 dbg(indent=0)
1216
1217 old_fillChar = self._fillChar # store so we can change choice lists accordingly if it changes
1218
1219 # First, Assign all parameters specified:
1220 for key in Field.valid_params.keys():
1221 if kwargs.has_key(key):
1222 setattr(self, '_' + key, kwargs[key] )
1223
1224 if kwargs.has_key('formatcodes'): # (set/changed)
1225 self._forceupper = '!' in self._formatcodes
1226 self._forcelower = '^' in self._formatcodes
1227 self._groupdigits = ',' in self._formatcodes
1228 self._okSpaces = '_' in self._formatcodes
1229 self._padZero = '0' in self._formatcodes
1230 self._autofit = 'F' in self._formatcodes
1231 self._insertRight = 'r' in self._formatcodes
1232 self._allowInsert = '>' in self._formatcodes
1233 self._alignRight = 'R' in self._formatcodes or 'r' in self._formatcodes
1234 self._moveOnFieldFull = not '<' in self._formatcodes
1235 self._selectOnFieldEntry = 'S' in self._formatcodes
1236
1237 if kwargs.has_key('groupChar'):
1238 self._groupChar = kwargs['groupChar']
1239 if kwargs.has_key('decimalChar'):
1240 self._decimalChar = kwargs['decimalChar']
1241 if kwargs.has_key('shiftDecimalChar'):
1242 self._shiftDecimalChar = kwargs['shiftDecimalChar']
1243
1244 if kwargs.has_key('formatcodes') or kwargs.has_key('validRegex'):
1245 self._regexMask = 'V' in self._formatcodes and self._validRegex
1246
1247 if kwargs.has_key('fillChar'):
1248 self._old_fillChar = old_fillChar
1249 ## dbg("self._old_fillChar: '%s'" % self._old_fillChar)
1250
1251 if kwargs.has_key('mask') or kwargs.has_key('validRegex'): # (set/changed)
1252 self._isInt = isInteger(self._mask)
1253 dbg('isInt?', self._isInt, 'self._mask:"%s"' % self._mask)
1254
1255 dbg(indent=0, suspend=0)
1256
1257
1258 def _ValidateParameters(self, **kwargs):
1259 """
1260 This function can be used to validate individual or multiple parameters for
1261 a masked edit field parameter after construction.
1262 """
1263 dbg(suspend=1)
1264 dbg('maskededit.Field::_ValidateParameters', indent=1)
1265 if self._index is not None: dbg('field index:', self._index)
1266 ## dbg('parameters:', indent=1)
1267 ## for key, value in kwargs.items():
1268 ## dbg('%s:' % key, value)
1269 ## dbg(indent=0)
1270 ## dbg("self._old_fillChar: '%s'" % self._old_fillChar)
1271
1272 # Verify proper numeric format params:
1273 if self._groupdigits and self._groupChar == self._decimalChar:
1274 dbg(indent=0, suspend=0)
1275 raise AttributeError("groupChar '%s' cannot be the same as decimalChar '%s'" % (self._groupChar, self._decimalChar))
1276
1277
1278 # Now go do validation, semantic and inter-dependency parameter processing:
1279 if kwargs.has_key('choices') or kwargs.has_key('compareNoCase') or kwargs.has_key('choiceRequired'): # (set/changed)
1280
1281 self._compareChoices = [choice.strip() for choice in self._choices]
1282
1283 if self._compareNoCase and self._choices:
1284 self._compareChoices = [item.lower() for item in self._compareChoices]
1285
1286 if kwargs.has_key('choices'):
1287 self._autoCompleteIndex = -1
1288
1289
1290 if kwargs.has_key('validRegex'): # (set/changed)
1291 if self._validRegex:
1292 try:
1293 if self._compareNoCase:
1294 self._filter = re.compile(self._validRegex, re.IGNORECASE)
1295 else:
1296 self._filter = re.compile(self._validRegex)
1297 except:
1298 dbg(indent=0, suspend=0)
1299 raise TypeError('%s: validRegex "%s" not a legal regular expression' % (str(self._index), self._validRegex))
1300 else:
1301 self._filter = None
1302
1303 if kwargs.has_key('validRange'): # (set/changed)
1304 self._hasRange = False
1305 self._rangeHigh = 0
1306 self._rangeLow = 0
1307 if self._validRange:
1308 if type(self._validRange) != types.TupleType or len( self._validRange )!= 2 or self._validRange[0] > self._validRange[1]:
1309 dbg(indent=0, suspend=0)
1310 raise TypeError('%s: validRange %s parameter must be tuple of form (a,b) where a <= b'
1311 % (str(self._index), repr(self._validRange)) )
1312
1313 self._hasRange = True
1314 self._rangeLow = self._validRange[0]
1315 self._rangeHigh = self._validRange[1]
1316
1317 if kwargs.has_key('choices') or (len(self._choices) and len(self._choices[0]) != len(self._mask)): # (set/changed)
1318 self._hasList = False
1319 if self._choices and type(self._choices) not in (types.TupleType, types.ListType):
1320 dbg(indent=0, suspend=0)
1321 raise TypeError('%s: choices must be a sequence of strings' % str(self._index))
1322 elif len( self._choices) > 0:
1323 for choice in self._choices:
1324 if type(choice) not in (types.StringType, types.UnicodeType):
1325 dbg(indent=0, suspend=0)
1326 raise TypeError('%s: choices must be a sequence of strings' % str(self._index))
1327
1328 length = len(self._mask)
1329 dbg('len(%s)' % self._mask, length, 'len(self._choices):', len(self._choices), 'length:', length, 'self._alignRight?', self._alignRight)
1330 if len(self._choices) and length:
1331 if len(self._choices[0]) > length:
1332 # changed mask without respecifying choices; readjust the width as appropriate:
1333 self._choices = [choice.strip() for choice in self._choices]
1334 if self._alignRight:
1335 self._choices = [choice.rjust( length ) for choice in self._choices]
1336 else:
1337 self._choices = [choice.ljust( length ) for choice in self._choices]
1338 dbg('aligned choices:', self._choices)
1339
1340 if hasattr(self, '_template'):
1341 # Verify each choice specified is valid:
1342 for choice in self._choices:
1343 if self.IsEmpty(choice) and not self._validRequired:
1344 # allow empty values even if invalid, (just colored differently)
1345 continue
1346 if not self.IsValid(choice):
1347 dbg(indent=0, suspend=0)
1348 raise ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self._index), choice))
1349 self._hasList = True
1350
1351 ## dbg("kwargs.has_key('fillChar')?", kwargs.has_key('fillChar'), "len(self._choices) > 0?", len(self._choices) > 0)
1352 ## dbg("self._old_fillChar:'%s'" % self._old_fillChar, "self._fillChar: '%s'" % self._fillChar)
1353 if kwargs.has_key('fillChar') and len(self._choices) > 0:
1354 if kwargs['fillChar'] != ' ':
1355 self._choices = [choice.replace(' ', self._fillChar) for choice in self._choices]
1356 else:
1357 self._choices = [choice.replace(self._old_fillChar, self._fillChar) for choice in self._choices]
1358 dbg('updated choices:', self._choices)
1359
1360
1361 if kwargs.has_key('autoSelect') and kwargs['autoSelect']:
1362 if not self._hasList:
1363 dbg('no list to auto complete; ignoring "autoSelect=True"')
1364 self._autoSelect = False
1365
1366 # reset field validity assumption:
1367 self._valid = True
1368 dbg(indent=0, suspend=0)
1369
1370
1371 def _GetParameter(self, paramname):
1372 """
1373 Routine for retrieving the value of any given parameter
1374 """
1375 if Field.valid_params.has_key(paramname):
1376 return getattr(self, '_' + paramname)
1377 else:
1378 TypeError('Field._GetParameter: invalid parameter "%s"' % key)
1379
1380
1381 def IsEmpty(self, slice):
1382 """
1383 Indicates whether the specified slice is considered empty for the
1384 field.
1385 """
1386 dbg('Field::IsEmpty("%s")' % slice, indent=1)
1387 if not hasattr(self, '_template'):
1388 dbg(indent=0)
1389 raise AttributeError('_template')
1390
1391 dbg('self._template: "%s"' % self._template)
1392 dbg('self._defaultValue: "%s"' % str(self._defaultValue))
1393 if slice == self._template and not self._defaultValue:
1394 dbg(indent=0)
1395 return True
1396
1397 elif slice == self._template:
1398 empty = True
1399 for pos in range(len(self._template)):
1400 ## dbg('slice[%(pos)d] != self._fillChar?' %locals(), slice[pos] != self._fillChar[pos])
1401 if slice[pos] not in (' ', self._fillChar):
1402 empty = False
1403 break
1404 dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals(), indent=0)
1405 return empty
1406 else:
1407 dbg("IsEmpty? 0 (slice doesn't match template)", indent=0)
1408 return False
1409
1410
1411 def IsValid(self, slice):
1412 """
1413 Indicates whether the specified slice is considered a valid value for the
1414 field.
1415 """
1416 dbg(suspend=1)
1417 dbg('Field[%s]::IsValid("%s")' % (str(self._index), slice), indent=1)
1418 valid = True # assume true to start
1419
1420 if self.IsEmpty(slice):
1421 dbg(indent=0, suspend=0)
1422 if self._emptyInvalid:
1423 return False
1424 else:
1425 return True
1426
1427 elif self._hasList and self._choiceRequired:
1428 dbg("(member of list required)")
1429 # do case-insensitive match on list; strip surrounding whitespace from slice (already done for choices):
1430 if self._fillChar != ' ':
1431 slice = slice.replace(self._fillChar, ' ')
1432 dbg('updated slice:"%s"' % slice)
1433 compareStr = slice.strip()
1434
1435 if self._compareNoCase:
1436 compareStr = compareStr.lower()
1437 valid = compareStr in self._compareChoices
1438
1439 elif self._hasRange and not self.IsEmpty(slice):
1440 dbg('validating against range')
1441 try:
1442 # allow float as well as int ranges (int comparisons for free.)
1443 valid = self._rangeLow <= float(slice) <= self._rangeHigh
1444 except:
1445 valid = False
1446
1447 elif self._validRegex and self._filter:
1448 dbg('validating against regex')
1449 valid = (re.match( self._filter, slice) is not None)
1450
1451 if valid and self._validFunc:
1452 dbg('validating against supplied function')
1453 valid = self._validFunc(slice)
1454 dbg('valid?', valid, indent=0, suspend=0)
1455 return valid
1456
1457
1458 def _AdjustField(self, slice):
1459 """ 'Fixes' an integer field. Right or left-justifies, as required."""
1460 dbg('Field::_AdjustField("%s")' % slice, indent=1)
1461 length = len(self._mask)
1462 ## dbg('length(self._mask):', length)
1463 ## dbg('self._useParensForNegatives?', self._useParensForNegatives)
1464 if self._isInt:
1465 if self._useParensForNegatives:
1466 signpos = slice.find('(')
1467 right_signpos = slice.find(')')
1468 intStr = slice.replace('(', '').replace(')', '') # drop sign, if any
1469 else:
1470 signpos = slice.find('-')
1471 intStr = slice.replace( '-', '' ) # drop sign, if any
1472 right_signpos = -1
1473
1474 intStr = intStr.replace(' ', '') # drop extra spaces
1475 intStr = string.replace(intStr,self._fillChar,"") # drop extra fillchars
1476 intStr = string.replace(intStr,"-","") # drop sign, if any
1477 intStr = string.replace(intStr, self._groupChar, "") # lose commas/dots
1478 ## dbg('intStr:"%s"' % intStr)
1479 start, end = self._extent
1480 field_len = end - start
1481 if not self._padZero and len(intStr) != field_len and intStr.strip():
1482 intStr = str(long(intStr))
1483 ## dbg('raw int str: "%s"' % intStr)
1484 ## dbg('self._groupdigits:', self._groupdigits, 'self._formatcodes:', self._formatcodes)
1485 if self._groupdigits:
1486 new = ''
1487 cnt = 1
1488 for i in range(len(intStr)-1, -1, -1):
1489 new = intStr[i] + new
1490 if (cnt) % 3 == 0:
1491 new = self._groupChar + new
1492 cnt += 1
1493 if new and new[0] == self._groupChar:
1494 new = new[1:]
1495 if len(new) <= length:
1496 # expanded string will still fit and leave room for sign:
1497 intStr = new
1498 # else... leave it without the commas...
1499
1500 dbg('padzero?', self._padZero)
1501 dbg('len(intStr):', len(intStr), 'field length:', length)
1502 if self._padZero and len(intStr) < length:
1503 intStr = '0' * (length - len(intStr)) + intStr
1504 if signpos != -1: # we had a sign before; restore it
1505 if self._useParensForNegatives:
1506 intStr = '(' + intStr[1:]
1507 if right_signpos != -1:
1508 intStr += ')'
1509 else:
1510 intStr = '-' + intStr[1:]
1511 elif signpos != -1 and slice[0:signpos].strip() == '': # - was before digits
1512 if self._useParensForNegatives:
1513 intStr = '(' + intStr
1514 if right_signpos != -1:
1515 intStr += ')'
1516 else:
1517 intStr = '-' + intStr
1518 elif right_signpos != -1:
1519 # must have had ')' but '(' was before field; re-add ')'
1520 intStr += ')'
1521 slice = intStr
1522
1523 slice = slice.strip() # drop extra spaces
1524
1525 if self._alignRight: ## Only if right-alignment is enabled
1526 slice = slice.rjust( length )
1527 else:
1528 slice = slice.ljust( length )
1529 if self._fillChar != ' ':
1530 slice = slice.replace(' ', self._fillChar)
1531 dbg('adjusted slice: "%s"' % slice, indent=0)
1532 return slice
1533
1534
1535 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
1536
1537 class MaskedEditMixin:
1538 """
1539 This class allows us to abstract the masked edit functionality that could
1540 be associated with any text entry control. (eg. wxTextCtrl, wxComboBox, etc.)
1541 """
1542 valid_ctrl_params = {
1543 'mask': 'XXXXXXXXXXXXX', ## mask string for formatting this control
1544 'autoformat': "", ## optional auto-format code to set format from masktags dictionary
1545 'fields': {}, ## optional list/dictionary of maskededit.Field class instances, indexed by position in mask
1546 'datestyle': 'MDY', ## optional date style for date-type values. Can trigger autocomplete year
1547 'autoCompleteKeycodes': [], ## Optional list of additional keycodes which will invoke field-auto-complete
1548 'useFixedWidthFont': True, ## Use fixed-width font instead of default for base control
1549 'retainFieldValidation': False, ## Set this to true if setting control-level parameters independently,
1550 ## from field validation constraints
1551 'emptyBackgroundColour': "White",
1552 'validBackgroundColour': "White",
1553 'invalidBackgroundColour': "Yellow",
1554 'foregroundColour': "Black",
1555 'signedForegroundColour': "Red",
1556 'demo': False}
1557
1558
1559 def __init__(self, name = 'wxMaskedEdit', **kwargs):
1560 """
1561 This is the "constructor" for setting up the mixin variable parameters for the composite class.
1562 """
1563
1564 self.name = name
1565
1566 # set up flag for doing optional things to base control if possible
1567 if not hasattr(self, 'controlInitialized'):
1568 self.controlInitialized = False
1569
1570 # Set internal state var for keeping track of whether or not a character
1571 # action results in a modification of the control, since .SetValue()
1572 # doesn't modify the base control's internal state:
1573 self.modified = False
1574 self._previous_mask = None
1575
1576 # Validate legitimate set of parameters:
1577 for key in kwargs.keys():
1578 if key.replace('Color', 'Colour') not in MaskedEditMixin.valid_ctrl_params.keys() + Field.valid_params.keys():
1579 raise TypeError('%s: invalid parameter "%s"' % (name, key))
1580
1581 ## Set up dictionary that can be used by subclasses to override or add to default
1582 ## behavior for individual characters. Derived subclasses needing to change
1583 ## default behavior for keys can either redefine the default functions for the
1584 ## common keys or add functions for specific keys to this list. Each function
1585 ## added should take the key event as argument, and return False if the key
1586 ## requires no further processing.
1587 ##
1588 ## Initially populated with navigation and function control keys:
1589 self._keyhandlers = {
1590 # default navigation keys and handlers:
1591 wx.WXK_BACK: self._OnErase,
1592 wx.WXK_LEFT: self._OnArrow,
1593 wx.WXK_RIGHT: self._OnArrow,
1594 wx.WXK_UP: self._OnAutoCompleteField,
1595 wx.WXK_DOWN: self._OnAutoCompleteField,
1596 wx.WXK_TAB: self._OnChangeField,
1597 wx.WXK_HOME: self._OnHome,
1598 wx.WXK_END: self._OnEnd,
1599 wx.WXK_RETURN: self._OnReturn,
1600 wx.WXK_PRIOR: self._OnAutoCompleteField,
1601 wx.WXK_NEXT: self._OnAutoCompleteField,
1602
1603 # default function control keys and handlers:
1604 wx.WXK_DELETE: self._OnErase,
1605 WXK_CTRL_A: self._OnCtrl_A,
1606 WXK_CTRL_C: self._OnCtrl_C,
1607 WXK_CTRL_S: self._OnCtrl_S,
1608 WXK_CTRL_V: self._OnCtrl_V,
1609 WXK_CTRL_X: self._OnCtrl_X,
1610 WXK_CTRL_Z: self._OnCtrl_Z,
1611 }
1612
1613 ## bind standard navigational and control keycodes to this instance,
1614 ## so that they can be augmented and/or changed in derived classes:
1615 self._nav = list(nav)
1616 self._control = list(control)
1617
1618 ## Dynamically evaluate and store string constants for mask chars
1619 ## so that locale settings can be made after this module is imported
1620 ## and the controls created after that is done can allow the
1621 ## appropriate characters:
1622 self.maskchardict = {
1623 '#': string.digits,
1624 'A': string.uppercase,
1625 'a': string.lowercase,
1626 'X': string.letters + string.punctuation + string.digits,
1627 'C': string.letters,
1628 'N': string.letters + string.digits,
1629 '&': string.punctuation
1630 }
1631
1632 ## self._ignoreChange is used by MaskedComboBox, because
1633 ## of the hack necessary to determine the selection; it causes
1634 ## EVT_TEXT messages from the combobox to be ignored if set.
1635 self._ignoreChange = False
1636
1637 # These are used to keep track of previous value, for undo functionality:
1638 self._curValue = None
1639 self._prevValue = None
1640
1641 self._valid = True
1642
1643 # Set defaults for each parameter for this instance, and fully
1644 # populate initial parameter list for configuration:
1645 for key, value in MaskedEditMixin.valid_ctrl_params.items():
1646 setattr(self, '_' + key, copy.copy(value))
1647 if not kwargs.has_key(key):
1648 ## dbg('%s: "%s"' % (key, repr(value)))
1649 kwargs[key] = copy.copy(value)
1650
1651 # Create a "field" that holds global parameters for control constraints
1652 self._ctrl_constraints = self._fields[-1] = Field(index=-1)
1653 self.SetCtrlParameters(**kwargs)
1654
1655
1656
1657 def SetCtrlParameters(self, **kwargs):
1658 """
1659 This public function can be used to set individual or multiple masked edit
1660 parameters after construction.
1661 """
1662 dbg(suspend=1)
1663 dbg('MaskedEditMixin::SetCtrlParameters', indent=1)
1664 ## dbg('kwargs:', indent=1)
1665 ## for key, value in kwargs.items():
1666 ## dbg(key, '=', value)
1667 ## dbg(indent=0)
1668
1669 # Validate keyword arguments:
1670 constraint_kwargs = {}
1671 ctrl_kwargs = {}
1672 for key, value in kwargs.items():
1673 key = key.replace('Color', 'Colour') # for b-c, and standard wxPython spelling
1674 if key not in MaskedEditMixin.valid_ctrl_params.keys() + Field.valid_params.keys():
1675 dbg(indent=0, suspend=0)
1676 raise TypeError('Invalid keyword argument "%s" for control "%s"' % (key, self.name))
1677 elif key in Field.valid_params.keys():
1678 constraint_kwargs[key] = value
1679 else:
1680 ctrl_kwargs[key] = value
1681
1682 mask = None
1683 reset_args = {}
1684
1685 if ctrl_kwargs.has_key('autoformat'):
1686 autoformat = ctrl_kwargs['autoformat']
1687 else:
1688 autoformat = None
1689
1690 if autoformat != self._autoformat and autoformat in masktags.keys():
1691 dbg('autoformat:', autoformat)
1692 self._autoformat = autoformat
1693 mask = masktags[self._autoformat]['mask']
1694 # gather rest of any autoformat parameters:
1695 for param, value in masktags[self._autoformat].items():
1696 if param == 'mask': continue # (must be present; already accounted for)
1697 constraint_kwargs[param] = value
1698
1699 elif autoformat and not autoformat in masktags.keys():
1700 raise AttributeError('invalid value for autoformat parameter: %s' % repr(autoformat))
1701 else:
1702 dbg('autoformat not selected')
1703 if kwargs.has_key('mask'):
1704 mask = kwargs['mask']
1705 dbg('mask:', mask)
1706
1707 ## Assign style flags
1708 if mask is None:
1709 dbg('preserving previous mask')
1710 mask = self._previous_mask # preserve previous mask
1711 else:
1712 dbg('mask (re)set')
1713 reset_args['reset_mask'] = mask
1714 constraint_kwargs['mask'] = mask
1715
1716 # wipe out previous fields; preserve new control-level constraints
1717 self._fields = {-1: self._ctrl_constraints}
1718
1719
1720 if ctrl_kwargs.has_key('fields'):
1721 # do field parameter type validation, and conversion to internal dictionary
1722 # as appropriate:
1723 fields = ctrl_kwargs['fields']
1724 if type(fields) in (types.ListType, types.TupleType):
1725 for i in range(len(fields)):
1726 field = fields[i]
1727 if not isinstance(field, Field):
1728 dbg(indent=0, suspend=0)
1729 raise AttributeError('invalid type for field parameter: %s' % repr(field))
1730 self._fields[i] = field
1731
1732 elif type(fields) == types.DictionaryType:
1733 for index, field in fields.items():
1734 if not isinstance(field, Field):
1735 dbg(indent=0, suspend=0)
1736 raise AttributeError('invalid type for field parameter: %s' % repr(field))
1737 self._fields[index] = field
1738 else:
1739 dbg(indent=0, suspend=0)
1740 raise AttributeError('fields parameter must be a list or dictionary; not %s' % repr(fields))
1741
1742 # Assign constraint parameters for entire control:
1743 ## dbg('control constraints:', indent=1)
1744 ## for key, value in constraint_kwargs.items():
1745 ## dbg('%s:' % key, value)
1746 ## dbg(indent=0)
1747
1748 # determine if changing parameters that should affect the entire control:
1749 for key in MaskedEditMixin.valid_ctrl_params.keys():
1750 if key in ( 'mask', 'fields' ): continue # (processed separately)
1751 if ctrl_kwargs.has_key(key):
1752 setattr(self, '_' + key, ctrl_kwargs[key])
1753
1754 # Validate color parameters, converting strings to named colors and validating
1755 # result if appropriate:
1756 for key in ('emptyBackgroundColour', 'invalidBackgroundColour', 'validBackgroundColour',
1757 'foregroundColour', 'signedForegroundColour'):
1758 if ctrl_kwargs.has_key(key):
1759 if type(ctrl_kwargs[key]) in (types.StringType, types.UnicodeType):
1760 c = wx.NamedColour(ctrl_kwargs[key])
1761 if c.Get() == (-1, -1, -1):
1762 raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs[key]), key))
1763 else:
1764 # replace attribute with wxColour object:
1765 setattr(self, '_' + key, c)
1766 # attach a python dynamic attribute to wxColour for debug printouts
1767 c._name = ctrl_kwargs[key]
1768
1769 elif type(ctrl_kwargs[key]) != type(wx.BLACK):
1770 raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs[key]), key))
1771
1772
1773 dbg('self._retainFieldValidation:', self._retainFieldValidation)
1774 if not self._retainFieldValidation:
1775 # Build dictionary of any changing parameters which should be propagated to the
1776 # component fields:
1777 for arg in Field.propagating_params:
1778 ## dbg('kwargs.has_key(%s)?' % arg, kwargs.has_key(arg))
1779 ## dbg('getattr(self._ctrl_constraints, _%s)?' % arg, getattr(self._ctrl_constraints, '_'+arg))
1780 reset_args[arg] = kwargs.has_key(arg) and kwargs[arg] != getattr(self._ctrl_constraints, '_'+arg)
1781 ## dbg('reset_args[%s]?' % arg, reset_args[arg])
1782
1783 # Set the control-level constraints:
1784 self._ctrl_constraints._SetParameters(**constraint_kwargs)
1785
1786 # This routine does the bulk of the interdependent parameter processing, determining
1787 # the field extents of the mask if changed, resetting parameters as appropriate,
1788 # determining the overall template value for the control, etc.
1789 self._configure(mask, **reset_args)
1790
1791 # now that we've propagated the field constraints and mask portions to the
1792 # various fields, validate the constraints
1793 self._ctrl_constraints._ValidateParameters(**constraint_kwargs)
1794
1795 # Validate that all choices for given fields are at least of the
1796 # necessary length, and that they all would be valid pastes if pasted
1797 # into their respective fields:
1798 ## dbg('validating choices')
1799 self._validateChoices()
1800
1801
1802 self._autofit = self._ctrl_constraints._autofit
1803 self._isNeg = False
1804
1805 self._isDate = 'D' in self._ctrl_constraints._formatcodes and isDateType(mask)
1806 self._isTime = 'T' in self._ctrl_constraints._formatcodes and isTimeType(mask)
1807 if self._isDate:
1808 # Set _dateExtent, used in date validation to locate date in string;
1809 # always set as though year will be 4 digits, even if mask only has
1810 # 2 digits, so we can always properly process the intended year for
1811 # date validation (leap years, etc.)
1812 if self._mask.find('CCC') != -1: self._dateExtent = 11
1813 else: self._dateExtent = 10
1814
1815 self._4digityear = len(self._mask) > 8 and self._mask[9] == '#'
1816
1817 if self._isDate and self._autoformat:
1818 # Auto-decide datestyle:
1819 if self._autoformat.find('MDDY') != -1: self._datestyle = 'MDY'
1820 elif self._autoformat.find('YMMD') != -1: self._datestyle = 'YMD'
1821 elif self._autoformat.find('YMMMD') != -1: self._datestyle = 'YMD'
1822 elif self._autoformat.find('DMMY') != -1: self._datestyle = 'DMY'
1823 elif self._autoformat.find('DMMMY') != -1: self._datestyle = 'DMY'
1824
1825
1826 if self.controlInitialized:
1827 # Then the base control is available for configuration;
1828 # take action on base control based on new settings, as appropriate.
1829 if kwargs.has_key('useFixedWidthFont'):
1830 # Set control font - fixed width by default
1831 self._setFont()
1832
1833 if reset_args.has_key('reset_mask'):
1834 dbg('reset mask')
1835 curvalue = self._GetValue()
1836 if curvalue.strip():
1837 try:
1838 dbg('attempting to _SetInitialValue(%s)' % self._GetValue())
1839 self._SetInitialValue(self._GetValue())
1840 except Exception, e:
1841 dbg('exception caught:', e)
1842 dbg("current value doesn't work; attempting to reset to template")
1843 self._SetInitialValue()
1844 else:
1845 dbg('attempting to _SetInitialValue() with template')
1846 self._SetInitialValue()
1847
1848 elif kwargs.has_key('useParensForNegatives'):
1849 newvalue = self._getSignedValue()[0]
1850
1851 if newvalue is not None:
1852 # Adjust for new mask:
1853 if len(newvalue) < len(self._mask):
1854 newvalue += ' '
1855 elif len(newvalue) > len(self._mask):
1856 if newvalue[-1] in (' ', ')'):
1857 newvalue = newvalue[:-1]
1858
1859 dbg('reconfiguring value for parens:"%s"' % newvalue)
1860 self._SetValue(newvalue)
1861
1862 if self._prevValue != newvalue:
1863 self._prevValue = newvalue # disallow undo of sign type
1864
1865 if self._autofit:
1866 dbg('setting client size to:', self._CalcSize())
1867 self.SetClientSize(self._CalcSize())
1868
1869 # Set value/type-specific formatting
1870 self._applyFormatting()
1871 dbg(indent=0, suspend=0)
1872
1873 def SetMaskParameters(self, **kwargs):
1874 """ old name for this function """
1875 return self.SetCtrlParameters(**kwargs)
1876
1877
1878 def GetCtrlParameter(self, paramname):
1879 """
1880 Routine for retrieving the value of any given parameter
1881 """
1882 if MaskedEditMixin.valid_ctrl_params.has_key(paramname.replace('Color','Colour')):
1883 return getattr(self, '_' + paramname.replace('Color', 'Colour'))
1884 elif Field.valid_params.has_key(paramname):
1885 return self._ctrl_constraints._GetParameter(paramname)
1886 else:
1887 TypeError('"%s".GetCtrlParameter: invalid parameter "%s"' % (self.name, paramname))
1888
1889 def GetMaskParameter(self, paramname):
1890 """ old name for this function """
1891 return self.GetCtrlParameter(paramname)
1892
1893
1894 # ## TRICKY BIT: to avoid a ton of boiler-plate, and to
1895 # ## automate the getter/setter generation for each valid
1896 # ## control parameter so we never forget to add the
1897 # ## functions when adding parameters, this loop
1898 # ## programmatically adds them to the class:
1899 # ## (This makes it easier for Designers like Boa to
1900 # ## deal with masked controls.)
1901 # ##
1902 for param in valid_ctrl_params.keys() + Field.valid_params.keys():
1903 propname = param[0].upper() + param[1:]
1904 exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))
1905 exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
1906 if param.find('Colour') != -1:
1907 # add non-british spellings, for backward-compatibility
1908 propname.replace('Colour', 'Color')
1909 exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))
1910 exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
1911
1912
1913 def SetFieldParameters(self, field_index, **kwargs):
1914 """
1915 Routine provided to modify the parameters of a given field.
1916 Because changes to fields can affect the overall control,
1917 direct access to the fields is prevented, and the control
1918 is always "reconfigured" after setting a field parameter.
1919 """
1920 if field_index not in self._field_indices:
1921 raise IndexError('%s is not a valid field for control "%s".' % (str(field_index), self.name))
1922 # set parameters as requested:
1923 self._fields[field_index]._SetParameters(**kwargs)
1924
1925 # Possibly reprogram control template due to resulting changes, and ensure
1926 # control-level params are still propagated to fields:
1927 self._configure(self._previous_mask)
1928 self._fields[field_index]._ValidateParameters(**kwargs)
1929
1930 if self.controlInitialized:
1931 if kwargs.has_key('fillChar') or kwargs.has_key('defaultValue'):
1932 self._SetInitialValue()
1933
1934 if self._autofit:
1935 self.SetClientSize(self._CalcSize())
1936
1937 # Set value/type-specific formatting
1938 self._applyFormatting()
1939
1940
1941 def GetFieldParameter(self, field_index, paramname):
1942 """
1943 Routine provided for getting a parameter of an individual field.
1944 """
1945 if field_index not in self._field_indices:
1946 raise IndexError('%s is not a valid field for control "%s".' % (str(field_index), self.name))
1947 elif Field.valid_params.has_key(paramname):
1948 return self._fields[field_index]._GetParameter(paramname)
1949 else:
1950 TypeError('"%s".GetFieldParameter: invalid parameter "%s"' % (self.name, paramname))
1951
1952
1953 def _SetKeycodeHandler(self, keycode, func):
1954 """
1955 This function adds and/or replaces key event handling functions
1956 used by the control. <func> should take the event as argument
1957 and return False if no further action on the key is necessary.
1958 """
1959 self._keyhandlers[keycode] = func
1960
1961
1962 def _SetKeyHandler(self, char, func):
1963 """
1964 This function adds and/or replaces key event handling functions
1965 for ascii characters. <func> should take the event as argument
1966 and return False if no further action on the key is necessary.
1967 """
1968 self._SetKeycodeHandler(ord(char), func)
1969
1970
1971 def _AddNavKeycode(self, keycode, handler=None):
1972 """
1973 This function allows a derived subclass to augment the list of
1974 keycodes that are considered "navigational" keys.
1975 """
1976 self._nav.append(keycode)
1977 if handler:
1978 self._keyhandlers[keycode] = handler
1979
1980
1981 def _AddNavKey(self, char, handler=None):
1982 """
1983 This function is a convenience function so you don't have to
1984 remember to call ord() for ascii chars to be used for navigation.
1985 """
1986 self._AddNavKeycode(ord(char), handler)
1987
1988
1989 def _GetNavKeycodes(self):
1990 """
1991 This function retrieves the current list of navigational keycodes for
1992 the control.
1993 """
1994 return self._nav
1995
1996
1997 def _SetNavKeycodes(self, keycode_func_tuples):
1998 """
1999 This function allows you to replace the current list of keycode processed
2000 as navigation keys, and bind associated optional keyhandlers.
2001 """
2002 self._nav = []
2003 for keycode, func in keycode_func_tuples:
2004 self._nav.append(keycode)
2005 if func:
2006 self._keyhandlers[keycode] = func
2007
2008
2009 def _processMask(self, mask):
2010 """
2011 This subroutine expands {n} syntax in mask strings, and looks for escaped
2012 special characters and returns the expanded mask, and an dictionary
2013 of booleans indicating whether or not a given position in the mask is
2014 a mask character or not.
2015 """
2016 dbg('_processMask: mask', mask, indent=1)
2017 # regular expression for parsing c{n} syntax:
2018 rex = re.compile('([' +string.join(maskchars,"") + '])\{(\d+)\}')
2019 s = mask
2020 match = rex.search(s)
2021 while match: # found an(other) occurrence
2022 maskchr = s[match.start(1):match.end(1)] # char to be repeated
2023 repcount = int(s[match.start(2):match.end(2)]) # the number of times
2024 replacement = string.join( maskchr * repcount, "") # the resulting substr
2025 s = s[:match.start(1)] + replacement + s[match.end(2)+1:] #account for trailing '}'
2026 match = rex.search(s) # look for another such entry in mask
2027
2028 self._decimalChar = self._ctrl_constraints._decimalChar
2029 self._shiftDecimalChar = self._ctrl_constraints._shiftDecimalChar
2030
2031 self._isFloat = isFloatingPoint(s) and not self._ctrl_constraints._validRegex
2032 self._isInt = isInteger(s) and not self._ctrl_constraints._validRegex
2033 self._signOk = '-' in self._ctrl_constraints._formatcodes and (self._isFloat or self._isInt)
2034 self._useParens = self._ctrl_constraints._useParensForNegatives
2035 self._isNeg = False
2036 ## dbg('self._signOk?', self._signOk, 'self._useParens?', self._useParens)
2037 ## dbg('isFloatingPoint(%s)?' % (s), isFloatingPoint(s),
2038 ## 'ctrl regex:', self._ctrl_constraints._validRegex)
2039
2040 if self._signOk and s[0] != ' ':
2041 s = ' ' + s
2042 if self._ctrl_constraints._defaultValue and self._ctrl_constraints._defaultValue[0] != ' ':
2043 self._ctrl_constraints._defaultValue = ' ' + self._ctrl_constraints._defaultValue
2044 self._signpos = 0
2045
2046 if self._useParens:
2047 s += ' '
2048 self._ctrl_constraints._defaultValue += ' '
2049
2050 # Now, go build up a dictionary of booleans, indexed by position,
2051 # indicating whether or not a given position is masked or not
2052 ismasked = {}
2053 i = 0
2054 while i < len(s):
2055 if s[i] == '\\': # if escaped character:
2056 ismasked[i] = False # mark position as not a mask char
2057 if i+1 < len(s): # if another char follows...
2058 s = s[:i] + s[i+1:] # elide the '\'
2059 if i+2 < len(s) and s[i+1] == '\\':
2060 # if next char also a '\', char is a literal '\'
2061 s = s[:i] + s[i+1:] # elide the 2nd '\' as well
2062 else: # else if special char, mark position accordingly
2063 ismasked[i] = s[i] in maskchars
2064 ## dbg('ismasked[%d]:' % i, ismasked[i], s)
2065 i += 1 # increment to next char
2066 ## dbg('ismasked:', ismasked)
2067 dbg('new mask: "%s"' % s, indent=0)
2068
2069 return s, ismasked
2070
2071
2072 def _calcFieldExtents(self):
2073 """
2074 Subroutine responsible for establishing/configuring field instances with
2075 indices and editable extents appropriate to the specified mask, and building
2076 the lookup table mapping each position to the corresponding field.
2077 """
2078 self._lookupField = {}
2079 if self._mask:
2080
2081 ## Create dictionary of positions,characters in mask
2082 self.maskdict = {}
2083 for charnum in range( len( self._mask)):
2084 self.maskdict[charnum] = self._mask[charnum:charnum+1]
2085
2086 # For the current mask, create an ordered list of field extents
2087 # and a dictionary of positions that map to field indices:
2088
2089 if self._signOk: start = 1
2090 else: start = 0
2091
2092 if self._isFloat:
2093 # Skip field "discovery", and just construct a 2-field control with appropriate
2094 # constraints for a floating-point entry.
2095
2096 # .setdefault always constructs 2nd argument even if not needed, so we do this
2097 # the old-fashioned way...
2098 if not self._fields.has_key(0):
2099 self._fields[0] = Field()
2100 if not self._fields.has_key(1):
2101 self._fields[1] = Field()
2102
2103 self._decimalpos = string.find( self._mask, '.')
2104 dbg('decimal pos =', self._decimalpos)
2105
2106 formatcodes = self._fields[0]._GetParameter('formatcodes')
2107 if 'R' not in formatcodes: formatcodes += 'R'
2108 self._fields[0]._SetParameters(index=0, extent=(start, self._decimalpos),
2109 mask=self._mask[start:self._decimalpos], formatcodes=formatcodes)
2110 end = len(self._mask)
2111 if self._signOk and self._useParens:
2112 end -= 1
2113 self._fields[1]._SetParameters(index=1, extent=(self._decimalpos+1, end),
2114 mask=self._mask[self._decimalpos+1:end])
2115
2116 for i in range(self._decimalpos+1):
2117 self._lookupField[i] = 0
2118
2119 for i in range(self._decimalpos+1, len(self._mask)+1):
2120 self._lookupField[i] = 1
2121
2122 elif self._isInt:
2123 # Skip field "discovery", and just construct a 1-field control with appropriate
2124 # constraints for a integer entry.
2125 if not self._fields.has_key(0):
2126 self._fields[0] = Field(index=0)
2127 end = len(self._mask)
2128 if self._signOk and self._useParens:
2129 end -= 1
2130 self._fields[0]._SetParameters(index=0, extent=(start, end),
2131 mask=self._mask[start:end])
2132 for i in range(len(self._mask)+1):
2133 self._lookupField[i] = 0
2134 else:
2135 # generic control; parse mask to figure out where the fields are:
2136 field_index = 0
2137 pos = 0
2138 i = self._findNextEntry(pos,adjustInsert=False) # go to 1st entry point:
2139 if i < len(self._mask): # no editable chars!
2140 for j in range(pos, i+1):
2141 self._lookupField[j] = field_index
2142 pos = i # figure out field for 1st editable space:
2143
2144 while i <= len(self._mask):
2145 ## dbg('searching: outer field loop: i = ', i)
2146 if self._isMaskChar(i):
2147 ## dbg('1st char is mask char; recording edit_start=', i)
2148 edit_start = i
2149 # Skip to end of editable part of current field:
2150 while i < len(self._mask) and self._isMaskChar(i):
2151 self._lookupField[i] = field_index
2152 i += 1
2153 ## dbg('edit_end =', i)
2154 edit_end = i
2155 self._lookupField[i] = field_index
2156 ## dbg('self._fields.has_key(%d)?' % field_index, self._fields.has_key(field_index))
2157 if not self._fields.has_key(field_index):
2158 kwargs = Field.valid_params.copy()
2159 kwargs['index'] = field_index
2160 kwargs['extent'] = (edit_start, edit_end)
2161 kwargs['mask'] = self._mask[edit_start:edit_end]
2162 self._fields[field_index] = Field(**kwargs)
2163 else:
2164 self._fields[field_index]._SetParameters(
2165 index=field_index,
2166 extent=(edit_start, edit_end),
2167 mask=self._mask[edit_start:edit_end])
2168 pos = i
2169 i = self._findNextEntry(pos, adjustInsert=False) # go to next field:
2170 if i > pos:
2171 for j in range(pos, i+1):
2172 self._lookupField[j] = field_index
2173 if i >= len(self._mask):
2174 break # if past end, we're done
2175 else:
2176 field_index += 1
2177 ## dbg('next field:', field_index)
2178
2179 indices = self._fields.keys()
2180 indices.sort()
2181 self._field_indices = indices[1:]
2182 ## dbg('lookupField map:', indent=1)
2183 ## for i in range(len(self._mask)):
2184 ## dbg('pos %d:' % i, self._lookupField[i])
2185 ## dbg(indent=0)
2186
2187 # Verify that all field indices specified are valid for mask:
2188 for index in self._fields.keys():
2189 if index not in [-1] + self._lookupField.values():
2190 raise IndexError('field %d is not a valid field for mask "%s"' % (index, self._mask))
2191
2192
2193 def _calcTemplate(self, reset_fillchar, reset_default):
2194 """
2195 Subroutine for processing current fillchars and default values for
2196 whole control and individual fields, constructing the resulting
2197 overall template, and adjusting the current value as necessary.
2198 """
2199 default_set = False
2200 if self._ctrl_constraints._defaultValue:
2201 default_set = True
2202 else:
2203 for field in self._fields.values():
2204 if field._defaultValue and not reset_default:
2205 default_set = True
2206 dbg('default set?', default_set)
2207
2208 # Determine overall new template for control, and keep track of previous
2209 # values, so that current control value can be modified as appropriate:
2210 if self.controlInitialized: curvalue = list(self._GetValue())
2211 else: curvalue = None
2212
2213 if hasattr(self, '_fillChar'): old_fillchars = self._fillChar
2214 else: old_fillchars = None
2215
2216 if hasattr(self, '_template'): old_template = self._template
2217 else: old_template = None
2218
2219 self._template = ""
2220
2221 self._fillChar = {}
2222 reset_value = False
2223
2224 for field in self._fields.values():
2225 field._template = ""
2226
2227 for pos in range(len(self._mask)):
2228 ## dbg('pos:', pos)
2229 field = self._FindField(pos)
2230 ## dbg('field:', field._index)
2231 start, end = field._extent
2232
2233 if pos == 0 and self._signOk:
2234 self._template = ' ' # always make 1st 1st position blank, regardless of fillchar
2235 elif self._isFloat and pos == self._decimalpos:
2236 self._template += self._decimalChar
2237 elif self._isMaskChar(pos):
2238 if field._fillChar != self._ctrl_constraints._fillChar and not reset_fillchar:
2239 fillChar = field._fillChar
2240 else:
2241 fillChar = self._ctrl_constraints._fillChar
2242 self._fillChar[pos] = fillChar
2243
2244 # Replace any current old fillchar with new one in current value;
2245 # if action required, set reset_value flag so we can take that action
2246 # after we're all done
2247 if self.controlInitialized and old_fillchars and old_fillchars.has_key(pos) and curvalue:
2248 if curvalue[pos] == old_fillchars[pos] and old_fillchars[pos] != fillChar:
2249 reset_value = True
2250 curvalue[pos] = fillChar
2251
2252 if not field._defaultValue and not self._ctrl_constraints._defaultValue:
2253 ## dbg('no default value')
2254 self._template += fillChar
2255 field._template += fillChar
2256
2257 elif field._defaultValue and not reset_default:
2258 ## dbg('len(field._defaultValue):', len(field._defaultValue))
2259 ## dbg('pos-start:', pos-start)
2260 if len(field._defaultValue) > pos-start:
2261 ## dbg('field._defaultValue[pos-start]: "%s"' % field._defaultValue[pos-start])
2262 self._template += field._defaultValue[pos-start]
2263 field._template += field._defaultValue[pos-start]
2264 else:
2265 ## dbg('field default not long enough; using fillChar')
2266 self._template += fillChar
2267 field._template += fillChar
2268 else:
2269 if len(self._ctrl_constraints._defaultValue) > pos:
2270 ## dbg('using control default')
2271 self._template += self._ctrl_constraints._defaultValue[pos]
2272 field._template += self._ctrl_constraints._defaultValue[pos]
2273 else:
2274 ## dbg('ctrl default not long enough; using fillChar')
2275 self._template += fillChar
2276 field._template += fillChar
2277 ## dbg('field[%d]._template now "%s"' % (field._index, field._template))
2278 ## dbg('self._template now "%s"' % self._template)
2279 else:
2280 self._template += self._mask[pos]
2281
2282 self._fields[-1]._template = self._template # (for consistency)
2283
2284 if curvalue: # had an old value, put new one back together
2285 newvalue = string.join(curvalue, "")
2286 else:
2287 newvalue = None
2288
2289 if default_set:
2290 self._defaultValue = self._template
2291 dbg('self._defaultValue:', self._defaultValue)
2292 if not self.IsEmpty(self._defaultValue) and not self.IsValid(self._defaultValue):
2293 ## dbg(indent=0)
2294 raise ValueError('Default value of "%s" is not a valid value for control "%s"' % (self._defaultValue, self.name))
2295
2296 # if no fillchar change, but old value == old template, replace it:
2297 if newvalue == old_template:
2298 newvalue = self._template
2299 reset_value = True
2300 else:
2301 self._defaultValue = None
2302
2303 if reset_value:
2304 dbg('resetting value to: "%s"' % newvalue)
2305 pos = self._GetInsertionPoint()
2306 sel_start, sel_to = self._GetSelection()
2307 self._SetValue(newvalue)
2308 self._SetInsertionPoint(pos)
2309 self._SetSelection(sel_start, sel_to)
2310
2311
2312 def _propagateConstraints(self, **reset_args):
2313 """
2314 Subroutine for propagating changes to control-level constraints and
2315 formatting to the individual fields as appropriate.
2316 """
2317 parent_codes = self._ctrl_constraints._formatcodes
2318 parent_includes = self._ctrl_constraints._includeChars
2319 parent_excludes = self._ctrl_constraints._excludeChars
2320 for i in self._field_indices:
2321 field = self._fields[i]
2322 inherit_args = {}
2323 if len(self._field_indices) == 1:
2324 inherit_args['formatcodes'] = parent_codes
2325 inherit_args['includeChars'] = parent_includes
2326 inherit_args['excludeChars'] = parent_excludes
2327 else:
2328 field_codes = current_codes = field._GetParameter('formatcodes')
2329 for c in parent_codes:
2330 if c not in field_codes: field_codes += c
2331 if field_codes != current_codes:
2332 inherit_args['formatcodes'] = field_codes
2333
2334 include_chars = current_includes = field._GetParameter('includeChars')
2335 for c in parent_includes:
2336 if not c in include_chars: include_chars += c
2337 if include_chars != current_includes:
2338 inherit_args['includeChars'] = include_chars
2339
2340 exclude_chars = current_excludes = field._GetParameter('excludeChars')
2341 for c in parent_excludes:
2342 if not c in exclude_chars: exclude_chars += c
2343 if exclude_chars != current_excludes:
2344 inherit_args['excludeChars'] = exclude_chars
2345
2346 if reset_args.has_key('defaultValue') and reset_args['defaultValue']:
2347 inherit_args['defaultValue'] = "" # (reset for field)
2348
2349 for param in Field.propagating_params:
2350 ## dbg('reset_args.has_key(%s)?' % param, reset_args.has_key(param))
2351 ## dbg('reset_args.has_key(%(param)s) and reset_args[%(param)s]?' % locals(), reset_args.has_key(param) and reset_args[param])
2352 if reset_args.has_key(param):
2353 inherit_args[param] = self.GetCtrlParameter(param)
2354 ## dbg('inherit_args[%s]' % param, inherit_args[param])
2355
2356 if inherit_args:
2357 field._SetParameters(**inherit_args)
2358 field._ValidateParameters(**inherit_args)
2359
2360
2361 def _validateChoices(self):
2362 """
2363 Subroutine that validates that all choices for given fields are at
2364 least of the necessary length, and that they all would be valid pastes
2365 if pasted into their respective fields.
2366 """
2367 for field in self._fields.values():
2368 if field._choices:
2369 index = field._index
2370 if len(self._field_indices) == 1 and index == 0 and field._choices == self._ctrl_constraints._choices:
2371 dbg('skipping (duplicate) choice validation of field 0')
2372 continue
2373 ## dbg('checking for choices for field', field._index)
2374 start, end = field._extent
2375 field_length = end - start
2376 ## dbg('start, end, length:', start, end, field_length)
2377 for choice in field._choices:
2378 ## dbg('testing "%s"' % choice)
2379 valid_paste, ignore, replace_to = self._validatePaste(choice, start, end)
2380 if not valid_paste:
2381 ## dbg(indent=0)
2382 raise ValueError('"%s" could not be entered into field %d of control "%s"' % (choice, index, self.name))
2383 elif replace_to > end:
2384 ## dbg(indent=0)
2385 raise ValueError('"%s" will not fit into field %d of control "%s"' (choice, index, self.name))
2386 ## dbg(choice, 'valid in field', index)
2387
2388
2389 def _configure(self, mask, **reset_args):
2390 """
2391 This function sets flags for automatic styling options. It is
2392 called whenever a control or field-level parameter is set/changed.
2393
2394 This routine does the bulk of the interdependent parameter processing, determining
2395 the field extents of the mask if changed, resetting parameters as appropriate,
2396 determining the overall template value for the control, etc.
2397
2398 reset_args is supplied if called from control's .SetCtrlParameters()
2399 routine, and indicates which if any parameters which can be
2400 overridden by individual fields have been reset by request for the
2401 whole control.
2402
2403 """
2404 dbg(suspend=1)
2405 dbg('MaskedEditMixin::_configure("%s")' % mask, indent=1)
2406
2407 # Preprocess specified mask to expand {n} syntax, handle escaped
2408 # mask characters, etc and build the resulting positionally keyed
2409 # dictionary for which positions are mask vs. template characters:
2410 self._mask, self.ismasked = self._processMask(mask)
2411 self._masklength = len(self._mask)
2412 ## dbg('processed mask:', self._mask)
2413
2414 # Preserve original mask specified, for subsequent reprocessing
2415 # if parameters change.
2416 dbg('mask: "%s"' % self._mask, 'previous mask: "%s"' % self._previous_mask)
2417 self._previous_mask = mask # save unexpanded mask for next time
2418 # Set expanded mask and extent of field -1 to width of entire control:
2419 self._ctrl_constraints._SetParameters(mask = self._mask, extent=(0,self._masklength))
2420
2421 # Go parse mask to determine where each field is, construct field
2422 # instances as necessary, configure them with those extents, and
2423 # build lookup table mapping each position for control to its corresponding
2424 # field.
2425 ## dbg('calculating field extents')
2426
2427 self._calcFieldExtents()
2428
2429
2430 # Go process defaultValues and fillchars to construct the overall
2431 # template, and adjust the current value as necessary:
2432 reset_fillchar = reset_args.has_key('fillChar') and reset_args['fillChar']
2433 reset_default = reset_args.has_key('defaultValue') and reset_args['defaultValue']
2434
2435 ## dbg('calculating template')
2436 self._calcTemplate(reset_fillchar, reset_default)
2437
2438 # Propagate control-level formatting and character constraints to each
2439 # field if they don't already have them; if only one field, propagate
2440 # control-level validation constraints to field as well:
2441 ## dbg('propagating constraints')
2442 self._propagateConstraints(**reset_args)
2443
2444
2445 if self._isFloat and self._fields[0]._groupChar == self._decimalChar:
2446 raise AttributeError('groupChar (%s) and decimalChar (%s) must be distinct.' %
2447 (self._fields[0]._groupChar, self._decimalChar) )
2448
2449 ## dbg('fields:', indent=1)
2450 ## for i in [-1] + self._field_indices:
2451 ## dbg('field %d:' % i, self._fields[i].__dict__)
2452 ## dbg(indent=0)
2453
2454 # Set up special parameters for numeric control, if appropriate:
2455 if self._signOk:
2456 self._signpos = 0 # assume it starts here, but it will move around on floats
2457 signkeys = ['-', '+', ' ']
2458 if self._useParens:
2459 signkeys += ['(', ')']
2460 for key in signkeys:
2461 keycode = ord(key)
2462 if not self._keyhandlers.has_key(keycode):
2463 self._SetKeyHandler(key, self._OnChangeSign)
2464
2465
2466
2467 if self._isFloat or self._isInt:
2468 if self.controlInitialized:
2469 value = self._GetValue()
2470 ## dbg('value: "%s"' % value, 'len(value):', len(value),
2471 ## 'len(self._ctrl_constraints._mask):',len(self._ctrl_constraints._mask))
2472 if len(value) < len(self._ctrl_constraints._mask):
2473 newvalue = value
2474 if self._useParens and len(newvalue) < len(self._ctrl_constraints._mask) and newvalue.find('(') == -1:
2475 newvalue += ' '
2476 if self._signOk and len(newvalue) < len(self._ctrl_constraints._mask) and newvalue.find(')') == -1:
2477 newvalue = ' ' + newvalue
2478 if len(newvalue) < len(self._ctrl_constraints._mask):
2479 if self._ctrl_constraints._alignRight:
2480 newvalue = newvalue.rjust(len(self._ctrl_constraints._mask))
2481 else:
2482 newvalue = newvalue.ljust(len(self._ctrl_constraints._mask))
2483 dbg('old value: "%s"' % value)
2484 dbg('new value: "%s"' % newvalue)
2485 try:
2486 self._SetValue(newvalue)
2487 except Exception, e:
2488 dbg('exception raised:', e, 'resetting to initial value')
2489 self._SetInitialValue()
2490
2491 elif len(value) > len(self._ctrl_constraints._mask):
2492 newvalue = value
2493 if not self._useParens and newvalue[-1] == ' ':
2494 newvalue = newvalue[:-1]
2495 if not self._signOk and len(newvalue) > len(self._ctrl_constraints._mask):
2496 newvalue = newvalue[1:]
2497 if not self._signOk:
2498 newvalue, signpos, right_signpos = self._getSignedValue(newvalue)
2499
2500 dbg('old value: "%s"' % value)
2501 dbg('new value: "%s"' % newvalue)
2502 try:
2503 self._SetValue(newvalue)
2504 except Exception, e:
2505 dbg('exception raised:', e, 'resetting to initial value')
2506 self._SetInitialValue()
2507 elif not self._signOk and ('(' in value or '-' in value):
2508 newvalue, signpos, right_signpos = self._getSignedValue(value)
2509 dbg('old value: "%s"' % value)
2510 dbg('new value: "%s"' % newvalue)
2511 try:
2512 self._SetValue(newvalue)
2513 except e:
2514 dbg('exception raised:', e, 'resetting to initial value')
2515 self._SetInitialValue()
2516
2517 # Replace up/down arrow default handling:
2518 # make down act like tab, up act like shift-tab:
2519
2520 ## dbg('Registering numeric navigation and control handlers (if not already set)')
2521 if not self._keyhandlers.has_key(wx.WXK_DOWN):
2522 self._SetKeycodeHandler(wx.WXK_DOWN, self._OnChangeField)
2523 if not self._keyhandlers.has_key(wx.WXK_UP):
2524 self._SetKeycodeHandler(wx.WXK_UP, self._OnUpNumeric) # (adds "shift" to up arrow, and calls _OnChangeField)
2525
2526 # On ., truncate contents right of cursor to decimal point (if any)
2527 # leaves cusor after decimal point if floating point, otherwise at 0.
2528 if not self._keyhandlers.has_key(ord(self._decimalChar)):
2529 self._SetKeyHandler(self._decimalChar, self._OnDecimalPoint)
2530 if not self._keyhandlers.has_key(ord(self._shiftDecimalChar)):
2531 self._SetKeyHandler(self._shiftDecimalChar, self._OnChangeField) # (Shift-'.' == '>' on US keyboards)
2532
2533 # Allow selective insert of groupchar in numbers:
2534 if not self._keyhandlers.has_key(ord(self._fields[0]._groupChar)):
2535 self._SetKeyHandler(self._fields[0]._groupChar, self._OnGroupChar)
2536
2537 dbg(indent=0, suspend=0)
2538
2539
2540 def _SetInitialValue(self, value=""):
2541 """
2542 fills the control with the generated or supplied default value.
2543 It will also set/reset the font if necessary and apply
2544 formatting to the control at this time.
2545 """
2546 dbg('MaskedEditMixin::_SetInitialValue("%s")' % value, indent=1)
2547 if not value:
2548 self._prevValue = self._curValue = self._template
2549 # don't apply external validation rules in this case, as template may
2550 # not coincide with "legal" value...
2551 try:
2552 self._SetValue(self._curValue) # note the use of "raw" ._SetValue()...
2553 except Exception, e:
2554 dbg('exception thrown:', e, indent=0)
2555 raise
2556 else:
2557 # Otherwise apply validation as appropriate to passed value:
2558 ## dbg('value = "%s", length:' % value, len(value))
2559 self._prevValue = self._curValue = value
2560 try:
2561 self.SetValue(value) # use public (validating) .SetValue()
2562 except Exception, e:
2563 dbg('exception thrown:', e, indent=0)
2564 raise
2565
2566
2567 # Set value/type-specific formatting
2568 self._applyFormatting()
2569 dbg(indent=0)
2570
2571
2572 def _calcSize(self, size=None):
2573 """ Calculate automatic size if allowed; must be called after the base control is instantiated"""
2574 ## dbg('MaskedEditMixin::_calcSize', indent=1)
2575 cont = (size is None or size == wx.DefaultSize)
2576
2577 if cont and self._autofit:
2578 sizing_text = 'M' * self._masklength
2579 if wx.Platform != "__WXMSW__": # give it a little extra space
2580 sizing_text += 'M'
2581 if wx.Platform == "__WXMAC__": # give it even a little more...
2582 sizing_text += 'M'
2583 ## dbg('len(sizing_text):', len(sizing_text), 'sizing_text: "%s"' % sizing_text)
2584 w, h = self.GetTextExtent(sizing_text)
2585 size = (w+4, self.GetClientSize().height)
2586 ## dbg('size:', size, indent=0)
2587 return size
2588
2589
2590 def _setFont(self):
2591 """ Set the control's font typeface -- pass the font name as str."""
2592 ## dbg('MaskedEditMixin::_setFont', indent=1)
2593 if not self._useFixedWidthFont:
2594 self._font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
2595 else:
2596 font = self.GetFont() # get size, weight, etc from current font
2597
2598 # Set to teletype font (guaranteed to be mappable to all wxWindows
2599 # platforms:
2600 self._font = wx.Font( font.GetPointSize(), wx.TELETYPE, font.GetStyle(),
2601 font.GetWeight(), font.GetUnderlined())
2602 ## dbg('font string: "%s"' % font.GetNativeFontInfo().ToString())
2603
2604 self.SetFont(self._font)
2605 ## dbg(indent=0)
2606
2607
2608 def _OnTextChange(self, event):
2609 """
2610 Handler for EVT_TEXT event.
2611 self._Change() is provided for subclasses, and may return False to
2612 skip this method logic. This function returns True if the event
2613 detected was a legitimate event, or False if it was a "bogus"
2614 EVT_TEXT event. (NOTE: There is currently an issue with calling
2615 .SetValue from within the EVT_CHAR handler that causes duplicate
2616 EVT_TEXT events for the same change.)
2617 """
2618 newvalue = self._GetValue()
2619 dbg('MaskedEditMixin::_OnTextChange: value: "%s"' % newvalue, indent=1)
2620 bValid = False
2621 if self._ignoreChange: # ie. if an "intermediate text change event"
2622 dbg(indent=0)
2623 return bValid
2624
2625 ##! WS: For some inexplicable reason, every wxTextCtrl.SetValue
2626 ## call is generating two (2) EVT_TEXT events.
2627 ## This is the only mechanism I can find to mask this problem:
2628 if newvalue == self._curValue:
2629 dbg('ignoring bogus text change event', indent=0)
2630 else:
2631 dbg('curvalue: "%s", newvalue: "%s"' % (self._curValue, newvalue))
2632 if self._Change():
2633 if self._signOk and self._isNeg and newvalue.find('-') == -1 and newvalue.find('(') == -1:
2634 dbg('clearing self._isNeg')
2635 self._isNeg = False
2636 text, self._signpos, self._right_signpos = self._getSignedValue()
2637 self._CheckValid() # Recolor control as appropriate
2638 dbg('calling event.Skip()')
2639 event.Skip()
2640 bValid = True
2641 self._prevValue = self._curValue # save for undo
2642 self._curValue = newvalue # Save last seen value for next iteration
2643 dbg(indent=0)
2644 return bValid
2645
2646
2647 def _OnKeyDown(self, event):
2648 """
2649 This function allows the control to capture Ctrl-events like Ctrl-tab,
2650 that are not normally seen by the "cooked" EVT_CHAR routine.
2651 """
2652 # Get keypress value, adjusted by control options (e.g. convert to upper etc)
2653 key = event.GetKeyCode()
2654 if key in self._nav and event.ControlDown():
2655 # then this is the only place we will likely see these events;
2656 # process them now:
2657 dbg('MaskedEditMixin::OnKeyDown: calling _OnChar')
2658 self._OnChar(event)
2659 return
2660 # else allow regular EVT_CHAR key processing
2661 event.Skip()
2662
2663
2664 def _OnChar(self, event):
2665 """
2666 This is the engine of wxMaskedEdit controls. It examines each keystroke,
2667 decides if it's allowed, where it should go or what action to take.
2668 """
2669 dbg('MaskedEditMixin::_OnChar', indent=1)
2670
2671 # Get keypress value, adjusted by control options (e.g. convert to upper etc)
2672 key = event.GetKeyCode()
2673 orig_pos = self._GetInsertionPoint()
2674 orig_value = self._GetValue()
2675 dbg('keycode = ', key)
2676 dbg('current pos = ', orig_pos)
2677 dbg('current selection = ', self._GetSelection())
2678
2679 if not self._Keypress(key):
2680 dbg(indent=0)
2681 return
2682
2683 # If no format string for this control, or the control is marked as "read-only",
2684 # skip the rest of the special processing, and just "do the standard thing:"
2685 if not self._mask or not self._IsEditable():
2686 event.Skip()
2687 dbg(indent=0)
2688 return
2689
2690 # Process navigation and control keys first, with
2691 # position/selection unadulterated:
2692 if key in self._nav + self._control:
2693 if self._keyhandlers.has_key(key):
2694 keep_processing = self._keyhandlers[key](event)
2695 if self._GetValue() != orig_value:
2696 self.modified = True
2697 if not keep_processing:
2698 dbg(indent=0)
2699 return
2700 self._applyFormatting()
2701 dbg(indent=0)
2702 return
2703
2704 # Else... adjust the position as necessary for next input key,
2705 # and determine resulting selection:
2706 pos = self._adjustPos( orig_pos, key ) ## get insertion position, adjusted as needed
2707 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
2708 dbg("pos, sel_start, sel_to:", pos, sel_start, sel_to)
2709
2710 keep_processing = True
2711 # Capture user past end of format field
2712 if pos > len(self.maskdict):
2713 dbg("field length exceeded:",pos)
2714 keep_processing = False
2715
2716 if keep_processing:
2717 if self._isMaskChar(pos): ## Get string of allowed characters for validation
2718 okchars = self._getAllowedChars(pos)
2719 else:
2720 dbg('Not a valid position: pos = ', pos,"chars=",maskchars)
2721 okchars = ""
2722
2723 key = self._adjustKey(pos, key) # apply formatting constraints to key:
2724
2725 if self._keyhandlers.has_key(key):
2726 # there's an override for default behavior; use override function instead
2727 dbg('using supplied key handler:', self._keyhandlers[key])
2728 keep_processing = self._keyhandlers[key](event)
2729 if self._GetValue() != orig_value:
2730 self.modified = True
2731 if not keep_processing:
2732 dbg(indent=0)
2733 return
2734 # else skip default processing, but do final formatting
2735 if key < wx.WXK_SPACE or key > 255:
2736 dbg('key < WXK_SPACE or key > 255')
2737 event.Skip() # non alphanumeric
2738 keep_processing = False
2739 else:
2740 field = self._FindField(pos)
2741 dbg("key ='%s'" % chr(key))
2742 if chr(key) == ' ':
2743 dbg('okSpaces?', field._okSpaces)
2744
2745
2746
2747 if chr(key) in field._excludeChars + self._ctrl_constraints._excludeChars:
2748 keep_processing = False
2749
2750 if keep_processing and self._isCharAllowed( chr(key), pos, checkRegex = True ):
2751 dbg("key allowed by mask")
2752 # insert key into candidate new value, but don't change control yet:
2753 oldstr = self._GetValue()
2754 newstr, newpos, new_select_to, match_field, match_index = self._insertKey(
2755 chr(key), pos, sel_start, sel_to, self._GetValue(), allowAutoSelect = True)
2756 dbg("str with '%s' inserted:" % chr(key), '"%s"' % newstr)
2757 if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
2758 dbg('not valid; checking to see if adjusted string is:')
2759 keep_processing = False
2760 if self._isFloat and newstr != self._template:
2761 newstr = self._adjustFloat(newstr)
2762 dbg('adjusted str:', newstr)
2763 if self.IsValid(newstr):
2764 dbg("it is!")
2765 keep_processing = True
2766 wx.CallAfter(self._SetInsertionPoint, self._decimalpos)
2767 if not keep_processing:
2768 dbg("key disallowed by validation")
2769 if not wx.Validator_IsSilent() and orig_pos == pos:
2770 wx.Bell()
2771
2772 if keep_processing:
2773 unadjusted = newstr
2774
2775 # special case: adjust date value as necessary:
2776 if self._isDate and newstr != self._template:
2777 newstr = self._adjustDate(newstr)
2778 dbg('adjusted newstr:', newstr)
2779
2780 if newstr != orig_value:
2781 self.modified = True
2782
2783 wx.CallAfter(self._SetValue, newstr)
2784
2785 # Adjust insertion point on date if just entered 2 digit year, and there are now 4 digits:
2786 if not self.IsDefault() and self._isDate and self._4digityear:
2787 year2dig = self._dateExtent - 2
2788 if pos == year2dig and unadjusted[year2dig] != newstr[year2dig]:
2789 newpos = pos+2
2790
2791 wx.CallAfter(self._SetInsertionPoint, newpos)
2792
2793 if match_field is not None:
2794 dbg('matched field')
2795 self._OnAutoSelect(match_field, match_index)
2796
2797 if new_select_to != newpos:
2798 dbg('queuing selection: (%d, %d)' % (newpos, new_select_to))
2799 wx.CallAfter(self._SetSelection, newpos, new_select_to)
2800 else:
2801 newfield = self._FindField(newpos)
2802 if newfield != field and newfield._selectOnFieldEntry:
2803 dbg('queuing selection: (%d, %d)' % (newfield._extent[0], newfield._extent[1]))
2804 wx.CallAfter(self._SetSelection, newfield._extent[0], newfield._extent[1])
2805 keep_processing = False
2806
2807 elif keep_processing:
2808 dbg('char not allowed')
2809 keep_processing = False
2810 if (not wx.Validator_IsSilent()) and orig_pos == pos:
2811 wx.Bell()
2812
2813 self._applyFormatting()
2814
2815 # Move to next insertion point
2816 if keep_processing and key not in self._nav:
2817 pos = self._GetInsertionPoint()
2818 next_entry = self._findNextEntry( pos )
2819 if pos != next_entry:
2820 dbg("moving from %(pos)d to next valid entry: %(next_entry)d" % locals())
2821 wx.CallAfter(self._SetInsertionPoint, next_entry )
2822
2823 if self._isTemplateChar(pos):
2824 self._AdjustField(pos)
2825 dbg(indent=0)
2826
2827
2828 def _FindFieldExtent(self, pos=None, getslice=False, value=None):
2829 """ returns editable extent of field corresponding to
2830 position pos, and, optionally, the contents of that field
2831 in the control or the value specified.
2832 Template chars are bound to the preceding field.
2833 For masks beginning with template chars, these chars are ignored
2834 when calculating the current field.
2835
2836 Eg: with template (###) ###-####,
2837 >>> self._FindFieldExtent(pos=0)
2838 1, 4
2839 >>> self._FindFieldExtent(pos=1)
2840 1, 4
2841 >>> self._FindFieldExtent(pos=5)
2842 1, 4
2843 >>> self._FindFieldExtent(pos=6)
2844 6, 9
2845 >>> self._FindFieldExtent(pos=10)
2846 10, 14
2847 etc.
2848 """
2849 dbg('MaskedEditMixin::_FindFieldExtent(pos=%s, getslice=%s)' % (
2850 str(pos), str(getslice)) ,indent=1)
2851
2852 field = self._FindField(pos)
2853 if not field:
2854 if getslice:
2855 return None, None, ""
2856 else:
2857 return None, None
2858 edit_start, edit_end = field._extent
2859 if getslice:
2860 if value is None: value = self._GetValue()
2861 slice = value[edit_start:edit_end]
2862 dbg('edit_start:', edit_start, 'edit_end:', edit_end, 'slice: "%s"' % slice)
2863 dbg(indent=0)
2864 return edit_start, edit_end, slice
2865 else:
2866 dbg('edit_start:', edit_start, 'edit_end:', edit_end)
2867 dbg(indent=0)
2868 return edit_start, edit_end
2869
2870
2871 def _FindField(self, pos=None):
2872 """
2873 Returns the field instance in which pos resides.
2874 Template chars are bound to the preceding field.
2875 For masks beginning with template chars, these chars are ignored
2876 when calculating the current field.
2877
2878 """
2879 ## dbg('MaskedEditMixin::_FindField(pos=%s)' % str(pos) ,indent=1)
2880 if pos is None: pos = self._GetInsertionPoint()
2881 elif pos < 0 or pos > self._masklength:
2882 raise IndexError('position %s out of range of control' % str(pos))
2883
2884 if len(self._fields) == 0:
2885 dbg(indent=0)
2886 return None
2887
2888 # else...
2889 ## dbg(indent=0)
2890 return self._fields[self._lookupField[pos]]
2891
2892
2893 def ClearValue(self):
2894 """ Blanks the current control value by replacing it with the default value."""
2895 dbg("MaskedEditMixin::ClearValue - value reset to default value (template)")
2896 self._SetValue( self._template )
2897 self._SetInsertionPoint(0)
2898 self.Refresh()
2899
2900
2901 def _baseCtrlEventHandler(self, event):
2902 """
2903 This function is used whenever a key should be handled by the base control.
2904 """
2905 event.Skip()
2906 return False
2907
2908
2909 def _OnUpNumeric(self, event):
2910 """
2911 Makes up-arrow act like shift-tab should; ie. take you to start of
2912 previous field.
2913 """
2914 dbg('MaskedEditMixin::_OnUpNumeric', indent=1)
2915 event.m_shiftDown = 1
2916 dbg('event.ShiftDown()?', event.ShiftDown())
2917 self._OnChangeField(event)
2918 dbg(indent=0)
2919
2920
2921 def _OnArrow(self, event):
2922 """
2923 Used in response to left/right navigation keys; makes these actions skip
2924 over mask template chars.
2925 """
2926 dbg("MaskedEditMixin::_OnArrow", indent=1)
2927 pos = self._GetInsertionPoint()
2928 keycode = event.GetKeyCode()
2929 sel_start, sel_to = self._GetSelection()
2930 entry_end = self._goEnd(getPosOnly=True)
2931 if keycode in (wx.WXK_RIGHT, wx.WXK_DOWN):
2932 if( ( not self._isTemplateChar(pos) and pos+1 > entry_end)
2933 or ( self._isTemplateChar(pos) and pos >= entry_end) ):
2934 dbg("can't advance", indent=0)
2935 return False
2936 elif self._isTemplateChar(pos):
2937 self._AdjustField(pos)
2938 elif keycode in (wx.WXK_LEFT,wx.WXK_UP) and sel_start == sel_to and pos > 0 and self._isTemplateChar(pos-1):
2939 dbg('adjusting field')
2940 self._AdjustField(pos)
2941
2942 # treat as shifted up/down arrows as tab/reverse tab:
2943 if event.ShiftDown() and keycode in (wx.WXK_UP, wx.WXK_DOWN):
2944 # remove "shifting" and treat as (forward) tab:
2945 event.m_shiftDown = False
2946 keep_processing = self._OnChangeField(event)
2947
2948 elif self._FindField(pos)._selectOnFieldEntry:
2949 if( keycode in (wx.WXK_UP, wx.WXK_LEFT)
2950 and sel_start != 0
2951 and self._isTemplateChar(sel_start-1)
2952 and sel_start != self._masklength
2953 and not self._signOk and not self._useParens):
2954
2955 # call _OnChangeField to handle "ctrl-shifted event"
2956 # (which moves to previous field and selects it.)
2957 event.m_shiftDown = True
2958 event.m_ControlDown = True
2959 keep_processing = self._OnChangeField(event)
2960 elif( keycode in (wx.WXK_DOWN, wx.WXK_RIGHT)
2961 and sel_to != self._masklength
2962 and self._isTemplateChar(sel_to)):
2963
2964 # when changing field to the right, ensure don't accidentally go left instead
2965 event.m_shiftDown = False
2966 keep_processing = self._OnChangeField(event)
2967 else:
2968 # treat arrows as normal, allowing selection
2969 # as appropriate:
2970 dbg('using base ctrl event processing')
2971 event.Skip()
2972 else:
2973 if( (sel_to == self._fields[0]._extent[0] and keycode == wx.WXK_LEFT)
2974 or (sel_to == self._masklength and keycode == wx.WXK_RIGHT) ):
2975 if not wx.Validator_IsSilent():
2976 wx.Bell()
2977 else:
2978 # treat arrows as normal, allowing selection
2979 # as appropriate:
2980 dbg('using base event processing')
2981 event.Skip()
2982
2983 keep_processing = False
2984 dbg(indent=0)
2985 return keep_processing
2986
2987
2988 def _OnCtrl_S(self, event):
2989 """ Default Ctrl-S handler; prints value information if demo enabled. """
2990 dbg("MaskedEditMixin::_OnCtrl_S")
2991 if self._demo:
2992 print 'MaskedEditMixin.GetValue() = "%s"\nMaskedEditMixin.GetPlainValue() = "%s"' % (self.GetValue(), self.GetPlainValue())
2993 print "Valid? => " + str(self.IsValid())
2994 print "Current field, start, end, value =", str( self._FindFieldExtent(getslice=True))
2995 return False
2996
2997
2998 def _OnCtrl_X(self, event=None):
2999 """ Handles ctrl-x keypress in control and Cut operation on context menu.
3000 Should return False to skip other processing. """
3001 dbg("MaskedEditMixin::_OnCtrl_X", indent=1)
3002 self.Cut()
3003 dbg(indent=0)
3004 return False
3005
3006 def _OnCtrl_C(self, event=None):
3007 """ Handles ctrl-C keypress in control and Copy operation on context menu.
3008 Uses base control handling. Should return False to skip other processing."""
3009 self.Copy()
3010 return False
3011
3012 def _OnCtrl_V(self, event=None):
3013 """ Handles ctrl-V keypress in control and Paste operation on context menu.
3014 Should return False to skip other processing. """
3015 dbg("MaskedEditMixin::_OnCtrl_V", indent=1)
3016 self.Paste()
3017 dbg(indent=0)
3018 return False
3019
3020 def _OnCtrl_Z(self, event=None):
3021 """ Handles ctrl-Z keypress in control and Undo operation on context menu.
3022 Should return False to skip other processing. """
3023 dbg("MaskedEditMixin::_OnCtrl_Z", indent=1)
3024 self.Undo()
3025 dbg(indent=0)
3026 return False
3027
3028 def _OnCtrl_A(self,event=None):
3029 """ Handles ctrl-a keypress in control. Should return False to skip other processing. """
3030 end = self._goEnd(getPosOnly=True)
3031 if not event or event.ShiftDown():
3032 wx.CallAfter(self._SetInsertionPoint, 0)
3033 wx.CallAfter(self._SetSelection, 0, self._masklength)
3034 else:
3035 wx.CallAfter(self._SetInsertionPoint, 0)
3036 wx.CallAfter(self._SetSelection, 0, end)
3037 return False
3038
3039
3040 def _OnErase(self, event=None):
3041 """ Handles backspace and delete keypress in control. Should return False to skip other processing."""
3042 dbg("MaskedEditMixin::_OnErase", indent=1)
3043 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
3044
3045 if event is None: # called as action routine from Cut() operation.
3046 key = wx.WXK_DELETE
3047 else:
3048 key = event.GetKeyCode()
3049
3050 field = self._FindField(sel_to)
3051 start, end = field._extent
3052 value = self._GetValue()
3053 oldstart = sel_start
3054
3055 # If trying to erase beyond "legal" bounds, disallow operation:
3056 if( (sel_to == 0 and key == wx.WXK_BACK)
3057 or (self._signOk and sel_to == 1 and value[0] == ' ' and key == wx.WXK_BACK)
3058 or (sel_to == self._masklength and sel_start == sel_to and key == wx.WXK_DELETE and not field._insertRight)
3059 or (self._signOk and self._useParens
3060 and sel_start == sel_to
3061 and sel_to == self._masklength - 1
3062 and value[sel_to] == ' ' and key == wx.WXK_DELETE and not field._insertRight) ):
3063 if not wx.Validator_IsSilent():
3064 wx.Bell()
3065 dbg(indent=0)
3066 return False
3067
3068
3069 if( field._insertRight # an insert-right field
3070 and value[start:end] != self._template[start:end] # and field not empty
3071 and sel_start >= start # and selection starts in field
3072 and ((sel_to == sel_start # and no selection
3073 and sel_to == end # and cursor at right edge
3074 and key in (wx.WXK_BACK, wx.WXK_DELETE)) # and either delete or backspace key
3075 or # or
3076 (key == wx.WXK_BACK # backspacing
3077 and (sel_to == end # and selection ends at right edge
3078 or sel_to < end and field._allowInsert)) ) ): # or allow right insert at any point in field
3079
3080 dbg('delete left')
3081 # if backspace but left of cursor is empty, adjust cursor right before deleting
3082 while( key == wx.WXK_BACK
3083 and sel_start == sel_to
3084 and sel_start < end
3085 and value[start:sel_start] == self._template[start:sel_start]):
3086 sel_start += 1
3087 sel_to = sel_start
3088
3089 dbg('sel_start, start:', sel_start, start)
3090
3091 if sel_start == sel_to:
3092 keep = sel_start -1
3093 else:
3094 keep = sel_start
3095 newfield = value[start:keep] + value[sel_to:end]
3096
3097 # handle sign char moving from outside field into the field:
3098 move_sign_into_field = False
3099 if not field._padZero and self._signOk and self._isNeg and value[0] in ('-', '('):
3100 signchar = value[0]
3101 newfield = signchar + newfield
3102 move_sign_into_field = True
3103 dbg('cut newfield: "%s"' % newfield)
3104
3105 # handle what should fill in from the left:
3106 left = ""
3107 for i in range(start, end - len(newfield)):
3108 if field._padZero:
3109 left += '0'
3110 elif( self._signOk and self._isNeg and i == 1
3111 and ((self._useParens and newfield.find('(') == -1)
3112 or (not self._useParens and newfield.find('-') == -1)) ):
3113 left += ' '
3114 else:
3115 left += self._template[i] # this can produce strange results in combination with default values...
3116 newfield = left + newfield
3117 dbg('filled newfield: "%s"' % newfield)
3118
3119 newstr = value[:start] + newfield + value[end:]
3120
3121 # (handle sign located in "mask position" in front of field prior to delete)
3122 if move_sign_into_field:
3123 newstr = ' ' + newstr[1:]
3124 pos = sel_to
3125 else:
3126 # handle erasure of (left) sign, moving selection accordingly...
3127 if self._signOk and sel_start == 0:
3128 newstr = value = ' ' + value[1:]
3129 sel_start += 1
3130
3131 if field._allowInsert and sel_start >= start:
3132 # selection (if any) falls within current insert-capable field:
3133 select_len = sel_to - sel_start
3134 # determine where cursor should end up:
3135 if key == wx.WXK_BACK:
3136 if select_len == 0:
3137 newpos = sel_start -1
3138 else:
3139 newpos = sel_start
3140 erase_to = sel_to
3141 else:
3142 newpos = sel_start
3143 if sel_to == sel_start:
3144 erase_to = sel_to + 1
3145 else:
3146 erase_to = sel_to
3147
3148 if self._isTemplateChar(newpos) and select_len == 0:
3149 if self._signOk:
3150 if value[newpos] in ('(', '-'):
3151 newpos += 1 # don't move cusor
3152 newstr = ' ' + value[newpos:]
3153 elif value[newpos] == ')':
3154 # erase right sign, but don't move cursor; (matching left sign handled later)
3155 newstr = value[:newpos] + ' '
3156 else:
3157 # no deletion; just move cursor
3158 newstr = value
3159 else:
3160 # no deletion; just move cursor
3161 newstr = value
3162 else:
3163 if erase_to > end: erase_to = end
3164 erase_len = erase_to - newpos
3165
3166 left = value[start:newpos]
3167 dbg("retained ='%s'" % value[erase_to:end], 'sel_to:', sel_to, "fill: '%s'" % self._template[end - erase_len:end])
3168 right = value[erase_to:end] + self._template[end-erase_len:end]
3169 pos_adjust = 0
3170 if field._alignRight:
3171 rstripped = right.rstrip()
3172 if rstripped != right:
3173 pos_adjust = len(right) - len(rstripped)
3174 right = rstripped
3175
3176 if not field._insertRight and value[-1] == ')' and end == self._masklength - 1:
3177 # need to shift ) into the field:
3178 right = right[:-1] + ')'
3179 value = value[:-1] + ' '
3180
3181 newfield = left+right
3182 if pos_adjust:
3183 newfield = newfield.rjust(end-start)
3184 newpos += pos_adjust
3185 dbg("left='%s', right ='%s', newfield='%s'" %(left, right, newfield))
3186 newstr = value[:start] + newfield + value[end:]
3187
3188 pos = newpos
3189
3190 else:
3191 if sel_start == sel_to:
3192 dbg("current sel_start, sel_to:", sel_start, sel_to)
3193 if key == wx.WXK_BACK:
3194 sel_start, sel_to = sel_to-1, sel_to-1
3195 dbg("new sel_start, sel_to:", sel_start, sel_to)
3196
3197 if field._padZero and not value[start:sel_to].replace('0', '').replace(' ','').replace(field._fillChar, ''):
3198 # preceding chars (if any) are zeros, blanks or fillchar; new char should be 0:
3199 newchar = '0'
3200 else:
3201 newchar = self._template[sel_to] ## get an original template character to "clear" the current char
3202 dbg('value = "%s"' % value, 'value[%d] = "%s"' %(sel_start, value[sel_start]))
3203
3204 if self._isTemplateChar(sel_to):
3205 if sel_to == 0 and self._signOk and value[sel_to] == '-': # erasing "template" sign char
3206 newstr = ' ' + value[1:]
3207 sel_to += 1
3208 elif self._signOk and self._useParens and (value[sel_to] == ')' or value[sel_to] == '('):
3209 # allow "change sign" by removing both parens:
3210 newstr = value[:self._signpos] + ' ' + value[self._signpos+1:-1] + ' '
3211 else:
3212 newstr = value
3213 newpos = sel_to
3214 else:
3215 if field._insertRight and sel_start == sel_to:
3216 # force non-insert-right behavior, by selecting char to be replaced:
3217 sel_to += 1
3218 newstr, ignore = self._insertKey(newchar, sel_start, sel_start, sel_to, value)
3219
3220 else:
3221 # selection made
3222 newstr = self._eraseSelection(value, sel_start, sel_to)
3223
3224 pos = sel_start # put cursor back at beginning of selection
3225
3226 if self._signOk and self._useParens:
3227 # account for resultant unbalanced parentheses:
3228 left_signpos = newstr.find('(')
3229 right_signpos = newstr.find(')')
3230
3231 if left_signpos == -1 and right_signpos != -1:
3232 # erased left-sign marker; get rid of right sign marker:
3233 newstr = newstr[:right_signpos] + ' ' + newstr[right_signpos+1:]
3234
3235 elif left_signpos != -1 and right_signpos == -1:
3236 # erased right-sign marker; get rid of left-sign marker:
3237 newstr = newstr[:left_signpos] + ' ' + newstr[left_signpos+1:]
3238
3239 dbg("oldstr:'%s'" % value, 'oldpos:', oldstart)
3240 dbg("newstr:'%s'" % newstr, 'pos:', pos)
3241
3242 # if erasure results in an invalid field, disallow it:
3243 dbg('field._validRequired?', field._validRequired)
3244 dbg('field.IsValid("%s")?' % newstr[start:end], field.IsValid(newstr[start:end]))
3245 if field._validRequired and not field.IsValid(newstr[start:end]):
3246 if not wx.Validator_IsSilent():
3247 wx.Bell()
3248 dbg(indent=0)
3249 return False
3250
3251 # if erasure results in an invalid value, disallow it:
3252 if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
3253 if not wx.Validator_IsSilent():
3254 wx.Bell()
3255 dbg(indent=0)
3256 return False
3257
3258 dbg('setting value (later) to', newstr)
3259 wx.CallAfter(self._SetValue, newstr)
3260 dbg('setting insertion point (later) to', pos)
3261 wx.CallAfter(self._SetInsertionPoint, pos)
3262 dbg(indent=0)
3263 return False
3264
3265
3266 def _OnEnd(self,event):
3267 """ Handles End keypress in control. Should return False to skip other processing. """
3268 dbg("MaskedEditMixin::_OnEnd", indent=1)
3269 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3270 if not event.ControlDown():
3271 end = self._masklength # go to end of control
3272 if self._signOk and self._useParens:
3273 end = end - 1 # account for reserved char at end
3274 else:
3275 end_of_input = self._goEnd(getPosOnly=True)
3276 sel_start, sel_to = self._GetSelection()
3277 if sel_to < pos: sel_to = pos
3278 field = self._FindField(sel_to)
3279 field_end = self._FindField(end_of_input)
3280
3281 # pick different end point if either:
3282 # - cursor not in same field
3283 # - or at or past last input already
3284 # - or current selection = end of current field:
3285 ## dbg('field != field_end?', field != field_end)
3286 ## dbg('sel_to >= end_of_input?', sel_to >= end_of_input)
3287 if field != field_end or sel_to >= end_of_input:
3288 edit_start, edit_end = field._extent
3289 ## dbg('edit_end:', edit_end)
3290 ## dbg('sel_to:', sel_to)
3291 ## dbg('sel_to == edit_end?', sel_to == edit_end)
3292 ## dbg('field._index < self._field_indices[-1]?', field._index < self._field_indices[-1])
3293
3294 if sel_to == edit_end and field._index < self._field_indices[-1]:
3295 edit_start, edit_end = self._FindFieldExtent(self._findNextEntry(edit_end)) # go to end of next field:
3296 end = edit_end
3297 dbg('end moved to', end)
3298
3299 elif sel_to == edit_end and field._index == self._field_indices[-1]:
3300 # already at edit end of last field; select to end of control:
3301 end = self._masklength
3302 dbg('end moved to', end)
3303 else:
3304 end = edit_end # select to end of current field
3305 dbg('end moved to ', end)
3306 else:
3307 # select to current end of input
3308 end = end_of_input
3309
3310
3311 ## dbg('pos:', pos, 'end:', end)
3312
3313 if event.ShiftDown():
3314 if not event.ControlDown():
3315 dbg("shift-end; select to end of control")
3316 else:
3317 dbg("shift-ctrl-end; select to end of non-whitespace")
3318 wx.CallAfter(self._SetInsertionPoint, pos)
3319 wx.CallAfter(self._SetSelection, pos, end)
3320 else:
3321 if not event.ControlDown():
3322 dbg('go to end of control:')
3323 wx.CallAfter(self._SetInsertionPoint, end)
3324 wx.CallAfter(self._SetSelection, end, end)
3325
3326 dbg(indent=0)
3327 return False
3328
3329
3330 def _OnReturn(self, event):
3331 """
3332 Changes the event to look like a tab event, so we can then call
3333 event.Skip() on it, and have the parent form "do the right thing."
3334 """
3335 dbg('MaskedEditMixin::OnReturn')
3336 event.m_keyCode = wx.WXK_TAB
3337 event.Skip()
3338
3339
3340 def _OnHome(self,event):
3341 """ Handles Home keypress in control. Should return False to skip other processing."""
3342 dbg("MaskedEditMixin::_OnHome", indent=1)
3343 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3344 sel_start, sel_to = self._GetSelection()
3345
3346 # There are 5 cases here:
3347
3348 # 1) shift: select from start of control to end of current
3349 # selection.
3350 if event.ShiftDown() and not event.ControlDown():
3351 dbg("shift-home; select to start of control")
3352 start = 0
3353 end = sel_start
3354
3355 # 2) no shift, no control: move cursor to beginning of control.
3356 elif not event.ControlDown():
3357 dbg("home; move to start of control")
3358 start = 0
3359 end = 0
3360
3361 # 3) No shift, control: move cursor back to beginning of field; if
3362 # there already, go to beginning of previous field.
3363 # 4) shift, control, start of selection not at beginning of control:
3364 # move sel_start back to start of field; if already there, go to
3365 # start of previous field.
3366 elif( event.ControlDown()
3367 and (not event.ShiftDown()
3368 or (event.ShiftDown() and sel_start > 0) ) ):
3369 if len(self._field_indices) > 1:
3370 field = self._FindField(sel_start)
3371 start, ignore = field._extent
3372 if sel_start == start and field._index != self._field_indices[0]: # go to start of previous field:
3373 start, ignore = self._FindFieldExtent(sel_start-1)
3374 elif sel_start == start:
3375 start = 0 # go to literal beginning if edit start
3376 # not at that point
3377 end_of_field = True
3378
3379 else:
3380 start = 0
3381
3382 if not event.ShiftDown():
3383 dbg("ctrl-home; move to beginning of field")
3384 end = start
3385 else:
3386 dbg("shift-ctrl-home; select to beginning of field")
3387 end = sel_to
3388
3389 else:
3390 # 5) shift, control, start of selection at beginning of control:
3391 # unselect by moving sel_to backward to beginning of current field;
3392 # if already there, move to start of previous field.
3393 start = sel_start
3394 if len(self._field_indices) > 1:
3395 # find end of previous field:
3396 field = self._FindField(sel_to)
3397 if sel_to > start and field._index != self._field_indices[0]:
3398 ignore, end = self._FindFieldExtent(field._extent[0]-1)
3399 else:
3400 end = start
3401 end_of_field = True
3402 else:
3403 end = start
3404 end_of_field = False
3405 dbg("shift-ctrl-home; unselect to beginning of field")
3406
3407 dbg('queuing new sel_start, sel_to:', (start, end))
3408 wx.CallAfter(self._SetInsertionPoint, start)
3409 wx.CallAfter(self._SetSelection, start, end)
3410 dbg(indent=0)
3411 return False
3412
3413
3414 def _OnChangeField(self, event):
3415 """
3416 Primarily handles TAB events, but can be used for any key that
3417 designer wants to change fields within a masked edit control.
3418 NOTE: at the moment, although coded to handle shift-TAB and
3419 control-shift-TAB, these events are not sent to the controls
3420 by the framework.
3421 """
3422 dbg('MaskedEditMixin::_OnChangeField', indent = 1)
3423 # determine end of current field:
3424 pos = self._GetInsertionPoint()
3425 dbg('current pos:', pos)
3426 sel_start, sel_to = self._GetSelection()
3427
3428 if self._masklength < 0: # no fields; process tab normally
3429 self._AdjustField(pos)
3430 if event.GetKeyCode() == wx.WXK_TAB:
3431 dbg('tab to next ctrl')
3432 event.Skip()
3433 #else: do nothing
3434 dbg(indent=0)
3435 return False
3436
3437
3438 if event.ShiftDown():
3439
3440 # "Go backward"
3441
3442 # NOTE: doesn't yet work with SHIFT-tab under wx; the control
3443 # never sees this event! (But I've coded for it should it ever work,
3444 # and it *does* work for '.' in IpAddrCtrl.)
3445 field = self._FindField(pos)
3446 index = field._index
3447 field_start = field._extent[0]
3448 if pos < field_start:
3449 dbg('cursor before 1st field; cannot change to a previous field')
3450 if not wx.Validator_IsSilent():
3451 wx.Bell()
3452 return False
3453
3454 if event.ControlDown():
3455 dbg('queuing select to beginning of field:', field_start, pos)
3456 wx.CallAfter(self._SetInsertionPoint, field_start)
3457 wx.CallAfter(self._SetSelection, field_start, pos)
3458 dbg(indent=0)
3459 return False
3460
3461 elif index == 0:
3462 # We're already in the 1st field; process shift-tab normally:
3463 self._AdjustField(pos)
3464 if event.GetKeyCode() == wx.WXK_TAB:
3465 dbg('tab to previous ctrl')
3466 event.Skip()
3467 else:
3468 dbg('position at beginning')
3469 wx.CallAfter(self._SetInsertionPoint, field_start)
3470 dbg(indent=0)
3471 return False
3472 else:
3473 # find beginning of previous field:
3474 begin_prev = self._FindField(field_start-1)._extent[0]
3475 self._AdjustField(pos)
3476 dbg('repositioning to', begin_prev)
3477 wx.CallAfter(self._SetInsertionPoint, begin_prev)
3478 if self._FindField(begin_prev)._selectOnFieldEntry:
3479 edit_start, edit_end = self._FindFieldExtent(begin_prev)
3480 dbg('queuing selection to (%d, %d)' % (edit_start, edit_end))
3481 wx.CallAfter(self._SetInsertionPoint, edit_start)
3482 wx.CallAfter(self._SetSelection, edit_start, edit_end)
3483 dbg(indent=0)
3484 return False
3485
3486 else:
3487 # "Go forward"
3488 field = self._FindField(sel_to)
3489 field_start, field_end = field._extent
3490 if event.ControlDown():
3491 dbg('queuing select to end of field:', pos, field_end)
3492 wx.CallAfter(self._SetInsertionPoint, pos)
3493 wx.CallAfter(self._SetSelection, pos, field_end)
3494 dbg(indent=0)
3495 return False
3496 else:
3497 if pos < field_start:
3498 dbg('cursor before 1st field; go to start of field')
3499 wx.CallAfter(self._SetInsertionPoint, field_start)
3500 if field._selectOnFieldEntry:
3501 wx.CallAfter(self._SetSelection, field_start, field_end)
3502 else:
3503 wx.CallAfter(self._SetSelection, field_start, field_start)
3504 return False
3505 # else...
3506 dbg('end of current field:', field_end)
3507 dbg('go to next field')
3508 if field_end == self._fields[self._field_indices[-1]]._extent[1]:
3509 self._AdjustField(pos)
3510 if event.GetKeyCode() == wx.WXK_TAB:
3511 dbg('tab to next ctrl')
3512 event.Skip()
3513 else:
3514 dbg('position at end')
3515 wx.CallAfter(self._SetInsertionPoint, field_end)
3516 dbg(indent=0)
3517 return False
3518 else:
3519 # we have to find the start of the next field
3520 next_pos = self._findNextEntry(field_end)
3521 if next_pos == field_end:
3522 dbg('already in last field')
3523 self._AdjustField(pos)
3524 if event.GetKeyCode() == wx.WXK_TAB:
3525 dbg('tab to next ctrl')
3526 event.Skip()
3527 #else: do nothing
3528 dbg(indent=0)
3529 return False
3530 else:
3531 self._AdjustField( pos )
3532
3533 # move cursor to appropriate point in the next field and select as necessary:
3534 field = self._FindField(next_pos)
3535 edit_start, edit_end = field._extent
3536 if field._selectOnFieldEntry:
3537 dbg('move to ', next_pos)
3538 wx.CallAfter(self._SetInsertionPoint, next_pos)
3539 edit_start, edit_end = self._FindFieldExtent(next_pos)
3540 dbg('queuing select', edit_start, edit_end)
3541 wx.CallAfter(self._SetSelection, edit_start, edit_end)
3542 else:
3543 if field._insertRight:
3544 next_pos = field._extent[1]
3545 dbg('move to ', next_pos)
3546 wx.CallAfter(self._SetInsertionPoint, next_pos)
3547 dbg(indent=0)
3548 return False
3549
3550
3551 def _OnDecimalPoint(self, event):
3552 dbg('MaskedEditMixin::_OnDecimalPoint', indent=1)
3553
3554 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3555
3556 if self._isFloat: ## handle float value, move to decimal place
3557 dbg('key == Decimal tab; decimal pos:', self._decimalpos)
3558 value = self._GetValue()
3559 if pos < self._decimalpos:
3560 clipped_text = value[0:pos] + self._decimalChar + value[self._decimalpos+1:]
3561 dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text)
3562 newstr = self._adjustFloat(clipped_text)
3563 else:
3564 newstr = self._adjustFloat(value)
3565 wx.CallAfter(self._SetValue, newstr)
3566 fraction = self._fields[1]
3567 start, end = fraction._extent
3568 wx.CallAfter(self._SetInsertionPoint, start)
3569 if fraction._selectOnFieldEntry:
3570 dbg('queuing selection after decimal point to:', (start, end))
3571 wx.CallAfter(self._SetSelection, start, end)
3572 keep_processing = False
3573
3574 if self._isInt: ## handle integer value, truncate from current position
3575 dbg('key == Integer decimal event')
3576 value = self._GetValue()
3577 clipped_text = value[0:pos]
3578 dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text)
3579 newstr = self._adjustInt(clipped_text)
3580 dbg('newstr: "%s"' % newstr)
3581 wx.CallAfter(self._SetValue, newstr)
3582 newpos = len(newstr.rstrip())
3583 if newstr.find(')') != -1:
3584 newpos -= 1 # (don't move past right paren)
3585 wx.CallAfter(self._SetInsertionPoint, newpos)
3586 keep_processing = False
3587 dbg(indent=0)
3588
3589
3590 def _OnChangeSign(self, event):
3591 dbg('MaskedEditMixin::_OnChangeSign', indent=1)
3592 key = event.GetKeyCode()
3593 pos = self._adjustPos(self._GetInsertionPoint(), key)
3594 value = self._eraseSelection()
3595 integer = self._fields[0]
3596 start, end = integer._extent
3597
3598 ## dbg('adjusted pos:', pos)
3599 if chr(key) in ('-','+','(', ')') or (chr(key) == " " and pos == self._signpos):
3600 cursign = self._isNeg
3601 dbg('cursign:', cursign)
3602 if chr(key) in ('-','(', ')'):
3603 self._isNeg = (not self._isNeg) ## flip value
3604 else:
3605 self._isNeg = False
3606 dbg('isNeg?', self._isNeg)
3607
3608 text, self._signpos, self._right_signpos = self._getSignedValue(candidate=value)
3609 dbg('text:"%s"' % text, 'signpos:', self._signpos, 'right_signpos:', self._right_signpos)
3610 if text is None:
3611 text = value
3612
3613 if self._isNeg and self._signpos is not None and self._signpos != -1:
3614 if self._useParens and self._right_signpos is not None:
3615 text = text[:self._signpos] + '(' + text[self._signpos+1:self._right_signpos] + ')' + text[self._right_signpos+1:]
3616 else:
3617 text = text[:self._signpos] + '-' + text[self._signpos+1:]
3618 else:
3619 ## dbg('self._isNeg?', self._isNeg, 'self.IsValid(%s)' % text, self.IsValid(text))
3620 if self._useParens:
3621 text = text[:self._signpos] + ' ' + text[self._signpos+1:self._right_signpos] + ' ' + text[self._right_signpos+1:]
3622 else:
3623 text = text[:self._signpos] + ' ' + text[self._signpos+1:]
3624 dbg('clearing self._isNeg')
3625 self._isNeg = False
3626
3627 wx.CallAfter(self._SetValue, text)
3628 wx.CallAfter(self._applyFormatting)
3629 dbg('pos:', pos, 'signpos:', self._signpos)
3630 if pos == self._signpos or integer.IsEmpty(text[start:end]):
3631 wx.CallAfter(self._SetInsertionPoint, self._signpos+1)
3632 else:
3633 wx.CallAfter(self._SetInsertionPoint, pos)
3634
3635 keep_processing = False
3636 else:
3637 keep_processing = True
3638 dbg(indent=0)
3639 return keep_processing
3640
3641
3642 def _OnGroupChar(self, event):
3643 """
3644 This handler is only registered if the mask is a numeric mask.
3645 It allows the insertion of ',' or '.' if appropriate.
3646 """
3647 dbg('MaskedEditMixin::_OnGroupChar', indent=1)
3648 keep_processing = True
3649 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
3650 sel_start, sel_to = self._GetSelection()
3651 groupchar = self._fields[0]._groupChar
3652 if not self._isCharAllowed(groupchar, pos, checkRegex=True):
3653 keep_processing = False
3654 if not wx.Validator_IsSilent():
3655 wx.Bell()
3656
3657 if keep_processing:
3658 newstr, newpos = self._insertKey(groupchar, pos, sel_start, sel_to, self._GetValue() )
3659 dbg("str with '%s' inserted:" % groupchar, '"%s"' % newstr)
3660 if self._ctrl_constraints._validRequired and not self.IsValid(newstr):
3661 keep_processing = False
3662 if not wx.Validator_IsSilent():
3663 wx.Bell()
3664
3665 if keep_processing:
3666 wx.CallAfter(self._SetValue, newstr)
3667 wx.CallAfter(self._SetInsertionPoint, newpos)
3668 keep_processing = False
3669 dbg(indent=0)
3670 return keep_processing
3671
3672
3673 def _findNextEntry(self,pos, adjustInsert=True):
3674 """ Find the insertion point for the next valid entry character position."""
3675 if self._isTemplateChar(pos): # if changing fields, pay attn to flag
3676 adjustInsert = adjustInsert
3677 else: # else within a field; flag not relevant
3678 adjustInsert = False
3679
3680 while self._isTemplateChar(pos) and pos < self._masklength:
3681 pos += 1
3682
3683 # if changing fields, and we've been told to adjust insert point,
3684 # look at new field; if empty and right-insert field,
3685 # adjust to right edge:
3686 if adjustInsert and pos < self._masklength:
3687 field = self._FindField(pos)
3688 start, end = field._extent
3689 slice = self._GetValue()[start:end]
3690 if field._insertRight and field.IsEmpty(slice):
3691 pos = end
3692 return pos
3693
3694
3695 def _findNextTemplateChar(self, pos):
3696 """ Find the position of the next non-editable character in the mask."""
3697 while not self._isTemplateChar(pos) and pos < self._masklength:
3698 pos += 1
3699 return pos
3700
3701
3702 def _OnAutoCompleteField(self, event):
3703 dbg('MaskedEditMixin::_OnAutoCompleteField', indent =1)
3704 pos = self._GetInsertionPoint()
3705 field = self._FindField(pos)
3706 edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
3707
3708 match_index = None
3709 keycode = event.GetKeyCode()
3710
3711 if field._fillChar != ' ':
3712 text = slice.replace(field._fillChar, '')
3713 else:
3714 text = slice
3715 text = text.strip()
3716 keep_processing = True # (assume True to start)
3717 dbg('field._hasList?', field._hasList)
3718 if field._hasList:
3719 dbg('choices:', field._choices)
3720 dbg('compareChoices:', field._compareChoices)
3721 choices, choice_required = field._compareChoices, field._choiceRequired
3722 if keycode in (wx.WXK_PRIOR, wx.WXK_UP):
3723 direction = -1
3724 else:
3725 direction = 1
3726 match_index, partial_match = self._autoComplete(direction, choices, text, compareNoCase=field._compareNoCase, current_index = field._autoCompleteIndex)
3727 if( match_index is None
3728 and (keycode in self._autoCompleteKeycodes + [wx.WXK_PRIOR, wx.WXK_NEXT]
3729 or (keycode in [wx.WXK_UP, wx.WXK_DOWN] and event.ShiftDown() ) ) ):
3730 # Select the 1st thing from the list:
3731 match_index = 0
3732
3733 if( match_index is not None
3734 and ( keycode in self._autoCompleteKeycodes + [wx.WXK_PRIOR, wx.WXK_NEXT]
3735 or (keycode in [wx.WXK_UP, wx.WXK_DOWN] and event.ShiftDown())
3736 or (keycode == wx.WXK_DOWN and partial_match) ) ):
3737
3738 # We're allowed to auto-complete:
3739 dbg('match found')
3740 value = self._GetValue()
3741 newvalue = value[:edit_start] + field._choices[match_index] + value[edit_end:]
3742 dbg('setting value to "%s"' % newvalue)
3743 self._SetValue(newvalue)
3744 self._SetInsertionPoint(min(edit_end, len(newvalue.rstrip())))
3745 self._OnAutoSelect(field, match_index)
3746 self._CheckValid() # recolor as appopriate
3747
3748
3749 if keycode in (wx.WXK_UP, wx.WXK_DOWN, wx.WXK_LEFT, wx.WXK_RIGHT):
3750 # treat as left right arrow if unshifted, tab/shift tab if shifted.
3751 if event.ShiftDown():
3752 if keycode in (wx.WXK_DOWN, wx.WXK_RIGHT):
3753 # remove "shifting" and treat as (forward) tab:
3754 event.m_shiftDown = False
3755 keep_processing = self._OnChangeField(event)
3756 else:
3757 keep_processing = self._OnArrow(event)
3758 # else some other key; keep processing the key
3759
3760 dbg('keep processing?', keep_processing, indent=0)
3761 return keep_processing
3762
3763
3764 def _OnAutoSelect(self, field, match_index = None):
3765 """
3766 Function called if autoselect feature is enabled and entire control
3767 is selected:
3768 """
3769 dbg('MaskedEditMixin::OnAutoSelect', field._index)
3770 if match_index is not None:
3771 field._autoCompleteIndex = match_index
3772
3773
3774 def _autoComplete(self, direction, choices, value, compareNoCase, current_index):
3775 """
3776 This function gets called in response to Auto-complete events.
3777 It attempts to find a match to the specified value against the
3778 list of choices; if exact match, the index of then next
3779 appropriate value in the list, based on the given direction.
3780 If not an exact match, it will return the index of the 1st value from
3781 the choice list for which the partial value can be extended to match.
3782 If no match found, it will return None.
3783 The function returns a 2-tuple, with the 2nd element being a boolean
3784 that indicates if partial match was necessary.
3785 """
3786 dbg('autoComplete(direction=', direction, 'choices=',choices, 'value=',value,'compareNoCase?', compareNoCase, 'current_index:', current_index, indent=1)
3787 if value is None:
3788 dbg('nothing to match against', indent=0)
3789 return (None, False)
3790
3791 partial_match = False
3792
3793 if compareNoCase:
3794 value = value.lower()
3795
3796 last_index = len(choices) - 1
3797 if value in choices:
3798 dbg('"%s" in', choices)
3799 if current_index is not None and choices[current_index] == value:
3800 index = current_index
3801 else:
3802 index = choices.index(value)
3803
3804 dbg('matched "%s" (%d)' % (choices[index], index))
3805 if direction == -1:
3806 dbg('going to previous')
3807 if index == 0: index = len(choices) - 1
3808 else: index -= 1
3809 else:
3810 if index == len(choices) - 1: index = 0
3811 else: index += 1
3812 dbg('change value to "%s" (%d)' % (choices[index], index))
3813 match = index
3814 else:
3815 partial_match = True
3816 value = value.strip()
3817 dbg('no match; try to auto-complete:')
3818 match = None
3819 dbg('searching for "%s"' % value)
3820 if current_index is None:
3821 indices = range(len(choices))
3822 if direction == -1:
3823 indices.reverse()
3824 else:
3825 if direction == 1:
3826 indices = range(current_index +1, len(choices)) + range(current_index+1)
3827 dbg('range(current_index+1 (%d), len(choices) (%d)) + range(%d):' % (current_index+1, len(choices), current_index+1), indices)
3828 else:
3829 indices = range(current_index-1, -1, -1) + range(len(choices)-1, current_index-1, -1)
3830 dbg('range(current_index-1 (%d), -1) + range(len(choices)-1 (%d)), current_index-1 (%d):' % (current_index-1, len(choices)-1, current_index-1), indices)
3831 ## dbg('indices:', indices)
3832 for index in indices:
3833 choice = choices[index]
3834 if choice.find(value, 0) == 0:
3835 dbg('match found:', choice)
3836 match = index
3837 break
3838 else: dbg('choice: "%s" - no match' % choice)
3839 if match is not None:
3840 dbg('matched', match)
3841 else:
3842 dbg('no match found')
3843 dbg(indent=0)
3844 return (match, partial_match)
3845
3846
3847 def _AdjustField(self, pos):
3848 """
3849 This function gets called by default whenever the cursor leaves a field.
3850 The pos argument given is the char position before leaving that field.
3851 By default, floating point, integer and date values are adjusted to be
3852 legal in this function. Derived classes may override this function
3853 to modify the value of the control in a different way when changing fields.
3854
3855 NOTE: these change the value immediately, and restore the cursor to
3856 the passed location, so that any subsequent code can then move it
3857 based on the operation being performed.
3858 """
3859 newvalue = value = self._GetValue()
3860 field = self._FindField(pos)
3861 start, end, slice = self._FindFieldExtent(getslice=True)
3862 newfield = field._AdjustField(slice)
3863 newvalue = value[:start] + newfield + value[end:]
3864
3865 if self._isFloat and newvalue != self._template:
3866 newvalue = self._adjustFloat(newvalue)
3867
3868 if self._ctrl_constraints._isInt and value != self._template:
3869 newvalue = self._adjustInt(value)
3870
3871 if self._isDate and value != self._template:
3872 newvalue = self._adjustDate(value, fixcentury=True)
3873 if self._4digityear:
3874 year2dig = self._dateExtent - 2
3875 if pos == year2dig and value[year2dig] != newvalue[year2dig]:
3876 pos = pos+2
3877
3878 if newvalue != value:
3879 self._SetValue(newvalue)
3880 self._SetInsertionPoint(pos)
3881
3882
3883 def _adjustKey(self, pos, key):
3884 """ Apply control formatting to the key (e.g. convert to upper etc). """
3885 field = self._FindField(pos)
3886 if field._forceupper and key in range(97,123):
3887 key = ord( chr(key).upper())
3888
3889 if field._forcelower and key in range(97,123):
3890 key = ord( chr(key).lower())
3891
3892 return key
3893
3894
3895 def _adjustPos(self, pos, key):
3896 """
3897 Checks the current insertion point position and adjusts it if
3898 necessary to skip over non-editable characters.
3899 """
3900 dbg('_adjustPos', pos, key, indent=1)
3901 sel_start, sel_to = self._GetSelection()
3902 # If a numeric or decimal mask, and negatives allowed, reserve the
3903 # first space for sign, and last one if using parens.
3904 if( self._signOk
3905 and ((pos == self._signpos and key in (ord('-'), ord('+'), ord(' ')) )
3906 or self._useParens and pos == self._masklength -1)):
3907 dbg('adjusted pos:', pos, indent=0)
3908 return pos
3909
3910 if key not in self._nav:
3911 field = self._FindField(pos)
3912
3913 dbg('field._insertRight?', field._insertRight)
3914 if field._insertRight: # if allow right-insert
3915 start, end = field._extent
3916 slice = self._GetValue()[start:end].strip()
3917 field_len = end - start
3918 if pos == end: # if cursor at right edge of field
3919 # if not filled or supposed to stay in field, keep current position
3920 ## dbg('pos==end')
3921 ## dbg('len (slice):', len(slice))
3922 ## dbg('field_len?', field_len)
3923 ## dbg('pos==end; len (slice) < field_len?', len(slice) < field_len)
3924 ## dbg('not field._moveOnFieldFull?', not field._moveOnFieldFull)
3925 if len(slice) == field_len and field._moveOnFieldFull:
3926 # move cursor to next field:
3927 pos = self._findNextEntry(pos)
3928 self._SetInsertionPoint(pos)
3929 if pos < sel_to:
3930 self._SetSelection(pos, sel_to) # restore selection
3931 else:
3932 self._SetSelection(pos, pos) # remove selection
3933 else: # leave cursor alone
3934 pass
3935 else:
3936 # if at start of control, move to right edge
3937 if sel_to == sel_start and self._isTemplateChar(pos) and pos != end:
3938 pos = end # move to right edge
3939 ## elif sel_start <= start and sel_to == end:
3940 ## # select to right edge of field - 1 (to replace char)
3941 ## pos = end - 1
3942 ## self._SetInsertionPoint(pos)
3943 ## # restore selection
3944 ## self._SetSelection(sel_start, pos)
3945
3946 elif self._signOk and sel_start == 0: # if selected to beginning and signed,
3947 # adjust to past reserved sign position:
3948 pos = self._fields[0]._extent[0]
3949 self._SetInsertionPoint(pos)
3950 # restore selection
3951 self._SetSelection(pos, sel_to)
3952 else:
3953 pass # leave position/selection alone
3954
3955 # else make sure the user is not trying to type over a template character
3956 # If they are, move them to the next valid entry position
3957 elif self._isTemplateChar(pos):
3958 if( not field._moveOnFieldFull
3959 and (not self._signOk
3960 or (self._signOk
3961 and field._index == 0
3962 and pos > 0) ) ): # don't move to next field without explicit cursor movement
3963 pass
3964 else:
3965 # find next valid position
3966 pos = self._findNextEntry(pos)
3967 self._SetInsertionPoint(pos)
3968 if pos < sel_to: # restore selection
3969 self._SetSelection(pos, sel_to)
3970 dbg('adjusted pos:', pos, indent=0)
3971 return pos
3972
3973
3974 def _adjustFloat(self, candidate=None):
3975 """
3976 'Fixes' an floating point control. Collapses spaces, right-justifies, etc.
3977 """
3978 dbg('MaskedEditMixin::_adjustFloat, candidate = "%s"' % candidate, indent=1)
3979 lenInt,lenFraction = [len(s) for s in self._mask.split('.')] ## Get integer, fraction lengths
3980
3981 if candidate is None: value = self._GetValue()
3982 else: value = candidate
3983 dbg('value = "%(value)s"' % locals(), 'len(value):', len(value))
3984 intStr, fracStr = value.split(self._decimalChar)
3985
3986 intStr = self._fields[0]._AdjustField(intStr)
3987 dbg('adjusted intStr: "%s"' % intStr)
3988 lenInt = len(intStr)
3989 fracStr = fracStr + ('0'*(lenFraction-len(fracStr))) # add trailing spaces to decimal
3990
3991 dbg('intStr "%(intStr)s"' % locals())
3992 dbg('lenInt:', lenInt)
3993
3994 intStr = string.rjust( intStr[-lenInt:], lenInt)
3995 dbg('right-justifed intStr = "%(intStr)s"' % locals())
3996 newvalue = intStr + self._decimalChar + fracStr
3997
3998 if self._signOk:
3999 if len(newvalue) < self._masklength:
4000 newvalue = ' ' + newvalue
4001 signedvalue = self._getSignedValue(newvalue)[0]
4002 if signedvalue is not None: newvalue = signedvalue
4003
4004 # Finally, align string with decimal position, left-padding with
4005 # fillChar:
4006 newdecpos = newvalue.find(self._decimalChar)
4007 if newdecpos < self._decimalpos:
4008 padlen = self._decimalpos - newdecpos
4009 newvalue = string.join([' ' * padlen] + [newvalue] ,'')
4010
4011 if self._signOk and self._useParens:
4012 if newvalue.find('(') != -1:
4013 newvalue = newvalue[:-1] + ')'
4014 else:
4015 newvalue = newvalue[:-1] + ' '
4016
4017 dbg('newvalue = "%s"' % newvalue)
4018 if candidate is None:
4019 wx.CallAfter(self._SetValue, newvalue)
4020 dbg(indent=0)
4021 return newvalue
4022
4023
4024 def _adjustInt(self, candidate=None):
4025 """ 'Fixes' an integer control. Collapses spaces, right or left-justifies."""
4026 dbg("MaskedEditMixin::_adjustInt", candidate)
4027 lenInt = self._masklength
4028 if candidate is None: value = self._GetValue()
4029 else: value = candidate
4030
4031 intStr = self._fields[0]._AdjustField(value)
4032 intStr = intStr.strip() # drop extra spaces
4033 dbg('adjusted field: "%s"' % intStr)
4034
4035 if self._isNeg and intStr.find('-') == -1 and intStr.find('(') == -1:
4036 if self._useParens:
4037 intStr = '(' + intStr + ')'
4038 else:
4039 intStr = '-' + intStr
4040 elif self._isNeg and intStr.find('-') != -1 and self._useParens:
4041 intStr = intStr.replace('-', '(')
4042
4043 if( self._signOk and ((self._useParens and intStr.find('(') == -1)
4044 or (not self._useParens and intStr.find('-') == -1))):
4045 intStr = ' ' + intStr
4046 if self._useParens:
4047 intStr += ' ' # space for right paren position
4048
4049 elif self._signOk and self._useParens and intStr.find('(') != -1 and intStr.find(')') == -1:
4050 # ensure closing right paren:
4051 intStr += ')'
4052
4053 if self._fields[0]._alignRight: ## Only if right-alignment is enabled
4054 intStr = intStr.rjust( lenInt )
4055 else:
4056 intStr = intStr.ljust( lenInt )
4057
4058 if candidate is None:
4059 wx.CallAfter(self._SetValue, intStr )
4060 return intStr
4061
4062
4063 def _adjustDate(self, candidate=None, fixcentury=False, force4digit_year=False):
4064 """
4065 'Fixes' a date control, expanding the year if it can.
4066 Applies various self-formatting options.
4067 """
4068 dbg("MaskedEditMixin::_adjustDate", indent=1)
4069 if candidate is None: text = self._GetValue()
4070 else: text = candidate
4071 dbg('text=', text)
4072 if self._datestyle == "YMD":
4073 year_field = 0
4074 else:
4075 year_field = 2
4076
4077 dbg('getYear: "%s"' % getYear(text, self._datestyle))
4078 year = string.replace( getYear( text, self._datestyle),self._fields[year_field]._fillChar,"") # drop extra fillChars
4079 month = getMonth( text, self._datestyle)
4080 day = getDay( text, self._datestyle)
4081 dbg('self._datestyle:', self._datestyle, 'year:', year, 'Month', month, 'day:', day)
4082
4083 yearVal = None
4084 yearstart = self._dateExtent - 4
4085 if( len(year) < 4
4086 and (fixcentury
4087 or force4digit_year
4088 or (self._GetInsertionPoint() > yearstart+1 and text[yearstart+2] == ' ')
4089 or (self._GetInsertionPoint() > yearstart+2 and text[yearstart+3] == ' ') ) ):
4090 ## user entered less than four digits and changing fields or past point where we could
4091 ## enter another digit:
4092 try:
4093 yearVal = int(year)
4094 except:
4095 dbg('bad year=', year)
4096 year = text[yearstart:self._dateExtent]
4097
4098 if len(year) < 4 and yearVal:
4099 if len(year) == 2:
4100 # Fix year adjustment to be less "20th century" :-) and to adjust heuristic as the
4101 # years pass...
4102 now = wx.DateTime_Now()
4103 century = (now.GetYear() /100) * 100 # "this century"
4104 twodig_year = now.GetYear() - century # "this year" (2 digits)
4105 # if separation between today's 2-digit year and typed value > 50,
4106 # assume last century,
4107 # else assume this century.
4108 #
4109 # Eg: if 2003 and yearVal == 30, => 2030
4110 # if 2055 and yearVal == 80, => 2080
4111 # if 2010 and yearVal == 96, => 1996
4112 #
4113 if abs(yearVal - twodig_year) > 50:
4114 yearVal = (century - 100) + yearVal
4115 else:
4116 yearVal = century + yearVal
4117 year = str( yearVal )
4118 else: # pad with 0's to make a 4-digit year
4119 year = "%04d" % yearVal
4120 if self._4digityear or force4digit_year:
4121 text = makeDate(year, month, day, self._datestyle, text) + text[self._dateExtent:]
4122 dbg('newdate: "%s"' % text, indent=0)
4123 return text
4124
4125
4126 def _goEnd(self, getPosOnly=False):
4127 """ Moves the insertion point to the end of user-entry """
4128 dbg("MaskedEditMixin::_goEnd; getPosOnly:", getPosOnly, indent=1)
4129 text = self._GetValue()
4130 ## dbg('text: "%s"' % text)
4131 i = 0
4132 if len(text.rstrip()):
4133 for i in range( min( self._masklength-1, len(text.rstrip())), -1, -1):
4134 ## dbg('i:', i, 'self._isMaskChar(%d)' % i, self._isMaskChar(i))
4135 if self._isMaskChar(i):
4136 char = text[i]
4137 ## dbg("text[%d]: '%s'" % (i, char))
4138 if char != ' ':
4139 i += 1
4140 break
4141
4142 if i == 0:
4143 pos = self._goHome(getPosOnly=True)
4144 else:
4145 pos = min(i,self._masklength)
4146
4147 field = self._FindField(pos)
4148 start, end = field._extent
4149 if field._insertRight and pos < end:
4150 pos = end
4151 dbg('next pos:', pos)
4152 dbg(indent=0)
4153 if getPosOnly:
4154 return pos
4155 else:
4156 self._SetInsertionPoint(pos)
4157
4158
4159 def _goHome(self, getPosOnly=False):
4160 """ Moves the insertion point to the beginning of user-entry """
4161 dbg("MaskedEditMixin::_goHome; getPosOnly:", getPosOnly, indent=1)
4162 text = self._GetValue()
4163 for i in range(self._masklength):
4164 if self._isMaskChar(i):
4165 break
4166 pos = max(i, 0)
4167 dbg(indent=0)
4168 if getPosOnly:
4169 return pos
4170 else:
4171 self._SetInsertionPoint(max(i,0))
4172
4173
4174
4175 def _getAllowedChars(self, pos):
4176 """ Returns a string of all allowed user input characters for the provided
4177 mask character plus control options
4178 """
4179 maskChar = self.maskdict[pos]
4180 okchars = self.maskchardict[maskChar] ## entry, get mask approved characters
4181 field = self._FindField(pos)
4182 if okchars and field._okSpaces: ## Allow spaces?
4183 okchars += " "
4184 if okchars and field._includeChars: ## any additional included characters?
4185 okchars += field._includeChars
4186 ## dbg('okchars[%d]:' % pos, okchars)
4187 return okchars
4188
4189
4190 def _isMaskChar(self, pos):
4191 """ Returns True if the char at position pos is a special mask character (e.g. NCXaA#)
4192 """
4193 if pos < self._masklength:
4194 return self.ismasked[pos]
4195 else:
4196 return False
4197
4198
4199 def _isTemplateChar(self,Pos):
4200 """ Returns True if the char at position pos is a template character (e.g. -not- NCXaA#)
4201 """
4202 if Pos < self._masklength:
4203 return not self._isMaskChar(Pos)
4204 else:
4205 return False
4206
4207
4208 def _isCharAllowed(self, char, pos, checkRegex=False, allowAutoSelect=True, ignoreInsertRight=False):
4209 """ Returns True if character is allowed at the specific position, otherwise False."""
4210 dbg('_isCharAllowed', char, pos, checkRegex, indent=1)
4211 field = self._FindField(pos)
4212 right_insert = False
4213
4214 if self.controlInitialized:
4215 sel_start, sel_to = self._GetSelection()
4216 else:
4217 sel_start, sel_to = pos, pos
4218
4219 if (field._insertRight or self._ctrl_constraints._insertRight) and not ignoreInsertRight:
4220 start, end = field._extent
4221 field_len = end - start
4222 if self.controlInitialized:
4223 value = self._GetValue()
4224 fstr = value[start:end].strip()
4225 if field._padZero:
4226 while fstr and fstr[0] == '0':
4227 fstr = fstr[1:]
4228 input_len = len(fstr)
4229 if self._signOk and '-' in fstr or '(' in fstr:
4230 input_len -= 1 # sign can move out of field, so don't consider it in length
4231 else:
4232 value = self._template
4233 input_len = 0 # can't get the current "value", so use 0
4234
4235
4236 # if entire field is selected or position is at end and field is not full,
4237 # or if allowed to right-insert at any point in field and field is not full and cursor is not at a fillChar:
4238 if( (sel_start, sel_to) == field._extent
4239 or (pos == end and input_len < field_len)):
4240 pos = end - 1
4241 dbg('pos = end - 1 = ', pos, 'right_insert? 1')
4242 right_insert = True
4243 elif( field._allowInsert and sel_start == sel_to
4244 and (sel_to == end or (sel_to < self._masklength and value[sel_start] != field._fillChar))
4245 and input_len < field_len ):
4246 pos = sel_to - 1 # where character will go
4247 dbg('pos = sel_to - 1 = ', pos, 'right_insert? 1')
4248 right_insert = True
4249 # else leave pos alone...
4250 else:
4251 dbg('pos stays ', pos, 'right_insert? 0')
4252
4253
4254 if self._isTemplateChar( pos ): ## if a template character, return empty
4255 dbg('%d is a template character; returning False' % pos, indent=0)
4256 return False
4257
4258 if self._isMaskChar( pos ):
4259 okChars = self._getAllowedChars(pos)
4260
4261 if self._fields[0]._groupdigits and (self._isInt or (self._isFloat and pos < self._decimalpos)):
4262 okChars += self._fields[0]._groupChar
4263
4264 if self._signOk:
4265 if self._isInt or (self._isFloat and pos < self._decimalpos):
4266 okChars += '-'
4267 if self._useParens:
4268 okChars += '('
4269 elif self._useParens and (self._isInt or (self._isFloat and pos > self._decimalpos)):
4270 okChars += ')'
4271
4272 ## dbg('%s in %s?' % (char, okChars), char in okChars)
4273 approved = char in okChars
4274
4275 if approved and checkRegex:
4276 dbg("checking appropriate regex's")
4277 value = self._eraseSelection(self._GetValue())
4278 if right_insert:
4279 at = pos+1
4280 else:
4281 at = pos
4282 if allowAutoSelect:
4283 newvalue, ignore, ignore, ignore, ignore = self._insertKey(char, at, sel_start, sel_to, value, allowAutoSelect=True)
4284 else:
4285 newvalue, ignore = self._insertKey(char, at, sel_start, sel_to, value)
4286 dbg('newvalue: "%s"' % newvalue)
4287
4288 fields = [self._FindField(pos)] + [self._ctrl_constraints]
4289 for field in fields: # includes fields[-1] == "ctrl_constraints"
4290 if field._regexMask and field._filter:
4291 dbg('checking vs. regex')
4292 start, end = field._extent
4293 slice = newvalue[start:end]
4294 approved = (re.match( field._filter, slice) is not None)
4295 dbg('approved?', approved)
4296 if not approved: break
4297 dbg(indent=0)
4298 return approved
4299 else:
4300 dbg('%d is a !???! character; returning False', indent=0)
4301 return False
4302
4303
4304 def _applyFormatting(self):
4305 """ Apply formatting depending on the control's state.
4306 Need to find a way to call this whenever the value changes, in case the control's
4307 value has been changed or set programatically.
4308 """
4309 dbg(suspend=1)
4310 dbg('MaskedEditMixin::_applyFormatting', indent=1)
4311
4312 # Handle negative numbers
4313 if self._signOk:
4314 text, signpos, right_signpos = self._getSignedValue()
4315 dbg('text: "%s", signpos:' % text, signpos)
4316 if not text or text[signpos] not in ('-','('):
4317 self._isNeg = False
4318 dbg('no valid sign found; new sign:', self._isNeg)
4319 if text and signpos != self._signpos:
4320 self._signpos = signpos
4321 elif text and self._valid and not self._isNeg and text[signpos] in ('-', '('):
4322 dbg('setting _isNeg to True')
4323 self._isNeg = True
4324 dbg('self._isNeg:', self._isNeg)
4325
4326 if self._signOk and self._isNeg:
4327 fc = self._signedForegroundColour
4328 else:
4329 fc = self._foregroundColour
4330
4331 if hasattr(fc, '_name'):
4332 c =fc._name
4333 else:
4334 c = fc
4335 dbg('setting foreground to', c)
4336 self.SetForegroundColour(fc)
4337
4338 if self._valid:
4339 dbg('valid')
4340 if self.IsEmpty():
4341 bc = self._emptyBackgroundColour
4342 else:
4343 bc = self._validBackgroundColour
4344 else:
4345 dbg('invalid')
4346 bc = self._invalidBackgroundColour
4347 if hasattr(bc, '_name'):
4348 c =bc._name
4349 else:
4350 c = bc
4351 dbg('setting background to', c)
4352 self.SetBackgroundColour(bc)
4353 self._Refresh()
4354 dbg(indent=0, suspend=0)
4355
4356
4357 def _getAbsValue(self, candidate=None):
4358 """ Return an unsigned value (i.e. strip the '-' prefix if any), and sign position(s).
4359 """
4360 dbg('MaskedEditMixin::_getAbsValue; candidate="%s"' % candidate, indent=1)
4361 if candidate is None: text = self._GetValue()
4362 else: text = candidate
4363 right_signpos = text.find(')')
4364
4365 if self._isInt:
4366 if self._ctrl_constraints._alignRight and self._fields[0]._fillChar == ' ':
4367 signpos = text.find('-')
4368 if signpos == -1:
4369 dbg('no - found; searching for (')
4370 signpos = text.find('(')
4371 elif signpos != -1:
4372 dbg('- found at', signpos)
4373
4374 if signpos == -1:
4375 dbg('signpos still -1')
4376 dbg('len(%s) (%d) < len(%s) (%d)?' % (text, len(text), self._mask, self._masklength), len(text) < self._masklength)
4377 if len(text) < self._masklength:
4378 text = ' ' + text
4379 if len(text) < self._masklength:
4380 text += ' '
4381 if len(text) > self._masklength and text[-1] in (')', ' '):
4382 text = text[:-1]
4383 else:
4384 dbg('len(%s) (%d), len(%s) (%d)' % (text, len(text), self._mask, self._masklength))
4385 dbg('len(%s) - (len(%s) + 1):' % (text, text.lstrip()) , len(text) - (len(text.lstrip()) + 1))
4386 signpos = len(text) - (len(text.lstrip()) + 1)
4387
4388 if self._useParens and not text.strip():
4389 signpos -= 1 # empty value; use penultimate space
4390 dbg('signpos:', signpos)
4391 if signpos >= 0:
4392 text = text[:signpos] + ' ' + text[signpos+1:]
4393
4394 else:
4395 if self._signOk:
4396 signpos = 0
4397 text = self._template[0] + text[1:]
4398 else:
4399 signpos = -1
4400
4401 if right_signpos != -1:
4402 if self._signOk:
4403 text = text[:right_signpos] + ' ' + text[right_signpos+1:]
4404 elif len(text) > self._masklength:
4405 text = text[:right_signpos] + text[right_signpos+1:]
4406 right_signpos = -1
4407
4408
4409 elif self._useParens and self._signOk:
4410 # figure out where it ought to go:
4411 right_signpos = self._masklength - 1 # initial guess
4412 if not self._ctrl_constraints._alignRight:
4413 dbg('not right-aligned')
4414 if len(text.strip()) == 0:
4415 right_signpos = signpos + 1
4416 elif len(text.strip()) < self._masklength:
4417 right_signpos = len(text.rstrip())
4418 dbg('right_signpos:', right_signpos)
4419
4420 groupchar = self._fields[0]._groupChar
4421 try:
4422 value = long(text.replace(groupchar,'').replace('(','-').replace(')','').replace(' ', ''))
4423 except:
4424 dbg('invalid number', indent=0)
4425 return None, signpos, right_signpos
4426
4427 else: # float value
4428 try:
4429 groupchar = self._fields[0]._groupChar
4430 value = float(text.replace(groupchar,'').replace(self._decimalChar, '.').replace('(', '-').replace(')','').replace(' ', ''))
4431 dbg('value:', value)
4432 except:
4433 value = None
4434
4435 if value < 0 and value is not None:
4436 signpos = text.find('-')
4437 if signpos == -1:
4438 signpos = text.find('(')
4439
4440 text = text[:signpos] + self._template[signpos] + text[signpos+1:]
4441 else:
4442 # look forwards up to the decimal point for the 1st non-digit
4443 dbg('decimal pos:', self._decimalpos)
4444 dbg('text: "%s"' % text)
4445 if self._signOk:
4446 signpos = self._decimalpos - (len(text[:self._decimalpos].lstrip()) + 1)
4447 # prevent checking for empty string - Tomo - Wed 14 Jan 2004 03:19:09 PM CET
4448 if len(text) >= signpos+1 and text[signpos+1] in ('-','('):
4449 signpos += 1
4450 else:
4451 signpos = -1
4452 dbg('signpos:', signpos)
4453
4454 if self._useParens:
4455 if self._signOk:
4456 right_signpos = self._masklength - 1
4457 text = text[:right_signpos] + ' '
4458 if text[signpos] == '(':
4459 text = text[:signpos] + ' ' + text[signpos+1:]
4460 else:
4461 right_signpos = text.find(')')
4462 if right_signpos != -1:
4463 text = text[:-1]
4464 right_signpos = -1
4465
4466 if value is None:
4467 dbg('invalid number')
4468 text = None
4469
4470 dbg('abstext = "%s"' % text, 'signpos:', signpos, 'right_signpos:', right_signpos)
4471 dbg(indent=0)
4472 return text, signpos, right_signpos
4473
4474
4475 def _getSignedValue(self, candidate=None):
4476 """ Return a signed value by adding a "-" prefix if the value
4477 is set to negative, or a space if positive.
4478 """
4479 dbg('MaskedEditMixin::_getSignedValue; candidate="%s"' % candidate, indent=1)
4480 if candidate is None: text = self._GetValue()
4481 else: text = candidate
4482
4483
4484 abstext, signpos, right_signpos = self._getAbsValue(text)
4485 if self._signOk:
4486 if abstext is None:
4487 dbg(indent=0)
4488 return abstext, signpos, right_signpos
4489
4490 if self._isNeg or text[signpos] in ('-', '('):
4491 if self._useParens:
4492 sign = '('
4493 else:
4494 sign = '-'
4495 else:
4496 sign = ' '
4497 if abstext[signpos] not in string.digits:
4498 text = abstext[:signpos] + sign + abstext[signpos+1:]
4499 else:
4500 # this can happen if value passed is too big; sign assumed to be
4501 # in position 0, but if already filled with a digit, prepend sign...
4502 text = sign + abstext
4503 if self._useParens and text.find('(') != -1:
4504 text = text[:right_signpos] + ')' + text[right_signpos+1:]
4505 else:
4506 text = abstext
4507 dbg('signedtext = "%s"' % text, 'signpos:', signpos, 'right_signpos', right_signpos)
4508 dbg(indent=0)
4509 return text, signpos, right_signpos
4510
4511
4512 def GetPlainValue(self, candidate=None):
4513 """ Returns control's value stripped of the template text.
4514 plainvalue = MaskedEditMixin.GetPlainValue()
4515 """
4516 dbg('MaskedEditMixin::GetPlainValue; candidate="%s"' % candidate, indent=1)
4517
4518 if candidate is None: text = self._GetValue()
4519 else: text = candidate
4520
4521 if self.IsEmpty():
4522 dbg('returned ""', indent=0)
4523 return ""
4524 else:
4525 plain = ""
4526 for idx in range( min(len(self._template), len(text)) ):
4527 if self._mask[idx] in maskchars:
4528 plain += text[idx]
4529
4530 if self._isFloat or self._isInt:
4531 dbg('plain so far: "%s"' % plain)
4532 plain = plain.replace('(', '-').replace(')', ' ')
4533 dbg('plain after sign regularization: "%s"' % plain)
4534
4535 if self._signOk and self._isNeg and plain.count('-') == 0:
4536 # must be in reserved position; add to "plain value"
4537 plain = '-' + plain.strip()
4538
4539 if self._fields[0]._alignRight:
4540 lpad = plain.count(',')
4541 plain = ' ' * lpad + plain.replace(',','')
4542 else:
4543 plain = plain.replace(',','')
4544 dbg('plain after pad and group:"%s"' % plain)
4545
4546 dbg('returned "%s"' % plain.rstrip(), indent=0)
4547 return plain.rstrip()
4548
4549
4550 def IsEmpty(self, value=None):
4551 """
4552 Returns True if control is equal to an empty value.
4553 (Empty means all editable positions in the template == fillChar.)
4554 """
4555 if value is None: value = self._GetValue()
4556 if value == self._template and not self._defaultValue:
4557 ## dbg("IsEmpty? 1 (value == self._template and not self._defaultValue)")
4558 return True # (all mask chars == fillChar by defn)
4559 elif value == self._template:
4560 empty = True
4561 for pos in range(len(self._template)):
4562 ## dbg('isMaskChar(%(pos)d)?' % locals(), self._isMaskChar(pos))
4563 ## dbg('value[%(pos)d] != self._fillChar?' %locals(), value[pos] != self._fillChar[pos])
4564 if self._isMaskChar(pos) and value[pos] not in (' ', self._fillChar[pos]):
4565 empty = False
4566 ## dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals())
4567 return empty
4568 else:
4569 ## dbg("IsEmpty? 0 (value doesn't match template)")
4570 return False
4571
4572
4573 def IsDefault(self, value=None):
4574 """
4575 Returns True if the value specified (or the value of the control if not specified)
4576 is equal to the default value.
4577 """
4578 if value is None: value = self._GetValue()
4579 return value == self._template
4580
4581
4582 def IsValid(self, value=None):
4583 """ Indicates whether the value specified (or the current value of the control
4584 if not specified) is considered valid."""
4585 ## dbg('MaskedEditMixin::IsValid("%s")' % value, indent=1)
4586 if value is None: value = self._GetValue()
4587 ret = self._CheckValid(value)
4588 ## dbg(indent=0)
4589 return ret
4590
4591
4592 def _eraseSelection(self, value=None, sel_start=None, sel_to=None):
4593 """ Used to blank the selection when inserting a new character. """
4594 dbg("MaskedEditMixin::_eraseSelection", indent=1)
4595 if value is None: value = self._GetValue()
4596 if sel_start is None or sel_to is None:
4597 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
4598 dbg('value: "%s"' % value)
4599 dbg("current sel_start, sel_to:", sel_start, sel_to)
4600
4601 newvalue = list(value)
4602 for i in range(sel_start, sel_to):
4603 if self._signOk and newvalue[i] in ('-', '(', ')'):
4604 dbg('found sign (%s) at' % newvalue[i], i)
4605
4606 # balance parentheses:
4607 if newvalue[i] == '(':
4608 right_signpos = value.find(')')
4609 if right_signpos != -1:
4610 newvalue[right_signpos] = ' '
4611
4612 elif newvalue[i] == ')':
4613 left_signpos = value.find('(')
4614 if left_signpos != -1:
4615 newvalue[left_signpos] = ' '
4616
4617 newvalue[i] = ' '
4618
4619 elif self._isMaskChar(i):
4620 field = self._FindField(i)
4621 if field._padZero:
4622 newvalue[i] = '0'
4623 else:
4624 newvalue[i] = self._template[i]
4625
4626 value = string.join(newvalue,"")
4627 dbg('new value: "%s"' % value)
4628 dbg(indent=0)
4629 return value
4630
4631
4632 def _insertKey(self, char, pos, sel_start, sel_to, value, allowAutoSelect=False):
4633 """ Handles replacement of the character at the current insertion point."""
4634 dbg('MaskedEditMixin::_insertKey', "\'" + char + "\'", pos, sel_start, sel_to, '"%s"' % value, indent=1)
4635
4636 text = self._eraseSelection(value)
4637 field = self._FindField(pos)
4638 start, end = field._extent
4639 newtext = ""
4640 newpos = pos
4641
4642 if pos != sel_start and sel_start == sel_to:
4643 # adjustpos must have moved the position; make selection match:
4644 sel_start = sel_to = pos
4645
4646 dbg('field._insertRight?', field._insertRight)
4647 if( field._insertRight # field allows right insert
4648 and ((sel_start, sel_to) == field._extent # and whole field selected
4649 or (sel_start == sel_to # or nothing selected
4650 and (sel_start == end # and cursor at right edge
4651 or (field._allowInsert # or field allows right-insert
4652 and sel_start < end # next to other char in field:
4653 and text[sel_start] != field._fillChar) ) ) ) ):
4654 dbg('insertRight')
4655 fstr = text[start:end]
4656 erasable_chars = [field._fillChar, ' ']
4657
4658 if field._padZero:
4659 erasable_chars.append('0')
4660
4661 erased = ''
4662 ## dbg("fstr[0]:'%s'" % fstr[0])
4663 ## dbg('field_index:', field._index)
4664 ## dbg("fstr[0] in erasable_chars?", fstr[0] in erasable_chars)
4665 ## dbg("self._signOk and field._index == 0 and fstr[0] in ('-','(')?",
4666 ## self._signOk and field._index == 0 and fstr[0] in ('-','('))
4667 if fstr[0] in erasable_chars or (self._signOk and field._index == 0 and fstr[0] in ('-','(')):
4668 erased = fstr[0]
4669 ## dbg('value: "%s"' % text)
4670 ## dbg('fstr: "%s"' % fstr)
4671 ## dbg("erased: '%s'" % erased)
4672 field_sel_start = sel_start - start
4673 field_sel_to = sel_to - start
4674 dbg('left fstr: "%s"' % fstr[1:field_sel_start])
4675 dbg('right fstr: "%s"' % fstr[field_sel_to:end])
4676 fstr = fstr[1:field_sel_start] + char + fstr[field_sel_to:end]
4677 if field._alignRight and sel_start != sel_to:
4678 field_len = end - start
4679 ## pos += (field_len - len(fstr)) # move cursor right by deleted amount
4680 pos = sel_to
4681 dbg('setting pos to:', pos)
4682 if field._padZero:
4683 fstr = '0' * (field_len - len(fstr)) + fstr
4684 else:
4685 fstr = fstr.rjust(field_len) # adjust the field accordingly
4686 dbg('field str: "%s"' % fstr)
4687
4688 newtext = text[:start] + fstr + text[end:]
4689 if erased in ('-', '(') and self._signOk:
4690 newtext = erased + newtext[1:]
4691 dbg('newtext: "%s"' % newtext)
4692
4693 if self._signOk and field._index == 0:
4694 start -= 1 # account for sign position
4695
4696 ## dbg('field._moveOnFieldFull?', field._moveOnFieldFull)
4697 ## dbg('len(fstr.lstrip()) == end-start?', len(fstr.lstrip()) == end-start)
4698 if( field._moveOnFieldFull and pos == end
4699 and len(fstr.lstrip()) == end-start): # if field now full
4700 newpos = self._findNextEntry(end) # go to next field
4701 else:
4702 newpos = pos # else keep cursor at current position
4703
4704 if not newtext:
4705 dbg('not newtext')
4706 if newpos != pos:
4707 dbg('newpos:', newpos)
4708 if self._signOk and self._useParens:
4709 old_right_signpos = text.find(')')
4710
4711 if field._allowInsert and not field._insertRight and sel_to <= end and sel_start >= start:
4712 # inserting within a left-insert-capable field
4713 field_len = end - start
4714 before = text[start:sel_start]
4715 after = text[sel_to:end].strip()
4716 ## dbg("current field:'%s'" % text[start:end])
4717 ## dbg("before:'%s'" % before, "after:'%s'" % after)
4718 new_len = len(before) + len(after) + 1 # (for inserted char)
4719 ## dbg('new_len:', new_len)
4720
4721 if new_len < field_len:
4722 retained = after + self._template[end-(field_len-new_len):end]
4723 elif new_len > end-start:
4724 retained = after[1:]
4725 else:
4726 retained = after
4727
4728 left = text[0:start] + before
4729 ## dbg("left:'%s'" % left, "retained:'%s'" % retained)
4730 right = retained + text[end:]
4731 else:
4732 left = text[0:pos]
4733 right = text[pos+1:]
4734
4735 newtext = left + char + right
4736
4737 if self._signOk and self._useParens:
4738 # Balance parentheses:
4739 left_signpos = newtext.find('(')
4740
4741 if left_signpos == -1: # erased '('; remove ')'
4742 right_signpos = newtext.find(')')
4743 if right_signpos != -1:
4744 newtext = newtext[:right_signpos] + ' ' + newtext[right_signpos+1:]
4745
4746 elif old_right_signpos != -1:
4747 right_signpos = newtext.find(')')
4748
4749 if right_signpos == -1: # just replaced right-paren
4750 if newtext[pos] == ' ': # we just erased '); erase '('
4751 newtext = newtext[:left_signpos] + ' ' + newtext[left_signpos+1:]
4752 else: # replaced with digit; move ') over
4753 if self._ctrl_constraints._alignRight or self._isFloat:
4754 newtext = newtext[:-1] + ')'
4755 else:
4756 rstripped_text = newtext.rstrip()
4757 right_signpos = len(rstripped_text)
4758 dbg('old_right_signpos:', old_right_signpos, 'right signpos now:', right_signpos)
4759 newtext = newtext[:right_signpos] + ')' + newtext[right_signpos+1:]
4760
4761 if( field._insertRight # if insert-right field (but we didn't start at right edge)
4762 and field._moveOnFieldFull # and should move cursor when full
4763 and len(newtext[start:end].strip()) == end-start): # and field now full
4764 newpos = self._findNextEntry(end) # go to next field
4765 dbg('newpos = nextentry =', newpos)
4766 else:
4767 dbg('pos:', pos, 'newpos:', pos+1)
4768 newpos = pos+1
4769
4770
4771 if allowAutoSelect:
4772 new_select_to = newpos # (default return values)
4773 match_field = None
4774 match_index = None
4775
4776 if field._autoSelect:
4777 match_index, partial_match = self._autoComplete(1, # (always forward)
4778 field._compareChoices,
4779 newtext[start:end],
4780 compareNoCase=field._compareNoCase,
4781 current_index = field._autoCompleteIndex-1)
4782 if match_index is not None and partial_match:
4783 matched_str = newtext[start:end]
4784 newtext = newtext[:start] + field._choices[match_index] + newtext[end:]
4785 new_select_to = end
4786 match_field = field
4787 if field._insertRight:
4788 # adjust position to just after partial match in field
4789 newpos = end - (len(field._choices[match_index].strip()) - len(matched_str.strip()))
4790
4791 elif self._ctrl_constraints._autoSelect:
4792 match_index, partial_match = self._autoComplete(
4793 1, # (always forward)
4794 self._ctrl_constraints._compareChoices,
4795 newtext,
4796 self._ctrl_constraints._compareNoCase,
4797 current_index = self._ctrl_constraints._autoCompleteIndex - 1)
4798 if match_index is not None and partial_match:
4799 matched_str = newtext
4800 newtext = self._ctrl_constraints._choices[match_index]
4801 new_select_to = self._ctrl_constraints._extent[1]
4802 match_field = self._ctrl_constraints
4803 if self._ctrl_constraints._insertRight:
4804 # adjust position to just after partial match in control:
4805 newpos = self._masklength - (len(self._ctrl_constraints._choices[match_index].strip()) - len(matched_str.strip()))
4806
4807 dbg('newtext: "%s"' % newtext, 'newpos:', newpos, 'new_select_to:', new_select_to)
4808 dbg(indent=0)
4809 return newtext, newpos, new_select_to, match_field, match_index
4810 else:
4811 dbg('newtext: "%s"' % newtext, 'newpos:', newpos)
4812 dbg(indent=0)
4813 return newtext, newpos
4814
4815
4816 def _OnFocus(self,event):
4817 """
4818 This event handler is currently necessary to work around new default
4819 behavior as of wxPython2.3.3;
4820 The TAB key auto selects the entire contents of the wxTextCtrl *after*
4821 the EVT_SET_FOCUS event occurs; therefore we can't query/adjust the selection
4822 *here*, because it hasn't happened yet. So to prevent this behavior, and
4823 preserve the correct selection when the focus event is not due to tab,
4824 we need to pull the following trick:
4825 """
4826 dbg('MaskedEditMixin::_OnFocus')
4827 wx.CallAfter(self._fixSelection)
4828 event.Skip()
4829 self.Refresh()
4830
4831
4832 def _CheckValid(self, candidate=None):
4833 """
4834 This is the default validation checking routine; It verifies that the
4835 current value of the control is a "valid value," and has the side
4836 effect of coloring the control appropriately.
4837 """
4838 dbg(suspend=1)
4839 dbg('MaskedEditMixin::_CheckValid: candidate="%s"' % candidate, indent=1)
4840 oldValid = self._valid
4841 if candidate is None: value = self._GetValue()
4842 else: value = candidate
4843 dbg('value: "%s"' % value)
4844 oldvalue = value
4845 valid = True # assume True
4846
4847 if not self.IsDefault(value) and self._isDate: ## Date type validation
4848 valid = self._validateDate(value)
4849 dbg("valid date?", valid)
4850
4851 elif not self.IsDefault(value) and self._isTime:
4852 valid = self._validateTime(value)
4853 dbg("valid time?", valid)
4854
4855 elif not self.IsDefault(value) and (self._isInt or self._isFloat): ## Numeric type
4856 valid = self._validateNumeric(value)
4857 dbg("valid Number?", valid)
4858
4859 if valid: # and not self.IsDefault(value): ## generic validation accounts for IsDefault()
4860 ## valid so far; ensure also allowed by any list or regex provided:
4861 valid = self._validateGeneric(value)
4862 dbg("valid value?", valid)
4863
4864 dbg('valid?', valid)
4865
4866 if not candidate:
4867 self._valid = valid
4868 self._applyFormatting()
4869 if self._valid != oldValid:
4870 dbg('validity changed: oldValid =',oldValid,'newvalid =', self._valid)
4871 dbg('oldvalue: "%s"' % oldvalue, 'newvalue: "%s"' % self._GetValue())
4872 dbg(indent=0, suspend=0)
4873 return valid
4874
4875
4876 def _validateGeneric(self, candidate=None):
4877 """ Validate the current value using the provided list or Regex filter (if any).
4878 """
4879 if candidate is None:
4880 text = self._GetValue()
4881 else:
4882 text = candidate
4883
4884 valid = True # assume True
4885 for i in [-1] + self._field_indices: # process global constraints first:
4886 field = self._fields[i]
4887 start, end = field._extent
4888 slice = text[start:end]
4889 valid = field.IsValid(slice)
4890 if not valid:
4891 break
4892
4893 return valid
4894
4895
4896 def _validateNumeric(self, candidate=None):
4897 """ Validate that the value is within the specified range (if specified.)"""
4898 if candidate is None: value = self._GetValue()
4899 else: value = candidate
4900 try:
4901 groupchar = self._fields[0]._groupChar
4902 if self._isFloat:
4903 number = float(value.replace(groupchar, '').replace(self._decimalChar, '.').replace('(', '-').replace(')', ''))
4904 else:
4905 number = long( value.replace(groupchar, '').replace('(', '-').replace(')', ''))
4906 if value.strip():
4907 if self._fields[0]._alignRight:
4908 require_digit_at = self._fields[0]._extent[1]-1
4909 else:
4910 require_digit_at = self._fields[0]._extent[0]
4911 dbg('require_digit_at:', require_digit_at)
4912 dbg("value[rda]: '%s'" % value[require_digit_at])
4913 if value[require_digit_at] not in list(string.digits):
4914 valid = False
4915 return valid
4916 # else...
4917 dbg('number:', number)
4918 if self._ctrl_constraints._hasRange:
4919 valid = self._ctrl_constraints._rangeLow <= number <= self._ctrl_constraints._rangeHigh
4920 else:
4921 valid = True
4922 groupcharpos = value.rfind(groupchar)
4923 if groupcharpos != -1: # group char present
4924 dbg('groupchar found at', groupcharpos)
4925 if self._isFloat and groupcharpos > self._decimalpos:
4926 # 1st one found on right-hand side is past decimal point
4927 dbg('groupchar in fraction; illegal')
4928 valid = False
4929 elif self._isFloat:
4930 integer = value[:self._decimalpos].strip()
4931 else:
4932 integer = value.strip()
4933 dbg("integer:'%s'" % integer)
4934 if integer[0] in ('-', '('):
4935 integer = integer[1:]
4936 if integer[-1] == ')':
4937 integer = integer[:-1]
4938
4939 parts = integer.split(groupchar)
4940 dbg('parts:', parts)
4941 for i in range(len(parts)):
4942 if i == 0 and abs(int(parts[0])) > 999:
4943 dbg('group 0 too long; illegal')
4944 valid = False
4945 break
4946 elif i > 0 and (len(parts[i]) != 3 or ' ' in parts[i]):
4947 dbg('group %i (%s) not right size; illegal' % (i, parts[i]))
4948 valid = False
4949 break
4950 except ValueError:
4951 dbg('value not a valid number')
4952 valid = False
4953 return valid
4954
4955
4956 def _validateDate(self, candidate=None):
4957 """ Validate the current date value using the provided Regex filter.
4958 Generally used for character types.BufferType
4959 """
4960 dbg('MaskedEditMixin::_validateDate', indent=1)
4961 if candidate is None: value = self._GetValue()
4962 else: value = candidate
4963 dbg('value = "%s"' % value)
4964 text = self._adjustDate(value, force4digit_year=True) ## Fix the date up before validating it
4965 dbg('text =', text)
4966 valid = True # assume True until proven otherwise
4967
4968 try:
4969 # replace fillChar in each field with space:
4970 datestr = text[0:self._dateExtent]
4971 for i in range(3):
4972 field = self._fields[i]
4973 start, end = field._extent
4974 fstr = datestr[start:end]
4975 fstr.replace(field._fillChar, ' ')
4976 datestr = datestr[:start] + fstr + datestr[end:]
4977
4978 year, month, day = getDateParts( datestr, self._datestyle)
4979 year = int(year)
4980 dbg('self._dateExtent:', self._dateExtent)
4981 if self._dateExtent == 11:
4982 month = charmonths_dict[month.lower()]
4983 else:
4984 month = int(month)
4985 day = int(day)
4986 dbg('year, month, day:', year, month, day)
4987
4988 except ValueError:
4989 dbg('cannot convert string to integer parts')
4990 valid = False
4991 except KeyError:
4992 dbg('cannot convert string to integer month')
4993 valid = False
4994
4995 if valid:
4996 # use wxDateTime to unambiguously try to parse the date:
4997 # ### Note: because wxDateTime is *brain-dead* and expects months 0-11,
4998 # rather than 1-12, so handle accordingly:
4999 if month > 12:
5000 valid = False
5001 else:
5002 month -= 1
5003 try:
5004 dbg("trying to create date from values day=%d, month=%d, year=%d" % (day,month,year))
5005 dateHandler = wx.DateTimeFromDMY(day,month,year)
5006 dbg("succeeded")
5007 dateOk = True
5008 except:
5009 dbg('cannot convert string to valid date')
5010 dateOk = False
5011 if not dateOk:
5012 valid = False
5013
5014 if valid:
5015 # wxDateTime doesn't take kindly to leading/trailing spaces when parsing,
5016 # so we eliminate them here:
5017 timeStr = text[self._dateExtent+1:].strip() ## time portion of the string
5018 if timeStr:
5019 dbg('timeStr: "%s"' % timeStr)
5020 try:
5021 checkTime = dateHandler.ParseTime(timeStr)
5022 valid = checkTime == len(timeStr)
5023 except:
5024 valid = False
5025 if not valid:
5026 dbg('cannot convert string to valid time')
5027 if valid: dbg('valid date')
5028 dbg(indent=0)
5029 return valid
5030
5031
5032 def _validateTime(self, candidate=None):
5033 """ Validate the current time value using the provided Regex filter.
5034 Generally used for character types.BufferType
5035 """
5036 dbg('MaskedEditMixin::_validateTime', indent=1)
5037 # wxDateTime doesn't take kindly to leading/trailing spaces when parsing,
5038 # so we eliminate them here:
5039 if candidate is None: value = self._GetValue().strip()
5040 else: value = candidate.strip()
5041 dbg('value = "%s"' % value)
5042 valid = True # assume True until proven otherwise
5043
5044 dateHandler = wx.DateTime_Today()
5045 try:
5046 checkTime = dateHandler.ParseTime(value)
5047 dbg('checkTime:', checkTime, 'len(value)', len(value))
5048 valid = checkTime == len(value)
5049 except:
5050 valid = False
5051
5052 if not valid:
5053 dbg('cannot convert string to valid time')
5054 if valid: dbg('valid time')
5055 dbg(indent=0)
5056 return valid
5057
5058
5059 def _OnKillFocus(self,event):
5060 """ Handler for EVT_KILL_FOCUS event.
5061 """
5062 dbg('MaskedEditMixin::_OnKillFocus', 'isDate=',self._isDate, indent=1)
5063 if self._mask and self._IsEditable():
5064 self._AdjustField(self._GetInsertionPoint())
5065 self._CheckValid() ## Call valid handler
5066
5067 self._LostFocus() ## Provided for subclass use
5068 event.Skip()
5069 dbg(indent=0)
5070
5071
5072 def _fixSelection(self):
5073 """
5074 This gets called after the TAB traversal selection is made, if the
5075 focus event was due to this, but before the EVT_LEFT_* events if
5076 the focus shift was due to a mouse event.
5077
5078 The trouble is that, a priori, there's no explicit notification of
5079 why the focus event we received. However, the whole reason we need to
5080 do this is because the default behavior on TAB traveral in a wxTextCtrl is
5081 now to select the entire contents of the window, something we don't want.
5082 So we can *now* test the selection range, and if it's "the whole text"
5083 we can assume the cause, change the insertion point to the start of
5084 the control, and deselect.
5085 """
5086 dbg('MaskedEditMixin::_fixSelection', indent=1)
5087 if not self._mask or not self._IsEditable():
5088 dbg(indent=0)
5089 return
5090
5091 sel_start, sel_to = self._GetSelection()
5092 dbg('sel_start, sel_to:', sel_start, sel_to, 'self.IsEmpty()?', self.IsEmpty())
5093
5094 if( sel_start == 0 and sel_to >= len( self._mask ) #(can be greater in numeric controls because of reserved space)
5095 and (not self._ctrl_constraints._autoSelect or self.IsEmpty() or self.IsDefault() ) ):
5096 # This isn't normally allowed, and so assume we got here by the new
5097 # "tab traversal" behavior, so we need to reset the selection
5098 # and insertion point:
5099 dbg('entire text selected; resetting selection to start of control')
5100 self._goHome()
5101 field = self._FindField(self._GetInsertionPoint())
5102 edit_start, edit_end = field._extent
5103 if field._selectOnFieldEntry:
5104 self._SetInsertionPoint(edit_start)
5105 self._SetSelection(edit_start, edit_end)
5106
5107 elif field._insertRight:
5108 self._SetInsertionPoint(edit_end)
5109 self._SetSelection(edit_end, edit_end)
5110
5111 elif (self._isFloat or self._isInt):
5112
5113 text, signpos, right_signpos = self._getAbsValue()
5114 if text is None or text == self._template:
5115 integer = self._fields[0]
5116 edit_start, edit_end = integer._extent
5117
5118 if integer._selectOnFieldEntry:
5119 dbg('select on field entry:')
5120 self._SetInsertionPoint(edit_start)
5121 self._SetSelection(edit_start, edit_end)
5122
5123 elif integer._insertRight:
5124 dbg('moving insertion point to end')
5125 self._SetInsertionPoint(edit_end)
5126 self._SetSelection(edit_end, edit_end)
5127 else:
5128 dbg('numeric ctrl is empty; start at beginning after sign')
5129 self._SetInsertionPoint(signpos+1) ## Move past minus sign space if signed
5130 self._SetSelection(signpos+1, signpos+1)
5131
5132 elif sel_start > self._goEnd(getPosOnly=True):
5133 dbg('cursor beyond the end of the user input; go to end of it')
5134 self._goEnd()
5135 else:
5136 dbg('sel_start, sel_to:', sel_start, sel_to, 'self._masklength:', self._masklength)
5137 dbg(indent=0)
5138
5139
5140 def _Keypress(self,key):
5141 """ Method provided to override OnChar routine. Return False to force
5142 a skip of the 'normal' OnChar process. Called before class OnChar.
5143 """
5144 return True
5145
5146
5147 def _LostFocus(self):
5148 """ Method provided for subclasses. _LostFocus() is called after
5149 the class processes its EVT_KILL_FOCUS event code.
5150 """
5151 pass
5152
5153
5154 def _OnDoubleClick(self, event):
5155 """ selects field under cursor on dclick."""
5156 pos = self._GetInsertionPoint()
5157 field = self._FindField(pos)
5158 start, end = field._extent
5159 self._SetInsertionPoint(start)
5160 self._SetSelection(start, end)
5161
5162
5163 def _Change(self):
5164 """ Method provided for subclasses. Called by internal EVT_TEXT
5165 handler. Return False to override the class handler, True otherwise.
5166 """
5167 return True
5168
5169
5170 def _Cut(self):
5171 """
5172 Used to override the default Cut() method in base controls, instead
5173 copying the selection to the clipboard and then blanking the selection,
5174 leaving only the mask in the selected area behind.
5175 Note: _Cut (read "undercut" ;-) must be called from a Cut() override in the
5176 derived control because the mixin functions can't override a method of
5177 a sibling class.
5178 """
5179 dbg("MaskedEditMixin::_Cut", indent=1)
5180 value = self._GetValue()
5181 dbg('current value: "%s"' % value)
5182 sel_start, sel_to = self._GetSelection() ## check for a range of selected text
5183 dbg('selected text: "%s"' % value[sel_start:sel_to].strip())
5184 do = wxTextDataObject()
5185 do.SetText(value[sel_start:sel_to].strip())
5186 wxTheClipboard.Open()
5187 wxTheClipboard.SetData(do)
5188 wxTheClipboard.Close()
5189
5190 if sel_to - sel_start != 0:
5191 self._OnErase()
5192 dbg(indent=0)
5193
5194
5195 # WS Note: overriding Copy is no longer necessary given that you
5196 # can no longer select beyond the last non-empty char in the control.
5197 #
5198 ## def _Copy( self ):
5199 ## """
5200 ## Override the wxTextCtrl's .Copy function, with our own
5201 ## that does validation. Need to strip trailing spaces.
5202 ## """
5203 ## sel_start, sel_to = self._GetSelection()
5204 ## select_len = sel_to - sel_start
5205 ## textval = wxTextCtrl._GetValue(self)
5206 ##
5207 ## do = wxTextDataObject()
5208 ## do.SetText(textval[sel_start:sel_to].strip())
5209 ## wxTheClipboard.Open()
5210 ## wxTheClipboard.SetData(do)
5211 ## wxTheClipboard.Close()
5212
5213
5214 def _getClipboardContents( self ):
5215 """ Subroutine for getting the current contents of the clipboard.
5216 """
5217 do = wxTextDataObject()
5218 wxTheClipboard.Open()
5219 success = wxTheClipboard.GetData(do)
5220 wxTheClipboard.Close()
5221
5222 if not success:
5223 return None
5224 else:
5225 # Remove leading and trailing spaces before evaluating contents
5226 return do.GetText().strip()
5227
5228
5229 def _validatePaste(self, paste_text, sel_start, sel_to, raise_on_invalid=False):
5230 """
5231 Used by paste routine and field choice validation to see
5232 if a given slice of paste text is legal for the area in question:
5233 returns validity, replacement text, and extent of paste in
5234 template.
5235 """
5236 dbg(suspend=1)
5237 dbg('MaskedEditMixin::_validatePaste("%(paste_text)s", %(sel_start)d, %(sel_to)d), raise_on_invalid? %(raise_on_invalid)d' % locals(), indent=1)
5238 select_length = sel_to - sel_start
5239 maxlength = select_length
5240 dbg('sel_to - sel_start:', maxlength)
5241 if maxlength == 0:
5242 maxlength = self._masklength - sel_start
5243 item = 'control'
5244 else:
5245 item = 'selection'
5246 dbg('maxlength:', maxlength)
5247 length_considered = len(paste_text)
5248 if length_considered > maxlength:
5249 dbg('paste text will not fit into the %s:' % item, indent=0)
5250 if raise_on_invalid:
5251 dbg(indent=0, suspend=0)
5252 if item == 'control':
5253 raise ValueError('"%s" will not fit into the control "%s"' % (paste_text, self.name))
5254 else:
5255 raise ValueError('"%s" will not fit into the selection' % paste_text)
5256 else:
5257 dbg(indent=0, suspend=0)
5258 return False, None, None
5259
5260 text = self._template
5261 dbg('length_considered:', length_considered)
5262
5263 valid_paste = True
5264 replacement_text = ""
5265 replace_to = sel_start
5266 i = 0
5267 while valid_paste and i < length_considered and replace_to < self._masklength:
5268 if paste_text[i:] == self._template[replace_to:length_considered]:
5269 # remainder of paste matches template; skip char-by-char analysis
5270 dbg('remainder paste_text[%d:] (%s) matches template[%d:%d]' % (i, paste_text[i:], replace_to, length_considered))
5271 replacement_text += paste_text[i:]
5272 replace_to = i = length_considered
5273 continue
5274 # else:
5275 char = paste_text[i]
5276 field = self._FindField(replace_to)
5277 if not field._compareNoCase:
5278 if field._forceupper: char = char.upper()
5279 elif field._forcelower: char = char.lower()
5280
5281 dbg('char:', "'"+char+"'", 'i =', i, 'replace_to =', replace_to)
5282 dbg('self._isTemplateChar(%d)?' % replace_to, self._isTemplateChar(replace_to))
5283 if not self._isTemplateChar(replace_to) and self._isCharAllowed( char, replace_to, allowAutoSelect=False, ignoreInsertRight=True):
5284 replacement_text += char
5285 dbg("not template(%(replace_to)d) and charAllowed('%(char)s',%(replace_to)d)" % locals())
5286 dbg("replacement_text:", '"'+replacement_text+'"')
5287 i += 1
5288 replace_to += 1
5289 elif( char == self._template[replace_to]
5290 or (self._signOk and
5291 ( (i == 0 and (char == '-' or (self._useParens and char == '(')))
5292 or (i == self._masklength - 1 and self._useParens and char == ')') ) ) ):
5293 replacement_text += char
5294 dbg("'%(char)s' == template(%(replace_to)d)" % locals())
5295 dbg("replacement_text:", '"'+replacement_text+'"')
5296 i += 1
5297 replace_to += 1
5298 else:
5299 next_entry = self._findNextEntry(replace_to, adjustInsert=False)
5300 if next_entry == replace_to:
5301 valid_paste = False
5302 else:
5303 replacement_text += self._template[replace_to:next_entry]
5304 dbg("skipping template; next_entry =", next_entry)
5305 dbg("replacement_text:", '"'+replacement_text+'"')
5306 replace_to = next_entry # so next_entry will be considered on next loop
5307
5308 if not valid_paste and raise_on_invalid:
5309 dbg('raising exception', indent=0, suspend=0)
5310 raise ValueError('"%s" cannot be inserted into the control "%s"' % (paste_text, self.name))
5311
5312 elif i < len(paste_text):
5313 valid_paste = False
5314 if raise_on_invalid:
5315 dbg('raising exception', indent=0, suspend=0)
5316 raise ValueError('"%s" will not fit into the control "%s"' % (paste_text, self.name))
5317
5318 dbg('valid_paste?', valid_paste)
5319 if valid_paste:
5320 dbg('replacement_text: "%s"' % replacement_text, 'replace to:', replace_to)
5321 dbg(indent=0, suspend=0)
5322 return valid_paste, replacement_text, replace_to
5323
5324
5325 def _Paste( self, value=None, raise_on_invalid=False, just_return_value=False ):
5326 """
5327 Used to override the base control's .Paste() function,
5328 with our own that does validation.
5329 Note: _Paste must be called from a Paste() override in the
5330 derived control because the mixin functions can't override a
5331 method of a sibling class.
5332 """
5333 dbg('MaskedEditMixin::_Paste (value = "%s")' % value, indent=1)
5334 if value is None:
5335 paste_text = self._getClipboardContents()
5336 else:
5337 paste_text = value
5338
5339 if paste_text is not None:
5340 dbg('paste text: "%s"' % paste_text)
5341 # (conversion will raise ValueError if paste isn't legal)
5342 sel_start, sel_to = self._GetSelection()
5343 dbg('selection:', (sel_start, sel_to))
5344
5345 # special case: handle allowInsert fields properly
5346 field = self._FindField(sel_start)
5347 edit_start, edit_end = field._extent
5348 new_pos = None
5349 if field._allowInsert and sel_to <= edit_end and sel_start + len(paste_text) < edit_end:
5350 new_pos = sel_start + len(paste_text) # store for subsequent positioning
5351 paste_text = paste_text + self._GetValue()[sel_to:edit_end].rstrip()
5352 dbg('paste within insertable field; adjusted paste_text: "%s"' % paste_text, 'end:', edit_end)
5353 sel_to = sel_start + len(paste_text)
5354
5355 # Another special case: paste won't fit, but it's a right-insert field where entire
5356 # non-empty value is selected, and there's room if the selection is expanded leftward:
5357 if( len(paste_text) > sel_to - sel_start
5358 and field._insertRight
5359 and sel_start > edit_start
5360 and sel_to >= edit_end
5361 and not self._GetValue()[edit_start:sel_start].strip() ):
5362 # text won't fit within selection, but left of selection is empty;
5363 # check to see if we can expand selection to accomodate the value:
5364 empty_space = sel_start - edit_start
5365 amount_needed = len(paste_text) - (sel_to - sel_start)
5366 if amount_needed <= empty_space:
5367 sel_start -= amount_needed
5368 dbg('expanded selection to:', (sel_start, sel_to))
5369
5370
5371 # another special case: deal with signed values properly:
5372 if self._signOk:
5373 signedvalue, signpos, right_signpos = self._getSignedValue()
5374 paste_signpos = paste_text.find('-')
5375 if paste_signpos == -1:
5376 paste_signpos = paste_text.find('(')
5377
5378 # if paste text will result in signed value:
5379 ## dbg('paste_signpos != -1?', paste_signpos != -1)
5380 ## dbg('sel_start:', sel_start, 'signpos:', signpos)
5381 ## dbg('field._insertRight?', field._insertRight)
5382 ## dbg('sel_start - len(paste_text) >= signpos?', sel_start - len(paste_text) <= signpos)
5383 if paste_signpos != -1 and (sel_start <= signpos
5384 or (field._insertRight and sel_start - len(paste_text) <= signpos)):
5385 signed = True
5386 else:
5387 signed = False
5388 # remove "sign" from paste text, so we can auto-adjust for sign type after paste:
5389 paste_text = paste_text.replace('-', ' ').replace('(',' ').replace(')','')
5390 dbg('unsigned paste text: "%s"' % paste_text)
5391 else:
5392 signed = False
5393
5394 # another special case: deal with insert-right fields when selection is empty and
5395 # cursor is at end of field:
5396 ## dbg('field._insertRight?', field._insertRight)
5397 ## dbg('sel_start == edit_end?', sel_start == edit_end)
5398 ## dbg('sel_start', sel_start, 'sel_to', sel_to)
5399 if field._insertRight and sel_start == edit_end and sel_start == sel_to:
5400 sel_start -= len(paste_text)
5401 if sel_start < 0:
5402 sel_start = 0
5403 dbg('adjusted selection:', (sel_start, sel_to))
5404
5405 try:
5406 valid_paste, replacement_text, replace_to = self._validatePaste(paste_text, sel_start, sel_to, raise_on_invalid)
5407 except:
5408 dbg('exception thrown', indent=0)
5409 raise
5410
5411 if not valid_paste:
5412 dbg('paste text not legal for the selection or portion of the control following the cursor;')
5413 if not wx.Validator_IsSilent():
5414 wx.Bell()
5415 dbg(indent=0)
5416 return False
5417 # else...
5418 text = self._eraseSelection()
5419
5420 new_text = text[:sel_start] + replacement_text + text[replace_to:]
5421 if new_text:
5422 new_text = string.ljust(new_text,self._masklength)
5423 if signed:
5424 new_text, signpos, right_signpos = self._getSignedValue(candidate=new_text)
5425 if new_text:
5426 if self._useParens:
5427 new_text = new_text[:signpos] + '(' + new_text[signpos+1:right_signpos] + ')' + new_text[right_signpos+1:]
5428 else:
5429 new_text = new_text[:signpos] + '-' + new_text[signpos+1:]
5430 if not self._isNeg:
5431 self._isNeg = 1
5432
5433 dbg("new_text:", '"'+new_text+'"')
5434
5435 if not just_return_value:
5436 if new_text == '':
5437 self.ClearValue()
5438 else:
5439 wx.CallAfter(self._SetValue, new_text)
5440 if new_pos is None:
5441 new_pos = sel_start + len(replacement_text)
5442 wx.CallAfter(self._SetInsertionPoint, new_pos)
5443 else:
5444 dbg(indent=0)
5445 return new_text
5446 elif just_return_value:
5447 dbg(indent=0)
5448 return self._GetValue()
5449 dbg(indent=0)
5450
5451 def _Undo(self):
5452 """ Provides an Undo() method in base controls. """
5453 dbg("MaskedEditMixin::_Undo", indent=1)
5454 value = self._GetValue()
5455 prev = self._prevValue
5456 dbg('current value: "%s"' % value)
5457 dbg('previous value: "%s"' % prev)
5458 if prev is None:
5459 dbg('no previous value', indent=0)
5460 return
5461
5462 elif value != prev:
5463 # Determine what to select: (relies on fixed-length strings)
5464 # (This is a lot harder than it would first appear, because
5465 # of mask chars that stay fixed, and so break up the "diff"...)
5466
5467 # Determine where they start to differ:
5468 i = 0
5469 length = len(value) # (both are same length in masked control)
5470
5471 while( value[:i] == prev[:i] ):
5472 i += 1
5473 sel_start = i - 1
5474
5475
5476 # handle signed values carefully, so undo from signed to unsigned or vice-versa
5477 # works properly:
5478 if self._signOk:
5479 text, signpos, right_signpos = self._getSignedValue(candidate=prev)
5480 if self._useParens:
5481 if prev[signpos] == '(' and prev[right_signpos] == ')':
5482 self._isNeg = True
5483 else:
5484 self._isNeg = False
5485 # eliminate source of "far-end" undo difference if using balanced parens:
5486 value = value.replace(')', ' ')
5487 prev = prev.replace(')', ' ')
5488 elif prev[signpos] == '-':
5489 self._isNeg = True
5490 else:
5491 self._isNeg = False
5492
5493 # Determine where they stop differing in "undo" result:
5494 sm = difflib.SequenceMatcher(None, a=value, b=prev)
5495 i, j, k = sm.find_longest_match(sel_start, length, sel_start, length)
5496 dbg('i,j,k = ', (i,j,k), 'value[i:i+k] = "%s"' % value[i:i+k], 'prev[j:j+k] = "%s"' % prev[j:j+k] )
5497
5498 if k == 0: # no match found; select to end
5499 sel_to = length
5500 else:
5501 code_5tuples = sm.get_opcodes()
5502 for op, i1, i2, j1, j2 in code_5tuples:
5503 dbg("%7s value[%d:%d] (%s) prev[%d:%d] (%s)" %
5504 (op, i1, i2, value[i1:i2], j1, j2, prev[j1:j2]))
5505
5506 diff_found = False
5507 # look backward through operations needed to produce "previous" value;
5508 # first change wins:
5509 for next_op in range(len(code_5tuples)-1, -1, -1):
5510 op, i1, i2, j1, j2 = code_5tuples[next_op]
5511 dbg('value[i1:i2]: "%s"' % value[i1:i2], 'template[i1:i2] "%s"' % self._template[i1:i2])
5512 if op == 'insert' and prev[j1:j2] != self._template[j1:j2]:
5513 dbg('insert found: selection =>', (j1, j2))
5514 sel_start = j1
5515 sel_to = j2
5516 diff_found = True
5517 break
5518 elif op == 'delete' and value[i1:i2] != self._template[i1:i2]:
5519 field = self._FindField(i2)
5520 edit_start, edit_end = field._extent
5521 if field._insertRight and i2 == edit_end:
5522 sel_start = i2
5523 sel_to = i2
5524 else:
5525 sel_start = i1
5526 sel_to = j1
5527 dbg('delete found: selection =>', (sel_start, sel_to))
5528 diff_found = True
5529 break
5530 elif op == 'replace':
5531 dbg('replace found: selection =>', (j1, j2))
5532 sel_start = j1
5533 sel_to = j2
5534 diff_found = True
5535 break
5536
5537
5538 if diff_found:
5539 # now go forwards, looking for earlier changes:
5540 for next_op in range(len(code_5tuples)):
5541 op, i1, i2, j1, j2 = code_5tuples[next_op]
5542 field = self._FindField(i1)
5543 if op == 'equal':
5544 continue
5545 elif op == 'replace':
5546 dbg('setting sel_start to', i1)
5547 sel_start = i1
5548 break
5549 elif op == 'insert' and not value[i1:i2]:
5550 dbg('forward %s found' % op)
5551 if prev[j1:j2].strip():
5552 dbg('item to insert non-empty; setting sel_start to', j1)
5553 sel_start = j1
5554 break
5555 elif not field._insertRight:
5556 dbg('setting sel_start to inserted space:', j1)
5557 sel_start = j1
5558 break
5559 elif op == 'delete' and field._insertRight and not value[i1:i2].lstrip():
5560 continue
5561 else:
5562 # we've got what we need
5563 break
5564
5565
5566 if not diff_found:
5567 dbg('no insert,delete or replace found (!)')
5568 # do "left-insert"-centric processing of difference based on l.c.s.:
5569 if i == j and j != sel_start: # match starts after start of selection
5570 sel_to = sel_start + (j-sel_start) # select to start of match
5571 else:
5572 sel_to = j # (change ends at j)
5573
5574
5575 # There are several situations where the calculated difference is
5576 # not what we want to select. If changing sign, or just adding
5577 # group characters, we really don't want to highlight the characters
5578 # changed, but instead leave the cursor where it is.
5579 # Also, there a situations in which the difference can be ambiguous;
5580 # Consider:
5581 #
5582 # current value: 11234
5583 # previous value: 1111234
5584 #
5585 # Where did the cursor actually lie and which 1s were selected on the delete
5586 # operation?
5587 #
5588 # Also, difflib can "get it wrong;" Consider:
5589 #
5590 # current value: " 128.66"
5591 # previous value: " 121.86"
5592 #
5593 # difflib produces the following opcodes, which are sub-optimal:
5594 # equal value[0:9] ( 12) prev[0:9] ( 12)
5595 # insert value[9:9] () prev[9:11] (1.)
5596 # equal value[9:10] (8) prev[11:12] (8)
5597 # delete value[10:11] (.) prev[12:12] ()
5598 # equal value[11:12] (6) prev[12:13] (6)
5599 # delete value[12:13] (6) prev[13:13] ()
5600 #
5601 # This should have been:
5602 # equal value[0:9] ( 12) prev[0:9] ( 12)
5603 # replace value[9:11] (8.6) prev[9:11] (1.8)
5604 # equal value[12:13] (6) prev[12:13] (6)
5605 #
5606 # But it didn't figure this out!
5607 #
5608 # To get all this right, we use the previous selection recorded to help us...
5609
5610 if (sel_start, sel_to) != self._prevSelection:
5611 dbg('calculated selection', (sel_start, sel_to), "doesn't match previous", self._prevSelection)
5612
5613 prev_sel_start, prev_sel_to = self._prevSelection
5614 field = self._FindField(sel_start)
5615
5616 if self._signOk and (self._prevValue[sel_start] in ('-', '(', ')')
5617 or self._curValue[sel_start] in ('-', '(', ')')):
5618 # change of sign; leave cursor alone...
5619 sel_start, sel_to = self._prevSelection
5620
5621 elif field._groupdigits and (self._curValue[sel_start:sel_to] == field._groupChar
5622 or self._prevValue[sel_start:sel_to] == field._groupChar):
5623 # do not highlight grouping changes
5624 sel_start, sel_to = self._prevSelection
5625
5626 else:
5627 calc_select_len = sel_to - sel_start
5628 prev_select_len = prev_sel_to - prev_sel_start
5629
5630 dbg('sel_start == prev_sel_start', sel_start == prev_sel_start)
5631 dbg('sel_to > prev_sel_to', sel_to > prev_sel_to)
5632
5633 if prev_select_len >= calc_select_len:
5634 # old selection was bigger; trust it:
5635 sel_start, sel_to = self._prevSelection
5636
5637 elif( sel_to > prev_sel_to # calculated select past last selection
5638 and prev_sel_to < len(self._template) # and prev_sel_to not at end of control
5639 and sel_to == len(self._template) ): # and calculated selection goes to end of control
5640
5641 i, j, k = sm.find_longest_match(prev_sel_to, length, prev_sel_to, length)
5642 dbg('i,j,k = ', (i,j,k), 'value[i:i+k] = "%s"' % value[i:i+k], 'prev[j:j+k] = "%s"' % prev[j:j+k] )
5643 if k > 0:
5644 # difflib must not have optimized opcodes properly;
5645 sel_to = j
5646
5647 else:
5648 # look for possible ambiguous diff:
5649
5650 # if last change resulted in no selection, test from resulting cursor position:
5651 if prev_sel_start == prev_sel_to:
5652 calc_select_len = sel_to - sel_start
5653 field = self._FindField(prev_sel_start)
5654
5655 # determine which way to search from last cursor position for ambiguous change:
5656 if field._insertRight:
5657 test_sel_start = prev_sel_start
5658 test_sel_to = prev_sel_start + calc_select_len
5659 else:
5660 test_sel_start = prev_sel_start - calc_select_len
5661 test_sel_to = prev_sel_start
5662 else:
5663 test_sel_start, test_sel_to = prev_sel_start, prev_sel_to
5664
5665 dbg('test selection:', (test_sel_start, test_sel_to))
5666 dbg('calc change: "%s"' % self._prevValue[sel_start:sel_to])
5667 dbg('test change: "%s"' % self._prevValue[test_sel_start:test_sel_to])
5668
5669 # if calculated selection spans characters, and same characters
5670 # "before" the previous insertion point are present there as well,
5671 # select the ones related to the last known selection instead.
5672 if( sel_start != sel_to
5673 and test_sel_to < len(self._template)
5674 and self._prevValue[test_sel_start:test_sel_to] == self._prevValue[sel_start:sel_to] ):
5675
5676 sel_start, sel_to = test_sel_start, test_sel_to
5677
5678 dbg('sel_start, sel_to:', sel_start, sel_to)
5679 dbg('previous value: "%s"' % self._prevValue)
5680 self._SetValue(self._prevValue)
5681 self._SetInsertionPoint(sel_start)
5682 self._SetSelection(sel_start, sel_to)
5683 else:
5684 dbg('no difference between previous value')
5685 dbg(indent=0)
5686
5687
5688 def _OnClear(self, event):
5689 """ Provides an action for context menu delete operation """
5690 self.ClearValue()
5691
5692
5693 def _OnContextMenu(self, event):
5694 dbg('MaskedEditMixin::OnContextMenu()', indent=1)
5695 menu = wxMenu()
5696 menu.Append(wxID_UNDO, "Undo", "")
5697 menu.AppendSeparator()
5698 menu.Append(wxID_CUT, "Cut", "")
5699 menu.Append(wxID_COPY, "Copy", "")
5700 menu.Append(wxID_PASTE, "Paste", "")
5701 menu.Append(wxID_CLEAR, "Delete", "")
5702 menu.AppendSeparator()
5703 menu.Append(wxID_SELECTALL, "Select All", "")
5704
5705 EVT_MENU(menu, wxID_UNDO, self._OnCtrl_Z)
5706 EVT_MENU(menu, wxID_CUT, self._OnCtrl_X)
5707 EVT_MENU(menu, wxID_COPY, self._OnCtrl_C)
5708 EVT_MENU(menu, wxID_PASTE, self._OnCtrl_V)
5709 EVT_MENU(menu, wxID_CLEAR, self._OnClear)
5710 EVT_MENU(menu, wxID_SELECTALL, self._OnCtrl_A)
5711
5712 # ## WSS: The base control apparently handles
5713 # enable/disable of wID_CUT, wxID_COPY, wxID_PASTE
5714 # and wxID_CLEAR menu items even if the menu is one
5715 # we created. However, it doesn't do undo properly,
5716 # so we're keeping track of previous values ourselves.
5717 # Therefore, we have to override the default update for
5718 # that item on the menu:
5719 EVT_UPDATE_UI(self, wxID_UNDO, self._UndoUpdateUI)
5720 self._contextMenu = menu
5721
5722 self.PopupMenu(menu, event.GetPosition())
5723 menu.Destroy()
5724 self._contextMenu = None
5725 dbg(indent=0)
5726
5727 def _UndoUpdateUI(self, event):
5728 if self._prevValue is None or self._prevValue == self._curValue:
5729 self._contextMenu.Enable(wxID_UNDO, False)
5730 else:
5731 self._contextMenu.Enable(wxID_UNDO, True)
5732
5733
5734 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
5735
5736 class MaskedTextCtrl( wx.TextCtrl, MaskedEditMixin ):
5737 """
5738 This is the primary derivation from MaskedEditMixin. It provides
5739 a general masked text control that can be configured with different
5740 masks.
5741 """
5742
5743 def __init__( self, parent, id=-1, value = '',
5744 pos = wx.DefaultPosition,
5745 size = wx.DefaultSize,
5746 style = wx.TE_PROCESS_TAB,
5747 validator=wx.DefaultValidator, ## placeholder provided for data-transfer logic
5748 name = 'maskedTextCtrl',
5749 setupEventHandling = True, ## setup event handling by default
5750 **kwargs):
5751
5752 wx.TextCtrl.__init__(self, parent, id, value='',
5753 pos=pos, size = size,
5754 style=style, validator=validator,
5755 name=name)
5756
5757 self.controlInitialized = True
5758 MaskedEditMixin.__init__( self, name, **kwargs )
5759 self._SetInitialValue(value)
5760
5761 if setupEventHandling:
5762 ## Setup event handlers
5763 self.Bind(wx.EVT_SET_FOCUS, self._OnFocus ) ## defeat automatic full selection
5764 self.Bind(wx.EVT_KILL_FOCUS, self._OnKillFocus ) ## run internal validator
5765 self.Bind(wx.EVT_LEFT_DCLICK, self._OnDoubleClick) ## select field under cursor on dclick
5766 self.Bind(wx.EVT_RIGHT_UP, self._OnContextMenu ) ## bring up an appropriate context menu
5767 self.Bind(wx.EVT_KEY_DOWN, self._OnKeyDown ) ## capture control events not normally seen, eg ctrl-tab.
5768 self.Bind(wx.EVT_CHAR, self._OnChar ) ## handle each keypress
5769 self.Bind(wx.EVT_TEXT, self._OnTextChange ) ## color control appropriately & keep
5770 ## track of previous value for undo
5771
5772
5773 def __repr__(self):
5774 return "<MaskedTextCtrl: %s>" % self.GetValue()
5775
5776
5777 def _GetSelection(self):
5778 """
5779 Allow mixin to get the text selection of this control.
5780 REQUIRED by any class derived from MaskedEditMixin.
5781 """
5782 return self.GetSelection()
5783
5784 def _SetSelection(self, sel_start, sel_to):
5785 """
5786 Allow mixin to set the text selection of this control.
5787 REQUIRED by any class derived from MaskedEditMixin.
5788 """
5789 ## dbg("MaskedTextCtrl::_SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
5790 return self.SetSelection( sel_start, sel_to )
5791
5792 def SetSelection(self, sel_start, sel_to):
5793 """
5794 This is just for debugging...
5795 """
5796 dbg("MaskedTextCtrl::SetSelection(%(sel_start)d, %(sel_to)d)" % locals())
5797 wx.TextCtrl.SetSelection(self, sel_start, sel_to)
5798
5799
5800 def _GetInsertionPoint(self):
5801 return self.GetInsertionPoint()
5802
5803 def _SetInsertionPoint(self, pos):
5804 ## dbg("MaskedTextCtrl::_SetInsertionPoint(%(pos)d)" % locals())
5805 self.SetInsertionPoint(pos)
5806
5807 def SetInsertionPoint(self, pos):
5808 """
5809 This is just for debugging...
5810 """
5811 dbg("MaskedTextCtrl::SetInsertionPoint(%(pos)d)" % locals())
5812 wx.TextCtrl.SetInsertionPoint(self, pos)
5813
5814
5815 def _GetValue(self):
5816 """
5817 Allow mixin to get the raw value of the control with this function.
5818 REQUIRED by any class derived from MaskedEditMixin.
5819 """
5820 return self.GetValue()
5821
5822 def _SetValue(self, value):
5823 """
5824 Allow mixin to set the raw value of the control with this function.
5825 REQUIRED by any class derived from MaskedEditMixin.
5826 """
5827 dbg('MaskedTextCtrl::_SetValue("%(value)s")' % locals(), indent=1)
5828 # Record current selection and insertion point, for undo
5829 self._prevSelection = self._GetSelection()
5830 self._prevInsertionPoint = self._GetInsertionPoint()
5831 wx.TextCtrl.SetValue(self, value)
5832 dbg(indent=0)
5833
5834 def SetValue(self, value):
5835 """
5836 This function redefines the externally accessible .SetValue to be
5837 a smart "paste" of the text in question, so as not to corrupt the
5838 masked control. NOTE: this must be done in the class derived
5839 from the base wx control.
5840 """
5841 dbg('MaskedTextCtrl::SetValue = "%s"' % value, indent=1)
5842
5843 if not self._mask:
5844 wx.TextCtrl.SetValue(self, value) # revert to base control behavior
5845 return
5846
5847 # empty previous contents, replacing entire value:
5848 self._SetInsertionPoint(0)
5849 self._SetSelection(0, self._masklength)
5850 if self._signOk and self._useParens:
5851 signpos = value.find('-')
5852 if signpos != -1:
5853 value = value[:signpos] + '(' + value[signpos+1:].strip() + ')'
5854 elif value.find(')') == -1 and len(value) < self._masklength:
5855 value += ' ' # add place holder for reserved space for right paren
5856
5857 if( len(value) < self._masklength # value shorter than control
5858 and (self._isFloat or self._isInt) # and it's a numeric control
5859 and self._ctrl_constraints._alignRight ): # and it's a right-aligned control
5860
5861 dbg('len(value)', len(value), ' < self._masklength', self._masklength)
5862 # try to intelligently "pad out" the value to the right size:
5863 value = self._template[0:self._masklength - len(value)] + value
5864 if self._isFloat and value.find('.') == -1:
5865 value = value[1:]
5866 dbg('padded value = "%s"' % value)
5867
5868 # make SetValue behave the same as if you had typed the value in:
5869 try:
5870 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
5871 if self._isFloat:
5872 self._isNeg = False # (clear current assumptions)
5873 value = self._adjustFloat(value)
5874 elif self._isInt:
5875 self._isNeg = False # (clear current assumptions)
5876 value = self._adjustInt(value)
5877 elif self._isDate and not self.IsValid(value) and self._4digityear:
5878 value = self._adjustDate(value, fixcentury=True)
5879 except ValueError:
5880 # If date, year might be 2 digits vs. 4; try adjusting it:
5881 if self._isDate and self._4digityear:
5882 dateparts = value.split(' ')
5883 dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
5884 value = string.join(dateparts, ' ')
5885 dbg('adjusted value: "%s"' % value)
5886 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
5887 else:
5888 dbg('exception thrown', indent=0)
5889 raise
5890
5891 self._SetValue(value)
5892 ## dbg('queuing insertion after .SetValue', self._masklength)
5893 wx.CallAfter(self._SetInsertionPoint, self._masklength)
5894 wx.CallAfter(self._SetSelection, self._masklength, self._masklength)
5895 dbg(indent=0)
5896
5897
5898 def Clear(self):
5899 """ Blanks the current control value by replacing it with the default value."""
5900 dbg("MaskedTextCtrl::Clear - value reset to default value (template)")
5901 if self._mask:
5902 self.ClearValue()
5903 else:
5904 wx.TextCtrl.Clear(self) # else revert to base control behavior
5905
5906
5907 def _Refresh(self):
5908 """
5909 Allow mixin to refresh the base control with this function.
5910 REQUIRED by any class derived from MaskedEditMixin.
5911 """
5912 dbg('MaskedTextCtrl::_Refresh', indent=1)
5913 wx.TextCtrl.Refresh(self)
5914 dbg(indent=0)
5915
5916
5917 def Refresh(self):
5918 """
5919 This function redefines the externally accessible .Refresh() to
5920 validate the contents of the masked control as it refreshes.
5921 NOTE: this must be done in the class derived from the base wx control.
5922 """
5923 dbg('MaskedTextCtrl::Refresh', indent=1)
5924 self._CheckValid()
5925 self._Refresh()
5926 dbg(indent=0)
5927
5928
5929 def _IsEditable(self):
5930 """
5931 Allow mixin to determine if the base control is editable with this function.
5932 REQUIRED by any class derived from MaskedEditMixin.
5933 """
5934 return wx.TextCtrl.IsEditable(self)
5935
5936
5937 def Cut(self):
5938 """
5939 This function redefines the externally accessible .Cut to be
5940 a smart "erase" of the text in question, so as not to corrupt the
5941 masked control. NOTE: this must be done in the class derived
5942 from the base wx control.
5943 """
5944 if self._mask:
5945 self._Cut() # call the mixin's Cut method
5946 else:
5947 wx.TextCtrl.Cut(self) # else revert to base control behavior
5948
5949
5950 def Paste(self):
5951 """
5952 This function redefines the externally accessible .Paste to be
5953 a smart "paste" of the text in question, so as not to corrupt the
5954 masked control. NOTE: this must be done in the class derived
5955 from the base wx control.
5956 """
5957 if self._mask:
5958 self._Paste() # call the mixin's Paste method
5959 else:
5960 wx.TextCtrl.Paste(self, value) # else revert to base control behavior
5961
5962
5963 def Undo(self):
5964 """
5965 This function defines the undo operation for the control. (The default
5966 undo is 1-deep.)
5967 """
5968 if self._mask:
5969 self._Undo()
5970 else:
5971 wx.TextCtrl.Undo(self) # else revert to base control behavior
5972
5973
5974 def IsModified(self):
5975 """
5976 This function overrides the raw wxTextCtrl method, because the
5977 masked edit mixin uses SetValue to change the value, which doesn't
5978 modify the state of this attribute. So, we keep track on each
5979 keystroke to see if the value changes, and if so, it's been
5980 modified.
5981 """
5982 return wx.TextCtrl.IsModified(self) or self.modified
5983
5984
5985 def _CalcSize(self, size=None):
5986 """
5987 Calculate automatic size if allowed; use base mixin function.
5988 """
5989 return self._calcSize(size)
5990
5991
5992 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
5993 ## Because calling SetSelection programmatically does not fire EVT_COMBOBOX
5994 ## events, we have to do it ourselves when we auto-complete.
5995 class MaskedComboBoxSelectEvent(wx.PyCommandEvent):
5996 def __init__(self, id, selection = 0, object=None):
5997 wx.PyCommandEvent.__init__(self, wx.wxEVT_COMMAND_COMBOBOX_SELECTED, id)
5998
5999 self.__selection = selection
6000 self.SetEventObject(object)
6001
6002 def GetSelection(self):
6003 """Retrieve the value of the control at the time
6004 this event was generated."""
6005 return self.__selection
6006
6007
6008 class MaskedComboBox( wx.ComboBox, MaskedEditMixin ):
6009 """
6010 This masked edit control adds the ability to use a masked input
6011 on a combobox, and do auto-complete of such values.
6012 """
6013 def __init__( self, parent, id=-1, value = '',
6014 pos = wx.DefaultPosition,
6015 size = wx.DefaultSize,
6016 choices = [],
6017 style = wx.CB_DROPDOWN,
6018 validator = wx.DefaultValidator,
6019 name = "maskedComboBox",
6020 setupEventHandling = True, ## setup event handling by default):
6021 **kwargs):
6022
6023
6024 # This is necessary, because wxComboBox currently provides no
6025 # method for determining later if this was specified in the
6026 # constructor for the control...
6027 self.__readonly = style & wx.CB_READONLY == wx.CB_READONLY
6028
6029 kwargs['choices'] = choices ## set up maskededit to work with choice list too
6030
6031 ## Since combobox completion is case-insensitive, always validate same way
6032 if not kwargs.has_key('compareNoCase'):
6033 kwargs['compareNoCase'] = True
6034
6035 MaskedEditMixin.__init__( self, name, **kwargs )
6036 self._choices = self._ctrl_constraints._choices
6037 dbg('self._choices:', self._choices)
6038
6039 if self._ctrl_constraints._alignRight:
6040 choices = [choice.rjust(self._masklength) for choice in choices]
6041 else:
6042 choices = [choice.ljust(self._masklength) for choice in choices]
6043
6044 wx.ComboBox.__init__(self, parent, id, value='',
6045 pos=pos, size = size,
6046 choices=choices, style=style|wx.WANTS_CHARS,
6047 validator=validator,
6048 name=name)
6049
6050 self.controlInitialized = True
6051
6052 # Set control font - fixed width by default
6053 self._setFont()
6054
6055 if self._autofit:
6056 self.SetClientSize(self._CalcSize())
6057
6058 if value:
6059 # ensure value is width of the mask of the control:
6060 if self._ctrl_constraints._alignRight:
6061 value = value.rjust(self._masklength)
6062 else:
6063 value = value.ljust(self._masklength)
6064
6065 if self.__readonly:
6066 self.SetStringSelection(value)
6067 else:
6068 self._SetInitialValue(value)
6069
6070
6071 self._SetKeycodeHandler(wx.WXK_UP, self.OnSelectChoice)
6072 self._SetKeycodeHandler(wx.WXK_DOWN, self.OnSelectChoice)
6073
6074 if setupEventHandling:
6075 ## Setup event handlers
6076 self.Bind(wx.EVT_SET_FOCUS, self._OnFocus ) ## defeat automatic full selection
6077 self.Bind(wx.EVT_KILL_FOCUS, self._OnKillFocus ) ## run internal validator
6078 self.Bind(wx.EVT_LEFT_DCLICK, self._OnDoubleClick) ## select field under cursor on dclick
6079 self.Bind(wx.EVT_RIGHT_UP, self._OnContextMenu ) ## bring up an appropriate context menu
6080 self.Bind(wx.EVT_CHAR, self._OnChar ) ## handle each keypress
6081 self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown ) ## for special processing of up/down keys
6082 self.Bind(wx.EVT_KEY_DOWN, self._OnKeyDown ) ## for processing the rest of the control keys
6083 ## (next in evt chain)
6084 self.Bind(wx.EVT_TEXT, self._OnTextChange ) ## color control appropriately & keep
6085 ## track of previous value for undo
6086
6087
6088
6089 def __repr__(self):
6090 return "<MaskedComboBox: %s>" % self.GetValue()
6091
6092
6093 def _CalcSize(self, size=None):
6094 """
6095 Calculate automatic size if allowed; augment base mixin function
6096 to account for the selector button.
6097 """
6098 size = self._calcSize(size)
6099 return (size[0]+20, size[1])
6100
6101
6102 def _GetSelection(self):
6103 """
6104 Allow mixin to get the text selection of this control.
6105 REQUIRED by any class derived from MaskedEditMixin.
6106 """
6107 return self.GetMark()
6108
6109 def _SetSelection(self, sel_start, sel_to):
6110 """
6111 Allow mixin to set the text selection of this control.
6112 REQUIRED by any class derived from MaskedEditMixin.
6113 """
6114 return self.SetMark( sel_start, sel_to )
6115
6116
6117 def _GetInsertionPoint(self):
6118 return self.GetInsertionPoint()
6119
6120 def _SetInsertionPoint(self, pos):
6121 self.SetInsertionPoint(pos)
6122
6123
6124 def _GetValue(self):
6125 """
6126 Allow mixin to get the raw value of the control with this function.
6127 REQUIRED by any class derived from MaskedEditMixin.
6128 """
6129 return self.GetValue()
6130
6131 def _SetValue(self, value):
6132 """
6133 Allow mixin to set the raw value of the control with this function.
6134 REQUIRED by any class derived from MaskedEditMixin.
6135 """
6136 # For wxComboBox, ensure that values are properly padded so that
6137 # if varying length choices are supplied, they always show up
6138 # in the window properly, and will be the appropriate length
6139 # to match the mask:
6140 if self._ctrl_constraints._alignRight:
6141 value = value.rjust(self._masklength)
6142 else:
6143 value = value.ljust(self._masklength)
6144
6145 # Record current selection and insertion point, for undo
6146 self._prevSelection = self._GetSelection()
6147 self._prevInsertionPoint = self._GetInsertionPoint()
6148 wx.ComboBox.SetValue(self, value)
6149 # text change events don't always fire, so we check validity here
6150 # to make certain formatting is applied:
6151 self._CheckValid()
6152
6153 def SetValue(self, value):
6154 """
6155 This function redefines the externally accessible .SetValue to be
6156 a smart "paste" of the text in question, so as not to corrupt the
6157 masked control. NOTE: this must be done in the class derived
6158 from the base wx control.
6159 """
6160 if not self._mask:
6161 wx.ComboBox.SetValue(value) # revert to base control behavior
6162 return
6163 # else...
6164 # empty previous contents, replacing entire value:
6165 self._SetInsertionPoint(0)
6166 self._SetSelection(0, self._masklength)
6167
6168 if( len(value) < self._masklength # value shorter than control
6169 and (self._isFloat or self._isInt) # and it's a numeric control
6170 and self._ctrl_constraints._alignRight ): # and it's a right-aligned control
6171 # try to intelligently "pad out" the value to the right size:
6172 value = self._template[0:self._masklength - len(value)] + value
6173 dbg('padded value = "%s"' % value)
6174
6175 # For wxComboBox, ensure that values are properly padded so that
6176 # if varying length choices are supplied, they always show up
6177 # in the window properly, and will be the appropriate length
6178 # to match the mask:
6179 elif self._ctrl_constraints._alignRight:
6180 value = value.rjust(self._masklength)
6181 else:
6182 value = value.ljust(self._masklength)
6183
6184
6185 # make SetValue behave the same as if you had typed the value in:
6186 try:
6187 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
6188 if self._isFloat:
6189 self._isNeg = False # (clear current assumptions)
6190 value = self._adjustFloat(value)
6191 elif self._isInt:
6192 self._isNeg = False # (clear current assumptions)
6193 value = self._adjustInt(value)
6194 elif self._isDate and not self.IsValid(value) and self._4digityear:
6195 value = self._adjustDate(value, fixcentury=True)
6196 except ValueError:
6197 # If date, year might be 2 digits vs. 4; try adjusting it:
6198 if self._isDate and self._4digityear:
6199 dateparts = value.split(' ')
6200 dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True)
6201 value = string.join(dateparts, ' ')
6202 dbg('adjusted value: "%s"' % value)
6203 value = self._Paste(value, raise_on_invalid=True, just_return_value=True)
6204 else:
6205 raise
6206
6207 self._SetValue(value)
6208 ## dbg('queuing insertion after .SetValue', self._masklength)
6209 wx.CallAfter(self._SetInsertionPoint, self._masklength)
6210 wx.CallAfter(self._SetSelection, self._masklength, self._masklength)
6211
6212
6213 def _Refresh(self):
6214 """
6215 Allow mixin to refresh the base control with this function.
6216 REQUIRED by any class derived from MaskedEditMixin.
6217 """
6218 wx.ComboBox.Refresh(self)
6219
6220 def Refresh(self):
6221 """
6222 This function redefines the externally accessible .Refresh() to
6223 validate the contents of the masked control as it refreshes.
6224 NOTE: this must be done in the class derived from the base wx control.
6225 """
6226 self._CheckValid()
6227 self._Refresh()
6228
6229
6230 def _IsEditable(self):
6231 """
6232 Allow mixin to determine if the base control is editable with this function.
6233 REQUIRED by any class derived from MaskedEditMixin.
6234 """
6235 return not self.__readonly
6236
6237
6238 def Cut(self):
6239 """
6240 This function redefines the externally accessible .Cut to be
6241 a smart "erase" of the text in question, so as not to corrupt the
6242 masked control. NOTE: this must be done in the class derived
6243 from the base wx control.
6244 """
6245 if self._mask:
6246 self._Cut() # call the mixin's Cut method
6247 else:
6248 wx.ComboBox.Cut(self) # else revert to base control behavior
6249
6250
6251 def Paste(self):
6252 """
6253 This function redefines the externally accessible .Paste to be
6254 a smart "paste" of the text in question, so as not to corrupt the
6255 masked control. NOTE: this must be done in the class derived
6256 from the base wx control.
6257 """
6258 if self._mask:
6259 self._Paste() # call the mixin's Paste method
6260 else:
6261 wx.ComboBox.Paste(self) # else revert to base control behavior
6262
6263
6264 def Undo(self):
6265 """
6266 This function defines the undo operation for the control. (The default
6267 undo is 1-deep.)
6268 """
6269 if self._mask:
6270 self._Undo()
6271 else:
6272 wx.ComboBox.Undo() # else revert to base control behavior
6273
6274
6275 def Append( self, choice, clientData=None ):
6276 """
6277 This function override is necessary so we can keep track of any additions to the list
6278 of choices, because wxComboBox doesn't have an accessor for the choice list.
6279 The code here is the same as in the SetParameters() mixin function, but is
6280 done for the individual value as appended, so the list can be built incrementally
6281 without speed penalty.
6282 """
6283 if self._mask:
6284 if type(choice) not in (types.StringType, types.UnicodeType):
6285 raise TypeError('%s: choices must be a sequence of strings' % str(self._index))
6286 elif not self.IsValid(choice):
6287 raise ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self._index), choice))
6288
6289 if not self._ctrl_constraints._choices:
6290 self._ctrl_constraints._compareChoices = []
6291 self._ctrl_constraints._choices = []
6292 self._hasList = True
6293
6294 compareChoice = choice.strip()
6295
6296 if self._ctrl_constraints._compareNoCase:
6297 compareChoice = compareChoice.lower()
6298
6299 if self._ctrl_constraints._alignRight:
6300 choice = choice.rjust(self._masklength)
6301 else:
6302 choice = choice.ljust(self._masklength)
6303 if self._ctrl_constraints._fillChar != ' ':
6304 choice = choice.replace(' ', self._fillChar)
6305 dbg('updated choice:', choice)
6306
6307
6308 self._ctrl_constraints._compareChoices.append(compareChoice)
6309 self._ctrl_constraints._choices.append(choice)
6310 self._choices = self._ctrl_constraints._choices # (for shorthand)
6311
6312 if( not self.IsValid(choice) and
6313 (not self._ctrl_constraints.IsEmpty(choice) or
6314 (self._ctrl_constraints.IsEmpty(choice) and self._ctrl_constraints._validRequired) ) ):
6315 raise ValueError('"%s" is not a valid value for the control "%s" as specified.' % (choice, self.name))
6316
6317 wx.ComboBox.Append(self, choice, clientData)
6318
6319
6320
6321 def Clear( self ):
6322 """
6323 This function override is necessary so we can keep track of any additions to the list
6324 of choices, because wxComboBox doesn't have an accessor for the choice list.
6325 """
6326 if self._mask:
6327 self._choices = []
6328 self._ctrl_constraints._autoCompleteIndex = -1
6329 if self._ctrl_constraints._choices:
6330 self.SetCtrlParameters(choices=[])
6331 wx.ComboBox.Clear(self)
6332
6333
6334 def SetCtrlParameters( self, **kwargs ):
6335 """
6336 Override mixin's default SetCtrlParameters to detect changes in choice list, so
6337 we can update the base control:
6338 """
6339 MaskedEditMixin.SetCtrlParameters(self, **kwargs )
6340 if( self.controlInitialized
6341 and (kwargs.has_key('choices') or self._choices != self._ctrl_constraints._choices) ):
6342 wx.ComboBox.Clear(self)
6343 self._choices = self._ctrl_constraints._choices
6344 for choice in self._choices:
6345 wx.ComboBox.Append( self, choice )
6346
6347
6348 def GetMark(self):
6349 """
6350 This function is a hack to make up for the fact that wxComboBox has no
6351 method for returning the selected portion of its edit control. It
6352 works, but has the nasty side effect of generating lots of intermediate
6353 events.
6354 """
6355 dbg(suspend=1) # turn off debugging around this function
6356 dbg('MaskedComboBox::GetMark', indent=1)
6357 if self.__readonly:
6358 dbg(indent=0)
6359 return 0, 0 # no selection possible for editing
6360 ## sel_start, sel_to = wxComboBox.GetMark(self) # what I'd *like* to have!
6361 sel_start = sel_to = self.GetInsertionPoint()
6362 dbg("current sel_start:", sel_start)
6363 value = self.GetValue()
6364 dbg('value: "%s"' % value)
6365
6366 self._ignoreChange = True # tell _OnTextChange() to ignore next event (if any)
6367
6368 wx.ComboBox.Cut(self)
6369 newvalue = self.GetValue()
6370 dbg("value after Cut operation:", newvalue)
6371
6372 if newvalue != value: # something was selected; calculate extent
6373 dbg("something selected")
6374 sel_to = sel_start + len(value) - len(newvalue)
6375 wx.ComboBox.SetValue(self, value) # restore original value and selection (still ignoring change)
6376 wx.ComboBox.SetInsertionPoint(self, sel_start)
6377 wx.ComboBox.SetMark(self, sel_start, sel_to)
6378
6379 self._ignoreChange = False # tell _OnTextChange() to pay attn again
6380
6381 dbg('computed selection:', sel_start, sel_to, indent=0, suspend=0)
6382 return sel_start, sel_to
6383
6384
6385 def SetSelection(self, index):
6386 """
6387 Necessary for bookkeeping on choice selection, to keep current value
6388 current.
6389 """
6390 dbg('MaskedComboBox::SetSelection(%d)' % index)
6391 if self._mask:
6392 self._prevValue = self._curValue
6393 self._curValue = self._choices[index]
6394 self._ctrl_constraints._autoCompleteIndex = index
6395 wx.ComboBox.SetSelection(self, index)
6396
6397
6398 def OnKeyDown(self, event):
6399 """
6400 This function is necessary because navigation and control key
6401 events do not seem to normally be seen by the wxComboBox's
6402 EVT_CHAR routine. (Tabs don't seem to be visible no matter
6403 what... {:-( )
6404 """
6405 if event.GetKeyCode() in self._nav + self._control:
6406 self._OnChar(event)
6407 return
6408 else:
6409 event.Skip() # let mixin default KeyDown behavior occur
6410
6411
6412 def OnSelectChoice(self, event):
6413 """
6414 This function appears to be necessary, because the processing done
6415 on the text of the control somehow interferes with the combobox's
6416 selection mechanism for the arrow keys.
6417 """
6418 dbg('MaskedComboBox::OnSelectChoice', indent=1)
6419
6420 if not self._mask:
6421 event.Skip()
6422 return
6423
6424 value = self.GetValue().strip()
6425
6426 if self._ctrl_constraints._compareNoCase:
6427 value = value.lower()
6428
6429 if event.GetKeyCode() == wx.WXK_UP:
6430 direction = -1
6431 else:
6432 direction = 1
6433 match_index, partial_match = self._autoComplete(
6434 direction,
6435 self._ctrl_constraints._compareChoices,
6436 value,
6437 self._ctrl_constraints._compareNoCase,
6438 current_index = self._ctrl_constraints._autoCompleteIndex)
6439 if match_index is not None:
6440 dbg('setting selection to', match_index)
6441 # issue appropriate event to outside:
6442 self._OnAutoSelect(self._ctrl_constraints, match_index=match_index)
6443 self._CheckValid()
6444 keep_processing = False
6445 else:
6446 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
6447 field = self._FindField(pos)
6448 if self.IsEmpty() or not field._hasList:
6449 dbg('selecting 1st value in list')
6450 self._OnAutoSelect(self._ctrl_constraints, match_index=0)
6451 self._CheckValid()
6452 keep_processing = False
6453 else:
6454 # attempt field-level auto-complete
6455 dbg(indent=0)
6456 keep_processing = self._OnAutoCompleteField(event)
6457 dbg('keep processing?', keep_processing, indent=0)
6458 return keep_processing
6459
6460
6461 def _OnAutoSelect(self, field, match_index):
6462 """
6463 Override mixin (empty) autocomplete handler, so that autocompletion causes
6464 combobox to update appropriately.
6465 """
6466 dbg('MaskedComboBox::OnAutoSelect', field._index, indent=1)
6467 ## field._autoCompleteIndex = match_index
6468 if field == self._ctrl_constraints:
6469 self.SetSelection(match_index)
6470 dbg('issuing combo selection event')
6471 self.GetEventHandler().ProcessEvent(
6472 MaskedComboBoxSelectEvent( self.GetId(), match_index, self ) )
6473 self._CheckValid()
6474 dbg('field._autoCompleteIndex:', match_index)
6475 dbg('self.GetSelection():', self.GetSelection())
6476 dbg(indent=0)
6477
6478
6479 def _OnReturn(self, event):
6480 """
6481 For wxComboBox, it seems that if you hit return when the dropdown is
6482 dropped, the event that dismisses the dropdown will also blank the
6483 control, because of the implementation of wxComboBox. So here,
6484 we look and if the selection is -1, and the value according to
6485 (the base control!) is a value in the list, then we schedule a
6486 programmatic wxComboBox.SetSelection() call to pick the appropriate
6487 item in the list. (and then do the usual OnReturn bit.)
6488 """
6489 dbg('MaskedComboBox::OnReturn', indent=1)
6490 dbg('current value: "%s"' % self.GetValue(), 'current index:', self.GetSelection())
6491 if self.GetSelection() == -1 and self.GetValue().lower().strip() in self._ctrl_constraints._compareChoices:
6492 wx.CallAfter(self.SetSelection, self._ctrl_constraints._autoCompleteIndex)
6493
6494 event.m_keyCode = wx.WXK_TAB
6495 event.Skip()
6496 dbg(indent=0)
6497
6498
6499 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6500
6501 class IpAddrCtrl( MaskedTextCtrl ):
6502 """
6503 This class is a particular type of MaskedTextCtrl that accepts
6504 and understands the semantics of IP addresses, reformats input
6505 as you move from field to field, and accepts '.' as a navigation
6506 character, so that typing an IP address can be done naturally.
6507 """
6508 def __init__( self, parent, id=-1, value = '',
6509 pos = wx.DefaultPosition,
6510 size = wx.DefaultSize,
6511 style = wx.TE_PROCESS_TAB,
6512 validator = wx.DefaultValidator,
6513 name = 'IpAddrCtrl',
6514 setupEventHandling = True, ## setup event handling by default
6515 **kwargs):
6516
6517 if not kwargs.has_key('mask'):
6518 kwargs['mask'] = mask = "###.###.###.###"
6519 if not kwargs.has_key('formatcodes'):
6520 kwargs['formatcodes'] = 'F_Sr<'
6521 if not kwargs.has_key('validRegex'):
6522 kwargs['validRegex'] = "( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))(\.( \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))){3}"
6523
6524
6525 MaskedTextCtrl.__init__(
6526 self, parent, id=id, value = value,
6527 pos=pos, size=size,
6528 style = style,
6529 validator = validator,
6530 name = name,
6531 setupEventHandling = setupEventHandling,
6532 **kwargs)
6533
6534 # set up individual field parameters as well:
6535 field_params = {}
6536 field_params['validRegex'] = "( | \d| \d |\d | \d\d|\d\d |\d \d|(1\d\d|2[0-4]\d|25[0-5]))"
6537
6538 # require "valid" string; this prevents entry of any value > 255, but allows
6539 # intermediate constructions; overall control validation requires well-formatted value.
6540 field_params['formatcodes'] = 'V'
6541
6542 if field_params:
6543 for i in self._field_indices:
6544 self.SetFieldParameters(i, **field_params)
6545
6546 # This makes '.' act like tab:
6547 self._AddNavKey('.', handler=self.OnDot)
6548 self._AddNavKey('>', handler=self.OnDot) # for "shift-."
6549
6550
6551 def OnDot(self, event):
6552 dbg('IpAddrCtrl::OnDot', indent=1)
6553 pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
6554 oldvalue = self.GetValue()
6555 edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
6556 if not event.ShiftDown():
6557 if pos > edit_start and pos < edit_end:
6558 # clip data in field to the right of pos, if adjusting fields
6559 # when not at delimeter; (assumption == they hit '.')
6560 newvalue = oldvalue[:pos] + ' ' * (edit_end - pos) + oldvalue[edit_end:]
6561 self._SetValue(newvalue)
6562 self._SetInsertionPoint(pos)
6563 dbg(indent=0)
6564 return self._OnChangeField(event)
6565
6566
6567
6568 def GetAddress(self):
6569 value = MaskedTextCtrl.GetValue(self)
6570 return value.replace(' ','') # remove spaces from the value
6571
6572
6573 def _OnCtrl_S(self, event):
6574 dbg("IpAddrCtrl::_OnCtrl_S")
6575 if self._demo:
6576 print "value:", self.GetAddress()
6577 return False
6578
6579 def SetValue(self, value):
6580 dbg('IpAddrCtrl::SetValue(%s)' % str(value), indent=1)
6581 if type(value) not in (types.StringType, types.UnicodeType):
6582 dbg(indent=0)
6583 raise ValueError('%s must be a string', str(value))
6584
6585 bValid = True # assume True
6586 parts = value.split('.')
6587 if len(parts) != 4:
6588 bValid = False
6589 else:
6590 for i in range(4):
6591 part = parts[i]
6592 if not 0 <= len(part) <= 3:
6593 bValid = False
6594 break
6595 elif part.strip(): # non-empty part
6596 try:
6597 j = string.atoi(part)
6598 if not 0 <= j <= 255:
6599 bValid = False
6600 break
6601 else:
6602 parts[i] = '%3d' % j
6603 except:
6604 bValid = False
6605 break
6606 else:
6607 # allow empty sections for SetValue (will result in "invalid" value,
6608 # but this may be useful for initializing the control:
6609 parts[i] = ' ' # convert empty field to 3-char length
6610
6611 if not bValid:
6612 dbg(indent=0)
6613 raise ValueError('value (%s) must be a string of form n.n.n.n where n is empty or in range 0-255' % str(value))
6614 else:
6615 dbg('parts:', parts)
6616 value = string.join(parts, '.')
6617 MaskedTextCtrl.SetValue(self, value)
6618 dbg(indent=0)
6619
6620
6621 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6622 ## these are helper subroutines:
6623
6624 def movetofloat( origvalue, fmtstring, neg, addseparators=False, sepchar = ',',fillchar=' '):
6625 """ addseparators = add separator character every three numerals if True
6626 """
6627 fmt0 = fmtstring.split('.')
6628 fmt1 = fmt0[0]
6629 fmt2 = fmt0[1]
6630 val = origvalue.split('.')[0].strip()
6631 ret = fillchar * (len(fmt1)-len(val)) + val + "." + "0" * len(fmt2)
6632 if neg:
6633 ret = '-' + ret[1:]
6634 return (ret,len(fmt1))
6635
6636
6637 def isDateType( fmtstring ):
6638 """ Checks the mask and returns True if it fits an allowed
6639 date or datetime format.
6640 """
6641 dateMasks = ("^##/##/####",
6642 "^##-##-####",
6643 "^##.##.####",
6644 "^####/##/##",
6645 "^####-##-##",
6646 "^####.##.##",
6647 "^##/CCC/####",
6648 "^##.CCC.####",
6649 "^##/##/##$",
6650 "^##/##/## ",
6651 "^##/CCC/##$",
6652 "^##.CCC.## ",)
6653 reString = "|".join(dateMasks)
6654 filter = re.compile( reString)
6655 if re.match(filter,fmtstring): return True
6656 return False
6657
6658 def isTimeType( fmtstring ):
6659 """ Checks the mask and returns True if it fits an allowed
6660 time format.
6661 """
6662 reTimeMask = "^##:##(:##)?( (AM|PM))?"
6663 filter = re.compile( reTimeMask )
6664 if re.match(filter,fmtstring): return True
6665 return False
6666
6667
6668 def isFloatingPoint( fmtstring):
6669 filter = re.compile("[ ]?[#]+\.[#]+\n")
6670 if re.match(filter,fmtstring+"\n"): return True
6671 return False
6672
6673
6674 def isInteger( fmtstring ):
6675 filter = re.compile("[#]+\n")
6676 if re.match(filter,fmtstring+"\n"): return True
6677 return False
6678
6679
6680 def getDateParts( dateStr, dateFmt ):
6681 if len(dateStr) > 11: clip = dateStr[0:11]
6682 else: clip = dateStr
6683 if clip[-2] not in string.digits:
6684 clip = clip[:-1] # (got part of time; drop it)
6685
6686 dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.')
6687 slices = clip.split(dateSep)
6688 if dateFmt == "MDY":
6689 y,m,d = (slices[2],slices[0],slices[1]) ## year, month, date parts
6690 elif dateFmt == "DMY":
6691 y,m,d = (slices[2],slices[1],slices[0]) ## year, month, date parts
6692 elif dateFmt == "YMD":
6693 y,m,d = (slices[0],slices[1],slices[2]) ## year, month, date parts
6694 else:
6695 y,m,d = None, None, None
6696 if not y:
6697 return None
6698 else:
6699 return y,m,d
6700
6701
6702 def getDateSepChar(dateStr):
6703 clip = dateStr[0:10]
6704 dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.')
6705 return dateSep
6706
6707
6708 def makeDate( year, month, day, dateFmt, dateStr):
6709 sep = getDateSepChar( dateStr)
6710 if dateFmt == "MDY":
6711 return "%s%s%s%s%s" % (month,sep,day,sep,year) ## year, month, date parts
6712 elif dateFmt == "DMY":
6713 return "%s%s%s%s%s" % (day,sep,month,sep,year) ## year, month, date parts
6714 elif dateFmt == "YMD":
6715 return "%s%s%s%s%s" % (year,sep,month,sep,day) ## year, month, date parts
6716 else:
6717 return none
6718
6719
6720 def getYear(dateStr,dateFmt):
6721 parts = getDateParts( dateStr, dateFmt)
6722 return parts[0]
6723
6724 def getMonth(dateStr,dateFmt):
6725 parts = getDateParts( dateStr, dateFmt)
6726 return parts[1]
6727
6728 def getDay(dateStr,dateFmt):
6729 parts = getDateParts( dateStr, dateFmt)
6730 return parts[2]
6731
6732 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6733 class test(wx.PySimpleApp):
6734 def OnInit(self):
6735 from wx.lib.rcsizer import RowColSizer
6736 self.frame = wx.Frame( None, -1, "MaskedEditMixin 0.0.7 Demo Page #1", size = (700,600))
6737 self.panel = wx.Panel( self.frame, -1)
6738 self.sizer = RowColSizer()
6739 self.labels = []
6740 self.editList = []
6741 rowcount = 4
6742
6743 id, id1 = wx.NewId(), wx.NewId()
6744 self.command1 = wx.Button( self.panel, id, "&Close" )
6745 self.command2 = wx.Button( self.panel, id1, "&AutoFormats" )
6746 self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5)
6747 self.sizer.Add(self.command2, row=0, col=1, colspan=2, flag=wx.ALL, border = 5)
6748 self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1 )
6749 ## self.panel.SetDefaultItem(self.command1 )
6750 self.panel.Bind(wx.EVT_BUTTON, self.onClickPage, self.command2)
6751
6752 self.check1 = wx.CheckBox( self.panel, -1, "Disallow Empty" )
6753 self.check2 = wx.CheckBox( self.panel, -1, "Highlight Empty" )
6754 self.sizer.Add( self.check1, row=0,col=3, flag=wx.ALL,border=5 )
6755 self.sizer.Add( self.check2, row=0,col=4, flag=wx.ALL,border=5 )
6756 self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck1, self.check1 )
6757 self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck2, self.check2 )
6758
6759
6760 label = """Press ctrl-s in any field to output the value and plain value. Press ctrl-x to clear and re-set any field.
6761 Note that all controls have been auto-sized by including F in the format code.
6762 Try entering nonsensical or partial values in validated fields to see what happens (use ctrl-s to test the valid status)."""
6763 label2 = "\nNote that the State and Last Name fields are list-limited (Name:Smith,Jones,Williams)."
6764
6765 self.label1 = wx.StaticText( self.panel, -1, label)
6766 self.label2 = wx.StaticText( self.panel, -1, "Description")
6767 self.label3 = wx.StaticText( self.panel, -1, "Mask Value")
6768 self.label4 = wx.StaticText( self.panel, -1, "Format")
6769 self.label5 = wx.StaticText( self.panel, -1, "Reg Expr Val. (opt)")
6770 self.label6 = wx.StaticText( self.panel, -1, "wxMaskedEdit Ctrl")
6771 self.label7 = wx.StaticText( self.panel, -1, label2)
6772 self.label7.SetForegroundColour("Blue")
6773 self.label1.SetForegroundColour("Blue")
6774 self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6775 self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6776 self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6777 self.label5.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6778 self.label6.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6779
6780 self.sizer.Add( self.label1, row=1,col=0,colspan=7, flag=wx.ALL,border=5)
6781 self.sizer.Add( self.label7, row=2,col=0,colspan=7, flag=wx.ALL,border=5)
6782 self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5)
6783 self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5)
6784 self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5)
6785 self.sizer.Add( self.label5, row=3,col=3, flag=wx.ALL,border=5)
6786 self.sizer.Add( self.label6, row=3,col=4, flag=wx.ALL,border=5)
6787
6788 # The following list is of the controls for the demo. Feel free to play around with
6789 # the options!
6790 controls = [
6791 #description mask excl format regexp range,list,initial
6792 ("Phone No", "(###) ###-#### x:###", "", 'F!^-R', "^\(\d\d\d\) \d\d\d-\d\d\d\d", (),[],''),
6793 ("Last Name Only", "C{14}", "", 'F {list}', '^[A-Z][a-zA-Z]+', (),('Smith','Jones','Williams'),''),
6794 ("Full Name", "C{14}", "", 'F_', '^[A-Z][a-zA-Z]+ [A-Z][a-zA-Z]+', (),[],''),
6795 ("Social Sec#", "###-##-####", "", 'F', "\d{3}-\d{2}-\d{4}", (),[],''),
6796 ("U.S. Zip+4", "#{5}-#{4}", "", 'F', "\d{5}-(\s{4}|\d{4})",(),[],''),
6797 ("U.S. State (2 char)\n(with default)","AA", "", 'F!', "[A-Z]{2}", (),states, 'AZ'),
6798 ("Customer No", "\CAA-###", "", 'F!', "C[A-Z]{2}-\d{3}", (),[],''),
6799 ("Date (MDY) + Time\n(with default)", "##/##/#### ##:## AM", 'BCDEFGHIJKLMNOQRSTUVWXYZ','DFR!',"", (),[], r'03/05/2003 12:00 AM'),
6800 ("Invoice Total", "#{9}.##", "", 'F-R,', "", (),[], ''),
6801 ("Integer (signed)\n(with default)", "#{6}", "", 'F-R', "", (),[], '0 '),
6802 ("Integer (unsigned)\n(with default), 1-399", "######", "", 'F', "", (1,399),[], '1 '),
6803 ("Month selector", "XXX", "", 'F', "", (),
6804 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],""),
6805 ("fraction selector","#/##", "", 'F', "^\d\/\d\d?", (),
6806 ['2/3', '3/4', '1/2', '1/4', '1/8', '1/16', '1/32', '1/64'], "")
6807 ]
6808
6809 for control in controls:
6810 self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL)
6811 self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL)
6812 self.sizer.Add( wx.StaticText( self.panel, -1, control[3]),row=rowcount, col=2,border=5, flag=wx.ALL)
6813 self.sizer.Add( wx.StaticText( self.panel, -1, control[4][:20]),row=rowcount, col=3,border=5, flag=wx.ALL)
6814
6815 if control in controls[:]:#-2]:
6816 newControl = MaskedTextCtrl( self.panel, -1, "",
6817 mask = control[1],
6818 excludeChars = control[2],
6819 formatcodes = control[3],
6820 includeChars = "",
6821 validRegex = control[4],
6822 validRange = control[5],
6823 choices = control[6],
6824 defaultValue = control[7],
6825 demo = True)
6826 if control[6]: newControl.SetCtrlParameters(choiceRequired = True)
6827 else:
6828 newControl = MaskedComboBox( self.panel, -1, "",
6829 choices = control[7],
6830 choiceRequired = True,
6831 mask = control[1],
6832 formatcodes = control[3],
6833 excludeChars = control[2],
6834 includeChars = "",
6835 validRegex = control[4],
6836 validRange = control[5],
6837 demo = True)
6838 self.editList.append( newControl )
6839
6840 self.sizer.Add( newControl, row=rowcount,col=4,flag=wx.ALL,border=5)
6841 rowcount += 1
6842
6843 self.sizer.AddGrowableCol(4)
6844
6845 self.panel.SetSizer(self.sizer)
6846 self.panel.SetAutoLayout(1)
6847
6848 self.frame.Show(1)
6849 self.MainLoop()
6850
6851 return True
6852
6853 def onClick(self, event):
6854 self.frame.Close()
6855
6856 def onClickPage(self, event):
6857 self.page2 = test2(self.frame,-1,"")
6858 self.page2.Show(True)
6859
6860 def _onCheck1(self,event):
6861 """ Set required value on/off """
6862 value = event.IsChecked()
6863 if value:
6864 for control in self.editList:
6865 control.SetCtrlParameters(emptyInvalid=True)
6866 control.Refresh()
6867 else:
6868 for control in self.editList:
6869 control.SetCtrlParameters(emptyInvalid=False)
6870 control.Refresh()
6871 self.panel.Refresh()
6872
6873 def _onCheck2(self,event):
6874 """ Highlight empty values"""
6875 value = event.IsChecked()
6876 if value:
6877 for control in self.editList:
6878 control.SetCtrlParameters( emptyBackgroundColour = 'Aquamarine')
6879 control.Refresh()
6880 else:
6881 for control in self.editList:
6882 control.SetCtrlParameters( emptyBackgroundColour = 'White')
6883 control.Refresh()
6884 self.panel.Refresh()
6885
6886
6887 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6888
6889 class test2(wx.Frame):
6890 def __init__(self, parent, id, caption):
6891 wx.Frame.__init__( self, parent, id, "wxMaskedEdit control 0.0.7 Demo Page #2 -- AutoFormats", size = (550,600))
6892 from wx.lib.rcsizer import RowColSizer
6893 self.panel = wx.Panel( self, -1)
6894 self.sizer = RowColSizer()
6895 self.labels = []
6896 self.texts = []
6897 rowcount = 4
6898
6899 label = """\
6900 All these controls have been created by passing a single parameter, the AutoFormat code.
6901 The class contains an internal dictionary of types and formats (autoformats).
6902 To see a great example of validations in action, try entering a bad email address, then tab out."""
6903
6904 self.label1 = wx.StaticText( self.panel, -1, label)
6905 self.label2 = wx.StaticText( self.panel, -1, "Description")
6906 self.label3 = wx.StaticText( self.panel, -1, "AutoFormat Code")
6907 self.label4 = wx.StaticText( self.panel, -1, "wxMaskedEdit Control")
6908 self.label1.SetForegroundColour("Blue")
6909 self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6910 self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6911 self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD))
6912
6913 self.sizer.Add( self.label1, row=1,col=0,colspan=3, flag=wx.ALL,border=5)
6914 self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5)
6915 self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5)
6916 self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5)
6917
6918 id, id1 = wx.NewId(), wx.NewId()
6919 self.command1 = wx.Button( self.panel, id, "&Close")
6920 self.command2 = wx.Button( self.panel, id1, "&Print Formats")
6921 self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1)
6922 self.panel.SetDefaultItem(self.command1)
6923 self.panel.Bind(wx.EVT_BUTTON, self.onClickPrint, self.command2)
6924
6925 # The following list is of the controls for the demo. Feel free to play around with
6926 # the options!
6927 controls = [
6928 ("Phone No","USPHONEFULLEXT"),
6929 ("US Date + Time","USDATETIMEMMDDYYYY/HHMM"),
6930 ("US Date MMDDYYYY","USDATEMMDDYYYY/"),
6931 ("Time (with seconds)","TIMEHHMMSS"),
6932 ("Military Time\n(without seconds)","MILTIMEHHMM"),
6933 ("Social Sec#","USSOCIALSEC"),
6934 ("Credit Card","CREDITCARD"),
6935 ("Expiration MM/YY","EXPDATEMMYY"),
6936 ("Percentage","PERCENT"),
6937 ("Person's Age","AGE"),
6938 ("US Zip Code","USZIP"),
6939 ("US Zip+4","USZIPPLUS4"),
6940 ("Email Address","EMAIL"),
6941 ("IP Address", "(derived control IpAddrCtrl)")
6942 ]
6943
6944 for control in controls:
6945 self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL)
6946 self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL)
6947 if control in controls[:-1]:
6948 self.sizer.Add( MaskedTextCtrl( self.panel, -1, "",
6949 autoformat = control[1],
6950 demo = True),
6951 row=rowcount,col=2,flag=wx.ALL,border=5)
6952 else:
6953 self.sizer.Add( IpAddrCtrl( self.panel, -1, "", demo=True ),
6954 row=rowcount,col=2,flag=wx.ALL,border=5)
6955 rowcount += 1
6956
6957 self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5)
6958 self.sizer.Add(self.command2, row=0, col=1, flag=wx.ALL, border = 5)
6959 self.sizer.AddGrowableCol(3)
6960
6961 self.panel.SetSizer(self.sizer)
6962 self.panel.SetAutoLayout(1)
6963
6964 def onClick(self, event):
6965 self.Close()
6966
6967 def onClickPrint(self, event):
6968 for format in masktags.keys():
6969 sep = "+------------------------+"
6970 print "%s\n%s \n Mask: %s \n RE Validation string: %s\n" % (sep,format, masktags[format]['mask'], masktags[format]['validRegex'])
6971
6972 ## ---------- ---------- ---------- ---------- ---------- ---------- ----------
6973
6974 if __name__ == "__main__":
6975 app = test(False)
6976
6977 i=1
6978 ##
6979 ## Current Issues:
6980 ## ===================================
6981 ##
6982 ## 1. WS: For some reason I don't understand, the control is generating two (2)
6983 ## EVT_TEXT events for every one (1) .SetValue() of the underlying control.
6984 ## I've been unsuccessful in determining why or in my efforts to make just one
6985 ## occur. So, I've added a hack to save the last seen value from the
6986 ## control in the EVT_TEXT handler, and if *different*, call event.Skip()
6987 ## to propagate it down the event chain, and let the application see it.
6988 ##
6989 ## 2. WS: MaskedComboBox is deficient in several areas, all having to do with the
6990 ## behavior of the underlying control that I can't fix. The problems are:
6991 ## a) The background coloring doesn't work in the text field of the control;
6992 ## instead, there's a only border around it that assumes the correct color.
6993 ## b) The control will not pass WXK_TAB to the event handler, no matter what
6994 ## I do, and there's no style wxCB_PROCESS_TAB like wxTE_PROCESS_TAB to
6995 ## indicate that we want these events. As a result, MaskedComboBox
6996 ## doesn't do the nice field-tabbing that MaskedTextCtrl does.
6997 ## c) Auto-complete had to be reimplemented for the control because programmatic
6998 ## setting of the value of the text field does not set up the auto complete
6999 ## the way that the control processing keystrokes does. (But I think I've
7000 ## implemented a fairly decent approximation.) Because of this the control
7001 ## also won't auto-complete on dropdown, and there's no event I can catch
7002 ## to work around this problem.
7003 ## d) There is no method provided for getting the selection; the hack I've
7004 ## implemented has its flaws, not the least of which is that due to the
7005 ## strategy that I'm using, the paste buffer is always replaced by the
7006 ## contents of the control's selection when in focus, on each keystroke;
7007 ## this makes it impossible to paste anything into a MaskedComboBox
7008 ## at the moment... :-(
7009 ## e) The other deficient behavior, likely induced by the workaround for (d),
7010 ## is that you can can't shift-left to select more than one character
7011 ## at a time.
7012 ##
7013 ##
7014 ## 3. WS: Controls on wxPanels don't seem to pass Shift-WXK_TAB to their
7015 ## EVT_KEY_DOWN or EVT_CHAR event handlers. Until this is fixed in
7016 ## wxWindows, shift-tab won't take you backwards through the fields of
7017 ## a MaskedTextCtrl like it should. Until then Shifted arrow keys will
7018 ## work like shift-tab and tab ought to.
7019 ##
7020
7021 ## To-Do's:
7022 ## =============================##
7023 ## 1. Add Popup list for auto-completable fields that simulates combobox on individual
7024 ## fields. Example: City validates against list of cities, or zip vs zip code list.
7025 ## 2. Allow optional monetary symbols (eg. $, pounds, etc.) at front of a "decimal"
7026 ## control.
7027 ## 3. Fix shift-left selection for MaskedComboBox.
7028 ## 5. Transform notion of "decimal control" to be less "entire control"-centric,
7029 ## so that monetary symbols can be included and still have the appropriate
7030 ## semantics. (Big job, as currently written, but would make control even
7031 ## more useful for business applications.)
7032
7033
7034 ## CHANGELOG:
7035 ## ====================
7036 ## Version 1.4
7037 ## (Reported) bugs fixed:
7038 ## 1. Right-click menu allowed "cut" operation that destroyed mask
7039 ## (was implemented by base control)
7040 ## 2. MaskedComboBox didn't allow .Append() of mixed-case values; all
7041 ## got converted to lower case.
7042 ## 3. MaskedComboBox selection didn't deal with spaces in values
7043 ## properly when autocompleting, and didn't have a concept of "next"
7044 ## match for handling choice list duplicates.
7045 ## 4. Size of MaskedComboBox was always default.
7046 ## 5. Email address regexp allowed some "non-standard" things, and wasn't
7047 ## general enough.
7048 ## 6. Couldn't easily reset MaskedComboBox contents programmatically.
7049 ## 7. Couldn't set emptyInvalid during construction.
7050 ## 8. Under some versions of wxPython, readonly comboboxes can apparently
7051 ## return a GetInsertionPoint() result (655535), causing masked control
7052 ## to fail.
7053 ## 9. Specifying an empty mask caused the controls to traceback.
7054 ## 10. Can't specify float ranges for validRange.
7055 ## 11. '.' from within a the static portion of a restricted IP address
7056 ## destroyed the mask from that point rightward; tab when cursor is
7057 ## before 1st field takes cursor past that field.
7058 ##
7059 ## Enhancements:
7060 ## 12. Added Ctrl-Z/Undo handling, (and implemented context-menu properly.)
7061 ## 13. Added auto-select option on char input for masked controls with
7062 ## choice lists.
7063 ## 14. Added '>' formatcode, allowing insert within a given or each field
7064 ## as appropriate, rather than requiring "overwrite". This makes single
7065 ## field controls that just have validation rules (eg. EMAIL) much more
7066 ## friendly. The same flag controls left shift when deleting vs just
7067 ## blanking the value, and for right-insert fields, allows right-insert
7068 ## at any non-blank (non-sign) position in the field.
7069 ## 15. Added option to use to indicate negative values for numeric controls.
7070 ## 16. Improved OnFocus handling of numeric controls.
7071 ## 17. Enhanced Home/End processing to allow operation on a field level,
7072 ## using ctrl key.
7073 ## 18. Added individual Get/Set functions for control parameters, for
7074 ## simplified integration with Boa Constructor.
7075 ## 19. Standardized "Colour" parameter names to match wxPython, with
7076 ## non-british spellings still supported for backward-compatibility.
7077 ## 20. Added '&' mask specification character for punctuation only (no letters
7078 ## or digits).
7079 ## 21. Added (in a separate file) wxMaskedCtrl() factory function to provide
7080 ## unified interface to the masked edit subclasses.
7081 ##
7082 ##
7083 ## Version 1.3
7084 ## 1. Made it possible to configure grouping, decimal and shift-decimal characters,
7085 ## to make controls more usable internationally.
7086 ## 2. Added code to smart "adjust" value strings presented to .SetValue()
7087 ## for right-aligned numeric format controls if they are shorter than
7088 ## than the control width, prepending the missing portion, prepending control
7089 ## template left substring for the missing characters, so that setting
7090 ## numeric values is easier.
7091 ## 3. Renamed SetMaskParameters SetCtrlParameters() (with old name preserved
7092 ## for b-c), as this makes more sense.
7093 ##
7094 ## Version 1.2
7095 ## 1. Fixed .SetValue() to replace the current value, rather than the current
7096 ## selection. Also changed it to generate ValueError if presented with
7097 ## either a value which doesn't follow the format or won't fit. Also made
7098 ## set value adjust numeric and date controls as if user entered the value.
7099 ## Expanded doc explaining how SetValue() works.
7100 ## 2. Fixed EUDATE* autoformats, fixed IsDateType mask list, and added ability to
7101 ## use 3-char months for dates, and EUDATETIME, and EUDATEMILTIME autoformats.
7102 ## 3. Made all date autoformats automatically pick implied "datestyle".
7103 ## 4. Added IsModified override, since base wxTextCtrl never reports modified if
7104 ## .SetValue used to change the value, which is what the masked edit controls
7105 ## use internally.
7106 ## 5. Fixed bug in date position adjustment on 2 to 4 digit date conversion when
7107 ## using tab to "leave field" and auto-adjust.
7108 ## 6. Fixed bug in _isCharAllowed() for negative number insertion on pastes,
7109 ## and bug in ._Paste() that didn't account for signs in signed masks either.
7110 ## 7. Fixed issues with _adjustPos for right-insert fields causing improper
7111 ## selection/replacement of values
7112 ## 8. Fixed _OnHome handler to properly handle extending current selection to
7113 ## beginning of control.
7114 ## 9. Exposed all (valid) autoformats to demo, binding descriptions to
7115 ## autoformats.
7116 ## 10. Fixed a couple of bugs in email regexp.
7117 ## 11. Made maskchardict an instance var, to make mask chars to be more
7118 ## amenable to international use.
7119 ## 12. Clarified meaning of '-' formatcode in doc.
7120 ## 13. Fixed a couple of coding bugs being flagged by Python2.1.
7121 ## 14. Fixed several issues with sign positioning, erasure and validity
7122 ## checking for "numeric" masked controls.
7123 ## 15. Added validation to IpAddrCtrl.SetValue().
7124 ##
7125 ## Version 1.1
7126 ## 1. Changed calling interface to use boolean "useFixedWidthFont" (True by default)
7127 ## vs. literal font facename, and use wxTELETYPE as the font family
7128 ## if so specified.
7129 ## 2. Switched to use of dbg module vs. locally defined version.
7130 ## 3. Revamped entire control structure to use Field classes to hold constraint
7131 ## and formatting data, to make code more hierarchical, allow for more
7132 ## sophisticated masked edit construction.
7133 ## 4. Better strategy for managing options, and better validation on keywords.
7134 ## 5. Added 'V' format code, which requires that in order for a character
7135 ## to be accepted, it must result in a string that passes the validRegex.
7136 ## 6. Added 'S' format code which means "select entire field when navigating
7137 ## to new field."
7138 ## 7. Added 'r' format code to allow "right-insert" fields. (implies 'R'--right-alignment)
7139 ## 8. Added '<' format code to allow fields to require explicit cursor movement
7140 ## to leave field.
7141 ## 9. Added validFunc option to other validation mechanisms, that allows derived
7142 ## classes to add dynamic validation constraints to the control.
7143 ## 10. Fixed bug in validatePaste code causing possible IndexErrors, and also
7144 ## fixed failure to obey case conversion codes when pasting.
7145 ## 11. Implemented '0' (zero-pad) formatting code, as it wasn't being done anywhere...
7146 ## 12. Removed condition from OnDecimalPoint, so that it always truncates right on '.'
7147 ## 13. Enhanced IpAddrCtrl to use right-insert fields, selection on field traversal,
7148 ## individual field validation to prevent field values > 255, and require explicit
7149 ## tab/. to change fields.
7150 ## 14. Added handler for left double-click to select field under cursor.
7151 ## 15. Fixed handling for "Read-only" styles.
7152 ## 16. Separated signedForegroundColor from 'R' style, and added foregroundColor
7153 ## attribute, for more consistent and controllable coloring.
7154 ## 17. Added retainFieldValidation parameter, allowing top-level constraints
7155 ## such as "validRequired" to be set independently of field-level equivalent.
7156 ## (needed in TimeCtrl for bounds constraints.)
7157 ## 18. Refactored code a bit, cleaned up and commented code more heavily, fixed
7158 ## some of the logic for setting/resetting parameters, eg. fillChar, defaultValue,
7159 ## etc.
7160 ## 19. Fixed maskchar setting for upper/lowercase, to work in all locales.
7161 ##
7162 ##
7163 ## Version 1.0
7164 ## 1. Decimal point behavior restored for decimal and integer type controls:
7165 ## decimal point now trucates the portion > 0.
7166 ## 2. Return key now works like the tab character and moves to the next field,
7167 ## provided no default button is set for the form panel on which the control
7168 ## resides.
7169 ## 3. Support added in _FindField() for subclasses controls (like timecontrol)
7170 ## to determine where the current insertion point is within the mask (i.e.
7171 ## which sub-'field'). See method documentation for more info and examples.
7172 ## 4. Added Field class and support for all constraints to be field-specific
7173 ## in addition to being globally settable for the control.
7174 ## Choices for each field are validated for length and pastability into
7175 ## the field in question, raising ValueError if not appropriate for the control.
7176 ## Also added selective additional validation based on individual field constraints.
7177 ## By default, SHIFT-WXK_DOWN, SHIFT-WXK_UP, WXK_PRIOR and WXK_NEXT all
7178 ## auto-complete fields with choice lists, supplying the 1st entry in
7179 ## the choice list if the field is empty, and cycling through the list in
7180 ## the appropriate direction if already a match. WXK_DOWN will also auto-
7181 ## complete if the field is partially completed and a match can be made.
7182 ## SHIFT-WXK_UP/DOWN will also take you to the next field after any
7183 ## auto-completion performed.
7184 ## 5. Added autoCompleteKeycodes=[] parameters for allowing further
7185 ## customization of the control. Any keycode supplied as a member
7186 ## of the _autoCompleteKeycodes list will be treated like WXK_NEXT. If
7187 ## requireFieldChoice is set, then a valid value from each non-empty
7188 ## choice list will be required for the value of the control to validate.
7189 ## 6. Fixed "auto-sizing" to be relative to the font actually used, rather
7190 ## than making assumptions about character width.
7191 ## 7. Fixed GetMaskParameter(), which was non-functional in previous version.
7192 ## 8. Fixed exceptions raised to provide info on which control had the error.
7193 ## 9. Fixed bug in choice management of MaskedComboBox.
7194 ## 10. Fixed bug in IpAddrCtrl causing traceback if field value was of
7195 ## the form '# #'. Modified control code for IpAddrCtrl so that '.'
7196 ## in the middle of a field clips the rest of that field, similar to
7197 ## decimal and integer controls.
7198 ##
7199 ##
7200 ## Version 0.0.7
7201 ## 1. "-" is a toggle for sign; "+" now changes - signed numerics to positive.
7202 ## 2. ',' in formatcodes now causes numeric values to be comma-delimited (e.g.333,333).
7203 ## 3. New support for selecting text within the control.(thanks Will Sadkin!)
7204 ## Shift-End and Shift-Home now select text as you would expect
7205 ## Control-Shift-End selects to the end of the mask string, even if value not entered.
7206 ## Control-A selects all *entered* text, Shift-Control-A selects everything in the control.
7207 ## 4. event.Skip() added to onKillFocus to correct remnants when running in Linux (contributed-
7208 ## for some reason I couldn't find the original email but thanks!!!)
7209 ## 5. All major key-handling code moved to their own methods for easier subclassing: OnHome,
7210 ## OnErase, OnEnd, OnCtrl_X, OnCtrl_A, etc.
7211 ## 6. Email and autoformat validations corrected using regex provided by Will Sadkin (thanks!).
7212 ## (The rest of the changes in this version were done by Will Sadkin with permission from Jeff...)
7213 ## 7. New mechanism for replacing default behavior for any given key, using
7214 ## ._SetKeycodeHandler(keycode, func) and ._SetKeyHandler(char, func) now available
7215 ## for easier subclassing of the control.
7216 ## 8. Reworked the delete logic, cut, paste and select/replace logic, as well as some bugs
7217 ## with insertion point/selection modification. Changed Ctrl-X to use standard "cut"
7218 ## semantics, erasing the selection, rather than erasing the entire control.
7219 ## 9. Added option for an "default value" (ie. the template) for use when a single fillChar
7220 ## is not desired in every position. Added IsDefault() function to mean "does the value
7221 ## equal the template?" and modified .IsEmpty() to mean "do all of the editable
7222 ## positions in the template == the fillChar?"
7223 ## 10. Extracted mask logic into mixin, so we can have both MaskedTextCtrl and MaskedComboBox,
7224 ## now included.
7225 ## 11. MaskedComboBox now adds the capability to validate from list of valid values.
7226 ## Example: City validates against list of cities, or zip vs zip code list.
7227 ## 12. Fixed oversight in EVT_TEXT handler that prevented the events from being
7228 ## passed to the next handler in the event chain, causing updates to the
7229 ## control to be invisible to the parent code.
7230 ## 13. Added IPADDR autoformat code, and subclass IpAddrCtrl for controlling tabbing within
7231 ## the control, that auto-reformats as you move between cells.
7232 ## 14. Mask characters [A,a,X,#] can now appear in the format string as literals, by using '\'.
7233 ## 15. It is now possible to specify repeating masks, e.g. #{3}-#{3}-#{14}
7234 ## 16. Fixed major bugs in date validation, due to the fact that
7235 ## wxDateTime.ParseDate is too liberal, and will accept any form that
7236 ## makes any kind of sense, regardless of the datestyle you specified
7237 ## for the control. Unfortunately, the strategy used to fix it only
7238 ## works for versions of wxPython post 2.3.3.1, as a C++ assert box
7239 ## seems to show up on an invalid date otherwise, instead of a catchable
7240 ## exception.
7241 ## 17. Enhanced date adjustment to automatically adjust heuristic based on
7242 ## current year, making last century/this century determination on
7243 ## 2-digit year based on distance between today's year and value;
7244 ## if > 50 year separation, assume last century (and don't assume last
7245 ## century is 20th.)
7246 ## 18. Added autoformats and support for including HHMMSS as well as HHMM for
7247 ## date times, and added similar time, and militaray time autoformats.
7248 ## 19. Enhanced tabbing logic so that tab takes you to the next field if the
7249 ## control is a multi-field control.
7250 ## 20. Added stub method called whenever the control "changes fields", that
7251 ## can be overridden by subclasses (eg. IpAddrCtrl.)
7252 ## 21. Changed a lot of code to be more functionally-oriented so side-effects
7253 ## aren't as problematic when maintaining code and/or adding features.
7254 ## Eg: IsValid() now does not have side-effects; it merely reflects the
7255 ## validity of the value of the control; to determine validity AND recolor
7256 ## the control, _CheckValid() should be used with a value argument of None.
7257 ## Similarly, made most reformatting function take an optional candidate value
7258 ## rather than just using the current value of the control, and only
7259 ## have them change the value of the control if a candidate is not specified.
7260 ## In this way, you can do validation *before* changing the control.
7261 ## 22. Changed validRequired to mean "disallow chars that result in invalid
7262 ## value." (Old meaning now represented by emptyInvalid.) (This was
7263 ## possible once I'd made the changes in (19) above.)
7264 ## 23. Added .SetMaskParameters and .GetMaskParameter methods, so they
7265 ## can be set/modified/retrieved after construction. Removed individual
7266 ## parameter setting functions, in favor of this mechanism, so that
7267 ## all adjustment of the control based on changing parameter values can
7268 ## be handled in one place with unified mechanism.
7269 ## 24. Did a *lot* of testing and fixing re: numeric values. Added ability
7270 ## to type "grouping char" (ie. ',') and validate as appropriate.
7271 ## 25. Fixed ZIPPLUS4 to allow either 5 or 4, but if > 5 must be 9.
7272 ## 26. Fixed assumption about "decimal or integer" masks so that they're only
7273 ## made iff there's no validRegex associated with the field. (This
7274 ## is so things like zipcodes which look like integers can have more
7275 ## restrictive validation (ie. must be 5 digits.)
7276 ## 27. Added a ton more doc strings to explain use and derivation requirements
7277 ## and did regularization of the naming conventions.
7278 ## 28. Fixed a range bug in _adjustKey preventing z from being handled properly.
7279 ## 29. Changed behavior of '.' (and shift-.) in numeric controls to move to
7280 ## reformat the value and move the next field as appropriate. (shift-'.',
7281 ## ie. '>' moves to the previous field.
7282
7283 ## Version 0.0.6
7284 ## 1. Fixed regex bug that caused autoformat AGE to invalidate any age ending
7285 ## in '0'.
7286 ## 2. New format character 'D' to trigger date type. If the user enters 2 digits in the
7287 ## year position, the control will expand the value to four digits, using numerals below
7288 ## 50 as 21st century (20+nn) and less than 50 as 20th century (19+nn).
7289 ## Also, new optional parameter datestyle = set to one of {MDY|DMY|YDM}
7290 ## 3. revalid parameter renamed validRegex to conform to standard for all validation
7291 ## parameters (see 2 new ones below).
7292 ## 4. New optional init parameter = validRange. Used only for int/dec (numeric) types.
7293 ## Allows the developer to specify a valid low/high range of values.
7294 ## 5. New optional init parameter = validList. Used for character types. Allows developer
7295 ## to send a list of values to the control to be used for specific validation.
7296 ## See the Last Name Only example - it is list restricted to Smith/Jones/Williams.
7297 ## 6. Date type fields now use wxDateTime's parser to validate the date and time.
7298 ## This works MUCH better than my kludgy regex!! Thanks to Robin Dunn for pointing
7299 ## me toward this solution!
7300 ## 7. Date fields now automatically expand 2-digit years when it can. For example,
7301 ## if the user types "03/10/67", then "67" will auto-expand to "1967". If a two-year
7302 ## date is entered it will be expanded in any case when the user tabs out of the
7303 ## field.
7304 ## 8. New class functions: SetValidBackgroundColor, SetInvalidBackgroundColor, SetEmptyBackgroundColor,
7305 ## SetSignedForeColor allow accessto override default class coloring behavior.
7306 ## 9. Documentation updated and improved.
7307 ## 10. Demo - page 2 is now a wxFrame class instead of a wxPyApp class. Works better.
7308 ## Two new options (checkboxes) - test highlight empty and disallow empty.
7309 ## 11. Home and End now work more intuitively, moving to the first and last user-entry
7310 ## value, respectively.
7311 ## 12. New class function: SetRequired(bool). Sets the control's entry required flag
7312 ## (i.e. disallow empty values if True).
7313 ##
7314 ## Version 0.0.5
7315 ## 1. get_plainValue method renamed to GetPlainValue following the wxWindows
7316 ## StudlyCaps(tm) standard (thanks Paul Moore). ;)
7317 ## 2. New format code 'F' causes the control to auto-fit (auto-size) itself
7318 ## based on the length of the mask template.
7319 ## 3. Class now supports "autoformat" codes. These can be passed to the class
7320 ## on instantiation using the parameter autoformat="code". If the code is in
7321 ## the dictionary, it will self set the mask, formatting, and validation string.
7322 ## I have included a number of samples, but I am hoping that someone out there
7323 ## can help me to define a whole bunch more.
7324 ## 4. I have added a second page to the demo (as well as a second demo class, test2)
7325 ## to showcase how autoformats work. The way they self-format and self-size is,
7326 ## I must say, pretty cool.
7327 ## 5. Comments added and some internal cosmetic revisions re: matching the code
7328 ## standards for class submission.
7329 ## 6. Regex validation is now done in real time - field turns yellow immediately
7330 ## and stays yellow until the entered value is valid
7331 ## 7. Cursor now skips over template characters in a more intuitive way (before the
7332 ## next keypress).
7333 ## 8. Change, Keypress and LostFocus methods added for convenience of subclasses.
7334 ## Developer may use these methods which will be called after EVT_TEXT, EVT_CHAR,
7335 ## and EVT_KILL_FOCUS, respectively.
7336 ## 9. Decimal and numeric handlers have been rewritten and now work more intuitively.
7337 ##
7338 ## Version 0.0.4
7339 ## 1. New .IsEmpty() method returns True if the control's value is equal to the
7340 ## blank template string
7341 ## 2. Control now supports a new init parameter: revalid. Pass a regular expression
7342 ## that the value will have to match when the control loses focus. If invalid,
7343 ## the control's BackgroundColor will turn yellow, and an internal flag is set (see next).
7344 ## 3. Demo now shows revalid functionality. Try entering a partial value, such as a
7345 ## partial social security number.
7346 ## 4. New .IsValid() value returns True if the control is empty, or if the value matches
7347 ## the revalid expression. If not, .IsValid() returns False.
7348 ## 5. Decimal values now collapse to decimal with '.00' on losefocus if the user never
7349 ## presses the decimal point.
7350 ## 6. Cursor now goes to the beginning of the field if the user clicks in an
7351 ## "empty" field intead of leaving the insertion point in the middle of the
7352 ## field.
7353 ## 7. New "N" mask type includes upper and lower chars plus digits. a-zA-Z0-9.
7354 ## 8. New formatcodes init parameter replaces other init params and adds functions.
7355 ## String passed to control on init controls:
7356 ## _ Allow spaces
7357 ## ! Force upper
7358 ## ^ Force lower
7359 ## R Show negative #s in red
7360 ## , Group digits
7361 ## - Signed numerals
7362 ## 0 Numeric fields get leading zeros
7363 ## 9. Ctrl-X in any field clears the current value.
7364 ## 10. Code refactored and made more modular (esp in OnChar method). Should be more
7365 ## easy to read and understand.
7366 ## 11. Demo enhanced.
7367 ## 12. Now has _doc_.
7368 ##
7369 ## Version 0.0.3
7370 ## 1. GetPlainValue() now returns the value without the template characters;
7371 ## so, for example, a social security number (123-33-1212) would return as
7372 ## 123331212; also removes white spaces from numeric/decimal values, so
7373 ## "- 955.32" is returned "-955.32". Press ctrl-S to see the plain value.
7374 ## 2. Press '.' in an integer style masked control and truncate any trailing digits.
7375 ## 3. Code moderately refactored. Internal names improved for clarity. Additional
7376 ## internal documentation.
7377 ## 4. Home and End keys now supported to move cursor to beginning or end of field.
7378 ## 5. Un-signed integers and decimals now supported.
7379 ## 6. Cosmetic improvements to the demo.
7380 ## 7. Class renamed to MaskedTextCtrl.
7381 ## 8. Can now specify include characters that will override the basic
7382 ## controls: for example, includeChars = "@." for email addresses
7383 ## 9. Added mask character 'C' -> allow any upper or lowercase character
7384 ## 10. .SetSignColor(str:color) sets the foreground color for negative values
7385 ## in signed controls (defaults to red)
7386 ## 11. Overview documentation written.
7387 ##
7388 ## Version 0.0.2
7389 ## 1. Tab now works properly when pressed in last position
7390 ## 2. Decimal types now work (e.g. #####.##)
7391 ## 3. Signed decimal or numeric values supported (i.e. negative numbers)
7392 ## 4. Negative decimal or numeric values now can show in red.
7393 ## 5. Can now specify an "exclude list" with the excludeChars parameter.
7394 ## See date/time formatted example - you can only enter A or P in the
7395 ## character mask space (i.e. AM/PM).
7396 ## 6. Backspace now works properly, including clearing data from a selected
7397 ## region but leaving template characters intact. Also delete key.
7398 ## 7. Left/right arrows now work properly.
7399 ## 8. Removed EventManager call from test so demo should work with wxPython 2.3.3
7400 ##