-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimetracker.py
More file actions
456 lines (388 loc) · 17.2 KB
/
Copy pathtimetracker.py
File metadata and controls
456 lines (388 loc) · 17.2 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
#!/usr/bin/env python3
"""
TimeTracker — a small always-on-top desktop widget for punching in and out,
recording breaks and lunches, and reviewing hours and overtime.
Click the widget -> action menu (punch in / break / lunch / punch out)
Right-click the widget -> dashboard, settings, quit
Drag the widget -> move it; position is remembered
"""
import os
import sys
import time
import socket
from datetime import datetime, date, timedelta
import tkinter as tk
from tkinter import messagebox
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import tt_core as C
from tt_ui import (
BG_PANEL, BG_CARD, BG_HOVER, FG, FG_DIM, ACCENT, AMBER, RED,
BORDER, CHROMA, FONT, FlatButton, round_rect, parse_time, center_on_screen,
enable_dpi_awareness, get_theme, DEFAULT_THEME,
)
from tt_dashboard import Dashboard
W, H = 228, 60
SINGLE_INSTANCE_PORT = 49731
# which theme colour represents each state
STATE_KEY = {C.OUT: "dim", C.WORKING: "ok", C.BREAK: "warn", C.LUNCH: "info"}
# actions offered for each state: (event type, label, icon, theme colour key)
ACTIONS = {
C.OUT: [(C.E_IN, "Punch In", "▶", "ok")],
C.WORKING: [
(C.E_BREAK_START, "Start Break", "⏸", "warn"),
(C.E_LUNCH_START, "Start Lunch", "🍴", "info"),
(C.E_OUT, "Punch Out", "⏹", "danger"),
],
C.BREAK: [(C.E_BREAK_END, "End Break — back to work", "▶", "ok")],
C.LUNCH: [(C.E_LUNCH_END, "End Lunch — back to work", "▶", "ok")],
}
def mix(colour, other, amount):
"""Blend two #rrggbb colours; used for hover states that suit any theme."""
a = [int(colour[i:i + 2], 16) for i in (1, 3, 5)]
b = [int(other[i:i + 2], 16) for i in (1, 3, 5)]
return "#%02x%02x%02x" % tuple(
int(round(x + (y - x) * amount)) for x, y in zip(a, b))
def hover_bg(theme):
"""A subtle raised background that works on light and dark themes alike."""
return mix(theme["bg"], theme["fg"], 0.10)
class Widget(tk.Tk):
def __init__(self, store):
super().__init__()
self.store = store
self.dashboard = None
self.popup = None
self.theme = get_theme(store.get("widget_theme", DEFAULT_THEME))
self.overrideredirect(True)
self.attributes("-topmost", True)
self.configure(bg=CHROMA)
self._transparent = True
try:
self.attributes("-transparentcolor", CHROMA)
except tk.TclError:
self._transparent = False
self.configure(bg=self.theme["bg"])
self._restore_position()
self.canvas = tk.Canvas(
self, width=W, height=H, highlightthickness=0, bd=0,
bg=CHROMA if self._transparent else self.theme["bg"])
self.canvas.pack()
self._draw_chrome()
for target in (self.canvas,):
target.bind("<ButtonPress-1>", self._press)
target.bind("<B1-Motion>", self._drag)
target.bind("<ButtonRelease-1>", self._release)
target.bind("<Button-3>", self._context_menu)
target.bind("<Enter>", lambda e: self._hover(True))
target.bind("<Leave>", lambda e: self._hover(False))
self.bind("<Escape>", lambda e: self._close_popup())
self._drag_from = None
self._moved = False
if getattr(store, "migrated_from", None):
self.after(600, lambda: messagebox.showinfo(
"Timesheet moved",
"Your timesheet was moved out of Python's sandboxed AppData "
"folder (which Windows can wipe) into:\n\n"
f"{C.DB_PATH}\n\nMoved from:\n{store.migrated_from}", parent=self))
self._check_stale_session()
self._tick()
# ------------------------------------------------------------ chrome
def _draw_chrome(self):
t = self.theme
c = self.canvas
c.delete("all")
self.body = round_rect(c, 1, 1, W - 1, H - 1, 14,
fill=t["bg"], outline=t["border"], width=1)
self.dot = c.create_oval(15, H // 2 - 4, 23, H // 2 + 4,
fill=t["dim"], outline="")
self.t_main = c.create_text(33, H // 2 - 9, anchor="w", text="0:00",
fill=t["fg"], font=(FONT, 15, "bold"))
self.t_sub = c.create_text(33, H // 2 + 12, anchor="w", text="",
fill=t["dim"], font=(FONT, 8))
self.t_grip = c.create_text(W - 14, H // 2, text="⋮", fill=t["border"],
font=(FONT, 12))
def apply_theme(self):
"""Re-read the chosen theme and repaint the pill immediately."""
self.theme = get_theme(self.store.get("widget_theme", DEFAULT_THEME))
self._close_popup()
self._draw_chrome()
self._render()
def _hover(self, on):
t = self.theme
self.canvas.itemconfig(self.body,
outline=t["accent"] if on else t["border"])
self.canvas.itemconfig(self.t_grip, fill=t["dim"] if on else t["border"])
# ------------------------------------------------------------ position
def _restore_position(self):
try:
x = int(self.store.get("win_x", ""))
y = int(self.store.get("win_y", ""))
except (TypeError, ValueError):
x = self.winfo_screenwidth() - W - 40
y = 60
x = max(0, min(x, self.winfo_screenwidth() - W))
y = max(0, min(y, self.winfo_screenheight() - H))
self.geometry(f"{W}x{H}+{x}+{y}")
def _press(self, e):
self._drag_from = (e.x_root, e.y_root, self.winfo_x(), self.winfo_y())
self._moved = False
def _drag(self, e):
if not self._drag_from:
return
sx, sy, wx, wy = self._drag_from
dx, dy = e.x_root - sx, e.y_root - sy
if abs(dx) > 3 or abs(dy) > 3:
self._moved = True
self._close_popup()
nx = max(0, min(wx + dx, self.winfo_screenwidth() - W))
ny = max(0, min(wy + dy, self.winfo_screenheight() - H))
self.geometry(f"+{nx}+{ny}")
def _release(self, e):
self._drag_from = None
if self._moved:
self.store.set("win_x", self.winfo_x())
self.store.set("win_y", self.winfo_y())
else:
self._toggle_popup()
# ------------------------------------------------------------ live view
def _today_totals(self):
lo = C.day_start_ts(date.today() - timedelta(days=1))
days = C.build_days(self.store.events(lo))
return days.get(date.today()) or C.DayTotals(date.today())
def _render(self):
t = self.theme
state, since = self.store.current_state()
b = self._today_totals()
std = self.store.hours_per_day() * 3600
now = int(time.time())
ot = b.overtime(std)
self.canvas.itemconfig(self.dot, fill=t[STATE_KEY[state]])
if state == C.WORKING:
main, main_fg = C.hms(b.work), t["fg"]
sub = f"Working · in at {C.clock(b.first_in)}"
elif state == C.BREAK:
main, main_fg = C.hms(now - since if since else 0), t["warn"]
sub = f"On break · worked {C.hm(b.work)}"
elif state == C.LUNCH:
main, main_fg = C.hms(now - since if since else 0), t["info"]
sub = f"At lunch · worked {C.hm(b.work)}"
else:
main, main_fg = C.hms(b.work), t["dim"]
mk = self.store.mark(date.today())
if mk and not b.work:
sub = C.mark_text(mk)
elif b.work:
sub = f"Done for today · out {C.clock(b.last_out)}"
else:
sub = "Clocked out · click to punch in"
if ot > 0:
sub += f" · OT {C.hm(ot)}"
self.canvas.itemconfig(self.t_main, text=main, fill=main_fg)
self.canvas.itemconfig(self.t_sub, text=sub)
def _tick(self):
self._render()
self.after(1000, self._tick)
# ------------------------------------------------------------ actions
def punch(self, etype):
state, _ = self.store.current_state()
if etype not in C.TRANSITIONS.get(state, {}):
messagebox.showwarning(
"Not allowed",
f"You are currently {C.STATE_LABELS[state].lower()}; "
f"'{C.EVENT_LABELS[etype]}' does not apply.", parent=self)
return
self.store.add_event(etype)
self._close_popup()
self._refresh_all()
def _refresh_all(self):
if self.dashboard and self.dashboard.winfo_exists():
self.dashboard.refresh()
def open_dashboard(self):
self._close_popup()
if self.dashboard and self.dashboard.winfo_exists():
self.dashboard.deiconify()
self.dashboard.lift()
self.dashboard.focus_force()
self.dashboard.refresh()
return
self.dashboard = Dashboard(self, self.store, on_change=self._refresh_all,
on_theme=self.apply_theme)
# ------------------------------------------------------------ popup
def _toggle_popup(self):
if self.popup and self.popup.winfo_exists():
self._close_popup()
else:
self._open_popup()
def _close_popup(self, _=None):
if self.popup and self.popup.winfo_exists():
self.popup.destroy()
self.popup = None
def _open_popup(self):
state, since = self.store.current_state()
b = self._today_totals()
std = self.store.hours_per_day() * 3600
t = self.theme
hov = hover_bg(t)
p = tk.Toplevel(self)
self.popup = p
p.overrideredirect(True)
p.attributes("-topmost", True)
p.configure(bg=t["border"])
inner = tk.Frame(p, bg=t["bg"])
inner.pack(fill="both", expand=True, padx=1, pady=1)
# summary header
head = tk.Frame(inner, bg=t["bg"])
head.pack(fill="x", padx=14, pady=(12, 8))
tk.Label(head, text=C.STATE_LABELS[state].upper(), bg=t["bg"],
fg=t[STATE_KEY[state]], font=(FONT, 8, "bold")).pack(anchor="w")
tk.Label(head, text=f"Today {C.hm(b.work)}", bg=t["bg"], fg=t["fg"],
font=(FONT, 14, "bold")).pack(anchor="w", pady=(2, 0))
detail = f"Break {C.hm(b.brk)} · Lunch {C.hm(b.lunch)}"
ot = b.overtime(std)
if ot:
detail += f" · OT {C.hm(ot)}"
tk.Label(head, text=detail, bg=t["bg"], fg=t["dim"],
font=(FONT, 8)).pack(anchor="w", pady=(1, 0))
tk.Frame(inner, bg=t["border"], height=1).pack(fill="x", pady=(2, 6))
for etype, label, icon, ckey in ACTIONS[state]:
FlatButton(inner, label, lambda e=etype: self.punch(e), icon=icon,
fg=t[ckey], bg=t["bg"], hover=hov,
pad=(14, 8), bold=True).pack(fill="x")
tk.Frame(inner, bg=t["border"], height=1).pack(fill="x", pady=(6, 2))
FlatButton(inner, "View hours & timesheet", self.open_dashboard, icon="▤",
fg=t["accent"], bg=t["bg"], hover=hov,
pad=(14, 8)).pack(fill="x")
FlatButton(inner, "Quit", self.quit_app, icon="✕", fg=t["dim"],
bg=t["bg"], hover=hov, pad=(14, 7),
font_size=9).pack(fill="x", pady=(0, 6))
p.update_idletasks()
pw, ph = max(238, p.winfo_reqwidth()), p.winfo_reqheight()
x = self.winfo_x()
y = self.winfo_y() + H + 6
if y + ph > self.winfo_screenheight():
y = self.winfo_y() - ph - 6
x = max(0, min(x, self.winfo_screenwidth() - pw))
p.geometry(f"{pw}x{ph}+{x}+{max(0, y)}")
p.bind("<Escape>", self._close_popup)
p.bind("<FocusOut>", lambda e: self.after(120, self._close_if_unfocused))
p.focus_force()
def _close_if_unfocused(self):
if not self.popup or not self.popup.winfo_exists():
return
try:
if self.popup.focus_displayof() is None:
self._close_popup()
except (tk.TclError, KeyError):
self._close_popup()
def _context_menu(self, e):
t = self.theme
m = tk.Menu(self, tearoff=0, bg=t["bg"], fg=t["fg"],
activebackground=t["accent"], activeforeground=t["bg"],
bd=0, font=(FONT, 9))
m.add_command(label="View hours & timesheet", command=self.open_dashboard)
m.add_separator()
m.add_command(label="Reset widget position", command=self._reset_position)
m.add_command(label=f"Data file: {C.DB_PATH}", state="disabled")
m.add_separator()
m.add_command(label="Quit", command=self.quit_app)
try:
m.tk_popup(e.x_root, e.y_root)
finally:
m.grab_release()
def _reset_position(self):
x, y = self.winfo_screenwidth() - W - 40, 60
self.geometry(f"+{x}+{y}")
self.store.set("win_x", x)
self.store.set("win_y", y)
# ------------------------------------------------------------ recovery
def _check_stale_session(self):
"""If the machine was shut down mid-shift, offer to correct the punch-out."""
state, since = self.store.current_state()
if state == C.OUT or not since:
return
started = datetime.fromtimestamp(since)
if started.date() >= date.today():
return
self.after(400, lambda: StaleDialog(self, self.store, state, since,
self._refresh_all))
def quit_app(self):
self._close_popup()
self.destroy()
class StaleDialog(tk.Toplevel):
"""Shown when the app finds an unfinished session from a previous day."""
def __init__(self, master, store, state, since, on_change):
super().__init__(master)
self.store, self.on_change = store, on_change
self.title("Unfinished session")
self.configure(bg=BG_PANEL)
self.resizable(False, False)
self.attributes("-topmost", True)
center_on_screen(self, 430, 240)
started = datetime.fromtimestamp(since)
tk.Label(self, text="You never punched out", bg=BG_PANEL, fg=AMBER,
font=(FONT, 14, "bold")).pack(anchor="w", padx=20, pady=(18, 4))
tk.Label(self,
text=(f"{C.STATE_LABELS[state]} since "
f"{started.strftime('%a %d %b, %H:%M')}.\n"
"Set the time you actually finished, or keep the clock running."),
bg=BG_PANEL, fg=FG_DIM, justify="left",
font=(FONT, 9)).pack(anchor="w", padx=20)
row = tk.Frame(self, bg=BG_PANEL)
row.pack(anchor="w", padx=20, pady=14)
self.date_var = tk.StringVar(value=started.date().isoformat())
self.time_var = tk.StringVar(value="18:00")
for var, width in ((self.date_var, 12), (self.time_var, 8)):
tk.Entry(row, textvariable=var, bg=BG_CARD, fg=FG, width=width,
insertbackground=FG, relief="flat", justify="center",
font=(FONT, 10), highlightthickness=1,
highlightbackground=BORDER,
highlightcolor=ACCENT).pack(side="left", padx=(0, 8), ipady=3)
btns = tk.Frame(self, bg=BG_PANEL)
btns.pack(fill="x", padx=20, pady=(4, 18))
FlatButton(btns, "Punch out at this time", self._fix, bg=ACCENT,
hover="#68b2ff", fg="#08111d", pad=(16, 7),
bold=True).pack(side="left")
FlatButton(btns, "Keep running", self.destroy, fg=FG_DIM,
bg=BG_PANEL, hover=BG_HOVER, pad=(14, 7)).pack(side="left", padx=8)
self.grab_set()
def _fix(self):
from tt_ui import parse_date
d = parse_date(self.date_var.get())
t = parse_time(self.time_var.get())
if not d or not t:
messagebox.showwarning("Invalid", "Check the date and time.", parent=self)
return
ts = int(datetime(d.year, d.month, d.day, t[0], t[1], t[2]).timestamp())
state, since = self.store.current_state()
if ts <= since:
messagebox.showwarning(
"Invalid", "That is before the session started.", parent=self)
return
# close any open break/lunch first, then punch out
if state == C.BREAK:
self.store.add_event(C.E_BREAK_END, ts=ts, note="auto-close")
elif state == C.LUNCH:
self.store.add_event(C.E_LUNCH_END, ts=ts, note="auto-close")
self.store.add_event(C.E_OUT, ts=ts, note="auto-close")
self.on_change()
self.destroy()
def single_instance_guard():
"""Refuse to start a second copy — two widgets would fight over the log."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(("127.0.0.1", SINGLE_INSTANCE_PORT))
s.listen(1)
except OSError:
root = tk.Tk()
root.withdraw()
messagebox.showinfo("TimeTracker", "TimeTracker is already running.")
root.destroy()
sys.exit(0)
return s # keep the socket alive for the process lifetime
def main():
enable_dpi_awareness()
guard = single_instance_guard() # noqa: F841 (must stay referenced)
store = C.Store()
app = Widget(store)
app.mainloop()
if __name__ == "__main__":
main()