toolboxes.py 31 KB

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