goutput.py 29 KB

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