toolboxes.py 31 KB

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