prompt.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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. 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 'style' in kwargs:
  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 = utils.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 = utils.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', errors='replace')
  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 cmd in self.moduleDesc:
  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 group not in result:
  478. result[group] = list()
  479. result[group].append(name)
  480. # for better auto-completion:
  481. # not only result['r']={...,'colors.out',...}, but also result['r.colors']={'out',...}
  482. for i in range(len(name.split('.'))-1):
  483. group = '.'.join([group,name.split('.',1)[0]])
  484. name = name.split('.',1)[1]
  485. if group not in result:
  486. result[group] = list()
  487. result[group].append(name)
  488. # sort list of names
  489. for group in result.keys():
  490. result[group].sort()
  491. return result
  492. def _getListOfMaps(self):
  493. """!Get list of maps"""
  494. result = dict()
  495. result['raster'] = grass.list_strings('rast')
  496. result['vector'] = grass.list_strings('vect')
  497. return result
  498. def OnRunCmd(self, event):
  499. """!Run command"""
  500. cmdString = event.GetString()
  501. if self.standAlone:
  502. return
  503. if cmdString[:2] == 'd.' and not self.parent.curr_page:
  504. self.parent.NewDisplay(show=True)
  505. cmd = utils.split(cmdString)
  506. if len(cmd) > 1:
  507. self.parent.RunCmd(cmd, switchPage = True)
  508. else:
  509. self.parent.RunCmd(cmd, switchPage = False)
  510. self.OnUpdateStatusBar(None)
  511. def OnUpdateStatusBar(self, event):
  512. """!Update Layer Manager status bar"""
  513. if self.standAlone:
  514. return
  515. if event is None:
  516. self.parent.parent.statusbar.SetStatusText("")
  517. else:
  518. self.parent.parent.statusbar.SetStatusText(_("Type GRASS command and run by pressing ENTER"))
  519. event.Skip()
  520. def GetPanel(self):
  521. """!Get main widget panel"""
  522. return self.panel
  523. def GetInput(self):
  524. """!Get main prompt widget"""
  525. return self.input
  526. 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 OnTextSelectionChanged(self, event):
  596. """!Copy selected text to clipboard and skip event.
  597. The same function is in GMStc class (goutput.py).
  598. """
  599. self.Copy()
  600. event.Skip()
  601. def OnItemChanged(self, event):
  602. """!Change text in statusbar
  603. if the item selection in the auto-completion list is changed"""
  604. # list of commands
  605. if self.toComplete['entity'] == 'command':
  606. item = self.toComplete['cmd'].rpartition('.')[0] + '.' + self.autoCompList[event.GetIndex()]
  607. try:
  608. desc = self.moduleDesc[item]['desc']
  609. except KeyError:
  610. desc = ''
  611. self.ShowStatusText(desc)
  612. # list of flags
  613. elif self.toComplete['entity'] == 'flags':
  614. desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()])['description']
  615. self.ShowStatusText(desc)
  616. # list of parameters
  617. elif self.toComplete['entity'] == 'params':
  618. item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
  619. desc = item['name'] + '=' + item['type']
  620. if not item['required']:
  621. desc = '[' + desc + ']'
  622. desc += ': ' + item['description']
  623. self.ShowStatusText(desc)
  624. # list of flags and commands
  625. elif self.toComplete['entity'] == 'params+flags':
  626. if self.autoCompList[event.GetIndex()][0] == '-':
  627. desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()].strip('-'))['description']
  628. else:
  629. item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
  630. desc = item['name'] + '=' + item['type']
  631. if not item['required']:
  632. desc = '[' + desc + ']'
  633. desc += ': ' + item['description']
  634. self.ShowStatusText(desc)
  635. else:
  636. self.ShowStatusText('')
  637. def OnItemSelected(self, event):
  638. """!Item selected from the list"""
  639. lastWord = self.GetWordLeft()
  640. # to insert selection correctly if selected word partly matches written text
  641. match = difflib.SequenceMatcher(None, event.GetText(), lastWord)
  642. matchTuple = match.find_longest_match(0, len(event.GetText()), 0, len(lastWord))
  643. compl = event.GetText()[matchTuple[2]:]
  644. text = self.GetTextLeft() + compl
  645. # add space or '=' at the end
  646. end = '='
  647. for char in ('.','-','='):
  648. if text.split(' ')[-1].find(char) >= 0:
  649. end = ' '
  650. compl += end
  651. text += end
  652. self.AddText(compl)
  653. pos = len(text)
  654. self.SetCurrentPos(pos)
  655. cmd = text.strip().split(' ')[0]
  656. if not self.cmdDesc or cmd != self.cmdDesc.get_name():
  657. if cmd in ('r.mapcalc', 'r3.mapcalc'):
  658. self.parent.parent.OnMapCalculator(event = None, cmd = [cmd])
  659. # add command to history & clean prompt
  660. self.UpdateCmdHistory([cmd])
  661. self.OnCmdErase(None)
  662. else:
  663. try:
  664. self.cmdDesc = menuform.GUI().ParseInterface(cmd = [cmd])
  665. except IOError:
  666. self.cmdDesc = None
  667. def UpdateCmdHistory(self, cmd):
  668. """!Update command history
  669. @param cmd command given as a list
  670. """
  671. # add command to history
  672. self.cmdbuffer.append(' '.join(cmd))
  673. # keep command history to a managable size
  674. if len(self.cmdbuffer) > 200:
  675. del self.cmdbuffer[0]
  676. self.cmdindex = len(self.cmdbuffer)
  677. def EntityToComplete(self):
  678. """!Determines which part of command (flags, parameters) should
  679. be completed at current cursor position"""
  680. entry = self.GetTextLeft()
  681. toComplete = dict()
  682. try:
  683. cmd = entry.split()[0].strip()
  684. except IndexError:
  685. return None
  686. if len(entry.split(' ')) > 1:
  687. if cmd in globalvar.grassCmd['all']:
  688. toComplete['cmd'] = cmd
  689. if entry[-1] == ' ':
  690. words = entry.split(' ')
  691. if any(word.startswith('-') for word in words):
  692. toComplete['entity'] = 'params'
  693. return toComplete
  694. else:
  695. toComplete['entity'] = 'params+flags'
  696. return toComplete
  697. else:
  698. #get word left from current position
  699. word = self.GetWordLeft(withDelimiter = True)
  700. if word[0] == '=':
  701. # get name of parameter
  702. paramName = self.GetWordLeft(withDelimiter = False, ignoredDelimiter = '=').strip('=')
  703. if paramName:
  704. try:
  705. param = self.cmdDesc.get_param(paramName)
  706. except ValueError:
  707. return
  708. else:
  709. return
  710. if param['values']:
  711. toComplete['entity'] = 'param values'
  712. return toComplete
  713. elif param['prompt'] == 'raster' and param['element'] == 'cell':
  714. toComplete['entity'] = 'raster map'
  715. return toComplete
  716. elif param['prompt'] == 'vector' and param['element'] == 'vector':
  717. toComplete['entity'] = 'vector map'
  718. return toComplete
  719. elif word[0] == '-':
  720. toComplete['entity'] = 'flags'
  721. return toComplete
  722. elif word[0] == ' ':
  723. toComplete['entity'] = 'params'
  724. return toComplete
  725. else:
  726. return None
  727. else:
  728. toComplete['entity'] = 'command'
  729. toComplete['cmd'] = cmd
  730. return toComplete
  731. def GetWordLeft(self, withDelimiter = False, ignoredDelimiter = None):
  732. """!Get word left from current cursor position. The beginning
  733. of the word is given by space or chars: .,-=
  734. @param withDelimiter returns the word with the initial delimeter
  735. @param ignoredDelimiter finds the word ignoring certain delimeter
  736. """
  737. textLeft = self.GetTextLeft()
  738. parts = list()
  739. if ignoredDelimiter is None:
  740. ignoredDelimiter = ''
  741. for char in set(' .,-=') - set(ignoredDelimiter):
  742. if not withDelimiter:
  743. delimiter = ''
  744. else:
  745. delimiter = char
  746. parts.append(delimiter + textLeft.rpartition(char)[2])
  747. return min(parts, key=lambda x: len(x))
  748. def ShowList(self):
  749. """!Show sorted auto-completion list if it is not empty"""
  750. if len(self.autoCompList) > 0:
  751. self.autoCompList.sort()
  752. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  753. def OnKeyPressed(self, event):
  754. """!Key press capture for autocompletion, calltips, and command history
  755. @todo event.ControlDown() for manual autocomplete
  756. """
  757. # keycodes used: "." = 46, "=" = 61, "-" = 45
  758. pos = self.GetCurrentPos()
  759. #complete command after pressing '.'
  760. if event.GetKeyCode() == 46 and not event.ShiftDown():
  761. self.autoCompList = list()
  762. entry = self.GetTextLeft()
  763. self.InsertText(pos, '.')
  764. self.CharRight()
  765. self.toComplete = self.EntityToComplete()
  766. if self.toComplete['entity'] == 'command':
  767. try:
  768. self.autoCompList = self.moduleList[entry.strip()]
  769. except KeyError:
  770. return
  771. self.ShowList()
  772. # complete flags after pressing '-'
  773. elif event.GetKeyCode() == 45 and not event.ShiftDown():
  774. self.autoCompList = list()
  775. entry = self.GetTextLeft()
  776. self.InsertText(pos, '-')
  777. self.CharRight()
  778. self.toComplete = self.EntityToComplete()
  779. if self.toComplete['entity'] == 'flags' and self.cmdDesc:
  780. if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite
  781. for flag in self.cmdDesc.get_options()['flags']:
  782. if len(flag['name']) == 1:
  783. self.autoCompList.append(flag['name'])
  784. else:
  785. for flag in self.cmdDesc.get_options()['flags']:
  786. if len(flag['name']) > 1:
  787. self.autoCompList.append(flag['name'])
  788. self.ShowList()
  789. # complete map or values after parameter
  790. elif event.GetKeyCode() == 61 and not event.ShiftDown():
  791. self.autoCompList = list()
  792. self.InsertText(pos, '=')
  793. self.CharRight()
  794. self.toComplete = self.EntityToComplete()
  795. if self.toComplete:
  796. if self.toComplete['entity'] == 'raster map':
  797. self.autoCompList = self.mapList['raster']
  798. elif self.toComplete['entity'] == 'vector map':
  799. self.autoCompList = self.mapList['vector']
  800. elif self.toComplete['entity'] == 'param values':
  801. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  802. self.autoCompList = self.cmdDesc.get_param(param)['values']
  803. self.ShowList()
  804. # complete after pressing CTRL + Space
  805. elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
  806. self.autoCompList = list()
  807. self.toComplete = self.EntityToComplete()
  808. if self.toComplete is None:
  809. return
  810. #complete command
  811. if self.toComplete['entity'] == 'command':
  812. for command in globalvar.grassCmd['all']:
  813. if command.find(self.toComplete['cmd']) == 0:
  814. dotNumber = list(self.toComplete['cmd']).count('.')
  815. self.autoCompList.append(command.split('.',dotNumber)[-1])
  816. # complete flags in such situations (| is cursor):
  817. # r.colors -| ...w, q, l
  818. # r.colors -w| ...w, q, l
  819. elif self.toComplete['entity'] == 'flags':
  820. for flag in self.cmdDesc.get_options()['flags']:
  821. if len(flag['name']) == 1:
  822. self.autoCompList.append(flag['name'])
  823. # complete parameters in such situations (| is cursor):
  824. # r.colors -w | ...color, map, rast, rules
  825. # r.colors col| ...color
  826. elif self.toComplete['entity'] == 'params':
  827. for param in self.cmdDesc.get_options()['params']:
  828. if param['name'].find(self.GetWordLeft(withDelimiter=False)) == 0:
  829. self.autoCompList.append(param['name'])
  830. # complete flags or parameters in such situations (| is cursor):
  831. # r.colors | ...-w, -q, -l, color, map, rast, rules
  832. # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules
  833. elif self.toComplete['entity'] == 'params+flags':
  834. self.autoCompList = list()
  835. for param in self.cmdDesc.get_options()['params']:
  836. self.autoCompList.append(param['name'])
  837. for flag in self.cmdDesc.get_options()['flags']:
  838. if len(flag['name']) == 1:
  839. self.autoCompList.append('-' + flag['name'])
  840. else:
  841. self.autoCompList.append('--' + flag['name'])
  842. self.ShowList()
  843. # complete map or values after parameter
  844. # r.buffer input=| ...list of raster maps
  845. # r.buffer units=| ... feet, kilometers, ...
  846. elif self.toComplete['entity'] == 'raster map':
  847. self.autoCompList = list()
  848. self.autoCompList = self.mapList['raster']
  849. elif self.toComplete['entity'] == 'vector map':
  850. self.autoCompList = list()
  851. self.autoCompList = self.mapList['vector']
  852. elif self.toComplete['entity'] == 'param values':
  853. self.autoCompList = list()
  854. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  855. self.autoCompList = self.cmdDesc.get_param(param)['values']
  856. self.ShowList()
  857. elif event.GetKeyCode() == wx.WXK_TAB:
  858. # show GRASS command calltips (to hide press 'ESC')
  859. entry = self.GetTextLeft()
  860. try:
  861. cmd = entry.split()[0].strip()
  862. except IndexError:
  863. cmd = ''
  864. if cmd not in globalvar.grassCmd['all']:
  865. return
  866. usage, description = self.GetCommandUsage(cmd)
  867. self.CallTipSetBackground("#f4f4d1")
  868. self.CallTipSetForeground("BLACK")
  869. self.CallTipShow(pos, usage + '\n\n' + description)
  870. elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and \
  871. not self.AutoCompActive():
  872. # Command history using up and down
  873. if len(self.cmdbuffer) < 1:
  874. return
  875. self.DocumentEnd()
  876. # move through command history list index values
  877. if event.GetKeyCode() == wx.WXK_UP:
  878. self.cmdindex = self.cmdindex - 1
  879. if event.GetKeyCode() == wx.WXK_DOWN:
  880. self.cmdindex = self.cmdindex + 1
  881. if self.cmdindex < 0:
  882. self.cmdindex = 0
  883. if self.cmdindex > len(self.cmdbuffer) - 1:
  884. self.cmdindex = len(self.cmdbuffer) - 1
  885. try:
  886. txt = self.cmdbuffer[self.cmdindex]
  887. except:
  888. txt = ''
  889. # clear current line and insert command history
  890. self.DelLineLeft()
  891. self.DelLineRight()
  892. pos = self.GetCurrentPos()
  893. self.InsertText(pos,txt)
  894. self.LineEnd()
  895. self.parent.parent.statusbar.SetStatusText('')
  896. elif event.GetKeyCode() == wx.WXK_RETURN and \
  897. self.AutoCompActive() == False:
  898. # run command on line when <return> is pressed
  899. if self.parent.GetName() == "ModelerDialog":
  900. self.parent.OnOk(None)
  901. return
  902. # find the command to run
  903. line = self.GetCurLine()[0].strip()
  904. if len(line) == 0:
  905. return
  906. # parse command into list
  907. try:
  908. cmd = utils.split(str(line))
  909. except UnicodeError:
  910. cmd = utils.split(utils.EncodeString((line)))
  911. cmd = map(utils.DecodeString, cmd)
  912. # send the command list to the processor
  913. if cmd[0] in ('r.mapcalc', 'r3.mapcalc') and len(cmd) == 1:
  914. self.parent.parent.OnMapCalculator(event = None, cmd = cmd)
  915. else:
  916. self.parent.RunCmd(cmd)
  917. # add command to history & clean prompt
  918. self.UpdateCmdHistory(cmd)
  919. self.OnCmdErase(None)
  920. self.parent.parent.statusbar.SetStatusText('')
  921. elif event.GetKeyCode() == wx.WXK_SPACE:
  922. items = self.GetTextLeft().split()
  923. if len(items) == 1:
  924. cmd = items[0].strip()
  925. if cmd in globalvar.grassCmd['all'] and \
  926. cmd != 'r.mapcalc' and \
  927. (not self.cmdDesc or cmd != self.cmdDesc.get_name()):
  928. try:
  929. self.cmdDesc = menuform.GUI().ParseInterface(cmd = [cmd])
  930. except IOError:
  931. self.cmdDesc = None
  932. event.Skip()
  933. else:
  934. event.Skip()
  935. def ShowStatusText(self, text):
  936. """!Sets statusbar text, if it's too long, it is cut off"""
  937. maxLen = self.parent.parent.statusbar.GetFieldRect(0).GetWidth()/ 7 # any better way?
  938. if len(text) < maxLen:
  939. self.parent.parent.statusbar.SetStatusText(text)
  940. else:
  941. self.parent.parent.statusbar.SetStatusText(text[:maxLen]+'...')
  942. def GetTextLeft(self):
  943. """!Returns all text left of the caret"""
  944. pos = self.GetCurrentPos()
  945. self.HomeExtend()
  946. entry = self.GetSelectedText()
  947. self.SetCurrentPos(pos)
  948. return entry
  949. def GetCommandUsage(self, command):
  950. """!Returns command syntax by running command help"""
  951. usage = ''
  952. description = ''
  953. ret, out = gcmd.RunCommand(command, 'help', getErrorMsg = True)
  954. if ret == 0:
  955. cmdhelp = out.splitlines()
  956. addline = False
  957. helplist = []
  958. description = ''
  959. for line in cmdhelp:
  960. if "Usage:" in line:
  961. addline = True
  962. continue
  963. elif "Flags:" in line:
  964. addline = False
  965. break
  966. elif addline == True:
  967. line = line.strip()
  968. helplist.append(line)
  969. for line in cmdhelp:
  970. if "Description:" in line:
  971. addline = True
  972. continue
  973. elif "Keywords:" in line:
  974. addline = False
  975. break
  976. elif addline == True:
  977. description += (line + ' ')
  978. description = description.strip()
  979. for line in helplist:
  980. usage += line + '\n'
  981. return usage.strip(), description
  982. else:
  983. return ''
  984. def OnDestroy(self, event):
  985. """!The clipboard contents can be preserved after
  986. the app has exited"""
  987. wx.TheClipboard.Flush()
  988. event.Skip()
  989. def OnCmdErase(self, event):
  990. """!Erase command prompt"""
  991. self.Home()
  992. self.DelLineRight()