##// END OF EJS Templates
Fix Qt inputhook...
Thomas Kluyver -
Show More
@@ -1,584 +1,584 b''
1 1 # coding: utf-8
2 2 """
3 3 Inputhook management for GUI event loop integration.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 try:
18 18 import ctypes
19 19 except ImportError:
20 20 ctypes = None
21 21 except SystemError: # IronPython issue, 2/8/2014
22 22 ctypes = None
23 23 import os
24 24 import sys
25 25 from distutils.version import LooseVersion as V
26 26
27 27 from IPython.utils.warn import warn
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Constants
31 31 #-----------------------------------------------------------------------------
32 32
33 33 # Constants for identifying the GUI toolkits.
34 34 GUI_WX = 'wx'
35 35 GUI_QT = 'qt'
36 36 GUI_QT4 = 'qt4'
37 37 GUI_GTK = 'gtk'
38 38 GUI_TK = 'tk'
39 39 GUI_OSX = 'osx'
40 40 GUI_GLUT = 'glut'
41 41 GUI_PYGLET = 'pyglet'
42 42 GUI_GTK3 = 'gtk3'
43 43 GUI_NONE = 'none' # i.e. disable
44 44
45 45 #-----------------------------------------------------------------------------
46 46 # Utilities
47 47 #-----------------------------------------------------------------------------
48 48
49 49 def _stdin_ready_posix():
50 50 """Return True if there's something to read on stdin (posix version)."""
51 51 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
52 52 return bool(infds)
53 53
54 54 def _stdin_ready_nt():
55 55 """Return True if there's something to read on stdin (nt version)."""
56 56 return msvcrt.kbhit()
57 57
58 58 def _stdin_ready_other():
59 59 """Return True, assuming there's something to read on stdin."""
60 60 return True #
61 61
62 62
63 63 def _ignore_CTRL_C_posix():
64 64 """Ignore CTRL+C (SIGINT)."""
65 65 signal.signal(signal.SIGINT, signal.SIG_IGN)
66 66
67 67 def _allow_CTRL_C_posix():
68 68 """Take CTRL+C into account (SIGINT)."""
69 69 signal.signal(signal.SIGINT, signal.default_int_handler)
70 70
71 71 def _ignore_CTRL_C_other():
72 72 """Ignore CTRL+C (not implemented)."""
73 73 pass
74 74
75 75 def _allow_CTRL_C_other():
76 76 """Take CTRL+C into account (not implemented)."""
77 77 pass
78 78
79 79 if os.name == 'posix':
80 80 import select
81 81 import signal
82 82 stdin_ready = _stdin_ready_posix
83 83 ignore_CTRL_C = _ignore_CTRL_C_posix
84 84 allow_CTRL_C = _allow_CTRL_C_posix
85 85 elif os.name == 'nt':
86 86 import msvcrt
87 87 stdin_ready = _stdin_ready_nt
88 88 ignore_CTRL_C = _ignore_CTRL_C_other
89 89 allow_CTRL_C = _allow_CTRL_C_other
90 90 else:
91 91 stdin_ready = _stdin_ready_other
92 92 ignore_CTRL_C = _ignore_CTRL_C_other
93 93 allow_CTRL_C = _allow_CTRL_C_other
94 94
95 95
96 96 #-----------------------------------------------------------------------------
97 97 # Main InputHookManager class
98 98 #-----------------------------------------------------------------------------
99 99
100 100
101 101 class InputHookManager(object):
102 102 """Manage PyOS_InputHook for different GUI toolkits.
103 103
104 104 This class installs various hooks under ``PyOSInputHook`` to handle
105 105 GUI event loop integration.
106 106 """
107 107
108 108 def __init__(self):
109 109 if ctypes is None:
110 110 warn("IPython GUI event loop requires ctypes, %gui will not be available")
111 111 return
112 112 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
113 113 self.guihooks = {}
114 114 self.aliases = {}
115 115 self.apps = {}
116 116 self._reset()
117 117
118 118 def _reset(self):
119 119 self._callback_pyfunctype = None
120 120 self._callback = None
121 121 self._installed = False
122 122 self._current_gui = None
123 123
124 124 def get_pyos_inputhook(self):
125 125 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
126 126 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
127 127
128 128 def get_pyos_inputhook_as_func(self):
129 129 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
130 130 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
131 131
132 132 def set_inputhook(self, callback):
133 133 """Set PyOS_InputHook to callback and return the previous one."""
134 134 # On platforms with 'readline' support, it's all too likely to
135 135 # have a KeyboardInterrupt signal delivered *even before* an
136 136 # initial ``try:`` clause in the callback can be executed, so
137 137 # we need to disable CTRL+C in this situation.
138 138 ignore_CTRL_C()
139 139 self._callback = callback
140 140 self._callback_pyfunctype = self.PYFUNC(callback)
141 141 pyos_inputhook_ptr = self.get_pyos_inputhook()
142 142 original = self.get_pyos_inputhook_as_func()
143 143 pyos_inputhook_ptr.value = \
144 144 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
145 145 self._installed = True
146 146 return original
147 147
148 148 def clear_inputhook(self, app=None):
149 149 """Set PyOS_InputHook to NULL and return the previous one.
150 150
151 151 Parameters
152 152 ----------
153 153 app : optional, ignored
154 154 This parameter is allowed only so that clear_inputhook() can be
155 155 called with a similar interface as all the ``enable_*`` methods. But
156 156 the actual value of the parameter is ignored. This uniform interface
157 157 makes it easier to have user-level entry points in the main IPython
158 158 app like :meth:`enable_gui`."""
159 159 pyos_inputhook_ptr = self.get_pyos_inputhook()
160 160 original = self.get_pyos_inputhook_as_func()
161 161 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
162 162 allow_CTRL_C()
163 163 self._reset()
164 164 return original
165 165
166 166 def clear_app_refs(self, gui=None):
167 167 """Clear IPython's internal reference to an application instance.
168 168
169 169 Whenever we create an app for a user on qt4 or wx, we hold a
170 170 reference to the app. This is needed because in some cases bad things
171 171 can happen if a user doesn't hold a reference themselves. This
172 172 method is provided to clear the references we are holding.
173 173
174 174 Parameters
175 175 ----------
176 176 gui : None or str
177 177 If None, clear all app references. If ('wx', 'qt4') clear
178 178 the app for that toolkit. References are not held for gtk or tk
179 179 as those toolkits don't have the notion of an app.
180 180 """
181 181 if gui is None:
182 182 self.apps = {}
183 183 elif gui in self.apps:
184 184 del self.apps[gui]
185 185
186 186 def register(self, toolkitname, *aliases):
187 187 """Register a class to provide the event loop for a given GUI.
188 188
189 189 This is intended to be used as a class decorator. It should be passed
190 190 the names with which to register this GUI integration. The classes
191 191 themselves should subclass :class:`InputHookBase`.
192 192
193 193 ::
194 194
195 195 @inputhook_manager.register('qt')
196 196 class QtInputHook(InputHookBase):
197 197 def enable(self, app=None):
198 198 ...
199 199 """
200 200 def decorator(cls):
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 from IPython.external.appnope import nope
321 321 self.manager.set_inputhook(inputhook_wx)
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 from IPython.external.appnope import nap
338 338 nap()
339 339
340 340 @inputhook_manager.register('qt', 'qt4')
341 341 class Qt4InputHook(InputHookBase):
342 342 def enable(self, app=None):
343 343 """Enable event loop integration with PyQt4.
344 344
345 345 Parameters
346 346 ----------
347 347 app : Qt Application, optional.
348 348 Running application to use. If not given, we probe Qt for an
349 349 existing application object, and create a new one if none is found.
350 350
351 351 Notes
352 352 -----
353 353 This methods sets the PyOS_InputHook for PyQt4, which allows
354 354 the PyQt4 to integrate with terminal based applications like
355 355 IPython.
356 356
357 357 If ``app`` is not given we probe for an existing one, and return it if
358 358 found. If no existing app is found, we create an :class:`QApplication`
359 359 as follows::
360 360
361 361 from PyQt4 import QtCore
362 362 app = QtGui.QApplication(sys.argv)
363 363 """
364 364 from IPython.lib.inputhookqt4 import create_inputhook_qt4
365 365 from IPython.external.appnope import nope
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 nope()
369 369
370 370 return app
371 371
372 372 def disable_qt4(self):
373 373 """Disable event loop integration with PyQt4.
374 374
375 375 This restores appnapp on OS X
376 376 """
377 377 from IPython.external.appnope import nap
378 378 nap()
379 379
380 380
381 381 @inputhook_manager.register('qt5')
382 382 class Qt5InputHook(Qt4InputHook):
383 383 def enable(self, app=None):
384 384 os.environ['QT_API'] = 'pyqt5'
385 385 return Qt4InputHook.enable(self, app)
386 386
387 387
388 388 @inputhook_manager.register('gtk')
389 389 class GtkInputHook(InputHookBase):
390 390 def enable(self, app=None):
391 391 """Enable event loop integration with PyGTK.
392 392
393 393 Parameters
394 394 ----------
395 395 app : ignored
396 396 Ignored, it's only a placeholder to keep the call signature of all
397 397 gui activation methods consistent, which simplifies the logic of
398 398 supporting magics.
399 399
400 400 Notes
401 401 -----
402 402 This methods sets the PyOS_InputHook for PyGTK, which allows
403 403 the PyGTK to integrate with terminal based applications like
404 404 IPython.
405 405 """
406 406 import gtk
407 407 try:
408 408 gtk.set_interactive(True)
409 409 except AttributeError:
410 410 # For older versions of gtk, use our own ctypes version
411 411 from IPython.lib.inputhookgtk import inputhook_gtk
412 412 self.manager.set_inputhook(inputhook_gtk)
413 413
414 414
415 415 @inputhook_manager.register('tk')
416 416 class TkInputHook(InputHookBase):
417 417 def enable(self, app=None):
418 418 """Enable event loop integration with Tk.
419 419
420 420 Parameters
421 421 ----------
422 422 app : toplevel :class:`Tkinter.Tk` widget, optional.
423 423 Running toplevel widget to use. If not given, we probe Tk for an
424 424 existing one, and create a new one if none is found.
425 425
426 426 Notes
427 427 -----
428 428 If you have already created a :class:`Tkinter.Tk` object, the only
429 429 thing done by this method is to register with the
430 430 :class:`InputHookManager`, since creating that object automatically
431 431 sets ``PyOS_InputHook``.
432 432 """
433 433 if app is None:
434 434 try:
435 435 from tkinter import Tk # Py 3
436 436 except ImportError:
437 437 from Tkinter import Tk # Py 2
438 438 app = Tk()
439 439 app.withdraw()
440 440 self.manager.apps[GUI_TK] = app
441 441 return app
442 442
443 443
444 444 @inputhook_manager.register('glut')
445 445 class GlutInputHook(InputHookBase):
446 446 def enable(self, app=None):
447 447 """Enable event loop integration with GLUT.
448 448
449 449 Parameters
450 450 ----------
451 451
452 452 app : ignored
453 453 Ignored, it's only a placeholder to keep the call signature of all
454 454 gui activation methods consistent, which simplifies the logic of
455 455 supporting magics.
456 456
457 457 Notes
458 458 -----
459 459
460 460 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
461 461 integrate with terminal based applications like IPython. Due to GLUT
462 462 limitations, it is currently not possible to start the event loop
463 463 without first creating a window. You should thus not create another
464 464 window but use instead the created one. See 'gui-glut.py' in the
465 465 docs/examples/lib directory.
466 466
467 467 The default screen mode is set to:
468 468 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
469 469 """
470 470
471 471 import OpenGL.GLUT as glut
472 472 from IPython.lib.inputhookglut import glut_display_mode, \
473 473 glut_close, glut_display, \
474 474 glut_idle, inputhook_glut
475 475
476 476 if GUI_GLUT not in self.manager.apps:
477 477 glut.glutInit( sys.argv )
478 478 glut.glutInitDisplayMode( glut_display_mode )
479 479 # This is specific to freeglut
480 480 if bool(glut.glutSetOption):
481 481 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
482 482 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
483 483 glut.glutCreateWindow( sys.argv[0] )
484 484 glut.glutReshapeWindow( 1, 1 )
485 485 glut.glutHideWindow( )
486 486 glut.glutWMCloseFunc( glut_close )
487 487 glut.glutDisplayFunc( glut_display )
488 488 glut.glutIdleFunc( glut_idle )
489 489 else:
490 490 glut.glutWMCloseFunc( glut_close )
491 491 glut.glutDisplayFunc( glut_display )
492 492 glut.glutIdleFunc( glut_idle)
493 493 self.manager.set_inputhook( inputhook_glut )
494 494
495 495
496 496 def disable(self):
497 497 """Disable event loop integration with glut.
498 498
499 499 This sets PyOS_InputHook to NULL and set the display function to a
500 500 dummy one and set the timer to a dummy timer that will be triggered
501 501 very far in the future.
502 502 """
503 503 import OpenGL.GLUT as glut
504 504 from glut_support import glutMainLoopEvent
505 505
506 506 glut.glutHideWindow() # This is an event to be processed below
507 507 glutMainLoopEvent()
508 508 super(GlutInputHook, self).disable()
509 509
510 510 @inputhook_manager.register('pyglet')
511 511 class PygletInputHook(InputHookBase):
512 512 def enable(self, app=None):
513 513 """Enable event loop integration with pyglet.
514 514
515 515 Parameters
516 516 ----------
517 517 app : ignored
518 518 Ignored, it's only a placeholder to keep the call signature of all
519 519 gui activation methods consistent, which simplifies the logic of
520 520 supporting magics.
521 521
522 522 Notes
523 523 -----
524 524 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
525 525 pyglet to integrate with terminal based applications like
526 526 IPython.
527 527
528 528 """
529 529 from IPython.lib.inputhookpyglet import inputhook_pyglet
530 530 self.manager.set_inputhook(inputhook_pyglet)
531 531 return app
532 532
533 533
534 534 @inputhook_manager.register('gtk3')
535 535 class Gtk3InputHook(InputHookBase):
536 536 def enable(self, app=None):
537 537 """Enable event loop integration with Gtk3 (gir bindings).
538 538
539 539 Parameters
540 540 ----------
541 541 app : ignored
542 542 Ignored, it's only a placeholder to keep the call signature of all
543 543 gui activation methods consistent, which simplifies the logic of
544 544 supporting magics.
545 545
546 546 Notes
547 547 -----
548 548 This methods sets the PyOS_InputHook for Gtk3, which allows
549 549 the Gtk3 to integrate with terminal based applications like
550 550 IPython.
551 551 """
552 552 from IPython.lib.inputhookgtk3 import inputhook_gtk3
553 553 self.manager.set_inputhook(inputhook_gtk3)
554 554
555 555
556 556 clear_inputhook = inputhook_manager.clear_inputhook
557 557 set_inputhook = inputhook_manager.set_inputhook
558 558 current_gui = inputhook_manager.current_gui
559 559 clear_app_refs = inputhook_manager.clear_app_refs
560 560 enable_gui = inputhook_manager.enable_gui
561 561 disable_gui = inputhook_manager.disable_gui
562 562 register = inputhook_manager.register
563 563 guis = inputhook_manager.guihooks
564 564
565 565 # Deprecated methods: kept for backwards compatibility, do not use in new code
566 566 def _make_deprecated_enable(name):
567 567 def enable_toolkit(app=None):
568 568 warn("This function is deprecated - use enable_gui(%r) instead" % name)
569 569 inputhook_manager.enable_gui(name, app)
570 570
571 571 enable_osx = _make_deprecated_enable('osx')
572 572 enable_wx = _make_deprecated_enable('wx')
573 573 enable_qt4 = _make_deprecated_enable('qt4')
574 574 enable_gtk = _make_deprecated_enable('gtk')
575 575 enable_tk = _make_deprecated_enable('tk')
576 576 enable_glut = _make_deprecated_enable('glut')
577 577 enable_pyglet = _make_deprecated_enable('pyglet')
578 578 enable_gtk3 = _make_deprecated_enable('gtk3')
579 579
580 580 def _deprecated_disable():
581 581 warn("This function is deprecated: use disable_gui() instead")
582 582 inputhook_manager.disable_gui()
583 583 disable_wx = disable_qt4 = disable_gtk = disable_gtk3 = disable_glut = \
584 584 disable_pyglet = disable_osx = _deprecated_disable
General Comments 0
You need to be logged in to leave comments. Login now