goutput.py 27 KB

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