prompt.py 34 KB

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