persian-clock-widget 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/widget.py ADDED
@@ -0,0 +1,3570 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ ویجت حرفه‌ای ساعت تهران، تقویم شمسی، مناسبت‌ها، ابزار کپی زمان برنامه‌نویسی (۱۰ فرمت API + تولیدکننده GUID) و سیستم آلارم/رویداد
4
+ طراحی و توسعه: شایان بامیار (® Shayan Bamyar)
5
+ """
6
+
7
+ from datetime import datetime, timezone
8
+ import json
9
+ import os
10
+ import sys
11
+ import time
12
+ import tkinter as tk
13
+ from tkinter import colorchooser, font as tkfont, ttk
14
+ import uuid
15
+
16
+ try:
17
+ from src.alarm_manager import (
18
+ AlarmManagerWindow,
19
+ AlarmStore,
20
+ AnimatedBellPopup,
21
+ draw_outlined_canvas_text,
22
+ )
23
+ from src.calendar_data import (
24
+ PERSIAN_MONTHS,
25
+ PERSIAN_WEEK_SHORT,
26
+ TEHRAN_TZ,
27
+ get_jalali_month_days,
28
+ get_month_calendar,
29
+ get_today_info,
30
+ gregorian_to_jalali,
31
+ )
32
+ from src.win_utils import (
33
+ SystemTrayIcon,
34
+ apply_rounded_corners,
35
+ apply_z_order_and_clickthrough,
36
+ enable_dpi_awareness,
37
+ get_data_dir,
38
+ get_monitor_work_area_at,
39
+ get_resource_path,
40
+ hide_from_taskbar,
41
+ is_startup_enabled,
42
+ register_bundled_fonts,
43
+ set_startup_enabled,
44
+ )
45
+ from src.taskbar_clock import (
46
+ TaskbarButtonProxy,
47
+ TaskbarClockOverlay,
48
+ WindowsClockReplacer,
49
+ get_windows11_tray_clock_hidden,
50
+ set_windows11_tray_clock_hidden,
51
+ )
52
+ except ImportError:
53
+ from alarm_manager import (
54
+ AlarmManagerWindow,
55
+ AlarmStore,
56
+ AnimatedBellPopup,
57
+ draw_outlined_canvas_text,
58
+ )
59
+ from calendar_data import (
60
+ PERSIAN_MONTHS,
61
+ PERSIAN_WEEK_SHORT,
62
+ TEHRAN_TZ,
63
+ get_jalali_month_days,
64
+ get_month_calendar,
65
+ get_today_info,
66
+ gregorian_to_jalali,
67
+ )
68
+ from win_utils import (
69
+ SystemTrayIcon,
70
+ apply_rounded_corners,
71
+ apply_z_order_and_clickthrough,
72
+ enable_dpi_awareness,
73
+ get_data_dir,
74
+ get_monitor_work_area_at,
75
+ get_resource_path,
76
+ hide_from_taskbar,
77
+ is_startup_enabled,
78
+ register_bundled_fonts,
79
+ set_startup_enabled,
80
+ )
81
+ from taskbar_clock import (
82
+ TaskbarButtonProxy,
83
+ TaskbarClockOverlay,
84
+ WindowsClockReplacer,
85
+ get_windows11_tray_clock_hidden,
86
+ set_windows11_tray_clock_hidden,
87
+ )
88
+
89
+ DATA_DIR = get_data_dir()
90
+ CONFIG_PATH = os.path.join(DATA_DIR, "config.json")
91
+ CUSTOM_OCCASIONS_PATH = os.path.join(DATA_DIR, "custom_occasions.json")
92
+ ALARMS_PATH = os.path.join(DATA_DIR, "alarms.json")
93
+
94
+ TRANSPARENT_KEY = "#010203"
95
+
96
+ DEFAULT_CONFIG = {
97
+ "x": None,
98
+ "y": None,
99
+ "locked": False, # False = آزاد (🔓) | True = فیکس و Click-Through (🔒)
100
+ "z_mode": "topmost", # 'topmost' (همیشه روی برنامه‌ها) یا 'desktop' (چسبیده به دسکتاپ)
101
+ "opacity": 0.90,
102
+ "transparent_bg": False,
103
+ "persian_digits": False,
104
+ "calendar_expanded": False,
105
+ "calendar_position": "beside",
106
+ # تنظیمات رنگ‌ها
107
+ "bg_color": "#141821",
108
+ "border_color": "#2A3244",
109
+ "clock_color": "#F8FAFC",
110
+ "date_color": "#CBD5E1",
111
+ "occasion_color": "#94A3B8",
112
+ "holiday_color": "#F87171",
113
+ "accent_color": "#38BDF8",
114
+ # تنظیمات سایز ویجت و فونت‌ها (با پیش‌فرض فونت وزیر Vazir)
115
+ "widget_scale": 100,
116
+ "font_family": "Vazir",
117
+ "clock_font_family": "Vazir",
118
+ "clock_font_size": 26,
119
+ "date_font_size": 11,
120
+ "occasion_font_size": 9,
121
+ # نمایش و جایگزینی در تسک‌بار ویندوز
122
+ "replace_windows_clock": False, # ⭐ جایگزینی کامل و پوشاندن ساعت پیش‌فرض ویندوز
123
+ "replace_clock_hide_widget": False, # مخفی کردن ویجت دسکتاپ هنگام فعال بودن جایگزین
124
+ "replace_clock_width": 118, # عرض باکس پوشش‌دهنده ساعت ویندوز
125
+ "replace_clock_offset": 8, # فاصله از گوشه راست تسک‌بار
126
+ "replace_clock_bg": "auto", # تشخیص خودکار رنگ تسک‌بار ویندوز (یا رنگ دلخواه)
127
+ "taskbar_clock": False, # نمایش ساعت و تاریخ شمسی روی خود نوار تسک‌بار (شناور)
128
+ "taskbar_clock_seconds": False, # نمایش ثانیه در ساعت تسک‌بار
129
+ "taskbar_clock_offset": None, # مکان ذخیره‌شده ساعت روی تسک‌بار (فاصله از لبه راست)
130
+ "taskbar_button": False, # نمایش دکمه/آیکون برنامه در تسک‌بار
131
+ "snap_side": "right", # جهت چسبیدن به لبه صفحه در حالت قفل ('right' یا 'left')
132
+ "primary_timezone": "tehran", # 'tehran' یا 'utc' (تایم اصلی ویجت بدون نمایش +03:30)
133
+ "show_utc": False, # نمایش ردیف مجزای ساعت و تاریخ UTC در ویجت برای برنامه‌نویسان
134
+ }
135
+
136
+
137
+ def format_digits(text: str, use_persian: bool) -> str:
138
+ """تبدیل اعداد انگلیسی به فارسی در صورت فعال بودن گزینه مربوطه"""
139
+ if not use_persian:
140
+ return str(text)
141
+ en = "0123456789"
142
+ fa = "۰۱۲۳۴۵۶۷۸۹"
143
+ return str(text).translate(str.maketrans(en, fa))
144
+
145
+
146
+ class HoverTooltip:
147
+ """
148
+ افکت Hover فوری و نمایش Tooltip شناور همیشه در بالاترین لایه (Topmost)
149
+ هنگام نگه داشتن ماوس روی آیکون‌ها
150
+ """
151
+
152
+ def __init__(
153
+ self,
154
+ widget: tk.Widget,
155
+ text_or_fn,
156
+ base_bg_fn,
157
+ base_fg_fn,
158
+ hover_bg: str = "#0284C7",
159
+ hover_fg: str = "#FFFFFF",
160
+ font_family: str = "Vazir",
161
+ ):
162
+ self.widget = widget
163
+ self.text_or_fn = text_or_fn
164
+ self.base_bg_fn = base_bg_fn
165
+ self.base_fg_fn = base_fg_fn
166
+ self.hover_bg = hover_bg
167
+ self.hover_fg = hover_fg
168
+ self.font_family = font_family
169
+ self.tip_win: tk.Toplevel | None = None
170
+ self._after_id: str | None = None
171
+ self.is_hovered = False
172
+
173
+ self.widget.bind("<Enter>", self._on_enter, add="+")
174
+ self.widget.bind("<Leave>", self._on_leave, add="+")
175
+ self.widget.bind("<ButtonPress>", self._on_press, add="+")
176
+
177
+ def _on_enter(self, event=None):
178
+ self.is_hovered = True
179
+ try:
180
+ self.widget.configure(bg=self.hover_bg, fg=self.hover_fg)
181
+ except Exception:
182
+ pass
183
+ self._cancel_timer()
184
+ self._after_id = self.widget.after(90, self._show_tip)
185
+
186
+ def _on_leave(self, event=None):
187
+ self.is_hovered = False
188
+ self._cancel_timer()
189
+ try:
190
+ self.widget.configure(bg=self.base_bg_fn(), fg=self.base_fg_fn())
191
+ except Exception:
192
+ pass
193
+ self._hide_tip()
194
+
195
+ def _on_press(self, event=None):
196
+ self._cancel_timer()
197
+ self._hide_tip()
198
+
199
+ def _cancel_timer(self):
200
+ if self._after_id is not None:
201
+ try:
202
+ self.widget.after_cancel(self._after_id)
203
+ except Exception:
204
+ pass
205
+ self._after_id = None
206
+
207
+ def _show_tip(self):
208
+ if not self.is_hovered or self.tip_win is not None:
209
+ return
210
+ txt = self.text_or_fn() if callable(self.text_or_fn) else str(self.text_or_fn)
211
+ if not txt:
212
+ return
213
+ try:
214
+ wx = self.widget.winfo_rootx()
215
+ wy = self.widget.winfo_rooty()
216
+ wh = self.widget.winfo_height()
217
+
218
+ win = tk.Toplevel(self.widget)
219
+ self.tip_win = win
220
+ win.overrideredirect(True)
221
+ win.attributes("-topmost", True)
222
+ win.configure(bg="#0F172A")
223
+
224
+ frm = tk.Frame(
225
+ win,
226
+ bg="#0F172A",
227
+ highlightbackground="#38BDF8",
228
+ highlightthickness=1,
229
+ padx=8,
230
+ pady=4,
231
+ )
232
+ frm.pack()
233
+ lbl = tk.Label(
234
+ frm,
235
+ text=txt,
236
+ font=(self.font_family, 8, "bold"),
237
+ fg="#F8FAFC",
238
+ bg="#0F172A",
239
+ )
240
+ lbl.pack()
241
+
242
+ win.update_idletasks()
243
+ tw = win.winfo_reqwidth()
244
+ th = win.winfo_reqheight()
245
+ ml, mt, mr, mb = get_monitor_work_area_at(wx, wy, win)
246
+
247
+ # نمایش در بالای آیکون یا پایین آیکون به‌گونه‌ای که در مانیتور فعلی کامل دیده شود
248
+ pos_x = wx - (tw // 3)
249
+ if pos_x + tw > mr - 8:
250
+ pos_x = mr - tw - 8
251
+ pos_x = max(ml + 8, pos_x)
252
+
253
+ if wy - th - 6 >= mt + 8:
254
+ pos_y = wy - th - 6
255
+ else:
256
+ pos_y = min(mb - th - 8, wy + wh + 6)
257
+
258
+ win.geometry(f"+{int(pos_x)}+{int(pos_y)}")
259
+ hide_from_taskbar(win)
260
+ apply_z_order_and_clickthrough(win, "topmost", click_through=True)
261
+ except Exception:
262
+ self._hide_tip()
263
+
264
+ def _hide_tip(self):
265
+ if self.tip_win is not None:
266
+ try:
267
+ self.tip_win.destroy()
268
+ except Exception:
269
+ pass
270
+ self.tip_win = None
271
+
272
+
273
+ class PersianClockWidget:
274
+ BASE_MIN_W = 290
275
+ BASE_CALENDAR_W = 310
276
+ BASE_CALENDAR_H = 385
277
+
278
+ LOCK_BTN_SIZE = 24
279
+ LOCK_OFFSET_X = 8
280
+ LOCK_OFFSET_Y = 8
281
+ GAP = 8
282
+
283
+ def __init__(self):
284
+ enable_dpi_awareness()
285
+ register_bundled_fonts()
286
+
287
+ self.config = self._load_config()
288
+ if self.config.get("z_mode") == "overlay_locked":
289
+ self.config["z_mode"] = "topmost"
290
+ self.config["locked"] = True
291
+
292
+ # پنجره ریشه مخفی (بدون هیچ آیکونی در Taskbar)
293
+ self.root = tk.Tk()
294
+ self.root.title("PersianClockHiddenRoot")
295
+ self.root.attributes("-alpha", 0.0)
296
+ self.root.withdraw()
297
+
298
+ sys_fams = set(tkfont.families())
299
+ if self.config["font_family"] not in sys_fams:
300
+ for candidate in ("Vazir", "B Yekan+", "A Iranian Sans", "Tahoma"):
301
+ if candidate in sys_fams:
302
+ self.config["font_family"] = candidate
303
+ break
304
+ if self.config["clock_font_family"] not in sys_fams:
305
+ for candidate in ("Vazir", "B Yekan+", "A Iranian Sans", "Segoe UI Semibold", "Tahoma"):
306
+ if candidate in sys_fams:
307
+ self.config["clock_font_family"] = candidate
308
+ break
309
+
310
+ ico_path = get_resource_path(os.path.join("assets", "icons", "app_icon.ico"))
311
+ if os.path.exists(ico_path):
312
+ try:
313
+ self.root.iconbitmap(default=ico_path)
314
+ except Exception:
315
+ pass
316
+
317
+ self.alarm_store = AlarmStore(ALARMS_PATH)
318
+
319
+ today = get_today_info(CUSTOM_OCCASIONS_PATH)
320
+ self.current_jy = today["jy"]
321
+ self.current_jm = today["jm"]
322
+ self.current_jd = today["jd"]
323
+
324
+ self.view_jy = today["jy"]
325
+ self.view_jm = today["jm"]
326
+ self.selected_day_info = today
327
+
328
+ self._computed_w = self.BASE_MIN_W
329
+ self._computed_h = 118
330
+ self._toast_text = ""
331
+
332
+ self._drag_start_x = 0
333
+ self._drag_start_y = 0
334
+ self._is_dragging = False
335
+ self._is_minimized = False
336
+ self._unlocked_x = self.config.get("x")
337
+ self._unlocked_y = self.config.get("y")
338
+ self._tooltips: list[HoverTooltip] = []
339
+
340
+ self.widget_win: tk.Toplevel | None = None
341
+ self.lock_win: tk.Toplevel | None = None
342
+ self.cal_win: tk.Toplevel | None = None
343
+ self.dev_popup_win: tk.Toplevel | None = None
344
+ self.settings_win: tk.Toplevel | None = None
345
+ self.alarm_win: AlarmManagerWindow | None = None
346
+ self.custom_occ_win: tk.Toplevel | None = None
347
+
348
+ self._build_compact_ui()
349
+ self._build_lock_badge_window()
350
+ self._build_calendar_window()
351
+ self._build_context_menu()
352
+ self._build_dev_copy_menu()
353
+
354
+ self._init_position()
355
+ self.root.after(60, self._apply_all_styles)
356
+
357
+ self.tray = SystemTrayIcon(
358
+ tooltip=self._format_tray_tooltip(today),
359
+ on_left_click=self._on_tray_left_click,
360
+ on_right_click=self._on_tray_right_click,
361
+ )
362
+ self.tray.start()
363
+
364
+ self.taskbar_clock: TaskbarClockOverlay | None = None
365
+ self.taskbar_proxy: TaskbarButtonProxy | None = None
366
+ self.clock_replacer: WindowsClockReplacer | None = None
367
+ self.root.after(300, self.sync_taskbar_features)
368
+
369
+ self._update_clock_loop()
370
+ self._keep_z_order_loop()
371
+
372
+ # ------------------------------------------------------------------
373
+ # نمایش در تسک‌بار (ساعت روی تسک‌بار + دکمه برنامه در تسک‌بار)
374
+ # ------------------------------------------------------------------
375
+ def format_digits_public(self, text: str, use_fa: bool) -> str:
376
+ return format_digits(text, use_fa)
377
+
378
+ def sync_taskbar_features(self):
379
+ """فعال/غیرفعال کردن جایگزین ساعت ویندوز، ساعت روی تسک‌بار و دکمه تسک‌بار بر اساس تنظیمات"""
380
+ want_replacer = bool(self.config.get("replace_windows_clock", False))
381
+ want_clock = bool(self.config.get("taskbar_clock", False))
382
+ want_btn = bool(self.config.get("taskbar_button", False))
383
+ hide_desktop = bool(self.config.get("replace_clock_hide_widget", False)) and want_replacer
384
+
385
+ # ۱. جایگزین کامل ساعت و تاریخ ویندوز
386
+ if want_replacer and self.clock_replacer is None:
387
+ self.clock_replacer = WindowsClockReplacer(self)
388
+ self.clock_replacer.refresh(get_today_info(CUSTOM_OCCASIONS_PATH))
389
+ elif not want_replacer and self.clock_replacer is not None:
390
+ self.clock_replacer.destroy()
391
+ self.clock_replacer = None
392
+
393
+ # ۲. ساعت و تاریخ شناور روی تسک‌بار
394
+ if want_clock and self.taskbar_clock is None:
395
+ self.taskbar_clock = TaskbarClockOverlay(self)
396
+ self.taskbar_clock.refresh(get_today_info(CUSTOM_OCCASIONS_PATH))
397
+ elif not want_clock and self.taskbar_clock is not None:
398
+ self.taskbar_clock.destroy()
399
+ self.taskbar_clock = None
400
+
401
+ # ۳. دکمه/آیکون برنامه در تسک‌بار
402
+ if want_btn and self.taskbar_proxy is None:
403
+ self.taskbar_proxy = TaskbarButtonProxy(self)
404
+ elif not want_btn and self.taskbar_proxy is not None:
405
+ self.taskbar_proxy.destroy()
406
+ self.taskbar_proxy = None
407
+
408
+ # ۴. مدیریت نمایش/مخفی‌سازی ویجت دسکتاپ بر اساس تنظیمات جایگزینی
409
+ if hide_desktop:
410
+ if self.widget_win and self.widget_win.winfo_viewable():
411
+ self.widget_win.withdraw()
412
+ if self.lock_win and self.lock_win.winfo_viewable():
413
+ self.lock_win.withdraw()
414
+ else:
415
+ if not getattr(self, "_is_minimized", False):
416
+ if self.widget_win and not self.widget_win.winfo_viewable():
417
+ self.widget_win.deiconify()
418
+ if self.lock_win and not self.lock_win.winfo_viewable() and self.config.get("locked"):
419
+ self.lock_win.deiconify()
420
+
421
+ for var_name, key in (
422
+ ("_settings_tb_clock_var", "taskbar_clock"),
423
+ ("_settings_tb_btn_var", "taskbar_button"),
424
+ ("_settings_replace_clock_var", "replace_windows_clock"),
425
+ ("_settings_hide_widget_var", "replace_clock_hide_widget"),
426
+ ):
427
+ var = getattr(self, var_name, None)
428
+ if var is not None:
429
+ try:
430
+ var.set(bool(self.config.get(key, False)))
431
+ except Exception:
432
+ pass
433
+
434
+ def _toggle_taskbar_setting(self, key: str):
435
+ self.config[key] = not self.config.get(key, False)
436
+ self._save_config()
437
+ self.sync_taskbar_features()
438
+
439
+ def minimize_widget(self):
440
+ """مخفی کردن ویجت از صفحه دسکتاپ و تسک‌بار؛ فقط در Hidden Icons (سینی سیستم)"""
441
+ self._is_minimized = True
442
+ self._close_dev_popup_window()
443
+ if self.widget_win:
444
+ self.widget_win.withdraw()
445
+ if self.lock_win:
446
+ self.lock_win.withdraw()
447
+ if self.cal_win:
448
+ self.cal_win.withdraw()
449
+ # هنگام مینیمایز یا بستن، هیچ آیکونی در تسک‌بار نمایش داده نشود (فقط در Hidden Icons بماند)
450
+ if self.taskbar_proxy is not None:
451
+ self.taskbar_proxy.destroy()
452
+ self.taskbar_proxy = None
453
+ info = get_today_info(CUSTOM_OCCASIONS_PATH)
454
+ if getattr(self, "taskbar_clock", None) is not None:
455
+ try:
456
+ self.taskbar_clock.refresh(info)
457
+ except Exception:
458
+ pass
459
+ if getattr(self, "clock_replacer", None) is not None:
460
+ try:
461
+ self.clock_replacer.refresh(info)
462
+ except Exception:
463
+ pass
464
+
465
+ def restore_widget(self):
466
+ """نمایش مجدد ویجت روی صفحه دسکتاپ"""
467
+ self._is_minimized = False
468
+ if self.widget_win:
469
+ self.widget_win.deiconify()
470
+ self.widget_win.lift()
471
+ if self.lock_win:
472
+ self.lock_win.deiconify()
473
+ self.lock_win.lift()
474
+ self._position_lock_window()
475
+ self._apply_all_styles()
476
+ self.sync_taskbar_features()
477
+
478
+ def on_taskbar_clicked(self):
479
+ """کلیک روی ساعت تسک‌بار یا دکمه تسک‌بار: بازیابی از مینیمایز یا باز/بسته کردن تقویم"""
480
+ now_ts = time.monotonic()
481
+ if now_ts - getattr(self, "_last_tb_click_ts", 0.0) < 0.22:
482
+ return
483
+ self._last_tb_click_ts = now_ts
484
+
485
+ hide_desktop = (
486
+ bool(self.config.get("replace_windows_clock", False))
487
+ and bool(self.config.get("replace_clock_hide_widget", False))
488
+ )
489
+ if self._is_minimized:
490
+ if not hide_desktop:
491
+ self.restore_widget()
492
+ return
493
+ self._is_minimized = False
494
+
495
+ if not hide_desktop:
496
+ if self.widget_win and not self.widget_win.winfo_viewable():
497
+ self.widget_win.deiconify()
498
+ if self.lock_win and not self.lock_win.winfo_viewable() and self.config.get("locked"):
499
+ self.lock_win.deiconify()
500
+
501
+ self._toggle_calendar(None)
502
+ if self.config.get("calendar_expanded") and self.cal_win:
503
+ self.cal_win.lift()
504
+
505
+ def show_menu_at_pointer(self):
506
+ self._populate_context_menu()
507
+ x = self.root.winfo_pointerx()
508
+ y = self.root.winfo_pointery()
509
+ try:
510
+ self.menu.tk_popup(x, y)
511
+ finally:
512
+ self.menu.grab_release()
513
+
514
+ def _get_btn_base_bg(self) -> str:
515
+ return "#1E2638" if not self.config.get("transparent_bg", False) else "#141821"
516
+
517
+ def _attach_hover(
518
+ self,
519
+ widget: tk.Widget,
520
+ tooltip_text,
521
+ base_fg_fn,
522
+ hover_bg: str = "#0284C7",
523
+ hover_fg: str = "#FFFFFF",
524
+ base_bg_fn=None,
525
+ ):
526
+ tip = HoverTooltip(
527
+ widget=widget,
528
+ text_or_fn=tooltip_text,
529
+ base_bg_fn=base_bg_fn or self._get_btn_base_bg,
530
+ base_fg_fn=base_fg_fn,
531
+ hover_bg=hover_bg,
532
+ hover_fg=hover_fg,
533
+ font_family=self.config.get("font_family", "Vazir"),
534
+ )
535
+ self._tooltips.append(tip)
536
+
537
+ def _format_tray_tooltip(self, info: dict) -> str:
538
+ base = f"{info['time_str']} | {info['date_text']}"
539
+ if info.get("has_occasion") and info.get("occasion"):
540
+ return f"{base} - {info['occasion']}"
541
+ return base
542
+
543
+ def _load_config(self) -> dict:
544
+ cfg = DEFAULT_CONFIG.copy()
545
+ if os.path.exists(CONFIG_PATH):
546
+ try:
547
+ with open(CONFIG_PATH, "r", encoding="utf-8") as f:
548
+ saved = json.load(f)
549
+ if isinstance(saved, dict):
550
+ cfg.update(saved)
551
+ except Exception:
552
+ pass
553
+ return cfg
554
+
555
+ def _save_config(self):
556
+ try:
557
+ os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
558
+ with open(CONFIG_PATH, "w", encoding="utf-8") as f:
559
+ json.dump(self.config, f, ensure_ascii=False, indent=2)
560
+ except Exception:
561
+ pass
562
+
563
+ @property
564
+ def compact_w(self) -> int:
565
+ return self._computed_w
566
+
567
+ @property
568
+ def compact_h(self) -> int:
569
+ return self._computed_h
570
+
571
+ @property
572
+ def calendar_w(self) -> int:
573
+ scale = max(80, min(150, int(self.config.get("widget_scale", 100)))) / 100.0
574
+ return int(self.BASE_CALENDAR_W * scale)
575
+
576
+ @property
577
+ def calendar_h(self) -> int:
578
+ scale = max(80, min(150, int(self.config.get("widget_scale", 100)))) / 100.0
579
+ return int(self.BASE_CALENDAR_H * scale)
580
+
581
+ def _build_compact_ui(self):
582
+ self.widget_win = tk.Toplevel(self.root)
583
+ self.widget_win.title("ویجت ساعت و تقویم")
584
+ self.widget_win.overrideredirect(True)
585
+ self.widget_win.protocol("WM_DELETE_WINDOW", self.minimize_widget)
586
+ self.root.protocol("WM_DELETE_WINDOW", self.minimize_widget)
587
+
588
+ bg = TRANSPARENT_KEY if self.config["transparent_bg"] else self.config["bg_color"]
589
+ self.widget_win.configure(bg=bg)
590
+
591
+ self.main_frame = tk.Frame(
592
+ self.widget_win,
593
+ bg=bg,
594
+ highlightbackground=self.config["border_color"] if not self.config["transparent_bg"] else bg,
595
+ highlightthickness=0 if self.config["transparent_bg"] else 1,
596
+ )
597
+ self.main_frame.pack(fill="both", expand=True)
598
+
599
+ self.canvas = tk.Canvas(
600
+ self.main_frame,
601
+ bg=bg,
602
+ highlightthickness=0,
603
+ bd=0,
604
+ )
605
+ self.canvas.pack(fill="both", expand=True)
606
+
607
+ self.btn_container = tk.Frame(self.canvas, bg=bg)
608
+
609
+ # ۱. دکمه باز/بسته کردن تقویم (Extend)
610
+ self.extend_btn = tk.Label(
611
+ self.btn_container,
612
+ text="◂ تقویم",
613
+ font=(self.config["font_family"], 8, "bold"),
614
+ fg=self.config["accent_color"],
615
+ bg="#1E2638",
616
+ padx=5,
617
+ pady=2,
618
+ cursor="hand2",
619
+ )
620
+ self.extend_btn.pack(side="left", padx=(0, 3))
621
+ self.extend_btn.bind("<Button-1>", self._toggle_calendar)
622
+ self.extend_btn.bind("<Double-Button-1>", lambda e: "break")
623
+ self._attach_hover(
624
+ self.extend_btn,
625
+ lambda: "بستن تقویم ماهانه" if self.config.get("calendar_expanded") else "نمایش تقویم ماهانه و مناسبت‌ها",
626
+ base_fg_fn=lambda: self.config.get("accent_color", "#38BDF8"),
627
+ hover_bg="#0284C7",
628
+ hover_fg="#FFFFFF",
629
+ )
630
+
631
+ # ۲. دکمه کپی ۱۰ فرمت زمان برنامه‌نویسی برای API + GUID
632
+ self.copy_time_btn = tk.Label(
633
+ self.btn_container,
634
+ text="📋",
635
+ font=("Segoe UI Emoji", 8),
636
+ fg="#A7F3D0",
637
+ bg="#1E2638",
638
+ padx=5,
639
+ pady=2,
640
+ cursor="hand2",
641
+ )
642
+ self.copy_time_btn.pack(side="left", padx=(0, 3))
643
+ self.copy_time_btn.bind("<Button-1>", self._toggle_dev_popup_window)
644
+ self.copy_time_btn.bind("<Double-Button-1>", lambda e: "break")
645
+ self._attach_hover(
646
+ self.copy_time_btn,
647
+ "کپی زمان (۱۰ فرمت API: تاریخ+ساعت / تاریخ جدا / ساعت جدا) + GUID",
648
+ base_fg_fn=lambda: "#A7F3D0",
649
+ hover_bg="#059669",
650
+ hover_fg="#FFFFFF",
651
+ )
652
+
653
+ # ۳. دکمه اختصاصی رندر و کپی سریع GUID (UUID v4)
654
+ self.guid_btn = tk.Label(
655
+ self.btn_container,
656
+ text="GUID",
657
+ font=("Consolas", 8, "bold"),
658
+ fg="#C4B5FD",
659
+ bg="#1E2638",
660
+ padx=5,
661
+ pady=2,
662
+ cursor="hand2",
663
+ )
664
+ self.guid_btn.pack(side="left", padx=(0, 3))
665
+ self.guid_btn.bind("<Button-1>", self._quick_copy_guid)
666
+ self.guid_btn.bind("<Double-Button-1>", lambda e: "break")
667
+ self.guid_btn.bind("<Button-3>", self._toggle_dev_popup_window)
668
+ self._attach_hover(
669
+ self.guid_btn,
670
+ "کلیک چپ: رندر و کپی فوری GUID جدید | کلیک راست: منوی کامل",
671
+ base_fg_fn=lambda: "#C4B5FD",
672
+ hover_bg="#7C3AED",
673
+ hover_fg="#FFFFFF",
674
+ )
675
+
676
+ # ۳.۵. دکمه سوییچ سریع تایم‌زون اصلی بین تهران و UTC (بدون نمایش +03:30)
677
+ is_utc_primary = self.config.get("primary_timezone", "tehran") == "utc"
678
+ self.tz_btn = tk.Label(
679
+ self.btn_container,
680
+ text="UTC" if is_utc_primary else "TEH",
681
+ font=("Consolas", 8, "bold"),
682
+ fg="#38BDF8" if is_utc_primary else "#E2E8F0",
683
+ bg="#1E2638",
684
+ padx=5,
685
+ pady=2,
686
+ cursor="hand2",
687
+ )
688
+ self.tz_btn.pack(side="left", padx=(0, 3))
689
+ self.tz_btn.bind("<Button-1>", self._toggle_primary_timezone)
690
+ self.tz_btn.bind("<Double-Button-1>", lambda e: "break")
691
+ self._attach_hover(
692
+ self.tz_btn,
693
+ "تبدیل سریع ساعت اصلی بین تهران و UTC (بدون نمایش +03:30)",
694
+ base_fg_fn=lambda: "#38BDF8" if self.config.get("primary_timezone", "tehran") == "utc" else "#E2E8F0",
695
+ hover_bg="#0284C7",
696
+ hover_fg="#FFFFFF",
697
+ )
698
+
699
+ # ۴. دکمه مدیریت رویدادها و آلارم‌ها
700
+ self.alarm_btn = tk.Label(
701
+ self.btn_container,
702
+ text="⏰",
703
+ font=("Segoe UI Emoji", 8),
704
+ fg="#FBBF24",
705
+ bg="#1E2638",
706
+ padx=5,
707
+ pady=2,
708
+ cursor="hand2",
709
+ )
710
+ self.alarm_btn.pack(side="left", padx=(0, 3))
711
+ self.alarm_btn.bind("<Button-1>", lambda e: (self.open_alarm_manager(), "break")[1])
712
+ self.alarm_btn.bind("<Double-Button-1>", lambda e: "break")
713
+ self._attach_hover(
714
+ self.alarm_btn,
715
+ "مدیریت رویدادها و آلارم‌ها (تقویم چندانتخابی)",
716
+ base_fg_fn=lambda: "#FBBF24",
717
+ hover_bg="#D97706",
718
+ hover_fg="#FFFFFF",
719
+ )
720
+
721
+ # ۵. دکمه تنظیمات ظاهری
722
+ self.settings_btn = tk.Label(
723
+ self.btn_container,
724
+ text="⚙",
725
+ font=("Segoe UI", 8),
726
+ fg=self.config["date_color"],
727
+ bg="#1E2638",
728
+ padx=5,
729
+ pady=2,
730
+ cursor="hand2",
731
+ )
732
+ self.settings_btn.pack(side="left", padx=(0, 2))
733
+ self.settings_btn.bind("<Button-1>", lambda e: (self.open_settings_window(), "break")[1])
734
+ self.settings_btn.bind("<Double-Button-1>", lambda e: "break")
735
+ self._attach_hover(
736
+ self.settings_btn,
737
+ "تنظیمات ظاهری، رنگ، سایز و فونت",
738
+ base_fg_fn=lambda: self.config.get("date_color", "#CBD5E1"),
739
+ hover_bg="#475569",
740
+ hover_fg="#FFFFFF",
741
+ )
742
+
743
+ # ۶. دکمه مینیمایز و بستن به Hidden Icons (بدون آیکون در تسک‌بار)
744
+ self.min_btn = tk.Label(
745
+ self.btn_container,
746
+ text="🗕",
747
+ font=("Segoe UI", 8, "bold"),
748
+ fg=self.config["date_color"],
749
+ bg="#1E2638",
750
+ padx=5,
751
+ pady=2,
752
+ cursor="hand2",
753
+ )
754
+ self.min_btn.pack(side="left", padx=(0, 2))
755
+ self.min_btn.bind("<Button-1>", lambda e: (self.minimize_widget(), "break")[1])
756
+ self.min_btn.bind("<Double-Button-1>", lambda e: "break")
757
+ self._attach_hover(
758
+ self.min_btn,
759
+ "مینیمایز به Hidden Icons (بدون آیکون در تسک‌بار)",
760
+ base_fg_fn=lambda: self.config.get("date_color", "#CBD5E1"),
761
+ hover_bg="#475569",
762
+ hover_fg="#FFFFFF",
763
+ )
764
+
765
+ # ۷. دکمه بستن ویجت (انتقال به Hidden Icons؛ برای خروج کامل از راست‌کلیک سینی سیستم استفاده کنید)
766
+ self.close_btn = tk.Label(
767
+ self.btn_container,
768
+ text="✕",
769
+ font=("Segoe UI", 8, "bold"),
770
+ fg="#FCA5A5",
771
+ bg="#1E2638",
772
+ padx=5,
773
+ pady=2,
774
+ cursor="hand2",
775
+ )
776
+ self.close_btn.pack(side="left")
777
+ self.close_btn.bind("<Button-1>", lambda e: (self.minimize_widget(), "break")[1])
778
+ self.close_btn.bind("<Double-Button-1>", lambda e: "break")
779
+ self._attach_hover(
780
+ self.close_btn,
781
+ "بستن ویجت روی دسکتاپ (ارسال به Hidden Icons)",
782
+ base_fg_fn=lambda: "#FCA5A5",
783
+ hover_bg="#DC2626",
784
+ hover_fg="#FFFFFF",
785
+ )
786
+
787
+ # ایجاد یک‌باره پنجره نوار ابزار روی Canvas تا در رفرش ثانیه‌ای حذف نشود و Hover پایدار بماند
788
+ toolbar_x = self.LOCK_OFFSET_X + self.LOCK_BTN_SIZE + 8
789
+ toolbar_y = self.LOCK_OFFSET_Y
790
+ self._toolbar_win_id = self.canvas.create_window(
791
+ toolbar_x,
792
+ toolbar_y,
793
+ window=self.btn_container,
794
+ anchor="nw",
795
+ tags="toolbar",
796
+ )
797
+
798
+ # بایندینگ درگ و دابل‌کلیک فقط روی بوم و قاب اصلی (نه روی toplevel تا دکمه‌های نوار ابزار را نگیرد)
799
+ for w in (self.main_frame, self.canvas):
800
+ w.bind("<ButtonPress-1>", self._on_drag_start)
801
+ w.bind("<B1-Motion>", self._on_drag_motion)
802
+ w.bind("<ButtonRelease-1>", self._on_drag_end)
803
+ w.bind("<Button-3>", self._show_context_menu)
804
+ w.bind("<Double-Button-1>", self._toggle_calendar)
805
+
806
+ def _quick_copy_guid(self, event=None):
807
+ """تولید و کپی فوری یک GUID (UUID v4) استاندارد با یک کلیک روی دکمه GUID"""
808
+ if self.config.get("locked", False):
809
+ return "break"
810
+ new_guid = str(uuid.uuid4())
811
+ self._copy_to_clipboard(new_guid, f"✓ GUID کپی شد!")
812
+ return "break"
813
+
814
+ def _update_tz_btn_appearance(self):
815
+ if hasattr(self, "tz_btn") and self.tz_btn.winfo_exists():
816
+ is_utc = self.config.get("primary_timezone", "tehran") == "utc"
817
+ self.tz_btn.configure(
818
+ text="UTC" if is_utc else "TEH",
819
+ fg="#38BDF8" if is_utc else "#E2E8F0",
820
+ bg=self._get_btn_base_bg(),
821
+ )
822
+
823
+ def _toggle_primary_timezone(self, event=None):
824
+ """سوییچ سریع ساعت اصلی ویجت بین تهران و UTC (بدون نمایش +03:30)"""
825
+ if event is not None and self.config.get("locked", False):
826
+ return "break"
827
+ cur = self.config.get("primary_timezone", "tehran")
828
+ new_tz = "utc" if cur != "utc" else "tehran"
829
+ self.config["primary_timezone"] = new_tz
830
+ self._save_config()
831
+ self._update_tz_btn_appearance()
832
+ var = getattr(self, "_settings_primary_tz_var", None)
833
+ if var is not None:
834
+ try:
835
+ var.set(new_tz)
836
+ except Exception:
837
+ pass
838
+ self._refresh_display()
839
+ return "break"
840
+
841
+ def _toggle_show_utc(self):
842
+ self.config["show_utc"] = not bool(self.config.get("show_utc", False))
843
+ self._save_config()
844
+ var = getattr(self, "_settings_show_utc_var", None)
845
+ if var is not None:
846
+ try:
847
+ var.set(bool(self.config["show_utc"]))
848
+ except Exception:
849
+ pass
850
+ self._refresh_display()
851
+
852
+ def _build_lock_badge_window(self):
853
+ self.lock_win = tk.Toplevel(self.root)
854
+ self.lock_win.overrideredirect(True)
855
+ self.lock_win.configure(bg="#1E293B")
856
+
857
+ self.lock_frame = tk.Frame(
858
+ self.lock_win,
859
+ bg="#1E293B",
860
+ highlightbackground=self.config["border_color"],
861
+ highlightthickness=1,
862
+ )
863
+ self.lock_frame.pack(fill="both", expand=True)
864
+
865
+ self.lock_btn_label = tk.Label(
866
+ self.lock_frame,
867
+ text="🔒" if self.config.get("locked") else "🔓",
868
+ font=("Segoe UI Emoji", 8),
869
+ fg="#FBBF24" if self.config.get("locked") else self.config["accent_color"],
870
+ bg="#1E293B",
871
+ cursor="hand2",
872
+ )
873
+ self.lock_btn_label.pack(fill="both", expand=True)
874
+
875
+ self.lock_btn_label.bind("<Button-1>", lambda e: self._toggle_lock())
876
+ self.lock_frame.bind("<Button-1>", lambda e: self._toggle_lock())
877
+ self.lock_btn_label.bind("<Button-3>", self._on_lock_btn_right_click)
878
+ self._attach_hover(
879
+ self.lock_btn_label,
880
+ lambda: "باز کردن قفل ویجت (🔓)" if self.config.get("locked") else "قفل روی صفحه و عبوردهی کلیک (🔒)",
881
+ base_fg_fn=lambda: "#FBBF24" if self.config.get("locked") else self.config.get("accent_color", "#38BDF8"),
882
+ hover_bg="#334155",
883
+ hover_fg="#FDE047",
884
+ )
885
+
886
+ def _on_lock_btn_right_click(self, event):
887
+ if not self.config.get("locked", False):
888
+ self._show_context_menu(event)
889
+
890
+ def _position_lock_window(self):
891
+ if not self.lock_win or not self.widget_win:
892
+ return
893
+ wx = self.widget_win.winfo_x()
894
+ wy = self.widget_win.winfo_y()
895
+ sz = self.LOCK_BTN_SIZE
896
+ lx = wx + self.LOCK_OFFSET_X
897
+ ly = wy + self.LOCK_OFFSET_Y
898
+ self.lock_win.geometry(f"{sz}x{sz}+{int(lx)}+{int(ly)}")
899
+
900
+ def _get_dev_copy_data(self) -> dict:
901
+ """محاسبه لحظه‌ای ۱۰ فرمت پرکاربرد تاریخ و ساعت برای API + مقادیر GUID"""
902
+ now_utc = datetime.now(timezone.utc)
903
+ now_teh = now_utc.astimezone(TEHRAN_TZ)
904
+ jy, jm, jd = gregorian_to_jalali(now_teh.year, now_teh.month, now_teh.day)
905
+
906
+ ms_teh = now_teh.microsecond // 1000
907
+ ms_utc = now_utc.microsecond // 1000
908
+
909
+ fmt_1_utc_iso = f"{now_utc.strftime('%Y-%m-%dT%H:%M:%S')}.{ms_utc:03d}Z"
910
+ fmt_2_teh_iso = f"{now_teh.strftime('%Y-%m-%dT%H:%M:%S')}.{ms_teh:03d}+03:30"
911
+ fmt_3_sql_dt = f"{now_teh.strftime('%Y-%m-%d %H:%M:%S')}.{ms_teh:03d}"
912
+ fmt_4_jalali_dt = f"{jy:04d}/{jm:02d}/{jd:02d} {now_teh.strftime('%H:%M:%S')}.{ms_teh:03d}"
913
+
914
+ fmt_5_greg_date = now_teh.strftime("%Y-%m-%d")
915
+ fmt_6_jalali_date = f"{jy:04d}/{jm:02d}/{jd:02d}"
916
+
917
+ fmt_7_time_ms = f"{now_teh.strftime('%H:%M:%S')}.{ms_teh:03d}"
918
+ fmt_8_time_std = now_teh.strftime("%H:%M:%S")
919
+
920
+ unix_ms = int(now_utc.timestamp() * 1000)
921
+ unix_sec = int(now_utc.timestamp())
922
+ fmt_9_unix_ms = str(unix_ms)
923
+ fmt_10_unix_sec = str(unix_sec)
924
+
925
+ new_guid_lower = str(uuid.uuid4())
926
+ new_guid_upper = new_guid_lower.upper()
927
+ new_guid_no_dash = new_guid_lower.replace("-", "")
928
+ empty_guid = "00000000-0000-0000-0000-000000000000"
929
+
930
+ json_payload = json.dumps(
931
+ {
932
+ "utc_iso": fmt_1_utc_iso,
933
+ "tehran_iso": fmt_2_teh_iso,
934
+ "sql_datetime": fmt_3_sql_dt,
935
+ "jalali_datetime": fmt_4_jalali_dt,
936
+ "date_gregorian": fmt_5_greg_date,
937
+ "date_jalali": fmt_6_jalali_date,
938
+ "time_ms": fmt_7_time_ms,
939
+ "time_std": fmt_8_time_std,
940
+ "unix_ms": unix_ms,
941
+ "unix_sec": unix_sec,
942
+ "guid": new_guid_lower,
943
+ },
944
+ ensure_ascii=False,
945
+ )
946
+
947
+ return {
948
+ "fmt_1_utc_iso": fmt_1_utc_iso,
949
+ "fmt_2_teh_iso": fmt_2_teh_iso,
950
+ "fmt_3_sql_dt": fmt_3_sql_dt,
951
+ "fmt_4_jalali_dt": fmt_4_jalali_dt,
952
+ "fmt_5_greg_date": fmt_5_greg_date,
953
+ "fmt_6_jalali_date": fmt_6_jalali_date,
954
+ "fmt_7_time_ms": fmt_7_time_ms,
955
+ "fmt_8_time_std": fmt_8_time_std,
956
+ "fmt_9_unix_ms": fmt_9_unix_ms,
957
+ "fmt_10_unix_sec": fmt_10_unix_sec,
958
+ "new_guid_lower": new_guid_lower,
959
+ "new_guid_upper": new_guid_upper,
960
+ "new_guid_no_dash": new_guid_no_dash,
961
+ "empty_guid": empty_guid,
962
+ "json_payload": json_payload,
963
+ }
964
+
965
+ def _toggle_dev_popup_window(self, event=None):
966
+ """
967
+ نمایش پنجره شناور اختصاصی کپی زمان برنامه‌نویسی (۱۰ فرمت API) و GUID
968
+ با فاصله استاندارد از ویجت و در بالاترین لایه (Topmost) تا هرگز زیر ویجت نرود.
969
+ """
970
+ if self.config.get("locked", False):
971
+ return "break"
972
+ if self.dev_popup_win and self.dev_popup_win.winfo_exists():
973
+ self._close_dev_popup_window()
974
+ return "break"
975
+ # جلوگیری از باز شدن مجدد در همان کلیک وقتی FocusOut پنجره را تازه بسته است
976
+ if time.monotonic() - getattr(self, "_dev_popup_closed_ts", 0.0) < 0.28:
977
+ return "break"
978
+
979
+ d = self._get_dev_copy_data()
980
+ font_fa = self.config.get("font_family", "Vazir")
981
+
982
+ win = tk.Toplevel(self.root)
983
+ self.dev_popup_win = win
984
+ win.title("ابزار کپی زمان API و GUID")
985
+ win.overrideredirect(True)
986
+ win.attributes("-topmost", True)
987
+ win.configure(bg="#0F172A")
988
+
989
+ outer = tk.Frame(
990
+ win,
991
+ bg="#0F172A",
992
+ highlightbackground="#38BDF8",
993
+ highlightthickness=1,
994
+ padx=10,
995
+ pady=8,
996
+ )
997
+ outer.pack(fill="both", expand=True)
998
+
999
+ # هدر پنل
1000
+ hdr = tk.Frame(outer, bg="#0F172A")
1001
+ hdr.pack(fill="x", pady=(0, 6))
1002
+ tk.Label(
1003
+ hdr,
1004
+ text="📋 کپی سریع تاریخ، ساعت API و تولید GUID",
1005
+ font=(font_fa, 9, "bold"),
1006
+ fg="#38BDF8",
1007
+ bg="#0F172A",
1008
+ ).pack(side="right")
1009
+
1010
+ close_lbl = tk.Label(
1011
+ hdr,
1012
+ text="✕",
1013
+ font=("Segoe UI", 9, "bold"),
1014
+ fg="#94A3B8",
1015
+ bg="#1E293B",
1016
+ padx=6,
1017
+ pady=1,
1018
+ cursor="hand2",
1019
+ )
1020
+ close_lbl.pack(side="left")
1021
+ close_lbl.bind("<Button-1>", lambda e: self._close_dev_popup_window())
1022
+ close_lbl.bind("<Enter>", lambda e: close_lbl.configure(bg="#EF4444", fg="#FFFFFF"))
1023
+ close_lbl.bind("<Leave>", lambda e: close_lbl.configure(bg="#1E293B", fg="#94A3B8"))
1024
+
1025
+ def add_section_title(txt: str):
1026
+ tk.Label(
1027
+ outer,
1028
+ text=txt,
1029
+ font=(font_fa, 8, "bold"),
1030
+ fg="#FBBF24",
1031
+ bg="#0F172A",
1032
+ anchor="e",
1033
+ ).pack(fill="x", pady=(4, 2))
1034
+
1035
+ def add_copy_row(title_txt: str, value_txt: str, copy_fn_or_val, toast_msg: str = "✓ کپی شد!"):
1036
+ row = tk.Frame(outer, bg="#1E293B", padx=6, pady=3, cursor="hand2")
1037
+ row.pack(fill="x", pady=1)
1038
+
1039
+ val_lbl = tk.Label(
1040
+ row,
1041
+ text=value_txt,
1042
+ font=("Consolas", 8, "bold"),
1043
+ fg="#38BDF8",
1044
+ bg="#1E293B",
1045
+ anchor="w",
1046
+ cursor="hand2",
1047
+ )
1048
+ val_lbl.pack(side="left")
1049
+
1050
+ t_lbl = tk.Label(
1051
+ row,
1052
+ text=title_txt,
1053
+ font=(font_fa, 8),
1054
+ fg="#E2E8F0",
1055
+ bg="#1E293B",
1056
+ anchor="e",
1057
+ cursor="hand2",
1058
+ )
1059
+ t_lbl.pack(side="right")
1060
+
1061
+ def on_click(e=None):
1062
+ val = copy_fn_or_val() if callable(copy_fn_or_val) else copy_fn_or_val
1063
+ self._copy_to_clipboard(val, toast_msg)
1064
+ self._close_dev_popup_window()
1065
+
1066
+ def on_enter(e=None):
1067
+ row.configure(bg="#0284C7")
1068
+ val_lbl.configure(bg="#0284C7", fg="#FFFFFF")
1069
+ t_lbl.configure(bg="#0284C7", fg="#FFFFFF")
1070
+
1071
+ def on_leave(e=None):
1072
+ row.configure(bg="#1E293B")
1073
+ val_lbl.configure(bg="#1E293B", fg="#38BDF8")
1074
+ t_lbl.configure(bg="#1E293B", fg="#E2E8F0")
1075
+
1076
+ for w in (row, val_lbl, t_lbl):
1077
+ w.bind("<Button-1>", on_click)
1078
+ w.bind("<Enter>", on_enter)
1079
+ w.bind("<Leave>", on_leave)
1080
+
1081
+ # بخش اول: تولید و کپی GUID (UUID v4)
1082
+ add_section_title("🔑 تولید و کپی GUID (UUID v4):")
1083
+ add_copy_row("🎲 رندر GUID جدید (استاندارد)", d["new_guid_lower"], lambda: str(uuid.uuid4()), "✓ GUID کپی شد!")
1084
+ add_copy_row("🎲 رندر GUID (حروف بزرگ)", d["new_guid_upper"], lambda: str(uuid.uuid4()).upper(), "✓ GUID (Upper) کپی شد!")
1085
+ add_copy_row("🎲 رندر GUID (بدون خط تیره)", d["new_guid_no_dash"], lambda: uuid.uuid4().hex, "✓ GUID (Hex) کپی شد!")
1086
+ add_copy_row("🎲 کپی Empty GUID (صفر)", d["empty_guid"], d["empty_guid"], "✓ Empty GUID کپی شد!")
1087
+
1088
+ # بخش دوم: ۱۰ فرمت پرکاربرد تاریخ و ساعت برای API
1089
+ add_section_title("📅+🕒 تاریخ و ساعت با هم (Date & Time - API):")
1090
+ add_copy_row("۱. ISO-8601 UTC (با میلی‌ثانیه)", d["fmt_1_utc_iso"], d["fmt_1_utc_iso"])
1091
+ add_copy_row("۲. ISO-8601 تهران (با میلی‌ثانیه)", d["fmt_2_teh_iso"], d["fmt_2_teh_iso"])
1092
+ add_copy_row("۳. SQL / API DateTime", d["fmt_3_sql_dt"], d["fmt_3_sql_dt"])
1093
+ add_copy_row("۴. تاریخ و ساعت شمسی (با ms)", d["fmt_4_jalali_dt"], d["fmt_4_jalali_dt"])
1094
+
1095
+ add_section_title("📅 فقط تاریخ جدا (Date Only):")
1096
+ add_copy_row("۵. فقط تاریخ میلادی (Gregorian)", d["fmt_5_greg_date"], d["fmt_5_greg_date"])
1097
+ add_copy_row("۶. فقط تاریخ شمسی (Jalali)", d["fmt_6_jalali_date"], d["fmt_6_jalali_date"])
1098
+
1099
+ add_section_title("🕒 فقط ساعت جدا (Time Only) و تایم‌استمپ:")
1100
+ add_copy_row("۷. فقط ساعت + میلی‌ثانیه (تهران)", d["fmt_7_time_ms"], d["fmt_7_time_ms"])
1101
+ add_copy_row("۸. فقط ساعت استاندارد (HH:MM:SS)", d["fmt_8_time_std"], d["fmt_8_time_std"])
1102
+ add_copy_row("۹. Unix Timestamp (میلی‌ثانیه ms)", d["fmt_9_unix_ms"], d["fmt_9_unix_ms"])
1103
+ add_copy_row("۱۰. Unix Timestamp (ثانیه sec)", d["fmt_10_unix_sec"], d["fmt_10_unix_sec"])
1104
+
1105
+ add_copy_row("📦 کپی همه موارد به صورت JSON", "{ ... }", d["json_payload"], "✓ JSON کپی شد!")
1106
+
1107
+ win.update_idletasks()
1108
+ pw = max(370, win.winfo_reqwidth())
1109
+ ph = win.winfo_reqheight()
1110
+
1111
+ wx = self.widget_win.winfo_x()
1112
+ wy = self.widget_win.winfo_y()
1113
+ ww = self.compact_w
1114
+ wh = self.compact_h
1115
+ screen_w = self.root.winfo_screenwidth()
1116
+ screen_h = self.root.winfo_screenheight()
1117
+
1118
+ # قرارگیری با فاصله ۱۲ پیکسلی در پایین یا بالای ویجت (بدون همپوشانی با خود ویجت)
1119
+ px = wx + ww - pw
1120
+ px = max(10, min(px, screen_w - pw - 10))
1121
+ if wy + wh + 12 + ph <= screen_h - 40:
1122
+ py = wy + wh + 12
1123
+ elif wy - ph - 12 >= 10:
1124
+ py = wy - ph - 12
1125
+ else:
1126
+ # در کنار ویجت با فاصله ۱۲ پیکسل
1127
+ if wx - pw - 12 >= 10:
1128
+ px = wx - pw - 12
1129
+ else:
1130
+ px = min(screen_w - pw - 10, wx + ww + 12)
1131
+ py = max(10, min(wy, screen_h - ph - 40))
1132
+
1133
+ win.geometry(f"{pw}x{ph}+{int(px)}+{int(py)}")
1134
+ hide_from_taskbar(win)
1135
+ apply_rounded_corners(win, pw, ph, radius=12, enabled=True)
1136
+ apply_z_order_and_clickthrough(win, "topmost", click_through=False)
1137
+ win.lift()
1138
+ win.bind("<Escape>", lambda e: self._close_dev_popup_window())
1139
+ win.after(60, lambda: win.winfo_exists() and win.focus_force())
1140
+ win.after(180, lambda: win.winfo_exists() and win.bind("<FocusOut>", self._on_dev_popup_focus_out))
1141
+ return "break"
1142
+
1143
+ def _on_dev_popup_focus_out(self, event=None):
1144
+ if self.dev_popup_win is None or not self.dev_popup_win.winfo_exists():
1145
+ return
1146
+ try:
1147
+ foc = self.root.focus_get()
1148
+ if foc is not None and str(foc).startswith(str(self.dev_popup_win)):
1149
+ return
1150
+ except Exception:
1151
+ pass
1152
+ self._dev_popup_closed_ts = time.monotonic()
1153
+ self._close_dev_popup_window()
1154
+
1155
+ def _close_dev_popup_window(self):
1156
+ if self.dev_popup_win is not None:
1157
+ self._dev_popup_closed_ts = time.monotonic()
1158
+ try:
1159
+ self.dev_popup_win.destroy()
1160
+ except Exception:
1161
+ pass
1162
+ self.dev_popup_win = None
1163
+
1164
+ def _build_dev_copy_menu(self):
1165
+ """منوی آبشاری کپی زمان و GUID برای منوی راست‌کلیک System Tray"""
1166
+ self.copy_menu = tk.Menu(
1167
+ self.root,
1168
+ tearoff=0,
1169
+ bg="#0F172A",
1170
+ fg="#F8FAFC",
1171
+ activebackground="#0284C7",
1172
+ activeforeground="#FFFFFF",
1173
+ font=("Consolas", 9),
1174
+ )
1175
+
1176
+ def _populate_dev_copy_menu(self):
1177
+ self.copy_menu.delete(0, "end")
1178
+ d = self._get_dev_copy_data()
1179
+
1180
+ self.copy_menu.add_command(label="─── 🔑 GUID / UUID v4 Generator ───", state="disabled")
1181
+ self.copy_menu.add_command(
1182
+ label=f"🎲 Render & Copy GUID (v4): {d['new_guid_lower']}",
1183
+ command=lambda: self._copy_to_clipboard(str(uuid.uuid4()), "✓ GUID کپی شد!"),
1184
+ )
1185
+ self.copy_menu.add_command(
1186
+ label=f"🎲 Render GUID (UPPERCASE): {d['new_guid_upper']}",
1187
+ command=lambda: self._copy_to_clipboard(str(uuid.uuid4()).upper(), "✓ GUID (Upper) کپی شد!"),
1188
+ )
1189
+ self.copy_menu.add_command(
1190
+ label=f"🎲 Render GUID (No Hyphens): {d['new_guid_no_dash']}",
1191
+ command=lambda: self._copy_to_clipboard(uuid.uuid4().hex, "✓ GUID (Hex) کپی شد!"),
1192
+ )
1193
+ self.copy_menu.add_command(
1194
+ label=f"🎲 Copy Empty GUID (0000...): {d['empty_guid']}",
1195
+ command=lambda: self._copy_to_clipboard(d["empty_guid"], "✓ Empty GUID کپی شد!"),
1196
+ )
1197
+
1198
+ self.copy_menu.add_separator()
1199
+ self.copy_menu.add_command(label="─── 📅+🕒 Date & Time (API / ISO / DB) ───", state="disabled")
1200
+ for lbl, val in [
1201
+ (f"1. ISO-8601 UTC (ms): {d['fmt_1_utc_iso']}", d["fmt_1_utc_iso"]),
1202
+ (f"2. ISO-8601 Tehran (ms): {d['fmt_2_teh_iso']}", d["fmt_2_teh_iso"]),
1203
+ (f"3. SQL / API DateTime: {d['fmt_3_sql_dt']}", d["fmt_3_sql_dt"]),
1204
+ (f"4. Jalali DateTime (ms): {d['fmt_4_jalali_dt']}", d["fmt_4_jalali_dt"]),
1205
+ ]:
1206
+ self.copy_menu.add_command(label=lbl, command=lambda v=val: self._copy_to_clipboard(v))
1207
+
1208
+ self.copy_menu.add_separator()
1209
+ self.copy_menu.add_command(label="─── 📅 Date Only (فقط تاریخ جدا) ───", state="disabled")
1210
+ for lbl, val in [
1211
+ (f"5. Date Only (Gregorian): {d['fmt_5_greg_date']}", d["fmt_5_greg_date"]),
1212
+ (f"6. Date Only (Jalali): {d['fmt_6_jalali_date']}", d["fmt_6_jalali_date"]),
1213
+ ]:
1214
+ self.copy_menu.add_command(label=lbl, command=lambda v=val: self._copy_to_clipboard(v))
1215
+
1216
+ self.copy_menu.add_separator()
1217
+ self.copy_menu.add_command(label="─── 🕒 Time Only & Unix Epoch ───", state="disabled")
1218
+ for lbl, val in [
1219
+ (f"7. Time Only + ms (Teh): {d['fmt_7_time_ms']}", d["fmt_7_time_ms"]),
1220
+ (f"8. Time Only (HH:MM:SS): {d['fmt_8_time_std']}", d["fmt_8_time_std"]),
1221
+ (f"9. Unix Timestamp (ms): {d['fmt_9_unix_ms']}", d["fmt_9_unix_ms"]),
1222
+ (f"10. Unix Timestamp (sec): {d['fmt_10_unix_sec']}", d["fmt_10_unix_sec"]),
1223
+ ]:
1224
+ self.copy_menu.add_command(label=lbl, command=lambda v=val: self._copy_to_clipboard(v))
1225
+
1226
+ self.copy_menu.add_separator()
1227
+ self.copy_menu.add_command(
1228
+ label="📦 Copy All as JSON Object",
1229
+ command=lambda v=d["json_payload"]: self._copy_to_clipboard(v, "✓ JSON کپی شد!"),
1230
+ )
1231
+
1232
+ def _copy_to_clipboard(self, text_val: str, toast_msg: str = "✓ کپی شد!"):
1233
+ self.root.clipboard_clear()
1234
+ self.root.clipboard_append(text_val)
1235
+ self.root.update()
1236
+ self._show_toast(toast_msg)
1237
+
1238
+ def _show_toast(self, msg: str):
1239
+ self._toast_text = msg
1240
+ self._refresh_display()
1241
+
1242
+ def _clear():
1243
+ self._toast_text = ""
1244
+ self._refresh_display()
1245
+
1246
+ self.root.after(1600, _clear)
1247
+
1248
+ def _build_calendar_window(self):
1249
+ self.cal_win = tk.Toplevel(self.root)
1250
+ self.cal_win.overrideredirect(True)
1251
+ bg = self.config["bg_color"]
1252
+ self.cal_win.configure(bg=bg)
1253
+
1254
+ self.cal_frame = tk.Frame(
1255
+ self.cal_win,
1256
+ bg=bg,
1257
+ highlightbackground=self.config["border_color"],
1258
+ highlightthickness=1,
1259
+ padx=12,
1260
+ pady=10,
1261
+ )
1262
+ self.cal_frame.pack(fill="both", expand=True)
1263
+
1264
+ self.cal_header = tk.Frame(self.cal_frame, bg=bg)
1265
+ self.cal_header.pack(fill="x", pady=(0, 6))
1266
+
1267
+ self.next_month_btn = tk.Label(
1268
+ self.cal_header,
1269
+ text="‹",
1270
+ font=("Segoe UI", 13, "bold"),
1271
+ fg=self.config["clock_color"],
1272
+ bg="#1E2638",
1273
+ padx=8,
1274
+ pady=0,
1275
+ cursor="hand2",
1276
+ )
1277
+ self.next_month_btn.pack(side="left")
1278
+ self.next_month_btn.bind("<Button-1>", lambda e: self._change_month(1))
1279
+ self._attach_hover(
1280
+ self.next_month_btn,
1281
+ "ماه بعد",
1282
+ base_fg_fn=lambda: self.config.get("clock_color", "#F8FAFC"),
1283
+ hover_bg="#0284C7",
1284
+ hover_fg="#FFFFFF",
1285
+ base_bg_fn=lambda: "#1E2638",
1286
+ )
1287
+
1288
+ self.today_btn = tk.Label(
1289
+ self.cal_header,
1290
+ text="امروز",
1291
+ font=(self.config["font_family"], 8, "bold"),
1292
+ fg=self.config["accent_color"],
1293
+ bg="#1E2638",
1294
+ padx=6,
1295
+ pady=2,
1296
+ cursor="hand2",
1297
+ )
1298
+ self.today_btn.pack(side="left", padx=(4, 0))
1299
+ self.today_btn.bind("<Button-1>", lambda e: self._go_to_today())
1300
+ self._attach_hover(
1301
+ self.today_btn,
1302
+ "بازگشت به تاریخ امروز",
1303
+ base_fg_fn=lambda: self.config.get("accent_color", "#38BDF8"),
1304
+ hover_bg="#0284C7",
1305
+ hover_fg="#FFFFFF",
1306
+ base_bg_fn=lambda: "#1E2638",
1307
+ )
1308
+
1309
+ self.prev_month_btn = tk.Label(
1310
+ self.cal_header,
1311
+ text="›",
1312
+ font=("Segoe UI", 13, "bold"),
1313
+ fg=self.config["clock_color"],
1314
+ bg="#1E2638",
1315
+ padx=8,
1316
+ pady=0,
1317
+ cursor="hand2",
1318
+ )
1319
+ self.prev_month_btn.pack(side="right")
1320
+ self.prev_month_btn.bind("<Button-1>", lambda e: self._change_month(-1))
1321
+ self._attach_hover(
1322
+ self.prev_month_btn,
1323
+ "ماه قبل",
1324
+ base_fg_fn=lambda: self.config.get("clock_color", "#F8FAFC"),
1325
+ hover_bg="#0284C7",
1326
+ hover_fg="#FFFFFF",
1327
+ base_bg_fn=lambda: "#1E2638",
1328
+ )
1329
+
1330
+ self.cal_title_canvas = tk.Canvas(
1331
+ self.cal_header,
1332
+ height=26,
1333
+ bg=bg,
1334
+ highlightthickness=0,
1335
+ )
1336
+ self.cal_title_canvas.pack(side="right", fill="x", expand=True)
1337
+
1338
+ self.week_header = tk.Frame(self.cal_frame, bg=bg)
1339
+ self.week_header.pack(fill="x", pady=(0, 4))
1340
+ self.week_canvases: list[tk.Canvas] = []
1341
+ for col_idx in range(7):
1342
+ c_canvas = tk.Canvas(
1343
+ self.week_header,
1344
+ width=36,
1345
+ height=22,
1346
+ bg=bg,
1347
+ highlightthickness=0,
1348
+ )
1349
+ c_canvas.grid(row=0, column=col_idx, sticky="nsew", padx=1)
1350
+ self.week_header.grid_columnconfigure(col_idx, weight=1)
1351
+ self.week_canvases.append(c_canvas)
1352
+
1353
+ self.days_grid_frame = tk.Frame(self.cal_frame, bg=bg)
1354
+ self.days_grid_frame.pack(fill="x", pady=(0, 6))
1355
+
1356
+ self.day_cells: list[tk.Canvas] = []
1357
+ for r in range(6):
1358
+ self.days_grid_frame.grid_rowconfigure(r, weight=1)
1359
+ for c in range(7):
1360
+ self.days_grid_frame.grid_columnconfigure(c, weight=1)
1361
+ cell = tk.Canvas(
1362
+ self.days_grid_frame,
1363
+ width=36,
1364
+ height=28,
1365
+ bg=bg,
1366
+ highlightthickness=0,
1367
+ cursor="hand2",
1368
+ )
1369
+ cell.grid(row=r, column=c, sticky="nsew", padx=1, pady=1)
1370
+ self.day_cells.append(cell)
1371
+
1372
+ self.cal_sep = tk.Frame(self.cal_frame, bg=self.config["border_color"], height=1)
1373
+ self.cal_sep.pack(fill="x", pady=(2, 6))
1374
+
1375
+ self.detail_canvas = tk.Canvas(
1376
+ self.cal_frame,
1377
+ height=74,
1378
+ bg=bg,
1379
+ highlightthickness=0,
1380
+ )
1381
+ self.detail_canvas.pack(fill="both", expand=True)
1382
+
1383
+ self.cal_bottom_bar = tk.Frame(self.cal_frame, bg=bg)
1384
+ self.cal_bottom_bar.pack(fill="x", pady=(4, 0))
1385
+
1386
+ self.add_event_btn = tk.Label(
1387
+ self.cal_bottom_bar,
1388
+ text="⏰ + آلارم / رویداد",
1389
+ font=(self.config["font_family"], 8, "bold"),
1390
+ fg="#FBBF24",
1391
+ bg="#1E2638",
1392
+ padx=7,
1393
+ pady=3,
1394
+ cursor="hand2",
1395
+ )
1396
+ self.add_event_btn.pack(side="right")
1397
+ self.add_event_btn.bind("<Button-1>", lambda e: self.open_alarm_manager())
1398
+ self._attach_hover(
1399
+ self.add_event_btn,
1400
+ "افزودن یا ویرایش آلارم و رویداد با انتخاب چندروزه",
1401
+ base_fg_fn=lambda: "#FBBF24",
1402
+ hover_bg="#D97706",
1403
+ hover_fg="#FFFFFF",
1404
+ base_bg_fn=lambda: "#1E2638",
1405
+ )
1406
+
1407
+ self.add_occasion_btn = tk.Label(
1408
+ self.cal_bottom_bar,
1409
+ text="🎂 + مناسبت / تولد",
1410
+ font=(self.config["font_family"], 8, "bold"),
1411
+ fg="#F472B6",
1412
+ bg="#1E2638",
1413
+ padx=7,
1414
+ pady=3,
1415
+ cursor="hand2",
1416
+ )
1417
+ self.add_occasion_btn.pack(side="right", padx=(0, 6))
1418
+ self.add_occasion_btn.bind("<Button-1>", lambda e: self.open_custom_occasions_manager())
1419
+ self._attach_hover(
1420
+ self.add_occasion_btn,
1421
+ "ثبت تولد دوستان و مناسبت‌های شخصی روی تقویم + آلارم روز قبل",
1422
+ base_fg_fn=lambda: "#F472B6",
1423
+ hover_bg="#DB2777",
1424
+ hover_fg="#FFFFFF",
1425
+ base_bg_fn=lambda: "#1E2638",
1426
+ )
1427
+
1428
+ self.cal_copyright_lbl = tk.Label(
1429
+ self.cal_bottom_bar,
1430
+ text="® Shayan Bamyar",
1431
+ font=("Segoe UI", 7, "bold"),
1432
+ fg="#64748B",
1433
+ bg=bg,
1434
+ )
1435
+ self.cal_copyright_lbl.pack(side="left")
1436
+
1437
+ self.cal_win.bind("<Button-3>", self._show_context_menu)
1438
+
1439
+ if not self.config.get("calendar_expanded", False):
1440
+ self.cal_win.withdraw()
1441
+
1442
+ def _render_calendar_month(self):
1443
+ month_data = get_month_calendar(self.view_jy, self.view_jm, CUSTOM_OCCASIONS_PATH)
1444
+ use_fa = self.config.get("persian_digits", False)
1445
+ bg = self.config["bg_color"]
1446
+ font_fa = self.config.get("font_family", "Vazir")
1447
+
1448
+ self.cal_title_canvas.configure(bg=bg)
1449
+ self.cal_title_canvas.delete("all")
1450
+ self.cal_title_canvas.update_idletasks()
1451
+ tw = max(140, self.cal_title_canvas.winfo_width())
1452
+ draw_outlined_canvas_text(
1453
+ self.cal_title_canvas,
1454
+ tw // 2,
1455
+ 13,
1456
+ text=format_digits(month_data["header_title"], use_fa),
1457
+ font_spec=(font_fa, 10, "bold"),
1458
+ fill=self.config["clock_color"],
1459
+ outline="#000000",
1460
+ )
1461
+
1462
+ for col_idx, w_canvas in enumerate(self.week_canvases):
1463
+ p_idx = 6 - col_idx
1464
+ day_short = PERSIAN_WEEK_SHORT[p_idx]
1465
+ fg_color = self.config["holiday_color"] if p_idx == 6 else self.config["occasion_color"]
1466
+ w_canvas.configure(bg=bg)
1467
+ w_canvas.delete("all")
1468
+ draw_outlined_canvas_text(
1469
+ w_canvas,
1470
+ 18,
1471
+ 11,
1472
+ text=day_short,
1473
+ font_spec=(font_fa, 8, "bold"),
1474
+ fill=fg_color,
1475
+ outline="#000000",
1476
+ )
1477
+
1478
+ for cell in self.day_cells:
1479
+ cell.configure(bg=bg, cursor="arrow")
1480
+ cell.delete("all")
1481
+ cell.unbind("<Button-1>")
1482
+ cell.unbind("<Enter>")
1483
+ cell.unbind("<Leave>")
1484
+
1485
+ first_week_idx = month_data["first_day_week_idx"]
1486
+
1487
+ for day_info in month_data["days"]:
1488
+ d = day_info["jd"]
1489
+ offset = first_week_idx + (d - 1)
1490
+ row = offset // 7
1491
+ persian_col = offset % 7
1492
+ grid_col = 6 - persian_col
1493
+ cell_idx = row * 7 + grid_col
1494
+ if cell_idx >= len(self.day_cells):
1495
+ continue
1496
+
1497
+ cell = self.day_cells[cell_idx]
1498
+ day_str = format_digits(str(d), use_fa)
1499
+
1500
+ user_alarms = self.alarm_store.get_events_for_jalali_day(
1501
+ day_info["jy"], day_info["jm"], day_info["jd"], day_info["persian_week_idx"]
1502
+ )
1503
+ has_any_event = day_info["has_occasion"] or len(user_alarms) > 0
1504
+
1505
+ is_today = (
1506
+ day_info["jy"] == self.current_jy
1507
+ and day_info["jm"] == self.current_jm
1508
+ and day_info["jd"] == self.current_jd
1509
+ )
1510
+ is_selected = (
1511
+ self.selected_day_info
1512
+ and day_info["jy"] == self.selected_day_info["jy"]
1513
+ and day_info["jm"] == self.selected_day_info["jm"]
1514
+ and day_info["jd"] == self.selected_day_info["jd"]
1515
+ )
1516
+
1517
+ if is_today:
1518
+ cell_bg = "#0369A1"
1519
+ cell_fg = "#FFFFFF"
1520
+ elif is_selected:
1521
+ cell_bg = "#334155"
1522
+ cell_fg = self.config["holiday_color"] if day_info["is_holiday"] else "#FFFFFF"
1523
+ else:
1524
+ cell_bg = bg
1525
+ cell_fg = self.config["holiday_color"] if day_info["is_holiday"] else self.config["clock_color"]
1526
+
1527
+ cell.configure(bg=cell_bg, cursor="hand2")
1528
+ draw_outlined_canvas_text(
1529
+ cell,
1530
+ 18,
1531
+ 12,
1532
+ text=day_str,
1533
+ font_spec=(font_fa, 9, "bold" if (is_today or is_selected) else "normal"),
1534
+ fill=cell_fg,
1535
+ outline="#000000",
1536
+ )
1537
+ if has_any_event:
1538
+ dot_color = "#FBBF24" if user_alarms else self.config["accent_color"]
1539
+ cell.create_oval(16, 22, 20, 26, fill=dot_color, outline="#000000")
1540
+
1541
+ cell.bind("<Button-1>", lambda e, info=day_info: self._on_day_clicked(info))
1542
+ if not is_today and not is_selected:
1543
+ cell.bind("<Enter>", lambda e, c=cell: c.configure(bg="#1E293B"))
1544
+ cell.bind("<Leave>", lambda e, c=cell, b=cell_bg: c.configure(bg=b))
1545
+
1546
+ self._update_selected_day_panel()
1547
+
1548
+ def _on_day_clicked(self, day_info: dict):
1549
+ if self.config.get("locked", False):
1550
+ return
1551
+ self.selected_day_info = day_info
1552
+ self._render_calendar_month()
1553
+
1554
+ def _update_selected_day_panel(self):
1555
+ info = self.selected_day_info
1556
+ if not info:
1557
+ return
1558
+ use_fa = self.config.get("persian_digits", False)
1559
+ bg = self.config["bg_color"]
1560
+ font_fa = self.config.get("font_family", "Vazir")
1561
+
1562
+ self.detail_canvas.configure(bg=bg)
1563
+ self.detail_canvas.delete("all")
1564
+ cw = self.calendar_w - 28
1565
+
1566
+ status_badge = " (تعطیل)" if info["is_holiday"] else ""
1567
+ header_text = format_digits(f"{info['date_text']}{status_badge}", use_fa)
1568
+
1569
+ draw_outlined_canvas_text(
1570
+ self.detail_canvas,
1571
+ cw - 4,
1572
+ 4,
1573
+ text=header_text,
1574
+ font_spec=(font_fa, 9, "bold"),
1575
+ fill=self.config["holiday_color"] if info["is_holiday"] else self.config["accent_color"],
1576
+ outline="#000000",
1577
+ anchor="ne",
1578
+ justify="right",
1579
+ )
1580
+
1581
+ lines = []
1582
+ for title, is_hol in info.get("events", []):
1583
+ prefix = "🔴 " if is_hol else "• "
1584
+ lines.append(f"{prefix}{title}")
1585
+
1586
+ user_alarms = self.alarm_store.get_events_for_jalali_day(
1587
+ info["jy"], info["jm"], info["jd"], info["persian_week_idx"]
1588
+ )
1589
+ for a in user_alarms:
1590
+ t_str = f"{int(a.get('hour', 0)):02d}:{int(a.get('minute', 0)):02d}"
1591
+ lines.append(f"⏰ {t_str} - {a.get('title', '')}")
1592
+
1593
+ if lines:
1594
+ occ_text = format_digits("\n".join(lines[:3]), use_fa)
1595
+ draw_outlined_canvas_text(
1596
+ self.detail_canvas,
1597
+ cw - 4,
1598
+ 26,
1599
+ text=occ_text,
1600
+ font_spec=(font_fa, 8),
1601
+ fill=self.config["holiday_color"] if (info["is_holiday"] and info["has_occasion"]) else self.config["date_color"],
1602
+ outline="#000000",
1603
+ anchor="ne",
1604
+ justify="right",
1605
+ width=cw - 8,
1606
+ )
1607
+
1608
+ def _change_month(self, delta: int):
1609
+ if self.config.get("locked", False):
1610
+ return
1611
+ new_jm = self.view_jm + delta
1612
+ new_jy = self.view_jy
1613
+ if new_jm > 12:
1614
+ new_jm = 1
1615
+ new_jy += 1
1616
+ elif new_jm < 1:
1617
+ new_jm = 12
1618
+ new_jy -= 1
1619
+ self.view_jy = new_jy
1620
+ self.view_jm = new_jm
1621
+ month_data = get_month_calendar(self.view_jy, self.view_jm, CUSTOM_OCCASIONS_PATH)
1622
+ if self.view_jy == self.current_jy and self.view_jm == self.current_jm:
1623
+ for d_info in month_data["days"]:
1624
+ if d_info["jd"] == self.current_jd:
1625
+ self.selected_day_info = d_info
1626
+ break
1627
+ else:
1628
+ self.selected_day_info = month_data["days"][0]
1629
+ self._render_calendar_month()
1630
+
1631
+ def _go_to_today(self):
1632
+ if self.config.get("locked", False):
1633
+ return
1634
+ today = get_today_info(CUSTOM_OCCASIONS_PATH)
1635
+ self.view_jy = today["jy"]
1636
+ self.view_jm = today["jm"]
1637
+ self.selected_day_info = today
1638
+ self._render_calendar_month()
1639
+
1640
+ def _toggle_calendar(self, event=None):
1641
+ if event is not None and self.config.get("locked", False):
1642
+ return "break"
1643
+ expanded = not self.config.get("calendar_expanded", False)
1644
+ self.config["calendar_expanded"] = expanded
1645
+ self._save_config()
1646
+ self._sync_calendar_visibility()
1647
+ return "break"
1648
+
1649
+ def _sync_calendar_visibility(self):
1650
+ expanded = self.config.get("calendar_expanded", False)
1651
+ is_locked = bool(self.config.get("locked", False))
1652
+ z_mode = self.config.get("z_mode", "topmost")
1653
+
1654
+ if expanded:
1655
+ today = get_today_info(CUSTOM_OCCASIONS_PATH)
1656
+ self.view_jy = today["jy"]
1657
+ self.view_jm = today["jm"]
1658
+ if not self.selected_day_info:
1659
+ self.selected_day_info = today
1660
+ self._position_calendar_window()
1661
+ self.cal_win.deiconify()
1662
+ self._render_calendar_month()
1663
+ hide_from_taskbar(self.cal_win)
1664
+ apply_rounded_corners(self.cal_win, self.calendar_w, self.calendar_h, radius=16, enabled=True)
1665
+ cal_alpha = max(0.85, float(self.config.get("opacity", 0.90)))
1666
+ if is_locked and cal_alpha >= 1.0:
1667
+ cal_alpha = 0.99
1668
+ self.cal_win.attributes("-alpha", cal_alpha)
1669
+ apply_z_order_and_clickthrough(self.cal_win, z_mode, click_through=is_locked)
1670
+ self.extend_btn.configure(text="▸ بستن")
1671
+ else:
1672
+ if self.cal_win:
1673
+ self.cal_win.withdraw()
1674
+ self.extend_btn.configure(text="◂ تقویم")
1675
+
1676
+ def _position_calendar_window(self):
1677
+ if not self.cal_win or not self.widget_win:
1678
+ return
1679
+ cw, ch = self.calendar_w, self.calendar_h
1680
+
1681
+ # در صورتی که ویجت دسکتاپ مخفی است، تقویم بالای ساعت گوشه مانیتور محل کلیک باز شود
1682
+ hide_desktop = (
1683
+ bool(self.config.get("replace_windows_clock", False))
1684
+ and bool(self.config.get("replace_clock_hide_widget", False))
1685
+ )
1686
+ if hide_desktop or not self.widget_win.winfo_viewable():
1687
+ try:
1688
+ px = self.root.winfo_pointerx()
1689
+ py = self.root.winfo_pointery()
1690
+ except Exception:
1691
+ px, py = 0, 0
1692
+ ml, mt, mr, mb = get_monitor_work_area_at(px, py, self.root)
1693
+ cx = mr - cw - 12
1694
+ cy = mb - ch - 12
1695
+ self.cal_win.geometry(f"{cw}x{ch}+{int(cx)}+{int(cy)}")
1696
+ return
1697
+
1698
+ wx = self.widget_win.winfo_x()
1699
+ wy = self.widget_win.winfo_y()
1700
+ ww, wh = self.compact_w, self.compact_h
1701
+ ml, mt, mr, mb = get_monitor_work_area_at(wx + ww // 2, wy + wh // 2, self.root)
1702
+
1703
+ mode = self.config.get("calendar_position", "beside")
1704
+ if mode == "below":
1705
+ cx = wx + ww - cw
1706
+ cy = wy + wh + self.GAP
1707
+ if cy + ch > mb - 8:
1708
+ cy = wy - ch - self.GAP
1709
+ else:
1710
+ if wx - cw - self.GAP >= ml + 8:
1711
+ cx = wx - cw - self.GAP
1712
+ else:
1713
+ cx = wx + ww + self.GAP
1714
+ cy = wy
1715
+ if cy + ch > mb - 8:
1716
+ cy = max(mt + 8, mb - ch - 8)
1717
+
1718
+ cx = max(8, min(cx, screen_w - cw - 8))
1719
+ cy = max(8, min(cy, screen_h - ch - 8))
1720
+ self.cal_win.geometry(f"{cw}x{ch}+{int(cx)}+{int(cy)}")
1721
+
1722
+ def open_alarm_manager(self):
1723
+ if self.alarm_win and self.alarm_win.win and self.alarm_win.win.winfo_exists():
1724
+ self.alarm_win.win.deiconify()
1725
+ self.alarm_win.win.lift()
1726
+ self.alarm_win.win.focus_force()
1727
+ return
1728
+
1729
+ sel = self.selected_day_info or get_today_info(CUSTOM_OCCASIONS_PATH)
1730
+ init_jalali = (sel["jy"], sel["jm"], sel["jd"])
1731
+ self.alarm_win = AlarmManagerWindow(
1732
+ root=self.root,
1733
+ store=self.alarm_store,
1734
+ font_family=self.config.get("font_family", "Vazir"),
1735
+ initial_jalali=init_jalali,
1736
+ on_change_callback=self._on_alarms_updated,
1737
+ )
1738
+
1739
+ def _load_custom_occasions_dict(self) -> dict:
1740
+ if os.path.exists(CUSTOM_OCCASIONS_PATH):
1741
+ try:
1742
+ with open(CUSTOM_OCCASIONS_PATH, "r", encoding="utf-8") as f:
1743
+ data = json.load(f)
1744
+ if isinstance(data, dict):
1745
+ return data
1746
+ except Exception:
1747
+ pass
1748
+ return {}
1749
+
1750
+ def _save_custom_occasions_dict(self, data: dict):
1751
+ os.makedirs(os.path.dirname(CUSTOM_OCCASIONS_PATH), exist_ok=True)
1752
+ with open(CUSTOM_OCCASIONS_PATH, "w", encoding="utf-8") as f:
1753
+ json.dump(data, f, ensure_ascii=False, indent=2)
1754
+
1755
+ def open_custom_occasions_manager(self):
1756
+ """پنجره مدیریت مناسبت‌های شخصی و تولد دوستان + ثبت خودکار آلارم یادآور ۱ روز قبل"""
1757
+ if self.custom_occ_win and self.custom_occ_win.winfo_exists():
1758
+ self.custom_occ_win.deiconify()
1759
+ self.custom_occ_win.lift()
1760
+ self.custom_occ_win.focus_force()
1761
+ return
1762
+
1763
+ font_fa = self.config.get("font_family", "Vazir")
1764
+ sel = self.selected_day_info or get_today_info(CUSTOM_OCCASIONS_PATH)
1765
+ init_m = int(sel.get("jm", 1))
1766
+ init_d = int(sel.get("jd", 1))
1767
+ init_y = int(sel.get("jy", 1405))
1768
+
1769
+ win = tk.Toplevel(self.root)
1770
+ self.custom_occ_win = win
1771
+ win.title("🎂 مدیریت مناسبت‌های شخصی و تولدها")
1772
+ win.configure(bg="#0F172A")
1773
+ win.attributes("-topmost", True)
1774
+ w, h = 470, 520
1775
+ sx = (win.winfo_screenwidth() - w) // 2
1776
+ sy = (win.winfo_screenheight() - h) // 2
1777
+ win.geometry(f"{w}x{h}+{sx}+{sy}")
1778
+ win.resizable(False, False)
1779
+
1780
+ container = tk.Frame(win, bg="#0F172A", padx=14, pady=12)
1781
+ container.pack(fill="both", expand=True)
1782
+
1783
+ tk.Label(
1784
+ container,
1785
+ text="🎂 ثبت روز تولد دوستان و مناسبت‌های شخصی در تقویم",
1786
+ font=(font_fa, 10, "bold"),
1787
+ fg="#F472B6",
1788
+ bg="#0F172A",
1789
+ ).pack(anchor="e", pady=(0, 8))
1790
+
1791
+ form = tk.LabelFrame(
1792
+ container,
1793
+ text=" افزودن مناسبت جدید ",
1794
+ font=(font_fa, 9, "bold"),
1795
+ fg="#E2E8F0",
1796
+ bg="#1E293B",
1797
+ bd=1,
1798
+ padx=10,
1799
+ pady=8,
1800
+ )
1801
+ form.pack(fill="x", pady=(0, 10))
1802
+
1803
+ # عنوان مناسبت
1804
+ row1 = tk.Frame(form, bg="#1E293B")
1805
+ row1.pack(fill="x", pady=3)
1806
+ tk.Label(row1, text="عنوان:", font=(font_fa, 9), fg="#CBD5E1", bg="#1E293B").pack(side="right", padx=(6, 0))
1807
+ title_entry = tk.Entry(
1808
+ row1,
1809
+ font=(font_fa, 9),
1810
+ bg="#0F172A",
1811
+ fg="#F8FAFC",
1812
+ insertbackground="#F8FAFC",
1813
+ relief="flat",
1814
+ justify="right",
1815
+ )
1816
+ title_entry.pack(side="right", fill="x", expand=True, ipady=4, padx=(0, 6))
1817
+ title_entry.focus_set()
1818
+
1819
+ # نوع مناسبت
1820
+ row2 = tk.Frame(form, bg="#1E293B")
1821
+ row2.pack(fill="x", pady=4)
1822
+ kind_var = tk.StringVar(value="birthday")
1823
+ holiday_var = tk.BooleanVar(value=False)
1824
+ prev_alarm_var = tk.BooleanVar(value=True)
1825
+
1826
+ def on_kind_change():
1827
+ if kind_var.get() == "birthday":
1828
+ prev_alarm_var.set(True)
1829
+ holiday_var.set(False)
1830
+ elif kind_var.get() == "holiday":
1831
+ holiday_var.set(True)
1832
+ else:
1833
+ holiday_var.set(False)
1834
+
1835
+ for val, lbl_txt, fg_c in (
1836
+ ("birthday", "🎂 روز تولد", "#F472B6"),
1837
+ ("personal", "🎉 مناسبت شخصی", "#38BDF8"),
1838
+ ("holiday", "🏖 تعطیل شخصی", "#F87171"),
1839
+ ):
1840
+ tk.Radiobutton(
1841
+ row2,
1842
+ text=lbl_txt,
1843
+ value=val,
1844
+ variable=kind_var,
1845
+ command=on_kind_change,
1846
+ font=(font_fa, 8, "bold"),
1847
+ fg=fg_c,
1848
+ bg="#1E293B",
1849
+ selectcolor="#0F172A",
1850
+ activebackground="#1E293B",
1851
+ ).pack(side="right", padx=(8, 0))
1852
+
1853
+ # انتخاب ماه و روز شمسی
1854
+ row3 = tk.Frame(form, bg="#1E293B")
1855
+ row3.pack(fill="x", pady=4)
1856
+ tk.Label(row3, text="تاریخ شمسی:", font=(font_fa, 9), fg="#CBD5E1", bg="#1E293B").pack(side="right", padx=(6, 0))
1857
+
1858
+ month_names = [f"{m} - {PERSIAN_MONTHS[m]}" for m in range(1, 13)]
1859
+ month_var = tk.StringVar(value=month_names[max(0, min(11, init_m - 1))])
1860
+ m_menu = tk.OptionMenu(row3, month_var, *month_names)
1861
+ m_menu.configure(
1862
+ font=(font_fa, 8, "bold"),
1863
+ bg="#0F172A",
1864
+ fg="#F8FAFC",
1865
+ activebackground="#334155",
1866
+ highlightthickness=0,
1867
+ bd=0,
1868
+ )
1869
+ m_menu["menu"].configure(bg="#0F172A", fg="#F8FAFC", font=(font_fa, 8))
1870
+ m_menu.pack(side="right", padx=(6, 0))
1871
+
1872
+ tk.Label(row3, text="روز:", font=(font_fa, 9), fg="#CBD5E1", bg="#1E293B").pack(side="right", padx=(8, 4))
1873
+ day_spin = tk.Spinbox(
1874
+ row3,
1875
+ from_=1,
1876
+ to=31,
1877
+ width=4,
1878
+ font=("Segoe UI", 9, "bold"),
1879
+ bg="#0F172A",
1880
+ fg="#F8FAFC",
1881
+ buttonbackground="#334155",
1882
+ )
1883
+ day_spin.delete(0, "end")
1884
+ day_spin.insert(0, str(init_d))
1885
+ day_spin.pack(side="right")
1886
+
1887
+ # تیک آلارم ۱ روز قبل (تکرار سالانه)
1888
+ row4 = tk.Frame(form, bg="#1E293B")
1889
+ row4.pack(fill="x", pady=(6, 2))
1890
+ tk.Checkbutton(
1891
+ row4,
1892
+ text="⏰ ثبت خودکار آلارم یادآور ۱ روز قبل (تکرار سالانه)",
1893
+ variable=prev_alarm_var,
1894
+ font=(font_fa, 8, "bold"),
1895
+ fg="#FBBF24",
1896
+ bg="#1E293B",
1897
+ selectcolor="#0F172A",
1898
+ activebackground="#1E293B",
1899
+ anchor="e",
1900
+ ).pack(side="right")
1901
+
1902
+ row5 = tk.Frame(form, bg="#1E293B")
1903
+ row5.pack(fill="x", pady=2)
1904
+ tk.Label(row5, text="ساعت یادآوری روز قبل:", font=(font_fa, 8), fg="#CBD5E1", bg="#1E293B").pack(side="right", padx=(6, 0))
1905
+ sp_m = tk.Spinbox(row5, from_=0, to=59, width=3, format="%02.0f", font=("Segoe UI", 9, "bold"), bg="#0F172A", fg="#F8FAFC", buttonbackground="#334155")
1906
+ sp_m.delete(0, "end")
1907
+ sp_m.insert(0, "00")
1908
+ sp_m.pack(side="right", padx=2)
1909
+ tk.Label(row5, text=":", font=("Segoe UI", 9, "bold"), fg="#F8FAFC", bg="#1E293B").pack(side="right")
1910
+ sp_h = tk.Spinbox(row5, from_=0, to=23, width=3, format="%02.0f", font=("Segoe UI", 9, "bold"), bg="#0F172A", fg="#F8FAFC", buttonbackground="#334155")
1911
+ sp_h.delete(0, "end")
1912
+ sp_h.insert(0, "09")
1913
+ sp_h.pack(side="right", padx=2)
1914
+
1915
+ status_lbl = tk.Label(form, text="", font=(font_fa, 8, "bold"), fg="#10B981", bg="#1E293B")
1916
+ status_lbl.pack(anchor="e", pady=(2, 0))
1917
+
1918
+ # بخش لیست مناسبت‌های ثبت‌شده
1919
+ list_frame = tk.LabelFrame(
1920
+ container,
1921
+ text=" مناسبت‌های شخصی ثبت‌شده ",
1922
+ font=(font_fa, 9, "bold"),
1923
+ fg="#E2E8F0",
1924
+ bg="#1E293B",
1925
+ bd=1,
1926
+ padx=8,
1927
+ pady=6,
1928
+ )
1929
+ list_frame.pack(fill="both", expand=True)
1930
+
1931
+ list_canvas = tk.Canvas(list_frame, bg="#1E293B", highlightthickness=0)
1932
+ scrollbar = tk.Scrollbar(list_frame, orient="vertical", command=list_canvas.yview)
1933
+ items_inner = tk.Frame(list_canvas, bg="#1E293B")
1934
+ items_inner.bind("<Configure>", lambda e: list_canvas.configure(scrollregion=list_canvas.bbox("all")))
1935
+ list_canvas.create_window((0, 0), window=items_inner, anchor="nw")
1936
+ list_canvas.configure(yscrollcommand=scrollbar.set)
1937
+ scrollbar.pack(side="left", fill="y")
1938
+ list_canvas.pack(side="right", fill="both", expand=True)
1939
+
1940
+ def refresh_list():
1941
+ for ch in items_inner.winfo_children():
1942
+ ch.destroy()
1943
+ data = self._load_custom_occasions_dict()
1944
+ if not data:
1945
+ tk.Label(
1946
+ items_inner,
1947
+ text="هنوز مناسبتی ثبت نشده است.",
1948
+ font=(font_fa, 8),
1949
+ fg="#64748B",
1950
+ bg="#1E293B",
1951
+ ).pack(pady=16, padx=10)
1952
+ return
1953
+
1954
+ for mmdd in sorted(data.keys()):
1955
+ items = data.get(mmdd, [])
1956
+ try:
1957
+ m_i, d_i = map(int, mmdd.split("-"))
1958
+ m_name = PERSIAN_MONTHS[m_i] if 1 <= m_i <= 12 else str(m_i)
1959
+ date_lbl = f"{d_i} {m_name}"
1960
+ except Exception:
1961
+ date_lbl = mmdd
1962
+
1963
+ for idx_i, item in enumerate(items):
1964
+ t = item.get("title", "") if isinstance(item, dict) else str(item)
1965
+ is_h = bool(item.get("holiday", False)) if isinstance(item, dict) else False
1966
+ row = tk.Frame(items_inner, bg="#0F172A", padx=8, pady=5)
1967
+ row.pack(fill="x", pady=2, padx=2)
1968
+
1969
+ def make_del(k=mmdd, ix=idx_i, occ_title=t):
1970
+ def _del():
1971
+ d_cur = self._load_custom_occasions_dict()
1972
+ lst = d_cur.get(k, [])
1973
+ if 0 <= ix < len(lst):
1974
+ lst.pop(ix)
1975
+ if lst:
1976
+ d_cur[k] = lst
1977
+ else:
1978
+ d_cur.pop(k, None)
1979
+ self._save_custom_occasions_dict(d_cur)
1980
+ # حذف آلارم یادآور سالانه مرتبط در صورت وجود
1981
+ clean_t = occ_title.replace("🎂 ", "").strip()
1982
+ expected_alarm = f"🎂 یادآور فردا: {clean_t}"
1983
+ before_n = len(self.alarm_store.alarms)
1984
+ self.alarm_store.alarms = [
1985
+ a for a in self.alarm_store.alarms
1986
+ if not (a.get("repeat_mode") == "yearly" and a.get("title") == expected_alarm)
1987
+ ]
1988
+ if len(self.alarm_store.alarms) != before_n:
1989
+ self.alarm_store.save()
1990
+ self._on_alarms_updated()
1991
+ refresh_list()
1992
+ return _del
1993
+
1994
+ tk.Button(
1995
+ row,
1996
+ text="🗑 حذف",
1997
+ font=(font_fa, 8),
1998
+ bg="#7F1D1D",
1999
+ fg="#FCA5A5",
2000
+ relief="flat",
2001
+ cursor="hand2",
2002
+ command=make_del(),
2003
+ ).pack(side="left")
2004
+
2005
+ tk.Label(
2006
+ row,
2007
+ text=f"📅 {date_lbl} — {t}",
2008
+ font=(font_fa, 8, "bold"),
2009
+ fg="#F87171" if is_h else "#F8FAFC",
2010
+ bg="#0F172A",
2011
+ anchor="e",
2012
+ ).pack(side="right", fill="x", expand=True, padx=(8, 0))
2013
+
2014
+ def on_add_occasion():
2015
+ raw_title = title_entry.get().strip()
2016
+ if not raw_title:
2017
+ status_lbl.configure(text="لطفاً عنوان مناسبت یا نام را وارد کنید.", fg="#F87171")
2018
+ return
2019
+ try:
2020
+ jm = int(month_var.get().split("-")[0].strip())
2021
+ jd = int(day_spin.get())
2022
+ max_d = get_jalali_month_days(init_y, jm)
2023
+ jd = max(1, min(jd, max_d))
2024
+ except Exception:
2025
+ status_lbl.configure(text="تاریخ واردشده معتبر نیست.", fg="#F87171")
2026
+ return
2027
+
2028
+ kind = kind_var.get()
2029
+ final_title = raw_title
2030
+ if kind == "birthday" and "🎂" not in final_title:
2031
+ final_title = f"🎂 {final_title}"
2032
+
2033
+ key = f"{jm:02d}-{jd:02d}"
2034
+ data = self._load_custom_occasions_dict()
2035
+ data.setdefault(key, [])
2036
+ data[key].append({"title": final_title, "holiday": bool(holiday_var.get())})
2037
+ self._save_custom_occasions_dict(data)
2038
+
2039
+ alarm_msg = ""
2040
+ if prev_alarm_var.get():
2041
+ try:
2042
+ ah = max(0, min(23, int(sp_h.get())))
2043
+ am = max(0, min(59, int(sp_m.get())))
2044
+ except Exception:
2045
+ ah, am = 9, 0
2046
+ if jd > 1:
2047
+ pm, pd = jm, jd - 1
2048
+ else:
2049
+ pm = 12 if jm == 1 else jm - 1
2050
+ pd = get_jalali_month_days(init_y, pm)
2051
+ prev_key = f"{pm:02d}-{pd:02d}"
2052
+ clean_t = final_title.replace("🎂 ", "").strip()
2053
+ self.alarm_store.add_or_update({
2054
+ "title": f"🎂 یادآور فردا: {clean_t}",
2055
+ "hour": ah,
2056
+ "minute": am,
2057
+ "repeat_mode": "yearly",
2058
+ "yearly_days": [prev_key],
2059
+ "enabled": True,
2060
+ "play_sound": True,
2061
+ })
2062
+ alarm_msg = f" + آلارم روز قبل ({pd} {PERSIAN_MONTHS[pm]} ساعت {ah:02d}:{am:02d})"
2063
+
2064
+ title_entry.delete(0, "end")
2065
+ status_lbl.configure(text=f"✓ «{final_title}» ثبت شد{alarm_msg}", fg="#10B981")
2066
+ self._on_alarms_updated()
2067
+ refresh_list()
2068
+
2069
+ tk.Button(
2070
+ form,
2071
+ text="✓ افزودن مناسبت به تقویم",
2072
+ font=(font_fa, 9, "bold"),
2073
+ bg="#059669",
2074
+ fg="#FFFFFF",
2075
+ padx=12,
2076
+ pady=4,
2077
+ relief="flat",
2078
+ cursor="hand2",
2079
+ command=on_add_occasion,
2080
+ ).pack(anchor="w", pady=(6, 0))
2081
+
2082
+ refresh_list()
2083
+ hide_from_taskbar(win)
2084
+ apply_rounded_corners(win, w, h, radius=14, enabled=True)
2085
+
2086
+ def _on_alarms_updated(self):
2087
+ self._refresh_display()
2088
+ if self.config.get("calendar_expanded"):
2089
+ self._render_calendar_month()
2090
+
2091
+ def _on_alarm_dismissed(self, alarm: dict):
2092
+ """وقتی آلارم بدون Snooze بسته شد، اگر یک‌باره یا تاریخ‌محور بود از لیست حذف شود"""
2093
+ removed = self.alarm_store.on_alarm_dismissed(alarm)
2094
+ if removed:
2095
+ self._on_alarms_updated()
2096
+ if self.alarm_win and self.alarm_win.win and self.alarm_win.win.winfo_exists():
2097
+ self.alarm_win._refresh_list()
2098
+ self.alarm_win._render_picker_calendar()
2099
+
2100
+ def _init_position(self):
2101
+ ww, wh = self.compact_w, self.compact_h
2102
+
2103
+ x = self.config.get("x")
2104
+ y = self.config.get("y")
2105
+ if x is None or y is None:
2106
+ ml, mt, mr, mb = get_monitor_work_area_at(0, 0, self.root)
2107
+ x = mr - ww - 32
2108
+ y = mt + 32
2109
+ self.config["x"] = x
2110
+ self.config["y"] = y
2111
+ self._save_config()
2112
+ else:
2113
+ ml, mt, mr, mb = get_monitor_work_area_at(int(x) + ww // 2, int(y) + wh // 2, self.root)
2114
+
2115
+ if self.config.get("locked"):
2116
+ snap_side = self.config.get("snap_side", "right")
2117
+ x = (mr - ww) if snap_side == "right" else ml
2118
+
2119
+ x = max(ml, min(int(x), mr - ww))
2120
+ y = max(mt, min(int(y), mb - wh))
2121
+ self.widget_win.geometry(f"{ww}x{wh}+{x}+{y}")
2122
+ self._position_lock_window()
2123
+
2124
+ def _apply_all_styles(self):
2125
+ if not self.widget_win:
2126
+ return
2127
+
2128
+ hide_from_taskbar(self.widget_win)
2129
+ if self.lock_win:
2130
+ hide_from_taskbar(self.lock_win)
2131
+
2132
+ is_locked = bool(self.config.get("locked", False))
2133
+ transparent_bg = bool(self.config.get("transparent_bg", False))
2134
+ bg_color = self.config.get("bg_color", "#141821")
2135
+ border_color = self.config.get("border_color", "#2A3244")
2136
+ bg = TRANSPARENT_KEY if transparent_bg else bg_color
2137
+
2138
+ self.widget_win.configure(bg=bg)
2139
+ self.main_frame.configure(
2140
+ bg=bg,
2141
+ highlightbackground=border_color if not transparent_bg else bg,
2142
+ highlightthickness=0 if transparent_bg else 1,
2143
+ )
2144
+ self.canvas.configure(bg=bg)
2145
+ self.btn_container.configure(bg=bg)
2146
+
2147
+ btn_bg = self._get_btn_base_bg()
2148
+ font_fa = self.config.get("font_family", "Vazir")
2149
+
2150
+ for tip in self._tooltips:
2151
+ tip.font_family = font_fa
2152
+
2153
+ self.extend_btn.configure(
2154
+ bg=btn_bg,
2155
+ fg=self.config.get("accent_color", "#38BDF8"),
2156
+ font=(font_fa, 8, "bold"),
2157
+ )
2158
+ self.copy_time_btn.configure(bg=btn_bg, fg="#A7F3D0")
2159
+ self.guid_btn.configure(bg=btn_bg, fg="#C4B5FD")
2160
+ self.alarm_btn.configure(bg=btn_bg, fg="#FBBF24")
2161
+ self.settings_btn.configure(
2162
+ bg=btn_bg,
2163
+ fg=self.config.get("date_color", "#CBD5E1"),
2164
+ )
2165
+ if hasattr(self, "tz_btn"):
2166
+ self._update_tz_btn_appearance()
2167
+ if hasattr(self, "min_btn"):
2168
+ self.min_btn.configure(
2169
+ bg=btn_bg,
2170
+ fg=self.config.get("date_color", "#CBD5E1"),
2171
+ )
2172
+ if hasattr(self, "close_btn"):
2173
+ self.close_btn.configure(bg=btn_bg, fg="#FCA5A5")
2174
+
2175
+ self._refresh_display()
2176
+
2177
+ ww, wh = self.compact_w, self.compact_h
2178
+ cur_x = self.widget_win.winfo_x()
2179
+ cur_y = self.widget_win.winfo_y()
2180
+ ml, mt, mr, mb = get_monitor_work_area_at(cur_x + ww // 2, cur_y + wh // 2, self.root)
2181
+ if is_locked:
2182
+ snap_side = self.config.get("snap_side", "right")
2183
+ pos_x = (mr - ww) if snap_side == "right" else ml
2184
+ pos_y = max(mt, min(cur_y, mb - wh))
2185
+ else:
2186
+ pos_x = max(ml, min(cur_x, mr - ww))
2187
+ pos_y = max(mt, min(cur_y, mb - wh))
2188
+ self.widget_win.geometry(f"{ww}x{wh}+{int(pos_x)}+{int(pos_y)}")
2189
+ self._position_lock_window()
2190
+
2191
+ alpha_val = float(self.config.get("opacity", 0.90))
2192
+ if is_locked and alpha_val >= 1.0:
2193
+ alpha_val = 0.99
2194
+
2195
+ if transparent_bg:
2196
+ apply_rounded_corners(self.widget_win, ww, wh, enabled=False)
2197
+ self.widget_win.attributes("-transparentcolor", TRANSPARENT_KEY)
2198
+ self.widget_win.attributes("-alpha", alpha_val)
2199
+ else:
2200
+ self.widget_win.attributes("-transparentcolor", "")
2201
+ self.widget_win.attributes("-alpha", alpha_val)
2202
+ apply_rounded_corners(self.widget_win, ww, wh, radius=16, enabled=True)
2203
+
2204
+ z_mode = self.config.get("z_mode", "topmost")
2205
+ if self.lock_win:
2206
+ lock_bg = "#1E2638" if not transparent_bg else "#141821"
2207
+ lock_border = "#F59E0B" if is_locked else border_color
2208
+ self.lock_win.configure(bg=lock_bg)
2209
+ self.lock_frame.configure(bg=lock_bg, highlightbackground=lock_border, highlightthickness=1)
2210
+ self.lock_btn_label.configure(
2211
+ text="🔒" if is_locked else "🔓",
2212
+ fg="#FBBF24" if is_locked else self.config.get("accent_color", "#38BDF8"),
2213
+ bg=lock_bg,
2214
+ )
2215
+ apply_rounded_corners(self.lock_win, self.LOCK_BTN_SIZE, self.LOCK_BTN_SIZE, radius=6, enabled=True)
2216
+ self.lock_win.attributes("-alpha", max(0.85, alpha_val))
2217
+ apply_z_order_and_clickthrough(self.lock_win, z_mode, click_through=False)
2218
+
2219
+ if self.cal_win:
2220
+ self.cal_win.configure(bg=bg_color)
2221
+ self.cal_frame.configure(bg=bg_color, highlightbackground=border_color)
2222
+ self.cal_header.configure(bg=bg_color)
2223
+ self.week_header.configure(bg=bg_color)
2224
+ self.days_grid_frame.configure(bg=bg_color)
2225
+ self.cal_sep.configure(bg=border_color)
2226
+ self.cal_bottom_bar.configure(bg=bg_color)
2227
+ self.cal_copyright_lbl.configure(bg=bg_color)
2228
+ self.add_event_btn.configure(font=(font_fa, 8, "bold"))
2229
+ self.today_btn.configure(font=(font_fa, 8, "bold"))
2230
+
2231
+ apply_z_order_and_clickthrough(
2232
+ self.widget_win,
2233
+ z_mode,
2234
+ click_through=is_locked,
2235
+ )
2236
+ if self.lock_win:
2237
+ apply_z_order_and_clickthrough(self.lock_win, z_mode, click_through=False)
2238
+
2239
+ self._sync_calendar_visibility()
2240
+
2241
+ def _on_drag_start(self, event):
2242
+ if self.config.get("locked", False):
2243
+ return
2244
+ self._close_dev_popup_window()
2245
+ self._is_dragging = True
2246
+ self._drag_start_x = event.x_root - self.widget_win.winfo_x()
2247
+ self._drag_start_y = event.y_root - self.widget_win.winfo_y()
2248
+
2249
+ def _on_drag_motion(self, event):
2250
+ if not self._is_dragging or self.config.get("locked", False):
2251
+ return
2252
+ new_x = event.x_root - self._drag_start_x
2253
+ new_y = event.y_root - self._drag_start_y
2254
+ self.widget_win.geometry(f"{self.compact_w}x{self.compact_h}+{int(new_x)}+{int(new_y)}")
2255
+ self._position_lock_window()
2256
+ if self.config.get("calendar_expanded", False):
2257
+ self._position_calendar_window()
2258
+
2259
+ def _on_drag_end(self, event):
2260
+ if not self._is_dragging:
2261
+ return
2262
+ self._is_dragging = False
2263
+ self.config["x"] = self.widget_win.winfo_x()
2264
+ self.config["y"] = self.widget_win.winfo_y()
2265
+ self._unlocked_x = self.config["x"]
2266
+ self._unlocked_y = self.config["y"]
2267
+ self._save_config()
2268
+ z_mode = self.config.get("z_mode", "topmost")
2269
+ is_locked = bool(self.config.get("locked", False))
2270
+ apply_z_order_and_clickthrough(self.widget_win, z_mode, click_through=is_locked)
2271
+ if self.lock_win:
2272
+ apply_z_order_and_clickthrough(self.lock_win, z_mode, click_through=False)
2273
+
2274
+ def _build_context_menu(self):
2275
+ self.menu = tk.Menu(
2276
+ self.root,
2277
+ tearoff=0,
2278
+ bg="#1E293B",
2279
+ fg="#F8FAFC",
2280
+ activebackground="#0284C7",
2281
+ activeforeground="#FFFFFF",
2282
+ font=("Tahoma", 9),
2283
+ )
2284
+
2285
+ def _populate_context_menu(self):
2286
+ self.menu.delete(0, "end")
2287
+
2288
+ locked_label = (
2289
+ "🔓 باز کردن قفل ویجت (فعال‌سازی کلیک و جابه‌جایی)"
2290
+ if self.config.get("locked")
2291
+ else "🔒 قفل و فیکس کردن ویجت (کوچک‌ترین حالت و چسبیدن به لبه صفحه)"
2292
+ )
2293
+ self.menu.add_command(label=locked_label, command=self._toggle_lock)
2294
+ self.menu.add_separator()
2295
+
2296
+ if getattr(self, "_is_minimized", False):
2297
+ self.menu.add_command(
2298
+ label="🗖 نمایش مجدد ویجت روی صفحه (Restore)",
2299
+ command=self.restore_widget,
2300
+ )
2301
+ else:
2302
+ self.menu.add_command(
2303
+ label="🗕 مینیمایز / بستن به Hidden Icons (بدون آیکون در تسک‌بار)",
2304
+ command=self.minimize_widget,
2305
+ )
2306
+ self.menu.add_separator()
2307
+
2308
+ is_utc_primary = self.config.get("primary_timezone", "tehran") == "utc"
2309
+ tz_label = (
2310
+ "🕒 ساعت اصلی: UTC (تبدیل به تهران)"
2311
+ if is_utc_primary
2312
+ else "🕒 ساعت اصلی: تهران (تبدیل به UTC)"
2313
+ )
2314
+ self.menu.add_command(label=tz_label, command=self._toggle_primary_timezone)
2315
+ utc_row_label = (
2316
+ "✓ 🌐 نمایش ردیف زمان UTC/تهران در ویجت (فعال)"
2317
+ if self.config.get("show_utc")
2318
+ else "🌐 نمایش ردیف زمان UTC در ویجت"
2319
+ )
2320
+ self.menu.add_command(label=utc_row_label, command=self._toggle_show_utc)
2321
+ self.menu.add_separator()
2322
+
2323
+ self.menu.add_command(
2324
+ label="🎲 رندر و کپی فوری GUID جدید (UUID v4)",
2325
+ command=lambda: self._copy_to_clipboard(str(uuid.uuid4()), "✓ GUID کپی شد!"),
2326
+ )
2327
+ self.menu.add_command(
2328
+ label="📋 باز کردن پنل کپی زمان (۱۰ فرمت API) و GUID...",
2329
+ command=self._toggle_dev_popup_window,
2330
+ )
2331
+
2332
+ self._populate_dev_copy_menu()
2333
+ self.menu.add_cascade(
2334
+ label="🕒 لیست سریع فرمت‌های زمان API و GUID",
2335
+ menu=self.copy_menu,
2336
+ )
2337
+ self.menu.add_separator()
2338
+
2339
+ self.menu.add_command(
2340
+ label="⏰ مدیریت رویدادها و آلارم‌ها...",
2341
+ command=self.open_alarm_manager,
2342
+ )
2343
+ self.menu.add_command(
2344
+ label="🎂 مدیریت مناسبت‌های شخصی و تولدها...",
2345
+ command=self.open_custom_occasions_manager,
2346
+ )
2347
+
2348
+ self.menu.add_command(
2349
+ label="⚙️ تنظیمات ظاهری، رنگ، سایز و فونت...",
2350
+ command=self.open_settings_window,
2351
+ )
2352
+
2353
+ cal_text = "▾ بستن تقویم ماهانه" if self.config.get("calendar_expanded") else "📅 نمایش تقویم ماهانه (Extend)"
2354
+ self.menu.add_command(label=cal_text, command=lambda: self._toggle_calendar(None))
2355
+
2356
+ z_menu = tk.Menu(
2357
+ self.menu,
2358
+ tearoff=0,
2359
+ bg="#1E293B",
2360
+ fg="#F8FAFC",
2361
+ activebackground="#0284C7",
2362
+ activeforeground="#FFFFFF",
2363
+ font=("Tahoma", 9),
2364
+ )
2365
+ cur_z = self.config.get("z_mode", "topmost")
2366
+ for mode_key, mode_title in [
2367
+ ("topmost", "همیشه روی تمام برنامه‌ها (Z-Index بالا - پیشنهادی)"),
2368
+ ("desktop", "چسبیده به دسکتاپ (پشت پنجره‌های باز)"),
2369
+ ]:
2370
+ prefix = "✓ " if cur_z == mode_key else ""
2371
+ z_menu.add_command(
2372
+ label=f"{prefix}{mode_title}",
2373
+ command=lambda m=mode_key: self._set_z_mode(m),
2374
+ )
2375
+ self.menu.add_cascade(label="📌 لایه قرارگیری (Z-Index)", menu=z_menu)
2376
+
2377
+ bg_label = (
2378
+ "✓ 🖼 حالت: بدون پس‌زمینه (تغییر به کارت با پس‌زمینه)"
2379
+ if self.config.get("transparent_bg")
2380
+ else "🖼 حالت: با پس‌زمینه (تغییر به بدون پس‌زمینه)"
2381
+ )
2382
+ self.menu.add_command(label=bg_label, command=self._toggle_transparent_bg)
2383
+
2384
+ digits_label = (
2385
+ "🔢 نمایش اعداد: فارسی (تغییر به انگلیسی)"
2386
+ if self.config.get("persian_digits")
2387
+ else "🔢 نمایش اعداد: انگلیسی (تغییر به فارسی)"
2388
+ )
2389
+ self.menu.add_command(label=digits_label, command=self._toggle_digits)
2390
+
2391
+ self.menu.add_separator()
2392
+
2393
+ startup_on = is_startup_enabled()
2394
+ os_name_fa = "ویندوز" if sys.platform == "win32" else "لینوکس"
2395
+ startup_label = f"✓ 🚀 اجرا با شروع {os_name_fa} (فعال)" if startup_on else f"🚀 اجرا خودکار با شروع {os_name_fa} (Startup)"
2396
+ self.menu.add_command(label=startup_label, command=self._toggle_startup)
2397
+
2398
+ # جایگزینی کامل ساعت ویندوز در تسک‌بار
2399
+ replace_clk_label = (
2400
+ "✓ ⭐ جایگزینی کامل ساعت و تاریخ ویندوز در تسک‌بار (فعال)"
2401
+ if self.config.get("replace_windows_clock")
2402
+ else "⭐ جایگزینی کامل ساعت و تاریخ ویندوز در تسک‌بار"
2403
+ )
2404
+ self.menu.add_command(label=replace_clk_label, command=lambda: self._toggle_taskbar_setting("replace_windows_clock"))
2405
+
2406
+ if self.config.get("replace_windows_clock"):
2407
+ hide_desk_label = (
2408
+ "✓ 👁️ مخفی کردن ویجت دسکتاپ (فقط ساعت تسک‌بار)"
2409
+ if self.config.get("replace_clock_hide_widget")
2410
+ else "👁️ مخفی کردن ویجت دسکتاپ (فقط ساعت تسک‌بار)"
2411
+ )
2412
+ self.menu.add_command(label=hide_desk_label, command=lambda: self._toggle_taskbar_setting("replace_clock_hide_widget"))
2413
+
2414
+ tb_clock_label = (
2415
+ "✓ 🕒 نمایش ساعت و تاریخ شناور روی تسک‌بار (فعال)"
2416
+ if self.config.get("taskbar_clock")
2417
+ else "🕒 نمایش ساعت و تاریخ شناور روی تسک‌بار"
2418
+ )
2419
+ self.menu.add_command(label=tb_clock_label, command=lambda: self._toggle_taskbar_setting("taskbar_clock"))
2420
+ tb_btn_label = (
2421
+ "✓ 📌 نمایش آیکون برنامه در تسک‌بار (فعال)"
2422
+ if self.config.get("taskbar_button")
2423
+ else "📌 نمایش آیکون برنامه در تسک‌بار"
2424
+ )
2425
+ self.menu.add_command(label=tb_btn_label, command=lambda: self._toggle_taskbar_setting("taskbar_button"))
2426
+
2427
+ self.menu.add_command(label="🔄 بازنشانی مکان به گوشه مانیتور", command=self._reset_position)
2428
+ self.menu.add_separator()
2429
+ self.menu.add_command(label="® Shayan Bamyar", state="disabled")
2430
+ self.menu.add_command(label="❌ خروج کامل از ویجت", command=self.quit_app)
2431
+
2432
+ def _show_context_menu(self, event):
2433
+ if self.config.get("locked", False):
2434
+ return
2435
+ self._populate_context_menu()
2436
+ try:
2437
+ self.menu.tk_popup(event.x_root, event.y_root)
2438
+ finally:
2439
+ self.menu.grab_release()
2440
+
2441
+ def _set_z_mode(self, mode: str):
2442
+ self.config["z_mode"] = mode
2443
+ self._save_config()
2444
+ self._apply_all_styles()
2445
+
2446
+ def _toggle_lock(self):
2447
+ self._close_dev_popup_window()
2448
+ going_to_lock = not self.config.get("locked", False)
2449
+ self.config["locked"] = going_to_lock
2450
+ wx = self.widget_win.winfo_x() if self.widget_win else int(self.config.get("x") or 0)
2451
+ wy = self.widget_win.winfo_y() if self.widget_win else int(self.config.get("y") or 0)
2452
+ ml, _mt, mr, _mb = get_monitor_work_area_at(wx + self.compact_w // 2, wy + self.compact_h // 2, self.root)
2453
+ if going_to_lock:
2454
+ # ذخیره مکان آزاد قبل از قفل و تعیین جهت چسبیدن به لبه مانیتور فعلی (چپ یا راست)
2455
+ if self.widget_win:
2456
+ self._unlocked_x = wx
2457
+ self._unlocked_y = wy
2458
+ center_x = wx + (self.compact_w / 2)
2459
+ self.config["snap_side"] = "right" if center_x >= ((ml + mr) / 2) else "left"
2460
+ if self.config.get("calendar_expanded", False):
2461
+ self.config["calendar_expanded"] = False
2462
+ else:
2463
+ # هنگام باز کردن قفل، مکان در همان مانیتور فعلی بماند و از صفحه بیرون نزند
2464
+ if self.config.get("snap_side") == "right":
2465
+ self.config["x"] = max(ml + 10, mr - self.BASE_MIN_W - 20)
2466
+ elif getattr(self, "_unlocked_x", None) is not None:
2467
+ self.config["x"] = max(ml + 10, min(int(self._unlocked_x), mr - self.BASE_MIN_W - 10))
2468
+ self._save_config()
2469
+ self._apply_all_styles()
2470
+ if hasattr(self, "_settings_lock_var") and self._settings_lock_var is not None:
2471
+ try:
2472
+ self._settings_lock_var.set(bool(self.config["locked"]))
2473
+ except Exception:
2474
+ pass
2475
+
2476
+ def _toggle_transparent_bg(self):
2477
+ self.config["transparent_bg"] = not self.config.get("transparent_bg", False)
2478
+ self._save_config()
2479
+ self._apply_all_styles()
2480
+
2481
+ def _toggle_digits(self):
2482
+ self.config["persian_digits"] = not self.config.get("persian_digits", False)
2483
+ self._save_config()
2484
+ self._apply_all_styles()
2485
+
2486
+ def _toggle_startup(self):
2487
+ cur = is_startup_enabled()
2488
+ set_startup_enabled(not cur, os.path.abspath(sys.argv[0]))
2489
+
2490
+ def _reset_position(self):
2491
+ self.config["x"] = None
2492
+ self.config["y"] = None
2493
+ self._init_position()
2494
+ if self.config.get("calendar_expanded"):
2495
+ self._position_calendar_window()
2496
+
2497
+ def open_settings_window(self):
2498
+ if self.settings_win and self.settings_win.winfo_exists():
2499
+ self.settings_win.deiconify()
2500
+ self.settings_win.lift()
2501
+ self.settings_win.focus_force()
2502
+ return
2503
+
2504
+ win = tk.Toplevel(self.root)
2505
+ self.settings_win = win
2506
+ win.title("تنظیمات ویجت ساعت و تقویم شمسی")
2507
+ win.configure(bg="#0F172A")
2508
+ win.resizable(False, False)
2509
+ win.attributes("-topmost", True)
2510
+
2511
+ ico_path = get_resource_path(os.path.join("assets", "icons", "app_icon.ico"))
2512
+ if os.path.exists(ico_path):
2513
+ try:
2514
+ win.iconbitmap(ico_path)
2515
+ except Exception:
2516
+ pass
2517
+
2518
+ w_width, w_height = 500, 800
2519
+ sx = (win.winfo_screenwidth() - w_width) // 2
2520
+ sy = (win.winfo_screenheight() - w_height) // 2
2521
+ win.geometry(f"{w_width}x{w_height}+{sx}+{sy}")
2522
+
2523
+ font_fa = self.config.get("font_family", "Vazir")
2524
+ container = tk.Frame(win, bg="#0F172A", padx=18, pady=14)
2525
+ container.pack(fill="both", expand=True)
2526
+
2527
+ tk.Label(
2528
+ container,
2529
+ text="⚙️ تنظیمات ظاهری و رفتاری ویجت",
2530
+ font=(font_fa, 12, "bold"),
2531
+ fg="#38BDF8",
2532
+ bg="#0F172A",
2533
+ anchor="e",
2534
+ ).pack(fill="x", pady=(0, 8))
2535
+
2536
+ sec1 = tk.LabelFrame(
2537
+ container,
2538
+ text=" ۱. لایه نمایش (Z-Index) و قفل روی صفحه ",
2539
+ font=(font_fa, 9, "bold"),
2540
+ fg="#E2E8F0",
2541
+ bg="#1E293B",
2542
+ bd=1,
2543
+ padx=10,
2544
+ pady=6,
2545
+ )
2546
+ sec1.pack(fill="x", pady=(0, 8))
2547
+
2548
+ z_var = tk.StringVar(value=self.config.get("z_mode", "topmost"))
2549
+
2550
+ def on_z_change():
2551
+ self.config["z_mode"] = z_var.get()
2552
+ self._save_config()
2553
+ self._apply_all_styles()
2554
+
2555
+ for val, txt in [
2556
+ ("topmost", "همیشه روی تمام برنامه‌ها (با باز شدن برنامه‌ها، ویجت روی آن‌ها می‌ماند)"),
2557
+ ("desktop", "چسبیده به والپیپر دسکتاپ (پشت پنجره‌های باز)"),
2558
+ ]:
2559
+ tk.Radiobutton(
2560
+ sec1,
2561
+ text=txt,
2562
+ variable=z_var,
2563
+ value=val,
2564
+ command=on_z_change,
2565
+ font=(font_fa, 8),
2566
+ fg="#F8FAFC",
2567
+ bg="#1E293B",
2568
+ selectcolor="#0F172A",
2569
+ activebackground="#1E293B",
2570
+ activeforeground="#38BDF8",
2571
+ anchor="w",
2572
+ ).pack(fill="x", pady=1)
2573
+
2574
+ self._settings_lock_var = tk.BooleanVar(value=bool(self.config.get("locked", False)))
2575
+
2576
+ def on_lock_change():
2577
+ new_locked = self._settings_lock_var.get()
2578
+ self.config["locked"] = new_locked
2579
+ wx = self.widget_win.winfo_x() if self.widget_win else int(self.config.get("x") or 0)
2580
+ wy = self.widget_win.winfo_y() if self.widget_win else int(self.config.get("y") or 0)
2581
+ ml, _mt, mr, _mb = get_monitor_work_area_at(wx + self.compact_w // 2, wy + self.compact_h // 2, self.root)
2582
+ if new_locked:
2583
+ if self.widget_win:
2584
+ self._unlocked_x = wx
2585
+ self._unlocked_y = wy
2586
+ center_x = wx + (self.compact_w / 2)
2587
+ self.config["snap_side"] = "right" if center_x >= ((ml + mr) / 2) else "left"
2588
+ if self.config.get("calendar_expanded", False):
2589
+ self.config["calendar_expanded"] = False
2590
+ else:
2591
+ if self.config.get("snap_side") == "right":
2592
+ self.config["x"] = max(ml + 10, mr - self.BASE_MIN_W - 20)
2593
+ elif getattr(self, "_unlocked_x", None) is not None:
2594
+ self.config["x"] = max(ml + 10, min(int(self._unlocked_x), mr - self.BASE_MIN_W - 10))
2595
+ self._save_config()
2596
+ self._apply_all_styles()
2597
+
2598
+ tk.Checkbutton(
2599
+ sec1,
2600
+ text="قفل و فیکس کردن ویجت (🔒 عبوردهی کلیک به برنامه زیرین؛ فقط دکمه قفل قابل کلیک است)",
2601
+ variable=self._settings_lock_var,
2602
+ command=on_lock_change,
2603
+ font=(font_fa, 8, "bold"),
2604
+ fg="#FBBF24",
2605
+ bg="#1E293B",
2606
+ selectcolor="#0F172A",
2607
+ activebackground="#1E293B",
2608
+ ).pack(anchor="w", pady=(4, 0))
2609
+
2610
+ startup_var = tk.BooleanVar(value=is_startup_enabled())
2611
+ os_name_fa = "ویندوز" if sys.platform == "win32" else "لینوکس"
2612
+
2613
+ def on_startup_change():
2614
+ want = bool(startup_var.get())
2615
+ script_target = os.path.abspath(sys.argv[0]) if sys.argv else os.path.abspath(__file__)
2616
+ ok = set_startup_enabled(want, script_target)
2617
+ if not ok:
2618
+ startup_var.set(is_startup_enabled())
2619
+
2620
+ tk.Checkbutton(
2621
+ sec1,
2622
+ text=f"🚀 اجرا خودکار ویجت هم‌زمان با بالا آمدن {os_name_fa} (Startup)",
2623
+ variable=startup_var,
2624
+ command=on_startup_change,
2625
+ font=(font_fa, 8, "bold"),
2626
+ fg="#38BDF8",
2627
+ bg="#1E293B",
2628
+ selectcolor="#0F172A",
2629
+ activebackground="#1E293B",
2630
+ ).pack(anchor="w", pady=(2, 0))
2631
+
2632
+ sec2 = tk.LabelFrame(
2633
+ container,
2634
+ text=" ۲. پس‌زمینه و میزان شفافیت ",
2635
+ font=(font_fa, 9, "bold"),
2636
+ fg="#E2E8F0",
2637
+ bg="#1E293B",
2638
+ bd=1,
2639
+ padx=10,
2640
+ pady=6,
2641
+ )
2642
+ sec2.pack(fill="x", pady=(0, 8))
2643
+
2644
+ trans_var = tk.BooleanVar(value=bool(self.config.get("transparent_bg", False)))
2645
+
2646
+ def on_trans_change():
2647
+ self.config["transparent_bg"] = trans_var.get()
2648
+ self._save_config()
2649
+ self._apply_all_styles()
2650
+
2651
+ tk.Checkbutton(
2652
+ sec2,
2653
+ text="حالت بدون پس‌زمینه (نمایش فقط متن با خط دور مشکی روی صفحه)",
2654
+ variable=trans_var,
2655
+ command=on_trans_change,
2656
+ font=(font_fa, 8, "bold"),
2657
+ fg="#F8FAFC",
2658
+ bg="#1E293B",
2659
+ selectcolor="#0F172A",
2660
+ activebackground="#1E293B",
2661
+ ).pack(anchor="w")
2662
+
2663
+ op_row = tk.Frame(sec2, bg="#1E293B")
2664
+ op_row.pack(fill="x", pady=(4, 0))
2665
+ tk.Label(
2666
+ op_row,
2667
+ text="شفافیت کل ویجت (%):",
2668
+ font=(font_fa, 8),
2669
+ fg="#CBD5E1",
2670
+ bg="#1E293B",
2671
+ ).pack(side="right")
2672
+
2673
+ op_scale = tk.Scale(
2674
+ op_row,
2675
+ from_=25,
2676
+ to=100,
2677
+ orient="horizontal",
2678
+ bg="#1E293B",
2679
+ fg="#F8FAFC",
2680
+ highlightthickness=0,
2681
+ troughcolor="#0F172A",
2682
+ length=220,
2683
+ command=lambda v: self._on_opacity_slider(int(v)),
2684
+ )
2685
+ op_scale.set(int(float(self.config.get("opacity", 0.90)) * 100))
2686
+ op_scale.pack(side="left")
2687
+
2688
+ sec3 = tk.LabelFrame(
2689
+ container,
2690
+ text=" ۳. انتخاب رنگ نوشته‌ها و پس‌زمینه ",
2691
+ font=(font_fa, 9, "bold"),
2692
+ fg="#E2E8F0",
2693
+ bg="#1E293B",
2694
+ bd=1,
2695
+ padx=10,
2696
+ pady=6,
2697
+ )
2698
+ sec3.pack(fill="x", pady=(0, 8))
2699
+
2700
+ color_items = [
2701
+ ("clock_color", "رنگ ساعت:"),
2702
+ ("date_color", "رنگ تاریخ شمسی:"),
2703
+ ("occasion_color", "رنگ مناسبت‌ها:"),
2704
+ ("holiday_color", "رنگ روزهای تعطیل:"),
2705
+ ("bg_color", "رنگ کارت پس‌زمینه:"),
2706
+ ("accent_color", "رنگ دکمه‌ها و تاکید:"),
2707
+ ]
2708
+
2709
+ self._color_previews: dict[str, tk.Button] = {}
2710
+ grid_colors = tk.Frame(sec3, bg="#1E293B")
2711
+ grid_colors.pack(fill="x")
2712
+
2713
+ for idx, (cfg_key, label_txt) in enumerate(color_items):
2714
+ r = idx // 2
2715
+ c = (idx % 2) * 2
2716
+ tk.Label(
2717
+ grid_colors,
2718
+ text=label_txt,
2719
+ font=(font_fa, 8),
2720
+ fg="#CBD5E1",
2721
+ bg="#1E293B",
2722
+ anchor="e",
2723
+ ).grid(row=r, column=c + 1, sticky="e", padx=(6, 4), pady=3)
2724
+
2725
+ btn = tk.Button(
2726
+ grid_colors,
2727
+ text="انتخاب رنگ",
2728
+ font=(font_fa, 8),
2729
+ bg=self.config.get(cfg_key, "#FFFFFF"),
2730
+ fg="#000000" if cfg_key != "bg_color" else "#FFFFFF",
2731
+ width=10,
2732
+ relief="flat",
2733
+ cursor="hand2",
2734
+ command=lambda k=cfg_key: self._pick_color(k),
2735
+ )
2736
+ btn.grid(row=r, column=c, sticky="w", padx=4, pady=3)
2737
+ self._color_previews[cfg_key] = btn
2738
+
2739
+ for ci in range(4):
2740
+ grid_colors.grid_columnconfigure(ci, weight=1)
2741
+
2742
+ sec4 = tk.LabelFrame(
2743
+ container,
2744
+ text=" ۴. اندازه ویجت و تنظیمات فونت (پیش‌فرض: Vazir) ",
2745
+ font=(font_fa, 9, "bold"),
2746
+ fg="#E2E8F0",
2747
+ bg="#1E293B",
2748
+ bd=1,
2749
+ padx=10,
2750
+ pady=6,
2751
+ )
2752
+ sec4.pack(fill="x", pady=(0, 8))
2753
+
2754
+ scale_row = tk.Frame(sec4, bg="#1E293B")
2755
+ scale_row.pack(fill="x", pady=2)
2756
+ tk.Label(
2757
+ scale_row,
2758
+ text="اندازه کلی ویجت (%):",
2759
+ font=(font_fa, 8),
2760
+ fg="#CBD5E1",
2761
+ bg="#1E293B",
2762
+ ).pack(side="right")
2763
+
2764
+ widget_scale_slider = tk.Scale(
2765
+ scale_row,
2766
+ from_=70,
2767
+ to=170,
2768
+ orient="horizontal",
2769
+ bg="#1E293B",
2770
+ fg="#F8FAFC",
2771
+ highlightthickness=0,
2772
+ troughcolor="#0F172A",
2773
+ length=220,
2774
+ command=lambda v: self._on_scale_slider(int(v)),
2775
+ )
2776
+ widget_scale_slider.set(int(self.config.get("widget_scale", 100)))
2777
+ widget_scale_slider.pack(side="left")
2778
+
2779
+ bundled_and_std = [
2780
+ "Vazir",
2781
+ "B Yekan+",
2782
+ "A Iranian Sans",
2783
+ "Tahoma",
2784
+ "Segoe UI",
2785
+ "Calibri",
2786
+ "Arial",
2787
+ "Consolas",
2788
+ ]
2789
+ try:
2790
+ sys_fonts = set(tkfont.families())
2791
+ for pf in ["Vazirmatn", "IRANSans", "IRANSansWeb", "B Nazanin", "B Yekan", "Samim", "Shabnam"]:
2792
+ if pf in sys_fonts and pf not in bundled_and_std:
2793
+ bundled_and_std.append(pf)
2794
+ except Exception:
2795
+ pass
2796
+
2797
+ font_row = tk.Frame(sec4, bg="#1E293B")
2798
+ font_row.pack(fill="x", pady=3)
2799
+ tk.Label(
2800
+ font_row,
2801
+ text="فونت تاریخ و متون:",
2802
+ font=(font_fa, 8),
2803
+ fg="#CBD5E1",
2804
+ bg="#1E293B",
2805
+ ).pack(side="right")
2806
+
2807
+ font_cb = ttk.Combobox(font_row, values=bundled_and_std, state="readonly", width=20)
2808
+ font_cb.set(self.config.get("font_family", "Vazir"))
2809
+ font_cb.pack(side="left")
2810
+
2811
+ clock_font_row = tk.Frame(sec4, bg="#1E293B")
2812
+ clock_font_row.pack(fill="x", pady=3)
2813
+ tk.Label(
2814
+ clock_font_row,
2815
+ text="فونت اعداد ساعت:",
2816
+ font=(font_fa, 8),
2817
+ fg="#CBD5E1",
2818
+ bg="#1E293B",
2819
+ ).pack(side="right")
2820
+
2821
+ clock_font_cb = ttk.Combobox(
2822
+ clock_font_row,
2823
+ values=["Vazir", "B Yekan+", "A Iranian Sans", "Segoe UI Semibold", "Tahoma", "Consolas"],
2824
+ state="readonly",
2825
+ width=20,
2826
+ )
2827
+ clock_font_cb.set(self.config.get("clock_font_family", "Vazir"))
2828
+ clock_font_cb.pack(side="left")
2829
+
2830
+ def on_font_selected(event=None):
2831
+ self.config["font_family"] = font_cb.get()
2832
+ self.config["clock_font_family"] = clock_font_cb.get()
2833
+ self._save_config()
2834
+ self._apply_all_styles()
2835
+
2836
+ font_cb.bind("<<ComboboxSelected>>", on_font_selected)
2837
+ clock_font_cb.bind("<<ComboboxSelected>>", on_font_selected)
2838
+
2839
+ sizes_row = tk.Frame(sec4, bg="#1E293B")
2840
+ sizes_row.pack(fill="x", pady=(6, 2))
2841
+
2842
+ def make_size_spin(parent, label_text, cfg_key, min_v, max_v):
2843
+ frame = tk.Frame(parent, bg="#1E293B")
2844
+ frame.pack(side="right", expand=True)
2845
+ tk.Label(
2846
+ frame,
2847
+ text=label_text,
2848
+ font=(font_fa, 8),
2849
+ fg="#CBD5E1",
2850
+ bg="#1E293B",
2851
+ ).pack(side="right", padx=(2, 4))
2852
+ sp = tk.Spinbox(
2853
+ frame,
2854
+ from_=min_v,
2855
+ to=max_v,
2856
+ width=4,
2857
+ font=("Segoe UI", 9),
2858
+ bg="#0F172A",
2859
+ fg="#F8FAFC",
2860
+ buttonbackground="#334155",
2861
+ )
2862
+ sp.delete(0, "end")
2863
+ sp.insert(0, str(self.config.get(cfg_key, 10)))
2864
+
2865
+ def on_spin_change(*args):
2866
+ try:
2867
+ val = int(sp.get())
2868
+ if min_v <= val <= max_v:
2869
+ self.config[cfg_key] = val
2870
+ self._save_config()
2871
+ self._apply_all_styles()
2872
+ except ValueError:
2873
+ pass
2874
+
2875
+ sp.configure(command=on_spin_change)
2876
+ sp.bind("<Return>", on_spin_change)
2877
+ sp.bind("<FocusOut>", on_spin_change)
2878
+ sp.pack(side="left")
2879
+
2880
+ make_size_spin(sizes_row, "ساعت:", "clock_font_size", 12, 52)
2881
+ make_size_spin(sizes_row, "تاریخ:", "date_font_size", 6, 28)
2882
+ make_size_spin(sizes_row, "مناسبت:", "occasion_font_size", 6, 22)
2883
+
2884
+ sec5 = tk.LabelFrame(
2885
+ container,
2886
+ text=" ۵. نمایش و جایگزینی در تسک‌بار ویندوز ",
2887
+ font=(font_fa, 9, "bold"),
2888
+ fg="#E2E8F0",
2889
+ bg="#1E293B",
2890
+ bd=1,
2891
+ padx=10,
2892
+ pady=6,
2893
+ )
2894
+ sec5.pack(fill="x", pady=(0, 8))
2895
+
2896
+ self._settings_replace_clock_var = tk.BooleanVar(value=bool(self.config.get("replace_windows_clock", False)))
2897
+ self._settings_hide_widget_var = tk.BooleanVar(value=bool(self.config.get("replace_clock_hide_widget", False)))
2898
+ self._settings_tb_clock_var = tk.BooleanVar(value=bool(self.config.get("taskbar_clock", False)))
2899
+ self._settings_tb_btn_var = tk.BooleanVar(value=bool(self.config.get("taskbar_button", False)))
2900
+ tb_sec_var = tk.BooleanVar(value=bool(self.config.get("taskbar_clock_seconds", False)))
2901
+
2902
+ def on_tb_change():
2903
+ self.config["replace_windows_clock"] = bool(self._settings_replace_clock_var.get())
2904
+ self.config["replace_clock_hide_widget"] = bool(self._settings_hide_widget_var.get())
2905
+ self.config["taskbar_clock"] = bool(self._settings_tb_clock_var.get())
2906
+ self.config["taskbar_button"] = bool(self._settings_tb_btn_var.get())
2907
+ self.config["taskbar_clock_seconds"] = bool(tb_sec_var.get())
2908
+ self._save_config()
2909
+ self.sync_taskbar_features()
2910
+
2911
+ def on_reset_replacer_pos():
2912
+ self.config["replace_clock_offset"] = 8
2913
+ self.config["replace_clock_width"] = 118
2914
+ self._save_config()
2915
+ try:
2916
+ sp_rw.delete(0, "end")
2917
+ sp_rw.insert(0, "118")
2918
+ except Exception:
2919
+ pass
2920
+ if self.clock_replacer:
2921
+ self.clock_replacer.refresh(get_today_info(CUSTOM_OCCASIONS_PATH))
2922
+
2923
+ def on_tb_reset_pos():
2924
+ self.config["taskbar_clock_offset"] = None
2925
+ self._save_config()
2926
+ if self.taskbar_clock:
2927
+ self.taskbar_clock.refresh(get_today_info(CUSTOM_OCCASIONS_PATH))
2928
+
2929
+ def on_pick_replacer_bg():
2930
+ cur_c = self.config.get("replace_clock_bg", "auto")
2931
+ if cur_c == "auto":
2932
+ cur_c = "#1C1C1C"
2933
+ c = colorchooser.askcolor(initialcolor=cur_c, title="انتخاب رنگ پس‌زمینه ساعت تسک‌بار", parent=win)
2934
+ if c and c[1]:
2935
+ self.config["replace_clock_bg"] = c[1]
2936
+ self._save_config()
2937
+ if self.clock_replacer:
2938
+ self.clock_replacer.refresh(get_today_info(CUSTOM_OCCASIONS_PATH))
2939
+
2940
+ def on_auto_replacer_bg():
2941
+ self.config["replace_clock_bg"] = "auto"
2942
+ self._save_config()
2943
+ if self.clock_replacer:
2944
+ self.clock_replacer._last_color_probe_ts = 0.0
2945
+ self.clock_replacer.refresh(get_today_info(CUSTOM_OCCASIONS_PATH))
2946
+
2947
+ win11_hide_var = tk.BooleanVar(value=get_windows11_tray_clock_hidden())
2948
+
2949
+ def on_toggle_win11_clock():
2950
+ want_hide = bool(win11_hide_var.get())
2951
+ set_windows11_tray_clock_hidden(want_hide)
2952
+ try:
2953
+ os.startfile("ms-settings:dateandtime")
2954
+ except Exception:
2955
+ pass
2956
+
2957
+ # الف) جایگزینی کامل ساعت ویندوز
2958
+ tk.Checkbutton(
2959
+ sec5,
2960
+ text="⭐ جایگزینی کامل ساعت و تاریخ ویندوز در تسک‌بار (پوشاندن ساعت انگلیسی با ساعت و تاریخ شمسی)",
2961
+ variable=self._settings_replace_clock_var,
2962
+ command=on_tb_change,
2963
+ font=(font_fa, 8, "bold"),
2964
+ fg="#38BDF8",
2965
+ bg="#1E293B",
2966
+ selectcolor="#0F172A",
2967
+ activebackground="#1E293B",
2968
+ anchor="w",
2969
+ ).pack(fill="x", pady=2)
2970
+
2971
+ tk.Checkbutton(
2972
+ sec5,
2973
+ text=" 👁️ مخفی کردن ویجت دسکتاپ هنگام فعال بودن جایگزینی (نمایش اختصاصی در تسک‌بار)",
2974
+ variable=self._settings_hide_widget_var,
2975
+ command=on_tb_change,
2976
+ font=(font_fa, 8),
2977
+ fg="#CBD5E1",
2978
+ bg="#1E293B",
2979
+ selectcolor="#0F172A",
2980
+ activebackground="#1E293B",
2981
+ anchor="w",
2982
+ ).pack(fill="x", pady=1)
2983
+
2984
+ tk.Checkbutton(
2985
+ sec5,
2986
+ text=" 🗑 حذف کامل ساعت و تاریخ انگلیسی از تسک‌بار ویندوز ۱۱ (تنظیم رسمی ویندوز)",
2987
+ variable=win11_hide_var,
2988
+ command=on_toggle_win11_clock,
2989
+ font=(font_fa, 8),
2990
+ fg="#FBBF24",
2991
+ bg="#1E293B",
2992
+ selectcolor="#0F172A",
2993
+ activebackground="#1E293B",
2994
+ anchor="w",
2995
+ ).pack(fill="x", pady=1)
2996
+
2997
+ # ب) گزینه‌های دیگر تسک‌بار
2998
+ for var, txt in (
2999
+ (self._settings_tb_clock_var, "🕒 نمایش ساعت و تاریخ شمسی شناور روی تسک‌بار (کنار ساعت ویندوز)"),
3000
+ (tb_sec_var, "⏱ نمایش ثانیه در ساعت تسک‌بار"),
3001
+ (self._settings_tb_btn_var, "📌 نمایش دکمه/آیکون برنامه در نوار وظیفه (تسک‌بار)"),
3002
+ ):
3003
+ tk.Checkbutton(
3004
+ sec5,
3005
+ text=txt,
3006
+ variable=var,
3007
+ command=on_tb_change,
3008
+ font=(font_fa, 8),
3009
+ fg="#F8FAFC",
3010
+ bg="#1E293B",
3011
+ selectcolor="#0F172A",
3012
+ activebackground="#1E293B",
3013
+ anchor="w",
3014
+ ).pack(fill="x", pady=1)
3015
+
3016
+ btn_row = tk.Frame(sec5, bg="#1E293B")
3017
+ btn_row.pack(fill="x", pady=(4, 0))
3018
+
3019
+ tk.Label(
3020
+ btn_row,
3021
+ text="عرض:",
3022
+ font=(font_fa, 8),
3023
+ fg="#CBD5E1",
3024
+ bg="#1E293B",
3025
+ ).pack(side="left", padx=(0, 3))
3026
+
3027
+ sp_rw = tk.Spinbox(
3028
+ btn_row,
3029
+ from_=80,
3030
+ to=200,
3031
+ width=4,
3032
+ font=("Segoe UI", 8, "bold"),
3033
+ bg="#0F172A",
3034
+ fg="#F8FAFC",
3035
+ buttonbackground="#334155",
3036
+ )
3037
+ sp_rw.delete(0, "end")
3038
+ sp_rw.insert(0, str(self.config.get("replace_clock_width", 118)))
3039
+
3040
+ def on_rw_change(*args):
3041
+ try:
3042
+ val = int(sp_rw.get())
3043
+ if 80 <= val <= 200:
3044
+ self.config["replace_clock_width"] = val
3045
+ self._save_config()
3046
+ if self.clock_replacer:
3047
+ self.clock_replacer.refresh(get_today_info(CUSTOM_OCCASIONS_PATH))
3048
+ except ValueError:
3049
+ pass
3050
+
3051
+ sp_rw.configure(command=on_rw_change)
3052
+ sp_rw.bind("<Return>", on_rw_change)
3053
+ sp_rw.bind("<FocusOut>", on_rw_change)
3054
+ sp_rw.pack(side="left", padx=(0, 6))
3055
+
3056
+ tk.Button(
3057
+ btn_row,
3058
+ text="🔄 مکان پیش‌فرض",
3059
+ font=(font_fa, 8),
3060
+ bg="#334155",
3061
+ fg="#F8FAFC",
3062
+ relief="flat",
3063
+ cursor="hand2",
3064
+ command=on_reset_replacer_pos,
3065
+ ).pack(side="left", padx=(0, 5))
3066
+
3067
+ tk.Button(
3068
+ btn_row,
3069
+ text="🎨 رنگ خودکار",
3070
+ font=(font_fa, 8),
3071
+ bg="#334155",
3072
+ fg="#38BDF8",
3073
+ relief="flat",
3074
+ cursor="hand2",
3075
+ command=on_auto_replacer_bg,
3076
+ ).pack(side="left", padx=(0, 5))
3077
+
3078
+ tk.Button(
3079
+ btn_row,
3080
+ text="🎨 رنگ دلخواه",
3081
+ font=(font_fa, 8),
3082
+ bg="#334155",
3083
+ fg="#F8FAFC",
3084
+ relief="flat",
3085
+ cursor="hand2",
3086
+ command=on_pick_replacer_bg,
3087
+ ).pack(side="left", padx=(0, 5))
3088
+
3089
+ tk.Button(
3090
+ btn_row,
3091
+ text="بازنشانی ساعت شناور",
3092
+ font=(font_fa, 8),
3093
+ bg="#334155",
3094
+ fg="#CBD5E1",
3095
+ relief="flat",
3096
+ cursor="hand2",
3097
+ command=on_tb_reset_pos,
3098
+ ).pack(side="left")
3099
+
3100
+ # بخش ۶: تنظیمات تایم‌زون اصلی (تهران / UTC) و نمایش UTC برای برنامه‌نویسان
3101
+ sec6 = tk.LabelFrame(
3102
+ container,
3103
+ text=" ۶. تایم‌زون اصلی و نمایش UTC (ویژه برنامه‌نویسان و سرور) ",
3104
+ font=(font_fa, 9, "bold"),
3105
+ fg="#38BDF8",
3106
+ bg="#1E293B",
3107
+ bd=1,
3108
+ padx=10,
3109
+ pady=6,
3110
+ )
3111
+ sec6.pack(fill="x", pady=(0, 8))
3112
+
3113
+ self._settings_primary_tz_var = tk.StringVar(
3114
+ value=self.config.get("primary_timezone", "tehran")
3115
+ )
3116
+ self._settings_show_utc_var = tk.BooleanVar(
3117
+ value=bool(self.config.get("show_utc", False))
3118
+ )
3119
+
3120
+ def on_tz_settings_change():
3121
+ self.config["primary_timezone"] = self._settings_primary_tz_var.get()
3122
+ self.config["show_utc"] = bool(self._settings_show_utc_var.get())
3123
+ self._save_config()
3124
+ self._update_tz_btn_appearance()
3125
+ self._refresh_display()
3126
+
3127
+ tz_radio_row = tk.Frame(sec6, bg="#1E293B")
3128
+ tz_radio_row.pack(fill="x", pady=(0, 3))
3129
+ for tz_val, tz_txt in (
3130
+ ("tehran", "🇮🇷 ساعت اصلی: تهران (شمسی)"),
3131
+ ("utc", "🌐 ساعت اصلی: UTC (تایم سرور، بدون +03:30)"),
3132
+ ):
3133
+ tk.Radiobutton(
3134
+ tz_radio_row,
3135
+ text=tz_txt,
3136
+ variable=self._settings_primary_tz_var,
3137
+ value=tz_val,
3138
+ command=on_tz_settings_change,
3139
+ font=(font_fa, 8, "bold"),
3140
+ fg="#F8FAFC",
3141
+ bg="#1E293B",
3142
+ selectcolor="#0F172A",
3143
+ activebackground="#1E293B",
3144
+ activeforeground="#38BDF8",
3145
+ ).pack(side="left", padx=(0, 14))
3146
+
3147
+ tk.Checkbutton(
3148
+ sec6,
3149
+ text="🕒 نمایش ردیف ساعت و تاریخ UTC (یا ساعت تهران در حالت UTC) داخل ویجت",
3150
+ variable=self._settings_show_utc_var,
3151
+ command=on_tz_settings_change,
3152
+ font=(font_fa, 8),
3153
+ fg="#A7F3D0",
3154
+ bg="#1E293B",
3155
+ selectcolor="#0F172A",
3156
+ activebackground="#1E293B",
3157
+ anchor="w",
3158
+ ).pack(fill="x", pady=(2, 0))
3159
+
3160
+ bottom_bar = tk.Frame(container, bg="#0F172A")
3161
+ bottom_bar.pack(fill="x", pady=(8, 0))
3162
+
3163
+ tk.Button(
3164
+ bottom_bar,
3165
+ text="بستن و ذخیره",
3166
+ font=(font_fa, 9, "bold"),
3167
+ bg="#0284C7",
3168
+ fg="#FFFFFF",
3169
+ padx=16,
3170
+ pady=4,
3171
+ relief="flat",
3172
+ cursor="hand2",
3173
+ command=win.destroy,
3174
+ ).pack(side="left")
3175
+
3176
+ tk.Label(
3177
+ bottom_bar,
3178
+ text="® Shayan Bamyar",
3179
+ font=("Segoe UI", 8, "bold"),
3180
+ fg="#64748B",
3181
+ bg="#0F172A",
3182
+ ).pack(side="left", padx=14)
3183
+
3184
+ tk.Button(
3185
+ bottom_bar,
3186
+ text="بازنشانی پیش‌فرض",
3187
+ font=(font_fa, 8),
3188
+ bg="#334155",
3189
+ fg="#F8FAFC",
3190
+ padx=10,
3191
+ pady=4,
3192
+ relief="flat",
3193
+ cursor="hand2",
3194
+ command=lambda: self._reset_all_defaults(win),
3195
+ ).pack(side="right")
3196
+
3197
+ def _on_opacity_slider(self, val: int):
3198
+ self.config["opacity"] = round(val / 100.0, 2)
3199
+ self._save_config()
3200
+ self._apply_all_styles()
3201
+
3202
+ def _on_scale_slider(self, val: int):
3203
+ self.config["widget_scale"] = int(val)
3204
+ self._save_config()
3205
+ self._apply_all_styles()
3206
+
3207
+ def _pick_color(self, cfg_key: str):
3208
+ initial = self.config.get(cfg_key, "#FFFFFF")
3209
+ color_code = colorchooser.askcolor(
3210
+ color=initial,
3211
+ title="انتخاب رنگ دلخواه",
3212
+ parent=self.settings_win if self.settings_win else self.root,
3213
+ )
3214
+ if color_code and color_code[1]:
3215
+ hex_c = color_code[1]
3216
+ self.config[cfg_key] = hex_c
3217
+ self._save_config()
3218
+ if cfg_key in self._color_previews and self._color_previews[cfg_key].winfo_exists():
3219
+ self._color_previews[cfg_key].configure(bg=hex_c)
3220
+ self._apply_all_styles()
3221
+
3222
+ def _reset_all_defaults(self, settings_win):
3223
+ x, y = self.config.get("x"), self.config.get("y")
3224
+ self.config = DEFAULT_CONFIG.copy()
3225
+ self.config["x"] = x
3226
+ self.config["y"] = y
3227
+ self._save_config()
3228
+ self._apply_all_styles()
3229
+ self.sync_taskbar_features()
3230
+ if settings_win and settings_win.winfo_exists():
3231
+ settings_win.destroy()
3232
+ self.open_settings_window()
3233
+
3234
+ def _on_tray_left_click(self):
3235
+ def _act():
3236
+ if self._is_minimized:
3237
+ self.restore_widget()
3238
+ return
3239
+ if self.widget_win:
3240
+ self.widget_win.deiconify()
3241
+ if self.lock_win:
3242
+ self.lock_win.deiconify()
3243
+ self._toggle_calendar(None)
3244
+ self.root.after(0, _act)
3245
+
3246
+ def _on_tray_right_click(self):
3247
+ def _popup():
3248
+ self._populate_context_menu()
3249
+ x = self.root.winfo_pointerx()
3250
+ y = self.root.winfo_pointery()
3251
+ self.root.focus_force()
3252
+ try:
3253
+ self.menu.tk_popup(x, y)
3254
+ finally:
3255
+ self.menu.grab_release()
3256
+ self.root.after(0, _popup)
3257
+
3258
+ def _refresh_display(self):
3259
+ info = get_today_info(CUSTOM_OCCASIONS_PATH)
3260
+ self.current_jy = info["jy"]
3261
+ self.current_jm = info["jm"]
3262
+ self.current_jd = info["jd"]
3263
+
3264
+ prev_count = len(self.alarm_store.alarms)
3265
+ due_alarms = self.alarm_store.check_due_alarms(info)
3266
+ if len(self.alarm_store.alarms) != prev_count:
3267
+ if self.alarm_win and self.alarm_win.win and self.alarm_win.win.winfo_exists():
3268
+ self.alarm_win._refresh_list()
3269
+ self.alarm_win._render_picker_calendar()
3270
+ if self.config.get("calendar_expanded"):
3271
+ self._render_calendar_month()
3272
+
3273
+ for alarm in due_alarms:
3274
+ if alarm.get("show_popup", True) or alarm.get("play_sound", True):
3275
+ AnimatedBellPopup(
3276
+ root=self.root,
3277
+ alarm=alarm,
3278
+ font_family=self.config.get("font_family", "Vazir"),
3279
+ on_snooze=lambda a: self.alarm_store.add_snooze(a, 5),
3280
+ on_dismiss=self._on_alarm_dismissed,
3281
+ )
3282
+
3283
+ use_fa = self.config.get("persian_digits", False)
3284
+ is_locked = bool(self.config.get("locked", False))
3285
+ scale = max(70, min(200, int(self.config.get("widget_scale", 100)))) / 100.0
3286
+
3287
+ c_size = max(10, int(self.config.get("clock_font_size", 26) * scale))
3288
+ d_size = max(6, int(self.config.get("date_font_size", 11) * scale))
3289
+ o_size = max(6, int(self.config.get("occasion_font_size", 9) * scale))
3290
+
3291
+ font_fa = self.config.get("font_family", "Vazir")
3292
+ font_clock = self.config.get("clock_font_family", "Vazir")
3293
+
3294
+ # فقط متون پویا را پاک می‌کنیم تا نوار ابزار (toolbar) و وضعیت Hover آیکون‌ها هرگز ریست نشوند
3295
+ self.canvas.delete("drawn_text")
3296
+
3297
+ toolbar_x = self.LOCK_OFFSET_X + self.LOCK_BTN_SIZE + 8
3298
+ toolbar_y = self.LOCK_OFFSET_Y
3299
+ # فضای نوار ابزار همیشه رزرو می‌شود (چه قفل چه باز) تا ابعاد و مکان ویجت
3300
+ # بعد از قفل/باز کردن هیچ تغییری نکند و ویجت روی صفحه جابه‌جا نشود
3301
+ self.canvas.coords(self._toolbar_win_id, toolbar_x, toolbar_y)
3302
+ self.btn_container.update_idletasks()
3303
+ toolbar_right = toolbar_x + self.btn_container.winfo_reqwidth()
3304
+ if not is_locked:
3305
+ self.canvas.itemconfigure(self._toolbar_win_id, state="normal")
3306
+ else:
3307
+ self.canvas.itemconfigure(self._toolbar_win_id, state="hidden")
3308
+
3309
+ primary_tz = self.config.get("primary_timezone", "tehran")
3310
+ show_utc = bool(self.config.get("show_utc", False))
3311
+ now_utc = datetime.now(timezone.utc)
3312
+
3313
+ if primary_tz == "utc":
3314
+ time_str = format_digits(now_utc.strftime("%H:%M"), use_fa)
3315
+ date_str = format_digits(f"UTC • {now_utc.strftime('%Y-%m-%d')}", use_fa)
3316
+ date_fill = self.config.get("accent_color", "#38BDF8")
3317
+ utc_line_str = (
3318
+ format_digits(f"TEH {info['time_str']}:{info['second']:02d} • {info['date_text']}", use_fa)
3319
+ if show_utc
3320
+ else ""
3321
+ )
3322
+ else:
3323
+ time_str = format_digits(info["time_str"], use_fa)
3324
+ date_str = format_digits(info["date_text"], use_fa)
3325
+ date_fill = (
3326
+ self.config.get("holiday_color", "#F87171")
3327
+ if info["is_holiday"]
3328
+ else self.config.get("date_color", "#CBD5E1")
3329
+ )
3330
+ utc_line_str = (
3331
+ format_digits(f"UTC {now_utc.strftime('%H:%M:%S')} • {now_utc.strftime('%Y-%m-%d')}", use_fa)
3332
+ if show_utc
3333
+ else ""
3334
+ )
3335
+
3336
+ today_alarms = self.alarm_store.get_events_for_jalali_day(
3337
+ info["jy"], info["jm"], info["jd"], info["persian_week_idx"]
3338
+ )
3339
+ occ_parts = []
3340
+ if info["has_occasion"] and info["occasion"]:
3341
+ occ_parts.append(info["occasion"])
3342
+ for a in today_alarms:
3343
+ occ_parts.append(f"⏰ {int(a['hour']):02d}:{int(a['minute']):02d} {a['title']}")
3344
+ occ_full = " | ".join(occ_parts)
3345
+ if len(occ_full) > 40:
3346
+ occ_full = occ_full[:39] + "…"
3347
+ occ_str = format_digits(occ_full, use_fa) if occ_full else ""
3348
+
3349
+ tmp_t = self.canvas.create_text(0, 0, text=time_str, font=(font_clock, c_size, "bold"), anchor="nw")
3350
+ tmp_d = self.canvas.create_text(0, 0, text=date_str, font=(font_fa, d_size, "bold"), anchor="nw")
3351
+ tb_t = self.canvas.bbox(tmp_t) or (0, 0, 90, 32)
3352
+ tb_d = self.canvas.bbox(tmp_d) or (0, 0, 140, 20)
3353
+ time_w, time_h = tb_t[2] - tb_t[0], tb_t[3] - tb_t[1]
3354
+ date_w, date_h = tb_d[2] - tb_d[0], tb_d[3] - tb_d[1]
3355
+
3356
+ utc_w, utc_h = 0, 0
3357
+ if utc_line_str:
3358
+ tmp_u = self.canvas.create_text(0, 0, text=utc_line_str, font=("Consolas", max(7, o_size), "bold"), anchor="nw")
3359
+ tb_u = self.canvas.bbox(tmp_u) or (0, 0, 140, 16)
3360
+ utc_w, utc_h = tb_u[2] - tb_u[0], tb_u[3] - tb_u[1]
3361
+ self.canvas.delete(tmp_u)
3362
+
3363
+ occ_w, occ_h = 0, 0
3364
+ if occ_str:
3365
+ tmp_o = self.canvas.create_text(0, 0, text=occ_str, font=(font_fa, o_size), anchor="nw")
3366
+ tb_o = self.canvas.bbox(tmp_o) or (0, 0, 120, 16)
3367
+ occ_w, occ_h = tb_o[2] - tb_o[0], tb_o[3] - tb_o[1]
3368
+
3369
+ self.canvas.delete(tmp_t, tmp_d)
3370
+ if occ_str:
3371
+ self.canvas.delete(tmp_o)
3372
+
3373
+ if is_locked:
3374
+ top_needed_w = self.LOCK_OFFSET_X + self.LOCK_BTN_SIZE + 10 + time_w + 14
3375
+ body_needed_w = max(date_w, utc_w, occ_w) + 24
3376
+ target_w = max(top_needed_w, body_needed_w, int(130 * scale))
3377
+ else:
3378
+ top_needed_w = toolbar_right + time_w + 38
3379
+ body_needed_w = max(date_w, utc_w, occ_w) + 32
3380
+ target_w = max(int(self.BASE_MIN_W * scale), top_needed_w, body_needed_w)
3381
+
3382
+ right_x = target_w - 14
3383
+ cur_y = 6
3384
+
3385
+ draw_outlined_canvas_text(
3386
+ self.canvas,
3387
+ right_x,
3388
+ cur_y,
3389
+ text=time_str,
3390
+ font_spec=(font_clock, c_size, "bold"),
3391
+ fill=self.config.get("clock_color", "#F8FAFC"),
3392
+ outline="#000000",
3393
+ anchor="ne",
3394
+ justify="right",
3395
+ tags="drawn_text",
3396
+ )
3397
+ cur_y += max(time_h, self.LOCK_BTN_SIZE + 4) + 4
3398
+
3399
+ draw_outlined_canvas_text(
3400
+ self.canvas,
3401
+ right_x,
3402
+ cur_y,
3403
+ text=date_str,
3404
+ font_spec=(font_fa, d_size, "bold"),
3405
+ fill=date_fill,
3406
+ outline="#000000",
3407
+ anchor="ne",
3408
+ justify="right",
3409
+ tags="drawn_text",
3410
+ )
3411
+ cur_y += date_h + 4
3412
+
3413
+ if utc_line_str:
3414
+ draw_outlined_canvas_text(
3415
+ self.canvas,
3416
+ right_x,
3417
+ cur_y,
3418
+ text=utc_line_str,
3419
+ font_spec=("Consolas", max(7, o_size), "bold"),
3420
+ fill="#38BDF8" if primary_tz != "utc" else "#A7F3D0",
3421
+ outline="#000000",
3422
+ anchor="ne",
3423
+ justify="right",
3424
+ tags="drawn_text",
3425
+ )
3426
+ cur_y += utc_h + 4
3427
+ else:
3428
+ cur_y += 1
3429
+
3430
+ if occ_str:
3431
+ draw_outlined_canvas_text(
3432
+ self.canvas,
3433
+ right_x,
3434
+ cur_y,
3435
+ text=occ_str,
3436
+ font_spec=(font_fa, o_size),
3437
+ fill=self.config.get("holiday_color", "#F87171")
3438
+ if (info["is_holiday"] and info["has_occasion"])
3439
+ else self.config.get("occasion_color", "#94A3B8"),
3440
+ outline="#000000",
3441
+ anchor="ne",
3442
+ justify="right",
3443
+ tags="drawn_text",
3444
+ )
3445
+ cur_y += occ_h + 4
3446
+
3447
+ footer_y = cur_y + 2
3448
+ if self._toast_text:
3449
+ draw_outlined_canvas_text(
3450
+ self.canvas,
3451
+ 10,
3452
+ footer_y,
3453
+ text=self._toast_text,
3454
+ font_spec=(font_fa, 8, "bold"),
3455
+ fill="#10B981",
3456
+ outline="#000000",
3457
+ anchor="nw",
3458
+ tags="drawn_text",
3459
+ )
3460
+ target_h = footer_y + 18
3461
+ elif not is_locked:
3462
+ draw_outlined_canvas_text(
3463
+ self.canvas,
3464
+ 10,
3465
+ footer_y,
3466
+ text="® Shayan Bamyar",
3467
+ font_spec=("Segoe UI", 7, "bold"),
3468
+ fill="#64748B",
3469
+ outline="#000000",
3470
+ anchor="nw",
3471
+ tags="drawn_text",
3472
+ )
3473
+ target_h = footer_y + 18
3474
+ else:
3475
+ # در حالت قفل، فوتر @shayan bamyar حذف می‌شود و ارتفاع به حداقل ممکن کاهش می‌یابد
3476
+ target_h = cur_y + 6
3477
+
3478
+ size_changed = (target_w != self._computed_w) or (target_h != self._computed_h)
3479
+ self._computed_w = target_w
3480
+ self._computed_h = target_h
3481
+
3482
+ if self.widget_win and not getattr(self, "_is_minimized", False) and not self._is_dragging:
3483
+ cur_cx = self.widget_win.winfo_x()
3484
+ cur_cy = self.widget_win.winfo_y()
3485
+ ml, mt, mr, mb = get_monitor_work_area_at(cur_cx + target_w // 2, cur_cy + target_h // 2, self.root)
3486
+ if is_locked:
3487
+ snap_side = self.config.get("snap_side", "right")
3488
+ target_x = (mr - target_w) if snap_side == "right" else ml
3489
+ target_y = max(mt, min(cur_cy, mb - target_h))
3490
+ else:
3491
+ target_x = max(ml, min(cur_cx, mr - target_w))
3492
+ target_y = max(mt, min(cur_cy, mb - target_h))
3493
+
3494
+ if size_changed or (cur_cx != target_x) or (cur_cy != target_y):
3495
+ self.widget_win.geometry(f"{target_w}x{target_h}+{int(target_x)}+{int(target_y)}")
3496
+ self._position_lock_window()
3497
+ if not self.config.get("transparent_bg", False):
3498
+ apply_rounded_corners(self.widget_win, target_w, target_h, radius=10 if is_locked else 16, enabled=True)
3499
+ if self.config.get("calendar_expanded"):
3500
+ self._position_calendar_window()
3501
+
3502
+ if hasattr(self, "tray") and self.tray:
3503
+ self.tray.update_tooltip(self._format_tray_tooltip(info))
3504
+
3505
+ if getattr(self, "clock_replacer", None) is not None:
3506
+ try:
3507
+ self.clock_replacer.refresh(info)
3508
+ except Exception:
3509
+ pass
3510
+ if getattr(self, "taskbar_clock", None) is not None:
3511
+ try:
3512
+ self.taskbar_clock.refresh(info)
3513
+ except Exception:
3514
+ pass
3515
+ if getattr(self, "taskbar_proxy", None) is not None:
3516
+ self.taskbar_proxy.update_title(
3517
+ format_digits(f"{info['time_str'][:5]} | {info['date_text']}", use_fa)
3518
+ )
3519
+
3520
+ def _update_clock_loop(self):
3521
+ self._refresh_display()
3522
+ self.root.after(1000, self._update_clock_loop)
3523
+
3524
+ def _keep_z_order_loop(self):
3525
+ if not self._is_dragging and not getattr(self, "_is_minimized", False) and self.widget_win and self.widget_win.winfo_viewable():
3526
+ z_mode = self.config.get("z_mode", "topmost")
3527
+ is_locked = bool(self.config.get("locked", False))
3528
+ apply_z_order_and_clickthrough(self.widget_win, z_mode, click_through=is_locked)
3529
+ if self.lock_win and self.lock_win.winfo_viewable():
3530
+ apply_z_order_and_clickthrough(self.lock_win, z_mode, click_through=False)
3531
+ if self.cal_win and self.config.get("calendar_expanded"):
3532
+ apply_z_order_and_clickthrough(self.cal_win, z_mode, click_through=is_locked)
3533
+ # حفظ پنجره کپی زمان/GUID و Tooltipها روی ویجت تا هرگز زیر ویجت نروند
3534
+ if self.dev_popup_win and self.dev_popup_win.winfo_exists():
3535
+ apply_z_order_and_clickthrough(self.dev_popup_win, "topmost", click_through=False)
3536
+ for tip in self._tooltips:
3537
+ if tip.tip_win and tip.tip_win.winfo_exists():
3538
+ apply_z_order_and_clickthrough(tip.tip_win, "topmost", click_through=True)
3539
+ if getattr(self, "clock_replacer", None) is not None:
3540
+ self.clock_replacer.keep_on_top()
3541
+ if getattr(self, "taskbar_clock", None) is not None:
3542
+ self.taskbar_clock.keep_on_top()
3543
+ self.root.after(800, self._keep_z_order_loop)
3544
+
3545
+ def quit_app(self):
3546
+ try:
3547
+ if getattr(self, "clock_replacer", None) is not None:
3548
+ self.clock_replacer.destroy()
3549
+ if getattr(self, "taskbar_clock", None) is not None:
3550
+ self.taskbar_clock.destroy()
3551
+ if getattr(self, "taskbar_proxy", None) is not None:
3552
+ self.taskbar_proxy.destroy()
3553
+ except Exception:
3554
+ pass
3555
+ try:
3556
+ if hasattr(self, "tray") and self.tray:
3557
+ self.tray.stop()
3558
+ except Exception:
3559
+ pass
3560
+ self.root.quit()
3561
+ self.root.destroy()
3562
+ sys.exit(0)
3563
+
3564
+ def run(self):
3565
+ self.root.mainloop()
3566
+
3567
+
3568
+ if __name__ == "__main__":
3569
+ app = PersianClockWidget()
3570
+ app.run()