toolboxes.py 30 KB

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