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
  42. if not os.getenv("GISBASE"):
  43. sys.exit("GRASS is not running. Exiting...")
  44. # TODO: change the system to remove strange derived classes
  45. class MenuTreeModelBuilder:
  46. """!Abstract menu data class"""
  47. def __init__(self, filename):
  48. self.menustyle = UserSettings.Get(group = 'appearance',
  49. key = 'menustyle',
  50. subkey = 'selection')
  51. xmlTree = etree.parse(filename)
  52. expandAddons(xmlTree)
  53. self.model = TreeModel(ModuleNode)
  54. self._createModel(xmlTree)
  55. def _createModel(self, xmlTree):
  56. root = xmlTree.getroot()
  57. menubar = root.findall('menubar')[0]
  58. menus = menubar.findall('menu')
  59. for m in menus:
  60. self._createMenu(m, self.model.root)
  61. def _createMenu(self, menu, node):
  62. label = _(menu.find('label').text)
  63. items = menu.find('items')
  64. node = self.model.AppendNode(parent=node, label=label)
  65. for item in items:
  66. self._createItem(item, node)
  67. def _createItem(self, item, node):
  68. if item.tag == 'separator':
  69. data = dict(label='', description='', handler='',
  70. command='', keywords='', shortcut='', wxId='')
  71. self.model.AppendNode(parent=node, label='', data=data)
  72. elif item.tag == 'menuitem':
  73. origLabel = _(item.find('label').text)
  74. handler = item.find('handler').text
  75. desc = item.find('help') # optional
  76. gcmd = item.find('command') # optional
  77. keywords = item.find('keywords') # optional
  78. shortcut = item.find('shortcut') # optional
  79. wxId = item.find('id') # optional
  80. if gcmd != None:
  81. gcmd = gcmd.text
  82. else:
  83. gcmd = ""
  84. if desc.text:
  85. desc = _(desc.text)
  86. else:
  87. desc = ""
  88. if keywords is None or keywords.text is None:
  89. keywords = ""
  90. else:
  91. keywords = keywords.text
  92. if shortcut != None:
  93. shortcut = shortcut.text
  94. else:
  95. shortcut = ""
  96. if wxId != None:
  97. wxId = eval('wx.' + wxId.text)
  98. else:
  99. wxId = wx.ID_ANY
  100. label = origLabel
  101. if gcmd:
  102. if self.menustyle == 1:
  103. label += ' [' + gcmd + ']'
  104. elif self.menustyle == 2:
  105. label = ' [' + gcmd + ']'
  106. data = dict(label=origLabel, description=desc, handler=handler,
  107. command=gcmd, keywords=keywords, shortcut=shortcut, wxId=wxId)
  108. self.model.AppendNode(parent=node, label=label, data=data)
  109. elif item.tag == 'menu':
  110. self._createMenu(item, node)
  111. else:
  112. raise ValueError(_("Unknow tag %s") % item.tag)
  113. def GetModel(self, separators=False):
  114. """Returns copy of model with or without separators
  115. (for menu or for search tree).
  116. """
  117. if separators:
  118. return copy.deepcopy(self.model)
  119. else:
  120. model = copy.deepcopy(self.model)
  121. removeSeparators(model)
  122. return model
  123. def PrintTree(self, fh):
  124. for child in self.model.root.children:
  125. printTree(node=child, fh=fh)
  126. def PrintStrings(self, fh):
  127. """!Print menu strings to file (used for localization)
  128. @param fh file descriptor
  129. """
  130. className = str(self.__class__).split('.', 1)[1]
  131. fh.write('menustrings_%s = [\n' % className)
  132. for child in self.model.root.children:
  133. printStrings(child, fh)
  134. fh.write(' \'\']\n')
  135. def PrintCommands(self, fh):
  136. printCommands(self.model.root, fh, itemSep=' | ', menuSep=' > ')
  137. def removeSeparators(model, node=None):
  138. if not node:
  139. node = model.root
  140. if node.label:
  141. for child in reversed(node.children):
  142. removeSeparators(model, child)
  143. else:
  144. model.RemoveNode(node)
  145. def printTree(node, fh, indent=0):
  146. if not node.label:
  147. return
  148. text = '%s- %s\n' % (' ' * indent, node.label.replace('&', ''))
  149. fh.write(text)
  150. for child in node.children:
  151. printTree(node=child, fh=fh, indent=indent + 2)
  152. def printStrings(node, fh):
  153. # node.label - with module in brackets
  154. # node.data['label'] - without module in brackets
  155. if node.label and not node.data:
  156. fh.write(' _(%r),\n' % str(node.label))
  157. if node.data:
  158. if 'label' in node.data and node.data['label']:
  159. fh.write(' _(%r),\n' % str(node.data['label']))
  160. if 'description' in node.data and node.data['description']:
  161. fh.write(' _(%r),\n' % str(node.data['description']))
  162. for child in node.children:
  163. printStrings(node=child, fh=fh)
  164. def printCommands(node, fh, itemSep, menuSep):
  165. def collectParents(node, parents):
  166. parent = node.parent
  167. if parent.parent:
  168. parents.insert(0, node.parent)
  169. collectParents(node.parent, parents)
  170. data = node.data
  171. if data and 'command' in data and data['command']:
  172. fh.write('%s%s' % (data['command'], itemSep))
  173. parents = [node]
  174. collectParents(node, parents)
  175. labels = [parent.label.replace('&', '') for parent in parents]
  176. fh.write(menuSep.join(labels))
  177. fh.write('\n')
  178. for child in node.children:
  179. printCommands(child, fh, itemSep, menuSep)
  180. if __name__ == "__main__":
  181. # i18N
  182. import gettext
  183. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  184. action = 'strings'
  185. menu = 'manager'
  186. for arg in sys.argv:
  187. if arg in ('strings', 'tree', 'commands', 'dump'):
  188. action = arg
  189. elif arg in ('manager', 'module_tree', 'modeler', 'psmap'):
  190. menu = arg
  191. gui_wx_path = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
  192. if gui_wx_path not in sys.path:
  193. sys.path.append(gui_wx_path)
  194. # FIXME: cross-dependencies
  195. if menu == 'manager':
  196. from lmgr.menudata import LayerManagerMenuData
  197. from core.globalvar import ETCWXDIR
  198. filename = os.path.join(ETCWXDIR, 'xml', 'menudata.xml')
  199. menudata = LayerManagerMenuData(filename)
  200. # FIXME: since module descriptions are used again we have now the third copy of the same string (one is in modules)
  201. elif menu == 'module_tree':
  202. from lmgr.menudata import LayerManagerModuleTree
  203. from core.globalvar import ETCWXDIR
  204. filename = os.path.join(ETCWXDIR, 'xml', 'module_tree_menudata.xml')
  205. menudata = LayerManagerModuleTree(filename)
  206. elif menu == 'modeler':
  207. from gmodeler.menudata import ModelerMenuData
  208. menudata = ModelerMenuData()
  209. elif menu == 'psmap':
  210. from psmap.menudata import PsMapMenuData
  211. menudata = PsMapMenuData()
  212. else:
  213. import grass.script.core as gscore
  214. gscore.fatal("Unknown value for parameter menu: " % menu)
  215. if action == 'strings':
  216. menudata.PrintStrings(sys.stdout)
  217. elif action == 'tree':
  218. menudata.PrintTree(sys.stdout)
  219. elif action == 'commands':
  220. menudata.PrintCommands(sys.stdout)
  221. elif action == 'dump':
  222. print menudata.model
  223. else:
  224. import grass.script.core as gscore
  225. gscore.fatal("Unknown value for parameter action: " % action)
  226. sys.exit(0)