toolboxes.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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. from __future__ import print_function
  11. import os
  12. import sys
  13. import copy
  14. import xml.etree.ElementTree as etree
  15. from xml.parsers import expat
  16. # Get the XML parsing exceptions to catch. The behavior chnaged with Python 2.7
  17. # and ElementTree 1.3.
  18. if hasattr(etree, 'ParseError'):
  19. ETREE_EXCEPTIONS = (etree.ParseError, expat.ExpatError)
  20. else:
  21. ETREE_EXCEPTIONS = (expat.ExpatError)
  22. if sys.version_info[0:2] > (2, 6):
  23. has_xpath = True
  24. else:
  25. has_xpath = False
  26. import grass.script.task as gtask
  27. import grass.script.core as gcore
  28. from grass.script.utils import try_remove, decode
  29. from grass.exceptions import ScriptError, CalledModuleError
  30. # duplicating code from core/globalvar.py
  31. # if this will become part of grass Python library or module, this should be
  32. # parametrized, so we will get rid of the definition here
  33. # (GUI will use its definition and build also its own)
  34. WXGUIDIR = os.path.join(os.getenv("GISBASE"), "gui", "wxpython")
  35. # this could be placed to functions
  36. mainMenuFile = os.path.join(WXGUIDIR, 'xml', 'main_menu.xml')
  37. toolboxesFile = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
  38. wxguiItemsFile = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
  39. moduleItemsFile = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
  40. def GetSettingsPath():
  41. # this is for cases during compilation and it is not possible to import wx
  42. # TODO: if the function would be in the grass Python library there would
  43. # no need to do this
  44. try:
  45. from core.utils import GetSettingsPath as actualGetSettingsPath
  46. return actualGetSettingsPath()
  47. except ImportError:
  48. # expecting that there will be no such path
  49. # (these files are always check for existence here)
  50. return ""
  51. def _getUserToolboxesFile():
  52. userToolboxesFile = os.path.join(
  53. GetSettingsPath(),
  54. 'toolboxes', 'toolboxes.xml')
  55. if not os.path.exists(userToolboxesFile):
  56. userToolboxesFile = None
  57. return userToolboxesFile
  58. def _getUserMainMenuFile():
  59. userMainMenuFile = os.path.join(
  60. GetSettingsPath(),
  61. 'toolboxes', 'main_menu.xml')
  62. if not os.path.exists(userMainMenuFile):
  63. userMainMenuFile = None
  64. return userMainMenuFile
  65. # TODO: this should be part of some reader object
  66. _MESSAGES = []
  67. def _warning(message):
  68. """Show warning"""
  69. _MESSAGES.append("WARNING: %s" % message)
  70. def getMessages():
  71. return _MESSAGES
  72. def clearMessages():
  73. del _MESSAGES[:]
  74. def _debug(level, message):
  75. """Show debug message"""
  76. # this has interface as originally used GUI Debug but uses grass.script
  77. gcore.debug(message, level)
  78. def toolboxesOutdated():
  79. """Removes auto-generated menudata.xml
  80. to let gui regenerate it next time it starts."""
  81. path = os.path.join(GetSettingsPath(), 'toolboxes', 'menudata.xml')
  82. if os.path.exists(path):
  83. try_remove(path)
  84. def getMenudataFile(userRootFile, newFile, fallback):
  85. """Returns path to XML file for building menu or another tree.
  86. Creates toolbox directory where user defined toolboxes should be
  87. located. Checks whether it is needed to create new XML file (user
  88. changed toolboxes) or the already generated file could be used.
  89. If something goes wrong during building or user doesn't modify menu,
  90. default file (from distribution) is returned.
  91. """
  92. _debug(
  93. 1,
  94. "toolboxes.getMenudataFile: {userRootFile}, {newFile}, {fallback}".format(
  95. **locals()))
  96. distributionRootFile = os.path.join(WXGUIDIR, 'xml', userRootFile)
  97. userRootFile = os.path.join(GetSettingsPath(), 'toolboxes', userRootFile)
  98. if not os.path.exists(userRootFile):
  99. userRootFile = None
  100. # always create toolboxes directory if does not exist yet
  101. tbDir = _setupToolboxes()
  102. if tbDir:
  103. menudataFile = os.path.join(tbDir, newFile)
  104. generateNew = False
  105. # when any of main_menu.xml or toolboxes.xml are changed,
  106. # generate new menudata.xml
  107. if os.path.exists(menudataFile):
  108. # remove menu file when there is no main_menu and toolboxes
  109. if not _getUserToolboxesFile() and not userRootFile:
  110. os.remove(menudataFile)
  111. _debug(
  112. 2, "toolboxes.getMenudataFile: no user defined files, menudata deleted")
  113. return fallback
  114. if bool(_getUserToolboxesFile()) != bool(userRootFile):
  115. # always generate new because we don't know if there has been
  116. # any change
  117. generateNew = True
  118. _debug(
  119. 2, "toolboxes.getMenudataFile: only one of the user defined files")
  120. else:
  121. # if newer files -> generate new
  122. menudataTime = os.path.getmtime(menudataFile)
  123. if _getUserToolboxesFile():
  124. if os.path.getmtime(
  125. _getUserToolboxesFile()) > menudataTime:
  126. _debug(
  127. 2, "toolboxes.getMenudataFile: user toolboxes is newer than menudata")
  128. generateNew = True
  129. if userRootFile:
  130. if os.path.getmtime(userRootFile) > menudataTime:
  131. _debug(
  132. 2, "toolboxes.getMenudataFile: user root file is newer than menudata")
  133. generateNew = True
  134. elif _getUserToolboxesFile() or userRootFile:
  135. _debug(2, "toolboxes.getMenudataFile: no menudata")
  136. generateNew = True
  137. else:
  138. _debug(2, "toolboxes.getMenudataFile: no user defined files")
  139. return fallback
  140. if generateNew:
  141. try:
  142. # The case when user does not have custom root
  143. # file but has toolboxes requieres regeneration.
  144. # Unfortunately, this is the case can be often: defined
  145. # toolboxes but undefined module tree file.
  146. _debug(2, "toolboxes.getMenudataFile: creating a tree")
  147. tree = createTree(
  148. distributionRootFile=distributionRootFile,
  149. userRootFile=userRootFile)
  150. except ETREE_EXCEPTIONS:
  151. _warning(_("Unable to parse user toolboxes XML files. "
  152. "Default files will be loaded."))
  153. return fallback
  154. try:
  155. xml = _getXMLString(tree.getroot())
  156. fh = open(menudataFile, 'w')
  157. fh.write(xml)
  158. fh.close()
  159. return menudataFile
  160. except:
  161. _debug(
  162. 2,
  163. "toolboxes.getMenudataFile: writing menudata failed, returning fallback file")
  164. return fallback
  165. else:
  166. return menudataFile
  167. else:
  168. _debug(2, "toolboxes.getMenudataFile: returning menudata fallback file")
  169. return fallback
  170. def _setupToolboxes():
  171. """Create 'toolboxes' directory if doesn't exist."""
  172. basePath = GetSettingsPath()
  173. path = os.path.join(basePath, 'toolboxes')
  174. if not os.path.exists(basePath):
  175. return None
  176. if _createPath(path):
  177. return path
  178. return None
  179. def _createPath(path):
  180. """Creates path (for toolboxes) if it doesn't exist'"""
  181. if not os.path.exists(path):
  182. try:
  183. os.mkdir(path)
  184. except OSError as e:
  185. # we cannot use GError or similar because the gui doesn't start at
  186. # all
  187. gcore.warning(
  188. '%(reason)s\n%(detail)s' % ({
  189. 'reason': _('Unable to create toolboxes directory.'),
  190. 'detail': str(e)}))
  191. return False
  192. return True
  193. def createTree(distributionRootFile, userRootFile, userDefined=True):
  194. """Creates XML file with data for menu.
  195. Parses toolboxes files from distribution and from users,
  196. puts them together, adds metadata to modules and convert
  197. tree to previous format used for loading menu.
  198. :param userDefined: use toolboxes defined by user or not (during compilation)
  199. :return: ElementTree instance
  200. """
  201. if userDefined and userRootFile:
  202. mainMenu = etree.parse(userRootFile)
  203. else:
  204. mainMenu = etree.parse(distributionRootFile)
  205. toolboxes = etree.parse(toolboxesFile)
  206. if userDefined and _getUserToolboxesFile():
  207. userToolboxes = etree.parse(_getUserToolboxesFile())
  208. else:
  209. userToolboxes = None
  210. wxguiItems = etree.parse(wxguiItemsFile)
  211. moduleItems = etree.parse(moduleItemsFile)
  212. return toolboxes2menudata(mainMenu=mainMenu,
  213. toolboxes=toolboxes,
  214. userToolboxes=userToolboxes,
  215. wxguiItems=wxguiItems,
  216. moduleItems=moduleItems)
  217. def toolboxes2menudata(mainMenu, toolboxes, userToolboxes,
  218. wxguiItems, moduleItems):
  219. """Creates XML file with data for menu.
  220. Parses toolboxes files from distribution and from users,
  221. puts them together, adds metadata to modules and convert
  222. tree to previous format used for loading menu.
  223. :param userDefined: use toolboxes defined by user or not (during compilation)
  224. :return: ElementTree instance
  225. """
  226. root = mainMenu.getroot()
  227. userHasToolboxes = False
  228. # in case user has empty toolboxes file (to avoid genereation)
  229. if userToolboxes and userToolboxes.findall('.//toolbox'):
  230. _expandUserToolboxesItem(root, userToolboxes)
  231. _expandToolboxes(root, userToolboxes)
  232. userHasToolboxes = True
  233. if not userHasToolboxes:
  234. _removeUserToolboxesItem(root)
  235. _expandToolboxes(root, toolboxes)
  236. # we do not expand addons here since they need to be expanded in runtime
  237. _expandItems(root, moduleItems, 'module-item')
  238. _expandItems(root, wxguiItems, 'wxgui-item')
  239. # in case of compilation there are no additional runtime modules
  240. # but we need to create empty elements
  241. _expandRuntimeModules(root)
  242. _addHandlers(root)
  243. _convertTree(root)
  244. _indent(root)
  245. return mainMenu
  246. def _indent(elem, level=0):
  247. """Helper function to fix indentation of XML files."""
  248. i = "\n" + level * " "
  249. if len(elem):
  250. if not elem.text or not elem.text.strip():
  251. elem.text = i + " "
  252. if not elem.tail or not elem.tail.strip():
  253. elem.tail = i
  254. for elem in elem:
  255. _indent(elem, level + 1)
  256. if not elem.tail or not elem.tail.strip():
  257. elem.tail = i
  258. else:
  259. if level and (not elem.tail or not elem.tail.strip()):
  260. elem.tail = i
  261. def expandAddons(tree):
  262. """Expands addons element.
  263. """
  264. root = tree.getroot()
  265. _expandAddonsItem(root)
  266. # expanding and converting is done twice, so there is some overhead
  267. # we don't load metadata by calling modules on Windows because when
  268. # installed addons are not compatible, Windows show ugly crash dialog
  269. # for every incompatible addon
  270. if sys.platform == "win32":
  271. _expandRuntimeModules(root, loadMetadata=False)
  272. else:
  273. _expandRuntimeModules(root, loadMetadata=True)
  274. _addHandlers(root)
  275. _convertTree(root)
  276. def _expandToolboxes(node, toolboxes):
  277. """Expands tree with toolboxes.
  278. Function is called recursively.
  279. :param node: tree node where to look for subtoolboxes to be expanded
  280. :param toolboxes: tree of toolboxes to be used for expansion
  281. >>> menu = etree.fromstring('''
  282. ... <toolbox name="Raster">
  283. ... <label>&amp;Raster</label>
  284. ... <items>
  285. ... <module-item name="r.mask"/>
  286. ... <wxgui-item name="RasterMapCalculator"/>
  287. ... <subtoolbox name="NeighborhoodAnalysis"/>
  288. ... <subtoolbox name="OverlayRasters"/>
  289. ... </items>
  290. ... </toolbox>''')
  291. >>> toolboxes = etree.fromstring('''
  292. ... <toolboxes>
  293. ... <toolbox name="NeighborhoodAnalysis">
  294. ... <label>Neighborhood analysis</label>
  295. ... <items>
  296. ... <module-item name="r.neighbors"/>
  297. ... <module-item name="v.neighbors"/>
  298. ... </items>
  299. ... </toolbox>
  300. ... <toolbox name="OverlayRasters">
  301. ... <label>Overlay rasters</label>
  302. ... <items>
  303. ... <module-item name="r.cross"/>
  304. ... </items>
  305. ... </toolbox>
  306. ... </toolboxes>''')
  307. >>> _expandToolboxes(menu, toolboxes)
  308. >>> print(etree.tostring(menu))
  309. <toolbox name="Raster">
  310. <label>&amp;Raster</label>
  311. <items>
  312. <module-item name="r.mask" />
  313. <wxgui-item name="RasterMapCalculator" />
  314. <toolbox name="NeighborhoodAnalysis">
  315. <label>Neighborhood analysis</label>
  316. <items>
  317. <module-item name="r.neighbors" />
  318. <module-item name="v.neighbors" />
  319. </items>
  320. </toolbox>
  321. <toolbox name="OverlayRasters">
  322. <label>Overlay rasters</label>
  323. <items>
  324. <module-item name="r.cross" />
  325. </items>
  326. </toolbox>
  327. </items>
  328. </toolbox>
  329. """
  330. nodes = node.findall('.//toolbox')
  331. if node.tag == 'toolbox': # root
  332. nodes.append(node)
  333. for n in nodes:
  334. if n.find('items') is None:
  335. continue
  336. for subtoolbox in n.findall('./items/subtoolbox'):
  337. items = n.find('./items')
  338. idx = items.getchildren().index(subtoolbox)
  339. if has_xpath:
  340. toolbox = toolboxes.find(
  341. './/toolbox[@name="%s"]' %
  342. subtoolbox.get('name'))
  343. else:
  344. toolbox = None
  345. potentialToolboxes = toolboxes.findall('.//toolbox')
  346. sName = subtoolbox.get('name')
  347. for pToolbox in potentialToolboxes:
  348. if pToolbox.get('name') == sName:
  349. toolbox = pToolbox
  350. break
  351. if toolbox is None: # not in file
  352. continue
  353. _expandToolboxes(toolbox, toolboxes)
  354. items.insert(idx, toolbox)
  355. items.remove(subtoolbox)
  356. def _expandUserToolboxesItem(node, toolboxes):
  357. """Expand tag 'user-toolboxes-list'.
  358. Include all user toolboxes.
  359. >>> tree = etree.fromstring('<toolbox><items><user-toolboxes-list/></items></toolbox>')
  360. >>> toolboxes = etree.fromstring('<toolboxes><toolbox name="UserToolbox"><items><module-item name="g.region"/></items></toolbox></toolboxes>')
  361. >>> _expandUserToolboxesItem(tree, toolboxes)
  362. >>> etree.tostring(tree)
  363. b'<toolbox><items><toolbox name="GeneratedUserToolboxesList"><label>Custom toolboxes</label><items><toolbox name="UserToolbox"><items><module-item name="g.region" /></items></toolbox></items></toolbox></items></toolbox>'
  364. """
  365. tboxes = toolboxes.findall('.//toolbox')
  366. for n in node.findall('./items/user-toolboxes-list'):
  367. items = node.find('./items')
  368. idx = items.getchildren().index(n)
  369. el = etree.Element(
  370. 'toolbox', attrib={
  371. 'name': 'GeneratedUserToolboxesList'})
  372. items.insert(idx, el)
  373. label = etree.SubElement(el, 'label')
  374. label.text = _("Custom toolboxes")
  375. it = etree.SubElement(el, 'items')
  376. for toolbox in tboxes:
  377. it.append(copy.deepcopy(toolbox))
  378. items.remove(n)
  379. def _removeUserToolboxesItem(root):
  380. """Removes tag 'user-toolboxes-list' if there are no user toolboxes.
  381. >>> tree = etree.fromstring('<toolbox><items><user-toolboxes-list/></items></toolbox>')
  382. >>> _removeUserToolboxesItem(tree)
  383. >>> etree.tostring(tree)
  384. b'<toolbox><items /></toolbox>'
  385. """
  386. for n in root.findall('./items/user-toolboxes-list'):
  387. items = root.find('./items')
  388. items.remove(n)
  389. def _getAddons():
  390. try:
  391. output = gcore.read_command('g.extension', quiet=True, flags='ag')
  392. except CalledModuleError as error:
  393. _warning(_("List of addons cannot be obtained"
  394. " because g.extension failed."
  395. " Details: %s") % error)
  396. return []
  397. flist = []
  398. for line in output.splitlines():
  399. if not line.startswith('name'):
  400. continue
  401. for fexe in line.split('=', 1)[1].split(','):
  402. flist.append(fexe)
  403. return sorted(flist)
  404. def _removeAddonsItem(node, addonsNodes):
  405. # TODO: change impl to be similar with the remove toolboxes
  406. for n in addonsNodes:
  407. items = node.find('./items')
  408. if items is not None:
  409. items.remove(n)
  410. # because of inconsistent menudata file
  411. items = node.find('./menubar')
  412. if items is not None:
  413. items.remove(n)
  414. def _expandAddonsItem(node):
  415. """Expands addons element with currently installed addons.
  416. .. note::
  417. there is no mechanism yet to tell the gui to rebuild the
  418. menudata.xml file when new addons are added/removed.
  419. """
  420. # no addonsTag -> do nothing
  421. addonsTags = node.findall('.//addons')
  422. if not addonsTags:
  423. return
  424. # fetch addons
  425. addons = _getAddons()
  426. # no addons -> remove addons tag
  427. if not addons:
  428. _removeAddonsItem(node, addonsTags)
  429. return
  430. # create addons toolbox
  431. # keywords and desc are handled later automatically
  432. for n in addonsTags:
  433. # find parent is not possible with implementation of etree (in 2.7)
  434. items = node.find('./menubar')
  435. idx = items.getchildren().index(n)
  436. # do not set name since it is already in menudata file
  437. # attib={'name': 'AddonsList'}
  438. el = etree.Element('menu')
  439. items.insert(idx, el)
  440. label = etree.SubElement(el, 'label')
  441. label.text = _("Addons")
  442. it = etree.SubElement(el, 'items')
  443. for addon in addons:
  444. addonItem = etree.SubElement(it, 'module-item')
  445. addonItem.attrib = {'name': addon}
  446. addonLabel = etree.SubElement(addonItem, 'label')
  447. addonLabel.text = addon
  448. items.remove(n)
  449. def _expandItems(node, items, itemTag):
  450. """Expand items from file
  451. >>> tree = etree.fromstring('<items><module-item name="g.region"></module-item></items>')
  452. >>> items = etree.fromstring('<module-items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></module-items>')
  453. >>> _expandItems(tree, items, 'module-item')
  454. >>> etree.tostring(tree)
  455. b'<items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></items>'
  456. """
  457. for moduleItem in node.findall('.//' + itemTag):
  458. itemName = moduleItem.get('name')
  459. if has_xpath:
  460. moduleNode = items.find('.//%s[@name="%s"]' % (itemTag, itemName))
  461. else:
  462. moduleNode = None
  463. potentialModuleNodes = items.findall('.//%s' % itemTag)
  464. for mNode in potentialModuleNodes:
  465. if mNode.get('name') == itemName:
  466. moduleNode = mNode
  467. break
  468. if moduleNode is None: # module not available in dist
  469. continue
  470. mItemChildren = moduleItem.getchildren()
  471. tagList = [n.tag for n in mItemChildren]
  472. for node in moduleNode.getchildren():
  473. if node.tag not in tagList:
  474. moduleItem.append(node)
  475. def _expandRuntimeModules(node, loadMetadata=True):
  476. """Add information to modules (desc, keywords)
  477. by running them with --interface-description.
  478. If loadMetadata is False, modules are not called,
  479. useful for incompatible addons.
  480. >>> tree = etree.fromstring('<items>'
  481. ... '<module-item name="g.region"></module-item>'
  482. ... '</items>')
  483. >>> _expandRuntimeModules(tree)
  484. >>> etree.tostring(tree)
  485. b'<items><module-item name="g.region"><module>g.region</module><description>Manages the boundary definitions for the geographic region.</description><keywords>general,settings,computational region,extent,resolution,level1</keywords></module-item></items>'
  486. >>> tree = etree.fromstring('<items>'
  487. ... '<module-item name="m.proj"></module-item>'
  488. ... '</items>')
  489. >>> _expandRuntimeModules(tree)
  490. >>> etree.tostring(tree)
  491. b'<items><module-item name="m.proj"><module>m.proj</module><description>Converts coordinates from one projection to another (cs2cs frontend).</description><keywords>miscellaneous,projection,transformation</keywords></module-item></items>'
  492. """
  493. hasErrors = False
  494. modules = node.findall('.//module-item')
  495. for module in modules:
  496. name = module.get('name')
  497. if module.find('module') is None:
  498. n = etree.SubElement(module, 'module')
  499. n.text = name
  500. if module.find('description') is None:
  501. if loadMetadata:
  502. desc, keywords = _loadMetadata(name)
  503. else:
  504. desc, keywords = '', ''
  505. n = etree.SubElement(module, 'description')
  506. n.text = _escapeXML(desc)
  507. n = etree.SubElement(module, 'keywords')
  508. n.text = _escapeXML(','.join(keywords))
  509. if loadMetadata and not desc:
  510. hasErrors = True
  511. if hasErrors:
  512. # not translatable until toolboxes compilation on Mac is fixed
  513. # translating causes importing globalvar, where sys.exit is called
  514. sys.stderr.write(
  515. "WARNING: Some addons failed when loading. "
  516. "Please consider to update your addons by running 'g.extension.all -f'.\n")
  517. def _escapeXML(text):
  518. """Helper function for correct escaping characters for XML.
  519. Duplicate function in core/toolboxes and probably also in man compilation
  520. and some existing Python package.
  521. >>> _escapeXML('<>&')
  522. '&amp;lt;&gt;&amp;'
  523. """
  524. return text.replace('<', '&lt;').replace("&", '&amp;').replace(">", '&gt;')
  525. def _loadMetadata(module):
  526. """Load metadata to modules.
  527. :param module: module name
  528. :return: (description, keywords as a list)
  529. """
  530. try:
  531. task = gtask.parse_interface(module)
  532. except ScriptError as e:
  533. sys.stderr.write("%s: %s\n" % (module, e))
  534. return '', ''
  535. return task.get_description(full=True), \
  536. task.get_keywords()
  537. def _addHandlers(node):
  538. """Add missing handlers to modules"""
  539. for n in node.findall('.//module-item'):
  540. if n.find('handler') is None:
  541. handlerNode = etree.SubElement(n, 'handler')
  542. handlerNode.text = 'OnMenuCmd'
  543. # e.g. g.region -p
  544. for n in node.findall('.//wxgui-item'):
  545. if n.find('command') is not None:
  546. handlerNode = etree.SubElement(n, 'handler')
  547. handlerNode.text = 'RunMenuCmd'
  548. def _convertTag(node, old, new):
  549. """Converts tag name.
  550. >>> tree = etree.fromstring('<toolboxes><toolbox><items><module-item/></items></toolbox></toolboxes>')
  551. >>> _convertTag(tree, 'toolbox', 'menu')
  552. >>> _convertTag(tree, 'module-item', 'menuitem')
  553. >>> etree.tostring(tree)
  554. b'<toolboxes><menu><items><menuitem /></items></menu></toolboxes>'
  555. """
  556. for n in node.findall('.//%s' % old):
  557. n.tag = new
  558. def _convertTagAndRemoveAttrib(node, old, new):
  559. """Converts tag name and removes attributes.
  560. >>> tree = etree.fromstring('<toolboxes><toolbox name="Raster"><items><module-item name="g.region"/></items></toolbox></toolboxes>')
  561. >>> _convertTagAndRemoveAttrib(tree, 'toolbox', 'menu')
  562. >>> _convertTagAndRemoveAttrib(tree, 'module-item', 'menuitem')
  563. >>> etree.tostring(tree)
  564. b'<toolboxes><menu><items><menuitem /></items></menu></toolboxes>'
  565. """
  566. for n in node.findall('.//%s' % old):
  567. n.tag = new
  568. n.attrib = {}
  569. def _convertTree(root):
  570. """Converts tree to be the form readable by core/menutree.py.
  571. >>> 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>')
  572. >>> _convertTree(tree)
  573. >>> etree.tostring(tree)
  574. b'<menudata><menubar><menu><label>Raster</label><items><menuitem><command>g.region</command></menuitem></items></menu></menubar></menudata>'
  575. """
  576. root.attrib = {}
  577. label = root.find('label')
  578. # must check because of inconsistent XML menudata file
  579. if label is not None:
  580. root.remove(label)
  581. _convertTag(root, 'description', 'help')
  582. _convertTag(root, 'wx-id', 'id')
  583. _convertTag(root, 'module', 'command')
  584. _convertTag(root, 'related-module', 'command')
  585. _convertTagAndRemoveAttrib(root, 'wxgui-item', 'menuitem')
  586. _convertTagAndRemoveAttrib(root, 'module-item', 'menuitem')
  587. root.tag = 'menudata'
  588. i1 = root.find('./items')
  589. # must check because of inconsistent XML menudata file
  590. if i1 is not None:
  591. i1.tag = 'menubar'
  592. _convertTagAndRemoveAttrib(root, 'toolbox', 'menu')
  593. def _getXMLString(root):
  594. """Converts XML tree to string
  595. Since it is usually requier, this function adds a comment (about
  596. autogenerated file) to XML file.
  597. :return: XML as string
  598. """
  599. xml = etree.tostring(root, encoding='UTF-8')
  600. return xml.replace(b"<?xml version='1.0' encoding='UTF-8'?>\n",
  601. b"<?xml version='1.0' encoding='UTF-8'?>\n"
  602. b"<!--This is an auto-generated file-->\n")
  603. def do_doctest_gettext_workaround():
  604. """Setups environment for doing a doctest with gettext usage.
  605. When using gettext with dynamically defined underscore function
  606. (`_("For translation")`), doctest does not work properly.
  607. One option is to use `import as` instead of dynamically defined
  608. underscore function but this requires change all modules which are
  609. used by tested module.
  610. The second option is to define dummy underscore function and one
  611. other function which creates the right environment to satisfy all.
  612. This is done by this function. Moreover, `sys.displayhook` and also
  613. `sys.__displayhook__` needs to be redefined too (the later one probably
  614. should not be newer redefined but some cases just requires that).
  615. GRASS specific note is that wxGUI switched to use imported
  616. underscore function for translation. However, GRASS Python libraries
  617. still uses the dynamically defined underscore function, so this
  618. workaround function is still needed when you import something from
  619. GRASS Python libraries.
  620. """
  621. def new_displayhook(string):
  622. """A replacement for default `sys.displayhook`"""
  623. if string is not None:
  624. sys.stdout.write("%r\n" % (string,))
  625. def new_translator(string):
  626. """A fake gettext underscore function."""
  627. return string
  628. sys.displayhook = new_displayhook
  629. sys.__displayhook__ = new_displayhook
  630. import __builtin__
  631. __builtin__._ = new_translator
  632. def doc_test():
  633. """Tests the module using doctest
  634. :return: a number of failed tests
  635. """
  636. import doctest
  637. do_doctest_gettext_workaround()
  638. return doctest.testmod().failed
  639. def module_test():
  640. """Tests the module using test files included in the current
  641. directory and in files from distribution.
  642. """
  643. toolboxesFile = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
  644. userToolboxesFile = 'data/test_toolboxes_user_toolboxes.xml'
  645. menuFile = 'data/test_toolboxes_menu.xml'
  646. wxguiItemsFile = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
  647. moduleItemsFile = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
  648. toolboxes = etree.parse(toolboxesFile)
  649. userToolboxes = etree.parse(userToolboxesFile)
  650. menu = etree.parse(menuFile)
  651. wxguiItems = etree.parse(wxguiItemsFile)
  652. moduleItems = etree.parse(moduleItemsFile)
  653. tree = toolboxes2menudata(mainMenu=menu,
  654. toolboxes=toolboxes,
  655. userToolboxes=userToolboxes,
  656. wxguiItems=wxguiItems,
  657. moduleItems=moduleItems)
  658. root = tree.getroot()
  659. tested = _getXMLString(root)
  660. # for generating correct test file supposing that the implementation
  661. # is now correct and working
  662. # run the normal test and check the difference before overwriting
  663. # the old correct test file
  664. if len(sys.argv) > 2 and sys.argv[2] == "generate-correct-file":
  665. sys.stdout.write(_getXMLString(root))
  666. return 0
  667. menudataFile = 'data/test_toolboxes_menudata_ref.xml'
  668. with open(menudataFile) as correctMenudata:
  669. correct = str(correctMenudata.read())
  670. import difflib
  671. differ = difflib.Differ()
  672. result = list(differ.compare(correct.splitlines(True),
  673. tested.splitlines(True)))
  674. someDiff = False
  675. for line in result:
  676. if line.startswith('+') or line.startswith('-'):
  677. sys.stdout.write(line)
  678. someDiff = True
  679. if someDiff:
  680. print("Difference between files.")
  681. return 1
  682. else:
  683. print("OK")
  684. return 0
  685. def validate_file(filename):
  686. try:
  687. etree.parse(filename)
  688. except ETREE_EXCEPTIONS as error:
  689. print("XML file <{name}> is not well formed: {error}".format(
  690. name=filename, error=error))
  691. return 1
  692. return 0
  693. def main():
  694. """Converts the toolboxes files on standard paths to the menudata file
  695. File is written to the standard output.
  696. """
  697. # TODO: fix parameter handling
  698. if len(sys.argv) > 1:
  699. mainFile = os.path.join(WXGUIDIR, 'xml', 'module_tree.xml')
  700. else:
  701. mainFile = os.path.join(WXGUIDIR, 'xml', 'main_menu.xml')
  702. tree = createTree(distributionRootFile=mainFile, userRootFile=None,
  703. userDefined=False)
  704. root = tree.getroot()
  705. sys.stdout.write(decode(_getXMLString(root), encoding='UTF-8'))
  706. return 0
  707. if __name__ == '__main__':
  708. # TODO: fix parameter handling
  709. if len(sys.argv) > 1:
  710. if sys.argv[1] == 'doctest':
  711. sys.exit(doc_test())
  712. elif sys.argv[1] == 'test':
  713. sys.exit(module_test())
  714. elif sys.argv[1] == 'validate':
  715. sys.exit(validate_file(sys.argv[2]))
  716. sys.exit(main())