toolboxes.py 30 KB

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