gconsole.py 24 KB

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