menutree.py 8.9 KB

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