prompt.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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(cmd=None, entity=None)
  245. try:
  246. cmd = entry.split()[0].strip()
  247. except IndexError:
  248. return toComplete
  249. try:
  250. splitted = utils.split(str(entry))
  251. except ValueError: # No closing quotation error
  252. return toComplete
  253. if len(splitted) > 0 and cmd in globalvar.grassCmd:
  254. toComplete['cmd'] = cmd
  255. if entry[-1] == ' ':
  256. words = entry.split(' ')
  257. if any(word.startswith('-') for word in words):
  258. toComplete['entity'] = 'params'
  259. else:
  260. toComplete['entity'] = 'params+flags'
  261. else:
  262. # get word left from current position
  263. word = self.GetWordLeft(withDelimiter = True)
  264. if word[0] == '=' and word[-1] == '@':
  265. toComplete['entity'] = 'mapsets'
  266. elif word[0] == '=':
  267. # get name of parameter
  268. paramName = self.GetWordLeft(withDelimiter = False, ignoredDelimiter = '=').strip('=')
  269. if paramName:
  270. try:
  271. param = self.cmdDesc.get_param(paramName)
  272. except (ValueError, AttributeError):
  273. return toComplete
  274. else:
  275. return toComplete
  276. if param['values']:
  277. toComplete['entity'] = 'param values'
  278. elif param['prompt'] == 'raster' and param['element'] == 'cell':
  279. toComplete['entity'] = 'raster map'
  280. elif param['prompt'] == 'vector' and param['element'] == 'vector':
  281. toComplete['entity'] = 'vector map'
  282. elif word[0] == '-':
  283. toComplete['entity'] = 'flags'
  284. elif word[0] == ' ':
  285. toComplete['entity'] = 'params'
  286. else:
  287. toComplete['entity'] = 'command'
  288. toComplete['cmd'] = cmd
  289. return toComplete
  290. def GetWordLeft(self, withDelimiter = False, ignoredDelimiter = None):
  291. """!Get word left from current cursor position. The beginning
  292. of the word is given by space or chars: .,-=
  293. @param withDelimiter returns the word with the initial delimeter
  294. @param ignoredDelimiter finds the word ignoring certain delimeter
  295. """
  296. textLeft = self.GetTextLeft()
  297. parts = list()
  298. if ignoredDelimiter is None:
  299. ignoredDelimiter = ''
  300. for char in set(' .,-=') - set(ignoredDelimiter):
  301. if not withDelimiter:
  302. delimiter = ''
  303. else:
  304. delimiter = char
  305. parts.append(delimiter + textLeft.rpartition(char)[2])
  306. return min(parts, key=lambda x: len(x))
  307. def ShowList(self):
  308. """!Show sorted auto-completion list if it is not empty"""
  309. if len(self.autoCompList) > 0:
  310. self.autoCompList.sort()
  311. self.AutoCompShow(lenEntered = 0, itemList = ' '.join(self.autoCompList))
  312. def OnKeyPressed(self, event):
  313. """!Key press capture for autocompletion, calltips, and command history
  314. @todo event.ControlDown() for manual autocomplete
  315. """
  316. # keycodes used: "." = 46, "=" = 61, "-" = 45
  317. pos = self.GetCurrentPos()
  318. # complete command after pressing '.'
  319. if event.GetKeyCode() == 46 and not event.ShiftDown():
  320. self.autoCompList = list()
  321. entry = self.GetTextLeft()
  322. self.InsertText(pos, '.')
  323. self.CharRight()
  324. self.toComplete = self.EntityToComplete()
  325. try:
  326. if self.toComplete['entity'] == 'command':
  327. for command in globalvar.grassCmd:
  328. try:
  329. if command.find(self.toComplete['cmd']) == 0:
  330. dotNumber = list(self.toComplete['cmd']).count('.')
  331. self.autoCompList.append(command.split('.',dotNumber)[-1])
  332. except UnicodeDecodeError, e: # TODO: fix it
  333. sys.stderr.write(DecodeString(command) + ": " + unicode(e))
  334. except (KeyError, TypeError):
  335. return
  336. self.ShowList()
  337. # complete flags after pressing '-'
  338. elif event.GetKeyCode() == 45 and not event.ShiftDown():
  339. self.autoCompList = list()
  340. entry = self.GetTextLeft()
  341. self.InsertText(pos, '-')
  342. self.CharRight()
  343. self.toComplete = self.EntityToComplete()
  344. if self.toComplete['entity'] == 'flags' and self.cmdDesc:
  345. if self.GetTextLeft()[-2:] == ' -': # complete e.g. --quite
  346. for flag in self.cmdDesc.get_options()['flags']:
  347. if len(flag['name']) == 1:
  348. self.autoCompList.append(flag['name'])
  349. else:
  350. for flag in self.cmdDesc.get_options()['flags']:
  351. if len(flag['name']) > 1:
  352. self.autoCompList.append(flag['name'])
  353. self.ShowList()
  354. # complete map or values after parameter
  355. elif event.GetKeyCode() == 61 and not event.ShiftDown():
  356. self.autoCompList = list()
  357. self.InsertText(pos, '=')
  358. self.CharRight()
  359. self.toComplete = self.EntityToComplete()
  360. if self.toComplete['entity'] == 'raster map':
  361. self.autoCompList = self.mapList['raster']
  362. elif self.toComplete['entity'] == 'vector map':
  363. self.autoCompList = self.mapList['vector']
  364. elif self.toComplete['entity'] == 'param values':
  365. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  366. self.autoCompList = self.cmdDesc.get_param(param)['values']
  367. self.ShowList()
  368. # complete mapset ('@')
  369. elif event.GetKeyCode() == 50 and event.ShiftDown():
  370. self.autoCompList = list()
  371. self.InsertText(pos, '@')
  372. self.CharRight()
  373. self.toComplete = self.EntityToComplete()
  374. if self.toComplete['entity'] == 'mapsets':
  375. self.autoCompList = self.mapsetList
  376. self.ShowList()
  377. # complete after pressing CTRL + Space
  378. elif event.GetKeyCode() == wx.WXK_SPACE and event.ControlDown():
  379. self.autoCompList = list()
  380. self.toComplete = self.EntityToComplete()
  381. #complete command
  382. if self.toComplete['entity'] == 'command':
  383. for command in globalvar.grassCmd:
  384. if command.find(self.toComplete['cmd']) == 0:
  385. dotNumber = list(self.toComplete['cmd']).count('.')
  386. self.autoCompList.append(command.split('.',dotNumber)[-1])
  387. # complete flags in such situations (| is cursor):
  388. # r.colors -| ...w, q, l
  389. # r.colors -w| ...w, q, l
  390. elif self.toComplete['entity'] == 'flags' and self.cmdDesc:
  391. for flag in self.cmdDesc.get_options()['flags']:
  392. if len(flag['name']) == 1:
  393. self.autoCompList.append(flag['name'])
  394. # complete parameters in such situations (| is cursor):
  395. # r.colors -w | ...color, map, rast, rules
  396. # r.colors col| ...color
  397. elif self.toComplete['entity'] == 'params' and self.cmdDesc:
  398. for param in self.cmdDesc.get_options()['params']:
  399. if param['name'].find(self.GetWordLeft(withDelimiter=False)) == 0:
  400. self.autoCompList.append(param['name'])
  401. # complete flags or parameters in such situations (| is cursor):
  402. # r.colors | ...-w, -q, -l, color, map, rast, rules
  403. # r.colors color=grey | ...-w, -q, -l, color, map, rast, rules
  404. elif self.toComplete['entity'] == 'params+flags' and self.cmdDesc:
  405. self.autoCompList = list()
  406. for param in self.cmdDesc.get_options()['params']:
  407. self.autoCompList.append(param['name'])
  408. for flag in self.cmdDesc.get_options()['flags']:
  409. if len(flag['name']) == 1:
  410. self.autoCompList.append('-' + flag['name'])
  411. else:
  412. self.autoCompList.append('--' + flag['name'])
  413. self.ShowList()
  414. # complete map or values after parameter
  415. # r.buffer input=| ...list of raster maps
  416. # r.buffer units=| ... feet, kilometers, ...
  417. elif self.toComplete['entity'] == 'raster map':
  418. self.autoCompList = list()
  419. self.autoCompList = self.mapList['raster']
  420. elif self.toComplete['entity'] == 'vector map':
  421. self.autoCompList = list()
  422. self.autoCompList = self.mapList['vector']
  423. elif self.toComplete['entity'] == 'param values':
  424. self.autoCompList = list()
  425. param = self.GetWordLeft(withDelimiter = False, ignoredDelimiter='=').strip(' =')
  426. self.autoCompList = self.cmdDesc.get_param(param)['values']
  427. self.ShowList()
  428. elif event.GetKeyCode() == wx.WXK_TAB:
  429. # show GRASS command calltips (to hide press 'ESC')
  430. entry = self.GetTextLeft()
  431. try:
  432. cmd = entry.split()[0].strip()
  433. except IndexError:
  434. cmd = ''
  435. if cmd not in globalvar.grassCmd:
  436. return
  437. info = gtask.command_info(GetRealCmd(cmd))
  438. self.CallTipSetBackground("#f4f4d1")
  439. self.CallTipSetForeground("BLACK")
  440. self.CallTipShow(pos, info['usage'] + '\n\n' + info['description'])
  441. elif event.GetKeyCode() in [wx.WXK_UP, wx.WXK_DOWN] and \
  442. not self.AutoCompActive():
  443. # Command history using up and down
  444. if len(self.cmdbuffer) < 1:
  445. return
  446. self.DocumentEnd()
  447. # move through command history list index values
  448. if event.GetKeyCode() == wx.WXK_UP:
  449. self.cmdindex = self.cmdindex - 1
  450. if event.GetKeyCode() == wx.WXK_DOWN:
  451. self.cmdindex = self.cmdindex + 1
  452. if self.cmdindex < 0:
  453. self.cmdindex = 0
  454. if self.cmdindex > len(self.cmdbuffer) - 1:
  455. self.cmdindex = len(self.cmdbuffer) - 1
  456. try:
  457. txt = self.cmdbuffer[self.cmdindex]
  458. except KeyError:
  459. txt = ''
  460. # clear current line and insert command history
  461. self.DelLineLeft()
  462. self.DelLineRight()
  463. pos = self.GetCurrentPos()
  464. self.InsertText(pos,txt)
  465. self.LineEnd()
  466. self.ShowStatusText('')
  467. elif event.GetKeyCode() in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER) and \
  468. self.AutoCompActive() == False:
  469. # run command on line when <return> is pressed
  470. self._runCmd(self.GetCurLine()[0].strip())
  471. elif event.GetKeyCode() == wx.WXK_SPACE:
  472. items = self.GetTextLeft().split()
  473. if len(items) == 1:
  474. cmd = items[0].strip()
  475. if cmd in globalvar.grassCmd and \
  476. (not self.cmdDesc or cmd != self.cmdDesc.get_name()):
  477. try:
  478. self.cmdDesc = gtask.parse_interface(GetRealCmd(cmd))
  479. except IOError:
  480. self.cmdDesc = None
  481. event.Skip()
  482. else:
  483. event.Skip()
  484. def ShowStatusText(self, text):
  485. """!Requests showing of notification, e.g. showing in a statusbar."""
  486. self.showNotification.emit(message=text)
  487. def GetTextLeft(self):
  488. """!Returns all text left of the caret"""
  489. pos = self.GetCurrentPos()
  490. self.HomeExtend()
  491. entry = self.GetSelectedText()
  492. self.SetCurrentPos(pos)
  493. return entry
  494. def OnDestroy(self, event):
  495. """!The clipboard contents can be preserved after
  496. the app has exited"""
  497. wx.TheClipboard.Flush()
  498. event.Skip()
  499. def OnCmdErase(self, event):
  500. """!Erase command prompt"""
  501. self.Home()
  502. self.DelLineRight()