prompt.py 43 KB

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