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