pyglet.py 2.3 KB

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