prompt.py 23 KB

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