goutput.py 25 KB

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