prompt.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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.SetUseHorizontalScrollBar(True)
  135. # support light and dark mode
  136. bg_color = wx.SystemSettings().GetColour(wx.SYS_COLOUR_WINDOW)
  137. fg_color = wx.SystemSettings().GetColour(wx.SYS_COLOUR_WINDOWTEXT)
  138. selection_color = wx.SystemSettings().GetColour(wx.SYS_COLOUR_HIGHLIGHT)
  139. self.StyleSetBackground(wx.stc.STC_STYLE_DEFAULT, bg_color)
  140. self.StyleSetForeground(wx.stc.STC_STYLE_DEFAULT, fg_color)
  141. self.SetCaretForeground(fg_color)
  142. self.SetSelBackground(True, selection_color)
  143. self.StyleClearAll()
  144. #
  145. # bindings
  146. #
  147. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  148. self.Bind(wx.EVT_CHAR, self.OnChar)
  149. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  150. self.Bind(wx.stc.EVT_STC_AUTOCOMP_SELECTION, self.OnItemSelected)
  151. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemChanged)
  152. if sys.platform != 'darwin': # unstable on Mac with wxPython 3
  153. self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
  154. # signal which requests showing of a notification
  155. self.showNotification = Signal('GPromptSTC.showNotification')
  156. # signal to notify selected command
  157. self.commandSelected = Signal('GPromptSTC.commandSelected')
  158. def OnTextSelectionChanged(self, event):
  159. """Copy selected text to clipboard and skip event.
  160. The same function is in GStc class (goutput.py).
  161. """
  162. wx.CallAfter(self.Copy)
  163. event.Skip()
  164. def OnItemChanged(self, event):
  165. """Change text in statusbar
  166. if the item selection in the auto-completion list is changed"""
  167. # list of commands
  168. if self.toComplete['entity'] == 'command':
  169. item = self.toComplete['cmd'].rpartition(
  170. '.')[0] + '.' + self.autoCompList[event.GetIndex()]
  171. try:
  172. nodes = self._menuModel.SearchNodes(key='command', value=item)
  173. desc = ''
  174. if nodes:
  175. self.commandSelected.emit(command=item)
  176. desc = nodes[0].data['description']
  177. except KeyError:
  178. desc = ''
  179. self.ShowStatusText(desc)
  180. # list of flags
  181. elif self.toComplete['entity'] == 'flags':
  182. desc = self.cmdDesc.get_flag(
  183. self.autoCompList[
  184. event.GetIndex()])['description']
  185. self.ShowStatusText(desc)
  186. # list of parameters
  187. elif self.toComplete['entity'] == 'params':
  188. item = self.cmdDesc.get_param(self.autoCompList[event.GetIndex()])
  189. desc = item['name'] + '=' + item['type']
  190. if not item['required']:
  191. desc = '[' + desc + ']'
  192. desc += ': ' + item['description']
  193. self.ShowStatusText(desc)
  194. # list of flags and commands
  195. elif self.toComplete['entity'] == 'params+flags':
  196. if self.autoCompList[event.GetIndex()][0] == '-':
  197. desc = self.cmdDesc.get_flag(
  198. self.autoCompList[
  199. event.GetIndex()].strip('-'))['description']
  200. else:
  201. item = self.cmdDesc.get_param(
  202. self.autoCompList[event.GetIndex()])
  203. desc = item['name'] + '=' + item['type']
  204. if not item['required']:
  205. desc = '[' + desc + ']'
  206. desc += ': ' + item['description']
  207. self.ShowStatusText(desc)
  208. else:
  209. self.ShowStatusText('')
  210. def OnItemSelected(self, event):
  211. """Item selected from the list"""
  212. lastWord = self.GetWordLeft()
  213. # to insert selection correctly if selected word partly matches written
  214. # text
  215. match = difflib.SequenceMatcher(None, event.GetText(), lastWord)
  216. matchTuple = match.find_longest_match(
  217. 0, len(event.GetText()), 0, len(lastWord))
  218. compl = event.GetText()[matchTuple[2]:]
  219. text = self.GetTextLeft() + compl
  220. # add space or '=' at the end
  221. end = '='
  222. for char in ('.', '-', '='):
  223. if text.split(' ')[-1].find(char) >= 0:
  224. end = ' '
  225. compl += end
  226. text += end
  227. self.AddText(compl)
  228. pos = len(text)
  229. self.SetCurrentPos(pos)
  230. cmd = text.strip().split(' ')[0]
  231. if not self.cmdDesc or cmd != self.cmdDesc.get_name():
  232. try:
  233. self.cmdDesc = gtask.parse_interface(cmd)
  234. except IOError:
  235. self.cmdDesc = None
  236. def OnKillFocus(self, event):
  237. """Hides autocomplete"""
  238. # hide autocomplete
  239. if self.AutoCompActive():
  240. self.AutoCompCancel()
  241. event.Skip()
  242. def SetTextAndFocus(self, text):
  243. pos = len(text)
  244. self.commandSelected.emit(command=text)
  245. self.SetText(text)
  246. self.SetSelectionStart(pos)
  247. self.SetCurrentPos(pos)
  248. self.SetFocus()
  249. def UpdateCmdHistory(self, cmd):
  250. """Update command history
  251. :param cmd: command given as a string
  252. """
  253. # add command to history
  254. self.cmdbuffer.append(cmd)
  255. # update also traced commands
  256. self.commands.append(cmd)
  257. # keep command history to a managable size
  258. if len(self.cmdbuffer) > 200:
  259. del self.cmdbuffer[0]
  260. self.cmdindex = len(self.cmdbuffer)
  261. def EntityToComplete(self):
  262. """Determines which part of command (flags, parameters) should
  263. be completed at current cursor position"""
  264. entry = self.GetTextLeft()
  265. toComplete = dict(cmd=None, entity=None)
  266. try:
  267. cmd = entry.split()[0].strip()
  268. except IndexError:
  269. return toComplete
  270. try:
  271. splitted = utils.split(str(entry))
  272. except ValueError: # No closing quotation error
  273. return toComplete
  274. if len(splitted) > 0 and cmd in globalvar.grassCmd:
  275. toComplete['cmd'] = cmd
  276. if entry[-1] == ' ':
  277. words = entry.split(' ')
  278. if any(word.startswith('-') for word in words):
  279. toComplete['entity'] = 'params'
  280. else:
  281. toComplete['entity'] = 'params+flags'
  282. else:
  283. # get word left from current position
  284. word = self.GetWordLeft(withDelimiter=True)
  285. if word[0] == '=' and word[-1] == '@':
  286. toComplete['entity'] = 'mapsets'
  287. elif word[0] == '=':
  288. # get name of parameter
  289. paramName = self.GetWordLeft(
  290. withDelimiter=False, ignoredDelimiter='=').strip('=')
  291. if paramName:
  292. try:
  293. param = self.cmdDesc.get_param(paramName)
  294. except (ValueError, AttributeError):
  295. return toComplete
  296. else:
  297. return toComplete
  298. if param['values']:
  299. toComplete['entity'] = 'param values'
  300. elif param['prompt'] == 'raster' and param['element'] == 'cell':
  301. toComplete['entity'] = 'raster map'
  302. elif param['prompt'] == 'vector' and param['element'] == 'vector':
  303. toComplete['entity'] = 'vector map'
  304. elif word[0] == '-':
  305. toComplete['entity'] = 'flags'
  306. elif word[0] == ' ':
  307. toComplete['entity'] = 'params'
  308. else:
  309. toComplete['entity'] = 'command'
  310. toComplete['cmd'] = cmd
  311. return toComplete
  312. def GetWordLeft(self, withDelimiter=False, ignoredDelimiter=None):
  313. """Get word left from current cursor position. The beginning
  314. of the word is given by space or chars: .,-=
  315. :param withDelimiter: returns the word with the initial delimeter
  316. :param ignoredDelimiter: finds the word ignoring certain delimeter
  317. """
  318. textLeft = self.GetTextLeft()
  319. parts = list()
  320. if ignoredDelimiter is None:
  321. ignoredDelimiter = ''
  322. for char in set(' .,-=') - set(ignoredDelimiter):
  323. if not withDelimiter:
  324. delimiter = ''
  325. else:
  326. delimiter = char
  327. parts.append(delimiter + textLeft.rpartition(char)[2])
  328. return min(parts, key=lambda x: len(x))
  329. def ShowList(self):
  330. """Show sorted auto-completion list if it is not empty"""
  331. if len(self.autoCompList) > 0:
  332. self.autoCompList.sort()
  333. self.AutoCompShow(0, itemList=' '.join(self.autoCompList))
  334. def OnKeyPressed(self, event):
  335. """Key pressed capture special treatment for tabulator to show help"""
  336. pos = self.GetCurrentPos()
  337. if event.GetKeyCode() == wx.WXK_TAB:
  338. # show GRASS command calltips (to hide press 'ESC')
  339. entry = self.GetTextLeft()
  340. try:
  341. cmd = entry.split()[0].strip()
  342. except IndexError:
  343. cmd = ''
  344. if cmd not in globalvar.grassCmd:
  345. return
  346. info = gtask.command_info(cmd)
  347. self.CallTipSetBackground("#f4f4d1")
  348. self.CallTipSetForeground("BLACK")
  349. self.CallTipShow(pos, info['usage'] + '\n\n' + info['description'])
  350. elif event.GetKeyCode() in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER) and \
  351. not self.AutoCompActive():
  352. # run command on line when <return> is pressed
  353. self._runCmd(self.GetCurLine()[0].strip())
  354. elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and \
  355. not self.AutoCompActive():
  356. # Command history using up and down
  357. if len(self.cmdbuffer) < 1:
  358. return
  359. self.DocumentEnd()
  360. # move through command history list index values
  361. if event.GetKeyCode() == wx.WXK_UP:
  362. self.cmdindex = self.cmdindex - 1
  363. if event.GetKeyCode() == wx.WXK_DOWN:
  364. self.cmdindex = self.cmdindex + 1
  365. if self.cmdindex < 0:
  366. self.cmdindex = 0
  367. if self.cmdindex > len(self.cmdbuffer) - 1:
  368. self.cmdindex = len(self.cmdbuffer) - 1
  369. try:
  370. # without strip causes problem on windows
  371. txt = self.cmdbuffer[self.cmdindex].strip()
  372. except KeyError:
  373. txt = ''
  374. # clear current line and insert command history
  375. self.DelLineLeft()
  376. self.DelLineRight()
  377. pos = self.GetCurrentPos()
  378. self.InsertText(pos, txt)
  379. self.LineEnd()
  380. self.ShowStatusText('')
  381. else:
  382. event.Skip()
  383. def OnChar(self, event):
  384. """Key char capture for autocompletion, calltips, and command history
  385. .. todo::
  386. event.ControlDown() for manual autocomplete
  387. """
  388. # keycodes used: "." = 46, "=" = 61, "-" = 45
  389. pos = self.GetCurrentPos()
  390. # complete command after pressing '.'
  391. if event.GetKeyCode() == 46:
  392. self.autoCompList = list()
  393. entry = self.GetTextLeft()
  394. self.InsertText(pos, '.')
  395. self.CharRight()
  396. self.toComplete = self.EntityToComplete()
  397. try:
  398. if self.toComplete['entity'] == 'command':
  399. for command in globalvar.grassCmd:
  400. try:
  401. if command.find(self.toComplete['cmd']) == 0:
  402. dotNumber = list(
  403. self.toComplete['cmd']).count('.')
  404. self.autoCompList.append(
  405. command.split('.', dotNumber)[-1])
  406. except UnicodeDecodeError as error:
  407. sys.stderr.write(
  408. DecodeString(command) + ": " + str(error))
  409. except (KeyError, TypeError):
  410. return
  411. self.ShowList()
  412. # complete flags after pressing '-'
  413. elif (event.GetKeyCode() == 45) \
  414. or event.GetKeyCode() == wx.WXK_NUMPAD_SUBTRACT \
  415. or event.GetKeyCode() == wx.WXK_SUBTRACT:
  416. self.autoCompList = list()
  417. entry = self.GetTextLeft()
  418. self.InsertText(pos, '-')
  419. self.CharRight()
  420. self.toComplete = self.EntityToComplete()
  421. if self.toComplete['entity'] == 'flags' and self.cmdDesc:
  422. if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite
  423. for flag in self.cmdDesc.get_options()['flags']:
  424. if len(flag['name']) == 1:
  425. self.autoCompList.append(flag['name'])
  426. else:
  427. for flag in self.cmdDesc.get_options()['flags']:
  428. if len(flag['name']) > 1:
  429. self.autoCompList.append(flag['name'])
  430. self.ShowList()
  431. # complete map or values after parameter
  432. elif event.GetKeyCode() == 61:
  433. self.autoCompList = list()
  434. self.InsertText(pos, '=')
  435. self.CharRight()
  436. self.toComplete = self.EntityToComplete()
  437. if self.toComplete['entity'] == 'raster map':
  438. self.autoCompList = self.mapList['raster']
  439. elif self.toComplete['entity'] == 'vector map':
  440. self.autoCompList = self.mapList['vector']
  441. elif self.toComplete['entity'] == 'param values':
  442. param = self.GetWordLeft(
  443. withDelimiter=False,
  444. ignoredDelimiter='=').strip(' =')
  445. self.autoCompList = self.cmdDesc.get_param(param)['values']
  446. self.ShowList()
  447. # complete mapset ('@')
  448. elif event.GetKeyCode() == 64:
  449. self.autoCompList = list()
  450. self.InsertText(pos, '@')
  451. self.CharRight()
  452. self.toComplete = self.EntityToComplete()
  453. if self.toComplete['entity'] == 'mapsets':
  454. self.autoCompList = self.mapsetList
  455. self.ShowList()
  456. # complete after pressing CTRL + Space
  457. elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
  458. self.autoCompList = list()
  459. self.toComplete = self.EntityToComplete()
  460. # complete command
  461. if self.toComplete['entity'] == 'command':
  462. for command in globalvar.grassCmd:
  463. if command.find(self.toComplete['cmd']) == 0:
  464. dotNumber = list(self.toComplete['cmd']).count('.')
  465. self.autoCompList.append(
  466. command.split('.', dotNumber)[-1])
  467. # complete flags in such situations (| is cursor):
  468. # r.colors -| ...w, q, l
  469. # r.colors -w| ...w, q, l
  470. elif self.toComplete['entity'] == 'flags' and self.cmdDesc:
  471. for flag in self.cmdDesc.get_options()['flags']:
  472. if len(flag['name']) == 1:
  473. self.autoCompList.append(flag['name'])
  474. # complete parameters in such situations (| is cursor):
  475. # r.colors -w | ...color, map, rast, rules
  476. # r.colors col| ...color
  477. elif self.toComplete['entity'] == 'params' and self.cmdDesc:
  478. for param in self.cmdDesc.get_options()['params']:
  479. if param['name'].find(
  480. self.GetWordLeft(withDelimiter=False)) == 0:
  481. self.autoCompList.append(param['name'])
  482. # complete flags or parameters in such situations (| is cursor):
  483. # r.colors | ...-w, -q, -l, color, map, rast, rules
  484. # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules
  485. elif self.toComplete['entity'] == 'params+flags' and self.cmdDesc:
  486. self.autoCompList = list()
  487. for param in self.cmdDesc.get_options()['params']:
  488. self.autoCompList.append(param['name'])
  489. for flag in self.cmdDesc.get_options()['flags']:
  490. if len(flag['name']) == 1:
  491. self.autoCompList.append('-' + flag['name'])
  492. else:
  493. self.autoCompList.append('--' + flag['name'])
  494. self.ShowList()
  495. # complete map or values after parameter
  496. # r.buffer input=| ...list of raster maps
  497. # r.buffer units=| ... feet, kilometers, ...
  498. elif self.toComplete['entity'] == 'raster map':
  499. self.autoCompList = list()
  500. self.autoCompList = self.mapList['raster']
  501. elif self.toComplete['entity'] == 'vector map':
  502. self.autoCompList = list()
  503. self.autoCompList = self.mapList['vector']
  504. elif self.toComplete['entity'] == 'param values':
  505. self.autoCompList = list()
  506. param = self.GetWordLeft(
  507. withDelimiter=False,
  508. ignoredDelimiter='=').strip(' =')
  509. self.autoCompList = self.cmdDesc.get_param(param)['values']
  510. self.ShowList()
  511. elif event.GetKeyCode() == wx.WXK_SPACE:
  512. items = self.GetTextLeft().split()
  513. if len(items) == 1:
  514. cmd = items[0].strip()
  515. if cmd in globalvar.grassCmd and \
  516. (not self.cmdDesc or cmd != self.cmdDesc.get_name()):
  517. try:
  518. self.cmdDesc = gtask.parse_interface(cmd)
  519. except IOError:
  520. self.cmdDesc = None
  521. event.Skip()
  522. else:
  523. event.Skip()
  524. def ShowStatusText(self, text):
  525. """Requests showing of notification, e.g. showing in a statusbar."""
  526. self.showNotification.emit(message=text)
  527. def GetTextLeft(self):
  528. """Returns all text left of the caret"""
  529. pos = self.GetCurrentPos()
  530. self.HomeExtend()
  531. entry = self.GetSelectedText()
  532. self.SetCurrentPos(pos)
  533. return entry
  534. def OnDestroy(self, event):
  535. """The clipboard contents can be preserved after
  536. the app has exited"""
  537. if wx.TheClipboard.IsOpened():
  538. wx.TheClipboard.Flush()
  539. event.Skip()
  540. def OnCmdErase(self, event):
  541. """Erase command prompt"""
  542. self.Home()
  543. self.DelLineRight()