gtk3reactor.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. This module provides support for Twisted to interact with the gtk3 mainloop
  5. via Gobject introspection. This is like gi, but slightly slower and requires a
  6. working $DISPLAY.
  7. In order to use this support, simply do the following::
  8. from twisted.internet import gtk3reactor
  9. gtk3reactor.install()
  10. If you wish to use a GApplication, register it with the reactor::
  11. from twisted.internet import reactor
  12. reactor.registerGApplication(app)
  13. Then use twisted.internet APIs as usual.
  14. """
  15. from __future__ import division, absolute_import
  16. import os
  17. from twisted.internet import gireactor
  18. from twisted.python import runtime
  19. # Newer versions of gtk3/pygoject raise a RuntimeError, or just break in a
  20. # confusing manner, if the program is not running under X11. We therefore try
  21. # to fail in a more reasonable manner, and check for $DISPLAY as a reasonable
  22. # approximation of availability of X11. This is somewhat over-aggressive,
  23. # since some older versions of gtk3/pygobject do work with missing $DISPLAY,
  24. # but it's too hard to figure out which, so we always require it.
  25. if (runtime.platform.getType() == 'posix' and
  26. not runtime.platform.isMacOSX() and not os.environ.get("DISPLAY")):
  27. raise ImportError(
  28. "Gtk3 requires X11, and no DISPLAY environment variable is set")
  29. class Gtk3Reactor(gireactor.GIReactor):
  30. """
  31. A reactor using the gtk3+ event loop.
  32. """
  33. def __init__(self):
  34. """
  35. Override init to set the C{useGtk} flag.
  36. """
  37. gireactor.GIReactor.__init__(self, useGtk=True)
  38. class PortableGtk3Reactor(gireactor.PortableGIReactor):
  39. """
  40. Portable GTK+ 3.x reactor.
  41. """
  42. def __init__(self):
  43. """
  44. Override init to set the C{useGtk} flag.
  45. """
  46. gireactor.PortableGIReactor.__init__(self, useGtk=True)
  47. def install():
  48. """
  49. Configure the Twisted mainloop to be run inside the gtk3+ mainloop.
  50. """
  51. if runtime.platform.getType() == 'posix':
  52. reactor = Gtk3Reactor()
  53. else:
  54. reactor = PortableGtk3Reactor()
  55. from twisted.internet.main import installReactor
  56. installReactor(reactor)
  57. return reactor
  58. __all__ = ['install']