goutput.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. @author Martin Landa <landa.martin gmail.com>
  15. """
  16. import os
  17. import sys
  18. import textwrap
  19. import time
  20. import threading
  21. import Queue
  22. import wx
  23. import wx.stc
  24. from wx.lib.newevent import NewEvent
  25. import grass.script as grass
  26. import globalvar
  27. import gcmd
  28. import utils
  29. from debug import Debug as Debug
  30. from preferences import globalSettings as UserSettings
  31. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  32. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  33. wxCmdRun, EVT_CMD_RUN = NewEvent()
  34. wxCmdDone, EVT_CMD_DONE = NewEvent()
  35. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  36. def GrassCmd(cmd, stdout, stderr):
  37. """!Return GRASS command thread"""
  38. return gcmd.CommandThread(cmd,
  39. stdout=stdout, stderr=stderr)
  40. class CmdThread(threading.Thread):
  41. """!Thread for GRASS commands"""
  42. requestId = 0
  43. def __init__(self, parent, requestQ, resultQ, **kwds):
  44. threading.Thread.__init__(self, **kwds)
  45. self.setDaemon(True)
  46. self.parent = parent # GMConsole
  47. self.requestQ = requestQ
  48. self.resultQ = resultQ
  49. self.start()
  50. def RunCmd(self, callable, onDone, *args, **kwds):
  51. CmdThread.requestId += 1
  52. self.requestCmd = None
  53. self.requestQ.put((CmdThread.requestId, callable, onDone, args, kwds))
  54. return CmdThread.requestId
  55. def run(self):
  56. while True:
  57. requestId, callable, onDone, args, kwds = self.requestQ.get()
  58. requestTime = time.time()
  59. event = wxCmdRun(cmd=args[0],
  60. pid=requestId)
  61. wx.PostEvent(self.parent, event)
  62. time.sleep(.1)
  63. self.requestCmd = callable(*args, **kwds)
  64. self.resultQ.put((requestId, self.requestCmd.run()))
  65. try:
  66. returncode = self.requestCmd.module.returncode
  67. except AttributeError:
  68. returncode = 0 # being optimistic
  69. try:
  70. aborted = self.requestCmd.aborted
  71. except AttributeError:
  72. aborted = False
  73. time.sleep(.1)
  74. event = wxCmdDone(aborted = aborted,
  75. returncode = returncode,
  76. time = requestTime,
  77. pid = requestId,
  78. onDone = onDone)
  79. # send event
  80. wx.PostEvent(self.parent, event)
  81. def abort(self):
  82. self.requestCmd.abort()
  83. class GMConsole(wx.Panel):
  84. """
  85. Create and manage output console for commands entered on the
  86. GIS Manager command line.
  87. """
  88. def __init__(self, parent, id=wx.ID_ANY, margin=False, pageid=0,
  89. pos=wx.DefaultPosition, size=wx.DefaultSize,
  90. style=wx.TAB_TRAVERSAL | wx.FULL_REPAINT_ON_RESIZE):
  91. wx.Panel.__init__(self, parent, id, pos, size, style)
  92. self.SetName("GMConsole")
  93. # initialize variables
  94. self.Map = None
  95. self.parent = parent # GMFrame | CmdPanel
  96. self.lineWidth = 80
  97. self.pageid = pageid
  98. # remember position of line begining (used for '\r')
  99. self.linePos = -1
  100. #
  101. # create queues
  102. #
  103. self.requestQ = Queue.Queue()
  104. self.resultQ = Queue.Queue()
  105. #
  106. # progress bar
  107. #
  108. self.console_progressbar = wx.Gauge(parent=self, id=wx.ID_ANY,
  109. range=100, pos=(110, 50), size=(-1, 25),
  110. style=wx.GA_HORIZONTAL)
  111. self.console_progressbar.Bind(EVT_CMD_PROGRESS, self.OnCmdProgress)
  112. # abort
  113. self.btn_abort = wx.Button(parent=self, id=wx.ID_STOP)
  114. self.btn_abort.SetToolTipString(_("Abort the running command"))
  115. self.btn_abort.Bind(wx.EVT_BUTTON, self.OnCmdAbort)
  116. self.btn_abort.Enable(False)
  117. #
  118. # text control for command output
  119. #
  120. self.cmd_output = GMStc(parent=self, id=wx.ID_ANY, margin=margin,
  121. wrap=None)
  122. self.cmd_output_timer = wx.Timer(self.cmd_output, id=wx.ID_ANY)
  123. self.cmd_output.Bind(EVT_CMD_OUTPUT, self.OnCmdOutput)
  124. self.cmd_output.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  125. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  126. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  127. #
  128. # stream redirection
  129. #
  130. self.cmd_stdout = GMStdout(self)
  131. self.cmd_stderr = GMStderr(self)
  132. #
  133. # thread
  134. #
  135. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  136. #
  137. # buttons
  138. #
  139. self.console_clear = wx.Button(parent=self, id=wx.ID_CLEAR)
  140. self.console_save = wx.Button(parent=self, id=wx.ID_SAVE)
  141. self.Bind(wx.EVT_BUTTON, self.ClearHistory, self.console_clear)
  142. self.Bind(wx.EVT_BUTTON, self.SaveHistory, self.console_save)
  143. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  144. self.__layout()
  145. def __layout(self):
  146. """!Do layout"""
  147. boxsizer1 = wx.BoxSizer(wx.VERTICAL)
  148. gridsizer1 = wx.GridSizer(rows=1, cols=2, vgap=0, hgap=0)
  149. boxsizer1.Add(item=self.cmd_output, proportion=1,
  150. flag=wx.EXPAND | wx.ADJUST_MINSIZE, border=0)
  151. gridsizer1.Add(item=self.console_clear, proportion=0,
  152. flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, border=0)
  153. gridsizer1.Add(item=self.console_save, proportion=0,
  154. flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ADJUST_MINSIZE, border=0)
  155. boxsizer1.Add(item=gridsizer1, proportion=0,
  156. flag=wx.EXPAND | wx.ALIGN_CENTRE_VERTICAL | wx.TOP | wx.BOTTOM,
  157. border=5)
  158. boxsizer2 = wx.BoxSizer(wx.HORIZONTAL)
  159. boxsizer2.Add(item=self.console_progressbar, proportion=1,
  160. flag=wx.EXPAND | wx.ALIGN_CENTRE_VERTICAL)
  161. boxsizer2.Add(item=self.btn_abort, proportion=0,
  162. flag=wx.ALIGN_CENTRE_VERTICAL | wx.LEFT,
  163. border = 5)
  164. boxsizer1.Add(item=boxsizer2, proportion=0,
  165. flag=wx.EXPAND | wx.ALIGN_CENTRE_VERTICAL | wx.ALL,
  166. border=5)
  167. boxsizer1.Fit(self)
  168. boxsizer1.SetSizeHints(self)
  169. # layout
  170. self.SetAutoLayout(True)
  171. self.SetSizer(boxsizer1)
  172. def Redirect(self):
  173. """!Redirect stderr
  174. @return True redirected
  175. @return False failed
  176. """
  177. if Debug.get_level() == 0:
  178. # don't redirect when debugging is enabled
  179. sys.stdout = self.cmd_stdout
  180. sys.stderr = self.cmd_stderr
  181. return True
  182. return False
  183. def WriteLog(self, text, style = None, wrap = None,
  184. switchPage = False):
  185. """!Generic method for writing log message in
  186. given style
  187. @param line text line
  188. @param style text style (see GMStc)
  189. @param stdout write to stdout or stderr
  190. """
  191. if switchPage and \
  192. self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
  193. self.parent.notebook.SetSelection(self.parent.goutput.pageid)
  194. if not style:
  195. style = self.cmd_output.StyleDefault
  196. # p1 = self.cmd_output.GetCurrentPos()
  197. p1 = self.cmd_output.GetEndStyled()
  198. self.cmd_output.GotoPos(p1)
  199. for line in text.splitlines():
  200. # fill space
  201. if len(line) < self.lineWidth:
  202. diff = self.lineWidth - len(line)
  203. line += diff * ' '
  204. self.cmd_output.AddTextWrapped(line, wrap=wrap) # adds '\n'
  205. p2 = self.cmd_output.GetCurrentPos()
  206. self.cmd_output.StartStyling(p1, 0xff)
  207. self.cmd_output.SetStyling(p2 - p1, style)
  208. self.cmd_output.EnsureCaretVisible()
  209. def WriteCmdLog(self, line, pid=None):
  210. """!Write message in selected style"""
  211. if pid:
  212. line = '(' + str(pid) + ') ' + line
  213. self.WriteLog(line, style=self.cmd_output.StyleCommand, switchPage = True)
  214. def WriteWarning(self, line):
  215. """!Write message in warning style"""
  216. self.WriteLog(line, style=self.cmd_output.StyleWarning, switchPage = True)
  217. def WriteError(self, line):
  218. """!Write message in error style"""
  219. self.WriteLog(line, style=self.cmd_output.StyleError, switchPage = True)
  220. def RunCmd(self, command, compReg=True, switchPage=False,
  221. onDone = None):
  222. """
  223. Run in GUI GRASS (or other) commands typed into
  224. console command text widget, and send stdout output to output
  225. text widget.
  226. Command is transformed into a list for processing.
  227. TODO: Display commands (*.d) are captured and
  228. processed separately by mapdisp.py. Display commands are
  229. rendered in map display widget that currently has
  230. the focus (as indicted by mdidx).
  231. @param command command (list)
  232. @param compReg if true use computation region
  233. @param switchPage switch to output page
  234. @param onDone function to be called when command is finished
  235. """
  236. # map display window available ?
  237. try:
  238. curr_disp = self.parent.curr_page.maptree.mapdisplay
  239. self.Map = curr_disp.GetRender()
  240. except:
  241. curr_disp = None
  242. # command given as a string ?
  243. try:
  244. cmdlist = command.strip().split(' ')
  245. except:
  246. cmdlist = command
  247. # update history file
  248. env = grass.gisenv()
  249. fileHistory = open(os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'],
  250. '.bash_history'), 'a')
  251. cmdString = ' '.join(cmdlist)
  252. try:
  253. fileHistory.write(cmdString + '\n')
  254. finally:
  255. fileHistory.close()
  256. # update history items
  257. if self.parent.GetName() == 'LayerManager':
  258. try:
  259. self.parent.cmdinput.SetHistoryItems()
  260. except AttributeError:
  261. pass
  262. if cmdlist[0] in globalvar.grassCmd['all']:
  263. # send GRASS command without arguments to GUI command interface
  264. # except display commands (they are handled differently)
  265. if cmdlist[0][0:2] == "d.":
  266. #
  267. # display GRASS commands
  268. #
  269. try:
  270. layertype = {'d.rast' : 'raster',
  271. 'd.rgb' : 'rgb',
  272. 'd.his' : 'his',
  273. 'd.shaded' : 'shaded',
  274. 'd.legend' : 'rastleg',
  275. 'd.rast.arrow' : 'rastarrow',
  276. 'd.rast.num' : 'rastnum',
  277. 'd.vect' : 'vector',
  278. 'd.vect.thematic': 'thememap',
  279. 'd.vect.chart' : 'themechart',
  280. 'd.grid' : 'grid',
  281. 'd.geodesic' : 'geodesic',
  282. 'd.rhumbline' : 'rhumb',
  283. 'd.labels' : 'labels'}[cmdlist[0]]
  284. except KeyError:
  285. wx.MessageBox(message=_("Command '%s' not yet implemented.") % cmdlist[0])
  286. return None
  287. # add layer into layer tree
  288. if cmdlist[0] == 'd.rast':
  289. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  290. layerType = 'raster')
  291. elif cmdlist[0] == 'd.vect':
  292. lname = utils.GetLayerNameFromCmd(cmdlist, fullyQualified = True,
  293. layerType = 'vector')
  294. else:
  295. lname = None
  296. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  297. lname=lname,
  298. lcmd=cmdlist)
  299. else:
  300. #
  301. # other GRASS commands (r|v|g|...)
  302. #
  303. # switch to 'Command output'
  304. if switchPage:
  305. if self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
  306. self.parent.notebook.SetSelection(self.parent.goutput.pageid)
  307. self.parent.SetFocus() # -> set focus
  308. self.parent.Raise()
  309. # activate computational region (set with g.region)
  310. # for all non-display commands.
  311. if compReg:
  312. tmpreg = os.getenv("GRASS_REGION")
  313. if os.environ.has_key("GRASS_REGION"):
  314. del os.environ["GRASS_REGION"]
  315. if len(cmdlist) == 1:
  316. import menuform
  317. # process GRASS command without argument
  318. menuform.GUI().ParseCommand(cmdlist, parentframe=self)
  319. else:
  320. # process GRASS command with argument
  321. self.cmdThread.RunCmd(GrassCmd,
  322. onDone,
  323. cmdlist,
  324. self.cmd_stdout, self.cmd_stderr)
  325. self.btn_abort.Enable()
  326. self.cmd_output_timer.Start(50)
  327. return None
  328. # deactivate computational region and return to display settings
  329. if compReg and tmpreg:
  330. os.environ["GRASS_REGION"] = tmpreg
  331. else:
  332. # Send any other command to the shell. Send output to
  333. # console output window
  334. # if command is not a GRASS command, treat it like a shell command
  335. try:
  336. gcmd.Command(cmdlist,
  337. stdout=self.cmd_stdout,
  338. stderr=self.cmd_stderr)
  339. except gcmd.CmdError, e:
  340. print >> sys.stderr, e
  341. return None
  342. def ClearHistory(self, event):
  343. """!Clear history of commands"""
  344. self.cmd_output.ClearAll()
  345. self.console_progressbar.SetValue(0)
  346. def SaveHistory(self, event):
  347. """!Save history of commands"""
  348. self.history = self.cmd_output.GetSelectedText()
  349. if self.history == '':
  350. self.history = self.cmd_output.GetText()
  351. # add newline if needed
  352. if len(self.history) > 0 and self.history[-1] != '\n':
  353. self.history += '\n'
  354. wildcard = "Text file (*.txt)|*.txt"
  355. dlg = wx.FileDialog(
  356. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  357. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  358. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  359. # Show the dialog and retrieve the user response. If it is the OK response,
  360. # process the data.
  361. if dlg.ShowModal() == wx.ID_OK:
  362. path = dlg.GetPath()
  363. output = open(path, "w")
  364. output.write(self.history)
  365. output.close()
  366. dlg.Destroy()
  367. def GetCmd(self):
  368. """!Get running command or None"""
  369. return self.requestQ.get()
  370. def OnCmdOutput(self, event):
  371. """!Print command output"""
  372. message = event.text
  373. type = event.type
  374. if self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
  375. textP = self.parent.notebook.GetPageText(self.parent.goutput.pageid)
  376. if textP[-1] != ')':
  377. textP += ' (...)'
  378. self.parent.notebook.SetPageText(self.parent.goutput.pageid,
  379. textP)
  380. # message prefix
  381. if type == 'warning':
  382. messege = 'WARNING: ' + message
  383. elif type == 'error':
  384. message = 'ERROR: ' + message
  385. p1 = self.cmd_output.GetEndStyled()
  386. self.cmd_output.GotoPos(p1)
  387. if '\b' in message:
  388. if self.linepos < 0:
  389. self.linepos = p1
  390. last_c = ''
  391. for c in message:
  392. if c == '\b':
  393. self.linepos -= 1
  394. else:
  395. if c == '\r':
  396. pos = self.cmd_output.GetCurLine()[1]
  397. # self.cmd_output.SetCurrentPos(pos)
  398. else:
  399. self.cmd_output.SetCurrentPos(self.linepos)
  400. self.cmd_output.ReplaceSelection(c)
  401. self.linepos = self.cmd_output.GetCurrentPos()
  402. if c != ' ':
  403. last_c = c
  404. if last_c not in ('0123456789'):
  405. self.cmd_output.AddTextWrapped('\n', wrap=None)
  406. self.linepos = -1
  407. else:
  408. self.linepos = -1 # don't force position
  409. if '\n' not in message:
  410. self.cmd_output.AddTextWrapped(message, wrap=60)
  411. else:
  412. self.cmd_output.AddTextWrapped(message, wrap=None)
  413. p2 = self.cmd_output.GetCurrentPos()
  414. if p2 >= p1:
  415. self.cmd_output.StartStyling(p1, 0xff)
  416. if type == 'error':
  417. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  418. elif type == 'warning':
  419. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  420. elif type == 'message':
  421. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  422. else: # unknown
  423. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  424. self.cmd_output.EnsureCaretVisible()
  425. def OnCmdProgress(self, event):
  426. """!Update progress message info"""
  427. self.console_progressbar.SetValue(event.value)
  428. def OnCmdAbort(self, event):
  429. """!Abort running command"""
  430. self.cmdThread.abort()
  431. def OnCmdRun(self, event):
  432. """!Run command"""
  433. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  434. def OnCmdDone(self, event):
  435. """!Command done (or aborted)"""
  436. if event.aborted:
  437. # Thread aborted (using our convention of None return)
  438. self.WriteLog(_('Please note that the data are left in incosistent stage '
  439. 'and can be corrupted'), self.cmd_output.StyleWarning)
  440. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  441. _('Command aborted'),
  442. (time.time() - event.time)))
  443. # pid=self.cmdThread.requestId)
  444. else:
  445. try:
  446. # Process results here
  447. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  448. _('Command finished'),
  449. (time.time() - event.time)))
  450. # pid=event.pid)
  451. except KeyError:
  452. # stopped deamon
  453. pass
  454. if event.onDone:
  455. event.onDone(returncode = event.returncode)
  456. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  457. self.cmd_output_timer.Stop()
  458. # set focus on prompt
  459. if self.parent.GetName() == "LayerManager":
  460. self.parent.cmdinput.SetFocus()
  461. self.btn_abort.Enable(False)
  462. else:
  463. # updated command dialog
  464. dialog = self.parent.parent
  465. if hasattr(self.parent.parent, "btn_abort"):
  466. dialog.btn_abort.Enable(False)
  467. if hasattr(self.parent.parent, "btn_cancel"):
  468. dialog.btn_cancel.Enable(True)
  469. if hasattr(self.parent.parent, "btn_clipboard"):
  470. dialog.btn_clipboard.Enable(True)
  471. if hasattr(self.parent.parent, "btn_help"):
  472. dialog.btn_help.Enable(True)
  473. dialog.btn_run.Enable(True)
  474. if event.returncode == 0 and \
  475. not event.aborted and hasattr(dialog, "addbox") and \
  476. dialog.addbox.IsChecked():
  477. # add new map into layer tree
  478. if dialog.outputType in ('raster', 'vector'):
  479. # add layer into layer tree
  480. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  481. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param='output')
  482. winName = self.parent.parent.parent.GetName()
  483. if winName == 'LayerManager':
  484. mapTree = self.parent.parent.parent.curr_page.maptree
  485. else: # GMConsole
  486. mapTree = self.parent.parent.parent.parent.curr_page.maptree
  487. if dialog.outputType == 'raster':
  488. lcmd = ['d.rast',
  489. 'map=%s' % name]
  490. else:
  491. lcmd = ['d.vect',
  492. 'map=%s' % name]
  493. mapTree.AddLayer(ltype=dialog.outputType,
  494. lcmd=lcmd,
  495. lname=name)
  496. if dialog.get_dcmd is None and \
  497. dialog.closebox.IsChecked():
  498. time.sleep(1)
  499. dialog.Close()
  500. event.Skip()
  501. def OnProcessPendingOutputWindowEvents(self, event):
  502. self.ProcessPendingEvents()
  503. class GMStdout:
  504. """!GMConsole standard output
  505. Based on FrameOutErr.py
  506. Name: FrameOutErr.py
  507. Purpose: Redirecting stdout / stderr
  508. Author: Jean-Michel Fauth, Switzerland
  509. Copyright: (c) 2005-2007 Jean-Michel Fauth
  510. Licence: GPL
  511. """
  512. def __init__(self, parent):
  513. self.parent = parent # GMConsole
  514. def write(self, s):
  515. if len(s) == 0 or s == '\n':
  516. return
  517. for line in s.splitlines():
  518. if len(line) == 0:
  519. continue
  520. evt = wxCmdOutput(text=line + '\n',
  521. type='')
  522. wx.PostEvent(self.parent.cmd_output, evt)
  523. class GMStderr:
  524. """!GMConsole standard error output
  525. Based on FrameOutErr.py
  526. Name: FrameOutErr.py
  527. Purpose: Redirecting stdout / stderr
  528. Author: Jean-Michel Fauth, Switzerland
  529. Copyright: (c) 2005-2007 Jean-Michel Fauth
  530. Licence: GPL
  531. """
  532. def __init__(self, parent):
  533. self.parent = parent # GMConsole
  534. self.type = ''
  535. self.message = ''
  536. self.printMessage = False
  537. def write(self, s):
  538. if "GtkPizza" in s:
  539. return
  540. # remove/replace escape sequences '\b' or '\r' from stream
  541. progressValue = -1
  542. for line in s.splitlines():
  543. if len(line) == 0:
  544. continue
  545. if 'GRASS_INFO_PERCENT' in line:
  546. value = int(line.rsplit(':', 1)[1].strip())
  547. if value >= 0 and value < 100:
  548. progressValue = value
  549. else:
  550. progressValue = 0
  551. elif 'GRASS_INFO_MESSAGE' in line:
  552. self.type = 'message'
  553. self.message += line.split(':', 1)[1].strip() + '\n'
  554. elif 'GRASS_INFO_WARNING' in line:
  555. self.type = 'warning'
  556. self.message += line.split(':', 1)[1].strip() + '\n'
  557. elif 'GRASS_INFO_ERROR' in line:
  558. self.type = 'error'
  559. self.message += line.split(':', 1)[1].strip() + '\n'
  560. elif 'GRASS_INFO_END' in line:
  561. self.printMessage = True
  562. elif self.type == '':
  563. if len(line) == 0:
  564. continue
  565. evt = wxCmdOutput(text=line,
  566. type='')
  567. wx.PostEvent(self.parent.cmd_output, evt)
  568. elif len(line) > 0:
  569. self.message += line.strip() + '\n'
  570. if self.printMessage and len(self.message) > 0:
  571. evt = wxCmdOutput(text=self.message,
  572. type=self.type)
  573. wx.PostEvent(self.parent.cmd_output, evt)
  574. self.type = ''
  575. self.message = ''
  576. self.printMessage = False
  577. # update progress message
  578. if progressValue > -1:
  579. # self.gmgauge.SetValue(progressValue)
  580. evt = wxCmdProgress(value=progressValue)
  581. wx.PostEvent(self.parent.console_progressbar, evt)
  582. class GMStc(wx.stc.StyledTextCtrl):
  583. """!Styled GMConsole
  584. Based on FrameOutErr.py
  585. Name: FrameOutErr.py
  586. Purpose: Redirecting stdout / stderr
  587. Author: Jean-Michel Fauth, Switzerland
  588. Copyright: (c) 2005-2007 Jean-Michel Fauth
  589. Licence: GPL
  590. """
  591. def __init__(self, parent, id, margin=False, wrap=None):
  592. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  593. self.parent = parent
  594. #
  595. # styles
  596. #
  597. self.StyleDefault = 0
  598. self.StyleDefaultSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  599. self.StyleCommand = 1
  600. self.StyleCommandSpec = "face:Courier New,size:10,fore:#000000,back:#bcbcbc"
  601. self.StyleOutput = 2
  602. self.StyleOutputSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  603. # fatal error
  604. self.StyleError = 3
  605. self.StyleErrorSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  606. # warning
  607. self.StyleWarning = 4
  608. self.StyleWarningSpec = "face:Courier New,size:10,fore:#0000FF,back:#FFFFFF"
  609. # message
  610. self.StyleMessage = 5
  611. self.StyleMessageSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  612. # unknown
  613. self.StyleUnknown = 6
  614. self.StyleUnknownSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  615. # default and clear => init
  616. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  617. self.StyleClearAll()
  618. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  619. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  620. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  621. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  622. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  623. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  624. #
  625. # line margins
  626. #
  627. # TODO print number only from cmdlog
  628. self.SetMarginWidth(1, 0)
  629. self.SetMarginWidth(2, 0)
  630. if margin:
  631. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  632. self.SetMarginWidth(0, 30)
  633. else:
  634. self.SetMarginWidth(0, 0)
  635. #
  636. # miscellaneous
  637. #
  638. self.SetViewWhiteSpace(False)
  639. self.SetTabWidth(4)
  640. self.SetUseTabs(False)
  641. self.UsePopUp(True)
  642. self.SetSelBackground(True, "#FFFF00")
  643. self.SetUseHorizontalScrollBar(True)
  644. #
  645. # bindins
  646. #
  647. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  648. def OnDestroy(self, evt):
  649. """!The clipboard contents can be preserved after
  650. the app has exited"""
  651. wx.TheClipboard.Flush()
  652. evt.Skip()
  653. def AddTextWrapped(self, txt, wrap=None):
  654. """!Add string to text area.
  655. String is wrapped and linesep is also added to the end
  656. of the string"""
  657. if wrap:
  658. txt = textwrap.fill(txt, wrap) + '\n'
  659. else:
  660. if txt[-1] != '\n':
  661. txt += '\n'
  662. if '\r' in txt:
  663. self.parent.linePos = -1
  664. for seg in txt.split('\r'):
  665. if self.parent.linePos > -1:
  666. self.SetCurrentPos(self.parent.linePos)
  667. self.ReplaceSelection(seg)
  668. else:
  669. self.parent.linePos = self.GetCurrentPos()
  670. self.AddText(seg)
  671. else:
  672. self.parent.linePos = self.GetCurrentPos()
  673. try:
  674. self.AddText(txt)
  675. except UnicodeDecodeError:
  676. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  677. if enc:
  678. txt = unicode(txt, enc)
  679. elif os.environ.has_key('GRASS_DB_ENCODING'):
  680. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  681. else:
  682. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  683. self.AddText(txt)