gconsole.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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-2012 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 core import globalvar
  30. from core.gcmd import CommandThread, GError, GException
  31. from core.events import gMapCreated
  32. from gui_core.forms import GUI
  33. from core.debug import Debug
  34. from core.settings import UserSettings
  35. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  36. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  37. wxCmdRun, EVT_CMD_RUN = NewEvent()
  38. wxCmdDone, EVT_CMD_DONE = NewEvent()
  39. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  40. wxCmdPrepare, EVT_CMD_PREPARE = NewEvent()
  41. def GrassCmd(cmd, env=None, stdout=None, stderr=None):
  42. """!Return GRASS command thread"""
  43. return CommandThread(cmd, env=env,
  44. stdout=stdout, stderr=stderr)
  45. class CmdThread(threading.Thread):
  46. """!Thread for GRASS commands"""
  47. requestId = 0
  48. def __init__(self, receiver, requestQ=None, resultQ=None, **kwds):
  49. """!
  50. @param receiver event receiver (used in PostEvent)
  51. """
  52. threading.Thread.__init__(self, **kwds)
  53. if requestQ is None:
  54. self.requestQ = Queue.Queue()
  55. else:
  56. self.requestQ = requestQ
  57. if resultQ is None:
  58. self.resultQ = Queue.Queue()
  59. else:
  60. self.resultQ = resultQ
  61. self.setDaemon(True)
  62. self.requestCmd = None
  63. self.receiver = receiver
  64. self._want_abort_all = False
  65. self.start()
  66. def RunCmd(self, *args, **kwds):
  67. """!Run command in queue
  68. @param args unnamed command arguments
  69. @param kwds named command arguments
  70. @return request id in queue
  71. """
  72. CmdThread.requestId += 1
  73. self.requestCmd = None
  74. self.requestQ.put((CmdThread.requestId, args, kwds))
  75. return CmdThread.requestId
  76. def GetId(self):
  77. """!Get id for next command"""
  78. return CmdThread.requestId + 1
  79. def SetId(self, id):
  80. """!Set starting id"""
  81. CmdThread.requestId = id
  82. def run(self):
  83. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  84. while True:
  85. requestId, args, kwds = self.requestQ.get()
  86. for key in ('callable', 'onDone', 'onPrepare', 'userData'):
  87. if key in kwds:
  88. vars()[key] = kwds[key]
  89. del kwds[key]
  90. else:
  91. vars()[key] = None
  92. if not vars()['callable']:
  93. vars()['callable'] = GrassCmd
  94. requestTime = time.time()
  95. # prepare
  96. if not self.receiver:
  97. return
  98. event = wxCmdPrepare(cmd=args[0],
  99. time=requestTime,
  100. pid=requestId,
  101. onPrepare=vars()['onPrepare'],
  102. userData=vars()['userData'])
  103. wx.PostEvent(self.receiver, event)
  104. # run command
  105. event = wxCmdRun(cmd=args[0],
  106. pid=requestId)
  107. wx.PostEvent(self.receiver, event)
  108. time.sleep(.1)
  109. self.requestCmd = vars()['callable'](*args, **kwds)
  110. if self._want_abort_all and self.requestCmd is not None:
  111. self.requestCmd.abort()
  112. if self.requestQ.empty():
  113. self._want_abort_all = False
  114. self.resultQ.put((requestId, self.requestCmd.run()))
  115. try:
  116. returncode = self.requestCmd.module.returncode
  117. except AttributeError:
  118. returncode = 0 # being optimistic
  119. try:
  120. aborted = self.requestCmd.aborted
  121. except AttributeError:
  122. aborted = False
  123. time.sleep(.1)
  124. # set default color table for raster data
  125. if UserSettings.Get(group='rasterLayer',
  126. key='colorTable', subkey='enabled') and \
  127. args[0][0][:2] == 'r.':
  128. colorTable = UserSettings.Get(group='rasterLayer',
  129. key='colorTable',
  130. subkey='selection')
  131. mapName = None
  132. if args[0][0] == 'r.mapcalc':
  133. try:
  134. mapName = args[0][1].split('=', 1)[0].strip()
  135. except KeyError:
  136. pass
  137. else:
  138. moduleInterface = GUI(show=None).ParseCommand(args[0])
  139. outputParam = moduleInterface.get_param(value='output',
  140. raiseError=False)
  141. if outputParam and outputParam['prompt'] == 'raster':
  142. mapName = outputParam['value']
  143. if mapName:
  144. argsColor = list(args)
  145. argsColor[0] = ['r.colors',
  146. 'map=%s' % mapName,
  147. 'color=%s' % colorTable]
  148. self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
  149. self.resultQ.put((requestId, self.requestCmdColor.run()))
  150. if not self.receiver:
  151. return
  152. event = wxCmdDone(cmd=args[0],
  153. aborted=aborted,
  154. returncode=returncode,
  155. time=requestTime,
  156. pid=requestId,
  157. onDone=vars()['onDone'],
  158. userData=vars()['userData'])
  159. # send event
  160. wx.PostEvent(self.receiver, event)
  161. def abort(self, abortall=True):
  162. """!Abort command(s)"""
  163. if abortall:
  164. self._want_abort_all = True
  165. if self.requestCmd is not None:
  166. self.requestCmd.abort()
  167. if self.requestQ.empty():
  168. self._want_abort_all = False
  169. class GStdout:
  170. """!GConsole standard output
  171. Based on FrameOutErr.py
  172. Name: FrameOutErr.py
  173. Purpose: Redirecting stdout / stderr
  174. Author: Jean-Michel Fauth, Switzerland
  175. Copyright: (c) 2005-2007 Jean-Michel Fauth
  176. Licence: GPL
  177. """
  178. def __init__(self, receiver):
  179. """!
  180. @param receiver event receiver (used in PostEvent)
  181. """
  182. self.receiver = receiver
  183. def write(self, s):
  184. if len(s) == 0 or s == '\n':
  185. return
  186. for line in s.splitlines():
  187. if len(line) == 0:
  188. continue
  189. evt = wxCmdOutput(text=line + '\n',
  190. type='')
  191. wx.PostEvent(self.receiver, evt)
  192. class GStderr:
  193. """!GConsole standard error output
  194. Based on FrameOutErr.py
  195. Name: FrameOutErr.py
  196. Purpose: Redirecting stdout / stderr
  197. Author: Jean-Michel Fauth, Switzerland
  198. Copyright: (c) 2005-2007 Jean-Michel Fauth
  199. Licence: GPL
  200. """
  201. def __init__(self, receiver):
  202. """!
  203. @param receiver event receiver (used in PostEvent)
  204. """
  205. self.receiver = receiver
  206. self.type = ''
  207. self.message = ''
  208. self.printMessage = False
  209. def flush(self):
  210. pass
  211. def write(self, s):
  212. if "GtkPizza" in s:
  213. return
  214. # remove/replace escape sequences '\b' or '\r' from stream
  215. progressValue = -1
  216. for line in s.splitlines():
  217. if len(line) == 0:
  218. continue
  219. if 'GRASS_INFO_PERCENT' in line:
  220. value = int(line.rsplit(':', 1)[1].strip())
  221. if value >= 0 and value < 100:
  222. progressValue = value
  223. else:
  224. progressValue = 0
  225. elif 'GRASS_INFO_MESSAGE' in line:
  226. self.type = 'message'
  227. self.message += line.split(':', 1)[1].strip() + '\n'
  228. elif 'GRASS_INFO_WARNING' in line:
  229. self.type = 'warning'
  230. self.message += line.split(':', 1)[1].strip() + '\n'
  231. elif 'GRASS_INFO_ERROR' in line:
  232. self.type = 'error'
  233. self.message += line.split(':', 1)[1].strip() + '\n'
  234. elif 'GRASS_INFO_END' in line:
  235. self.printMessage = True
  236. elif self.type == '':
  237. if len(line) == 0:
  238. continue
  239. evt = wxCmdOutput(text=line,
  240. type='')
  241. wx.PostEvent(self.receiver, evt)
  242. elif len(line) > 0:
  243. self.message += line.strip() + '\n'
  244. if self.printMessage and len(self.message) > 0:
  245. evt = wxCmdOutput(text=self.message,
  246. type=self.type)
  247. wx.PostEvent(self.receiver, evt)
  248. self.type = ''
  249. self.message = ''
  250. self.printMessage = False
  251. # update progress message
  252. if progressValue > -1:
  253. # self.gmgauge.SetValue(progressValue)
  254. evt = wxCmdProgress(value=progressValue)
  255. wx.PostEvent(self.receiver, evt)
  256. # events related to messages
  257. # TODO: create separete class for handling messages?
  258. gWriteLog, EVT_WRITE_LOG = NewEvent()
  259. gWriteCmdLog, EVT_WRITE_CMD_LOG = NewEvent()
  260. gWriteWarning, EVT_WRITE_WARNING = NewEvent()
  261. gWriteError, EVT_WRITE_ERROR = NewEvent()
  262. # Occurs when an ignored command is called.
  263. # Attribute cmd contains command (as a list).
  264. gIgnoredCmdRun, EVT_IGNORED_CMD_RUN = NewEvent()
  265. # Occurs when important command is called.
  266. # Determined by switchPage and priority parameters of GConsole.RunCmd()
  267. # currently used only for Layer Manager
  268. # because others (forms and gmodeler) just wants to see all commands
  269. # (because commands are the main part of their work)
  270. gImportantCmdRun, EVT_IMPORTANT_CMD_RUN = NewEvent()
  271. class GConsole(wx.EvtHandler):
  272. """!
  273. """
  274. def __init__(self, guiparent=None, giface=None, ignoredCmdPattern=None):
  275. """!
  276. @param guiparent parent window for created GUI objects
  277. @param lmgr layer manager window (TODO: replace by giface)
  278. @param ignoredCmdPattern regular expression specifying commads
  279. to be ignored (e.g. @c '^d\..*' for display commands)
  280. """
  281. wx.EvtHandler.__init__(self)
  282. self._guiparent = guiparent
  283. self._giface = giface
  284. self._ignoredCmdPattern = ignoredCmdPattern
  285. # create queues
  286. self.requestQ = Queue.Queue()
  287. self.resultQ = Queue.Queue()
  288. self.cmdOutputTimer = wx.Timer(self)
  289. self.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  290. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  291. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  292. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  293. # stream redirection
  294. self.cmdStdOut = GStdout(receiver=self)
  295. self.cmdStdErr = GStderr(receiver=self)
  296. # thread
  297. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  298. def Redirect(self):
  299. """!Redirect stdout/stderr
  300. """
  301. if Debug.GetLevel() == 0 and int(grass.gisenv().get('DEBUG', 0)) == 0:
  302. # don't redirect when debugging is enabled
  303. sys.stdout = self.cmdStdOut
  304. sys.stderr = self.cmdStdErr
  305. else:
  306. enc = locale.getdefaultlocale()[1]
  307. if enc:
  308. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  309. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  310. else:
  311. sys.stdout = sys.__stdout__
  312. sys.stderr = sys.__stderr__
  313. def WriteLog(self, text, style=None, wrap=None,
  314. switchPage=False, priority=1):
  315. """!Generic method for writing log message in
  316. given style
  317. @param line text line
  318. @param switchPage for backward compatibility
  319. (replace by priority: False=1, True=2)
  320. @param priority priority of this message
  321. (0=no priority, 1=normal, 2=medium, 3=high)
  322. """
  323. event = gWriteLog(text=text, wrap=wrap,
  324. switchPage=switchPage, priority=priority)
  325. wx.PostEvent(self, event)
  326. def WriteCmdLog(self, line, pid=None, switchPage=True):
  327. """!Write message in selected style
  328. @param line message to be printed
  329. @param pid process pid or None
  330. @param switchPage True to switch page
  331. """
  332. event = gWriteCmdLog(line=line, pid=pid,
  333. switchPage=switchPage)
  334. wx.PostEvent(self, event)
  335. def WriteWarning(self, line):
  336. """!Write message in warning style"""
  337. event = gWriteWarning(line=line)
  338. wx.PostEvent(self, event)
  339. def WriteError(self, line):
  340. """!Write message in error style"""
  341. event = gWriteError(line=line)
  342. wx.PostEvent(self, event)
  343. def RunCmd(self, command, compReg=True, switchPage=False, skipInterface=False,
  344. onDone=None, onPrepare=None, userData=None, priority=1):
  345. """!Run command typed into console command prompt (GPrompt).
  346. @todo Document the other event.
  347. @todo Solve problem with the other event
  348. (now uses gOutputText event but there is no text,
  349. 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. @todo replace swichPage and priority by parameter 'silent' or 'important'
  354. also possible solution is RunCmdSilently and RunCmdWithoutNotifyingAUser
  355. @param command command given as a list (produced e.g. by utils.split())
  356. @param compReg True use computation region
  357. @param switchPage switch to output page
  358. @param priority command importance - possible replacement for switchPage
  359. @param skipInterface True to do not launch GRASS interface
  360. parser when command has no arguments given
  361. @param onDone function to be called when command is finished
  362. @param onPrepare function to be called before command is launched
  363. @param userData data defined for the command
  364. """
  365. if len(command) == 0:
  366. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  367. return
  368. # update history file
  369. env = grass.gisenv()
  370. try:
  371. filePath = os.path.join(env['GISDBASE'],
  372. env['LOCATION_NAME'],
  373. env['MAPSET'],
  374. '.bash_history')
  375. fileHistory = codecs.open(filePath, encoding='utf-8', mode='a')
  376. except IOError, e:
  377. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  378. {'filePath': filePath, 'error': e},
  379. parent=self._guiparent)
  380. fileHistory = None
  381. if fileHistory:
  382. try:
  383. fileHistory.write(' '.join(command) + os.linesep)
  384. finally:
  385. fileHistory.close()
  386. if command[0] in globalvar.grassCmd:
  387. # send GRASS command without arguments to GUI command interface
  388. # except ignored commands (event is emitted)
  389. if self._ignoredCmdPattern and \
  390. re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
  391. '--help' not in command and '--ui' not in command:
  392. event = gIgnoredCmdRun(cmd=command)
  393. wx.PostEvent(self, event)
  394. return
  395. else:
  396. # other GRASS commands (r|v|g|...)
  397. try:
  398. task = GUI(show=None).ParseCommand(command)
  399. except GException, e:
  400. GError(parent=self._guiparent,
  401. message=unicode(e),
  402. showTraceback=False)
  403. return
  404. hasParams = False
  405. if task:
  406. options = task.get_options()
  407. hasParams = options['params'] and options['flags']
  408. # check for <input>=-
  409. for p in options['params']:
  410. if p.get('prompt', '') == 'input' and \
  411. p.get('element', '') == 'file' and \
  412. p.get('age', 'new') == 'old' and \
  413. p.get('value', '') == '-':
  414. GError(parent=self._guiparent,
  415. message=_("Unable to run command:\n%(cmd)s\n\n"
  416. "Option <%(opt)s>: read from standard input is not "
  417. "supported by wxGUI") % {'cmd': ' '.join(command),
  418. 'opt': p.get('name', '')})
  419. return
  420. if len(command) == 1 and hasParams and \
  421. command[0] != 'v.krige':
  422. # no arguments given
  423. try:
  424. GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
  425. except GException, e:
  426. print >> sys.stderr, e
  427. return
  428. # documenting old behavior/implementation:
  429. # switch and focus if required
  430. # important commad
  431. # TODO: add also user data, cmd, ... to the event?
  432. importantEvent = gImportantCmdRun()
  433. wx.PostEvent(self, importantEvent)
  434. # activate computational region (set with g.region)
  435. # for all non-display commands.
  436. if compReg:
  437. tmpreg = os.getenv("GRASS_REGION")
  438. if "GRASS_REGION" in os.environ:
  439. del os.environ["GRASS_REGION"]
  440. # process GRASS command with argument
  441. self.cmdThread.RunCmd(command,
  442. stdout=self.cmdStdOut,
  443. stderr=self.cmdStdErr,
  444. onDone=onDone, onPrepare=onPrepare,
  445. userData=userData,
  446. env=os.environ.copy())
  447. self.cmdOutputTimer.Start(50)
  448. # deactivate computational region and return to display settings
  449. if compReg and tmpreg:
  450. os.environ["GRASS_REGION"] = tmpreg
  451. else:
  452. # Send any other command to the shell. Send output to
  453. # console output window
  454. if len(command) == 1 and not skipInterface:
  455. try:
  456. task = gtask.parse_interface(command[0])
  457. except:
  458. task = None
  459. else:
  460. task = None
  461. if task:
  462. # process GRASS command without argument
  463. GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
  464. else:
  465. self.cmdThread.RunCmd(command,
  466. stdout=self.cmdStdOut,
  467. stderr=self.cmdStdErr,
  468. onDone=onDone, onPrepare=onPrepare,
  469. userData=userData)
  470. self.cmdOutputTimer.Start(50)
  471. def GetLog(self, err=False):
  472. """!Get widget used for logging
  473. @todo what's this?
  474. @param err True to get stderr widget
  475. """
  476. if err:
  477. return self.cmdStdErr
  478. return self.cmdStdOut
  479. def GetCmd(self):
  480. """!Get running command or None"""
  481. return self.requestQ.get()
  482. def OnCmdAbort(self, event):
  483. """!Abort running command"""
  484. self.cmdThread.abort()
  485. event.Skip()
  486. def OnCmdRun(self, event):
  487. """!Run command"""
  488. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  489. event.Skip()
  490. def OnCmdDone(self, event):
  491. """!Command done (or aborted)
  492. Posts event EVT_MAP_CREATED.
  493. """
  494. # Process results here
  495. try:
  496. ctime = time.time() - event.time
  497. if ctime < 60:
  498. stime = _("%d sec") % int(ctime)
  499. else:
  500. mtime = int(ctime / 60)
  501. stime = _("%(min)d min %(sec)d sec") % {'min': mtime,
  502. 'sec': int(ctime - (mtime * 60))}
  503. except KeyError:
  504. # stopped deamon
  505. stime = _("unknown")
  506. if event.aborted:
  507. # Thread aborted (using our convention of None return)
  508. self.WriteWarning(_('Please note that the data are left in'
  509. ' inconsistent state and may be corrupted'))
  510. msg = _('Command aborted')
  511. else:
  512. msg = _('Command finished')
  513. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime))
  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. # find which maps were created
  525. try:
  526. task = GUI(show=None).ParseCommand(event.cmd)
  527. except GException, e:
  528. print >> sys.stderr, e
  529. task = None
  530. return
  531. for p in task.get_options()['params']:
  532. prompt = p.get('prompt', '')
  533. if prompt in ('raster', 'vector', '3d-raster') and \
  534. p.get('age', 'old') == 'new' and \
  535. p.get('value', None):
  536. name = p.get('value')
  537. if '@' not in name:
  538. name = name + '@' + grass.gisenv()['MAPSET']
  539. mapEvent = gMapCreated(self._guiparent.GetId(),
  540. name=name, ltype=prompt, add=None)
  541. wx.PostEvent(self._guiparent, mapEvent)
  542. event.Skip()
  543. def OnProcessPendingOutputWindowEvents(self, event):
  544. wx.GetApp().ProcessPendingEvents()