prompt.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. """!
  2. @package gui_core.prompt
  3. @brief wxGUI command prompt
  4. Classes:
  5. - prompt::PromptListCtrl
  6. - prompt::TextCtrlAutoComplete
  7. - prompt::GPrompt
  8. - prompt::GPromptPopUp
  9. - prompt::GPromptSTC
  10. (C) 2009-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public License
  12. (>=v2). Read the file COPYING that comes with GRASS for details.
  13. @author Martin Landa <landa.martin gmail.com>
  14. @author Michael Barton <michael.barton@asu.edu>
  15. @author Vaclav Petras <wenzeslaus gmail.com> (copy&paste customization)
  16. """
  17. import os
  18. import sys
  19. import difflib
  20. import codecs
  21. import wx
  22. import wx.stc
  23. import wx.lib.mixins.listctrl as listmix
  24. from grass.script import core as grass
  25. from grass.script import task as gtask
  26. from core import globalvar
  27. from core import utils
  28. from lmgr.menudata import ManagerData
  29. from core.gcmd import EncodeString, DecodeString, GetRealCmd
  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 'style' in kwargs:
  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
  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 = gtask.parse_interface(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 = utils.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 = utils.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, modulesData):
  404. self.parent = parent # GConsole
  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. # probably only subclasses need this
  411. self.modulesData = modulesData
  412. self.mapList = self._getListOfMaps()
  413. self.mapsetList = utils.ListOfMapsets()
  414. # auto complete items
  415. self.autoCompList = list()
  416. self.autoCompFilter = None
  417. # command description (gtask.grassTask)
  418. self.cmdDesc = None
  419. self.cmdbuffer = self._readHistory()
  420. self.cmdindex = len(self.cmdbuffer)
  421. # list of traced commands
  422. self.commands = list()
  423. def _readHistory(self):
  424. """!Get list of commands from history file"""
  425. hist = list()
  426. env = grass.gisenv()
  427. try:
  428. fileHistory = codecs.open(os.path.join(env['GISDBASE'],
  429. env['LOCATION_NAME'],
  430. env['MAPSET'],
  431. '.bash_history'),
  432. encoding = 'utf-8', mode = 'r', errors='replace')
  433. except IOError:
  434. return hist
  435. try:
  436. for line in fileHistory.readlines():
  437. hist.append(line.replace('\n', ''))
  438. finally:
  439. fileHistory.close()
  440. return hist
  441. def _getListOfMaps(self):
  442. """!Get list of maps"""
  443. result = dict()
  444. result['raster'] = grass.list_strings('rast')
  445. result['vector'] = grass.list_strings('vect')
  446. return result
  447. def _runCmd(self, cmdString):
  448. """!Run command
  449. @param cmdString command to run (given as a string)
  450. """
  451. if self.parent.GetName() == "ModelerDialog":
  452. self.parent.OnOk(None)
  453. return
  454. if not cmdString or self.standAlone:
  455. return
  456. if cmdString[:2] == 'd.' and not self.parent.parent.GetMapDisplay():
  457. self.parent.parent.NewDisplay(show = True)
  458. self.commands.append(cmdString) # trace commands
  459. # parse command into list
  460. try:
  461. cmd = utils.split(str(cmdString))
  462. except UnicodeError:
  463. cmd = utils.split(EncodeString((cmdString)))
  464. cmd = map(DecodeString, cmd)
  465. # send the command list to the processor
  466. if cmd[0] in ('r.mapcalc', 'r3.mapcalc') and len(cmd) == 1:
  467. self.parent.parent.OnMapCalculator(event = None, cmd = cmd)
  468. else:
  469. self.parent.RunCmd(cmd)
  470. # add command to history & clean prompt
  471. self.UpdateCmdHistory(cmd)
  472. self.OnCmdErase(None)
  473. self.parent.parent.statusbar.SetStatusText('')
  474. def OnUpdateStatusBar(self, event):
  475. """!Update Layer Manager status bar"""
  476. if self.standAlone:
  477. return
  478. if event is None:
  479. self.parent.parent.statusbar.SetStatusText("")
  480. else:
  481. self.parent.parent.statusbar.SetStatusText(_("Type GRASS command and run by pressing ENTER"))
  482. event.Skip()
  483. def GetPanel(self):
  484. """!Get main widget panel"""
  485. return self.panel
  486. def GetInput(self):
  487. """!Get main prompt widget"""
  488. return self.input
  489. def SetFilter(self, data, module = True):
  490. """!Set filter
  491. @param data data dict
  492. @param module True to filter modules, otherwise data
  493. """
  494. if module:
  495. # TODO: remove this and module param
  496. raise NotImplementedError("Replace by call to common ModulesData object (SetFilter with module=True)")
  497. else:
  498. if data:
  499. self.dataList = data
  500. else:
  501. self.dataList = self._getListOfMaps()
  502. def GetCommands(self):
  503. """!Get list of launched commands"""
  504. return self.commands
  505. def ClearCommands(self):
  506. """!Clear list of commands"""
  507. del self.commands[:]
  508. class GPromptPopUp(GPrompt, TextCtrlAutoComplete):
  509. """!Interactive wxGUI prompt - popup version"""
  510. def __init__(self, parent):
  511. GPrompt.__init__(self, parent)
  512. ### todo: fix TextCtrlAutoComplete to work also on Macs
  513. ### reason: missing wx.PopupWindow()
  514. try:
  515. TextCtrlAutoComplete.__init__(self, parent = self.panel, id = wx.ID_ANY,
  516. value = "",
  517. style = wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  518. statusbar = self.parent.parent.statusbar)
  519. self.SetItems(self._readHistory())
  520. except NotImplementedError:
  521. # wx.PopupWindow may be not available in wxMac
  522. # see http://trac.wxwidgets.org/ticket/9377
  523. wx.TextCtrl.__init__(parent = self.panel, id = wx.ID_ANY,
  524. value = "",
  525. style=wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  526. size = (-1, 25))
  527. self.searchBy.Enable(False)
  528. self.search.Enable(False)
  529. self.SetFont(wx.Font(10, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.NORMAL, 0, ''))
  530. wx.CallAfter(self.SetInsertionPoint, 0)
  531. # bidnings
  532. self.Bind(wx.EVT_TEXT_ENTER, self.OnRunCmd)
  533. self.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  534. def OnCmdErase(self, event):
  535. """!Erase command prompt"""
  536. self.input.SetValue('')
  537. def OnRunCmd(self, event):
  538. """!Run command"""
  539. self._runCmd(event.GetString())
  540. class GPromptSTC(GPrompt, wx.stc.StyledTextCtrl):
  541. """!Styled wxGUI prompt with autocomplete and calltips"""
  542. def __init__(self, parent, modulesData, id = wx.ID_ANY, margin = False):
  543. GPrompt.__init__(self, parent, modulesData)
  544. wx.stc.StyledTextCtrl.__init__(self, self.panel, id)
  545. #
  546. # styles
  547. #
  548. self.SetWrapMode(True)
  549. self.SetUndoCollection(True)
  550. #
  551. # create command and map lists for autocompletion
  552. #
  553. self.AutoCompSetIgnoreCase(False)
  554. #
  555. # line margins
  556. #
  557. # TODO print number only from cmdlog
  558. self.SetMarginWidth(1, 0)
  559. self.SetMarginWidth(2, 0)
  560. if margin:
  561. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  562. self.SetMarginWidth(0, 30)
  563. else:
  564. self.SetMarginWidth(0, 0)
  565. #
  566. # miscellaneous
  567. #
  568. self.SetViewWhiteSpace(False)
  569. self.SetUseTabs(False)
  570. self.UsePopUp(True)
  571. self.SetSelBackground(True, "#FFFF00")
  572. self.SetUseHorizontalScrollBar(True)
  573. #
  574. # bindings
  575. #
  576. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  577. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  578. self.Bind(wx.stc.EVT_STC_AUTOCOMP_SELECTION, self.OnItemSelected)
  579. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemChanged)
  580. def OnTextSelectionChanged(self, event):
  581. """!Copy selected text to clipboard and skip event.
  582. The same function is in GStc class (goutput.py).
  583. """
  584. wx.CallAfter(self.Copy)
  585. event.Skip()
  586. def OnItemChanged(self, event):
  587. """!Change text in statusbar
  588. if the item selection in the auto-completion list is changed"""
  589. # list of commands
  590. if self.toComplete['entity'] == 'command':
  591. item = self.toComplete['cmd'].rpartition('.')[0] + '.' + self.autoCompList[event.GetIndex()]
  592. try:
  593. desc = self.modulesData.GetCommandDesc(item)
  594. except KeyError:
  595. desc = ''
  596. self.ShowStatusText(desc)
  597. # list of flags
  598. elif self.toComplete['entity'] == 'flags':
  599. desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()])['description']
  600. self.ShowStatusText(desc)
  601. # list of parameters
  602. elif self.toComplete['entity'] == 'params':
  603. item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
  604. desc = item['name'] + '=' + item['type']
  605. if not item['required']:
  606. desc = '[' + desc + ']'
  607. desc += ': ' + item['description']
  608. self.ShowStatusText(desc)
  609. # list of flags and commands
  610. elif self.toComplete['entity'] == 'params+flags':
  611. if self.autoCompList[event.GetIndex()][0] == '-':
  612. desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()].strip('-'))['description']
  613. else:
  614. item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
  615. desc = item['name'] + '=' + item['type']
  616. if not item['required']:
  617. desc = '[' + desc + ']'
  618. desc += ': ' + item['description']
  619. self.ShowStatusText(desc)
  620. else:
  621. self.ShowStatusText('')
  622. def OnItemSelected(self, event):
  623. """!Item selected from the list"""
  624. lastWord = self.GetWordLeft()
  625. # to insert selection correctly if selected word partly matches written text
  626. match = difflib.SequenceMatcher(None, event.GetText(), lastWord)
  627. matchTuple = match.find_longest_match(0, len(event.GetText()), 0, len(lastWord))
  628. compl = event.GetText()[matchTuple[2]:]
  629. text = self.GetTextLeft() + compl
  630. # add space or '=' at the end
  631. end = '='
  632. for char in ('.','-','='):
  633. if text.split(' ')[-1].find(char) >= 0:
  634. end = ' '
  635. compl += end
  636. text += end
  637. self.AddText(compl)
  638. pos = len(text)
  639. self.SetCurrentPos(pos)
  640. cmd = text.strip().split(' ')[0]
  641. if not self.cmdDesc or cmd != self.cmdDesc.get_name():
  642. if cmd in ('r.mapcalc', 'r3.mapcalc') and \
  643. self.parent.parent.GetName() == 'LayerManager':
  644. self.parent.parent.OnMapCalculator(event = None, cmd = [cmd])
  645. # add command to history & clean prompt
  646. self.UpdateCmdHistory([cmd])
  647. self.OnCmdErase(None)
  648. else:
  649. try:
  650. self.cmdDesc = gtask.parse_interface(GetRealCmd(cmd))
  651. except IOError:
  652. self.cmdDesc = None
  653. def UpdateCmdHistory(self, cmd):
  654. """!Update command history
  655. @param cmd command given as a list
  656. """
  657. # add command to history
  658. self.cmdbuffer.append(' '.join(cmd))
  659. # keep command history to a managable size
  660. if len(self.cmdbuffer) > 200:
  661. del self.cmdbuffer[0]
  662. self.cmdindex = len(self.cmdbuffer)
  663. def EntityToComplete(self):
  664. """!Determines which part of command (flags, parameters) should
  665. be completed at current cursor position"""
  666. entry = self.GetTextLeft()
  667. toComplete = dict()
  668. try:
  669. cmd = entry.split()[0].strip()
  670. except IndexError:
  671. return None
  672. try:
  673. splitted = utils.split(str(entry))
  674. except ValueError: # No closing quotation error
  675. return None
  676. if len(splitted) > 1:
  677. if cmd in globalvar.grassCmd:
  678. toComplete['cmd'] = cmd
  679. if entry[-1] == ' ':
  680. words = entry.split(' ')
  681. if any(word.startswith('-') for word in words):
  682. toComplete['entity'] = 'params'
  683. else:
  684. toComplete['entity'] = 'params+flags'
  685. else:
  686. # get word left from current position
  687. word = self.GetWordLeft(withDelimiter = True)
  688. if word[0] == '=' and word[-1] == '@':
  689. toComplete['entity'] = 'mapsets'
  690. elif word[0] == '=':
  691. # get name of parameter
  692. paramName = self.GetWordLeft(withDelimiter = False, ignoredDelimiter = '=').strip('=')
  693. if paramName:
  694. try:
  695. param = self.cmdDesc.get_param(paramName)
  696. except (ValueError, AttributeError):
  697. return None
  698. else:
  699. return None
  700. if param['values']:
  701. toComplete['entity'] = 'param values'
  702. elif param['prompt'] == 'raster' and param['element'] == 'cell':
  703. toComplete['entity'] = 'raster map'
  704. elif param['prompt'] == 'vector' and param['element'] == 'vector':
  705. toComplete['entity'] = 'vector map'
  706. elif word[0] == '-':
  707. toComplete['entity'] = 'flags'
  708. elif word[0] == ' ':
  709. toComplete['entity'] = 'params'
  710. else:
  711. return None
  712. else:
  713. toComplete['entity'] = 'command'
  714. toComplete['cmd'] = cmd
  715. return toComplete
  716. def GetWordLeft(self, withDelimiter = False, ignoredDelimiter = None):
  717. """!Get word left from current cursor position. The beginning
  718. of the word is given by space or chars: .,-=
  719. @param withDelimiter returns the word with the initial delimeter
  720. @param ignoredDelimiter finds the word ignoring certain delimeter
  721. """
  722. textLeft = self.GetTextLeft()
  723. parts = list()
  724. if ignoredDelimiter is None:
  725. ignoredDelimiter = ''
  726. for char in set(' .,-=') - set(ignoredDelimiter):
  727. if not withDelimiter:
  728. delimiter = ''
  729. else:
  730. delimiter = char
  731. parts.append(delimiter + textLeft.rpartition(char)[2])
  732. return min(parts, key=lambda x: len(x))
  733. def ShowList(self):
  734. """!Show sorted auto-completion list if it is not empty"""
  735. if len(self.autoCompList) > 0:
  736. self.autoCompList.sort()
  737. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  738. def OnKeyPressed(self, event):
  739. """!Key press capture for autocompletion, calltips, and command history
  740. @todo event.ControlDown() for manual autocomplete
  741. """
  742. # keycodes used: "." = 46, "=" = 61, "-" = 45
  743. pos = self.GetCurrentPos()
  744. # complete command after pressing '.'
  745. if event.GetKeyCode() == 46 and not event.ShiftDown():
  746. self.autoCompList = list()
  747. entry = self.GetTextLeft()
  748. self.InsertText(pos, '.')
  749. self.CharRight()
  750. self.toComplete = self.EntityToComplete()
  751. try:
  752. if self.toComplete['entity'] == 'command':
  753. self.autoCompList = self.modulesData.GetCommandItems(entry.strip())
  754. except (KeyError, TypeError):
  755. return
  756. self.ShowList()
  757. # complete flags after pressing '-'
  758. elif event.GetKeyCode() == 45 and not event.ShiftDown():
  759. self.autoCompList = list()
  760. entry = self.GetTextLeft()
  761. self.InsertText(pos, '-')
  762. self.CharRight()
  763. self.toComplete = self.EntityToComplete()
  764. if self.toComplete['entity'] == 'flags' and self.cmdDesc:
  765. if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite
  766. for flag in self.cmdDesc.get_options()['flags']:
  767. if len(flag['name']) == 1:
  768. self.autoCompList.append(flag['name'])
  769. else:
  770. for flag in self.cmdDesc.get_options()['flags']:
  771. if len(flag['name']) > 1:
  772. self.autoCompList.append(flag['name'])
  773. self.ShowList()
  774. # complete map or values after parameter
  775. elif event.GetKeyCode() == 61 and not event.ShiftDown():
  776. self.autoCompList = list()
  777. self.InsertText(pos, '=')
  778. self.CharRight()
  779. self.toComplete = self.EntityToComplete()
  780. if self.toComplete and 'entity' in self.toComplete:
  781. if self.toComplete['entity'] == 'raster map':
  782. self.autoCompList = self.mapList['raster']
  783. elif self.toComplete['entity'] == 'vector map':
  784. self.autoCompList = self.mapList['vector']
  785. elif self.toComplete['entity'] == 'param values':
  786. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  787. self.autoCompList = self.cmdDesc.get_param(param)['values']
  788. self.ShowList()
  789. # complete mapset ('@')
  790. elif event.GetKeyCode() == 50 and event.ShiftDown():
  791. self.autoCompList = list()
  792. self.InsertText(pos, '@')
  793. self.CharRight()
  794. self.toComplete = self.EntityToComplete()
  795. if self.toComplete and self.toComplete['entity'] == 'mapsets':
  796. self.autoCompList = self.mapsetList
  797. self.ShowList()
  798. # complete after pressing CTRL + Space
  799. elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
  800. self.autoCompList = list()
  801. self.toComplete = self.EntityToComplete()
  802. if self.toComplete is None:
  803. return
  804. #complete command
  805. if self.toComplete['entity'] == 'command':
  806. for command in globalvar.grassCmd:
  807. if command.find(self.toComplete['cmd']) == 0:
  808. dotNumber = list(self.toComplete['cmd']).count('.')
  809. self.autoCompList.append(command.split('.',dotNumber)[-1])
  810. # complete flags in such situations (| is cursor):
  811. # r.colors -| ...w, q, l
  812. # r.colors -w| ...w, q, l
  813. elif self.toComplete['entity'] == 'flags' and self.cmdDesc:
  814. for flag in self.cmdDesc.get_options()['flags']:
  815. if len(flag['name']) == 1:
  816. self.autoCompList.append(flag['name'])
  817. # complete parameters in such situations (| is cursor):
  818. # r.colors -w | ...color, map, rast, rules
  819. # r.colors col| ...color
  820. elif self.toComplete['entity'] == 'params' and self.cmdDesc:
  821. for param in self.cmdDesc.get_options()['params']:
  822. if param['name'].find(self.GetWordLeft(withDelimiter=False)) == 0:
  823. self.autoCompList.append(param['name'])
  824. # complete flags or parameters in such situations (| is cursor):
  825. # r.colors | ...-w, -q, -l, color, map, rast, rules
  826. # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules
  827. elif self.toComplete['entity'] == 'params+flags' and self.cmdDesc:
  828. self.autoCompList = list()
  829. for param in self.cmdDesc.get_options()['params']:
  830. self.autoCompList.append(param['name'])
  831. for flag in self.cmdDesc.get_options()['flags']:
  832. if len(flag['name']) == 1:
  833. self.autoCompList.append('-' + flag['name'])
  834. else:
  835. self.autoCompList.append('--' + flag['name'])
  836. self.ShowList()
  837. # complete map or values after parameter
  838. # r.buffer input=| ...list of raster maps
  839. # r.buffer units=| ... feet, kilometers, ...
  840. elif self.toComplete['entity'] == 'raster map':
  841. self.autoCompList = list()
  842. self.autoCompList = self.mapList['raster']
  843. elif self.toComplete['entity'] == 'vector map':
  844. self.autoCompList = list()
  845. self.autoCompList = self.mapList['vector']
  846. elif self.toComplete['entity'] == 'param values':
  847. self.autoCompList = list()
  848. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  849. self.autoCompList = self.cmdDesc.get_param(param)['values']
  850. self.ShowList()
  851. elif event.GetKeyCode() == wx.WXK_TAB:
  852. # show GRASS command calltips (to hide press 'ESC')
  853. entry = self.GetTextLeft()
  854. try:
  855. cmd = entry.split()[0].strip()
  856. except IndexError:
  857. cmd = ''
  858. if cmd not in globalvar.grassCmd:
  859. return
  860. info = gtask.command_info(GetRealCmd(cmd))
  861. self.CallTipSetBackground("#f4f4d1")
  862. self.CallTipSetForeground("BLACK")
  863. self.CallTipShow(pos, info['usage'] + '\n\n' + info['description'])
  864. elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and \
  865. not self.AutoCompActive():
  866. # Command history using up and down
  867. if len(self.cmdbuffer) < 1:
  868. return
  869. self.DocumentEnd()
  870. # move through command history list index values
  871. if event.GetKeyCode() == wx.WXK_UP:
  872. self.cmdindex = self.cmdindex - 1
  873. if event.GetKeyCode() == wx.WXK_DOWN:
  874. self.cmdindex = self.cmdindex + 1
  875. if self.cmdindex < 0:
  876. self.cmdindex = 0
  877. if self.cmdindex > len(self.cmdbuffer) - 1:
  878. self.cmdindex = len(self.cmdbuffer) - 1
  879. try:
  880. txt = self.cmdbuffer[self.cmdindex]
  881. except:
  882. txt = ''
  883. # clear current line and insert command history
  884. self.DelLineLeft()
  885. self.DelLineRight()
  886. pos = self.GetCurrentPos()
  887. self.InsertText(pos,txt)
  888. self.LineEnd()
  889. self.parent.parent.statusbar.SetStatusText('')
  890. elif event.GetKeyCode() == wx.WXK_RETURN and \
  891. self.AutoCompActive() == False:
  892. # run command on line when <return> is pressed
  893. self._runCmd(self.GetCurLine()[0].strip())
  894. elif event.GetKeyCode() == wx.WXK_SPACE:
  895. items = self.GetTextLeft().split()
  896. if len(items) == 1:
  897. cmd = items[0].strip()
  898. if cmd in globalvar.grassCmd and \
  899. cmd != 'r.mapcalc' and \
  900. (not self.cmdDesc or cmd != self.cmdDesc.get_name()):
  901. try:
  902. self.cmdDesc = gtask.parse_interface(GetRealCmd(cmd))
  903. except IOError:
  904. self.cmdDesc = None
  905. event.Skip()
  906. else:
  907. event.Skip()
  908. def ShowStatusText(self, text):
  909. """!Sets statusbar text, if it's too long, it is cut off"""
  910. maxLen = self.parent.parent.statusbar.GetFieldRect(0).GetWidth()/ 7 # any better way?
  911. if len(text) < maxLen:
  912. self.parent.parent.statusbar.SetStatusText(text)
  913. else:
  914. self.parent.parent.statusbar.SetStatusText(text[:maxLen]+'...')
  915. def GetTextLeft(self):
  916. """!Returns all text left of the caret"""
  917. pos = self.GetCurrentPos()
  918. self.HomeExtend()
  919. entry = self.GetSelectedText()
  920. self.SetCurrentPos(pos)
  921. return entry
  922. def OnDestroy(self, event):
  923. """!The clipboard contents can be preserved after
  924. the app has exited"""
  925. wx.TheClipboard.Flush()
  926. event.Skip()
  927. def OnCmdErase(self, event):
  928. """!Erase command prompt"""
  929. self.Home()
  930. self.DelLineRight()