prompt.py 22 KB

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