menutree.py 7.5 KB

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