toolboxes.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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. """Get translated version of a string"""
  58. # is attribute initialized to actual value?
  59. if _.translate is None:
  60. try:
  61. # if not get the translate function named _
  62. from core.utils import _ as actual_translate
  63. # assign the imported function to translade attribute
  64. _.translate = actual_translate
  65. except ImportError:
  66. # speak English if there is a problem with import of wx
  67. def noop_traslate(string):
  68. return string
  69. _.translate = noop_traslate
  70. return _.translate(string)
  71. # attribute translate of function _
  72. _.translate = None
  73. def _warning(message):
  74. """Show warning"""
  75. # TODO: enable choice between GUI and script behavior
  76. # import only when really needed
  77. from core.gcmd import GError
  78. GError(message)
  79. def _debug(level, message):
  80. """Show debug message"""
  81. # this has interface as originally used GUI Debug but uses grass.script
  82. gcore.debug(message, level)
  83. def _encode_string(string):
  84. """Encode a unicode *string* using the system encoding
  85. If it is not possible to use system encoding, UTF-8 is used.
  86. """
  87. try:
  88. from core.gcmd import EncodeString
  89. return EncodeString(string)
  90. except ImportError:
  91. # This is the case when we have errors during compilation but
  92. # the environment is not complete (compilation, custom setups
  93. # of GRASS environmet) and we cannot import wx correctly.
  94. # UTF-8 is pretty good guess for most cases (and should work for
  95. # Mac OS X where wx 32 vs 64 bit issue is happaning).
  96. return string.encode('utf-8')
  97. def toolboxesOutdated():
  98. """Removes auto-generated menudata.xml
  99. to let gui regenerate it next time it starts."""
  100. path = os.path.join(GetSettingsPath(), 'toolboxes', 'menudata.xml')
  101. if os.path.exists(path):
  102. try_remove(path)
  103. def getMenudataFile(userRootFile, newFile, fallback):
  104. """Returns path to XML file for building menu or another tree.
  105. Creates toolbox directory where user defined toolboxes should be
  106. located. Checks whether it is needed to create new XML file (user
  107. changed toolboxes) or the already generated file could be used.
  108. If something goes wrong during building or user doesn't modify menu,
  109. default file (from distribution) is returned.
  110. """
  111. _debug(1, "toolboxes.getMenudataFile: {userRootFile}, {newFile}, {fallback}".format(**locals()))
  112. distributionRootFile = os.path.join(WXGUIDIR, 'xml', userRootFile)
  113. userRootFile = os.path.join(GetSettingsPath(), 'toolboxes', userRootFile)
  114. if not os.path.exists(userRootFile):
  115. userRootFile = None
  116. # always create toolboxes directory if does not exist yet
  117. tbDir = _setupToolboxes()
  118. if tbDir:
  119. menudataFile = os.path.join(tbDir, newFile)
  120. generateNew = False
  121. # when any of main_menu.xml or toolboxes.xml are changed,
  122. # generate new menudata.xml
  123. if os.path.exists(menudataFile):
  124. # remove menu file when there is no main_menu and toolboxes
  125. if not userToolboxesFile and not userRootFile:
  126. os.remove(menudataFile)
  127. _debug(2, "toolboxes.getMenudataFile: no user defined files, menudata deleted")
  128. return fallback
  129. if bool(userToolboxesFile) != bool(userRootFile):
  130. # always generate new because we don't know if there has been any change
  131. generateNew = True
  132. _debug(2, "toolboxes.getMenudataFile: only one of the user defined files")
  133. else:
  134. # if newer files -> generate new
  135. menudataTime = os.path.getmtime(menudataFile)
  136. if userToolboxesFile:
  137. if os.path.getmtime(userToolboxesFile) > menudataTime:
  138. _debug(2, "toolboxes.getMenudataFile: user toolboxes is newer than menudata")
  139. generateNew = True
  140. if userRootFile:
  141. if os.path.getmtime(userRootFile) > menudataTime:
  142. _debug(2, "toolboxes.getMenudataFile: user root file is newer than menudata")
  143. generateNew = True
  144. elif userToolboxesFile or userRootFile:
  145. _debug(2, "toolboxes.getMenudataFile: no menudata")
  146. generateNew = True
  147. else:
  148. _debug(2, "toolboxes.getMenudataFile: no user defined files")
  149. return fallback
  150. if generateNew:
  151. try:
  152. # The case when user does not have custom root
  153. # file but has toolboxes requieres regeneration.
  154. # Unfortunately, this is the case can be often: defined
  155. # toolboxes but undefined module tree file.
  156. _debug(2, "toolboxes.getMenudataFile: creating a tree")
  157. tree = createTree(distributionRootFile=distributionRootFile, userRootFile=userRootFile)
  158. except ETREE_EXCEPTIONS:
  159. _warning(_("Unable to parse user toolboxes XML files. "
  160. "Default files will be loaded."))
  161. return fallback
  162. try:
  163. xml = _getXMLString(tree.getroot())
  164. fh = open(menudataFile, 'w')
  165. fh.write(xml)
  166. fh.close()
  167. return menudataFile
  168. except:
  169. _debug(2, "toolboxes.getMenudataFile: writing menudata failed, returning fallback file")
  170. return fallback
  171. else:
  172. return menudataFile
  173. else:
  174. _debug(2, "toolboxes.getMenudataFile: returning menudata fallback file")
  175. return fallback
  176. def _setupToolboxes():
  177. """Create 'toolboxes' directory if doesn't exist."""
  178. basePath = GetSettingsPath()
  179. path = os.path.join(basePath, 'toolboxes')
  180. if not os.path.exists(basePath):
  181. return None
  182. if _createPath(path):
  183. return path
  184. return None
  185. def _createPath(path):
  186. """Creates path (for toolboxes) if it doesn't exist'"""
  187. if not os.path.exists(path):
  188. try:
  189. os.mkdir(path)
  190. except OSError as e:
  191. # we cannot use GError or similar because the gui doesn't start at all
  192. gcore.warning('%(reason)s\n%(detail)s' %
  193. ({'reason':_('Unable to create toolboxes directory.'),
  194. 'detail': str(e)}))
  195. return False
  196. return True
  197. def createTree(distributionRootFile, userRootFile, userDefined=True):
  198. """Creates XML file with data for menu.
  199. Parses toolboxes files from distribution and from users,
  200. puts them together, adds metadata to modules and convert
  201. tree to previous format used for loading menu.
  202. :param userDefined: use toolboxes defined by user or not (during compilation)
  203. :return: ElementTree instance
  204. """
  205. if userDefined and userRootFile:
  206. mainMenu = etree.parse(userRootFile)
  207. else:
  208. mainMenu = etree.parse(distributionRootFile)
  209. toolboxes = etree.parse(toolboxesFile)
  210. if userDefined and userToolboxesFile:
  211. userToolboxes = etree.parse(userToolboxesFile)
  212. else:
  213. userToolboxes = None
  214. wxguiItems = etree.parse(wxguiItemsFile)
  215. moduleItems = etree.parse(moduleItemsFile)
  216. return toolboxes2menudata(mainMenu=mainMenu,
  217. toolboxes=toolboxes,
  218. userToolboxes=userToolboxes,
  219. wxguiItems=wxguiItems,
  220. moduleItems=moduleItems)
  221. def toolboxes2menudata(mainMenu, toolboxes, userToolboxes,
  222. wxguiItems, moduleItems):
  223. """Creates XML file with data for menu.
  224. Parses toolboxes files from distribution and from users,
  225. puts them together, adds metadata to modules and convert
  226. tree to previous format used for loading menu.
  227. :param userDefined: use toolboxes defined by user or not (during compilation)
  228. :return: ElementTree instance
  229. """
  230. root = mainMenu.getroot()
  231. userHasToolboxes = False
  232. # in case user has empty toolboxes file (to avoid genereation)
  233. if userToolboxes and userToolboxes.findall('.//toolbox'):
  234. _expandUserToolboxesItem(root, userToolboxes)
  235. _expandToolboxes(root, userToolboxes)
  236. userHasToolboxes = True
  237. if not userHasToolboxes:
  238. _removeUserToolboxesItem(root)
  239. _expandToolboxes(root, toolboxes)
  240. # we do not expand addons here since they need to be expanded in runtime
  241. _expandItems(root, moduleItems, 'module-item')
  242. _expandItems(root, wxguiItems, 'wxgui-item')
  243. # in case of compilation there are no additional runtime modules
  244. # but we need to create empty elements
  245. _expandRuntimeModules(root)
  246. _addHandlers(root)
  247. _convertTree(root)
  248. _indent(root)
  249. return mainMenu
  250. def _indent(elem, level=0):
  251. """Helper function to fix indentation of XML files."""
  252. i = "\n" + level * " "
  253. if len(elem):
  254. if not elem.text or not elem.text.strip():
  255. elem.text = i + " "
  256. if not elem.tail or not elem.tail.strip():
  257. elem.tail = i
  258. for elem in elem:
  259. _indent(elem, level + 1)
  260. if not elem.tail or not elem.tail.strip():
  261. elem.tail = i
  262. else:
  263. if level and (not elem.tail or not elem.tail.strip()):
  264. elem.tail = i
  265. def expandAddons(tree):
  266. """Expands addons element.
  267. """
  268. root = tree.getroot()
  269. _expandAddonsItem(root)
  270. # expanding and converting is done twice, so there is some overhead
  271. # we don't load metadata by calling modules on Windows because when
  272. # installed addons are not compatible, Windows show ugly crash dialog
  273. # for every incompatible addon
  274. if sys.platform == "win32":
  275. _expandRuntimeModules(root, loadMetadata=False)
  276. else:
  277. _expandRuntimeModules(root, loadMetadata=True)
  278. _addHandlers(root)
  279. _convertTree(root)
  280. def _expandToolboxes(node, toolboxes):
  281. """Expands tree with toolboxes.
  282. Function is called recursively.
  283. :param node: tree node where to look for subtoolboxes to be expanded
  284. :param toolboxes: tree of toolboxes to be used for expansion
  285. >>> menu = etree.fromstring('''
  286. ... <toolbox name="Raster">
  287. ... <label>&amp;Raster</label>
  288. ... <items>
  289. ... <module-item name="r.mask"/>
  290. ... <wxgui-item name="RasterMapCalculator"/>
  291. ... <subtoolbox name="NeighborhoodAnalysis"/>
  292. ... <subtoolbox name="OverlayRasters"/>
  293. ... </items>
  294. ... </toolbox>''')
  295. >>> toolboxes = etree.fromstring('''
  296. ... <toolboxes>
  297. ... <toolbox name="NeighborhoodAnalysis">
  298. ... <label>Neighborhood analysis</label>
  299. ... <items>
  300. ... <module-item name="r.neighbors"/>
  301. ... <module-item name="v.neighbors"/>
  302. ... </items>
  303. ... </toolbox>
  304. ... <toolbox name="OverlayRasters">
  305. ... <label>Overlay rasters</label>
  306. ... <items>
  307. ... <module-item name="r.cross"/>
  308. ... </items>
  309. ... </toolbox>
  310. ... </toolboxes>''')
  311. >>> _expandToolboxes(menu, toolboxes)
  312. >>> print etree.tostring(menu)
  313. <toolbox name="Raster">
  314. <label>&amp;Raster</label>
  315. <items>
  316. <module-item name="r.mask" />
  317. <wxgui-item name="RasterMapCalculator" />
  318. <toolbox name="NeighborhoodAnalysis">
  319. <label>Neighborhood analysis</label>
  320. <items>
  321. <module-item name="r.neighbors" />
  322. <module-item name="v.neighbors" />
  323. </items>
  324. </toolbox>
  325. <toolbox name="OverlayRasters">
  326. <label>Overlay rasters</label>
  327. <items>
  328. <module-item name="r.cross" />
  329. </items>
  330. </toolbox>
  331. </items>
  332. </toolbox>
  333. """
  334. nodes = node.findall('.//toolbox')
  335. if node.tag == 'toolbox': # root
  336. nodes.append(node)
  337. for n in nodes:
  338. if n.find('items') is None:
  339. continue
  340. for subtoolbox in n.findall('./items/subtoolbox'):
  341. items = n.find('./items')
  342. idx = items.getchildren().index(subtoolbox)
  343. if has_xpath:
  344. toolbox = toolboxes.find('.//toolbox[@name="%s"]' % subtoolbox.get('name'))
  345. else:
  346. toolbox = None
  347. potentialToolboxes = toolboxes.findall('.//toolbox')
  348. sName = subtoolbox.get('name')
  349. for pToolbox in potentialToolboxes:
  350. if pToolbox.get('name') == sName:
  351. toolbox = pToolbox
  352. break
  353. if toolbox is None: # not in file
  354. continue
  355. _expandToolboxes(toolbox, toolboxes)
  356. items.insert(idx, toolbox)
  357. items.remove(subtoolbox)
  358. def _expandUserToolboxesItem(node, toolboxes):
  359. """Expand tag 'user-toolboxes-list'.
  360. Include all user toolboxes.
  361. >>> tree = etree.fromstring('<toolbox><items><user-toolboxes-list/></items></toolbox>')
  362. >>> toolboxes = etree.fromstring('<toolboxes><toolbox name="UserToolbox"><items><module-item name="g.region"/></items></toolbox></toolboxes>')
  363. >>> _expandUserToolboxesItem(tree, toolboxes)
  364. >>> etree.tostring(tree)
  365. '<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>'
  366. """
  367. tboxes = toolboxes.findall('.//toolbox')
  368. for n in node.findall('./items/user-toolboxes-list'):
  369. items = node.find('./items')
  370. idx = items.getchildren().index(n)
  371. el = etree.Element('toolbox', attrib={'name': 'GeneratedUserToolboxesList'})
  372. items.insert(idx, el)
  373. label = etree.SubElement(el, tag='label')
  374. label.text = _("Custom toolboxes")
  375. it = etree.SubElement(el, tag='items')
  376. for toolbox in tboxes:
  377. it.append(copy.deepcopy(toolbox))
  378. items.remove(n)
  379. def _removeUserToolboxesItem(root):
  380. """Removes tag 'user-toolboxes-list' if there are no user toolboxes.
  381. >>> tree = etree.fromstring('<toolbox><items><user-toolboxes-list/></items></toolbox>')
  382. >>> _removeUserToolboxesItem(tree)
  383. >>> etree.tostring(tree)
  384. '<toolbox><items /></toolbox>'
  385. """
  386. for n in root.findall('./items/user-toolboxes-list'):
  387. items = root.find('./items')
  388. items.remove(n)
  389. def _getAddons():
  390. try:
  391. output = gcore.read_command('g.extension', quiet=True, flags='a')
  392. except CalledModuleError:
  393. _warning(_("List of addons cannot be obtained"
  394. " because g.extension failed."))
  395. return []
  396. return sorted(output.splitlines())
  397. def _removeAddonsItem(node, addonsNodes):
  398. # TODO: change impl to be similar with the remove toolboxes
  399. for n in addonsNodes:
  400. items = node.find('./items')
  401. if items is not None:
  402. items.remove(n)
  403. # because of inconsistent menudata file
  404. items = node.find('./menubar')
  405. if items is not None:
  406. items.remove(n)
  407. def _expandAddonsItem(node):
  408. """Expands addons element with currently installed addons.
  409. .. note::
  410. there is no mechanism yet to tell the gui to rebuild the
  411. menudata.xml file when new addons are added/removed.
  412. """
  413. # no addonsTag -> do nothing
  414. addonsTags = node.findall('.//addons')
  415. if not addonsTags:
  416. return
  417. # fetch addons
  418. addons = _getAddons()
  419. # no addons -> remove addons tag
  420. if not addons:
  421. _removeAddonsItem(node, addonsTags)
  422. return
  423. # create addons toolbox
  424. # keywords and desc are handled later automatically
  425. for n in addonsTags:
  426. # find parent is not possible with implementation of etree (in 2.7)
  427. items = node.find('./menubar')
  428. idx = items.getchildren().index(n)
  429. # do not set name since it is already in menudata file
  430. # attib={'name': 'AddonsList'}
  431. el = etree.Element('menu')
  432. items.insert(idx, el)
  433. label = etree.SubElement(el, tag='label')
  434. label.text = _("Addons")
  435. it = etree.SubElement(el, tag='items')
  436. for addon in addons:
  437. addonItem = etree.SubElement(it, tag='module-item')
  438. addonItem.attrib = {'name': addon}
  439. addonLabel = etree.SubElement(addonItem, tag='label')
  440. addonLabel.text = addon
  441. items.remove(n)
  442. def _expandItems(node, items, itemTag):
  443. """Expand items from file
  444. >>> tree = etree.fromstring('<items><module-item name="g.region"></module-item></items>')
  445. >>> items = etree.fromstring('<module-items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></module-items>')
  446. >>> _expandItems(tree, items, 'module-item')
  447. >>> etree.tostring(tree)
  448. '<items><module-item name="g.region"><module>g.region</module><description>GRASS region management</description></module-item></items>'
  449. """
  450. for moduleItem in node.findall('.//' + itemTag):
  451. itemName = moduleItem.get('name')
  452. if has_xpath:
  453. moduleNode = items.find('.//%s[@name="%s"]' % (itemTag, itemName))
  454. else:
  455. moduleNode = None
  456. potentialModuleNodes = items.findall('.//%s' % itemTag)
  457. for mNode in potentialModuleNodes:
  458. if mNode.get('name') == itemName:
  459. moduleNode = mNode
  460. break
  461. if moduleNode is None: # module not available in dist
  462. continue
  463. mItemChildren = moduleItem.getchildren()
  464. tagList = [n.tag for n in mItemChildren]
  465. for node in moduleNode.getchildren():
  466. if node.tag not in tagList:
  467. moduleItem.append(node)
  468. def _expandRuntimeModules(node, loadMetadata=True):
  469. """Add information to modules (desc, keywords)
  470. by running them with --interface-description.
  471. If loadMetadata is False, modules are not called,
  472. useful for incompatible addons.
  473. >>> tree = etree.fromstring('<items>'
  474. ... '<module-item name="g.region"></module-item>'
  475. ... '</items>')
  476. >>> _expandRuntimeModules(tree)
  477. >>> etree.tostring(tree)
  478. '<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>'
  479. >>> tree = etree.fromstring('<items>'
  480. ... '<module-item name="m.proj"></module-item>'
  481. ... '</items>')
  482. >>> _expandRuntimeModules(tree)
  483. >>> etree.tostring(tree)
  484. '<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>'
  485. """
  486. hasErrors = False
  487. modules = node.findall('.//module-item')
  488. for module in modules:
  489. name = module.get('name')
  490. if module.find('module') is None:
  491. n = etree.SubElement(parent=module, tag='module')
  492. n.text = name
  493. if module.find('description') is None:
  494. if loadMetadata:
  495. desc, keywords = _loadMetadata(name)
  496. else:
  497. desc, keywords = '', ''
  498. n = etree.SubElement(parent=module, tag='description')
  499. n.text = _escapeXML(desc)
  500. n = etree.SubElement(parent=module, tag='keywords')
  501. n.text = _escapeXML(','.join(keywords))
  502. if loadMetadata and not desc:
  503. hasErrors = True
  504. if hasErrors:
  505. sys.stderr.write(_("WARNING: Some addons failed when loading. "
  506. "Please consider to update your addons by running 'g.extension.all -f'.\n"))
  507. def _escapeXML(text):
  508. """Helper function for correct escaping characters for XML.
  509. Duplicate function in core/toolboxes and probably also in man compilation
  510. and some existing Python package.
  511. >>> _escapeXML('<>&')
  512. '&amp;lt;&gt;&amp;'
  513. """
  514. return text.replace('<', '&lt;').replace("&", '&amp;').replace(">", '&gt;')
  515. def _loadMetadata(module):
  516. """Load metadata to modules.
  517. :param module: module name
  518. :return: (description, keywords as a list)
  519. """
  520. try:
  521. task = gtask.parse_interface(module)
  522. except ScriptError as e:
  523. e = _encode_string(e.value)
  524. # for some reason this works well only if it is separate
  525. sys.stderr.write("%s\n" % module)
  526. sys.stderr.write("%s\n" % e)
  527. return '', ''
  528. except UnicodeDecodeError as e:
  529. sys.stderr.write("%s\n%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 = 'data/test_toolboxes_user_toolboxes.xml'
  641. menuFile = 'data/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 = 'data/test_toolboxes_menudata_ref.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 validate_file(filename):
  682. try:
  683. etree.parse(filename)
  684. except ETREE_EXCEPTIONS as error:
  685. print "XML file <{name}> is not well formed: {error}".format(
  686. name=filename, error=error)
  687. return 1
  688. return 0
  689. def main():
  690. """Converts the toolboxes files on standard paths to the menudata file
  691. File is written to the standard output.
  692. """
  693. # TODO: fix parameter handling
  694. if len(sys.argv) > 1:
  695. mainFile = os.path.join(WXGUIDIR, 'xml', 'module_tree.xml')
  696. else:
  697. mainFile = os.path.join(WXGUIDIR, 'xml', 'main_menu.xml')
  698. tree = createTree(distributionRootFile=mainFile, userRootFile=None,
  699. userDefined=False)
  700. root = tree.getroot()
  701. sys.stdout.write(_getXMLString(root))
  702. return 0
  703. if __name__ == '__main__':
  704. # TODO: fix parameter handling
  705. if len(sys.argv) > 1:
  706. if sys.argv[1] == 'doctest':
  707. sys.exit(doc_test())
  708. elif sys.argv[1] == 'test':
  709. sys.exit(module_test())
  710. elif sys.argv[1] == 'validate':
  711. sys.exit(validate_file(sys.argv[2]))
  712. sys.exit(main())