ghelp.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. """!
  2. @package help.py
  3. @brief Help window
  4. Classes:
  5. - SearchModuleWindow
  6. - ItemTree
  7. - MenuTreeWindow
  8. - MenuTree
  9. - AboutWindow
  10. - InstallExtensionWindow
  11. - ExtensionTree
  12. - HelpFrame
  13. - HelpWindow
  14. - HelpPanel
  15. (C) 2008-2011 by the GRASS Development Team
  16. This program is free software under the GNU General Public License
  17. (>=v2). Read the file COPYING that comes with GRASS for details.
  18. @author Martin Landa <landa.martin gmail.com>
  19. """
  20. import os
  21. import codecs
  22. import wx
  23. try:
  24. import wx.lib.agw.customtreectrl as CT
  25. from wx.lib.agw.hyperlink import HyperLinkCtrl
  26. except ImportError:
  27. import wx.lib.customtreectrl as CT
  28. from wx.lib.hyperlink import HyperLinkCtrl
  29. import wx.lib.flatnotebook as FN
  30. import wx.lib.scrolledpanel as scrolled
  31. import grass.script as grass
  32. from grass.script import task as gtask
  33. import menudata
  34. import gcmd
  35. import globalvar
  36. import gdialogs
  37. import utils
  38. import menuform
  39. class HelpFrame(wx.Frame):
  40. """!GRASS Quickstart help window"""
  41. def __init__(self, parent, id, title, size, file):
  42. wx.Frame.__init__(self, parent = parent, id = id, title = title, size = size)
  43. sizer = wx.BoxSizer(wx.VERTICAL)
  44. # text
  45. content = HelpPanel(parent = self)
  46. content.LoadPage(file)
  47. sizer.Add(item = content, proportion = 1, flag = wx.EXPAND)
  48. self.SetAutoLayout(True)
  49. self.SetSizer(sizer)
  50. self.Layout()
  51. class SearchModuleWindow(wx.Panel):
  52. """!Search module window (used in MenuTreeWindow)"""
  53. def __init__(self, parent, id = wx.ID_ANY, cmdPrompt = None,
  54. showChoice = True, showTip = False, **kwargs):
  55. self.showTip = showTip
  56. self.showChoice = showChoice
  57. self.cmdPrompt = cmdPrompt
  58. wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
  59. self._searchDict = { _('description') : 'description',
  60. _('command') : 'command',
  61. _('keywords') : 'keywords' }
  62. self.box = wx.StaticBox(parent = self, id = wx.ID_ANY,
  63. label = " %s " % _("Find module(s)"))
  64. self.searchBy = wx.Choice(parent = self, id = wx.ID_ANY,
  65. choices = [_('description'),
  66. _('keywords'),
  67. _('command')])
  68. self.searchBy.SetSelection(0)
  69. self.search = wx.TextCtrl(parent = self, id = wx.ID_ANY,
  70. value = "", size = (-1, 25),
  71. style = wx.TE_PROCESS_ENTER)
  72. self.search.Bind(wx.EVT_TEXT, self.OnSearchModule)
  73. if self.showTip:
  74. self.searchTip = gdialogs.StaticWrapText(parent = self, id = wx.ID_ANY,
  75. size = (-1, 35))
  76. if self.showChoice:
  77. self.searchChoice = wx.Choice(parent = self, id = wx.ID_ANY)
  78. if self.cmdPrompt:
  79. self.searchChoice.SetItems(self.cmdPrompt.GetCommandItems())
  80. self.searchChoice.Bind(wx.EVT_CHOICE, self.OnSelectModule)
  81. self._layout()
  82. def _layout(self):
  83. """!Do layout"""
  84. sizer = wx.StaticBoxSizer(self.box, wx.HORIZONTAL)
  85. gridSizer = wx.GridBagSizer(hgap = 3, vgap = 3)
  86. gridSizer.AddGrowableCol(1)
  87. gridSizer.Add(item = self.searchBy,
  88. flag = wx.ALIGN_CENTER_VERTICAL, pos = (0, 0))
  89. gridSizer.Add(item = self.search,
  90. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos = (0, 1))
  91. row = 1
  92. if self.showTip:
  93. gridSizer.Add(item = self.searchTip,
  94. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos = (row, 0), span = (1, 2))
  95. row += 1
  96. if self.showChoice:
  97. gridSizer.Add(item = self.searchChoice,
  98. flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, pos = (row, 0), span = (1, 2))
  99. sizer.Add(item = gridSizer, proportion = 1)
  100. self.SetSizer(sizer)
  101. sizer.Fit(self)
  102. def GetSelection(self):
  103. """!Get selected element"""
  104. selection = self.searchBy.GetStringSelection()
  105. return self._searchDict[selection]
  106. def SetSelection(self, i):
  107. """!Set selection element"""
  108. self.searchBy.SetSelection(i)
  109. def OnSearchModule(self, event):
  110. """!Search module by keywords or description"""
  111. if not self.cmdPrompt:
  112. event.Skip()
  113. return
  114. text = event.GetString()
  115. if not text:
  116. self.cmdPrompt.SetFilter(None)
  117. mList = self.cmdPrompt.GetCommandItems()
  118. self.searchChoice.SetItems(mList)
  119. if self.showTip:
  120. self.searchTip.SetLabel(_("%d modules found") % len(mList))
  121. event.Skip()
  122. return
  123. modules = dict()
  124. iFound = 0
  125. for module, data in self.cmdPrompt.moduleDesc.iteritems():
  126. found = False
  127. sel = self.searchBy.GetSelection()
  128. if sel == 0: # -> description
  129. if text in data['desc']:
  130. found = True
  131. elif sel == 1: # keywords
  132. if text in ','.join(data['keywords']):
  133. found = True
  134. else: # command
  135. if module[:len(text)] == text:
  136. found = True
  137. if found:
  138. iFound += 1
  139. try:
  140. group, name = module.split('.')
  141. except ValueError:
  142. continue # TODO
  143. if group not in modules:
  144. modules[group] = list()
  145. modules[group].append(name)
  146. self.cmdPrompt.SetFilter(modules)
  147. self.searchChoice.SetItems(self.cmdPrompt.GetCommandItems())
  148. if self.showTip:
  149. self.searchTip.SetLabel(_("%d modules found") % iFound)
  150. event.Skip()
  151. def OnSelectModule(self, event):
  152. """!Module selected from choice, update command prompt"""
  153. cmd = event.GetString().split(' ', 1)[0]
  154. text = cmd + ' '
  155. pos = len(text)
  156. if self.cmdPrompt:
  157. self.cmdPrompt.SetText(text)
  158. self.cmdPrompt.SetSelectionStart(pos)
  159. self.cmdPrompt.SetCurrentPos(pos)
  160. self.cmdPrompt.SetFocus()
  161. desc = self.cmdPrompt.GetCommandDesc(cmd)
  162. if self.showTip:
  163. self.searchTip.SetLabel(desc)
  164. def Reset(self):
  165. """!Reset widget"""
  166. self.searchBy.SetSelection(0)
  167. self.search.SetValue('')
  168. if self.showTip:
  169. self.searchTip.SetLabel('')
  170. class MenuTreeWindow(wx.Panel):
  171. """!Show menu tree"""
  172. def __init__(self, parent, id = wx.ID_ANY, **kwargs):
  173. self.parent = parent # LayerManager
  174. wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
  175. self.dataBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
  176. label = " %s " % _("Menu tree (double-click to run command)"))
  177. # tree
  178. self.tree = MenuTree(parent = self, data = menudata.ManagerData())
  179. self.tree.Load()
  180. # search widget
  181. self.search = SearchModuleWindow(parent = self, showChoice = False)
  182. # buttons
  183. self.btnRun = wx.Button(self, id = wx.ID_OK, label = _("&Run"))
  184. self.btnRun.SetToolTipString(_("Run selected command"))
  185. self.btnRun.Enable(False)
  186. # bindings
  187. self.btnRun.Bind(wx.EVT_BUTTON, self.OnRun)
  188. self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnItemActivated)
  189. self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnItemSelected)
  190. self.search.Bind(wx.EVT_TEXT_ENTER, self.OnShowItem)
  191. self.search.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  192. self._layout()
  193. self.search.SetFocus()
  194. def _layout(self):
  195. """!Do dialog layout"""
  196. sizer = wx.BoxSizer(wx.VERTICAL)
  197. # body
  198. dataSizer = wx.StaticBoxSizer(self.dataBox, wx.HORIZONTAL)
  199. dataSizer.Add(item = self.tree, proportion =1,
  200. flag = wx.EXPAND)
  201. # buttons
  202. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  203. btnSizer.Add(item = self.btnRun, proportion = 0)
  204. sizer.Add(item = dataSizer, proportion = 1,
  205. flag = wx.EXPAND | wx.ALL, border = 5)
  206. sizer.Add(item = self.search, proportion = 0,
  207. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
  208. sizer.Add(item = btnSizer, proportion = 0,
  209. flag = wx.ALIGN_RIGHT | wx.BOTTOM | wx.RIGHT, border = 5)
  210. sizer.Fit(self)
  211. sizer.SetSizeHints(self)
  212. self.SetSizer(sizer)
  213. self.Fit()
  214. self.SetAutoLayout(True)
  215. self.Layout()
  216. def OnCloseWindow(self, event):
  217. """!Close window"""
  218. self.Destroy()
  219. def OnRun(self, event):
  220. """!Run selected command"""
  221. if not self.tree.GetSelected():
  222. return # should not happen
  223. data = self.tree.GetPyData(self.tree.GetSelected())
  224. if not data:
  225. return
  226. handler = 'self.parent.' + data['handler'].lstrip('self.')
  227. if data['handler'] == 'self.OnXTerm':
  228. wx.MessageBox(parent = self,
  229. message = _('You must run this command from the menu or command line',
  230. 'This command require an XTerm'),
  231. caption = _('Message'), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  232. elif data['command']:
  233. eval(handler)(event = None, cmd = data['command'].split())
  234. else:
  235. eval(handler)(None)
  236. def OnShowItem(self, event):
  237. """!Show selected item"""
  238. self.tree.OnShowItem(event)
  239. if self.tree.GetSelected():
  240. self.btnRun.Enable()
  241. else:
  242. self.btnRun.Enable(False)
  243. def OnItemActivated(self, event):
  244. """!Item activated (double-click)"""
  245. item = event.GetItem()
  246. if not item or not item.IsOk():
  247. return
  248. data = self.tree.GetPyData(item)
  249. if not data or 'command' not in data:
  250. return
  251. self.tree.itemSelected = item
  252. self.OnRun(None)
  253. def OnItemSelected(self, event):
  254. """!Item selected"""
  255. item = event.GetItem()
  256. if not item or not item.IsOk():
  257. return
  258. data = self.tree.GetPyData(item)
  259. if not data or 'command' not in data:
  260. return
  261. if data['command']:
  262. label = data['command'] + ' -- ' + data['description']
  263. else:
  264. label = data['description']
  265. self.parent.SetStatusText(label, 0)
  266. def OnUpdateStatusBar(self, event):
  267. """!Update statusbar text"""
  268. element = self.search.GetSelection()
  269. self.tree.SearchItems(element = element,
  270. value = event.GetString())
  271. nItems = len(self.tree.itemsMarked)
  272. if event.GetString():
  273. self.parent.SetStatusText(_("%d modules match") % nItems, 0)
  274. else:
  275. self.parent.SetStatusText("", 0)
  276. event.Skip()
  277. class ItemTree(CT.CustomTreeCtrl):
  278. def __init__(self, parent, id = wx.ID_ANY,
  279. ctstyle = CT.TR_HIDE_ROOT | CT.TR_FULL_ROW_HIGHLIGHT | CT.TR_HAS_BUTTONS |
  280. CT.TR_LINES_AT_ROOT | CT.TR_SINGLE, **kwargs):
  281. if globalvar.hasAgw:
  282. super(ItemTree, self).__init__(parent, id, agwStyle = ctstyle, **kwargs)
  283. else:
  284. super(ItemTree, self).__init__(parent, id, style = ctstyle, **kwargs)
  285. self.root = self.AddRoot(_("Menu tree"))
  286. self.itemsMarked = [] # list of marked items
  287. self.itemSelected = None
  288. def SearchItems(self, element, value):
  289. """!Search item
  290. @param element element index (see self.searchBy)
  291. @param value
  292. @return list of found tree items
  293. """
  294. items = list()
  295. if not value:
  296. return items
  297. item = self.GetFirstChild(self.root)[0]
  298. self._processItem(item, element, value, items)
  299. self.itemsMarked = items
  300. self.itemSelected = None
  301. return items
  302. def _processItem(self, item, element, value, listOfItems):
  303. """!Search items (used by SearchItems)
  304. @param item reference item
  305. @param listOfItems list of found items
  306. """
  307. while item and item.IsOk():
  308. subItem = self.GetFirstChild(item)[0]
  309. if subItem:
  310. self._processItem(subItem, element, value, listOfItems)
  311. data = self.GetPyData(item)
  312. if data and element in data and \
  313. value.lower() in data[element].lower():
  314. listOfItems.append(item)
  315. item = self.GetNextSibling(item)
  316. def GetSelected(self):
  317. """!Get selected item"""
  318. return self.itemSelected
  319. def OnShowItem(self, event):
  320. """!Highlight first found item in menu tree"""
  321. if len(self.itemsMarked) > 0:
  322. if self.GetSelected():
  323. self.ToggleItemSelection(self.GetSelected())
  324. idx = self.itemsMarked.index(self.GetSelected()) + 1
  325. else:
  326. idx = 0
  327. try:
  328. self.ToggleItemSelection(self.itemsMarked[idx])
  329. self.itemSelected = self.itemsMarked[idx]
  330. self.EnsureVisible(self.itemsMarked[idx])
  331. except IndexError:
  332. self.ToggleItemSelection(self.itemsMarked[0]) # reselect first item
  333. self.EnsureVisible(self.itemsMarked[0])
  334. self.itemSelected = self.itemsMarked[0]
  335. else:
  336. for item in self.root.GetChildren():
  337. self.Collapse(item)
  338. itemSelected = self.GetSelection()
  339. if itemSelected:
  340. self.ToggleItemSelection(itemSelected)
  341. self.itemSelected = None
  342. class MenuTree(ItemTree):
  343. """!Menu tree class"""
  344. def __init__(self, parent, data, **kwargs):
  345. self.parent = parent
  346. self.menudata = data
  347. super(MenuTree, self).__init__(parent, **kwargs)
  348. def Load(self, data = None):
  349. """!Load menu data tree
  350. @param data menu data (None to use self.menudata)
  351. """
  352. if not data:
  353. data = self.menudata
  354. self.itemsMarked = [] # list of marked items
  355. for eachMenuData in data.GetMenu():
  356. for label, items in eachMenuData:
  357. item = self.AppendItem(parentId = self.root,
  358. text = label.replace('&', ''))
  359. self.__AppendItems(item, items)
  360. def __AppendItems(self, item, data):
  361. """!Append items into tree (used by Load()
  362. @param item tree item (parent)
  363. @parent data menu data"""
  364. for eachItem in data:
  365. if len(eachItem) == 2:
  366. if eachItem[0]:
  367. itemSub = self.AppendItem(parentId = item,
  368. text = eachItem[0])
  369. self.__AppendItems(itemSub, eachItem[1])
  370. else:
  371. if eachItem[0]:
  372. itemNew = self.AppendItem(parentId = item,
  373. text = eachItem[0])
  374. data = { 'item' : eachItem[0],
  375. 'description' : eachItem[1],
  376. 'handler' : eachItem[2],
  377. 'command' : eachItem[3],
  378. 'keywords' : eachItem[4] }
  379. self.SetPyData(itemNew, data)
  380. class AboutWindow(wx.Frame):
  381. """!Create custom About Window
  382. @todo improve styling
  383. """
  384. def __init__(self, parent, size = (750, 400),
  385. title = _('About GRASS GIS'), **kwargs):
  386. wx.Frame.__init__(self, parent = parent, id = wx.ID_ANY, size = size, **kwargs)
  387. panel = wx.Panel(parent = self, id = wx.ID_ANY)
  388. # icon
  389. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  390. # get version and web site
  391. vInfo = grass.version()
  392. infoTxt = wx.Panel(parent = panel, id = wx.ID_ANY)
  393. infoSizer = wx.BoxSizer(wx.VERTICAL)
  394. infoGridSizer = wx.GridBagSizer(vgap = 5, hgap = 5)
  395. infoGridSizer.AddGrowableCol(0)
  396. infoGridSizer.AddGrowableCol(1)
  397. logo = os.path.join(globalvar.ETCDIR, "gui", "icons", "grass.ico")
  398. logoBitmap = wx.StaticBitmap(parent = infoTxt, id = wx.ID_ANY,
  399. bitmap = wx.Bitmap(name = logo,
  400. type = wx.BITMAP_TYPE_ICO))
  401. infoSizer.Add(item = logoBitmap, proportion = 0,
  402. flag = wx.ALL | wx.ALIGN_CENTER, border = 25)
  403. info = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
  404. label = 'GRASS GIS ' + vInfo['version'] + '\n\n')
  405. info.SetFont(wx.Font(13, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
  406. infoSizer.Add(item = info, proportion = 0,
  407. flag = wx.BOTTOM | wx.ALIGN_CENTER, border = 15)
  408. row = 0
  409. infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
  410. label = _('Official GRASS site:')),
  411. pos = (row, 0),
  412. flag = wx.ALIGN_RIGHT)
  413. infoGridSizer.Add(item = HyperLinkCtrl(parent = infoTxt, id = wx.ID_ANY,
  414. label = 'http://grass.osgeo.org'),
  415. pos = (row, 1),
  416. flag = wx.ALIGN_LEFT)
  417. row += 2
  418. infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
  419. label = _('SVN Revision:')),
  420. pos = (row, 0),
  421. flag = wx.ALIGN_RIGHT)
  422. infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
  423. label = vInfo['revision']),
  424. pos = (row, 1),
  425. flag = wx.ALIGN_LEFT)
  426. row += 1
  427. infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
  428. label = _('GIS Library Revision:')),
  429. pos = (row, 0),
  430. flag = wx.ALIGN_RIGHT)
  431. infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY,
  432. label = vInfo['libgis_revision'] + ' (' +
  433. vInfo['libgis_date'].split(' ')[0] + ')'),
  434. pos = (row, 1),
  435. flag = wx.ALIGN_LEFT)
  436. infoSizer.Add(item = infoGridSizer,
  437. proportion = 1,
  438. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL,
  439. border = 25)
  440. # create a flat notebook for displaying information about GRASS
  441. aboutNotebook = menuform.GNotebook(panel, style = globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON)
  442. aboutNotebook.SetTabAreaColour(globalvar.FNPageColor)
  443. for title, win in ((_("Info"), infoTxt),
  444. (_("Copyright"), self._pageCopyright()),
  445. (_("License"), self._pageLicense()),
  446. (_("Authors"), self._pageCredit()),
  447. (_("Contributors"), self._pageContributors()),
  448. (_("Extra contributors"), self._pageContributors(extra = True)),
  449. (_("Translators"), self._pageTranslators())):
  450. aboutNotebook.AddPage(page = win, text = title)
  451. wx.CallAfter(aboutNotebook.SetSelection, 0)
  452. # buttons
  453. btnClose = wx.Button(parent = panel, id = wx.ID_CLOSE)
  454. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  455. btnSizer.Add(item = btnClose, proportion = 0,
  456. flag = wx.ALL | wx.ALIGN_RIGHT,
  457. border = 5)
  458. # bindings
  459. btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
  460. infoTxt.SetSizer(infoSizer)
  461. infoSizer.Fit(infoTxt)
  462. sizer = wx.BoxSizer(wx.VERTICAL)
  463. sizer.Add(item = aboutNotebook, proportion = 1,
  464. flag = wx.EXPAND | wx.ALL, border = 1)
  465. sizer.Add(item = btnSizer, proportion = 0,
  466. flag = wx.ALL | wx.ALIGN_RIGHT, border = 1)
  467. panel.SetSizer(sizer)
  468. self.Layout()
  469. def _pageCopyright(self):
  470. """Copyright information"""
  471. copyfile = os.path.join(os.getenv("GISBASE"), "COPYING")
  472. if os.path.exists(copyfile):
  473. copyrightFile = open(copyfile, 'r')
  474. copytext = copyrightFile.read()
  475. copyrightFile.close()
  476. else:
  477. copytext = _('%s file missing') % 'COPYING'
  478. # put text into a scrolling panel
  479. copyrightwin = scrolled.ScrolledPanel(self, id = wx.ID_ANY,
  480. size = wx.DefaultSize,
  481. style = wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER)
  482. copyrighttxt = wx.StaticText(copyrightwin, id = wx.ID_ANY, label = copytext)
  483. copyrightwin.SetAutoLayout(True)
  484. copyrightwin.sizer = wx.BoxSizer(wx.VERTICAL)
  485. copyrightwin.sizer.Add(item = copyrighttxt, proportion = 1,
  486. flag = wx.EXPAND | wx.ALL, border = 3)
  487. copyrightwin.SetSizer(copyrightwin.sizer)
  488. copyrightwin.Layout()
  489. copyrightwin.SetupScrolling()
  490. return copyrightwin
  491. def _pageLicense(self):
  492. """Licence about"""
  493. licfile = os.path.join(os.getenv("GISBASE"), "GPL.TXT")
  494. if os.path.exists(licfile):
  495. licenceFile = open(licfile, 'r')
  496. license = ''.join(licenceFile.readlines())
  497. licenceFile.close()
  498. else:
  499. license = _('%s file missing') % 'GPL.TXT'
  500. # put text into a scrolling panel
  501. licensewin = scrolled.ScrolledPanel(self, id = wx.ID_ANY,
  502. style = wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER)
  503. licensetxt = wx.StaticText(licensewin, id = wx.ID_ANY, label = license)
  504. licensewin.SetAutoLayout(True)
  505. licensewin.sizer = wx.BoxSizer(wx.VERTICAL)
  506. licensewin.sizer.Add(item = licensetxt, proportion = 1,
  507. flag = wx.EXPAND | wx.ALL, border = 3)
  508. licensewin.SetSizer(licensewin.sizer)
  509. licensewin.Layout()
  510. licensewin.SetupScrolling()
  511. return licensewin
  512. def _pageCredit(self):
  513. """Credit about"""
  514. # credits
  515. authfile = os.path.join(os.getenv("GISBASE"), "AUTHORS")
  516. if os.path.exists(authfile):
  517. authorsFile = open(authfile, 'r')
  518. authors = unicode(''.join(authorsFile.readlines()), "utf-8")
  519. authorsFile.close()
  520. else:
  521. authors = _('%s file missing') % 'AUTHORS'
  522. authorwin = scrolled.ScrolledPanel(self, id = wx.ID_ANY,
  523. style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
  524. authortxt = wx.StaticText(authorwin, id = wx.ID_ANY, label = authors)
  525. authorwin.SetAutoLayout(1)
  526. authorwin.SetupScrolling()
  527. authorwin.sizer = wx.BoxSizer(wx.VERTICAL)
  528. authorwin.sizer.Add(item = authortxt, proportion = 1,
  529. flag = wx.EXPAND | wx.ALL, border = 3)
  530. authorwin.SetSizer(authorwin.sizer)
  531. authorwin.Layout()
  532. return authorwin
  533. def _pageContributors(self, extra = False):
  534. """Contributors info"""
  535. if extra:
  536. contribfile = os.path.join(os.getenv("GISBASE"), "contributors_extra.csv")
  537. else:
  538. contribfile = os.path.join(os.getenv("GISBASE"), "contributors.csv")
  539. if os.path.exists(contribfile):
  540. contribFile = codecs.open(contribfile, encoding = 'utf-8', mode = 'r')
  541. contribs = list()
  542. errLines = list()
  543. for line in contribFile.readlines()[1:]:
  544. line = line.rstrip('\n')
  545. try:
  546. if extra:
  547. name, email, rfc2_agreed = line.split(',')
  548. else:
  549. cvs_id, name, email, country, osgeo_id, rfc2_agreed = line.split(',')
  550. except ValueError:
  551. errLines.append(line)
  552. continue
  553. if extra:
  554. contribs.append((name, email))
  555. else:
  556. contribs.append((name, email, country, osgeo_id))
  557. contribFile.close()
  558. if errLines:
  559. gcmd.GError(parent = self,
  560. message = _("Error when reading file '%s'.") % contribfile + \
  561. "\n\n" + _("Lines:") + " %s" % \
  562. os.linesep.join(map(utils.DecodeString, errLines)))
  563. else:
  564. contribs = None
  565. contribwin = scrolled.ScrolledPanel(self, id = wx.ID_ANY,
  566. style = wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER)
  567. contribwin.SetAutoLayout(True)
  568. contribwin.SetupScrolling()
  569. contribwin.sizer = wx.BoxSizer(wx.VERTICAL)
  570. if not contribs:
  571. contribtxt = wx.StaticText(contribwin, id = wx.ID_ANY,
  572. label = _('%s file missing') % contribfile)
  573. contribwin.sizer.Add(item = contribtxt, proportion = 1,
  574. flag = wx.EXPAND | wx.ALL, border = 3)
  575. else:
  576. if extra:
  577. items = (_('Name'), _('E-mail'))
  578. else:
  579. items = (_('Name'), _('E-mail'), _('Country'), _('OSGeo_ID'))
  580. contribBox = wx.FlexGridSizer(cols = len(items), vgap = 5, hgap = 5)
  581. for item in items:
  582. contribBox.Add(item = wx.StaticText(parent = contribwin, id = wx.ID_ANY,
  583. label = item))
  584. for vals in sorted(contribs, key = lambda x: x[0]):
  585. for item in vals:
  586. contribBox.Add(item = wx.StaticText(parent = contribwin, id = wx.ID_ANY,
  587. label = item))
  588. contribwin.sizer.Add(item = contribBox, proportion = 1,
  589. flag = wx.EXPAND | wx.ALL, border = 3)
  590. contribwin.SetSizer(contribwin.sizer)
  591. contribwin.Layout()
  592. return contribwin
  593. def _pageTranslators(self):
  594. """Translators info"""
  595. translatorsfile = os.path.join(os.getenv("GISBASE"), "translators.csv")
  596. if os.path.exists(translatorsfile):
  597. translatorsFile = open(translatorsfile, 'r')
  598. translators = dict()
  599. errLines = list()
  600. for line in translatorsFile.readlines()[1:]:
  601. line = line.rstrip('\n')
  602. try:
  603. name, email, languages = line.split(',')
  604. except ValueError:
  605. errLines.append(line)
  606. continue
  607. for language in languages.split(' '):
  608. if language not in translators:
  609. translators[language] = list()
  610. translators[language].append((name, email))
  611. translatorsFile.close()
  612. if errLines:
  613. gcmd.GError(parent = self,
  614. message = _("Error when reading file '%s'.") % translatorsfile + \
  615. "\n\n" + _("Lines:") + " %s" % \
  616. os.linesep.join(map(utils.DecodeString, errLines)))
  617. else:
  618. translators = None
  619. translatorswin = scrolled.ScrolledPanel(self, id = wx.ID_ANY,
  620. style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
  621. translatorswin.SetAutoLayout(1)
  622. translatorswin.SetupScrolling()
  623. translatorswin.sizer = wx.BoxSizer(wx.VERTICAL)
  624. if not translators:
  625. translatorstxt = wx.StaticText(translatorswin, id = wx.ID_ANY,
  626. label = _('%s file missing') % 'translators.csv')
  627. translatorswin.sizer.Add(item = translatorstxt, proportion = 1,
  628. flag = wx.EXPAND | wx.ALL, border = 3)
  629. else:
  630. translatorsBox = wx.FlexGridSizer(cols = 3, vgap = 5, hgap = 5)
  631. languages = translators.keys()
  632. languages.sort()
  633. translatorsBox.Add(item = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
  634. label = _('Name')))
  635. translatorsBox.Add(item = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
  636. label = _('E-mail')))
  637. translatorsBox.Add(item = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
  638. label = _('Language')))
  639. for lang in languages:
  640. for translator in translators[lang]:
  641. name, email = translator
  642. translatorsBox.Add(item = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
  643. label = unicode(name, "utf-8")))
  644. translatorsBox.Add(item = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
  645. label = email))
  646. translatorsBox.Add(item = wx.StaticText(parent = translatorswin, id = wx.ID_ANY,
  647. label = lang))
  648. translatorswin.sizer.Add(item = translatorsBox, proportion = 1,
  649. flag = wx.EXPAND | wx.ALL, border = 3)
  650. translatorswin.SetSizer(translatorswin.sizer)
  651. translatorswin.Layout()
  652. return translatorswin
  653. def OnCloseWindow(self, event):
  654. """!Close window"""
  655. self.Close()
  656. class InstallExtensionWindow(wx.Frame):
  657. def __init__(self, parent, id = wx.ID_ANY,
  658. title = _("Fetch & install extension from GRASS Addons"), **kwargs):
  659. self.parent = parent
  660. self.options = dict() # list of options
  661. wx.Frame.__init__(self, parent = parent, id = id, title = title, **kwargs)
  662. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  663. self.repoBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  664. label = " %s " % _("Repository"))
  665. self.treeBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  666. label = " %s " % _("List of extensions"))
  667. self.repo = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY)
  668. self.fullDesc = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  669. label = _("Fetch full info including description and keywords (takes time)"))
  670. self.fullDesc.SetValue(True)
  671. self.search = SearchModuleWindow(parent = self.panel)
  672. self.search.SetSelection(0)
  673. self.tree = ExtensionTree(parent = self.panel, log = parent.GetLogWindow())
  674. self.optionBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  675. label = " %s " % _("Options"))
  676. task = gtask.parse_interface('g.extension')
  677. for f in task.get_options()['flags']:
  678. name = f.get('name', '')
  679. desc = f.get('label', '')
  680. if not desc:
  681. desc = f.get('description', '')
  682. if not name and not desc:
  683. continue
  684. if name in ('l', 'c', 'g', 'quiet', 'verbose'):
  685. continue
  686. self.options[name] = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  687. label = desc)
  688. self.repo.SetValue(task.get_param(value = 'svnurl').get('default',
  689. 'http://svn.osgeo.org/grass/grass-addons/grass7'))
  690. self.statusbar = self.CreateStatusBar(number = 1)
  691. self.btnFetch = wx.Button(parent = self.panel, id = wx.ID_ANY,
  692. label = _("&Fetch"))
  693. self.btnFetch.SetToolTipString(_("Fetch list of available modules from GRASS Addons SVN repository"))
  694. self.btnClose = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  695. self.btnInstall = wx.Button(parent = self.panel, id = wx.ID_ANY,
  696. label = _("&Install"))
  697. self.btnInstall.SetToolTipString(_("Install selected add-ons GRASS module"))
  698. self.btnInstall.Enable(False)
  699. self.btnCmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
  700. label = _("Command dialog"))
  701. self.btnCmd.SetToolTipString(_('Open %s dialog') % 'g.extension')
  702. self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
  703. self.btnFetch.Bind(wx.EVT_BUTTON, self.OnFetch)
  704. self.btnInstall.Bind(wx.EVT_BUTTON, self.OnInstall)
  705. self.btnCmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
  706. self.tree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnItemActivated)
  707. self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnItemSelected)
  708. self.search.Bind(wx.EVT_TEXT_ENTER, self.OnShowItem)
  709. self.search.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  710. self._layout()
  711. def _layout(self):
  712. """!Do layout"""
  713. sizer = wx.BoxSizer(wx.VERTICAL)
  714. repoSizer = wx.StaticBoxSizer(self.repoBox, wx.VERTICAL)
  715. repo1Sizer = wx.BoxSizer(wx.HORIZONTAL)
  716. repo1Sizer.Add(item = self.repo, proportion = 1,
  717. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL, border = 1)
  718. repo1Sizer.Add(item = self.btnFetch, proportion = 0,
  719. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL, border = 1)
  720. repoSizer.Add(item = repo1Sizer,
  721. flag = wx.EXPAND)
  722. repoSizer.Add(item = self.fullDesc)
  723. findSizer = wx.BoxSizer(wx.HORIZONTAL)
  724. findSizer.Add(item = self.search, proportion = 1)
  725. treeSizer = wx.StaticBoxSizer(self.treeBox, wx.HORIZONTAL)
  726. treeSizer.Add(item = self.tree, proportion = 1,
  727. flag = wx.ALL | wx.EXPAND, border = 1)
  728. # options
  729. optionSizer = wx.StaticBoxSizer(self.optionBox, wx.VERTICAL)
  730. for key in self.options.keys():
  731. optionSizer.Add(item = self.options[key], proportion = 0)
  732. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  733. btnSizer.Add(item = self.btnCmd, proportion = 0,
  734. flag = wx.RIGHT, border = 5)
  735. btnSizer.AddSpacer(10)
  736. btnSizer.Add(item = self.btnClose, proportion = 0,
  737. flag = wx.RIGHT, border = 5)
  738. btnSizer.Add(item = self.btnInstall, proportion = 0)
  739. sizer.Add(item = repoSizer, proportion = 0,
  740. flag = wx.ALL | wx.EXPAND, border = 3)
  741. sizer.Add(item = findSizer, proportion = 0,
  742. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  743. sizer.Add(item = treeSizer, proportion = 1,
  744. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  745. sizer.Add(item = optionSizer, proportion = 0,
  746. flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 3)
  747. sizer.Add(item = btnSizer, proportion = 0,
  748. flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  749. self.panel.SetSizer(sizer)
  750. sizer.Fit(self.panel)
  751. self.Layout()
  752. def _getCmd(self):
  753. item = self.tree.GetSelected()
  754. if not item or not item.IsOk():
  755. return ['g.extension']
  756. name = self.tree.GetItemText(item)
  757. if not name:
  758. gcmd.GError(_("Extension not defined"), parent = self)
  759. return
  760. flags = list()
  761. for key in self.options.keys():
  762. if self.options[key].IsChecked():
  763. flags.append('-%s' % key)
  764. return ['g.extension'] + flags + ['extension=' + name,
  765. 'svnurl=' + self.repo.GetValue().strip()]
  766. def OnUpdateStatusBar(self, event):
  767. """!Update statusbar text"""
  768. element = self.search.GetSelection()
  769. if not self.tree.IsLoaded():
  770. self.SetStatusText(_("Fetch list of available extensions by clicking on 'Fetch' button"), 0)
  771. return
  772. self.tree.SearchItems(element = element,
  773. value = event.GetString())
  774. nItems = len(self.tree.itemsMarked)
  775. if event.GetString():
  776. self.SetStatusText(_("%d items match") % nItems, 0)
  777. else:
  778. self.SetStatusText("", 0)
  779. event.Skip()
  780. def OnCloseWindow(self, event):
  781. """!Close window"""
  782. self.Destroy()
  783. def OnFetch(self, event):
  784. """!Fetch list of available extensions"""
  785. wx.BeginBusyCursor()
  786. self.SetStatusText(_("Fetching list of modules from GRASS-Addons SVN (be patient)..."), 0)
  787. self.tree.Load(url = self.repo.GetValue().strip(), full = self.fullDesc.IsChecked())
  788. self.SetStatusText("", 0)
  789. wx.EndBusyCursor()
  790. def OnItemActivated(self, event):
  791. item = event.GetItem()
  792. data = self.tree.GetPyData(item)
  793. if data and 'command' in data:
  794. self.OnInstall(event = None)
  795. def OnInstall(self, event):
  796. """!Install selected extension"""
  797. log = self.parent.GetLogWindow()
  798. log.RunCmd(self._getCmd(), onDone = self.OnDone)
  799. def OnDone(self, cmd, returncode):
  800. item = self.tree.GetSelected()
  801. if not item or not item.IsOk() or \
  802. returncode != 0 or \
  803. not os.getenv('GRASS_ADDON_PATH'):
  804. return
  805. name = self.tree.GetItemText(item)
  806. globalvar.grassCmd['all'].append(name)
  807. def OnItemSelected(self, event):
  808. """!Item selected"""
  809. item = event.GetItem()
  810. self.tree.itemSelected = item
  811. data = self.tree.GetPyData(item)
  812. if not data:
  813. self.SetStatusText('', 0)
  814. self.btnInstall.Enable(False)
  815. else:
  816. self.SetStatusText(data.get('description', ''), 0)
  817. self.btnInstall.Enable(True)
  818. def OnShowItem(self, event):
  819. """!Show selected item"""
  820. self.tree.OnShowItem(event)
  821. if self.tree.GetSelected():
  822. self.btnInstall.Enable()
  823. else:
  824. self.btnInstall.Enable(False)
  825. def OnCmdDialog(self, event):
  826. """!Shows command dialog"""
  827. menuform.GUI(parent = self).ParseCommand(cmd = self._getCmd())
  828. class ExtensionTree(ItemTree):
  829. """!List of available extensions"""
  830. def __init__(self, parent, log, id = wx.ID_ANY,
  831. ctstyle = CT.TR_HIDE_ROOT | CT.TR_FULL_ROW_HIGHLIGHT | CT.TR_HAS_BUTTONS |
  832. CT.TR_LINES_AT_ROOT | CT.TR_SINGLE,
  833. **kwargs):
  834. self.parent = parent # GMFrame
  835. self.log = log
  836. super(ExtensionTree, self).__init__(parent, id, ctstyle = ctstyle, **kwargs)
  837. self._initTree()
  838. def _initTree(self):
  839. for prefix in ('display', 'database',
  840. 'general', 'imagery',
  841. 'misc', 'postscript', 'paint',
  842. 'raster', 'raster3D', 'sites', 'vector', 'wxGUI', 'other'):
  843. self.AppendItem(parentId = self.root,
  844. text = prefix)
  845. self._loaded = False
  846. def _expandPrefix(self, c):
  847. name = { 'd' : 'display',
  848. 'db' : 'database',
  849. 'g' : 'general',
  850. 'i' : 'imagery',
  851. 'm' : 'misc',
  852. 'ps' : 'postscript',
  853. 'p' : 'paint',
  854. 'r' : 'raster',
  855. 'r3' : 'raster3D',
  856. 's' : 'sites',
  857. 'v' : 'vector',
  858. 'wx' : 'wxGUI',
  859. 'u' : 'other' }
  860. if c in name:
  861. return name[c]
  862. return c
  863. def _findItem(self, text):
  864. """!Find item"""
  865. item = self.GetFirstChild(self.root)[0]
  866. while item and item.IsOk():
  867. if text == self.GetItemText(item):
  868. return item
  869. item = self.GetNextSibling(item)
  870. return None
  871. def Load(self, url, full = False):
  872. """!Load list of extensions"""
  873. self.DeleteAllItems()
  874. self.root = self.AddRoot(_("Menu tree"))
  875. self._initTree()
  876. if full:
  877. flags = 'g'
  878. else:
  879. flags = 'l'
  880. ret = gcmd.RunCommand('g.extension', read = True,
  881. svnurl = url,
  882. flags = flags, quiet = True)
  883. if not ret:
  884. return
  885. mdict = dict()
  886. for line in ret.splitlines():
  887. if full:
  888. key, value = line.split('=', 1)
  889. if key == 'name':
  890. try:
  891. prefix, name = value.split('.', 1)
  892. except ValueError:
  893. prefix = 'u'
  894. name = value
  895. if prefix not in mdict:
  896. mdict[prefix] = dict()
  897. mdict[prefix][name] = dict()
  898. else:
  899. mdict[prefix][name][key] = value
  900. else:
  901. try:
  902. prefix, name = line.strip().split('.', 1)
  903. except:
  904. prefix = 'unknown'
  905. name = line.strip()
  906. if self._expandPrefix(prefix) == prefix:
  907. prefix = 'unknown'
  908. if prefix not in mdict:
  909. mdict[prefix] = dict()
  910. mdict[prefix][name] = { 'command' : prefix + '.' + name }
  911. for prefix in mdict.keys():
  912. prefixName = self._expandPrefix(prefix)
  913. item = self._findItem(prefixName)
  914. names = mdict[prefix].keys()
  915. names.sort()
  916. for name in names:
  917. new = self.AppendItem(parentId = item,
  918. text = prefix + '.' + name)
  919. data = dict()
  920. for key in mdict[prefix][name].keys():
  921. data[key] = mdict[prefix][name][key]
  922. self.SetPyData(new, data)
  923. self._loaded = True
  924. def IsLoaded(self):
  925. """Check if items are loaded"""
  926. return self._loaded
  927. class HelpWindow(wx.html.HtmlWindow):
  928. """!This panel holds the text from GRASS docs.
  929. GISBASE must be set in the environment to find the html docs dir.
  930. The SYNOPSIS section is skipped, since this Panel is supposed to
  931. be integrated into the cmdPanel and options are obvious there.
  932. """
  933. def __init__(self, parent, grass_command, text, skip_description,
  934. **kwargs):
  935. """!If grass_command is given, the corresponding HTML help
  936. file will be presented, with all links pointing to absolute
  937. paths of local files.
  938. If 'skip_description' is True, the HTML corresponding to
  939. SYNOPSIS will be skipped, thus only presenting the help file
  940. from the DESCRIPTION section onwards.
  941. If 'text' is given, it must be the HTML text to be presented
  942. in the Panel.
  943. """
  944. self.parent = parent
  945. wx.InitAllImageHandlers()
  946. wx.html.HtmlWindow.__init__(self, parent = parent, **kwargs)
  947. gisbase = os.getenv("GISBASE")
  948. self.loaded = False
  949. self.history = list()
  950. self.historyIdx = 0
  951. self.fspath = os.path.join(gisbase, "docs", "html")
  952. self.SetStandardFonts (size = 10)
  953. self.SetBorders(10)
  954. if text is None:
  955. if skip_description:
  956. url = os.path.join(self.fspath, grass_command + ".html")
  957. self.fillContentsFromFile(url,
  958. skip_description = skip_description)
  959. self.history.append(url)
  960. self.loaded = True
  961. else:
  962. ### FIXME: calling LoadPage() is strangely time-consuming (only first call)
  963. # self.LoadPage(self.fspath + grass_command + ".html")
  964. self.loaded = False
  965. else:
  966. self.SetPage(text)
  967. self.loaded = True
  968. def OnLinkClicked(self, linkinfo):
  969. url = linkinfo.GetHref()
  970. if url[:4] != 'http':
  971. url = os.path.join(self.fspath, url)
  972. self.history.append(url)
  973. self.historyIdx += 1
  974. self.parent.OnHistory()
  975. super(HelpWindow, self).OnLinkClicked(linkinfo)
  976. def fillContentsFromFile(self, htmlFile, skip_description = True):
  977. """!Load content from file"""
  978. aLink = re.compile(r'(<a href="?)(.+\.html?["\s]*>)', re.IGNORECASE)
  979. imgLink = re.compile(r'(<img src="?)(.+\.[png|gif])', re.IGNORECASE)
  980. try:
  981. contents = []
  982. skip = False
  983. for l in file(htmlFile, "rb").readlines():
  984. if "DESCRIPTION" in l:
  985. skip = False
  986. if not skip:
  987. # do skip the options description if requested
  988. if "SYNOPSIS" in l:
  989. skip = skip_description
  990. else:
  991. # FIXME: find only first item
  992. findALink = aLink.search(l)
  993. if findALink is not None:
  994. contents.append(aLink.sub(findALink.group(1)+
  995. self.fspath+findALink.group(2),l))
  996. findImgLink = imgLink.search(l)
  997. if findImgLink is not None:
  998. contents.append(imgLink.sub(findImgLink.group(1)+
  999. self.fspath+findImgLink.group(2),l))
  1000. if findALink is None and findImgLink is None:
  1001. contents.append(l)
  1002. self.SetPage("".join(contents))
  1003. self.loaded = True
  1004. except: # The Manual file was not found
  1005. self.loaded = False
  1006. class HelpPanel(wx.Panel):
  1007. def __init__(self, parent, grass_command = "index", text = None,
  1008. skip_description = False, **kwargs):
  1009. self.grass_command = grass_command
  1010. wx.Panel.__init__(self, parent = parent, id = wx.ID_ANY)
  1011. self.content = HelpWindow(self, grass_command, text,
  1012. skip_description)
  1013. self.btnNext = wx.Button(parent = self, id = wx.ID_ANY,
  1014. label = _("&Next"))
  1015. self.btnNext.Enable(False)
  1016. self.btnPrev = wx.Button(parent = self, id = wx.ID_ANY,
  1017. label = _("&Previous"))
  1018. self.btnPrev.Enable(False)
  1019. self.btnNext.Bind(wx.EVT_BUTTON, self.OnNext)
  1020. self.btnPrev.Bind(wx.EVT_BUTTON, self.OnPrev)
  1021. self._layout()
  1022. def _layout(self):
  1023. """!Do layout"""
  1024. sizer = wx.BoxSizer(wx.VERTICAL)
  1025. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1026. btnSizer.Add(item = self.btnPrev, proportion = 0,
  1027. flag = wx.ALL, border = 5)
  1028. btnSizer.Add(item = wx.Size(1, 1), proportion = 1)
  1029. btnSizer.Add(item = self.btnNext, proportion = 0,
  1030. flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  1031. sizer.Add(item = self.content, proportion = 1,
  1032. flag = wx.EXPAND)
  1033. sizer.Add(item = btnSizer, proportion = 0,
  1034. flag = wx.EXPAND)
  1035. self.SetSizer(sizer)
  1036. sizer.Fit(self)
  1037. def LoadPage(self, path = None):
  1038. """!Load page"""
  1039. if not path:
  1040. path = os.path.join(self.content.fspath, self.grass_command + ".html")
  1041. self.content.history.append(path)
  1042. self.content.LoadPage(path)
  1043. def IsFile(self):
  1044. """!Check if file exists"""
  1045. return os.path.isfile(os.path.join(self.content.fspath, self.grass_command + ".html"))
  1046. def IsLoaded(self):
  1047. return self.content.loaded
  1048. def OnHistory(self):
  1049. """!Update buttons"""
  1050. nH = len(self.content.history)
  1051. iH = self.content.historyIdx
  1052. if iH == nH - 1:
  1053. self.btnNext.Enable(False)
  1054. elif iH > -1:
  1055. self.btnNext.Enable(True)
  1056. if iH < 1:
  1057. self.btnPrev.Enable(False)
  1058. else:
  1059. self.btnPrev.Enable(True)
  1060. def OnNext(self, event):
  1061. """Load next page"""
  1062. self.content.historyIdx += 1
  1063. idx = self.content.historyIdx
  1064. path = self.content.history[idx]
  1065. self.content.LoadPage(path)
  1066. self.OnHistory()
  1067. event.Skip()
  1068. def OnPrev(self, event):
  1069. """Load previous page"""
  1070. self.content.historyIdx -= 1
  1071. idx = self.content.historyIdx
  1072. path = self.content.history[idx]
  1073. self.content.LoadPage(path)
  1074. self.OnHistory()
  1075. event.Skip()