##// END OF EJS Templates
Added machinery to IPythonWidget for updating the previous prompt number.
Added machinery to IPythonWidget for updating the previous prompt number.

File last commit:

r2730:18dcf1de
r2733:769661eb
Show More
frontend_widget.py
382 lines | 14.3 KiB | text/x-python | PythonLexer
epatters
* Added ability to interrupt a kernel to FrontendWidget...
r2687 # Standard library imports
import signal
epatters
Added banners to FrontendWidget and IPythonWidget.
r2714 import sys
epatters
* Added ability to interrupt a kernel to FrontendWidget...
r2687
epatters
Initial checkin of Qt frontend code.
r2602 # System library imports
from pygments.lexers import PythonLexer
from PyQt4 import QtCore, QtGui
import zmq
# Local imports
epatters
Updated to FrontendWidget to reflect BlockBreaker API changes.
r2685 from IPython.core.inputsplitter import InputSplitter
epatters
Initial checkin of Qt frontend code.
r2602 from call_tip_widget import CallTipWidget
from completion_lexer import CompletionLexer
from console_widget import HistoryConsoleWidget
epatters
Fixed imports and removed references to ETS/EPD
r2603 from pygments_highlighter import PygmentsHighlighter
epatters
Initial checkin of Qt frontend code.
r2602
class FrontendHighlighter(PygmentsHighlighter):
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 """ A PygmentsHighlighter that can be turned on and off and that ignores
prompts.
epatters
Initial checkin of Qt frontend code.
r2602 """
def __init__(self, frontend):
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 super(FrontendHighlighter, self).__init__(frontend.document())
epatters
Initial checkin of Qt frontend code.
r2602 self._current_offset = 0
self._frontend = frontend
self.highlighting_on = False
def highlightBlock(self, qstring):
""" Highlight a block of text. Reimplemented to highlight selectively.
"""
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 if not self.highlighting_on:
return
# The input to this function is unicode string that may contain
# 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
# Don't highlight the part of the string that contains the prompt.
if string.startswith(prompt):
self._current_offset = len(prompt)
qstring.remove(0, len(prompt))
else:
self._current_offset = 0
PygmentsHighlighter.highlightBlock(self, qstring)
epatters
Initial checkin of Qt frontend code.
r2602
def setFormat(self, start, count, format):
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 """ Reimplemented to highlight selectively.
epatters
Initial checkin of Qt frontend code.
r2602 """
start += self._current_offset
PygmentsHighlighter.setFormat(self, start, count, format)
class FrontendWidget(HistoryConsoleWidget):
epatters
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627 """ A Qt frontend for a generic Python kernel.
epatters
Initial checkin of Qt frontend code.
r2602 """
epatters
* ConsoleWidget now has better support for non-GUI tab completion. Multiple matches are formatted into columns....
r2723
epatters
Initial checkin of Qt frontend code.
r2602 # Emitted when an 'execute_reply' is received from the kernel.
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 executed = QtCore.pyqtSignal(object)
epatters
Initial checkin of Qt frontend code.
r2602
#---------------------------------------------------------------------------
epatters
Minor comment cleanup.
r2669 # 'QObject' interface
epatters
Initial checkin of Qt frontend code.
r2602 #---------------------------------------------------------------------------
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643 def __init__(self, parent=None):
epatters
Initial checkin of Qt frontend code.
r2602 super(FrontendWidget, self).__init__(parent)
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643 # FrontendWidget protected variables.
epatters
Initial checkin of Qt frontend code.
r2602 self._call_tip_widget = CallTipWidget(self)
self._completion_lexer = CompletionLexer(PythonLexer())
epatters
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627 self._hidden = True
epatters
Initial checkin of Qt frontend code.
r2602 self._highlighter = FrontendHighlighter(self)
epatters
Updated to FrontendWidget to reflect BlockBreaker API changes.
r2685 self._input_splitter = InputSplitter(input_mode='replace')
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 self._kernel_manager = None
epatters
Initial checkin of Qt frontend code.
r2602
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 # Configure the ConsoleWidget.
epatters
* ConsoleWidget now has better support for non-GUI tab completion. Multiple matches are formatted into columns....
r2723 self.tab_width = 4
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 self._set_continuation_prompt('... ')
epatters
* Adding object_info_request support to prototype kernel....
r2612 self.document().contentsChange.connect(self._document_contents_change)
epatters
Minor comment cleanup.
r2669 #---------------------------------------------------------------------------
# 'QWidget' interface
#---------------------------------------------------------------------------
epatters
Initial checkin of Qt frontend code.
r2602 def focusOutEvent(self, event):
""" Reimplemented to hide calltips.
"""
self._call_tip_widget.hide()
epatters
* Added ability to interrupt a kernel to FrontendWidget...
r2687 super(FrontendWidget, self).focusOutEvent(event)
epatters
Initial checkin of Qt frontend code.
r2602
def keyPressEvent(self, event):
epatters
* Added ability to interrupt a kernel to FrontendWidget...
r2687 """ Reimplemented to allow calltips to process events and to send
signals to the kernel.
epatters
Initial checkin of Qt frontend code.
r2602 """
epatters
* Added ability to interrupt a kernel to FrontendWidget...
r2687 if self._executing and event.key() == QtCore.Qt.Key_C and \
self._control_down(event.modifiers()):
self._interrupt_kernel()
else:
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 if self._call_tip_widget.isVisible():
self._call_tip_widget.keyPressEvent(event)
epatters
* Added ability to interrupt a kernel to FrontendWidget...
r2687 super(FrontendWidget, self).keyPressEvent(event)
epatters
Initial checkin of Qt frontend code.
r2602
#---------------------------------------------------------------------------
# 'ConsoleWidget' abstract interface
#---------------------------------------------------------------------------
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
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.
epatters
Initial checkin of Qt frontend code.
r2602 """
epatters
* ConsoleWidget now has better support for non-GUI tab completion. Multiple matches are formatted into columns....
r2723 complete = self._input_splitter.push(source.expandtabs(4))
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 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
epatters
Initial checkin of Qt frontend code.
r2602
def _prompt_started_hook(self):
""" Called immediately after a new prompt is displayed.
"""
epatters
Fixed bug where syntax highlighting was enabled during raw_input mode.
r2709 if not self._reading:
self._highlighter.highlighting_on = True
epatters
Initial checkin of Qt frontend code.
r2602
epatters
Fixed bug where syntax highlighting was enabled during raw_input mode.
r2709 # Auto-indent if this is a continuation prompt.
if self._get_prompt_cursor().blockNumber() != \
self._get_end_cursor().blockNumber():
epatters
* Moved AnsiCodeProcessor to separate file, refactored its API, and added unit tests....
r2716 spaces = self._input_splitter.indent_spaces
epatters
Minor cleanup related to tab widths.
r2721 self.appendPlainText('\t' * (spaces / self.tab_width))
self.appendPlainText(' ' * (spaces % self.tab_width))
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688
epatters
Initial checkin of Qt frontend code.
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.
"""
epatters
Fixed bug where syntax highlighting was enabled during raw_input mode.
r2709 if not self._reading:
self._highlighter.highlighting_on = False
epatters
Initial checkin of Qt frontend code.
r2602
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()
epatters
* Moved AnsiCodeProcessor to separate file, refactored its API, and added unit tests....
r2716 return not self._complete()
epatters
Initial checkin of Qt frontend code.
r2602
#---------------------------------------------------------------------------
# 'FrontendWidget' interface
#---------------------------------------------------------------------------
def execute_file(self, path, hidden=False):
""" Attempts to execute file with 'path'. If 'hidden', no output is
shown.
"""
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 self.execute('execfile("%s")' % path, hidden=hidden)
epatters
Initial checkin of Qt frontend code.
r2602
epatters
Initial checkin of Qt kernel manager. Began refactor of FrontendWidget.
r2609 def _get_kernel_manager(self):
""" Returns the current kernel manager.
"""
return self._kernel_manager
def _set_kernel_manager(self, kernel_manager):
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643 """ Disconnect from the current kernel manager (if any) and set a new
kernel manager.
epatters
Initial checkin of Qt kernel manager. Began refactor of FrontendWidget.
r2609 """
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643 # Disconnect the old kernel manager, if necessary.
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 if self._kernel_manager is not None:
epatters
Merge branch 'kernelmanager' of git://github.com/ellisonbg/ipython into qtfrontend. Fixed breakage and conflicts from merge....
r2701 self._kernel_manager.started_channels.disconnect(
self._started_channels)
self._kernel_manager.stopped_channels.disconnect(
self._stopped_channels)
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643
# Disconnect the old kernel manager's channels.
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 sub = self._kernel_manager.sub_channel
xreq = self._kernel_manager.xreq_channel
epatters
Basic raw_input implementation is now working.
r2707 rep = self._kernel_manager.rep_channel
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 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)
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 rep.input_requested.disconnect(self._handle_req)
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
epatters
* Added 'req_port' option to 'launch_kernel' and the kernel entry point....
r2702 # Handle the case where the old kernel manager is still listening.
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 if self._kernel_manager.channels_running:
epatters
Merge branch 'kernelmanager' of git://github.com/ellisonbg/ipython into qtfrontend. Fixed breakage and conflicts from merge....
r2701 self._stopped_channels()
epatters
* Added ability to interrupt a kernel to FrontendWidget...
r2687
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643 # Set the new kernel manager.
epatters
Initial checkin of Qt kernel manager. Began refactor of FrontendWidget.
r2609 self._kernel_manager = kernel_manager
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643 if kernel_manager is None:
return
# Connect the new kernel manager.
epatters
Merge branch 'kernelmanager' of git://github.com/ellisonbg/ipython into qtfrontend. Fixed breakage and conflicts from merge....
r2701 kernel_manager.started_channels.connect(self._started_channels)
kernel_manager.stopped_channels.connect(self._stopped_channels)
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643
# Connect the new kernel manager's channels.
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 sub = kernel_manager.sub_channel
xreq = kernel_manager.xreq_channel
epatters
Basic raw_input implementation is now working.
r2707 rep = kernel_manager.rep_channel
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 sub.message_received.connect(self._handle_sub)
xreq.execute_reply.connect(self._handle_execute_reply)
epatters
* Adding object_info_request support to prototype kernel....
r2612 xreq.complete_reply.connect(self._handle_complete_reply)
xreq.object_info_reply.connect(self._handle_object_info_reply)
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 rep.input_requested.connect(self._handle_req)
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611
epatters
Merge branch 'kernelmanager' of git://github.com/ellisonbg/ipython into qtfrontend. Fixed breakage and conflicts from merge....
r2701 # Handle the case where the kernel manager started channels before
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643 # we connected.
Brian Granger
Kernel manager is cleaned up and simplified. Still bugs though.
r2699 if kernel_manager.channels_running:
epatters
Merge branch 'kernelmanager' of git://github.com/ellisonbg/ipython into qtfrontend. Fixed breakage and conflicts from merge....
r2701 self._started_channels()
epatters
Initial checkin of Qt kernel manager. Began refactor of FrontendWidget.
r2609
kernel_manager = property(_get_kernel_manager, _set_kernel_manager)
epatters
Initial checkin of Qt frontend code.
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
epatters
* Adding object_info_request support to prototype kernel....
r2612 name = '.'.join(context)
self._calltip_id = self.kernel_manager.xreq_channel.object_info(name)
self._calltip_pos = self.textCursor().position()
epatters
Initial checkin of Qt frontend code.
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)
epatters
* Adding object_info_request support to prototype kernel....
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()
epatters
Initial checkin of Qt frontend code.
r2602 return True
epatters
Added banners to FrontendWidget and IPythonWidget.
r2714 def _get_banner(self):
""" Gets a banner to display at the beginning of a session.
"""
banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \
'"license" for more information.'
return banner % (sys.version, sys.platform)
epatters
Initial checkin of Qt frontend code.
r2602 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)
epatters
Made use of plain text consistent.
r2720 text = str(cursor.selection().toPlainText())
epatters
Initial checkin of Qt frontend code.
r2602 return self._completion_lexer.get_context(text)
epatters
* Added ability to interrupt a kernel to FrontendWidget...
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')
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 def _show_interpreter_prompt(self):
""" Shows a prompt for the interpreter.
"""
self._show_prompt('>>> ')
epatters
Initial checkin of Qt frontend code.
r2602 #------ Signal handlers ----------------------------------------------------
epatters
Progress on raw_input.
r2705 def _started_channels(self):
""" Called when the kernel manager has started listening.
"""
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 self._reset()
epatters
Added banners to FrontendWidget and IPythonWidget.
r2714 self.appendPlainText(self._get_banner())
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 self._show_interpreter_prompt()
epatters
Progress on raw_input.
r2705
def _stopped_channels(self):
""" Called when the kernel manager has stopped listening.
"""
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 # FIXME: Print a message here?
epatters
Progress on raw_input.
r2705 pass
epatters
Initial checkin of Qt frontend code.
r2602 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()
epatters
Basic raw_input implementation is now working.
r2707 def _handle_req(self, req):
epatters
Fixed bugs with raw_input and finished and implementing InStream.
r2708 # Make sure that all output from the SUB channel has been processed
# before entering readline mode.
self.kernel_manager.sub_channel.flush()
epatters
Reading a line is now correctly implemented in ConsoleWidget.
r2706 def callback(line):
epatters
* Change input mechanism: replace raw_input instead of stdin....
r2730 self.kernel_manager.rep_channel.input(line)
self._readline(req['content']['prompt'], callback=callback)
epatters
Progress on raw_input.
r2705
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 def _handle_sub(self, omsg):
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 if self._hidden:
return
handler = getattr(self, '_handle_%s' % omsg['msg_type'], None)
if handler is not None:
handler(omsg)
epatters
Initial checkin of Qt frontend code.
r2602
def _handle_pyout(self, omsg):
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 self.appendPlainText(omsg['content']['data'] + '\n')
epatters
Initial checkin of Qt frontend code.
r2602
def _handle_stream(self, omsg):
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 self.appendPlainText(omsg['content']['data'])
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 self.moveCursor(QtGui.QTextCursor.End)
epatters
Initial checkin of Qt frontend code.
r2602
epatters
* Moved AnsiCodeProcessor to separate file, refactored its API, and added unit tests....
r2716 def _handle_execute_reply(self, reply):
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 if self._hidden:
return
epatters
Added a flush method to the SubSocketChannel. The Qt console frontend now uses this method to ensure that output has been processed before it writes a new prompt.
r2614 # Make sure that all output from the SUB channel has been processed
# before writing a new prompt.
self.kernel_manager.sub_channel.flush()
epatters
* Moved AnsiCodeProcessor to separate file, refactored its API, and added unit tests....
r2716 status = reply['content']['status']
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 if status == 'error':
epatters
* Moved AnsiCodeProcessor to separate file, refactored its API, and added unit tests....
r2716 self._handle_execute_error(reply)
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 elif status == 'aborted':
text = "ERROR: ABORTED\n"
self.appendPlainText(text)
epatters
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627 self._hidden = True
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 self._show_interpreter_prompt()
epatters
* Moved AnsiCodeProcessor to separate file, refactored its API, and added unit tests....
r2716 self.executed.emit(reply)
def _handle_execute_error(self, reply):
content = reply['content']
traceback = ''.join(content['traceback'])
self.appendPlainText(traceback)
epatters
Initial checkin of Qt frontend code.
r2602
epatters
* Adding object_info_request support to prototype kernel....
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'])
epatters
Initial checkin of Qt frontend code.
r2602
epatters
* Adding object_info_request support to prototype kernel....
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:
epatters
Improved docstring formatting in call tips.
r2666 self._call_tip_widget.show_docstring(doc)