frontend_widget.py
667 lines
| 27.6 KiB
| text/x-python
|
PythonLexer
|
r3004 | from __future__ import print_function | ||
|
r2687 | # Standard library imports | ||
|
r2934 | from collections import namedtuple | ||
|
r2714 | import sys | ||
|
r3090 | import time | ||
|
r2687 | |||
|
r2602 | # System library imports | ||
from pygments.lexers import PythonLexer | ||||
|
r5258 | from IPython.external import qt | ||
|
r3304 | from IPython.external.qt import QtCore, QtGui | ||
|
r2602 | |||
# Local imports | ||||
|
r2971 | from IPython.core.inputsplitter import InputSplitter, transform_classic_prompt | ||
|
r3051 | from IPython.core.oinspect import call_tip | ||
|
r2770 | from IPython.frontend.qt.base_frontend_mixin import BaseFrontendMixin | ||
|
r4689 | from IPython.utils.traitlets import Bool, Instance, Unicode | ||
|
r2894 | from bracket_matcher import BracketMatcher | ||
|
r2602 | from call_tip_widget import CallTipWidget | ||
from completion_lexer import CompletionLexer | ||||
|
r2983 | from history_console_widget import HistoryConsoleWidget | ||
|
r2603 | from pygments_highlighter import PygmentsHighlighter | ||
|
r2602 | |||
class FrontendHighlighter(PygmentsHighlighter): | ||||
|
r4058 | """ A PygmentsHighlighter that understands and ignores prompts. | ||
|
r2602 | """ | ||
def __init__(self, frontend): | ||||
|
r2736 | super(FrontendHighlighter, self).__init__(frontend._control.document()) | ||
|
r2602 | self._current_offset = 0 | ||
self._frontend = frontend | ||||
self.highlighting_on = False | ||||
|
r3304 | def highlightBlock(self, string): | ||
|
r2602 | """ Highlight a block of text. Reimplemented to highlight selectively. | ||
""" | ||||
|
r2715 | if not self.highlighting_on: | ||
return | ||||
|
r3304 | # The input to this function is a unicode string that may contain | ||
|
r2715 | # paragraph break characters, non-breaking spaces, etc. Here we acquire | ||
# the string as plain text so we can compare it. | ||||
current_block = self.currentBlock() | ||||
string = self._frontend._get_block_plain_text(current_block) | ||||
# Decide whether to check for the regular or continuation prompt. | ||||
if current_block.contains(self._frontend._prompt_pos): | ||||
prompt = self._frontend._prompt | ||||
else: | ||||
prompt = self._frontend._continuation_prompt | ||||
|
r4058 | # Only highlight if we can identify a prompt, but make sure not to | ||
# highlight the prompt. | ||||
|
r2715 | if string.startswith(prompt): | ||
self._current_offset = len(prompt) | ||||
|
r3304 | string = string[len(prompt):] | ||
|
r4058 | super(FrontendHighlighter, self).highlightBlock(string) | ||
|
r2602 | |||
|
r2825 | def rehighlightBlock(self, block): | ||
""" Reimplemented to temporarily enable highlighting if disabled. | ||||
""" | ||||
old = self.highlighting_on | ||||
self.highlighting_on = True | ||||
super(FrontendHighlighter, self).rehighlightBlock(block) | ||||
self.highlighting_on = old | ||||
|
r2602 | def setFormat(self, start, count, format): | ||
|
r2715 | """ Reimplemented to highlight selectively. | ||
|
r2602 | """ | ||
start += self._current_offset | ||||
|
r4058 | super(FrontendHighlighter, self).setFormat(start, count, format) | ||
|
r2602 | |||
|
r2770 | class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin): | ||
|
r2627 | """ A Qt frontend for a generic Python kernel. | ||
|
r2602 | """ | ||
|
r2851 | |||
|
r4689 | # The text to show when the kernel is (re)started. | ||
banner = Unicode() | ||||
|
r4569 | |||
|
r2851 | # An option and corresponding signal for overriding the default kernel | ||
# interrupt behavior. | ||||
|
r2884 | custom_interrupt = Bool(False) | ||
|
r3304 | custom_interrupt_requested = QtCore.Signal() | ||
|
r2851 | |||
|
r2913 | # An option and corresponding signals for overriding the default kernel | ||
|
r2851 | # restart behavior. | ||
|
r2884 | custom_restart = Bool(False) | ||
|
r3304 | custom_restart_kernel_died = QtCore.Signal(float) | ||
custom_restart_requested = QtCore.Signal() | ||||
|
r3516 | |||
|
r4689 | # Whether to automatically show calltips on open-parentheses. | ||
enable_calltips = Bool(True, config=True, | ||||
help="Whether to draw information calltips on open-parentheses.") | ||||
|
r3682 | # Emitted when a user visible 'execute_request' has been submitted to the | ||
# kernel from the FrontendWidget. Contains the code to be executed. | ||||
executing = QtCore.Signal(object) | ||||
|
r3516 | # Emitted when a user-visible 'execute_reply' has been received from the | ||
# kernel and processed by the FrontendWidget. Contains the response message. | ||||
|
r3304 | executed = QtCore.Signal(object) | ||
|
r2961 | |||
# Emitted when an exit request has been received from the kernel. | ||||
|
r5035 | exit_requested = QtCore.Signal(object) | ||
|
r4872 | |||
|
r2851 | # Protected class variables. | ||
|
r2934 | _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos']) | ||
_CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos']) | ||||
_ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind']) | ||||
|
r2894 | _input_splitter_class = InputSplitter | ||
|
r3129 | _local_kernel = False | ||
|
r3971 | _highlighter = Instance(FrontendHighlighter) | ||
|
r2800 | |||
|
r2602 | #--------------------------------------------------------------------------- | ||
|
r2736 | # 'object' interface | ||
|
r2602 | #--------------------------------------------------------------------------- | ||
|
r4872 | |||
|
r2736 | def __init__(self, *args, **kw): | ||
super(FrontendWidget, self).__init__(*args, **kw) | ||||
|
r5285 | # FIXME: remove this when PySide min version is updated past 1.0.7 | ||
|
r5258 | # forcefully disable calltips if PySide is < 1.0.7, because they crash | ||
if qt.QT_API == qt.QT_API_PYSIDE: | ||||
import PySide | ||||
if PySide.__version_info__ < (1,0,7): | ||||
|
r5285 | self.log.warn("PySide %s < 1.0.7 detected, disabling calltips" % PySide.__version__) | ||
|
r5258 | self.enable_calltips = False | ||
|
r2602 | |||
|
r2643 | # FrontendWidget protected variables. | ||
|
r2894 | self._bracket_matcher = BracketMatcher(self._control) | ||
|
r2736 | self._call_tip_widget = CallTipWidget(self._control) | ||
|
r2602 | self._completion_lexer = CompletionLexer(PythonLexer()) | ||
|
r2990 | self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None) | ||
|
r2824 | self._hidden = False | ||
|
r2894 | self._highlighter = FrontendHighlighter(self) | ||
|
r3004 | self._input_splitter = self._input_splitter_class(input_mode='cell') | ||
|
r2611 | self._kernel_manager = None | ||
|
r2934 | self._request_info = {} | ||
|
r2602 | |||
|
r2715 | # Configure the ConsoleWidget. | ||
|
r2723 | self.tab_width = 4 | ||
|
r2715 | self._set_continuation_prompt('... ') | ||
|
r3031 | # Configure the CallTipWidget. | ||
self._call_tip_widget.setFont(self.font) | ||||
self.font_changed.connect(self._call_tip_widget.setFont) | ||||
|
r2990 | # Configure actions. | ||
action = self._copy_raw_action | ||||
key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C | ||||
action.setEnabled(False) | ||||
action.setShortcut(QtGui.QKeySequence(key)) | ||||
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) | ||||
action.triggered.connect(self.copy_raw) | ||||
self.copy_available.connect(action.setEnabled) | ||||
self.addAction(action) | ||||
|
r2736 | # Connect signal handlers. | ||
document = self._control.document() | ||||
document.contentsChange.connect(self._document_contents_change) | ||||
|
r4872 | |||
|
r3361 | # Set flag for whether we are connected via localhost. | ||
|
r4872 | self._local_kernel = kw.get('local_kernel', | ||
|
r3361 | FrontendWidget._local_kernel) | ||
|
r2612 | |||
|
r2669 | #--------------------------------------------------------------------------- | ||
|
r2971 | # 'ConsoleWidget' public interface | ||
#--------------------------------------------------------------------------- | ||||
def copy(self): | ||||
""" Copy the currently selected text to the clipboard, removing prompts. | ||||
""" | ||||
|
r3304 | text = self._control.textCursor().selection().toPlainText() | ||
|
r2971 | if text: | ||
lines = map(transform_classic_prompt, text.splitlines()) | ||||
text = '\n'.join(lines) | ||||
|
r3022 | QtGui.QApplication.clipboard().setText(text) | ||
|
r2971 | |||
#--------------------------------------------------------------------------- | ||||
|
r2602 | # 'ConsoleWidget' abstract interface | ||
#--------------------------------------------------------------------------- | ||||
|
r2688 | def _is_complete(self, source, interactive): | ||
""" Returns whether 'source' can be completely processed and a new | ||||
prompt created. When triggered by an Enter/Return key press, | ||||
'interactive' is True; otherwise, it is False. | ||||
|
r2602 | """ | ||
|
r3022 | complete = self._input_splitter.push(source) | ||
|
r2688 | if interactive: | ||
complete = not self._input_splitter.push_accepts_more() | ||||
return complete | ||||
|
r2961 | def _execute(self, source, hidden): | ||
|
r2688 | """ Execute 'source'. If 'hidden', do not show any output. | ||
|
r2926 | |||
See parent class :meth:`execute` docstring for full details. | ||||
|
r2688 | """ | ||
|
r3974 | msg_id = self.kernel_manager.shell_channel.execute(source, hidden) | ||
|
r2934 | self._request_info['execute'] = self._ExecutionRequest(msg_id, 'user') | ||
|
r2688 | self._hidden = hidden | ||
|
r3682 | if not hidden: | ||
self.executing.emit(source) | ||||
|
r4872 | |||
|
r2602 | def _prompt_started_hook(self): | ||
""" Called immediately after a new prompt is displayed. | ||||
""" | ||||
|
r2709 | if not self._reading: | ||
self._highlighter.highlighting_on = True | ||||
|
r2602 | |||
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. | ||||
""" | ||||
|
r3361 | # Flush all state from the input splitter so the next round of | ||
# reading input starts with a clean buffer. | ||||
self._input_splitter.reset() | ||||
|
r2709 | if not self._reading: | ||
self._highlighter.highlighting_on = False | ||||
|
r2602 | |||
def _tab_pressed(self): | ||||
""" Called when the tab key is pressed. Returns whether to continue | ||||
processing the event. | ||||
""" | ||||
|
r2847 | # Perform tab completion if: | ||
# 1) The cursor is in the input buffer. | ||||
# 2) There is a non-whitespace character before the cursor. | ||||
text = self._get_input_buffer_cursor_line() | ||||
if text is None: | ||||
return False | ||||
complete = bool(text[:self._get_input_buffer_cursor_column()].strip()) | ||||
if complete: | ||||
self._complete() | ||||
return not complete | ||||
|
r2602 | |||
#--------------------------------------------------------------------------- | ||||
|
r2787 | # 'ConsoleWidget' protected interface | ||
#--------------------------------------------------------------------------- | ||||
|
r2990 | def _context_menu_make(self, pos): | ||
""" Reimplemented to add an action for raw copy. | ||||
""" | ||||
menu = super(FrontendWidget, self)._context_menu_make(pos) | ||||
for before_action in menu.actions(): | ||||
if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ | ||||
QtGui.QKeySequence.ExactMatch: | ||||
menu.insertAction(before_action, self._copy_raw_action) | ||||
break | ||||
return menu | ||||
|
r5063 | def request_interrupt_kernel(self): | ||
if self._executing: | ||||
self.interrupt_kernel() | ||||
def request_restart_kernel(self): | ||||
message = 'Are you sure you want to restart the kernel?' | ||||
self.restart_kernel(message, now=False) | ||||
|
r2851 | def _event_filter_console_keypress(self, event): | ||
|
r3022 | """ Reimplemented for execution interruption and smart backspace. | ||
|
r2851 | """ | ||
key = event.key() | ||||
|
r2941 | if self._control_key_down(event.modifiers(), include_command=False): | ||
|
r3022 | |||
|
r2897 | if key == QtCore.Qt.Key_C and self._executing: | ||
|
r5063 | self.request_interrupt_kernel() | ||
|
r2914 | return True | ||
|
r3022 | |||
|
r2851 | elif key == QtCore.Qt.Key_Period: | ||
|
r5063 | self.request_restart_kernel() | ||
|
r2851 | return True | ||
|
r3022 | |||
elif not event.modifiers() & QtCore.Qt.AltModifier: | ||||
# Smart backspace: remove four characters in one backspace if: | ||||
# 1) everything left of the cursor is whitespace | ||||
# 2) the four characters immediately left of the cursor are spaces | ||||
if key == QtCore.Qt.Key_Backspace: | ||||
col = self._get_input_buffer_cursor_column() | ||||
cursor = self._control.textCursor() | ||||
if col > 3 and not cursor.hasSelection(): | ||||
text = self._get_input_buffer_cursor_line()[:col] | ||||
if text.endswith(' ') and not text.strip(): | ||||
cursor.movePosition(QtGui.QTextCursor.Left, | ||||
QtGui.QTextCursor.KeepAnchor, 4) | ||||
cursor.removeSelectedText() | ||||
return True | ||||
|
r2851 | return super(FrontendWidget, self)._event_filter_console_keypress(event) | ||
|
r2896 | def _insert_continuation_prompt(self, cursor): | ||
|
r2787 | """ Reimplemented for auto-indentation. | ||
""" | ||||
|
r2896 | super(FrontendWidget, self)._insert_continuation_prompt(cursor) | ||
|
r3022 | cursor.insertText(' ' * self._input_splitter.indent_spaces) | ||
|
r2787 | |||
#--------------------------------------------------------------------------- | ||||
|
r2770 | # 'BaseFrontendMixin' abstract interface | ||
|
r2602 | #--------------------------------------------------------------------------- | ||
|
r2770 | def _handle_complete_reply(self, rep): | ||
""" Handle replies for tab completion. | ||||
|
r2602 | """ | ||
|
r4793 | self.log.debug("complete: %s", rep.get('content', '')) | ||
|
r2770 | cursor = self._get_cursor() | ||
|
r2934 | info = self._request_info.get('complete') | ||
if info and info.id == rep['parent_header']['msg_id'] and \ | ||||
info.pos == cursor.position(): | ||||
|
r2867 | text = '.'.join(self._get_context()) | ||
|
r2770 | cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) | ||
self._complete_with_items(cursor, rep['content']['matches']) | ||||
|
r2602 | |||
|
r2770 | def _handle_execute_reply(self, msg): | ||
""" Handles replies for code execution. | ||||
|
r2609 | """ | ||
|
r4793 | self.log.debug("execute: %s", msg.get('content', '')) | ||
|
r2934 | info = self._request_info.get('execute') | ||
|
r5188 | # unset reading flag, because if execute finished, raw_input can't | ||
# still be pending. | ||||
self._reading = False | ||||
|
r2934 | if info and info.id == msg['parent_header']['msg_id'] and \ | ||
|
r2961 | info.kind == 'user' and not self._hidden: | ||
|
r2770 | # Make sure that all output from the SUB channel has been processed | ||
# before writing a new prompt. | ||||
self.kernel_manager.sub_channel.flush() | ||||
|
r3000 | # Reset the ANSI style information to prevent bad text in stdout | ||
# from messing up our colors. We're not a true terminal so we're | ||||
# allowed to do this. | ||||
if self.ansi_codes: | ||||
self._ansi_processor.reset_sgr() | ||||
|
r2770 | content = msg['content'] | ||
status = content['status'] | ||||
if status == 'ok': | ||||
self._process_execute_ok(msg) | ||||
elif status == 'error': | ||||
self._process_execute_error(msg) | ||||
|
r5188 | elif status == 'aborted': | ||
|
r2770 | self._process_execute_abort(msg) | ||
|
r2797 | self._show_interpreter_prompt_for_reply(msg) | ||
|
r2770 | self.executed.emit(msg) | ||
|
r5030 | else: | ||
super(FrontendWidget, self)._handle_execute_reply(msg) | ||||
|
r2770 | |||
def _handle_input_request(self, msg): | ||||
""" Handle requests for raw_input. | ||||
""" | ||||
|
r4793 | self.log.debug("input: %s", msg.get('content', '')) | ||
|
r2771 | if self._hidden: | ||
raise RuntimeError('Request for raw input during hidden execution.') | ||||
|
r2770 | # Make sure that all output from the SUB channel has been processed | ||
# before entering readline mode. | ||||
self.kernel_manager.sub_channel.flush() | ||||
def callback(line): | ||||
|
r3974 | self.kernel_manager.stdin_channel.input(line) | ||
|
r5188 | if self._reading: | ||
self.log.debug("Got second input request, assuming first was interrupted.") | ||||
self._reading = False | ||||
|
r2770 | self._readline(msg['content']['prompt'], callback=callback) | ||
|
r2609 | |||
|
r2913 | def _handle_kernel_died(self, since_last_heartbeat): | ||
""" Handle the kernel's death by asking if the user wants to restart. | ||||
""" | ||||
|
r4793 | self.log.debug("kernel died: %s", since_last_heartbeat) | ||
|
r2913 | if self.custom_restart: | ||
self.custom_restart_kernel_died.emit(since_last_heartbeat) | ||||
else: | ||||
|
r3033 | message = 'The kernel heartbeat has been inactive for %.2f ' \ | ||
'seconds. Do you want to restart the kernel? You may ' \ | ||||
'first want to check the network connection.' % \ | ||||
since_last_heartbeat | ||||
|
r3030 | self.restart_kernel(message, now=True) | ||
|
r2913 | |||
|
r2770 | def _handle_object_info_reply(self, rep): | ||
""" Handle replies for call tips. | ||||
|
r2609 | """ | ||
|
r4793 | self.log.debug("oinfo: %s", rep.get('content', '')) | ||
|
r2770 | cursor = self._get_cursor() | ||
|
r2934 | info = self._request_info.get('call_tip') | ||
if info and info.id == rep['parent_header']['msg_id'] and \ | ||||
info.pos == cursor.position(): | ||||
|
r3051 | # Get the information for a call tip. For now we format the call | ||
# line as string, later we can pass False to format_call and | ||||
# syntax-highlight it ourselves for nicer formatting in the | ||||
# calltip. | ||||
|
r3934 | content = rep['content'] | ||
# if this is from pykernel, 'docstring' will be the only key | ||||
if content.get('ismagic', False): | ||||
|
r3685 | # Don't generate a call-tip for magics. Ideally, we should | ||
# generate a tooltip, but not on ( like we do for actual | ||||
# callables. | ||||
call_info, doc = None, None | ||||
else: | ||||
|
r3934 | call_info, doc = call_tip(content, format_call=True) | ||
|
r3051 | if call_info or doc: | ||
self._call_tip_widget.show_call_info(call_info, doc) | ||||
|
r2643 | |||
|
r2770 | def _handle_pyout(self, msg): | ||
""" Handle display hook output. | ||||
""" | ||||
|
r4793 | self.log.debug("pyout: %s", msg.get('content', '')) | ||
|
r2824 | if not self._hidden and self._is_from_this_session(msg): | ||
|
r4056 | text = msg['content']['data'] | ||
self._append_plain_text(text + '\n', before_prompt=True) | ||||
|
r2609 | |||
|
r2770 | def _handle_stream(self, msg): | ||
""" Handle stdout, stderr, and stdin. | ||||
""" | ||||
|
r4793 | self.log.debug("stream: %s", msg.get('content', '')) | ||
|
r2824 | if not self._hidden and self._is_from_this_session(msg): | ||
|
r2997 | # Most consoles treat tabs as being 8 space characters. Convert tabs | ||
# to spaces so that output looks as expected regardless of this | ||||
# widget's tab width. | ||||
text = msg['content']['data'].expandtabs(8) | ||||
|
r4872 | |||
|
r4056 | self._append_plain_text(text, before_prompt=True) | ||
|
r2824 | self._control.moveCursor(QtGui.QTextCursor.End) | ||
|
r3035 | |||
|
r3090 | def _handle_shutdown_reply(self, msg): | ||
""" Handle shutdown signal, only if from other console. | ||||
""" | ||||
|
r4793 | self.log.debug("shutdown: %s", msg.get('content', '')) | ||
|
r3090 | if not self._hidden and not self._is_from_this_session(msg): | ||
|
r3129 | if self._local_kernel: | ||
if not msg['content']['restart']: | ||||
|
r5038 | self.exit_requested.emit(self) | ||
|
r3129 | else: | ||
# we just got notified of a restart! | ||||
time.sleep(0.25) # wait 1/4 sec to reset | ||||
# lest the request for a new prompt | ||||
# goes to the old kernel | ||||
self.reset() | ||||
else: # remote kernel, prompt on Kernel shutdown/reset | ||||
title = self.window().windowTitle() | ||||
if not msg['content']['restart']: | ||||
reply = QtGui.QMessageBox.question(self, title, | ||||
|
r3361 | "Kernel has been shutdown permanently. " | ||
"Close the Console?", | ||||
|
r3129 | QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) | ||
if reply == QtGui.QMessageBox.Yes: | ||||
|
r5035 | self.exit_requested.emit(self) | ||
|
r3129 | else: | ||
reply = QtGui.QMessageBox.question(self, title, | ||||
"Kernel has been reset. Clear the Console?", | ||||
QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) | ||||
if reply == QtGui.QMessageBox.Yes: | ||||
time.sleep(0.25) # wait 1/4 sec to reset | ||||
# lest the request for a new prompt | ||||
# goes to the old kernel | ||||
self.reset() | ||||
|
r3090 | |||
|
r2770 | def _started_channels(self): | ||
|
r4872 | """ Called when the KernelManager channels have started listening or | ||
|
r2770 | when the frontend is assigned an already listening KernelManager. | ||
""" | ||||
|
r3033 | self.reset() | ||
|
r2770 | |||
#--------------------------------------------------------------------------- | ||||
|
r2971 | # 'FrontendWidget' public interface | ||
|
r2770 | #--------------------------------------------------------------------------- | ||
|
r2990 | def copy_raw(self): | ||
""" Copy the currently selected text to the clipboard without attempting | ||||
to remove prompts or otherwise alter the text. | ||||
""" | ||||
self._control.copy() | ||||
|
r2770 | def execute_file(self, path, hidden=False): | ||
""" Attempts to execute file with 'path'. If 'hidden', no output is | ||||
shown. | ||||
""" | ||||
|
r3797 | self.execute('execfile(%r)' % path, hidden=hidden) | ||
|
r2609 | |||
|
r2913 | def interrupt_kernel(self): | ||
""" Attempts to interrupt the running kernel. | ||||
|
r5188 | |||
Also unsets _reading flag, to avoid runtime errors | ||||
if raw_input is called again. | ||||
|
r2913 | """ | ||
if self.custom_interrupt: | ||||
|
r5188 | self._reading = False | ||
|
r2913 | self.custom_interrupt_requested.emit() | ||
elif self.kernel_manager.has_kernel: | ||||
|
r5188 | self._reading = False | ||
|
r3027 | self.kernel_manager.interrupt_kernel() | ||
|
r2913 | else: | ||
self._append_plain_text('Kernel process is either remote or ' | ||||
'unspecified. Cannot interrupt.\n') | ||||
|
r3033 | def reset(self): | ||
""" Resets the widget to its initial state. Similar to ``clear``, but | ||||
also re-writes the banner and aborts execution if necessary. | ||||
|
r4872 | """ | ||
|
r3033 | if self._executing: | ||
self._executing = False | ||||
self._request_info['execute'] = None | ||||
self._reading = False | ||||
self._highlighter.highlighting_on = False | ||||
self._control.clear() | ||||
|
r4689 | self._append_plain_text(self.banner) | ||
|
r5161 | # update output marker for stdout/stderr, so that startup | ||
# messages appear after banner: | ||||
self._append_before_prompt_pos = self._get_cursor().position() | ||||
|
r3033 | self._show_interpreter_prompt() | ||
|
r3030 | def restart_kernel(self, message, now=False): | ||
|
r2913 | """ Attempts to restart the running kernel. | ||
""" | ||||
|
r3033 | # FIXME: now should be configurable via a checkbox in the dialog. Right | ||
# now at least the heartbeat path sets it to True and the manual restart | ||||
# to False. But those should just be the pre-selected states of a | ||||
# checkbox that the user could override if so desired. But I don't know | ||||
# enough Qt to go implementing the checkbox now. | ||||
if self.custom_restart: | ||||
self.custom_restart_requested.emit() | ||||
elif self.kernel_manager.has_kernel: | ||||
# Pause the heart beat channel to prevent further warnings. | ||||
self.kernel_manager.hb_channel.pause() | ||||
# Prompt the user to restart the kernel. Un-pause the heartbeat if | ||||
# they decline. (If they accept, the heartbeat will be un-paused | ||||
# automatically when the kernel is restarted.) | ||||
buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | ||||
result = QtGui.QMessageBox.question(self, 'Restart kernel?', | ||||
message, buttons) | ||||
if result == QtGui.QMessageBox.Yes: | ||||
try: | ||||
self.kernel_manager.restart_kernel(now=now) | ||||
except RuntimeError: | ||||
self._append_plain_text('Kernel started externally. ' | ||||
'Cannot restart.\n') | ||||
else: | ||||
self.reset() | ||||
|
r2913 | else: | ||
|
r3033 | self.kernel_manager.hb_channel.unpause() | ||
else: | ||||
self._append_plain_text('Kernel process is either remote or ' | ||||
'unspecified. Cannot restart.\n') | ||||
|
r2913 | |||
|
r2602 | #--------------------------------------------------------------------------- | ||
# 'FrontendWidget' protected interface | ||||
#--------------------------------------------------------------------------- | ||||
def _call_tip(self): | ||||
""" Shows a call tip, if appropriate, at the current cursor location. | ||||
""" | ||||
# Decide if it makes sense to show a call tip | ||||
|
r4569 | if not self.enable_calltips: | ||
return False | ||||
|
r2736 | cursor = self._get_cursor() | ||
|
r2602 | cursor.movePosition(QtGui.QTextCursor.Left) | ||
|
r3304 | if cursor.document().characterAt(cursor.position()) != '(': | ||
|
r2602 | return False | ||
context = self._get_context(cursor) | ||||
if not context: | ||||
return False | ||||
# Send the metadata request to the kernel | ||||
|
r2612 | name = '.'.join(context) | ||
|
r3974 | msg_id = self.kernel_manager.shell_channel.object_info(name) | ||
|
r2934 | pos = self._get_cursor().position() | ||
self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) | ||||
|
r2602 | return True | ||
def _complete(self): | ||||
""" Performs completion at the current cursor location. | ||||
""" | ||||
|
r2867 | context = self._get_context() | ||
if context: | ||||
# Send the completion request to the kernel | ||||
|
r3974 | msg_id = self.kernel_manager.shell_channel.complete( | ||
|
r2867 | '.'.join(context), # text | ||
self._get_input_buffer_cursor_line(), # line | ||||
self._get_input_buffer_cursor_column(), # cursor_pos | ||||
|
r4872 | self.input_buffer) # block | ||
|
r2934 | pos = self._get_cursor().position() | ||
info = self._CompletionRequest(msg_id, pos) | ||||
self._request_info['complete'] = info | ||||
|
r2602 | |||
def _get_context(self, cursor=None): | ||||
|
r2864 | """ Gets the context for the specified cursor (or the current cursor | ||
if none is specified). | ||||
|
r2602 | """ | ||
if cursor is None: | ||||
|
r2736 | cursor = self._get_cursor() | ||
|
r4872 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, | ||
|
r2602 | QtGui.QTextCursor.KeepAnchor) | ||
|
r3304 | text = cursor.selection().toPlainText() | ||
|
r2602 | return self._completion_lexer.get_context(text) | ||
|
r2770 | def _process_execute_abort(self, msg): | ||
""" Process a reply for an aborted execution request. | ||||
|
r2715 | """ | ||
|
r2770 | self._append_plain_text("ERROR: execution aborted\n") | ||
|
r2602 | |||
|
r2770 | def _process_execute_error(self, msg): | ||
""" Process a reply for an execution request that resulted in an error. | ||||
|
r2705 | """ | ||
|
r2770 | content = msg['content'] | ||
|
r3187 | # If a SystemExit is passed along, this means exit() was called - also | ||
# all the ipython %exit magic syntax of '-k' to be used to keep | ||||
# the kernel running | ||||
if content['ename']=='SystemExit': | ||||
keepkernel = content['evalue']=='-k' or content['evalue']=='True' | ||||
self._keep_kernel_on_exit = keepkernel | ||||
|
r5035 | self.exit_requested.emit(self) | ||
|
r3187 | else: | ||
traceback = ''.join(content['traceback']) | ||||
self._append_plain_text(traceback) | ||||
|
r2705 | |||
|
r2770 | def _process_execute_ok(self, msg): | ||
""" Process a reply for a successful execution equest. | ||||
|
r2705 | """ | ||
|
r2835 | payload = msg['content']['payload'] | ||
for item in payload: | ||||
if not self._process_execute_payload(item): | ||||
|
r2969 | warning = 'Warning: received unknown payload of type %s' | ||
|
r3006 | print(warning % repr(item['source'])) | ||
|
r2835 | |||
def _process_execute_payload(self, item): | ||||
""" Process a single payload item from the list of payload items in an | ||||
execution reply. Returns whether the payload was handled. | ||||
""" | ||||
|
r2770 | # The basic FrontendWidget doesn't handle payloads, as they are a | ||
# mechanism for going beyond the standard Python interpreter model. | ||||
|
r2835 | return False | ||
|
r2705 | |||
|
r2770 | def _show_interpreter_prompt(self): | ||
""" Shows a prompt for the interpreter. | ||||
""" | ||||
self._show_prompt('>>> ') | ||||
|
r2797 | def _show_interpreter_prompt_for_reply(self, msg): | ||
""" Shows a prompt for the interpreter given an 'execute_reply' message. | ||||
""" | ||||
self._show_interpreter_prompt() | ||||
|
r2770 | #------ Signal handlers ---------------------------------------------------- | ||
|
r2602 | def _document_contents_change(self, position, removed, added): | ||
|
r2744 | """ Called whenever the document's content changes. Display a call tip | ||
|
r2602 | if appropriate. | ||
""" | ||||
# Calculate where the cursor should be *after* the change: | ||||
position += added | ||||
|
r2736 | document = self._control.document() | ||
if position == self._get_cursor().position(): | ||||
|
r2602 | self._call_tip() | ||
|
r4689 | |||
#------ Trait default initializers ----------------------------------------- | ||||
def _banner_default(self): | ||||
""" Returns the standard Python banner. | ||||
""" | ||||
banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \ | ||||
'"license" for more information.' | ||||
return banner % (sys.version, sys.platform) | ||||