goutput.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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. # process GRASS command with argument
  336. self.cmdThread.RunCmd(GrassCmd,
  337. onDone,
  338. cmdlist,
  339. self.cmd_stdout, self.cmd_stderr)
  340. self.btn_abort.Enable()
  341. self.cmd_output_timer.Start(50)
  342. return None
  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.parent.notebook.GetSelection() != self.parent.goutput.pageid:
  377. textP = self.parent.notebook.GetPageText(self.parent.goutput.pageid)
  378. if textP[-1] != ')':
  379. textP += ' (...)'
  380. self.parent.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. else:
  447. try:
  448. # Process results here
  449. self.WriteCmdLog('(%s) %s (%d sec)' % (str(time.ctime()),
  450. _('Command finished'),
  451. (time.time() - event.time)))
  452. # pid=event.pid)
  453. except KeyError:
  454. # stopped deamon
  455. pass
  456. if event.onDone:
  457. event.onDone(returncode = event.returncode)
  458. self.console_progressbar.SetValue(0) # reset progress bar on '0%'
  459. self.cmd_output_timer.Stop()
  460. # set focus on prompt
  461. if self.parent.GetName() == "LayerManager":
  462. self.parent.cmdinput.SetFocus()
  463. self.btn_abort.Enable(False)
  464. else:
  465. # updated command dialog
  466. dialog = self.parent.parent
  467. if hasattr(self.parent.parent, "btn_abort"):
  468. dialog.btn_abort.Enable(False)
  469. if hasattr(self.parent.parent, "btn_cancel"):
  470. dialog.btn_cancel.Enable(True)
  471. if hasattr(self.parent.parent, "btn_clipboard"):
  472. dialog.btn_clipboard.Enable(True)
  473. if hasattr(self.parent.parent, "btn_help"):
  474. dialog.btn_help.Enable(True)
  475. dialog.btn_run.Enable(True)
  476. if event.returncode == 0 and \
  477. not event.aborted and hasattr(dialog, "addbox") and \
  478. dialog.addbox.IsChecked():
  479. # add new map into layer tree
  480. if dialog.outputType in ('raster', 'vector'):
  481. # add layer into layer tree
  482. cmd = dialog.notebookpanel.createCmd(ignoreErrors = True)
  483. name = utils.GetLayerNameFromCmd(cmd, fullyQualified=True, param='output')
  484. winName = self.parent.parent.parent.GetName()
  485. if winName == 'LayerManager':
  486. mapTree = self.parent.parent.parent.curr_page.maptree
  487. else: # GMConsole
  488. mapTree = self.parent.parent.parent.parent.curr_page.maptree
  489. if dialog.outputType == 'raster':
  490. lcmd = ['d.rast',
  491. 'map=%s' % name]
  492. else:
  493. lcmd = ['d.vect',
  494. 'map=%s' % name]
  495. mapTree.AddLayer(ltype=dialog.outputType,
  496. lcmd=lcmd,
  497. lname=name)
  498. if dialog.get_dcmd is None and \
  499. dialog.closebox.IsChecked():
  500. time.sleep(1)
  501. dialog.Close()
  502. event.Skip()
  503. def OnProcessPendingOutputWindowEvents(self, event):
  504. self.ProcessPendingEvents()
  505. class GMStdout:
  506. """!GMConsole standard output
  507. Based on FrameOutErr.py
  508. Name: FrameOutErr.py
  509. Purpose: Redirecting stdout / stderr
  510. Author: Jean-Michel Fauth, Switzerland
  511. Copyright: (c) 2005-2007 Jean-Michel Fauth
  512. Licence: GPL
  513. """
  514. def __init__(self, parent):
  515. self.parent = parent # GMConsole
  516. def write(self, s):
  517. if len(s) == 0 or s == '\n':
  518. return
  519. for line in s.splitlines():
  520. if len(line) == 0:
  521. continue
  522. evt = wxCmdOutput(text=line + '\n',
  523. type='')
  524. wx.PostEvent(self.parent.cmd_output, evt)
  525. class GMStderr:
  526. """!GMConsole standard error output
  527. Based on FrameOutErr.py
  528. Name: FrameOutErr.py
  529. Purpose: Redirecting stdout / stderr
  530. Author: Jean-Michel Fauth, Switzerland
  531. Copyright: (c) 2005-2007 Jean-Michel Fauth
  532. Licence: GPL
  533. """
  534. def __init__(self, parent):
  535. self.parent = parent # GMConsole
  536. self.type = ''
  537. self.message = ''
  538. self.printMessage = False
  539. def write(self, s):
  540. if "GtkPizza" in s:
  541. return
  542. # remove/replace escape sequences '\b' or '\r' from stream
  543. progressValue = -1
  544. for line in s.splitlines():
  545. if len(line) == 0:
  546. continue
  547. if 'GRASS_INFO_PERCENT' in line:
  548. value = int(line.rsplit(':', 1)[1].strip())
  549. if value >= 0 and value < 100:
  550. progressValue = value
  551. else:
  552. progressValue = 0
  553. elif 'GRASS_INFO_MESSAGE' in line:
  554. self.type = 'message'
  555. self.message += line.split(':', 1)[1].strip() + '\n'
  556. elif 'GRASS_INFO_WARNING' in line:
  557. self.type = 'warning'
  558. self.message += line.split(':', 1)[1].strip() + '\n'
  559. elif 'GRASS_INFO_ERROR' in line:
  560. self.type = 'error'
  561. self.message += line.split(':', 1)[1].strip() + '\n'
  562. elif 'GRASS_INFO_END' in line:
  563. self.printMessage = True
  564. elif self.type == '':
  565. if len(line) == 0:
  566. continue
  567. evt = wxCmdOutput(text=line,
  568. type='')
  569. wx.PostEvent(self.parent.cmd_output, evt)
  570. elif len(line) > 0:
  571. self.message += line.strip() + '\n'
  572. if self.printMessage and len(self.message) > 0:
  573. evt = wxCmdOutput(text=self.message,
  574. type=self.type)
  575. wx.PostEvent(self.parent.cmd_output, evt)
  576. self.type = ''
  577. self.message = ''
  578. self.printMessage = False
  579. # update progress message
  580. if progressValue > -1:
  581. # self.gmgauge.SetValue(progressValue)
  582. evt = wxCmdProgress(value=progressValue)
  583. wx.PostEvent(self.parent.console_progressbar, evt)
  584. class GMStc(wx.stc.StyledTextCtrl):
  585. """!Styled GMConsole
  586. Based on FrameOutErr.py
  587. Name: FrameOutErr.py
  588. Purpose: Redirecting stdout / stderr
  589. Author: Jean-Michel Fauth, Switzerland
  590. Copyright: (c) 2005-2007 Jean-Michel Fauth
  591. Licence: GPL
  592. """
  593. def __init__(self, parent, id, margin=False, wrap=None):
  594. wx.stc.StyledTextCtrl.__init__(self, parent, id)
  595. self.parent = parent
  596. #
  597. # styles
  598. #
  599. self.StyleDefault = 0
  600. self.StyleDefaultSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  601. self.StyleCommand = 1
  602. self.StyleCommandSpec = "face:Courier New,size:10,fore:#000000,back:#bcbcbc"
  603. self.StyleOutput = 2
  604. self.StyleOutputSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  605. # fatal error
  606. self.StyleError = 3
  607. self.StyleErrorSpec = "face:Courier New,size:10,fore:#7F0000,back:#FFFFFF"
  608. # warning
  609. self.StyleWarning = 4
  610. self.StyleWarningSpec = "face:Courier New,size:10,fore:#0000FF,back:#FFFFFF"
  611. # message
  612. self.StyleMessage = 5
  613. self.StyleMessageSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  614. # unknown
  615. self.StyleUnknown = 6
  616. self.StyleUnknownSpec = "face:Courier New,size:10,fore:#000000,back:#FFFFFF"
  617. # default and clear => init
  618. self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, self.StyleDefaultSpec)
  619. self.StyleClearAll()
  620. self.StyleSetSpec(self.StyleCommand, self.StyleCommandSpec)
  621. self.StyleSetSpec(self.StyleOutput, self.StyleOutputSpec)
  622. self.StyleSetSpec(self.StyleError, self.StyleErrorSpec)
  623. self.StyleSetSpec(self.StyleWarning, self.StyleWarningSpec)
  624. self.StyleSetSpec(self.StyleMessage, self.StyleMessageSpec)
  625. self.StyleSetSpec(self.StyleUnknown, self.StyleUnknownSpec)
  626. #
  627. # line margins
  628. #
  629. # TODO print number only from cmdlog
  630. self.SetMarginWidth(1, 0)
  631. self.SetMarginWidth(2, 0)
  632. if margin:
  633. self.SetMarginType(0, wx.stc.STC_MARGIN_NUMBER)
  634. self.SetMarginWidth(0, 30)
  635. else:
  636. self.SetMarginWidth(0, 0)
  637. #
  638. # miscellaneous
  639. #
  640. self.SetViewWhiteSpace(False)
  641. self.SetTabWidth(4)
  642. self.SetUseTabs(False)
  643. self.UsePopUp(True)
  644. self.SetSelBackground(True, "#FFFF00")
  645. self.SetUseHorizontalScrollBar(True)
  646. #
  647. # bindins
  648. #
  649. self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
  650. def OnDestroy(self, evt):
  651. """!The clipboard contents can be preserved after
  652. the app has exited"""
  653. wx.TheClipboard.Flush()
  654. evt.Skip()
  655. def AddTextWrapped(self, txt, wrap=None):
  656. """!Add string to text area.
  657. String is wrapped and linesep is also added to the end
  658. of the string"""
  659. if wrap:
  660. txt = textwrap.fill(txt, wrap) + '\n'
  661. else:
  662. if txt[-1] != '\n':
  663. txt += '\n'
  664. if '\r' in txt:
  665. self.parent.linePos = -1
  666. for seg in txt.split('\r'):
  667. if self.parent.linePos > -1:
  668. self.SetCurrentPos(self.parent.linePos)
  669. self.ReplaceSelection(seg)
  670. else:
  671. self.parent.linePos = self.GetCurrentPos()
  672. self.AddText(seg)
  673. else:
  674. self.parent.linePos = self.GetCurrentPos()
  675. try:
  676. self.AddText(txt)
  677. except UnicodeDecodeError:
  678. enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
  679. if enc:
  680. txt = unicode(txt, enc)
  681. elif os.environ.has_key('GRASS_DB_ENCODING'):
  682. txt = unicode(txt, os.environ['GRASS_DB_ENCODING'])
  683. else:
  684. txt = _('Unable to encode text. Please set encoding in GUI preferences.') + '\n'
  685. self.AddText(txt)