prompt.py 23 KB

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