toolboxes.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. """!
  2. @package core.toolboxes
  3. @brief Functions for modifying menu from default/user toolboxes specified in XML files
  4. (C) 2013 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. @author Vaclav Petras <wenzeslaus gmail.com>
  8. @author Anna Petrasova <kratochanna gmail.com>
  9. """
  10. import os
  11. import sys
  12. import copy
  13. import xml.etree.ElementTree as etree
  14. from xml.parsers import expat
  15. # Get the XML parsing exceptions to catch. The behavior chnaged with Python 2.7
  16. # and ElementTree 1.3.
  17. if hasattr(etree, 'ParseError'):
  18. ETREE_EXCEPTIONS = (etree.ParseError, expat.ExpatError)
  19. else:
  20. ETREE_EXCEPTIONS = (expat.ExpatError)
  21. if sys.version_info[0:2] > (2, 6):
  22. has_xpath = True
  23. else:
  24. has_xpath = False
  25. if __name__ == '__main__':
  26. sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
  27. from core.globalvar import ETCWXDIR
  28. from core.utils import GetSettingsPath
  29. from core.gcmd import GError
  30. import grass.script.task as gtask
  31. from grass.script.core import ScriptError
  32. # this could be placed to functions
  33. mainMenuFile = os.path.join(ETCWXDIR, 'xml', 'main_menu.xml')
  34. toolboxesFile = os.path.join(ETCWXDIR, 'xml', 'toolboxes.xml')
  35. wxguiItemsFile = os.path.join(ETCWXDIR, 'xml', 'wxgui_items.xml')
  36. moduleItemsFile = os.path.join(ETCWXDIR, 'xml', 'module_items.xml')
  37. userToolboxesFile = os.path.join(GetSettingsPath(), 'toolboxes', 'toolboxes.xml')
  38. userMainMenuFile = os.path.join(GetSettingsPath(), 'toolboxes', 'main_menu.xml')
  39. if not os.path.exists(userToolboxesFile):
  40. userToolboxesFile = None
  41. if not os.path.exists(userMainMenuFile):
  42. userMainMenuFile = None
  43. def getMenuFile():
  44. """!Returns path to XML file for building menu.
  45. Creates toolbox directory where user defined toolboxes should be located.
  46. Checks whether it is needed to create new XML file (user changed toolboxes)
  47. or the already generated file could be used.
  48. If something goes wrong during building or user doesn't modify menu,
  49. default file (from distribution) is returned.
  50. """
  51. fallback = os.path.join(ETCWXDIR, 'xml', 'menudata.xml')
  52. # always create toolboxes directory if does not exist yet
  53. tbDir = _setupToolboxes()
  54. if tbDir:
  55. menudataFile = os.path.join(tbDir, 'menudata.xml')
  56. generateNew = False
  57. # when any of main_menu.xml or toolboxes.xml are changed,
  58. # generate new menudata.xml
  59. if os.path.exists(menudataFile):
  60. # remove menu file when there is no main_menu and toolboxes
  61. if not userToolboxesFile and not userMainMenuFile:
  62. os.remove(menudataFile)
  63. return fallback
  64. if bool(userToolboxesFile) != bool(userMainMenuFile):
  65. # always generate new because we don't know if there has been any change
  66. generateNew = True
  67. else:
  68. # if newer files -> generate new
  69. menudataTime = os.path.getmtime(menudataFile)
  70. if userToolboxesFile:
  71. if os.path.getmtime(userToolboxesFile) > menudataTime:
  72. generateNew = True
  73. if userMainMenuFile:
  74. if os.path.getmtime(userMainMenuFile) > menudataTime:
  75. generateNew = True
  76. elif userToolboxesFile or userMainMenuFile:
  77. generateNew = True
  78. else:
  79. return fallback
  80. if generateNew:
  81. try:
  82. tree = toolboxes2menudata()
  83. except ETREE_EXCEPTIONS:
  84. GError(_("Unable to parse user toolboxes XML files. "
  85. "Default toolboxes will be loaded."))
  86. return fallback
  87. try:
  88. xml = _getXMLString(tree.getroot())
  89. fh = open(os.path.join(tbDir, 'menudata.xml'), 'w')
  90. fh.write(xml)
  91. fh.close()
  92. return menudataFile
  93. except:
  94. return fallback
  95. else:
  96. return menudataFile
  97. else:
  98. return fallback
  99. def _setupToolboxes():
  100. """!Create 'toolboxes' directory if doesn't exist."""
  101. path = os.path.join(GetSettingsPath(), 'toolboxes')
  102. if not os.path.exists(path):
  103. try:
  104. os.mkdir(path)
  105. except:
  106. GError(_('Unable to create toolboxes directory.'))
  107. return None
  108. return path
  109. def toolboxes2menudata(userDefined=True):
  110. """!Creates XML file with data for menu.
  111. Parses toolboxes files from distribution and from users,
  112. puts them together, adds metadata to modules and convert
  113. tree to previous format used for loading menu.
  114. @param userDefined use toolboxes defined by user or not (during compilation)
  115. @return ElementTree instance
  116. """
  117. wxguiItems = etree.parse(wxguiItemsFile)
  118. moduleItems = etree.parse(moduleItemsFile)
  119. if userDefined and userMainMenuFile:
  120. mainMenu = etree.parse(userMainMenuFile)
  121. else:
  122. mainMenu = etree.parse(mainMenuFile)
  123. root = mainMenu.getroot()
  124. if userDefined and userToolboxesFile:
  125. userToolboxes = etree.parse(userToolboxesFile)
  126. _expandUserToolboxesItem(root, userToolboxes)
  127. _expandToolboxes(root, userToolboxes)
  128. if not userToolboxesFile:
  129. _removeUserToolboxesItem(root)
  130. toolboxes = etree.parse(toolboxesFile)
  131. _expandToolboxes(root, toolboxes)
  132. _expandItems(root, moduleItems, 'module-item')
  133. _expandItems(root, wxguiItems, 'wxgui-item')
  134. # in case of compilation there are no additional runtime modules
  135. # but we need to create empty elements
  136. _expandRuntimeModules(root)
  137. _addHandlers(root)
  138. _convertTree(root)
  139. _indent(root)
  140. return mainMenu
  141. def _indent(elem, level=0):
  142. """!Helper function to fix indentation of XML files."""
  143. i = "\n" + level * " "
  144. if len(elem):
  145. if not elem.text or not elem.text.strip():
  146. elem.text = i + " "
  147. if not elem.tail or not elem.tail.strip():
  148. elem.tail = i
  149. for elem in elem:
  150. _indent(elem, level + 1)
  151. if not elem.tail or not elem.tail.strip():
  152. elem.tail = i
  153. else:
  154. if level and (not elem.tail or not elem.tail.strip()):
  155. elem.tail = i
  156. def _expandToolboxes(node, toolboxes):
  157. """!Expands tree with toolboxes.
  158. Function is called recursively.
  159. @param node tree node where to look for subtoolboxes to be expanded
  160. @param toolboxes tree of toolboxes to be used for expansion
  161. >>> menu = etree.fromstring('''
  162. ... <toolbox name="Raster">
  163. ... <label>&amp;Raster</label>
  164. ... <items>
  165. ... <module-item name="r.mask"/>
  166. ... <wxgui-item name="RasterMapCalculator"/>
  167. ... <subtoolbox name="NeighborhoodAnalysis"/>
  168. ... <subtoolbox name="OverlayRasters"/>
  169. ... </items>
  170. ... </toolbox>''')
  171. >>> toolboxes = etree.fromstring('''
  172. ... <toolboxes>
  173. ... <toolbox name="NeighborhoodAnalysis">
  174. ... <label>Neighborhood analysis</label>
  175. ... <items>
  176. ... <module-item name="r.neighbors"/>
  177. ... <module-item name="v.neighbors"/>
  178. ... </items>
  179. ... </toolbox>
  180. ... <toolbox name="OverlayRasters">
  181. ... <label>Overlay rasters</label>
  182. ... <items>
  183. ... <module-item name="r.cross"/>
  184. ... </items>
  185. ... </toolbox>
  186. ... </toolboxes>''')
  187. >>> _expandToolboxes(menu, toolboxes)
  188. >>> print etree.tostring(menu)
  189. <toolbox name="Raster">
  190. <label>&amp;Raster</label>
  191. <items>
  192. <module-item name="r.mask" />
  193. <wxgui-item name="RasterMapCalculator" />
  194. <toolbox name="NeighborhoodAnalysis">
  195. <label>Neighborhood analysis</label>
  196. <items>
  197. <module-item name="r.neighbors" />
  198. <module-item name="v.neighbors" />
  199. </items>
  200. </toolbox>
  201. <toolbox name="OverlayRasters">
  202. <label>Overlay rasters</label>
  203. <items>
  204. <module-item name="r.cross" />
  205. </items>
  206. </toolbox>
  207. </items>
  208. </toolbox>
  209. """
  210. nodes = node.findall('.//toolbox')
  211. if node.tag == 'toolbox': # root
  212. nodes.append(node)
  213. for n in nodes:
  214. if n.find('items') is None:
  215. continue
  216. for subtoolbox in n.findall('./items/subtoolbox'):
  217. items = n.find('./items')
  218. idx = items.getchildren().index(subtoolbox)
  219. if has_xpath:
  220. toolbox = toolboxes.find('.//toolbox[@name="%s"]' % subtoolbox.get('name'))
  221. else:
  222. toolbox = None
  223. potentialToolboxes = toolboxes.findall('.//toolbox')
  224. sName = subtoolbox.get('name')
  225. for pToolbox in potentialToolboxes:
  226. if pToolbox.get('name') == sName:
  227. toolbox = pToolbox
  228. break
  229. if toolbox is None: # not in file
  230. continue
  231. _expandToolboxes(toolbox, toolboxes)
  232. items.insert(idx, toolbox)
  233. items.remove(subtoolbox)
  234. def _expandUserToolboxesItem(node, toolboxes):
  235. """!Expand tag 'user-toolboxes-list'.
  236. Include all user toolboxes.
  237. >>> tree = etree.fromstring('<toolbox><items><user-toolboxes-list/></items></toolbox>')
  238. >>> toolboxes = etree.fromstring('<toolboxes><toolbox name="UserToolbox"><items><module-item name="g.region"/></items></toolbox></toolboxes>')
  239. >>> _expandUserToolboxesItem(tree, toolboxes)
  240. >>> etree.tostring(tree)
  241. '<toolbox><items><toolbox name="GeneratedUserToolboxesList"><label>Toolboxes</label><items><toolbox name="UserToolbox"><items><module-item name="g.region" /></items></toolbox></items></toolbox></items></toolbox>'
  242. """
  243. tboxes = toolboxes.findall('.//toolbox')
  244. for n in node.findall('./items/user-toolboxes-list'):
  245. items = node.find('./items')
  246. idx = items.getchildren().index(n)
  247. el = etree.Element('toolbox', attrib={'name': 'GeneratedUserToolboxesList'})
  248. items.insert(idx, el)
  249. label = etree.SubElement(el, tag='label')
  250. label.text = _("Toolboxes")
  251. it = etree.SubElement(el, tag='items')
  252. for toolbox in tboxes:
  253. it.append(copy.deepcopy(toolbox))
  254. items.remove(n)
  255. def _removeUserToolboxesItem(root):
  256. """!Removes tag 'user-toolboxes-list' if there are no user toolboxes.
  257. >>> tree = etree.fromstring('<toolbox><items><user-toolboxes-list/></items></toolbox>')
  258. >>> _removeUserToolboxesItem(tree)
  259. >>> etree.tostring(tree)
  260. '<toolbox><items /></toolbox>'
  261. """
  262. for n in root.findall('./items/user-toolboxes-list'):
  263. items = root.find('./items')
  264. items.remove(n)
  265. def _expandItems(node, items, itemTag):
  266. """!Expand items from file
  267. >>> tree = etree.fromstring('<items><module-item name="g.region"></module-item></items>')
  268. >>> items = etree.fromstring('<module-items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></module-items>')
  269. >>> _expandItems(tree, items, 'module-item')
  270. >>> etree.tostring(tree)
  271. '<items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></items>'
  272. """
  273. for moduleItem in node.findall('.//' + itemTag):
  274. itemName = moduleItem.get('name')
  275. if has_xpath:
  276. moduleNode = items.find('.//%s[@name="%s"]' % (itemTag, itemName))
  277. else:
  278. moduleNode = None
  279. potentialModuleNodes = items.findall('.//%s' % itemTag)
  280. for mNode in potentialModuleNodes:
  281. if mNode.get('name') == itemName:
  282. moduleNode = mNode
  283. break
  284. if moduleNode is None: # module not available in dist
  285. continue
  286. mItemChildren = moduleItem.getchildren()
  287. tagList = [n.tag for n in mItemChildren]
  288. for node in moduleNode.getchildren():
  289. if node.tag not in tagList:
  290. moduleItem.append(node)
  291. def _expandRuntimeModules(node):
  292. """!Add information to modules (desc, keywords)
  293. by running them with --interface-description.
  294. >>> tree = etree.fromstring('<items>'
  295. ... '<module-item name="g.region"></module-item>'
  296. ... '</items>')
  297. >>> _expandRuntimeModules(tree)
  298. >>> etree.tostring(tree)
  299. '<items><module-item name="g.region"><module>g.region</module><description>Manages the boundary definitions for the geographic region.</description><keywords>general,settings</keywords></module-item></items>'
  300. """
  301. modules = node.findall('.//module-item')
  302. for module in modules:
  303. name = module.get('name')
  304. if module.find('module') is None:
  305. n = etree.SubElement(parent=module, tag='module')
  306. n.text = name
  307. if module.find('description') is None:
  308. desc, keywords = _loadMetadata(name)
  309. n = etree.SubElement(parent=module, tag='description')
  310. n.text = _escapeXML(desc)
  311. n = etree.SubElement(parent=module, tag='keywords')
  312. n.text = _escapeXML(','.join(keywords))
  313. def _escapeXML(text):
  314. """!Helper function for correct escaping characters for XML.
  315. Duplicate function in core/toolboxes and probably also in man compilation
  316. and some existing Python package.
  317. >>> _escapeXML('<>&')
  318. '&amp;lt;&gt;&amp;'
  319. """
  320. return text.replace('<', '&lt;').replace("&", '&amp;').replace(">", '&gt;')
  321. def _loadMetadata(module):
  322. """!Load metadata to modules.
  323. @param module module name
  324. @return (description, keywords as a list)
  325. """
  326. try:
  327. task = gtask.parse_interface(module)
  328. except ScriptError:
  329. return '', ''
  330. return task.get_description(full=True), \
  331. task.get_keywords()
  332. def _addHandlers(node):
  333. """!Add missing handlers to modules"""
  334. for n in node.findall('.//module-item'):
  335. if n.find('handler') is None:
  336. handlerNode = etree.SubElement(parent=n, tag='handler')
  337. handlerNode.text = 'OnMenuCmd'
  338. # e.g. g.region -p
  339. for n in node.findall('.//wxgui-item'):
  340. if n.find('command') is not None:
  341. handlerNode = etree.SubElement(parent=n, tag='handler')
  342. handlerNode.text = 'RunMenuCmd'
  343. def _convertTag(node, old, new):
  344. """!Converts tag name.
  345. >>> tree = etree.fromstring('<toolboxes><toolbox><items><module-item/></items></toolbox></toolboxes>')
  346. >>> _convertTag(tree, 'toolbox', 'menu')
  347. >>> _convertTag(tree, 'module-item', 'menuitem')
  348. >>> etree.tostring(tree)
  349. '<toolboxes><menu><items><menuitem /></items></menu></toolboxes>'
  350. """
  351. for n in node.findall('.//%s' % old):
  352. n.tag = new
  353. def _convertTagAndRemoveAttrib(node, old, new):
  354. """Converts tag name and removes attributes.
  355. >>> tree = etree.fromstring('<toolboxes><toolbox name="Raster"><items><module-item name="g.region"/></items></toolbox></toolboxes>')
  356. >>> _convertTagAndRemoveAttrib(tree, 'toolbox', 'menu')
  357. >>> _convertTagAndRemoveAttrib(tree, 'module-item', 'menuitem')
  358. >>> etree.tostring(tree)
  359. '<toolboxes><menu><items><menuitem /></items></menu></toolboxes>'
  360. """
  361. for n in node.findall('.//%s' % old):
  362. n.tag = new
  363. n.attrib = {}
  364. def _convertTree(root):
  365. """!Converts tree to be the form readable by core/menutree.py.
  366. >>> tree = etree.fromstring('<toolbox name="MainMenu"><label>Main menu</label><items><toolbox><label>Raster</label><items><module-item name="g.region"><module>g.region</module></module-item></items></toolbox></items></toolbox>')
  367. >>> _convertTree(tree)
  368. >>> etree.tostring(tree)
  369. '<menudata><menubar><menu><label>Raster</label><items><menuitem><command>g.region</command></menuitem></items></menu></menubar></menudata>'
  370. """
  371. root.attrib = {}
  372. label = root.find('label')
  373. root.remove(label)
  374. _convertTag(root, 'description', 'help')
  375. _convertTag(root, 'wx-id', 'id')
  376. _convertTag(root, 'module', 'command')
  377. _convertTag(root, 'related-module', 'command')
  378. _convertTagAndRemoveAttrib(root, 'wxgui-item', 'menuitem')
  379. _convertTagAndRemoveAttrib(root, 'module-item', 'menuitem')
  380. root.tag = 'menudata'
  381. i1 = root.find('./items')
  382. i1.tag = 'menubar'
  383. _convertTagAndRemoveAttrib(root, 'toolbox', 'menu')
  384. def _getXMLString(root):
  385. """!Converts XML tree to string
  386. Since it is usually requier, this function adds a comment (about
  387. autogenerated file) to XML file.
  388. @return XML as string
  389. """
  390. xml = etree.tostring(root, encoding='UTF-8')
  391. return xml.replace("<?xml version='1.0' encoding='UTF-8'?>\n",
  392. "<?xml version='1.0' encoding='UTF-8'?>\n"
  393. "<!--This is an auto-generated file-->\n")
  394. def do_doctest_gettext_workaround():
  395. """Setups environment for doing a doctest with gettext usage.
  396. When using gettext with dynamically defined underscore function
  397. (`_("For translation")`), doctest does not work properly. One option is to
  398. use `import as` instead of dynamically defined underscore function but this
  399. would require change all modules which are used by tested module. This
  400. should be considered for the future. The second option is to define dummy
  401. underscore function and one other function which creates the right
  402. environment to satisfy all. This is done by this function.
  403. """
  404. def new_displayhook(string):
  405. """A replacement for default `sys.displayhook`"""
  406. if string is not None:
  407. sys.stdout.write("%r\n" % (string,))
  408. def new_translator(string):
  409. """A fake gettext underscore function."""
  410. return string
  411. sys.displayhook = new_displayhook
  412. import __builtin__
  413. __builtin__._ = new_translator
  414. def test():
  415. """Tests the module using doctest
  416. @return a number of failed tests
  417. """
  418. import doctest
  419. do_doctest_gettext_workaround()
  420. return doctest.testmod().failed
  421. def main():
  422. """Converts the toolboxes files on standard paths to the menudata file
  423. File is written to the standard output.
  424. """
  425. tree = toolboxes2menudata(userDefined=False)
  426. root = tree.getroot()
  427. sys.stdout.write(_getXMLString(root))
  428. return 0
  429. if __name__ == '__main__':
  430. if len(sys.argv) > 1:
  431. if sys.argv[1] == 'doctest':
  432. sys.exit(test())
  433. sys.exit(main())