prompt.py 22 KB

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