DirectGuiBase.py 42 KB

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