prompt.py 22 KB

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