prompt.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. """!
  2. @package gui_core.prompt
  3. @brief wxGUI command prompt
  4. Classes:
  5. - PromptListCtrl
  6. - TextCtrlAutoComplete
  7. - GPrompt
  8. - GPromptPopUp
  9. - GPromptSTC
  10. (C) 2009-2011 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. @author Vaclav Petras <wenzeslaus gmail.com> (copy&paste customization)
  17. """
  18. import os
  19. import sys
  20. import difflib
  21. import codecs
  22. import wx
  23. import wx.stc
  24. import wx.lib.mixins.listctrl as listmix
  25. from grass.script import core as grass
  26. from grass.script import task as gtask
  27. from core import globalvar
  28. from core import utils
  29. from lmgr.menudata import ManagerData
  30. from core.gcmd import EncodeString, DecodeString
  31. class PromptListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
  32. """!PopUp window used by GPromptPopUp"""
  33. def __init__(self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition,
  34. size = wx.DefaultSize, style = 0):
  35. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  36. listmix.ListCtrlAutoWidthMixin.__init__(self)
  37. class TextCtrlAutoComplete(wx.ComboBox, listmix.ColumnSorterMixin):
  38. """!Auto complete text area used by GPromptPopUp"""
  39. def __init__ (self, parent, statusbar,
  40. id = wx.ID_ANY, choices = [], **kwargs):
  41. """!Constructor works just like wx.TextCtrl except you can pass in a
  42. list of choices. You can also change the choice list at any time
  43. by calling setChoices.
  44. Inspired by http://wiki.wxpython.org/TextCtrlAutoComplete
  45. """
  46. self.statusbar = statusbar
  47. if 'style' in kwargs:
  48. kwargs['style'] = wx.TE_PROCESS_ENTER | kwargs['style']
  49. else:
  50. kwargs['style'] = wx.TE_PROCESS_ENTER
  51. wx.ComboBox.__init__(self, parent, id, **kwargs)
  52. # some variables
  53. self._choices = choices
  54. self._hideOnNoMatch = True
  55. self._module = None # currently selected module
  56. self._choiceType = None # type of choice (module, params, flags, raster, vector ...)
  57. self._screenheight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)
  58. self._historyItem = 0 # last item
  59. # sort variable needed by listmix
  60. self.itemDataMap = dict()
  61. # widgets
  62. try:
  63. self.dropdown = wx.PopupWindow(self)
  64. except NotImplementedError:
  65. self.Destroy()
  66. raise NotImplementedError
  67. # create the list and bind the events
  68. self.dropdownlistbox = PromptListCtrl(parent = self.dropdown,
  69. style = wx.LC_REPORT | wx.LC_SINGLE_SEL | \
  70. wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER,
  71. pos = wx.Point(0, 0))
  72. listmix.ColumnSorterMixin.__init__(self, 1)
  73. # set choices (list of GRASS modules)
  74. self._choicesCmd = globalvar.grassCmd['all']
  75. self._choicesMap = dict()
  76. for type in ('raster', 'vector'):
  77. self._choicesMap[type] = grass.list_strings(type = type[:4])
  78. # first search for GRASS module
  79. self.SetChoices(self._choicesCmd)
  80. self.SetMinSize(self.GetSize())
  81. # bindings...
  82. self.Bind(wx.EVT_KILL_FOCUS, self.OnControlChanged)
  83. self.Bind(wx.EVT_TEXT, self.OnEnteredText)
  84. self.Bind(wx.EVT_TEXT_ENTER, self.OnRunCmd)
  85. self.Bind(wx.EVT_KEY_DOWN , self.OnKeyDown)
  86. ### self.Bind(wx.EVT_LEFT_DOWN, self.OnClick)
  87. # if need drop down on left click
  88. self.dropdown.Bind(wx.EVT_LISTBOX , self.OnListItemSelected, self.dropdownlistbox)
  89. self.dropdownlistbox.Bind(wx.EVT_LEFT_DOWN, self.OnListClick)
  90. self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.OnListDClick)
  91. self.dropdownlistbox.Bind(wx.EVT_LIST_COL_CLICK, self.OnListColClick)
  92. self.Bind(wx.EVT_COMBOBOX, self.OnCommandSelect)
  93. def _updateDataList(self, choices):
  94. """!Update data list"""
  95. # delete, if need, all the previous data
  96. if self.dropdownlistbox.GetColumnCount() != 0:
  97. self.dropdownlistbox.DeleteAllColumns()
  98. self.dropdownlistbox.DeleteAllItems()
  99. # and update the dict
  100. if choices:
  101. for numVal, data in enumerate(choices):
  102. self.itemDataMap[numVal] = data
  103. else:
  104. numVal = 0
  105. self.SetColumnCount(numVal)
  106. def _setListSize(self):
  107. """!Set list size"""
  108. choices = self._choices
  109. longest = 0
  110. for choice in choices:
  111. longest = max(len(choice), longest)
  112. longest += 3
  113. itemcount = min(len( choices ), 7) + 2
  114. charheight = self.dropdownlistbox.GetCharHeight()
  115. charwidth = self.dropdownlistbox.GetCharWidth()
  116. self.popupsize = wx.Size(charwidth*longest, charheight*itemcount)
  117. self.dropdownlistbox.SetSize(self.popupsize)
  118. self.dropdown.SetClientSize(self.popupsize)
  119. def _showDropDown(self, show = True):
  120. """!Either display the drop down list (show = True) or hide it
  121. (show = False).
  122. """
  123. if show:
  124. size = self.dropdown.GetSize()
  125. width, height = self.GetSizeTuple()
  126. x, y = self.ClientToScreenXY(0, height)
  127. if size.GetWidth() != width:
  128. size.SetWidth(width)
  129. self.dropdown.SetSize(size)
  130. self.dropdownlistbox.SetSize(self.dropdown.GetClientSize())
  131. if (y + size.GetHeight()) < self._screenheight:
  132. self.dropdown.SetPosition(wx.Point(x, y))
  133. else:
  134. self.dropdown.SetPosition(wx.Point(x, y - height - size.GetHeight()))
  135. self.dropdown.Show(show)
  136. def _listItemVisible(self):
  137. """!Moves the selected item to the top of the list ensuring it is
  138. always visible.
  139. """
  140. toSel = self.dropdownlistbox.GetFirstSelected()
  141. if toSel == -1:
  142. return
  143. self.dropdownlistbox.EnsureVisible(toSel)
  144. def _setModule(self, name):
  145. """!Set module's choices (flags, parameters)"""
  146. # get module's description
  147. if name in self._choicesCmd and not self._module:
  148. try:
  149. self._module = gtask.parse_interface(name)
  150. except IOError:
  151. self._module = None
  152. # set choices (flags)
  153. self._choicesMap['flag'] = self._module.get_list_flags()
  154. for idx in range(len(self._choicesMap['flag'])):
  155. item = self._choicesMap['flag'][idx]
  156. desc = self._module.get_flag(item)['label']
  157. if not desc:
  158. desc = self._module.get_flag(item)['description']
  159. self._choicesMap['flag'][idx] = '%s (%s)' % (item, desc)
  160. # set choices (parameters)
  161. self._choicesMap['param'] = self._module.get_list_params()
  162. for idx in range(len(self._choicesMap['param'])):
  163. item = self._choicesMap['param'][idx]
  164. desc = self._module.get_param(item)['label']
  165. if not desc:
  166. desc = self._module.get_param(item)['description']
  167. self._choicesMap['param'][idx] = '%s (%s)' % (item, desc)
  168. def _setValueFromSelected(self):
  169. """!Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
  170. Will do nothing if no item is selected in the wx.ListCtrl.
  171. """
  172. sel = self.dropdownlistbox.GetFirstSelected()
  173. if sel < 0:
  174. return
  175. if self._colFetch != -1:
  176. col = self._colFetch
  177. else:
  178. col = self._colSearch
  179. itemtext = self.dropdownlistbox.GetItem(sel, col).GetText()
  180. cmd = utils.split(str(self.GetValue()))
  181. if len(cmd) > 0 and cmd[0] in self._choicesCmd:
  182. # -> append text (skip last item)
  183. if self._choiceType == 'param':
  184. itemtext = itemtext.split(' ')[0]
  185. self.SetValue(' '.join(cmd) + ' ' + itemtext + '=')
  186. optType = self._module.get_param(itemtext)['prompt']
  187. if optType in ('raster', 'vector'):
  188. # -> raster/vector map
  189. self.SetChoices(self._choicesMap[optType], optType)
  190. elif self._choiceType == 'flag':
  191. itemtext = itemtext.split(' ')[0]
  192. if len(itemtext) > 1:
  193. prefix = '--'
  194. else:
  195. prefix = '-'
  196. self.SetValue(' '.join(cmd[:-1]) + ' ' + prefix + itemtext)
  197. elif self._choiceType in ('raster', 'vector'):
  198. self.SetValue(' '.join(cmd[:-1]) + ' ' + cmd[-1].split('=', 1)[0] + '=' + itemtext)
  199. else:
  200. # -> reset text
  201. self.SetValue(itemtext + ' ')
  202. # define module
  203. self._setModule(itemtext)
  204. # use parameters as default choices
  205. self._choiceType = 'param'
  206. self.SetChoices(self._choicesMap['param'], type = 'param')
  207. self.SetInsertionPointEnd()
  208. self._showDropDown(False)
  209. def GetListCtrl(self):
  210. """!Method required by listmix.ColumnSorterMixin"""
  211. return self.dropdownlistbox
  212. def SetChoices(self, choices, type = 'module'):
  213. """!Sets the choices available in the popup wx.ListBox.
  214. The items will be sorted case insensitively.
  215. @param choices list of choices
  216. @param type type of choices (module, param, flag, raster, vector)
  217. """
  218. self._choices = choices
  219. self._choiceType = type
  220. self.dropdownlistbox.SetWindowStyleFlag(wx.LC_REPORT | wx.LC_SINGLE_SEL |
  221. wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER)
  222. if not isinstance(choices, list):
  223. self._choices = [ x for x in choices ]
  224. if self._choiceType not in ('raster', 'vector'):
  225. # do not sort raster/vector maps
  226. utils.ListSortLower(self._choices)
  227. self._updateDataList(self._choices)
  228. self.dropdownlistbox.InsertColumn(0, "")
  229. for num, colVal in enumerate(self._choices):
  230. index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1)
  231. self.dropdownlistbox.SetStringItem(index, 0, colVal)
  232. self.dropdownlistbox.SetItemData(index, num)
  233. self._setListSize()
  234. # there is only one choice for both search and fetch if setting a single column:
  235. self._colSearch = 0
  236. self._colFetch = -1
  237. def OnClick(self, event):
  238. """Left mouse button pressed"""
  239. sel = self.dropdownlistbox.GetFirstSelected()
  240. if not self.dropdown.IsShown():
  241. if sel > -1:
  242. self.dropdownlistbox.Select(sel)
  243. else:
  244. self.dropdownlistbox.Select(0)
  245. self._listItemVisible()
  246. self._showDropDown()
  247. else:
  248. self.dropdown.Hide()
  249. def OnCommandSelect(self, event):
  250. """!Command selected from history"""
  251. self._historyItem = event.GetSelection() - len(self.GetItems())
  252. self.SetFocus()
  253. def OnListClick(self, evt):
  254. """!Left mouse button pressed"""
  255. toSel, flag = self.dropdownlistbox.HitTest( evt.GetPosition() )
  256. #no values on poition, return
  257. if toSel == -1: return
  258. self.dropdownlistbox.Select(toSel)
  259. def OnListDClick(self, evt):
  260. """!Mouse button double click"""
  261. self._setValueFromSelected()
  262. def OnListColClick(self, evt):
  263. """!Left mouse button pressed on column"""
  264. col = evt.GetColumn()
  265. # reverse the sort
  266. if col == self._colSearch:
  267. self._ascending = not self._ascending
  268. self.SortListItems( evt.GetColumn(), ascending=self._ascending )
  269. self._colSearch = evt.GetColumn()
  270. evt.Skip()
  271. def OnListItemSelected(self, event):
  272. """!Item selected"""
  273. self._setValueFromSelected()
  274. event.Skip()
  275. def OnEnteredText(self, event):
  276. """!Text entered"""
  277. text = event.GetString()
  278. if not text:
  279. # control is empty; hide dropdown if shown:
  280. if self.dropdown.IsShown():
  281. self._showDropDown(False)
  282. event.Skip()
  283. return
  284. try:
  285. cmd = utils.split(str(text))
  286. except ValueError, e:
  287. self.statusbar.SetStatusText(str(e))
  288. cmd = text.split(' ')
  289. pattern = str(text)
  290. if len(cmd) > 0 and cmd[0] in self._choicesCmd and not self._module:
  291. self._setModule(cmd[0])
  292. elif len(cmd) > 1 and cmd[0] in self._choicesCmd:
  293. if self._module:
  294. if len(cmd[-1].split('=', 1)) == 1:
  295. # new option
  296. if cmd[-1][0] == '-':
  297. # -> flags
  298. self.SetChoices(self._choicesMap['flag'], type = 'flag')
  299. pattern = cmd[-1].lstrip('-')
  300. else:
  301. # -> options
  302. self.SetChoices(self._choicesMap['param'], type = 'param')
  303. pattern = cmd[-1]
  304. else:
  305. # value
  306. pattern = cmd[-1].split('=', 1)[1]
  307. else:
  308. # search for GRASS modules
  309. if self._module:
  310. # -> switch back to GRASS modules list
  311. self.SetChoices(self._choicesCmd)
  312. self._module = None
  313. self._choiceType = None
  314. self._choiceType
  315. self._choicesMap
  316. found = False
  317. choices = self._choices
  318. for numCh, choice in enumerate(choices):
  319. if choice.lower().startswith(pattern):
  320. found = True
  321. if found:
  322. self._showDropDown(True)
  323. item = self.dropdownlistbox.GetItem(numCh)
  324. toSel = item.GetId()
  325. self.dropdownlistbox.Select(toSel)
  326. break
  327. if not found:
  328. self.dropdownlistbox.Select(self.dropdownlistbox.GetFirstSelected(), False)
  329. if self._hideOnNoMatch:
  330. self._showDropDown(False)
  331. if self._module and '=' not in cmd[-1]:
  332. message = ''
  333. if cmd[-1][0] == '-': # flag
  334. message = _("Warning: flag <%(flag)s> not found in '%(module)s'") % \
  335. { 'flag' : cmd[-1][1:], 'module' : self._module.name }
  336. else: # option
  337. message = _("Warning: option <%(param)s> not found in '%(module)s'") % \
  338. { 'param' : cmd[-1], 'module' : self._module.name }
  339. self.statusbar.SetStatusText(message)
  340. if self._module and len(cmd[-1]) == 2 and cmd[-1][-2] == '=':
  341. optType = self._module.get_param(cmd[-1][:-2])['prompt']
  342. if optType in ('raster', 'vector'):
  343. # -> raster/vector map
  344. self.SetChoices(self._choicesMap[optType], optType)
  345. self._listItemVisible()
  346. event.Skip()
  347. def OnKeyDown (self, event):
  348. """!Do some work when the user press on the keys: up and down:
  349. move the cursor left and right: move the search
  350. """
  351. skip = True
  352. sel = self.dropdownlistbox.GetFirstSelected()
  353. visible = self.dropdown.IsShown()
  354. KC = event.GetKeyCode()
  355. if KC == wx.WXK_RIGHT:
  356. # right -> show choices
  357. if sel < (self.dropdownlistbox.GetItemCount() - 1):
  358. self.dropdownlistbox.Select(sel + 1)
  359. self._listItemVisible()
  360. self._showDropDown()
  361. skip = False
  362. elif KC == wx.WXK_UP:
  363. if visible:
  364. if sel > 0:
  365. self.dropdownlistbox.Select(sel - 1)
  366. self._listItemVisible()
  367. self._showDropDown()
  368. skip = False
  369. else:
  370. self._historyItem -= 1
  371. try:
  372. self.SetValue(self.GetItems()[self._historyItem])
  373. except IndexError:
  374. self._historyItem += 1
  375. elif KC == wx.WXK_DOWN:
  376. if visible:
  377. if sel < (self.dropdownlistbox.GetItemCount() - 1):
  378. self.dropdownlistbox.Select(sel + 1)
  379. self._listItemVisible()
  380. self._showDropDown()
  381. skip = False
  382. else:
  383. if self._historyItem < -1:
  384. self._historyItem += 1
  385. self.SetValue(self.GetItems()[self._historyItem])
  386. if visible:
  387. if event.GetKeyCode() == wx.WXK_RETURN:
  388. self._setValueFromSelected()
  389. skip = False
  390. if event.GetKeyCode() == wx.WXK_ESCAPE:
  391. self._showDropDown(False)
  392. skip = False
  393. if skip:
  394. event.Skip()
  395. def OnControlChanged(self, event):
  396. """!Control changed"""
  397. if self.IsShown():
  398. self._showDropDown(False)
  399. event.Skip()
  400. class GPrompt(object):
  401. """!Abstract class for interactive wxGUI prompt
  402. See subclass GPromptPopUp and GPromptSTC.
  403. """
  404. def __init__(self, parent):
  405. self.parent = parent # GMConsole
  406. self.panel = self.parent.GetPanel()
  407. if self.parent.parent.GetName() not in ("LayerManager", "Modeler"):
  408. self.standAlone = True
  409. else:
  410. self.standAlone = False
  411. # dictionary of modules (description, keywords, ...)
  412. if not self.standAlone:
  413. if self.parent.parent.GetName() == 'Modeler':
  414. self.moduleDesc = ManagerData().GetModules()
  415. else:
  416. self.moduleDesc = parent.parent.menubar.GetData().GetModules()
  417. self.moduleList = self._getListOfModules()
  418. self.mapList = self._getListOfMaps()
  419. self.mapsetList = utils.ListOfMapsets()
  420. else:
  421. self.moduleDesc = self.moduleList = self.mapList = None
  422. # auto complete items
  423. self.autoCompList = list()
  424. self.autoCompFilter = None
  425. # command description (gtask.grassTask)
  426. self.cmdDesc = None
  427. self.cmdbuffer = self._readHistory()
  428. self.cmdindex = len(self.cmdbuffer)
  429. def _readHistory(self):
  430. """!Get list of commands from history file"""
  431. hist = list()
  432. env = grass.gisenv()
  433. try:
  434. fileHistory = codecs.open(os.path.join(env['GISDBASE'],
  435. env['LOCATION_NAME'],
  436. env['MAPSET'],
  437. '.bash_history'),
  438. encoding = 'utf-8', mode = 'r', errors='replace')
  439. except IOError:
  440. return hist
  441. try:
  442. for line in fileHistory.readlines():
  443. hist.append(line.replace('\n', ''))
  444. finally:
  445. fileHistory.close()
  446. return hist
  447. def GetCommandDesc(self, cmd):
  448. """!Get description for given command"""
  449. if cmd in self.moduleDesc:
  450. return self.moduleDesc[cmd]['desc']
  451. return ''
  452. def GetCommandItems(self):
  453. """!Get list of available commands"""
  454. items = list()
  455. if self.autoCompFilter is not None:
  456. mList = self.autoCompFilter
  457. else:
  458. mList = self.moduleList
  459. if not mList:
  460. return items
  461. prefixes = mList.keys()
  462. prefixes.sort()
  463. for prefix in prefixes:
  464. for command in mList[prefix]:
  465. name = prefix + '.' + command
  466. if name not in items:
  467. items.append(name)
  468. items.sort()
  469. return items
  470. def _getListOfModules(self):
  471. """!Get list of modules"""
  472. result = dict()
  473. for module in globalvar.grassCmd['all']:
  474. try:
  475. group, name = module.split('.',1)
  476. except ValueError:
  477. continue # TODO
  478. if group not in result:
  479. result[group] = list()
  480. result[group].append(name)
  481. # for better auto-completion:
  482. # not only result['r']={...,'colors.out',...}, but also result['r.colors']={'out',...}
  483. for i in range(len(name.split('.'))-1):
  484. group = '.'.join([group,name.split('.',1)[0]])
  485. name = name.split('.',1)[1]
  486. if group not in result:
  487. result[group] = list()
  488. result[group].append(name)
  489. # sort list of names
  490. for group in result.keys():
  491. result[group].sort()
  492. return result
  493. def _getListOfMaps(self):
  494. """!Get list of maps"""
  495. result = dict()
  496. result['raster'] = grass.list_strings('rast')
  497. result['vector'] = grass.list_strings('vect')
  498. return result
  499. def OnRunCmd(self, event):
  500. """!Run command"""
  501. cmdString = event.GetString()
  502. if self.standAlone:
  503. return
  504. if cmdString[:2] == 'd.' and not self.parent.curr_page:
  505. self.parent.NewDisplay(show=True)
  506. cmd = utils.split(cmdString)
  507. if len(cmd) > 1:
  508. self.parent.RunCmd(cmd, switchPage = True)
  509. else:
  510. self.parent.RunCmd(cmd, switchPage = False)
  511. self.OnUpdateStatusBar(None)
  512. def OnUpdateStatusBar(self, event):
  513. """!Update Layer Manager status bar"""
  514. if self.standAlone:
  515. return
  516. if event is None:
  517. self.parent.parent.statusbar.SetStatusText("")
  518. else:
  519. self.parent.parent.statusbar.SetStatusText(_("Type GRASS command and run by pressing ENTER"))
  520. event.Skip()
  521. def GetPanel(self):
  522. """!Get main widget panel"""
  523. return self.panel
  524. def GetInput(self):
  525. """!Get main prompt widget"""
  526. return self.input
  527. def SetFilter(self, data, module = True):
  528. """!Set filter
  529. @param data data dict
  530. @param module True to filter modules, otherwise data
  531. """
  532. if module:
  533. if data:
  534. self.moduleList = data
  535. else:
  536. self.moduleList = self._getListOfModules()
  537. else:
  538. if data:
  539. self.dataList = data
  540. else:
  541. self.dataList = self._getListOfMaps()
  542. class GPromptPopUp(GPrompt, TextCtrlAutoComplete):
  543. """!Interactive wxGUI prompt - popup version"""
  544. def __init__(self, parent):
  545. GPrompt.__init__(self, parent)
  546. ### todo: fix TextCtrlAutoComplete to work also on Macs
  547. ### reason: missing wx.PopupWindow()
  548. try:
  549. TextCtrlAutoComplete.__init__(self, parent = self.panel, id = wx.ID_ANY,
  550. value = "",
  551. style = wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  552. statusbar = self.parent.parent.statusbar)
  553. self.SetItems(self._readHistory())
  554. except NotImplementedError:
  555. # wx.PopupWindow may be not available in wxMac
  556. # see http://trac.wxwidgets.org/ticket/9377
  557. wx.TextCtrl.__init__(parent = self.panel, id = wx.ID_ANY,
  558. value = "",
  559. style=wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  560. size = (-1, 25))
  561. self.searchBy.Enable(False)
  562. self.search.Enable(False)
  563. self.SetFont(wx.Font(10, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.NORMAL, 0, ''))
  564. wx.CallAfter(self.SetInsertionPoint, 0)
  565. # bidnings
  566. self.Bind(wx.EVT_TEXT_ENTER, self.OnRunCmd)
  567. self.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  568. def OnCmdErase(self, event):
  569. """!Erase command prompt"""
  570. self.input.SetValue('')
  571. class GPromptSTC(GPrompt, wx.stc.StyledTextCtrl):
  572. """!Styled wxGUI prompt with autocomplete and calltips"""
  573. def __init__(self, parent, id = wx.ID_ANY, margin = False):
  574. GPrompt.__init__(self, parent)
  575. wx.stc.StyledTextCtrl.__init__(self, self.panel, id)
  576. #
  577. # styles
  578. #
  579. self.SetWrapMode(True)
  580. self.SetUndoCollection(True)
  581. #
  582. # create command and map lists for autocompletion
  583. #
  584. self.AutoCompSetIgnoreCase(False)
  585. #
  586. # line margins
  587. #
  588. # TODO print number only from cmdlog
  589. self.SetMarginWidth(1, 0)
  590. self.SetMarginWidth(2, 0)
  591. if margin:
  592. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  593. self.SetMarginWidth(0, 30)
  594. else:
  595. self.SetMarginWidth(0, 0)
  596. #
  597. # miscellaneous
  598. #
  599. self.SetViewWhiteSpace(False)
  600. self.SetUseTabs(False)
  601. self.UsePopUp(True)
  602. self.SetSelBackground(True, "#FFFF00")
  603. self.SetUseHorizontalScrollBar(True)
  604. #
  605. # bindings
  606. #
  607. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  608. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  609. self.Bind(wx.stc.EVT_STC_AUTOCOMP_SELECTION, self.OnItemSelected)
  610. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemChanged)
  611. def OnTextSelectionChanged(self, event):
  612. """!Copy selected text to clipboard and skip event.
  613. The same function is in GMStc class (goutput.py).
  614. """
  615. self.Copy()
  616. event.Skip()
  617. def OnItemChanged(self, event):
  618. """!Change text in statusbar
  619. if the item selection in the auto-completion list is changed"""
  620. # list of commands
  621. if self.toComplete['entity'] == 'command':
  622. item = self.toComplete['cmd'].rpartition('.')[0] + '.' + self.autoCompList[event.GetIndex()]
  623. try:
  624. desc = self.moduleDesc[item]['desc']
  625. except KeyError:
  626. desc = ''
  627. self.ShowStatusText(desc)
  628. # list of flags
  629. elif self.toComplete['entity'] == 'flags':
  630. desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()])['description']
  631. self.ShowStatusText(desc)
  632. # list of parameters
  633. elif self.toComplete['entity'] == 'params':
  634. item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
  635. desc = item['name'] + '=' + item['type']
  636. if not item['required']:
  637. desc = '[' + desc + ']'
  638. desc += ': ' + item['description']
  639. self.ShowStatusText(desc)
  640. # list of flags and commands
  641. elif self.toComplete['entity'] == 'params+flags':
  642. if self.autoCompList[event.GetIndex()][0] == '-':
  643. desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()].strip('-'))['description']
  644. else:
  645. item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
  646. desc = item['name'] + '=' + item['type']
  647. if not item['required']:
  648. desc = '[' + desc + ']'
  649. desc += ': ' + item['description']
  650. self.ShowStatusText(desc)
  651. else:
  652. self.ShowStatusText('')
  653. def OnItemSelected(self, event):
  654. """!Item selected from the list"""
  655. lastWord = self.GetWordLeft()
  656. # to insert selection correctly if selected word partly matches written text
  657. match = difflib.SequenceMatcher(None, event.GetText(), lastWord)
  658. matchTuple = match.find_longest_match(0, len(event.GetText()), 0, len(lastWord))
  659. compl = event.GetText()[matchTuple[2]:]
  660. text = self.GetTextLeft() + compl
  661. # add space or '=' at the end
  662. end = '='
  663. for char in ('.','-','='):
  664. if text.split(' ')[-1].find(char) >= 0:
  665. end = ' '
  666. compl += end
  667. text += end
  668. self.AddText(compl)
  669. pos = len(text)
  670. self.SetCurrentPos(pos)
  671. cmd = text.strip().split(' ')[0]
  672. if not self.cmdDesc or cmd != self.cmdDesc.get_name():
  673. if cmd in ('r.mapcalc', 'r3.mapcalc') and \
  674. self.parent.parent.GetName() == 'LayerManager':
  675. self.parent.parent.OnMapCalculator(event = None, cmd = [cmd])
  676. # add command to history & clean prompt
  677. self.UpdateCmdHistory([cmd])
  678. self.OnCmdErase(None)
  679. else:
  680. try:
  681. self.cmdDesc = gtask.parse_interface(cmd)
  682. except IOError:
  683. self.cmdDesc = None
  684. def UpdateCmdHistory(self, cmd):
  685. """!Update command history
  686. @param cmd command given as a list
  687. """
  688. # add command to history
  689. self.cmdbuffer.append(' '.join(cmd))
  690. # keep command history to a managable size
  691. if len(self.cmdbuffer) > 200:
  692. del self.cmdbuffer[0]
  693. self.cmdindex = len(self.cmdbuffer)
  694. def EntityToComplete(self):
  695. """!Determines which part of command (flags, parameters) should
  696. be completed at current cursor position"""
  697. entry = self.GetTextLeft()
  698. toComplete = dict()
  699. try:
  700. cmd = entry.split()[0].strip()
  701. except IndexError:
  702. return None
  703. if len(utils.split(str(entry))) > 1:
  704. if cmd in globalvar.grassCmd['all']:
  705. toComplete['cmd'] = cmd
  706. if entry[-1] == ' ':
  707. words = entry.split(' ')
  708. if any(word.startswith('-') for word in words):
  709. toComplete['entity'] = 'params'
  710. else:
  711. toComplete['entity'] = 'params+flags'
  712. else:
  713. # get word left from current position
  714. word = self.GetWordLeft(withDelimiter = True)
  715. if word[0] == '=' and word[-1] == '@':
  716. toComplete['entity'] = 'mapsets'
  717. elif word[0] == '=':
  718. # get name of parameter
  719. paramName = self.GetWordLeft(withDelimiter = False, ignoredDelimiter = '=').strip('=')
  720. if paramName:
  721. try:
  722. param = self.cmdDesc.get_param(paramName)
  723. except (ValueError, AttributeError):
  724. return None
  725. else:
  726. return None
  727. if param['values']:
  728. toComplete['entity'] = 'param values'
  729. elif param['prompt'] == 'raster' and param['element'] == 'cell':
  730. toComplete['entity'] = 'raster map'
  731. elif param['prompt'] == 'vector' and param['element'] == 'vector':
  732. toComplete['entity'] = 'vector map'
  733. elif word[0] == '-':
  734. toComplete['entity'] = 'flags'
  735. elif word[0] == ' ':
  736. toComplete['entity'] = 'params'
  737. else:
  738. return None
  739. else:
  740. toComplete['entity'] = 'command'
  741. toComplete['cmd'] = cmd
  742. return toComplete
  743. def GetWordLeft(self, withDelimiter = False, ignoredDelimiter = None):
  744. """!Get word left from current cursor position. The beginning
  745. of the word is given by space or chars: .,-=
  746. @param withDelimiter returns the word with the initial delimeter
  747. @param ignoredDelimiter finds the word ignoring certain delimeter
  748. """
  749. textLeft = self.GetTextLeft()
  750. parts = list()
  751. if ignoredDelimiter is None:
  752. ignoredDelimiter = ''
  753. for char in set(' .,-=') - set(ignoredDelimiter):
  754. if not withDelimiter:
  755. delimiter = ''
  756. else:
  757. delimiter = char
  758. parts.append(delimiter + textLeft.rpartition(char)[2])
  759. return min(parts, key=lambda x: len(x))
  760. def ShowList(self):
  761. """!Show sorted auto-completion list if it is not empty"""
  762. if len(self.autoCompList) > 0:
  763. self.autoCompList.sort()
  764. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  765. def OnKeyPressed(self, event):
  766. """!Key press capture for autocompletion, calltips, and command history
  767. @todo event.ControlDown() for manual autocomplete
  768. """
  769. # keycodes used: "." = 46, "=" = 61, "-" = 45
  770. pos = self.GetCurrentPos()
  771. #complete command after pressing '.'
  772. if event.GetKeyCode() == 46 and not event.ShiftDown():
  773. self.autoCompList = list()
  774. entry = self.GetTextLeft()
  775. self.InsertText(pos, '.')
  776. self.CharRight()
  777. self.toComplete = self.EntityToComplete()
  778. try:
  779. if self.toComplete['entity'] == 'command':
  780. self.autoCompList = self.moduleList[entry.strip()]
  781. except (KeyError, TypeError):
  782. return
  783. self.ShowList()
  784. # complete flags after pressing '-'
  785. elif event.GetKeyCode() == 45 and not event.ShiftDown():
  786. self.autoCompList = list()
  787. entry = self.GetTextLeft()
  788. self.InsertText(pos, '-')
  789. self.CharRight()
  790. self.toComplete = self.EntityToComplete()
  791. if self.toComplete['entity'] == 'flags' and self.cmdDesc:
  792. if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite
  793. for flag in self.cmdDesc.get_options()['flags']:
  794. if len(flag['name']) == 1:
  795. self.autoCompList.append(flag['name'])
  796. else:
  797. for flag in self.cmdDesc.get_options()['flags']:
  798. if len(flag['name']) > 1:
  799. self.autoCompList.append(flag['name'])
  800. self.ShowList()
  801. # complete map or values after parameter
  802. elif event.GetKeyCode() == 61 and not event.ShiftDown():
  803. self.autoCompList = list()
  804. self.InsertText(pos, '=')
  805. self.CharRight()
  806. self.toComplete = self.EntityToComplete()
  807. if self.toComplete and 'entity' in self.toComplete:
  808. if self.toComplete['entity'] == 'raster map':
  809. self.autoCompList = self.mapList['raster']
  810. elif self.toComplete['entity'] == 'vector map':
  811. self.autoCompList = self.mapList['vector']
  812. elif self.toComplete['entity'] == 'param values':
  813. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  814. self.autoCompList = self.cmdDesc.get_param(param)['values']
  815. self.ShowList()
  816. # complete mapset ('@')
  817. elif event.GetKeyCode() == 50 and event.ShiftDown():
  818. self.autoCompList = list()
  819. self.InsertText(pos, '@')
  820. self.CharRight()
  821. self.toComplete = self.EntityToComplete()
  822. if self.toComplete and self.toComplete['entity'] == 'mapsets':
  823. self.autoCompList = self.mapsetList
  824. self.ShowList()
  825. # complete after pressing CTRL + Space
  826. elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
  827. self.autoCompList = list()
  828. self.toComplete = self.EntityToComplete()
  829. if self.toComplete is None:
  830. return
  831. #complete command
  832. if self.toComplete['entity'] == 'command':
  833. for command in globalvar.grassCmd['all']:
  834. if command.find(self.toComplete['cmd']) == 0:
  835. dotNumber = list(self.toComplete['cmd']).count('.')
  836. self.autoCompList.append(command.split('.',dotNumber)[-1])
  837. # complete flags in such situations (| is cursor):
  838. # r.colors -| ...w, q, l
  839. # r.colors -w| ...w, q, l
  840. elif self.toComplete['entity'] == 'flags' and self.cmdDesc:
  841. for flag in self.cmdDesc.get_options()['flags']:
  842. if len(flag['name']) == 1:
  843. self.autoCompList.append(flag['name'])
  844. # complete parameters in such situations (| is cursor):
  845. # r.colors -w | ...color, map, rast, rules
  846. # r.colors col| ...color
  847. elif self.toComplete['entity'] == 'params' and self.cmdDesc:
  848. for param in self.cmdDesc.get_options()['params']:
  849. if param['name'].find(self.GetWordLeft(withDelimiter=False)) == 0:
  850. self.autoCompList.append(param['name'])
  851. # complete flags or parameters in such situations (| is cursor):
  852. # r.colors | ...-w, -q, -l, color, map, rast, rules
  853. # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules
  854. elif self.toComplete['entity'] == 'params+flags' and self.cmdDesc:
  855. self.autoCompList = list()
  856. for param in self.cmdDesc.get_options()['params']:
  857. self.autoCompList.append(param['name'])
  858. for flag in self.cmdDesc.get_options()['flags']:
  859. if len(flag['name']) == 1:
  860. self.autoCompList.append('-' + flag['name'])
  861. else:
  862. self.autoCompList.append('--' + flag['name'])
  863. self.ShowList()
  864. # complete map or values after parameter
  865. # r.buffer input=| ...list of raster maps
  866. # r.buffer units=| ... feet, kilometers, ...
  867. elif self.toComplete['entity'] == 'raster map':
  868. self.autoCompList = list()
  869. self.autoCompList = self.mapList['raster']
  870. elif self.toComplete['entity'] == 'vector map':
  871. self.autoCompList = list()
  872. self.autoCompList = self.mapList['vector']
  873. elif self.toComplete['entity'] == 'param values':
  874. self.autoCompList = list()
  875. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  876. self.autoCompList = self.cmdDesc.get_param(param)['values']
  877. self.ShowList()
  878. elif event.GetKeyCode() == wx.WXK_TAB:
  879. # show GRASS command calltips (to hide press 'ESC')
  880. entry = self.GetTextLeft()
  881. try:
  882. cmd = entry.split()[0].strip()
  883. except IndexError:
  884. cmd = ''
  885. if cmd not in globalvar.grassCmd['all']:
  886. return
  887. info = gtask.command_info(cmd)
  888. self.CallTipSetBackground("#f4f4d1")
  889. self.CallTipSetForeground("BLACK")
  890. self.CallTipShow(pos, info['usage'] + '\n\n' + info['description'])
  891. elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and \
  892. not self.AutoCompActive():
  893. # Command history using up and down
  894. if len(self.cmdbuffer) < 1:
  895. return
  896. self.DocumentEnd()
  897. # move through command history list index values
  898. if event.GetKeyCode() == wx.WXK_UP:
  899. self.cmdindex = self.cmdindex - 1
  900. if event.GetKeyCode() == wx.WXK_DOWN:
  901. self.cmdindex = self.cmdindex + 1
  902. if self.cmdindex < 0:
  903. self.cmdindex = 0
  904. if self.cmdindex > len(self.cmdbuffer) - 1:
  905. self.cmdindex = len(self.cmdbuffer) - 1
  906. try:
  907. txt = self.cmdbuffer[self.cmdindex]
  908. except:
  909. txt = ''
  910. # clear current line and insert command history
  911. self.DelLineLeft()
  912. self.DelLineRight()
  913. pos = self.GetCurrentPos()
  914. self.InsertText(pos,txt)
  915. self.LineEnd()
  916. self.parent.parent.statusbar.SetStatusText('')
  917. elif event.GetKeyCode() == wx.WXK_RETURN and \
  918. self.AutoCompActive() == False:
  919. # run command on line when <return> is pressed
  920. if self.parent.GetName() == "ModelerDialog":
  921. self.parent.OnOk(None)
  922. return
  923. # find the command to run
  924. line = self.GetCurLine()[0].strip()
  925. if len(line) == 0:
  926. return
  927. # parse command into list
  928. try:
  929. cmd = utils.split(str(line))
  930. except UnicodeError:
  931. cmd = utils.split(utils.EncodeString((line)))
  932. cmd = map(utils.DecodeString, cmd)
  933. # send the command list to the processor
  934. if cmd[0] in ('r.mapcalc', 'r3.mapcalc') and len(cmd) == 1:
  935. self.parent.parent.OnMapCalculator(event = None, cmd = cmd)
  936. else:
  937. self.parent.RunCmd(cmd)
  938. # add command to history & clean prompt
  939. self.UpdateCmdHistory(cmd)
  940. self.OnCmdErase(None)
  941. self.parent.parent.statusbar.SetStatusText('')
  942. elif event.GetKeyCode() == wx.WXK_SPACE:
  943. items = self.GetTextLeft().split()
  944. if len(items) == 1:
  945. cmd = items[0].strip()
  946. if cmd in globalvar.grassCmd['all'] and \
  947. cmd != 'r.mapcalc' and \
  948. (not self.cmdDesc or cmd != self.cmdDesc.get_name()):
  949. try:
  950. self.cmdDesc = gtask.parse_interface(cmd)
  951. except IOError:
  952. self.cmdDesc = None
  953. event.Skip()
  954. else:
  955. event.Skip()
  956. def ShowStatusText(self, text):
  957. """!Sets statusbar text, if it's too long, it is cut off"""
  958. maxLen = self.parent.parent.statusbar.GetFieldRect(0).GetWidth()/ 7 # any better way?
  959. if len(text) < maxLen:
  960. self.parent.parent.statusbar.SetStatusText(text)
  961. else:
  962. self.parent.parent.statusbar.SetStatusText(text[:maxLen]+'...')
  963. def GetTextLeft(self):
  964. """!Returns all text left of the caret"""
  965. pos = self.GetCurrentPos()
  966. self.HomeExtend()
  967. entry = self.GetSelectedText()
  968. self.SetCurrentPos(pos)
  969. return entry
  970. def OnDestroy(self, event):
  971. """!The clipboard contents can be preserved after
  972. the app has exited"""
  973. wx.TheClipboard.Flush()
  974. event.Skip()
  975. def OnCmdErase(self, event):
  976. """!Erase command prompt"""
  977. self.Home()
  978. self.DelLineRight()