Added 'description' class attribute to every command class (to help the
[python/dscho.git] / Demo / threads / wpi.py
blobd4c0ef9b6de14686a19483be0e863d8b6a307136
1 # Display digits of pi in a window, calculating in a separate thread.
2 # Compare ../scripts/pi.py.
4 import sys
5 import time
6 import thread
7 import stdwin
8 from stdwinevents import *
10 ok = 1
12 digits = []
14 def worker():
15 k, a, b, a1, b1 = 2l, 4l, 1l, 12l, 4l
16 while ok:
17 # Next approximation
18 p, q, k = k*k, 2l*k+1l, k+1l
19 a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
20 # Print common digits
21 d, d1 = a/b, a1/b1
22 #print a, b, a1, b1
23 while d == d1:
24 digits.append(`int(d)`)
25 a, a1 = 10l*(a%b), 10l*(a1%b1)
26 d, d1 = a/b, a1/b1
28 def main():
29 global ok
30 digits_seen = 0
31 thread.start_new_thread(worker, ())
32 tw = stdwin.textwidth('0 ')
33 lh = stdwin.lineheight()
34 stdwin.setdefwinsize(20 * tw, 20 * lh)
35 stdwin.setdefscrollbars(0, 1)
36 win = stdwin.open('digits of pi')
37 options = win.menucreate('Options')
38 options.additem('Auto scroll')
39 autoscroll = 1
40 options.check(0, autoscroll)
41 while 1:
42 win.settimer(1)
43 type, w, detail = stdwin.getevent()
44 if type == WE_CLOSE:
45 ok = 0
46 sys.exit(0)
47 elif type == WE_DRAW:
48 (left, top), (right, bottom) = detail
49 digits_seen = len(digits)
50 d = win.begindrawing()
51 for i in range(digits_seen):
52 h = (i % 20) * tw
53 v = (i / 20) * lh
54 if top-lh < v < bottom:
55 d.text((h, v), digits[i])
56 d.close()
57 elif type == WE_TIMER:
58 n = len(digits)
59 if n > digits_seen:
60 win.settitle(`n` + ' digits of pi')
61 d = win.begindrawing()
62 for i in range(digits_seen, n):
63 h = (i % 20) * tw
64 v = (i / 20) * lh
65 d.text((h, v), digits[i])
66 d.close()
67 digits_seen = n
68 height = (v + 20*lh) / (20*lh) * (20*lh)
69 win.setdocsize(0, height)
70 if autoscroll:
71 win.show((0, v), (h+tw, v+lh))
72 elif type == WE_MENU:
73 menu, item = detail
74 if menu == options:
75 if item == 0:
76 autoscroll = (not autoscroll)
77 options.check(0, autoscroll)
80 main()