prompt.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. """!
  2. @package prompt.py
  3. @brief wxGUI command prompt
  4. Classes:
  5. - PromptListCtrl
  6. - TextCtrlAutoComplete
  7. - GPrompt
  8. - GPromptPopUp
  9. - GPromptSTC
  10. (C) 2009-2010 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Martin Landa <landa.martin gmail.com>
  15. @author Michael Barton <michael.barton@asu.edu>
  16. """
  17. import os
  18. import sys
  19. import shlex
  20. import copy
  21. import wx
  22. import wx.stc
  23. import wx.lib.mixins.listctrl as listmix
  24. from grass.script import core as grass
  25. import globalvar
  26. import menudata
  27. import menuform
  28. import gcmd
  29. import utils
  30. class PromptListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
  31. """!PopUp window used by GPromptPopUp"""
  32. def __init__(self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition,
  33. size = wx.DefaultSize, style = 0):
  34. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  35. listmix.ListCtrlAutoWidthMixin.__init__(self)
  36. class TextCtrlAutoComplete(wx.ComboBox, listmix.ColumnSorterMixin):
  37. """!Auto complete text area used by GPromptPopUp"""
  38. def __init__ (self, parent, statusbar,
  39. id = wx.ID_ANY, choices = [], **kwargs):
  40. """!Constructor works just like wx.TextCtrl except you can pass in a
  41. list of choices. You can also change the choice list at any time
  42. by calling setChoices.
  43. Inspired by http://wiki.wxpython.org/TextCtrlAutoComplete
  44. """
  45. self.statusbar = statusbar
  46. if kwargs.has_key('style'):
  47. kwargs['style'] = wx.TE_PROCESS_ENTER | kwargs['style']
  48. else:
  49. kwargs['style'] = wx.TE_PROCESS_ENTER
  50. wx.ComboBox.__init__(self, parent, id, **kwargs)
  51. # some variables
  52. self._choices = choices
  53. self._hideOnNoMatch = True
  54. self._module = None # currently selected module
  55. self._choiceType = None # type of choice (module, params, flags, raster, vector ...)
  56. self._screenheight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)
  57. self._historyItem = 0 # last item
  58. # sort variable needed by listmix
  59. self.itemDataMap = dict()
  60. # widgets
  61. try:
  62. self.dropdown = wx.PopupWindow(self)
  63. except NotImplementedError:
  64. self.Destroy()
  65. raise NotImplementedError
  66. # create the list and bind the events
  67. self.dropdownlistbox = PromptListCtrl(parent = self.dropdown,
  68. style = wx.LC_REPORT | wx.LC_SINGLE_SEL | \
  69. wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER,
  70. pos = wx.Point(0, 0))
  71. listmix.ColumnSorterMixin.__init__(self, 1)
  72. # set choices (list of GRASS modules)
  73. self._choicesCmd = globalvar.grassCmd['all']
  74. self._choicesMap = dict()
  75. for type in ('raster', 'vector'):
  76. self._choicesMap[type] = grass.list_strings(type = type[:4])
  77. # first search for GRASS module
  78. self.SetChoices(self._choicesCmd)
  79. self.SetMinSize(self.GetSize())
  80. # bindings...
  81. self.Bind(wx.EVT_KILL_FOCUS, self.OnControlChanged)
  82. self.Bind(wx.EVT_TEXT, self.OnEnteredText)
  83. self.Bind(wx.EVT_TEXT_ENTER, self.OnRunCmd)
  84. self.Bind(wx.EVT_KEY_DOWN , self.OnKeyDown)
  85. ### self.Bind(wx.EVT_LEFT_DOWN, self.OnClick)
  86. # if need drop down on left click
  87. self.dropdown.Bind(wx.EVT_LISTBOX , self.OnListItemSelected, self.dropdownlistbox)
  88. self.dropdownlistbox.Bind(wx.EVT_LEFT_DOWN, self.OnListClick)
  89. self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.OnListDClick)
  90. self.dropdownlistbox.Bind(wx.EVT_LIST_COL_CLICK, self.OnListColClick)
  91. self.Bind(wx.EVT_COMBOBOX, self.OnCommandSelect)
  92. def _updateDataList(self, choices):
  93. """!Update data list"""
  94. # delete, if need, all the previous data
  95. if self.dropdownlistbox.GetColumnCount() != 0:
  96. self.dropdownlistbox.DeleteAllColumns()
  97. self.dropdownlistbox.DeleteAllItems()
  98. # and update the dict
  99. if choices:
  100. for numVal, data in enumerate(choices):
  101. self.itemDataMap[numVal] = data
  102. else:
  103. numVal = 0
  104. self.SetColumnCount(numVal)
  105. def _setListSize(self):
  106. """!Set list size"""
  107. choices = self._choices
  108. longest = 0
  109. for choice in choices:
  110. longest = max(len(choice), longest)
  111. longest += 3
  112. itemcount = min(len( choices ), 7) + 2
  113. charheight = self.dropdownlistbox.GetCharHeight()
  114. charwidth = self.dropdownlistbox.GetCharWidth()
  115. self.popupsize = wx.Size(charwidth*longest, charheight*itemcount)
  116. self.dropdownlistbox.SetSize(self.popupsize)
  117. self.dropdown.SetClientSize(self.popupsize)
  118. def _showDropDown(self, show = True):
  119. """!Either display the drop down list (show = True) or hide it
  120. (show = False).
  121. """
  122. if show:
  123. size = self.dropdown.GetSize()
  124. width, height = self.GetSizeTuple()
  125. x, y = self.ClientToScreenXY(0, height)
  126. if size.GetWidth() != width:
  127. size.SetWidth(width)
  128. self.dropdown.SetSize(size)
  129. self.dropdownlistbox.SetSize(self.dropdown.GetClientSize())
  130. if (y + size.GetHeight()) < self._screenheight:
  131. self.dropdown.SetPosition(wx.Point(x, y))
  132. else:
  133. self.dropdown.SetPosition(wx.Point(x, y - height - size.GetHeight()))
  134. self.dropdown.Show(show)
  135. def _listItemVisible(self):
  136. """!Moves the selected item to the top of the list ensuring it is
  137. always visible.
  138. """
  139. toSel = self.dropdownlistbox.GetFirstSelected()
  140. if toSel == -1:
  141. return
  142. self.dropdownlistbox.EnsureVisible(toSel)
  143. def _setModule(self, name):
  144. """!Set module's choices (flags, parameters)"""
  145. # get module's description
  146. if name in self._choicesCmd and not self._module:
  147. try:
  148. self._module = menuform.GUI().ParseInterface(cmd = [name])
  149. except IOError:
  150. self._module = None
  151. # set choices (flags)
  152. self._choicesMap['flag'] = self._module.get_list_flags()
  153. for idx in range(len(self._choicesMap['flag'])):
  154. item = self._choicesMap['flag'][idx]
  155. desc = self._module.get_flag(item)['label']
  156. if not desc:
  157. desc = self._module.get_flag(item)['description']
  158. self._choicesMap['flag'][idx] = '%s (%s)' % (item, desc)
  159. # set choices (parameters)
  160. self._choicesMap['param'] = self._module.get_list_params()
  161. for idx in range(len(self._choicesMap['param'])):
  162. item = self._choicesMap['param'][idx]
  163. desc = self._module.get_param(item)['label']
  164. if not desc:
  165. desc = self._module.get_param(item)['description']
  166. self._choicesMap['param'][idx] = '%s (%s)' % (item, desc)
  167. def _setValueFromSelected(self):
  168. """!Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
  169. Will do nothing if no item is selected in the wx.ListCtrl.
  170. """
  171. sel = self.dropdownlistbox.GetFirstSelected()
  172. if sel < 0:
  173. return
  174. if self._colFetch != -1:
  175. col = self._colFetch
  176. else:
  177. col = self._colSearch
  178. itemtext = self.dropdownlistbox.GetItem(sel, col).GetText()
  179. cmd = shlex.split(str(self.GetValue()))
  180. if len(cmd) > 0 and cmd[0] in self._choicesCmd:
  181. # -> append text (skip last item)
  182. if self._choiceType == 'param':
  183. itemtext = itemtext.split(' ')[0]
  184. self.SetValue(' '.join(cmd) + ' ' + itemtext + '=')
  185. optType = self._module.get_param(itemtext)['prompt']
  186. if optType in ('raster', 'vector'):
  187. # -> raster/vector map
  188. self.SetChoices(self._choicesMap[optType], optType)
  189. elif self._choiceType == 'flag':
  190. itemtext = itemtext.split(' ')[0]
  191. if len(itemtext) > 1:
  192. prefix = '--'
  193. else:
  194. prefix = '-'
  195. self.SetValue(' '.join(cmd[:-1]) + ' ' + prefix + itemtext)
  196. elif self._choiceType in ('raster', 'vector'):
  197. self.SetValue(' '.join(cmd[:-1]) + ' ' + cmd[-1].split('=', 1)[0] + '=' + itemtext)
  198. else:
  199. # -> reset text
  200. self.SetValue(itemtext + ' ')
  201. # define module
  202. self._setModule(itemtext)
  203. # use parameters as default choices
  204. self._choiceType = 'param'
  205. self.SetChoices(self._choicesMap['param'], type = 'param')
  206. self.SetInsertionPointEnd()
  207. self._showDropDown(False)
  208. def GetListCtrl(self):
  209. """!Method required by listmix.ColumnSorterMixin"""
  210. return self.dropdownlistbox
  211. def SetChoices(self, choices, type = 'module'):
  212. """!Sets the choices available in the popup wx.ListBox.
  213. The items will be sorted case insensitively.
  214. @param choices list of choices
  215. @param type type of choices (module, param, flag, raster, vector)
  216. """
  217. self._choices = choices
  218. self._choiceType = type
  219. self.dropdownlistbox.SetWindowStyleFlag(wx.LC_REPORT | wx.LC_SINGLE_SEL |
  220. wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER)
  221. if not isinstance(choices, list):
  222. self._choices = [ x for x in choices ]
  223. if self._choiceType not in ('raster', 'vector'):
  224. # do not sort raster/vector maps
  225. utils.ListSortLower(self._choices)
  226. self._updateDataList(self._choices)
  227. self.dropdownlistbox.InsertColumn(0, "")
  228. for num, colVal in enumerate(self._choices):
  229. index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1)
  230. self.dropdownlistbox.SetStringItem(index, 0, colVal)
  231. self.dropdownlistbox.SetItemData(index, num)
  232. self._setListSize()
  233. # there is only one choice for both search and fetch if setting a single column:
  234. self._colSearch = 0
  235. self._colFetch = -1
  236. def OnClick(self, event):
  237. """Left mouse button pressed"""
  238. sel = self.dropdownlistbox.GetFirstSelected()
  239. if not self.dropdown.IsShown():
  240. if sel > -1:
  241. self.dropdownlistbox.Select(sel)
  242. else:
  243. self.dropdownlistbox.Select(0)
  244. self._listItemVisible()
  245. self._showDropDown()
  246. else:
  247. self.dropdown.Hide()
  248. def OnCommandSelect(self, event):
  249. """!Command selected from history"""
  250. self._historyItem = event.GetSelection() - len(self.GetItems())
  251. self.SetFocus()
  252. def OnListClick(self, evt):
  253. """!Left mouse button pressed"""
  254. toSel, flag = self.dropdownlistbox.HitTest( evt.GetPosition() )
  255. #no values on poition, return
  256. if toSel == -1: return
  257. self.dropdownlistbox.Select(toSel)
  258. def OnListDClick(self, evt):
  259. """!Mouse button double click"""
  260. self._setValueFromSelected()
  261. def OnListColClick(self, evt):
  262. """!Left mouse button pressed on column"""
  263. col = evt.GetColumn()
  264. # reverse the sort
  265. if col == self._colSearch:
  266. self._ascending = not self._ascending
  267. self.SortListItems( evt.GetColumn(), ascending=self._ascending )
  268. self._colSearch = evt.GetColumn()
  269. evt.Skip()
  270. def OnListItemSelected(self, event):
  271. """!Item selected"""
  272. self._setValueFromSelected()
  273. event.Skip()
  274. def OnEnteredText(self, event):
  275. """!Text entered"""
  276. text = event.GetString()
  277. if not text:
  278. # control is empty; hide dropdown if shown:
  279. if self.dropdown.IsShown():
  280. self._showDropDown(False)
  281. event.Skip()
  282. return
  283. try:
  284. cmd = shlex.split(str(text))
  285. except ValueError, e:
  286. self.statusbar.SetStatusText(str(e))
  287. cmd = text.split(' ')
  288. pattern = str(text)
  289. if len(cmd) > 0 and cmd[0] in self._choicesCmd and not self._module:
  290. self._setModule(cmd[0])
  291. elif len(cmd) > 1 and cmd[0] in self._choicesCmd:
  292. if self._module:
  293. if len(cmd[-1].split('=', 1)) == 1:
  294. # new option
  295. if cmd[-1][0] == '-':
  296. # -> flags
  297. self.SetChoices(self._choicesMap['flag'], type = 'flag')
  298. pattern = cmd[-1].lstrip('-')
  299. else:
  300. # -> options
  301. self.SetChoices(self._choicesMap['param'], type = 'param')
  302. pattern = cmd[-1]
  303. else:
  304. # value
  305. pattern = cmd[-1].split('=', 1)[1]
  306. else:
  307. # search for GRASS modules
  308. if self._module:
  309. # -> switch back to GRASS modules list
  310. self.SetChoices(self._choicesCmd)
  311. self._module = None
  312. self._choiceType = None
  313. self._choiceType
  314. self._choicesMap
  315. found = False
  316. choices = self._choices
  317. for numCh, choice in enumerate(choices):
  318. if choice.lower().startswith(pattern):
  319. found = True
  320. if found:
  321. self._showDropDown(True)
  322. item = self.dropdownlistbox.GetItem(numCh)
  323. toSel = item.GetId()
  324. self.dropdownlistbox.Select(toSel)
  325. break
  326. if not found:
  327. self.dropdownlistbox.Select(self.dropdownlistbox.GetFirstSelected(), False)
  328. if self._hideOnNoMatch:
  329. self._showDropDown(False)
  330. if self._module and '=' not in cmd[-1]:
  331. message = ''
  332. if cmd[-1][0] == '-': # flag
  333. message = _("Warning: flag <%(flag)s> not found in '%(module)s'") % \
  334. { 'flag' : cmd[-1][1:], 'module' : self._module.name }
  335. else: # option
  336. message = _("Warning: option <%(param)s> not found in '%(module)s'") % \
  337. { 'param' : cmd[-1], 'module' : self._module.name }
  338. self.statusbar.SetStatusText(message)
  339. if self._module and len(cmd[-1]) == 2 and cmd[-1][-2] == '=':
  340. optType = self._module.get_param(cmd[-1][:-2])['prompt']
  341. if optType in ('raster', 'vector'):
  342. # -> raster/vector map
  343. self.SetChoices(self._choicesMap[optType], optType)
  344. self._listItemVisible()
  345. event.Skip()
  346. def OnKeyDown (self, event):
  347. """!Do some work when the user press on the keys: up and down:
  348. move the cursor left and right: move the search
  349. """
  350. skip = True
  351. sel = self.dropdownlistbox.GetFirstSelected()
  352. visible = self.dropdown.IsShown()
  353. KC = event.GetKeyCode()
  354. if KC == wx.WXK_RIGHT:
  355. # right -> show choices
  356. if sel < (self.dropdownlistbox.GetItemCount() - 1):
  357. self.dropdownlistbox.Select(sel + 1)
  358. self._listItemVisible()
  359. self._showDropDown()
  360. skip = False
  361. elif KC == wx.WXK_UP:
  362. if visible:
  363. if sel > 0:
  364. self.dropdownlistbox.Select(sel - 1)
  365. self._listItemVisible()
  366. self._showDropDown()
  367. skip = False
  368. else:
  369. self._historyItem -= 1
  370. try:
  371. self.SetValue(self.GetItems()[self._historyItem])
  372. except IndexError:
  373. self._historyItem += 1
  374. elif KC == wx.WXK_DOWN:
  375. if visible:
  376. if sel < (self.dropdownlistbox.GetItemCount() - 1):
  377. self.dropdownlistbox.Select(sel + 1)
  378. self._listItemVisible()
  379. self._showDropDown()
  380. skip = False
  381. else:
  382. if self._historyItem < -1:
  383. self._historyItem += 1
  384. self.SetValue(self.GetItems()[self._historyItem])
  385. if visible:
  386. if event.GetKeyCode() == wx.WXK_RETURN:
  387. self._setValueFromSelected()
  388. skip = False
  389. if event.GetKeyCode() == wx.WXK_ESCAPE:
  390. self._showDropDown(False)
  391. skip = False
  392. if skip:
  393. event.Skip()
  394. def OnControlChanged(self, event):
  395. """!Control changed"""
  396. if self.IsShown():
  397. self._showDropDown(False)
  398. event.Skip()
  399. class GPrompt(object):
  400. """!Abstract class for interactive wxGUI prompt
  401. See subclass GPromptPopUp and GPromptSTC.
  402. """
  403. def __init__(self, parent):
  404. self.parent = parent # GMConsole
  405. self.panel = self.parent.GetPanel()
  406. if self.parent.parent.GetName() not in ("LayerManager", "Modeler"):
  407. self.standAlone = True
  408. else:
  409. self.standAlone = False
  410. # dictionary of modules (description, keywords, ...)
  411. if not self.standAlone:
  412. if self.parent.parent.GetName() == 'Modeler':
  413. self.moduleDesc = menudata.ManagerData().GetModules()
  414. else:
  415. self.moduleDesc = parent.parent.menubar.GetData().GetModules()
  416. self.moduleList = self._getListOfModules()
  417. self.mapList = self._getListOfMaps()
  418. else:
  419. self.moduleDesc = self.moduleList = self.mapList = None
  420. # auto complete items
  421. self.autoCompList = list()
  422. self.autoCompFilter = None
  423. # command description (menuform.grassTask)
  424. self.cmdDesc = None
  425. self.cmdbuffer = self._readHistory()
  426. self.cmdindex = len(self.cmdbuffer)
  427. def CheckKey(self, text, keywords):
  428. """!Check if text is in keywords (unused)"""
  429. found = 0
  430. keys = text.split(',')
  431. if len(keys) > 1: # -> multiple keys
  432. for k in keys[:-1]:
  433. k = k.strip()
  434. for key in keywords:
  435. if k == key: # full match
  436. found += 1
  437. break
  438. k = keys[-1].strip()
  439. for key in keywords:
  440. if k in key: # partial match
  441. found +=1
  442. break
  443. else:
  444. for key in keywords:
  445. if text in key: # partial match
  446. found +=1
  447. break
  448. if found == len(keys):
  449. return True
  450. return False
  451. def _readHistory(self):
  452. """!Get list of commands from history file"""
  453. hist = list()
  454. env = grass.gisenv()
  455. try:
  456. fileHistory = open(os.path.join(env['GISDBASE'],
  457. env['LOCATION_NAME'],
  458. env['MAPSET'],
  459. '.bash_history'), 'r')
  460. except IOError:
  461. return hist
  462. try:
  463. for line in fileHistory.readlines():
  464. hist.append(line.replace('\n', ''))
  465. finally:
  466. fileHistory.close()
  467. return hist
  468. def GetCommandDesc(self, cmd):
  469. """!Get description for given command"""
  470. if self.moduleDesc.has_key(cmd):
  471. return self.moduleDesc[cmd]['desc']
  472. return ''
  473. def GetCommandItems(self):
  474. """!Get list of available commands"""
  475. items = list()
  476. if self.autoCompFilter is not None:
  477. mList = self.autoCompFilter
  478. else:
  479. mList = self.moduleList
  480. if not mList:
  481. return items
  482. prefixes = mList.keys()
  483. prefixes.sort()
  484. for prefix in prefixes:
  485. for command in mList[prefix]:
  486. name = prefix + '.' + command
  487. items.append(name)
  488. items.sort()
  489. return items
  490. def _getListOfModules(self):
  491. """!Get list of modules"""
  492. result = dict()
  493. for module in globalvar.grassCmd['all']:
  494. try:
  495. group, name = module.split('.', 1)
  496. except ValueError:
  497. continue # TODO
  498. if not result.has_key(group):
  499. result[group] = list()
  500. result[group].append(name)
  501. # sort list of names
  502. for group in result.keys():
  503. result[group].sort()
  504. return result
  505. def _getListOfMaps(self):
  506. """!Get list of maps"""
  507. result = dict()
  508. result['raster'] = grass.list_strings('rast')
  509. result['vector'] = grass.list_strings('vect')
  510. return result
  511. def OnRunCmd(self, event):
  512. """!Run command"""
  513. cmdString = event.GetString()
  514. if self.standAlone:
  515. return
  516. if cmdString[:2] == 'd.' and not self.parent.curr_page:
  517. self.parent.NewDisplay(show=True)
  518. cmd = utils.split(cmdString)
  519. if len(cmd) > 1:
  520. self.parent.RunCmd(cmd, switchPage = True)
  521. else:
  522. self.parent.RunCmd(cmd, switchPage = False)
  523. self.OnUpdateStatusBar(None)
  524. def OnUpdateStatusBar(self, event):
  525. """!Update Layer Manager status bar"""
  526. if self.standAlone:
  527. return
  528. if event is None:
  529. self.parent.parent.statusbar.SetStatusText("")
  530. else:
  531. self.parent.parent.statusbar.SetStatusText(_("Type GRASS command and run by pressing ENTER"))
  532. event.Skip()
  533. def GetPanel(self):
  534. """!Get main widget panel"""
  535. return self.panel
  536. def GetInput(self):
  537. """!Get main prompt widget"""
  538. return self.input
  539. class GPromptPopUp(GPrompt, TextCtrlAutoComplete):
  540. """!Interactive wxGUI prompt - popup version"""
  541. def __init__(self, parent):
  542. GPrompt.__init__(self, parent)
  543. ### todo: fix TextCtrlAutoComplete to work also on Macs
  544. ### reason: missing wx.PopupWindow()
  545. try:
  546. TextCtrlAutoComplete.__init__(self, parent = self.panel, id = wx.ID_ANY,
  547. value = "",
  548. style = wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  549. statusbar = self.parent.parent.statusbar)
  550. self.SetItems(self._readHistory())
  551. except NotImplementedError:
  552. # wx.PopupWindow may be not available in wxMac
  553. # see http://trac.wxwidgets.org/ticket/9377
  554. wx.TextCtrl.__init__(parent = self.panel, id = wx.ID_ANY,
  555. value = "",
  556. style=wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  557. size = (-1, 25))
  558. self.searchBy.Enable(False)
  559. self.search.Enable(False)
  560. self.SetFont(wx.Font(10, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.NORMAL, 0, ''))
  561. wx.CallAfter(self.SetInsertionPoint, 0)
  562. # bidnings
  563. self.Bind(wx.EVT_TEXT_ENTER, self.OnRunCmd)
  564. self.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  565. def OnCmdErase(self, event):
  566. """!Erase command prompt"""
  567. self.input.SetValue('')
  568. class GPromptSTC(GPrompt, wx.stc.StyledTextCtrl):
  569. """!Styled wxGUI prompt with autocomplete and calltips"""
  570. def __init__(self, parent, id = wx.ID_ANY, margin = False):
  571. GPrompt.__init__(self, parent)
  572. wx.stc.StyledTextCtrl.__init__(self, self.panel, id)
  573. #
  574. # styles
  575. #
  576. self.SetWrapMode(True)
  577. self.SetUndoCollection(True)
  578. #
  579. # create command and map lists for autocompletion
  580. #
  581. self.AutoCompSetIgnoreCase(False)
  582. #
  583. # line margins
  584. #
  585. # TODO print number only from cmdlog
  586. self.SetMarginWidth(1, 0)
  587. self.SetMarginWidth(2, 0)
  588. if margin:
  589. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  590. self.SetMarginWidth(0, 30)
  591. else:
  592. self.SetMarginWidth(0, 0)
  593. #
  594. # miscellaneous
  595. #
  596. self.SetViewWhiteSpace(False)
  597. self.SetUseTabs(False)
  598. self.UsePopUp(True)
  599. self.SetSelBackground(True, "#FFFF00")
  600. self.SetUseHorizontalScrollBar(True)
  601. #
  602. # bindings
  603. #
  604. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  605. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  606. self.Bind(wx.stc.EVT_STC_AUTOCOMP_SELECTION, self.OnItemSelected)
  607. def SetFilter(self, items):
  608. """!Sets filter
  609. @param choices list of items to be filtered
  610. """
  611. self.autoCompFilter = items
  612. def OnItemSelected(self, event):
  613. """!Item selected from the list"""
  614. text = self.GetTextLeft()[:self.AutoCompPosStart()] + event.GetText() + ' '
  615. self.SetText(text)
  616. pos = len(text)
  617. self.SetSelectionStart(pos)
  618. self.SetCurrentPos(pos)
  619. cmd = text.split()[0]
  620. if not self.cmdDesc or cmd != self.cmdDesc.get_name():
  621. if cmd in ('r.mapcalc', 'r3.mapcalc'):
  622. self.parent.parent.OnMapCalculator(event = None, cmd = [cmd])
  623. # add command to history & clean prompt
  624. self.UpdateCmdHistory([cmd])
  625. self.OnCmdErase(None)
  626. else:
  627. try:
  628. self.cmdDesc = menuform.GUI().ParseInterface(cmd = [cmd])
  629. except IOError:
  630. self.cmdDesc = None
  631. def UpdateCmdHistory(self, cmd):
  632. """!Update command history
  633. @param cmd command given as a list
  634. """
  635. # add command to history
  636. self.cmdbuffer.append(' '.join(cmd))
  637. # keep command history to a managable size
  638. if len(self.cmdbuffer) > 200:
  639. del self.cmdbuffer[0]
  640. self.cmdindex = len(self.cmdbuffer)
  641. def OnKeyPressed(self, event):
  642. """!Key press capture for autocompletion, calltips, and command history
  643. @todo event.ControlDown() for manual autocomplete
  644. """
  645. # keycodes used: "." = 46, "=" = 61, "," = 44
  646. if event.GetKeyCode() == 46 and not event.ShiftDown():
  647. # GRASS command autocomplete when '.' is pressed after 'r', 'v', 'i', 'g', 'db', or 'd'
  648. self.autoCompList = list()
  649. pos = self.GetCurrentPos()
  650. self.InsertText(pos, '.')
  651. self.CharRight()
  652. entry = self.GetTextLeft()
  653. if entry not in ['r.', 'v.', 'i.', 'g.', 'db.', 'd.']:
  654. return
  655. if self.autoCompFilter:
  656. self.autoCompList = self.autoCompFilter[entry[:-1]]
  657. else:
  658. self.autoCompList = self.moduleList[entry[:-1]]
  659. if len(self.autoCompList) > 0:
  660. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  661. elif event.GetKeyCode() == wx.WXK_TAB:
  662. # show GRASS command calltips (to hide press 'ESC')
  663. pos = self.GetCurrentPos()
  664. entry = self.GetTextLeft()
  665. try:
  666. cmd = entry.split()[0].strip()
  667. except IndexError:
  668. cmd = ''
  669. if cmd not in globalvar.grassCmd['all']:
  670. return
  671. usage, description = self.GetCommandUsage(cmd)
  672. self.CallTipSetBackground("#f4f4d1")
  673. self.CallTipSetForeground("BLACK")
  674. self.CallTipShow(pos, usage + '\n\n' + description)
  675. elif (event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown()) or \
  676. (not event.ShiftDown() and (event.GetKeyCode() == 61 or event.GetKeyCode() == 44)):
  677. # Autocompletion for map/data file name entry after '=', ',', or manually
  678. pos = self.GetCurrentPos()
  679. entry = self.GetTextLeft()
  680. if 'r.mapcalc' in entry:
  681. self.InsertText(pos, '=')
  682. self.CharRight()
  683. return
  684. if event.GetKeyCode() != 44:
  685. self.promptType = None
  686. if not self.cmdDesc:
  687. # No partial or complete GRASS command found
  688. return
  689. try:
  690. # find last typed option
  691. arg = entry.rstrip('=').rsplit(' ', 1)[1]
  692. except:
  693. arg = ''
  694. try:
  695. self.promptType = self.cmdDesc.get_param(arg)['prompt']
  696. except:
  697. pass
  698. if event.GetKeyCode() == 61:
  699. # autocompletion after '='
  700. # insert the '=' and move to after the '=', ready for a map name
  701. self.InsertText(pos, '=')
  702. self.CharRight()
  703. elif event.GetKeyCode() == 44:
  704. # autocompletion after ','
  705. # if comma is pressed, use the same maptype as previous for multiple map entries
  706. # insert the comma and move to after the comma ready for a map name
  707. self.InsertText(pos,',')
  708. self.CharRight()
  709. #must apply to an entry where '=[string]' has already been entered
  710. if '=' not in arg:
  711. return
  712. elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
  713. # manual autocompletion
  714. # map entries without arguments (as in r.info [mapname]) use ctrl-shift
  715. if not self.cmdDesc:
  716. return
  717. try:
  718. param = self.cmdDesc.get_list_params()[0]
  719. self.promptType = self.cmdDesc.get_param(param)['prompt']
  720. except IndexError:
  721. return
  722. if self.promptType and self.promptType in ('raster', 'raster3d', 'vector'):
  723. self.autoCompList = self.mapList[self.promptType]
  724. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  725. elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and \
  726. not self.AutoCompActive():
  727. # Command history using up and down
  728. if len(self.cmdbuffer) < 1:
  729. return
  730. self.DocumentEnd()
  731. # move through command history list index values
  732. if event.GetKeyCode() == wx.WXK_UP:
  733. self.cmdindex = self.cmdindex - 1
  734. if event.GetKeyCode() == wx.WXK_DOWN:
  735. self.cmdindex = self.cmdindex + 1
  736. if self.cmdindex < 0:
  737. self.cmdindex = 0
  738. if self.cmdindex > len(self.cmdbuffer) - 1:
  739. self.cmdindex = len(self.cmdbuffer) - 1
  740. try:
  741. txt = self.cmdbuffer[self.cmdindex]
  742. except:
  743. txt = ''
  744. # clear current line and insert command history
  745. self.DelLineLeft()
  746. self.DelLineRight()
  747. pos = self.GetCurrentPos()
  748. self.InsertText(pos,txt)
  749. self.LineEnd()
  750. elif event.GetKeyCode() == wx.WXK_RETURN and \
  751. self.AutoCompActive() == False:
  752. # run command on line when <return> is pressed
  753. if self.parent.GetName() == "ModelerDialog":
  754. self.parent.OnOk(None)
  755. return
  756. # find the command to run
  757. line = self.GetCurLine()[0].strip()
  758. if len(line) == 0:
  759. return
  760. # parse command into list
  761. try:
  762. cmd = utils.split(str(line))
  763. except UnicodeError:
  764. cmd = utils.split(utils.EncodeString((line)))
  765. # send the command list to the processor
  766. if cmd[0] in ('r.mapcalc', 'r3.mapcalc') and len(cmd) == 1:
  767. self.parent.parent.OnMapCalculator(event = None, cmd = cmd)
  768. else:
  769. self.parent.RunCmd(cmd)
  770. # add command to history & clean prompt
  771. self.UpdateCmdHistory(cmd)
  772. self.OnCmdErase(None)
  773. elif event.GetKeyCode() == wx.WXK_SPACE:
  774. items = self.GetTextLeft().split()
  775. if len(items) == 1:
  776. cmd = items[0].strip()
  777. if cmd in globalvar.grassCmd['all'] and \
  778. cmd != 'r.mapcalc' and \
  779. (not self.cmdDesc or cmd != self.cmdDesc.get_name()):
  780. try:
  781. self.cmdDesc = menuform.GUI().ParseInterface(cmd = [cmd])
  782. except IOError:
  783. self.cmdDesc = None
  784. event.Skip()
  785. else:
  786. event.Skip()
  787. def GetTextLeft(self):
  788. """!Returns all text left of the caret"""
  789. pos = self.GetCurrentPos()
  790. self.HomeExtend()
  791. entry = self.GetSelectedText()
  792. self.SetCurrentPos(pos)
  793. return entry
  794. def GetCommandUsage(self, command):
  795. """!Returns command syntax by running command help"""
  796. usage = ''
  797. description = ''
  798. ret, out = gcmd.RunCommand(command, 'help', getErrorMsg = True)
  799. if ret == 0:
  800. cmdhelp = out.splitlines()
  801. addline = False
  802. helplist = []
  803. description = ''
  804. for line in cmdhelp:
  805. if "Usage:" in line:
  806. addline = True
  807. continue
  808. elif "Flags:" in line:
  809. addline = False
  810. break
  811. elif addline == True:
  812. line = line.strip()
  813. helplist.append(line)
  814. for line in cmdhelp:
  815. if "Description:" in line:
  816. addline = True
  817. continue
  818. elif "Keywords:" in line:
  819. addline = False
  820. break
  821. elif addline == True:
  822. description += (line + ' ')
  823. description = description.strip()
  824. for line in helplist:
  825. usage += line + '\n'
  826. return usage.strip(), description
  827. else:
  828. return ''
  829. def OnDestroy(self, event):
  830. """!The clipboard contents can be preserved after
  831. the app has exited"""
  832. wx.TheClipboard.Flush()
  833. event.Skip()
  834. def OnCmdErase(self, event):
  835. """!Erase command prompt"""
  836. self.Home()
  837. self.DelLineRight()