prompt.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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 = list()
  444. def _getListOfModules(self):
  445. """!Get list of modules"""
  446. result = dict()
  447. for module in globalvar.grassCmd['all']:
  448. try:
  449. group, name = module.split('.', 1)
  450. except ValueError:
  451. continue # TODO
  452. if not result.has_key(group):
  453. result[group] = list()
  454. result[group].append(name)
  455. # sort list of names
  456. for group in result.keys():
  457. result[group].sort()
  458. return result
  459. def _getListOfMaps(self):
  460. """!Get list of maps"""
  461. result = dict()
  462. result['raster'] = grass.list_strings('rast')
  463. result['vector'] = grass.list_strings('vect')
  464. return result
  465. def OnRunCmd(self, event):
  466. """!Run command"""
  467. cmdString = event.GetString()
  468. if self.standAlone:
  469. return
  470. if cmdString[:2] == 'd.' and not self.parent.curr_page:
  471. self.parent.NewDisplay(show=True)
  472. cmd = shlex.split(str(cmdString))
  473. if len(cmd) > 1:
  474. self.parent.goutput.RunCmd(cmd, switchPage = True)
  475. else:
  476. self.parent.goutput.RunCmd(cmd, switchPage = False)
  477. self.OnUpdateStatusBar(None)
  478. def OnUpdateStatusBar(self, event):
  479. """!Update Layer Manager status bar"""
  480. if self.standAlone:
  481. return
  482. if event is None:
  483. self.parent.statusbar.SetStatusText("")
  484. else:
  485. self.parent.statusbar.SetStatusText(_("Type GRASS command and run by pressing ENTER"))
  486. event.Skip()
  487. def GetPanel(self):
  488. """!Get main widget panel"""
  489. return self.panel
  490. def GetInput(self):
  491. """!Get main prompt widget"""
  492. return self.input
  493. class GPromptPopUp(GPrompt, TextCtrlAutoComplete):
  494. """!Interactive wxGUI prompt - popup version"""
  495. def __init__(self, parent):
  496. GPrompt.__init__(self, parent)
  497. ### todo: fix TextCtrlAutoComplete to work also on Macs
  498. ### reason: missing wx.PopupWindow()
  499. try:
  500. TextCtrlAutoComplete.__init__(self, parent = self.panel, id = wx.ID_ANY,
  501. value = "",
  502. style = wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  503. statusbar = self.parent.parent.statusbar)
  504. except NotImplementedError:
  505. # wx.PopupWindow may be not available in wxMac
  506. # see http://trac.wxwidgets.org/ticket/9377
  507. wx.TextCtrl.__init__(parent = self.panel, id = wx.ID_ANY,
  508. value = "",
  509. style=wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  510. size = (-1, 25))
  511. self.searchBy.Enable(False)
  512. self.search.Enable(False)
  513. self.SetFont(wx.Font(10, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.NORMAL, 0, ''))
  514. wx.CallAfter(self.SetInsertionPoint, 0)
  515. # bidnings
  516. self.Bind(wx.EVT_TEXT_ENTER, self.OnRunCmd)
  517. self.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  518. def __checkKey(self, text, keywords):
  519. """!Check if text is in keywords (unused)"""
  520. found = 0
  521. keys = text.split(',')
  522. if len(keys) > 1: # -> multiple keys
  523. for k in keys[:-1]:
  524. k = k.strip()
  525. for key in keywords:
  526. if k == key: # full match
  527. found += 1
  528. break
  529. k = keys[-1].strip()
  530. for key in keywords:
  531. if k in key: # partial match
  532. found +=1
  533. break
  534. else:
  535. for key in keywords:
  536. if text in key: # partial match
  537. found +=1
  538. break
  539. if found == len(keys):
  540. return True
  541. return False
  542. def OnCmdErase(self, event):
  543. """!Erase command prompt"""
  544. self.input.SetValue('')
  545. class GPromptSTC(GPrompt, wx.stc.StyledTextCtrl):
  546. """!Styled wxGUI prompt with autocomplete and calltips"""
  547. def __init__(self, parent, id = wx.ID_ANY, margin = False):
  548. GPrompt.__init__(self, parent)
  549. wx.stc.StyledTextCtrl.__init__(self, self.panel, id)
  550. #
  551. # styles
  552. #
  553. self.SetWrapMode(True)
  554. self.SetUndoCollection(True)
  555. #
  556. # create command and map lists for autocompletion
  557. #
  558. self.AutoCompSetIgnoreCase(False)
  559. #
  560. # line margins
  561. #
  562. # TODO print number only from cmdlog
  563. self.SetMarginWidth(1, 0)
  564. self.SetMarginWidth(2, 0)
  565. if margin:
  566. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  567. self.SetMarginWidth(0, 30)
  568. else:
  569. self.SetMarginWidth(0, 0)
  570. #
  571. # miscellaneous
  572. #
  573. self.SetViewWhiteSpace(False)
  574. self.SetUseTabs(False)
  575. self.UsePopUp(True)
  576. self.SetSelBackground(True, "#FFFF00")
  577. self.SetUseHorizontalScrollBar(True)
  578. #
  579. # bindings
  580. #
  581. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  582. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  583. self.Bind(wx.stc.EVT_STC_AUTOCOMP_SELECTION, self.OnItemSelected)
  584. def SetFilter(self, items):
  585. """!Sets filter
  586. @param choices list of items to be filtered
  587. """
  588. self.autoCompFilter = items
  589. def OnItemSelected(self, event):
  590. """!Item selected from the list"""
  591. text = self.GetTextLeft()[:self.AutoCompPosStart()] + event.GetText() + ' '
  592. self.SetText(text)
  593. pos = len(text)
  594. self.SetSelectionStart(pos)
  595. self.SetCurrentPos(pos)
  596. cmd = text.split()[0]
  597. if not self.cmdDesc or cmd != self.cmdDesc.get_name():
  598. try:
  599. self.cmdDesc = menuform.GUI().ParseInterface(cmd = [cmd])
  600. except IOError:
  601. self.cmdDesc = None
  602. def OnKeyPressed(self, event):
  603. """!Key press capture for autocompletion, calltips, and command history
  604. @todo event.ControlDown() for manual autocomplete
  605. """
  606. # keycodes used: "." = 46, "=" = 61, "," = 44
  607. if event.GetKeyCode() == 46 and not event.ShiftDown():
  608. # GRASS command autocomplete when '.' is pressed after 'r', 'v', 'i', 'g', 'db', or 'd'
  609. self.autoCompList = list()
  610. pos = self.GetCurrentPos()
  611. self.InsertText(pos, '.')
  612. self.CharRight()
  613. entry = self.GetTextLeft()
  614. if entry not in ['r.', 'v.', 'i.', 'g.', 'db.', 'd.']:
  615. return
  616. if self.autoCompFilter:
  617. self.autoCompList = self.autoCompFilter[entry[:-1]]
  618. else:
  619. self.autoCompList = self.moduleList[entry[:-1]]
  620. if len(self.autoCompList) > 0:
  621. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  622. elif event.GetKeyCode() == wx.WXK_TAB:
  623. # show GRASS command calltips (to hide press 'ESC')
  624. pos = self.GetCurrentPos()
  625. entry = self.GetTextLeft()
  626. try:
  627. cmd = entry.split()[0].strip()
  628. except IndexError:
  629. cmd = ''
  630. if cmd not in globalvar.grassCmd['all']:
  631. return
  632. usage, description = self.GetCommandUsage(cmd)
  633. self.CallTipSetBackground("GREY")
  634. self.CallTipSetForeground("BLACK")
  635. self.CallTipShow(pos, usage + '\n\n' + description)
  636. elif (event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown()) or \
  637. event.GetKeyCode() == 61 or event.GetKeyCode() == 44:
  638. # Autocompletion for map/data file name entry after '=', ',', or manually
  639. pos = self.GetCurrentPos()
  640. entry = self.GetTextLeft()
  641. if event.GetKeyCode() != 44:
  642. self.promptType = None
  643. if not self.cmdDesc:
  644. # No partial or complete GRASS command found
  645. return
  646. try:
  647. # find last typed option
  648. arg = entry.rstrip('=').rsplit(' ', 1)[1]
  649. except:
  650. arg = ''
  651. self.promptType = self.cmdDesc.get_param(arg)['prompt']
  652. if event.GetKeyCode() == 61:
  653. # autocompletion after '='
  654. # insert the '=' and move to after the '=', ready for a map name
  655. self.InsertText(pos, '=')
  656. self.CharRight()
  657. elif event.GetKeyCode() == 44:
  658. # autocompletion after ','
  659. # if comma is pressed, use the same maptype as previous for multiple map entries
  660. # insert the comma and move to after the comma ready for a map name
  661. self.InsertText(pos,',')
  662. self.CharRight()
  663. #must apply to an entry where '=[string]' has already been entered
  664. if '=' not in arg:
  665. return
  666. elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
  667. # manual autocompletion
  668. # map entries without arguments (as in r.info [mapname]) use ctrl-shift
  669. cmdtype = self.GetTextLeft().split('.')[0]
  670. if cmdtype=='r' or cmdtype=='i':
  671. self.promptType = 'raster'
  672. elif cmdtype=='v':
  673. self.promptType = 'vector'
  674. elif cmdtype=='r3':
  675. self.promptType = 'raster3d'
  676. if self.promptType and self.promptType in ('raster', 'raster3d', 'vector'):
  677. self.autoCompList = self.mapList[self.promptType]
  678. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  679. elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and event.ControlDown():
  680. # Command history using ctrl-up and ctrl-down
  681. if len(self.cmdbuffer) < 1:
  682. return
  683. txt = ''
  684. self.DocumentEnd()
  685. # move through command history list index values
  686. if event.GetKeyCode() == wx.WXK_UP:
  687. self.cmdindex = self.cmdindex - 1
  688. if event.GetKeyCode() == wx.WXK_DOWN:
  689. self.cmdindex = self.cmdindex + 1
  690. if self.cmdindex < 0:
  691. self.cmdindex = 0
  692. if self.cmdindex > len(self.cmdbuffer) - 1:
  693. self.cmdindex = len(self.cmdbuffer) - 1
  694. try:
  695. txt = self.cmdbuffer[self.cmdindex]
  696. except:
  697. pass
  698. # clear current line and insert command history
  699. self.DelLineLeft()
  700. self.DelLineRight()
  701. pos = self.GetCurrentPos()
  702. self.InsertText(pos,txt)
  703. self.LineEnd()
  704. elif event.GetKeyCode() == wx.WXK_RETURN and self.AutoCompActive() == False:
  705. # Run command on line when <return> is pressed
  706. # find the command to run
  707. line = str(self.GetCurLine()[0]).strip()
  708. if len(line) == 0:
  709. return
  710. # parse command into list
  711. # TODO: shell commands should probably be passed as string
  712. cmd = shlex.split(str(line))
  713. #send the command list to the processor
  714. self.parent.RunCmd(cmd)
  715. # add command to history
  716. self.cmdbuffer.append(line)
  717. # keep command history to a managable size
  718. if len(self.cmdbuffer) > 200:
  719. del self.cmdbuffer[0]
  720. self.cmdindex = len(self.cmdbuffer)
  721. elif event.GetKeyCode() == wx.WXK_SPACE:
  722. items = self.GetTextLeft().split()
  723. if len(items) == 1:
  724. cmd = items[0].strip()
  725. if not self.cmdDesc or cmd != self.cmdDesc.get_name():
  726. try:
  727. self.cmdDesc = menuform.GUI().ParseInterface(cmd = [cmd])
  728. except IOError:
  729. self.cmdDesc = None
  730. event.Skip()
  731. else:
  732. event.Skip()
  733. def GetTextLeft(self):
  734. """!Returns all text left of the caret"""
  735. pos = self.GetCurrentPos()
  736. self.HomeExtend()
  737. entry = self.GetSelectedText()
  738. self.SetCurrentPos(pos)
  739. return entry
  740. def GetCommandUsage(self, command):
  741. """!Returns command syntax by running command help"""
  742. usage = ''
  743. description = ''
  744. ret, out = gcmd.RunCommand(command, 'help', getErrorMsg = True)
  745. if ret == 0:
  746. cmdhelp = out.splitlines()
  747. addline = False
  748. helplist = []
  749. description = ''
  750. for line in cmdhelp:
  751. if "Usage:" in line:
  752. addline = True
  753. continue
  754. elif "Flags:" in line:
  755. addline = False
  756. break
  757. elif addline == True:
  758. line = line.strip()
  759. helplist.append(line)
  760. for line in cmdhelp:
  761. if "Description:" in line:
  762. addline = True
  763. continue
  764. elif "Keywords:" in line:
  765. addline = False
  766. break
  767. elif addline == True:
  768. description += (line + ' ')
  769. description = description.strip()
  770. for line in helplist:
  771. usage += line + '\n'
  772. return usage.strip(), description
  773. else:
  774. return ''
  775. def OnDestroy(self, event):
  776. """!The clipboard contents can be preserved after
  777. the app has exited"""
  778. wx.TheClipboard.Flush()
  779. event.Skip()
  780. def OnCmdErase(self, event):
  781. """!Erase command prompt"""
  782. self.Home()
  783. self.DelLineRight()