prompt.py 22 KB

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