prompt.py 33 KB

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