toolboxes.py 30 KB

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