1 #---------------------------------------------------------------------------- 
   3 # Authors:      Jeff Childers, Will Sadkin 
   4 # Email:        jchilders_98@yahoo.com, wsadkin@nameconnector.com 
   6 # Copyright:    (c) 2003 by Jeff Childers, 2003 
   7 # Portions:     (c) 2002 by Will Sadkin, 2002-2003 
   9 # License:      wxWindows license 
  10 #---------------------------------------------------------------------------- 
  12 #   This was written way it is because of the lack of masked edit controls 
  13 #   in wxWindows/wxPython. 
  15 #   MaskedEdit controls are based on a suggestion made on [wxPython-Users] by 
  16 #   Jason Hihn, and borrows liberally from Will Sadkin's original masked edit 
  17 #   control for time entry, TimeCtrl (which is now rewritten using this 
  20 #   MaskedEdit controls do not normally use validators, because they do 
  21 #   careful manipulation of the cursor in the text window on each keystroke, 
  22 #   and validation is cursor-position specific, so the control intercepts the 
  23 #   key codes before the validator would fire.  However, validators can be 
  24 #   provided to do data transfer to the controls. 
  26 #---------------------------------------------------------------------------- 
  28 # 12/09/2003 - Jeff Grimmett (grimmtooth@softhome.net) 
  30 # o Updated for wx namespace. No guarantees. This is one huge file. 
  32 # 12/13/2003 - Jeff Grimmett (grimmtooth@softhome.net) 
  34 # o Missed wx.DateTime stuff earlier. 
  36 # 12/20/2003 - Jeff Grimmett (grimmtooth@softhome.net) 
  38 # o wxMaskedEditMixin -> MaskedEditMixin 
  39 # o wxMaskedTextCtrl -> MaskedTextCtrl 
  40 # o wxMaskedComboBoxSelectEvent -> MaskedComboBoxSelectEvent 
  41 # o wxMaskedComboBox -> MaskedComboBox 
  42 # o wxIpAddrCtrl -> IpAddrCtrl 
  43 # o wxTimeCtrl -> TimeCtrl 
  47 <b>Masked Edit Overview: 
  48 =====================</b> 
  50     is a sublassed text control that can carefully control the user's input 
  51     based on a mask string you provide. 
  53     General usage example: 
  54         control = MaskedTextCtrl( win, -1, '', mask = '(###) ###-####') 
  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. 
  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. 
  65     is actually a factory function for several types of masked edit controls: 
  67     <b>MaskedTextCtrl</b>   - standard masked edit text box 
  68     <b>MaskedComboBox</b>   - adds combobox capabilities 
  69     <b>IpAddrCtrl</b>       - adds special semantics for IP address entry 
  70     <b>TimeCtrl</b>         - special subclass handling lots of types as values 
  71     <b>wxMaskedNumCtrl</b>    - special subclass handling numeric values 
  73     It works by looking for a <b><i>controlType</i></b> parameter in the keyword 
  74     arguments of the control, to determine what kind of instance to return. 
  75     If not specified as a keyword argument, the default control type returned 
  76     will be MaskedTextCtrl. 
  78     Each of the above classes has its own set of arguments, but wxMaskedCtrl 
  79     provides a single "unified" interface for masked controls.  Those for 
  80     MaskedTextCtrl, MaskedComboBox and IpAddrCtrl are all documented 
  81     below; the others have their own demo pages and interface descriptions. 
  82     (See end of following discussion for how to configure the wxMaskedCtrl() 
  83     to select the above control types.) 
  86 <b>INITILIZATION PARAMETERS 
  87 ======================== 
  89 Allowed mask characters and 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             &       Allow string.punctuation only 
 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 
 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: 
 110       locale.setlocale(locale.LC_ALL, '') 
 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'.) 
 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. 
 132       Changing the mask for a control deletes any previous field classes 
 133       (and any associated validation or formatting constraints) for them. 
 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. 
 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: 
 149             R  Right-align field(s) 
 150             r  Right-insert in field(s) (implies R) 
 151             <  Stay in field until explicit navigation out of it 
 153             >  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.) 
 160                <i>Note: This also governs whether backspace/delete operations 
 161                shift contents of field to right of cursor, or just blank the 
 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> 
 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 
 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 
 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 
 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 
 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. 
 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. 
 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 
 220   eg: formatcodes = ',', groupChar="'"                   allows  12'345.34 
 221       formatcodes = ',', groupChar='.', decimalChar=','  allows  12.345,34 
 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. 
 229 <b>useParensForNegatives=False</b> 
 230   This option can be used with signed numeric format controls to 
 231   indicate signs via () rather than '-'. 
 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. 
 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. 
 246   Additional auto-complete keys can be specified via this parameter. 
 247   Any keys so specified will act like PageDown. 
 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: 
 257         excludeChars=   A string of characters to exclude even if otherwise allowed 
 258         includeChars=   A string of characters to allow even if otherwise disallowed 
 259         validRegex=     Use a regular expression to validate the contents of the text box 
 260         validRange=     Pass a rangeas list (low,high) to limit numeric fields/values 
 261         choices=        A list of strings that are allowed choices for the control. 
 262         choiceRequired= value must be member of choices list 
 263         compareNoCase=  Perform case-insensitive matching when validating against list 
 264                         <i>Note: for MaskedComboBox, this defaults to True.</i> 
 265         emptyInvalid=   Boolean indicating whether an empty value should be considered invalid 
 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.) 
 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. 
 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. 
 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 
 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': 
 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 
 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 
 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. 
 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. 
 322   Any field not represented by the list or dictionary will be 
 323   implicitly created by the control. 
 326     fields = [ Field(formatcodes='_r'), Field('choices=['a', 'b', 'c']) ] 
 329               1: ( Field(formatcodes='_R', choices=['a', 'b', 'c']), 
 330               3: ( Field(choices=['01', '02', '03'], choiceRequired=True) 
 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: 
 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 
 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. 
 347     formatcodes     # Augments control's settings 
 353     choiceRequired  #     '       '        ' 
 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' 
 366                     Returns the control's value to its default, and places the 
 367                     cursor at the beginning of the control. 
 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. 
 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 
 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 
 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' 
 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. 
 411                     Recolors the control as appropriate to its current settings. 
 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. 
 418                         ctl = MaskedTextCtrl( self, -1 ) 
 419                         ctl.SetCtrlParameters( mask='###-####', 
 420                                                defaultValue='555-1212', 
 423   <b>.GetCtrlParameter(parametername)</b> 
 424                     This function allows you to retrieve the current value of a parameter 
 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() 
 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.) 
 440   <b>.GetFieldParameter(field_index, parametername)</b> 
 441                     Allows the retrieval of field parameters after construction 
 444 The control detects certain common constructions. In order to use the signed feature 
 445 (negative numbers and coloring), the mask has to be all numbers with optionally one 
 446 decimal point. Without a decimal (e.g. '######', the control will treat it as an integer 
 447 value. With a decimal (e.g. '###.##'), the control will act as a floating point control 
 448 (i.e. press decimal to 'tab' to the decimal position). Pressing decimal in the 
 449 integer control truncates the value. 
 452 Check your controls by calling each control's .IsValid() function and the 
 453 .IsEmpty() function to determine which controls have been a) filled in and 
 454 b) filled in properly. 
 457 Regular expression validations can be used flexibly and creatively. 
 458 Take a look at the demo; the zip-code validation succeeds as long as the 
 459 first five numerals are entered. the last four are optional, but if 
 460 any are entered, there must be 4 to be valid. 
 462 <B>wxMaskedCtrl Configuration 
 463 ==========================</B> 
 464 wxMaskedCtrl works by looking for a special <b><i>controlType</i></b> 
 465 parameter in the variable arguments of the control, to determine 
 466 what kind of instance to return. 
 467 controlType can be one of: 
 469     controlTypes.MASKEDTEXT 
 470     controlTypes.MASKEDCOMBO 
 475 These constants are also available individually, ie, you can 
 476 use either of the following: 
 478     from wxPython.wx.lib.maskedctrl import wxMaskedCtrl, controlTypes 
 479     from wxPython.wx.lib.maskedctrl import wxMaskedCtrl, MASKEDCOMBO, MASKEDTEXT, NUMBER 
 481 If not specified as a keyword argument, the default controlType is 
 486 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
 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. 
 497   The following methods must be used and/or defined when deriving a control 
 498   from wxMaskedEditMixin.  NOTE: if deriving from a *masked edit* control 
 499   (eg. class IpAddrCtrl(MaskedTextCtrl) ), then this is NOT necessary, 
 500   as it's already been done for you in the base class. 
 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. 
 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. 
 526                         Similarly to _GetSelection, each class derived from 
 527                         wxMaskedEditMixin must define the function for setting 
 528                         the start and end of the current text selection. 
 529                         (eg. .SetSelection() for MaskedTextCtrl, and .SetMark() for 
 532         ._GetInsertionPoint() 
 533         ._SetInsertionPoint() 
 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. 
 541         ._SetValue()    REQUIRED 
 542                         Each class derived from wxMaskedEditMixin must define 
 543                         the functions used to get and set the raw value of the 
 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. 
 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. 
 565                         Each class derived from wxMaskedEditMixin must define 
 566                         the function used to refresh the base control. 
 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. 
 574         ._IsEditable()  REQUIRED 
 575                         Each class derived from wxMaskedEditMixin must define 
 576                         the function used to determine if the base control is 
 577                         editable or not.  (For MaskedComboBox, this has to 
 578                         be done with code, rather than specifying the proper 
 579                         function in the base control, as there isn't one...) 
 580         ._CalcSize()    REQUIRED 
 581                         Each class derived from wxMaskedEditMixin must define 
 582                         the function used to determine how wide the control 
 583                         should be given the mask.  (The mixin function 
 584                         ._calcSize() provides a baseline estimate.) 
 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: 
 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 
 608   where setupEventHandling is an argument to its constructor. 
 610   These 5 handlers must be "wired up" for the wxMaskedEdit 
 611   control to provide default behavior.  (The setupEventHandling 
 612   is an argument to MaskedTextCtrl and MaskedComboBox, so 
 613   that controls derived from *them* may replace one of these 
 614   handlers if they so choose.) 
 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. 
 621   The following routines are available to facilitate changing 
 622   the default behavior of wxMaskedEdit controls: 
 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 
 630                             self._SetKeycodeHandler(WXK_UP, self.IncrementValue) 
 631                             self._SetKeyHandler('-', self._OnChangeSign) 
 633         "Navigation" keys are assumed to change the cursor position, and 
 634         therefore don't cause automatic motion of the cursor as insertable 
 637         ._AddNavKeycode(keycode, handler=None) 
 638         ._AddNavKey(char, handler=None) 
 639                         Allows controls to specify other keys (and optional handlers) 
 640                         to be treated as navigational characters. (eg. '.' in IpAddrCtrl) 
 642         ._GetNavKeycodes()  Returns the current list of navigational keycodes. 
 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 
 652         ._FindField(pos) Returns the Field object associated with this position 
 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 
 664                         This is, the function that gets called for a given position 
 665                         whenever the cursor is adjusted to leave a given field. 
 666                         By default, it adjusts the year in date fields if mask is a date, 
 667                         It can be overridden by a derived class to 
 668                         adjust the value of the control at that time. 
 669                         (eg. IpAddrCtrl reformats the address in this way.) 
 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 
 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. 
 683         ._OnChar(event) This is the main EVT_CHAR handler for the 
 686     The following routines are used to handle standard actions 
 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) 
 696         _OnChangeField(event)   primarily used for tab events, but can be 
 697                                 used for other keys (eg. '.' in IpAddrCtrl) 
 699         _OnErase(event)         used for backspace and delete 
 713 # jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would 
 714 # be a good place to implement the 2.3 logger class 
 715 from wx
.tools
.dbg 
import Logger 
 
 720 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
 722 ## Constants for identifying control keys and classes of keys: 
 724 WXK_CTRL_A 
= (ord('A')+1) - ord('A')   ## These keys are not already defined in wx 
 725 WXK_CTRL_C 
= (ord('C')+1) - ord('A') 
 726 WXK_CTRL_S 
= (ord('S')+1) - ord('A') 
 727 WXK_CTRL_V 
= (ord('V')+1) - ord('A') 
 728 WXK_CTRL_X 
= (ord('X')+1) - ord('A') 
 729 WXK_CTRL_Z 
= (ord('Z')+1) - ord('A') 
 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
 
 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
 
 742 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
 744 ## Constants for masking. This is where mask characters 
 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. 
 753 maskchars 
= ("#","A","a","X","C","N", '&') 
 755 months 
= '(01|02|03|04|05|06|07|08|09|10|11|12)' 
 756 charmonths 
= '(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)' 
 757 charmonths_dict 
= {'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 
 758                    'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12} 
 760 days   
= '(01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)' 
 761 hours  
= '(0\d| \d|1[012])' 
 762 milhours 
= '(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23)' 
 763 minutes 
= """(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|\ 
 764 16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|\ 
 765 36|37|38|39|40|41|42|43|44|45|46|47|48|49|50|51|52|53|54|55|\ 
 768 am_pm_exclude 
= 'BCDEFGHIJKLMNOQRSTUVWXYZ\x8a\x8c\x8e\x9f\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde' 
 770 states 
= "AL,AK,AZ,AR,CA,CO,CT,DE,DC,FL,GA,GU,HI,ID,IL,IN,IA,KS,KY,LA,MA,ME,MD,MI,MN,MS,MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,OH,OK,OR,PA,PR,RI,SC,SD,TN,TX,UT,VA,VT,VI,WA,WV,WI,WY".split(',') 
 772 state_names 
= ['Alabama','Alaska','Arizona','Arkansas', 
 773                'California','Colorado','Connecticut', 
 774                'Delaware','District of Columbia', 
 775                'Florida','Georgia','Hawaii', 
 776                'Idaho','Illinois','Indiana','Iowa', 
 777                'Kansas','Kentucky','Louisiana', 
 778                'Maine','Maryland','Massachusetts','Michigan', 
 779                'Minnesota','Mississippi','Missouri','Montana', 
 780                'Nebraska','Nevada','New Hampshire','New Jersey', 
 781                'New Mexico','New York','North Carolina','North Dakokta', 
 782                'Ohio','Oklahoma','Oregon', 
 783                'Pennsylvania','Puerto Rico','Rhode Island', 
 784                'South Carolina','South Dakota', 
 785                'Tennessee','Texas','Utah', 
 786                'Vermont','Virginia', 
 787                'Washington','West Virginia', 
 788                'Wisconsin','Wyoming'] 
 790 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
 792 ## The following dictionary defines the current set of autoformats: 
 796            'mask': "(###) ###-#### x:###", 
 797            'formatcodes': 'F^->', 
 798            'validRegex': "^\(\d{3}\) \d{3}-\d{4}", 
 799            'description': "Phone Number w/opt. ext" 
 802            'mask': "###-###-#### x:###", 
 803            'formatcodes': 'F^->', 
 804            'validRegex': "^\d{3}-\d{3}-\d{4}", 
 805            'description': "Phone Number\n (w/hyphens and opt. ext)" 
 808            'mask': "(###) ###-####", 
 809            'formatcodes': 'F^->', 
 810            'validRegex': "^\(\d{3}\) \d{3}-\d{4}", 
 811            'description': "Phone Number only" 
 814            'mask': "###-###-####", 
 815            'formatcodes': 'F^->', 
 816            'validRegex': "^\d{3}-\d{3}-\d{4}", 
 817            'description': "Phone Number\n(w/hyphens)" 
 821            'formatcodes': 'F!V', 
 822            'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string
.join(states
,'|'), 
 824            'choiceRequired': True, 
 825            'description': "US State Code" 
 828            'mask': "ACCCCCCCCCCCCCCCCCCC", 
 830            'validRegex': "([ACDFGHIKLMNOPRSTUVW] |%s)" % string
.join(state_names
,'|'), 
 831            'choices': state_names
, 
 832            'choiceRequired': True, 
 833            'description': "US State Name" 
 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" 
 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)" 
 850        "USDATEMILTIMEMMDDYYYY/HHMMSS": { 
 851            'mask': "##/##/#### ##:##:##", 
 853            'validRegex': '^' + months 
+ '/' + days 
+ '/' + '\d{4} ' + milhours 
+ ':' + minutes 
+ ':' + seconds
, 
 854            'description': "US Date + Military Time" 
 856        "USDATEMILTIMEMMDDYYYY-HHMMSS": { 
 857            'mask': "##-##-#### ##:##:##", 
 859            'validRegex': '^' + months 
+ '-' + days 
+ '-' + '\d{4} ' + milhours 
+ ':' + minutes 
+ ':' + seconds
, 
 860            'description': "US Date + Military Time\n(w/hypens)" 
 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)" 
 869        "USDATEMILTIMEMMDDYYYY/HHMM": { 
 870            'mask': "##/##/#### ##:##", 
 872            'validRegex': '^' + months 
+ '/' + days 
+ '/' + '\d{4} ' + milhours 
+ ':' + minutes
, 
 873            'description': "US Date + Military Time\n(without seconds)" 
 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)" 
 882        "USDATEMILTIMEMMDDYYYY-HHMM": { 
 883            'mask': "##-##-#### ##:##", 
 885            'validRegex': '^' + months 
+ '-' + days 
+ '-' + '\d{4} ' + milhours 
+ ':' + minutes
, 
 886            'description': "US Date + Military Time\n(w/hyphens and w/o seconds)" 
 889            'mask': "##/##/####", 
 891            'validRegex': '^' + months 
+ '/' + days 
+ '/' + '\d{4}', 
 892            'description': "US Date\n(MMDDYYYY)" 
 897            'validRegex': '^' + months 
+ '/' + days 
+ '/\d\d', 
 898            'description': "US Date\n(MMDDYY)" 
 901            'mask': "##-##-####", 
 903            'validRegex': '^' + months 
+ '-' + days 
+ '-' +'\d{4}', 
 904            'description': "MM-DD-YYYY" 
 908            'mask': "####/##/##", 
 910            'validRegex': '^' + '\d{4}'+ '/' + months 
+ '/' + days
, 
 911            'description': "YYYY/MM/DD" 
 914            'mask': "####.##.##", 
 916            'validRegex': '^' + '\d{4}'+ '.' + months 
+ '.' + days
, 
 917            'description': "YYYY.MM.DD" 
 920            'mask': "##/##/####", 
 922            'validRegex': '^' + days 
+ '/' + months 
+ '/' + '\d{4}', 
 923            'description': "DD/MM/YYYY" 
 926            'mask': "##.##.####", 
 928            'validRegex': '^' + days 
+ '.' + months 
+ '.' + '\d{4}', 
 929            'description': "DD.MM.YYYY" 
 931        "EUDATEDDMMMYYYY.": { 
 932            'mask': "##.CCC.####", 
 934            'validRegex': '^' + days 
+ '.' + charmonths 
+ '.' + '\d{4}', 
 935            'description': "DD.Month.YYYY" 
 937        "EUDATEDDMMMYYYY/": { 
 938            'mask': "##/CCC/####", 
 940            'validRegex': '^' + days 
+ '/' + charmonths 
+ '/' + '\d{4}', 
 941            'description': "DD/Month/YYYY" 
 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" 
 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" 
 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" 
 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" 
 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" 
 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" 
 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" 
 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" 
1002        "EUDATEMILTIMEYYYYMMDD/HHMMSS": { 
1003            'mask': "####/##/## ##:##:##", 
1004            'formatcodes': 'DF', 
1005            'validRegex': '^' + '\d{4}'+ '/' + months 
+ '/' + days 
+ ' ' + milhours 
+ ':' + minutes 
+ ':' + seconds
, 
1006            'description': "YYYY/MM/DD Mil. Time" 
1008        "EUDATEMILTIMEYYYYMMDD.HHMMSS": { 
1009            'mask': "####.##.## ##:##:##", 
1010            'formatcodes': 'DF', 
1011            'validRegex': '^' + '\d{4}'+ '.' + months 
+ '.' + days 
+ ' ' + milhours 
+ ':' + minutes 
+ ':' + seconds
, 
1012            'description': "YYYY.MM.DD Mil. Time" 
1014        "EUDATEMILTIMEDDMMYYYY/HHMMSS": { 
1015            'mask': "##/##/#### ##:##:##", 
1016            'formatcodes': 'DF', 
1017            'validRegex': '^' + days 
+ '/' + months 
+ '/' + '\d{4} ' + milhours 
+ ':' + minutes 
+ ':' + seconds
, 
1018            'description': "DD/MM/YYYY Mil. Time" 
1020        "EUDATEMILTIMEDDMMYYYY.HHMMSS": { 
1021            'mask': "##.##.#### ##:##:##", 
1022            'formatcodes': 'DF', 
1023            'validRegex': '^' + days 
+ '.' + months 
+ '.' + '\d{4} ' + milhours 
+ ':' + minutes 
+ ':' + seconds
, 
1024            'description': "DD.MM.YYYY Mil. Time" 
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)" 
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)" 
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)" 
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)" 
1051            'mask': "##:##:## AM", 
1052            'excludeChars': am_pm_exclude
, 
1053            'formatcodes': 'TF!', 
1054            'validRegex': '^' + hours 
+ ':' + minutes 
+ ':' + seconds 
+ ' (A|P)M', 
1055            'description': "HH:MM:SS (A|P)M\n(see TimeCtrl)" 
1059            'excludeChars': am_pm_exclude
, 
1060            'formatcodes': 'TF!', 
1061            'validRegex': '^' + hours 
+ ':' + minutes 
+ ' (A|P)M', 
1062            'description': "HH:MM (A|P)M\n(see TimeCtrl)" 
1066            'formatcodes': 'TF', 
1067            'validRegex': '^' + milhours 
+ ':' + minutes 
+ ':' + seconds
, 
1068            'description': "Military HH:MM:SS\n(see TimeCtrl)" 
1072            'formatcodes': 'TF', 
1073            'validRegex': '^' + milhours 
+ ':' + minutes
, 
1074            'description': "Military HH:MM\n(see TimeCtrl)" 
1077            'mask': "###-##-####", 
1079            'validRegex': "\d{3}-\d{2}-\d{4}", 
1080            'description': "Social Sec#" 
1083            'mask': "####-####-####-####", 
1085            'validRegex': "\d{4}-\d{4}-\d{4}-\d{4}", 
1086            'description': "Credit Card" 
1091            'validRegex': "^" + months 
+ "/\d\d", 
1092            'description': "Expiration MM/YY" 
1097            'validRegex': "^\d{5}", 
1098            'description': "US 5-digit zip code" 
1101            'mask': "#####-####", 
1103            'validRegex': "\d{5}-(\s{4}|\d{4})", 
1104            'description': "US zip+4 code" 
1109            'validRegex': "^0.\d\d", 
1110            'description': "Percentage" 
1115            'validRegex': "^[1-9]{1}  |[1-9][0-9] |1[0|1|2][0-9]", 
1116            'description': "Age" 
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" 
1126            'mask': "###.###.###.###", 
1127            'formatcodes': 'F_Sr', 
1128            'validRegex': "(  \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))(\.(  \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))){3}", 
1129            'description': "IP Address\n(see IpAddrCtrl)" 
1133 # build demo-friendly dictionary of descriptions of autoformats 
1135 for key
, value 
in masktags
.items(): 
1136     autoformats
.append((key
, value
['description'])) 
1139 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
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 
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') 
1172     def __init__(self
, **kwargs
): 
1174         This is the "constructor" for setting up parameters for fields. 
1175         a field_index of -1 is used to indicate "the entire control." 
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(): 
1182                 raise TypeError('invalid parameter "%s"' % (key
)) 
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
) 
1191         self
._autoCompleteIndex 
= -1 
1192         self
._SetParameters
(**kwargs
) 
1193         self
._ValidateParameters
(**kwargs
) 
1198     def _SetParameters(self
, **kwargs
): 
1200         This function can be used to set individual or multiple parameters for 
1201         a masked edit field parameter after construction. 
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
) 
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
) 
1217         old_fillChar 
= self
._fillChar   
# store so we can change choice lists accordingly if it changes 
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
] ) 
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
 
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'] 
1244         if kwargs
.has_key('formatcodes') or kwargs
.has_key('validRegex'): 
1245             self
._regexMask   
= 'V' in self
._formatcodes 
and self
._validRegex
 
1247         if kwargs
.has_key('fillChar'): 
1248             self
._old
_fillChar 
= old_fillChar
 
1249 ##            dbg("self._old_fillChar: '%s'" % self._old_fillChar) 
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
) 
1255         dbg(indent
=0, suspend
=0) 
1258     def _ValidateParameters(self
, **kwargs
): 
1260         This function can be used to validate individual or multiple parameters for 
1261         a masked edit field parameter after construction. 
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) 
1270 ##        dbg("self._old_fillChar: '%s'" % self._old_fillChar) 
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
)) 
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) 
1281             self
._compareChoices 
= [choice
.strip() for choice 
in self
._choices
] 
1283             if self
._compareNoCase 
and self
._choices
: 
1284                 self
._compareChoices 
= [item
.lower() for item 
in self
._compareChoices
] 
1286             if kwargs
.has_key('choices'): 
1287                 self
._autoCompleteIndex 
= -1 
1290         if kwargs
.has_key('validRegex'):    # (set/changed) 
1291             if self
._validRegex
: 
1293                     if self
._compareNoCase
: 
1294                         self
._filter 
= re
.compile(self
._validRegex
, re
.IGNORECASE
) 
1296                         self
._filter 
= re
.compile(self
._validRegex
) 
1298                     dbg(indent
=0, suspend
=0) 
1299                     raise TypeError('%s: validRegex "%s" not a legal regular expression' % (str(self
._index
), self
._validRegex
)) 
1303         if kwargs
.has_key('validRange'):    # (set/changed) 
1304             self
._hasRange  
= False 
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
)) ) 
1313                 self
._hasRange  
= True 
1314                 self
._rangeLow  
= self
._validRange
[0] 
1315                 self
._rangeHigh 
= self
._validRange
[1] 
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
)) 
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
] 
1337                         self
._choices 
= [choice
.ljust( length 
) for choice 
in self
._choices
] 
1338                     dbg('aligned choices:', self
._choices
) 
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) 
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 
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
] 
1357                 self
._choices 
= [choice
.replace(self
._old
_fillChar
, self
._fillChar
) for choice 
in self
._choices
] 
1358             dbg('updated choices:', self
._choices
) 
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 
1366         # reset field validity assumption: 
1368         dbg(indent
=0, suspend
=0) 
1371     def _GetParameter(self
, paramname
): 
1373         Routine for retrieving the value of any given parameter 
1375         if Field
.valid_params
.has_key(paramname
): 
1376             return getattr(self
, '_' + paramname
) 
1378             TypeError('Field._GetParameter: invalid parameter "%s"' % key
) 
1381     def IsEmpty(self
, slice): 
1383         Indicates whether the specified slice is considered empty for the 
1386         dbg('Field::IsEmpty("%s")' % slice, indent
=1) 
1387         if not hasattr(self
, '_template'): 
1389             raise AttributeError('_template') 
1391         dbg('self._template: "%s"' % self
._template
) 
1392         dbg('self._defaultValue: "%s"' % str(self
._defaultValue
)) 
1393         if slice == self
._template 
and not self
._defaultValue
: 
1397         elif slice == self
._template
: 
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
): 
1404             dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals(), indent
=0) 
1407             dbg("IsEmpty? 0 (slice doesn't match template)", indent
=0) 
1411     def IsValid(self
, slice): 
1413         Indicates whether the specified slice is considered a valid value for the 
1417         dbg('Field[%s]::IsValid("%s")' % (str(self
._index
), slice), indent
=1) 
1418         valid 
= True    # assume true to start 
1420         if self
.IsEmpty(slice): 
1421             dbg(indent
=0, suspend
=0) 
1422             if self
._emptyInvalid
: 
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() 
1435             if self
._compareNoCase
: 
1436                 compareStr 
= compareStr
.lower() 
1437             valid 
= compareStr 
in self
._compareChoices
 
1439         elif self
._hasRange 
and not self
.IsEmpty(slice): 
1440             dbg('validating against range') 
1442                 # allow float as well as int ranges (int comparisons for free.) 
1443                 valid 
= self
._rangeLow 
<= float(slice) <= self
._rangeHigh
 
1447         elif self
._validRegex 
and self
._filter
: 
1448             dbg('validating against regex') 
1449             valid 
= (re
.match( self
._filter
, slice) is not None) 
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) 
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) 
1465             if self
._useParensForNegatives
: 
1466                 signpos 
= slice.find('(') 
1467                 right_signpos 
= slice.find(')') 
1468                 intStr 
= slice.replace('(', '').replace(')', '')    # drop sign, if any 
1470                 signpos 
= slice.find('-') 
1471                 intStr 
= slice.replace( '-', '' )                   # drop sign, if any 
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
: 
1488                 for i 
in range(len(intStr
)-1, -1, -1): 
1489                     new 
= intStr
[i
] + new
 
1491                         new 
= self
._groupChar 
+ new
 
1493                 if new 
and new
[0] == self
._groupChar
: 
1495                 if len(new
) <= length
: 
1496                     # expanded string will still fit and leave room for sign: 
1498                 # else... leave it without the commas... 
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: 
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: 
1517                     intStr 
= '-' + intStr
 
1518             elif right_signpos 
!= -1: 
1519                 # must have had ')' but '(' was before field; re-add ')' 
1523         slice = slice.strip() # drop extra spaces 
1525         if self
._alignRight
:     ## Only if right-alignment is enabled 
1526             slice = slice.rjust( length 
) 
1528             slice = slice.ljust( length 
) 
1529         if self
._fillChar 
!= ' ': 
1530             slice = slice.replace(' ', self
._fillChar
) 
1531         dbg('adjusted slice: "%s"' % slice, indent
=0) 
1535 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
1537 class MaskedEditMixin
: 
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.) 
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", 
1559     def __init__(self
, name 
= 'wxMaskedEdit', **kwargs
): 
1561         This is the "constructor" for setting up the mixin variable parameters for the composite class. 
1566         # set up flag for doing optional things to base control if possible 
1567         if not hasattr(self
, 'controlInitialized'): 
1568             self
.controlInitialized 
= False 
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 
1576         # Validate legitimate set of parameters: 
1577         for key 
in kwargs
.keys(): 
1578             if key
.replace('Color', 'Colour') not in MaskedEditMixin
.valid_ctrl_params
.keys() + Field
.valid_params
.keys(): 
1579                 raise TypeError('%s: invalid parameter "%s"' % (name
, key
)) 
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. 
1588         ## Initially populated with navigation and function control keys: 
1589         self
._keyhandlers 
= { 
1590             # default navigation keys and handlers: 
1591             wx
.WXK_BACK
:   self
._OnErase
, 
1592             wx
.WXK_LEFT
:   self
._OnArrow
, 
1593             wx
.WXK_RIGHT
:  self
._OnArrow
, 
1594             wx
.WXK_UP
:     self
._OnAutoCompleteField
, 
1595             wx
.WXK_DOWN
:   self
._OnAutoCompleteField
, 
1596             wx
.WXK_TAB
:    self
._OnChangeField
, 
1597             wx
.WXK_HOME
:   self
._OnHome
, 
1598             wx
.WXK_END
:    self
._OnEnd
, 
1599             wx
.WXK_RETURN
: self
._OnReturn
, 
1600             wx
.WXK_PRIOR
:  self
._OnAutoCompleteField
, 
1601             wx
.WXK_NEXT
:   self
._OnAutoCompleteField
, 
1603             # default function control keys and handlers: 
1604             wx
.WXK_DELETE
: self
._OnErase
, 
1605             WXK_CTRL_A
: self
._OnCtrl
_A
, 
1606             WXK_CTRL_C
: self
._OnCtrl
_C
, 
1607             WXK_CTRL_S
: self
._OnCtrl
_S
, 
1608             WXK_CTRL_V
: self
._OnCtrl
_V
, 
1609             WXK_CTRL_X
: self
._OnCtrl
_X
, 
1610             WXK_CTRL_Z
: self
._OnCtrl
_Z
, 
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
) 
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  
= { 
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
 
1632         ## self._ignoreChange is used by MaskedComboBox, because 
1633         ## of the hack necessary to determine the selection; it causes 
1634         ## EVT_TEXT messages from the combobox to be ignored if set. 
1635         self
._ignoreChange 
= False 
1637         # These are used to keep track of previous value, for undo functionality: 
1638         self
._curValue  
= None 
1639         self
._prevValue 
= None 
1643         # Set defaults for each parameter for this instance, and fully 
1644         # populate initial parameter list for configuration: 
1645         for key
, value 
in MaskedEditMixin
.valid_ctrl_params
.items(): 
1646             setattr(self
, '_' + key
, copy
.copy(value
)) 
1647             if not kwargs
.has_key(key
): 
1648 ##                dbg('%s: "%s"' % (key, repr(value))) 
1649                 kwargs
[key
] = copy
.copy(value
) 
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
) 
1657     def SetCtrlParameters(self
, **kwargs
): 
1659         This public function can be used to set individual or multiple masked edit 
1660         parameters after construction. 
1663         dbg('MaskedEditMixin::SetCtrlParameters', indent
=1) 
1664 ##        dbg('kwargs:', indent=1) 
1665 ##        for key, value in kwargs.items(): 
1666 ##            dbg(key, '=', value) 
1669         # Validate keyword arguments: 
1670         constraint_kwargs 
= {} 
1672         for key
, value 
in kwargs
.items(): 
1673             key 
= key
.replace('Color', 'Colour')    # for b-c, and standard wxPython spelling 
1674             if key 
not in MaskedEditMixin
.valid_ctrl_params
.keys() + Field
.valid_params
.keys(): 
1675                 dbg(indent
=0, suspend
=0) 
1676                 raise TypeError('Invalid keyword argument "%s" for control "%s"' % (key
, self
.name
)) 
1677             elif key 
in Field
.valid_params
.keys(): 
1678                 constraint_kwargs
[key
] = value
 
1680                 ctrl_kwargs
[key
] = value
 
1685         if ctrl_kwargs
.has_key('autoformat'): 
1686             autoformat 
= ctrl_kwargs
['autoformat'] 
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
 
1699         elif autoformat 
and not autoformat 
in masktags
.keys(): 
1700             raise AttributeError('invalid value for autoformat parameter: %s' % repr(autoformat
)) 
1702             dbg('autoformat not selected') 
1703             if kwargs
.has_key('mask'): 
1704                 mask 
= kwargs
['mask'] 
1707         ## Assign style flags 
1709             dbg('preserving previous mask') 
1710             mask 
= self
._previous
_mask   
# preserve previous mask 
1713             reset_args
['reset_mask'] = mask
 
1714             constraint_kwargs
['mask'] = mask
 
1716             # wipe out previous fields; preserve new control-level constraints 
1717             self
._fields 
= {-1: self._ctrl_constraints}
 
1720         if ctrl_kwargs
.has_key('fields'): 
1721             # do field parameter type validation, and conversion to internal dictionary 
1723             fields 
= ctrl_kwargs
['fields'] 
1724             if type(fields
) in (types
.ListType
, types
.TupleType
): 
1725                 for i 
in range(len(fields
)): 
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
 
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
 
1739                 dbg(indent
=0, suspend
=0) 
1740                 raise AttributeError('fields parameter must be a list or dictionary; not %s' % repr(fields
)) 
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) 
1748         # determine if changing parameters that should affect the entire control: 
1749         for key 
in MaskedEditMixin
.valid_ctrl_params
.keys(): 
1750             if key 
in ( 'mask', 'fields' ): continue    # (processed separately) 
1751             if ctrl_kwargs
.has_key(key
): 
1752                 setattr(self
, '_' + key
, ctrl_kwargs
[key
]) 
1754         # Validate color parameters, converting strings to named colors and validating 
1755         # result if appropriate: 
1756         for key 
in ('emptyBackgroundColour', 'invalidBackgroundColour', 'validBackgroundColour', 
1757                     'foregroundColour', 'signedForegroundColour'): 
1758             if ctrl_kwargs
.has_key(key
): 
1759                 if type(ctrl_kwargs
[key
]) in (types
.StringType
, types
.UnicodeType
): 
1760                     c 
= wx
.NamedColour(ctrl_kwargs
[key
]) 
1761                     if c
.Get() == (-1, -1, -1): 
1762                         raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs
[key
]), key
)) 
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
] 
1769                 elif type(ctrl_kwargs
[key
]) != type(wx
.BLACK
): 
1770                     raise TypeError('%s not a legal color specification for %s' % (repr(ctrl_kwargs
[key
]), key
)) 
1773         dbg('self._retainFieldValidation:', self
._retainFieldValidation
) 
1774         if not self
._retainFieldValidation
: 
1775             # Build dictionary of any changing parameters which should be propagated to the 
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]) 
1783         # Set the control-level constraints: 
1784         self
._ctrl
_constraints
._SetParameters
(**constraint_kwargs
) 
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
) 
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
) 
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
() 
1802         self
._autofit 
= self
._ctrl
_constraints
._autofit
 
1805         self
._isDate     
= 'D' in self
._ctrl
_constraints
._formatcodes 
and isDateType(mask
) 
1806         self
._isTime     
= 'T' in self
._ctrl
_constraints
._formatcodes 
and isTimeType(mask
) 
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 
1815             self
._4digityear 
= len(self
._mask
) > 8 and self
._mask
[9] == '#' 
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' 
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 
1833             if reset_args
.has_key('reset_mask'): 
1835                 curvalue 
= self
._GetValue
() 
1836                 if curvalue
.strip(): 
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
() 
1845                     dbg('attempting to _SetInitialValue() with template') 
1846                     self
._SetInitialValue
() 
1848             elif kwargs
.has_key('useParensForNegatives'): 
1849                 newvalue 
= self
._getSignedValue
()[0] 
1851                 if newvalue 
is not None: 
1852                     # Adjust for new mask: 
1853                     if len(newvalue
) < len(self
._mask
): 
1855                     elif len(newvalue
) > len(self
._mask
): 
1856                         if newvalue
[-1] in (' ', ')'): 
1857                             newvalue 
= newvalue
[:-1] 
1859                     dbg('reconfiguring value for parens:"%s"' % newvalue
) 
1860                     self
._SetValue
(newvalue
) 
1862                     if self
._prevValue 
!= newvalue
: 
1863                         self
._prevValue 
= newvalue  
# disallow undo of sign type 
1866                 dbg('setting client size to:', self
._CalcSize
()) 
1867                 self
.SetClientSize(self
._CalcSize
()) 
1869             # Set value/type-specific formatting 
1870             self
._applyFormatting
() 
1871         dbg(indent
=0, suspend
=0) 
1873     def SetMaskParameters(self
, **kwargs
): 
1874         """ old name for this function """ 
1875         return self
.SetCtrlParameters(**kwargs
) 
1878     def GetCtrlParameter(self
, paramname
): 
1880         Routine for retrieving the value of any given parameter 
1882         if MaskedEditMixin
.valid_ctrl_params
.has_key(paramname
.replace('Color','Colour')): 
1883             return getattr(self
, '_' + paramname
.replace('Color', 'Colour')) 
1884         elif Field
.valid_params
.has_key(paramname
): 
1885             return self
._ctrl
_constraints
._GetParameter
(paramname
) 
1887             TypeError('"%s".GetCtrlParameter: invalid parameter "%s"' % (self
.name
, paramname
)) 
1889     def GetMaskParameter(self
, paramname
): 
1890         """ old name for this function """ 
1891         return self
.GetCtrlParameter(paramname
) 
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.) 
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)) 
1913     def SetFieldParameters(self, field_index, **kwargs): 
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. 
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) 
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) 
1930         if self.controlInitialized: 
1931             if kwargs.has_key('fillChar') or kwargs.has_key('defaultValue'): 
1932                 self._SetInitialValue() 
1935                     self.SetClientSize(self._CalcSize()) 
1937             # Set value/type-specific formatting 
1938             self._applyFormatting() 
1941     def GetFieldParameter(self, field_index, paramname): 
1943         Routine provided for getting a parameter of an individual field. 
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) 
1950             TypeError('"%s".GetFieldParameter: invalid parameter "%s"' % (self.name, paramname)) 
1953     def _SetKeycodeHandler(self, keycode, func): 
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. 
1959         self._keyhandlers[keycode] = func 
1962     def _SetKeyHandler(self, char, func): 
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. 
1968         self._SetKeycodeHandler(ord(char), func) 
1971     def _AddNavKeycode(self, keycode, handler=None): 
1973         This function allows a derived subclass to augment the list of 
1974         keycodes that are considered "navigational" keys. 
1976         self._nav.append(keycode) 
1978             self._keyhandlers[keycode] = handler 
1981     def _AddNavKey(self, char, handler=None): 
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. 
1986         self._AddNavKeycode(ord(char), handler) 
1989     def _GetNavKeycodes(self): 
1991         This function retrieves the current list of navigational keycodes for 
1997     def _SetNavKeycodes(self, keycode_func_tuples): 
1999         This function allows you to replace the current list of keycode processed 
2000         as navigation keys, and bind associated optional keyhandlers. 
2003         for keycode, func in keycode_func_tuples: 
2004             self._nav.append(keycode) 
2006                 self._keyhandlers[keycode] = func 
2009     def _processMask(self, mask): 
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. 
2016         dbg('_processMask: mask', mask, indent=1) 
2017         # regular expression for parsing c{n} syntax: 
2018         rex = re.compile('([' +string.join(maskchars,"") + '])\{(\d+)\}') 
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 
2028         self._decimalChar = self._ctrl_constraints._decimalChar 
2029         self._shiftDecimalChar = self._ctrl_constraints._shiftDecimalChar 
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 
2036 ##        dbg('self._signOk?', self._signOk, 'self._useParens?', self._useParens) 
2037 ##        dbg('isFloatingPoint(%s)?' % (s), isFloatingPoint(s), 
2038 ##            'ctrl regex:', self._ctrl_constraints._validRegex) 
2040         if self._signOk and s[0] != ' ': 
2042             if self._ctrl_constraints._defaultValue and self._ctrl_constraints._defaultValue[0] != ' ': 
2043                 self._ctrl_constraints._defaultValue = ' ' + self._ctrl_constraints._defaultValue 
2048                 self._ctrl_constraints._defaultValue += ' ' 
2050         # Now, go build up a dictionary of booleans, indexed by position, 
2051         # indicating whether or not a given position is masked or not 
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) 
2072     def _calcFieldExtents(self): 
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. 
2078         self._lookupField = {} 
2081             ## Create dictionary of positions,characters in mask 
2083             for charnum in range( len( self._mask)): 
2084                 self.maskdict[charnum] = self._mask[charnum:charnum+1] 
2086             # For the current mask, create an ordered list of field extents 
2087             # and a dictionary of positions that map to field indices: 
2089             if self._signOk: start = 1 
2093                 # Skip field "discovery", and just construct a 2-field control with appropriate 
2094                 # constraints for a floating-point entry. 
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() 
2103                 self._decimalpos = string.find( self._mask, '.') 
2104                 dbg('decimal pos =', self._decimalpos) 
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: 
2113                 self._fields[1]._SetParameters(index=1, extent=(self._decimalpos+1, end), 
2114                                                mask=self._mask[self._decimalpos+1:end]) 
2116                 for i in range(self._decimalpos+1): 
2117                     self._lookupField[i] = 0 
2119                 for i in range(self._decimalpos+1, len(self._mask)+1): 
2120                     self._lookupField[i] = 1 
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: 
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 
2135                 # generic control; parse mask to figure out where the fields are: 
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: 
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) 
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 
2153 ##                        dbg('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) 
2164                             self._fields[field_index]._SetParameters( 
2166                                                                 extent=(edit_start, edit_end), 
2167                                                                 mask=self._mask[edit_start:edit_end]) 
2169                     i = self._findNextEntry(pos, adjustInsert=False)  # go to next field: 
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 
2177 ##                        dbg('next field:', field_index) 
2179         indices = self._fields.keys() 
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]) 
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)) 
2193     def _calcTemplate(self, reset_fillchar, reset_default): 
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. 
2200         if self._ctrl_constraints._defaultValue: 
2203             for field in self._fields.values(): 
2204                 if field._defaultValue and not reset_default: 
2206         dbg('default set?', default_set) 
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 
2213         if hasattr(self, '_fillChar'): old_fillchars = self._fillChar 
2214         else:                          old_fillchars = None 
2216         if hasattr(self, '_template'): old_template = self._template 
2217         else:                          old_template = None 
2224         for field in self._fields.values(): 
2225             field._template = "" 
2227         for pos in range(len(self._mask)): 
2229             field = self._FindField(pos) 
2230 ##            dbg('field:', field._index) 
2231             start, end = field._extent 
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 
2241                     fillChar = self._ctrl_constraints._fillChar 
2242                 self._fillChar[pos] = fillChar 
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: 
2250                         curvalue[pos] = fillChar 
2252                 if not field._defaultValue and not self._ctrl_constraints._defaultValue: 
2253 ##                    dbg('no default value') 
2254                     self._template += fillChar 
2255                     field._template += fillChar 
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] 
2265 ##                        dbg('field default not long enough; using fillChar') 
2266                         self._template += fillChar 
2267                         field._template += fillChar 
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] 
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) 
2280                 self._template += self._mask[pos] 
2282         self._fields[-1]._template = self._template     # (for consistency) 
2284         if curvalue:    # had an old value, put new one back together 
2285             newvalue = string.join(curvalue, "") 
2290             self._defaultValue = self._template 
2291             dbg('self._defaultValue:', self._defaultValue) 
2292             if not self.IsEmpty(self._defaultValue) and not self.IsValid(self._defaultValue): 
2294                 raise ValueError('Default value of "%s" is not a valid value for control "%s"' % (self._defaultValue, self.name)) 
2296             # if no fillchar change, but old value == old template, replace it: 
2297             if newvalue == old_template: 
2298                 newvalue = self._template 
2301             self._defaultValue = None 
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) 
2312     def _propagateConstraints(self, **reset_args): 
2314         Subroutine for propagating changes to control-level constraints and 
2315         formatting to the individual fields as appropriate. 
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] 
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 
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 
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 
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 
2346             if reset_args.has_key('defaultValue') and reset_args['defaultValue']: 
2347                 inherit_args['defaultValue'] = ""   # (reset for field) 
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]) 
2357                 field._SetParameters(**inherit_args) 
2358                 field._ValidateParameters(**inherit_args) 
2361     def _validateChoices(self): 
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. 
2367         for field in self._fields.values(): 
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') 
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) 
2382                         raise ValueError('"%s" could not be entered into field %d of control "%s"' % (choice, index, self.name)) 
2383                     elif replace_to > end: 
2385                         raise ValueError('"%s" will not fit into field %d of control "%s"' (choice, index, self.name)) 
2386 ##                    dbg(choice, 'valid in field', index) 
2389     def _configure(self, mask, **reset_args): 
2391         This function sets flags for automatic styling options.  It is 
2392         called whenever a control or field-level parameter is set/changed. 
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. 
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 
2405         dbg('MaskedEditMixin::_configure("%s")' % mask, indent=1) 
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) 
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)) 
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 
2425 ##        dbg('calculating field extents') 
2427         self._calcFieldExtents() 
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'] 
2435 ##        dbg('calculating template') 
2436         self._calcTemplate(reset_fillchar, reset_default) 
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) 
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) ) 
2449 ##        dbg('fields:', indent=1) 
2450 ##        for i in [-1] + self._field_indices: 
2451 ##            dbg('field %d:' % i, self._fields[i].__dict__) 
2454         # Set up special parameters for numeric control, if appropriate: 
2456             self._signpos = 0   # assume it starts here, but it will move around on floats 
2457             signkeys = ['-', '+', ' '] 
2459                 signkeys += ['(', ')'] 
2460             for key in signkeys: 
2462                 if not self._keyhandlers.has_key(keycode): 
2463                     self._SetKeyHandler(key, self._OnChangeSign) 
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): 
2474                     if self._useParens and len(newvalue) < len(self._ctrl_constraints._mask) and newvalue.find('(') == -1: 
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)) 
2482                             newvalue = newvalue.ljust(len(self._ctrl_constraints._mask)) 
2483                     dbg('old value: "%s"' % value) 
2484                     dbg('new value: "%s"' % newvalue) 
2486                         self._SetValue(newvalue) 
2487                     except Exception, e: 
2488                         dbg('exception raised:', e, 'resetting to initial value') 
2489                         self._SetInitialValue() 
2491                 elif len(value) > len(self._ctrl_constraints._mask): 
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) 
2500                     dbg('old value: "%s"' % value) 
2501                     dbg('new value: "%s"' % newvalue) 
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) 
2512                         self._SetValue(newvalue) 
2514                         dbg('exception raised:', e, 'resetting to initial value') 
2515                         self._SetInitialValue() 
2517             # Replace up/down arrow default handling: 
2518             # make down act like tab, up act like shift-tab: 
2520 ##            dbg('Registering numeric navigation and control handlers (if not already set)') 
2521             if not self._keyhandlers.has_key(wx.WXK_DOWN): 
2522                 self._SetKeycodeHandler(wx.WXK_DOWN, self._OnChangeField) 
2523             if not self._keyhandlers.has_key(wx.WXK_UP): 
2524                 self._SetKeycodeHandler(wx.WXK_UP, self._OnUpNumeric)  # (adds "shift" to up arrow, and calls _OnChangeField) 
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) 
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) 
2537         dbg(indent=0, suspend=0) 
2540     def _SetInitialValue(self, value=""): 
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. 
2546         dbg('MaskedEditMixin::_SetInitialValue("%s")' % value, indent=1) 
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... 
2552                 self._SetValue(self._curValue)  # note the use of "raw" ._SetValue()... 
2553             except Exception, e: 
2554                 dbg('exception thrown:', e, indent=0) 
2557             # Otherwise apply validation as appropriate to passed value: 
2558 ##            dbg('value = "%s", length:' % value, len(value)) 
2559             self._prevValue = self._curValue = value 
2561                 self.SetValue(value)            # use public (validating) .SetValue() 
2562             except Exception, e: 
2563                 dbg('exception thrown:', e, indent=0) 
2567         # Set value/type-specific formatting 
2568         self._applyFormatting() 
2572     def _calcSize(self, size=None): 
2573         """ Calculate automatic size if allowed; must be called after the base control is instantiated""" 
2574 ##        dbg('MaskedEditMixin::_calcSize', indent=1) 
2575         cont = (size is None or size == wx.DefaultSize) 
2577         if cont and self._autofit: 
2578             sizing_text = 'M' * self._masklength 
2579             if wx.Platform != "__WXMSW__":   # give it a little extra space 
2581             if wx.Platform == "__WXMAC__":   # give it even a little more... 
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) 
2591         """ Set the control's font typeface -- pass the font name as str.""" 
2592 ##        dbg('MaskedEditMixin::_setFont', indent=1) 
2593         if not self._useFixedWidthFont: 
2594             self._font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) 
2596             font = self.GetFont()   # get size, weight, etc from current font 
2598             # Set to teletype font (guaranteed to be mappable to all wxWindows 
2600             self._font = wx.Font( font.GetPointSize(), wx.TELETYPE, font.GetStyle(), 
2601                                  font.GetWeight(), font.GetUnderlined()) 
2602 ##            dbg('font string: "%s"' % font.GetNativeFontInfo().ToString()) 
2604         self.SetFont(self._font) 
2608     def _OnTextChange(self, event): 
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.) 
2618         newvalue = self._GetValue() 
2619         dbg('MaskedEditMixin::_OnTextChange: value: "%s"' % newvalue, indent=1) 
2621         if self._ignoreChange:      # ie. if an "intermediate text change event" 
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) 
2631             dbg('curvalue: "%s", newvalue: "%s"' % (self._curValue, newvalue)) 
2633                 if self._signOk and self._isNeg and newvalue.find('-') == -1 and newvalue.find('(') == -1: 
2634                     dbg('clearing self._isNeg') 
2636                     text, self._signpos, self._right_signpos = self._getSignedValue() 
2637                 self._CheckValid()  # Recolor control as appropriate 
2638             dbg('calling event.Skip()') 
2641         self._prevValue = self._curValue    # save for undo 
2642         self._curValue = newvalue           # Save last seen value for next iteration 
2647     def _OnKeyDown(self, event): 
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. 
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; 
2657             dbg('MaskedEditMixin::OnKeyDown: calling _OnChar') 
2660         # else allow regular EVT_CHAR key processing 
2664     def _OnChar(self, event): 
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. 
2669         dbg('MaskedEditMixin::_OnChar', indent=1) 
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()) 
2679         if not self._Keypress(key): 
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(): 
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: 
2700                 self._applyFormatting() 
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) 
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 
2717             if self._isMaskChar(pos):  ## Get string of allowed characters for validation 
2718                 okchars = self._getAllowedChars(pos) 
2720                 dbg('Not a valid position: pos = ', pos,"chars=",maskchars) 
2723         key = self._adjustKey(pos, key)     # apply formatting constraints to key: 
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: 
2734             # else skip default processing, but do final formatting 
2735         if key < wx.WXK_SPACE or key > 255: 
2736             dbg('key < WXK_SPACE or key > 255') 
2737             event.Skip()                # non alphanumeric 
2738             keep_processing = False 
2740             field = self._FindField(pos) 
2741             dbg("key ='%s'" % chr(key)) 
2743                 dbg('okSpaces?', field._okSpaces) 
2747             if chr(key) in field._excludeChars + self._ctrl_constraints._excludeChars: 
2748                 keep_processing = False 
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): 
2765                             keep_processing = True 
2766                             wx.CallAfter(self._SetInsertionPoint, self._decimalpos) 
2767                     if not keep_processing: 
2768                         dbg("key disallowed by validation") 
2769                         if not wx.Validator_IsSilent() and orig_pos == pos: 
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) 
2780                     if newstr != orig_value: 
2781                         self.modified = True 
2783                     wx.CallAfter(self._SetValue, newstr) 
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]: 
2791                     wx.CallAfter(self._SetInsertionPoint, newpos) 
2793                     if match_field is not None: 
2794                         dbg('matched field') 
2795                         self._OnAutoSelect(match_field, match_index) 
2797                     if new_select_to != newpos: 
2798                         dbg('queuing selection: (%d, %d)' % (newpos, new_select_to)) 
2799                         wx.CallAfter(self._SetSelection, newpos, new_select_to) 
2801                         newfield = self._FindField(newpos) 
2802                         if newfield != field and newfield._selectOnFieldEntry: 
2803                             dbg('queuing selection: (%d, %d)' % (newfield._extent[0], newfield._extent[1])) 
2804                             wx.CallAfter(self._SetSelection, newfield._extent[0], newfield._extent[1]) 
2805                     keep_processing = False 
2807             elif keep_processing: 
2808                 dbg('char not allowed') 
2809                 keep_processing = False 
2810                 if (not wx.Validator_IsSilent()) and orig_pos == pos: 
2813         self._applyFormatting() 
2815         # Move to next insertion point 
2816         if keep_processing and key not in self._nav: 
2817             pos = self._GetInsertionPoint() 
2818             next_entry = self._findNextEntry( pos ) 
2819             if pos != next_entry: 
2820                 dbg("moving from %(pos)d to next valid entry: %(next_entry)d" % locals()) 
2821                 wx.CallAfter(self._SetInsertionPoint, next_entry ) 
2823             if self._isTemplateChar(pos): 
2824                 self._AdjustField(pos) 
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. 
2836         Eg: with template (###) ###-####, 
2837         >>> self._FindFieldExtent(pos=0) 
2839         >>> self._FindFieldExtent(pos=1) 
2841         >>> self._FindFieldExtent(pos=5) 
2843         >>> self._FindFieldExtent(pos=6) 
2845         >>> self._FindFieldExtent(pos=10) 
2849         dbg('MaskedEditMixin::_FindFieldExtent(pos=%s, getslice=%s)' % ( 
2850                 str(pos), str(getslice)) ,indent=1) 
2852         field = self._FindField(pos) 
2855                 return None, None, "" 
2858         edit_start, edit_end = field._extent 
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) 
2864             return edit_start, edit_end, slice 
2866             dbg('edit_start:', edit_start, 'edit_end:', edit_end) 
2868             return edit_start, edit_end 
2871     def _FindField(self, pos=None): 
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. 
2879 ##        dbg('MaskedEditMixin::_FindField(pos=%s)' % str(pos) ,indent=1) 
2880         if pos is None: pos = self._GetInsertionPoint() 
2881         elif pos < 0 or pos > self._masklength: 
2882             raise IndexError('position %s out of range of control' % str(pos)) 
2884         if len(self._fields) == 0: 
2890         return self._fields[self._lookupField[pos]] 
2893     def ClearValue(self): 
2894         """ Blanks the current control value by replacing it with the default value.""" 
2895         dbg("MaskedEditMixin::ClearValue - value reset to default value (template)") 
2896         self._SetValue( self._template ) 
2897         self._SetInsertionPoint(0) 
2901     def _baseCtrlEventHandler(self, event): 
2903         This function is used whenever a key should be handled by the base control. 
2909     def _OnUpNumeric(self, event): 
2911         Makes up-arrow act like shift-tab should; ie. take you to start of 
2914         dbg('MaskedEditMixin::_OnUpNumeric', indent=1) 
2915         event.m_shiftDown = 1 
2916         dbg('event.ShiftDown()?', event.ShiftDown()) 
2917         self._OnChangeField(event) 
2921     def _OnArrow(self, event): 
2923         Used in response to left/right navigation keys; makes these actions skip 
2924         over mask template chars. 
2926         dbg("MaskedEditMixin::_OnArrow", indent=1) 
2927         pos = self._GetInsertionPoint() 
2928         keycode = event.GetKeyCode() 
2929         sel_start, sel_to = self._GetSelection() 
2930         entry_end = self._goEnd(getPosOnly=True) 
2931         if keycode in (wx.WXK_RIGHT, wx.WXK_DOWN): 
2932             if( ( not self._isTemplateChar(pos) and pos+1 > entry_end) 
2933                 or ( self._isTemplateChar(pos) and pos >= entry_end) ): 
2934                 dbg("can't advance", indent=0) 
2936             elif self._isTemplateChar(pos): 
2937                 self._AdjustField(pos) 
2938         elif keycode in (wx.WXK_LEFT,wx.WXK_UP) and sel_start == sel_to and pos > 0 and self._isTemplateChar(pos-1): 
2939             dbg('adjusting field') 
2940             self._AdjustField(pos) 
2942         # treat as shifted up/down arrows as tab/reverse tab: 
2943         if event.ShiftDown() and keycode in (wx.WXK_UP, wx.WXK_DOWN): 
2944             # remove "shifting" and treat as (forward) tab: 
2945             event.m_shiftDown = False 
2946             keep_processing = self._OnChangeField(event) 
2948         elif self._FindField(pos)._selectOnFieldEntry: 
2949             if( keycode in (wx.WXK_UP, wx.WXK_LEFT) 
2951                 and self._isTemplateChar(sel_start-1) 
2952                 and sel_start != self._masklength 
2953                 and not self._signOk and not self._useParens): 
2955                 # call _OnChangeField to handle "ctrl-shifted event" 
2956                 # (which moves to previous field and selects it.) 
2957                 event.m_shiftDown = True 
2958                 event.m_ControlDown = True 
2959                 keep_processing = self._OnChangeField(event) 
2960             elif( keycode in (wx.WXK_DOWN, wx.WXK_RIGHT) 
2961                   and sel_to != self._masklength 
2962                   and self._isTemplateChar(sel_to)): 
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) 
2968                 # treat arrows as normal, allowing selection 
2970                 dbg('using base ctrl event processing') 
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(): 
2978                 # treat arrows as normal, allowing selection 
2980                 dbg('using base event processing') 
2983         keep_processing = False 
2985         return keep_processing 
2988     def _OnCtrl_S(self, event): 
2989         """ Default Ctrl-S handler; prints value information if demo enabled. """ 
2990         dbg("MaskedEditMixin::_OnCtrl_S") 
2992             print 'MaskedEditMixin.GetValue()       = "%s"\nMaskedEditMixin.GetPlainValue() = "%s"' % (self.GetValue(), self.GetPlainValue()) 
2993             print "Valid? => " + str(self.IsValid()) 
2994             print "Current field, start, end, value =", str( self._FindFieldExtent(getslice=True)) 
2998     def _OnCtrl_X(self, event=None): 
2999         """ Handles ctrl-x keypress in control and Cut operation on context menu. 
3000             Should return False to skip other processing. """ 
3001         dbg("MaskedEditMixin::_OnCtrl_X", indent=1) 
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.""" 
3012     def _OnCtrl_V(self, event=None): 
3013         """ Handles ctrl-V keypress in control and Paste operation on context menu. 
3014             Should return False to skip other processing. """ 
3015         dbg("MaskedEditMixin::_OnCtrl_V", indent=1) 
3020     def _OnCtrl_Z(self, event=None): 
3021         """ Handles ctrl-Z keypress in control and Undo operation on context menu. 
3022             Should return False to skip other processing. """ 
3023         dbg("MaskedEditMixin::_OnCtrl_Z", indent=1) 
3028     def _OnCtrl_A(self,event=None): 
3029         """ Handles ctrl-a keypress in control. Should return False to skip other processing. """ 
3030         end = self._goEnd(getPosOnly=True) 
3031         if not event or event.ShiftDown(): 
3032             wx.CallAfter(self._SetInsertionPoint, 0) 
3033             wx.CallAfter(self._SetSelection, 0, self._masklength) 
3035             wx.CallAfter(self._SetInsertionPoint, 0) 
3036             wx.CallAfter(self._SetSelection, 0, end) 
3040     def _OnErase(self, event=None): 
3041         """ Handles backspace and delete keypress in control. Should return False to skip other processing.""" 
3042         dbg("MaskedEditMixin::_OnErase", indent=1) 
3043         sel_start, sel_to = self._GetSelection()                   ## check for a range of selected text 
3045         if event is None:   # called as action routine from Cut() operation. 
3048             key = event.GetKeyCode() 
3050         field = self._FindField(sel_to) 
3051         start, end = field._extent 
3052         value = self._GetValue() 
3053         oldstart = sel_start 
3055         # If trying to erase beyond "legal" bounds, disallow operation: 
3056         if( (sel_to == 0 and key == wx.WXK_BACK) 
3057             or (self._signOk and sel_to == 1 and value[0] == ' ' and key == wx.WXK_BACK) 
3058             or (sel_to == self._masklength and sel_start == sel_to and key == wx.WXK_DELETE and not field._insertRight) 
3059             or (self._signOk and self._useParens 
3060                 and sel_start == sel_to 
3061                 and sel_to == self._masklength - 1 
3062                 and value[sel_to] == ' ' and key == wx.WXK_DELETE and not field._insertRight) ): 
3063             if not wx.Validator_IsSilent(): 
3069         if( field._insertRight                                  # an insert-right field 
3070             and value[start:end] != self._template[start:end]   # and field not empty 
3071             and sel_start >= start                              # and selection starts in field 
3072             and ((sel_to == sel_start                           # and no selection 
3073                   and sel_to == end                             # and cursor at right edge 
3074                   and key in (wx.WXK_BACK, wx.WXK_DELETE))            # and either delete or backspace key 
3076                  (key == wx.WXK_BACK                               # backspacing 
3077                     and (sel_to == end                          # and selection ends at right edge 
3078                          or sel_to < end and field._allowInsert)) ) ):  # or allow right insert at any point in field 
3081             # if backspace but left of cursor is empty, adjust cursor right before deleting 
3082             while( key == wx.WXK_BACK 
3083                    and sel_start == sel_to 
3085                    and value[start:sel_start] == self._template[start:sel_start]): 
3089             dbg('sel_start, start:', sel_start, start) 
3091             if sel_start == sel_to: 
3095             newfield = value[start:keep] + value[sel_to:end] 
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 ('-', '('): 
3101                 newfield = signchar + newfield 
3102                 move_sign_into_field = True 
3103             dbg('cut newfield: "%s"' % newfield) 
3105             # handle what should fill in from the left: 
3107             for i in range(start, end - len(newfield)): 
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)) ): 
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) 
3119             newstr = value[:start] + newfield + value[end:] 
3121             # (handle sign located in "mask position" in front of field prior to delete) 
3122             if move_sign_into_field: 
3123                 newstr = ' ' + newstr[1:] 
3126             # handle erasure of (left) sign, moving selection accordingly... 
3127             if self._signOk and sel_start == 0: 
3128                 newstr = value = ' ' + value[1:] 
3131             if field._allowInsert and sel_start >= start: 
3132                 # selection (if any) falls within current insert-capable field: 
3133                 select_len = sel_to - sel_start 
3134                 # determine where cursor should end up: 
3135                 if key == wx.WXK_BACK: 
3137                         newpos = sel_start -1 
3143                     if sel_to == sel_start: 
3144                         erase_to = sel_to + 1 
3148                 if self._isTemplateChar(newpos) and select_len == 0: 
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] + ' ' 
3157                             # no deletion; just move cursor 
3160                         # no deletion; just move cursor 
3163                     if erase_to > end: erase_to = end 
3164                     erase_len = erase_to - newpos 
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] 
3170                     if field._alignRight: 
3171                         rstripped = right.rstrip() 
3172                         if rstripped != right: 
3173                             pos_adjust = len(right) - len(rstripped) 
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] + ' ' 
3181                     newfield = left+right 
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:] 
3191                 if sel_start == sel_to: 
3192                     dbg("current sel_start, sel_to:", sel_start, sel_to) 
3193                     if key == wx.WXK_BACK: 
3194                         sel_start, sel_to = sel_to-1, sel_to-1 
3195                         dbg("new sel_start, sel_to:", sel_start, sel_to) 
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: 
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])) 
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:] 
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] + ' ' 
3215                         if field._insertRight and sel_start == sel_to: 
3216                             # force non-insert-right behavior, by selecting char to be replaced: 
3218                         newstr, ignore = self._insertKey(newchar, sel_start, sel_start, sel_to, value) 
3222                     newstr = self._eraseSelection(value, sel_start, sel_to) 
3224                 pos = sel_start  # put cursor back at beginning of selection 
3226         if self._signOk and self._useParens: 
3227             # account for resultant unbalanced parentheses: 
3228             left_signpos = newstr.find('(') 
3229             right_signpos = newstr.find(')') 
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:] 
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:] 
3239         dbg("oldstr:'%s'" % value, 'oldpos:', oldstart) 
3240         dbg("newstr:'%s'" % newstr, 'pos:', pos) 
3242         # if erasure results in an invalid field, disallow it: 
3243         dbg('field._validRequired?', field._validRequired) 
3244         dbg('field.IsValid("%s")?' % newstr[start:end], field.IsValid(newstr[start:end])) 
3245         if field._validRequired and not field.IsValid(newstr[start:end]): 
3246             if not wx.Validator_IsSilent(): 
3251         # if erasure results in an invalid value, disallow it: 
3252         if self._ctrl_constraints._validRequired and not self.IsValid(newstr): 
3253             if not wx.Validator_IsSilent(): 
3258         dbg('setting value (later) to', newstr) 
3259         wx.CallAfter(self._SetValue, newstr) 
3260         dbg('setting insertion point (later) to', pos) 
3261         wx.CallAfter(self._SetInsertionPoint, pos) 
3266     def _OnEnd(self,event): 
3267         """ Handles End keypress in control. Should return False to skip other processing. """ 
3268         dbg("MaskedEditMixin::_OnEnd", indent=1) 
3269         pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode()) 
3270         if not event.ControlDown(): 
3271             end = self._masklength  # go to end of control 
3272             if self._signOk and self._useParens: 
3273                 end = end - 1       # account for reserved char at end 
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) 
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]) 
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: 
3297                     dbg('end moved to', end) 
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) 
3304                     end = edit_end  # select to end of current field 
3305                     dbg('end moved to ', end) 
3307                 # select to current end of input 
3311 ##        dbg('pos:', pos, 'end:', end) 
3313         if event.ShiftDown(): 
3314             if not event.ControlDown(): 
3315                 dbg("shift-end; select to end of control") 
3317                 dbg("shift-ctrl-end; select to end of non-whitespace") 
3318             wx.CallAfter(self._SetInsertionPoint, pos) 
3319             wx.CallAfter(self._SetSelection, pos, end) 
3321             if not event.ControlDown(): 
3322                 dbg('go to end of control:') 
3323             wx.CallAfter(self._SetInsertionPoint, end) 
3324             wx.CallAfter(self._SetSelection, end, end) 
3330     def _OnReturn(self, event): 
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." 
3335          dbg('MaskedEditMixin::OnReturn') 
3336          event.m_keyCode = wx.WXK_TAB 
3340     def _OnHome(self,event): 
3341         """ Handles Home keypress in control. Should return False to skip other processing.""" 
3342         dbg("MaskedEditMixin::_OnHome", indent=1) 
3343         pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode()) 
3344         sel_start, sel_to = self._GetSelection() 
3346         # There are 5 cases here: 
3348         # 1) shift: select from start of control to end of current 
3350         if event.ShiftDown() and not event.ControlDown(): 
3351             dbg("shift-home; select to start of control") 
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") 
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 
3382             if not event.ShiftDown(): 
3383                 dbg("ctrl-home; move to beginning of field") 
3386                 dbg("shift-ctrl-home; select to beginning of field") 
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. 
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) 
3404                 end_of_field = False 
3405             dbg("shift-ctrl-home; unselect to beginning of field") 
3407         dbg('queuing new sel_start, sel_to:', (start, end)) 
3408         wx.CallAfter(self._SetInsertionPoint, start) 
3409         wx.CallAfter(self._SetSelection, start, end) 
3414     def _OnChangeField(self, event): 
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 
3422         dbg('MaskedEditMixin::_OnChangeField', indent = 1) 
3423         # determine end of current field: 
3424         pos = self._GetInsertionPoint() 
3425         dbg('current pos:', pos) 
3426         sel_start, sel_to = self._GetSelection() 
3428         if self._masklength < 0:   # no fields; process tab normally 
3429             self._AdjustField(pos) 
3430             if event.GetKeyCode() == wx.WXK_TAB: 
3431                 dbg('tab to next ctrl') 
3438         if event.ShiftDown(): 
3442             # NOTE: doesn't yet work with SHIFT-tab under wx; the control 
3443             # never sees this event! (But I've coded for it should it ever work, 
3444             # and it *does* work for '.' in IpAddrCtrl.) 
3445             field = self._FindField(pos) 
3446             index = field._index 
3447             field_start = field._extent[0] 
3448             if pos < field_start: 
3449                 dbg('cursor before 1st field; cannot change to a previous field') 
3450                 if not wx.Validator_IsSilent(): 
3454             if event.ControlDown(): 
3455                 dbg('queuing select to beginning of field:', field_start, pos) 
3456                 wx.CallAfter(self._SetInsertionPoint, field_start) 
3457                 wx.CallAfter(self._SetSelection, field_start, pos) 
3462                   # We're already in the 1st field; process shift-tab normally: 
3463                 self._AdjustField(pos) 
3464                 if event.GetKeyCode() == wx.WXK_TAB: 
3465                     dbg('tab to previous ctrl') 
3468                     dbg('position at beginning') 
3469                     wx.CallAfter(self._SetInsertionPoint, field_start) 
3473                 # find beginning of previous field: 
3474                 begin_prev = self._FindField(field_start-1)._extent[0] 
3475                 self._AdjustField(pos) 
3476                 dbg('repositioning to', begin_prev) 
3477                 wx.CallAfter(self._SetInsertionPoint, begin_prev) 
3478                 if self._FindField(begin_prev)._selectOnFieldEntry: 
3479                     edit_start, edit_end = self._FindFieldExtent(begin_prev) 
3480                     dbg('queuing selection to (%d, %d)' % (edit_start, edit_end)) 
3481                     wx.CallAfter(self._SetInsertionPoint, edit_start) 
3482                     wx.CallAfter(self._SetSelection, edit_start, edit_end) 
3488             field = self._FindField(sel_to) 
3489             field_start, field_end = field._extent 
3490             if event.ControlDown(): 
3491                 dbg('queuing select to end of field:', pos, field_end) 
3492                 wx.CallAfter(self._SetInsertionPoint, pos) 
3493                 wx.CallAfter(self._SetSelection, pos, field_end) 
3497                 if pos < field_start: 
3498                     dbg('cursor before 1st field; go to start of field') 
3499                     wx.CallAfter(self._SetInsertionPoint, field_start) 
3500                     if field._selectOnFieldEntry: 
3501                         wx.CallAfter(self._SetSelection, field_start, field_end) 
3503                         wx.CallAfter(self._SetSelection, field_start, field_start) 
3506                 dbg('end of current field:', field_end) 
3507                 dbg('go to next field') 
3508                 if field_end == self._fields[self._field_indices[-1]]._extent[1]: 
3509                     self._AdjustField(pos) 
3510                     if event.GetKeyCode() == wx.WXK_TAB: 
3511                         dbg('tab to next ctrl') 
3514                         dbg('position at end') 
3515                         wx.CallAfter(self._SetInsertionPoint, field_end) 
3519                     # we have to find the start of the next field 
3520                     next_pos = self._findNextEntry(field_end) 
3521                     if next_pos == field_end: 
3522                         dbg('already in last field') 
3523                         self._AdjustField(pos) 
3524                         if event.GetKeyCode() == wx.WXK_TAB: 
3525                             dbg('tab to next ctrl') 
3531                         self._AdjustField( pos ) 
3533                         # move cursor to appropriate point in the next field and select as necessary: 
3534                         field = self._FindField(next_pos) 
3535                         edit_start, edit_end = field._extent 
3536                         if field._selectOnFieldEntry: 
3537                             dbg('move to ', next_pos) 
3538                             wx.CallAfter(self._SetInsertionPoint, next_pos) 
3539                             edit_start, edit_end = self._FindFieldExtent(next_pos) 
3540                             dbg('queuing select', edit_start, edit_end) 
3541                             wx.CallAfter(self._SetSelection, edit_start, edit_end) 
3543                             if field._insertRight: 
3544                                 next_pos = field._extent[1] 
3545                             dbg('move to ', next_pos) 
3546                             wx.CallAfter(self._SetInsertionPoint, next_pos) 
3551     def _OnDecimalPoint(self, event): 
3552         dbg('MaskedEditMixin::_OnDecimalPoint', indent=1) 
3554         pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode()) 
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) 
3564                 newstr = self._adjustFloat(value) 
3565             wx.CallAfter(self._SetValue, newstr) 
3566             fraction = self._fields[1] 
3567             start, end = fraction._extent 
3568             wx.CallAfter(self._SetInsertionPoint, start) 
3569             if fraction._selectOnFieldEntry: 
3570                 dbg('queuing selection after decimal point to:', (start, end)) 
3571                 wx.CallAfter(self._SetSelection, start, end) 
3572             keep_processing = False 
3574         if self._isInt:      ## handle integer value, truncate from current position 
3575             dbg('key == Integer decimal event') 
3576             value = self._GetValue() 
3577             clipped_text = value[0:pos] 
3578             dbg('value: "%s"' % self._GetValue(), "clipped_text:'%s'" % clipped_text) 
3579             newstr = self._adjustInt(clipped_text) 
3580             dbg('newstr: "%s"' % newstr) 
3581             wx.CallAfter(self._SetValue, newstr) 
3582             newpos = len(newstr.rstrip()) 
3583             if newstr.find(')') != -1: 
3584                 newpos -= 1     # (don't move past right paren) 
3585             wx.CallAfter(self._SetInsertionPoint, newpos) 
3586             keep_processing = False 
3590     def _OnChangeSign(self, event): 
3591         dbg('MaskedEditMixin::_OnChangeSign', indent=1) 
3592         key = event.GetKeyCode() 
3593         pos = self._adjustPos(self._GetInsertionPoint(), key) 
3594         value = self._eraseSelection() 
3595         integer = self._fields[0] 
3596         start, end = integer._extent 
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 
3606             dbg('isNeg?', self._isNeg) 
3608             text, self._signpos, self._right_signpos = self._getSignedValue(candidate=value) 
3609             dbg('text:"%s"' % text, 'signpos:', self._signpos, 'right_signpos:', self._right_signpos) 
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:] 
3617                     text = text[:self._signpos] + '-' + text[self._signpos+1:] 
3619 ##                dbg('self._isNeg?', self._isNeg, 'self.IsValid(%s)' % text, self.IsValid(text)) 
3621                     text = text[:self._signpos] + ' ' + text[self._signpos+1:self._right_signpos] + ' ' + text[self._right_signpos+1:] 
3623                     text = text[:self._signpos] + ' ' + text[self._signpos+1:] 
3624                 dbg('clearing self._isNeg') 
3627             wx.CallAfter(self._SetValue, text) 
3628             wx.CallAfter(self._applyFormatting) 
3629             dbg('pos:', pos, 'signpos:', self._signpos) 
3630             if pos == self._signpos or integer.IsEmpty(text[start:end]): 
3631                 wx.CallAfter(self._SetInsertionPoint, self._signpos+1) 
3633                 wx.CallAfter(self._SetInsertionPoint, pos) 
3635             keep_processing = False 
3637             keep_processing = True 
3639         return keep_processing 
3642     def _OnGroupChar(self, event): 
3644         This handler is only registered if the mask is a numeric mask. 
3645         It allows the insertion of ',' or '.' if appropriate. 
3647         dbg('MaskedEditMixin::_OnGroupChar', indent=1) 
3648         keep_processing = True 
3649         pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode()) 
3650         sel_start, sel_to = self._GetSelection() 
3651         groupchar = self._fields[0]._groupChar 
3652         if not self._isCharAllowed(groupchar, pos, checkRegex=True): 
3653             keep_processing = False 
3654             if not wx.Validator_IsSilent(): 
3658             newstr, newpos = self._insertKey(groupchar, pos, sel_start, sel_to, self._GetValue() ) 
3659             dbg("str with '%s' inserted:" % groupchar, '"%s"' % newstr) 
3660             if self._ctrl_constraints._validRequired and not self.IsValid(newstr): 
3661                 keep_processing = False 
3662                 if not wx.Validator_IsSilent(): 
3666             wx.CallAfter(self._SetValue, newstr) 
3667             wx.CallAfter(self._SetInsertionPoint, newpos) 
3668         keep_processing = False 
3670         return keep_processing 
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 
3680         while self._isTemplateChar(pos) and pos < self._masklength: 
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): 
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: 
3702     def _OnAutoCompleteField(self, event): 
3703         dbg('MaskedEditMixin::_OnAutoCompleteField', indent =1) 
3704         pos = self._GetInsertionPoint() 
3705         field = self._FindField(pos) 
3706         edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True) 
3709         keycode = event.GetKeyCode() 
3711         if field._fillChar != ' ': 
3712             text = slice.replace(field._fillChar, '') 
3716         keep_processing = True  # (assume True to start) 
3717         dbg('field._hasList?', field._hasList) 
3719             dbg('choices:', field._choices) 
3720             dbg('compareChoices:', field._compareChoices) 
3721             choices, choice_required = field._compareChoices, field._choiceRequired 
3722             if keycode in (wx.WXK_PRIOR, wx.WXK_UP): 
3726             match_index, partial_match = self._autoComplete(direction, choices, text, compareNoCase=field._compareNoCase, current_index = field._autoCompleteIndex) 
3727             if( match_index is None 
3728                 and (keycode in self._autoCompleteKeycodes + [wx.WXK_PRIOR, wx.WXK_NEXT] 
3729                      or (keycode in [wx.WXK_UP, wx.WXK_DOWN] and event.ShiftDown() ) ) ): 
3730                 # Select the 1st thing from the list: 
3733             if( match_index is not None 
3734                 and ( keycode in self._autoCompleteKeycodes + [wx.WXK_PRIOR, wx.WXK_NEXT] 
3735                       or (keycode in [wx.WXK_UP, wx.WXK_DOWN] and event.ShiftDown()) 
3736                       or (keycode == wx.WXK_DOWN and partial_match) ) ): 
3738                 # We're allowed to auto-complete: 
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 
3749         if keycode in (wx.WXK_UP, wx.WXK_DOWN, wx.WXK_LEFT, wx.WXK_RIGHT): 
3750             # treat as left right arrow if unshifted, tab/shift tab if shifted. 
3751             if event.ShiftDown(): 
3752                 if keycode in (wx.WXK_DOWN, wx.WXK_RIGHT): 
3753                     # remove "shifting" and treat as (forward) tab: 
3754                     event.m_shiftDown = False 
3755                 keep_processing = self._OnChangeField(event) 
3757                 keep_processing = self._OnArrow(event) 
3758         # else some other key; keep processing the key 
3760         dbg('keep processing?', keep_processing, indent=0) 
3761         return keep_processing 
3764     def _OnAutoSelect(self, field, match_index = None): 
3766         Function called if autoselect feature is enabled and entire control 
3769         dbg('MaskedEditMixin::OnAutoSelect', field._index) 
3770         if match_index is not None: 
3771             field._autoCompleteIndex = match_index 
3774     def _autoComplete(self, direction, choices, value, compareNoCase, current_index): 
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. 
3786         dbg('autoComplete(direction=', direction, 'choices=',choices, 'value=',value,'compareNoCase?', compareNoCase, 'current_index:', current_index, indent=1) 
3788             dbg('nothing to match against', indent=0) 
3789             return (None, False) 
3791         partial_match = False 
3794             value = value.lower() 
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 
3802                 index = choices.index(value) 
3804             dbg('matched "%s" (%d)' % (choices[index], index)) 
3806                 dbg('going to previous') 
3807                 if index == 0: index = len(choices) - 1 
3810                 if index == len(choices) - 1: index = 0 
3812             dbg('change value to "%s" (%d)' % (choices[index], index)) 
3815             partial_match = True 
3816             value = value.strip() 
3817             dbg('no match; try to auto-complete:') 
3819             dbg('searching for "%s"' % value) 
3820             if current_index is None: 
3821                 indices = range(len(choices)) 
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) 
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) 
3838                 else: dbg('choice: "%s" - no match' % choice) 
3839             if match is not None: 
3840                 dbg('matched', match) 
3842                 dbg('no match found') 
3844         return (match, partial_match) 
3847     def _AdjustField(self, pos): 
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. 
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. 
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:] 
3865         if self._isFloat and newvalue != self._template: 
3866             newvalue = self._adjustFloat(newvalue) 
3868         if self._ctrl_constraints._isInt and value != self._template: 
3869             newvalue = self._adjustInt(value) 
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]: 
3878         if newvalue != value: 
3879             self._SetValue(newvalue) 
3880             self._SetInsertionPoint(pos) 
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()) 
3889         if field._forcelower and key in range(97,123): 
3890             key = ord( chr(key).lower()) 
3895     def _adjustPos(self, pos, key): 
3897         Checks the current insertion point position and adjusts it if 
3898         necessary to skip over non-editable characters. 
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. 
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) 
3910         if key not in self._nav: 
3911             field = self._FindField(pos) 
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 
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) 
3930                             self._SetSelection(pos, sel_to)     # restore selection 
3932                             self._SetSelection(pos, pos)        # remove selection 
3933                     else: # leave cursor alone 
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) 
3942 ##                        self._SetInsertionPoint(pos) 
3943 ##                        # restore selection 
3944 ##                        self._SetSelection(sel_start, pos) 
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) 
3951                         self._SetSelection(pos, sel_to) 
3953                         pass    # leave position/selection alone 
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 
3961                                and field._index == 0 
3962                                and pos > 0) ) ):      # don't move to next field without explicit cursor movement 
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) 
3974     def _adjustFloat(self, candidate=None): 
3976         'Fixes' an floating point control. Collapses spaces, right-justifies, etc. 
3978         dbg('MaskedEditMixin::_adjustFloat, candidate = "%s"' % candidate, indent=1) 
3979         lenInt,lenFraction  = [len(s) for s in self._mask.split('.')]  ## Get integer, fraction lengths 
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) 
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 
3991         dbg('intStr "%(intStr)s"' % locals()) 
3992         dbg('lenInt:', lenInt) 
3994         intStr = string.rjust( intStr[-lenInt:], lenInt) 
3995         dbg('right-justifed intStr = "%(intStr)s"' % locals()) 
3996         newvalue = intStr + self._decimalChar + fracStr 
3999             if len(newvalue) < self._masklength: 
4000                 newvalue = ' ' + newvalue 
4001             signedvalue = self._getSignedValue(newvalue)[0] 
4002             if signedvalue is not None: newvalue = signedvalue 
4004         # Finally, align string with decimal position, left-padding with 
4006         newdecpos = newvalue.find(self._decimalChar) 
4007         if newdecpos < self._decimalpos: 
4008             padlen = self._decimalpos - newdecpos 
4009             newvalue = string.join([' ' * padlen] + [newvalue] ,'') 
4011         if self._signOk and self._useParens: 
4012             if newvalue.find('(') != -1: 
4013                 newvalue = newvalue[:-1] + ')' 
4015                 newvalue = newvalue[:-1] + ' ' 
4017         dbg('newvalue = "%s"' % newvalue) 
4018         if candidate is None: 
4019             wx.CallAfter(self._SetValue, newvalue) 
4024     def _adjustInt(self, candidate=None): 
4025         """ 'Fixes' an integer control. Collapses spaces, right or left-justifies.""" 
4026         dbg("MaskedEditMixin::_adjustInt", candidate) 
4027         lenInt = self._masklength 
4028         if candidate is None: value = self._GetValue() 
4029         else: value = candidate 
4031         intStr = self._fields[0]._AdjustField(value) 
4032         intStr = intStr.strip() # drop extra spaces 
4033         dbg('adjusted field: "%s"' % intStr) 
4035         if self._isNeg and intStr.find('-') == -1 and intStr.find('(') == -1: 
4037                 intStr = '(' + intStr + ')' 
4039                 intStr = '-' + intStr 
4040         elif self._isNeg and intStr.find('-') != -1 and self._useParens: 
4041             intStr = intStr.replace('-', '(') 
4043         if( self._signOk and ((self._useParens and intStr.find('(') == -1) 
4044                                 or (not self._useParens and intStr.find('-') == -1))): 
4045             intStr = ' ' + intStr 
4047                 intStr += ' '   # space for right paren position 
4049         elif self._signOk and self._useParens and intStr.find('(') != -1 and intStr.find(')') == -1: 
4050             # ensure closing right paren: 
4053         if self._fields[0]._alignRight:     ## Only if right-alignment is enabled 
4054             intStr = intStr.rjust( lenInt ) 
4056             intStr = intStr.ljust( lenInt ) 
4058         if candidate is None: 
4059             wx.CallAfter(self._SetValue, intStr ) 
4063     def _adjustDate(self, candidate=None, fixcentury=False, force4digit_year=False): 
4065         'Fixes' a date control, expanding the year if it can. 
4066         Applies various self-formatting options. 
4068         dbg("MaskedEditMixin::_adjustDate", indent=1) 
4069         if candidate is None: text    = self._GetValue() 
4070         else: text = candidate 
4072         if self._datestyle == "YMD": 
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) 
4084         yearstart = self._dateExtent - 4 
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: 
4095                 dbg('bad year=', year) 
4096                 year = text[yearstart:self._dateExtent] 
4098         if len(year) < 4 and yearVal: 
4100                 # Fix year adjustment to be less "20th century" :-) and to adjust heuristic as the 
4102                 now = wx.DateTime_Now() 
4103                 century = (now.GetYear() /100) * 100        # "this century" 
4104                 twodig_year = now.GetYear() - century       # "this year" (2 digits) 
4105                 # if separation between today's 2-digit year and typed value > 50, 
4106                 #      assume last century, 
4107                 # else assume this century. 
4109                 # Eg: if 2003 and yearVal == 30, => 2030 
4110                 #     if 2055 and yearVal == 80, => 2080 
4111                 #     if 2010 and yearVal == 96, => 1996 
4113                 if abs(yearVal - twodig_year) > 50: 
4114                     yearVal = (century - 100) + yearVal 
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) 
4126     def _goEnd(self, getPosOnly=False): 
4127         """ Moves the insertion point to the end of user-entry """ 
4128         dbg("MaskedEditMixin::_goEnd; getPosOnly:", getPosOnly, indent=1) 
4129         text = self._GetValue() 
4130 ##        dbg('text: "%s"' % text) 
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): 
4137 ##                    dbg("text[%d]: '%s'" % (i, char)) 
4143             pos = self._goHome(getPosOnly=True) 
4145             pos = min(i,self._masklength) 
4147         field = self._FindField(pos) 
4148         start, end = field._extent 
4149         if field._insertRight and pos < end: 
4151         dbg('next pos:', pos) 
4156             self._SetInsertionPoint(pos) 
4159     def _goHome(self, getPosOnly=False): 
4160         """ Moves the insertion point to the beginning of user-entry """ 
4161         dbg("MaskedEditMixin::_goHome; getPosOnly:", getPosOnly, indent=1) 
4162         text = self._GetValue() 
4163         for i in range(self._masklength): 
4164             if self._isMaskChar(i): 
4171             self._SetInsertionPoint(max(i,0)) 
4175     def _getAllowedChars(self, pos): 
4176         """ Returns a string of all allowed user input characters for the provided 
4177             mask character plus control options 
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? 
4184         if okchars and field._includeChars:      ## any additional included characters? 
4185             okchars += field._includeChars 
4186 ##        dbg('okchars[%d]:' % pos, okchars) 
4190     def _isMaskChar(self, pos): 
4191         """ Returns True if the char at position pos is a special mask character (e.g. NCXaA#) 
4193         if pos < self._masklength: 
4194             return self.ismasked[pos] 
4199     def _isTemplateChar(self,Pos): 
4200         """ Returns True if the char at position pos is a template character (e.g. -not- NCXaA#) 
4202         if Pos < self._masklength: 
4203             return not self._isMaskChar(Pos) 
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 
4214         if self.controlInitialized: 
4215             sel_start, sel_to = self._GetSelection() 
4217             sel_start, sel_to = pos, pos 
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() 
4226                     while fstr and fstr[0] == '0': 
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 
4232                 value = self._template 
4233                 input_len = 0   # can't get the current "value", so use 0 
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)): 
4241                 dbg('pos = end - 1 = ', pos, 'right_insert? 1') 
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') 
4249             # else leave pos alone... 
4251                 dbg('pos stays ', pos, 'right_insert? 0') 
4254         if self._isTemplateChar( pos ):  ## if a template character, return empty 
4255             dbg('%d is a template character; returning False' % pos, indent=0) 
4258         if self._isMaskChar( pos ): 
4259             okChars  = self._getAllowedChars(pos) 
4261             if self._fields[0]._groupdigits and (self._isInt or (self._isFloat and pos < self._decimalpos)): 
4262                 okChars += self._fields[0]._groupChar 
4265                 if self._isInt or (self._isFloat and pos < self._decimalpos): 
4269                 elif self._useParens and (self._isInt or (self._isFloat and pos > self._decimalpos)): 
4272 ##            dbg('%s in %s?' % (char, okChars), char in okChars) 
4273             approved = char in okChars 
4275             if approved and checkRegex: 
4276                 dbg("checking appropriate regex's") 
4277                 value = self._eraseSelection(self._GetValue()) 
4283                     newvalue, ignore, ignore, ignore, ignore = self._insertKey(char, at, sel_start, sel_to, value, allowAutoSelect=True) 
4285                     newvalue, ignore = self._insertKey(char, at, sel_start, sel_to, value) 
4286                 dbg('newvalue: "%s"' % newvalue) 
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 
4300             dbg('%d is a !???! character; returning False', indent=0) 
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. 
4310         dbg('MaskedEditMixin::_applyFormatting', indent=1) 
4312         # Handle negative numbers 
4314             text, signpos, right_signpos = self._getSignedValue() 
4315             dbg('text: "%s", signpos:' % text, signpos) 
4316             if not text or text[signpos] not in ('-','('): 
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') 
4324             dbg('self._isNeg:', self._isNeg) 
4326         if self._signOk and self._isNeg: 
4327             fc = self._signedForegroundColour 
4329             fc = self._foregroundColour 
4331         if hasattr(fc, '_name'): 
4335         dbg('setting foreground to', c) 
4336         self.SetForegroundColour(fc) 
4341                 bc = self._emptyBackgroundColour 
4343                 bc = self._validBackgroundColour 
4346             bc = self._invalidBackgroundColour 
4347         if hasattr(bc, '_name'): 
4351         dbg('setting background to', c) 
4352         self.SetBackgroundColour(bc) 
4354         dbg(indent=0, suspend=0) 
4357     def _getAbsValue(self, candidate=None): 
4358         """ Return an unsigned value (i.e. strip the '-' prefix if any), and sign position(s). 
4360         dbg('MaskedEditMixin::_getAbsValue; candidate="%s"' % candidate, indent=1) 
4361         if candidate is None: text = self._GetValue() 
4362         else: text = candidate 
4363         right_signpos = text.find(')') 
4366             if self._ctrl_constraints._alignRight and self._fields[0]._fillChar == ' ': 
4367                 signpos = text.find('-') 
4369                     dbg('no - found; searching for (') 
4370                     signpos = text.find('(') 
4372                     dbg('- found at', signpos) 
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: 
4379                     if len(text) < self._masklength: 
4381                     if len(text) > self._masklength and text[-1] in (')', ' '): 
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) 
4388                         if self._useParens and not text.strip(): 
4389                             signpos -= 1    # empty value; use penultimate space 
4390                 dbg('signpos:', signpos) 
4392                     text = text[:signpos] + ' ' + text[signpos+1:] 
4397                     text = self._template[0] + text[1:] 
4401             if right_signpos != -1: 
4403                     text = text[:right_signpos] + ' ' + text[right_signpos+1:] 
4404                 elif len(text) > self._masklength: 
4405                     text = text[:right_signpos] + text[right_signpos+1:] 
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) 
4420             groupchar = self._fields[0]._groupChar 
4422                 value = long(text.replace(groupchar,'').replace('(','-').replace(')','').replace(' ', '')) 
4424                 dbg('invalid number', indent=0) 
4425                 return None, signpos, right_signpos 
4429                 groupchar = self._fields[0]._groupChar 
4430                 value = float(text.replace(groupchar,'').replace(self._decimalChar, '.').replace('(', '-').replace(')','').replace(' ', '')) 
4431                 dbg('value:', value) 
4435             if value < 0 and value is not None: 
4436                 signpos = text.find('-') 
4438                     signpos = text.find('(') 
4440                 text = text[:signpos] + self._template[signpos] + text[signpos+1:] 
4442                 # look forwards up to the decimal point for the 1st non-digit 
4443                 dbg('decimal pos:', self._decimalpos) 
4444                 dbg('text: "%s"' % text) 
4446                     signpos = self._decimalpos - (len(text[:self._decimalpos].lstrip()) + 1) 
4447                     # prevent checking for empty string - Tomo - Wed 14 Jan 2004 03:19:09 PM CET 
4448                     if len(text) >= signpos+1 and  text[signpos+1] in ('-','('): 
4452                 dbg('signpos:', signpos) 
4456                     right_signpos = self._masklength - 1 
4457                     text = text[:right_signpos] + ' ' 
4458                     if text[signpos] == '(': 
4459                         text = text[:signpos] + ' ' + text[signpos+1:] 
4461                     right_signpos = text.find(')') 
4462                     if right_signpos != -1: 
4467                 dbg('invalid number') 
4470         dbg('abstext = "%s"' % text, 'signpos:', signpos, 'right_signpos:', right_signpos) 
4472         return text, signpos, right_signpos 
4475     def _getSignedValue(self, candidate=None): 
4476         """ Return a signed value by adding a "-" prefix if the value 
4477             is set to negative, or a space if positive. 
4479         dbg('MaskedEditMixin::_getSignedValue; candidate="%s"' % candidate, indent=1) 
4480         if candidate is None: text = self._GetValue() 
4481         else: text = candidate 
4484         abstext, signpos, right_signpos = self._getAbsValue(text) 
4488                 return abstext, signpos, right_signpos 
4490             if self._isNeg or text[signpos] in ('-', '('): 
4497             if abstext[signpos] not in string.digits: 
4498                 text = abstext[:signpos] + sign + abstext[signpos+1:] 
4500                 # this can happen if value passed is too big; sign assumed to be 
4501                 # in position 0, but if already filled with a digit, prepend sign... 
4502                 text = sign + abstext 
4503             if self._useParens and text.find('(') != -1: 
4504                 text = text[:right_signpos] + ')' + text[right_signpos+1:] 
4507         dbg('signedtext = "%s"' % text, 'signpos:', signpos, 'right_signpos', right_signpos) 
4509         return text, signpos, right_signpos 
4512     def GetPlainValue(self, candidate=None): 
4513         """ Returns control's value stripped of the template text. 
4514             plainvalue = MaskedEditMixin.GetPlainValue() 
4516         dbg('MaskedEditMixin::GetPlainValue; candidate="%s"' % candidate, indent=1) 
4518         if candidate is None: text = self._GetValue() 
4519         else: text = candidate 
4522             dbg('returned ""', indent=0) 
4526             for idx in range( min(len(self._template), len(text)) ): 
4527                 if self._mask[idx] in maskchars: 
4530             if self._isFloat or self._isInt: 
4531                 dbg('plain so far: "%s"' % plain) 
4532                 plain = plain.replace('(', '-').replace(')', ' ') 
4533                 dbg('plain after sign regularization: "%s"' % plain) 
4535                 if self._signOk and self._isNeg and plain.count('-') == 0: 
4536                     # must be in reserved position; add to "plain value" 
4537                     plain = '-' + plain.strip() 
4539                 if self._fields[0]._alignRight: 
4540                     lpad = plain.count(',') 
4541                     plain = ' ' * lpad + plain.replace(',','') 
4543                     plain = plain.replace(',','') 
4544                 dbg('plain after pad and group:"%s"' % plain) 
4546             dbg('returned "%s"' % plain.rstrip(), indent=0) 
4547             return plain.rstrip() 
4550     def IsEmpty(self, value=None): 
4552         Returns True if control is equal to an empty value. 
4553         (Empty means all editable positions in the template == fillChar.) 
4555         if value is None: value = self._GetValue() 
4556         if value == self._template and not self._defaultValue: 
4557 ##            dbg("IsEmpty? 1 (value == self._template and not self._defaultValue)") 
4558             return True     # (all mask chars == fillChar by defn) 
4559         elif value == self._template: 
4561             for pos in range(len(self._template)): 
4562 ##                dbg('isMaskChar(%(pos)d)?' % locals(), self._isMaskChar(pos)) 
4563 ##                dbg('value[%(pos)d] != self._fillChar?' %locals(), value[pos] != self._fillChar[pos]) 
4564                 if self._isMaskChar(pos) and value[pos] not in (' ', self._fillChar[pos]): 
4566 ##            dbg("IsEmpty? %(empty)d (do all mask chars == fillChar?)" % locals()) 
4569 ##            dbg("IsEmpty? 0 (value doesn't match template)") 
4573     def IsDefault(self, value=None): 
4575         Returns True if the value specified (or the value of the control if not specified) 
4576         is equal to the default value. 
4578         if value is None: value = self._GetValue() 
4579         return value == self._template 
4582     def IsValid(self, value=None): 
4583         """ Indicates whether the value specified (or the current value of the control 
4584         if not specified) is considered valid.""" 
4585 ##        dbg('MaskedEditMixin::IsValid("%s")' % value, indent=1) 
4586         if value is None: value = self._GetValue() 
4587         ret = self._CheckValid(value) 
4592     def _eraseSelection(self, value=None, sel_start=None, sel_to=None): 
4593         """ Used to blank the selection when inserting a new character. """ 
4594         dbg("MaskedEditMixin::_eraseSelection", indent=1) 
4595         if value is None: value = self._GetValue() 
4596         if sel_start is None or sel_to is None: 
4597             sel_start, sel_to = self._GetSelection()                   ## check for a range of selected text 
4598         dbg('value: "%s"' % value) 
4599         dbg("current sel_start, sel_to:", sel_start, sel_to) 
4601         newvalue = list(value) 
4602         for i in range(sel_start, sel_to): 
4603             if self._signOk and newvalue[i] in ('-', '(', ')'): 
4604                 dbg('found sign (%s) at' % newvalue[i], i) 
4606                 # balance parentheses: 
4607                 if newvalue[i] == '(': 
4608                     right_signpos = value.find(')') 
4609                     if right_signpos != -1: 
4610                         newvalue[right_signpos] = ' ' 
4612                 elif newvalue[i] == ')': 
4613                     left_signpos = value.find('(') 
4614                     if left_signpos != -1: 
4615                         newvalue[left_signpos] = ' ' 
4619             elif self._isMaskChar(i): 
4620                 field = self._FindField(i) 
4624                     newvalue[i] = self._template[i] 
4626         value = string.join(newvalue,"") 
4627         dbg('new value: "%s"' % value) 
4632     def _insertKey(self, char, pos, sel_start, sel_to, value, allowAutoSelect=False): 
4633         """ Handles replacement of the character at the current insertion point.""" 
4634         dbg('MaskedEditMixin::_insertKey', "\'" + char + "\'", pos, sel_start, sel_to, '"%s"' % value, indent=1) 
4636         text = self._eraseSelection(value) 
4637         field = self._FindField(pos) 
4638         start, end = field._extent 
4642         if pos != sel_start and sel_start == sel_to: 
4643             # adjustpos must have moved the position; make selection match: 
4644             sel_start = sel_to = pos 
4646         dbg('field._insertRight?', field._insertRight) 
4647         if( field._insertRight                                  # field allows right insert 
4648             and ((sel_start, sel_to) == field._extent           # and whole field selected 
4649                  or (sel_start == sel_to                        # or nothing selected 
4650                      and (sel_start == end                      # and cursor at right edge 
4651                           or (field._allowInsert                # or field allows right-insert 
4652                               and sel_start < end               # next to other char in field: 
4653                               and text[sel_start] != field._fillChar) ) ) ) ): 
4655             fstr = text[start:end] 
4656             erasable_chars = [field._fillChar, ' '] 
4659                 erasable_chars.append('0') 
4662 ##            dbg("fstr[0]:'%s'" % fstr[0]) 
4663 ##            dbg('field_index:', field._index) 
4664 ##            dbg("fstr[0] in erasable_chars?", fstr[0] in erasable_chars) 
4665 ##            dbg("self._signOk and field._index == 0 and fstr[0] in ('-','(')?", 
4666 ##                 self._signOk and field._index == 0 and fstr[0] in ('-','(')) 
4667             if fstr[0] in erasable_chars or (self._signOk and field._index == 0 and fstr[0] in ('-','(')): 
4669 ##                dbg('value:      "%s"' % text) 
4670 ##                dbg('fstr:       "%s"' % fstr) 
4671 ##                dbg("erased:     '%s'" % erased) 
4672                 field_sel_start = sel_start - start 
4673                 field_sel_to = sel_to - start 
4674                 dbg('left fstr:  "%s"' % fstr[1:field_sel_start]) 
4675                 dbg('right fstr: "%s"' % fstr[field_sel_to:end]) 
4676                 fstr = fstr[1:field_sel_start] + char + fstr[field_sel_to:end] 
4677             if field._alignRight and sel_start != sel_to: 
4678                 field_len = end - start 
4679 ##                pos += (field_len - len(fstr))    # move cursor right by deleted amount 
4681                 dbg('setting pos to:', pos) 
4683                     fstr = '0' * (field_len - len(fstr)) + fstr 
4685                     fstr = fstr.rjust(field_len)   # adjust the field accordingly 
4686             dbg('field str: "%s"' % fstr) 
4688             newtext = text[:start] + fstr + text[end:] 
4689             if erased in ('-', '(') and self._signOk: 
4690                 newtext = erased + newtext[1:] 
4691             dbg('newtext: "%s"' % newtext) 
4693             if self._signOk and field._index == 0: 
4694                 start -= 1             # account for sign position 
4696 ##            dbg('field._moveOnFieldFull?', field._moveOnFieldFull) 
4697 ##            dbg('len(fstr.lstrip()) == end-start?', len(fstr.lstrip()) == end-start) 
4698             if( field._moveOnFieldFull and pos == end 
4699                 and len(fstr.lstrip()) == end-start):   # if field now full 
4700                 newpos = self._findNextEntry(end)       #   go to next field 
4702                 newpos = pos                            # else keep cursor at current position 
4707                 dbg('newpos:', newpos) 
4708             if self._signOk and self._useParens: 
4709                 old_right_signpos = text.find(')') 
4711             if field._allowInsert and not field._insertRight and sel_to <= end and sel_start >= start: 
4712                 # inserting within a left-insert-capable field 
4713                 field_len = end - start 
4714                 before = text[start:sel_start] 
4715                 after = text[sel_to:end].strip() 
4716 ##                dbg("current field:'%s'" % text[start:end]) 
4717 ##                dbg("before:'%s'" % before, "after:'%s'" % after) 
4718                 new_len = len(before) + len(after) + 1 # (for inserted char) 
4719 ##                dbg('new_len:', new_len) 
4721                 if new_len < field_len: 
4722                     retained = after + self._template[end-(field_len-new_len):end] 
4723                 elif new_len > end-start: 
4724                     retained = after[1:] 
4728                 left = text[0:start] + before 
4729 ##                dbg("left:'%s'" % left, "retained:'%s'" % retained) 
4730                 right   = retained + text[end:] 
4733                 right   = text[pos+1:] 
4735             newtext = left + char + right 
4737             if self._signOk and self._useParens: 
4738                 # Balance parentheses: 
4739                 left_signpos = newtext.find('(') 
4741                 if left_signpos == -1:     # erased '('; remove ')' 
4742                     right_signpos = newtext.find(')') 
4743                     if right_signpos != -1: 
4744                         newtext = newtext[:right_signpos] + ' ' + newtext[right_signpos+1:] 
4746                 elif old_right_signpos != -1: 
4747                     right_signpos = newtext.find(')') 
4749                     if right_signpos == -1: # just replaced right-paren 
4750                         if newtext[pos] == ' ': # we just erased '); erase '(' 
4751                             newtext = newtext[:left_signpos] + ' ' + newtext[left_signpos+1:] 
4752                         else:   # replaced with digit; move ') over 
4753                             if self._ctrl_constraints._alignRight or self._isFloat: 
4754                                 newtext = newtext[:-1] + ')' 
4756                                 rstripped_text = newtext.rstrip() 
4757                                 right_signpos = len(rstripped_text) 
4758                                 dbg('old_right_signpos:', old_right_signpos, 'right signpos now:', right_signpos) 
4759                                 newtext = newtext[:right_signpos] + ')' + newtext[right_signpos+1:] 
4761             if( field._insertRight                                  # if insert-right field (but we didn't start at right edge) 
4762                 and field._moveOnFieldFull                          # and should move cursor when full 
4763                 and len(newtext[start:end].strip()) == end-start):  # and field now full 
4764                 newpos = self._findNextEntry(end)                   #   go to next field 
4765                 dbg('newpos = nextentry =', newpos) 
4767                 dbg('pos:', pos, 'newpos:', pos+1) 
4772             new_select_to = newpos     # (default return values) 
4776             if field._autoSelect: 
4777                 match_index, partial_match = self._autoComplete(1,  # (always forward) 
4778                                                                 field._compareChoices, 
4780                                                                 compareNoCase=field._compareNoCase, 
4781                                                                 current_index = field._autoCompleteIndex-1) 
4782                 if match_index is not None and partial_match: 
4783                     matched_str = newtext[start:end] 
4784                     newtext = newtext[:start] + field._choices[match_index] + newtext[end:] 
4787                     if field._insertRight: 
4788                         # adjust position to just after partial match in field 
4789                         newpos = end - (len(field._choices[match_index].strip()) - len(matched_str.strip())) 
4791             elif self._ctrl_constraints._autoSelect: 
4792                 match_index, partial_match = self._autoComplete( 
4793                                         1,  # (always forward) 
4794                                         self._ctrl_constraints._compareChoices, 
4796                                         self._ctrl_constraints._compareNoCase, 
4797                                         current_index = self._ctrl_constraints._autoCompleteIndex - 1) 
4798                 if match_index is not None and partial_match: 
4799                     matched_str = newtext 
4800                     newtext = self._ctrl_constraints._choices[match_index] 
4801                     new_select_to = self._ctrl_constraints._extent[1] 
4802                     match_field = self._ctrl_constraints 
4803                     if self._ctrl_constraints._insertRight: 
4804                         # adjust position to just after partial match in control: 
4805                         newpos = self._masklength - (len(self._ctrl_constraints._choices[match_index].strip()) - len(matched_str.strip())) 
4807             dbg('newtext: "%s"' % newtext, 'newpos:', newpos, 'new_select_to:', new_select_to) 
4809             return newtext, newpos, new_select_to, match_field, match_index 
4811             dbg('newtext: "%s"' % newtext, 'newpos:', newpos) 
4813             return newtext, newpos 
4816     def _OnFocus(self,event): 
4818         This event handler is currently necessary to work around new default 
4819         behavior as of wxPython2.3.3; 
4820         The TAB key auto selects the entire contents of the wxTextCtrl *after* 
4821         the EVT_SET_FOCUS event occurs; therefore we can't query/adjust the selection 
4822         *here*, because it hasn't happened yet.  So to prevent this behavior, and 
4823         preserve the correct selection when the focus event is not due to tab, 
4824         we need to pull the following trick: 
4826         dbg('MaskedEditMixin::_OnFocus') 
4827         wx.CallAfter(self._fixSelection) 
4832     def _CheckValid(self, candidate=None): 
4834         This is the default validation checking routine; It verifies that the 
4835         current value of the control is a "valid value," and has the side 
4836         effect of coloring the control appropriately. 
4839         dbg('MaskedEditMixin::_CheckValid: candidate="%s"' % candidate, indent=1) 
4840         oldValid = self._valid 
4841         if candidate is None: value = self._GetValue() 
4842         else: value = candidate 
4843         dbg('value: "%s"' % value) 
4845         valid = True    # assume True 
4847         if not self.IsDefault(value) and self._isDate:                    ## Date type validation 
4848             valid = self._validateDate(value) 
4849             dbg("valid date?", valid) 
4851         elif not self.IsDefault(value) and self._isTime: 
4852             valid = self._validateTime(value) 
4853             dbg("valid time?", valid) 
4855         elif not self.IsDefault(value) and (self._isInt or self._isFloat):  ## Numeric type 
4856             valid = self._validateNumeric(value) 
4857             dbg("valid Number?", valid) 
4859         if valid:   # and not self.IsDefault(value):    ## generic validation accounts for IsDefault() 
4860             ## valid so far; ensure also allowed by any list or regex provided: 
4861             valid = self._validateGeneric(value) 
4862             dbg("valid value?", valid) 
4864         dbg('valid?', valid) 
4868             self._applyFormatting() 
4869             if self._valid != oldValid: 
4870                 dbg('validity changed: oldValid =',oldValid,'newvalid =', self._valid) 
4871                 dbg('oldvalue: "%s"' % oldvalue, 'newvalue: "%s"' % self._GetValue()) 
4872         dbg(indent=0, suspend=0) 
4876     def _validateGeneric(self, candidate=None): 
4877         """ Validate the current value using the provided list or Regex filter (if any). 
4879         if candidate is None: 
4880             text = self._GetValue() 
4884         valid = True    # assume True 
4885         for i in [-1] + self._field_indices:   # process global constraints first: 
4886             field = self._fields[i] 
4887             start, end = field._extent 
4888             slice = text[start:end] 
4889             valid = field.IsValid(slice) 
4896     def _validateNumeric(self, candidate=None): 
4897         """ Validate that the value is within the specified range (if specified.)""" 
4898         if candidate is None: value = self._GetValue() 
4899         else: value = candidate 
4901             groupchar = self._fields[0]._groupChar 
4903                 number = float(value.replace(groupchar, '').replace(self._decimalChar, '.').replace('(', '-').replace(')', '')) 
4905                 number = long( value.replace(groupchar, '').replace('(', '-').replace(')', '')) 
4907                     if self._fields[0]._alignRight: 
4908                         require_digit_at = self._fields[0]._extent[1]-1 
4910                         require_digit_at = self._fields[0]._extent[0] 
4911                     dbg('require_digit_at:', require_digit_at) 
4912                     dbg("value[rda]: '%s'" % value[require_digit_at]) 
4913                     if value[require_digit_at] not in list(string.digits): 
4917             dbg('number:', number) 
4918             if self._ctrl_constraints._hasRange: 
4919                 valid = self._ctrl_constraints._rangeLow <= number <= self._ctrl_constraints._rangeHigh 
4922             groupcharpos = value.rfind(groupchar) 
4923             if groupcharpos != -1:  # group char present 
4924                 dbg('groupchar found at', groupcharpos) 
4925                 if self._isFloat and groupcharpos > self._decimalpos: 
4926                     # 1st one found on right-hand side is past decimal point 
4927                     dbg('groupchar in fraction; illegal') 
4930                     integer = value[:self._decimalpos].strip() 
4932                     integer = value.strip() 
4933                 dbg("integer:'%s'" % integer) 
4934                 if integer[0] in ('-', '('): 
4935                     integer = integer[1:] 
4936                 if integer[-1] == ')': 
4937                     integer = integer[:-1] 
4939                 parts = integer.split(groupchar) 
4940                 dbg('parts:', parts) 
4941                 for i in range(len(parts)): 
4942                     if i == 0 and abs(int(parts[0])) > 999: 
4943                         dbg('group 0 too long; illegal') 
4946                     elif i > 0 and (len(parts[i]) != 3 or ' ' in parts[i]): 
4947                         dbg('group %i (%s) not right size; illegal' % (i, parts[i])) 
4951             dbg('value not a valid number') 
4956     def _validateDate(self, candidate=None): 
4957         """ Validate the current date value using the provided Regex filter. 
4958             Generally used for character types.BufferType 
4960         dbg('MaskedEditMixin::_validateDate', indent=1) 
4961         if candidate is None: value = self._GetValue() 
4962         else: value = candidate 
4963         dbg('value = "%s"' % value) 
4964         text = self._adjustDate(value, force4digit_year=True)     ## Fix the date up before validating it 
4966         valid = True   # assume True until proven otherwise 
4969             # replace fillChar in each field with space: 
4970             datestr = text[0:self._dateExtent] 
4972                 field = self._fields[i] 
4973                 start, end = field._extent 
4974                 fstr = datestr[start:end] 
4975                 fstr.replace(field._fillChar, ' ') 
4976                 datestr = datestr[:start] + fstr + datestr[end:] 
4978             year, month, day = getDateParts( datestr, self._datestyle) 
4980             dbg('self._dateExtent:', self._dateExtent) 
4981             if self._dateExtent == 11: 
4982                 month = charmonths_dict[month.lower()] 
4986             dbg('year, month, day:', year, month, day) 
4989             dbg('cannot convert string to integer parts') 
4992             dbg('cannot convert string to integer month') 
4996             # use wxDateTime to unambiguously try to parse the date: 
4997             # ### Note: because wxDateTime is *brain-dead* and expects months 0-11, 
4998             # rather than 1-12, so handle accordingly: 
5004                     dbg("trying to create date from values day=%d, month=%d, year=%d" % (day,month,year)) 
5005                     dateHandler = wx.DateTimeFromDMY(day,month,year) 
5009                     dbg('cannot convert string to valid date') 
5015                 # wxDateTime doesn't take kindly to leading/trailing spaces when parsing, 
5016                 # so we eliminate them here: 
5017                 timeStr     = text[self._dateExtent+1:].strip()         ## time portion of the string 
5019                     dbg('timeStr: "%s"' % timeStr) 
5021                         checkTime    = dateHandler.ParseTime(timeStr) 
5022                         valid = checkTime == len(timeStr) 
5026                         dbg('cannot convert string to valid time') 
5027         if valid: dbg('valid date') 
5032     def _validateTime(self, candidate=None): 
5033         """ Validate the current time value using the provided Regex filter. 
5034             Generally used for character types.BufferType 
5036         dbg('MaskedEditMixin::_validateTime', indent=1) 
5037         # wxDateTime doesn't take kindly to leading/trailing spaces when parsing, 
5038         # so we eliminate them here: 
5039         if candidate is None: value = self._GetValue().strip() 
5040         else: value = candidate.strip() 
5041         dbg('value = "%s"' % value) 
5042         valid = True   # assume True until proven otherwise 
5044         dateHandler = wx.DateTime_Today() 
5046             checkTime    = dateHandler.ParseTime(value) 
5047             dbg('checkTime:', checkTime, 'len(value)', len(value)) 
5048             valid = checkTime == len(value) 
5053             dbg('cannot convert string to valid time') 
5054         if valid: dbg('valid time') 
5059     def _OnKillFocus(self,event): 
5060         """ Handler for EVT_KILL_FOCUS event. 
5062         dbg('MaskedEditMixin::_OnKillFocus', 'isDate=',self._isDate, indent=1) 
5063         if self._mask and self._IsEditable(): 
5064             self._AdjustField(self._GetInsertionPoint()) 
5065             self._CheckValid()   ## Call valid handler 
5067         self._LostFocus()    ## Provided for subclass use 
5072     def _fixSelection(self): 
5074         This gets called after the TAB traversal selection is made, if the 
5075         focus event was due to this, but before the EVT_LEFT_* events if 
5076         the focus shift was due to a mouse event. 
5078         The trouble is that, a priori, there's no explicit notification of 
5079         why the focus event we received.  However, the whole reason we need to 
5080         do this is because the default behavior on TAB traveral in a wxTextCtrl is 
5081         now to select the entire contents of the window, something we don't want. 
5082         So we can *now* test the selection range, and if it's "the whole text" 
5083         we can assume the cause, change the insertion point to the start of 
5084         the control, and deselect. 
5086         dbg('MaskedEditMixin::_fixSelection', indent=1) 
5087         if not self._mask or not self._IsEditable(): 
5091         sel_start, sel_to = self._GetSelection() 
5092         dbg('sel_start, sel_to:', sel_start, sel_to, 'self.IsEmpty()?', self.IsEmpty()) 
5094         if( sel_start == 0 and sel_to >= len( self._mask )   #(can be greater in numeric controls because of reserved space) 
5095             and (not self._ctrl_constraints._autoSelect or self.IsEmpty() or self.IsDefault() ) ): 
5096             # This isn't normally allowed, and so assume we got here by the new 
5097             # "tab traversal" behavior, so we need to reset the selection 
5098             # and insertion point: 
5099             dbg('entire text selected; resetting selection to start of control') 
5101             field = self._FindField(self._GetInsertionPoint()) 
5102             edit_start, edit_end = field._extent 
5103             if field._selectOnFieldEntry: 
5104                 self._SetInsertionPoint(edit_start) 
5105                 self._SetSelection(edit_start, edit_end) 
5107             elif field._insertRight: 
5108                 self._SetInsertionPoint(edit_end) 
5109                 self._SetSelection(edit_end, edit_end) 
5111         elif (self._isFloat or self._isInt): 
5113             text, signpos, right_signpos = self._getAbsValue() 
5114             if text is None or text == self._template: 
5115                 integer = self._fields[0] 
5116                 edit_start, edit_end = integer._extent 
5118                 if integer._selectOnFieldEntry: 
5119                     dbg('select on field entry:') 
5120                     self._SetInsertionPoint(edit_start) 
5121                     self._SetSelection(edit_start, edit_end) 
5123                 elif integer._insertRight: 
5124                     dbg('moving insertion point to end') 
5125                     self._SetInsertionPoint(edit_end) 
5126                     self._SetSelection(edit_end, edit_end) 
5128                     dbg('numeric ctrl is empty; start at beginning after sign') 
5129                     self._SetInsertionPoint(signpos+1)   ## Move past minus sign space if signed 
5130                     self._SetSelection(signpos+1, signpos+1) 
5132         elif sel_start > self._goEnd(getPosOnly=True): 
5133             dbg('cursor beyond the end of the user input; go to end of it') 
5136             dbg('sel_start, sel_to:', sel_start, sel_to, 'self._masklength:', self._masklength) 
5140     def _Keypress(self,key): 
5141         """ Method provided to override OnChar routine. Return False to force 
5142             a skip of the 'normal' OnChar process. Called before class OnChar. 
5147     def _LostFocus(self): 
5148         """ Method provided for subclasses. _LostFocus() is called after 
5149             the class processes its EVT_KILL_FOCUS event code. 
5154     def _OnDoubleClick(self, event): 
5155         """ selects field under cursor on dclick.""" 
5156         pos = self._GetInsertionPoint() 
5157         field = self._FindField(pos) 
5158         start, end = field._extent 
5159         self._SetInsertionPoint(start) 
5160         self._SetSelection(start, end) 
5164         """ Method provided for subclasses. Called by internal EVT_TEXT 
5165             handler. Return False to override the class handler, True otherwise. 
5172         Used to override the default Cut() method in base controls, instead 
5173         copying the selection to the clipboard and then blanking the selection, 
5174         leaving only the mask in the selected area behind. 
5175         Note: _Cut (read "undercut" ;-) must be called from a Cut() override in the 
5176         derived control because the mixin functions can't override a method of 
5179         dbg("MaskedEditMixin::_Cut", indent=1) 
5180         value = self._GetValue() 
5181         dbg('current value: "%s"' % value) 
5182         sel_start, sel_to = self._GetSelection()                   ## check for a range of selected text 
5183         dbg('selected text: "%s"' % value[sel_start:sel_to].strip()) 
5184         do = wxTextDataObject() 
5185         do.SetText(value[sel_start:sel_to].strip()) 
5186         wxTheClipboard.Open() 
5187         wxTheClipboard.SetData(do) 
5188         wxTheClipboard.Close() 
5190         if sel_to - sel_start != 0: 
5195 # WS Note: overriding Copy is no longer necessary given that you 
5196 # can no longer select beyond the last non-empty char in the control. 
5198 ##    def _Copy( self ): 
5200 ##        Override the wxTextCtrl's .Copy function, with our own 
5201 ##        that does validation.  Need to strip trailing spaces. 
5203 ##        sel_start, sel_to = self._GetSelection() 
5204 ##        select_len = sel_to - sel_start 
5205 ##        textval = wxTextCtrl._GetValue(self) 
5207 ##        do = wxTextDataObject() 
5208 ##        do.SetText(textval[sel_start:sel_to].strip()) 
5209 ##        wxTheClipboard.Open() 
5210 ##        wxTheClipboard.SetData(do) 
5211 ##        wxTheClipboard.Close() 
5214     def _getClipboardContents( self ): 
5215         """ Subroutine for getting the current contents of the clipboard. 
5217         do = wxTextDataObject() 
5218         wxTheClipboard.Open() 
5219         success = wxTheClipboard.GetData(do) 
5220         wxTheClipboard.Close() 
5225             # Remove leading and trailing spaces before evaluating contents 
5226             return do.GetText().strip() 
5229     def _validatePaste(self, paste_text, sel_start, sel_to, raise_on_invalid=False): 
5231         Used by paste routine and field choice validation to see 
5232         if a given slice of paste text is legal for the area in question: 
5233         returns validity, replacement text, and extent of paste in 
5237         dbg('MaskedEditMixin::_validatePaste("%(paste_text)s", %(sel_start)d, %(sel_to)d), raise_on_invalid? %(raise_on_invalid)d' % locals(), indent=1) 
5238         select_length = sel_to - sel_start 
5239         maxlength = select_length 
5240         dbg('sel_to - sel_start:', maxlength) 
5242             maxlength = self._masklength - sel_start 
5246         dbg('maxlength:', maxlength) 
5247         length_considered = len(paste_text) 
5248         if length_considered > maxlength: 
5249             dbg('paste text will not fit into the %s:' % item, indent=0) 
5250             if raise_on_invalid: 
5251                 dbg(indent=0, suspend=0) 
5252                 if item == 'control': 
5253                     raise ValueError('"%s" will not fit into the control "%s"' % (paste_text, self.name)) 
5255                     raise ValueError('"%s" will not fit into the selection' % paste_text) 
5257                 dbg(indent=0, suspend=0) 
5258                 return False, None, None 
5260         text = self._template 
5261         dbg('length_considered:', length_considered) 
5264         replacement_text = "" 
5265         replace_to = sel_start 
5267         while valid_paste and i < length_considered and replace_to < self._masklength: 
5268             if paste_text[i:] == self._template[replace_to:length_considered]: 
5269                 # remainder of paste matches template; skip char-by-char analysis 
5270                 dbg('remainder paste_text[%d:] (%s) matches template[%d:%d]' % (i, paste_text[i:], replace_to, length_considered)) 
5271                 replacement_text += paste_text[i:] 
5272                 replace_to = i = length_considered 
5275             char = paste_text[i] 
5276             field = self._FindField(replace_to) 
5277             if not field._compareNoCase: 
5278                 if field._forceupper:   char = char.upper() 
5279                 elif field._forcelower: char = char.lower() 
5281             dbg('char:', "'"+char+"'", 'i =', i, 'replace_to =', replace_to) 
5282             dbg('self._isTemplateChar(%d)?' % replace_to, self._isTemplateChar(replace_to)) 
5283             if not self._isTemplateChar(replace_to) and self._isCharAllowed( char, replace_to, allowAutoSelect=False, ignoreInsertRight=True): 
5284                 replacement_text += char 
5285                 dbg("not template(%(replace_to)d) and charAllowed('%(char)s',%(replace_to)d)" % locals()) 
5286                 dbg("replacement_text:", '"'+replacement_text+'"') 
5289             elif( char == self._template[replace_to] 
5290                   or (self._signOk and 
5291                           ( (i == 0 and (char == '-' or (self._useParens and char == '('))) 
5292                             or (i == self._masklength - 1 and self._useParens and char == ')') ) ) ): 
5293                 replacement_text += char 
5294                 dbg("'%(char)s' == template(%(replace_to)d)" % locals()) 
5295                 dbg("replacement_text:", '"'+replacement_text+'"') 
5299                 next_entry = self._findNextEntry(replace_to, adjustInsert=False) 
5300                 if next_entry == replace_to: 
5303                     replacement_text += self._template[replace_to:next_entry] 
5304                     dbg("skipping template; next_entry =", next_entry) 
5305                     dbg("replacement_text:", '"'+replacement_text+'"') 
5306                     replace_to = next_entry  # so next_entry will be considered on next loop 
5308         if not valid_paste and raise_on_invalid: 
5309             dbg('raising exception', indent=0, suspend=0) 
5310             raise ValueError('"%s" cannot be inserted into the control "%s"' % (paste_text, self.name)) 
5312         elif i < len(paste_text): 
5314             if raise_on_invalid: 
5315                 dbg('raising exception', indent=0, suspend=0) 
5316                 raise ValueError('"%s" will not fit into the control "%s"' % (paste_text, self.name)) 
5318         dbg('valid_paste?', valid_paste) 
5320             dbg('replacement_text: "%s"' % replacement_text, 'replace to:', replace_to) 
5321         dbg(indent=0, suspend=0) 
5322         return valid_paste, replacement_text, replace_to 
5325     def _Paste( self, value=None, raise_on_invalid=False, just_return_value=False ): 
5327         Used to override the base control's .Paste() function, 
5328         with our own that does validation. 
5329         Note: _Paste must be called from a Paste() override in the 
5330         derived control because the mixin functions can't override a 
5331         method of a sibling class. 
5333         dbg('MaskedEditMixin::_Paste (value = "%s")' % value, indent=1) 
5335             paste_text = self._getClipboardContents() 
5339         if paste_text is not None: 
5340             dbg('paste text: "%s"' % paste_text) 
5341             # (conversion will raise ValueError if paste isn't legal) 
5342             sel_start, sel_to = self._GetSelection() 
5343             dbg('selection:', (sel_start, sel_to)) 
5345             # special case: handle allowInsert fields properly 
5346             field = self._FindField(sel_start) 
5347             edit_start, edit_end = field._extent 
5349             if field._allowInsert and sel_to <= edit_end and sel_start + len(paste_text) < edit_end: 
5350                 new_pos = sel_start + len(paste_text)   # store for subsequent positioning 
5351                 paste_text = paste_text + self._GetValue()[sel_to:edit_end].rstrip() 
5352                 dbg('paste within insertable field; adjusted paste_text: "%s"' % paste_text, 'end:', edit_end) 
5353                 sel_to = sel_start + len(paste_text) 
5355             # Another special case: paste won't fit, but it's a right-insert field where entire 
5356             # non-empty value is selected, and there's room if the selection is expanded leftward: 
5357             if( len(paste_text) > sel_to - sel_start 
5358                 and field._insertRight 
5359                 and sel_start > edit_start 
5360                 and sel_to >= edit_end 
5361                 and not self._GetValue()[edit_start:sel_start].strip() ): 
5362                 # text won't fit within selection, but left of selection is empty; 
5363                 # check to see if we can expand selection to accomodate the value: 
5364                 empty_space = sel_start - edit_start 
5365                 amount_needed = len(paste_text) - (sel_to - sel_start) 
5366                 if amount_needed <= empty_space: 
5367                     sel_start -= amount_needed 
5368                     dbg('expanded selection to:', (sel_start, sel_to)) 
5371             # another special case: deal with signed values properly: 
5373                 signedvalue, signpos, right_signpos = self._getSignedValue() 
5374                 paste_signpos = paste_text.find('-') 
5375                 if paste_signpos == -1: 
5376                     paste_signpos = paste_text.find('(') 
5378                 # if paste text will result in signed value: 
5379 ##                dbg('paste_signpos != -1?', paste_signpos != -1) 
5380 ##                dbg('sel_start:', sel_start, 'signpos:', signpos) 
5381 ##                dbg('field._insertRight?', field._insertRight) 
5382 ##                dbg('sel_start - len(paste_text) >= signpos?', sel_start - len(paste_text) <= signpos) 
5383                 if paste_signpos != -1 and (sel_start <= signpos 
5384                                             or (field._insertRight and sel_start - len(paste_text) <= signpos)): 
5388                 # remove "sign" from paste text, so we can auto-adjust for sign type after paste: 
5389                 paste_text = paste_text.replace('-', ' ').replace('(',' ').replace(')','') 
5390                 dbg('unsigned paste text: "%s"' % paste_text) 
5394             # another special case: deal with insert-right fields when selection is empty and 
5395             # cursor is at end of field: 
5396 ##            dbg('field._insertRight?', field._insertRight) 
5397 ##            dbg('sel_start == edit_end?', sel_start == edit_end) 
5398 ##            dbg('sel_start', sel_start, 'sel_to', sel_to) 
5399             if field._insertRight and sel_start == edit_end and sel_start == sel_to: 
5400                 sel_start -= len(paste_text) 
5403                 dbg('adjusted selection:', (sel_start, sel_to)) 
5406                 valid_paste, replacement_text, replace_to = self._validatePaste(paste_text, sel_start, sel_to, raise_on_invalid) 
5408                 dbg('exception thrown', indent=0) 
5412                 dbg('paste text not legal for the selection or portion of the control following the cursor;') 
5413                 if not wx.Validator_IsSilent(): 
5418             text = self._eraseSelection() 
5420             new_text = text[:sel_start] + replacement_text + text[replace_to:] 
5422                 new_text = string.ljust(new_text,self._masklength) 
5424                 new_text, signpos, right_signpos = self._getSignedValue(candidate=new_text) 
5427                         new_text = new_text[:signpos] + '(' + new_text[signpos+1:right_signpos] + ')' + new_text[right_signpos+1:] 
5429                         new_text = new_text[:signpos] + '-' + new_text[signpos+1:] 
5433             dbg("new_text:", '"'+new_text+'"') 
5435             if not just_return_value: 
5439                     wx.CallAfter(self._SetValue, new_text) 
5441                         new_pos = sel_start + len(replacement_text) 
5442                     wx.CallAfter(self._SetInsertionPoint, new_pos) 
5446         elif just_return_value: 
5448             return self._GetValue() 
5452         """ Provides an Undo() method in base controls. """ 
5453         dbg("MaskedEditMixin::_Undo", indent=1) 
5454         value = self._GetValue() 
5455         prev = self._prevValue 
5456         dbg('current value:  "%s"' % value) 
5457         dbg('previous value: "%s"' % prev) 
5459             dbg('no previous value', indent=0) 
5463             # Determine what to select: (relies on fixed-length strings) 
5464             # (This is a lot harder than it would first appear, because 
5465             # of mask chars that stay fixed, and so break up the "diff"...) 
5467             # Determine where they start to differ: 
5469             length = len(value)     # (both are same length in masked control) 
5471             while( value[:i] == prev[:i] ): 
5476             # handle signed values carefully, so undo from signed to unsigned or vice-versa 
5479                 text, signpos, right_signpos = self._getSignedValue(candidate=prev) 
5481                     if prev[signpos] == '(' and prev[right_signpos] == ')': 
5485                     # eliminate source of "far-end" undo difference if using balanced parens: 
5486                     value = value.replace(')', ' ') 
5487                     prev = prev.replace(')', ' ') 
5488                 elif prev[signpos] == '-': 
5493             # Determine where they stop differing in "undo" result: 
5494             sm = difflib.SequenceMatcher(None, a=value, b=prev) 
5495             i, j, k = sm.find_longest_match(sel_start, length, sel_start, length) 
5496             dbg('i,j,k = ', (i,j,k), 'value[i:i+k] = "%s"' % value[i:i+k], 'prev[j:j+k] = "%s"' % prev[j:j+k] ) 
5498             if k == 0:                              # no match found; select to end 
5501                 code_5tuples = sm.get_opcodes() 
5502                 for op, i1, i2, j1, j2 in code_5tuples: 
5503                     dbg("%7s value[%d:%d] (%s) prev[%d:%d] (%s)" % 
5504                             (op, i1, i2, value[i1:i2], j1, j2, prev[j1:j2])) 
5507                 # look backward through operations needed to produce "previous" value; 
5508                 # first change wins: 
5509                 for next_op in range(len(code_5tuples)-1, -1, -1): 
5510                     op, i1, i2, j1, j2 = code_5tuples[next_op] 
5511                     dbg('value[i1:i2]: "%s"' % value[i1:i2], 'template[i1:i2] "%s"' % self._template[i1:i2]) 
5512                     if op == 'insert' and prev[j1:j2] != self._template[j1:j2]: 
5513                         dbg('insert found: selection =>', (j1, j2)) 
5518                     elif op == 'delete' and value[i1:i2] != self._template[i1:i2]: 
5519                         field = self._FindField(i2) 
5520                         edit_start, edit_end = field._extent 
5521                         if field._insertRight and i2 == edit_end: 
5527                         dbg('delete found: selection =>', (sel_start, sel_to)) 
5530                     elif op == 'replace': 
5531                         dbg('replace found: selection =>', (j1, j2)) 
5539                     # now go forwards, looking for earlier changes: 
5540                     for next_op in range(len(code_5tuples)): 
5541                         op, i1, i2, j1, j2 = code_5tuples[next_op] 
5542                         field = self._FindField(i1) 
5545                         elif op == 'replace': 
5546                             dbg('setting sel_start to', i1) 
5549                         elif op == 'insert' and not value[i1:i2]: 
5550                             dbg('forward %s found' % op) 
5551                             if prev[j1:j2].strip(): 
5552                                 dbg('item to insert non-empty; setting sel_start to', j1) 
5555                             elif not field._insertRight: 
5556                                 dbg('setting sel_start to inserted space:', j1) 
5559                         elif op == 'delete' and field._insertRight and not value[i1:i2].lstrip(): 
5562                             # we've got what we need 
5567                     dbg('no insert,delete or replace found (!)') 
5568                     # do "left-insert"-centric processing of difference based on l.c.s.: 
5569                     if i == j and j != sel_start:         # match starts after start of selection 
5570                         sel_to = sel_start + (j-sel_start)  # select to start of match 
5572                         sel_to = j                          # (change ends at j) 
5575             # There are several situations where the calculated difference is 
5576             # not what we want to select.  If changing sign, or just adding 
5577             # group characters, we really don't want to highlight the characters 
5578             # changed, but instead leave the cursor where it is. 
5579             # Also, there a situations in which the difference can be ambiguous; 
5582             # current value:    11234 
5583             # previous value:   1111234 
5585             # Where did the cursor actually lie and which 1s were selected on the delete 
5588             # Also, difflib can "get it wrong;" Consider: 
5590             # current value:    "       128.66" 
5591             # previous value:   "       121.86" 
5593             # difflib produces the following opcodes, which are sub-optimal: 
5594             #    equal value[0:9] (       12) prev[0:9] (       12) 
5595             #   insert value[9:9] () prev[9:11] (1.) 
5596             #    equal value[9:10] (8) prev[11:12] (8) 
5597             #   delete value[10:11] (.) prev[12:12] () 
5598             #    equal value[11:12] (6) prev[12:13] (6) 
5599             #   delete value[12:13] (6) prev[13:13] () 
5601             # This should have been: 
5602             #    equal value[0:9] (       12) prev[0:9] (       12) 
5603             #  replace value[9:11] (8.6) prev[9:11] (1.8) 
5604             #    equal value[12:13] (6) prev[12:13] (6) 
5606             # But it didn't figure this out! 
5608             # To get all this right, we use the previous selection recorded to help us... 
5610             if (sel_start, sel_to) != self._prevSelection: 
5611                 dbg('calculated selection', (sel_start, sel_to), "doesn't match previous", self._prevSelection) 
5613                 prev_sel_start, prev_sel_to = self._prevSelection 
5614                 field = self._FindField(sel_start) 
5616                 if self._signOk and (self._prevValue[sel_start] in ('-', '(', ')') 
5617                                      or self._curValue[sel_start] in ('-', '(', ')')): 
5618                     # change of sign; leave cursor alone... 
5619                     sel_start, sel_to = self._prevSelection 
5621                 elif field._groupdigits and (self._curValue[sel_start:sel_to] == field._groupChar 
5622                                              or self._prevValue[sel_start:sel_to] == field._groupChar): 
5623                     # do not highlight grouping changes 
5624                     sel_start, sel_to = self._prevSelection 
5627                     calc_select_len = sel_to - sel_start 
5628                     prev_select_len = prev_sel_to - prev_sel_start 
5630                     dbg('sel_start == prev_sel_start', sel_start == prev_sel_start) 
5631                     dbg('sel_to > prev_sel_to', sel_to > prev_sel_to) 
5633                     if prev_select_len >= calc_select_len: 
5634                         # old selection was bigger; trust it: 
5635                         sel_start, sel_to = self._prevSelection 
5637                     elif( sel_to > prev_sel_to                  # calculated select past last selection 
5638                           and prev_sel_to < len(self._template) # and prev_sel_to not at end of control 
5639                           and sel_to == len(self._template) ):  # and calculated selection goes to end of control 
5641                         i, j, k = sm.find_longest_match(prev_sel_to, length, prev_sel_to, length) 
5642                         dbg('i,j,k = ', (i,j,k), 'value[i:i+k] = "%s"' % value[i:i+k], 'prev[j:j+k] = "%s"' % prev[j:j+k] ) 
5644                             # difflib must not have optimized opcodes properly; 
5648                         # look for possible ambiguous diff: 
5650                         # if last change resulted in no selection, test from resulting cursor position: 
5651                         if prev_sel_start == prev_sel_to: 
5652                             calc_select_len = sel_to - sel_start 
5653                             field = self._FindField(prev_sel_start) 
5655                             # determine which way to search from last cursor position for ambiguous change: 
5656                             if field._insertRight: 
5657                                 test_sel_start = prev_sel_start 
5658                                 test_sel_to = prev_sel_start + calc_select_len 
5660                                 test_sel_start = prev_sel_start - calc_select_len 
5661                                 test_sel_to = prev_sel_start 
5663                             test_sel_start, test_sel_to = prev_sel_start, prev_sel_to 
5665                         dbg('test selection:', (test_sel_start, test_sel_to)) 
5666                         dbg('calc change: "%s"' % self._prevValue[sel_start:sel_to]) 
5667                         dbg('test change: "%s"' % self._prevValue[test_sel_start:test_sel_to]) 
5669                         # if calculated selection spans characters, and same characters 
5670                         # "before" the previous insertion point are present there as well, 
5671                         # select the ones related to the last known selection instead. 
5672                         if( sel_start != sel_to 
5673                             and test_sel_to < len(self._template) 
5674                             and self._prevValue[test_sel_start:test_sel_to] == self._prevValue[sel_start:sel_to] ): 
5676                             sel_start, sel_to = test_sel_start, test_sel_to 
5678             dbg('sel_start, sel_to:', sel_start, sel_to) 
5679             dbg('previous value: "%s"' % self._prevValue) 
5680             self._SetValue(self._prevValue) 
5681             self._SetInsertionPoint(sel_start) 
5682             self._SetSelection(sel_start, sel_to) 
5684             dbg('no difference between previous value') 
5688     def _OnClear(self, event): 
5689         """ Provides an action for context menu delete operation """ 
5693     def _OnContextMenu(self, event): 
5694         dbg('MaskedEditMixin::OnContextMenu()', indent=1) 
5696         menu.Append(wxID_UNDO, "Undo", "") 
5697         menu.AppendSeparator() 
5698         menu.Append(wxID_CUT, "Cut", "") 
5699         menu.Append(wxID_COPY, "Copy", "") 
5700         menu.Append(wxID_PASTE, "Paste", "") 
5701         menu.Append(wxID_CLEAR, "Delete", "") 
5702         menu.AppendSeparator() 
5703         menu.Append(wxID_SELECTALL, "Select All", "") 
5705         EVT_MENU(menu, wxID_UNDO, self._OnCtrl_Z) 
5706         EVT_MENU(menu, wxID_CUT, self._OnCtrl_X) 
5707         EVT_MENU(menu, wxID_COPY, self._OnCtrl_C) 
5708         EVT_MENU(menu, wxID_PASTE, self._OnCtrl_V) 
5709         EVT_MENU(menu, wxID_CLEAR, self._OnClear) 
5710         EVT_MENU(menu, wxID_SELECTALL, self._OnCtrl_A) 
5712         # ## WSS: The base control apparently handles 
5713         # enable/disable of wID_CUT, wxID_COPY, wxID_PASTE 
5714         # and wxID_CLEAR menu items even if the menu is one 
5715         # we created.  However, it doesn't do undo properly, 
5716         # so we're keeping track of previous values ourselves. 
5717         # Therefore, we have to override the default update for 
5718         # that item on the menu: 
5719         EVT_UPDATE_UI(self, wxID_UNDO, self._UndoUpdateUI) 
5720         self._contextMenu = menu 
5722         self.PopupMenu(menu, event.GetPosition()) 
5724         self._contextMenu = None 
5727     def _UndoUpdateUI(self, event): 
5728         if self._prevValue is None or self._prevValue == self._curValue: 
5729             self._contextMenu.Enable(wxID_UNDO, False) 
5731             self._contextMenu.Enable(wxID_UNDO, True) 
5734 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
5736 class MaskedTextCtrl( wx.TextCtrl, MaskedEditMixin ): 
5738     This is the primary derivation from MaskedEditMixin.  It provides 
5739     a general masked text control that can be configured with different 
5743     def __init__( self, parent, id=-1, value = '', 
5744                   pos = wx.DefaultPosition, 
5745                   size = wx.DefaultSize, 
5746                   style = wx.TE_PROCESS_TAB, 
5747                   validator=wx.DefaultValidator,     ## placeholder provided for data-transfer logic 
5748                   name = 'maskedTextCtrl', 
5749                   setupEventHandling = True,        ## setup event handling by default 
5752         wx.TextCtrl.__init__(self, parent, id, value='', 
5753                             pos=pos, size = size, 
5754                             style=style, validator=validator, 
5757         self.controlInitialized = True 
5758         MaskedEditMixin.__init__( self, name, **kwargs ) 
5759         self._SetInitialValue(value) 
5761         if setupEventHandling: 
5762             ## Setup event handlers 
5763             self.Bind(wx.EVT_SET_FOCUS, self._OnFocus )         ## defeat automatic full selection 
5764             self.Bind(wx.EVT_KILL_FOCUS, self._OnKillFocus )    ## run internal validator 
5765             self.Bind(wx.EVT_LEFT_DCLICK, self._OnDoubleClick)  ## select field under cursor on dclick 
5766             self.Bind(wx.EVT_RIGHT_UP, self._OnContextMenu )    ## bring up an appropriate context menu 
5767             self.Bind(wx.EVT_KEY_DOWN, self._OnKeyDown )        ## capture control events not normally seen, eg ctrl-tab. 
5768             self.Bind(wx.EVT_CHAR, self._OnChar )               ## handle each keypress 
5769             self.Bind(wx.EVT_TEXT, self._OnTextChange )         ## color control appropriately & keep 
5770                                                                 ## track of previous value for undo 
5774         return "<MaskedTextCtrl: %s>" % self.GetValue() 
5777     def _GetSelection(self): 
5779         Allow mixin to get the text selection of this control. 
5780         REQUIRED by any class derived from MaskedEditMixin. 
5782         return self.GetSelection() 
5784     def _SetSelection(self, sel_start, sel_to): 
5786         Allow mixin to set the text selection of this control. 
5787         REQUIRED by any class derived from MaskedEditMixin. 
5789 ##        dbg("MaskedTextCtrl::_SetSelection(%(sel_start)d, %(sel_to)d)" % locals()) 
5790         return self.SetSelection( sel_start, sel_to ) 
5792     def SetSelection(self, sel_start, sel_to): 
5794         This is just for debugging... 
5796         dbg("MaskedTextCtrl::SetSelection(%(sel_start)d, %(sel_to)d)" % locals()) 
5797         wx.TextCtrl.SetSelection(self, sel_start, sel_to) 
5800     def _GetInsertionPoint(self): 
5801         return self.GetInsertionPoint() 
5803     def _SetInsertionPoint(self, pos): 
5804 ##        dbg("MaskedTextCtrl::_SetInsertionPoint(%(pos)d)" % locals()) 
5805         self.SetInsertionPoint(pos) 
5807     def SetInsertionPoint(self, pos): 
5809         This is just for debugging... 
5811         dbg("MaskedTextCtrl::SetInsertionPoint(%(pos)d)" % locals()) 
5812         wx.TextCtrl.SetInsertionPoint(self, pos) 
5815     def _GetValue(self): 
5817         Allow mixin to get the raw value of the control with this function. 
5818         REQUIRED by any class derived from MaskedEditMixin. 
5820         return self.GetValue() 
5822     def _SetValue(self, value): 
5824         Allow mixin to set the raw value of the control with this function. 
5825         REQUIRED by any class derived from MaskedEditMixin. 
5827         dbg('MaskedTextCtrl::_SetValue("%(value)s")' % locals(), indent=1) 
5828         # Record current selection and insertion point, for undo 
5829         self._prevSelection = self._GetSelection() 
5830         self._prevInsertionPoint = self._GetInsertionPoint() 
5831         wx.TextCtrl.SetValue(self, value) 
5834     def SetValue(self, value): 
5836         This function redefines the externally accessible .SetValue to be 
5837         a smart "paste" of the text in question, so as not to corrupt the 
5838         masked control.  NOTE: this must be done in the class derived 
5839         from the base wx control. 
5841         dbg('MaskedTextCtrl::SetValue = "%s"' % value, indent=1) 
5844             wx.TextCtrl.SetValue(self, value)    # revert to base control behavior 
5847         # empty previous contents, replacing entire value: 
5848         self._SetInsertionPoint(0) 
5849         self._SetSelection(0, self._masklength) 
5850         if self._signOk and self._useParens: 
5851             signpos = value.find('-') 
5853                 value = value[:signpos] + '(' + value[signpos+1:].strip() + ')' 
5854             elif value.find(')') == -1 and len(value) < self._masklength: 
5855                 value += ' '    # add place holder for reserved space for right paren 
5857         if( len(value) < self._masklength                # value shorter than control 
5858             and (self._isFloat or self._isInt)            # and it's a numeric control 
5859             and self._ctrl_constraints._alignRight ):   # and it's a right-aligned control 
5861             dbg('len(value)', len(value), ' < self._masklength', self._masklength) 
5862             # try to intelligently "pad out" the value to the right size: 
5863             value = self._template[0:self._masklength - len(value)] + value 
5864             if self._isFloat and value.find('.') == -1: 
5866             dbg('padded value = "%s"' % value) 
5868         # make SetValue behave the same as if you had typed the value in: 
5870             value = self._Paste(value, raise_on_invalid=True, just_return_value=True) 
5872                 self._isNeg = False     # (clear current assumptions) 
5873                 value = self._adjustFloat(value) 
5875                 self._isNeg = False     # (clear current assumptions) 
5876                 value = self._adjustInt(value) 
5877             elif self._isDate and not self.IsValid(value) and self._4digityear: 
5878                 value = self._adjustDate(value, fixcentury=True) 
5880             # If date, year might be 2 digits vs. 4; try adjusting it: 
5881             if self._isDate and self._4digityear: 
5882                 dateparts = value.split(' ') 
5883                 dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True) 
5884                 value = string.join(dateparts, ' ') 
5885                 dbg('adjusted value: "%s"' % value) 
5886                 value = self._Paste(value, raise_on_invalid=True, just_return_value=True) 
5888                 dbg('exception thrown', indent=0) 
5891         self._SetValue(value) 
5892 ##        dbg('queuing insertion after .SetValue', self._masklength) 
5893         wx.CallAfter(self._SetInsertionPoint, self._masklength) 
5894         wx.CallAfter(self._SetSelection, self._masklength, self._masklength) 
5899         """ Blanks the current control value by replacing it with the default value.""" 
5900         dbg("MaskedTextCtrl::Clear - value reset to default value (template)") 
5904             wx.TextCtrl.Clear(self)    # else revert to base control behavior 
5909         Allow mixin to refresh the base control with this function. 
5910         REQUIRED by any class derived from MaskedEditMixin. 
5912         dbg('MaskedTextCtrl::_Refresh', indent=1) 
5913         wx.TextCtrl.Refresh(self) 
5919         This function redefines the externally accessible .Refresh() to 
5920         validate the contents of the masked control as it refreshes. 
5921         NOTE: this must be done in the class derived from the base wx control. 
5923         dbg('MaskedTextCtrl::Refresh', indent=1) 
5929     def _IsEditable(self): 
5931         Allow mixin to determine if the base control is editable with this function. 
5932         REQUIRED by any class derived from MaskedEditMixin. 
5934         return wx.TextCtrl.IsEditable(self) 
5939         This function redefines the externally accessible .Cut to be 
5940         a smart "erase" of the text in question, so as not to corrupt the 
5941         masked control.  NOTE: this must be done in the class derived 
5942         from the base wx control. 
5945             self._Cut()             # call the mixin's Cut method 
5947             wx.TextCtrl.Cut(self)    # else revert to base control behavior 
5952         This function redefines the externally accessible .Paste to be 
5953         a smart "paste" of the text in question, so as not to corrupt the 
5954         masked control.  NOTE: this must be done in the class derived 
5955         from the base wx control. 
5958             self._Paste()                   # call the mixin's Paste method 
5960             wx.TextCtrl.Paste(self, value)   # else revert to base control behavior 
5965         This function defines the undo operation for the control. (The default 
5971             wx.TextCtrl.Undo(self)   # else revert to base control behavior 
5974     def IsModified(self): 
5976         This function overrides the raw wxTextCtrl method, because the 
5977         masked edit mixin uses SetValue to change the value, which doesn't 
5978         modify the state of this attribute.  So, we keep track on each 
5979         keystroke to see if the value changes, and if so, it's been 
5982         return wx.TextCtrl.IsModified(self) or self.modified 
5985     def _CalcSize(self, size=None): 
5987         Calculate automatic size if allowed; use base mixin function. 
5989         return self._calcSize(size) 
5992 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
5993 ## Because calling SetSelection programmatically does not fire EVT_COMBOBOX 
5994 ## events, we have to do it ourselves when we auto-complete. 
5995 class MaskedComboBoxSelectEvent(wx.PyCommandEvent): 
5996     def __init__(self, id, selection = 0, object=None): 
5997         wx.PyCommandEvent.__init__(self, wx.wxEVT_COMMAND_COMBOBOX_SELECTED, id) 
5999         self.__selection = selection 
6000         self.SetEventObject(object) 
6002     def GetSelection(self): 
6003         """Retrieve the value of the control at the time 
6004         this event was generated.""" 
6005         return self.__selection 
6008 class MaskedComboBox( wx.ComboBox, MaskedEditMixin ): 
6010     This masked edit control adds the ability to use a masked input 
6011     on a combobox, and do auto-complete of such values. 
6013     def __init__( self, parent, id=-1, value = '', 
6014                   pos = wx.DefaultPosition, 
6015                   size = wx.DefaultSize, 
6017                   style = wx.CB_DROPDOWN, 
6018                   validator = wx.DefaultValidator, 
6019                   name = "maskedComboBox", 
6020                   setupEventHandling = True,        ## setup event handling by default): 
6024         # This is necessary, because wxComboBox currently provides no 
6025         # method for determining later if this was specified in the 
6026         # constructor for the control... 
6027         self.__readonly = style & wx.CB_READONLY == wx.CB_READONLY 
6029         kwargs['choices'] = choices                 ## set up maskededit to work with choice list too 
6031         ## Since combobox completion is case-insensitive, always validate same way 
6032         if not kwargs.has_key('compareNoCase'): 
6033             kwargs['compareNoCase'] = True 
6035         MaskedEditMixin.__init__( self, name, **kwargs ) 
6036         self._choices = self._ctrl_constraints._choices 
6037         dbg('self._choices:', self._choices) 
6039         if self._ctrl_constraints._alignRight: 
6040             choices = [choice.rjust(self._masklength) for choice in choices] 
6042             choices = [choice.ljust(self._masklength) for choice in choices] 
6044         wx.ComboBox.__init__(self, parent, id, value='', 
6045                             pos=pos, size = size, 
6046                             choices=choices, style=style|wx.WANTS_CHARS, 
6047                             validator=validator, 
6050         self.controlInitialized = True 
6052         # Set control font - fixed width by default 
6056             self.SetClientSize(self._CalcSize()) 
6059             # ensure value is width of the mask of the control: 
6060             if self._ctrl_constraints._alignRight: 
6061                 value = value.rjust(self._masklength) 
6063                 value = value.ljust(self._masklength) 
6066             self.SetStringSelection(value) 
6068             self._SetInitialValue(value) 
6071         self._SetKeycodeHandler(wx.WXK_UP, self.OnSelectChoice) 
6072         self._SetKeycodeHandler(wx.WXK_DOWN, self.OnSelectChoice) 
6074         if setupEventHandling: 
6075             ## Setup event handlers 
6076             self.Bind(wx.EVT_SET_FOCUS, self._OnFocus )         ## defeat automatic full selection 
6077             self.Bind(wx.EVT_KILL_FOCUS, self._OnKillFocus )    ## run internal validator 
6078             self.Bind(wx.EVT_LEFT_DCLICK, self._OnDoubleClick)  ## select field under cursor on dclick 
6079             self.Bind(wx.EVT_RIGHT_UP, self._OnContextMenu )    ## bring up an appropriate context menu 
6080             self.Bind(wx.EVT_CHAR, self._OnChar )               ## handle each keypress 
6081             self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown )         ## for special processing of up/down keys 
6082             self.Bind(wx.EVT_KEY_DOWN, self._OnKeyDown )        ## for processing the rest of the control keys 
6083                                                                 ## (next in evt chain) 
6084             self.Bind(wx.EVT_TEXT, self._OnTextChange )         ## color control appropriately & keep 
6085                                                                 ## track of previous value for undo 
6090         return "<MaskedComboBox: %s>" % self.GetValue() 
6093     def _CalcSize(self, size=None): 
6095         Calculate automatic size if allowed; augment base mixin function 
6096         to account for the selector button. 
6098         size = self._calcSize(size) 
6099         return (size[0]+20, size[1]) 
6102     def _GetSelection(self): 
6104         Allow mixin to get the text selection of this control. 
6105         REQUIRED by any class derived from MaskedEditMixin. 
6107         return self.GetMark() 
6109     def _SetSelection(self, sel_start, sel_to): 
6111         Allow mixin to set the text selection of this control. 
6112         REQUIRED by any class derived from MaskedEditMixin. 
6114         return self.SetMark( sel_start, sel_to ) 
6117     def _GetInsertionPoint(self): 
6118         return self.GetInsertionPoint() 
6120     def _SetInsertionPoint(self, pos): 
6121         self.SetInsertionPoint(pos) 
6124     def _GetValue(self): 
6126         Allow mixin to get the raw value of the control with this function. 
6127         REQUIRED by any class derived from MaskedEditMixin. 
6129         return self.GetValue() 
6131     def _SetValue(self, value): 
6133         Allow mixin to set the raw value of the control with this function. 
6134         REQUIRED by any class derived from MaskedEditMixin. 
6136         # For wxComboBox, ensure that values are properly padded so that 
6137         # if varying length choices are supplied, they always show up 
6138         # in the window properly, and will be the appropriate length 
6139         # to match the mask: 
6140         if self._ctrl_constraints._alignRight: 
6141             value = value.rjust(self._masklength) 
6143             value = value.ljust(self._masklength) 
6145         # Record current selection and insertion point, for undo 
6146         self._prevSelection = self._GetSelection() 
6147         self._prevInsertionPoint = self._GetInsertionPoint() 
6148         wx.ComboBox.SetValue(self, value) 
6149         # text change events don't always fire, so we check validity here 
6150         # to make certain formatting is applied: 
6153     def SetValue(self, value): 
6155         This function redefines the externally accessible .SetValue to be 
6156         a smart "paste" of the text in question, so as not to corrupt the 
6157         masked control.  NOTE: this must be done in the class derived 
6158         from the base wx control. 
6161             wx.ComboBox.SetValue(value)   # revert to base control behavior 
6164         # empty previous contents, replacing entire value: 
6165         self._SetInsertionPoint(0) 
6166         self._SetSelection(0, self._masklength) 
6168         if( len(value) < self._masklength                # value shorter than control 
6169             and (self._isFloat or self._isInt)            # and it's a numeric control 
6170             and self._ctrl_constraints._alignRight ):   # and it's a right-aligned control 
6171             # try to intelligently "pad out" the value to the right size: 
6172             value = self._template[0:self._masklength - len(value)] + value 
6173             dbg('padded value = "%s"' % value) 
6175         # For wxComboBox, ensure that values are properly padded so that 
6176         # if varying length choices are supplied, they always show up 
6177         # in the window properly, and will be the appropriate length 
6178         # to match the mask: 
6179         elif self._ctrl_constraints._alignRight: 
6180             value = value.rjust(self._masklength) 
6182             value = value.ljust(self._masklength) 
6185         # make SetValue behave the same as if you had typed the value in: 
6187             value = self._Paste(value, raise_on_invalid=True, just_return_value=True) 
6189                 self._isNeg = False     # (clear current assumptions) 
6190                 value = self._adjustFloat(value) 
6192                 self._isNeg = False     # (clear current assumptions) 
6193                 value = self._adjustInt(value) 
6194             elif self._isDate and not self.IsValid(value) and self._4digityear: 
6195                 value = self._adjustDate(value, fixcentury=True) 
6197             # If date, year might be 2 digits vs. 4; try adjusting it: 
6198             if self._isDate and self._4digityear: 
6199                 dateparts = value.split(' ') 
6200                 dateparts[0] = self._adjustDate(dateparts[0], fixcentury=True) 
6201                 value = string.join(dateparts, ' ') 
6202                 dbg('adjusted value: "%s"' % value) 
6203                 value = self._Paste(value, raise_on_invalid=True, just_return_value=True) 
6207         self._SetValue(value) 
6208 ##        dbg('queuing insertion after .SetValue', self._masklength) 
6209         wx.CallAfter(self._SetInsertionPoint, self._masklength) 
6210         wx.CallAfter(self._SetSelection, self._masklength, self._masklength) 
6215         Allow mixin to refresh the base control with this function. 
6216         REQUIRED by any class derived from MaskedEditMixin. 
6218         wx.ComboBox.Refresh(self) 
6222         This function redefines the externally accessible .Refresh() to 
6223         validate the contents of the masked control as it refreshes. 
6224         NOTE: this must be done in the class derived from the base wx control. 
6230     def _IsEditable(self): 
6232         Allow mixin to determine if the base control is editable with this function. 
6233         REQUIRED by any class derived from MaskedEditMixin. 
6235         return not self.__readonly 
6240         This function redefines the externally accessible .Cut to be 
6241         a smart "erase" of the text in question, so as not to corrupt the 
6242         masked control.  NOTE: this must be done in the class derived 
6243         from the base wx control. 
6246             self._Cut()             # call the mixin's Cut method 
6248             wx.ComboBox.Cut(self)    # else revert to base control behavior 
6253         This function redefines the externally accessible .Paste to be 
6254         a smart "paste" of the text in question, so as not to corrupt the 
6255         masked control.  NOTE: this must be done in the class derived 
6256         from the base wx control. 
6259             self._Paste()           # call the mixin's Paste method 
6261             wx.ComboBox.Paste(self)  # else revert to base control behavior 
6266         This function defines the undo operation for the control. (The default 
6272             wx.ComboBox.Undo()       # else revert to base control behavior 
6275     def Append( self, choice, clientData=None ): 
6277         This function override is necessary so we can keep track of any additions to the list 
6278         of choices, because wxComboBox doesn't have an accessor for the choice list. 
6279         The code here is the same as in the SetParameters() mixin function, but is 
6280         done for the individual value as appended, so the list can be built incrementally 
6281         without speed penalty. 
6284             if type(choice) not in (types.StringType, types.UnicodeType): 
6285                 raise TypeError('%s: choices must be a sequence of strings' % str(self._index)) 
6286             elif not self.IsValid(choice): 
6287                 raise ValueError('%s: "%s" is not a valid value for the control as specified.' % (str(self._index), choice)) 
6289             if not self._ctrl_constraints._choices: 
6290                 self._ctrl_constraints._compareChoices = [] 
6291                 self._ctrl_constraints._choices = [] 
6292                 self._hasList = True 
6294             compareChoice = choice.strip() 
6296             if self._ctrl_constraints._compareNoCase: 
6297                 compareChoice = compareChoice.lower() 
6299             if self._ctrl_constraints._alignRight: 
6300                 choice = choice.rjust(self._masklength) 
6302                 choice = choice.ljust(self._masklength) 
6303             if self._ctrl_constraints._fillChar != ' ': 
6304                 choice = choice.replace(' ', self._fillChar) 
6305             dbg('updated choice:', choice) 
6308             self._ctrl_constraints._compareChoices.append(compareChoice) 
6309             self._ctrl_constraints._choices.append(choice) 
6310             self._choices = self._ctrl_constraints._choices     # (for shorthand) 
6312             if( not self.IsValid(choice) and 
6313                (not self._ctrl_constraints.IsEmpty(choice) or 
6314                 (self._ctrl_constraints.IsEmpty(choice) and self._ctrl_constraints._validRequired) ) ): 
6315                 raise ValueError('"%s" is not a valid value for the control "%s" as specified.' % (choice, self.name)) 
6317         wx.ComboBox.Append(self, choice, clientData) 
6323         This function override is necessary so we can keep track of any additions to the list 
6324         of choices, because wxComboBox doesn't have an accessor for the choice list. 
6328             self._ctrl_constraints._autoCompleteIndex = -1 
6329             if self._ctrl_constraints._choices: 
6330                 self.SetCtrlParameters(choices=[]) 
6331         wx.ComboBox.Clear(self) 
6334     def SetCtrlParameters( self, **kwargs ): 
6336         Override mixin's default SetCtrlParameters to detect changes in choice list, so 
6337         we can update the base control: 
6339         MaskedEditMixin.SetCtrlParameters(self, **kwargs ) 
6340         if( self.controlInitialized 
6341             and (kwargs.has_key('choices') or self._choices != self._ctrl_constraints._choices) ): 
6342             wx.ComboBox.Clear(self) 
6343             self._choices = self._ctrl_constraints._choices 
6344             for choice in self._choices: 
6345                 wx.ComboBox.Append( self, choice ) 
6350         This function is a hack to make up for the fact that wxComboBox has no 
6351         method for returning the selected portion of its edit control.  It 
6352         works, but has the nasty side effect of generating lots of intermediate 
6355         dbg(suspend=1)  # turn off debugging around this function 
6356         dbg('MaskedComboBox::GetMark', indent=1) 
6359             return 0, 0 # no selection possible for editing 
6360 ##        sel_start, sel_to = wxComboBox.GetMark(self)        # what I'd *like* to have! 
6361         sel_start = sel_to = self.GetInsertionPoint() 
6362         dbg("current sel_start:", sel_start) 
6363         value = self.GetValue() 
6364         dbg('value: "%s"' % value) 
6366         self._ignoreChange = True               # tell _OnTextChange() to ignore next event (if any) 
6368         wx.ComboBox.Cut(self) 
6369         newvalue = self.GetValue() 
6370         dbg("value after Cut operation:", newvalue) 
6372         if newvalue != value:                   # something was selected; calculate extent 
6373             dbg("something selected") 
6374             sel_to = sel_start + len(value) - len(newvalue) 
6375             wx.ComboBox.SetValue(self, value)    # restore original value and selection (still ignoring change) 
6376             wx.ComboBox.SetInsertionPoint(self, sel_start) 
6377             wx.ComboBox.SetMark(self, sel_start, sel_to) 
6379         self._ignoreChange = False              # tell _OnTextChange() to pay attn again 
6381         dbg('computed selection:', sel_start, sel_to, indent=0, suspend=0) 
6382         return sel_start, sel_to 
6385     def SetSelection(self, index): 
6387         Necessary for bookkeeping on choice selection, to keep current value 
6390         dbg('MaskedComboBox::SetSelection(%d)' % index) 
6392             self._prevValue = self._curValue 
6393             self._curValue = self._choices[index] 
6394             self._ctrl_constraints._autoCompleteIndex = index 
6395         wx.ComboBox.SetSelection(self, index) 
6398     def OnKeyDown(self, event): 
6400         This function is necessary because navigation and control key 
6401         events do not seem to normally be seen by the wxComboBox's 
6402         EVT_CHAR routine.  (Tabs don't seem to be visible no matter 
6405         if event.GetKeyCode() in self._nav + self._control: 
6409             event.Skip()    # let mixin default KeyDown behavior occur 
6412     def OnSelectChoice(self, event): 
6414         This function appears to be necessary, because the processing done 
6415         on the text of the control somehow interferes with the combobox's 
6416         selection mechanism for the arrow keys. 
6418         dbg('MaskedComboBox::OnSelectChoice', indent=1) 
6424         value = self.GetValue().strip() 
6426         if self._ctrl_constraints._compareNoCase: 
6427             value = value.lower() 
6429         if event.GetKeyCode() == wx.WXK_UP: 
6433         match_index, partial_match = self._autoComplete( 
6435                                                 self._ctrl_constraints._compareChoices, 
6437                                                 self._ctrl_constraints._compareNoCase, 
6438                                                 current_index = self._ctrl_constraints._autoCompleteIndex) 
6439         if match_index is not None: 
6440             dbg('setting selection to', match_index) 
6441             # issue appropriate event to outside: 
6442             self._OnAutoSelect(self._ctrl_constraints, match_index=match_index) 
6444             keep_processing = False 
6446             pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode()) 
6447             field = self._FindField(pos) 
6448             if self.IsEmpty() or not field._hasList: 
6449                 dbg('selecting 1st value in list') 
6450                 self._OnAutoSelect(self._ctrl_constraints, match_index=0) 
6452                 keep_processing = False 
6454                 # attempt field-level auto-complete 
6456                 keep_processing = self._OnAutoCompleteField(event) 
6457         dbg('keep processing?', keep_processing, indent=0) 
6458         return keep_processing 
6461     def _OnAutoSelect(self, field, match_index): 
6463         Override mixin (empty) autocomplete handler, so that autocompletion causes 
6464         combobox to update appropriately. 
6466         dbg('MaskedComboBox::OnAutoSelect', field._index, indent=1) 
6467 ##        field._autoCompleteIndex = match_index 
6468         if field == self._ctrl_constraints: 
6469             self.SetSelection(match_index) 
6470             dbg('issuing combo selection event') 
6471             self.GetEventHandler().ProcessEvent( 
6472                 MaskedComboBoxSelectEvent( self.GetId(), match_index, self ) ) 
6474         dbg('field._autoCompleteIndex:', match_index) 
6475         dbg('self.GetSelection():', self.GetSelection()) 
6479     def _OnReturn(self, event): 
6481         For wxComboBox, it seems that if you hit return when the dropdown is 
6482         dropped, the event that dismisses the dropdown will also blank the 
6483         control, because of the implementation of wxComboBox.  So here, 
6484         we look and if the selection is -1, and the value according to 
6485         (the base control!) is a value in the list, then we schedule a 
6486         programmatic wxComboBox.SetSelection() call to pick the appropriate 
6487         item in the list. (and then do the usual OnReturn bit.) 
6489         dbg('MaskedComboBox::OnReturn', indent=1) 
6490         dbg('current value: "%s"' % self.GetValue(), 'current index:', self.GetSelection()) 
6491         if self.GetSelection() == -1 and self.GetValue().lower().strip() in self._ctrl_constraints._compareChoices: 
6492             wx.CallAfter(self.SetSelection, self._ctrl_constraints._autoCompleteIndex) 
6494         event.m_keyCode = wx.WXK_TAB 
6499 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
6501 class IpAddrCtrl( MaskedTextCtrl ): 
6503     This class is a particular type of MaskedTextCtrl that accepts 
6504     and understands the semantics of IP addresses, reformats input 
6505     as you move from field to field, and accepts '.' as a navigation 
6506     character, so that typing an IP address can be done naturally. 
6508     def __init__( self, parent, id=-1, value = '', 
6509                   pos = wx.DefaultPosition, 
6510                   size = wx.DefaultSize, 
6511                   style = wx.TE_PROCESS_TAB, 
6512                   validator = wx.DefaultValidator, 
6513                   name = 'IpAddrCtrl', 
6514                   setupEventHandling = True,        ## setup event handling by default 
6517         if not kwargs.has_key('mask'): 
6518            kwargs['mask'] = mask = "###.###.###.###" 
6519         if not kwargs.has_key('formatcodes'): 
6520             kwargs['formatcodes'] = 'F_Sr<' 
6521         if not kwargs.has_key('validRegex'): 
6522             kwargs['validRegex'] = "(  \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))(\.(  \d| \d\d|(1\d\d|2[0-4]\d|25[0-5]))){3}" 
6525         MaskedTextCtrl.__init__( 
6526                 self, parent, id=id, value = value, 
6529                 validator = validator, 
6531                 setupEventHandling = setupEventHandling, 
6534         # set up individual field parameters as well: 
6536         field_params['validRegex'] = "(   |  \d| \d |\d  | \d\d|\d\d |\d \d|(1\d\d|2[0-4]\d|25[0-5]))" 
6538         # require "valid" string; this prevents entry of any value > 255, but allows 
6539         # intermediate constructions; overall control validation requires well-formatted value. 
6540         field_params['formatcodes'] = 'V' 
6543             for i in self._field_indices: 
6544                 self.SetFieldParameters(i, **field_params) 
6546         # This makes '.' act like tab: 
6547         self._AddNavKey('.', handler=self.OnDot) 
6548         self._AddNavKey('>', handler=self.OnDot)    # for "shift-." 
6551     def OnDot(self, event): 
6552         dbg('IpAddrCtrl::OnDot', indent=1) 
6553         pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode()) 
6554         oldvalue = self.GetValue() 
6555         edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True) 
6556         if not event.ShiftDown(): 
6557             if pos > edit_start and pos < edit_end: 
6558                 # clip data in field to the right of pos, if adjusting fields 
6559                 # when not at delimeter; (assumption == they hit '.') 
6560                 newvalue = oldvalue[:pos] + ' ' * (edit_end - pos) + oldvalue[edit_end:] 
6561                 self._SetValue(newvalue) 
6562                 self._SetInsertionPoint(pos) 
6564         return self._OnChangeField(event) 
6568     def GetAddress(self): 
6569         value = MaskedTextCtrl.GetValue(self) 
6570         return value.replace(' ','')    # remove spaces from the value 
6573     def _OnCtrl_S(self, event): 
6574         dbg("IpAddrCtrl::_OnCtrl_S") 
6576             print "value:", self.GetAddress() 
6579     def SetValue(self, value): 
6580         dbg('IpAddrCtrl::SetValue(%s)' % str(value), indent=1) 
6581         if type(value) not in (types.StringType, types.UnicodeType): 
6583             raise ValueError('%s must be a string', str(value)) 
6585         bValid = True   # assume True 
6586         parts = value.split('.') 
6592                 if not 0 <= len(part) <= 3: 
6595                 elif part.strip():  # non-empty part 
6597                         j = string.atoi(part) 
6598                         if not 0 <= j <= 255: 
6602                             parts[i] = '%3d' % j 
6607                     # allow empty sections for SetValue (will result in "invalid" value, 
6608                     # but this may be useful for initializing the control: 
6609                     parts[i] = '   '    # convert empty field to 3-char length 
6613             raise ValueError('value (%s) must be a string of form n.n.n.n where n is empty or in range 0-255' % str(value)) 
6615             dbg('parts:', parts) 
6616             value = string.join(parts, '.') 
6617             MaskedTextCtrl.SetValue(self, value) 
6621 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
6622 ## these are helper subroutines: 
6624 def movetofloat( origvalue, fmtstring, neg, addseparators=False, sepchar = ',',fillchar=' '): 
6625     """ addseparators = add separator character every three numerals if True 
6627     fmt0 = fmtstring.split('.') 
6630     val  = origvalue.split('.')[0].strip() 
6631     ret  = fillchar * (len(fmt1)-len(val)) + val + "." + "0" * len(fmt2) 
6634     return (ret,len(fmt1)) 
6637 def isDateType( fmtstring ): 
6638     """ Checks the mask and returns True if it fits an allowed 
6639         date or datetime format. 
6641     dateMasks = ("^##/##/####", 
6653     reString  = "|".join(dateMasks) 
6654     filter = re.compile( reString) 
6655     if re.match(filter,fmtstring): return True 
6658 def isTimeType( fmtstring ): 
6659     """ Checks the mask and returns True if it fits an allowed 
6662     reTimeMask = "^##:##(:##)?( (AM|PM))?" 
6663     filter = re.compile( reTimeMask ) 
6664     if re.match(filter,fmtstring): return True 
6668 def isFloatingPoint( fmtstring): 
6669     filter = re.compile("[ ]?[#]+\.[#]+\n") 
6670     if re.match(filter,fmtstring+"\n"): return True 
6674 def isInteger( fmtstring ): 
6675     filter = re.compile("[#]+\n") 
6676     if re.match(filter,fmtstring+"\n"): return True 
6680 def getDateParts( dateStr, dateFmt ): 
6681     if len(dateStr) > 11: clip = dateStr[0:11] 
6682     else:                 clip = dateStr 
6683     if clip[-2] not in string.digits: 
6684         clip = clip[:-1]    # (got part of time; drop it) 
6686     dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.') 
6687     slices  = clip.split(dateSep) 
6688     if dateFmt == "MDY": 
6689         y,m,d = (slices[2],slices[0],slices[1])  ## year, month, date parts 
6690     elif dateFmt == "DMY": 
6691         y,m,d = (slices[2],slices[1],slices[0])  ## year, month, date parts 
6692     elif dateFmt == "YMD": 
6693         y,m,d = (slices[0],slices[1],slices[2])  ## year, month, date parts 
6695         y,m,d = None, None, None 
6702 def getDateSepChar(dateStr): 
6703     clip   = dateStr[0:10] 
6704     dateSep = (('/' in clip) * '/') + (('-' in clip) * '-') + (('.' in clip) * '.') 
6708 def makeDate( year, month, day, dateFmt, dateStr): 
6709     sep    = getDateSepChar( dateStr) 
6710     if dateFmt == "MDY": 
6711         return "%s%s%s%s%s" % (month,sep,day,sep,year)  ## year, month, date parts 
6712     elif dateFmt == "DMY": 
6713         return "%s%s%s%s%s" % (day,sep,month,sep,year)  ## year, month, date parts 
6714     elif dateFmt == "YMD": 
6715         return "%s%s%s%s%s" % (year,sep,month,sep,day)  ## year, month, date parts 
6720 def getYear(dateStr,dateFmt): 
6721     parts = getDateParts( dateStr, dateFmt) 
6724 def getMonth(dateStr,dateFmt): 
6725     parts = getDateParts( dateStr, dateFmt) 
6728 def getDay(dateStr,dateFmt): 
6729     parts = getDateParts( dateStr, dateFmt) 
6732 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
6733 class test(wx.PySimpleApp): 
6735             from wx.lib.rcsizer import RowColSizer 
6736             self.frame = wx.Frame( None, -1, "MaskedEditMixin 0.0.7 Demo Page #1", size = (700,600)) 
6737             self.panel = wx.Panel( self.frame, -1) 
6738             self.sizer = RowColSizer() 
6743             id, id1 = wx.NewId(), wx.NewId() 
6744             self.command1  = wx.Button( self.panel, id, "&Close" ) 
6745             self.command2  = wx.Button( self.panel, id1, "&AutoFormats" ) 
6746             self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5) 
6747             self.sizer.Add(self.command2, row=0, col=1, colspan=2, flag=wx.ALL, border = 5) 
6748             self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1 ) 
6749 ##            self.panel.SetDefaultItem(self.command1 ) 
6750             self.panel.Bind(wx.EVT_BUTTON, self.onClickPage, self.command2) 
6752             self.check1 = wx.CheckBox( self.panel, -1, "Disallow Empty" ) 
6753             self.check2 = wx.CheckBox( self.panel, -1, "Highlight Empty" ) 
6754             self.sizer.Add( self.check1, row=0,col=3, flag=wx.ALL,border=5 ) 
6755             self.sizer.Add( self.check2, row=0,col=4, flag=wx.ALL,border=5 ) 
6756             self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck1, self.check1 ) 
6757             self.panel.Bind(wx.EVT_CHECKBOX, self._onCheck2, self.check2 ) 
6760             label = """Press ctrl-s in any field to output the value and plain value. Press ctrl-x to clear and re-set any field. 
6761 Note that all controls have been auto-sized by including F in the format code. 
6762 Try entering nonsensical or partial values in validated fields to see what happens (use ctrl-s to test the valid status).""" 
6763             label2 = "\nNote that the State and Last Name fields are list-limited (Name:Smith,Jones,Williams)." 
6765             self.label1 = wx.StaticText( self.panel, -1, label) 
6766             self.label2 = wx.StaticText( self.panel, -1, "Description") 
6767             self.label3 = wx.StaticText( self.panel, -1, "Mask Value") 
6768             self.label4 = wx.StaticText( self.panel, -1, "Format") 
6769             self.label5 = wx.StaticText( self.panel, -1, "Reg Expr Val. (opt)") 
6770             self.label6 = wx.StaticText( self.panel, -1, "wxMaskedEdit Ctrl") 
6771             self.label7 = wx.StaticText( self.panel, -1, label2) 
6772             self.label7.SetForegroundColour("Blue") 
6773             self.label1.SetForegroundColour("Blue") 
6774             self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD)) 
6775             self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD)) 
6776             self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD)) 
6777             self.label5.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD)) 
6778             self.label6.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD)) 
6780             self.sizer.Add( self.label1, row=1,col=0,colspan=7, flag=wx.ALL,border=5) 
6781             self.sizer.Add( self.label7, row=2,col=0,colspan=7, flag=wx.ALL,border=5) 
6782             self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5) 
6783             self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5) 
6784             self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5) 
6785             self.sizer.Add( self.label5, row=3,col=3, flag=wx.ALL,border=5) 
6786             self.sizer.Add( self.label6, row=3,col=4, flag=wx.ALL,border=5) 
6788             # The following list is of the controls for the demo. Feel free to play around with 
6791             #description        mask                    excl format     regexp                              range,list,initial 
6792            ("Phone No",         "(###) ###-#### x:###", "", 'F!^-R',    "^\(\d\d\d\) \d\d\d-\d\d\d\d",    (),[],''), 
6793            ("Last Name Only",   "C{14}",                "", 'F {list}', '^[A-Z][a-zA-Z]+',                  (),('Smith','Jones','Williams'),''), 
6794            ("Full Name",        "C{14}",                "", 'F_',       '^[A-Z][a-zA-Z]+ [A-Z][a-zA-Z]+',   (),[],''), 
6795            ("Social Sec#",      "###-##-####",          "", 'F',        "\d{3}-\d{2}-\d{4}",                (),[],''), 
6796            ("U.S. Zip+4",       "#{5}-#{4}",            "", 'F',        "\d{5}-(\s{4}|\d{4})",(),[],''), 
6797            ("U.S. State (2 char)\n(with default)","AA",                 "", 'F!',       "[A-Z]{2}",                         (),states, 'AZ'), 
6798            ("Customer No",      "\CAA-###",              "", 'F!',      "C[A-Z]{2}-\d{3}",                   (),[],''), 
6799            ("Date (MDY) + Time\n(with default)",      "##/##/#### ##:## AM",  'BCDEFGHIJKLMNOQRSTUVWXYZ','DFR!',"",                (),[], r'03/05/2003 12:00 AM'), 
6800            ("Invoice Total",    "#{9}.##",              "", 'F-R,',     "",                                 (),[], ''), 
6801            ("Integer (signed)\n(with default)", "#{6}",                 "", 'F-R',      "",                                 (),[], '0     '), 
6802            ("Integer (unsigned)\n(with default), 1-399", "######",      "", 'F',        "",                                 (1,399),[], '1     '), 
6803            ("Month selector",   "XXX",                  "", 'F',        "",                                 (), 
6804                 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],""), 
6805            ("fraction selector","#/##",                 "", 'F',        "^\d\/\d\d?",                       (), 
6806                 ['2/3', '3/4', '1/2', '1/4', '1/8', '1/16', '1/32', '1/64'], "") 
6809             for control in controls: 
6810                 self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL) 
6811                 self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL) 
6812                 self.sizer.Add( wx.StaticText( self.panel, -1, control[3]),row=rowcount, col=2,border=5, flag=wx.ALL) 
6813                 self.sizer.Add( wx.StaticText( self.panel, -1, control[4][:20]),row=rowcount, col=3,border=5, flag=wx.ALL) 
6815                 if control in controls[:]:#-2]: 
6816                     newControl  = MaskedTextCtrl( self.panel, -1, "", 
6818                                                     excludeChars = control[2], 
6819                                                     formatcodes  = control[3], 
6821                                                     validRegex   = control[4], 
6822                                                     validRange   = control[5], 
6823                                                     choices      = control[6], 
6824                                                     defaultValue = control[7], 
6826                     if control[6]: newControl.SetCtrlParameters(choiceRequired = True) 
6828                     newControl = MaskedComboBox(  self.panel, -1, "", 
6829                                                     choices = control[7], 
6830                                                     choiceRequired  = True, 
6832                                                     formatcodes  = control[3], 
6833                                                     excludeChars = control[2], 
6835                                                     validRegex   = control[4], 
6836                                                     validRange   = control[5], 
6838                 self.editList.append( newControl ) 
6840                 self.sizer.Add( newControl, row=rowcount,col=4,flag=wx.ALL,border=5) 
6843             self.sizer.AddGrowableCol(4) 
6845             self.panel.SetSizer(self.sizer) 
6846             self.panel.SetAutoLayout(1) 
6853         def onClick(self, event): 
6856         def onClickPage(self, event): 
6857             self.page2 = test2(self.frame,-1,"") 
6858             self.page2.Show(True) 
6860         def _onCheck1(self,event): 
6861             """ Set required value on/off """ 
6862             value = event.IsChecked() 
6864                 for control in self.editList: 
6865                     control.SetCtrlParameters(emptyInvalid=True) 
6868                 for control in self.editList: 
6869                     control.SetCtrlParameters(emptyInvalid=False) 
6871             self.panel.Refresh() 
6873         def _onCheck2(self,event): 
6874             """ Highlight empty values""" 
6875             value = event.IsChecked() 
6877                 for control in self.editList: 
6878                     control.SetCtrlParameters( emptyBackgroundColour = 'Aquamarine') 
6881                 for control in self.editList: 
6882                     control.SetCtrlParameters( emptyBackgroundColour = 'White') 
6884             self.panel.Refresh() 
6887 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
6889 class test2(wx.Frame): 
6890         def __init__(self, parent, id, caption): 
6891             wx.Frame.__init__( self, parent, id, "wxMaskedEdit control 0.0.7 Demo Page #2 -- AutoFormats", size = (550,600)) 
6892             from wx.lib.rcsizer import RowColSizer 
6893             self.panel = wx.Panel( self, -1) 
6894             self.sizer = RowColSizer() 
6900 All these controls have been created by passing a single parameter, the AutoFormat code. 
6901 The class contains an internal dictionary of types and formats (autoformats). 
6902 To see a great example of validations in action, try entering a bad email address, then tab out.""" 
6904             self.label1 = wx.StaticText( self.panel, -1, label) 
6905             self.label2 = wx.StaticText( self.panel, -1, "Description") 
6906             self.label3 = wx.StaticText( self.panel, -1, "AutoFormat Code") 
6907             self.label4 = wx.StaticText( self.panel, -1, "wxMaskedEdit Control") 
6908             self.label1.SetForegroundColour("Blue") 
6909             self.label2.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD)) 
6910             self.label3.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD)) 
6911             self.label4.SetFont(wx.Font(9,wx.SWISS,wx.NORMAL,wx.BOLD)) 
6913             self.sizer.Add( self.label1, row=1,col=0,colspan=3, flag=wx.ALL,border=5) 
6914             self.sizer.Add( self.label2, row=3,col=0, flag=wx.ALL,border=5) 
6915             self.sizer.Add( self.label3, row=3,col=1, flag=wx.ALL,border=5) 
6916             self.sizer.Add( self.label4, row=3,col=2, flag=wx.ALL,border=5) 
6918             id, id1 = wx.NewId(), wx.NewId() 
6919             self.command1  = wx.Button( self.panel, id, "&Close") 
6920             self.command2  = wx.Button( self.panel, id1, "&Print Formats") 
6921             self.panel.Bind(wx.EVT_BUTTON, self.onClick, self.command1) 
6922             self.panel.SetDefaultItem(self.command1) 
6923             self.panel.Bind(wx.EVT_BUTTON, self.onClickPrint, self.command2) 
6925             # The following list is of the controls for the demo. Feel free to play around with 
6928            ("Phone No","USPHONEFULLEXT"), 
6929            ("US Date + Time","USDATETIMEMMDDYYYY/HHMM"), 
6930            ("US Date MMDDYYYY","USDATEMMDDYYYY/"), 
6931            ("Time (with seconds)","TIMEHHMMSS"), 
6932            ("Military Time\n(without seconds)","MILTIMEHHMM"), 
6933            ("Social Sec#","USSOCIALSEC"), 
6934            ("Credit Card","CREDITCARD"), 
6935            ("Expiration MM/YY","EXPDATEMMYY"), 
6936            ("Percentage","PERCENT"), 
6937            ("Person's Age","AGE"), 
6938            ("US Zip Code","USZIP"), 
6939            ("US Zip+4","USZIPPLUS4"), 
6940            ("Email Address","EMAIL"), 
6941            ("IP Address", "(derived control IpAddrCtrl)") 
6944             for control in controls: 
6945                 self.sizer.Add( wx.StaticText( self.panel, -1, control[0]),row=rowcount, col=0,border=5,flag=wx.ALL) 
6946                 self.sizer.Add( wx.StaticText( self.panel, -1, control[1]),row=rowcount, col=1,border=5, flag=wx.ALL) 
6947                 if control in controls[:-1]: 
6948                     self.sizer.Add( MaskedTextCtrl( self.panel, -1, "", 
6949                                                       autoformat  = control[1], 
6951                                 row=rowcount,col=2,flag=wx.ALL,border=5) 
6953                     self.sizer.Add( IpAddrCtrl( self.panel, -1, "", demo=True ), 
6954                                     row=rowcount,col=2,flag=wx.ALL,border=5) 
6957             self.sizer.Add(self.command1, row=0, col=0, flag=wx.ALL, border = 5) 
6958             self.sizer.Add(self.command2, row=0, col=1, flag=wx.ALL, border = 5) 
6959             self.sizer.AddGrowableCol(3) 
6961             self.panel.SetSizer(self.sizer) 
6962             self.panel.SetAutoLayout(1) 
6964         def onClick(self, event): 
6967         def onClickPrint(self, event): 
6968             for format in masktags.keys(): 
6969                 sep = "+------------------------+" 
6970                 print "%s\n%s  \n  Mask: %s \n  RE Validation string: %s\n" % (sep,format, masktags[format]['mask'], masktags[format]['validRegex']) 
6972 ## ---------- ---------- ---------- ---------- ---------- ---------- ---------- 
6974 if __name__ == "__main__": 
6980 ## =================================== 
6982 ## 1. WS: For some reason I don't understand, the control is generating two (2) 
6983 ##      EVT_TEXT events for every one (1) .SetValue() of the underlying control. 
6984 ##      I've been unsuccessful in determining why or in my efforts to make just one 
6985 ##      occur.  So, I've added a hack to save the last seen value from the 
6986 ##      control in the EVT_TEXT handler, and if *different*, call event.Skip() 
6987 ##      to propagate it down the event chain, and let the application see it. 
6989 ## 2. WS: MaskedComboBox is deficient in several areas, all having to do with the 
6990 ##      behavior of the underlying control that I can't fix.  The problems are: 
6991 ##      a) The background coloring doesn't work in the text field of the control; 
6992 ##         instead, there's a only border around it that assumes the correct color. 
6993 ##      b) The control will not pass WXK_TAB to the event handler, no matter what 
6994 ##         I do, and there's no style wxCB_PROCESS_TAB like wxTE_PROCESS_TAB to 
6995 ##         indicate that we want these events.  As a result, MaskedComboBox 
6996 ##         doesn't do the nice field-tabbing that MaskedTextCtrl does. 
6997 ##      c) Auto-complete had to be reimplemented for the control because programmatic 
6998 ##         setting of the value of the text field does not set up the auto complete 
6999 ##         the way that the control processing keystrokes does.  (But I think I've 
7000 ##         implemented a fairly decent approximation.)  Because of this the control 
7001 ##         also won't auto-complete on dropdown, and there's no event I can catch 
7002 ##         to work around this problem. 
7003 ##      d) There is no method provided for getting the selection; the hack I've 
7004 ##         implemented has its flaws, not the least of which is that due to the 
7005 ##         strategy that I'm using, the paste buffer is always replaced by the 
7006 ##         contents of the control's selection when in focus, on each keystroke; 
7007 ##         this makes it impossible to paste anything into a MaskedComboBox 
7008 ##         at the moment... :-( 
7009 ##      e) The other deficient behavior, likely induced by the workaround for (d), 
7010 ##         is that you can can't shift-left to select more than one character 
7014 ## 3. WS: Controls on wxPanels don't seem to pass Shift-WXK_TAB to their 
7015 ##      EVT_KEY_DOWN or EVT_CHAR event handlers.  Until this is fixed in 
7016 ##      wxWindows, shift-tab won't take you backwards through the fields of 
7017 ##      a MaskedTextCtrl like it should.  Until then Shifted arrow keys will 
7018 ##      work like shift-tab and tab ought to. 
7022 ## =============================## 
7023 ##  1. Add Popup list for auto-completable fields that simulates combobox on individual 
7024 ##     fields.  Example: City validates against list of cities, or zip vs zip code list. 
7025 ##  2. Allow optional monetary symbols (eg. $, pounds, etc.) at front of a "decimal" 
7027 ##  3. Fix shift-left selection for MaskedComboBox. 
7028 ##  5. Transform notion of "decimal control" to be less "entire control"-centric, 
7029 ##     so that monetary symbols can be included and still have the appropriate 
7030 ##     semantics.  (Big job, as currently written, but would make control even 
7031 ##     more useful for business applications.) 
7035 ## ==================== 
7037 ##  (Reported) bugs fixed: 
7038 ##   1. Right-click menu allowed "cut" operation that destroyed mask 
7039 ##      (was implemented by base control) 
7040 ##   2. MaskedComboBox didn't allow .Append() of mixed-case values; all 
7041 ##      got converted to lower case. 
7042 ##   3. MaskedComboBox selection didn't deal with spaces in values 
7043 ##      properly when autocompleting, and didn't have a concept of "next" 
7044 ##      match for handling choice list duplicates. 
7045 ##   4. Size of MaskedComboBox was always default. 
7046 ##   5. Email address regexp allowed some "non-standard" things, and wasn't 
7048 ##   6. Couldn't easily reset MaskedComboBox contents programmatically. 
7049 ##   7. Couldn't set emptyInvalid during construction. 
7050 ##   8. Under some versions of wxPython, readonly comboboxes can apparently 
7051 ##      return a GetInsertionPoint() result (655535), causing masked control 
7053 ##   9. Specifying an empty mask caused the controls to traceback. 
7054 ##  10. Can't specify float ranges for validRange. 
7055 ##  11. '.' from within a the static portion of a restricted IP address 
7056 ##      destroyed the mask from that point rightward; tab when cursor is 
7057 ##      before 1st field takes cursor past that field. 
7060 ##  12. Added Ctrl-Z/Undo handling, (and implemented context-menu properly.) 
7061 ##  13. Added auto-select option on char input for masked controls with 
7063 ##  14. Added '>' formatcode, allowing insert within a given or each field 
7064 ##      as appropriate, rather than requiring "overwrite".  This makes single 
7065 ##      field controls that just have validation rules (eg. EMAIL) much more 
7066 ##      friendly.  The same flag controls left shift when deleting vs just 
7067 ##      blanking the value, and for right-insert fields, allows right-insert 
7068 ##      at any non-blank (non-sign) position in the field. 
7069 ##  15. Added option to use to indicate negative values for numeric controls. 
7070 ##  16. Improved OnFocus handling of numeric controls. 
7071 ##  17. Enhanced Home/End processing to allow operation on a field level, 
7073 ##  18. Added individual Get/Set functions for control parameters, for 
7074 ##      simplified integration with Boa Constructor. 
7075 ##  19. Standardized "Colour" parameter names to match wxPython, with 
7076 ##      non-british spellings still supported for backward-compatibility. 
7077 ##  20. Added '&' mask specification character for punctuation only (no letters 
7079 ##  21. Added (in a separate file) wxMaskedCtrl() factory function to provide 
7080 ##      unified interface to the masked edit subclasses. 
7084 ##   1. Made it possible to configure grouping, decimal and shift-decimal characters, 
7085 ##      to make controls more usable internationally. 
7086 ##   2. Added code to smart "adjust" value strings presented to .SetValue() 
7087 ##      for right-aligned numeric format controls if they are shorter than 
7088 ##      than the control width,  prepending the missing portion, prepending control 
7089 ##      template left substring for the missing characters, so that setting 
7090 ##      numeric values is easier. 
7091 ##   3. Renamed SetMaskParameters SetCtrlParameters() (with old name preserved 
7092 ##      for b-c), as this makes more sense. 
7095 ##   1. Fixed .SetValue() to replace the current value, rather than the current 
7096 ##      selection. Also changed it to generate ValueError if presented with 
7097 ##      either a value which doesn't follow the format or won't fit.  Also made 
7098 ##      set value adjust numeric and date controls as if user entered the value. 
7099 ##      Expanded doc explaining how SetValue() works. 
7100 ##   2. Fixed EUDATE* autoformats, fixed IsDateType mask list, and added ability to 
7101 ##      use 3-char months for dates, and EUDATETIME, and EUDATEMILTIME autoformats. 
7102 ##   3. Made all date autoformats automatically pick implied "datestyle". 
7103 ##   4. Added IsModified override, since base wxTextCtrl never reports modified if 
7104 ##      .SetValue used to change the value, which is what the masked edit controls 
7106 ##   5. Fixed bug in date position adjustment on 2 to 4 digit date conversion when 
7107 ##      using tab to "leave field" and auto-adjust. 
7108 ##   6. Fixed bug in _isCharAllowed() for negative number insertion on pastes, 
7109 ##      and bug in ._Paste() that didn't account for signs in signed masks either. 
7110 ##   7. Fixed issues with _adjustPos for right-insert fields causing improper 
7111 ##      selection/replacement of values 
7112 ##   8. Fixed _OnHome handler to properly handle extending current selection to 
7113 ##      beginning of control. 
7114 ##   9. Exposed all (valid) autoformats to demo, binding descriptions to 
7116 ##  10. Fixed a couple of bugs in email regexp. 
7117 ##  11. Made maskchardict an instance var, to make mask chars to be more 
7118 ##      amenable to international use. 
7119 ##  12. Clarified meaning of '-' formatcode in doc. 
7120 ##  13. Fixed a couple of coding bugs being flagged by Python2.1. 
7121 ##  14. Fixed several issues with sign positioning, erasure and validity 
7122 ##      checking for "numeric" masked controls. 
7123 ##  15. Added validation to IpAddrCtrl.SetValue(). 
7126 ##   1. Changed calling interface to use boolean "useFixedWidthFont" (True by default) 
7127 ##      vs. literal font facename, and use wxTELETYPE as the font family 
7129 ##   2. Switched to use of dbg module vs. locally defined version. 
7130 ##   3. Revamped entire control structure to use Field classes to hold constraint 
7131 ##      and formatting data, to make code more hierarchical, allow for more 
7132 ##      sophisticated masked edit construction. 
7133 ##   4. Better strategy for managing options, and better validation on keywords. 
7134 ##   5. Added 'V' format code, which requires that in order for a character 
7135 ##      to be accepted, it must result in a string that passes the validRegex. 
7136 ##   6. Added 'S' format code which means "select entire field when navigating 
7138 ##   7. Added 'r' format code to allow "right-insert" fields. (implies 'R'--right-alignment) 
7139 ##   8. Added '<' format code to allow fields to require explicit cursor movement 
7141 ##   9. Added validFunc option to other validation mechanisms, that allows derived 
7142 ##      classes to add dynamic validation constraints to the control. 
7143 ##  10. Fixed bug in validatePaste code causing possible IndexErrors, and also 
7144 ##      fixed failure to obey case conversion codes when pasting. 
7145 ##  11. Implemented '0' (zero-pad) formatting code, as it wasn't being done anywhere... 
7146 ##  12. Removed condition from OnDecimalPoint, so that it always truncates right on '.' 
7147 ##  13. Enhanced IpAddrCtrl to use right-insert fields, selection on field traversal, 
7148 ##      individual field validation to prevent field values > 255, and require explicit 
7149 ##      tab/. to change fields. 
7150 ##  14. Added handler for left double-click to select field under cursor. 
7151 ##  15. Fixed handling for "Read-only" styles. 
7152 ##  16. Separated signedForegroundColor from 'R' style, and added foregroundColor 
7153 ##      attribute, for more consistent and controllable coloring. 
7154 ##  17. Added retainFieldValidation parameter, allowing top-level constraints 
7155 ##      such as "validRequired" to be set independently of field-level equivalent. 
7156 ##      (needed in TimeCtrl for bounds constraints.) 
7157 ##  18. Refactored code a bit, cleaned up and commented code more heavily, fixed 
7158 ##      some of the logic for setting/resetting parameters, eg. fillChar, defaultValue, 
7160 ##  19. Fixed maskchar setting for upper/lowercase, to work in all locales. 
7164 ##   1. Decimal point behavior restored for decimal and integer type controls: 
7165 ##      decimal point now trucates the portion > 0. 
7166 ##   2. Return key now works like the tab character and moves to the next field, 
7167 ##      provided no default button is set for the form panel on which the control 
7169 ##   3. Support added in _FindField() for subclasses controls (like timecontrol) 
7170 ##      to determine where the current insertion point is within the mask (i.e. 
7171 ##      which sub-'field'). See method documentation for more info and examples. 
7172 ##   4. Added Field class and support for all constraints to be field-specific 
7173 ##      in addition to being globally settable for the control. 
7174 ##      Choices for each field are validated for length and pastability into 
7175 ##      the field in question, raising ValueError if not appropriate for the control. 
7176 ##      Also added selective additional validation based on individual field constraints. 
7177 ##      By default, SHIFT-WXK_DOWN, SHIFT-WXK_UP, WXK_PRIOR and WXK_NEXT all 
7178 ##      auto-complete fields with choice lists, supplying the 1st entry in 
7179 ##      the choice list if the field is empty, and cycling through the list in 
7180 ##      the appropriate direction if already a match.  WXK_DOWN will also auto- 
7181 ##      complete if the field is partially completed and a match can be made. 
7182 ##      SHIFT-WXK_UP/DOWN will also take you to the next field after any 
7183 ##      auto-completion performed. 
7184 ##   5. Added autoCompleteKeycodes=[] parameters for allowing further 
7185 ##      customization of the control.  Any keycode supplied as a member 
7186 ##      of the _autoCompleteKeycodes list will be treated like WXK_NEXT.  If 
7187 ##      requireFieldChoice is set, then a valid value from each non-empty 
7188 ##      choice list will be required for the value of the control to validate. 
7189 ##   6. Fixed "auto-sizing" to be relative to the font actually used, rather 
7190 ##      than making assumptions about character width. 
7191 ##   7. Fixed GetMaskParameter(), which was non-functional in previous version. 
7192 ##   8. Fixed exceptions raised to provide info on which control had the error. 
7193 ##   9. Fixed bug in choice management of MaskedComboBox. 
7194 ##  10. Fixed bug in IpAddrCtrl causing traceback if field value was of 
7195 ##     the form '# #'.  Modified control code for IpAddrCtrl so that '.' 
7196 ##     in the middle of a field clips the rest of that field, similar to 
7197 ##     decimal and integer controls. 
7201 ##   1. "-" is a toggle for sign; "+" now changes - signed numerics to positive. 
7202 ##   2. ',' in formatcodes now causes numeric values to be comma-delimited (e.g.333,333). 
7203 ##   3. New support for selecting text within the control.(thanks Will Sadkin!) 
7204 ##      Shift-End and Shift-Home now select text as you would expect 
7205 ##      Control-Shift-End selects to the end of the mask string, even if value not entered. 
7206 ##      Control-A selects all *entered* text, Shift-Control-A selects everything in the control. 
7207 ##   4. event.Skip() added to onKillFocus to correct remnants when running in Linux (contributed- 
7208 ##      for some reason I couldn't find the original email but thanks!!!) 
7209 ##   5. All major key-handling code moved to their own methods for easier subclassing: OnHome, 
7210 ##      OnErase, OnEnd, OnCtrl_X, OnCtrl_A, etc. 
7211 ##   6. Email and autoformat validations corrected using regex provided by Will Sadkin (thanks!). 
7212 ##   (The rest of the changes in this version were done by Will Sadkin with permission from Jeff...) 
7213 ##   7. New mechanism for replacing default behavior for any given key, using 
7214 ##      ._SetKeycodeHandler(keycode, func) and ._SetKeyHandler(char, func) now available 
7215 ##      for easier subclassing of the control. 
7216 ##   8. Reworked the delete logic, cut, paste and select/replace logic, as well as some bugs 
7217 ##      with insertion point/selection modification.  Changed Ctrl-X to use standard "cut" 
7218 ##      semantics, erasing the selection, rather than erasing the entire control. 
7219 ##   9. Added option for an "default value" (ie. the template) for use when a single fillChar 
7220 ##      is not desired in every position.  Added IsDefault() function to mean "does the value 
7221 ##      equal the template?" and modified .IsEmpty() to mean "do all of the editable 
7222 ##      positions in the template == the fillChar?" 
7223 ##  10. Extracted mask logic into mixin, so we can have both MaskedTextCtrl and MaskedComboBox, 
7225 ##  11. MaskedComboBox now adds the capability to validate from list of valid values. 
7226 ##      Example: City validates against list of cities, or zip vs zip code list. 
7227 ##  12. Fixed oversight in EVT_TEXT handler that prevented the events from being 
7228 ##      passed to the next handler in the event chain, causing updates to the 
7229 ##      control to be invisible to the parent code. 
7230 ##  13. Added IPADDR autoformat code, and subclass IpAddrCtrl for controlling tabbing within 
7231 ##      the control, that auto-reformats as you move between cells. 
7232 ##  14. Mask characters [A,a,X,#] can now appear in the format string as literals, by using '\'. 
7233 ##  15. It is now possible to specify repeating masks, e.g. #{3}-#{3}-#{14} 
7234 ##  16. Fixed major bugs in date validation, due to the fact that 
7235 ##      wxDateTime.ParseDate is too liberal, and will accept any form that 
7236 ##      makes any kind of sense, regardless of the datestyle you specified 
7237 ##      for the control.  Unfortunately, the strategy used to fix it only 
7238 ##      works for versions of wxPython post 2.3.3.1, as a C++ assert box 
7239 ##      seems to show up on an invalid date otherwise, instead of a catchable 
7241 ##  17. Enhanced date adjustment to automatically adjust heuristic based on 
7242 ##      current year, making last century/this century determination on 
7243 ##      2-digit year based on distance between today's year and value; 
7244 ##      if > 50 year separation, assume last century (and don't assume last 
7245 ##      century is 20th.) 
7246 ##  18. Added autoformats and support for including HHMMSS as well as HHMM for 
7247 ##      date times, and added similar time, and militaray time autoformats. 
7248 ##  19. Enhanced tabbing logic so that tab takes you to the next field if the 
7249 ##      control is a multi-field control. 
7250 ##  20. Added stub method called whenever the control "changes fields", that 
7251 ##      can be overridden by subclasses (eg. IpAddrCtrl.) 
7252 ##  21. Changed a lot of code to be more functionally-oriented so side-effects 
7253 ##      aren't as problematic when maintaining code and/or adding features. 
7254 ##      Eg: IsValid() now does not have side-effects; it merely reflects the 
7255 ##      validity of the value of the control; to determine validity AND recolor 
7256 ##      the control, _CheckValid() should be used with a value argument of None. 
7257 ##      Similarly, made most reformatting function take an optional candidate value 
7258 ##      rather than just using the current value of the control, and only 
7259 ##      have them change the value of the control if a candidate is not specified. 
7260 ##      In this way, you can do validation *before* changing the control. 
7261 ##  22. Changed validRequired to mean "disallow chars that result in invalid 
7262 ##      value."  (Old meaning now represented by emptyInvalid.)  (This was 
7263 ##      possible once I'd made the changes in (19) above.) 
7264 ##  23. Added .SetMaskParameters and .GetMaskParameter methods, so they 
7265 ##      can be set/modified/retrieved after construction.  Removed individual 
7266 ##      parameter setting functions, in favor of this mechanism, so that 
7267 ##      all adjustment of the control based on changing parameter values can 
7268 ##      be handled in one place with unified mechanism. 
7269 ##  24. Did a *lot* of testing and fixing re: numeric values.  Added ability 
7270 ##      to type "grouping char" (ie. ',') and validate as appropriate. 
7271 ##  25. Fixed ZIPPLUS4 to allow either 5 or 4, but if > 5 must be 9. 
7272 ##  26. Fixed assumption about "decimal or integer" masks so that they're only 
7273 ##      made iff there's no validRegex associated with the field.  (This 
7274 ##      is so things like zipcodes which look like integers can have more 
7275 ##      restrictive validation (ie. must be 5 digits.) 
7276 ##  27. Added a ton more doc strings to explain use and derivation requirements 
7277 ##      and did regularization of the naming conventions. 
7278 ##  28. Fixed a range bug in _adjustKey preventing z from being handled properly. 
7279 ##  29. Changed behavior of '.' (and shift-.) in numeric controls to move to 
7280 ##      reformat the value and move the next field as appropriate. (shift-'.', 
7281 ##      ie. '>' moves to the previous field. 
7284 ##   1. Fixed regex bug that caused autoformat AGE to invalidate any age ending 
7286 ##   2. New format character 'D' to trigger date type. If the user enters 2 digits in the 
7287 ##      year position, the control will expand the value to four digits, using numerals below 
7288 ##      50 as 21st century (20+nn) and less than 50 as 20th century (19+nn). 
7289 ##      Also, new optional parameter datestyle = set to one of {MDY|DMY|YDM} 
7290 ##   3. revalid parameter renamed validRegex to conform to standard for all validation 
7291 ##      parameters (see 2 new ones below). 
7292 ##   4. New optional init parameter = validRange. Used only for int/dec (numeric) types. 
7293 ##      Allows the developer to specify a valid low/high range of values. 
7294 ##   5. New optional init parameter = validList. Used for character types. Allows developer 
7295 ##      to send a list of values to the control to be used for specific validation. 
7296 ##      See the Last Name Only example - it is list restricted to Smith/Jones/Williams. 
7297 ##   6. Date type fields now use wxDateTime's parser to validate the date and time. 
7298 ##      This works MUCH better than my kludgy regex!! Thanks to Robin Dunn for pointing 
7299 ##      me toward this solution! 
7300 ##   7. Date fields now automatically expand 2-digit years when it can. For example, 
7301 ##      if the user types "03/10/67", then "67" will auto-expand to "1967". If a two-year 
7302 ##      date is entered it will be expanded in any case when the user tabs out of the 
7304 ##   8. New class functions: SetValidBackgroundColor, SetInvalidBackgroundColor, SetEmptyBackgroundColor, 
7305 ##      SetSignedForeColor allow accessto override default class coloring behavior. 
7306 ##   9. Documentation updated and improved. 
7307 ##  10. Demo - page 2 is now a wxFrame class instead of a wxPyApp class. Works better. 
7308 ##      Two new options (checkboxes) - test highlight empty and disallow empty. 
7309 ##  11. Home and End now work more intuitively, moving to the first and last user-entry 
7310 ##      value, respectively. 
7311 ##  12. New class function: SetRequired(bool). Sets the control's entry required flag 
7312 ##      (i.e. disallow empty values if True). 
7315 ##   1. get_plainValue method renamed to GetPlainValue following the wxWindows 
7316 ##      StudlyCaps(tm) standard (thanks Paul Moore).  ;) 
7317 ##   2. New format code 'F' causes the control to auto-fit (auto-size) itself 
7318 ##      based on the length of the mask template. 
7319 ##   3. Class now supports "autoformat" codes. These can be passed to the class 
7320 ##      on instantiation using the parameter autoformat="code". If the code is in 
7321 ##      the dictionary, it will self set the mask, formatting, and validation string. 
7322 ##      I have included a number of samples, but I am hoping that someone out there 
7323 ##      can help me to define a whole bunch more. 
7324 ##   4. I have added a second page to the demo (as well as a second demo class, test2) 
7325 ##      to showcase how autoformats work. The way they self-format and self-size is, 
7326 ##      I must say, pretty cool. 
7327 ##   5. Comments added and some internal cosmetic revisions re: matching the code 
7328 ##      standards for class submission. 
7329 ##   6. Regex validation is now done in real time - field turns yellow immediately 
7330 ##      and stays yellow until the entered value is valid 
7331 ##   7. Cursor now skips over template characters in a more intuitive way (before the 
7333 ##   8. Change, Keypress and LostFocus methods added for convenience of subclasses. 
7334 ##      Developer may use these methods which will be called after EVT_TEXT, EVT_CHAR, 
7335 ##      and EVT_KILL_FOCUS, respectively. 
7336 ##   9. Decimal and numeric handlers have been rewritten and now work more intuitively. 
7339 ##   1. New .IsEmpty() method returns True if the control's value is equal to the 
7340 ##      blank template string 
7341 ##   2. Control now supports a new init parameter: revalid. Pass a regular expression 
7342 ##      that the value will have to match when the control loses focus. If invalid, 
7343 ##      the control's BackgroundColor will turn yellow, and an internal flag is set (see next). 
7344 ##   3. Demo now shows revalid functionality. Try entering a partial value, such as a 
7345 ##      partial social security number. 
7346 ##   4. New .IsValid() value returns True if the control is empty, or if the value matches 
7347 ##      the revalid expression. If not, .IsValid() returns False. 
7348 ##   5. Decimal values now collapse to decimal with '.00' on losefocus if the user never 
7349 ##      presses the decimal point. 
7350 ##   6. Cursor now goes to the beginning of the field if the user clicks in an 
7351 ##      "empty" field intead of leaving the insertion point in the middle of the 
7353 ##   7. New "N" mask type includes upper and lower chars plus digits. a-zA-Z0-9. 
7354 ##   8. New formatcodes init parameter replaces other init params and adds functions. 
7355 ##      String passed to control on init controls: 
7359 ##        R Show negative #s in red 
7361 ##        - Signed numerals 
7362 ##        0 Numeric fields get leading zeros 
7363 ##   9. Ctrl-X in any field clears the current value. 
7364 ##   10. Code refactored and made more modular (esp in OnChar method). Should be more 
7365 ##       easy to read and understand. 
7366 ##   11. Demo enhanced. 
7367 ##   12. Now has _doc_. 
7370 ##   1. GetPlainValue() now returns the value without the template characters; 
7371 ##      so, for example, a social security number (123-33-1212) would return as 
7372 ##      123331212; also removes white spaces from numeric/decimal values, so 
7373 ##      "-   955.32" is returned "-955.32". Press ctrl-S to see the plain value. 
7374 ##   2. Press '.' in an integer style masked control and truncate any trailing digits. 
7375 ##   3. Code moderately refactored. Internal names improved for clarity. Additional 
7376 ##      internal documentation. 
7377 ##   4. Home and End keys now supported to move cursor to beginning or end of field. 
7378 ##   5. Un-signed integers and decimals now supported. 
7379 ##   6. Cosmetic improvements to the demo. 
7380 ##   7. Class renamed to MaskedTextCtrl. 
7381 ##   8. Can now specify include characters that will override the basic 
7382 ##      controls: for example, includeChars = "@." for email addresses 
7383 ##   9. Added mask character 'C' -> allow any upper or lowercase character 
7384 ##   10. .SetSignColor(str:color) sets the foreground color for negative values 
7385 ##       in signed controls (defaults to red) 
7386 ##   11. Overview documentation written. 
7389 ##   1. Tab now works properly when pressed in last position 
7390 ##   2. Decimal types now work (e.g. #####.##) 
7391 ##   3. Signed decimal or numeric values supported (i.e. negative numbers) 
7392 ##   4. Negative decimal or numeric values now can show in red. 
7393 ##   5. Can now specify an "exclude list" with the excludeChars parameter. 
7394 ##      See date/time formatted example - you can only enter A or P in the 
7395 ##      character mask space (i.e. AM/PM). 
7396 ##   6. Backspace now works properly, including clearing data from a selected 
7397 ##      region but leaving template characters intact. Also delete key. 
7398 ##   7. Left/right arrows now work properly. 
7399 ##   8. Removed EventManager call from test so demo should work with wxPython 2.3.3