toolboxes.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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
  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. toolboxes = etree.parse(toolboxesFile)
  149. _expandToolboxes(root, toolboxes)
  150. _expandItems(root, moduleItems, 'module-item')
  151. _expandItems(root, wxguiItems, 'wxgui-item')
  152. # in case of compilation there are no additional runtime modules
  153. # but we need to create empty elements
  154. _expandRuntimeModules(root)
  155. _addHandlers(root)
  156. _convertTree(root)
  157. _indent(root)
  158. return mainMenu
  159. def _indent(elem, level=0):
  160. """!Helper function to fix indentation of XML files."""
  161. i = "\n" + level * " "
  162. if len(elem):
  163. if not elem.text or not elem.text.strip():
  164. elem.text = i + " "
  165. if not elem.tail or not elem.tail.strip():
  166. elem.tail = i
  167. for elem in elem:
  168. _indent(elem, level + 1)
  169. if not elem.tail or not elem.tail.strip():
  170. elem.tail = i
  171. else:
  172. if level and (not elem.tail or not elem.tail.strip()):
  173. elem.tail = i
  174. def _expandToolboxes(node, toolboxes):
  175. """!Expands tree with toolboxes.
  176. Function is called recursively.
  177. @param node tree node where to look for subtoolboxes to be expanded
  178. @param toolboxes tree of toolboxes to be used for expansion
  179. >>> menu = etree.fromstring('''
  180. ... <toolbox name="Raster">
  181. ... <label>&amp;Raster</label>
  182. ... <items>
  183. ... <module-item name="r.mask"/>
  184. ... <wxgui-item name="RasterMapCalculator"/>
  185. ... <subtoolbox name="NeighborhoodAnalysis"/>
  186. ... <subtoolbox name="OverlayRasters"/>
  187. ... </items>
  188. ... </toolbox>''')
  189. >>> toolboxes = etree.fromstring('''
  190. ... <toolboxes>
  191. ... <toolbox name="NeighborhoodAnalysis">
  192. ... <label>Neighborhood analysis</label>
  193. ... <items>
  194. ... <module-item name="r.neighbors"/>
  195. ... <module-item name="v.neighbors"/>
  196. ... </items>
  197. ... </toolbox>
  198. ... <toolbox name="OverlayRasters">
  199. ... <label>Overlay rasters</label>
  200. ... <items>
  201. ... <module-item name="r.cross"/>
  202. ... </items>
  203. ... </toolbox>
  204. ... </toolboxes>''')
  205. >>> _expandToolboxes(menu, toolboxes)
  206. >>> print etree.tostring(menu)
  207. <toolbox name="Raster">
  208. <label>&amp;Raster</label>
  209. <items>
  210. <module-item name="r.mask" />
  211. <wxgui-item name="RasterMapCalculator" />
  212. <toolbox name="NeighborhoodAnalysis">
  213. <label>Neighborhood analysis</label>
  214. <items>
  215. <module-item name="r.neighbors" />
  216. <module-item name="v.neighbors" />
  217. </items>
  218. </toolbox>
  219. <toolbox name="OverlayRasters">
  220. <label>Overlay rasters</label>
  221. <items>
  222. <module-item name="r.cross" />
  223. </items>
  224. </toolbox>
  225. </items>
  226. </toolbox>
  227. """
  228. nodes = node.findall('.//toolbox')
  229. if node.tag == 'toolbox': # root
  230. nodes.append(node)
  231. for n in nodes:
  232. if n.find('items') is None:
  233. continue
  234. for subtoolbox in n.findall('./items/subtoolbox'):
  235. items = n.find('./items')
  236. idx = items.getchildren().index(subtoolbox)
  237. if has_xpath:
  238. toolbox = toolboxes.find('.//toolbox[@name="%s"]' % subtoolbox.get('name'))
  239. else:
  240. toolbox = None
  241. potentialToolboxes = toolboxes.findall('.//toolbox')
  242. sName = subtoolbox.get('name')
  243. for pToolbox in potentialToolboxes:
  244. if pToolbox.get('name') == sName:
  245. toolbox = pToolbox
  246. break
  247. if toolbox is None: # not in file
  248. continue
  249. _expandToolboxes(toolbox, toolboxes)
  250. items.insert(idx, toolbox)
  251. items.remove(subtoolbox)
  252. def _expandUserToolboxesItem(node, toolboxes):
  253. """!Expand tag 'user-toolboxes-list'.
  254. Include all user toolboxes.
  255. >>> tree = etree.fromstring('<toolbox><items><user-toolboxes-list/></items></toolbox>')
  256. >>> toolboxes = etree.fromstring('<toolboxes><toolbox name="UserToolbox"><items><module-item name="g.region"/></items></toolbox></toolboxes>')
  257. >>> _expandUserToolboxesItem(tree, toolboxes)
  258. >>> etree.tostring(tree)
  259. '<toolbox><items><toolbox name="GeneratedUserToolboxesList"><label>Toolboxes</label><items><toolbox name="UserToolbox"><items><module-item name="g.region" /></items></toolbox></items></toolbox></items></toolbox>'
  260. """
  261. tboxes = toolboxes.findall('.//toolbox')
  262. for n in node.findall('./items/user-toolboxes-list'):
  263. items = node.find('./items')
  264. idx = items.getchildren().index(n)
  265. el = etree.Element('toolbox', attrib={'name': 'GeneratedUserToolboxesList'})
  266. items.insert(idx, el)
  267. label = etree.SubElement(el, tag='label')
  268. label.text = _("Toolboxes")
  269. it = etree.SubElement(el, tag='items')
  270. for toolbox in tboxes:
  271. it.append(copy.deepcopy(toolbox))
  272. items.remove(n)
  273. def _removeUserToolboxesItem(root):
  274. """!Removes tag 'user-toolboxes-list' if there are no user toolboxes.
  275. >>> tree = etree.fromstring('<toolbox><items><user-toolboxes-list/></items></toolbox>')
  276. >>> _removeUserToolboxesItem(tree)
  277. >>> etree.tostring(tree)
  278. '<toolbox><items /></toolbox>'
  279. """
  280. for n in root.findall('./items/user-toolboxes-list'):
  281. items = root.find('./items')
  282. items.remove(n)
  283. def _expandItems(node, items, itemTag):
  284. """!Expand items from file
  285. >>> tree = etree.fromstring('<items><module-item name="g.region"></module-item></items>')
  286. >>> items = etree.fromstring('<module-items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></module-items>')
  287. >>> _expandItems(tree, items, 'module-item')
  288. >>> etree.tostring(tree)
  289. '<items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></items>'
  290. """
  291. for moduleItem in node.findall('.//' + itemTag):
  292. itemName = moduleItem.get('name')
  293. if has_xpath:
  294. moduleNode = items.find('.//%s[@name="%s"]' % (itemTag, itemName))
  295. else:
  296. moduleNode = None
  297. potentialModuleNodes = items.findall('.//%s' % itemTag)
  298. for mNode in potentialModuleNodes:
  299. if mNode.get('name') == itemName:
  300. moduleNode = mNode
  301. break
  302. if moduleNode is None: # module not available in dist
  303. continue
  304. mItemChildren = moduleItem.getchildren()
  305. tagList = [n.tag for n in mItemChildren]
  306. for node in moduleNode.getchildren():
  307. if node.tag not in tagList:
  308. moduleItem.append(node)
  309. def _expandRuntimeModules(node):
  310. """!Add information to modules (desc, keywords)
  311. by running them with --interface-description.
  312. >>> tree = etree.fromstring('<items>'
  313. ... '<module-item name="g.region"></module-item>'
  314. ... '</items>')
  315. >>> _expandRuntimeModules(tree)
  316. >>> etree.tostring(tree)
  317. '<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>'
  318. """
  319. modules = node.findall('.//module-item')
  320. for module in modules:
  321. name = module.get('name')
  322. if module.find('module') is None:
  323. n = etree.SubElement(parent=module, tag='module')
  324. n.text = name
  325. if module.find('description') is None:
  326. desc, keywords = _loadMetadata(name)
  327. n = etree.SubElement(parent=module, tag='description')
  328. n.text = _escapeXML(desc)
  329. n = etree.SubElement(parent=module, tag='keywords')
  330. n.text = _escapeXML(','.join(keywords))
  331. def _escapeXML(text):
  332. """!Helper function for correct escaping characters for XML.
  333. Duplicate function in core/toolboxes and probably also in man compilation
  334. and some existing Python package.
  335. >>> _escapeXML('<>&')
  336. '&amp;lt;&gt;&amp;'
  337. """
  338. return text.replace('<', '&lt;').replace("&", '&amp;').replace(">", '&gt;')
  339. def _loadMetadata(module):
  340. """!Load metadata to modules.
  341. @param module module name
  342. @return (description, keywords as a list)
  343. """
  344. try:
  345. task = gtask.parse_interface(module)
  346. except ScriptError:
  347. return '', ''
  348. return task.get_description(full=True), \
  349. task.get_keywords()
  350. def _addHandlers(node):
  351. """!Add missing handlers to modules"""
  352. for n in node.findall('.//module-item'):
  353. if n.find('handler') is None:
  354. handlerNode = etree.SubElement(parent=n, tag='handler')
  355. handlerNode.text = 'OnMenuCmd'
  356. # e.g. g.region -p
  357. for n in node.findall('.//wxgui-item'):
  358. if n.find('command') is not None:
  359. handlerNode = etree.SubElement(parent=n, tag='handler')
  360. handlerNode.text = 'RunMenuCmd'
  361. def _convertTag(node, old, new):
  362. """!Converts tag name.
  363. >>> tree = etree.fromstring('<toolboxes><toolbox><items><module-item/></items></toolbox></toolboxes>')
  364. >>> _convertTag(tree, 'toolbox', 'menu')
  365. >>> _convertTag(tree, 'module-item', 'menuitem')
  366. >>> etree.tostring(tree)
  367. '<toolboxes><menu><items><menuitem /></items></menu></toolboxes>'
  368. """
  369. for n in node.findall('.//%s' % old):
  370. n.tag = new
  371. def _convertTagAndRemoveAttrib(node, old, new):
  372. """Converts tag name and removes attributes.
  373. >>> tree = etree.fromstring('<toolboxes><toolbox name="Raster"><items><module-item name="g.region"/></items></toolbox></toolboxes>')
  374. >>> _convertTagAndRemoveAttrib(tree, 'toolbox', 'menu')
  375. >>> _convertTagAndRemoveAttrib(tree, 'module-item', 'menuitem')
  376. >>> etree.tostring(tree)
  377. '<toolboxes><menu><items><menuitem /></items></menu></toolboxes>'
  378. """
  379. for n in node.findall('.//%s' % old):
  380. n.tag = new
  381. n.attrib = {}
  382. def _convertTree(root):
  383. """!Converts tree to be the form readable by core/menutree.py.
  384. >>> 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>')
  385. >>> _convertTree(tree)
  386. >>> etree.tostring(tree)
  387. '<menudata><menubar><menu><label>Raster</label><items><menuitem><command>g.region</command></menuitem></items></menu></menubar></menudata>'
  388. """
  389. root.attrib = {}
  390. label = root.find('label')
  391. root.remove(label)
  392. _convertTag(root, 'description', 'help')
  393. _convertTag(root, 'wx-id', 'id')
  394. _convertTag(root, 'module', 'command')
  395. _convertTag(root, 'related-module', 'command')
  396. _convertTagAndRemoveAttrib(root, 'wxgui-item', 'menuitem')
  397. _convertTagAndRemoveAttrib(root, 'module-item', 'menuitem')
  398. root.tag = 'menudata'
  399. i1 = root.find('./items')
  400. i1.tag = 'menubar'
  401. _convertTagAndRemoveAttrib(root, 'toolbox', 'menu')
  402. def _getXMLString(root):
  403. """!Converts XML tree to string
  404. Since it is usually requier, this function adds a comment (about
  405. autogenerated file) to XML file.
  406. @return XML as string
  407. """
  408. xml = etree.tostring(root, encoding='UTF-8')
  409. return xml.replace("<?xml version='1.0' encoding='UTF-8'?>\n",
  410. "<?xml version='1.0' encoding='UTF-8'?>\n"
  411. "<!--This is an auto-generated file-->\n")
  412. def do_doctest_gettext_workaround():
  413. """Setups environment for doing a doctest with gettext usage.
  414. When using gettext with dynamically defined underscore function
  415. (`_("For translation")`), doctest does not work properly. One option is to
  416. use `import as` instead of dynamically defined underscore function but this
  417. would require change all modules which are used by tested module. This
  418. should be considered for the future. The second option is to define dummy
  419. underscore function and one other function which creates the right
  420. environment to satisfy all. This is done by this function.
  421. """
  422. def new_displayhook(string):
  423. """A replacement for default `sys.displayhook`"""
  424. if string is not None:
  425. sys.stdout.write("%r\n" % (string,))
  426. def new_translator(string):
  427. """A fake gettext underscore function."""
  428. return string
  429. sys.displayhook = new_displayhook
  430. import __builtin__
  431. __builtin__._ = new_translator
  432. def test():
  433. """Tests the module using doctest
  434. @return a number of failed tests
  435. """
  436. import doctest
  437. do_doctest_gettext_workaround()
  438. return doctest.testmod().failed
  439. def main():
  440. """Converts the toolboxes files on standard paths to the menudata file
  441. File is written to the standard output.
  442. """
  443. tree = toolboxes2menudata(userDefined=False)
  444. root = tree.getroot()
  445. sys.stdout.write(_getXMLString(root))
  446. return 0
  447. if __name__ == '__main__':
  448. if len(sys.argv) > 1:
  449. if sys.argv[1] == 'doctest':
  450. sys.exit(test())
  451. sys.exit(main())