toolboxes.py 20 KB

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