prompt.py 43 KB

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