prompt.py 23 KB

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