pyglet.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """Enable pyglet to be used interacively with prompt_toolkit
  2. """
  3. from __future__ import absolute_import
  4. import os
  5. import sys
  6. import time
  7. from timeit import default_timer as clock
  8. import pyglet
  9. # On linux only, window.flip() has a bug that causes an AttributeError on
  10. # window close. For details, see:
  11. # http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
  12. if sys.platform.startswith('linux'):
  13. def flip(window):
  14. try:
  15. window.flip()
  16. except AttributeError:
  17. pass
  18. else:
  19. def flip(window):
  20. window.flip()
  21. def inputhook(context):
  22. """Run the pyglet event loop by processing pending events only.
  23. This keeps processing pending events until stdin is ready. After
  24. processing all pending events, a call to time.sleep is inserted. This is
  25. needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
  26. though for best performance.
  27. """
  28. # We need to protect against a user pressing Control-C when IPython is
  29. # idle and this is running. We trap KeyboardInterrupt and pass.
  30. try:
  31. t = clock()
  32. while not context.input_is_ready():
  33. pyglet.clock.tick()
  34. for window in pyglet.app.windows:
  35. window.switch_to()
  36. window.dispatch_events()
  37. window.dispatch_event('on_draw')
  38. flip(window)
  39. # We need to sleep at this point to keep the idle CPU load
  40. # low. However, if sleep to long, GUI response is poor. As
  41. # a compromise, we watch how often GUI events are being processed
  42. # and switch between a short and long sleep time. Here are some
  43. # stats useful in helping to tune this.
  44. # time CPU load
  45. # 0.001 13%
  46. # 0.005 3%
  47. # 0.01 1.5%
  48. # 0.05 0.5%
  49. used_time = clock() - t
  50. if used_time > 10.0:
  51. # print 'Sleep for 1 s' # dbg
  52. time.sleep(1.0)
  53. elif used_time > 0.1:
  54. # Few GUI events coming in, so we can sleep longer
  55. # print 'Sleep for 0.05 s' # dbg
  56. time.sleep(0.05)
  57. else:
  58. # Many GUI events coming in, so sleep only very little
  59. time.sleep(0.001)
  60. except KeyboardInterrupt:
  61. pass