menutree.py 7.9 KB

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