-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3232 lines (2796 loc) · 133 KB
/
Copy pathmain.py
File metadata and controls
3232 lines (2796 loc) · 133 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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import time
import threading
import winreg
import ctypes
import json
import uuid
import re
import winsound
import math
from PIL import Image, ImageDraw
import pystray
import customtkinter as ctk
import tkinter as tk
try:
import pywinstyles
except ImportError:
pywinstyles = None
# Import Windows Runtime notification APIs
import winrt.windows.ui.notifications as win_notify
import winrt.windows.data.xml.dom as win_xml
# Import Windows GUI/Power API bindings for sleep/wake monitoring
import win32gui
import win32con
def calculate_next_alarm(alarm_time_str, repeat_days):
"""
Computes the exact Epoch timestamp for the next alarm trigger.
alarm_time_str: "HH:MM" (e.g. "08:30")
repeat_days: list of ints [1..7] representing ISO weekdays (1 = Monday, 7 = Sunday).
Empty list represents a single (one-off) alarm.
"""
import datetime
now = datetime.datetime.now()
h, m = map(int, alarm_time_str.split(":"))
# Target datetime today
target = now.replace(hour=h, minute=m, second=0, microsecond=0)
if not repeat_days:
# One-off alarm. If it already passed today, schedule for tomorrow.
if target <= now:
target += datetime.timedelta(days=1)
return target.timestamp()
else:
# Recurring alarm. Find the next matching weekday (including today if target is in the future).
for offset in range(8):
candidate = target + datetime.timedelta(days=offset)
cand_weekday = candidate.isoweekday()
if cand_weekday in repeat_days:
if candidate > now:
return candidate.timestamp()
# Fallback
return (target + datetime.timedelta(days=1)).timestamp()
class PowerMonitor:
"""
Listens to native Windows power events (sleep/wake) using a lightweight
message-only window in a dedicated background thread.
"""
def __init__(self, on_resume_callback):
self.on_resume_callback = on_resume_callback
self.hwnd = None
self.thread = threading.Thread(target=self._run, daemon=True, name="PowerMonitorThread")
self.thread.start()
def _run(self):
wc = win32gui.WNDCLASS()
wc.lpfnWndProc = self.wnd_proc
wc.lpszClassName = "NativeLoopTimerPowerMonitor"
wc.hInstance = win32gui.GetModuleHandle(None)
try:
class_atom = win32gui.RegisterClass(wc)
except Exception:
class_atom = wc.lpszClassName
self.hwnd = win32gui.CreateWindowEx(
0,
class_atom,
"PowerMonitorWindow",
0, 0, 0, 0, 0,
win32con.HWND_MESSAGE,
0,
wc.hInstance,
None
)
win32gui.PumpMessages()
def wnd_proc(self, hwnd, msg, wparam, lparam):
if msg == win32con.WM_POWERBROADCAST:
# PBT_APMRESUMESUSPEND = 0x0007, PBT_APMRESUMEAUTOMATIC = 0x0012
if wparam in (0x0007, 0x0012):
print("[PowerMonitor] System wake-up event detected!")
self.on_resume_callback()
return win32gui.DefWindowProc(hwnd, msg, wparam, lparam)
class CTkCircularTimer(tk.Canvas):
def __init__(self, parent, size=280, bg_color="#1E293B", color="#10B981"):
super().__init__(parent, width=size, height=size, bg="#111827", highlightthickness=0)
self.size = size
self.color = color
self.ratio = 1.0
self.is_paused = False
self.time_str = "00:00"
self.bg_color = bg_color
self.draw()
self.animate() # Start continuous wave animation loop
def animate(self):
if self.winfo_exists():
self.draw()
self.after(40, self.animate) # Smooth 25fps fluid rippling
def set_progress(self, ratio, is_paused=False, color=None, time_str="00:00"):
self.ratio = max(0.0, min(1.0, ratio))
self.is_paused = is_paused
if color:
self.color = color
self.time_str = time_str
def draw(self):
import math
self.delete("all")
s = self.size
cx = s / 2
cy = s / 2
# Radii definitions
outer_r = (s / 2) - 15 # Outer ring track
inner_max_r = outer_r - 8 # Wave sphere container
# Setup vibrant color schemes
if self.color == "#10B981": # Green (Active)
fill_color = "#047857"
light_wave = "#10B981"
glow_rgb = (16, 185, 129)
elif self.color == "#F59E0B": # Yellow (Paused)
fill_color = "#78350F"
light_wave = "#FBBF24"
glow_rgb = (245, 158, 11)
elif self.color == "#EF4444": # Red (Stopped / Alert)
fill_color = "#7F1D1D"
light_wave = "#EF4444"
glow_rgb = (239, 68, 68)
else: # Blue (Idle / Target)
fill_color = "#1E3A8A"
light_wave = "#60A5FA"
glow_rgb = (59, 130, 246)
# 1. 🌌 Concentric Ambient Glow (Simulating radial glass glow)
bg_rgb = (17, 24, 39) # #111827 background
for idx, offset in enumerate([18, 10, 4]):
factor = (idx + 1) * 0.055
br = int(bg_rgb[0] + (glow_rgb[0] - bg_rgb[0]) * factor)
bg = int(bg_rgb[1] + (glow_rgb[1] - bg_rgb[1]) * factor)
bb = int(bg_rgb[2] + (glow_rgb[2] - bg_rgb[2]) * factor)
self.create_oval(cx - (outer_r + offset), cy - (outer_r + offset),
cx + (outer_r + offset), cy + (outer_r + offset),
fill=f"#{br:02x}{bg:02x}{bb:02x}", outline="")
# Base container background plate
self.create_oval(cx - outer_r, cy - outer_r, cx + outer_r, cy + outer_r,
fill="#1E293B", outline="")
if self.ratio > 0.0:
# Wave height coordinates based on timer ratio
liquid_h = cy - inner_max_r + (2 * inner_max_r * (1.0 - self.ratio))
left_x = int(cx - inner_max_r)
right_x = int(cx + inner_max_r)
# 2. 🌊 Underlay Wave: Deeper, slower cosine wave for volumetric depth
coords_deep = []
for x in range(left_x, right_x + 1):
x_rel = x - cx
y_boundary = math.sqrt(max(0.0, inner_max_r**2 - x_rel**2))
phase = time.time() * 2.5 # Slower speed
wave_y = 5.0 * math.cos((x_rel / inner_max_r * 2 * math.pi) - phase) + liquid_h + 3.0
clamped_y = max(cy - y_boundary, min(cy + y_boundary, wave_y))
coords_deep.extend([x, clamped_y])
# Close by tracing back along the bottom circular boundary arc
for x in range(right_x, left_x - 1, -1):
x_rel = x - cx
y_boundary = math.sqrt(max(0.0, inner_max_r**2 - x_rel**2))
coords_deep.extend([x, cy + y_boundary])
self.create_polygon(coords_deep, fill=fill_color, outline="")
# 3. 🌊 Overlay Wave: Active, faster sine wave representing foreground fluid
coords_active = []
for x in range(left_x, right_x + 1):
x_rel = x - cx
y_boundary = math.sqrt(max(0.0, inner_max_r**2 - x_rel**2))
phase = time.time() * 4.0 # Faster ripple speed
wave_y = 7.0 * math.sin((x_rel / inner_max_r * 2 * math.pi) + phase) + liquid_h
clamped_y = max(cy - y_boundary, min(cy + y_boundary, wave_y))
coords_active.extend([x, clamped_y])
# Close by tracing back along the bottom circular boundary arc
for x in range(right_x, left_x - 1, -1):
x_rel = x - cx
y_boundary = math.sqrt(max(0.0, inner_max_r**2 - x_rel**2))
coords_active.extend([x, cy + y_boundary])
self.create_polygon(coords_active, fill=light_wave, outline="")
# 4. 🥛 Translucent blurred glass plate overlay (Behind clock text for readability)
plate_r = inner_max_r * 0.72
self.create_oval(cx - plate_r, cy - plate_r, cx + plate_r, cy + plate_r,
fill="#0F172A", outline="#334155", width=1)
# 5. 🟢 Outer Progress Track Ring
self.create_oval(cx - outer_r, cy - outer_r, cx + outer_r, cy + outer_r,
outline="#334155", width=4)
extent = -360.0 * self.ratio
if extent != 0:
self.create_arc(cx - outer_r, cy - outer_r, cx + outer_r, cy + outer_r,
start=90, extent=extent, style="arc", outline=self.color, width=6)
# 6. 💎 VOLUMETRIC GLASS GLOSS SHEENS (Apple Specular Highlights)
# Top Specular crescent highlight
self.create_arc(cx - outer_r + 6, cy - outer_r + 6, cx + outer_r - 6, cy + outer_r - 6,
start=50, extent=80, style="arc", outline="#FFFFFF", width=3.5)
# Top Secondary glare rim
self.create_arc(cx - outer_r + 14, cy - outer_r + 14, cx + outer_r - 14, cy + outer_r - 14,
start=60, extent=60, style="arc", outline="#FFFFFF", width=1.2)
# Bottom Soft Reflective Rim (Ambient bounce reflection matching theme hue)
self.create_arc(cx - outer_r + 8, cy - outer_r + 8, cx + outer_r - 8, cy + outer_r - 8,
start=230, extent=80, style="arc", outline=self.color, width=2.0)
# 7. Countdown time string
font_size = int(s * 0.12)
# Text drop shadow
self.create_text(cx + 2, cy + 2, text=self.time_str, fill="#000000",
font=("Segoe UI", font_size, "bold"))
self.create_text(cx, cy, text=self.time_str, fill="#FFFFFF",
font=("Segoe UI", font_size, "bold"))
class CTkAlarmClock(tk.Canvas):
def __init__(self, parent, size=280, bg_color="#1E293B", clock_color="#10B981"):
super().__init__(parent, width=size, height=size, bg="#111827", highlightthickness=0)
self.size = size
self.clock_color = clock_color
self.is_paused = False
self.draw()
def set_progress(self, ratio, is_paused=False, color=None):
self.is_paused = is_paused
if color:
self.clock_color = color
self.draw()
def draw(self):
import math
self.delete("all")
s = self.size
cx = s / 2
cy = s / 2
r = (s / 2) - 30
# Determine color states
accent_color = self.clock_color
glow_color = "#10B981" if self.clock_color == "#10B981" else ("#F59E0B" if self.clock_color == "#F59E0B" else "#EF4444")
# 1. Background radial glow
bg_rgb = (17, 24, 39)
glow_rgb = (16, 185, 129) if self.clock_color == "#10B981" else ((245, 158, 11) if self.clock_color == "#F59E0B" else (239, 68, 68))
for idx, offset in enumerate([18, 10, 4]):
factor = (idx + 1) * 0.05
br = int(bg_rgb[0] + (glow_rgb[0] - bg_rgb[0]) * factor)
bg = int(bg_rgb[1] + (glow_rgb[1] - bg_rgb[1]) * factor)
bb = int(bg_rgb[2] + (glow_rgb[2] - bg_rgb[2]) * factor)
self.create_oval(cx - (r + offset), cy - (r + offset),
cx + (r + offset), cy + (r + offset),
fill=f"#{br:02x}{bg:02x}{bb:02x}", outline="")
# Alarm legs / feet
self.create_line(cx - r + 20, cy + r - 5, cx - r - 15, cy + r + 25, fill="#64748B", width=12, capstyle="round")
self.create_line(cx + r - 20, cy + r - 5, cx + r + 15, cy + r + 25, fill="#64748B", width=12, capstyle="round")
# Twin bells at top
bell_r = 25
self.create_oval(cx - r - 5, cy - r - 5, cx - r + 35, cy - r + 35, fill="#475569", outline="#64748B", width=2)
self.create_oval(cx + r - 35, cy - r - 5, cx + r + 5, cy - r + 35, fill="#475569", outline="#64748B", width=2)
# Clock body base
self.create_oval(cx - r, cy - r, cx + r, cy + r, fill="#1E293B", outline="#334155", width=4)
# Clock face plate
plate_r = r - 12
self.create_oval(cx - plate_r, cy - plate_r, cx + plate_r, cy + plate_r, fill="#0F172A", outline="")
# Clock hour hands (10:10 format)
hx = cx + (plate_r * 0.45) * math.cos(math.radians(-120))
hy = cy + (plate_r * 0.45) * math.sin(math.radians(-120))
self.create_line(cx, cy, hx, hy, fill=accent_color, width=8, capstyle="round")
# Clock minute hand
mx = cx + (plate_r * 0.70) * math.cos(math.radians(-30))
my = cy + (plate_r * 0.70) * math.sin(math.radians(-30))
self.create_line(cx, cy, mx, my, fill=accent_color, width=5, capstyle="round")
# Volumetric Glass Sheen layers
self.create_arc(cx - plate_r + 6, cy - plate_r + 6, cx + plate_r - 6, cy + plate_r - 6,
start=50, extent=80, style="arc", outline="#FFFFFF", width=3.0)
self.create_arc(cx - plate_r + 8, cy - plate_r + 8, cx + plate_r - 8, cy + plate_r - 8,
start=230, extent=80, style="arc", outline=accent_color, width=2.0)
# Center dot pin
self.create_oval(cx - 6, cy - 6, cx + 6, cy + 6, fill=accent_color, outline="")
class CTkToolTip:
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tooltip_window = None
self.widget.bind("<Enter>", self.show_tooltip)
self.widget.bind("<Leave>", self.hide_tooltip)
def show_tooltip(self, event=None):
if self.tooltip_window:
return
t = self.text() if callable(self.text) else self.text
if not t:
return
# Get widget screen coordinates
x = self.widget.winfo_rootx() + (self.widget.winfo_width() // 2) - 40
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 5
self.tooltip_window = tk.Toplevel(self.widget)
self.tooltip_window.wm_overrideredirect(True) # Remove window borders
self.tooltip_window.wm_geometry(f"+{x}+{y}")
self.tooltip_window.attributes("-topmost", True)
self.tooltip_window.configure(bg="#1E293B") # Dark slate
label = tk.Label(
self.tooltip_window,
text=t,
justify="left",
background="#1E293B",
foreground="#F3F4F6",
font=("Segoe UI", 9, "bold"),
padx=6,
pady=3,
highlightthickness=1,
highlightbackground="#4B5563" # Sleek border
)
label.pack()
def hide_tooltip(self, event=None):
if self.tooltip_window:
self.tooltip_window.destroy()
self.tooltip_window = None
class CTkFolderIcon(tk.Canvas):
def __init__(self, parent, size=32, bg_color="#1E293B", folder_color="#D1FAE5"):
super().__init__(parent, width=size, height=size, bg=bg_color, highlightthickness=0)
self.size = size
self.folder_color = folder_color
self.bg_color = bg_color
self.draw()
def set_color(self, folder_color):
self.folder_color = folder_color
self.draw()
def draw(self):
self.delete("all")
s = self.size
# 1. Draw Folder Tab
self.create_polygon(
[s*0.1, s*0.25,
s*0.45, s*0.25,
s*0.55, s*0.4,
s*0.1, s*0.4],
fill=self.folder_color, outline=""
)
# 2. Draw Rounded Folder Body
r = s * 0.1
self.create_rectangle(s*0.1, s*0.35+r, s*0.9, s*0.85-r, fill=self.folder_color, outline="")
self.create_rectangle(s*0.1+r, s*0.35, s*0.9-r, s*0.85, fill=self.folder_color, outline="")
self.create_oval(s*0.1, s*0.35, s*0.1+2*r, s*0.35+2*r, fill=self.folder_color, outline="")
self.create_oval(s*0.9-2*r, s*0.35, s*0.9, s*0.35+2*r, fill=self.folder_color, outline="")
self.create_oval(s*0.1, s*0.85-2*r, s*0.1+2*r, s*0.85, fill=self.folder_color, outline="")
self.create_oval(s*0.9-2*r, s*0.85-2*r, s*0.9, s*0.85, fill=self.folder_color, outline="")
class PiPWindow(ctk.CTkToplevel):
def __init__(self, parent_app):
super().__init__(parent_app.root)
self.app = parent_app
# Window setup
self.title(self.app.loc[self.app.current_lang].get("pip_title", "PiP Mode"))
self.overrideredirect(True) # Borderless
self.attributes("-topmost", True) # Always on top
self.attributes("-alpha", 0.85) # Transparent
# Background color matching our dark aesthetic
self.configure(fg_color="#1E293B")
# Apply Apple-like Frosted Glass "Liquid Glass" theme to PiP window if pywinstyles is available
if pywinstyles:
try:
pywinstyles.apply_style(self, "acrylic")
except Exception:
pass
# Position in bottom-right corner of screen
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
x = screen_width - 220
y = screen_height - 120
self.geometry(f"200x70+{x}+{y}")
# Drag bindings
self._drag_data = (0, 0)
self.bind("<Button-1>", self.start_drag)
self.bind("<B1-Motion>", self.on_drag)
# Main layout frame
self.content_frame = ctk.CTkFrame(self, fg_color="transparent")
self.content_frame.pack(fill="both", expand=True, padx=8, pady=6)
# Top half: Task name & Icon
self.task_label = ctk.CTkLabel(
self.content_frame,
text=self.app.loc[self.app.current_lang].get("pip_no_task", "No active task"),
font=ctk.CTkFont(family="Segoe UI", size=11, weight="bold"),
text_color="#E5E7EB",
anchor="w"
)
self.task_label.pack(side="top", anchor="w", fill="x")
# Bottom half: Timer countdown and Controls row
self.bottom_row = ctk.CTkFrame(self.content_frame, fg_color="transparent")
self.bottom_row.pack(side="top", fill="x", pady=(2, 0))
self.time_label = ctk.CTkLabel(
self.bottom_row,
text="00:00",
font=ctk.CTkFont(family="Segoe UI", size=18, weight="bold"),
text_color="#10B981",
anchor="w"
)
self.time_label.pack(side="left", anchor="w")
# Action buttons on the right side of the bottom row
btn_frame = ctk.CTkFrame(self.bottom_row, fg_color="transparent")
btn_frame.pack(side="right", fill="y")
self.play_btn = ctk.CTkButton(
btn_frame,
text="⏸",
width=22,
height=22,
fg_color="#374151",
hover_color="#4B5563",
corner_radius=4,
font=("Segoe UI", 10),
command=self.toggle_active_task
)
self.play_btn.pack(side="left", padx=2)
self.reset_btn = ctk.CTkButton(
btn_frame,
text="🔄",
width=22,
height=22,
fg_color="#374151",
hover_color="#4B5563",
corner_radius=4,
font=("Segoe UI", 10),
command=self.reset_active_task
)
self.reset_btn.pack(side="left", padx=2)
self.unpin_btn = ctk.CTkButton(
btn_frame,
text="↩",
width=22,
height=22,
fg_color="#374151",
hover_color="#60A5FA",
text_color="#60A5FA",
corner_radius=4,
font=("Segoe UI", 10, "bold"),
command=self.close_pip
)
self.unpin_btn.pack(side="left", padx=2)
# Start update cycle
self.update_pip()
def start_drag(self, event):
self._drag_data = (event.x_root, event.y_root)
def on_drag(self, event):
delta_x = event.x_root - self._drag_data[0]
delta_y = event.y_root - self._drag_data[1]
x = self.winfo_x() + delta_x
y = self.winfo_y() + delta_y
self.geometry(f"+{x}+{y}")
self._drag_data = (event.x_root, event.y_root)
def get_active_task(self):
with self.app.lock:
if not self.app.tasks:
return None
for t in self.app.tasks:
if t["type"] == "timer" and not t["is_paused"]:
return t
for t in self.app.tasks:
if t["type"] == "alarm" and not t["is_paused"]:
return t
for t in self.app.tasks:
if t["type"] == "timer" and t["is_paused"]:
return t
for t in self.app.tasks:
if t["type"] == "alarm" and t["is_paused"]:
return t
return self.app.tasks[0]
def update_pip(self):
if not self.winfo_exists():
return
task = self.get_active_task()
lang = self.app.current_lang
if not task:
self.task_label.configure(text=self.app.loc[lang]["empty_list"][:18])
self.time_label.configure(text="--:--", text_color="#9CA3AF")
self.play_btn.configure(state="disabled")
self.reset_btn.configure(state="disabled")
else:
self.play_btn.configure(state="normal")
self.reset_btn.configure(state="normal")
icon = "⏳" if task["type"] == "timer" else "⏰"
name = task["name"]
if len(name) > 10:
name = name[:8] + "..."
self.task_label.configure(text=f"{icon} {name}")
btn_text = "⏸" if not task["is_paused"] else "▶"
btn_fg = "#374151" if not task["is_paused"] else "#10B981"
self.play_btn.configure(text=btn_text, fg_color=btn_fg)
curr = time.time()
if task["is_paused"]:
if task["type"] == "timer":
rem = task["remaining_seconds"]
rem_min = int(rem // 60)
rem_sec = int(rem % 60)
self.time_label.configure(text=f"{rem_min:02d}:{rem_sec:02d}", text_color="#F59E0B")
else:
self.time_label.configure(text=self.app.loc[lang]["status_paused"][:6], text_color="#F59E0B")
else:
if task["type"] == "timer":
remaining = task["target_time"] - curr
if remaining < 0:
remaining = 0
rem_min = int(remaining // 60)
rem_sec = int(remaining % 60)
self.time_label.configure(text=f"{rem_min:02d}:{rem_sec:02d}", text_color="#10B981" if remaining >= 60.0 else "#EF4444")
else:
self.time_label.configure(text=task["alarm_time"], text_color="#10B981")
self.after(500, self.update_pip)
def toggle_active_task(self):
task = self.get_active_task()
if task:
self.app.toggle_task(task["id"])
def reset_active_task(self):
task = self.get_active_task()
if task:
self.app.reset_task(task["id"])
def close_pip(self):
self.app.pip_window = None
self.destroy()
self.app.show_window()
class TimerApp:
def __init__(self, config_dir=None):
# Default state
self.tasks = []
self.is_running = True
self.timer_thread = None
self.status_loop_active = False
self.lock = threading.Lock()
self.root = None
self.tray_icon = None
# UI task tracking to update text in real-time without flickering
self.task_labels = {}
self.task_status_badges = {}
self.task_progress_bars = {}
self.task_hourglasses = {}
self.task_card_widgets = {}
self.pip_window = None
self.current_folder = None
# Paths
self.app_dir = os.path.dirname(os.path.abspath(sys.argv[0] if getattr(sys, 'frozen', False) else __file__))
self.ico_path = os.path.join(self.app_dir, "app_icon.ico")
self.png_path = os.path.join(self.app_dir, "app_icon.png")
# Determine config directory (independent of app_dir for robustness)
if config_dir:
self.config_dir = config_dir
else:
appdata_dir = os.environ.get("APPDATA")
if appdata_dir:
self.config_dir = os.path.join(appdata_dir, "NativeLoopTimer")
else:
self.config_dir = self.app_dir
os.makedirs(self.config_dir, exist_ok=True)
# Migrate old local config.json if it exists and appdata config does not exist yet
local_config = os.path.join(self.app_dir, "config.json")
appdata_config = os.path.join(self.config_dir, "config.json")
if not config_dir and os.path.exists(local_config) and not os.path.exists(appdata_config):
try:
import shutil
shutil.copy2(local_config, appdata_config)
except Exception:
pass
# Localization data
self.loc = {
"zh": {
"title": "⏰ 多任务原生定时中心",
"subtitle": "独立多任务并发 · 暂停/恢复管理 · 系统级防丢自唤醒",
"tab_timer": "⏳ 定时器",
"tab_alarm": "⏰ 闹钟",
"timer_duration": "倒计时时间 (分钟):",
"timer_placeholder": "输入分钟数 (如 20 或 0.5)",
"timer_loop": "触发后自动循环计时",
"alarm_time": "闹钟时间:",
"alarm_hour_placeholder": "时",
"alarm_minute_placeholder": "分",
"repeat_cycle": "重复周期 (不勾选为单次):",
"everyday": "每天 (一至日)",
"weekdays": ["一", "二", "三", "四", "五", "六", "日"],
"msg_label": "提醒显示内容:",
"msg_placeholder": "输入 Toast 通知要显示的文本内容",
"msg_default": "时间到了!请起来活动一下,喝杯水休息一会吧!",
"add_task": "➕ 添加并启动新任务",
"add_task_short": "➕ 启动",
"pause_all": "⏸ 暂停全部",
"resume_all": "▶ 恢复全部",
"list_title": "⏳ 当前活动任务与闹钟列表",
"empty_list": "暂无运行中的定时任务,请在上方添加!",
"error_msg_empty": "❌ 请输入提醒内容!",
"sound_label": "🔔 响铃提示音选择:",
"error_timer_invalid": "❌ 循环时间必须是大于 0 的数字!",
"error_alarm_invalid": "❌ 闹钟时间格式无效!在小时 and 分钟框输入数字即可!",
"success_add": "✓ 任务添加并启动成功!",
"status_waiting": "等待中...",
"status_paused": "已暂停",
"status_paused_rem": "暂停 (余 {min}分{sec}秒)",
"status_rem": "剩余: {min}分{sec}秒",
"status_target": "目标: {time}{repeat}",
"repeat_everyday": " (每天)",
"repeat_weekdays": " (工作日)",
"repeat_weekends": " (周末)",
"repeat_days_fmt": " (周{days})",
"repeat_oneoff": " (单次)",
"toast_title_single": "定时中心提醒",
"toast_title_multi": "错过了 {count} 个提醒",
"tray_show": "显示设置 (Settings)",
"tray_pause": "全局暂停所有 (Pause All)",
"tray_resume": "全局恢复所有 (Resume All)",
"tray_exit": "退出 (Exit)",
"tray_title": "多任务原生定时中心",
"pip_title": "画中画模式",
"pip_no_task": "暂无活动任务",
"edit_task_title": "编辑任务设置",
"edit_task_header": "✏️ 修改任务配置",
"dialog_cancel": "取消",
"dialog_save": "保存",
"set_timer_display": "设定: {dur}分钟",
"set_alarm_display": "设定: {time}",
"group_label": "选择或输入分组 (Group Name):",
"group_combobox_placeholder": "输入或选择分组名称",
"group_default": "默认",
"filter_all": "全部显示 (Show All)",
"group_filter_label": "分组过滤:",
"folder_title": "文件夹",
"folder_back": "返回",
"folder_tasks_count": "{count} 个任务",
"rename_group_title": "重命名分组",
"rename_group_header": "✏️ 输入新的分组名称",
"rename_group_label": "分组名称:",
"tip_play": "播放/恢复",
"tip_pause": "暂停",
"tip_reset": "重置",
"tip_edit": "编辑任务",
"tip_delete": "删除任务",
"tip_rename": "重命名分组",
"tip_back": "返回",
"tip_drag": "长按并拖拽以排序",
"tip_lang": "切换语言 (Toggle Language)",
"tip_pip": "画中画模式 (PiP Mode)",
"view_all_tasks": "🔍 查看全部任务",
"all_tasks_title": "全部任务",
"tip_view_all": "查看所有分组的任务"
},
"en": {
"title": "⏰ Multi-Task Native Timer Center",
"subtitle": "Independent Concurrency · Pause/Resume Management · Wake-up Protection",
"tab_timer": "⏳ Timer",
"tab_alarm": "⏰ Alarm",
"timer_duration": "Countdown Duration (Minutes):",
"timer_placeholder": "Enter minutes (e.g. 20 or 0.5)",
"timer_loop": "Auto-loop timing after trigger",
"alarm_time": "Alarm Time:",
"alarm_hour_placeholder": "Hr",
"alarm_minute_placeholder": "Min",
"repeat_cycle": "Repeat Cycle (One-off if unchecked):",
"everyday": "Everyday (Mon-Sun)",
"weekdays": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
"msg_label": "Alert Message Content:",
"msg_placeholder": "Enter text to display in Toast notification",
"msg_default": "Time's up! Please get up, stretch, drink some water and take a break!",
"add_task": "➕ Add and Start New Task",
"add_task_short": "➕ Start",
"pause_all": "⏸ Pause All",
"resume_all": "▶ Resume All",
"list_title": "⏳ Active Tasks & Alarms List",
"empty_list": "No active tasks. Add a new one above!",
"error_msg_empty": "❌ Please enter the alert message!",
"sound_label": "🔔 Alert Sound Selector:",
"error_timer_invalid": "❌ Countdown duration must be a number greater than 0!",
"error_alarm_invalid": "❌ Invalid alarm time format! Just enter numbers in the hour and minute boxes!",
"success_add": "✓ Task added and started successfully!",
"status_waiting": "Waiting...",
"status_paused": "Paused",
"status_paused_rem": "Paused ({min}m {sec}s left)",
"status_rem": "Remaining: {min}m {sec}s",
"status_target": "Target: {time}{repeat}",
"repeat_everyday": " (Everyday)",
"repeat_weekdays": " (Weekdays)",
"repeat_weekends": " (Weekends)",
"repeat_days_fmt": " ({days})",
"repeat_oneoff": " (One-off)",
"toast_title_single": "Timer Center Reminder",
"toast_title_multi": "Missed {count} reminders",
"tray_show": "Show Settings",
"tray_pause": "Pause All Tasks",
"tray_resume": "Resume All Tasks",
"tray_exit": "Exit",
"tray_title": "Multi-Task Native Timer Center",
"pip_title": "PiP Mode",
"pip_no_task": "No active task",
"edit_task_title": "Edit Task Settings",
"edit_task_header": "✏️ Edit Task Configuration",
"dialog_cancel": "Cancel",
"dialog_save": "Save",
"set_timer_display": "Set: {dur} min",
"set_alarm_display": "Set: {time}",
"group_label": "Select or Enter Group Name:",
"group_combobox_placeholder": "Enter or select group",
"group_default": "Default",
"filter_all": "Show All",
"group_filter_label": "Group Filter:",
"folder_title": "Folders",
"folder_back": "Back",
"folder_tasks_count": "{count} tasks",
"rename_group_title": "Rename Group",
"rename_group_header": "✏️ Enter New Group Name",
"rename_group_label": "Group Name:",
"tip_play": "Play/Resume",
"tip_pause": "Pause",
"tip_reset": "Reset",
"tip_edit": "Edit Task",
"tip_delete": "Delete Task",
"tip_rename": "Rename Group",
"tip_back": "Back",
"tip_drag": "Hold and drag to sort",
"tip_lang": "Toggle Language",
"tip_pip": "PiP Mode",
"view_all_tasks": "🔍 View All Tasks",
"all_tasks_title": "All Tasks",
"tip_view_all": "View tasks from all groups"
}
}
self.current_lang = "zh"
# Bilingual sound selections mapped to high-quality Windows pre-installed media chimes
self.sound_options = {
"zh": {
"🔔 温馨叮咚 (Warm Ding)": "C:/Windows/Media/ding.wav",
"🔔 晨光风铃 (Morning Chimes)": "C:/Windows/Media/chimes.wav",
"🔔 静谧和弦 (Serene Chord)": "C:/Windows/Media/chord.wav",
"🔔 凯旋之声 (Tada Fanfare)": "C:/Windows/Media/tada.wav",
"🔔 电子警报 (Digital Alarm)": "C:/Windows/Media/Alarm03.wav",
"🔔 系统默认 (System Default)": "C:/Windows/Media/Windows Default.wav"
},
"en": {
"🔔 Warm Ding": "C:/Windows/Media/ding.wav",
"🔔 Morning Chimes": "C:/Windows/Media/chimes.wav",
"🔔 Serene Chord": "C:/Windows/Media/chord.wav",
"🔔 Tada Fanfare": "C:/Windows/Media/tada.wav",
"🔔 Digital Alarm": "C:/Windows/Media/Alarm03.wav",
"🔔 System Default": "C:/Windows/Media/Windows Default.wav"
}
}
# Initialize
self.app_id = "NativeLoopTimer"
self.register_app_id()
self.ensure_assets()
# Load tasks and language choice from config.json
self.tasks = self.load_config()
self.check_and_compensate_missed_tasks(time.time())
# Start power monitor
self.power_monitor = PowerMonitor(self.on_system_wake)
# Start timer scheduler thread
self.timer_thread = threading.Thread(target=self.timer_loop, daemon=True, name="SchedulerThread")
self.timer_thread.start()
def register_app_id(self):
"""Register the application under HKCU to authorize Toast notifications."""
path = rf"Software\Classes\AppUserModelId\{self.app_id}"
try:
key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, path)
winreg.SetValueEx(key, "DisplayName", 0, winreg.REG_SZ, "多任务原生定时中心 (NativeLoopTimer)")
winreg.CloseKey(key)
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(self.app_id)
print("[TimerApp] AppUserModelID successfully registered.")
except Exception as e:
print(f"[TimerApp] Warning registering AUMID: {e}")
def ensure_assets(self):
"""Programmatically generate a beautiful, modern multi-resolution icon."""
if not os.path.exists(self.ico_path) or not os.path.exists(self.png_path):
print("[TimerApp] Generating high-quality icon assets...")
size = 256
img = Image.new("RGBA", (size, size), color=(0, 0, 0, 0))
draw = ImageDraw.Draw(img)
# Draw premium dark gradient background
for r in range(120, 0, -1):
factor = r / 120.0
color_r = int(20 * factor + 54 * (1.0 - factor))
color_g = int(24 * factor + 86 * (1.0 - factor))
color_b = int(72 * factor + 224 * (1.0 - factor))
draw.ellipse([128 - r, 128 - r, 128 + r, 128 + r], fill=(color_r, color_g, color_b, 255))
# Draw elegant clock arc ring
draw.arc([48, 48, 208, 208], start=0, end=360, fill=(255, 255, 255, 210), width=10)
# Draw minimal clock hands (10:10 format)
draw.line([128, 128, 85, 85], fill=(255, 255, 255, 240), width=8) # Hour hand
draw.line([128, 128, 175, 85], fill=(255, 80, 100, 255), width=6) # Accent minute hand
draw.ellipse([120, 120, 136, 136], fill=(255, 255, 255, 255))
img.save(self.png_path, format="PNG")
img.save(self.ico_path, format="ICO", sizes=[(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)])
self.icon_img = Image.open(self.png_path)
def load_config(self):
"""Loads and normalizes task profiles from config.json."""
config_path = os.path.join(self.config_dir, "config.json")
if not os.path.exists(config_path):
self.current_lang = "zh"
return []
try:
with open(config_path, "r", encoding="utf-8") as f:
data = json.load(f)
tasks = data.get("tasks", [])
self.current_lang = data.get("language", "zh")
if self.current_lang not in ("zh", "en"):
self.current_lang = "zh"
# Normalize types to prevent JSON schema compatibility issues
for task in tasks:
task["is_paused"] = bool(task.get("is_paused", False))
task["sound_path"] = str(task.get("sound_path", "C:/Windows/Media/Windows Default.wav"))
task["group"] = str(task.get("group", self.loc[self.current_lang]["group_default"]))
task["order"] = float(task.get("order", float(task.get("created_at", time.time()))))
if task["type"] == "timer":
task["duration_minutes"] = float(task.get("duration_minutes", 20.0))
task["is_auto_loop"] = bool(task.get("is_auto_loop", True))
task["target_time"] = float(task.get("target_time", 0.0))
task["remaining_seconds"] = float(task.get("remaining_seconds", 0.0))
elif task["type"] == "alarm":
task["alarm_time"] = str(task.get("alarm_time", "08:30"))
task["repeat_days"] = [int(x) for x in task.get("repeat_days", [])]
task["target_time"] = float(task.get("target_time", 0.0))
return tasks
except Exception as e:
print(f"[TimerApp] Error loading config: {e}")
self.current_lang = "zh"
return []
def save_config(self):
"""Saves current memory task configurations into local config.json."""
config_path = os.path.join(self.config_dir, "config.json")
try:
with open(config_path, "w", encoding="utf-8") as f:
json.dump({"tasks": self.tasks, "language": self.current_lang}, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"[TimerApp] Error saving config: {e}")
def trigger_merged_notification(self, missed_tasks):
"""Pushes a single native Toast displaying all missed alerts in one visual card."""
if not missed_tasks:
return
try:
lang = self.current_lang
if len(missed_tasks) == 1:
title = self.loc[lang]["toast_title_single"]
message = missed_tasks[0]["name"]
else:
title = self.loc[lang]["toast_title_multi"].format(count=len(missed_tasks))
message = "\n".join([f"• {t['name']}" for t in missed_tasks])
xml_str = f"""
<toast duration="short">
<visual>
<binding template="ToastGeneric">
<text>{title}</text>
<text>{message}</text>
<image placement="appLogoOverride" hint-crop="circle" src="file:///{self.png_path.replace(chr(92), '/')}"/>
</binding>
</visual>
<audio silent="true"/>
</toast>
"""
xml_doc = win_xml.XmlDocument()
xml_doc.load_xml(xml_str)
notifier = win_notify.ToastNotificationManager.create_toast_notifier_with_id(self.app_id)
toast = win_notify.ToastNotification(xml_doc)
notifier.show(toast)
print(f"[TimerApp] Toast delivered: '{title}' - '{message}'")
# Asynchronously play the sound associated with the first missed task
first_task = missed_tasks[0]
sound_filepath = first_task.get("sound_path", "C:/Windows/Media/Windows Default.wav")
try:
if os.path.exists(sound_filepath):
winsound.PlaySound(sound_filepath, winsound.SND_FILENAME | winsound.SND_ASYNC)
else:
winsound.PlaySound("SystemAsterisk", winsound.SND_ALIAS | winsound.SND_ASYNC)
except Exception as se:
print(f"[TimerApp] Audio stream warning: {se}")
except Exception as e:
print(f"[TimerApp] Error sending notification: {e}")
def check_and_compensate_missed_tasks(self, curr_time):
"""Checks for expired tasks during sleep or shutdown and delivers a combined Toast."""
missed_tasks = []
with self.lock:
for task in self.tasks:
if task["is_paused"]:
continue
if curr_time >= task["target_time"]:
missed_tasks.append(task)
# Recalculate and reschedule targets
if task["type"] == "timer":
if task["is_auto_loop"]:
task["target_time"] = curr_time + (task["duration_minutes"] * 60.0)
else:
task["is_paused"] = True
elif task["type"] == "alarm":