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