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