qutebrowser/qutebrowser/widgets/console.py

188 lines
6.3 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:
# Copyright 2014 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 <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
2014-08-14 13:28:48 +02:00
from PyQt5.QtWidgets import QTextEdit, QWidget, QVBoxLayout, QApplication
2014-08-26 19:10:14 +02:00
from qutebrowser.config import config
from qutebrowser.models import cmdhistory
2014-08-26 20:20:17 +02:00
from qutebrowser.utils import utils
2014-08-26 19:10:14 +02:00
from qutebrowser.widgets import misc
2014-08-07 14:43:45 +02:00
2014-08-26 19:10:14 +02:00
class ConsoleLineEdit(misc.CommandLineEdit):
2014-08-07 14:43:45 +02:00
"""A QLineEdit which executes entered code and provides a history."""
write = pyqtSignal(str)
2014-08-13 09:07:18 +02:00
def __init__(self, parent):
2014-08-13 06:54:08 +02:00
if not hasattr(sys, 'ps1'):
sys.ps1 = '>>> '
if not hasattr(sys, 'ps2'):
sys.ps2 = '... '
super().__init__(parent)
self.set_prompt(sys.ps1)
2014-08-13 06:56:46 +02:00
self.setFont(config.get('fonts', 'debug-console'))
2014-08-07 14:43:45 +02:00
self._more = False
self._buffer = []
2014-08-13 07:14:21 +02:00
interpreter_locals = {
'__name__': '__console__',
'__doc__': None,
'qApp': QApplication.instance(),
2014-08-13 09:07:18 +02:00
# We use parent as self here because the user "feels" the whole
# console, not just the line edit.
'self': parent,
2014-08-13 07:14:21 +02:00
}
2014-08-26 19:10:14 +02:00
self._interpreter = code.InteractiveInterpreter(interpreter_locals)
self.history = cmdhistory.History()
2014-08-07 14:43:45 +02:00
self.returnPressed.connect(self.execute)
2014-08-13 06:54:08 +02:00
self.setText('')
def _curprompt(self):
2014-08-14 13:28:48 +02:00
"""Get the prompt which is visible currently."""
2014-08-13 06:54:08 +02:00
return sys.ps2 if self._more else sys.ps1
2014-08-07 14:43:45 +02:00
@pyqtSlot(str)
def execute(self):
"""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)
self.push(text)
self.setText('')
2014-08-07 14:43:45 +02:00
def push(self, line):
"""Push a line to the interpreter."""
self._buffer.append(line)
source = '\n'.join(self._buffer)
self.write.emit(self._curprompt() + line)
# We do two special things with the contextmanagers 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 ooen a crashdialog.
2014-08-26 19:10:14 +02:00
with utils.fake_io(self.write.emit), utils.disabled_excepthook():
self._more = self._interpreter.runsource(source, '<console>')
self.set_prompt(self._curprompt())
2014-08-07 14:43:45 +02:00
if not self._more:
self._buffer = []
def history_prev(self):
"""Go back in the history."""
try:
if not self.history.is_browsing():
2014-08-07 14:43:45 +02:00
item = self.history.start(self.text().strip())
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)
2014-08-13 06:54:08 +02:00
def setText(self, text):
"""Override setText to always prepend the prompt."""
super().setText(self._curprompt() + text)
2014-08-13 06:54:08 +02:00
def text(self):
"""Override text to strip the prompt."""
text = super().text()
return text[len(self._curprompt()):]
2014-08-13 06:54:08 +02:00
2014-08-07 14:43:45 +02:00
def keyPressEvent(self, e):
"""Override keyPressEvent to handle up/down keypresses."""
if e.key() == Qt.Key_Up:
self.history_prev()
e.accept()
elif e.key() == Qt.Key_Down:
self.history_next()
e.accept()
else:
super().keyPressEvent(e)
2014-08-13 06:56:46 +02:00
def on_config_changed(self, section, option):
"""Update font when config changed."""
if section == 'fonts' and option == 'debug-console':
self.setFont(config.get('fonts', 'debug-console'))
class ConsoleTextEdit(QTextEdit):
2014-08-14 13:28:48 +02:00
"""Custom QTextEdit for console input."""
2014-08-13 06:56:46 +02:00
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptRichText(False)
self.setReadOnly(True)
self.setFont(config.get('fonts', 'debug-console'))
self.setFocusPolicy(Qt.NoFocus)
2014-08-13 06:56:46 +02:00
2014-09-23 23:31:17 +02:00
def __repr__(self):
return '<{}>'.format(self.__class__.__name__)
2014-08-13 06:56:46 +02:00
def on_config_changed(self, section, option):
"""Update font when config changed."""
if section == 'fonts' and option == 'debug-console':
self.setFont(config.get('fonts', 'debug-console'))
2014-08-07 14:43:45 +02:00
class ConsoleWidget(QWidget):
"""A widget with an interactive Python console."""
def __init__(self, parent=None):
super().__init__(parent)
2014-08-13 09:07:18 +02:00
self.lineedit = ConsoleLineEdit(self)
2014-08-13 06:56:46 +02:00
self.output = ConsoleTextEdit()
2014-08-07 14:43:45 +02:00
self.lineedit.write.connect(self.output.append)
self.vbox = QVBoxLayout()
self.vbox.setSpacing(0)
self.vbox.addWidget(self.output)
self.vbox.addWidget(self.lineedit)
self.setLayout(self.vbox)
2014-08-13 05:15:58 +02:00
self.lineedit.setFocus()
2014-08-13 06:56:46 +02:00
2014-09-23 23:31:17 +02:00
def __repr__(self):
return '<{}, visible={}>'.format(
self.__class__.__name__, self.isVisible())
2014-08-13 06:56:46 +02:00
@pyqtSlot(str, str)
def on_config_changed(self, section, option):
"""Update font when config changed."""
self.lineedit.on_config_changed(section, option)
self.output.on_config_changed(section, option)