File: repl_widget.py

package info (click to toggle)
python-pyqtgraph 0.13.7-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,068 kB
  • sloc: python: 54,043; makefile: 129; ansic: 40; sh: 2
file content (219 lines) | stat: -rw-r--r-- 7,711 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import code, sys, traceback
from ..Qt import QtWidgets, QtGui, QtCore
from ..functions import mkBrush
from .CmdInput import CmdInput


class ReplWidget(QtWidgets.QWidget):
    sigCommandEntered = QtCore.Signal(object, object)  # self, command
    sigCommandRaisedException = QtCore.Signal(object, object)  # self, exc

    def __init__(self, globals, locals, parent=None):
        self.globals = globals
        self.locals = locals
        self._lastCommandRow = None
        self._commandBuffer = []  # buffer to hold multiple lines of input
        self.stdoutInterceptor = StdoutInterceptor(self.write)
        self.ps1 = ">>> "
        self.ps2 = "... "

        QtWidgets.QWidget.__init__(self, parent=parent)

        self._setupUi()

        # define text styles
        isDark = self.output.palette().color(QtGui.QPalette.ColorRole.Base).value() < 128
        outputBlockFormat = QtGui.QTextBlockFormat()
        outputFirstLineBlockFormat = QtGui.QTextBlockFormat(outputBlockFormat)
        outputFirstLineBlockFormat.setTopMargin(5)
        outputCharFormat = QtGui.QTextCharFormat()
        outputCharFormat.setFontWeight(QtGui.QFont.Weight.Normal)
        cmdBlockFormat = QtGui.QTextBlockFormat()
        cmdBlockFormat.setBackground(mkBrush("#335" if isDark else "#CCF"))
        cmdCharFormat = QtGui.QTextCharFormat()
        cmdCharFormat.setFontWeight(QtGui.QFont.Weight.Bold)
        self.textStyles = {
            'command': (cmdCharFormat, cmdBlockFormat),
            'output': (outputCharFormat, outputBlockFormat),
            'output_first_line': (outputCharFormat, outputFirstLineBlockFormat),
        }

        self.input.ps1 = self.ps1
        self.input.ps2 = self.ps2

    def _setupUi(self):
        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.setLayout(self.layout)

        self.output = QtWidgets.QTextEdit(self)
        font = QtGui.QFont()
        font.setFamily("Courier New")
        font.setStyleStrategy(QtGui.QFont.StyleStrategy.PreferAntialias)
        self.output.setFont(font)
        self.output.setReadOnly(True)
        self.layout.addWidget(self.output)
        
        # put input box in a horizontal layout so we can easily place buttons at the end
        self.inputWidget = QtWidgets.QWidget(self)
        self.layout.addWidget(self.inputWidget)
        self.inputLayout = QtWidgets.QHBoxLayout()
        self.inputWidget.setLayout(self.inputLayout)
        self.inputLayout.setContentsMargins(0, 0, 0, 0)

        self.input = CmdInput(parent=self)
        self.inputLayout.addWidget(self.input)

        self.input.sigExecuteCmd.connect(self.runCmd)

    def runCmd(self, cmd):
        if '\n' in cmd:
            for line in cmd.split('\n'):
                self.runCmd(line)
            return

        if len(self._commandBuffer) == 0:
            self.write(f"{self.ps1}{cmd}\n", style='command')
        else:
            self.write(f"{self.ps2}{cmd}\n", style='command')
        
        self.sigCommandEntered.emit(self, cmd)
        self._commandBuffer.append(cmd)

        fullcmd = '\n'.join(self._commandBuffer)
        try:
            cmdCode = code.compile_command(fullcmd)
            self.input.setMultiline(False)
        except Exception:
            # cannot continue processing this command; reset and print exception
            self._commandBuffer = []
            self.displayException()
            self.input.setMultiline(False)
        else:
            if cmdCode is None:
                # incomplete input; wait for next line
                self.input.setMultiline(True)
                return

            self._commandBuffer = []

            # run command
            try:
                with self.stdoutInterceptor:
                    exec(cmdCode, self.globals(), self.locals())
            except Exception as exc:
                self.displayException()
                self.sigCommandRaisedException.emit(self, exc)

            # Add a newline if the output did not
            cursor = self.output.textCursor()
            if cursor.columnNumber() > 0:
                self.write('\n')

    def write(self, strn, style='output', scrollToBottom='auto'):
        """Write a string into the console.

        If scrollToBottom is 'auto', then the console is automatically scrolled
        to fit the new text only if it was already at the bottom.
        """
        isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread()
        if not isGuiThread:
            sys.__stdout__.write(strn)
            return

        cursor = self.output.textCursor()
        cursor.movePosition(QtGui.QTextCursor.MoveOperation.End)
        self.output.setTextCursor(cursor)

        sb = self.output.verticalScrollBar()
        scroll = sb.value()
        if scrollToBottom == 'auto':
            atBottom = scroll == sb.maximum()
            scrollToBottom = atBottom

        row = cursor.blockNumber()
        if style == 'command':
            self._lastCommandRow = row

        if style == 'output' and row == self._lastCommandRow + 1:
            # adjust style for first line of output
            firstLine, endl, strn = strn.partition('\n')
            self._setTextStyle('output_first_line')
            self.output.insertPlainText(firstLine + endl)

        if len(strn) > 0:
            self._setTextStyle(style)
            self.output.insertPlainText(strn)
            # return to output style immediately to avoid seeing an extra line of command style
            if style != 'output':
                self._setTextStyle('output')

        if scrollToBottom:
            sb.setValue(sb.maximum())
        else:
            sb.setValue(scroll)

    def displayException(self):
        """
        Display the current exception and stack.
        """
        tb = traceback.format_exc()
        lines = []
        indent = 4
        prefix = '' 
        for l in tb.split('\n'):
            lines.append(" "*indent + prefix + l)
        self.write('\n'.join(lines))
        
    def _setTextStyle(self, style):
        charFormat, blockFormat = self.textStyles[style]
        cursor = self.output.textCursor()
        cursor.setBlockFormat(blockFormat)
        self.output.setCurrentCharFormat(charFormat)


class StdoutInterceptor:
    """Used to temporarily redirect writes meant for sys.stdout and sys.stderr to a new location
    """
    def __init__(self, writeFn):
        self._orig_stdout = None
        self._orig_stderr = None
        self.writeFn = writeFn

    def realOutputFiles(self):
        """Return the real sys.stdout and stderr (which are sometimes masked while running commands)
        """
        return (
            self._orig_stdout or sys.stdout,
            self._orig_stderr or sys.stderr
        )

    def print(self, *args):
        """Print to real stdout (for debugging)
        """
        self.realOutputFiles()[0].write(' '.join(map(str, args)) + "\n")

    def flush(self):
        # Need to implement this since we temporarily occlude sys.stdout
        pass

    def fileno(self):
        # Need to implement this since we temporarily occlude sys.stdout, and someone may be looking for it (faulthandler, for example)
        return 1

    def write(self, strn):
        self.writeFn(strn)

    def __enter__(self):
        self._orig_stdout = sys.stdout
        self._orig_stderr = sys.stderr
        sys.stdout = self
        sys.stderr = self

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout = self._orig_stdout
        sys.stderr = self._orig_stderr
        self._orig_stdout = None
        self._orig_stderr = None