prompt.py 34 KB

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