goutput.py 27 KB

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