prompt.py 22 KB

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