PageRenderTime 58ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/env/Lib/site-packages/wx-2.8-msw-unicode/wx/lib/masked/ipaddrctrl.py

https://bitbucket.org/beqa/nvdadependencyvirtualenvironment
Python | 220 lines | 198 code | 0 blank | 22 comment | 1 complexity | ccc933817c6cdbe038de4398d7530947 MD5 | raw file
  1. #----------------------------------------------------------------------------
  2. # Name: masked.ipaddrctrl.py
  3. # Authors: Will Sadkin
  4. # Email: wsadkin@nameconnector.com
  5. # Created: 02/11/2003
  6. # Copyright: (c) 2003 by Will Sadkin, 2003
  7. # RCS-ID: $Id: ipaddrctrl.py 29787 2004-10-11 22:13:18Z RD $
  8. # License: wxWidgets license
  9. #----------------------------------------------------------------------------
  10. # NOTE:
  11. # Masked.IpAddrCtrl is a minor modification to masked.TextCtrl, that is
  12. # specifically tailored for entering IP addresses. It allows for
  13. # right-insert fields and provides an accessor to obtain the entered
  14. # address with extra whitespace removed.
  15. #
  16. #----------------------------------------------------------------------------
  17. """
  18. Provides a smart text input control that understands the structure and
  19. limits of IP Addresses, and allows automatic field navigation as the
  20. user hits '.' when typing.
  21. """
  22. import wx, types, string
  23. from wx.lib.masked import BaseMaskedTextCtrl
  24. # jmg 12/9/03 - when we cut ties with Py 2.2 and earlier, this would
  25. # be a good place to implement the 2.3 logger class
  26. from wx.tools.dbg import Logger
  27. ##dbg = Logger()
  28. ##dbg(enable=0)
  29. class IpAddrCtrlAccessorsMixin:
  30. """
  31. Defines IpAddrCtrl's list of attributes having their own
  32. Get/Set functions, exposing only those that make sense for
  33. an IP address control.
  34. """
  35. exposed_basectrl_params = (
  36. 'fields',
  37. 'retainFieldValidation',
  38. 'formatcodes',
  39. 'fillChar',
  40. 'defaultValue',
  41. 'description',
  42. 'useFixedWidthFont',
  43. 'signedForegroundColour',
  44. 'emptyBackgroundColour',
  45. 'validBackgroundColour',
  46. 'invalidBackgroundColour',
  47. 'emptyInvalid',
  48. 'validFunc',
  49. 'validRequired',
  50. )
  51. for param in exposed_basectrl_params:
  52. propname = param[0].upper() + param[1:]
  53. exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))
  54. exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
  55. if param.find('Colour') != -1:
  56. # add non-british spellings, for backward-compatibility
  57. propname.replace('Colour', 'Color')
  58. exec('def Set%s(self, value): self.SetCtrlParameters(%s=value)' % (propname, param))
  59. exec('def Get%s(self): return self.GetCtrlParameter("%s")''' % (propname, param))
  60. class IpAddrCtrl( BaseMaskedTextCtrl, IpAddrCtrlAccessorsMixin ):
  61. """
  62. This class is a particular type of MaskedTextCtrl that accepts
  63. and understands the semantics of IP addresses, reformats input
  64. as you move from field to field, and accepts '.' as a navigation
  65. character, so that typing an IP address can be done naturally.
  66. """
  67. def __init__( self, parent, id=-1, value = '',
  68. pos = wx.DefaultPosition,
  69. size = wx.DefaultSize,
  70. style = wx.TE_PROCESS_TAB,
  71. validator = wx.DefaultValidator,
  72. name = 'IpAddrCtrl',
  73. setupEventHandling = True, ## setup event handling by default
  74. **kwargs):
  75. if not kwargs.has_key('mask'):
  76. kwargs['mask'] = mask = "###.###.###.###"
  77. if not kwargs.has_key('formatcodes'):
  78. kwargs['formatcodes'] = 'F_Sr<>'
  79. if not kwargs.has_key('validRegex'):
  80. 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}"
  81. BaseMaskedTextCtrl.__init__(
  82. self, parent, id=id, value = value,
  83. pos=pos, size=size,
  84. style = style,
  85. validator = validator,
  86. name = name,
  87. setupEventHandling = setupEventHandling,
  88. **kwargs)
  89. # set up individual field parameters as well:
  90. field_params = {}
  91. field_params['validRegex'] = "( | \d| \d |\d | \d\d|\d\d |\d \d|(1\d\d|2[0-4]\d|25[0-5]))"
  92. # require "valid" string; this prevents entry of any value > 255, but allows
  93. # intermediate constructions; overall control validation requires well-formatted value.
  94. field_params['formatcodes'] = 'V'
  95. if field_params:
  96. for i in self._field_indices:
  97. self.SetFieldParameters(i, **field_params)
  98. # This makes '.' act like tab:
  99. self._AddNavKey('.', handler=self.OnDot)
  100. self._AddNavKey('>', handler=self.OnDot) # for "shift-."
  101. def OnDot(self, event):
  102. """
  103. Defines what action to take when the '.' character is typed in the
  104. control. By default, the current field is right-justified, and the
  105. cursor is placed in the next field.
  106. """
  107. ## dbg('IpAddrCtrl::OnDot', indent=1)
  108. pos = self._adjustPos(self._GetInsertionPoint(), event.GetKeyCode())
  109. oldvalue = self.GetValue()
  110. edit_start, edit_end, slice = self._FindFieldExtent(pos, getslice=True)
  111. if not event.ShiftDown():
  112. if pos > edit_start and pos < edit_end:
  113. # clip data in field to the right of pos, if adjusting fields
  114. # when not at delimeter; (assumption == they hit '.')
  115. newvalue = oldvalue[:pos] + ' ' * (edit_end - pos) + oldvalue[edit_end:]
  116. self._SetValue(newvalue)
  117. self._SetInsertionPoint(pos)
  118. ## dbg(indent=0)
  119. return self._OnChangeField(event)
  120. def GetAddress(self):
  121. """
  122. Returns the control value, with any spaces removed.
  123. """
  124. value = BaseMaskedTextCtrl.GetValue(self)
  125. return value.replace(' ','') # remove spaces from the value
  126. def _OnCtrl_S(self, event):
  127. ## dbg("IpAddrCtrl::_OnCtrl_S")
  128. if self._demo:
  129. print "value:", self.GetAddress()
  130. return False
  131. def SetValue(self, value):
  132. """
  133. Takes a string value, validates it for a valid IP address,
  134. splits it into an array of 4 fields, justifies it
  135. appropriately, and inserts it into the control.
  136. Invalid values will raise a ValueError exception.
  137. """
  138. ## dbg('IpAddrCtrl::SetValue(%s)' % str(value), indent=1)
  139. if type(value) not in (types.StringType, types.UnicodeType):
  140. ## dbg(indent=0)
  141. raise ValueError('%s must be a string', str(value))
  142. bValid = True # assume True
  143. parts = value.split('.')
  144. if len(parts) != 4:
  145. bValid = False
  146. else:
  147. for i in range(4):
  148. part = parts[i]
  149. if not 0 <= len(part) <= 3:
  150. bValid = False
  151. break
  152. elif part.strip(): # non-empty part
  153. try:
  154. j = string.atoi(part)
  155. if not 0 <= j <= 255:
  156. bValid = False
  157. break
  158. else:
  159. parts[i] = '%3d' % j
  160. except:
  161. bValid = False
  162. break
  163. else:
  164. # allow empty sections for SetValue (will result in "invalid" value,
  165. # but this may be useful for initializing the control:
  166. parts[i] = ' ' # convert empty field to 3-char length
  167. if not bValid:
  168. ## dbg(indent=0)
  169. 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))
  170. else:
  171. ## dbg('parts:', parts)
  172. value = string.join(parts, '.')
  173. BaseMaskedTextCtrl.SetValue(self, value)
  174. ## dbg(indent=0)
  175. __i=0
  176. ## CHANGELOG:
  177. ## ====================
  178. ## Version 1.2
  179. ## 1. Fixed bugs involving missing imports now that these classes are in
  180. ## their own module.
  181. ## 2. Added doc strings for ePyDoc.
  182. ## 3. Renamed helper functions, vars etc. not intended to be visible in public
  183. ## interface to code.
  184. ##
  185. ## Version 1.1
  186. ## Made ipaddrctrls allow right-insert in subfields, now that insert/cut/paste works better