summaryrefslogtreecommitdiff
path: root/qutebrowser/misc/consolewidget.py
blob: 6d8d9916fd8dd352a64b8ae4c561e700cc8849be (plain)
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
# Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser.  If not, see <https://www.gnu.org/licenses/>.

"""Debugging console."""

import sys
import code
from typing import MutableSequence

from qutebrowser.qt.core import pyqtSignal, pyqtSlot, Qt
from qutebrowser.qt.widgets import QTextEdit, QWidget, QVBoxLayout, QApplication
from qutebrowser.qt.gui import QTextCursor

from qutebrowser.config import stylesheet
from qutebrowser.misc import cmdhistory, miscwidgets
from qutebrowser.utils import utils, objreg


console_widget = None


class ConsoleLineEdit(miscwidgets.CommandLineEdit):

    """A QLineEdit which executes entered code and provides a history.

    Attributes:
        _history: The command history of executed commands.

    Signals:
        execute: Emitted when a commandline should be executed.
    """

    execute = pyqtSignal(str)

    def __init__(self, _namespace, parent):
        """Constructor.

        Args:
            _namespace: The local namespace of the interpreter.
        """
        super().__init__(parent=parent)
        self._history = cmdhistory.History(parent=self)
        self.returnPressed.connect(self.on_return_pressed)

    @pyqtSlot()
    def on_return_pressed(self):
        """Execute the line of code which was entered."""
        self._history.stop()
        text = self.text()
        if text:
            self._history.append(text)
        self.execute.emit(text)
        self.setText('')

    def history_prev(self):
        """Go back in the history."""
        try:
            if not self._history.is_browsing():
                item = self._history.start(self.text().strip())
            else:
                item = self._history.previtem()
        except (cmdhistory.HistoryEmptyError,
                cmdhistory.HistoryEndReachedError):
            return
        self.setText(item)

    def history_next(self):
        """Go forward in the history."""
        if not self._history.is_browsing():
            return
        try:
            item = self._history.nextitem()
        except cmdhistory.HistoryEndReachedError:
            return
        self.setText(item)

    def keyPressEvent(self, e):
        """Override keyPressEvent to handle special keypresses."""
        if e.key() == Qt.Key.Key_Up:
            self.history_prev()
            e.accept()
        elif e.key() == Qt.Key.Key_Down:
            self.history_next()
            e.accept()
        elif e.modifiers() & Qt.KeyboardModifier.ControlModifier and e.key() == Qt.Key.Key_C:
            self.setText('')
            e.accept()
        else:
            super().keyPressEvent(e)


class ConsoleTextEdit(QTextEdit):

    """Custom QTextEdit for console output."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAcceptRichText(False)
        self.setReadOnly(True)
        self.setFocusPolicy(Qt.FocusPolicy.ClickFocus)

    def __repr__(self):
        return utils.get_repr(self)

    def append_text(self, text):
        """Append new text and scroll output to bottom.

        We can't use Qt's way to append stuff because that inserts weird
        newlines.
        """
        self.moveCursor(QTextCursor.MoveOperation.End)
        self.insertPlainText(text)
        scrollbar = self.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())


class ConsoleWidget(QWidget):

    """A widget with an interactive Python console.

    Attributes:
        _lineedit: The line edit in the console.
        _output: The output widget in the console.
        _vbox: The layout which contains everything.
        _more: A flag which is set when more input is expected.
        _buffer: The buffer for multi-line commands.
        _interpreter: The InteractiveInterpreter to execute code with.
    """

    STYLESHEET = """
        ConsoleWidget > ConsoleTextEdit, ConsoleWidget > ConsoleLineEdit {
            font: {{ conf.fonts.debug_console }};
        }
    """

    def __init__(self, parent=None):
        super().__init__(parent)
        if not hasattr(sys, 'ps1'):
            sys.ps1 = '>>> '
        if not hasattr(sys, 'ps2'):
            sys.ps2 = '... '
        namespace = {
            '__name__': '__console__',
            '__doc__': None,
            'q_app': QApplication.instance(),
            # We use parent as self here because the user "feels" the whole
            # console, not just the line edit.
            'self': parent,
            'objreg': objreg,
        }
        self._more = False
        self._buffer: MutableSequence[str] = []
        self._lineedit = ConsoleLineEdit(namespace, self)
        self._lineedit.execute.connect(self.push)
        self._output = ConsoleTextEdit()
        self.write(self._curprompt())
        self._vbox = QVBoxLayout()
        self._vbox.setSpacing(0)
        self._vbox.addWidget(self._output)
        self._vbox.addWidget(self._lineedit)
        stylesheet.set_register(self)
        self.setLayout(self._vbox)
        self._lineedit.setFocus()
        self._interpreter = code.InteractiveInterpreter(namespace)

    def __repr__(self):
        return utils.get_repr(self, visible=self.isVisible())

    def write(self, line):
        """Write a line of text (without added newline) to the output."""
        self._output.append_text(line)

    @pyqtSlot(str)
    def push(self, line):
        """Push a line to the interpreter."""
        self._buffer.append(line)
        source = '\n'.join(self._buffer)
        self.write(line + '\n')
        # We do two special things with the context managers here:
        #   - We replace stdout/stderr to capture output. Even if we could
        #     override InteractiveInterpreter's write method, most things are
        #     printed elsewhere (e.g. by exec). Other Python GUI shells do the
        #     same.
        #   - We disable our exception hook, so exceptions from the console get
        #     printed and don't open a crashdialog.
        with utils.fake_io(self.write), utils.disabled_excepthook():
            self._more = self._interpreter.runsource(source, '<console>')
        self.write(self._curprompt())
        if not self._more:
            self._buffer = []

    def _curprompt(self):
        """Get the prompt which is visible currently."""
        return sys.ps2 if self._more else sys.ps1


def init():
    """Initialize a global console."""
    global console_widget
    console_widget = ConsoleWidget()