prompt.py 43 KB

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