prompt.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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_KEY_DOWN, self.OnKeyPressed)
  138. self.Bind(wx.stc.EVT_STC_AUTOCOMP_SELECTION, self.OnItemSelected)
  139. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemChanged)
  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(GetRealCmd(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 list
  231. """
  232. if not self._updateCmdHistory:
  233. return
  234. # add command to history
  235. self.cmdbuffer.append(' '.join(cmd))
  236. # keep command history to a managable size
  237. if len(self.cmdbuffer) > 200:
  238. del self.cmdbuffer[0]
  239. self.cmdindex = len(self.cmdbuffer)
  240. def EntityToComplete(self):
  241. """!Determines which part of command (flags, parameters) should
  242. be completed at current cursor position"""
  243. entry = self.GetTextLeft()
  244. toComplete = dict()
  245. try:
  246. cmd = entry.split()[0].strip()
  247. except IndexError:
  248. return None
  249. try:
  250. splitted = utils.split(str(entry))
  251. except ValueError: # No closing quotation error
  252. return None
  253. if len(splitted) > 1:
  254. if 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 None
  275. else:
  276. return None
  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. return None
  289. else:
  290. toComplete['entity'] = 'command'
  291. toComplete['cmd'] = cmd
  292. return toComplete
  293. def GetWordLeft(self, withDelimiter = False, ignoredDelimiter = None):
  294. """!Get word left from current cursor position. The beginning
  295. of the word is given by space or chars: .,-=
  296. @param withDelimiter returns the word with the initial delimeter
  297. @param ignoredDelimiter finds the word ignoring certain delimeter
  298. """
  299. textLeft = self.GetTextLeft()
  300. parts = list()
  301. if ignoredDelimiter is None:
  302. ignoredDelimiter = ''
  303. for char in set(' .,-=') - set(ignoredDelimiter):
  304. if not withDelimiter:
  305. delimiter = ''
  306. else:
  307. delimiter = char
  308. parts.append(delimiter + textLeft.rpartition(char)[2])
  309. return min(parts, key=lambda x: len(x))
  310. def ShowList(self):
  311. """!Show sorted auto-completion list if it is not empty"""
  312. if len(self.autoCompList) > 0:
  313. self.autoCompList.sort()
  314. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  315. def OnKeyPressed(self, event):
  316. """!Key press capture for autocompletion, calltips, and command history
  317. @todo event.ControlDown() for manual autocomplete
  318. """
  319. # keycodes used: "." = 46, "=" = 61, "-" = 45
  320. pos = self.GetCurrentPos()
  321. # complete command after pressing '.'
  322. if event.GetKeyCode() == 46 and not event.ShiftDown():
  323. self.autoCompList = list()
  324. entry = self.GetTextLeft()
  325. self.InsertText(pos, '.')
  326. self.CharRight()
  327. self.toComplete = self.EntityToComplete()
  328. if self.toComplete is None:
  329. return
  330. try:
  331. if self.toComplete['entity'] == 'command':
  332. for command in globalvar.grassCmd:
  333. try:
  334. if command.find(self.toComplete['cmd']) == 0:
  335. dotNumber = list(self.toComplete['cmd']).count('.')
  336. self.autoCompList.append(command.split('.',dotNumber)[-1])
  337. except UnicodeDecodeError, e: # TODO: fix it
  338. sys.stderr.write(DecodeString(command) + ": " + unicode(e))
  339. except (KeyError, TypeError):
  340. return
  341. self.ShowList()
  342. # complete flags after pressing '-'
  343. elif event.GetKeyCode() == 45 and not event.ShiftDown():
  344. self.autoCompList = list()
  345. entry = self.GetTextLeft()
  346. self.InsertText(pos, '-')
  347. self.CharRight()
  348. self.toComplete = self.EntityToComplete()
  349. if self.toComplete['entity'] == 'flags' and self.cmdDesc:
  350. if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite
  351. for flag in self.cmdDesc.get_options()['flags']:
  352. if len(flag['name']) == 1:
  353. self.autoCompList.append(flag['name'])
  354. else:
  355. for flag in self.cmdDesc.get_options()['flags']:
  356. if len(flag['name']) > 1:
  357. self.autoCompList.append(flag['name'])
  358. self.ShowList()
  359. # complete map or values after parameter
  360. elif event.GetKeyCode() == 61 and not event.ShiftDown():
  361. self.autoCompList = list()
  362. self.InsertText(pos, '=')
  363. self.CharRight()
  364. self.toComplete = self.EntityToComplete()
  365. if self.toComplete and 'entity' in self.toComplete:
  366. if self.toComplete['entity'] == 'raster map':
  367. self.autoCompList = self.mapList['raster']
  368. elif self.toComplete['entity'] == 'vector map':
  369. self.autoCompList = self.mapList['vector']
  370. elif self.toComplete['entity'] == 'param values':
  371. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  372. self.autoCompList = self.cmdDesc.get_param(param)['values']
  373. self.ShowList()
  374. # complete mapset ('@')
  375. elif event.GetKeyCode() == 50 and event.ShiftDown():
  376. self.autoCompList = list()
  377. self.InsertText(pos, '@')
  378. self.CharRight()
  379. self.toComplete = self.EntityToComplete()
  380. if self.toComplete and self.toComplete['entity'] == 'mapsets':
  381. self.autoCompList = self.mapsetList
  382. self.ShowList()
  383. # complete after pressing CTRL + Space
  384. elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
  385. self.autoCompList = list()
  386. self.toComplete = self.EntityToComplete()
  387. if self.toComplete is None:
  388. return
  389. #complete command
  390. if self.toComplete['entity'] == 'command':
  391. for command in globalvar.grassCmd:
  392. if command.find(self.toComplete['cmd']) == 0:
  393. dotNumber = list(self.toComplete['cmd']).count('.')
  394. self.autoCompList.append(command.split('.',dotNumber)[-1])
  395. # complete flags in such situations (| is cursor):
  396. # r.colors -| ...w, q, l
  397. # r.colors -w| ...w, q, l
  398. elif self.toComplete['entity'] == 'flags' and self.cmdDesc:
  399. for flag in self.cmdDesc.get_options()['flags']:
  400. if len(flag['name']) == 1:
  401. self.autoCompList.append(flag['name'])
  402. # complete parameters in such situations (| is cursor):
  403. # r.colors -w | ...color, map, rast, rules
  404. # r.colors col| ...color
  405. elif self.toComplete['entity'] == 'params' and self.cmdDesc:
  406. for param in self.cmdDesc.get_options()['params']:
  407. if param['name'].find(self.GetWordLeft(withDelimiter=False)) == 0:
  408. self.autoCompList.append(param['name'])
  409. # complete flags or parameters in such situations (| is cursor):
  410. # r.colors | ...-w, -q, -l, color, map, rast, rules
  411. # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules
  412. elif self.toComplete['entity'] == 'params+flags' and self.cmdDesc:
  413. self.autoCompList = list()
  414. for param in self.cmdDesc.get_options()['params']:
  415. self.autoCompList.append(param['name'])
  416. for flag in self.cmdDesc.get_options()['flags']:
  417. if len(flag['name']) == 1:
  418. self.autoCompList.append('-' + flag['name'])
  419. else:
  420. self.autoCompList.append('--' + flag['name'])
  421. self.ShowList()
  422. # complete map or values after parameter
  423. # r.buffer input=| ...list of raster maps
  424. # r.buffer units=| ... feet, kilometers, ...
  425. elif self.toComplete['entity'] == 'raster map':
  426. self.autoCompList = list()
  427. self.autoCompList = self.mapList['raster']
  428. elif self.toComplete['entity'] == 'vector map':
  429. self.autoCompList = list()
  430. self.autoCompList = self.mapList['vector']
  431. elif self.toComplete['entity'] == 'param values':
  432. self.autoCompList = list()
  433. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  434. self.autoCompList = self.cmdDesc.get_param(param)['values']
  435. self.ShowList()
  436. elif event.GetKeyCode() == wx.WXK_TAB:
  437. # show GRASS command calltips (to hide press 'ESC')
  438. entry = self.GetTextLeft()
  439. try:
  440. cmd = entry.split()[0].strip()
  441. except IndexError:
  442. cmd = ''
  443. if cmd not in globalvar.grassCmd:
  444. return
  445. info = gtask.command_info(GetRealCmd(cmd))
  446. self.CallTipSetBackground("#f4f4d1")
  447. self.CallTipSetForeground("BLACK")
  448. self.CallTipShow(pos, info['usage'] + '\n\n' + info['description'])
  449. elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and \
  450. not self.AutoCompActive():
  451. # Command history using up and down
  452. if len(self.cmdbuffer) < 1:
  453. return
  454. self.DocumentEnd()
  455. # move through command history list index values
  456. if event.GetKeyCode() == wx.WXK_UP:
  457. self.cmdindex = self.cmdindex - 1
  458. if event.GetKeyCode() == wx.WXK_DOWN:
  459. self.cmdindex = self.cmdindex + 1
  460. if self.cmdindex < 0:
  461. self.cmdindex = 0
  462. if self.cmdindex > len(self.cmdbuffer) - 1:
  463. self.cmdindex = len(self.cmdbuffer) - 1
  464. try:
  465. txt = self.cmdbuffer[self.cmdindex]
  466. except KeyError:
  467. txt = ''
  468. # clear current line and insert command history
  469. self.DelLineLeft()
  470. self.DelLineRight()
  471. pos = self.GetCurrentPos()
  472. self.InsertText(pos,txt)
  473. self.LineEnd()
  474. self.ShowStatusText('')
  475. elif event.GetKeyCode() in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER) and \
  476. self.AutoCompActive() == False:
  477. # run command on line when <return> is pressed
  478. self._runCmd(self.GetCurLine()[0].strip())
  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()