DirectGuiBase.py 45 KB

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