prompt.py 43 KB

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