1 #----------------------------------------------------------------------------
2 # Name: wxPython.lib.maskednumctrl.py
5 # Copyright: (c) 2003 by Will Sadkin
7 # License: wxWindows license
8 #----------------------------------------------------------------------------
10 # This was written to provide a numeric edit control for wxPython that
11 # does things like right-insert (like a calculator), and does grouping, etc.
12 # (ie. the features of MaskedTextCtrl), but allows Get/Set of numeric
13 # values, rather than text.
15 # MaskedNumCtrl permits integer, and floating point values to be set
16 # retrieved or set via .GetValue() and .SetValue() (type chosen based on
17 # fraction width, and provides an EVT_MASKEDNUM() event function for trapping
18 # changes to the control.
20 # It supports negative numbers as well as the naturals, and has the option
21 # of not permitting leading zeros or an empty control; if an empty value is
22 # not allowed, attempting to delete the contents of the control will result
23 # in a (selected) value of zero, thus preserving a legitimate numeric value.
24 # Similarly, replacing the contents of the control with '-' will result in
25 # a selected (absolute) value of -1.
27 # MaskedNumCtrl also supports range limits, with the option of either
28 # enforcing them or simply coloring the text of the control if the limits
31 # MaskedNumCtrl is intended to support fixed-point numeric entry, and
32 # is derived from MaskedTextCtrl. As such, it supports a limited range
33 # of values to comply with a fixed-width entry mask.
34 #----------------------------------------------------------------------------
35 # 12/09/2003 - Jeff Grimmett (grimmtooth@softhome.net)
37 # o Updated for wx namespace
39 # 12/20/2003 - Jeff Grimmett (grimmtooth@softhome.net)
41 # o wxMaskedEditMixin -> MaskedEditMixin
42 # o wxMaskedTextCtrl -> MaskedTextCtrl
43 # o wxMaskedNumNumberUpdatedEvent -> MaskedNumNumberUpdatedEvent
44 # o wxMaskedNumCtrl -> MaskedNumCtrl
51 <LI>allows you to get and set integer or floating point numbers as value,</LI>
52 <LI>provides bounds support and optional value limiting,</LI>
53 <LI>has the right-insert input style that MaskedTextCtrl supports,</LI>
54 <LI>provides optional automatic grouping, sign control and format, grouping and decimal
55 character selection, etc. etc.</LI>
58 Being derived from MaskedTextCtrl, the control only allows
59 fixed-point notation. That is, it has a fixed (though reconfigurable)
60 maximum width for the integer portion and optional fixed width
68 pos = wxDefaultPosition,
71 validator = wxDefaultValidator,
72 name = "maskednumber",
73 <B>integerWidth</B> = 10,
74 <B>fractionWidth</B> = 0,
75 <B>allowNone</B> = False,
76 <B>allowNegative</B> = True,
77 <B>useParensForNegatives</B> = False,
78 <B>groupDigits</B> = False,
79 <B>groupChar</B> = ',',
80 <B>decimalChar</B> = '.',
83 <B>limited</B> = False,
84 <B>selectOnEntry</b> = True,
85 <B>foregroundColour</B> = "Black",
86 <B>signedForegroundColour</B> = "Red",
87 <B>emptyBackgroundColour</B> = "White",
88 <B>validBackgroundColour</B> = "White",
89 <B>invalidBackgroundColour</B> = "Yellow",
94 <DD>If no initial value is set, the default will be zero, or
95 the minimum value, if specified. If an illegal string is specified,
96 a ValueError will result. (You can always later set the initial
97 value with SetValue() after instantiation of the control.)
99 <DL><B>integerWidth</B>
100 <DD>Indicates how many places to the right of any decimal point
101 should be allowed in the control. This will, perforce, limit
102 the size of the values that can be entered. This number need
103 not include space for grouping characters or the sign, if either
104 of these options are enabled, as the resulting underlying
105 mask is automatically by the control. The default of 10
106 will allow any 32 bit integer value. The minimum value
107 for integerWidth is 1.
109 <DL><B>fractionWidth</B>
110 <DD>Indicates how many decimal places to show for numeric value.
111 If default (0), then the control will display and return only
112 integer or long values.
115 <DD>Boolean indicating whether or not the control is allowed to be
116 empty, representing a value of None for the control.
118 <DT><B>allowNegative</B>
119 <DD>Boolean indicating whether or not control is allowed to hold
122 <DT><B>useParensForNegatives</B>
123 <DD>If true, this will cause negative numbers to be displayed with ()s
124 rather than -, (although '-' will still trigger a negative number.)
126 <DT><B>groupDigits</B>
127 <DD>Indicates whether or not grouping characters should be allowed and/or
128 inserted when leaving the control or the decimal character is entered.
131 <DD>What grouping character will be used if allowed. (By default ',')
133 <DT><B>decimalChar</B>
134 <DD>If fractionWidth is > 0, what character will be used to represent
135 the decimal point. (By default '.')
138 <DD>The minimum value that the control should allow. This can be also be
139 adjusted with SetMin(). If the control is not limited, any value
140 below this bound will result in a background colored with the current
141 invalidBackgroundColour. If the min specified will not fit into the
142 control, the min setting will be ignored.
145 <DD>The maximum value that the control should allow. This can be
146 adjusted with SetMax(). If the control is not limited, any value
147 above this bound will result in a background colored with the current
148 invalidBackgroundColour. If the max specified will not fit into the
149 control, the max setting will be ignored.
152 <DD>Boolean indicating whether the control prevents values from
153 exceeding the currently set minimum and maximum values (bounds).
154 If False and bounds are set, out-of-bounds values will
155 result in a background colored with the current invalidBackgroundColour.
157 <DT><B>selectOnEntry</B>
158 <DD>Boolean indicating whether or not the value in each field of the
159 control should be automatically selected (for replacement) when
160 that field is entered, either by cursor movement or tabbing.
161 This can be desirable when using these controls for rapid data entry.
163 <DT><B>foregroundColour</B>
164 <DD>Color value used for positive values of the control.
166 <DT><B>signedForegroundColour</B>
167 <DD>Color value used for negative values of the control.
169 <DT><B>emptyBackgroundColour</B>
170 <DD>What background color to use when the control is considered
171 "empty." (allow_none must be set to trigger this behavior.)
173 <DT><B>validBackgroundColour</B>
174 <DD>What background color to use when the control value is
177 <DT><B>invalidBackgroundColour</B>
178 <DD>Color value used for illegal values or values out-of-bounds of the
179 control when the bounds are set but the control is not limited.
183 <DT><B>EVT_MASKEDNUM(win, id, func)</B>
184 <DD>Respond to a wxEVT_COMMAND_MASKED_NUMBER_UPDATED event, generated when
185 the value changes. Notice that this event will always be sent when the
186 control's contents changes - whether this is due to user input or
187 comes from the program itself (for example, if SetValue() is called.)
190 <DT><B>SetValue(int|long|float|string)</B>
191 <DD>Sets the value of the control to the value specified, if
192 possible. The resulting actual value of the control may be
193 altered to conform to the format of the control, changed
194 to conform with the bounds set on the control if limited,
195 or colored if not limited but the value is out-of-bounds.
196 A ValueError exception will be raised if an invalid value
199 <DT><B>GetValue()</B>
200 <DD>Retrieves the numeric value from the control. The value
201 retrieved will be either be returned as a long if the
202 fractionWidth is 0, or a float otherwise.
205 <DT><B>SetParameters(**kwargs)</B>
206 <DD>Allows simultaneous setting of various attributes
207 of the control after construction. Keyword arguments
208 allowed are the same parameters as supported in the constructor.
211 <DT><B>SetIntegerWidth(value)</B>
212 <DD>Resets the width of the integer portion of the control. The
213 value must be >= 1, or an AttributeError exception will result.
214 This value should account for any grouping characters that might
215 be inserted (if grouping is enabled), but does not need to account
216 for the sign, as that is handled separately by the control.
217 <DT><B>GetIntegerWidth()</B>
218 <DD>Returns the current width of the integer portion of the control,
219 not including any reserved sign position.
222 <DT><B>SetFractionWidth(value)</B>
223 <DD>Resets the width of the fractional portion of the control. The
224 value must be >= 0, or an AttributeError exception will result. If
225 0, the current value of the control will be truncated to an integer
227 <DT><B>GetFractionWidth()</B>
228 <DD>Returns the current width of the fractional portion of the control.
231 <DT><B>SetMin(min=None)</B>
232 <DD>Resets the minimum value of the control. If a value of <I>None</I>
233 is provided, then the control will have no explicit minimum value.
234 If the value specified is greater than the current maximum value,
235 then the function returns False and the minimum will not change from
236 its current setting. On success, the function returns True.
238 If successful and the current value is lower than the new lower
239 bound, if the control is limited, the value will be automatically
240 adjusted to the new minimum value; if not limited, the value in the
241 control will be colored as invalid.
243 If min > the max value allowed by the width of the control,
244 the function will return False, and the min will not be set.
247 <DD>Gets the current lower bound value for the control.
248 It will return None if no lower bound is currently specified.
251 <DT><B>SetMax(max=None)</B>
252 <DD>Resets the maximum value of the control. If a value of <I>None</I>
253 is provided, then the control will have no explicit maximum value.
254 If the value specified is less than the current minimum value, then
255 the function returns False and the maximum will not change from its
256 current setting. On success, the function returns True.
258 If successful and the current value is greater than the new upper
259 bound, if the control is limited the value will be automatically
260 adjusted to this maximum value; if not limited, the value in the
261 control will be colored as invalid.
263 If max > the max value allowed by the width of the control,
264 the function will return False, and the max will not be set.
267 <DD>Gets the current upper bound value for the control.
268 It will return None if no upper bound is currently specified.
271 <DT><B>SetBounds(min=None,max=None)</B>
272 <DD>This function is a convenience function for setting the min and max
273 values at the same time. The function only applies the maximum bound
274 if setting the minimum bound is successful, and returns True
275 only if both operations succeed. <B><I>Note:</I></B> leaving out an argument
276 will remove the corresponding bound.
277 <DT><B>GetBounds()</B>
278 <DD>This function returns a two-tuple (min,max), indicating the
279 current bounds of the control. Each value can be None if
280 that bound is not set.
283 <DT><B>IsInBounds(value=None)</B>
284 <DD>Returns <I>True</I> if no value is specified and the current value
285 of the control falls within the current bounds. This function can also
286 be called with a value to see if that value would fall within the current
287 bounds of the given control.
290 <DT><B>SetLimited(bool)</B>
291 <DD>If called with a value of True, this function will cause the control
292 to limit the value to fall within the bounds currently specified.
293 If the control's value currently exceeds the bounds, it will then
294 be limited accordingly.
295 If called with a value of False, this function will disable value
296 limiting, but coloring of out-of-bounds values will still take
297 place if bounds have been set for the control.
298 <DT><B>GetLimited()</B>
299 <DT><B>IsLimited()</B>
300 <DD>Returns <I>True</I> if the control is currently limiting the
301 value to fall within the current bounds.
304 <DT><B>SetAllowNone(bool)</B>
305 <DD>If called with a value of True, this function will cause the control
306 to allow the value to be empty, representing a value of None.
307 If called with a value of False, this function will prevent the value
308 from being None. If the value of the control is currently None,
309 ie. the control is empty, then the value will be changed to that
310 of the lower bound of the control, or 0 if no lower bound is set.
311 <DT><B>GetAllowNone()</B>
312 <DT><B>IsNoneAllowed()</B>
313 <DD>Returns <I>True</I> if the control currently allows its
317 <DT><B>SetAllowNegative(bool)</B>
318 <DD>If called with a value of True, this function will cause the
319 control to allow the value to be negative (and reserve space for
320 displaying the sign. If called with a value of False, and the
321 value of the control is currently negative, the value of the
322 control will be converted to the absolute value, and then
323 limited appropriately based on the existing bounds of the control
325 <DT><B>GetAllowNegative()</B>
326 <DT><B>IsNegativeAllowed()</B>
327 <DD>Returns <I>True</I> if the control currently permits values
331 <DT><B>SetGroupDigits(bool)</B>
332 <DD>If called with a value of True, this will make the control
333 automatically add and manage grouping characters to the presented
334 value in integer portion of the control.
335 <DT><B>GetGroupDigits()</B>
336 <DT><B>IsGroupingAllowed()</B>
337 <DD>Returns <I>True</I> if the control is currently set to group digits.
340 <DT><B>SetGroupChar()</B>
341 <DD>Sets the grouping character for the integer portion of the
342 control. (The default grouping character this is ','.
343 <DT><B>GetGroupChar()</B>
344 <DD>Returns the current grouping character for the control.
347 <DT><B>SetSelectOnEntry()</B>
348 <DD>If called with a value of <I>True</I>, this will make the control
349 automatically select the contents of each field as it is entered
350 within the control. (The default is True.)
351 <DT><B>GetSelectOnEntry()</B>
352 <DD>Returns <I>True</I> if the control currently auto selects
353 the field values on entry.
366 from sys
import maxint
367 MAXINT
= maxint
# (constants should be in upper case)
370 from wx
.tools
.dbg
import Logger
371 from wx
.lib
.maskededit
import MaskedEditMixin
, MaskedTextCtrl
, Field
376 #----------------------------------------------------------------------------
378 wxEVT_COMMAND_MASKED_NUMBER_UPDATED
= wx
.NewEventType()
379 EVT_MASKEDNUM
= wx
.PyEventBinder(wxEVT_COMMAND_MASKED_NUMBER_UPDATED
, 1)
381 #----------------------------------------------------------------------------
383 class MaskedNumNumberUpdatedEvent(wx
.PyCommandEvent
):
384 def __init__(self
, id, value
= 0, object=None):
385 wx
.PyCommandEvent
.__init
__(self
, wxEVT_COMMAND_MASKED_NUMBER_UPDATED
, id)
388 self
.SetEventObject(object)
391 """Retrieve the value of the control at the time
392 this event was generated."""
396 #----------------------------------------------------------------------------
398 class MaskedNumCtrl(MaskedTextCtrl
):
400 valid_ctrl_params
= {
401 'integerWidth': 10, # by default allow all 32-bit integers
402 'fractionWidth': 0, # by default, use integers
403 'decimalChar': '.', # by default, use '.' for decimal point
404 'allowNegative': True, # by default, allow negative numbers
405 'useParensForNegatives': False, # by default, use '-' to indicate negatives
406 'groupDigits': True, # by default, don't insert grouping
407 'groupChar': ',', # by default, use ',' for grouping
408 'min': None, # by default, no bounds set
410 'limited': False, # by default, no limiting even if bounds set
411 'allowNone': False, # by default, don't allow empty value
412 'selectOnEntry': True, # by default, select the value of each field on entry
413 'foregroundColour': "Black",
414 'signedForegroundColour': "Red",
415 'emptyBackgroundColour': "White",
416 'validBackgroundColour': "White",
417 'invalidBackgroundColour': "Yellow",
418 'useFixedWidthFont': True, # by default, use a fixed-width font
423 self
, parent
, id=-1, value
= 0,
424 pos
= wx
.DefaultPosition
, size
= wx
.DefaultSize
,
425 style
= wx
.TE_PROCESS_TAB
, validator
= wx
.DefaultValidator
,
429 dbg('MaskedNumCtrl::__init__', indent
=1)
431 # Set defaults for control:
432 dbg('setting defaults:')
433 for key
, param_value
in MaskedNumCtrl
.valid_ctrl_params
.items():
434 # This is done this way to make setattr behave consistently with
435 # "private attribute" name mangling
436 setattr(self
, '_' + key
, copy
.copy(param_value
))
438 # Assign defaults for all attributes:
439 init_args
= copy
.deepcopy(MaskedNumCtrl
.valid_ctrl_params
)
440 dbg('kwargs:', kwargs
)
441 for key
, param_value
in kwargs
.items():
442 key
= key
.replace('Color', 'Colour')
443 if key
not in MaskedNumCtrl
.valid_ctrl_params
.keys():
444 raise AttributeError('invalid keyword argument "%s"' % key
)
446 init_args
[key
] = param_value
447 dbg('init_args:', indent
=1)
448 for key
, param_value
in init_args
.items():
449 dbg('%s:' % key
, param_value
)
452 # Process initial fields for the control, as part of construction:
453 if type(init_args
['integerWidth']) != types
.IntType
:
454 raise AttributeError('invalid integerWidth (%s) specified; expected integer' % repr(init_args
['integerWidth']))
455 elif init_args
['integerWidth'] < 1:
456 raise AttributeError('invalid integerWidth (%s) specified; must be > 0' % repr(init_args
['integerWidth']))
460 if init_args
.has_key('fractionWidth'):
461 if type(init_args
['fractionWidth']) != types
.IntType
:
462 raise AttributeError('invalid fractionWidth (%s) specified; expected integer' % repr(self
._fractionWidth
))
463 elif init_args
['fractionWidth'] < 0:
464 raise AttributeError('invalid fractionWidth (%s) specified; must be >= 0' % repr(init_args
['fractionWidth']))
465 self
._fractionWidth
= init_args
['fractionWidth']
467 if self
._fractionWidth
:
468 fracmask
= '.' + '#{%d}' % self
._fractionWidth
469 dbg('fracmask:', fracmask
)
470 fields
[1] = Field(defaultValue
='0'*self
._fractionWidth
)
474 self
._integerWidth
= init_args
['integerWidth']
475 if init_args
['groupDigits']:
476 self
._groupSpace
= (self
._integerWidth
- 1) / 3
479 intmask
= '#{%d}' % (self
._integerWidth
+ self
._groupSpace
)
480 if self
._fractionWidth
:
484 fields
[0] = Field(formatcodes
='r<>', emptyInvalid
=emptyInvalid
)
485 dbg('intmask:', intmask
)
487 # don't bother to reprocess these arguments:
488 del init_args
['integerWidth']
489 del init_args
['fractionWidth']
492 mask
= intmask
+fracmask
494 # initial value of state vars
497 self
._typedSign
= False
499 # Construct the base control:
500 MaskedTextCtrl
.__init
__(
501 self
, parent
, id, '',
502 pos
, size
, style
, validator
, name
,
506 validFunc
=self
.IsInBounds
,
507 setupEventHandling
= False)
509 self
.Bind(wx
.EVT_SET_FOCUS
, self
._OnFocus
) ## defeat automatic full selection
510 self
.Bind(wx
.EVT_KILL_FOCUS
, self
._OnKillFocus
) ## run internal validator
511 self
.Bind(wx
.EVT_LEFT_DCLICK
, self
._OnDoubleClick
) ## select field under cursor on dclick
512 self
.Bind(wx
.EVT_RIGHT_UP
, self
._OnContextMenu
) ## bring up an appropriate context menu
513 self
.Bind(wx
.EVT_KEY_DOWN
, self
._OnKeyDown
) ## capture control events not normally seen, eg ctrl-tab.
514 self
.Bind(wx
.EVT_CHAR
, self
._OnChar
) ## handle each keypress
515 self
.Bind(wx
.EVT_TEXT
, self
.OnTextChange
) ## color control appropriately & keep
516 ## track of previous value for undo
518 # Establish any additional parameters, with appropriate error checking
519 self
.SetParameters(**init_args
)
521 # Set the value requested (if possible)
522 ## wxCallAfter(self.SetValue, value)
525 # Ensure proper coloring:
527 dbg('finished MaskedNumCtrl::__init__', indent
=0)
530 def SetParameters(self
, **kwargs
):
532 This routine is used to initialize and reconfigure the control:
534 dbg('MaskedNumCtrl::SetParameters', indent
=1)
535 maskededit_kwargs
= {}
536 reset_fraction_width
= False
539 if( (kwargs
.has_key('integerWidth') and kwargs
['integerWidth'] != self
._integerWidth
)
540 or (kwargs
.has_key('fractionWidth') and kwargs
['fractionWidth'] != self
._fractionWidth
)
541 or (kwargs
.has_key('groupDigits') and kwargs
['groupDigits'] != self
._groupDigits
) ):
545 if kwargs
.has_key('fractionWidth'):
546 if type(kwargs
['fractionWidth']) != types
.IntType
:
547 raise AttributeError('invalid fractionWidth (%s) specified; expected integer' % repr(kwargs
['fractionWidth']))
548 elif kwargs
['fractionWidth'] < 0:
549 raise AttributeError('invalid fractionWidth (%s) specified; must be >= 0' % repr(kwargs
['fractionWidth']))
551 if self
._fractionWidth
!= kwargs
['fractionWidth']:
552 self
._fractionWidth
= kwargs
['fractionWidth']
554 if self
._fractionWidth
:
555 fracmask
= '.' + '#{%d}' % self
._fractionWidth
556 fields
[1] = Field(defaultValue
='0'*self
._fractionWidth
)
561 dbg('fracmask:', fracmask
)
563 if kwargs
.has_key('integerWidth'):
564 if type(kwargs
['integerWidth']) != types
.IntType
:
566 raise AttributeError('invalid integerWidth (%s) specified; expected integer' % repr(kwargs
['integerWidth']))
567 elif kwargs
['integerWidth'] < 0:
569 raise AttributeError('invalid integerWidth (%s) specified; must be > 0' % repr(kwargs
['integerWidth']))
571 self
._integerWidth
= kwargs
['integerWidth']
573 if kwargs
.has_key('groupDigits'):
574 self
._groupDigits
= kwargs
['groupDigits']
576 if self
._groupDigits
:
577 self
._groupSpace
= (self
._integerWidth
- 1) / 3
581 intmask
= '#{%d}' % (self
._integerWidth
+ self
._groupSpace
)
582 dbg('intmask:', intmask
)
583 fields
[0] = Field(formatcodes
='r<>', emptyInvalid
=emptyInvalid
)
584 maskededit_kwargs
['fields'] = fields
586 # don't bother to reprocess these arguments:
587 if kwargs
.has_key('integerWidth'):
588 del kwargs
['integerWidth']
589 if kwargs
.has_key('fractionWidth'):
590 del kwargs
['fractionWidth']
592 maskededit_kwargs
['mask'] = intmask
+fracmask
594 if kwargs
.has_key('groupChar'):
595 old_groupchar
= self
._groupChar
# save so we can reformat properly
596 dbg("old_groupchar: '%s'" % old_groupchar
)
597 maskededit_kwargs
['groupChar'] = kwargs
['groupChar']
598 if kwargs
.has_key('decimalChar'):
599 old_decimalchar
= self
._decimalChar
600 dbg("old_decimalchar: '%s'" % old_decimalchar
)
601 maskededit_kwargs
['decimalChar'] = kwargs
['decimalChar']
603 # for all other parameters, assign keyword args as appropriate:
604 for key
, param_value
in kwargs
.items():
605 key
= key
.replace('Color', 'Colour')
606 if key
not in MaskedNumCtrl
.valid_ctrl_params
.keys():
607 raise AttributeError('invalid keyword argument "%s"' % key
)
608 elif key
not in MaskedEditMixin
.valid_ctrl_params
.keys():
609 setattr(self
, '_' + key
, param_value
)
610 elif key
in ('mask', 'autoformat'): # disallow explicit setting of mask
611 raise AttributeError('invalid keyword argument "%s"' % key
)
613 maskededit_kwargs
[key
] = param_value
614 dbg('kwargs:', kwargs
)
616 # reprocess existing format codes to ensure proper resulting format:
617 formatcodes
= self
.GetFormatcodes()
618 if kwargs
.has_key('allowNegative'):
619 if kwargs
['allowNegative'] and '-' not in formatcodes
:
621 maskededit_kwargs
['formatcodes'] = formatcodes
622 elif not kwargs
['allowNegative'] and '-' in formatcodes
:
623 formatcodes
= formatcodes
.replace('-','')
624 maskededit_kwargs
['formatcodes'] = formatcodes
626 if kwargs
.has_key('groupDigits'):
627 if kwargs
['groupDigits'] and ',' not in formatcodes
:
629 maskededit_kwargs
['formatcodes'] = formatcodes
630 elif not kwargs
['groupDigits'] and ',' in formatcodes
:
631 formatcodes
= formatcodes
.replace(',','')
632 maskededit_kwargs
['formatcodes'] = formatcodes
634 if kwargs
.has_key('selectOnEntry'):
635 self
._selectOnEntry
= kwargs
['selectOnEntry']
636 dbg("kwargs['selectOnEntry']?", kwargs
['selectOnEntry'], "'S' in formatcodes?", 'S' in formatcodes
)
637 if kwargs
['selectOnEntry'] and 'S' not in formatcodes
:
639 maskededit_kwargs
['formatcodes'] = formatcodes
640 elif not kwargs
['selectOnEntry'] and 'S' in formatcodes
:
641 formatcodes
= formatcodes
.replace('S','')
642 maskededit_kwargs
['formatcodes'] = formatcodes
644 if 'r' in formatcodes
and self
._fractionWidth
:
645 # top-level mask should only be right insert if no fractional
646 # part will be shown; ie. if reconfiguring control, remove
647 # previous "global" setting.
648 formatcodes
= formatcodes
.replace('r', '')
649 maskededit_kwargs
['formatcodes'] = formatcodes
651 if kwargs
.has_key('limited'):
652 if kwargs
['limited'] and not self
._limited
:
653 maskededit_kwargs
['validRequired'] = True
654 elif not kwargs
['limited'] and self
._limited
:
655 maskededit_kwargs
['validRequired'] = False
656 self
._limited
= kwargs
['limited']
658 dbg('maskededit_kwargs:', maskededit_kwargs
)
659 if maskededit_kwargs
.keys():
660 self
.SetCtrlParameters(**maskededit_kwargs
)
662 # Record end of integer and place cursor there:
663 integerEnd
= self
._fields
[0]._extent
[1]
664 self
.SetInsertionPoint(integerEnd
)
665 self
.SetSelection(integerEnd
, integerEnd
)
667 # Go ensure all the format codes necessary are present:
668 orig_intformat
= intformat
= self
.GetFieldParameter(0, 'formatcodes')
669 if 'r' not in intformat
:
671 if '>' not in intformat
:
673 if intformat
!= orig_intformat
:
674 if self
._fractionWidth
:
675 self
.SetFieldParameters(0, formatcodes
=intformat
)
677 self
.SetCtrlParameters(formatcodes
=intformat
)
679 # Set min and max as appropriate:
680 if kwargs
.has_key('min'):
682 if( self
._max
is None
684 or (self
._max
is not None and self
._max
>= min) ):
688 textmin
= self
._toGUI
(min, apply_limits
= False)
690 dbg('min will not fit into control; ignoring', indent
=0)
698 if kwargs
.has_key('max'):
700 if( self
._min
is None
702 or (self
._min
is not None and self
._min
<= max) ):
706 textmax
= self
._toGUI
(max, apply_limits
= False)
708 dbg('max will not fit into control; ignoring', indent
=0)
715 if kwargs
.has_key('allowNegative'):
716 self
._allowNegative
= kwargs
['allowNegative']
718 # Ensure current value of control obeys any new restrictions imposed:
719 text
= self
._GetValue
()
720 dbg('text value: "%s"' % text
)
721 if kwargs
.has_key('groupChar') and text
.find(old_groupchar
) != -1:
722 text
= text
.replace(old_groupchar
, self
._groupChar
)
723 if kwargs
.has_key('decimalChar') and text
.find(old_decimalchar
) != -1:
724 text
= text
.replace(old_decimalchar
, self
._decimalChar
)
725 if text
!= self
._GetValue
():
726 wx
.TextCtrl
.SetValue(self
, text
)
728 value
= self
.GetValue()
730 dbg('self._allowNegative?', self
._allowNegative
)
731 if not self
._allowNegative
and self
._isNeg
:
733 dbg('abs(value):', value
)
736 elif not self
._allowNone
and MaskedTextCtrl
.GetValue(self
) == '':
742 sel_start
, sel_to
= self
.GetSelection()
743 if self
.IsLimited() and self
._min
is not None and value
< self
._min
:
744 dbg('Set to min value:', self
._min
)
745 self
._SetValue
(self
._toGUI
(self
._min
))
747 elif self
.IsLimited() and self
._max
is not None and value
> self
._max
:
748 dbg('Setting to max value:', self
._max
)
749 self
._SetValue
(self
._toGUI
(self
._max
))
751 # reformat current value as appropriate to possibly new conditions
752 dbg('Reformatting value:', value
)
753 sel_start
, sel_to
= self
.GetSelection()
754 self
._SetValue
(self
._toGUI
(value
))
755 self
.Refresh() # recolor as appropriate
756 dbg('finished MaskedNumCtrl::SetParameters', indent
=0)
760 def _GetNumValue(self
, value
):
762 This function attempts to "clean up" a text value, providing a regularized
763 convertable string, via atol() or atof(), for any well-formed numeric text value.
765 return value
.replace(self
._groupChar
, '').replace(self
._decimalChar
, '.').replace('(', '-').replace(')','').strip()
768 def GetFraction(self
, candidate
=None):
770 Returns the fractional portion of the value as a float. If there is no
771 fractional portion, the value returned will be 0.0.
773 if not self
._fractionWidth
:
776 fracstart
, fracend
= self
._fields
[1]._extent
777 if candidate
is None:
778 value
= self
._toGUI
(MaskedTextCtrl
.GetValue(self
))
780 value
= self
._toGUI
(candidate
)
781 fracstring
= value
[fracstart
:fracend
].strip()
785 return string
.atof(fracstring
)
787 def _OnChangeSign(self
, event
):
788 dbg('MaskedNumCtrl::_OnChangeSign', indent
=1)
789 self
._typedSign
= True
790 MaskedEditMixin
._OnChangeSign
(self
, event
)
794 def _disallowValue(self
):
795 dbg('MaskedNumCtrl::_disallowValue')
796 # limited and -1 is out of bounds
799 if not wx
.Validator_IsSilent():
801 sel_start
, sel_to
= self
._GetSelection
()
802 dbg('queuing reselection of (%d, %d)' % (sel_start
, sel_to
))
803 wx
.CallAfter(self
.SetInsertionPoint
, sel_start
) # preserve current selection/position
804 wx
.CallAfter(self
.SetSelection
, sel_start
, sel_to
)
806 def _SetValue(self
, value
):
808 This routine supersedes the base masked control _SetValue(). It is
809 needed to ensure that the value of the control is always representable/convertable
810 to a numeric return value (via GetValue().) This routine also handles
811 automatic adjustment and grouping of the value without explicit intervention
815 dbg('MaskedNumCtrl::_SetValue("%s")' % value
, indent
=1)
817 if( (self
._fractionWidth
and value
.find(self
._decimalChar
) == -1) or
818 (self
._fractionWidth
== 0 and value
.find(self
._decimalChar
) != -1) ) :
819 value
= self
._toGUI
(value
)
821 numvalue
= self
._GetNumValue
(value
)
822 dbg('cleansed value: "%s"' % numvalue
)
827 dbg('calling base MaskedTextCtrl._SetValue(self, "%s")' % value
)
828 MaskedTextCtrl
._SetValue
(self
, value
)
831 elif self
._min
> 0 and self
.IsLimited():
832 replacement
= self
._min
835 dbg('empty value; setting replacement:', replacement
)
837 if replacement
is None:
838 # Go get the integer portion about to be set and verify its validity
839 intstart
, intend
= self
._fields
[0]._extent
840 dbg('intstart, intend:', intstart
, intend
)
841 dbg('raw integer:"%s"' % value
[intstart
:intend
])
842 int = self
._GetNumValue
(value
[intstart
:intend
])
843 numval
= self
._fromGUI
(value
)
845 dbg('integer: "%s"' % int)
847 fracval
= self
.GetFraction(value
)
848 except ValueError, e
:
849 dbg('Exception:', e
, 'must be out of bounds; disallow value')
850 self
._disallowValue
()
855 dbg('self._isNeg?', self
._isNeg
)
856 if int == '-' and self
._oldvalue
< 0 and not self
._typedSign
:
857 dbg('just a negative sign; old value < 0; setting replacement of 0')
860 elif int[:2] == '-0' and self
._fractionWidth
== 0:
861 if self
._oldvalue
< 0:
862 dbg('-0; setting replacement of 0')
865 elif not self
._limited
or (self
._min
< -1 and self
._max
>= -1):
866 dbg('-0; setting replacement of -1')
870 # limited and -1 is out of bounds
871 self
._disallowValue
()
875 elif int == '-' and (self
._oldvalue
>= 0 or self
._typedSign
) and self
._fractionWidth
== 0:
876 if not self
._limited
or (self
._min
< -1 and self
._max
>= -1):
877 dbg('just a negative sign; setting replacement of -1')
880 # limited and -1 is out of bounds
881 self
._disallowValue
()
885 elif( self
._typedSign
886 and int.find('-') != -1
888 and not self
._min
<= numval
<= self
._max
):
889 # changed sign resulting in value that's now out-of-bounds;
891 self
._disallowValue
()
895 if replacement
is None:
896 if int and int != '-':
900 # integer requested is not legal. This can happen if the user
901 # is attempting to insert a digit in the middle of the control
902 # resulting in something like " 3 45". Disallow such actions:
903 dbg('>>>>>>>>>>>>>>>> "%s" does not convert to a long!' % int)
904 if not wx
.Validator_IsSilent():
906 sel_start
, sel_to
= self
._GetSelection
()
907 dbg('queuing reselection of (%d, %d)' % (sel_start
, sel_to
))
908 wx
.CallAfter(self
.SetInsertionPoint
, sel_start
) # preserve current selection/position
909 wx
.CallAfter(self
.SetSelection
, sel_start
, sel_to
)
913 if int[0] == '0' and len(int) > 1:
914 dbg('numvalue: "%s"' % numvalue
.replace(' ', ''))
915 if self
._fractionWidth
:
916 value
= self
._toGUI
(string
.atof(numvalue
))
918 value
= self
._toGUI
(string
.atol(numvalue
))
919 dbg('modified value: "%s"' % value
)
921 self
._typedSign
= False # reset state var
923 if replacement
is not None:
924 # Value presented wasn't a legal number, but control should do something
925 # reasonable instead:
926 dbg('setting replacement value:', replacement
)
927 self
._SetValue
(self
._toGUI
(replacement
))
928 sel_start
= MaskedTextCtrl
.GetValue(self
).find(str(abs(replacement
))) # find where it put the 1, so we can select it
929 sel_to
= sel_start
+ len(str(abs(replacement
)))
930 dbg('queuing selection of (%d, %d)' %(sel_start
, sel_to
))
931 wx
.CallAfter(self
.SetInsertionPoint
, sel_start
)
932 wx
.CallAfter(self
.SetSelection
, sel_start
, sel_to
)
936 # Otherwise, apply appropriate formatting to value:
938 # Because we're intercepting the value and adjusting it
939 # before a sign change is detected, we need to do this here:
940 if '-' in value
or '(' in value
:
945 dbg('value:"%s"' % value
, 'self._useParens:', self
._useParens
)
946 if self
._fractionWidth
:
947 adjvalue
= self
._adjustFloat
(self
._GetNumValue
(value
).replace('.',self
._decimalChar
))
949 adjvalue
= self
._adjustInt
(self
._GetNumValue
(value
))
950 dbg('adjusted value: "%s"' % adjvalue
)
953 sel_start
, sel_to
= self
._GetSelection
() # record current insertion point
954 dbg('calling base MaskedTextCtrl._SetValue(self, "%s")' % adjvalue
)
955 MaskedTextCtrl
._SetValue
(self
, adjvalue
)
956 # After all actions so far scheduled, check that resulting cursor
957 # position is appropriate, and move if not:
958 wx
.CallAfter(self
._CheckInsertionPoint
)
960 dbg('finished MaskedNumCtrl::_SetValue', indent
=0)
962 def _CheckInsertionPoint(self
):
963 # If current insertion point is before the end of the integer and
964 # its before the 1st digit, place it just after the sign position:
965 dbg('MaskedNumCtrl::CheckInsertionPoint', indent
=1)
966 sel_start
, sel_to
= self
._GetSelection
()
967 text
= self
._GetValue
()
968 if sel_to
< self
._fields
[0]._extent
[1] and text
[sel_to
] in (' ', '-', '('):
969 text
, signpos
, right_signpos
= self
._getSignedValue
()
970 dbg('setting selection(%d, %d)' % (signpos
+1, signpos
+1))
971 self
.SetInsertionPoint(signpos
+1)
972 self
.SetSelection(signpos
+1, signpos
+1)
976 def _OnErase( self
, event
):
978 This overrides the base control _OnErase, so that erasing around
979 grouping characters auto selects the digit before or after the
980 grouping character, so that the erasure does the right thing.
982 dbg('MaskedNumCtrl::_OnErase', indent
=1)
984 #if grouping digits, make sure deletes next to group char always
985 # delete next digit to appropriate side:
986 if self
._groupDigits
:
987 key
= event
.GetKeyCode()
988 value
= MaskedTextCtrl
.GetValue(self
)
989 sel_start
, sel_to
= self
._GetSelection
()
991 if key
== wx
.WXK_BACK
:
992 # if 1st selected char is group char, select to previous digit
993 if sel_start
> 0 and sel_start
< len(self
._mask
) and value
[sel_start
:sel_to
] == self
._groupChar
:
994 self
.SetInsertionPoint(sel_start
-1)
995 self
.SetSelection(sel_start
-1, sel_to
)
997 # elif previous char is group char, select to previous digit
998 elif sel_start
> 1 and sel_start
== sel_to
and value
[sel_start
-1:sel_start
] == self
._groupChar
:
999 self
.SetInsertionPoint(sel_start
-2)
1000 self
.SetSelection(sel_start
-2, sel_to
)
1002 elif key
== wx
.WXK_DELETE
:
1003 if( sel_to
< len(self
._mask
) - 2 + (1 *self
._useParens
)
1004 and sel_start
== sel_to
1005 and value
[sel_to
] == self
._groupChar
):
1006 self
.SetInsertionPoint(sel_start
)
1007 self
.SetSelection(sel_start
, sel_to
+2)
1009 elif( sel_to
< len(self
._mask
) - 2 + (1 *self
._useParens
)
1010 and value
[sel_start
:sel_to
] == self
._groupChar
):
1011 self
.SetInsertionPoint(sel_start
)
1012 self
.SetSelection(sel_start
, sel_to
+1)
1014 MaskedTextCtrl
._OnErase
(self
, event
)
1018 def OnTextChange( self
, event
):
1020 Handles an event indicating that the text control's value
1021 has changed, and issue EVT_MaskedNum event.
1022 NOTE: using wxTextCtrl.SetValue() to change the control's
1023 contents from within a EVT_CHAR handler can cause double
1024 text events. So we check for actual changes to the text
1025 before passing the events on.
1027 dbg('MaskedNumCtrl::OnTextChange', indent
=1)
1028 if not MaskedTextCtrl
._OnTextChange
(self
, event
):
1032 # else... legal value
1034 value
= self
.GetValue()
1035 if value
!= self
._oldvalue
:
1037 self
.GetEventHandler().ProcessEvent(
1038 MaskedNumNumberUpdatedEvent( self
.GetId(), self
.GetValue(), self
) )
1042 # let normal processing of the text continue
1044 self
._oldvalue
= value
# record for next event
1047 def _GetValue(self
):
1049 Override of MaskedTextCtrl to allow amixin to get the raw text value of the
1050 control with this function.
1052 return wx
.TextCtrl
.GetValue(self
)
1057 Returns the current numeric value of the control.
1059 return self
._fromGUI
( MaskedTextCtrl
.GetValue(self
) )
1061 def SetValue(self
, value
):
1063 Sets the value of the control to the value specified.
1064 The resulting actual value of the control may be altered to
1065 conform with the bounds set on the control if limited,
1066 or colored if not limited but the value is out-of-bounds.
1067 A ValueError exception will be raised if an invalid value
1070 MaskedTextCtrl
.SetValue( self
, self
._toGUI
(value
) )
1073 def SetIntegerWidth(self
, value
):
1074 self
.SetCtrlParameters(integerWidth
=value
)
1075 def GetIntegerWidth(self
):
1076 return self
._integerWidth
1078 def SetFractionWidth(self
, value
):
1079 self
.SetCtrlParameters(fractionWidth
=value
)
1080 def GetFractionWidth(self
):
1081 return self
._fractionWidth
1085 def SetMin(self
, min=None):
1087 Sets the minimum value of the control. If a value of None
1088 is provided, then the control will have no explicit minimum value.
1089 If the value specified is greater than the current maximum value,
1090 then the function returns False and the minimum will not change from
1091 its current setting. On success, the function returns True.
1093 If successful and the current value is lower than the new lower
1094 bound, if the control is limited, the value will be automatically
1095 adjusted to the new minimum value; if not limited, the value in the
1096 control will be colored as invalid.
1098 If min > the max value allowed by the width of the control,
1099 the function will return False, and the min will not be set.
1101 dbg('MaskedNumCtrl::SetMin(%s)' % repr(min), indent
=1)
1102 if( self
._max
is None
1104 or (self
._max
is not None and self
._max
>= min) ):
1106 self
.SetParameters(min=min)
1117 Gets the lower bound value of the control. It will return
1118 None if not specified.
1123 def SetMax(self
, max=None):
1125 Sets the maximum value of the control. If a value of None
1126 is provided, then the control will have no explicit maximum value.
1127 If the value specified is less than the current minimum value, then
1128 the function returns False and the maximum will not change from its
1129 current setting. On success, the function returns True.
1131 If successful and the current value is greater than the new upper
1132 bound, if the control is limited the value will be automatically
1133 adjusted to this maximum value; if not limited, the value in the
1134 control will be colored as invalid.
1136 If max > the max value allowed by the width of the control,
1137 the function will return False, and the max will not be set.
1139 if( self
._min
is None
1141 or (self
._min
is not None and self
._min
<= max) ):
1143 self
.SetParameters(max=max)
1155 Gets the maximum value of the control. It will return the current
1156 maximum integer, or None if not specified.
1161 def SetBounds(self
, min=None, max=None):
1163 This function is a convenience function for setting the min and max
1164 values at the same time. The function only applies the maximum bound
1165 if setting the minimum bound is successful, and returns True
1166 only if both operations succeed.
1167 NOTE: leaving out an argument will remove the corresponding bound.
1169 ret
= self
.SetMin(min)
1170 return ret
and self
.SetMax(max)
1173 def GetBounds(self
):
1175 This function returns a two-tuple (min,max), indicating the
1176 current bounds of the control. Each value can be None if
1177 that bound is not set.
1179 return (self
._min
, self
._max
)
1182 def SetLimited(self
, limited
):
1184 If called with a value of True, this function will cause the control
1185 to limit the value to fall within the bounds currently specified.
1186 If the control's value currently exceeds the bounds, it will then
1187 be limited accordingly.
1189 If called with a value of False, this function will disable value
1190 limiting, but coloring of out-of-bounds values will still take
1191 place if bounds have been set for the control.
1193 self
.SetParameters(limited
= limited
)
1196 def IsLimited(self
):
1198 Returns True if the control is currently limiting the
1199 value to fall within the current bounds.
1201 return self
._limited
1203 def GetLimited(self
):
1204 """ (For regularization of property accessors) """
1205 return self
.IsLimited
1208 def IsInBounds(self
, value
=None):
1210 Returns True if no value is specified and the current value
1211 of the control falls within the current bounds. This function can
1212 also be called with a value to see if that value would fall within
1213 the current bounds of the given control.
1215 dbg('IsInBounds(%s)' % repr(value
), indent
=1)
1217 value
= self
.GetValue()
1220 value
= self
._GetNumValue
(self
._toGUI
(value
))
1221 except ValueError, e
:
1222 dbg('error getting NumValue(self._toGUI(value)):', e
, indent
=0)
1226 elif self
._fractionWidth
:
1227 value
= float(value
)
1233 if min is None: min = value
1234 if max is None: max = value
1236 # if bounds set, and value is None, return False
1237 if value
== None and (min is not None or max is not None):
1238 dbg('finished IsInBounds', indent
=0)
1241 dbg('finished IsInBounds', indent
=0)
1242 return min <= value
<= max
1245 def SetAllowNone(self
, allow_none
):
1247 Change the behavior of the validation code, allowing control
1248 to have a value of None or not, as appropriate. If the value
1249 of the control is currently None, and allow_none is False, the
1250 value of the control will be set to the minimum value of the
1251 control, or 0 if no lower bound is set.
1253 self
._allowNone
= allow_none
1254 if not allow_none
and self
.GetValue() is None:
1256 if min is not None: self
.SetValue(min)
1257 else: self
.SetValue(0)
1260 def IsNoneAllowed(self
):
1261 return self
._allowNone
1262 def GetAllowNone(self
):
1263 """ (For regularization of property accessors) """
1264 return self
.IsNoneAllowed()
1266 def SetAllowNegative(self
, value
):
1267 self
.SetParameters(allowNegative
=value
)
1268 def IsNegativeAllowed(self
):
1269 return self
._allowNegative
1270 def GetAllowNegative(self
):
1271 """ (For regularization of property accessors) """
1272 return self
.IsNegativeAllowed()
1274 def SetGroupDigits(self
, value
):
1275 self
.SetParameters(groupDigits
=value
)
1276 def IsGroupingAllowed(self
):
1277 return self
._groupDigits
1278 def GetGroupDigits(self
):
1279 """ (For regularization of property accessors) """
1280 return self
.IsGroupingAllowed()
1282 def SetGroupChar(self
, value
):
1283 self
.SetParameters(groupChar
=value
)
1284 def GetGroupChar(self
):
1285 return self
._groupChar
1287 def SetDecimalChar(self
, value
):
1288 self
.SetParameters(decimalChar
=value
)
1289 def GetDecimalChar(self
):
1290 return self
._decimalChar
1292 def SetSelectOnEntry(self
, value
):
1293 self
.SetParameters(selectOnEntry
=value
)
1294 def GetSelectOnEntry(self
):
1295 return self
._selectOnEntry
1297 # (Other parameter accessors are inherited from base class)
1300 def _toGUI( self
, value
, apply_limits
= True ):
1302 Conversion function used to set the value of the control; does
1303 type and bounds checking and raises ValueError if argument is
1306 dbg('MaskedNumCtrl::_toGUI(%s)' % repr(value
), indent
=1)
1307 if value
is None and self
.IsNoneAllowed():
1309 return self
._template
1311 elif type(value
) in (types
.StringType
, types
.UnicodeType
):
1312 value
= self
._GetNumValue
(value
)
1313 dbg('cleansed num value: "%s"' % value
)
1315 if self
._fractionWidth
or value
.find('.') != -1:
1316 value
= float(value
)
1319 except Exception, e
:
1320 dbg('exception raised:', e
, indent
=0)
1321 raise ValueError ('MaskedNumCtrl requires numeric value, passed %s'% repr(value
) )
1323 elif type(value
) not in (types
.IntType
, types
.LongType
, types
.FloatType
):
1326 'MaskedNumCtrl requires numeric value, passed %s'% repr(value
) )
1328 if not self
._allowNegative
and value
< 0:
1330 'control configured to disallow negative values, passed %s'% repr(value
) )
1332 if self
.IsLimited() and apply_limits
:
1335 if not min is None and value
< min:
1338 'value %d is below minimum value of control'% value
)
1339 if not max is None and value
> max:
1342 'value %d exceeds value of control'% value
)
1344 adjustwidth
= len(self
._mask
) - (1 * self
._useParens
* self
._signOk
)
1345 dbg('len(%s):' % self
._mask
, len(self
._mask
))
1346 dbg('adjustwidth - groupSpace:', adjustwidth
- self
._groupSpace
)
1347 dbg('adjustwidth:', adjustwidth
)
1348 if self
._fractionWidth
== 0:
1349 s
= str(long(value
)).rjust(self
._integerWidth
)
1351 format
= '%' + '%d.%df' % (self
._integerWidth
+self
._fractionWidth
+1, self
._fractionWidth
)
1352 s
= format
% float(value
)
1353 dbg('s:"%s"' % s
, 'len(s):', len(s
))
1354 if len(s
) > (adjustwidth
- self
._groupSpace
):
1356 raise ValueError ('value %s exceeds the integer width of the control (%d)' % (s
, self
._integerWidth
))
1357 elif s
[0] not in ('-', ' ') and self
._allowNegative
and len(s
) == (adjustwidth
- self
._groupSpace
):
1359 raise ValueError ('value %s exceeds the integer width of the control (%d)' % (s
, self
._integerWidth
))
1361 s
= s
.rjust(adjustwidth
).replace('.', self
._decimalChar
)
1362 if self
._signOk
and self
._useParens
:
1363 if s
.find('-') != -1:
1364 s
= s
.replace('-', '(') + ')'
1367 dbg('returned: "%s"' % s
, indent
=0)
1371 def _fromGUI( self
, value
):
1373 Conversion function used in getting the value of the control.
1376 dbg('MaskedNumCtrl::_fromGUI(%s)' % value
, indent
=1)
1377 # One or more of the underlying text control implementations
1378 # issue an intermediate EVT_TEXT when replacing the control's
1379 # value, where the intermediate value is an empty string.
1380 # So, to ensure consistency and to prevent spurious ValueErrors,
1381 # we make the following test, and react accordingly:
1384 if not self
.IsNoneAllowed():
1385 dbg('empty value; not allowed,returning 0', indent
= 0)
1386 if self
._fractionWidth
:
1391 dbg('empty value; returning None', indent
= 0)
1394 value
= self
._GetNumValue
(value
)
1395 dbg('Num value: "%s"' % value
)
1396 if self
._fractionWidth
:
1399 return float( value
)
1401 dbg("couldn't convert to float; returning None")
1412 return long( value
)
1414 dbg("couldn't convert to long; returning None")
1420 dbg('exception occurred; returning None')
1424 def _Paste( self
, value
=None, raise_on_invalid
=False, just_return_value
=False ):
1426 Preprocessor for base control paste; if value needs to be right-justified
1427 to fit in control, do so prior to paste:
1429 dbg('MaskedNumCtrl::_Paste (value = "%s")' % value
)
1431 paste_text
= self
._getClipboardContents
()
1435 # treat paste as "replace number", if appropriate:
1436 sel_start
, sel_to
= self
._GetSelection
()
1437 if sel_start
== sel_to
or self
._selectOnEntry
and (sel_start
, sel_to
) == self
._fields
[0]._extent
:
1438 paste_text
= self
._toGUI
(paste_text
)
1439 self
._SetSelection
(0, len(self
._mask
))
1441 return MaskedEditMixin
._Paste
(self
,
1443 raise_on_invalid
=raise_on_invalid
,
1444 just_return_value
=just_return_value
)
1448 #===========================================================================
1450 if __name__
== '__main__':
1454 class myDialog(wx
.Dialog
):
1455 def __init__(self
, parent
, id, title
,
1456 pos
= wx
.DefaultPosition
, size
= wx
.DefaultSize
,
1457 style
= wx
.DEFAULT_DIALOG_STYLE
):
1458 wx
.Dialog
.__init
__(self
, parent
, id, title
, pos
, size
, style
)
1460 self
.int_ctrl
= MaskedNumCtrl(self
, wx
.NewId(), size
=(55,20))
1461 self
.OK
= wx
.Button( self
, wx
.ID_OK
, "OK")
1462 self
.Cancel
= wx
.Button( self
, wx
.ID_CANCEL
, "Cancel")
1464 vs
= wx
.BoxSizer( wx
.VERTICAL
)
1465 vs
.Add( self
.int_ctrl
, 0, wx
.ALIGN_CENTRE|wx
.ALL
, 5 )
1466 hs
= wx
.BoxSizer( wx
.HORIZONTAL
)
1467 hs
.Add( self
.OK
, 0, wx
.ALIGN_CENTRE|wx
.ALL
, 5 )
1468 hs
.Add( self
.Cancel
, 0, wx
.ALIGN_CENTRE|wx
.ALL
, 5 )
1469 vs
.Add(hs
, 0, wx
.ALIGN_CENTRE|wx
.ALL
, 5 )
1471 self
.SetAutoLayout( True )
1474 vs
.SetSizeHints( self
)
1475 self
.Bind(EVT_MASKEDNUM
, self
.OnChange
, self
.int_ctrl
)
1477 def OnChange(self
, event
):
1478 print 'value now', event
.GetValue()
1480 class TestApp(wx
.App
):
1483 self
.frame
= wx
.Frame(None, -1, "Test", (20,20), (120,100) )
1484 self
.panel
= wx
.Panel(self
.frame
, -1)
1485 button
= wx
.Button(self
.panel
, -1, "Push Me", (20, 20))
1486 self
.Bind(wx
.EVT_BUTTON
, self
.OnClick
, button
)
1488 traceback
.print_exc()
1492 def OnClick(self
, event
):
1493 dlg
= myDialog(self
.panel
, -1, "test MaskedNumCtrl")
1494 dlg
.int_ctrl
.SetValue(501)
1495 dlg
.int_ctrl
.SetInsertionPoint(1)
1496 dlg
.int_ctrl
.SetSelection(1,2)
1497 rc
= dlg
.ShowModal()
1498 print 'final value', dlg
.int_ctrl
.GetValue()
1500 self
.frame
.Destroy()
1503 self
.frame
.Show(True)
1510 traceback
.print_exc()
1514 ## =============================##
1515 ## 1. Add support for printf-style format specification.
1516 ## 2. Add option for repositioning on 'illegal' insertion point.