gconsole.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. """
  2. @package core.gconsole
  3. @brief Command output widgets
  4. Classes:
  5. - goutput::CmdThread
  6. - goutput::GStdout
  7. - goutput::GStderr
  8. - goutput::GConsole
  9. (C) 2007-2015 by the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. @author Michael Barton (Arizona State University)
  13. @author Martin Landa <landa.martin gmail.com>
  14. @author Vaclav Petras <wenzeslaus gmail.com> (refactoring)
  15. @author Anna Kratochvilova <kratochanna gmail.com> (refactoring)
  16. @author Wolf Bergenheim <wolf bergenheim.net> (#962)
  17. """
  18. from __future__ import print_function
  19. import os
  20. import sys
  21. import re
  22. import time
  23. import threading
  24. if sys.version_info.major == 2:
  25. import Queue
  26. else:
  27. import queue as Queue
  28. import codecs
  29. import locale
  30. import wx
  31. from wx.lib.newevent import NewEvent
  32. import grass.script as grass
  33. from grass.script import task as gtask
  34. from grass.pydispatch.signal import Signal
  35. from core import globalvar
  36. from core.gcmd import CommandThread, GError, GException
  37. from gui_core.forms import GUI
  38. from core.debug import Debug
  39. from core.settings import UserSettings
  40. from core.giface import Notification
  41. from gui_core.widgets import FormNotebook
  42. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  43. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  44. wxCmdRun, EVT_CMD_RUN = NewEvent()
  45. wxCmdDone, EVT_CMD_DONE = NewEvent()
  46. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  47. wxCmdPrepare, EVT_CMD_PREPARE = NewEvent()
  48. def GrassCmd(cmd, env=None, stdout=None, stderr=None):
  49. """Return GRASS command thread"""
  50. return CommandThread(cmd, env=env, stdout=stdout, stderr=stderr)
  51. class CmdThread(threading.Thread):
  52. """Thread for GRASS commands"""
  53. requestId = 0
  54. def __init__(self, receiver, requestQ=None, resultQ=None, **kwds):
  55. """
  56. :param receiver: event receiver (used in PostEvent)
  57. """
  58. threading.Thread.__init__(self, **kwds)
  59. if requestQ is None:
  60. self.requestQ = Queue.Queue()
  61. else:
  62. self.requestQ = requestQ
  63. if resultQ is None:
  64. self.resultQ = Queue.Queue()
  65. else:
  66. self.resultQ = resultQ
  67. self.setDaemon(True)
  68. self.requestCmd = None
  69. self.receiver = receiver
  70. self._want_abort_all = False
  71. self.start()
  72. def RunCmd(self, *args, **kwds):
  73. """Run command in queue
  74. :param args: unnamed command arguments
  75. :param kwds: named command arguments
  76. :return: request id in queue
  77. """
  78. CmdThread.requestId += 1
  79. self.requestCmd = None
  80. self.requestQ.put((CmdThread.requestId, args, kwds))
  81. return CmdThread.requestId
  82. def GetId(self):
  83. """Get id for next command"""
  84. return CmdThread.requestId + 1
  85. def SetId(self, id):
  86. """Set starting id"""
  87. CmdThread.requestId = id
  88. def run(self):
  89. os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
  90. while True:
  91. requestId, args, kwds = self.requestQ.get()
  92. for key in (
  93. "callable",
  94. "onDone",
  95. "onPrepare",
  96. "userData",
  97. "addLayer",
  98. "notification",
  99. ):
  100. if key in kwds:
  101. vars()[key] = kwds[key]
  102. del kwds[key]
  103. else:
  104. vars()[key] = None
  105. if not vars()["callable"]:
  106. vars()["callable"] = GrassCmd
  107. requestTime = time.time()
  108. # prepare
  109. if self.receiver:
  110. event = wxCmdPrepare(
  111. cmd=args[0],
  112. time=requestTime,
  113. pid=requestId,
  114. onPrepare=vars()["onPrepare"],
  115. userData=vars()["userData"],
  116. )
  117. wx.PostEvent(self.receiver, event)
  118. # run command
  119. event = wxCmdRun(
  120. cmd=args[0], pid=requestId, notification=vars()["notification"]
  121. )
  122. wx.PostEvent(self.receiver, event)
  123. time.sleep(0.1)
  124. self.requestCmd = vars()["callable"](*args, **kwds)
  125. if self._want_abort_all and self.requestCmd is not None:
  126. self.requestCmd.abort()
  127. if self.requestQ.empty():
  128. self._want_abort_all = False
  129. self.resultQ.put((requestId, self.requestCmd.run()))
  130. try:
  131. returncode = self.requestCmd.module.returncode
  132. except AttributeError:
  133. returncode = 0 # being optimistic
  134. try:
  135. aborted = self.requestCmd.aborted
  136. except AttributeError:
  137. aborted = False
  138. time.sleep(0.1)
  139. # set default color table for raster data
  140. if (
  141. UserSettings.Get(
  142. group="rasterLayer", key="colorTable", subkey="enabled"
  143. )
  144. and args[0][0][:2] == "r."
  145. ):
  146. colorTable = UserSettings.Get(
  147. group="rasterLayer", key="colorTable", subkey="selection"
  148. )
  149. mapName = None
  150. if args[0][0] == "r.mapcalc":
  151. try:
  152. mapName = args[0][1].split("=", 1)[0].strip()
  153. except KeyError:
  154. pass
  155. else:
  156. moduleInterface = GUI(show=None).ParseCommand(args[0])
  157. outputParam = moduleInterface.get_param(
  158. value="output", raiseError=False
  159. )
  160. if outputParam and outputParam["prompt"] == "raster":
  161. mapName = outputParam["value"]
  162. if mapName:
  163. argsColor = list(args)
  164. argsColor[0] = [
  165. "r.colors",
  166. "map=%s" % mapName,
  167. "color=%s" % colorTable,
  168. ]
  169. self.requestCmdColor = vars()["callable"](*argsColor, **kwds)
  170. self.resultQ.put((requestId, self.requestCmdColor.run()))
  171. if self.receiver:
  172. event = wxCmdDone(
  173. cmd=args[0],
  174. aborted=aborted,
  175. returncode=returncode,
  176. time=requestTime,
  177. pid=requestId,
  178. onDone=vars()["onDone"],
  179. userData=vars()["userData"],
  180. addLayer=vars()["addLayer"],
  181. notification=vars()["notification"],
  182. )
  183. # send event
  184. wx.PostEvent(self.receiver, event)
  185. def abort(self, abortall=True):
  186. """Abort command(s)"""
  187. if abortall:
  188. self._want_abort_all = True
  189. if self.requestCmd is not None:
  190. self.requestCmd.abort()
  191. if self.requestQ.empty():
  192. self._want_abort_all = False
  193. class GStdout:
  194. """GConsole standard output
  195. Based on FrameOutErr.py
  196. Name: FrameOutErr.py
  197. Purpose: Redirecting stdout / stderr
  198. Author: Jean-Michel Fauth, Switzerland
  199. Copyright: (c) 2005-2007 Jean-Michel Fauth
  200. Licence: GPL
  201. """
  202. def __init__(self, receiver):
  203. """
  204. :param receiver: event receiver (used in PostEvent)
  205. """
  206. self.receiver = receiver
  207. def flush(self):
  208. pass
  209. def write(self, s):
  210. if len(s) == 0 or s == "\n":
  211. return
  212. for line in s.splitlines():
  213. if len(line) == 0:
  214. continue
  215. evt = wxCmdOutput(text=line + "\n", type="")
  216. wx.PostEvent(self.receiver, evt)
  217. class GStderr:
  218. """GConsole standard error output
  219. Based on FrameOutErr.py
  220. Name: FrameOutErr.py
  221. Purpose: Redirecting stdout / stderr
  222. Author: Jean-Michel Fauth, Switzerland
  223. Copyright: (c) 2005-2007 Jean-Michel Fauth
  224. Licence: GPL
  225. """
  226. def __init__(self, receiver):
  227. """
  228. :param receiver: event receiver (used in PostEvent)
  229. """
  230. self.receiver = receiver
  231. self.type = ""
  232. self.message = ""
  233. self.printMessage = False
  234. def flush(self):
  235. pass
  236. def write(self, s):
  237. if "GtkPizza" in s:
  238. return
  239. # remove/replace escape sequences '\b' or '\r' from stream
  240. progressValue = -1
  241. for line in s.splitlines():
  242. if len(line) == 0:
  243. continue
  244. if "GRASS_INFO_PERCENT" in line:
  245. value = int(line.rsplit(":", 1)[1].strip())
  246. if value >= 0 and value < 100:
  247. progressValue = value
  248. else:
  249. progressValue = 0
  250. elif "GRASS_INFO_MESSAGE" in line:
  251. self.type = "message"
  252. self.message += line.split(":", 1)[1].strip() + "\n"
  253. elif "GRASS_INFO_WARNING" in line:
  254. self.type = "warning"
  255. self.message += line.split(":", 1)[1].strip() + "\n"
  256. elif "GRASS_INFO_ERROR" in line:
  257. self.type = "error"
  258. self.message += line.split(":", 1)[1].strip() + "\n"
  259. elif "GRASS_INFO_END" in line:
  260. self.printMessage = True
  261. elif self.type == "":
  262. if len(line) == 0:
  263. continue
  264. evt = wxCmdOutput(text=line, type="")
  265. wx.PostEvent(self.receiver, evt)
  266. elif len(line) > 0:
  267. self.message += line.strip() + "\n"
  268. if self.printMessage and len(self.message) > 0:
  269. evt = wxCmdOutput(text=self.message, type=self.type)
  270. wx.PostEvent(self.receiver, evt)
  271. self.type = ""
  272. self.message = ""
  273. self.printMessage = False
  274. # update progress message
  275. if progressValue > -1:
  276. # self.gmgauge.SetValue(progressValue)
  277. evt = wxCmdProgress(value=progressValue)
  278. wx.PostEvent(self.receiver, evt)
  279. # Occurs when an ignored command is called.
  280. # Attribute cmd contains command (as a list).
  281. gIgnoredCmdRun, EVT_IGNORED_CMD_RUN = NewEvent()
  282. class GConsole(wx.EvtHandler):
  283. """Backend for command execution, esp. interactive command execution"""
  284. def __init__(self, guiparent=None, giface=None, ignoredCmdPattern=None):
  285. """
  286. :param guiparent: parent window for created GUI objects
  287. :param lmgr: layer manager window (TODO: replace by giface)
  288. :param ignoredCmdPattern: regular expression specifying commads
  289. to be ignored (e.g. @c '^d\..*' for
  290. display commands)
  291. """
  292. wx.EvtHandler.__init__(self)
  293. # Signal when some map is created or updated by a module.
  294. # attributes: name: map name, ltype: map type,
  295. self.mapCreated = Signal("GConsole.mapCreated")
  296. # emitted when map display should be re-render
  297. self.updateMap = Signal("GConsole.updateMap")
  298. # emitted when log message should be written
  299. self.writeLog = Signal("GConsole.writeLog")
  300. # emitted when command log message should be written
  301. self.writeCmdLog = Signal("GConsole.writeCmdLog")
  302. # emitted when warning message should be written
  303. self.writeWarning = Signal("GConsole.writeWarning")
  304. # emitted when error message should be written
  305. self.writeError = Signal("GConsole.writeError")
  306. self._guiparent = guiparent
  307. self._giface = giface
  308. self._ignoredCmdPattern = ignoredCmdPattern
  309. # create queues
  310. self.requestQ = Queue.Queue()
  311. self.resultQ = Queue.Queue()
  312. self.cmdOutputTimer = wx.Timer(self)
  313. self.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  314. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  315. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  316. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  317. # stream redirection
  318. self.cmdStdOut = GStdout(receiver=self)
  319. self.cmdStdErr = GStderr(receiver=self)
  320. # thread
  321. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  322. def Redirect(self):
  323. """Redirect stdout/stderr"""
  324. if Debug.GetLevel() == 0 and grass.debug_level(force=True) == 0:
  325. # don't redirect when debugging is enabled
  326. sys.stdout = self.cmdStdOut
  327. sys.stderr = self.cmdStdErr
  328. else:
  329. enc = locale.getdefaultlocale()[1]
  330. if enc:
  331. if sys.version_info.major == 2:
  332. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  333. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  334. else:
  335. # https://stackoverflow.com/questions/4374455/how-to-set-sys-stdout-encoding-in-python-3
  336. sys.stdout = codecs.getwriter(enc)(sys.__stdout__.detach())
  337. sys.stderr = codecs.getwriter(enc)(sys.__stderr__.detach())
  338. else:
  339. sys.stdout = sys.__stdout__
  340. sys.stderr = sys.__stderr__
  341. def WriteLog(
  342. self, text, style=None, wrap=None, notification=Notification.HIGHLIGHT
  343. ):
  344. """Generic method for writing log message in
  345. given style
  346. :param text: text line
  347. :param notification: form of notification
  348. """
  349. self.writeLog.emit(text=text, wrap=wrap, notification=notification)
  350. def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
  351. """Write message in selected style
  352. :param text: message to be printed
  353. :param pid: process pid or None
  354. :param notification: form of notification
  355. """
  356. self.writeCmdLog.emit(text=text, pid=pid, notification=notification)
  357. def WriteWarning(self, text):
  358. """Write message in warning style"""
  359. self.writeWarning.emit(text=text)
  360. def WriteError(self, text):
  361. """Write message in error style"""
  362. self.writeError.emit(text=text)
  363. def RunCmd(
  364. self,
  365. command,
  366. compReg=True,
  367. env=None,
  368. skipInterface=False,
  369. onDone=None,
  370. onPrepare=None,
  371. userData=None,
  372. addLayer=None,
  373. notification=Notification.MAKE_VISIBLE,
  374. ):
  375. """Run command typed into console command prompt (GPrompt).
  376. .. todo::
  377. Document the other event.
  378. .. todo::
  379. Solve problem with the other event (now uses gOutputText
  380. event but there is no text, use onPrepare handler instead?)
  381. .. todo::
  382. Skip interface is ignored and determined always automatically.
  383. Posts event EVT_IGNORED_CMD_RUN when command which should be ignored
  384. (according to ignoredCmdPattern) is run.
  385. For example, see layer manager which handles d.* on its own.
  386. :param command: command given as a list (produced e.g. by utils.split())
  387. :param compReg: True use computation region
  388. :param notification: form of notification
  389. :param bool skipInterface: True to do not launch GRASS interface
  390. parser when command has no arguments
  391. given
  392. :param onDone: function to be called when command is finished
  393. :param onPrepare: function to be called before command is launched
  394. :param addLayer: to be passed in the mapCreated signal
  395. :param userData: data defined for the command
  396. """
  397. if len(command) == 0:
  398. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  399. return
  400. # update history file
  401. self.UpdateHistoryFile(" ".join(command))
  402. if command[0] in globalvar.grassCmd:
  403. # send GRASS command without arguments to GUI command interface
  404. # except ignored commands (event is emitted)
  405. if (
  406. self._ignoredCmdPattern
  407. and re.compile(self._ignoredCmdPattern).search(" ".join(command))
  408. and "--help" not in command
  409. and "--ui" not in command
  410. ):
  411. event = gIgnoredCmdRun(cmd=command)
  412. wx.PostEvent(self, event)
  413. return
  414. else:
  415. # other GRASS commands (r|v|g|...)
  416. try:
  417. task = GUI(show=None).ParseCommand(command)
  418. except GException as e:
  419. GError(parent=self._guiparent, message=str(e), showTraceback=False)
  420. return
  421. hasParams = False
  422. if task:
  423. options = task.get_options()
  424. hasParams = options["params"] and options["flags"]
  425. # check for <input>=-
  426. for p in options["params"]:
  427. if (
  428. p.get("prompt", "") == "input"
  429. and p.get("element", "") == "file"
  430. and p.get("age", "new") == "old"
  431. and p.get("value", "") == "-"
  432. ):
  433. GError(
  434. parent=self._guiparent,
  435. message=_(
  436. "Unable to run command:\n%(cmd)s\n\n"
  437. "Option <%(opt)s>: read from standard input is not "
  438. "supported by wxGUI"
  439. )
  440. % {"cmd": " ".join(command), "opt": p.get("name", "")},
  441. )
  442. return
  443. if len(command) == 1:
  444. if command[0].startswith("g.gui."):
  445. import imp
  446. import inspect
  447. pyFile = command[0]
  448. if sys.platform == "win32":
  449. pyFile += ".py"
  450. pyPath = os.path.join(os.environ["GISBASE"], "scripts", pyFile)
  451. if not os.path.exists(pyPath):
  452. pyPath = os.path.join(
  453. os.environ["GRASS_ADDON_BASE"], "scripts", pyFile
  454. )
  455. if not os.path.exists(pyPath):
  456. GError(
  457. parent=self._guiparent,
  458. message=_("Module <%s> not found.") % command[0],
  459. )
  460. pymodule = imp.load_source(command[0].replace(".", "_"), pyPath)
  461. try: # PY3
  462. pymain = inspect.getfullargspec(pymodule.main)
  463. except AttributeError:
  464. pymain = inspect.getargspec(pymodule.main)
  465. if pymain and "giface" in pymain.args:
  466. pymodule.main(self._giface)
  467. return
  468. # no arguments given
  469. if hasParams and not isinstance(self._guiparent, FormNotebook):
  470. # also parent must be checked, see #3135 for details
  471. try:
  472. GUI(
  473. parent=self._guiparent, giface=self._giface
  474. ).ParseCommand(command)
  475. except GException as e:
  476. print(e, file=sys.stderr)
  477. return
  478. if env:
  479. env = env.copy()
  480. else:
  481. env = os.environ.copy()
  482. # activate computational region (set with g.region)
  483. # for all non-display commands.
  484. if compReg and "GRASS_REGION" in env:
  485. del env["GRASS_REGION"]
  486. # process GRASS command with argument
  487. self.cmdThread.RunCmd(
  488. command,
  489. stdout=self.cmdStdOut,
  490. stderr=self.cmdStdErr,
  491. onDone=onDone,
  492. onPrepare=onPrepare,
  493. userData=userData,
  494. addLayer=addLayer,
  495. env=env,
  496. notification=notification,
  497. )
  498. self.cmdOutputTimer.Start(50)
  499. # we don't need to change computational region settings
  500. # because we work on a copy
  501. else:
  502. # Send any other command to the shell. Send output to
  503. # console output window
  504. #
  505. # Check if the script has an interface (avoid double-launching
  506. # of the script)
  507. # check if we ignore the command (similar to grass commands part)
  508. if self._ignoredCmdPattern and re.compile(self._ignoredCmdPattern).search(
  509. " ".join(command)
  510. ):
  511. event = gIgnoredCmdRun(cmd=command)
  512. wx.PostEvent(self, event)
  513. return
  514. skipInterface = True
  515. if os.path.splitext(command[0])[1] in (".py", ".sh"):
  516. try:
  517. sfile = open(command[0], "r")
  518. for line in sfile.readlines():
  519. if len(line) < 2:
  520. continue
  521. if line[0] == "#" and line[1] == "%":
  522. skipInterface = False
  523. break
  524. sfile.close()
  525. except IOError:
  526. pass
  527. if len(command) == 1 and not skipInterface:
  528. try:
  529. task = gtask.parse_interface(command[0])
  530. except:
  531. task = None
  532. else:
  533. task = None
  534. if task:
  535. # process GRASS command without argument
  536. GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
  537. else:
  538. self.cmdThread.RunCmd(
  539. command,
  540. stdout=self.cmdStdOut,
  541. stderr=self.cmdStdErr,
  542. onDone=onDone,
  543. onPrepare=onPrepare,
  544. userData=userData,
  545. addLayer=addLayer,
  546. env=env,
  547. notification=notification,
  548. )
  549. self.cmdOutputTimer.Start(50)
  550. def GetLog(self, err=False):
  551. """Get widget used for logging
  552. .. todo::
  553. what's this?
  554. :param bool err: True to get stderr widget
  555. """
  556. if err:
  557. return self.cmdStdErr
  558. return self.cmdStdOut
  559. def GetCmd(self):
  560. """Get running command or None"""
  561. return self.requestQ.get()
  562. def OnCmdAbort(self, event):
  563. """Abort running command"""
  564. self.cmdThread.abort()
  565. event.Skip()
  566. def OnCmdRun(self, event):
  567. """Run command"""
  568. self.WriteCmdLog(
  569. "(%s)\n%s" % (str(time.ctime()), " ".join(event.cmd)),
  570. notification=event.notification,
  571. )
  572. event.Skip()
  573. def OnCmdDone(self, event):
  574. """Command done (or aborted)
  575. Sends signal mapCreated if map is recognized in output
  576. parameters or for specific modules (as r.colors).
  577. """
  578. # Process results here
  579. try:
  580. ctime = time.time() - event.time
  581. if ctime < 60:
  582. stime = _("%d sec") % int(ctime)
  583. else:
  584. mtime = int(ctime / 60)
  585. stime = _("%(min)d min %(sec)d sec") % {
  586. "min": mtime,
  587. "sec": int(ctime - (mtime * 60)),
  588. }
  589. except KeyError:
  590. # stopped deamon
  591. stime = _("unknown")
  592. if event.aborted:
  593. # Thread aborted (using our convention of None return)
  594. self.WriteWarning(
  595. _(
  596. "Please note that the data are left in"
  597. " inconsistent state and may be corrupted"
  598. )
  599. )
  600. msg = _("Command aborted")
  601. else:
  602. msg = _("Command finished")
  603. self.WriteCmdLog(
  604. "(%s) %s (%s)" % (str(time.ctime()), msg, stime),
  605. notification=event.notification,
  606. )
  607. if event.onDone:
  608. event.onDone(event)
  609. self.cmdOutputTimer.Stop()
  610. if event.cmd[0] == "g.gisenv":
  611. Debug.SetLevel()
  612. self.Redirect()
  613. # do nothing when no map added
  614. if event.returncode != 0 or event.aborted:
  615. event.Skip()
  616. return
  617. if event.cmd[0] not in globalvar.grassCmd:
  618. return
  619. # find which maps were created
  620. try:
  621. task = GUI(show=None).ParseCommand(event.cmd)
  622. except GException as e:
  623. print(e, file=sys.stderr)
  624. task = None
  625. return
  626. name = task.get_name()
  627. for p in task.get_options()["params"]:
  628. prompt = p.get("prompt", "")
  629. if prompt in ("raster", "vector", "raster_3d") and p.get("value", None):
  630. if p.get("age", "old") == "new" or name in (
  631. "r.colors",
  632. "r3.colors",
  633. "v.colors",
  634. "v.proj",
  635. "r.proj",
  636. ):
  637. # if multiple maps (e.g. r.series.interp), we need add each
  638. if p.get("multiple", False):
  639. lnames = p.get("value").split(",")
  640. # in case multiple input (old) maps in r.colors
  641. # we don't want to rerender it multiple times! just
  642. # once
  643. if p.get("age", "old") == "old":
  644. lnames = lnames[0:1]
  645. else:
  646. lnames = [p.get("value")]
  647. for lname in lnames:
  648. if "@" not in lname:
  649. lname += "@" + grass.gisenv()["MAPSET"]
  650. if grass.find_file(lname, element=p.get("element"))["fullname"]:
  651. self.mapCreated.emit(
  652. name=lname, ltype=prompt, add=event.addLayer
  653. )
  654. gisenv = grass.gisenv()
  655. self._giface.grassdbChanged.emit(
  656. grassdb=gisenv["GISDBASE"],
  657. location=gisenv["LOCATION_NAME"],
  658. mapset=gisenv["MAPSET"],
  659. action="new",
  660. map=lname.split("@")[0],
  661. element=prompt,
  662. )
  663. if name == "r.mask":
  664. self.updateMap.emit()
  665. event.Skip()
  666. def OnProcessPendingOutputWindowEvents(self, event):
  667. wx.GetApp().ProcessPendingEvents()
  668. def UpdateHistoryFile(self, command):
  669. """Update history file
  670. :param command: the command given as a string
  671. """
  672. env = grass.gisenv()
  673. try:
  674. filePath = os.path.join(
  675. env["GISDBASE"], env["LOCATION_NAME"], env["MAPSET"], ".wxgui_history"
  676. )
  677. fileHistory = codecs.open(filePath, encoding="utf-8", mode="a")
  678. except IOError as e:
  679. GError(
  680. _("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s")
  681. % {"filePath": filePath, "error": e},
  682. parent=self._guiparent,
  683. )
  684. return
  685. try:
  686. fileHistory.write(command + os.linesep)
  687. finally:
  688. fileHistory.close()
  689. # update wxGUI prompt
  690. if self._giface:
  691. self._giface.UpdateCmdHistory(command)