goutput.py 30 KB

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