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