menutree.py 7.7 KB

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