DirectEntry.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. """Contains the DirectEntry class, a type of DirectGUI widget that accepts
  2. text entered using the keyboard."""
  3. __all__ = ['DirectEntry']
  4. from panda3d.core import *
  5. from . import DirectGuiGlobals as DGG
  6. from .DirectFrame import *
  7. from .OnscreenText import OnscreenText
  8. import sys
  9. # import this to make sure it gets pulled into the publish
  10. import encodings.utf_8
  11. from direct.showbase.DirectObject import DirectObject
  12. # DirectEntry States:
  13. ENTRY_FOCUS_STATE = PGEntry.SFocus # 0
  14. ENTRY_NO_FOCUS_STATE = PGEntry.SNoFocus # 1
  15. ENTRY_INACTIVE_STATE = PGEntry.SInactive # 2
  16. class DirectEntry(DirectFrame):
  17. """
  18. DirectEntry(parent) - Create a DirectGuiWidget which responds
  19. to keyboard buttons
  20. """
  21. directWtext = ConfigVariableBool('direct-wtext', 1)
  22. AllowCapNamePrefixes = ("Al", "Ap", "Ben", "De", "Del", "Della", "Delle", "Der", "Di", "Du",
  23. "El", "Fitz", "La", "Las", "Le", "Les", "Lo", "Los",
  24. "Mac", "St", "Te", "Ten", "Van", "Von", )
  25. ForceCapNamePrefixes = ("D'", "DeLa", "Dell'", "L'", "M'", "Mc", "O'", )
  26. def __init__(self, parent = None, **kw):
  27. # Inherits from DirectFrame
  28. # A Direct Frame can have:
  29. # - A background texture (pass in path to image, or Texture Card)
  30. # - A midground geometry item (pass in geometry)
  31. # - A foreground text Node (pass in text string or Onscreen Text)
  32. # For a direct entry:
  33. # Each button has 3 states (focus, noFocus, disabled)
  34. # The same image/geom/text can be used for all three states or each
  35. # state can have a different text/geom/image
  36. # State transitions happen automatically based upon mouse interaction
  37. optiondefs = (
  38. # Define type of DirectGuiWidget
  39. ('pgFunc', PGEntry, None),
  40. ('numStates', 3, None),
  41. ('state', DGG.NORMAL, None),
  42. ('entryFont', None, DGG.INITOPT),
  43. ('width', 10, self.updateWidth),
  44. ('numLines', 1, self.updateNumLines),
  45. ('focus', 0, self.setFocus),
  46. ('cursorKeys', 1, self.setCursorKeysActive),
  47. ('obscured', 0, self.setObscureMode),
  48. # Setting backgroundFocus allows the entry box to get keyboard
  49. # events that are not handled by other things (i.e. events that
  50. # fall through to the background):
  51. ('backgroundFocus', 0, self.setBackgroundFocus),
  52. # Text used for the PGEntry text node
  53. # NOTE: This overrides the DirectFrame text option
  54. ('initialText', '', DGG.INITOPT),
  55. # Command to be called on hitting Enter
  56. ('command', None, None),
  57. ('extraArgs', [], None),
  58. # Command to be called when enter is hit but we fail to submit
  59. ('failedCommand', None, None),
  60. ('failedExtraArgs',[], None),
  61. # commands to be called when focus is gained or lost
  62. ('focusInCommand', None, None),
  63. ('focusInExtraArgs', [], None),
  64. ('focusOutCommand', None, None),
  65. ('focusOutExtraArgs', [], None),
  66. # Sounds to be used for button events
  67. ('rolloverSound', DGG.getDefaultRolloverSound(), self.setRolloverSound),
  68. ('clickSound', DGG.getDefaultClickSound(), self.setClickSound),
  69. ('autoCapitalize', 0, self.autoCapitalizeFunc),
  70. ('autoCapitalizeAllowPrefixes', DirectEntry.AllowCapNamePrefixes, None),
  71. ('autoCapitalizeForcePrefixes', DirectEntry.ForceCapNamePrefixes, None),
  72. )
  73. # Merge keyword options with default options
  74. self.defineoptions(kw, optiondefs)
  75. # Initialize superclasses
  76. DirectFrame.__init__(self, parent)
  77. if self['entryFont'] == None:
  78. font = DGG.getDefaultFont()
  79. else:
  80. font = self['entryFont']
  81. # Create Text Node Component
  82. self.onscreenText = self.createcomponent(
  83. 'text', (), None,
  84. OnscreenText,
  85. (), parent = hidden,
  86. # Pass in empty text to avoid extra work, since its really
  87. # The PGEntry which will use the TextNode to generate geometry
  88. text = '',
  89. align = TextNode.ALeft,
  90. font = font,
  91. scale = 1,
  92. # Don't get rid of the text node
  93. mayChange = 1)
  94. # We can get rid of the node path since we're just using the
  95. # onscreenText as an easy way to access a text node as a
  96. # component
  97. self.onscreenText.removeNode()
  98. # Bind command function
  99. self.bind(DGG.ACCEPT, self.commandFunc)
  100. self.bind(DGG.ACCEPTFAILED, self.failedCommandFunc)
  101. self.accept(self.guiItem.getFocusInEvent(), self.focusInCommandFunc)
  102. self.accept(self.guiItem.getFocusOutEvent(), self.focusOutCommandFunc)
  103. # listen for auto-capitalize events on a separate object to prevent
  104. # clashing with other parts of the system
  105. self._autoCapListener = DirectObject()
  106. # Call option initialization functions
  107. self.initialiseoptions(DirectEntry)
  108. if not hasattr(self, 'autoCapitalizeAllowPrefixes'):
  109. self.autoCapitalizeAllowPrefixes = DirectEntry.AllowCapNamePrefixes
  110. if not hasattr(self, 'autoCapitalizeForcePrefixes'):
  111. self.autoCapitalizeForcePrefixes = DirectEntry.ForceCapNamePrefixes
  112. # Update TextNodes for each state
  113. for i in range(self['numStates']):
  114. self.guiItem.setTextDef(i, self.onscreenText.textNode)
  115. # Now we should call setup() again to make sure it has the
  116. # right font def.
  117. self.setup()
  118. # Update initial text
  119. self.unicodeText = 0
  120. if self['initialText']:
  121. self.enterText(self['initialText'])
  122. def destroy(self):
  123. self.ignoreAll()
  124. self._autoCapListener.ignoreAll()
  125. DirectFrame.destroy(self)
  126. def setup(self):
  127. self.guiItem.setupMinimal(self['width'], self['numLines'])
  128. def updateWidth(self):
  129. self.guiItem.setMaxWidth(self['width'])
  130. def updateNumLines(self):
  131. self.guiItem.setNumLines(self['numLines'])
  132. def setFocus(self):
  133. PGEntry.setFocus(self.guiItem, self['focus'])
  134. def setCursorKeysActive(self):
  135. PGEntry.setCursorKeysActive(self.guiItem, self['cursorKeys'])
  136. def setObscureMode(self):
  137. PGEntry.setObscureMode(self.guiItem, self['obscured'])
  138. def setBackgroundFocus(self):
  139. PGEntry.setBackgroundFocus(self.guiItem, self['backgroundFocus'])
  140. def setRolloverSound(self):
  141. rolloverSound = self['rolloverSound']
  142. if rolloverSound:
  143. self.guiItem.setSound(DGG.ENTER + self.guiId, rolloverSound)
  144. else:
  145. self.guiItem.clearSound(DGG.ENTER + self.guiId)
  146. def setClickSound(self):
  147. clickSound = self['clickSound']
  148. if clickSound:
  149. self.guiItem.setSound(DGG.ACCEPT + self.guiId, clickSound)
  150. else:
  151. self.guiItem.clearSound(DGG.ACCEPT + self.guiId)
  152. def commandFunc(self, event):
  153. if self['command']:
  154. # Pass any extra args to command
  155. self['command'](*[self.get()] + self['extraArgs'])
  156. def failedCommandFunc(self, event):
  157. if self['failedCommand']:
  158. # Pass any extra args
  159. self['failedCommand'](*[self.get()] + self['failedExtraArgs'])
  160. def autoCapitalizeFunc(self):
  161. if self['autoCapitalize']:
  162. self._autoCapListener.accept(self.guiItem.getTypeEvent(), self._handleTyping)
  163. self._autoCapListener.accept(self.guiItem.getEraseEvent(), self._handleErasing)
  164. else:
  165. self._autoCapListener.ignore(self.guiItem.getTypeEvent())
  166. self._autoCapListener.ignore(self.guiItem.getEraseEvent())
  167. def focusInCommandFunc(self):
  168. if self['focusInCommand']:
  169. self['focusInCommand'](*self['focusInExtraArgs'])
  170. if self['autoCapitalize']:
  171. self.accept(self.guiItem.getTypeEvent(), self._handleTyping)
  172. self.accept(self.guiItem.getEraseEvent(), self._handleErasing)
  173. def _handleTyping(self, guiEvent):
  174. self._autoCapitalize()
  175. def _handleErasing(self, guiEvent):
  176. self._autoCapitalize()
  177. def _autoCapitalize(self):
  178. name = self.get().decode('utf-8')
  179. # capitalize each word, allowing for things like McMutton
  180. capName = ''
  181. # track each individual word to detect prefixes like Mc
  182. wordSoFar = ''
  183. # track whether the previous character was part of a word or not
  184. wasNonWordChar = True
  185. for i, character in enumerate(name):
  186. # test to see if we are between words
  187. # - Count characters that can't be capitalized as a break between words
  188. # This assumes that string.lower and string.upper will return different
  189. # values for all unicode letters.
  190. # - Don't count apostrophes as a break between words
  191. if character.lower() == character.upper() and character != "'":
  192. # we are between words
  193. wordSoFar = ''
  194. wasNonWordChar = True
  195. else:
  196. capitalize = False
  197. if wasNonWordChar:
  198. # first letter of a word, capitalize it unconditionally;
  199. capitalize = True
  200. elif (character == character.upper() and
  201. len(self.autoCapitalizeAllowPrefixes) and
  202. wordSoFar in self.autoCapitalizeAllowPrefixes):
  203. # first letter after one of the prefixes, allow it to be capitalized
  204. capitalize = True
  205. elif (len(self.autoCapitalizeForcePrefixes) and
  206. wordSoFar in self.autoCapitalizeForcePrefixes):
  207. # first letter after one of the force prefixes, force it to be capitalized
  208. capitalize = True
  209. if capitalize:
  210. # allow this letter to remain capitalized
  211. character = character.upper()
  212. else:
  213. character = character.lower()
  214. wordSoFar += character
  215. wasNonWordChar = False
  216. capName += character
  217. self.enterText(capName.encode('utf-8'))
  218. def focusOutCommandFunc(self):
  219. if self['focusOutCommand']:
  220. self['focusOutCommand'](*self['focusOutExtraArgs'])
  221. if self['autoCapitalize']:
  222. self.ignore(self.guiItem.getTypeEvent())
  223. self.ignore(self.guiItem.getEraseEvent())
  224. def set(self, text):
  225. """ Changes the text currently showing in the typable region;
  226. does not change the current cursor position. Also see
  227. enterText(). """
  228. if sys.version_info >= (3, 0):
  229. assert not isinstance(text, bytes)
  230. self.unicodeText = True
  231. self.guiItem.setWtext(text)
  232. else:
  233. self.unicodeText = isinstance(text, unicode)
  234. if self.unicodeText:
  235. self.guiItem.setWtext(text)
  236. else:
  237. self.guiItem.setText(text)
  238. def get(self, plain = False):
  239. """ Returns the text currently showing in the typable region.
  240. If plain is True, the returned text will not include any
  241. formatting characters like nested color-change codes. """
  242. wantWide = self.unicodeText or self.guiItem.isWtext()
  243. if not self.directWtext.getValue():
  244. # If the user has configured wide-text off, then always
  245. # return an 8-bit string. This will be encoded if
  246. # necessary, according to Panda's default encoding.
  247. wantWide = False
  248. if plain:
  249. if wantWide:
  250. return self.guiItem.getPlainWtext()
  251. else:
  252. return self.guiItem.getPlainText()
  253. else:
  254. if wantWide:
  255. return self.guiItem.getWtext()
  256. else:
  257. return self.guiItem.getText()
  258. def setCursorPosition(self, pos):
  259. if (pos < 0):
  260. self.guiItem.setCursorPosition(self.guiItem.getNumCharacters() + pos)
  261. else:
  262. self.guiItem.setCursorPosition(pos)
  263. def enterText(self, text):
  264. """ sets the entry's text, and moves the cursor to the end """
  265. self.set(text)
  266. self.setCursorPosition(self.guiItem.getNumCharacters())
  267. def getFont(self):
  268. return self.onscreenText.getFont()
  269. def getBounds(self, state = 0):
  270. # Compute the width and height for the entry itself, ignoring
  271. # geometry etc.
  272. tn = self.onscreenText.textNode
  273. mat = tn.getTransform()
  274. align = tn.getAlign()
  275. lineHeight = tn.getLineHeight()
  276. numLines = self['numLines']
  277. width = self['width']
  278. if align == TextNode.ALeft:
  279. left = 0.0
  280. right = width
  281. elif align == TextNode.ACenter:
  282. left = -width / 2.0
  283. right = width / 2.0
  284. elif align == TextNode.ARight:
  285. left = -width
  286. right = 0.0
  287. bottom = -0.3 * lineHeight - (lineHeight * (numLines - 1))
  288. top = lineHeight
  289. self.ll.set(left, 0.0, bottom)
  290. self.ur.set(right, 0.0, top)
  291. self.ll = mat.xformPoint(Point3.rfu(left, 0.0, bottom))
  292. self.ur = mat.xformPoint(Point3.rfu(right, 0.0, top))
  293. vec_right = Vec3.right()
  294. vec_up = Vec3.up()
  295. left = (vec_right[0] * self.ll[0]
  296. + vec_right[1] * self.ll[1]
  297. + vec_right[2] * self.ll[2])
  298. right = (vec_right[0] * self.ur[0]
  299. + vec_right[1] * self.ur[1]
  300. + vec_right[2] * self.ur[2])
  301. bottom = (vec_up[0] * self.ll[0]
  302. + vec_up[1] * self.ll[1]
  303. + vec_up[2] * self.ll[2])
  304. top = (vec_up[0] * self.ur[0]
  305. + vec_up[1] * self.ur[1]
  306. + vec_up[2] * self.ur[2])
  307. self.ll = Point3(left, 0.0, bottom)
  308. self.ur = Point3(right, 0.0, top)
  309. # Scale bounds to give a pad around graphics. We also want to
  310. # scale around the border width.
  311. pad = self['pad']
  312. borderWidth = self['borderWidth']
  313. self.bounds = [self.ll[0] - pad[0] - borderWidth[0],
  314. self.ur[0] + pad[0] + borderWidth[0],
  315. self.ll[2] - pad[1] - borderWidth[1],
  316. self.ur[2] + pad[1] + borderWidth[1]]
  317. return self.bounds