extensions.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. """!
  2. @package modules.extensions
  3. @brief GRASS Addons extensions management classes
  4. Classes:
  5. - extensions::InstallExtensionWindow
  6. - extensions::ExtensionTree
  7. - extensions::UninstallExtensionWindow
  8. - extensions::CheckListExtension
  9. (C) 2008-2013 by the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. @author Martin Landa <landa.martin gmail.com>
  13. """
  14. import os
  15. import sys
  16. import wx
  17. try:
  18. import wx.lib.agw.customtreectrl as CT
  19. except ImportError:
  20. import wx.lib.customtreectrl as CT
  21. import wx.lib.flatnotebook as FN
  22. import grass.script as grass
  23. from grass.script import task as gtask
  24. from core import globalvar
  25. from core.gcmd import GError, RunCommand
  26. from core.utils import SetAddOnPath
  27. from gui_core.forms import GUI
  28. from gui_core.widgets import ItemTree, GListCtrl, SearchModuleWidget, EVT_MODULE_SELECTED
  29. class ExtensionModulesData(object):
  30. """!Holds information about modules.
  31. @todo add some test
  32. @todo this class has some common methods with core::modulesdata::ModulesData
  33. """
  34. def __init__(self, modulesDesc):
  35. self.moduleDesc = modulesDesc
  36. self.moduleDescOriginal = modulesDesc
  37. def GetCommandDesc(self, cmd):
  38. """!Gets the description for a given module (command).
  39. If the given module is not available, an empty string is returned.
  40. \code
  41. print data.GetCommandDesc('r.info')
  42. Outputs basic information about a raster map.
  43. \endcode
  44. """
  45. if cmd in self.moduleDesc:
  46. return self.moduleDesc[cmd]['description']
  47. return ''
  48. def GetCommandItems(self):
  49. """!Gets list of available modules (commands).
  50. The list contains available module names.
  51. \code
  52. print data.GetCommandItems()[0:4]
  53. ['d.barscale', 'd.colorlist', 'd.colortable', 'd.correlate']
  54. \endcode
  55. """
  56. items = self.moduleDesc.keys()
  57. items.sort()
  58. return items
  59. def FindModules(self, text, findIn):
  60. """!Finds modules according to given text.
  61. @param text string to search
  62. @param findIn where to search for text
  63. (allowed values are 'description', 'keywords' and 'command')
  64. """
  65. modules = dict()
  66. iFound = 0
  67. for module, data in self.moduleDescOriginal.iteritems():
  68. found = False
  69. if findIn == 'description':
  70. if text in data['description']:
  71. found = True
  72. elif findIn == 'keywords':
  73. if text in data['keywords']:
  74. found = True
  75. elif findIn == 'command':
  76. if module[:len(text)] == text:
  77. found = True
  78. else:
  79. raise ValueError("Parameter findIn is not valid")
  80. if found:
  81. iFound += 1
  82. modules[module] = data
  83. return modules, iFound
  84. def SetFilter(self, data = None):
  85. """!Sets filter modules
  86. If @p data is not specified, module dictionary is derived
  87. from an internal data structures.
  88. @todo Document this method.
  89. @param data data dict
  90. """
  91. if data:
  92. self.moduleDesc = data
  93. else:
  94. self.moduleDesc = self.moduleDescOriginal
  95. def SetData(self, data):
  96. self.moduleDesc = self.moduleDescOriginal = data
  97. class InstallExtensionWindow(wx.Frame):
  98. def __init__(self, parent, id = wx.ID_ANY,
  99. title = _("Fetch & install extension from GRASS Addons"), **kwargs):
  100. self.parent = parent
  101. self.options = dict() # list of options
  102. wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
  103. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  104. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  105. self.repoBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  106. label = " %s " % _("Repository"))
  107. self.treeBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  108. label = " %s " % _("List of extensions - double-click to install"))
  109. self.repo = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY)
  110. self.tree = ExtensionTree(parent = self.panel, log = parent.GetLogWindow())
  111. self.modulesData = ExtensionModulesData(modulesDesc = self.tree.GetModules())
  112. self.search = SearchModuleWidget(parent = self.panel, modulesData = self.modulesData,
  113. showChoice = False)
  114. self.search.SetSelection(0)
  115. self.search.Bind(EVT_MODULE_SELECTED, self.OnShowItem)
  116. # show text in statusbar when notification appears
  117. self.search.showNotification.connect(lambda message: self.SetStatusText(message))
  118. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  119. label = " %s " % _("Options"))
  120. if sys.platform == 'win32':
  121. task = gtask.parse_interface('g.extension.py')
  122. else:
  123. task = gtask.parse_interface('g.extension')
  124. ignoreFlags = ['l', 'c', 'g', 'a', 'f', 't', 'quiet']
  125. if sys.platform == 'win32':
  126. ignoreFlags.append('d')
  127. ignoreFlags.append('i')
  128. for f in task.get_options()['flags']:
  129. name = f.get('name', '')
  130. desc = f.get('label', '')
  131. if not desc:
  132. desc = f.get('description', '')
  133. if not name and not desc:
  134. continue
  135. if name in ignoreFlags:
  136. continue
  137. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  138. label = desc)
  139. self.repo.SetValue(task.get_param(value = 'svnurl').get('default',
  140. 'http://svn.osgeo.org/grass/grass-addons/grass7'))
  141. self.statusbar = self.CreateStatusBar(number = 1)
  142. self.btnFetch = wx.Button(parent = self.panel, id = wx.ID_ANY,
  143. label = _("&Fetch"))
  144. self.btnFetch.SetToolTipString(_("Fetch list of available modules from GRASS Addons SVN repository"))
  145. self.btnClose = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  146. self.btnInstall = wx.Button(parent = self.panel, id = wx.ID_ANY,
  147. label = _("&Install"))
  148. self.btnInstall.SetToolTipString(_("Install selected add-ons GRASS module"))
  149. self.btnInstall.Enable(False)
  150. self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
  151. self.btnFetch.Bind(wx.EVT_BUTTON, self.OnFetch)
  152. self.btnInstall.Bind(wx.EVT_BUTTON, self.OnInstall)
  153. self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnItemActivated)
  154. self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnItemSelected)
  155. self.search.Bind(wx.EVT_TEXT_ENTER, self.OnShowItem)
  156. wx.CallAfter(self._fetch)
  157. self._layout()
  158. def _layout(self):
  159. """!Do layout"""
  160. sizer = wx.BoxSizer(wx.VERTICAL)
  161. repoSizer = wx.StaticBoxSizer(self.repoBox, wx.VERTICAL)
  162. repo1Sizer = wx.BoxSizer(wx.HORIZONTAL)
  163. repo1Sizer.Add(item = self.repo, proportion = 1,
  164. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL, border = 1)
  165. repo1Sizer.Add(item = self.btnFetch, proportion = 0,
  166. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL, border = 1)
  167. repoSizer.Add(item = repo1Sizer,
  168. flag = wx.EXPAND)
  169. findSizer = wx.BoxSizer(wx.HORIZONTAL)
  170. findSizer.Add(item = self.search, proportion = 1)
  171. treeSizer = wx.StaticBoxSizer(self.treeBox, wx.HORIZONTAL)
  172. treeSizer.Add(item = self.tree, proportion = 1,
  173. flag = wx.ALL | wx.EXPAND, border = 1)
  174. # options
  175. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  176. for key in self.options.keys():
  177. optionSizer.Add(item = self.options[key], proportion = 0)
  178. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  179. btnSizer.Add(item = self.btnClose, proportion = 0,
  180. flag = wx.RIGHT, border = 5)
  181. btnSizer.Add(item = self.btnInstall, proportion = 0)
  182. sizer.Add(item = repoSizer, proportion = 0,
  183. flag = wx.ALL | wx.EXPAND, border = 3)
  184. sizer.Add(item = findSizer, proportion = 0,
  185. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  186. sizer.Add(item = treeSizer, proportion = 1,
  187. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  188. sizer.Add(item = optionSizer, proportion = 0,
  189. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  190. sizer.Add(item = btnSizer, proportion = 0,
  191. flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  192. self.panel.SetSizer(sizer)
  193. sizer.Fit(self.panel)
  194. self.Layout()
  195. def _getCmd(self):
  196. item = self.tree.GetSelected()
  197. if not item or not item.IsOk():
  198. return ['g.extension']
  199. name = self.tree.GetItemText(item)
  200. if not name:
  201. GError(_("Extension not defined"), parent = self)
  202. return
  203. flags = list()
  204. for key in self.options.keys():
  205. if self.options[key].IsChecked():
  206. if len(key) == 1:
  207. flags.append('-%s' % key)
  208. else:
  209. flags.append('--%s' % key)
  210. return ['g.extension'] + flags + ['extension=' + name,
  211. 'svnurl=' + self.repo.GetValue().strip()]
  212. def OnUpdateStatusBar(self, event):
  213. """!Update statusbar text
  214. @todo This method is a dead code. Is it useful?
  215. """
  216. element = self.search.GetSelection()
  217. if not self.tree.IsLoaded():
  218. self.SetStatusText(_("Fetch list of available extensions by clicking on 'Fetch' button"), 0)
  219. return
  220. self.tree.SearchItems(element = element,
  221. value = event.GetEventObject().GetValue())
  222. nItems = len(self.tree.itemsMarked)
  223. if event.GetString():
  224. self.SetStatusText(_("%d items match") % nItems, 0)
  225. else:
  226. self.SetStatusText("", 0)
  227. event.Skip()
  228. def OnCloseWindow(self, event):
  229. """!Close window"""
  230. self.Destroy()
  231. def OnFetch(self, event):
  232. """!Fetch list of available extensions"""
  233. self._fetch()
  234. def _fetch(self):
  235. """!Fetch list of available extensions"""
  236. wx.BeginBusyCursor()
  237. self.SetStatusText(_("Fetching list of modules from GRASS-Addons SVN (be patient)..."), 0)
  238. self.tree.Load(url = self.repo.GetValue().strip())
  239. modulesDesc = self.tree.GetModules()
  240. self.modulesData.SetData(modulesDesc)
  241. self.SetStatusText("", 0)
  242. wx.EndBusyCursor()
  243. def OnItemActivated(self, event):
  244. item = event.GetItem()
  245. data = self.tree.GetPyData(item)
  246. if data and 'command' in data:
  247. self.OnInstall(event = None)
  248. def OnInstall(self, event):
  249. """!Install selected extension"""
  250. log = self.parent.GetLogWindow()
  251. log.RunCmd(self._getCmd(), onDone = self.OnDone)
  252. def OnDone(self, cmd, returncode):
  253. if returncode == 0:
  254. if not os.getenv('GRASS_ADDON_BASE'):
  255. SetAddOnPath(key = 'BASE')
  256. globalvar.UpdateGRASSAddOnCommands()
  257. def OnItemSelected(self, event):
  258. """!Item selected"""
  259. item = event.GetItem()
  260. self.tree.itemSelected = item
  261. data = self.tree.GetPyData(item)
  262. if data is None:
  263. self.SetStatusText('', 0)
  264. self.btnInstall.Enable(False)
  265. else:
  266. self.SetStatusText(data.get('description', ''), 0)
  267. self.btnInstall.Enable(True)
  268. def OnShowItem(self, event):
  269. """!Show selected item"""
  270. self.tree.OnShowItem(event)
  271. if self.tree.GetSelected():
  272. self.btnInstall.Enable()
  273. else:
  274. self.btnInstall.Enable(False)
  275. class ExtensionTree(ItemTree):
  276. """!List of available extensions"""
  277. def __init__(self, parent, log, id = wx.ID_ANY,
  278. ctstyle = CT.TR_HIDE_ROOT | CT.TR_FULL_ROW_HIGHLIGHT | CT.TR_HAS_BUTTONS |
  279. CT.TR_LINES_AT_ROOT | CT.TR_SINGLE,
  280. **kwargs):
  281. self.parent = parent # GMFrame
  282. self.log = log
  283. super(ExtensionTree, self).__init__(parent, id, ctstyle = ctstyle, **kwargs)
  284. self._initTree()
  285. def _initTree(self):
  286. for prefix in ('display', 'database',
  287. 'general', 'imagery',
  288. 'misc', 'postscript', 'paint',
  289. 'raster', 'raster3D', 'sites', 'vector', 'wxGUI', 'other'):
  290. self.AppendItem(parentId = self.root,
  291. text = prefix)
  292. self._loaded = False
  293. def _expandPrefix(self, c):
  294. name = { 'd' : 'display',
  295. 'db' : 'database',
  296. 'g' : 'general',
  297. 'i' : 'imagery',
  298. 'm' : 'misc',
  299. 'ps' : 'postscript',
  300. 'p' : 'paint',
  301. 'r' : 'raster',
  302. 'r3' : 'raster3D',
  303. 's' : 'sites',
  304. 'v' : 'vector',
  305. 'wx' : 'wxGUI',
  306. '' : 'other' }
  307. if c in name:
  308. return name[c]
  309. return c
  310. def _findItem(self, text):
  311. """!Find item"""
  312. item = self.GetFirstChild(self.root)[0]
  313. while item and item.IsOk():
  314. if text == self.GetItemText(item):
  315. return item
  316. item = self.GetNextSibling(item)
  317. return None
  318. def Load(self, url, full = True):
  319. """!Load list of extensions"""
  320. self.DeleteAllItems()
  321. self.root = self.AddRoot(_("Menu tree"))
  322. self._initTree()
  323. if full:
  324. flags = 'g'
  325. else:
  326. flags = 'l'
  327. ret = RunCommand('g.extension', read = True, parent = self,
  328. svnurl = url,
  329. flags = flags, quiet = True)
  330. if not ret:
  331. return
  332. mdict = dict()
  333. for line in ret.splitlines():
  334. if full:
  335. try:
  336. key, value = line.split('=', 1)
  337. except ValueError:
  338. key = 'name'
  339. value = line
  340. if key == 'name':
  341. try:
  342. prefix, name = value.split('.', 1)
  343. except ValueError:
  344. prefix = ''
  345. name = value
  346. if prefix not in mdict:
  347. mdict[prefix] = dict()
  348. mdict[prefix][name] = dict()
  349. mdict[prefix][name]['command'] = value
  350. else:
  351. mdict[prefix][name][key] = value
  352. else:
  353. try:
  354. prefix, name = line.strip().split('.', 1)
  355. except:
  356. prefix = ''
  357. name = line.strip()
  358. if self._expandPrefix(prefix) == prefix:
  359. prefix = ''
  360. if prefix not in mdict:
  361. mdict[prefix] = dict()
  362. mdict[prefix][name] = { 'command' : prefix + '.' + name }
  363. for prefix in mdict.keys():
  364. prefixName = self._expandPrefix(prefix)
  365. item = self._findItem(prefixName)
  366. names = mdict[prefix].keys()
  367. names.sort()
  368. for name in names:
  369. if prefix:
  370. text = prefix + '.' + name
  371. else:
  372. text = name
  373. new = self.AppendItem(parentId = item,
  374. text = text)
  375. data = dict()
  376. for key in mdict[prefix][name].keys():
  377. data[key] = mdict[prefix][name][key]
  378. self.SetPyData(new, data)
  379. self._loaded = True
  380. def IsLoaded(self):
  381. """Check if items are loaded"""
  382. return self._loaded
  383. def GetModules(self):
  384. modules = {}
  385. root = self.GetRootItem()
  386. child, cookie = self.GetFirstChild(root)
  387. while child and child.IsOk():
  388. if self.ItemHasChildren(child):
  389. subChild, subCookie = self.GetFirstChild(child)
  390. while subChild and subChild.IsOk():
  391. name = self.GetItemText(subChild)
  392. data = self.GetPyData(subChild)
  393. modules[name] = data
  394. subChild, subCookie = self.GetNextChild(child, subCookie)
  395. child, cookie = self.GetNextChild(root, cookie)
  396. return modules
  397. class UninstallExtensionWindow(wx.Frame):
  398. def __init__(self, parent, id = wx.ID_ANY,
  399. title = _("Uninstall GRASS Addons extensions"), **kwargs):
  400. self.parent = parent
  401. wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
  402. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  403. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  404. self.extBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  405. label = " %s " % _("List of installed extensions"))
  406. self.extList = CheckListExtension(parent = self.panel)
  407. # buttons
  408. self.btnUninstall = wx.Button(parent = self.panel, id = wx.ID_ANY,
  409. label = _("&Uninstall"))
  410. self.btnUninstall.SetToolTipString(_("Uninstall selected AddOns extensions"))
  411. self.btnClose = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  412. self.btnUninstall.Bind(wx.EVT_BUTTON, self.OnUninstall)
  413. self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
  414. self._layout()
  415. def _layout(self):
  416. """!Do layout"""
  417. sizer = wx.BoxSizer(wx.VERTICAL)
  418. extSizer = wx.StaticBoxSizer(self.extBox, wx.HORIZONTAL)
  419. extSizer.Add(item = self.extList, proportion = 1,
  420. flag = wx.ALL | wx.EXPAND, border = 1)
  421. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  422. btnSizer.Add(item = self.btnClose, proportion = 0,
  423. flag = wx.RIGHT, border = 5)
  424. btnSizer.Add(item = self.btnUninstall, proportion = 0)
  425. sizer.Add(item = extSizer, proportion = 1,
  426. flag = wx.ALL | wx.EXPAND, border = 3)
  427. sizer.Add(item = btnSizer, proportion = 0,
  428. flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  429. self.panel.SetSizer(sizer)
  430. sizer.Fit(self.panel)
  431. self.Layout()
  432. def OnCloseWindow(self, event):
  433. """!Close window"""
  434. self.Destroy()
  435. def OnUninstall(self, event):
  436. """!Uninstall selected extensions"""
  437. log = self.parent.GetLogWindow()
  438. eList = self.extList.GetExtensions()
  439. if not eList:
  440. GError(_("No extension selected for removal. "
  441. "Operation canceled."),
  442. parent = self)
  443. return
  444. for ext in eList:
  445. files = RunCommand('g.extension', parent = self, read = True, quiet = True,
  446. extension = ext, operation = 'remove').splitlines()
  447. dlg = wx.MessageDialog(parent = self,
  448. message = _("List of files to be removed:\n%(files)s\n\n"
  449. "Do you want really to remove <%(ext)s> extension?") % \
  450. { 'files' : os.linesep.join(files), 'ext' : ext },
  451. caption = _("Remove extension"),
  452. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  453. if dlg.ShowModal() == wx.ID_YES:
  454. RunCommand('g.extension', flags = 'f', parent = self, quiet = True,
  455. extension = ext, operation = 'remove')
  456. self.extList.LoadData()
  457. # update prompt
  458. globalvar.UpdateGRASSAddOnCommands(eList)
  459. log = self.parent.GetLogWindow()
  460. log.GetPrompt().SetFilter(None)
  461. class CheckListExtension(GListCtrl):
  462. """!List of mapset/owner/group"""
  463. def __init__(self, parent):
  464. GListCtrl.__init__(self, parent)
  465. # load extensions
  466. self.InsertColumn(0, _('Extension'))
  467. self.LoadData()
  468. def LoadData(self):
  469. """!Load data into list"""
  470. self.DeleteAllItems()
  471. for ext in RunCommand('g.extension',
  472. quiet = True, parent = self, read = True,
  473. flags = 'a').splitlines():
  474. if ext:
  475. self.InsertStringItem(sys.maxint, ext)
  476. def GetExtensions(self):
  477. """!Get extensions to be un-installed
  478. """
  479. extList = list()
  480. for i in range(self.GetItemCount()):
  481. if self.IsChecked(i):
  482. name = self.GetItemText(i)
  483. if name:
  484. extList.append(name)
  485. return extList