prompt.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. """!
  2. @package gui_core.prompt
  3. @brief wxGUI command prompt
  4. Classes:
  5. - prompt::GPrompt
  6. - prompt::GPromptSTC
  7. (C) 2009-2011 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Martin Landa <landa.martin gmail.com>
  11. @author Michael Barton <michael.barton@asu.edu>
  12. @author Vaclav Petras <wenzeslaus gmail.com> (copy&paste customization)
  13. """
  14. import os
  15. import difflib
  16. import codecs
  17. import wx
  18. import wx.stc
  19. from grass.script import core as grass
  20. from grass.script import task as gtask
  21. from grass.pydispatch.signal import Signal
  22. from core import globalvar
  23. from core import utils
  24. from core.gcmd import EncodeString, DecodeString, GetRealCmd
  25. class GPrompt(object):
  26. """!Abstract class for interactive wxGUI prompt
  27. Signal promptRunCmd - emitted to run command from prompt
  28. - attribute 'cmd'
  29. See subclass GPromptPopUp and GPromptSTC.
  30. """
  31. def __init__(self, parent, menuModel, updateCmdHistory):
  32. self.parent = parent # GConsole
  33. self.panel = self.parent.GetPanel()
  34. self.promptRunCmd = Signal('GPrompt.promptRunCmd')
  35. # probably only subclasses need this
  36. self._menuModel = menuModel
  37. self.mapList = self._getListOfMaps()
  38. self.mapsetList = utils.ListOfMapsets()
  39. # auto complete items
  40. self.autoCompList = list()
  41. self.autoCompFilter = None
  42. # command description (gtask.grassTask)
  43. self.cmdDesc = None
  44. self._updateCmdHistory = updateCmdHistory
  45. self.cmdbuffer = self._readHistory()
  46. self.cmdindex = len(self.cmdbuffer)
  47. # list of traced commands
  48. self.commands = list()
  49. def _readHistory(self):
  50. """!Get list of commands from history file"""
  51. hist = list()
  52. env = grass.gisenv()
  53. try:
  54. fileHistory = codecs.open(os.path.join(env['GISDBASE'],
  55. env['LOCATION_NAME'],
  56. env['MAPSET'],
  57. '.bash_history'),
  58. encoding = 'utf-8', mode = 'r', errors='replace')
  59. except IOError:
  60. return hist
  61. try:
  62. for line in fileHistory.readlines():
  63. hist.append(line.replace('\n', ''))
  64. finally:
  65. fileHistory.close()
  66. return hist
  67. def _getListOfMaps(self):
  68. """!Get list of maps"""
  69. result = dict()
  70. result['raster'] = grass.list_strings('rast')
  71. result['vector'] = grass.list_strings('vect')
  72. return result
  73. def _runCmd(self, cmdString):
  74. """!Run command
  75. @param cmdString command to run (given as a string)
  76. """
  77. if not cmdString:
  78. return
  79. self.commands.append(cmdString) # trace commands
  80. # parse command into list
  81. try:
  82. cmd = utils.split(str(cmdString))
  83. except UnicodeError:
  84. cmd = utils.split(EncodeString((cmdString)))
  85. cmd = map(DecodeString, cmd)
  86. self.promptRunCmd.emit(cmd=cmd)
  87. # add command to history & clean prompt
  88. self.UpdateCmdHistory(cmd)
  89. self.OnCmdErase(None)
  90. self.ShowStatusText('')
  91. def GetCommands(self):
  92. """!Get list of launched commands"""
  93. return self.commands
  94. def ClearCommands(self):
  95. """!Clear list of commands"""
  96. del self.commands[:]
  97. class GPromptSTC(GPrompt, wx.stc.StyledTextCtrl):
  98. """!Styled wxGUI prompt with autocomplete and calltips"""
  99. def __init__(self, parent, menuModel, updateCmdHistory = True, margin = False):
  100. GPrompt.__init__(self, parent = parent,
  101. menuModel = menuModel, updateCmdHistory = updateCmdHistory)
  102. wx.stc.StyledTextCtrl.__init__(self, self.panel, id = wx.ID_ANY)
  103. #
  104. # styles
  105. #
  106. self.SetWrapMode(True)
  107. self.SetUndoCollection(True)
  108. #
  109. # create command and map lists for autocompletion
  110. #
  111. self.AutoCompSetIgnoreCase(False)
  112. #
  113. # line margins
  114. #
  115. # TODO print number only from cmdlog
  116. self.SetMarginWidth(1, 0)
  117. self.SetMarginWidth(2, 0)
  118. if margin:
  119. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  120. self.SetMarginWidth(0, 30)
  121. else:
  122. self.SetMarginWidth(0, 0)
  123. #
  124. # miscellaneous
  125. #
  126. self.SetViewWhiteSpace(False)
  127. self.SetUseTabs(False)
  128. self.UsePopUp(True)
  129. self.SetSelBackground(True, "#FFFF00")
  130. self.SetUseHorizontalScrollBar(True)
  131. #
  132. # bindings
  133. #
  134. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  135. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  136. self.Bind(wx.stc.EVT_STC_AUTOCOMP_SELECTION, self.OnItemSelected)
  137. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemChanged)
  138. self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
  139. # signal which requests showing of a notification
  140. self.showNotification = Signal('GPromptSTC.showNotification')
  141. def OnTextSelectionChanged(self, event):
  142. """!Copy selected text to clipboard and skip event.
  143. The same function is in GStc class (goutput.py).
  144. """
  145. wx.CallAfter(self.Copy)
  146. event.Skip()
  147. def OnItemChanged(self, event):
  148. """!Change text in statusbar
  149. if the item selection in the auto-completion list is changed"""
  150. # list of commands
  151. if self.toComplete['entity'] == 'command':
  152. item = self.toComplete['cmd'].rpartition('.')[0] + '.' + self.autoCompList[event.GetIndex()]
  153. try:
  154. nodes = self._menuModel.SearchNodes(key='command', value=item)
  155. desc = ''
  156. if nodes:
  157. desc = nodes[0].data['description']
  158. except KeyError:
  159. desc = ''
  160. self.ShowStatusText(desc)
  161. # list of flags
  162. elif self.toComplete['entity'] == 'flags':
  163. desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()])['description']
  164. self.ShowStatusText(desc)
  165. # list of parameters
  166. elif self.toComplete['entity'] == 'params':
  167. item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
  168. desc = item['name'] + '=' + item['type']
  169. if not item['required']:
  170. desc = '[' + desc + ']'
  171. desc += ': ' + item['description']
  172. self.ShowStatusText(desc)
  173. # list of flags and commands
  174. elif self.toComplete['entity'] == 'params+flags':
  175. if self.autoCompList[event.GetIndex()][0] == '-':
  176. desc = self.cmdDesc.get_flag(self.autoCompList[event.GetIndex()].strip('-'))['description']
  177. else:
  178. item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
  179. desc = item['name'] + '=' + item['type']
  180. if not item['required']:
  181. desc = '[' + desc + ']'
  182. desc += ': ' + item['description']
  183. self.ShowStatusText(desc)
  184. else:
  185. self.ShowStatusText('')
  186. def OnItemSelected(self, event):
  187. """!Item selected from the list"""
  188. lastWord = self.GetWordLeft()
  189. # to insert selection correctly if selected word partly matches written text
  190. match = difflib.SequenceMatcher(None, event.GetText(), lastWord)
  191. matchTuple = match.find_longest_match(0, len(event.GetText()), 0, len(lastWord))
  192. compl = event.GetText()[matchTuple[2]:]
  193. text = self.GetTextLeft() + compl
  194. # add space or '=' at the end
  195. end = '='
  196. for char in ('.','-','='):
  197. if text.split(' ')[-1].find(char) >= 0:
  198. end = ' '
  199. compl += end
  200. text += end
  201. self.AddText(compl)
  202. pos = len(text)
  203. self.SetCurrentPos(pos)
  204. cmd = text.strip().split(' ')[0]
  205. if not self.cmdDesc or cmd != self.cmdDesc.get_name():
  206. try:
  207. self.cmdDesc = gtask.parse_interface(GetRealCmd(cmd))
  208. except IOError:
  209. self.cmdDesc = None
  210. def OnKillFocus(self, event):
  211. """!Hides autocomplete"""
  212. # hide autocomplete
  213. if self.AutoCompActive():
  214. self.AutoCompCancel()
  215. event.Skip()
  216. def SetTextAndFocus(self, text):
  217. pos = len(text)
  218. self.SetText(text)
  219. self.SetSelectionStart(pos)
  220. self.SetCurrentPos(pos)
  221. self.SetFocus()
  222. def UpdateCmdHistory(self, cmd):
  223. """!Update command history
  224. @param cmd command given as a list
  225. """
  226. if not self._updateCmdHistory:
  227. return
  228. # add command to history
  229. self.cmdbuffer.append(' '.join(cmd))
  230. # keep command history to a managable size
  231. if len(self.cmdbuffer) > 200:
  232. del self.cmdbuffer[0]
  233. self.cmdindex = len(self.cmdbuffer)
  234. def EntityToComplete(self):
  235. """!Determines which part of command (flags, parameters) should
  236. be completed at current cursor position"""
  237. entry = self.GetTextLeft()
  238. toComplete = dict()
  239. try:
  240. cmd = entry.split()[0].strip()
  241. except IndexError:
  242. return None
  243. try:
  244. splitted = utils.split(str(entry))
  245. except ValueError: # No closing quotation error
  246. return None
  247. if len(splitted) > 1:
  248. if cmd in globalvar.grassCmd:
  249. toComplete['cmd'] = cmd
  250. if entry[-1] == ' ':
  251. words = entry.split(' ')
  252. if any(word.startswith('-') for word in words):
  253. toComplete['entity'] = 'params'
  254. else:
  255. toComplete['entity'] = 'params+flags'
  256. else:
  257. # get word left from current position
  258. word = self.GetWordLeft(withDelimiter = True)
  259. if word[0] == '=' and word[-1] == '@':
  260. toComplete['entity'] = 'mapsets'
  261. elif word[0] == '=':
  262. # get name of parameter
  263. paramName = self.GetWordLeft(withDelimiter = False, ignoredDelimiter = '=').strip('=')
  264. if paramName:
  265. try:
  266. param = self.cmdDesc.get_param(paramName)
  267. except (ValueError, AttributeError):
  268. return None
  269. else:
  270. return None
  271. if param['values']:
  272. toComplete['entity'] = 'param values'
  273. elif param['prompt'] == 'raster' and param['element'] == 'cell':
  274. toComplete['entity'] = 'raster map'
  275. elif param['prompt'] == 'vector' and param['element'] == 'vector':
  276. toComplete['entity'] = 'vector map'
  277. elif word[0] == '-':
  278. toComplete['entity'] = 'flags'
  279. elif word[0] == ' ':
  280. toComplete['entity'] = 'params'
  281. else:
  282. return None
  283. else:
  284. toComplete['entity'] = 'command'
  285. toComplete['cmd'] = cmd
  286. return toComplete
  287. def GetWordLeft(self, withDelimiter = False, ignoredDelimiter = None):
  288. """!Get word left from current cursor position. The beginning
  289. of the word is given by space or chars: .,-=
  290. @param withDelimiter returns the word with the initial delimeter
  291. @param ignoredDelimiter finds the word ignoring certain delimeter
  292. """
  293. textLeft = self.GetTextLeft()
  294. parts = list()
  295. if ignoredDelimiter is None:
  296. ignoredDelimiter = ''
  297. for char in set(' .,-=') - set(ignoredDelimiter):
  298. if not withDelimiter:
  299. delimiter = ''
  300. else:
  301. delimiter = char
  302. parts.append(delimiter + textLeft.rpartition(char)[2])
  303. return min(parts, key=lambda x: len(x))
  304. def ShowList(self):
  305. """!Show sorted auto-completion list if it is not empty"""
  306. if len(self.autoCompList) > 0:
  307. self.autoCompList.sort()
  308. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  309. def OnKeyPressed(self, event):
  310. """!Key press capture for autocompletion, calltips, and command history
  311. @todo event.ControlDown() for manual autocomplete
  312. """
  313. # keycodes used: "." = 46, "=" = 61, "-" = 45
  314. pos = self.GetCurrentPos()
  315. # complete command after pressing '.'
  316. if event.GetKeyCode() == 46 and not event.ShiftDown():
  317. self.autoCompList = list()
  318. entry = self.GetTextLeft()
  319. self.InsertText(pos, '.')
  320. self.CharRight()
  321. self.toComplete = self.EntityToComplete()
  322. if self.toComplete is None:
  323. return
  324. try:
  325. if self.toComplete['entity'] == 'command':
  326. for command in globalvar.grassCmd:
  327. if command.find(self.toComplete['cmd']) == 0:
  328. dotNumber = list(self.toComplete['cmd']).count('.')
  329. self.autoCompList.append(command.split('.',dotNumber)[-1])
  330. except (KeyError, TypeError):
  331. return
  332. self.ShowList()
  333. # complete flags after pressing '-'
  334. elif event.GetKeyCode() == 45 and not event.ShiftDown():
  335. self.autoCompList = list()
  336. entry = self.GetTextLeft()
  337. self.InsertText(pos, '-')
  338. self.CharRight()
  339. self.toComplete = self.EntityToComplete()
  340. if self.toComplete['entity'] == 'flags' and self.cmdDesc:
  341. if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite
  342. for flag in self.cmdDesc.get_options()['flags']:
  343. if len(flag['name']) == 1:
  344. self.autoCompList.append(flag['name'])
  345. else:
  346. for flag in self.cmdDesc.get_options()['flags']:
  347. if len(flag['name']) > 1:
  348. self.autoCompList.append(flag['name'])
  349. self.ShowList()
  350. # complete map or values after parameter
  351. elif event.GetKeyCode() == 61 and not event.ShiftDown():
  352. self.autoCompList = list()
  353. self.InsertText(pos, '=')
  354. self.CharRight()
  355. self.toComplete = self.EntityToComplete()
  356. if self.toComplete and 'entity' in self.toComplete:
  357. if self.toComplete['entity'] == 'raster map':
  358. self.autoCompList = self.mapList['raster']
  359. elif self.toComplete['entity'] == 'vector map':
  360. self.autoCompList = self.mapList['vector']
  361. elif self.toComplete['entity'] == 'param values':
  362. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  363. self.autoCompList = self.cmdDesc.get_param(param)['values']
  364. self.ShowList()
  365. # complete mapset ('@')
  366. elif event.GetKeyCode() == 50 and event.ShiftDown():
  367. self.autoCompList = list()
  368. self.InsertText(pos, '@')
  369. self.CharRight()
  370. self.toComplete = self.EntityToComplete()
  371. if self.toComplete and self.toComplete['entity'] == 'mapsets':
  372. self.autoCompList = self.mapsetList
  373. self.ShowList()
  374. # complete after pressing CTRL + Space
  375. elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
  376. self.autoCompList = list()
  377. self.toComplete = self.EntityToComplete()
  378. if self.toComplete is None:
  379. return
  380. #complete command
  381. if self.toComplete['entity'] == 'command':
  382. for command in globalvar.grassCmd:
  383. if command.find(self.toComplete['cmd']) == 0:
  384. dotNumber = list(self.toComplete['cmd']).count('.')
  385. self.autoCompList.append(command.split('.',dotNumber)[-1])
  386. # complete flags in such situations (| is cursor):
  387. # r.colors -| ...w, q, l
  388. # r.colors -w| ...w, q, l
  389. elif self.toComplete['entity'] == 'flags' and self.cmdDesc:
  390. for flag in self.cmdDesc.get_options()['flags']:
  391. if len(flag['name']) == 1:
  392. self.autoCompList.append(flag['name'])
  393. # complete parameters in such situations (| is cursor):
  394. # r.colors -w | ...color, map, rast, rules
  395. # r.colors col| ...color
  396. elif self.toComplete['entity'] == 'params' and self.cmdDesc:
  397. for param in self.cmdDesc.get_options()['params']:
  398. if param['name'].find(self.GetWordLeft(withDelimiter=False)) == 0:
  399. self.autoCompList.append(param['name'])
  400. # complete flags or parameters in such situations (| is cursor):
  401. # r.colors | ...-w, -q, -l, color, map, rast, rules
  402. # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules
  403. elif self.toComplete['entity'] == 'params+flags' and self.cmdDesc:
  404. self.autoCompList = list()
  405. for param in self.cmdDesc.get_options()['params']:
  406. self.autoCompList.append(param['name'])
  407. for flag in self.cmdDesc.get_options()['flags']:
  408. if len(flag['name']) == 1:
  409. self.autoCompList.append('-' + flag['name'])
  410. else:
  411. self.autoCompList.append('--' + flag['name'])
  412. self.ShowList()
  413. # complete map or values after parameter
  414. # r.buffer input=| ...list of raster maps
  415. # r.buffer units=| ... feet, kilometers, ...
  416. elif self.toComplete['entity'] == 'raster map':
  417. self.autoCompList = list()
  418. self.autoCompList = self.mapList['raster']
  419. elif self.toComplete['entity'] == 'vector map':
  420. self.autoCompList = list()
  421. self.autoCompList = self.mapList['vector']
  422. elif self.toComplete['entity'] == 'param values':
  423. self.autoCompList = list()
  424. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  425. self.autoCompList = self.cmdDesc.get_param(param)['values']
  426. self.ShowList()
  427. elif event.GetKeyCode() == wx.WXK_TAB:
  428. # show GRASS command calltips (to hide press 'ESC')
  429. entry = self.GetTextLeft()
  430. try:
  431. cmd = entry.split()[0].strip()
  432. except IndexError:
  433. cmd = ''
  434. if cmd not in globalvar.grassCmd:
  435. return
  436. info = gtask.command_info(GetRealCmd(cmd))
  437. self.CallTipSetBackground("#f4f4d1")
  438. self.CallTipSetForeground("BLACK")
  439. self.CallTipShow(pos, info['usage'] + '\n\n' + info['description'])
  440. elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and \
  441. not self.AutoCompActive():
  442. # Command history using up and down
  443. if len(self.cmdbuffer) < 1:
  444. return
  445. self.DocumentEnd()
  446. # move through command history list index values
  447. if event.GetKeyCode() == wx.WXK_UP:
  448. self.cmdindex = self.cmdindex - 1
  449. if event.GetKeyCode() == wx.WXK_DOWN:
  450. self.cmdindex = self.cmdindex + 1
  451. if self.cmdindex < 0:
  452. self.cmdindex = 0
  453. if self.cmdindex > len(self.cmdbuffer) - 1:
  454. self.cmdindex = len(self.cmdbuffer) - 1
  455. try:
  456. txt = self.cmdbuffer[self.cmdindex]
  457. except KeyError:
  458. txt = ''
  459. # clear current line and insert command history
  460. self.DelLineLeft()
  461. self.DelLineRight()
  462. pos = self.GetCurrentPos()
  463. self.InsertText(pos,txt)
  464. self.LineEnd()
  465. self.ShowStatusText('')
  466. elif event.GetKeyCode() == wx.WXK_RETURN and \
  467. self.AutoCompActive() == False:
  468. # run command on line when <return> is pressed
  469. self._runCmd(self.GetCurLine()[0].strip())
  470. elif event.GetKeyCode() == wx.WXK_SPACE:
  471. items = self.GetTextLeft().split()
  472. if len(items) == 1:
  473. cmd = items[0].strip()
  474. if cmd in globalvar.grassCmd and \
  475. (not self.cmdDesc or cmd != self.cmdDesc.get_name()):
  476. try:
  477. self.cmdDesc = gtask.parse_interface(GetRealCmd(cmd))
  478. except IOError:
  479. self.cmdDesc = None
  480. event.Skip()
  481. else:
  482. event.Skip()
  483. def ShowStatusText(self, text):
  484. """!Requests showing of notification, e.g. showing in a statusbar."""
  485. self.showNotification.emit(message=text)
  486. def GetTextLeft(self):
  487. """!Returns all text left of the caret"""
  488. pos = self.GetCurrentPos()
  489. self.HomeExtend()
  490. entry = self.GetSelectedText()
  491. self.SetCurrentPos(pos)
  492. return entry
  493. def OnDestroy(self, event):
  494. """!The clipboard contents can be preserved after
  495. the app has exited"""
  496. wx.TheClipboard.Flush()
  497. event.Skip()
  498. def OnCmdErase(self, event):
  499. """!Erase command prompt"""
  500. self.Home()
  501. self.DelLineRight()