DirectEntry.py 15 KB

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