gconsole.py 26 KB

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