DirectGuiBase.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. """
  2. Base class for all DirectGui items. Handles composite widgets and
  3. command line argument parsing.
  4. Code overview:
  5. 1) Each widget defines a set of options (optiondefs) as a list of tuples
  6. of the form ``('name', defaultValue, handler)``.
  7. 'name' is the name of the option (used during construction of configure)
  8. handler can be: None, method, or INITOPT. If a method is specified, it
  9. will be called during widget construction (via initialiseoptions), if the
  10. Handler is specified as an INITOPT, this is an option that can only be set
  11. during widget construction.
  12. 2) :func:`~DirectGuiBase.defineoptions` is called. defineoption creates:
  13. self._constructorKeywords = { keyword: [value, useFlag] }
  14. A dictionary of the keyword options specified as part of the
  15. constructor keywords can be of the form 'component_option', where
  16. component is the name of a widget's component, a component group or a
  17. component alias.
  18. self._dynamicGroups
  19. A list of group names for which it is permissible to specify options
  20. before components of that group are created.
  21. If a widget is a derived class the order of execution would be::
  22. foo.optiondefs = {}
  23. foo.defineoptions()
  24. fooParent()
  25. fooParent.optiondefs = {}
  26. fooParent.defineoptions()
  27. 3) :func:`~DirectGuiBase.addoptions` is called. This combines options
  28. specified as keywords to the widget constructor (stored in
  29. self._constructorKeywords) with the default options (stored in optiondefs).
  30. Results are stored in
  31. ``self._optionInfo = { keyword: [default, current, handler] }``.
  32. If a keyword is of the form 'component_option' it is left in the
  33. self._constructorKeywords dictionary (for use by component constructors),
  34. otherwise it is 'used', and deleted from self._constructorKeywords.
  35. Notes:
  36. - constructor keywords override the defaults.
  37. - derived class default values override parent class defaults
  38. - derived class handler functions override parent class functions
  39. 4) Superclass initialization methods are called (resulting in nested calls
  40. to define options (see 2 above)
  41. 5) Widget components are created via calls to
  42. :func:`~DirectGuiBase.createcomponent`. User can specify aliases and groups
  43. for each component created.
  44. Aliases are alternate names for components, e.g. a widget may have a
  45. component with a name 'entryField', which itself may have a component
  46. named 'entry', you could add an alias 'entry' for the 'entryField_entry'
  47. These are stored in self.__componentAliases. If an alias is found,
  48. all keyword entries which use that alias are expanded to their full
  49. form (to avoid conversion later)
  50. Groups allow option specifications that apply to all members of the group.
  51. If a widget has components: 'text1', 'text2', and 'text3' which all belong
  52. to the 'text' group, they can be all configured with keywords of the form:
  53. 'text_keyword' (e.g. ``text_font='comic.rgb'``). A component's group
  54. is stored as the fourth element of its entry in self.__componentInfo.
  55. Note: the widget constructors have access to all remaining keywords in
  56. _constructorKeywords (those not transferred to _optionInfo by
  57. define/addoptions). If a component defines an alias that applies to
  58. one of the keywords, that keyword is replaced with a new keyword with
  59. the alias expanded.
  60. If a keyword (or substituted alias keyword) is used during creation of the
  61. component, it is deleted from self._constructorKeywords. If a group
  62. keyword applies to the component, that keyword is marked as used, but is
  63. not deleted from self._constructorKeywords, in case it applies to another
  64. component. If any constructor keywords remain at the end of component
  65. construction (and initialisation), an error is raised.
  66. 5) :func:`~DirectGuiBase.initialiseoptions` is called. This method calls any
  67. option handlers to respond to any keyword/default values, then checks to
  68. see if any keywords are left unused. If so, an error is raised.
  69. """
  70. __all__ = ['DirectGuiBase', 'DirectGuiWidget']
  71. from panda3d.core import (
  72. ConfigVariableBool,
  73. KeyboardButton,
  74. MouseWatcherRegion,
  75. NodePath,
  76. PGFrameStyle,
  77. PGItem,
  78. Point3,
  79. Texture,
  80. Vec3,
  81. )
  82. from direct.showbase import ShowBaseGlobal
  83. from direct.showbase.ShowBase import ShowBase
  84. from direct.showbase.MessengerGlobal import messenger
  85. from . import DirectGuiGlobals as DGG
  86. from direct.directtools.DirectUtil import ROUND_TO
  87. from direct.showbase import DirectObject
  88. from direct.task import Task
  89. from direct.task.TaskManagerGlobal import taskMgr
  90. _track_gui_items = ConfigVariableBool('track-gui-items', False)
  91. class DirectGuiBase(DirectObject.DirectObject):
  92. """Base class of all DirectGUI widgets."""
  93. def __init__(self):
  94. # Default id of all gui object, subclasses should override this
  95. self.guiId = 'guiObject'
  96. # List of all post initialization functions
  97. self.postInitialiseFuncList = []
  98. # To avoid doing things redundantly during initialisation
  99. self.fInit = 1
  100. # Mapping from each megawidget option to a list of information
  101. # about the option
  102. # - default value
  103. # - current value
  104. # - function to call when the option is initialised in the
  105. # call to initialiseoptions() in the constructor or
  106. # modified via configure(). If this is INITOPT, the
  107. # option is an initialisation option (an option that can
  108. # be set by the call to the constructor but can not be
  109. # used with configure).
  110. # This mapping is not initialised here, but in the call to
  111. # defineoptions() which precedes construction of this base class.
  112. #
  113. # self._optionInfo = {}
  114. # Mapping from each component name to a tuple of information
  115. # about the component.
  116. # - component widget instance
  117. # - configure function of widget instance
  118. # - the class of the widget (Frame, EntryField, etc)
  119. # - cget function of widget instance
  120. # - the name of the component group of this component, if any
  121. self.__componentInfo = {}
  122. # Mapping from alias names to the names of components or
  123. # sub-components.
  124. self.__componentAliases = {}
  125. # Contains information about the keywords provided to the
  126. # constructor. It is a mapping from the keyword to a tuple
  127. # containing:
  128. # - value of keyword
  129. # - a boolean indicating if the keyword has been used.
  130. # A keyword is used if, during the construction of a megawidget,
  131. # - it is defined in a call to defineoptions() or addoptions(), or
  132. # - it references, by name, a component of the megawidget, or
  133. # - it references, by group, at least one component
  134. # At the end of megawidget construction, a call is made to
  135. # initialiseoptions() which reports an error if there are
  136. # unused options given to the constructor.
  137. #
  138. # self._constructorKeywords = {}
  139. # List of dynamic component groups. If a group is included in
  140. # this list, then it not an error if a keyword argument for
  141. # the group is given to the constructor or to configure(), but
  142. # no components with this group have been created.
  143. # self._dynamicGroups = ()
  144. def defineoptions(self, keywords, optionDefs, dynamicGroups = ()):
  145. """ defineoptions(keywords, optionDefs, dynamicGroups = {}) """
  146. # Create options, providing the default value and the method
  147. # to call when the value is changed. If any option created by
  148. # base classes has the same name as one in <optionDefs>, the
  149. # base class's value and function will be overriden.
  150. # keywords is a dictionary of keyword/value pairs from the constructor
  151. # optionDefs is a dictionary of default options for the widget
  152. # dynamicGroups is a tuple of component groups for which you can
  153. # specify options even though no components of this group have
  154. # been created
  155. # This should be called before the constructor of the base
  156. # class, so that default values defined in the derived class
  157. # override those in the base class.
  158. if not hasattr(self, '_constructorKeywords'):
  159. tmp = {}
  160. for option, value in keywords.items():
  161. tmp[option] = [value, 0]
  162. self._constructorKeywords = tmp
  163. self._optionInfo = {}
  164. # Initialize dictionary of dynamic groups
  165. if not hasattr(self, '_dynamicGroups'):
  166. self._dynamicGroups = ()
  167. self._dynamicGroups = self._dynamicGroups + tuple(dynamicGroups)
  168. # Reconcile command line and default options
  169. self.addoptions(optionDefs, keywords)
  170. def addoptions(self, optionDefs, optionkeywords):
  171. """ addoptions(optionDefs) - add option def to option info """
  172. # Add additional options, providing the default value and the
  173. # method to call when the value is changed. See
  174. # "defineoptions" for more details
  175. # optimisations:
  176. optionInfo = self._optionInfo
  177. optionInfo_has_key = optionInfo.__contains__
  178. keywords = self._constructorKeywords
  179. keywords_has_key = keywords.__contains__
  180. FUNCTION = DGG._OPT_FUNCTION
  181. for name, default, function in optionDefs:
  182. if '_' not in name:
  183. default = optionkeywords.get(name, default)
  184. # The option will already exist if it has been defined
  185. # in a derived class. In this case, do not override the
  186. # default value of the option or the callback function
  187. # if it is not None.
  188. if not optionInfo_has_key(name):
  189. if keywords_has_key(name):
  190. # Overridden by keyword, use keyword value
  191. value = keywords[name][0]
  192. optionInfo[name] = [default, value, function]
  193. # Delete it from self._constructorKeywords
  194. del keywords[name]
  195. else:
  196. # Use optionDefs value
  197. optionInfo[name] = [default, default, function]
  198. elif optionInfo[name][FUNCTION] is None:
  199. # Only override function if not defined by derived class
  200. optionInfo[name][FUNCTION] = function
  201. else:
  202. # This option is of the form "component_option". If this is
  203. # not already defined in self._constructorKeywords add it.
  204. # This allows a derived class to override the default value
  205. # of an option of a component of a base class.
  206. if not keywords_has_key(name):
  207. keywords[name] = [default, 0]
  208. def initialiseoptions(self, myClass):
  209. """
  210. Call all initialisation functions to initialize widget
  211. options to default of keyword value
  212. """
  213. # This is to make sure this method class is only called by
  214. # the most specific class in the class hierarchy
  215. if self.__class__ is myClass:
  216. # Call the configuration callback function for every option.
  217. FUNCTION = DGG._OPT_FUNCTION
  218. self.fInit = 1
  219. for info in self._optionInfo.values():
  220. func = info[FUNCTION]
  221. if func is not None and func is not DGG.INITOPT:
  222. func()
  223. self.fInit = 0
  224. # Now check if anything is left over
  225. unusedOptions = []
  226. keywords = self._constructorKeywords
  227. for name in keywords:
  228. used = keywords[name][1]
  229. if not used:
  230. # This keyword argument has not been used. If it
  231. # does not refer to a dynamic group, mark it as
  232. # unused.
  233. index = name.find('_')
  234. if index < 0 or name[:index] not in self._dynamicGroups:
  235. unusedOptions.append(name)
  236. self._constructorKeywords = {}
  237. if len(unusedOptions) > 0:
  238. if len(unusedOptions) == 1:
  239. text = 'Unknown option "'
  240. else:
  241. text = 'Unknown options "'
  242. raise KeyError(text + ', '.join(unusedOptions) + \
  243. '" for ' + myClass.__name__)
  244. # Can now call post init func
  245. self.postInitialiseFunc()
  246. def postInitialiseFunc(self):
  247. for func in self.postInitialiseFuncList:
  248. func()
  249. def isinitoption(self, option):
  250. """
  251. Is this opition one that can only be specified at construction?
  252. """
  253. return self._optionInfo[option][DGG._OPT_FUNCTION] is DGG.INITOPT
  254. def options(self):
  255. """
  256. Print out a list of available widget options.
  257. Does not include subcomponent options.
  258. """
  259. options = []
  260. if hasattr(self, '_optionInfo'):
  261. for option, info in self._optionInfo.items():
  262. isinit = info[DGG._OPT_FUNCTION] is DGG.INITOPT
  263. default = info[DGG._OPT_DEFAULT]
  264. options.append((option, default, isinit))
  265. options.sort()
  266. return options
  267. def configure(self, option=None, **kw):
  268. """
  269. configure(option = None)
  270. Query or configure the megawidget options.
  271. """
  272. #
  273. # If not empty, *kw* is a dictionary giving new
  274. # values for some of the options of this gui item
  275. # For options defined for this widget, set
  276. # the value of the option to the new value and call the
  277. # configuration callback function, if any.
  278. #
  279. # If *option* is None, return all gui item configuration
  280. # options and settings. Options are returned as standard 3
  281. # element tuples
  282. #
  283. # If *option* is a string, return the 3 element tuple for the
  284. # given configuration option.
  285. # First, deal with the option queries.
  286. if len(kw) == 0:
  287. # This configure call is querying the values of one or all options.
  288. # Return 3-tuples:
  289. # (optionName, default, value)
  290. if option is None:
  291. rtn = {}
  292. for option, config in self._optionInfo.items():
  293. rtn[option] = (option,
  294. config[DGG._OPT_DEFAULT],
  295. config[DGG._OPT_VALUE])
  296. return rtn
  297. else:
  298. config = self._optionInfo[option]
  299. return (option, config[DGG._OPT_DEFAULT], config[DGG._OPT_VALUE])
  300. # optimizations:
  301. optionInfo = self._optionInfo
  302. optionInfo_has_key = optionInfo.__contains__
  303. componentInfo = self.__componentInfo
  304. componentInfo_has_key = componentInfo.__contains__
  305. componentAliases = self.__componentAliases
  306. componentAliases_has_key = componentAliases.__contains__
  307. VALUE = DGG._OPT_VALUE
  308. FUNCTION = DGG._OPT_FUNCTION
  309. # This will contain a list of options in *kw* which
  310. # are known to this gui item.
  311. directOptions = []
  312. # This will contain information about the options in
  313. # *kw* of the form <component>_<option>, where
  314. # <component> is a component of this megawidget. It is a
  315. # dictionary whose keys are the configure method of each
  316. # component and whose values are a dictionary of options and
  317. # values for the component.
  318. indirectOptions = {}
  319. indirectOptions_has_key = indirectOptions.__contains__
  320. for option, value in kw.items():
  321. if optionInfo_has_key(option):
  322. # This is one of the options of this gui item.
  323. # Check it is an initialisation option.
  324. if optionInfo[option][FUNCTION] is DGG.INITOPT:
  325. print('Cannot configure initialisation option "' \
  326. + option + '" for ' + self.__class__.__name__)
  327. break
  328. #raise KeyError, \
  329. # 'Cannot configure initialisation option "' \
  330. # + option + '" for ' + self.__class__.__name__
  331. optionInfo[option][VALUE] = value
  332. directOptions.append(option)
  333. else:
  334. index = option.find('_')
  335. if index >= 0:
  336. # This option may be of the form <component>_<option>.
  337. # e.g. if alias ('efEntry', 'entryField_entry')
  338. # and option = efEntry_width
  339. # component = efEntry, componentOption = width
  340. component = option[:index]
  341. componentOption = option[(index + 1):]
  342. # Expand component alias
  343. if componentAliases_has_key(component):
  344. # component = entryField, subcomponent = entry
  345. component, subComponent = componentAliases[component]
  346. if subComponent is not None:
  347. # componentOption becomes entry_width
  348. componentOption = subComponent + '_' \
  349. + componentOption
  350. # Expand option string to write on error
  351. # option = entryField_entry_width
  352. option = component + '_' + componentOption
  353. # Does this component exist
  354. if componentInfo_has_key(component):
  355. # Get the configure func for the named component
  356. # component = entryField
  357. componentConfigFuncs = [componentInfo[component][1]]
  358. else:
  359. # Check if this is a group name and configure all
  360. # components in the group.
  361. componentConfigFuncs = []
  362. # For each component
  363. for info in componentInfo.values():
  364. # Check if it is a member of this group
  365. if info[4] == component:
  366. # Yes, append its config func
  367. componentConfigFuncs.append(info[1])
  368. if len(componentConfigFuncs) == 0 and \
  369. component not in self._dynamicGroups:
  370. raise KeyError('Unknown option "' + option + \
  371. '" for ' + self.__class__.__name__)
  372. # Add the configure method(s) (may be more than
  373. # one if this is configuring a component group)
  374. # and option/value to dictionary.
  375. for componentConfigFunc in componentConfigFuncs:
  376. if not indirectOptions_has_key(componentConfigFunc):
  377. indirectOptions[componentConfigFunc] = {}
  378. # Create a dictionary of keyword/values keyed
  379. # on configuration function
  380. indirectOptions[componentConfigFunc][componentOption] \
  381. = value
  382. else:
  383. raise KeyError('Unknown option "' + option + \
  384. '" for ' + self.__class__.__name__)
  385. # Call the configure methods for any components.
  386. # Pass in the dictionary of keyword/values created above
  387. for func, options in indirectOptions.items():
  388. func(**options)
  389. # Call the configuration callback function for each option.
  390. for option in directOptions:
  391. info = optionInfo[option]
  392. func = info[DGG._OPT_FUNCTION]
  393. if func is not None:
  394. func()
  395. # Allow index style references
  396. def __setitem__(self, key, value):
  397. self.configure(**{key: value})
  398. def cget(self, option):
  399. """
  400. Get current configuration setting for this option
  401. """
  402. # Return the value of an option, for example myWidget['font'].
  403. if option in self._optionInfo:
  404. return self._optionInfo[option][DGG._OPT_VALUE]
  405. else:
  406. index = option.find('_')
  407. if index >= 0:
  408. component = option[:index]
  409. componentOption = option[(index + 1):]
  410. # Expand component alias
  411. if component in self.__componentAliases:
  412. component, subComponent = self.__componentAliases[
  413. component]
  414. if subComponent is not None:
  415. componentOption = subComponent + '_' + componentOption
  416. # Expand option string to write on error
  417. option = component + '_' + componentOption
  418. if component in self.__componentInfo:
  419. # Call cget on the component.
  420. componentCget = self.__componentInfo[component][3]
  421. return componentCget(componentOption)
  422. else:
  423. # If this is a group name, call cget for one of
  424. # the components in the group.
  425. for info in self.__componentInfo.values():
  426. if info[4] == component:
  427. componentCget = info[3]
  428. return componentCget(componentOption)
  429. # Option not found
  430. raise KeyError('Unknown option "' + option + \
  431. '" for ' + self.__class__.__name__)
  432. # Allow index style refererences
  433. __getitem__ = cget
  434. def createcomponent(self, componentName, componentAliases, componentGroup,
  435. widgetClass, *widgetArgs, **kw):
  436. """
  437. Create a component (during construction or later) for this widget.
  438. """
  439. # Check for invalid component name
  440. if '_' in componentName:
  441. raise ValueError('Component name "%s" must not contain "_"' % componentName)
  442. # Get construction keywords
  443. if hasattr(self, '_constructorKeywords'):
  444. keywords = self._constructorKeywords
  445. else:
  446. keywords = {}
  447. for alias, component in componentAliases:
  448. # Create aliases to the component and its sub-components.
  449. index = component.find('_')
  450. if index < 0:
  451. # Just a shorter name for one of this widget's components
  452. self.__componentAliases[alias] = (component, None)
  453. else:
  454. # An alias for a component of one of this widget's components
  455. mainComponent = component[:index]
  456. subComponent = component[(index + 1):]
  457. self.__componentAliases[alias] = (mainComponent, subComponent)
  458. # Remove aliases from the constructor keyword arguments by
  459. # replacing any keyword arguments that begin with *alias*
  460. # with corresponding keys beginning with *component*.
  461. alias = alias + '_'
  462. aliasLen = len(alias)
  463. for option in keywords.copy():
  464. if len(option) > aliasLen and option[:aliasLen] == alias:
  465. newkey = component + '_' + option[aliasLen:]
  466. keywords[newkey] = keywords[option]
  467. del keywords[option]
  468. # Find any keyword arguments for this component
  469. componentPrefix = componentName + '_'
  470. nameLen = len(componentPrefix)
  471. # First, walk through the option list looking for arguments
  472. # than refer to this component's group.
  473. for option in keywords:
  474. # Check if this keyword argument refers to the group
  475. # of this component. If so, add this to the options
  476. # to use when constructing the widget. Mark the
  477. # keyword argument as being used, but do not remove it
  478. # since it may be required when creating another
  479. # component.
  480. index = option.find('_')
  481. if index >= 0 and componentGroup == option[:index]:
  482. rest = option[(index + 1):]
  483. kw[rest] = keywords[option][0]
  484. keywords[option][1] = 1
  485. # Now that we've got the group arguments, walk through the
  486. # option list again and get out the arguments that refer to
  487. # this component specifically by name. These are more
  488. # specific than the group arguments, above; we walk through
  489. # the list afterwards so they will override.
  490. for option in keywords.copy():
  491. if len(option) > nameLen and option[:nameLen] == componentPrefix:
  492. # The keyword argument refers to this component, so add
  493. # this to the options to use when constructing the widget.
  494. kw[option[nameLen:]] = keywords[option][0]
  495. # And delete it from main construction keywords
  496. del keywords[option]
  497. # Return None if no widget class is specified
  498. if widgetClass is None:
  499. return None
  500. # Get arguments for widget constructor
  501. if len(widgetArgs) == 1 and isinstance(widgetArgs[0], tuple):
  502. # Arguments to the constructor can be specified as either
  503. # multiple trailing arguments to createcomponent() or as a
  504. # single tuple argument.
  505. widgetArgs = widgetArgs[0]
  506. # Create the widget
  507. widget = widgetClass(*widgetArgs, **kw)
  508. componentClass = widget.__class__.__name__
  509. self.__componentInfo[componentName] = (widget, widget.configure,
  510. componentClass, widget.cget, componentGroup)
  511. return widget
  512. def component(self, name):
  513. # Return a component widget of the megawidget given the
  514. # component's name
  515. # This allows the user of a megawidget to access and configure
  516. # widget components directly.
  517. # Find the main component and any subcomponents
  518. index = name.find('_')
  519. if index < 0:
  520. component = name
  521. remainingComponents = None
  522. else:
  523. component = name[:index]
  524. remainingComponents = name[(index + 1):]
  525. # Expand component alias
  526. # Example entry which is an alias for entryField_entry
  527. if component in self.__componentAliases:
  528. # component = entryField, subComponent = entry
  529. component, subComponent = self.__componentAliases[component]
  530. if subComponent is not None:
  531. if remainingComponents is None:
  532. # remainingComponents = entry
  533. remainingComponents = subComponent
  534. else:
  535. remainingComponents = subComponent + '_' \
  536. + remainingComponents
  537. # Get the component from __componentInfo dictionary
  538. widget = self.__componentInfo[component][0]
  539. if remainingComponents is None:
  540. # Not looking for subcomponent
  541. return widget
  542. else:
  543. # Recursive call on subcomponent
  544. return widget.component(remainingComponents)
  545. def components(self):
  546. # Return a list of all components.
  547. names = list(self.__componentInfo.keys())
  548. names.sort()
  549. return names
  550. def hascomponent(self, component):
  551. return component in self.__componentInfo
  552. def destroycomponent(self, name):
  553. # Remove a megawidget component.
  554. # This command is for use by megawidget designers to destroy a
  555. # megawidget component.
  556. self.__componentInfo[name][0].destroy()
  557. del self.__componentInfo[name]
  558. def destroy(self):
  559. # Clean out any hooks
  560. self.ignoreAll()
  561. del self._optionInfo
  562. del self.__componentInfo
  563. del self.postInitialiseFuncList
  564. def bind(self, event, command, extraArgs = []):
  565. """
  566. Bind the command (which should expect one arg) to the specified
  567. event (such as ENTER, EXIT, B1PRESS, B1CLICK, etc.)
  568. See DirectGuiGlobals for possible events
  569. """
  570. # Need to tack on gui item specific id
  571. gEvent = event + self.guiId
  572. if ConfigVariableBool('debug-directgui-msgs', False):
  573. from direct.showbase.PythonUtil import StackTrace
  574. print(gEvent)
  575. print(StackTrace())
  576. self.accept(gEvent, command, extraArgs = extraArgs)
  577. def unbind(self, event):
  578. """
  579. Unbind the specified event
  580. """
  581. # Need to tack on gui item specific id
  582. gEvent = event + self.guiId
  583. self.ignore(gEvent)
  584. def toggleGuiGridSnap():
  585. DirectGuiWidget.snapToGrid = 1 - DirectGuiWidget.snapToGrid
  586. def setGuiGridSpacing(spacing):
  587. DirectGuiWidget.gridSpacing = spacing
  588. class DirectGuiWidget(DirectGuiBase, NodePath):
  589. # Toggle if you wish widget's to snap to grid when draggin
  590. snapToGrid = 0
  591. gridSpacing = 0.05
  592. # Determine the default initial state for inactive (or
  593. # unclickable) components. If we are in edit mode, these are
  594. # actually clickable by default.
  595. guiEdit = ConfigVariableBool('direct-gui-edit', False)
  596. if guiEdit:
  597. inactiveInitState = DGG.NORMAL
  598. else:
  599. inactiveInitState = DGG.DISABLED
  600. guiDict = {}
  601. def __init__(self, parent = None, **kw):
  602. # Direct gui widgets are node paths
  603. # Direct gui widgets have:
  604. # - stateNodePaths (to hold visible representation of widget)
  605. # State node paths can have:
  606. # - a frame of type (None, FLAT, RAISED, GROOVE, RIDGE)
  607. # - arbitrary geometry for each state
  608. # They inherit from DirectGuiWidget
  609. # - Can create components (with aliases and groups)
  610. # - Can bind to mouse events
  611. # They inherit from NodePath
  612. # - Can position/scale them
  613. optiondefs = (
  614. # Widget's constructor
  615. ('pgFunc', PGItem, None),
  616. ('numStates', 1, None),
  617. ('invertedFrames', (), None),
  618. ('sortOrder', 0, None),
  619. # Widget's initial state
  620. ('state', DGG.NORMAL, self.setState),
  621. # Widget's frame characteristics
  622. ('relief', DGG.FLAT, self.setRelief),
  623. ('borderWidth', (.1, .1), self.setBorderWidth),
  624. ('borderUvWidth', (.1, .1), self.setBorderUvWidth),
  625. ('frameSize', None, self.setFrameSize),
  626. ('frameColor', (.8, .8, .8, 1), self.setFrameColor),
  627. ('frameTexture', None, self.setFrameTexture),
  628. ('frameVisibleScale', (1, 1), self.setFrameVisibleScale),
  629. ('pad', (0, 0), self.resetFrameSize),
  630. # Override button id (beware! your name may not be unique!)
  631. ('guiId', None, DGG.INITOPT),
  632. # Initial pos/scale of the widget
  633. ('pos', None, DGG.INITOPT),
  634. ('hpr', None, DGG.INITOPT),
  635. ('scale', None, DGG.INITOPT),
  636. ('color', None, DGG.INITOPT),
  637. # Do events pass through this widget?
  638. ('suppressMouse', 1, DGG.INITOPT),
  639. ('suppressKeys', 0, DGG.INITOPT),
  640. ('enableEdit', 1, DGG.INITOPT),
  641. )
  642. # Merge keyword options with default options
  643. self.defineoptions(kw, optiondefs)
  644. # Initialize the base classes (after defining the options).
  645. DirectGuiBase.__init__(self)
  646. NodePath.__init__(self)
  647. # Create a button
  648. self.guiItem = self['pgFunc']('')
  649. # Override automatically generated guiId
  650. if self['guiId']:
  651. self.guiItem.setId(self['guiId'])
  652. self.guiId = self.guiItem.getId()
  653. if ShowBaseGlobal.__dev__:
  654. # track gui items by guiId for tracking down leaks
  655. if _track_gui_items:
  656. if not hasattr(ShowBase, 'guiItems'):
  657. ShowBase.guiItems = {}
  658. if self.guiId in ShowBase.guiItems:
  659. ShowBase.notify.warning('duplicate guiId: %s (%s stomping %s)' %
  660. (self.guiId, self,
  661. ShowBase.guiItems[self.guiId]))
  662. ShowBase.guiItems[self.guiId] = self
  663. # Attach button to parent and make that self
  664. if parent is None:
  665. parent = ShowBaseGlobal.aspect2d
  666. self.assign(parent.attachNewNode(self.guiItem, self['sortOrder']))
  667. # Update pose to initial values
  668. if self['pos']:
  669. self.setPos(self['pos'])
  670. if self['hpr']:
  671. self.setHpr(self['hpr'])
  672. if self['scale']:
  673. self.setScale(self['scale'])
  674. if self['color']:
  675. self.setColor(self['color'])
  676. # Initialize names
  677. # Putting the class name in helps with debugging.
  678. self.setName("%s-%s" % (self.__class__.__name__, self.guiId))
  679. # Create
  680. self.stateNodePath = []
  681. for i in range(self['numStates']):
  682. self.stateNodePath.append(NodePath(self.guiItem.getStateDef(i)))
  683. # Initialize frame style
  684. self.frameStyle = []
  685. for i in range(self['numStates']):
  686. self.frameStyle.append(PGFrameStyle())
  687. # For holding bounds info
  688. self.ll = Point3(0)
  689. self.ur = Point3(0)
  690. # Is drag and drop enabled?
  691. if self['enableEdit'] and self.guiEdit:
  692. self.enableEdit()
  693. # Set up event handling
  694. suppressFlags = 0
  695. if self['suppressMouse']:
  696. suppressFlags |= MouseWatcherRegion.SFMouseButton
  697. suppressFlags |= MouseWatcherRegion.SFMousePosition
  698. if self['suppressKeys']:
  699. suppressFlags |= MouseWatcherRegion.SFOtherButton
  700. self.guiItem.setSuppressFlags(suppressFlags)
  701. # Bind destroy hook
  702. self.guiDict[self.guiId] = self
  703. # self.bind(DGG.DESTROY, self.destroy)
  704. # Update frame when everything has been initialized
  705. self.postInitialiseFuncList.append(self.frameInitialiseFunc)
  706. # Call option initialization functions
  707. self.initialiseoptions(DirectGuiWidget)
  708. def frameInitialiseFunc(self):
  709. # Now allow changes to take effect
  710. self.updateFrameStyle()
  711. if not self['frameSize']:
  712. self.resetFrameSize()
  713. def enableEdit(self):
  714. self.bind(DGG.B2PRESS, self.editStart)
  715. self.bind(DGG.B2RELEASE, self.editStop)
  716. self.bind(DGG.PRINT, self.printConfig)
  717. # Can we move this to showbase
  718. # Certainly we don't need to do this for every button!
  719. #mb = base.mouseWatcherNode.getModifierButtons()
  720. #mb.addButton(KeyboardButton.control())
  721. #base.mouseWatcherNode.setModifierButtons(mb)
  722. def disableEdit(self):
  723. self.unbind(DGG.B2PRESS)
  724. self.unbind(DGG.B2RELEASE)
  725. self.unbind(DGG.PRINT)
  726. #mb = base.mouseWatcherNode.getModifierButtons()
  727. #mb.removeButton(KeyboardButton.control())
  728. #base.mouseWatcherNode.setModifierButtons(mb)
  729. def editStart(self, event):
  730. taskMgr.remove('guiEditTask')
  731. vWidget2render2d = self.getPos(ShowBaseGlobal.render2d)
  732. vMouse2render2d = Point3(event.getMouse()[0], 0, event.getMouse()[1])
  733. editVec = Vec3(vWidget2render2d - vMouse2render2d)
  734. if base.mouseWatcherNode.getModifierButtons().isDown(
  735. KeyboardButton.control()):
  736. t = taskMgr.add(self.guiScaleTask, 'guiEditTask')
  737. t.refPos = vWidget2render2d
  738. t.editVecLen = editVec.length()
  739. t.initScale = self.getScale()
  740. else:
  741. t = taskMgr.add(self.guiDragTask, 'guiEditTask')
  742. t.editVec = editVec
  743. def guiScaleTask(self, state):
  744. mwn = base.mouseWatcherNode
  745. if mwn.hasMouse():
  746. vMouse2render2d = Point3(mwn.getMouse()[0], 0, mwn.getMouse()[1])
  747. newEditVecLen = Vec3(state.refPos - vMouse2render2d).length()
  748. self.setScale(state.initScale * (newEditVecLen/state.editVecLen))
  749. return Task.cont
  750. def guiDragTask(self, state):
  751. mwn = base.mouseWatcherNode
  752. if mwn.hasMouse():
  753. vMouse2render2d = Point3(mwn.getMouse()[0], 0, mwn.getMouse()[1])
  754. newPos = vMouse2render2d + state.editVec
  755. self.setPos(ShowBaseGlobal.render2d, newPos)
  756. if DirectGuiWidget.snapToGrid:
  757. newPos = self.getPos()
  758. newPos.set(
  759. ROUND_TO(newPos[0], DirectGuiWidget.gridSpacing),
  760. ROUND_TO(newPos[1], DirectGuiWidget.gridSpacing),
  761. ROUND_TO(newPos[2], DirectGuiWidget.gridSpacing))
  762. self.setPos(newPos)
  763. return Task.cont
  764. def editStop(self, event):
  765. taskMgr.remove('guiEditTask')
  766. def setState(self):
  767. if isinstance(self['state'], int):
  768. self.guiItem.setActive(self['state'])
  769. elif self['state'] == DGG.NORMAL or self['state'] == 'normal':
  770. self.guiItem.setActive(1)
  771. else:
  772. self.guiItem.setActive(0)
  773. def resetFrameSize(self):
  774. if not self.fInit:
  775. self.setFrameSize(fClearFrame = 1)
  776. def setFrameSize(self, fClearFrame = 0):
  777. # Use ready state to determine frame Type
  778. frameType = self.getFrameType()
  779. if self['frameSize']:
  780. # Use user specified bounds
  781. self.bounds = self['frameSize']
  782. #print "%s bounds = %s" % (self.getName(), self.bounds)
  783. bw = (0, 0)
  784. else:
  785. if fClearFrame and frameType != PGFrameStyle.TNone:
  786. self.frameStyle[0].setType(PGFrameStyle.TNone)
  787. self.guiItem.setFrameStyle(0, self.frameStyle[0])
  788. # To force an update of the button
  789. self.guiItem.getStateDef(0)
  790. # Clear out frame before computing bounds
  791. self.getBounds()
  792. # Restore frame style if necessary
  793. if frameType != PGFrameStyle.TNone:
  794. self.frameStyle[0].setType(frameType)
  795. self.guiItem.setFrameStyle(0, self.frameStyle[0])
  796. if frameType != PGFrameStyle.TNone and \
  797. frameType != PGFrameStyle.TFlat:
  798. bw = self['borderWidth']
  799. else:
  800. bw = (0, 0)
  801. # Set frame to new dimensions
  802. self.guiItem.setFrame(
  803. self.bounds[0] - bw[0],
  804. self.bounds[1] + bw[0],
  805. self.bounds[2] - bw[1],
  806. self.bounds[3] + bw[1])
  807. def getBounds(self, state = 0):
  808. self.stateNodePath[state].calcTightBounds(self.ll, self.ur)
  809. # Scale bounds to give a pad around graphics
  810. vec_right = Vec3.right()
  811. vec_up = Vec3.up()
  812. left = (vec_right[0] * self.ll[0]
  813. + vec_right[1] * self.ll[1]
  814. + vec_right[2] * self.ll[2])
  815. right = (vec_right[0] * self.ur[0]
  816. + vec_right[1] * self.ur[1]
  817. + vec_right[2] * self.ur[2])
  818. bottom = (vec_up[0] * self.ll[0]
  819. + vec_up[1] * self.ll[1]
  820. + vec_up[2] * self.ll[2])
  821. top = (vec_up[0] * self.ur[0]
  822. + vec_up[1] * self.ur[1]
  823. + vec_up[2] * self.ur[2])
  824. self.ll = Point3(left, 0.0, bottom)
  825. self.ur = Point3(right, 0.0, top)
  826. self.bounds = [self.ll[0] - self['pad'][0],
  827. self.ur[0] + self['pad'][0],
  828. self.ll[2] - self['pad'][1],
  829. self.ur[2] + self['pad'][1]]
  830. return self.bounds
  831. def getWidth(self):
  832. return self.bounds[1] - self.bounds[0]
  833. def getHeight(self):
  834. return self.bounds[3] - self.bounds[2]
  835. def getCenter(self):
  836. x = self.bounds[0] + (self.bounds[1] - self.bounds[0])/2.0
  837. y = self.bounds[2] + (self.bounds[3] - self.bounds[2])/2.0
  838. return (x, y)
  839. def getFrameType(self, state = 0):
  840. return self.frameStyle[state].getType()
  841. def updateFrameStyle(self):
  842. if not self.fInit:
  843. for i in range(self['numStates']):
  844. self.guiItem.setFrameStyle(i, self.frameStyle[i])
  845. def setRelief(self, fSetStyle = 1):
  846. relief = self['relief']
  847. # Convert None, and string arguments
  848. if relief is None:
  849. relief = PGFrameStyle.TNone
  850. elif isinstance(relief, str):
  851. # Convert string to frame style int
  852. relief = DGG.FrameStyleDict[relief]
  853. # Set style
  854. if relief == DGG.RAISED:
  855. for i in range(self['numStates']):
  856. if i in self['invertedFrames']:
  857. self.frameStyle[1].setType(DGG.SUNKEN)
  858. else:
  859. self.frameStyle[i].setType(DGG.RAISED)
  860. elif relief == DGG.SUNKEN:
  861. for i in range(self['numStates']):
  862. if i in self['invertedFrames']:
  863. self.frameStyle[1].setType(DGG.RAISED)
  864. else:
  865. self.frameStyle[i].setType(DGG.SUNKEN)
  866. else:
  867. for i in range(self['numStates']):
  868. self.frameStyle[i].setType(relief)
  869. # Apply styles
  870. self.updateFrameStyle()
  871. def setFrameColor(self):
  872. # this might be a single color or a list of colors
  873. colors = self['frameColor']
  874. if isinstance(colors[0], (int, float)):
  875. colors = (colors,)
  876. for i in range(self['numStates']):
  877. if i >= len(colors):
  878. color = colors[-1]
  879. else:
  880. color = colors[i]
  881. self.frameStyle[i].setColor(color[0], color[1], color[2], color[3])
  882. self.updateFrameStyle()
  883. def setFrameTexture(self):
  884. # this might be a single texture or a list of textures
  885. textures = self['frameTexture']
  886. if textures is None or \
  887. isinstance(textures, (Texture, str)):
  888. textures = (textures,) * self['numStates']
  889. for i in range(self['numStates']):
  890. if i >= len(textures):
  891. texture = textures[-1]
  892. else:
  893. texture = textures[i]
  894. if isinstance(texture, str):
  895. texture = base.loader.loadTexture(texture)
  896. if texture:
  897. self.frameStyle[i].setTexture(texture)
  898. else:
  899. self.frameStyle[i].clearTexture()
  900. self.updateFrameStyle()
  901. def setFrameVisibleScale(self):
  902. scale = self['frameVisibleScale']
  903. for i in range(self['numStates']):
  904. self.frameStyle[i].setVisibleScale(scale[0], scale[1])
  905. self.updateFrameStyle()
  906. def setBorderWidth(self):
  907. width = self['borderWidth']
  908. for i in range(self['numStates']):
  909. self.frameStyle[i].setWidth(width[0], width[1])
  910. self.updateFrameStyle()
  911. def setBorderUvWidth(self):
  912. uvWidth = self['borderUvWidth']
  913. for i in range(self['numStates']):
  914. self.frameStyle[i].setUvWidth(uvWidth[0], uvWidth[1])
  915. self.updateFrameStyle()
  916. def destroy(self):
  917. if hasattr(self, "frameStyle"):
  918. if ShowBaseGlobal.__dev__:
  919. if hasattr(ShowBase, 'guiItems'):
  920. ShowBase.guiItems.pop(self.guiId, None)
  921. # Destroy children
  922. for child in self.getChildren():
  923. childGui = self.guiDict.get(child.getName())
  924. if childGui:
  925. childGui.destroy()
  926. else:
  927. # RAU since we added the class to the name, try
  928. # it with the original name
  929. parts = child.getName().split('-')
  930. simpleChildGui = self.guiDict.get(parts[-1])
  931. if simpleChildGui:
  932. simpleChildGui.destroy()
  933. # messenger.send(DESTROY + child.getName())
  934. del self.guiDict[self.guiId]
  935. del self.frameStyle
  936. # Get rid of node path
  937. self.removeNode()
  938. for nodePath in self.stateNodePath:
  939. nodePath.removeNode()
  940. del self.stateNodePath
  941. del self.guiItem
  942. # Call superclass destruction method (clears out hooks)
  943. DirectGuiBase.destroy(self)
  944. def printConfig(self, indent = 0):
  945. space = ' ' * indent
  946. print('%s%s - %s' % (space, self.guiId, self.__class__.__name__))
  947. print('%sPos: %s' % (space, tuple(self.getPos())))
  948. print('%sScale: %s' % (space, tuple(self.getScale())))
  949. # Print out children info
  950. for child in self.getChildren():
  951. messenger.send(DGG.PRINT + child.getName(), [indent + 2])
  952. def copyOptions(self, other):
  953. """
  954. Copy other's options into our self so we look and feel like other
  955. """
  956. for key, value in other._optionInfo.items():
  957. self[key] = value[1]
  958. def taskName(self, idString):
  959. return idString + "-" + str(self.guiId)
  960. def uniqueName(self, idString):
  961. return idString + "-" + str(self.guiId)
  962. def setProp(self, propString, value):
  963. """
  964. Allows you to set a property like frame['text'] = 'Joe' in
  965. a function instead of an assignment.
  966. This is useful for setting properties inside function intervals
  967. where must input a function and extraArgs, not an assignment.
  968. """
  969. self[propString] = value