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 display commands)
  272. """
  273. wx.EvtHandler.__init__(self)
  274. # Signal when some map is created or updated by a module.
  275. # attributes: name: map name, ltype: map type,
  276. self.mapCreated = Signal('GConsole.mapCreated')
  277. # emitted when map display should be re-render
  278. self.updateMap = Signal('GConsole.updateMap')
  279. # emitted when log message should be written
  280. self.writeLog = Signal('GConsole.writeLog')
  281. # emitted when command log message should be written
  282. self.writeCmdLog = Signal('GConsole.writeCmdLog')
  283. # emitted when warning message should be written
  284. self.writeWarning = Signal('GConsole.writeWarning')
  285. # emitted when error message should be written
  286. self.writeError = Signal('GConsole.writeError')
  287. self._guiparent = guiparent
  288. self._giface = giface
  289. self._ignoredCmdPattern = ignoredCmdPattern
  290. # create queues
  291. self.requestQ = Queue.Queue()
  292. self.resultQ = Queue.Queue()
  293. self.cmdOutputTimer = wx.Timer(self)
  294. self.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  295. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  296. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  297. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  298. # stream redirection
  299. self.cmdStdOut = GStdout(receiver=self)
  300. self.cmdStdErr = GStderr(receiver=self)
  301. # thread
  302. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  303. def Redirect(self):
  304. """!Redirect stdout/stderr
  305. """
  306. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  307. # don't redirect when debugging is enabled
  308. sys.stdout = self.cmdStdOut
  309. sys.stderr = self.cmdStdErr
  310. else:
  311. enc = locale.getdefaultlocale()[1]
  312. if enc:
  313. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  314. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  315. else:
  316. sys.stdout = sys.__stdout__
  317. sys.stderr = sys.__stderr__
  318. def WriteLog(self, text, style=None, wrap=None,
  319. notification=Notification.HIGHLIGHT):
  320. """!Generic method for writing log message in
  321. given style
  322. @param text text line
  323. @param notification form of notification
  324. """
  325. self.writeLog.emit(text=text, wrap=wrap,
  326. notification=notification)
  327. def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
  328. """!Write message in selected style
  329. @param text message to be printed
  330. @param pid process pid or None
  331. @param notification form of notification
  332. """
  333. self.writeCmdLog.emit(text=text, pid=pid,
  334. notification=notification)
  335. def WriteWarning(self, text):
  336. """!Write message in warning style"""
  337. self.writeWarning.emit(text=text)
  338. def WriteError(self, text):
  339. """!Write message in error style"""
  340. self.writeError.emit(text=text)
  341. def RunCmd(self, command, compReg=True, skipInterface=False,
  342. onDone=None, onPrepare=None, userData=None, notification=Notification.MAKE_VISIBLE):
  343. """!Run command typed into console command prompt (GPrompt).
  344. @todo Document the other event.
  345. @todo Solve problem with the other event
  346. (now uses gOutputText event but there is no text,
  347. use onPrepare handler instead?)
  348. Posts event EVT_IGNORED_CMD_RUN when command which should be ignored
  349. (according to ignoredCmdPattern) is run.
  350. For example, see layer manager which handles d.* on its own.
  351. @param command command given as a list (produced e.g. by utils.split())
  352. @param compReg True use computation region
  353. @param notification form of notification
  354. @param skipInterface True to do not launch GRASS interface
  355. parser when command has no arguments given
  356. @param onDone function to be called when command is finished
  357. @param onPrepare function to be called before command is launched
  358. @param userData data defined for the command
  359. """
  360. if len(command) == 0:
  361. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  362. return
  363. # update history file
  364. self.UpdateHistoryFile(' '.join(command))
  365. if command[0] in globalvar.grassCmd:
  366. # send GRASS command without arguments to GUI command interface
  367. # except ignored commands (event is emitted)
  368. if self._ignoredCmdPattern and \
  369. re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
  370. '--help' not in command and '--ui' not in command:
  371. event = gIgnoredCmdRun(cmd=command)
  372. wx.PostEvent(self, event)
  373. return
  374. else:
  375. # other GRASS commands (r|v|g|...)
  376. try:
  377. task = GUI(show=None).ParseCommand(command)
  378. except GException as e:
  379. GError(parent=self._guiparent,
  380. message=unicode(e),
  381. showTraceback=False)
  382. return
  383. hasParams = False
  384. if task:
  385. options = task.get_options()
  386. hasParams = options['params'] and options['flags']
  387. # check for <input>=-
  388. for p in options['params']:
  389. if p.get('prompt', '') == 'input' and \
  390. p.get('element', '') == 'file' and \
  391. p.get('age', 'new') == 'old' and \
  392. p.get('value', '') == '-':
  393. GError(parent=self._guiparent,
  394. message=_("Unable to run command:\n%(cmd)s\n\n"
  395. "Option <%(opt)s>: read from standard input is not "
  396. "supported by wxGUI") % {'cmd': ' '.join(command),
  397. 'opt': p.get('name', '')})
  398. return
  399. if len(command) == 1 and hasParams and \
  400. command[0] != 'v.krige':
  401. # no arguments given
  402. try:
  403. GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
  404. except GException as e:
  405. print >> sys.stderr, e
  406. return
  407. # activate computational region (set with g.region)
  408. # for all non-display commands.
  409. if compReg:
  410. tmpreg = os.getenv("GRASS_REGION")
  411. if "GRASS_REGION" in os.environ:
  412. del os.environ["GRASS_REGION"]
  413. # process GRASS command with argument
  414. self.cmdThread.RunCmd(command,
  415. stdout=self.cmdStdOut,
  416. stderr=self.cmdStdErr,
  417. onDone=onDone, onPrepare=onPrepare,
  418. userData=userData,
  419. env=os.environ.copy(),
  420. notification=notification)
  421. self.cmdOutputTimer.Start(50)
  422. # deactivate computational region and return to display settings
  423. if compReg and tmpreg:
  424. os.environ["GRASS_REGION"] = tmpreg
  425. else:
  426. # Send any other command to the shell. Send output to
  427. # console output window
  428. #
  429. # Check if the script has an interface (avoid double-launching
  430. # of the script)
  431. # check if we ignore the command (similar to grass commands part)
  432. if self._ignoredCmdPattern and \
  433. re.compile(self._ignoredCmdPattern).search(' '.join(command)):
  434. event = gIgnoredCmdRun(cmd=command)
  435. wx.PostEvent(self, event)
  436. return
  437. skipInterface = True
  438. if os.path.splitext(command[0])[1] in ('.py', '.sh'):
  439. try:
  440. sfile = open(command[0], "r")
  441. for line in sfile.readlines():
  442. if len(line) < 2:
  443. continue
  444. if line[0] is '#' and line[1] is '%':
  445. skipInterface = False
  446. break
  447. sfile.close()
  448. except IOError:
  449. pass
  450. if len(command) == 1 and not skipInterface:
  451. try:
  452. task = gtask.parse_interface(command[0])
  453. except:
  454. task = None
  455. else:
  456. task = None
  457. if task:
  458. # process GRASS command without argument
  459. GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
  460. else:
  461. self.cmdThread.RunCmd(command,
  462. stdout=self.cmdStdOut,
  463. stderr=self.cmdStdErr,
  464. onDone=onDone, onPrepare=onPrepare,
  465. userData=userData,
  466. notification=notification)
  467. self.cmdOutputTimer.Start(50)
  468. def GetLog(self, err=False):
  469. """!Get widget used for logging
  470. @todo what's this?
  471. @param err True to get stderr widget
  472. """
  473. if err:
  474. return self.cmdStdErr
  475. return self.cmdStdOut
  476. def GetCmd(self):
  477. """!Get running command or None"""
  478. return self.requestQ.get()
  479. def OnCmdAbort(self, event):
  480. """!Abort running command"""
  481. self.cmdThread.abort()
  482. event.Skip()
  483. def OnCmdRun(self, event):
  484. """!Run command"""
  485. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)),
  486. notification=event.notification)
  487. event.Skip()
  488. def OnCmdDone(self, event):
  489. """!Command done (or aborted)
  490. Sends signal mapCreated if map is recognized in output
  491. parameters or for specific modules (as r.colors).
  492. """
  493. # Process results here
  494. try:
  495. ctime = time.time() - event.time
  496. if ctime < 60:
  497. stime = _("%d sec") % int(ctime)
  498. else:
  499. mtime = int(ctime / 60)
  500. stime = _("%(min)d min %(sec)d sec") % {'min': mtime,
  501. 'sec': int(ctime - (mtime * 60))}
  502. except KeyError:
  503. # stopped deamon
  504. stime = _("unknown")
  505. if event.aborted:
  506. # Thread aborted (using our convention of None return)
  507. self.WriteWarning(_('Please note that the data are left in'
  508. ' inconsistent state and may be corrupted'))
  509. msg = _('Command aborted')
  510. else:
  511. msg = _('Command finished')
  512. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime),
  513. notification=event.notification)
  514. if event.onDone:
  515. event.onDone(cmd=event.cmd, returncode=event.returncode)
  516. self.cmdOutputTimer.Stop()
  517. if event.cmd[0] == 'g.gisenv':
  518. Debug.SetLevel()
  519. self.Redirect()
  520. # do nothing when no map added
  521. if event.returncode != 0 or event.aborted:
  522. event.Skip()
  523. return
  524. if event.cmd[0] not in globalvar.grassCmd:
  525. return
  526. # find which maps were created
  527. try:
  528. task = GUI(show=None).ParseCommand(event.cmd)
  529. except GException as e:
  530. print >> sys.stderr, e
  531. task = None
  532. return
  533. name = task.get_name()
  534. for p in task.get_options()['params']:
  535. prompt = p.get('prompt', '')
  536. if prompt in ('raster', 'vector', '3d-raster') and p.get('value', None):
  537. if p.get('age', 'old') == 'new' or \
  538. name in ('r.colors', 'r3.colors', 'v.colors', 'v.proj', 'r.proj'):
  539. # if multiple maps (e.g. r.series.interp), we need add each
  540. if p.get('multiple', False):
  541. lnames = p.get('value').split(',')
  542. # in case multiple input (old) maps in r.colors
  543. # we don't want to rerender it multiple times! just once
  544. if p.get('age', 'old') == 'old':
  545. lnames = lnames[0:1]
  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)