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