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