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