goutput.py 25 KB

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