menutree.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. """!
  2. @package core.menutree
  3. @brief Creates tree structure for wxGUI menus (former menudata.py)
  4. Classes:
  5. - menutree::MenuTreeModelBuilder
  6. Usage:
  7. @code
  8. python menutree.py [action] [menu]
  9. @endcode
  10. where <i>action</i>:
  11. - strings (default, used for translations)
  12. - tree (simple tree structure)
  13. - commands (command names and their place in tree)
  14. - dump (tree structure with stored data)
  15. and <i>menu</i>:
  16. - manager (Layer Manager)
  17. - modeler (Graphical Modeler)
  18. - psmap (Cartographic Composer)
  19. (C) 2013 by the GRASS Development Team
  20. This program is free software under the GNU General Public License
  21. (>=v2). Read the file COPYING that comes with GRASS for details.
  22. @author Glynn Clements (menudata.py)
  23. @author Martin Landa <landa.martin gmail.com> (menudata.py)
  24. @author Anna Petrasova <kratochanna gmail.com>
  25. """
  26. import os
  27. import sys
  28. import copy
  29. try:
  30. import xml.etree.ElementTree as etree
  31. except ImportError:
  32. import elementtree.ElementTree as etree # Python <= 2.4
  33. import wx
  34. if __name__ == '__main__':
  35. gui_wx_path = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
  36. if gui_wx_path not in sys.path:
  37. sys.path.append(gui_wx_path)
  38. from core.treemodel import TreeModel, ModuleNode
  39. from core.settings import UserSettings
  40. from core.toolboxes import expandAddons
  41. if not os.getenv("GISBASE"):
  42. sys.exit("GRASS is not running. Exiting...")
  43. # TODO: change the system to remove strange derived classes
  44. class MenuTreeModelBuilder:
  45. """!Abstract menu data class"""
  46. def __init__(self, filename):
  47. self.menustyle = UserSettings.Get(group = 'appearance',
  48. key = 'menustyle',
  49. subkey = 'selection')
  50. xmlTree = etree.parse(filename)
  51. expandAddons(xmlTree)
  52. self.model = TreeModel(ModuleNode)
  53. self._createModel(xmlTree)
  54. def _createModel(self, xmlTree):
  55. root = xmlTree.getroot()
  56. menubar = root.findall('menubar')[0]
  57. menus = menubar.findall('menu')
  58. for m in menus:
  59. self._createMenu(m, self.model.root)
  60. def _createMenu(self, menu, node):
  61. label = _(menu.find('label').text)
  62. items = menu.find('items')
  63. node = self.model.AppendNode(parent=node, label=label)
  64. for item in items:
  65. self._createItem(item, node)
  66. def _createItem(self, item, node):
  67. if item.tag == 'separator':
  68. data = dict(label='', description='', handler='',
  69. command='', keywords='', shortcut='', wxId='')
  70. self.model.AppendNode(parent=node, label='', data=data)
  71. elif item.tag == 'menuitem':
  72. origLabel = _(item.find('label').text)
  73. handler = item.find('handler').text
  74. desc = item.find('help') # optional
  75. gcmd = item.find('command') # optional
  76. keywords = item.find('keywords') # optional
  77. shortcut = item.find('shortcut') # optional
  78. wxId = item.find('id') # optional
  79. if gcmd != None:
  80. gcmd = gcmd.text
  81. else:
  82. gcmd = ""
  83. if desc.text:
  84. desc = _(desc.text)
  85. else:
  86. desc = ""
  87. if keywords is None or keywords.text is None:
  88. keywords = ""
  89. else:
  90. keywords = keywords.text
  91. if shortcut != None:
  92. shortcut = shortcut.text
  93. else:
  94. shortcut = ""
  95. if wxId != None:
  96. wxId = eval('wx.' + wxId.text)
  97. else:
  98. wxId = wx.ID_ANY
  99. label = origLabel
  100. if gcmd:
  101. if self.menustyle == 1:
  102. label += ' [' + gcmd + ']'
  103. elif self.menustyle == 2:
  104. label = ' [' + gcmd + ']'
  105. data = dict(label=origLabel, description=desc, handler=handler,
  106. command=gcmd, keywords=keywords, shortcut=shortcut, wxId=wxId)
  107. self.model.AppendNode(parent=node, label=label, data=data)
  108. elif item.tag == 'menu':
  109. self._createMenu(item, node)
  110. else:
  111. raise ValueError(_("Unknow tag %s") % item.tag)
  112. def GetModel(self, separators=False):
  113. """Returns copy of model with or without separators
  114. (for menu or for search tree).
  115. """
  116. if separators:
  117. return copy.deepcopy(self.model)
  118. else:
  119. model = copy.deepcopy(self.model)
  120. removeSeparators(model)
  121. return model
  122. def PrintTree(self, fh):
  123. for child in self.model.root.children:
  124. printTree(node=child, fh=fh)
  125. def PrintStrings(self, fh):
  126. """!Print menu strings to file (used for localization)
  127. @param fh file descriptor
  128. """
  129. className = str(self.__class__).split('.', 1)[1]
  130. fh.write('menustrings_%s = [\n' % className)
  131. for child in self.model.root.children:
  132. printStrings(child, fh)
  133. fh.write(' \'\']\n')
  134. def PrintCommands(self, fh):
  135. printCommands(self.model.root, fh, itemSep=' | ', menuSep=' > ')
  136. def removeSeparators(model, node=None):
  137. if not node:
  138. node = model.root
  139. if node.label:
  140. for child in reversed(node.children):
  141. removeSeparators(model, child)
  142. else:
  143. model.RemoveNode(node)
  144. def printTree(node, fh, indent=0):
  145. if not node.label:
  146. return
  147. text = '%s- %s\n' % (' ' * indent, node.label.replace('&', ''))
  148. fh.write(text)
  149. for child in node.children:
  150. printTree(node=child, fh=fh, indent=indent + 2)
  151. def printStrings(node, fh):
  152. # node.label - with module in brackets
  153. # node.data['label'] - without module in brackets
  154. if node.label and not node.data:
  155. fh.write(' _(%r),\n' % str(node.label))
  156. if node.data:
  157. if 'label' in node.data and node.data['label']:
  158. fh.write(' _(%r),\n' % str(node.data['label']))
  159. if 'description' in node.data and node.data['description']:
  160. fh.write(' _(%r),\n' % str(node.data['description']))
  161. for child in node.children:
  162. printStrings(node=child, fh=fh)
  163. def printCommands(node, fh, itemSep, menuSep):
  164. def collectParents(node, parents):
  165. parent = node.parent
  166. if parent.parent:
  167. parents.insert(0, node.parent)
  168. collectParents(node.parent, parents)
  169. data = node.data
  170. if data and 'command' in data and data['command']:
  171. fh.write('%s%s' % (data['command'], itemSep))
  172. parents = [node]
  173. collectParents(node, parents)
  174. labels = [parent.label.replace('&', '') for parent in parents]
  175. fh.write(menuSep.join(labels))
  176. fh.write('\n')
  177. for child in node.children:
  178. printCommands(child, fh, itemSep, menuSep)
  179. if __name__ == "__main__":
  180. # i18N
  181. import gettext
  182. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  183. action = 'strings'
  184. menu = 'manager'
  185. for arg in sys.argv:
  186. if arg in ('strings', 'tree', 'commands', 'dump'):
  187. action = arg
  188. elif arg in ('manager', 'modeler', 'psmap'):
  189. menu = arg
  190. gui_wx_path = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
  191. if gui_wx_path not in sys.path:
  192. sys.path.append(gui_wx_path)
  193. # FIXME: cross-dependencies
  194. if menu == 'manager':
  195. from lmgr.menudata import LayerManagerMenuData
  196. from core.globalvar import ETCWXDIR
  197. filename = os.path.join(ETCWXDIR, 'xml', 'menudata.xml')
  198. menudata = LayerManagerMenuData(filename)
  199. elif menu == 'modeler':
  200. from gmodeler.menudata import ModelerMenuData
  201. menudata = ModelerMenuData()
  202. elif menu == 'psmap':
  203. from psmap.menudata import PsMapMenuData
  204. menudata = PsMapMenuData()
  205. if action == 'strings':
  206. menudata.PrintStrings(sys.stdout)
  207. elif action == 'tree':
  208. menudata.PrintTree(sys.stdout)
  209. elif action == 'commands':
  210. menudata.PrintCommands(sys.stdout)
  211. elif action == 'dump':
  212. print menudata.model
  213. sys.exit(0)