fixed performance issue with StringIO.
[sface.git] / sface / logwindow.py
1 import sys
2 from cStringIO import StringIO
3
4 from PyQt4.QtCore import *
5 from PyQt4.QtGui import *
6
7 from sface.config import config
8
9 import time
10
11 class LogIO(QObject):
12     def __init__(self, parent, old_stdout):
13         QObject.__init__(self, parent)
14         self.io = StringIO()
15         self.old_stdout = old_stdout
16
17     def write(self, txt):
18         self.io.write(txt)
19         self.parent().update()
20
21     def getText(self):
22         self.old_stdout.write("getText: ENTERING\n")
23         val = self.io.getvalue()
24         # looks like there is no other way
25         # to empty the StringIO
26         del self.io
27         self.io = StringIO()
28         self.old_stdout.write("getText: GOT VALUE\n")
29         self.old_stdout.write(val + "\n")
30         return val
31
32 class LogWindow(QDialog):
33     def __init__(self, parent=None):
34         QWidget.__init__(self, parent)
35         self.setWindowTitle("SFI Log")
36         self.text = QTextBrowser(self)
37         self.text.ensureCursorVisible()
38
39         layout = QVBoxLayout()
40         layout.addWidget(self.text)
41         self.setLayout(layout)
42
43         self.logio = LogIO(self, sys.stdout)
44
45     def redirectOutput(self):
46         print "\n\nRedirecting all output to Log Window. Please open the log window to see the output\n"
47         self.old_stdout = sys.stdout
48         self.old_stderr = sys.stderr
49         sys.stdout = self.logio
50         sys.stderr = self.logio
51
52     def update(self):
53         #starttime = time.time()
54         #self.logio.old_stdout.write("update: entering\n")#.flush()
55         #self.logio.old_stdout.write('one\n')#.flush()
56         self.text.insertPlainText(self.logio.getText())
57         #self.logio.old_stdout.write('two\n')#.flush()
58         c = self.text.textCursor()
59         #self.logio.old_stdout.write('three\n')#.flush()
60         c.movePosition(QTextCursor.End)
61         #self.logio.old_stdout.write('four\n')#.flush()
62         self.text.setTextCursor(c)
63         #self.logio.old_stdout.write('five\n')#.flush()
64         #self.logio.old_stdout.write("update: done \n")# + time.strftime(('%M:%S'),"[%.3f s]"%(time.time() - starttime)))#.flush()