toolboxes.py 21 KB

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