toolboxes.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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='ag')
  396. except CalledModuleError:
  397. _warning(_("List of addons cannot be obtained"
  398. " because g.extension failed."))
  399. return []
  400. flist = []
  401. for line in output.splitlines():
  402. if not line.startswith('executables'):
  403. continue
  404. for fexe in line.split('=', 1)[1].split(','):
  405. flist.append(fexe)
  406. return sorted(flist)
  407. def _removeAddonsItem(node, addonsNodes):
  408. # TODO: change impl to be similar with the remove toolboxes
  409. for n in addonsNodes:
  410. items = node.find('./items')
  411. if items is not None:
  412. items.remove(n)
  413. # because of inconsistent menudata file
  414. items = node.find('./menubar')
  415. if items is not None:
  416. items.remove(n)
  417. def _expandAddonsItem(node):
  418. """Expands addons element with currently installed addons.
  419. .. note::
  420. there is no mechanism yet to tell the gui to rebuild the
  421. menudata.xml file when new addons are added/removed.
  422. """
  423. # no addonsTag -> do nothing
  424. addonsTags = node.findall('.//addons')
  425. if not addonsTags:
  426. return
  427. # fetch addons
  428. addons = _getAddons()
  429. # no addons -> remove addons tag
  430. if not addons:
  431. _removeAddonsItem(node, addonsTags)
  432. return
  433. # create addons toolbox
  434. # keywords and desc are handled later automatically
  435. for n in addonsTags:
  436. # find parent is not possible with implementation of etree (in 2.7)
  437. items = node.find('./menubar')
  438. idx = items.getchildren().index(n)
  439. # do not set name since it is already in menudata file
  440. # attib={'name': 'AddonsList'}
  441. el = etree.Element('menu')
  442. items.insert(idx, el)
  443. label = etree.SubElement(el, tag='label')
  444. label.text = _("Addons")
  445. it = etree.SubElement(el, tag='items')
  446. for addon in addons:
  447. addonItem = etree.SubElement(it, tag='module-item')
  448. addonItem.attrib = {'name': addon}
  449. addonLabel = etree.SubElement(addonItem, tag='label')
  450. addonLabel.text = addon
  451. items.remove(n)
  452. def _expandItems(node, items, itemTag):
  453. """Expand items from file
  454. >>> tree = etree.fromstring('<items><module-item name="g.region"></module-item></items>')
  455. >>> items = etree.fromstring('<module-items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></module-items>')
  456. >>> _expandItems(tree, items, 'module-item')
  457. >>> etree.tostring(tree)
  458. '<items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></items>'
  459. """
  460. for moduleItem in node.findall('.//' + itemTag):
  461. itemName = moduleItem.get('name')
  462. if has_xpath:
  463. moduleNode = items.find('.//%s[@name="%s"]' % (itemTag, itemName))
  464. else:
  465. moduleNode = None
  466. potentialModuleNodes = items.findall('.//%s' % itemTag)
  467. for mNode in potentialModuleNodes:
  468. if mNode.get('name') == itemName:
  469. moduleNode = mNode
  470. break
  471. if moduleNode is None: # module not available in dist
  472. continue
  473. mItemChildren = moduleItem.getchildren()
  474. tagList = [n.tag for n in mItemChildren]
  475. for node in moduleNode.getchildren():
  476. if node.tag not in tagList:
  477. moduleItem.append(node)
  478. def _expandRuntimeModules(node, loadMetadata=True):
  479. """Add information to modules (desc, keywords)
  480. by running them with --interface-description.
  481. If loadMetadata is False, modules are not called,
  482. useful for incompatible addons.
  483. >>> tree = etree.fromstring('<items>'
  484. ... '<module-item name="g.region"></module-item>'
  485. ... '</items>')
  486. >>> _expandRuntimeModules(tree)
  487. >>> etree.tostring(tree)
  488. '<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>'
  489. >>> tree = etree.fromstring('<items>'
  490. ... '<module-item name="m.proj"></module-item>'
  491. ... '</items>')
  492. >>> _expandRuntimeModules(tree)
  493. >>> etree.tostring(tree)
  494. '<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>'
  495. """
  496. hasErrors = False
  497. modules = node.findall('.//module-item')
  498. for module in modules:
  499. name = module.get('name')
  500. if module.find('module') is None:
  501. n = etree.SubElement(parent=module, tag='module')
  502. n.text = name
  503. if module.find('description') is None:
  504. if loadMetadata:
  505. desc, keywords = _loadMetadata(name)
  506. else:
  507. desc, keywords = '', ''
  508. n = etree.SubElement(parent=module, tag='description')
  509. n.text = _escapeXML(desc)
  510. n = etree.SubElement(parent=module, tag='keywords')
  511. n.text = _escapeXML(','.join(keywords))
  512. if loadMetadata and not desc:
  513. hasErrors = True
  514. if hasErrors:
  515. # not translatable until toolboxes compilation on Mac is fixed
  516. # translating causes importing globalvar, where sys.exit is called
  517. sys.stderr.write("WARNING: Some addons failed when loading. "
  518. "Please consider to update your addons by running 'g.extension.all -f'.\n")
  519. def _escapeXML(text):
  520. """Helper function for correct escaping characters for XML.
  521. Duplicate function in core/toolboxes and probably also in man compilation
  522. and some existing Python package.
  523. >>> _escapeXML('<>&')
  524. '&amp;lt;&gt;&amp;'
  525. """
  526. return text.replace('<', '&lt;').replace("&", '&amp;').replace(">", '&gt;')
  527. def _loadMetadata(module):
  528. """Load metadata to modules.
  529. :param module: module name
  530. :return: (description, keywords as a list)
  531. """
  532. try:
  533. task = gtask.parse_interface(module)
  534. except ScriptError as e:
  535. sys.stderr.write("%s: %s\n" % (module, e))
  536. return '', ''
  537. return task.get_description(full=True), \
  538. task.get_keywords()
  539. def _addHandlers(node):
  540. """Add missing handlers to modules"""
  541. for n in node.findall('.//module-item'):
  542. if n.find('handler') is None:
  543. handlerNode = etree.SubElement(parent=n, tag='handler')
  544. handlerNode.text = 'OnMenuCmd'
  545. # e.g. g.region -p
  546. for n in node.findall('.//wxgui-item'):
  547. if n.find('command') is not None:
  548. handlerNode = etree.SubElement(parent=n, tag='handler')
  549. handlerNode.text = 'RunMenuCmd'
  550. def _convertTag(node, old, new):
  551. """Converts tag name.
  552. >>> tree = etree.fromstring('<toolboxes><toolbox><items><module-item/></items></toolbox></toolboxes>')
  553. >>> _convertTag(tree, 'toolbox', 'menu')
  554. >>> _convertTag(tree, 'module-item', 'menuitem')
  555. >>> etree.tostring(tree)
  556. '<toolboxes><menu><items><menuitem /></items></menu></toolboxes>'
  557. """
  558. for n in node.findall('.//%s' % old):
  559. n.tag = new
  560. def _convertTagAndRemoveAttrib(node, old, new):
  561. """Converts tag name and removes attributes.
  562. >>> tree = etree.fromstring('<toolboxes><toolbox name="Raster"><items><module-item name="g.region"/></items></toolbox></toolboxes>')
  563. >>> _convertTagAndRemoveAttrib(tree, 'toolbox', 'menu')
  564. >>> _convertTagAndRemoveAttrib(tree, 'module-item', 'menuitem')
  565. >>> etree.tostring(tree)
  566. '<toolboxes><menu><items><menuitem /></items></menu></toolboxes>'
  567. """
  568. for n in node.findall('.//%s' % old):
  569. n.tag = new
  570. n.attrib = {}
  571. def _convertTree(root):
  572. """Converts tree to be the form readable by core/menutree.py.
  573. >>> 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>')
  574. >>> _convertTree(tree)
  575. >>> etree.tostring(tree)
  576. '<menudata><menubar><menu><label>Raster</label><items><menuitem><command>g.region</command></menuitem></items></menu></menubar></menudata>'
  577. """
  578. root.attrib = {}
  579. label = root.find('label')
  580. # must check because of inconsistent XML menudata file
  581. if label is not None:
  582. root.remove(label)
  583. _convertTag(root, 'description', 'help')
  584. _convertTag(root, 'wx-id', 'id')
  585. _convertTag(root, 'module', 'command')
  586. _convertTag(root, 'related-module', 'command')
  587. _convertTagAndRemoveAttrib(root, 'wxgui-item', 'menuitem')
  588. _convertTagAndRemoveAttrib(root, 'module-item', 'menuitem')
  589. root.tag = 'menudata'
  590. i1 = root.find('./items')
  591. # must check because of inconsistent XML menudata file
  592. if i1 is not None:
  593. i1.tag = 'menubar'
  594. _convertTagAndRemoveAttrib(root, 'toolbox', 'menu')
  595. def _getXMLString(root):
  596. """Converts XML tree to string
  597. Since it is usually requier, this function adds a comment (about
  598. autogenerated file) to XML file.
  599. :return: XML as string
  600. """
  601. xml = etree.tostring(root, encoding='UTF-8')
  602. return xml.replace("<?xml version='1.0' encoding='UTF-8'?>\n",
  603. "<?xml version='1.0' encoding='UTF-8'?>\n"
  604. "<!--This is an auto-generated file-->\n")
  605. def do_doctest_gettext_workaround():
  606. """Setups environment for doing a doctest with gettext usage.
  607. When using gettext with dynamically defined underscore function
  608. (`_("For translation")`), doctest does not work properly.
  609. One option is to use `import as` instead of dynamically defined
  610. underscore function but this requires change all modules which are
  611. used by tested module.
  612. The second option is to define dummy underscore function and one
  613. other function which creates the right environment to satisfy all.
  614. This is done by this function. Moreover, `sys.displayhook` and also
  615. `sys.__displayhook__` needs to be redefined too (the later one probably
  616. should not be newer redefined but some cases just requires that).
  617. GRASS specific note is that wxGUI switched to use imported
  618. underscore function for translation. However, GRASS Python libraries
  619. still uses the dynamically defined underscore function, so this
  620. workaround function is still needed when you import something from
  621. GRASS Python libraries.
  622. """
  623. def new_displayhook(string):
  624. """A replacement for default `sys.displayhook`"""
  625. if string is not None:
  626. sys.stdout.write("%r\n" % (string,))
  627. def new_translator(string):
  628. """A fake gettext underscore function."""
  629. return string
  630. sys.displayhook = new_displayhook
  631. sys.__displayhook__ = new_displayhook
  632. import __builtin__
  633. __builtin__._ = new_translator
  634. def doc_test():
  635. """Tests the module using doctest
  636. :return: a number of failed tests
  637. """
  638. import doctest
  639. do_doctest_gettext_workaround()
  640. return doctest.testmod().failed
  641. def module_test():
  642. """Tests the module using test files included in the current
  643. directory and in files from distribution.
  644. """
  645. toolboxesFile = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
  646. userToolboxesFile = 'data/test_toolboxes_user_toolboxes.xml'
  647. menuFile = 'data/test_toolboxes_menu.xml'
  648. wxguiItemsFile = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
  649. moduleItemsFile = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
  650. toolboxes = etree.parse(toolboxesFile)
  651. userToolboxes = etree.parse(userToolboxesFile)
  652. menu = etree.parse(menuFile)
  653. wxguiItems = etree.parse(wxguiItemsFile)
  654. moduleItems = etree.parse(moduleItemsFile)
  655. tree = toolboxes2menudata(mainMenu=menu,
  656. toolboxes=toolboxes,
  657. userToolboxes=userToolboxes,
  658. wxguiItems=wxguiItems,
  659. moduleItems=moduleItems)
  660. root = tree.getroot()
  661. tested = _getXMLString(root)
  662. # for generating correct test file supposing that the implementation
  663. # is now correct and working
  664. # run the normal test and check the difference before overwriting
  665. # the old correct test file
  666. if len(sys.argv) > 2 and sys.argv[2] == "generate-correct-file":
  667. sys.stdout.write(_getXMLString(root))
  668. return 0
  669. menudataFile = 'data/test_toolboxes_menudata_ref.xml'
  670. with open(menudataFile) as correctMenudata:
  671. correct = str(correctMenudata.read())
  672. import difflib
  673. differ = difflib.Differ()
  674. result = list(differ.compare(correct.splitlines(True),
  675. tested.splitlines(True)))
  676. someDiff = False
  677. for line in result:
  678. if line.startswith('+') or line.startswith('-'):
  679. sys.stdout.write(line)
  680. someDiff = True
  681. if someDiff:
  682. print "Difference between files."
  683. return 1
  684. else:
  685. print "OK"
  686. return 0
  687. def validate_file(filename):
  688. try:
  689. etree.parse(filename)
  690. except ETREE_EXCEPTIONS as error:
  691. print "XML file <{name}> is not well formed: {error}".format(
  692. name=filename, error=error)
  693. return 1
  694. return 0
  695. def main():
  696. """Converts the toolboxes files on standard paths to the menudata file
  697. File is written to the standard output.
  698. """
  699. # TODO: fix parameter handling
  700. if len(sys.argv) > 1:
  701. mainFile = os.path.join(WXGUIDIR, 'xml', 'module_tree.xml')
  702. else:
  703. mainFile = os.path.join(WXGUIDIR, 'xml', 'main_menu.xml')
  704. tree = createTree(distributionRootFile=mainFile, userRootFile=None,
  705. userDefined=False)
  706. root = tree.getroot()
  707. sys.stdout.write(_getXMLString(root))
  708. return 0
  709. if __name__ == '__main__':
  710. # TODO: fix parameter handling
  711. if len(sys.argv) > 1:
  712. if sys.argv[1] == 'doctest':
  713. sys.exit(doc_test())
  714. elif sys.argv[1] == 'test':
  715. sys.exit(module_test())
  716. elif sys.argv[1] == 'validate':
  717. sys.exit(validate_file(sys.argv[2]))
  718. sys.exit(main())