prompt.py 23 KB

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