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