menutree.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 (Main menu in Layer Manager)
  17. - module_tree (Module tree in Layer Manager)
  18. - modeler (Graphical Modeler)
  19. - psmap (Cartographic Composer)
  20. (C) 2013 by the GRASS Development Team
  21. This program is free software under the GNU General Public License
  22. (>=v2). Read the file COPYING that comes with GRASS for details.
  23. @author Glynn Clements (menudata.py)
  24. @author Martin Landa <landa.martin gmail.com> (menudata.py)
  25. @author Anna Petrasova <kratochanna gmail.com>
  26. """
  27. import os
  28. import sys
  29. import copy
  30. try:
  31. import xml.etree.ElementTree as etree
  32. except ImportError:
  33. import elementtree.ElementTree as etree # Python <= 2.4
  34. import wx
  35. if __name__ == '__main__':
  36. gui_wx_path = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
  37. if gui_wx_path not in sys.path:
  38. sys.path.append(gui_wx_path)
  39. from core.treemodel import TreeModel, ModuleNode
  40. from core.settings import UserSettings
  41. from core.toolboxes import expandAddons as expAddons
  42. from core.utils import _
  43. if not os.getenv("GISBASE"):
  44. sys.exit("GRASS is not running. Exiting...")
  45. # TODO: change the system to remove strange derived classes
  46. class MenuTreeModelBuilder:
  47. """!Abstract menu data class"""
  48. def __init__(self, filename, expandAddons=True):
  49. self.menustyle = UserSettings.Get(group = 'appearance',
  50. key = 'menustyle',
  51. subkey = 'selection')
  52. xmlTree = etree.parse(filename)
  53. if expandAddons:
  54. expAddons(xmlTree)
  55. self.model = TreeModel(ModuleNode)
  56. self._createModel(xmlTree)
  57. def _createModel(self, xmlTree):
  58. root = xmlTree.getroot()
  59. menubar = root.findall('menubar')[0]
  60. menus = menubar.findall('menu')
  61. for m in menus:
  62. self._createMenu(m, self.model.root)
  63. def _createMenu(self, menu, node):
  64. label = _(menu.find('label').text)
  65. items = menu.find('items')
  66. node = self.model.AppendNode(parent=node, label=label)
  67. for item in items:
  68. self._createItem(item, node)
  69. def _createItem(self, item, node):
  70. if item.tag == 'separator':
  71. data = dict(label='', description='', handler='',
  72. command='', keywords='', shortcut='', wxId='')
  73. self.model.AppendNode(parent=node, label='', data=data)
  74. elif item.tag == 'menuitem':
  75. origLabel = _(item.find('label').text)
  76. handler = item.find('handler').text
  77. desc = item.find('help') # optional
  78. gcmd = item.find('command') # optional
  79. keywords = item.find('keywords') # optional
  80. shortcut = item.find('shortcut') # optional
  81. wxId = item.find('id') # optional
  82. if gcmd != None:
  83. gcmd = gcmd.text
  84. else:
  85. gcmd = ""
  86. if desc.text:
  87. desc = _(desc.text)
  88. else:
  89. desc = ""
  90. if keywords is None or keywords.text is None:
  91. keywords = ""
  92. else:
  93. keywords = keywords.text
  94. if shortcut != None:
  95. shortcut = shortcut.text
  96. else:
  97. shortcut = ""
  98. if wxId != None:
  99. wxId = eval('wx.' + wxId.text)
  100. else:
  101. wxId = wx.ID_ANY
  102. label = origLabel
  103. if gcmd:
  104. if self.menustyle == 1:
  105. label += ' [' + gcmd + ']'
  106. elif self.menustyle == 2:
  107. label = ' [' + gcmd + ']'
  108. data = dict(label=origLabel, description=desc, handler=handler,
  109. command=gcmd, keywords=keywords, shortcut=shortcut, wxId=wxId)
  110. self.model.AppendNode(parent=node, label=label, data=data)
  111. elif item.tag == 'menu':
  112. self._createMenu(item, node)
  113. else:
  114. raise ValueError(_("Unknow tag %s") % item.tag)
  115. def GetModel(self, separators=False):
  116. """Returns copy of model with or without separators
  117. (for menu or for search tree).
  118. """
  119. if separators:
  120. return copy.deepcopy(self.model)
  121. else:
  122. model = copy.deepcopy(self.model)
  123. removeSeparators(model)
  124. return model
  125. def PrintTree(self, fh):
  126. for child in self.model.root.children:
  127. printTree(node=child, fh=fh)
  128. def PrintStrings(self, fh):
  129. """!Print menu strings to file (used for localization)
  130. @param fh file descriptor
  131. """
  132. className = str(self.__class__).split('.', 1)[1]
  133. fh.write('menustrings_%s = [\n' % className)
  134. for child in self.model.root.children:
  135. printStrings(child, fh)
  136. fh.write(' \'\']\n')
  137. def PrintCommands(self, fh):
  138. printCommands(self.model.root, fh, itemSep=' | ', menuSep=' > ')
  139. def removeSeparators(model, node=None):
  140. if not node:
  141. node = model.root
  142. if node.label:
  143. for child in reversed(node.children):
  144. removeSeparators(model, child)
  145. else:
  146. model.RemoveNode(node)
  147. def printTree(node, fh, indent=0):
  148. if not node.label:
  149. return
  150. text = '%s- %s\n' % (' ' * indent, node.label.replace('&', ''))
  151. fh.write(text)
  152. for child in node.children:
  153. printTree(node=child, fh=fh, indent=indent + 2)
  154. def printStrings(node, fh):
  155. # node.label - with module in brackets
  156. # node.data['label'] - without module in brackets
  157. if node.label and not node.data:
  158. fh.write(' _(%r),\n' % str(node.label))
  159. if node.data:
  160. if 'label' in node.data and node.data['label']:
  161. fh.write(' _(%r),\n' % str(node.data['label']))
  162. if 'description' in node.data and node.data['description']:
  163. fh.write(' _(%r),\n' % str(node.data['description']))
  164. for child in node.children:
  165. printStrings(node=child, fh=fh)
  166. def printCommands(node, fh, itemSep, menuSep):
  167. def collectParents(node, parents):
  168. parent = node.parent
  169. if parent.parent:
  170. parents.insert(0, node.parent)
  171. collectParents(node.parent, parents)
  172. data = node.data
  173. if data and 'command' in data and data['command']:
  174. fh.write('%s%s' % (data['command'], itemSep))
  175. parents = [node]
  176. collectParents(node, parents)
  177. labels = [parent.label.replace('&', '') for parent in parents]
  178. fh.write(menuSep.join(labels))
  179. fh.write('\n')
  180. for child in node.children:
  181. printCommands(child, fh, itemSep, menuSep)
  182. if __name__ == "__main__":
  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', 'module_tree', '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. # FIXME: since module descriptions are used again we have now the third copy of the same string (one is in modules)
  200. elif menu == 'module_tree':
  201. from lmgr.menudata import LayerManagerModuleTree
  202. from core.globalvar import ETCWXDIR
  203. filename = os.path.join(ETCWXDIR, 'xml', 'module_tree_menudata.xml')
  204. menudata = LayerManagerModuleTree(filename)
  205. elif menu == 'modeler':
  206. from gmodeler.menudata import ModelerMenuData
  207. menudata = ModelerMenuData()
  208. elif menu == 'psmap':
  209. from psmap.menudata import PsMapMenuData
  210. menudata = PsMapMenuData()
  211. else:
  212. import grass.script.core as gscore
  213. gscore.fatal("Unknown value for parameter menu: " % menu)
  214. if action == 'strings':
  215. menudata.PrintStrings(sys.stdout)
  216. elif action == 'tree':
  217. menudata.PrintTree(sys.stdout)
  218. elif action == 'commands':
  219. menudata.PrintCommands(sys.stdout)
  220. elif action == 'dump':
  221. print menudata.model
  222. else:
  223. import grass.script.core as gscore
  224. gscore.fatal("Unknown value for parameter action: " % action)
  225. sys.exit(0)