prompt.py 22 KB

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