console_widget.py
1047 lines
| 38.8 KiB
| text/x-python
|
PythonLexer
epatters
|
r2602 | # Standard library imports | ||
epatters
|
r2665 | import sys | ||
epatters
|
r2602 | |||
# System library imports | ||||
from PyQt4 import QtCore, QtGui | ||||
# Local imports | ||||
epatters
|
r2716 | from ansi_code_processor import QtAnsiCodeProcessor | ||
epatters
|
r2602 | from completion_widget import CompletionWidget | ||
epatters
|
r2736 | class ConsoleWidget(QtGui.QWidget): | ||
epatters
|
r2602 | """ Base class for console-type widgets. This class is mainly concerned with | ||
dealing with the prompt, keeping the cursor inside the editing line, and | ||||
handling ANSI escape sequences. | ||||
""" | ||||
epatters
|
r2668 | # Whether to process ANSI escape codes. | ||
ansi_codes = True | ||||
# The maximum number of lines of text before truncation. | ||||
buffer_size = 500 | ||||
# Whether to use a CompletionWidget or plain text output for tab completion. | ||||
gui_completion = True | ||||
# Whether to override ShortcutEvents for the keybindings defined by this | ||||
# widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take | ||||
# priority (when it has focus) over, e.g., window-level menu shortcuts. | ||||
override_shortcuts = False | ||||
epatters
|
r2736 | # Signals that indicate ConsoleWidget state. | ||
copy_available = QtCore.pyqtSignal(bool) | ||||
redo_available = QtCore.pyqtSignal(bool) | ||||
undo_available = QtCore.pyqtSignal(bool) | ||||
epatters
|
r2668 | # Protected class variables. | ||
epatters
|
r2602 | _ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left, | ||
QtCore.Qt.Key_F : QtCore.Qt.Key_Right, | ||||
QtCore.Qt.Key_A : QtCore.Qt.Key_Home, | ||||
QtCore.Qt.Key_E : QtCore.Qt.Key_End, | ||||
QtCore.Qt.Key_P : QtCore.Qt.Key_Up, | ||||
QtCore.Qt.Key_N : QtCore.Qt.Key_Down, | ||||
QtCore.Qt.Key_D : QtCore.Qt.Key_Delete, } | ||||
epatters
|
r2687 | _shortcuts = set(_ctrl_down_remap.keys() + | ||
[ QtCore.Qt.Key_C, QtCore.Qt.Key_V ]) | ||||
epatters
|
r2602 | |||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2669 | # 'QObject' interface | ||
epatters
|
r2602 | #--------------------------------------------------------------------------- | ||
epatters
|
r2736 | def __init__(self, kind='plain', parent=None): | ||
""" Create a ConsoleWidget. | ||||
Parameters | ||||
---------- | ||||
kind : str, optional [default 'plain'] | ||||
The type of text widget to use. Valid values are 'plain', which | ||||
specifies a QPlainTextEdit, and 'rich', which specifies an | ||||
QTextEdit. | ||||
parent : QWidget, optional [default None] | ||||
The parent for this widget. | ||||
""" | ||||
super(ConsoleWidget, self).__init__(parent) | ||||
# Create the underlying text widget. | ||||
self._control = self._create_control(kind) | ||||
epatters
|
r2602 | |||
epatters
|
r2715 | # Initialize protected variables. Some variables contain useful state | ||
# information for subclasses; they should be considered read-only. | ||||
epatters
|
r2602 | self._ansi_processor = QtAnsiCodeProcessor() | ||
epatters
|
r2736 | self._completion_widget = CompletionWidget(self._control) | ||
epatters
|
r2643 | self._continuation_prompt = '> ' | ||
epatters
|
r2715 | self._continuation_prompt_html = None | ||
epatters
|
r2602 | self._executing = False | ||
self._prompt = '' | ||||
epatters
|
r2715 | self._prompt_html = None | ||
epatters
|
r2602 | self._prompt_pos = 0 | ||
self._reading = False | ||||
epatters
|
r2706 | self._reading_callback = None | ||
epatters
|
r2723 | self._tab_width = 8 | ||
epatters
|
r2602 | |||
epatters
|
r2736 | # Set a monospaced font. | ||
self.reset_font() | ||||
epatters
|
r2602 | |||
epatters
|
r2736 | def eventFilter(self, obj, event): | ||
""" Reimplemented to ensure a console-like behavior in the underlying | ||||
text widget. | ||||
""" | ||||
if obj == self._control: | ||||
etype = event.type() | ||||
# Disable moving text by drag and drop. | ||||
epatters
|
r2737 | if etype == QtCore.QEvent.DragMove: | ||
epatters
|
r2736 | return True | ||
elif etype == QtCore.QEvent.KeyPress: | ||||
return self._event_filter_keypress(event) | ||||
# On Mac OS, it is always unnecessary to override shortcuts, hence | ||||
# the check below. Users should just use the Control key instead of | ||||
# the Command key. | ||||
elif etype == QtCore.QEvent.ShortcutOverride: | ||||
if sys.platform != 'darwin' and \ | ||||
self._control_key_down(event.modifiers()) and \ | ||||
event.key() in self._shortcuts: | ||||
event.accept() | ||||
return False | ||||
return super(ConsoleWidget, self).eventFilter(obj, event) | ||||
epatters
|
r2668 | |||
epatters
|
r2669 | #--------------------------------------------------------------------------- | ||
epatters
|
r2736 | # 'ConsoleWidget' public interface | ||
epatters
|
r2669 | #--------------------------------------------------------------------------- | ||
epatters
|
r2643 | def clear(self, keep_input=False): | ||
epatters
|
r2736 | """ Clear the console, then write a new prompt. If 'keep_input' is set, | ||
epatters
|
r2715 | restores the old input buffer when the new prompt is written. | ||
epatters
|
r2643 | """ | ||
epatters
|
r2736 | self._control.clear() | ||
epatters
|
r2715 | if keep_input: | ||
epatters
|
r2643 | input_buffer = self.input_buffer | ||
self._show_prompt() | ||||
epatters
|
r2715 | if keep_input: | ||
self.input_buffer = input_buffer | ||||
epatters
|
r2643 | |||
epatters
|
r2736 | def copy(self): | ||
""" Copy the current selected text to the clipboard. | ||||
epatters
|
r2602 | """ | ||
epatters
|
r2736 | self._control.copy() | ||
epatters
|
r2602 | |||
epatters
|
r2688 | def execute(self, source=None, hidden=False, interactive=False): | ||
""" Executes source or the input buffer, possibly prompting for more | ||||
input. | ||||
Parameters: | ||||
----------- | ||||
source : str, optional | ||||
The source to execute. If not specified, the input buffer will be | ||||
used. If specified and 'hidden' is False, the input buffer will be | ||||
replaced with the source before execution. | ||||
hidden : bool, optional (default False) | ||||
If set, no output will be shown and the prompt will not be modified. | ||||
In other words, it will be completely invisible to the user that | ||||
an execution has occurred. | ||||
interactive : bool, optional (default False) | ||||
Whether the console is to treat the source as having been manually | ||||
entered by the user. The effect of this parameter depends on the | ||||
subclass implementation. | ||||
epatters
|
r2689 | Raises: | ||
------- | ||||
RuntimeError | ||||
If incomplete input is given and 'hidden' is True. In this case, | ||||
it not possible to prompt for more input. | ||||
epatters
|
r2688 | Returns: | ||
-------- | ||||
A boolean indicating whether the source was executed. | ||||
""" | ||||
if not hidden: | ||||
if source is not None: | ||||
self.input_buffer = source | ||||
epatters
|
r2736 | self._append_plain_text('\n') | ||
epatters
|
r2688 | self._executing_input_buffer = self.input_buffer | ||
self._executing = True | ||||
self._prompt_finished() | ||||
real_source = self.input_buffer if source is None else source | ||||
complete = self._is_complete(real_source, interactive) | ||||
if complete: | ||||
if not hidden: | ||||
# The maximum block count is only in effect during execution. | ||||
# This ensures that _prompt_pos does not become invalid due to | ||||
# text truncation. | ||||
epatters
|
r2736 | self._control.document().setMaximumBlockCount(self.buffer_size) | ||
epatters
|
r2688 | self._execute(real_source, hidden) | ||
elif hidden: | ||||
raise RuntimeError('Incomplete noninteractive input: "%s"' % source) | ||||
else: | ||||
self._show_continuation_prompt() | ||||
return complete | ||||
epatters
|
r2602 | |||
def _get_input_buffer(self): | ||||
epatters
|
r2665 | """ The text that the user has entered entered at the current prompt. | ||
""" | ||||
# If we're executing, the input buffer may not even exist anymore due to | ||||
epatters
|
r2615 | # the limit imposed by 'buffer_size'. Therefore, we store it. | ||
if self._executing: | ||||
return self._executing_input_buffer | ||||
epatters
|
r2602 | cursor = self._get_end_cursor() | ||
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) | ||||
input_buffer = str(cursor.selection().toPlainText()) | ||||
epatters
|
r2665 | # Strip out continuation prompts. | ||
epatters
|
r2643 | return input_buffer.replace('\n' + self._continuation_prompt, '\n') | ||
epatters
|
r2602 | |||
def _set_input_buffer(self, string): | ||||
epatters
|
r2665 | """ Replaces the text in the input buffer with 'string'. | ||
""" | ||||
epatters
|
r2717 | # Remove old text. | ||
epatters
|
r2602 | cursor = self._get_end_cursor() | ||
cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) | ||||
epatters
|
r2717 | cursor.removeSelectedText() | ||
# Insert new text with continuation prompts. | ||||
lines = string.splitlines(True) | ||||
if lines: | ||||
epatters
|
r2736 | self._append_plain_text(lines[0]) | ||
epatters
|
r2717 | for i in xrange(1, len(lines)): | ||
if self._continuation_prompt_html is None: | ||||
epatters
|
r2736 | self._append_plain_text(self._continuation_prompt) | ||
epatters
|
r2717 | else: | ||
epatters
|
r2736 | self._append_html(self._continuation_prompt_html) | ||
self._append_plain_text(lines[i]) | ||||
self._control.moveCursor(QtGui.QTextCursor.End) | ||||
epatters
|
r2602 | |||
input_buffer = property(_get_input_buffer, _set_input_buffer) | ||||
def _get_input_buffer_cursor_line(self): | ||||
epatters
|
r2665 | """ The text in the line of the input buffer in which the user's cursor | ||
rests. Returns a string if there is such a line; otherwise, None. | ||||
""" | ||||
epatters
|
r2615 | if self._executing: | ||
return None | ||||
epatters
|
r2736 | cursor = self._control.textCursor() | ||
epatters
|
r2602 | if cursor.position() >= self._prompt_pos: | ||
epatters
|
r2715 | text = self._get_block_plain_text(cursor.block()) | ||
epatters
|
r2602 | if cursor.blockNumber() == self._get_prompt_cursor().blockNumber(): | ||
return text[len(self._prompt):] | ||||
else: | ||||
epatters
|
r2643 | return text[len(self._continuation_prompt):] | ||
epatters
|
r2602 | else: | ||
return None | ||||
input_buffer_cursor_line = property(_get_input_buffer_cursor_line) | ||||
epatters
|
r2665 | def _get_font(self): | ||
""" The base font being used by the ConsoleWidget. | ||||
""" | ||||
epatters
|
r2736 | return self._control.document().defaultFont() | ||
epatters
|
r2665 | |||
def _set_font(self, font): | ||||
""" Sets the base font for the ConsoleWidget to the specified QFont. | ||||
""" | ||||
epatters
|
r2716 | font_metrics = QtGui.QFontMetrics(font) | ||
epatters
|
r2736 | self._control.setTabStopWidth(self.tab_width * font_metrics.width(' ')) | ||
epatters
|
r2716 | |||
epatters
|
r2665 | self._completion_widget.setFont(font) | ||
epatters
|
r2736 | self._control.document().setDefaultFont(font) | ||
epatters
|
r2665 | |||
font = property(_get_font, _set_font) | ||||
epatters
|
r2736 | def paste(self): | ||
""" Paste the contents of the clipboard into the input region. | ||||
""" | ||||
self._keep_cursor_in_buffer() | ||||
self._control.paste() | ||||
def print_(self, printer): | ||||
""" Print the contents of the ConsoleWidget to the specified QPrinter. | ||||
""" | ||||
self._control.print_(printer) | ||||
def redo(self): | ||||
""" Redo the last operation. If there is no operation to redo, nothing | ||||
happens. | ||||
""" | ||||
self._control.redo() | ||||
epatters
|
r2665 | def reset_font(self): | ||
""" Sets the font to the default fixed-width font for this platform. | ||||
""" | ||||
if sys.platform == 'win32': | ||||
name = 'Courier' | ||||
elif sys.platform == 'darwin': | ||||
name = 'Monaco' | ||||
else: | ||||
name = 'Monospace' | ||||
font = QtGui.QFont(name, QtGui.qApp.font().pointSize()) | ||||
font.setStyleHint(QtGui.QFont.TypeWriter) | ||||
self._set_font(font) | ||||
epatters
|
r2723 | |||
epatters
|
r2736 | def select_all(self): | ||
""" Selects all the text in the buffer. | ||||
""" | ||||
self._control.selectAll() | ||||
epatters
|
r2723 | def _get_tab_width(self): | ||
""" The width (in terms of space characters) for tab characters. | ||||
""" | ||||
return self._tab_width | ||||
def _set_tab_width(self, tab_width): | ||||
""" Sets the width (in terms of space characters) for tab characters. | ||||
""" | ||||
font_metrics = QtGui.QFontMetrics(self.font) | ||||
epatters
|
r2736 | self._control.setTabStopWidth(tab_width * font_metrics.width(' ')) | ||
epatters
|
r2723 | |||
self._tab_width = tab_width | ||||
tab_width = property(_get_tab_width, _set_tab_width) | ||||
epatters
|
r2736 | |||
def undo(self): | ||||
""" Undo the last operation. If there is no operation to undo, nothing | ||||
happens. | ||||
""" | ||||
self._control.undo() | ||||
epatters
|
r2602 | #--------------------------------------------------------------------------- | ||
# 'ConsoleWidget' abstract interface | ||||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2688 | def _is_complete(self, source, interactive): | ||
""" Returns whether 'source' can be executed. When triggered by an | ||||
Enter/Return key press, 'interactive' is True; otherwise, it is | ||||
False. | ||||
""" | ||||
raise NotImplementedError | ||||
def _execute(self, source, hidden): | ||||
""" Execute 'source'. If 'hidden', do not show any output. | ||||
epatters
|
r2602 | """ | ||
raise NotImplementedError | ||||
def _prompt_started_hook(self): | ||||
""" Called immediately after a new prompt is displayed. | ||||
""" | ||||
pass | ||||
def _prompt_finished_hook(self): | ||||
""" Called immediately after a prompt is finished, i.e. when some input | ||||
will be processed and a new prompt displayed. | ||||
""" | ||||
pass | ||||
def _up_pressed(self): | ||||
""" Called when the up key is pressed. Returns whether to continue | ||||
processing the event. | ||||
""" | ||||
return True | ||||
def _down_pressed(self): | ||||
""" Called when the down key is pressed. Returns whether to continue | ||||
processing the event. | ||||
""" | ||||
return True | ||||
def _tab_pressed(self): | ||||
""" Called when the tab key is pressed. Returns whether to continue | ||||
processing the event. | ||||
""" | ||||
return False | ||||
#-------------------------------------------------------------------------- | ||||
# 'ConsoleWidget' protected interface | ||||
#-------------------------------------------------------------------------- | ||||
epatters
|
r2736 | def _append_html(self, html): | ||
""" Appends html at the end of the console buffer. | ||||
""" | ||||
cursor = self._get_end_cursor() | ||||
self._insert_html(cursor, html) | ||||
epatters
|
r2715 | def _append_html_fetching_plain_text(self, html): | ||
""" Appends 'html', then returns the plain text version of it. | ||||
""" | ||||
anchor = self._get_end_cursor().position() | ||||
epatters
|
r2736 | self._append_html(html) | ||
epatters
|
r2715 | cursor = self._get_end_cursor() | ||
cursor.setPosition(anchor, QtGui.QTextCursor.KeepAnchor) | ||||
return str(cursor.selection().toPlainText()) | ||||
epatters
|
r2736 | def _append_plain_text(self, text): | ||
""" Appends plain text at the end of the console buffer, processing | ||||
ANSI codes if enabled. | ||||
""" | ||||
cursor = self._get_end_cursor() | ||||
if self.ansi_codes: | ||||
for substring in self._ansi_processor.split_string(text): | ||||
format = self._ansi_processor.get_format() | ||||
cursor.insertText(substring, format) | ||||
else: | ||||
cursor.insertText(text) | ||||
epatters
|
r2715 | def _append_plain_text_keeping_prompt(self, text): | ||
""" Writes 'text' after the current prompt, then restores the old prompt | ||||
with its old input buffer. | ||||
""" | ||||
input_buffer = self.input_buffer | ||||
epatters
|
r2736 | self._append_plain_text('\n') | ||
epatters
|
r2715 | self._prompt_finished() | ||
epatters
|
r2736 | self._append_plain_text(text) | ||
epatters
|
r2715 | self._show_prompt() | ||
self.input_buffer = input_buffer | ||||
epatters
|
r2736 | def _complete_with_items(self, cursor, items): | ||
""" Performs completion with 'items' at the specified cursor location. | ||||
""" | ||||
if len(items) == 1: | ||||
cursor.setPosition(self._control.textCursor().position(), | ||||
QtGui.QTextCursor.KeepAnchor) | ||||
cursor.insertText(items[0]) | ||||
elif len(items) > 1: | ||||
if self.gui_completion: | ||||
self._completion_widget.show_items(cursor, items) | ||||
else: | ||||
text = self._format_as_columns(items) | ||||
self._append_plain_text_keeping_prompt(text) | ||||
def _control_key_down(self, modifiers): | ||||
epatters
|
r2671 | """ Given a KeyboardModifiers flags object, return whether the Control | ||
key is down (on Mac OS, treat the Command key as a synonym for | ||||
Control). | ||||
""" | ||||
down = bool(modifiers & QtCore.Qt.ControlModifier) | ||||
# Note: on Mac OS, ControlModifier corresponds to the Command key while | ||||
# MetaModifier corresponds to the Control key. | ||||
if sys.platform == 'darwin': | ||||
down = down ^ bool(modifiers & QtCore.Qt.MetaModifier) | ||||
return down | ||||
epatters
|
r2736 | |||
def _create_control(self, kind): | ||||
""" Creates and sets the underlying text widget. | ||||
""" | ||||
layout = QtGui.QVBoxLayout(self) | ||||
layout.setMargin(0) | ||||
if kind == 'plain': | ||||
control = QtGui.QPlainTextEdit() | ||||
elif kind == 'rich': | ||||
control = QtGui.QTextEdit() | ||||
else: | ||||
raise ValueError("Kind %s unknown." % repr(kind)) | ||||
layout.addWidget(control) | ||||
control.installEventFilter(self) | ||||
epatters
|
r2737 | control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) | ||
control.customContextMenuRequested.connect(self._show_context_menu) | ||||
epatters
|
r2736 | control.copyAvailable.connect(self.copy_available) | ||
control.redoAvailable.connect(self.redo_available) | ||||
control.undoAvailable.connect(self.undo_available) | ||||
return control | ||||
def _event_filter_keypress(self, event): | ||||
""" Filter key events for the underlying text widget to create a | ||||
console-like interface. | ||||
""" | ||||
epatters
|
r2737 | key = event.key() | ||
ctrl_down = self._control_key_down(event.modifiers()) | ||||
# If the key is remapped, return immediately. | ||||
if ctrl_down and key in self._ctrl_down_remap: | ||||
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, | ||||
self._ctrl_down_remap[key], | ||||
QtCore.Qt.NoModifier) | ||||
QtGui.qApp.sendEvent(self._control, new_event) | ||||
return True | ||||
# If the completion widget accepts the key press, return immediately. | ||||
if self._completion_widget.isVisible(): | ||||
self._completion_widget.keyPressEvent(event) | ||||
if event.isAccepted(): | ||||
return True | ||||
# Otherwise, proceed normally and do not return early. | ||||
epatters
|
r2736 | intercepted = False | ||
cursor = self._control.textCursor() | ||||
position = cursor.position() | ||||
alt_down = event.modifiers() & QtCore.Qt.AltModifier | ||||
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier | ||||
if event.matches(QtGui.QKeySequence.Paste): | ||||
epatters
|
r2737 | # Call our paste instead of the underlying text widget's. | ||
epatters
|
r2736 | self.paste() | ||
intercepted = True | ||||
elif ctrl_down: | ||||
epatters
|
r2737 | if key == QtCore.Qt.Key_K: | ||
epatters
|
r2736 | if self._in_buffer(position): | ||
cursor.movePosition(QtGui.QTextCursor.EndOfLine, | ||||
QtGui.QTextCursor.KeepAnchor) | ||||
cursor.removeSelectedText() | ||||
intercepted = True | ||||
elif key == QtCore.Qt.Key_X: | ||||
intercepted = True | ||||
elif key == QtCore.Qt.Key_Y: | ||||
self.paste() | ||||
intercepted = True | ||||
elif alt_down: | ||||
if key == QtCore.Qt.Key_B: | ||||
self._set_cursor(self._get_word_start_cursor(position)) | ||||
intercepted = True | ||||
elif key == QtCore.Qt.Key_F: | ||||
self._set_cursor(self._get_word_end_cursor(position)) | ||||
intercepted = True | ||||
elif key == QtCore.Qt.Key_Backspace: | ||||
cursor = self._get_word_start_cursor(position) | ||||
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor) | ||||
cursor.removeSelectedText() | ||||
intercepted = True | ||||
elif key == QtCore.Qt.Key_D: | ||||
cursor = self._get_word_end_cursor(position) | ||||
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor) | ||||
cursor.removeSelectedText() | ||||
intercepted = True | ||||
else: | ||||
if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter): | ||||
if self._reading: | ||||
self._append_plain_text('\n') | ||||
self._reading = False | ||||
if self._reading_callback: | ||||
self._reading_callback() | ||||
elif not self._executing: | ||||
self.execute(interactive=True) | ||||
intercepted = True | ||||
elif key == QtCore.Qt.Key_Up: | ||||
if self._reading or not self._up_pressed(): | ||||
intercepted = True | ||||
else: | ||||
prompt_line = self._get_prompt_cursor().blockNumber() | ||||
intercepted = cursor.blockNumber() <= prompt_line | ||||
elif key == QtCore.Qt.Key_Down: | ||||
if self._reading or not self._down_pressed(): | ||||
intercepted = True | ||||
else: | ||||
end_line = self._get_end_cursor().blockNumber() | ||||
intercepted = cursor.blockNumber() == end_line | ||||
elif key == QtCore.Qt.Key_Tab: | ||||
if self._reading: | ||||
intercepted = False | ||||
else: | ||||
intercepted = not self._tab_pressed() | ||||
elif key == QtCore.Qt.Key_Left: | ||||
intercepted = not self._in_buffer(position - 1) | ||||
elif key == QtCore.Qt.Key_Home: | ||||
cursor.movePosition(QtGui.QTextCursor.StartOfLine) | ||||
start_line = cursor.blockNumber() | ||||
if start_line == self._get_prompt_cursor().blockNumber(): | ||||
start_pos = self._prompt_pos | ||||
else: | ||||
start_pos = cursor.position() | ||||
start_pos += len(self._continuation_prompt) | ||||
if shift_down and self._in_buffer(position): | ||||
self._set_selection(position, start_pos) | ||||
else: | ||||
self._set_position(start_pos) | ||||
intercepted = True | ||||
elif key == QtCore.Qt.Key_Backspace and not alt_down: | ||||
# Line deletion (remove continuation prompt) | ||||
len_prompt = len(self._continuation_prompt) | ||||
if not self._reading and \ | ||||
cursor.columnNumber() == len_prompt and \ | ||||
position != self._prompt_pos: | ||||
cursor.setPosition(position - len_prompt, | ||||
QtGui.QTextCursor.KeepAnchor) | ||||
cursor.removeSelectedText() | ||||
# Regular backwards deletion | ||||
else: | ||||
anchor = cursor.anchor() | ||||
if anchor == position: | ||||
intercepted = not self._in_buffer(position - 1) | ||||
else: | ||||
intercepted = not self._in_buffer(min(anchor, position)) | ||||
elif key == QtCore.Qt.Key_Delete: | ||||
anchor = cursor.anchor() | ||||
intercepted = not self._in_buffer(min(anchor, position)) | ||||
epatters
|
r2737 | # Don't move the cursor if control is down to allow copy-paste using | ||
epatters
|
r2736 | # the keyboard in any part of the buffer. | ||
if not ctrl_down: | ||||
self._keep_cursor_in_buffer() | ||||
return intercepted | ||||
epatters
|
r2715 | |||
epatters
|
r2725 | def _format_as_columns(self, items, separator=' '): | ||
epatters
|
r2723 | """ Transform a list of strings into a single string with columns. | ||
Parameters | ||||
---------- | ||||
epatters
|
r2725 | items : sequence of strings | ||
epatters
|
r2723 | The strings to process. | ||
separator : str, optional [default is two spaces] | ||||
The string that separates columns. | ||||
Returns | ||||
------- | ||||
The formatted string. | ||||
""" | ||||
epatters
|
r2724 | # Note: this code is adapted from columnize 0.3.2. | ||
# See http://code.google.com/p/pycolumnize/ | ||||
epatters
|
r2723 | font_metrics = QtGui.QFontMetrics(self.font) | ||
epatters
|
r2724 | displaywidth = max(5, (self.width() / font_metrics.width(' ')) - 1) | ||
epatters
|
r2725 | # Some degenerate cases. | ||
epatters
|
r2724 | size = len(items) | ||
if size == 0: | ||||
epatters
|
r2725 | return '\n' | ||
epatters
|
r2724 | elif size == 1: | ||
return '%s\n' % str(items[0]) | ||||
# Try every row count from 1 upwards | ||||
array_index = lambda nrows, row, col: nrows*col + row | ||||
for nrows in range(1, size): | ||||
ncols = (size + nrows - 1) // nrows | ||||
colwidths = [] | ||||
totwidth = -len(separator) | ||||
for col in range(ncols): | ||||
# Get max column width for this column | ||||
colwidth = 0 | ||||
for row in range(nrows): | ||||
i = array_index(nrows, row, col) | ||||
if i >= size: break | ||||
x = items[i] | ||||
colwidth = max(colwidth, len(x)) | ||||
colwidths.append(colwidth) | ||||
totwidth += colwidth + len(separator) | ||||
if totwidth > displaywidth: | ||||
break | ||||
if totwidth <= displaywidth: | ||||
break | ||||
# The smallest number of rows computed and the max widths for each | ||||
# column has been obtained. Now we just have to format each of the rows. | ||||
string = '' | ||||
for row in range(nrows): | ||||
texts = [] | ||||
for col in range(ncols): | ||||
i = row + nrows*col | ||||
if i >= size: | ||||
texts.append('') | ||||
else: | ||||
texts.append(items[i]) | ||||
while texts and not texts[-1]: | ||||
del texts[-1] | ||||
for col in range(len(texts)): | ||||
texts[col] = texts[col].ljust(colwidths[col]) | ||||
epatters
|
r2725 | string += '%s\n' % str(separator.join(texts)) | ||
epatters
|
r2724 | return string | ||
epatters
|
r2723 | |||
epatters
|
r2715 | def _get_block_plain_text(self, block): | ||
""" Given a QTextBlock, return its unformatted text. | ||||
""" | ||||
cursor = QtGui.QTextCursor(block) | ||||
cursor.movePosition(QtGui.QTextCursor.StartOfBlock) | ||||
cursor.movePosition(QtGui.QTextCursor.EndOfBlock, | ||||
QtGui.QTextCursor.KeepAnchor) | ||||
return str(cursor.selection().toPlainText()) | ||||
epatters
|
r2736 | |||
def _get_cursor(self): | ||||
""" Convenience method that returns a cursor for the current position. | ||||
""" | ||||
return self._control.textCursor() | ||||
epatters
|
r2602 | |||
def _get_end_cursor(self): | ||||
""" Convenience method that returns a cursor for the last character. | ||||
""" | ||||
epatters
|
r2736 | cursor = self._control.textCursor() | ||
epatters
|
r2602 | cursor.movePosition(QtGui.QTextCursor.End) | ||
return cursor | ||||
def _get_prompt_cursor(self): | ||||
""" Convenience method that returns a cursor for the prompt position. | ||||
""" | ||||
epatters
|
r2736 | cursor = self._control.textCursor() | ||
epatters
|
r2602 | cursor.setPosition(self._prompt_pos) | ||
return cursor | ||||
def _get_selection_cursor(self, start, end): | ||||
""" Convenience method that returns a cursor with text selected between | ||||
the positions 'start' and 'end'. | ||||
""" | ||||
epatters
|
r2736 | cursor = self._control.textCursor() | ||
epatters
|
r2602 | cursor.setPosition(start) | ||
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor) | ||||
return cursor | ||||
def _get_word_start_cursor(self, position): | ||||
""" Find the start of the word to the left the given position. If a | ||||
sequence of non-word characters precedes the first word, skip over | ||||
them. (This emulates the behavior of bash, emacs, etc.) | ||||
""" | ||||
epatters
|
r2736 | document = self._control.document() | ||
epatters
|
r2602 | position -= 1 | ||
while self._in_buffer(position) and \ | ||||
not document.characterAt(position).isLetterOrNumber(): | ||||
position -= 1 | ||||
while self._in_buffer(position) and \ | ||||
document.characterAt(position).isLetterOrNumber(): | ||||
position -= 1 | ||||
epatters
|
r2736 | cursor = self._control.textCursor() | ||
epatters
|
r2602 | cursor.setPosition(position + 1) | ||
return cursor | ||||
def _get_word_end_cursor(self, position): | ||||
""" Find the end of the word to the right the given position. If a | ||||
sequence of non-word characters precedes the first word, skip over | ||||
them. (This emulates the behavior of bash, emacs, etc.) | ||||
""" | ||||
epatters
|
r2736 | document = self._control.document() | ||
epatters
|
r2602 | end = self._get_end_cursor().position() | ||
while position < end and \ | ||||
not document.characterAt(position).isLetterOrNumber(): | ||||
position += 1 | ||||
while position < end and \ | ||||
document.characterAt(position).isLetterOrNumber(): | ||||
position += 1 | ||||
epatters
|
r2736 | cursor = self._control.textCursor() | ||
epatters
|
r2602 | cursor.setPosition(position) | ||
return cursor | ||||
epatters
|
r2733 | def _insert_html(self, cursor, html): | ||
""" Insert HTML using the specified cursor in such a way that future | ||||
formatting is unaffected. | ||||
""" | ||||
cursor.insertHtml(html) | ||||
# After inserting HTML, the text document "remembers" the current | ||||
# formatting, which means that subsequent calls adding plain text | ||||
# will result in similar formatting, a behavior that we do not want. To | ||||
# prevent this, we make sure that the last character has no formatting. | ||||
cursor.movePosition(QtGui.QTextCursor.Left, | ||||
QtGui.QTextCursor.KeepAnchor) | ||||
if cursor.selection().toPlainText().trimmed().isEmpty(): | ||||
# If the last character is whitespace, it doesn't matter how it's | ||||
# formatted, so just clear the formatting. | ||||
cursor.setCharFormat(QtGui.QTextCharFormat()) | ||||
else: | ||||
# Otherwise, add an unformatted space. | ||||
cursor.movePosition(QtGui.QTextCursor.Right) | ||||
cursor.insertText(' ', QtGui.QTextCharFormat()) | ||||
epatters
|
r2736 | def _in_buffer(self, position): | ||
""" Returns whether the given position is inside the editing region. | ||||
""" | ||||
return position >= self._prompt_pos | ||||
def _keep_cursor_in_buffer(self): | ||||
""" Ensures that the cursor is inside the editing region. Returns | ||||
whether the cursor was moved. | ||||
""" | ||||
cursor = self._control.textCursor() | ||||
if cursor.position() < self._prompt_pos: | ||||
cursor.movePosition(QtGui.QTextCursor.End) | ||||
self._control.setTextCursor(cursor) | ||||
return True | ||||
else: | ||||
return False | ||||
epatters
|
r2602 | def _prompt_started(self): | ||
""" Called immediately after a new prompt is displayed. | ||||
""" | ||||
epatters
|
r2688 | # Temporarily disable the maximum block count to permit undo/redo and | ||
# to ensure that the prompt position does not change due to truncation. | ||||
epatters
|
r2736 | self._control.document().setMaximumBlockCount(0) | ||
self._control.setUndoRedoEnabled(True) | ||||
epatters
|
r2615 | |||
epatters
|
r2736 | self._control.setReadOnly(False) | ||
self._control.moveCursor(QtGui.QTextCursor.End) | ||||
epatters
|
r2615 | |||
epatters
|
r2602 | self._executing = False | ||
self._prompt_started_hook() | ||||
def _prompt_finished(self): | ||||
""" Called immediately after a prompt is finished, i.e. when some input | ||||
will be processed and a new prompt displayed. | ||||
""" | ||||
epatters
|
r2736 | self._control.setUndoRedoEnabled(False) | ||
self._control.setReadOnly(True) | ||||
epatters
|
r2602 | self._prompt_finished_hook() | ||
epatters
|
r2706 | def _readline(self, prompt='', callback=None): | ||
""" Reads one line of input from the user. | ||||
Parameters | ||||
---------- | ||||
prompt : str, optional | ||||
The prompt to print before reading the line. | ||||
callback : callable, optional | ||||
A callback to execute with the read line. If not specified, input is | ||||
read *synchronously* and this method does not return until it has | ||||
been read. | ||||
Returns | ||||
------- | ||||
If a callback is specified, returns nothing. Otherwise, returns the | ||||
input string with the trailing newline stripped. | ||||
epatters
|
r2705 | """ | ||
epatters
|
r2706 | if self._reading: | ||
raise RuntimeError('Cannot read a line. Widget is already reading.') | ||||
if not callback and not self.isVisible(): | ||||
# If the user cannot see the widget, this function cannot return. | ||||
raise RuntimeError('Cannot synchronously read a line if the widget' | ||||
'is not visible!') | ||||
epatters
|
r2705 | |||
self._reading = True | ||||
epatters
|
r2708 | self._show_prompt(prompt, newline=False) | ||
epatters
|
r2706 | |||
if callback is None: | ||||
self._reading_callback = None | ||||
while self._reading: | ||||
QtCore.QCoreApplication.processEvents() | ||||
return self.input_buffer.rstrip('\n') | ||||
else: | ||||
self._reading_callback = lambda: \ | ||||
callback(self.input_buffer.rstrip('\n')) | ||||
epatters
|
r2705 | |||
epatters
|
r2715 | def _reset(self): | ||
""" Clears the console and resets internal state variables. | ||||
""" | ||||
epatters
|
r2736 | self._control.clear() | ||
epatters
|
r2715 | self._executing = self._reading = False | ||
def _set_continuation_prompt(self, prompt, html=False): | ||||
""" Sets the continuation prompt. | ||||
Parameters | ||||
---------- | ||||
prompt : str | ||||
The prompt to show when more input is needed. | ||||
html : bool, optional (default False) | ||||
If set, the prompt will be inserted as formatted HTML. Otherwise, | ||||
the prompt will be treated as plain text, though ANSI color codes | ||||
will be handled. | ||||
""" | ||||
if html: | ||||
self._continuation_prompt_html = prompt | ||||
else: | ||||
self._continuation_prompt = prompt | ||||
self._continuation_prompt_html = None | ||||
epatters
|
r2736 | |||
def _set_cursor(self, cursor): | ||||
""" Convenience method to set the current cursor. | ||||
""" | ||||
self._control.setTextCursor(cursor) | ||||
epatters
|
r2715 | |||
epatters
|
r2602 | def _set_position(self, position): | ||
""" Convenience method to set the position of the cursor. | ||||
""" | ||||
epatters
|
r2736 | cursor = self._control.textCursor() | ||
epatters
|
r2602 | cursor.setPosition(position) | ||
epatters
|
r2736 | self._control.setTextCursor(cursor) | ||
epatters
|
r2602 | |||
def _set_selection(self, start, end): | ||||
""" Convenience method to set the current selected text. | ||||
""" | ||||
epatters
|
r2736 | self._control.setTextCursor(self._get_selection_cursor(start, end)) | ||
epatters
|
r2602 | |||
epatters
|
r2737 | def _show_context_menu(self, pos): | ||
""" Shows a context menu at the given QPoint (in widget coordinates). | ||||
""" | ||||
menu = QtGui.QMenu() | ||||
copy_action = QtGui.QAction('Copy', menu) | ||||
copy_action.triggered.connect(self.copy) | ||||
copy_action.setEnabled(self._get_cursor().hasSelection()) | ||||
copy_action.setShortcut(QtGui.QKeySequence.Copy) | ||||
menu.addAction(copy_action) | ||||
paste_action = QtGui.QAction('Paste', menu) | ||||
paste_action.triggered.connect(self.paste) | ||||
paste_action.setEnabled(self._control.canPaste()) | ||||
paste_action.setShortcut(QtGui.QKeySequence.Paste) | ||||
menu.addAction(paste_action) | ||||
menu.addSeparator() | ||||
select_all_action = QtGui.QAction('Select All', menu) | ||||
select_all_action.triggered.connect(self.select_all) | ||||
menu.addAction(select_all_action) | ||||
menu.exec_(self._control.mapToGlobal(pos)) | ||||
epatters
|
r2715 | def _show_prompt(self, prompt=None, html=False, newline=True): | ||
epatters
|
r2708 | """ Writes a new prompt at the end of the buffer. | ||
Parameters | ||||
---------- | ||||
prompt : str, optional | ||||
The prompt to show. If not specified, the previous prompt is used. | ||||
epatters
|
r2715 | html : bool, optional (default False) | ||
Only relevant when a prompt is specified. If set, the prompt will | ||||
be inserted as formatted HTML. Otherwise, the prompt will be treated | ||||
as plain text, though ANSI color codes will be handled. | ||||
epatters
|
r2708 | newline : bool, optional (default True) | ||
If set, a new line will be written before showing the prompt if | ||||
there is not already a newline at the end of the buffer. | ||||
""" | ||||
epatters
|
r2715 | # Insert a preliminary newline, if necessary. | ||
epatters
|
r2708 | if newline: | ||
cursor = self._get_end_cursor() | ||||
if cursor.position() > 0: | ||||
cursor.movePosition(QtGui.QTextCursor.Left, | ||||
QtGui.QTextCursor.KeepAnchor) | ||||
if str(cursor.selection().toPlainText()) != '\n': | ||||
epatters
|
r2736 | self._append_plain_text('\n') | ||
epatters
|
r2705 | |||
epatters
|
r2715 | # Write the prompt. | ||
if prompt is None: | ||||
if self._prompt_html is None: | ||||
epatters
|
r2736 | self._append_plain_text(self._prompt) | ||
epatters
|
r2715 | else: | ||
epatters
|
r2736 | self._append_html(self._prompt_html) | ||
epatters
|
r2715 | else: | ||
if html: | ||||
self._prompt = self._append_html_fetching_plain_text(prompt) | ||||
self._prompt_html = prompt | ||||
else: | ||||
epatters
|
r2736 | self._append_plain_text(prompt) | ||
epatters
|
r2715 | self._prompt = prompt | ||
self._prompt_html = None | ||||
epatters
|
r2705 | |||
epatters
|
r2602 | self._prompt_pos = self._get_end_cursor().position() | ||
self._prompt_started() | ||||
def _show_continuation_prompt(self): | ||||
""" Writes a new continuation prompt at the end of the buffer. | ||||
""" | ||||
epatters
|
r2715 | if self._continuation_prompt_html is None: | ||
epatters
|
r2736 | self._append_plain_text(self._continuation_prompt) | ||
epatters
|
r2715 | else: | ||
self._continuation_prompt = self._append_html_fetching_plain_text( | ||||
self._continuation_prompt_html) | ||||
epatters
|
r2602 | |||
epatters
|
r2715 | self._prompt_started() | ||
epatters
|
r2602 | |||
class HistoryConsoleWidget(ConsoleWidget): | ||||
""" A ConsoleWidget that keeps a history of the commands that have been | ||||
executed. | ||||
""" | ||||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2736 | # 'object' interface | ||
epatters
|
r2602 | #--------------------------------------------------------------------------- | ||
epatters
|
r2736 | def __init__(self, *args, **kw): | ||
super(HistoryConsoleWidget, self).__init__(*args, **kw) | ||||
epatters
|
r2602 | self._history = [] | ||
self._history_index = 0 | ||||
#--------------------------------------------------------------------------- | ||||
# 'ConsoleWidget' public interface | ||||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2688 | def execute(self, source=None, hidden=False, interactive=False): | ||
epatters
|
r2602 | """ Reimplemented to the store history. | ||
""" | ||||
epatters
|
r2689 | if not hidden: | ||
history = self.input_buffer if source is None else source | ||||
epatters
|
r2688 | |||
executed = super(HistoryConsoleWidget, self).execute( | ||||
source, hidden, interactive) | ||||
if executed and not hidden: | ||||
epatters
|
r2689 | self._history.append(history.rstrip()) | ||
epatters
|
r2602 | self._history_index = len(self._history) | ||
epatters
|
r2688 | |||
epatters
|
r2602 | return executed | ||
#--------------------------------------------------------------------------- | ||||
# 'ConsoleWidget' abstract interface | ||||
#--------------------------------------------------------------------------- | ||||
def _up_pressed(self): | ||||
""" Called when the up key is pressed. Returns whether to continue | ||||
processing the event. | ||||
""" | ||||
prompt_cursor = self._get_prompt_cursor() | ||||
epatters
|
r2736 | if self._get_cursor().blockNumber() == prompt_cursor.blockNumber(): | ||
epatters
|
r2602 | self.history_previous() | ||
# Go to the first line of prompt for seemless history scrolling. | ||||
cursor = self._get_prompt_cursor() | ||||
cursor.movePosition(QtGui.QTextCursor.EndOfLine) | ||||
epatters
|
r2736 | self._set_cursor(cursor) | ||
epatters
|
r2602 | |||
return False | ||||
return True | ||||
def _down_pressed(self): | ||||
""" Called when the down key is pressed. Returns whether to continue | ||||
processing the event. | ||||
""" | ||||
end_cursor = self._get_end_cursor() | ||||
epatters
|
r2736 | if self._get_cursor().blockNumber() == end_cursor.blockNumber(): | ||
epatters
|
r2602 | self.history_next() | ||
return False | ||||
return True | ||||
#--------------------------------------------------------------------------- | ||||
# 'HistoryConsoleWidget' interface | ||||
#--------------------------------------------------------------------------- | ||||
def history_previous(self): | ||||
""" If possible, set the input buffer to the previous item in the | ||||
history. | ||||
""" | ||||
if self._history_index > 0: | ||||
self._history_index -= 1 | ||||
self.input_buffer = self._history[self._history_index] | ||||
def history_next(self): | ||||
""" Set the input buffer to the next item in the history, or a blank | ||||
line if there is no subsequent item. | ||||
""" | ||||
if self._history_index < len(self._history): | ||||
self._history_index += 1 | ||||
if self._history_index < len(self._history): | ||||
self.input_buffer = self._history[self._history_index] | ||||
else: | ||||
self.input_buffer = '' | ||||