goutput.py 26 KB

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