goutput.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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. self.parent.curr_page.maptree.AddLayer(ltype=layertype,
  289. lcmd=cmdlist)
  290. else:
  291. #
  292. # other GRASS commands (r|v|g|...)
  293. #
  294. # switch to 'Command output'
  295. if switchPage:
  296. if self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
  297. self.parent.notebook.SetSelection(self.parent.goutput.pageid)
  298. self.parent.SetFocus() # -> set focus
  299. self.parent.Raise()
  300. # activate computational region (set with g.region)
  301. # for all non-display commands.
  302. if compReg:
  303. tmpreg = os.getenv("GRASS_REGION")
  304. if os.environ.has_key("GRASS_REGION"):
  305. del os.environ["GRASS_REGION"]
  306. if len(cmdlist) == 1:
  307. import menuform
  308. # process GRASS command without argument
  309. menuform.GUI().ParseCommand(cmdlist, parentframe=self)
  310. else:
  311. # process GRASS command with argument
  312. self.cmdThread.RunCmd(GrassCmd,
  313. onDone,
  314. cmdlist,
  315. self.cmd_stdout, self.cmd_stderr)
  316. self.btn_abort.Enable()
  317. self.cmd_output_timer.Start(50)
  318. return None
  319. # deactivate computational region and return to display settings
  320. if compReg and tmpreg:
  321. os.environ["GRASS_REGION"] = tmpreg
  322. else:
  323. # Send any other command to the shell. Send output to
  324. # console output window
  325. # if command is not a GRASS command, treat it like a shell command
  326. try:
  327. gcmd.Command(cmdlist,
  328. stdout=self.cmd_stdout,
  329. stderr=self.cmd_stderr)
  330. except gcmd.CmdError, e:
  331. print >> sys.stderr, e
  332. return None
  333. def ClearHistory(self, event):
  334. """!Clear history of commands"""
  335. self.cmd_output.ClearAll()
  336. self.console_progressbar.SetValue(0)
  337. def SaveHistory(self, event):
  338. """!Save history of commands"""
  339. self.history = self.cmd_output.GetSelectedText()
  340. if self.history == '':
  341. self.history = self.cmd_output.GetText()
  342. # add newline if needed
  343. if len(self.history) > 0 and self.history[-1] != '\n':
  344. self.history += '\n'
  345. wildcard = "Text file (*.txt)|*.txt"
  346. dlg = wx.FileDialog(
  347. self, message=_("Save file as..."), defaultDir=os.getcwd(),
  348. defaultFile="grass_cmd_history.txt", wildcard=wildcard,
  349. style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
  350. # Show the dialog and retrieve the user response. If it is the OK response,
  351. # process the data.
  352. if dlg.ShowModal() == wx.ID_OK:
  353. path = dlg.GetPath()
  354. output = open(path, "w")
  355. output.write(self.history)
  356. output.close()
  357. dlg.Destroy()
  358. def GetCmd(self):
  359. """!Get running command or None"""
  360. return self.requestQ.get()
  361. def OnCmdOutput(self, event):
  362. """!Print command output"""
  363. message = event.text
  364. type = event.type
  365. if self.parent.notebook.GetSelection() != self.parent.goutput.pageid:
  366. textP = self.parent.notebook.GetPageText(self.parent.goutput.pageid)
  367. if textP[-1] != ')':
  368. textP += ' (...)'
  369. self.parent.notebook.SetPageText(self.parent.goutput.pageid,
  370. textP)
  371. # message prefix
  372. if type == 'warning':
  373. messege = 'WARNING: ' + message
  374. elif type == 'error':
  375. message = 'ERROR: ' + message
  376. p1 = self.cmd_output.GetEndStyled()
  377. self.cmd_output.GotoPos(p1)
  378. if '\b' in message:
  379. if self.linepos < 0:
  380. self.linepos = p1
  381. last_c = ''
  382. for c in message:
  383. if c == '\b':
  384. self.linepos -= 1
  385. else:
  386. if c == '\r':
  387. pos = self.cmd_output.GetCurLine()[1]
  388. # self.cmd_output.SetCurrentPos(pos)
  389. else:
  390. self.cmd_output.SetCurrentPos(self.linepos)
  391. self.cmd_output.ReplaceSelection(c)
  392. self.linepos = self.cmd_output.GetCurrentPos()
  393. if c != ' ':
  394. last_c = c
  395. if last_c not in ('0123456789'):
  396. self.cmd_output.AddTextWrapped('\n', wrap=None)
  397. self.linepos = -1
  398. else:
  399. self.linepos = -1 # don't force position
  400. if '\n' not in message:
  401. self.cmd_output.AddTextWrapped(message, wrap=60)
  402. else:
  403. self.cmd_output.AddTextWrapped(message, wrap=None)
  404. p2 = self.cmd_output.GetCurrentPos()
  405. if p2 >= p1:
  406. self.cmd_output.StartStyling(p1, 0xff)
  407. if type == 'error':
  408. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleError)
  409. elif type == 'warning':
  410. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleWarning)
  411. elif type == 'message':
  412. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleMessage)
  413. else: # unknown
  414. self.cmd_output.SetStyling(p2 - p1, self.cmd_output.StyleUnknown)
  415. self.cmd_output.EnsureCaretVisible()
  416. def OnCmdProgress(self, event):
  417. """!Update progress message info"""
  418. self.console_progressbar.SetValue(event.value)
  419. def OnCmdAbort(self, event):
  420. """!Abort running command"""
  421. self.cmdThread.abort()
  422. def OnCmdRun(self, event):
  423. """!Run command"""
  424. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)))
  425. def OnCmdDone(self, event):
  426. """!Command done (or aborted)"""
  427. if event.aborted:
  428. # Thread aborted (using our convention of None return)
  429. self.WriteLog(_('Please note that the data are left in incosistent stage '
  430. 'and can be corrupted'), self.cmd_output.StyleWarning)
  431. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  432. _('Command aborted'),
  433. (time.time() - event.time)))
  434. # pid=self.cmdThread.requestId)
  435. else:
  436. try:
  437. # Process results here
  438. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  439. _('Command finished'),
  440. (time.time() - event.time)))
  441. # pid=event.pid)
  442. except KeyError:
  443. # stopped deamon
  444. pass
  445. if event.onDone:
  446. event.onDone(returncode = event.returncode)
  447. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  448. self.cmd_output_timer.Stop()
  449. # set focus on prompt
  450. if self.parent.GetName() == "LayerManager":
  451. self.parent.cmdinput.SetFocus()
  452. self.btn_abort.Enable(False)
  453. else:
  454. # updated command dialog
  455. dialog = self.parent.parent
  456. if hasattr(self.parent.parent, "btn_abort"):
  457. dialog.btn_abort.Enable(False)
  458. if hasattr(self.parent.parent, "btn_cancel"):
  459. dialog.btn_cancel.Enable(True)
  460. if hasattr(self.parent.parent, "btn_clipboard"):
  461. dialog.btn_clipboard.Enable(True)
  462. if hasattr(self.parent.parent, "btn_help"):
  463. dialog.btn_help.Enable(True)
  464. dialog.btn_run.Enable(True)
  465. if event.returncode == 0 and \
  466. not event.aborted and hasattr(dialog, "addbox") and \
  467. dialog.addbox.IsChecked():
  468. # add new map into layer tree
  469. if dialog.outputType in ('raster', 'vector'):
  470. # add layer into layer tree
  471. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  472. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param='output')
  473. winName = self.parent.parent.parent.GetName()
  474. if winName == 'LayerManager':
  475. mapTree = self.parent.parent.parent.curr_page.maptree
  476. else: # GMConsole
  477. mapTree = self.parent.parent.parent.parent.curr_page.maptree
  478. if dialog.outputType == 'raster':
  479. lcmd = ['d.rast',
  480. 'map=%s' % name]
  481. else:
  482. lcmd = ['d.vect',
  483. 'map=%s' % name]
  484. mapTree.AddLayer(ltype=dialog.outputType,
  485. lcmd=lcmd,
  486. lname=name)
  487. if dialog.get_dcmd is None and \
  488. dialog.closebox.IsChecked():
  489. time.sleep(1)
  490. dialog.Close()
  491. event.Skip()
  492. def OnProcessPendingOutputWindowEvents(self, event):
  493. self.ProcessPendingEvents()
  494. class GMStdout:
  495. """!GMConsole standard output
  496. Based on FrameOutErr.py
  497. Name: FrameOutErr.py
  498. Purpose: Redirecting stdout / stderr
  499. Author: Jean-Michel Fauth, Switzerland
  500. Copyright: (c) 2005-2007 Jean-Michel Fauth
  501. Licence: GPL
  502. """
  503. def __init__(self, parent):
  504. self.parent = parent # GMConsole
  505. def write(self, s):
  506. if len(s) == 0 or s == '\n':
  507. return
  508. for line in s.splitlines():
  509. if len(line) == 0:
  510. continue
  511. evt = wxCmdOutput(text=line + '\n',
  512. type='')
  513. wx.PostEvent(self.parent.cmd_output, evt)
  514. class GMStderr:
  515. """!GMConsole standard error output
  516. Based on FrameOutErr.py
  517. Name: FrameOutErr.py
  518. Purpose: Redirecting stdout / stderr
  519. Author: Jean-Michel Fauth, Switzerland
  520. Copyright: (c) 2005-2007 Jean-Michel Fauth
  521. Licence: GPL
  522. """
  523. def __init__(self, parent):
  524. self.parent = parent # GMConsole
  525. self.type = ''
  526. self.message = ''
  527. self.printMessage = False
  528. def write(self, s):
  529. if "GtkPizza" in s:
  530. return
  531. # remove/replace escape sequences '\b' or '\r' from stream
  532. progressValue = -1
  533. for line in s.splitlines():
  534. if len(line) == 0:
  535. continue
  536. if 'GRASS_INFO_PERCENT' in line:
  537. value = int(line.rsplit(':', 1)[1].strip())
  538. if value >= 0 and value < 100:
  539. progressValue = value
  540. else:
  541. progressValue = 0
  542. elif 'GRASS_INFO_MESSAGE' in line:
  543. self.type = 'message'
  544. self.message += line.split(':', 1)[1].strip() + '\n'
  545. elif 'GRASS_INFO_WARNING' in line:
  546. self.type = 'warning'
  547. self.message += line.split(':', 1)[1].strip() + '\n'
  548. elif 'GRASS_INFO_ERROR' in line:
  549. self.type = 'error'
  550. self.message += line.split(':', 1)[1].strip() + '\n'
  551. elif 'GRASS_INFO_END' in line:
  552. self.printMessage = True
  553. elif self.type == '':
  554. if len(line) == 0:
  555. continue
  556. evt = wxCmdOutput(text=line,
  557. type='')
  558. wx.PostEvent(self.parent.cmd_output, evt)
  559. elif len(line) > 0:
  560. self.message += line.strip() + '\n'
  561. if self.printMessage and len(self.message) > 0:
  562. evt = wxCmdOutput(text=self.message,
  563. type=self.type)
  564. wx.PostEvent(self.parent.cmd_output, evt)
  565. self.type = ''
  566. self.message = ''
  567. self.printMessage = False
  568. # update progress message
  569. if progressValue > -1:
  570. # self.gmgauge.SetValue(progressValue)
  571. evt = wxCmdProgress(value=progressValue)
  572. wx.PostEvent(self.parent.console_progressbar, evt)
  573. class GMStc(wx.stc.StyledTextCtrl):
  574. """!Styled GMConsole
  575. Based on FrameOutErr.py
  576. Name: FrameOutErr.py
  577. Purpose: Redirecting stdout / stderr
  578. Author: Jean-Michel Fauth, Switzerland
  579. Copyright: (c) 2005-2007 Jean-Michel Fauth
  580. Licence: GPL
  581. """
  582. def __init__(self, parent, id, margin=False, wrap=None):
  583. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  584. self.parent = parent
  585. #
  586. # styles
  587. #
  588. self.StyleDefault = 0
  589. self.StyleDefaultSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  590. self.StyleCommand = 1
  591. self.StyleCommandSpec = "face:Courier New,size:10,fore:#000000,back:#bcbcbc"
  592. self.StyleOutput = 2
  593. self.StyleOutputSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  594. # fatal error
  595. self.StyleError = 3
  596. self.StyleErrorSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  597. # warning
  598. self.StyleWarning = 4
  599. self.StyleWarningSpec = "face:Courier New,size:10,fore:#0000FF,back:#FFFFFF"
  600. # message
  601. self.StyleMessage = 5
  602. self.StyleMessageSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  603. # unknown
  604. self.StyleUnknown = 6
  605. self.StyleUnknownSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  606. # default and clear => init
  607. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  608. self.StyleClearAll()
  609. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  610. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  611. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  612. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  613. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  614. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  615. #
  616. # line margins
  617. #
  618. # TODO print number only from cmdlog
  619. self.SetMarginWidth(1, 0)
  620. self.SetMarginWidth(2, 0)
  621. if margin:
  622. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  623. self.SetMarginWidth(0, 30)
  624. else:
  625. self.SetMarginWidth(0, 0)
  626. #
  627. # miscellaneous
  628. #
  629. self.SetViewWhiteSpace(False)
  630. self.SetTabWidth(4)
  631. self.SetUseTabs(False)
  632. self.UsePopUp(True)
  633. self.SetSelBackground(True, "#FFFF00")
  634. self.SetUseHorizontalScrollBar(True)
  635. #
  636. # bindins
  637. #
  638. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  639. def OnDestroy(self, evt):
  640. """!The clipboard contents can be preserved after
  641. the app has exited"""
  642. wx.TheClipboard.Flush()
  643. evt.Skip()
  644. def AddTextWrapped(self, txt, wrap=None):
  645. """!Add string to text area.
  646. String is wrapped and linesep is also added to the end
  647. of the string"""
  648. if wrap:
  649. txt = textwrap.fill(txt, wrap) + '\n'
  650. else:
  651. if txt[-1] != '\n':
  652. txt += '\n'
  653. if '\r' in txt:
  654. self.parent.linePos = -1
  655. for seg in txt.split('\r'):
  656. if self.parent.linePos > -1:
  657. self.SetCurrentPos(self.parent.linePos)
  658. self.ReplaceSelection(seg)
  659. else:
  660. self.parent.linePos = self.GetCurrentPos()
  661. self.AddText(seg)
  662. else:
  663. self.parent.linePos = self.GetCurrentPos()
  664. try:
  665. self.AddText(txt)
  666. except UnicodeDecodeError:
  667. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  668. if enc:
  669. txt = unicode(txt, enc)
  670. elif os.environ.has_key('GRASS_DB_ENCODING'):
  671. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  672. else:
  673. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  674. self.AddText(txt)