DirectEntry.py 15 KB

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