Repository navigation
Expand file tree
/
Copy pathproctor_clock.py
More file actions
398 lines (353 loc) · 13.7 KB
/
Copy pathproctor_clock.py
File metadata and controls
398 lines (353 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env python
# coding: UTF-8
# license: GPL
#
## @package _08c_clock
#
# A very simple analog Clock.
#
# The program transforms worldcoordinates into screencoordinates
# and vice versa according to an algorithm found in:
# "Programming principles in computer graphics" by Leendert Ammeraal.
#
# Based on the code of Anton Vredegoor(anton.vredegoor@gmail.com)
#
# @author Paulo Roma
# @since 01/05/2014
# @see https://code.activestate.com/recipes/578875-analog-Clock
# @see http://orion.lcg.ufrj.br/python/figuras/fluminense.png
import sys, os
from datetime import timedelta, datetime
from math import sin, cos, pi
from threading import Thread
try:
from tkinter import Tk, Canvas, BOTH, YES, ALL # python 3
except ImportError:
try:
from mtTkinter import Tk, Canvas, BOTH, YES, ALL # for thread safe
except ImportError:
try:
from Tkinter import Tk, Canvas, BOTH, YES, ALL # python 2
except ImportError:
print("Cannot find Tkinter")
HAS_PIL = True
# we need PIL for resizing the background image
# in Fedora do: yum install python-pillow-tk
# or yum install python3-pillow-tk
try:
from PIL import Image, ImageTk
except ImportError:
HAS_PIL = False
## Class for handling the mapping from window coordinates
# to viewport coordinates.
#
class Mapper:
## Constructor.
#
# @param world window rectangle.
# @param viewport screen rectangle.
#
def __init__(self, world, viewport):
self.world = world
self.viewport = viewport
# default initial world size is a 2-by-2 grid with min-max points at
# [-1(x-min), -1(y-min), 1(x-max), 1(y-max)]
# other initial grid anchor points are possible with their own effects
# Remember that, from the screen's perspective, y increases downward
# whereas, from the world's perspective, y increases upward!
# window coordinates
x_min_world, y_min_world, x_max_world, y_max_world = self.world
# screen coordinates
x_min_viewport, y_min_viewport, x_max_viewport, y_max_viewport = self.viewport
# window factor
x_factor = float(x_max_viewport-x_min_viewport) / float(x_max_world-x_min_world)
y_factor = float(y_max_viewport-y_min_viewport) / float(y_max_world-y_min_world)
self.factor = min(x_factor, y_factor) # From the x and y fractions pick the smallest
# Center point of the world
x_center_world = 0.5 *(x_min_world + x_max_world)
y_center_world = 0.5 *(y_min_world + y_max_world)
# Center point of the viewport (window in screen coordinates)
x_center_viewport = 0.5 *(x_min_viewport + x_max_viewport)
y_center_viewport = 0.5 *(y_min_viewport + y_max_viewport)
# Center offsets
self.c_1 = x_center_viewport - self.factor * x_center_world
self.c_2 = y_center_viewport - self.factor * y_center_world
#print(world)
#print(viewport)
#print(self.factor)
#print(self.c_1)
#print(self.c_2)
## Maps a single point from world(window) coordinates to viewport(screen) coordinates.
#
# @param x, y given point.
# @return a new point in screen coordinates.
#
def _window_to_viewport(self, x_world, y_world):
x_viewport = self.factor * x_world + self.c_1
y_viewport = self.factor * -y_world + self.c_2 # y_viewport axis is upside down
return x_viewport, y_viewport
## Maps two points from world(window) coordinates to viewport(screen) coordinates.
#
# @param x1, y1 first point.
# @param x2, y2 second point.
# @return two new points in screen coordinates.
#
def window_to_viewport(self, x_world_1, y_world_1, x_world_2, y_world_2):
world_point_1 = self._window_to_viewport(x_world_1, y_world_1)
world_point_2 = self._window_to_viewport(x_world_2, y_world_2)
return world_point_1, world_point_2
## Class for creating a new thread.
#
class MakeThread(Thread):
#"""Creates a thread."""
## Constructor
# @param func function to run on this thread.
#
def __init__(self, func):
Thread.__init__(self)
self.__action = func
self.debug = False
## Destructor
#
def __del__(self):
if self.debug:
print("Thread end")
## Starts this thread(called by self.start())
#
def run(self):
if self.debug:
print("Thread begin")
self.__action()
## Class for drawing a simple analog Clock.
# The backgroung image may be changed by pressing key 'i'.
# The image path is hardcoded. It should be available in directory 'images'.
#
class Clock:
## Constructor.
#
# @param root the Tkinder GUI API
# @param delta_hours time zone.
# @param is_show_image whether to use a background image.
# @param width canvas width.
# @param height canvas height.
# @param is_use_thread whether to use a separate thread for running the Clock.
#
def __init__(self, root, delta_hours=0, is_show_image=False, width=400, height=400, is_use_thread=False):
self.world = [-1, -1, 1, 1]
#self.img_path = './images/fluminense.png' # image path
#if HAS_PIL and os.path.exists(self.img_path): # no(in Windows) and no(path doesn't exist)
# self.show_image = is_show_image
#else:
# self.show_image = False # this is probably what we'll get most times
self.set_colors() # sets colors based on show_image value
self.circlesize = 0.1 # defines the radius of the center circle as 0.09 ??
self._all = 'handles' # no idea what this does yet
self.root = root
width, height = width, height
self.pad = width/10 # not sure why we're basing the padding on the width but okay
self.d_minutes = 0
self.d_hours = 0
self.play = True
flu = None
self.flu = None
#if self.show_image: # nope
# self.flu_img = Image.open(self.img_path)
self.root.bind("<Escape>", lambda _: root.destroy()) # more tkinter stuff
self.delta = timedelta(hours=delta_hours)
self.canvas = Canvas(root, width=width, height=height, background=self.bg_color)
viewport = (self.pad, self.pad, width-self.pad, height-self.pad) # create viewport with
# padded values
self.my_mapper = Mapper(self.world, viewport) # create Mapper for the window that will be created
self.root.title('Clock')
self.root.bind("<Configure>", self.resize)
#self.root.bind("<KeyPress-i>", self.toggle_image)
self.root.bind("<KeyPress-f>", self.add_minute) # forward one minute
self.root.bind("<KeyPress-v>", self.subtract_minute) # reverse one minute
self.root.bind("<space>", self.reset_time) # reset minutes
self.root.bind("<KeyPress-F>", self.add_hour) # forward one hour
self.root.bind("<KeyPress-V>", self.subtract_hour) # reverse one hour
self.root.bind("<KeyPress-p>", self.toggle_play_pause) # pause
self.canvas.pack(fill=BOTH, expand=YES) # ???
#if is_use_thread:
# new_thread = MakeThread(self.poll)
# new_thread.debug = True
# new_thread.start()
#else:
self.poll()
## Called when the window changes, by means of a user input.
#
def resize(self, event):
if event:
my_canvas = self.canvas
my_canvas.delete(ALL) # erase the whole canvas
width = my_canvas.winfo_width() # get new window width
height = my_canvas.winfo_height() # get new window height
img_size = min(width, height)
self.pad = img_size/10 # AHA! padding does scale up with min(width, height)
viewport = (self.pad, self.pad, width-self.pad, height-self.pad)
self.my_mapper = Mapper(self.world, viewport)
#if self.show_image: # nope
# flu = self.flu_img.resize((int(0.8*0.8*img_size), int(0.8*img_size)), Image.ANTIALIAS)
# if flu:
# self.flu = ImageTk.PhotoImage(flu)
# my_canvas.create_image(width/2, height/2, image=self.flu)
# else:
self.canvas.create_rectangle([[0, 0], [width, height]], fill=self.bg_color)
#self.canvas = Canvas(root, width=width, height=height, background=self.bg_color)
# Why are we calling create_rectangle(...) all of a sudden?
self.redraw() # redraw the Clock
## Sets the Clock colors.
#
def set_colors(self):
#if self.show_image: # nope
# self.bg_color = 'antique white'
# self.time_color = 'dark orange'
# self.circle_color = 'dark green'
# self.second_color = 'red'
#else:
self.bg_color = '#ffffff'
self.time_color = '#000000'
self.circle_color = '#000000' # originally, #808080
self.second_color = '#ff0000'
## Toggles the displaying of a background image.
#
def toggle_image(self, event):
if HAS_PIL and os.path.exists(self.img_path): # nope
self.show_image = not self.show_image
self.set_colors()
self.resize(event)
## Redraws the whole Clock.
#
def redraw(self):
start = pi/2 # 12h is at pi/2 ~ 90*
h_step = pi/6 # each hour step is pi/6 ~ 30*
m_step = pi/30 # each minute step is pi/30 ~ 6*
self.paint_circle(0, 0) # draw a circle at the centre of the Clock
for i in range(12): # draw the minute ticks as circles
angle = start-i*h_step
x_coord, y_coord = cos(angle), sin(angle)
self.paint_line(x_coord*1.13, y_coord*1.13, x_coord*1.2, y_coord*1.2, width=4)
k = 12 if i==0 else i
self.paint_number(x_coord, y_coord, str(k))
for j in range(60):
angle = start-j*m_step
x_coord, y_coord = cos(angle), sin(angle)
self.paint_line(x_coord*1.13, y_coord*1.13, x_coord*1.18, y_coord*1.18, width=3)
self.paint_hms() # draw the handles
#if not self.show_image:
## Set Clock forward or back by a given number of minutes
#
def seek_time(self, event, hour_change=0, minute_change=0):
self.d_minutes += minute_change
self.d_hours += hour_change
self.resize(event)
def add_minute(self, event):
if event:
self.seek_time(event, minute_change=1)
def subtract_minute(self, event):
if event:
self.seek_time(event, minute_change=-1)
def add_hour(self, event):
if event:
self.seek_time(event, hour_change=1)
def subtract_hour(self, event):
if event:
self.seek_time(event, hour_change=-1)
def toggle_play_pause(self, event):
if event:
self.play = False if self.play else True
print(self.play)
self.poll()
def reset_time(self, event):
if event:
#self.seek_time(hour_change=-1*self.d_hours, minute_change=-1*self.d_minutes)
self.d_hours = 0
self.d_minutes = 0
self.resize(event)
## Draws the handles.
#
def paint_hms(self):
self.canvas.delete(self._all) # delete the handles
current_datetime = datetime.timetuple(datetime.utcnow()-self.delta)
trash, trash, trash, hour, minute, second, trash, trash, trash = current_datetime
if trash:
trash = None
minute = (minute + self.d_minutes) % 60
hour = (hour + self.d_hours) % 12
self.root.title('%02i:%02i:%02i' %(hour, minute, second))
hl = 0.70 # hour length
angle = pi/2 - pi/6 *(hour + minute/60.0)
x_coord, y_coord = cos(angle)*hl, sin(angle)*hl
# draw the hour handle
self.paint_handle(x_coord, y_coord, self.time_color, self.pad/3)
ml = 0.98 # minute length
angle = pi/2 - pi/30 *(minute + second/60.0)
x_coord, y_coord = cos(angle)*ml, sin(angle)*ml
# draw the minute handle
self.paint_handle(x_coord, y_coord, self.time_color, self.pad/4)
sl = 0.99 # second length
angle = pi/2 - pi/30 * second
x_coord, y_coord = cos(angle)*sl, sin(angle)*sl
# draw the second handle
self.paint_handle(x_coord, y_coord, self.second_color, self.pad/15)
def paint_handle(self, x, y, fill, width):
self.paint_line(x, y, fill=fill,
width=width, tag=self._all)
def paint_line(self, x1, y1, x2=0, y2=0, fill='#000000', width=3, tag=''):
scl = self.canvas.create_line
xy1, xy2 = self.my_mapper.window_to_viewport(x1, y1, x2, y2)
scl(xy1, xy2, fill=fill, tag=tag,
width=width)
## Draws a circle at a given point.
#
# @param x, y given point.
#
def paint_circle(self, x_coord, y_coord):
circle_size = self.circlesize/3
sco = self.canvas.create_oval
xy1, xy2 = self.my_mapper.window_to_viewport(-circle_size+x_coord, -circle_size+y_coord, circle_size+x_coord, circle_size+y_coord)
sco(xy1, xy2,fill=self.time_color)
def paint_number(self, x_coord, y_coord, i):
circle_size = self.circlesize / 2.0
sct = self.canvas.create_text
x, y = self.my_mapper._window_to_viewport(x_coord, y_coord)
sct(x, y, font='Helvetica 24 bold', text=i)
## Animates the Clock, by redrawing everything after a certain time interval.
#
def poll(self):
self.redraw()
if self.play:
self.root.after(200, self.poll)
## Main program for testing.
#
# @param argv time zone, image background flag,
# Clock width, Clock height, create thread flag.
#
def main(argv=None):
# if argv is None:
argv = sys.argv
# if len(argv) > 2:
# try:
# delta_hours = int(argv[1])
# is_show_image = (argv[2] == 'True')
# width = int(argv[3])
# height = int(argv[4])
# is_use_thread = (argv[5] == 'True')
# except ValueError:
# print("A timezone is expected.")
# return 1
#else:
delta_hours = 5 # EST
is_show_image = False
width = height = 400
is_use_thread = False
root = Tk() # TODO: find out what this and the following does
root.geometry('+0+0')
# delta_hours: how far are you from utc?
# Sometimes the Clock may be run from another timezone ...
Clock(root, delta_hours, is_show_image, width, height, is_use_thread)
root.mainloop() # This officially starts the window and binds its event listeners
# Create a new window
# With space for the new time
if __name__ == '__main__':
sys.exit(main())