From 2a14265cc0e3e98d8d8c45aee19503700ddf9c63 2010-08-25 21:11:08 From: Brian Granger Date: 2010-08-25 21:11:08 Subject: [PATCH] Initial GUI support in kernel. --- diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index debf617..df785f5 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -194,8 +194,8 @@ class InteractiveShell(Configurable, Magic): # TODO: this part of prompt management should be moved to the frontends. # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' separate_in = SeparateStr('\n', config=True) - separate_out = SeparateStr('\n', config=True) - separate_out2 = SeparateStr('\n', config=True) + separate_out = SeparateStr('', config=True) + separate_out2 = SeparateStr('', config=True) system_header = Str('IPython system call: ', config=True) system_verbose = CBool(False, config=True) wildcards_case_sensitive = CBool(True, config=True) diff --git a/IPython/lib/pylabtools.py b/IPython/lib/pylabtools.py index 7149746..ad8ed7d 100644 --- a/IPython/lib/pylabtools.py +++ b/IPython/lib/pylabtools.py @@ -23,29 +23,21 @@ from IPython.utils.decorators import flag_calls # Main classes and functions #----------------------------------------------------------------------------- -def pylab_activate(user_ns, gui=None, import_all=True): - """Activate pylab mode in the user's namespace. - Loads and initializes numpy, matplotlib and friends for interactive use. +def find_gui_and_backend(gui=None): + """Given a gui string return the gui and mpl backend. Parameters ---------- - user_ns : dict - Namespace where the imports will occur. - - gui : optional, string - A valid gui name following the conventions of the %gui magic. - - import_all : optional, boolean - If true, an 'import *' is done from numpy and pylab. + gui : str + Can be one of ('tk','gtk','wx','qt','qt4','payload-svg'). Returns ------- - The actual gui used (if not given as input, it was obtained from matplotlib - itself, and will be needed next to configure IPython's gui integration. + A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', + 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_payload_svg'). """ - # Initialize matplotlib to interactive mode always import matplotlib # If user specifies a GUI, that dictates the backend, otherwise we read the @@ -54,7 +46,9 @@ def pylab_activate(user_ns, gui=None, import_all=True): 'gtk': 'GTKAgg', 'wx': 'WXAgg', 'qt': 'Qt4Agg', # qt3 not supported - 'qt4': 'Qt4Agg' } + 'qt4': 'Qt4Agg', + 'payload-svg' : \ + 'module://IPython.zmq.pylab.backend_payload_svg'} if gui: # select backend based on requested gui @@ -65,23 +59,25 @@ def pylab_activate(user_ns, gui=None, import_all=True): # should be for IPython, so we can activate inputhook accordingly b2g = dict(zip(g2b.values(),g2b.keys())) gui = b2g.get(backend, None) + return gui, backend - # We must set the desired backend before importing pylab - matplotlib.use(backend) - - # This must be imported last in the matplotlib series, after - # backend/interactivity choices have been made + +def activate_matplotlib(backend): + """Activate the given backend and set interactive to True.""" + + import matplotlib + if backend.startswith('module://'): + # Work around bug in matplotlib: matplotlib.use converts the + # backend_id to lowercase even if a module name is specified! + matplotlib.rcParams['backend'] = backend + else: + matplotlib.use(backend) + matplotlib.interactive(True) import matplotlib.pylab as pylab - # XXX For now leave this commented out, but depending on discussions with - # mpl-dev, we may be able to allow interactive switching... - #import matplotlib.pyplot - #matplotlib.pyplot.switch_backend(backend) - pylab.show._needmain = False - # We need to detect at runtime whether show() is called by the user. - # For this, we wrap it into a decorator which adds a 'called' flag. - pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) +def import_pylab(user_ns, import_all=True): + """Import the standard pylab symbols into user_ns.""" # Import numpy as np/pyplot as plt are conventions we're trying to # somewhat standardize on. Making them available to users by default @@ -97,7 +93,47 @@ def pylab_activate(user_ns, gui=None, import_all=True): exec("from matplotlib.pylab import *\n" "from numpy import *\n") in user_ns - matplotlib.interactive(True) + +def pylab_activate(user_ns, gui=None, import_all=True): + """Activate pylab mode in the user's namespace. + + Loads and initializes numpy, matplotlib and friends for interactive use. + + Parameters + ---------- + user_ns : dict + Namespace where the imports will occur. + + gui : optional, string + A valid gui name following the conventions of the %gui magic. + + import_all : optional, boolean + If true, an 'import *' is done from numpy and pylab. + + Returns + ------- + The actual gui used (if not given as input, it was obtained from matplotlib + itself, and will be needed next to configure IPython's gui integration. + """ + + gui, backend = find_gui_and_backend(gui) + activate_matplotlib(backend) + + # This must be imported last in the matplotlib series, after + # backend/interactivity choices have been made + import matplotlib.pylab as pylab + + # XXX For now leave this commented out, but depending on discussions with + # mpl-dev, we may be able to allow interactive switching... + #import matplotlib.pyplot + #matplotlib.pyplot.switch_backend(backend) + + pylab.show._needmain = False + # We need to detect at runtime whether show() is called by the user. + # For this, we wrap it into a decorator which adds a 'called' flag. + pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) + + import_pylab(user_ns) print """ Welcome to pylab, a matplotlib-based Python environment [backend: %s]. diff --git a/IPython/zmq/entry_point.py b/IPython/zmq/entry_point.py index 3585696..b07b849 100644 --- a/IPython/zmq/entry_point.py +++ b/IPython/zmq/entry_point.py @@ -79,6 +79,7 @@ def make_kernel(namespace, kernel_factory, # Redirect input streams and set a display hook. if out_stream_factory: + pass sys.stdout = out_stream_factory(session, pub_socket, u'stdout') sys.stderr = out_stream_factory(session, pub_socket, u'stderr') if display_hook_factory: diff --git a/IPython/zmq/ipkernel.py b/IPython/zmq/ipkernel.py index 250c66a..6be1be3 100755 --- a/IPython/zmq/ipkernel.py +++ b/IPython/zmq/ipkernel.py @@ -25,8 +25,8 @@ import zmq # Local imports. from IPython.config.configurable import Configurable +from IPython.lib import pylabtools from IPython.utils.traitlets import Instance -from completer import KernelCompleter from entry_point import base_launch_kernel, make_argument_parser, make_kernel, \ start_kernel from iostream import OutStream @@ -49,15 +49,6 @@ class Kernel(Configurable): pub_socket = Instance('zmq.Socket') req_socket = Instance('zmq.Socket') - # Maps user-friendly backend names to matplotlib backend identifiers. - _pylab_map = { 'tk': 'TkAgg', - 'gtk': 'GTKAgg', - 'wx': 'WXAgg', - 'qt': 'Qt4Agg', # qt3 not supported - 'qt4': 'Qt4Agg', - 'payload-svg' : \ - 'module://IPython.zmq.pylab.backend_payload_svg' } - def __init__(self, **kwargs): super(Kernel, self).__init__(**kwargs) @@ -77,62 +68,32 @@ class Kernel(Configurable): for msg_type in msg_types: self.handlers[msg_type] = getattr(self, msg_type) - def activate_pylab(self, backend=None, import_all=True): - """ Activates pylab in this kernel's namespace. - - Parameters: - ----------- - backend : str, optional - A valid backend name. - - import_all : bool, optional - If true, an 'import *' is done from numpy and pylab. - """ - # FIXME: This is adapted from IPython.lib.pylabtools.pylab_activate. - # Common functionality should be refactored. - - # We must set the desired backend before importing pylab. - import matplotlib - if backend: - backend_id = self._pylab_map[backend] - if backend_id.startswith('module://'): - # Work around bug in matplotlib: matplotlib.use converts the - # backend_id to lowercase even if a module name is specified! - matplotlib.rcParams['backend'] = backend_id + def do_one_iteration(self): + try: + ident = self.reply_socket.recv(zmq.NOBLOCK) + except zmq.ZMQError, e: + if e.errno == zmq.EAGAIN: + return else: - matplotlib.use(backend_id) - - # Import numpy as np/pyplot as plt are conventions we're trying to - # somewhat standardize on. Making them available to users by default - # will greatly help this. - exec ("import numpy\n" - "import matplotlib\n" - "from matplotlib import pylab, mlab, pyplot\n" - "np = numpy\n" - "plt = pyplot\n" - ) in self.shell.user_ns - - if import_all: - exec("from matplotlib.pylab import *\n" - "from numpy import *\n") in self.shell.user_ns - - matplotlib.interactive(True) + raise + # FIXME: Bug in pyzmq/zmq? + # assert self.reply_socket.rcvmore(), "Missing message part." + msg = self.reply_socket.recv_json() + omsg = Message(msg) + print>>sys.__stdout__ + print>>sys.__stdout__, omsg + handler = self.handlers.get(omsg.msg_type, None) + if handler is None: + print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg + else: + handler(ident, omsg) def start(self): """ Start the kernel main loop. """ while True: - ident = self.reply_socket.recv() - assert self.reply_socket.rcvmore(), "Missing message part." - msg = self.reply_socket.recv_json() - omsg = Message(msg) - print>>sys.__stdout__ - print>>sys.__stdout__, omsg - handler = self.handlers.get(omsg.msg_type, None) - if handler is None: - print >> sys.__stderr__, "UNKNOWN MESSAGE TYPE:", omsg - else: - handler(ident, omsg) + time.sleep(0.05) + self.do_one_iteration() #--------------------------------------------------------------------------- # Kernel request handlers @@ -330,6 +291,19 @@ class Kernel(Configurable): return symbol, [] + +class QtKernel(Kernel): + + def start(self): + """Start a kernel with QtPy4 event loop integration.""" + from PyQt4 import QtGui, QtCore + self.qapp = app = QtGui.QApplication([]) + self.qtimer = QtCore.QTimer() + self.qtimer.timeout.connect(self.do_one_iteration) + self.qtimer.start(50) + self.qapp.exec_() + + #----------------------------------------------------------------------------- # Kernel main and launch functions #----------------------------------------------------------------------------- @@ -386,13 +360,31 @@ given, the GUI backend is matplotlib's, otherwise use one of: \ ['tk', 'gtk', 'qt', 'wx', 'payload-svg'].") namespace = parser.parse_args() - kernel = make_kernel(namespace, Kernel, OutStream) + kernel_class = Kernel + + _kernel_classes = { + 'qt' : QtKernel, + 'qt4' : QtKernel, + 'payload-svg':Kernel + } if namespace.pylab: if namespace.pylab == 'auto': - kernel.activate_pylab() + gui, backend = pylabtools.find_gui_and_backend() else: - kernel.activate_pylab(namespace.pylab) - + gui, backend = pylabtools.find_gui_and_backend(namespace.pylab) + print gui, backend + kernel_class = _kernel_classes.get(gui) + if kernel_class is None: + raise ValueError('GUI is not supported: %r' % gui) + pylabtools.activate_matplotlib(backend) + + print>>sys.__stdout__, kernel_class + kernel = make_kernel(namespace, kernel_class, OutStream) + print >>sys.__stdout__, kernel + + if namespace.pylab: + pylabtools.import_pylab(kernel.shell.user_ns) + start_kernel(namespace, kernel) if __name__ == '__main__': diff --git a/IPython/zmq/zmqshell.py b/IPython/zmq/zmqshell.py index 0e2c1a8..b87767e 100644 --- a/IPython/zmq/zmqshell.py +++ b/IPython/zmq/zmqshell.py @@ -15,7 +15,7 @@ from IPython.utils.traitlets import Instance, Type, Dict from IPython.utils.warn import warn from IPython.zmq.session import extract_header from IPython.core.payloadpage import install_payload_page - +from session import Session # Install the payload version of page. install_payload_page() @@ -23,7 +23,7 @@ install_payload_page() class ZMQDisplayHook(DisplayHook): - session = Instance('IPython.zmq.session.Session') + session = Instance(Session) pub_socket = Instance('zmq.Socket') parent_header = Dict({})