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