goutput.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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
  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.": # display GRASS commands
  142. try:
  143. layertype = {'d.rast' : 'raster',
  144. 'd.rgb' : 'rgb',
  145. 'd.his' : 'his',
  146. 'd.shaded' : 'shaded',
  147. 'd.legend' : 'rastleg',
  148. 'd.rast.arrow' : 'rastarrow',
  149. 'd.rast.num' : 'rastnum',
  150. 'd.vect' : 'vector',
  151. 'd.vect.thematic': 'thememap',
  152. 'd.vect.chart' : 'themechart',
  153. 'd.grid' : 'grid',
  154. 'd.geodesic' : 'geodesic',
  155. 'd.rhumbline' : 'rhumb',
  156. 'd.labels' : 'labels'}[cmdlist[0]]
  157. except KeyError:
  158. wx.MessageBox(message=_("Command '%s' not yet implemented.") % cmdlist[0])
  159. return False
  160. # add layer into layer tree
  161. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  162. lcmd=cmdlist)
  163. else: # other GRASS commands (r|v|g|...)
  164. if hasattr(self.parent, "curr_page"):
  165. # change notebook page only for Layer Manager
  166. if self.parent.notebook.GetSelection() != 1:
  167. self.parent.notebook.SetSelection(1)
  168. # activate computational region (set with g.region)
  169. # for all non-display commands.
  170. tmpreg = os.getenv("GRASS_REGION")
  171. os.unsetenv("GRASS_REGION")
  172. if len(cmdlist) == 1:
  173. import menuform
  174. # process GRASS command without argument
  175. menuform.GUI().ParseCommand(cmdlist, parentframe=self)
  176. else:
  177. # process GRASS command with argument
  178. cmdPID = len(self.cmdThreads.keys())+1
  179. self.WriteCmdLog('%s' % ' '.join(cmdlist), pid=cmdPID)
  180. grassCmd = gcmd.Command(cmdlist, wait=False,
  181. stdout=self.cmd_stdout,
  182. stderr=self.cmd_stderr)
  183. self.cmdThreads[grassCmd.cmdThread] = { 'cmdPID' : cmdPID }
  184. return grassCmd
  185. # deactivate computational region and return to display settings
  186. if tmpreg:
  187. os.environ["GRASS_REGION"] = tmpreg
  188. else:
  189. # Send any other command to the shell. Send output to
  190. # console output window
  191. if hasattr(self.parent, "curr_page"):
  192. # change notebook page only for Layer Manager
  193. if self.parent.notebook.GetSelection() != 1:
  194. self.parent.notebook.SetSelection(1)
  195. print "$ " + ' '.join(cmdlist)
  196. # if command is not a GRASS command, treat it like a shell command
  197. generalCmd = subprocess.Popen(cmdlist,
  198. stdout=subprocess.PIPE,
  199. stderr=subprocess.PIPE)
  200. for outline in generalCmd.stdout:
  201. print outline
  202. return None
  203. def ClearHistory(self, event):
  204. """Clear history of commands"""
  205. self.cmd_output.ClearAll()
  206. self.console_progressbar.SetValue(0)
  207. def SaveHistory(self, event):
  208. """Save history of commands"""
  209. self.history = self.cmd_output.GetSelectedText()
  210. if self.history == '':
  211. self.history = self.cmd_output.GetText()
  212. # add newline if needed
  213. if len(self.history) > 0 and self.history[-1] != os.linesep:
  214. self.history += os.linesep
  215. wildcard = "Text file (*.txt)|*.txt"
  216. dlg = wx.FileDialog(
  217. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  218. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  219. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  220. # Show the dialog and retrieve the user response. If it is the OK response,
  221. # process the data.
  222. if dlg.ShowModal() == wx.ID_OK:
  223. path = dlg.GetPath()
  224. output = open(path, "w")
  225. output.write(self.history)
  226. output.close()
  227. dlg.Destroy()
  228. def GetListOfCmdThreads(self, onlyAlive=True):
  229. """Return list of command threads)"""
  230. list = []
  231. for t in self.cmdThreads.keys():
  232. Debug.msg (4, "GMConsole.GetListOfCmdThreads(): name=%s, alive=%s" %
  233. (t.getName(), t.isAlive()))
  234. if onlyAlive and not t.isAlive():
  235. continue
  236. list.append(t)
  237. return list
  238. def OnResult(self, event):
  239. """Show result status"""
  240. if event.cmdThread.aborted:
  241. # Thread aborted (using our convention of None return)
  242. self.WriteLog(_('Please note that the data are left in incosistent stage '
  243. 'and can be corrupted'), self.cmd_output.StyleWarning)
  244. self.WriteCmdLog(_('Command aborted'),
  245. pid=self.cmdThreads[event.cmdThread]['cmdPID'])
  246. else:
  247. # Process results here
  248. self.WriteCmdLog(_('Command finished (%d sec)') % (time.time() - event.cmdThread.startTime),
  249. pid=self.cmdThreads[event.cmdThread]['cmdPID'])
  250. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  251. # updated command dialog
  252. if hasattr(self.parent.parent, "btn_run"):
  253. dialog = self.parent.parent
  254. if hasattr(self.parent.parent, "btn_abort"):
  255. dialog.btn_abort.Enable(False)
  256. dialog.btn_run.Enable(True)
  257. if dialog.get_dcmd is None and \
  258. dialog.closebox.IsChecked():
  259. time.sleep(1)
  260. dialog.Close()
  261. class GMStdout:
  262. """GMConsole standard output
  263. Based on FrameOutErr.py
  264. Name: FrameOutErr.py
  265. Purpose: Redirecting stdout / stderr
  266. Author: Jean-Michel Fauth, Switzerland
  267. Copyright: (c) 2005-2007 Jean-Michel Fauth
  268. Licence: GPL
  269. """
  270. def __init__(self, gmstc):
  271. self.gmstc = gmstc
  272. def write(self, s):
  273. if len(s) == 0:
  274. return
  275. s = s.replace('\n', os.linesep)
  276. for line in s.split(os.linesep):
  277. p1 = self.gmstc.GetCurrentPos() # get caret position
  278. self.gmstc.AddTextWrapped(line, wrap=None) # no wrapping && adds os.linesep
  279. self.gmstc.EnsureCaretVisible()
  280. p2 = self.gmstc.GetCurrentPos()
  281. self.gmstc.StartStyling(p1, 0xff)
  282. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleOutput)
  283. class GMStderr:
  284. """GMConsole standard error output
  285. Based on FrameOutErr.py
  286. Name: FrameOutErr.py
  287. Purpose: Redirecting stdout / stderr
  288. Author: Jean-Michel Fauth, Switzerland
  289. Copyright: (c) 2005-2007 Jean-Michel Fauth
  290. Licence: GPL
  291. """
  292. def __init__(self, gmstc, gmgauge, notebook, pageid):
  293. self.gmstc = gmstc
  294. self.gmgauge = gmgauge
  295. self.notebook = notebook
  296. self.pageid = pageid
  297. def write(self, s):
  298. if self.pageid > -1:
  299. # swith notebook page to 'command output'
  300. if self.notebook.GetSelection() != self.pageid:
  301. self.notebook.SetSelection(self.pageid)
  302. s = s.replace('\n', os.linesep)
  303. # remove/replace escape sequences '\b' or '\r' from stream
  304. s = s.replace('\b', '').replace('\r', '%s' % os.linesep)
  305. type = ''
  306. message = ''
  307. printMessage = False
  308. for line in s.split(os.linesep):
  309. if len(line) == 0:
  310. continue
  311. if 'GRASS_INFO_PERCENT' in line:
  312. # 'GRASS_INFO_PERCENT: 10' -> value=10
  313. value = int(line.split(':')[1].strip())
  314. if value < 100:
  315. self.gmgauge.SetValue(value)
  316. else:
  317. self.gmgauge.SetValue(0) # reset progress bar on '0%'
  318. elif 'GRASS_INFO_MESSAGE' in line:
  319. type = 'message'
  320. if len(message) > 0:
  321. message += os.linesep
  322. message += line.split(':', 1)[1].strip()
  323. elif 'GRASS_INFO_WARNING' in line:
  324. type = 'warning'
  325. if len(message) > 0:
  326. message += os.linesep
  327. message += line.split(':', 1)[1].strip()
  328. elif 'GRASS_INFO_ERROR' in line:
  329. type = 'error'
  330. if len(message) > 0:
  331. message += os.linesep
  332. message += line.split(':', 1)[1].strip()
  333. elif 'GRASS_INFO_END' in line:
  334. printMessage = True
  335. elif not type:
  336. if len(line) > 0:
  337. p1 = self.gmstc.GetCurrentPos()
  338. self.gmstc.AddTextWrapped(line, wrap=60) # wrap && add os.linesep
  339. self.gmstc.EnsureCaretVisible()
  340. p2 = self.gmstc.GetCurrentPos()
  341. self.gmstc.StartStyling(p1, 0xff)
  342. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleUnknown)
  343. elif len(line) > 0:
  344. message += os.linesep + line.strip()
  345. if printMessage and len(message) > 0:
  346. p1 = self.gmstc.GetCurrentPos()
  347. if type == 'warning':
  348. message = 'WARNING: ' + message
  349. elif type == 'error':
  350. message = 'ERROR: ' + message
  351. if '\n' not in message:
  352. self.gmstc.AddTextWrapped(message, wrap=60) #wrap && add os.linesep
  353. else:
  354. self.gmstc.AddText(message + os.linesep)
  355. self.gmstc.EnsureCaretVisible()
  356. p2 = self.gmstc.GetCurrentPos()
  357. self.gmstc.StartStyling(p1, 0xff)
  358. if type == 'error':
  359. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleError)
  360. elif type == 'warning':
  361. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleWarning)
  362. elif type == 'message':
  363. self.gmstc.SetStyling(p2 - p1 + 1, self.gmstc.StyleMessage)
  364. type = ''
  365. message = ''
  366. class GMStc(wx.stc.StyledTextCtrl):
  367. """Styled GMConsole
  368. Based on FrameOutErr.py
  369. Name: FrameOutErr.py
  370. Purpose: Redirecting stdout / stderr
  371. Author: Jean-Michel Fauth, Switzerland
  372. Copyright: (c) 2005-2007 Jean-Michel Fauth
  373. Licence: GPL
  374. """
  375. def __init__(self, parent, id, margin=False, wrap=None):
  376. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  377. self.parent = parent
  378. self.wrap = wrap
  379. #
  380. # styles
  381. #
  382. self.StyleDefault = 0
  383. self.StyleDefaultSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  384. self.StyleCommand = 1
  385. self.StyleCommandSpec = "face:Courier New,size:10,fore:#000000,back:#bcbcbc"
  386. self.StyleOutput = 2
  387. self.StyleOutputSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  388. # fatal error
  389. self.StyleError = 3
  390. self.StyleErrorSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  391. # warning
  392. self.StyleWarning = 4
  393. self.StyleWarningSpec = "face:Courier New,size:10,fore:#0000FF,back:#FFFFFF"
  394. # message
  395. self.StyleMessage = 5
  396. self.StyleMessageSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  397. # unknown
  398. self.StyleUnknown = 6
  399. self.StyleUnknownSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  400. # default and clear => init
  401. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  402. self.StyleClearAll()
  403. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  404. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  405. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  406. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  407. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  408. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  409. #
  410. # line margins
  411. #
  412. # TODO print number only from cmdlog
  413. self.SetMarginWidth(1, 0)
  414. self.SetMarginWidth(2, 0)
  415. if margin:
  416. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  417. self.SetMarginWidth(0, 30)
  418. else:
  419. self.SetMarginWidth(0, 0)
  420. #
  421. # miscellaneous
  422. #
  423. self.SetViewWhiteSpace(False)
  424. self.SetTabWidth(4)
  425. self.SetUseTabs(False)
  426. self.UsePopUp(True)
  427. self.SetSelBackground(True, "#FFFF00")
  428. self.SetUseHorizontalScrollBar(True)
  429. #
  430. # bindins
  431. #
  432. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  433. def OnDestroy(self, evt):
  434. """The clipboard contents can be preserved after
  435. the app has exited"""
  436. wx.TheClipboard.Flush()
  437. evt.Skip()
  438. def AddTextWrapped(self, str, wrap=None):
  439. """Add string to text area.
  440. String is wrapped and linesep is also added to the end
  441. of the string"""
  442. if wrap is None and self.wrap:
  443. wrap = self.wrap
  444. if wrap is not None:
  445. str = textwrap.fill(str, wrap) + os.linesep
  446. else:
  447. str += os.linesep
  448. self.AddText(str)
  449. def SetWrap(self, wrap):
  450. """Set wrapping value
  451. @param wrap wrapping value
  452. @return current wrapping value
  453. """
  454. if wrap > 0:
  455. self.wrap = wrap
  456. return self.wrap