Show More
frontend_widget.py
330 lines
| 12.4 KiB
| text/x-python
|
PythonLexer
|
r2687 | # Standard library imports | ||
import signal | ||||
|
r2602 | # System library imports | ||
from pygments.lexers import PythonLexer | ||||
from PyQt4 import QtCore, QtGui | ||||
import zmq | ||||
# Local imports | ||||
|
r2685 | from IPython.core.inputsplitter import InputSplitter | ||
|
r2602 | from call_tip_widget import CallTipWidget | ||
from completion_lexer import CompletionLexer | ||||
from console_widget import HistoryConsoleWidget | ||||
|
r2603 | from pygments_highlighter import PygmentsHighlighter | ||
|
r2602 | |||
class FrontendHighlighter(PygmentsHighlighter): | ||||
""" A Python PygmentsHighlighter that can be turned on and off and which | ||||
knows about continuation prompts. | ||||
""" | ||||
def __init__(self, frontend): | ||||
PygmentsHighlighter.__init__(self, frontend.document(), PythonLexer()) | ||||
self._current_offset = 0 | ||||
self._frontend = frontend | ||||
self.highlighting_on = False | ||||
def highlightBlock(self, qstring): | ||||
""" Highlight a block of text. Reimplemented to highlight selectively. | ||||
""" | ||||
if self.highlighting_on: | ||||
|
r2643 | for prompt in (self._frontend._continuation_prompt, | ||
self._frontend._prompt): | ||||
|
r2602 | if qstring.startsWith(prompt): | ||
qstring.remove(0, len(prompt)) | ||||
self._current_offset = len(prompt) | ||||
break | ||||
PygmentsHighlighter.highlightBlock(self, qstring) | ||||
def setFormat(self, start, count, format): | ||||
""" Reimplemented to avoid highlighting continuation prompts. | ||||
""" | ||||
start += self._current_offset | ||||
PygmentsHighlighter.setFormat(self, start, count, format) | ||||
class FrontendWidget(HistoryConsoleWidget): | ||||
|
r2627 | """ A Qt frontend for a generic Python kernel. | ||
|
r2602 | """ | ||
# Emitted when an 'execute_reply' is received from the kernel. | ||||
|
r2611 | executed = QtCore.pyqtSignal(object) | ||
|
r2602 | |||
#--------------------------------------------------------------------------- | ||||
|
r2669 | # 'QObject' interface | ||
|
r2602 | #--------------------------------------------------------------------------- | ||
|
r2643 | def __init__(self, parent=None): | ||
|
r2602 | super(FrontendWidget, self).__init__(parent) | ||
|
r2643 | # ConsoleWidget protected variables. | ||
self._continuation_prompt = '... ' | ||||
self._prompt = '>>> ' | ||||
# FrontendWidget protected variables. | ||||
|
r2602 | self._call_tip_widget = CallTipWidget(self) | ||
self._completion_lexer = CompletionLexer(PythonLexer()) | ||||
|
r2627 | self._hidden = True | ||
|
r2602 | self._highlighter = FrontendHighlighter(self) | ||
|
r2685 | self._input_splitter = InputSplitter(input_mode='replace') | ||
|
r2611 | self._kernel_manager = None | ||
|
r2602 | |||
|
r2612 | self.document().contentsChange.connect(self._document_contents_change) | ||
|
r2669 | #--------------------------------------------------------------------------- | ||
# 'QWidget' interface | ||||
#--------------------------------------------------------------------------- | ||||
|
r2602 | def focusOutEvent(self, event): | ||
""" Reimplemented to hide calltips. | ||||
""" | ||||
self._call_tip_widget.hide() | ||||
|
r2687 | super(FrontendWidget, self).focusOutEvent(event) | ||
|
r2602 | |||
def keyPressEvent(self, event): | ||||
|
r2687 | """ Reimplemented to allow calltips to process events and to send | ||
signals to the kernel. | ||||
|
r2602 | """ | ||
|
r2687 | if self._executing and event.key() == QtCore.Qt.Key_C and \ | ||
self._control_down(event.modifiers()): | ||||
self._interrupt_kernel() | ||||
else: | ||||
|
r2688 | if self._call_tip_widget.isVisible(): | ||
self._call_tip_widget.keyPressEvent(event) | ||||
|
r2687 | super(FrontendWidget, self).keyPressEvent(event) | ||
|
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 | """ | ||
|
r2688 | complete = self._input_splitter.push(source) | ||
if interactive: | ||||
complete = not self._input_splitter.push_accepts_more() | ||||
return complete | ||||
def _execute(self, source, hidden): | ||||
""" Execute 'source'. If 'hidden', do not show any output. | ||||
""" | ||||
self.kernel_manager.xreq_channel.execute(source) | ||||
self._hidden = hidden | ||||
|
r2602 | |||
def _prompt_started_hook(self): | ||||
""" Called immediately after a new prompt is displayed. | ||||
""" | ||||
self._highlighter.highlighting_on = True | ||||
|
r2688 | # Auto-indent if this is a continuation prompt. | ||
if self._get_prompt_cursor().blockNumber() != \ | ||||
self._get_end_cursor().blockNumber(): | ||||
self.appendPlainText(' ' * self._input_splitter.indent_spaces) | ||||
|
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. | ||||
""" | ||||
self._highlighter.highlighting_on = False | ||||
def _tab_pressed(self): | ||||
""" Called when the tab key is pressed. Returns whether to continue | ||||
processing the event. | ||||
""" | ||||
self._keep_cursor_in_buffer() | ||||
cursor = self.textCursor() | ||||
if not self._complete(): | ||||
cursor.insertText(' ') | ||||
return False | ||||
#--------------------------------------------------------------------------- | ||||
# 'FrontendWidget' interface | ||||
#--------------------------------------------------------------------------- | ||||
def execute_file(self, path, hidden=False): | ||||
""" Attempts to execute file with 'path'. If 'hidden', no output is | ||||
shown. | ||||
""" | ||||
|
r2688 | self.execute('execfile("%s")' % path, hidden=hidden) | ||
|
r2602 | |||
|
r2609 | def _get_kernel_manager(self): | ||
""" Returns the current kernel manager. | ||||
""" | ||||
return self._kernel_manager | ||||
def _set_kernel_manager(self, kernel_manager): | ||||
|
r2643 | """ Disconnect from the current kernel manager (if any) and set a new | ||
kernel manager. | ||||
|
r2609 | """ | ||
|
r2643 | # Disconnect the old kernel manager, if necessary. | ||
|
r2611 | if self._kernel_manager is not None: | ||
|
r2701 | self._kernel_manager.started_channels.disconnect( | ||
self._started_channels) | ||||
self._kernel_manager.stopped_channels.disconnect( | ||||
self._stopped_channels) | ||||
|
r2643 | |||
# Disconnect the old kernel manager's channels. | ||||
|
r2611 | sub = self._kernel_manager.sub_channel | ||
xreq = self._kernel_manager.xreq_channel | ||||
sub.message_received.disconnect(self._handle_sub) | ||||
xreq.execute_reply.disconnect(self._handle_execute_reply) | ||||
xreq.complete_reply.disconnect(self._handle_complete_reply) | ||||
xreq.object_info_reply.disconnect(self._handle_object_info_reply) | ||||
|
r2702 | # Handle the case where the old kernel manager is still listening. | ||
|
r2699 | if self._kernel_manager.channels_running: | ||
|
r2701 | self._stopped_channels() | ||
|
r2687 | |||
|
r2643 | # Set the new kernel manager. | ||
|
r2609 | self._kernel_manager = kernel_manager | ||
|
r2643 | if kernel_manager is None: | ||
return | ||||
# Connect the new kernel manager. | ||||
|
r2701 | kernel_manager.started_channels.connect(self._started_channels) | ||
kernel_manager.stopped_channels.connect(self._stopped_channels) | ||||
|
r2643 | |||
# Connect the new kernel manager's channels. | ||||
|
r2611 | sub = kernel_manager.sub_channel | ||
xreq = kernel_manager.xreq_channel | ||||
sub.message_received.connect(self._handle_sub) | ||||
xreq.execute_reply.connect(self._handle_execute_reply) | ||||
|
r2612 | xreq.complete_reply.connect(self._handle_complete_reply) | ||
xreq.object_info_reply.connect(self._handle_object_info_reply) | ||||
|
r2611 | |||
|
r2701 | # Handle the case where the kernel manager started channels before | ||
|
r2643 | # we connected. | ||
|
r2699 | if kernel_manager.channels_running: | ||
|
r2701 | self._started_channels() | ||
|
r2609 | |||
kernel_manager = property(_get_kernel_manager, _set_kernel_manager) | ||||
|
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 | ||||
cursor = self.textCursor() | ||||
cursor.movePosition(QtGui.QTextCursor.Left) | ||||
document = self.document() | ||||
if document.characterAt(cursor.position()).toAscii() != '(': | ||||
return False | ||||
context = self._get_context(cursor) | ||||
if not context: | ||||
return False | ||||
# Send the metadata request to the kernel | ||||
|
r2612 | name = '.'.join(context) | ||
self._calltip_id = self.kernel_manager.xreq_channel.object_info(name) | ||||
self._calltip_pos = self.textCursor().position() | ||||
|
r2602 | return True | ||
def _complete(self): | ||||
""" Performs completion at the current cursor location. | ||||
""" | ||||
# Decide if it makes sense to do completion | ||||
context = self._get_context() | ||||
if not context: | ||||
return False | ||||
# Send the completion request to the kernel | ||||
text = '.'.join(context) | ||||
|
r2612 | self._complete_id = self.kernel_manager.xreq_channel.complete( | ||
text, self.input_buffer_cursor_line, self.input_buffer) | ||||
self._complete_pos = self.textCursor().position() | ||||
|
r2602 | return True | ||
def _get_context(self, cursor=None): | ||||
""" Gets the context at the current cursor location. | ||||
""" | ||||
if cursor is None: | ||||
cursor = self.textCursor() | ||||
cursor.movePosition(QtGui.QTextCursor.StartOfLine, | ||||
QtGui.QTextCursor.KeepAnchor) | ||||
text = unicode(cursor.selectedText()) | ||||
return self._completion_lexer.get_context(text) | ||||
|
r2687 | def _interrupt_kernel(self): | ||
""" Attempts to the interrupt the kernel. | ||||
""" | ||||
if self.kernel_manager.has_kernel: | ||||
self.kernel_manager.signal_kernel(signal.SIGINT) | ||||
else: | ||||
self.appendPlainText('Kernel process is either remote or ' | ||||
'unspecified. Cannot interrupt.\n') | ||||
|
r2602 | #------ Signal handlers ---------------------------------------------------- | ||
def _document_contents_change(self, position, removed, added): | ||||
""" Called whenever the document's content changes. Display a calltip | ||||
if appropriate. | ||||
""" | ||||
# Calculate where the cursor should be *after* the change: | ||||
position += added | ||||
document = self.document() | ||||
if position == self.textCursor().position(): | ||||
self._call_tip() | ||||
|
r2611 | def _handle_sub(self, omsg): | ||
|
r2688 | if self._hidden: | ||
return | ||||
handler = getattr(self, '_handle_%s' % omsg['msg_type'], None) | ||||
if handler is not None: | ||||
handler(omsg) | ||||
|
r2602 | |||
def _handle_pyout(self, omsg): | ||||
|
r2611 | session = omsg['parent_header']['session'] | ||
if session == self.kernel_manager.session.session: | ||||
self.appendPlainText(omsg['content']['data'] + '\n') | ||||
|
r2602 | |||
def _handle_stream(self, omsg): | ||||
|
r2611 | self.appendPlainText(omsg['content']['data']) | ||
|
r2688 | self.moveCursor(QtGui.QTextCursor.End) | ||
|
r2602 | |||
|
r2611 | def _handle_execute_reply(self, rep): | ||
|
r2688 | if self._hidden: | ||
return | ||||
|
r2614 | # Make sure that all output from the SUB channel has been processed | ||
# before writing a new prompt. | ||||
self.kernel_manager.sub_channel.flush() | ||||
|
r2611 | content = rep['content'] | ||
status = content['status'] | ||||
if status == 'error': | ||||
self.appendPlainText(content['traceback'][-1]) | ||||
elif status == 'aborted': | ||||
text = "ERROR: ABORTED\n" | ||||
self.appendPlainText(text) | ||||
|
r2627 | self._hidden = True | ||
|
r2643 | self._show_prompt() | ||
|
r2611 | self.executed.emit(rep) | ||
|
r2602 | |||
|
r2612 | def _handle_complete_reply(self, rep): | ||
cursor = self.textCursor() | ||||
if rep['parent_header']['msg_id'] == self._complete_id and \ | ||||
cursor.position() == self._complete_pos: | ||||
text = '.'.join(self._get_context()) | ||||
cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) | ||||
self._complete_with_items(cursor, rep['content']['matches']) | ||||
|
r2602 | |||
|
r2612 | def _handle_object_info_reply(self, rep): | ||
cursor = self.textCursor() | ||||
if rep['parent_header']['msg_id'] == self._calltip_id and \ | ||||
cursor.position() == self._calltip_pos: | ||||
doc = rep['content']['docstring'] | ||||
if doc: | ||||
|
r2666 | self._call_tip_widget.show_docstring(doc) | ||
|
r2643 | |||
|
r2701 | def _started_channels(self): | ||
|
r2643 | self.clear() | ||
|
r2701 | def _stopped_channels(self): | ||
|
r2643 | pass | ||