toolboxes.py 19 KB

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