goutput.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. """
  2. @package goutput
  3. @brief Command output log widget
  4. Classes:
  5. - GMConsole
  6. - GMStc
  7. - GMStdout
  8. - GMStderr
  9. (C) 2007-2008 by the GRASS Development Team
  10. This program is free software under the GNU General Public
  11. License (>=v2). Read the file COPYING that comes with GRASS
  12. for details.
  13. @author Michael Barton (Arizona State University)
  14. Martin Landa <landa.martin gmail.com>
  15. """
  16. import os
  17. import sys
  18. import textwrap
  19. import time
  20. import wx
  21. import wx.stc
  22. import globalvar
  23. import gcmd
  24. from debug import Debug as Debug
  25. class GMConsole(wx.Panel):
  26. """
  27. Create and manage output console for commands entered on the
  28. GIS Manager command line.
  29. """
  30. def __init__(self, parent, id=wx.ID_ANY, margin=False, pageid=0,
  31. pos=wx.DefaultPosition, size=wx.DefaultSize,
  32. style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE):
  33. wx.Panel.__init__(self, parent, id, pos, size, style)
  34. # initialize variables
  35. self.Map = None
  36. self.parent = parent # GMFrame
  37. self.cmdThreads = {} # cmdThread : cmdPID
  38. self.lineWidth = 80
  39. self.pageid = pageid
  40. # progress bar
  41. self.console_progressbar = wx.Gauge(parent=self, id=wx.ID_ANY,
  42. range=100, pos=(110, 50), size=(-1, 25),
  43. style=wx.GA_HORIZONTAL)
  44. # text control for command output
  45. self.cmd_output = GMStc(parent=self, id=wx.ID_ANY, margin=margin,
  46. wrap=None)
  47. # redirect
  48. self.cmd_stdout = GMStdout(self.cmd_output)
  49. ### sys.stdout = self.cmd_stdout
  50. self.cmd_stderr = GMStderr(self.cmd_output,
  51. self.console_progressbar,
  52. self.parent.notebook,
  53. pageid)
  54. if Debug.get_level() == 0:
  55. # don't redirect when debugging is enabled
  56. sys.stderr = self.cmd_stderr
  57. # buttons
  58. self.console_clear = wx.Button(parent=self, id=wx.ID_CLEAR)
  59. self.console_save = wx.Button(parent=self, id=wx.ID_SAVE)
  60. self.Bind(wx.EVT_BUTTON, self.ClearHistory, self.console_clear)
  61. self.Bind(wx.EVT_BUTTON, self.SaveHistory, self.console_save)
  62. # output control layout
  63. boxsizer1 = wx.BoxSizer(wx.VERTICAL)
  64. gridsizer1 = wx.GridSizer(rows=1, cols=2, vgap=0, hgap=0)
  65. boxsizer1.Add(item=self.cmd_output, proportion=1,
  66. flag=wx.EXPAND | wx.ADJUST_MINSIZE, border=0)
  67. gridsizer1.Add(item=self.console_clear, proportion=0,
  68. flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, border=0)
  69. gridsizer1.Add(item=self.console_save, proportion=0,
  70. flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, border=0)
  71. boxsizer1.Add(item=gridsizer1, proportion=0,
  72. flag=wx.EXPAND | wx.ALIGN_CENTRE_VERTICAL | wx.TOP | wx.BOTTOM,
  73. border=5)
  74. boxsizer1.Add(item=self.console_progressbar, proportion=0,
  75. flag=wx.EXPAND | wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  76. boxsizer1.Fit(self)
  77. boxsizer1.SetSizeHints(self)
  78. # set up event handler for any command thread results
  79. gcmd.EVT_RESULT(self, self.OnResult)
  80. # layout
  81. self.SetAutoLayout(True)
  82. self.SetSizer(boxsizer1)
  83. def WriteLog(self, line, style=None, wrap=None):
  84. """Generic method for writing log message in
  85. given style
  86. @param line text line
  87. @param style text style (see GMStc)
  88. @param stdout write to stdout or stderr
  89. """
  90. if not style:
  91. style = self.cmd_output.StyleDefault
  92. self.cmd_output.GotoPos(self.cmd_output.GetEndStyled())
  93. p1 = self.cmd_output.GetCurrentPos()
  94. # fill space
  95. if len(line) < self.lineWidth:
  96. diff = 80 - len(line)
  97. line += diff * ' '
  98. self.cmd_output.AddTextWrapped(line, wrap=wrap) # adds os.linesep
  99. self.cmd_output.EnsureCaretVisible()
  100. p2 = self.cmd_output.GetCurrentPos()
  101. self.cmd_output.StartStyling(p1, 0xff)
  102. self.cmd_output.SetStyling(p2 - p1, style)
  103. def WriteCmdLog(self, line, pid=None):
  104. """Write out line in selected style"""
  105. if pid:
  106. line = '(' + str(pid) + ') ' + line
  107. self.WriteLog(line, self.cmd_output.StyleCommand)
  108. def RunCmd(self, command):
  109. """
  110. Run in GUI GRASS (or other) commands typed into
  111. console command text widget, and send stdout output to output
  112. text widget.
  113. Command is transformed into a list for processing.
  114. TODO: Display commands (*.d) are captured and
  115. processed separately by mapdisp.py. Display commands are
  116. rendered in map display widget that currently has
  117. the focus (as indicted by mdidx).
  118. """
  119. # map display window available ?
  120. try:
  121. curr_disp = self.parent.curr_page.maptree.mapdisplay
  122. self.Map = curr_disp.GetRender()
  123. except:
  124. curr_disp = None
  125. if len(self.GetListOfCmdThreads()) > 0:
  126. # only one running command enabled (per GMConsole instance)
  127. busy = wx.BusyInfo(message=_("Unable to run the command, another command is running..."),
  128. parent=self)
  129. wx.Yield()
  130. time.sleep(3)
  131. busy.Destroy()
  132. return None
  133. # command given as a string ?
  134. try:
  135. cmdlist = command.strip().split(' ')
  136. except:
  137. cmdlist = command
  138. if cmdlist[0] in globalvar.grassCmd['all']:
  139. # send GRASS command without arguments to GUI command interface
  140. # except display commands (they are handled differently)
  141. if cmdlist[0][0:2] == "d.":
  142. #
  143. # display GRASS commands
  144. #
  145. try:
  146. layertype = {'d.rast' : 'raster',
  147. 'd.rgb' : 'rgb',
  148. 'd.his' : 'his',
  149. 'd.shaded' : 'shaded',
  150. 'd.legend' : 'rastleg',
  151. 'd.rast.arrow' : 'rastarrow',
  152. 'd.rast.num' : 'rastnum',
  153. 'd.vect' : 'vector',
  154. 'd.vect.thematic': 'thememap',
  155. 'd.vect.chart' : 'themechart',
  156. 'd.grid' : 'grid',
  157. 'd.geodesic' : 'geodesic',
  158. 'd.rhumbline' : 'rhumb',
  159. 'd.labels' : 'labels'}[cmdlist[0]]
  160. except KeyError:
  161. wx.MessageBox(message=_("Command '%s' not yet implemented.") % cmdlist[0])
  162. return None
  163. # add layer into layer tree
  164. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  165. lcmd=cmdlist)
  166. else:
  167. #
  168. # other GRASS commands (r|v|g|...)
  169. #
  170. if hasattr(self.parent, "curr_page"):
  171. # change notebook page only for Layer Manager
  172. if self.parent.notebook.GetSelection() != 1:
  173. self.parent.notebook.SetSelection(1)
  174. # activate computational region (set with g.region)
  175. # for all non-display commands.
  176. tmpreg = os.getenv("GRASS_REGION")
  177. os.unsetenv("GRASS_REGION")
  178. if len(cmdlist) == 1:
  179. import menuform
  180. # process GRASS command without argument
  181. menuform.GUI().ParseCommand(cmdlist, parentframe=self)
  182. else:
  183. # process GRASS command with argument
  184. cmdPID = len(self.cmdThreads.keys())+1
  185. self.WriteCmdLog('%s' % ' '.join(cmdlist), pid=cmdPID)
  186. grassCmd = gcmd.Command(cmdlist, wait=False,
  187. stdout=self.cmd_stdout,
  188. stderr=self.cmd_stderr)
  189. self.cmdThreads[grassCmd.cmdThread] = { 'cmdPID' : cmdPID }
  190. return grassCmd
  191. # deactivate computational region and return to display settings
  192. if tmpreg:
  193. os.environ["GRASS_REGION"] = tmpreg
  194. else:
  195. # Send any other command to the shell. Send output to
  196. # console output window
  197. if hasattr(self.parent, "curr_page"):
  198. # change notebook page only for Layer Manager
  199. if self.parent.notebook.GetSelection() != 1:
  200. self.parent.notebook.SetSelection(1)
  201. # if command is not a GRASS command, treat it like a shell command
  202. try:
  203. generalCmd = gcmd.Command(cmdlist,
  204. stdout=self.cmd_stdout,
  205. stderr=self.cmd_stderr)
  206. except gcmd.CmdError, e:
  207. print >> sys.stderr, e
  208. return None
  209. def ClearHistory(self, event):
  210. """Clear history of commands"""
  211. self.cmd_output.ClearAll()
  212. self.console_progressbar.SetValue(0)
  213. def SaveHistory(self, event):
  214. """Save history of commands"""
  215. self.history = self.cmd_output.GetSelectedText()
  216. if self.history == '':
  217. self.history = self.cmd_output.GetText()
  218. # add newline if needed
  219. if len(self.history) > 0 and self.history[-1] != os.linesep:
  220. self.history += os.linesep
  221. wildcard = "Text file (*.txt)|*.txt"
  222. dlg = wx.FileDialog(
  223. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  224. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  225. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  226. # Show the dialog and retrieve the user response. If it is the OK response,
  227. # process the data.
  228. if dlg.ShowModal() == wx.ID_OK:
  229. path = dlg.GetPath()
  230. output = open(path, "w")
  231. output.write(self.history)
  232. output.close()
  233. dlg.Destroy()
  234. def GetListOfCmdThreads(self, onlyAlive=True):
  235. """Return list of command threads)"""
  236. list = []
  237. for t in self.cmdThreads.keys():
  238. Debug.msg (4, "GMConsole.GetListOfCmdThreads(): name=%s, alive=%s" %
  239. (t.getName(), t.isAlive()))
  240. if onlyAlive and not t.isAlive():
  241. continue
  242. list.append(t)
  243. return list
  244. def OnResult(self, event):
  245. """Show result status"""
  246. if event.cmdThread.aborted:
  247. # Thread aborted (using our convention of None return)
  248. self.WriteLog(_('Please note that the data are left in incosistent stage '
  249. 'and can be corrupted'), self.cmd_output.StyleWarning)
  250. self.WriteCmdLog(_('Command aborted'),
  251. pid=self.cmdThreads[event.cmdThread]['cmdPID'])
  252. else:
  253. try:
  254. # Process results here
  255. self.WriteCmdLog(_('Command finished (%d sec)') % (time.time() - event.cmdThread.startTime),
  256. pid=self.cmdThreads[event.cmdThread]['cmdPID'])
  257. except KeyError:
  258. # stopped deamon
  259. pass
  260. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  261. # updated command dialog
  262. if hasattr(self.parent.parent, "btn_run"):
  263. dialog = self.parent.parent
  264. if hasattr(self.parent.parent, "btn_abort"):
  265. dialog.btn_abort.Enable(False)
  266. dialog.btn_run.Enable(True)
  267. if dialog.get_dcmd is None and \
  268. dialog.closebox.IsChecked():
  269. time.sleep(1)
  270. dialog.Close()
  271. class GMStdout:
  272. """GMConsole standard output
  273. Based on FrameOutErr.py
  274. Name: FrameOutErr.py
  275. Purpose: Redirecting stdout / stderr
  276. Author: Jean-Michel Fauth, Switzerland
  277. Copyright: (c) 2005-2007 Jean-Michel Fauth
  278. Licence: GPL
  279. """
  280. def __init__(self, gmstc):
  281. self.gmstc = gmstc
  282. def write(self, s):
  283. if len(s) == 0:
  284. return
  285. s = s.replace('\n', os.linesep)
  286. for line in s.split(os.linesep):
  287. p1 = self.gmstc.GetCurrentPos() # get caret position
  288. self.gmstc.AddTextWrapped(line, wrap=None) # no wrapping && adds os.linesep
  289. self.gmstc.EnsureCaretVisible()
  290. p2 = self.gmstc.GetCurrentPos()
  291. self.gmstc.StartStyling(p1, 0xff)
  292. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleOutput)
  293. class GMStderr:
  294. """GMConsole standard error output
  295. Based on FrameOutErr.py
  296. Name: FrameOutErr.py
  297. Purpose: Redirecting stdout / stderr
  298. Author: Jean-Michel Fauth, Switzerland
  299. Copyright: (c) 2005-2007 Jean-Michel Fauth
  300. Licence: GPL
  301. """
  302. def __init__(self, gmstc, gmgauge, notebook, pageid):
  303. self.gmstc = gmstc
  304. self.gmgauge = gmgauge
  305. self.notebook = notebook
  306. self.pageid = pageid
  307. def write(self, s):
  308. if self.pageid > -1:
  309. # swith notebook page to 'command output'
  310. if self.notebook.GetSelection() != self.pageid:
  311. self.notebook.SetSelection(self.pageid)
  312. s = s.replace('\n', os.linesep)
  313. # remove/replace escape sequences '\b' or '\r' from stream
  314. s = s.replace('\b', '').replace('\r', '%s' % os.linesep)
  315. type = ''
  316. message = ''
  317. printMessage = False
  318. for line in s.split(os.linesep):
  319. if len(line) == 0:
  320. continue
  321. if 'GRASS_INFO_PERCENT' in line:
  322. # 'GRASS_INFO_PERCENT: 10' -> value=10
  323. value = int(line.split(':')[1].strip())
  324. if value < 100:
  325. self.gmgauge.SetValue(value)
  326. else:
  327. self.gmgauge.SetValue(0) # reset progress bar on '0%'
  328. elif 'GRASS_INFO_MESSAGE' in line:
  329. type = 'message'
  330. if len(message) > 0:
  331. message += os.linesep
  332. message += line.split(':', 1)[1].strip()
  333. elif 'GRASS_INFO_WARNING' in line:
  334. type = 'warning'
  335. if len(message) > 0:
  336. message += os.linesep
  337. message += line.split(':', 1)[1].strip()
  338. elif 'GRASS_INFO_ERROR' in line:
  339. type = 'error'
  340. if len(message) > 0:
  341. message += os.linesep
  342. message += line.split(':', 1)[1].strip()
  343. elif 'GRASS_INFO_END' in line:
  344. printMessage = True
  345. elif not type:
  346. if len(line) > 0:
  347. p1 = self.gmstc.GetCurrentPos()
  348. self.gmstc.AddTextWrapped(line, wrap=60) # wrap && add os.linesep
  349. self.gmstc.EnsureCaretVisible()
  350. p2 = self.gmstc.GetCurrentPos()
  351. self.gmstc.StartStyling(p1, 0xff)
  352. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleUnknown)
  353. elif len(line) > 0:
  354. message += os.linesep + line.strip()
  355. if printMessage and len(message) > 0:
  356. p1 = self.gmstc.GetCurrentPos()
  357. if type == 'warning':
  358. message = 'WARNING: ' + message
  359. elif type == 'error':
  360. message = 'ERROR: ' + message
  361. if '\n' not in message:
  362. self.gmstc.AddTextWrapped(message, wrap=60) #wrap && add os.linesep
  363. else:
  364. self.gmstc.AddText(message + os.linesep)
  365. self.gmstc.EnsureCaretVisible()
  366. p2 = self.gmstc.GetCurrentPos()
  367. self.gmstc.StartStyling(p1, 0xff)
  368. if type == 'error':
  369. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleError)
  370. elif type == 'warning':
  371. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleWarning)
  372. elif type == 'message':
  373. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleMessage)
  374. type = ''
  375. message = ''
  376. class GMStc(wx.stc.StyledTextCtrl):
  377. """Styled GMConsole
  378. Based on FrameOutErr.py
  379. Name: FrameOutErr.py
  380. Purpose: Redirecting stdout / stderr
  381. Author: Jean-Michel Fauth, Switzerland
  382. Copyright: (c) 2005-2007 Jean-Michel Fauth
  383. Licence: GPL
  384. """
  385. def __init__(self, parent, id, margin=False, wrap=None):
  386. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  387. self.parent = parent
  388. self.wrap = wrap
  389. #
  390. # styles
  391. #
  392. self.StyleDefault = 0
  393. self.StyleDefaultSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  394. self.StyleCommand = 1
  395. self.StyleCommandSpec = "face:Courier New,size:10,fore:#000000,back:#bcbcbc"
  396. self.StyleOutput = 2
  397. self.StyleOutputSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  398. # fatal error
  399. self.StyleError = 3
  400. self.StyleErrorSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  401. # warning
  402. self.StyleWarning = 4
  403. self.StyleWarningSpec = "face:Courier New,size:10,fore:#0000FF,back:#FFFFFF"
  404. # message
  405. self.StyleMessage = 5
  406. self.StyleMessageSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  407. # unknown
  408. self.StyleUnknown = 6
  409. self.StyleUnknownSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  410. # default and clear => init
  411. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  412. self.StyleClearAll()
  413. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  414. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  415. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  416. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  417. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  418. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  419. #
  420. # line margins
  421. #
  422. # TODO print number only from cmdlog
  423. self.SetMarginWidth(1, 0)
  424. self.SetMarginWidth(2, 0)
  425. if margin:
  426. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  427. self.SetMarginWidth(0, 30)
  428. else:
  429. self.SetMarginWidth(0, 0)
  430. #
  431. # miscellaneous
  432. #
  433. self.SetViewWhiteSpace(False)
  434. self.SetTabWidth(4)
  435. self.SetUseTabs(False)
  436. self.UsePopUp(True)
  437. self.SetSelBackground(True, "#FFFF00")
  438. self.SetUseHorizontalScrollBar(True)
  439. #
  440. # bindins
  441. #
  442. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  443. def OnDestroy(self, evt):
  444. """The clipboard contents can be preserved after
  445. the app has exited"""
  446. wx.TheClipboard.Flush()
  447. evt.Skip()
  448. def AddTextWrapped(self, str, wrap=None):
  449. """Add string to text area.
  450. String is wrapped and linesep is also added to the end
  451. of the string"""
  452. if wrap is None and self.wrap:
  453. wrap = self.wrap
  454. if wrap is not None:
  455. str = textwrap.fill(str, wrap) + os.linesep
  456. else:
  457. str += os.linesep
  458. self.AddText(str)
  459. def SetWrap(self, wrap):
  460. """Set wrapping value
  461. @param wrap wrapping value
  462. @return current wrapping value
  463. """
  464. if wrap > 0:
  465. self.wrap = wrap
  466. return self.wrap