##// END OF EJS Templates
Refactor inputhook to allow easy extension.
Thomas Kluyver -
Show More
@@ -1,542 +1,560 b''
1 # coding: utf-8
1 # coding: utf-8
2 """
2 """
3 Inputhook management for GUI event loop integration.
3 Inputhook management for GUI event loop integration.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 try:
17 try:
18 import ctypes
18 import ctypes
19 except ImportError:
19 except ImportError:
20 ctypes = None
20 ctypes = None
21 except SystemError: # IronPython issue, 2/8/2014
21 except SystemError: # IronPython issue, 2/8/2014
22 ctypes = None
22 ctypes = None
23 import os
23 import os
24 import sys
24 import sys
25 from distutils.version import LooseVersion as V
25 from distutils.version import LooseVersion as V
26
26
27 from IPython.utils.warn import warn
27 from IPython.utils.warn import warn
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Constants
30 # Constants
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 # Constants for identifying the GUI toolkits.
33 # Constants for identifying the GUI toolkits.
34 GUI_WX = 'wx'
34 GUI_WX = 'wx'
35 GUI_QT = 'qt'
35 GUI_QT = 'qt'
36 GUI_QT4 = 'qt4'
36 GUI_QT4 = 'qt4'
37 GUI_GTK = 'gtk'
37 GUI_GTK = 'gtk'
38 GUI_TK = 'tk'
38 GUI_TK = 'tk'
39 GUI_OSX = 'osx'
39 GUI_OSX = 'osx'
40 GUI_GLUT = 'glut'
40 GUI_GLUT = 'glut'
41 GUI_PYGLET = 'pyglet'
41 GUI_PYGLET = 'pyglet'
42 GUI_GTK3 = 'gtk3'
42 GUI_GTK3 = 'gtk3'
43 GUI_NONE = 'none' # i.e. disable
43 GUI_NONE = 'none' # i.e. disable
44
44
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46 # Utilities
46 # Utilities
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48
48
49 def _stdin_ready_posix():
49 def _stdin_ready_posix():
50 """Return True if there's something to read on stdin (posix version)."""
50 """Return True if there's something to read on stdin (posix version)."""
51 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
51 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
52 return bool(infds)
52 return bool(infds)
53
53
54 def _stdin_ready_nt():
54 def _stdin_ready_nt():
55 """Return True if there's something to read on stdin (nt version)."""
55 """Return True if there's something to read on stdin (nt version)."""
56 return msvcrt.kbhit()
56 return msvcrt.kbhit()
57
57
58 def _stdin_ready_other():
58 def _stdin_ready_other():
59 """Return True, assuming there's something to read on stdin."""
59 """Return True, assuming there's something to read on stdin."""
60 return True #
60 return True #
61
61
62
62
63 def _ignore_CTRL_C_posix():
63 def _ignore_CTRL_C_posix():
64 """Ignore CTRL+C (SIGINT)."""
64 """Ignore CTRL+C (SIGINT)."""
65 signal.signal(signal.SIGINT, signal.SIG_IGN)
65 signal.signal(signal.SIGINT, signal.SIG_IGN)
66
66
67 def _allow_CTRL_C_posix():
67 def _allow_CTRL_C_posix():
68 """Take CTRL+C into account (SIGINT)."""
68 """Take CTRL+C into account (SIGINT)."""
69 signal.signal(signal.SIGINT, signal.default_int_handler)
69 signal.signal(signal.SIGINT, signal.default_int_handler)
70
70
71 def _ignore_CTRL_C_other():
71 def _ignore_CTRL_C_other():
72 """Ignore CTRL+C (not implemented)."""
72 """Ignore CTRL+C (not implemented)."""
73 pass
73 pass
74
74
75 def _allow_CTRL_C_other():
75 def _allow_CTRL_C_other():
76 """Take CTRL+C into account (not implemented)."""
76 """Take CTRL+C into account (not implemented)."""
77 pass
77 pass
78
78
79 if os.name == 'posix':
79 if os.name == 'posix':
80 import select
80 import select
81 import signal
81 import signal
82 stdin_ready = _stdin_ready_posix
82 stdin_ready = _stdin_ready_posix
83 ignore_CTRL_C = _ignore_CTRL_C_posix
83 ignore_CTRL_C = _ignore_CTRL_C_posix
84 allow_CTRL_C = _allow_CTRL_C_posix
84 allow_CTRL_C = _allow_CTRL_C_posix
85 elif os.name == 'nt':
85 elif os.name == 'nt':
86 import msvcrt
86 import msvcrt
87 stdin_ready = _stdin_ready_nt
87 stdin_ready = _stdin_ready_nt
88 ignore_CTRL_C = _ignore_CTRL_C_other
88 ignore_CTRL_C = _ignore_CTRL_C_other
89 allow_CTRL_C = _allow_CTRL_C_other
89 allow_CTRL_C = _allow_CTRL_C_other
90 else:
90 else:
91 stdin_ready = _stdin_ready_other
91 stdin_ready = _stdin_ready_other
92 ignore_CTRL_C = _ignore_CTRL_C_other
92 ignore_CTRL_C = _ignore_CTRL_C_other
93 allow_CTRL_C = _allow_CTRL_C_other
93 allow_CTRL_C = _allow_CTRL_C_other
94
94
95
95
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97 # Main InputHookManager class
97 # Main InputHookManager class
98 #-----------------------------------------------------------------------------
98 #-----------------------------------------------------------------------------
99
99
100
100
101 class InputHookManager(object):
101 class InputHookManager(object):
102 """Manage PyOS_InputHook for different GUI toolkits.
102 """Manage PyOS_InputHook for different GUI toolkits.
103
103
104 This class installs various hooks under ``PyOSInputHook`` to handle
104 This class installs various hooks under ``PyOSInputHook`` to handle
105 GUI event loop integration.
105 GUI event loop integration.
106 """
106 """
107
107
108 def __init__(self):
108 def __init__(self):
109 if ctypes is None:
109 if ctypes is None:
110 warn("IPython GUI event loop requires ctypes, %gui will not be available")
110 warn("IPython GUI event loop requires ctypes, %gui will not be available")
111 return
111 return
112 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
112 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
113 self._apps = {}
113 self.guihooks = {}
114 self.aliases = {}
115 self.apps = {}
114 self._reset()
116 self._reset()
115
117
116 def _reset(self):
118 def _reset(self):
117 self._callback_pyfunctype = None
119 self._callback_pyfunctype = None
118 self._callback = None
120 self._callback = None
119 self._installed = False
121 self._installed = False
120 self._current_gui = None
122 self._current_gui = None
121
123
122 def get_pyos_inputhook(self):
124 def get_pyos_inputhook(self):
123 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
125 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
124 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
126 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
125
127
126 def get_pyos_inputhook_as_func(self):
128 def get_pyos_inputhook_as_func(self):
127 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
129 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
128 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
130 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
129
131
130 def set_inputhook(self, callback):
132 def set_inputhook(self, callback):
131 """Set PyOS_InputHook to callback and return the previous one."""
133 """Set PyOS_InputHook to callback and return the previous one."""
132 # On platforms with 'readline' support, it's all too likely to
134 # On platforms with 'readline' support, it's all too likely to
133 # have a KeyboardInterrupt signal delivered *even before* an
135 # have a KeyboardInterrupt signal delivered *even before* an
134 # initial ``try:`` clause in the callback can be executed, so
136 # initial ``try:`` clause in the callback can be executed, so
135 # we need to disable CTRL+C in this situation.
137 # we need to disable CTRL+C in this situation.
136 ignore_CTRL_C()
138 ignore_CTRL_C()
137 self._callback = callback
139 self._callback = callback
138 self._callback_pyfunctype = self.PYFUNC(callback)
140 self._callback_pyfunctype = self.PYFUNC(callback)
139 pyos_inputhook_ptr = self.get_pyos_inputhook()
141 pyos_inputhook_ptr = self.get_pyos_inputhook()
140 original = self.get_pyos_inputhook_as_func()
142 original = self.get_pyos_inputhook_as_func()
141 pyos_inputhook_ptr.value = \
143 pyos_inputhook_ptr.value = \
142 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
144 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
143 self._installed = True
145 self._installed = True
144 return original
146 return original
145
147
146 def clear_inputhook(self, app=None):
148 def clear_inputhook(self, app=None):
147 """Set PyOS_InputHook to NULL and return the previous one.
149 """Set PyOS_InputHook to NULL and return the previous one.
148
150
149 Parameters
151 Parameters
150 ----------
152 ----------
151 app : optional, ignored
153 app : optional, ignored
152 This parameter is allowed only so that clear_inputhook() can be
154 This parameter is allowed only so that clear_inputhook() can be
153 called with a similar interface as all the ``enable_*`` methods. But
155 called with a similar interface as all the ``enable_*`` methods. But
154 the actual value of the parameter is ignored. This uniform interface
156 the actual value of the parameter is ignored. This uniform interface
155 makes it easier to have user-level entry points in the main IPython
157 makes it easier to have user-level entry points in the main IPython
156 app like :meth:`enable_gui`."""
158 app like :meth:`enable_gui`."""
157 pyos_inputhook_ptr = self.get_pyos_inputhook()
159 pyos_inputhook_ptr = self.get_pyos_inputhook()
158 original = self.get_pyos_inputhook_as_func()
160 original = self.get_pyos_inputhook_as_func()
159 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
161 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
160 allow_CTRL_C()
162 allow_CTRL_C()
161 self._reset()
163 self._reset()
162 return original
164 return original
163
165
164 def clear_app_refs(self, gui=None):
166 def clear_app_refs(self, gui=None):
165 """Clear IPython's internal reference to an application instance.
167 """Clear IPython's internal reference to an application instance.
166
168
167 Whenever we create an app for a user on qt4 or wx, we hold a
169 Whenever we create an app for a user on qt4 or wx, we hold a
168 reference to the app. This is needed because in some cases bad things
170 reference to the app. This is needed because in some cases bad things
169 can happen if a user doesn't hold a reference themselves. This
171 can happen if a user doesn't hold a reference themselves. This
170 method is provided to clear the references we are holding.
172 method is provided to clear the references we are holding.
171
173
172 Parameters
174 Parameters
173 ----------
175 ----------
174 gui : None or str
176 gui : None or str
175 If None, clear all app references. If ('wx', 'qt4') clear
177 If None, clear all app references. If ('wx', 'qt4') clear
176 the app for that toolkit. References are not held for gtk or tk
178 the app for that toolkit. References are not held for gtk or tk
177 as those toolkits don't have the notion of an app.
179 as those toolkits don't have the notion of an app.
178 """
180 """
179 if gui is None:
181 if gui is None:
180 self._apps = {}
182 self.apps = {}
181 elif gui in self._apps:
183 elif gui in self.apps:
182 del self._apps[gui]
184 del self.apps[gui]
183
185
184 def enable_wx(self, app=None):
186 def register(self, toolkitname, *aliases):
187 """Register a class to provide the event loop for a given GUI.
188
189 This is intended to be used as a class decorator. It should be passed
190 the names with which to register this GUI integration. The classes
191 themselves should subclass :class:`InputHookBase`.
192
193 Examples
194 --------
195
196 @inputhook_manager.register('qt')
197 class QtInputHook(InputHookBase):
198 def enable(self, app=None):
199 ...
200 """
201 def decorator(cls):
202 inst = cls(self)
203 self.guihooks[toolkitname] = inst
204 for a in aliases:
205 self.aliases[a] = toolkitname
206 return cls
207 return decorator
208
209 def current_gui(self):
210 """Return a string indicating the currently active GUI or None."""
211 return self._current_gui
212
213 def enable_gui(self, gui=None, app=None):
214 """Switch amongst GUI input hooks by name.
215
216 This is a higher level method than :meth:`set_inputhook` - it uses the
217 GUI name to look up a registered object which enables the input hook
218 for that GUI.
219
220 Parameters
221 ----------
222 gui : optional, string or None
223 If None (or 'none'), clears input hook, otherwise it must be one
224 of the recognized GUI names (see ``GUI_*`` constants in module).
225
226 app : optional, existing application object.
227 For toolkits that have the concept of a global app, you can supply an
228 existing one. If not given, the toolkit will be probed for one, and if
229 none is found, a new one will be created. Note that GTK does not have
230 this concept, and passing an app if ``gui=="GTK"`` will raise an error.
231
232 Returns
233 -------
234 The output of the underlying gui switch routine, typically the actual
235 PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
236 one.
237 """
238 if gui in (None, GUI_NONE):
239 return self.disable_gui()
240
241 if gui in self.aliases:
242 return self.enable_gui(self.aliases[gui], app)
243
244 try:
245 gui_hook = self.guihooks[gui]
246 except KeyError:
247 e = "Invalid GUI request {!r}, valid ones are: {}"
248 raise ValueError(e.format(gui, ', '.join(self.guihooks)))
249 self._current_gui = gui
250 return gui_hook.enable(app)
251
252 def disable_gui(self):
253 """Disable GUI event loop integration.
254
255 If an application was registered, this sets its ``_in_event_loop``
256 attribute to False. It then calls :meth:`clear_inputhook`.
257 """
258 gui = self._current_gui
259 if gui in self.apps:
260 self.apps[gui]._in_event_loop = False
261 return self.clear_inputhook()
262
263 class InputHookBase(object):
264 """Base class for input hooks for specific toolkits.
265
266 Subclasses should define an :meth:`enable` method with one argument, ``app``,
267 which will either be an instance of the toolkit's application class, or None.
268 They may also define a :meth:`disable` method with no arguments.
269 """
270 def __init__(self, manager):
271 self.manager = manager
272
273 def disable(self):
274 pass
275
276 inputhook_manager = InputHookManager()
277
278 @inputhook_manager.register('wx')
279 class WxInputHook(InputHookBase):
280 def enable(self, app=None):
185 """Enable event loop integration with wxPython.
281 """Enable event loop integration with wxPython.
186
282
187 Parameters
283 Parameters
188 ----------
284 ----------
189 app : WX Application, optional.
285 app : WX Application, optional.
190 Running application to use. If not given, we probe WX for an
286 Running application to use. If not given, we probe WX for an
191 existing application object, and create a new one if none is found.
287 existing application object, and create a new one if none is found.
192
288
193 Notes
289 Notes
194 -----
290 -----
195 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
291 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
196 the wxPython to integrate with terminal based applications like
292 the wxPython to integrate with terminal based applications like
197 IPython.
293 IPython.
198
294
199 If ``app`` is not given we probe for an existing one, and return it if
295 If ``app`` is not given we probe for an existing one, and return it if
200 found. If no existing app is found, we create an :class:`wx.App` as
296 found. If no existing app is found, we create an :class:`wx.App` as
201 follows::
297 follows::
202
298
203 import wx
299 import wx
204 app = wx.App(redirect=False, clearSigInt=False)
300 app = wx.App(redirect=False, clearSigInt=False)
205 """
301 """
206 import wx
302 import wx
207
303
208 wx_version = V(wx.__version__).version
304 wx_version = V(wx.__version__).version
209
305
210 if wx_version < [2, 8]:
306 if wx_version < [2, 8]:
211 raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
307 raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
212
308
213 from IPython.lib.inputhookwx import inputhook_wx
309 from IPython.lib.inputhookwx import inputhook_wx
214 from IPython.external.appnope import nope
310 from IPython.external.appnope import nope
215 self.set_inputhook(inputhook_wx)
311 self.manager.set_inputhook(inputhook_wx)
216 nope()
312 nope()
217 self._current_gui = GUI_WX
313
218 import wx
314 import wx
219 if app is None:
315 if app is None:
220 app = wx.GetApp()
316 app = wx.GetApp()
221 if app is None:
317 if app is None:
222 app = wx.App(redirect=False, clearSigInt=False)
318 app = wx.App(redirect=False, clearSigInt=False)
223 app._in_event_loop = True
319 app._in_event_loop = True
224 self._apps[GUI_WX] = app
320 self.manager.apps[GUI_WX] = app
225 return app
321 return app
226
322
227 def disable_wx(self):
323 def disable(self):
228 """Disable event loop integration with wxPython.
324 """Disable event loop integration with wxPython.
229
325
230 This merely sets PyOS_InputHook to NULL.
326 This restores appnapp on OS X
231 """
327 """
232 from IPython.external.appnope import nap
328 from IPython.external.appnope import nap
233 if GUI_WX in self._apps:
234 self._apps[GUI_WX]._in_event_loop = False
235 self.clear_inputhook()
236 nap()
329 nap()
237
330
238 def enable_qt4(self, app=None):
331 @inputhook_manager.register('qt', 'qt4')
332 class Qt4InputHook(InputHookBase):
333 def enable(self, app=None):
239 """Enable event loop integration with PyQt4.
334 """Enable event loop integration with PyQt4.
240
335
241 Parameters
336 Parameters
242 ----------
337 ----------
243 app : Qt Application, optional.
338 app : Qt Application, optional.
244 Running application to use. If not given, we probe Qt for an
339 Running application to use. If not given, we probe Qt for an
245 existing application object, and create a new one if none is found.
340 existing application object, and create a new one if none is found.
246
341
247 Notes
342 Notes
248 -----
343 -----
249 This methods sets the PyOS_InputHook for PyQt4, which allows
344 This methods sets the PyOS_InputHook for PyQt4, which allows
250 the PyQt4 to integrate with terminal based applications like
345 the PyQt4 to integrate with terminal based applications like
251 IPython.
346 IPython.
252
347
253 If ``app`` is not given we probe for an existing one, and return it if
348 If ``app`` is not given we probe for an existing one, and return it if
254 found. If no existing app is found, we create an :class:`QApplication`
349 found. If no existing app is found, we create an :class:`QApplication`
255 as follows::
350 as follows::
256
351
257 from PyQt4 import QtCore
352 from PyQt4 import QtCore
258 app = QtGui.QApplication(sys.argv)
353 app = QtGui.QApplication(sys.argv)
259 """
354 """
260 from IPython.lib.inputhookqt4 import create_inputhook_qt4
355 from IPython.lib.inputhookqt4 import create_inputhook_qt4
261 from IPython.external.appnope import nope
356 from IPython.external.appnope import nope
262 app, inputhook_qt4 = create_inputhook_qt4(self, app)
357 app, inputhook_qt4 = create_inputhook_qt4(self, app)
263 self.set_inputhook(inputhook_qt4)
358 self.manager.set_inputhook(inputhook_qt4)
264 nope()
359 nope()
265
360
266 self._current_gui = GUI_QT4
267 app._in_event_loop = True
361 app._in_event_loop = True
268 self._apps[GUI_QT4] = app
362 self.manager.apps[GUI_QT4] = app
269 return app
363 return app
270
364
271 def disable_qt4(self):
365 def disable_qt4(self):
272 """Disable event loop integration with PyQt4.
366 """Disable event loop integration with PyQt4.
273
367
274 This merely sets PyOS_InputHook to NULL.
368 This restores appnapp on OS X
275 """
369 """
276 from IPython.external.appnope import nap
370 from IPython.external.appnope import nap
277 if GUI_QT4 in self._apps:
278 self._apps[GUI_QT4]._in_event_loop = False
279 self.clear_inputhook()
280 nap()
371 nap()
281
372
282 def enable_gtk(self, app=None):
373 @inputhook_manager.register('gtk')
374 class GtkInputHook(InputHookBase):
375 def enable(self, app=None):
283 """Enable event loop integration with PyGTK.
376 """Enable event loop integration with PyGTK.
284
377
285 Parameters
378 Parameters
286 ----------
379 ----------
287 app : ignored
380 app : ignored
288 Ignored, it's only a placeholder to keep the call signature of all
381 Ignored, it's only a placeholder to keep the call signature of all
289 gui activation methods consistent, which simplifies the logic of
382 gui activation methods consistent, which simplifies the logic of
290 supporting magics.
383 supporting magics.
291
384
292 Notes
385 Notes
293 -----
386 -----
294 This methods sets the PyOS_InputHook for PyGTK, which allows
387 This methods sets the PyOS_InputHook for PyGTK, which allows
295 the PyGTK to integrate with terminal based applications like
388 the PyGTK to integrate with terminal based applications like
296 IPython.
389 IPython.
297 """
390 """
298 import gtk
391 import gtk
299 try:
392 try:
300 gtk.set_interactive(True)
393 gtk.set_interactive(True)
301 self._current_gui = GUI_GTK
302 except AttributeError:
394 except AttributeError:
303 # For older versions of gtk, use our own ctypes version
395 # For older versions of gtk, use our own ctypes version
304 from IPython.lib.inputhookgtk import inputhook_gtk
396 from IPython.lib.inputhookgtk import inputhook_gtk
305 self.set_inputhook(inputhook_gtk)
397 self.manager.set_inputhook(inputhook_gtk)
306 self._current_gui = GUI_GTK
307
398
308 def disable_gtk(self):
309 """Disable event loop integration with PyGTK.
310
311 This merely sets PyOS_InputHook to NULL.
312 """
313 self.clear_inputhook()
314
399
315 def enable_tk(self, app=None):
400 @inputhook_manager.register('tk')
401 class TkInputHook(InputHookBase):
402 def enable(self, app=None):
316 """Enable event loop integration with Tk.
403 """Enable event loop integration with Tk.
317
404
318 Parameters
405 Parameters
319 ----------
406 ----------
320 app : toplevel :class:`Tkinter.Tk` widget, optional.
407 app : toplevel :class:`Tkinter.Tk` widget, optional.
321 Running toplevel widget to use. If not given, we probe Tk for an
408 Running toplevel widget to use. If not given, we probe Tk for an
322 existing one, and create a new one if none is found.
409 existing one, and create a new one if none is found.
323
410
324 Notes
411 Notes
325 -----
412 -----
326 If you have already created a :class:`Tkinter.Tk` object, the only
413 If you have already created a :class:`Tkinter.Tk` object, the only
327 thing done by this method is to register with the
414 thing done by this method is to register with the
328 :class:`InputHookManager`, since creating that object automatically
415 :class:`InputHookManager`, since creating that object automatically
329 sets ``PyOS_InputHook``.
416 sets ``PyOS_InputHook``.
330 """
417 """
331 self._current_gui = GUI_TK
332 if app is None:
418 if app is None:
333 try:
419 try:
334 from tkinter import Tk # Py 3
420 from tkinter import Tk # Py 3
335 except ImportError:
421 except ImportError:
336 from Tkinter import Tk # Py 2
422 from Tkinter import Tk # Py 2
337 app = Tk()
423 app = Tk()
338 app.withdraw()
424 app.withdraw()
339 self._apps[GUI_TK] = app
425 self.manager.apps[GUI_TK] = app
340 return app
426 return app
341
427
342 def disable_tk(self):
343 """Disable event loop integration with Tkinter.
344
345 This merely sets PyOS_InputHook to NULL.
346 """
347 self.clear_inputhook()
348
349
428
350 def enable_glut(self, app=None):
429 @inputhook_manager.register('glut')
351 """ Enable event loop integration with GLUT.
430 class GlutInputHook(InputHookBase):
431 def enable(self, app=None):
432 """Enable event loop integration with GLUT.
352
433
353 Parameters
434 Parameters
354 ----------
435 ----------
355
436
356 app : ignored
437 app : ignored
357 Ignored, it's only a placeholder to keep the call signature of all
438 Ignored, it's only a placeholder to keep the call signature of all
358 gui activation methods consistent, which simplifies the logic of
439 gui activation methods consistent, which simplifies the logic of
359 supporting magics.
440 supporting magics.
360
441
361 Notes
442 Notes
362 -----
443 -----
363
444
364 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
445 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
365 integrate with terminal based applications like IPython. Due to GLUT
446 integrate with terminal based applications like IPython. Due to GLUT
366 limitations, it is currently not possible to start the event loop
447 limitations, it is currently not possible to start the event loop
367 without first creating a window. You should thus not create another
448 without first creating a window. You should thus not create another
368 window but use instead the created one. See 'gui-glut.py' in the
449 window but use instead the created one. See 'gui-glut.py' in the
369 docs/examples/lib directory.
450 docs/examples/lib directory.
370
451
371 The default screen mode is set to:
452 The default screen mode is set to:
372 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
453 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
373 """
454 """
374
455
375 import OpenGL.GLUT as glut
456 import OpenGL.GLUT as glut
376 from IPython.lib.inputhookglut import glut_display_mode, \
457 from IPython.lib.inputhookglut import glut_display_mode, \
377 glut_close, glut_display, \
458 glut_close, glut_display, \
378 glut_idle, inputhook_glut
459 glut_idle, inputhook_glut
379
460
380 if GUI_GLUT not in self._apps:
461 if GUI_GLUT not in self.manager.apps:
381 glut.glutInit( sys.argv )
462 glut.glutInit( sys.argv )
382 glut.glutInitDisplayMode( glut_display_mode )
463 glut.glutInitDisplayMode( glut_display_mode )
383 # This is specific to freeglut
464 # This is specific to freeglut
384 if bool(glut.glutSetOption):
465 if bool(glut.glutSetOption):
385 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
466 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
386 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
467 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
387 glut.glutCreateWindow( sys.argv[0] )
468 glut.glutCreateWindow( sys.argv[0] )
388 glut.glutReshapeWindow( 1, 1 )
469 glut.glutReshapeWindow( 1, 1 )
389 glut.glutHideWindow( )
470 glut.glutHideWindow( )
390 glut.glutWMCloseFunc( glut_close )
471 glut.glutWMCloseFunc( glut_close )
391 glut.glutDisplayFunc( glut_display )
472 glut.glutDisplayFunc( glut_display )
392 glut.glutIdleFunc( glut_idle )
473 glut.glutIdleFunc( glut_idle )
393 else:
474 else:
394 glut.glutWMCloseFunc( glut_close )
475 glut.glutWMCloseFunc( glut_close )
395 glut.glutDisplayFunc( glut_display )
476 glut.glutDisplayFunc( glut_display )
396 glut.glutIdleFunc( glut_idle)
477 glut.glutIdleFunc( glut_idle)
397 self.set_inputhook( inputhook_glut )
478 self.manager.set_inputhook( inputhook_glut )
398 self._current_gui = GUI_GLUT
479 self.manager.apps[GUI_GLUT] = True
399 self._apps[GUI_GLUT] = True
400
480
401
481
402 def disable_glut(self):
482 def disable(self):
403 """Disable event loop integration with glut.
483 """Disable event loop integration with glut.
404
484
405 This sets PyOS_InputHook to NULL and set the display function to a
485 This sets PyOS_InputHook to NULL and set the display function to a
406 dummy one and set the timer to a dummy timer that will be triggered
486 dummy one and set the timer to a dummy timer that will be triggered
407 very far in the future.
487 very far in the future.
408 """
488 """
409 import OpenGL.GLUT as glut
489 import OpenGL.GLUT as glut
410 from glut_support import glutMainLoopEvent
490 from glut_support import glutMainLoopEvent
411
491
412 glut.glutHideWindow() # This is an event to be processed below
492 glut.glutHideWindow() # This is an event to be processed below
413 glutMainLoopEvent()
493 glutMainLoopEvent()
414 self.clear_inputhook()
494 super(GlutInputHook, self).disable()
415
495
416 def enable_pyglet(self, app=None):
496 @inputhook_manager.register('pyglet')
497 class PygletInputHook(InputHookBase):
498 def enable(self, app=None):
417 """Enable event loop integration with pyglet.
499 """Enable event loop integration with pyglet.
418
500
419 Parameters
501 Parameters
420 ----------
502 ----------
421 app : ignored
503 app : ignored
422 Ignored, it's only a placeholder to keep the call signature of all
504 Ignored, it's only a placeholder to keep the call signature of all
423 gui activation methods consistent, which simplifies the logic of
505 gui activation methods consistent, which simplifies the logic of
424 supporting magics.
506 supporting magics.
425
507
426 Notes
508 Notes
427 -----
509 -----
428 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
510 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
429 pyglet to integrate with terminal based applications like
511 pyglet to integrate with terminal based applications like
430 IPython.
512 IPython.
431
513
432 """
514 """
433 from IPython.lib.inputhookpyglet import inputhook_pyglet
515 from IPython.lib.inputhookpyglet import inputhook_pyglet
434 self.set_inputhook(inputhook_pyglet)
516 self.manager.set_inputhook(inputhook_pyglet)
435 self._current_gui = GUI_PYGLET
436 return app
517 return app
437
518
438 def disable_pyglet(self):
439 """Disable event loop integration with pyglet.
440
441 This merely sets PyOS_InputHook to NULL.
442 """
443 self.clear_inputhook()
444
519
445 def enable_gtk3(self, app=None):
520 @inputhook_manager.register('gtk3')
521 class Gtk3InputHook(InputHookBase):
522 def enable(self, app=None):
446 """Enable event loop integration with Gtk3 (gir bindings).
523 """Enable event loop integration with Gtk3 (gir bindings).
447
524
448 Parameters
525 Parameters
449 ----------
526 ----------
450 app : ignored
527 app : ignored
451 Ignored, it's only a placeholder to keep the call signature of all
528 Ignored, it's only a placeholder to keep the call signature of all
452 gui activation methods consistent, which simplifies the logic of
529 gui activation methods consistent, which simplifies the logic of
453 supporting magics.
530 supporting magics.
454
531
455 Notes
532 Notes
456 -----
533 -----
457 This methods sets the PyOS_InputHook for Gtk3, which allows
534 This methods sets the PyOS_InputHook for Gtk3, which allows
458 the Gtk3 to integrate with terminal based applications like
535 the Gtk3 to integrate with terminal based applications like
459 IPython.
536 IPython.
460 """
537 """
461 from IPython.lib.inputhookgtk3 import inputhook_gtk3
538 from IPython.lib.inputhookgtk3 import inputhook_gtk3
462 self.set_inputhook(inputhook_gtk3)
539 self.manager.set_inputhook(inputhook_gtk3)
463 self._current_gui = GUI_GTK
540 self.manager._current_gui = GUI_GTK
464
541
465 def disable_gtk3(self):
466 """Disable event loop integration with PyGTK.
467
542
468 This merely sets PyOS_InputHook to NULL.
469 """
470 self.clear_inputhook()
471
472 def current_gui(self):
473 """Return a string indicating the currently active GUI or None."""
474 return self._current_gui
475
476 inputhook_manager = InputHookManager()
477
478 enable_wx = inputhook_manager.enable_wx
479 disable_wx = inputhook_manager.disable_wx
480 enable_qt4 = inputhook_manager.enable_qt4
481 disable_qt4 = inputhook_manager.disable_qt4
482 enable_gtk = inputhook_manager.enable_gtk
483 disable_gtk = inputhook_manager.disable_gtk
484 enable_tk = inputhook_manager.enable_tk
485 disable_tk = inputhook_manager.disable_tk
486 enable_glut = inputhook_manager.enable_glut
487 disable_glut = inputhook_manager.disable_glut
488 enable_pyglet = inputhook_manager.enable_pyglet
489 disable_pyglet = inputhook_manager.disable_pyglet
490 enable_gtk3 = inputhook_manager.enable_gtk3
491 disable_gtk3 = inputhook_manager.disable_gtk3
492 clear_inputhook = inputhook_manager.clear_inputhook
543 clear_inputhook = inputhook_manager.clear_inputhook
493 set_inputhook = inputhook_manager.set_inputhook
544 set_inputhook = inputhook_manager.set_inputhook
494 current_gui = inputhook_manager.current_gui
545 current_gui = inputhook_manager.current_gui
495 clear_app_refs = inputhook_manager.clear_app_refs
546 clear_app_refs = inputhook_manager.clear_app_refs
496
547 enable_gui = inputhook_manager.enable_gui
497 guis = {None: clear_inputhook,
548 disable_gui = inputhook_manager.disable_gui
498 GUI_NONE: clear_inputhook,
549 guis = inputhook_manager.guihooks
499 GUI_OSX: lambda app=False: None,
550
500 GUI_TK: enable_tk,
551 # Deprecated methods: kept for backwards compatibility, do not use in new code
501 GUI_GTK: enable_gtk,
552 enable_wx = lambda app=None: inputhook_manager.enable_gui('wx', app)
502 GUI_WX: enable_wx,
553 enable_qt4 = lambda app=None: inputhook_manager.enable_gui('qt4', app)
503 GUI_QT: enable_qt4, # qt3 not supported
554 enable_gtk = lambda app=None: inputhook_manager.enable_gui('gtk', app)
504 GUI_QT4: enable_qt4,
555 enable_tk = lambda app=None: inputhook_manager.enable_gui('tk', app)
505 GUI_GLUT: enable_glut,
556 enable_glut = lambda app=None: inputhook_manager.enable_gui('glut', app)
506 GUI_PYGLET: enable_pyglet,
557 enable_pyglet = lambda app=None: inputhook_manager.enable_gui('pyglet', app)
507 GUI_GTK3: enable_gtk3,
558 enable_gtk3 = lambda app=None: inputhook_manager.enable_gui('gtk3', app)
508 }
559 disable_wx = disable_qt4 = disable_gtk = disable_gtk3 = disable_glut = \
509
560 disable_pyglet = inputhook_manager.disable_gui No newline at end of file
510
511 # Convenience function to switch amongst them
512 def enable_gui(gui=None, app=None):
513 """Switch amongst GUI input hooks by name.
514
515 This is just a utility wrapper around the methods of the InputHookManager
516 object.
517
518 Parameters
519 ----------
520 gui : optional, string or None
521 If None (or 'none'), clears input hook, otherwise it must be one
522 of the recognized GUI names (see ``GUI_*`` constants in module).
523
524 app : optional, existing application object.
525 For toolkits that have the concept of a global app, you can supply an
526 existing one. If not given, the toolkit will be probed for one, and if
527 none is found, a new one will be created. Note that GTK does not have
528 this concept, and passing an app if ``gui=="GTK"`` will raise an error.
529
530 Returns
531 -------
532 The output of the underlying gui switch routine, typically the actual
533 PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
534 one.
535 """
536 try:
537 gui_hook = guis[gui]
538 except KeyError:
539 e = "Invalid GUI request %r, valid ones are:%s" % (gui, guis.keys())
540 raise ValueError(e)
541 return gui_hook(app)
542
General Comments 0
You need to be logged in to leave comments. Login now