prompt.py 43 KB

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