##// END OF EJS Templates
Remove deprecated methods....
Matthias Bussonnier -
Show More
@@ -1,588 +1,574 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 110 else:
111 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 200 if ctypes is not None:
201 201 inst = cls(self)
202 202 self.guihooks[toolkitname] = inst
203 203 for a in aliases:
204 204 self.aliases[a] = toolkitname
205 205 return cls
206 206 return decorator
207 207
208 208 def current_gui(self):
209 209 """Return a string indicating the currently active GUI or None."""
210 210 return self._current_gui
211 211
212 212 def enable_gui(self, gui=None, app=None):
213 213 """Switch amongst GUI input hooks by name.
214 214
215 215 This is a higher level method than :meth:`set_inputhook` - it uses the
216 216 GUI name to look up a registered object which enables the input hook
217 217 for that GUI.
218 218
219 219 Parameters
220 220 ----------
221 221 gui : optional, string or None
222 222 If None (or 'none'), clears input hook, otherwise it must be one
223 223 of the recognized GUI names (see ``GUI_*`` constants in module).
224 224
225 225 app : optional, existing application object.
226 226 For toolkits that have the concept of a global app, you can supply an
227 227 existing one. If not given, the toolkit will be probed for one, and if
228 228 none is found, a new one will be created. Note that GTK does not have
229 229 this concept, and passing an app if ``gui=="GTK"`` will raise an error.
230 230
231 231 Returns
232 232 -------
233 233 The output of the underlying gui switch routine, typically the actual
234 234 PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
235 235 one.
236 236 """
237 237 if gui in (None, GUI_NONE):
238 238 return self.disable_gui()
239 239
240 240 if gui in self.aliases:
241 241 return self.enable_gui(self.aliases[gui], app)
242 242
243 243 try:
244 244 gui_hook = self.guihooks[gui]
245 245 except KeyError:
246 246 e = "Invalid GUI request {!r}, valid ones are: {}"
247 247 raise ValueError(e.format(gui, ', '.join(self.guihooks)))
248 248 self._current_gui = gui
249 249
250 250 app = gui_hook.enable(app)
251 251 if app is not None:
252 252 app._in_event_loop = True
253 253 self.apps[gui] = app
254 254 return app
255 255
256 256 def disable_gui(self):
257 257 """Disable GUI event loop integration.
258 258
259 259 If an application was registered, this sets its ``_in_event_loop``
260 260 attribute to False. It then calls :meth:`clear_inputhook`.
261 261 """
262 262 gui = self._current_gui
263 263 if gui in self.apps:
264 264 self.apps[gui]._in_event_loop = False
265 265 return self.clear_inputhook()
266 266
267 267 class InputHookBase(object):
268 268 """Base class for input hooks for specific toolkits.
269 269
270 270 Subclasses should define an :meth:`enable` method with one argument, ``app``,
271 271 which will either be an instance of the toolkit's application class, or None.
272 272 They may also define a :meth:`disable` method with no arguments.
273 273 """
274 274 def __init__(self, manager):
275 275 self.manager = manager
276 276
277 277 def disable(self):
278 278 pass
279 279
280 280 inputhook_manager = InputHookManager()
281 281
282 282 @inputhook_manager.register('osx')
283 283 class NullInputHook(InputHookBase):
284 284 """A null inputhook that doesn't need to do anything"""
285 285 def enable(self, app=None):
286 286 pass
287 287
288 288 @inputhook_manager.register('wx')
289 289 class WxInputHook(InputHookBase):
290 290 def enable(self, app=None):
291 291 """Enable event loop integration with wxPython.
292 292
293 293 Parameters
294 294 ----------
295 295 app : WX Application, optional.
296 296 Running application to use. If not given, we probe WX for an
297 297 existing application object, and create a new one if none is found.
298 298
299 299 Notes
300 300 -----
301 301 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
302 302 the wxPython to integrate with terminal based applications like
303 303 IPython.
304 304
305 305 If ``app`` is not given we probe for an existing one, and return it if
306 306 found. If no existing app is found, we create an :class:`wx.App` as
307 307 follows::
308 308
309 309 import wx
310 310 app = wx.App(redirect=False, clearSigInt=False)
311 311 """
312 312 import wx
313 313
314 314 wx_version = V(wx.__version__).version
315 315
316 316 if wx_version < [2, 8]:
317 317 raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
318 318
319 319 from IPython.lib.inputhookwx import inputhook_wx
320 320 self.manager.set_inputhook(inputhook_wx)
321 321 if _use_appnope():
322 322 from appnope import nope
323 323 nope()
324 324
325 325 import wx
326 326 if app is None:
327 327 app = wx.GetApp()
328 328 if app is None:
329 329 app = wx.App(redirect=False, clearSigInt=False)
330 330
331 331 return app
332 332
333 333 def disable(self):
334 334 """Disable event loop integration with wxPython.
335 335
336 336 This restores appnapp on OS X
337 337 """
338 338 if _use_appnope():
339 339 from appnope import nap
340 340 nap()
341 341
342 342 @inputhook_manager.register('qt', 'qt4')
343 343 class Qt4InputHook(InputHookBase):
344 344 def enable(self, app=None):
345 345 """Enable event loop integration with PyQt4.
346 346
347 347 Parameters
348 348 ----------
349 349 app : Qt Application, optional.
350 350 Running application to use. If not given, we probe Qt for an
351 351 existing application object, and create a new one if none is found.
352 352
353 353 Notes
354 354 -----
355 355 This methods sets the PyOS_InputHook for PyQt4, which allows
356 356 the PyQt4 to integrate with terminal based applications like
357 357 IPython.
358 358
359 359 If ``app`` is not given we probe for an existing one, and return it if
360 360 found. If no existing app is found, we create an :class:`QApplication`
361 361 as follows::
362 362
363 363 from PyQt4 import QtCore
364 364 app = QtGui.QApplication(sys.argv)
365 365 """
366 366 from IPython.lib.inputhookqt4 import create_inputhook_qt4
367 367 app, inputhook_qt4 = create_inputhook_qt4(self.manager, app)
368 368 self.manager.set_inputhook(inputhook_qt4)
369 369 if _use_appnope():
370 370 from appnope import nope
371 371 nope()
372 372
373 373 return app
374 374
375 375 def disable_qt4(self):
376 376 """Disable event loop integration with PyQt4.
377 377
378 378 This restores appnapp on OS X
379 379 """
380 380 if _use_appnope():
381 381 from appnope import nap
382 382 nap()
383 383
384 384
385 385 @inputhook_manager.register('qt5')
386 386 class Qt5InputHook(Qt4InputHook):
387 387 def enable(self, app=None):
388 388 os.environ['QT_API'] = 'pyqt5'
389 389 return Qt4InputHook.enable(self, app)
390 390
391 391
392 392 @inputhook_manager.register('gtk')
393 393 class GtkInputHook(InputHookBase):
394 394 def enable(self, app=None):
395 395 """Enable event loop integration with PyGTK.
396 396
397 397 Parameters
398 398 ----------
399 399 app : ignored
400 400 Ignored, it's only a placeholder to keep the call signature of all
401 401 gui activation methods consistent, which simplifies the logic of
402 402 supporting magics.
403 403
404 404 Notes
405 405 -----
406 406 This methods sets the PyOS_InputHook for PyGTK, which allows
407 407 the PyGTK to integrate with terminal based applications like
408 408 IPython.
409 409 """
410 410 import gtk
411 411 try:
412 412 gtk.set_interactive(True)
413 413 except AttributeError:
414 414 # For older versions of gtk, use our own ctypes version
415 415 from IPython.lib.inputhookgtk import inputhook_gtk
416 416 self.manager.set_inputhook(inputhook_gtk)
417 417
418 418
419 419 @inputhook_manager.register('tk')
420 420 class TkInputHook(InputHookBase):
421 421 def enable(self, app=None):
422 422 """Enable event loop integration with Tk.
423 423
424 424 Parameters
425 425 ----------
426 426 app : toplevel :class:`Tkinter.Tk` widget, optional.
427 427 Running toplevel widget to use. If not given, we probe Tk for an
428 428 existing one, and create a new one if none is found.
429 429
430 430 Notes
431 431 -----
432 432 If you have already created a :class:`Tkinter.Tk` object, the only
433 433 thing done by this method is to register with the
434 434 :class:`InputHookManager`, since creating that object automatically
435 435 sets ``PyOS_InputHook``.
436 436 """
437 437 if app is None:
438 438 try:
439 439 from tkinter import Tk # Py 3
440 440 except ImportError:
441 441 from Tkinter import Tk # Py 2
442 442 app = Tk()
443 443 app.withdraw()
444 444 self.manager.apps[GUI_TK] = app
445 445 return app
446 446
447 447
448 448 @inputhook_manager.register('glut')
449 449 class GlutInputHook(InputHookBase):
450 450 def enable(self, app=None):
451 451 """Enable event loop integration with GLUT.
452 452
453 453 Parameters
454 454 ----------
455 455
456 456 app : ignored
457 457 Ignored, it's only a placeholder to keep the call signature of all
458 458 gui activation methods consistent, which simplifies the logic of
459 459 supporting magics.
460 460
461 461 Notes
462 462 -----
463 463
464 464 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
465 465 integrate with terminal based applications like IPython. Due to GLUT
466 466 limitations, it is currently not possible to start the event loop
467 467 without first creating a window. You should thus not create another
468 468 window but use instead the created one. See 'gui-glut.py' in the
469 469 docs/examples/lib directory.
470 470
471 471 The default screen mode is set to:
472 472 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
473 473 """
474 474
475 475 import OpenGL.GLUT as glut
476 476 from IPython.lib.inputhookglut import glut_display_mode, \
477 477 glut_close, glut_display, \
478 478 glut_idle, inputhook_glut
479 479
480 480 if GUI_GLUT not in self.manager.apps:
481 481 glut.glutInit( sys.argv )
482 482 glut.glutInitDisplayMode( glut_display_mode )
483 483 # This is specific to freeglut
484 484 if bool(glut.glutSetOption):
485 485 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
486 486 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
487 487 glut.glutCreateWindow( sys.argv[0] )
488 488 glut.glutReshapeWindow( 1, 1 )
489 489 glut.glutHideWindow( )
490 490 glut.glutWMCloseFunc( glut_close )
491 491 glut.glutDisplayFunc( glut_display )
492 492 glut.glutIdleFunc( glut_idle )
493 493 else:
494 494 glut.glutWMCloseFunc( glut_close )
495 495 glut.glutDisplayFunc( glut_display )
496 496 glut.glutIdleFunc( glut_idle)
497 497 self.manager.set_inputhook( inputhook_glut )
498 498
499 499
500 500 def disable(self):
501 501 """Disable event loop integration with glut.
502 502
503 503 This sets PyOS_InputHook to NULL and set the display function to a
504 504 dummy one and set the timer to a dummy timer that will be triggered
505 505 very far in the future.
506 506 """
507 507 import OpenGL.GLUT as glut
508 508 from glut_support import glutMainLoopEvent
509 509
510 510 glut.glutHideWindow() # This is an event to be processed below
511 511 glutMainLoopEvent()
512 512 super(GlutInputHook, self).disable()
513 513
514 514 @inputhook_manager.register('pyglet')
515 515 class PygletInputHook(InputHookBase):
516 516 def enable(self, app=None):
517 517 """Enable event loop integration with pyglet.
518 518
519 519 Parameters
520 520 ----------
521 521 app : ignored
522 522 Ignored, it's only a placeholder to keep the call signature of all
523 523 gui activation methods consistent, which simplifies the logic of
524 524 supporting magics.
525 525
526 526 Notes
527 527 -----
528 528 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
529 529 pyglet to integrate with terminal based applications like
530 530 IPython.
531 531
532 532 """
533 533 from IPython.lib.inputhookpyglet import inputhook_pyglet
534 534 self.manager.set_inputhook(inputhook_pyglet)
535 535 return app
536 536
537 537
538 538 @inputhook_manager.register('gtk3')
539 539 class Gtk3InputHook(InputHookBase):
540 540 def enable(self, app=None):
541 541 """Enable event loop integration with Gtk3 (gir bindings).
542 542
543 543 Parameters
544 544 ----------
545 545 app : ignored
546 546 Ignored, it's only a placeholder to keep the call signature of all
547 547 gui activation methods consistent, which simplifies the logic of
548 548 supporting magics.
549 549
550 550 Notes
551 551 -----
552 552 This methods sets the PyOS_InputHook for Gtk3, which allows
553 553 the Gtk3 to integrate with terminal based applications like
554 554 IPython.
555 555 """
556 556 from IPython.lib.inputhookgtk3 import inputhook_gtk3
557 557 self.manager.set_inputhook(inputhook_gtk3)
558 558
559 559
560 560 clear_inputhook = inputhook_manager.clear_inputhook
561 561 set_inputhook = inputhook_manager.set_inputhook
562 562 current_gui = inputhook_manager.current_gui
563 563 clear_app_refs = inputhook_manager.clear_app_refs
564 564 enable_gui = inputhook_manager.enable_gui
565 565 disable_gui = inputhook_manager.disable_gui
566 566 register = inputhook_manager.register
567 567 guis = inputhook_manager.guihooks
568 568
569 # Deprecated methods: kept for backwards compatibility, do not use in new code
570 def _make_deprecated_enable(name):
571 def enable_toolkit(app=None):
572 warn("This function is deprecated - use enable_gui(%r) instead" % name)
573 inputhook_manager.enable_gui(name, app)
574
575 enable_osx = _make_deprecated_enable('osx')
576 enable_wx = _make_deprecated_enable('wx')
577 enable_qt4 = _make_deprecated_enable('qt4')
578 enable_gtk = _make_deprecated_enable('gtk')
579 enable_tk = _make_deprecated_enable('tk')
580 enable_glut = _make_deprecated_enable('glut')
581 enable_pyglet = _make_deprecated_enable('pyglet')
582 enable_gtk3 = _make_deprecated_enable('gtk3')
583 569
584 570 def _deprecated_disable():
585 571 warn("This function is deprecated: use disable_gui() instead")
586 572 inputhook_manager.disable_gui()
587 573 disable_wx = disable_qt4 = disable_gtk = disable_gtk3 = disable_glut = \
588 574 disable_pyglet = disable_osx = _deprecated_disable
General Comments 0
You need to be logged in to leave comments. Login now