qutebrowser/qutebrowser/misc/consolewidget.py

214 lines
7.0 KiB
Python
Raw Normal View History

2014-08-07 14:43:45 +02:00
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
2016-01-04 07:12:39 +01:00
# Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
2014-08-07 14:43:45 +02:00
#
# 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 <http://www.gnu.org/licenses/>.
"""Debugging console."""
2014-08-13 06:54:08 +02:00
import sys
2014-08-26 19:10:14 +02:00
import code
2014-08-07 14:43:45 +02:00
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt
from PyQt5.QtWidgets import QTextEdit, QWidget, QVBoxLayout, QApplication
from PyQt5.QtGui import QTextCursor
2014-08-26 19:10:14 +02:00
from qutebrowser.config import config
from qutebrowser.misc import cmdhistory, miscwidgets
from qutebrowser.utils import utils, objreg
2014-08-07 14:43:45 +02:00
class ConsoleLineEdit(miscwidgets.CommandLineEdit):
2014-08-07 14:43:45 +02:00
2014-09-24 22:22:02 +02:00
"""A QLineEdit which executes entered code and provides a history.
Attributes:
_history: The command history of executed commands.
2014-10-10 07:34:34 +02:00
Signals:
execute: Emitted when a commandline should be executed.
2014-09-24 22:22:02 +02:00
"""
2014-08-07 14:43:45 +02:00
2014-10-10 07:34:34 +02:00
execute = pyqtSignal(str)
2014-08-07 14:43:45 +02:00
def __init__(self, _namespace, parent):
2014-10-10 07:34:34 +02:00
"""Constructor.
Args:
_namespace: The local namespace of the interpreter.
2014-10-10 07:34:34 +02:00
"""
super().__init__(parent)
self.update_font()
objreg.get('config').changed.connect(self.update_font)
self._history = cmdhistory.History(parent=self)
2014-10-10 07:34:34 +02:00
self.returnPressed.connect(self.on_return_pressed)
2014-08-07 14:43:45 +02:00
@pyqtSlot(str)
2014-10-10 07:34:34 +02:00
def on_return_pressed(self):
2014-08-07 14:43:45 +02:00
"""Execute the line of code which was entered."""
self._history.stop()
2014-08-07 14:43:45 +02:00
text = self.text()
2014-08-13 09:08:31 +02:00
if text:
self._history.append(text)
2014-10-10 07:34:34 +02:00
self.execute.emit(text)
self.setText('')
2014-08-07 14:43:45 +02:00
def history_prev(self):
"""Go back in the history."""
try:
if not self._history.is_browsing():
item = self._history.start(self.text().strip())
2014-08-07 14:43:45 +02:00
else:
item = self._history.previtem()
2014-08-26 19:10:14 +02:00
except (cmdhistory.HistoryEmptyError,
cmdhistory.HistoryEndReachedError):
2014-08-07 14:43:45 +02:00
return
self.setText(item)
def history_next(self):
"""Go forward in the history."""
if not self._history.is_browsing():
2014-08-07 14:43:45 +02:00
return
try:
item = self._history.nextitem()
2014-08-26 19:10:14 +02:00
except cmdhistory.HistoryEndReachedError:
2014-08-07 14:43:45 +02:00
return
self.setText(item)
def keyPressEvent(self, e):
"""Override keyPressEvent to handle special keypresses."""
2014-08-07 14:43:45 +02:00
if e.key() == Qt.Key_Up:
self.history_prev()
e.accept()
elif e.key() == Qt.Key_Down:
self.history_next()
e.accept()
elif e.modifiers() & Qt.ControlModifier and e.key() == Qt.Key_C:
self.setText('')
e.accept()
2014-08-07 14:43:45 +02:00
else:
super().keyPressEvent(e)
@config.change_filter('fonts', 'debug-console')
def update_font(self):
"""Set the correct font."""
self.setFont(config.get('fonts', 'debug-console'))
2014-08-13 06:56:46 +02:00
class ConsoleTextEdit(QTextEdit):
"""Custom QTextEdit for console output."""
2014-08-14 13:28:48 +02:00
2014-08-13 06:56:46 +02:00
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptRichText(False)
self.setReadOnly(True)
objreg.get('config').changed.connect(self.update_font)
self.update_font()
self.setFocusPolicy(Qt.ClickFocus)
2014-08-13 06:56:46 +02:00
2014-09-23 23:31:17 +02:00
def __repr__(self):
2014-09-26 15:48:24 +02:00
return utils.get_repr(self)
2014-09-23 23:31:17 +02:00
@config.change_filter('fonts', 'debug-console')
def update_font(self):
2014-08-13 06:56:46 +02:00
"""Update font when config changed."""
self.setFont(config.get('fonts', 'debug-console'))
2014-08-13 06:56:46 +02:00
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.End)
self.insertPlainText(text)
scrollbar = self.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
2014-08-07 14:43:45 +02:00
class ConsoleWidget(QWidget):
2014-09-24 22:22:02 +02:00
"""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.
2014-10-10 07:34:34 +02:00
_more: A flag which is set when more input is expected.
2015-03-31 20:49:29 +02:00
_buffer: The buffer for multi-line commands.
2014-10-10 07:34:34 +02:00
_interpreter: The InteractiveInterpreter to execute code with.
2014-09-24 22:22:02 +02:00
"""
2014-08-07 14:43:45 +02:00
def __init__(self, parent=None):
super().__init__(parent)
2014-10-10 07:34:34 +02:00
if not hasattr(sys, 'ps1'):
sys.ps1 = '>>> '
if not hasattr(sys, 'ps2'):
sys.ps2 = '... '
namespace = {
'__name__': '__console__',
'__doc__': None,
'qApp': QApplication.instance(),
# We use parent as self here because the user "feels" the whole
# console, not just the line edit.
'self': parent,
'objreg': objreg,
2014-10-10 07:34:34 +02:00
}
self._more = False
self._buffer = []
self._lineedit = ConsoleLineEdit(namespace, self)
self._lineedit.execute.connect(self.push)
self._output = ConsoleTextEdit()
2014-10-10 07:34:34 +02:00
self.write(self._curprompt())
self._vbox = QVBoxLayout()
self._vbox.setSpacing(0)
self._vbox.addWidget(self._output)
self._vbox.addWidget(self._lineedit)
self.setLayout(self._vbox)
self._lineedit.setFocus()
2014-10-10 07:34:34 +02:00
self._interpreter = code.InteractiveInterpreter(namespace)
2014-09-23 23:31:17 +02:00
def __repr__(self):
2014-09-26 15:48:24 +02:00
return utils.get_repr(self, visible=self.isVisible())
2014-10-10 07:34:34 +02:00
def write(self, line):
2014-10-10 07:50:50 +02:00
"""Write a line of text (without added newline) to the output."""
2014-10-10 07:34:34 +02:00
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')
2015-03-31 20:49:29 +02:00
# We do two special things with the context managers here:
2014-10-10 07:34:34 +02:00
# - 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
2015-03-31 20:49:29 +02:00
# printed and don't open a crashdialog.
2014-10-10 07:34:34 +02:00
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