pyglet.py 2.3 KB

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