menutree.py 8.8 KB

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