-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnote.py
More file actions
2322 lines (1921 loc) · 86.8 KB
/
note.py
File metadata and controls
2322 lines (1921 loc) · 86.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
极简桌面便笺软件 - MyNote
功能:无边框、可拖拽、待办事项、数据持久化、置顶/嵌入模式
"""
import tkinter as tk
from tkinter import font as tkfont
import json
import os
import sys
from typing import List, Dict, Optional
from datetime import datetime
import ctypes
import ctypes.wintypes
# Windows API 常量
GWL_EXSTYLE = -20
WS_EX_TOOLWINDOW = 0x00000080
WS_EX_NOACTIVATE = 0x08000000
# Windows DWM API 常量(用于模糊效果和圆角)
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
DWMWA_WINDOW_CORNER_PREFERENCE = 33 # Windows 11 圆角
DWMWA_BORDER_COLOR = 34
ACCENT_ENABLE_BLURBEHIND = 3
ACCENT_ENABLE_ACRYLICBLURBEHIND = 4
# 圆角选项
DWMWCP_DEFAULT = 0
DWMWCP_DONOTROUND = 1
DWMWCP_ROUND = 2
DWMWCP_ROUNDSMALL = 3
class ACCENT_POLICY(ctypes.Structure):
_fields_ = [
('AccentState', ctypes.c_uint),
('AccentFlags', ctypes.c_uint),
('GradientColor', ctypes.c_uint),
('AnimationId', ctypes.c_uint),
]
class WINDOWCOMPOSITIONATTRIBDATA(ctypes.Structure):
_fields_ = [
('Attrib', ctypes.c_int),
('pvData', ctypes.POINTER(ACCENT_POLICY)),
('cbData', ctypes.c_size_t),
]
# ===== 配置类 =====
class Config:
"""集中管理所有配置常量"""
# 路径配置
@staticmethod
def get_base_path():
"""获取程序根目录"""
if getattr(sys, 'frozen', False):
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.abspath(__file__))
BASE_DIR = None # 延迟初始化
DATA_FILE = None # 延迟初始化
# 默认配置
DEFAULT_CONFIG = {
"items": [],
"window": {"x": 100, "y": 100, "width": 320, "height": 450},
"settings": {
"mode": "topmost", # topmost 或 desktop
"visibility_mode": "always_visible", # always_visible 或 auto_hide
"font_size": 13,
"opacity_focused": 1.0,
"opacity_unfocused": 0.7
}
}
# UI 配色
COLOR_BG = "#2b2b2b" # 背景深灰
COLOR_TEXT = "#ffffff" # 文本纯白色
COLOR_TEXT_DIM = "#a0a0a0" # 暗淡文本(浅灰)
COLOR_ACCENT = "#0078D7" # 强调色-系统蓝色
COLOR_CHECKBOX = "#5c5c5c" # 复选框边框
COLOR_PROGRESS = "#0078D7" # 进度条系统蓝色
# UI 尺寸常量
CHECKBOX_SIZE = 26 # 复选框大小
CHECKBOX_CENTER = 13 # 复选框中心位置
CHECKBOX_RADIUS = 8 # 复选框圆角半径
TEXT_PADY = 2 # 文本内边距
RESIZE_EDGE_SIZE = 15 # 窗口调整边缘大小(从10px增加到15px)
DRAG_THRESHOLD_MS = 300 # 长按触发拖拽的时间阈值(毫秒)
# 字体常量
FONT_FAMILY = 'Microsoft YaHei'
# 初始化路径配置
Config.BASE_DIR = Config.get_base_path()
Config.DATA_FILE = os.path.join(Config.BASE_DIR, 'notes_data.json')
# ===== 数据管理 =====
class DataManager:
"""处理数据的加载、保存"""
@staticmethod
def load() -> Dict:
"""从文件加载数据"""
if os.path.exists(Config.DATA_FILE):
try:
with open(Config.DATA_FILE, 'r', encoding='utf-8') as f:
data = json.load(f)
# 合并默认配置(防止缺少新字段)
for key in Config.DEFAULT_CONFIG:
if key not in data:
data[key] = Config.DEFAULT_CONFIG[key]
return data
except Exception as e:
print(f"加载数据失败: {e}")
return Config.DEFAULT_CONFIG.copy()
@staticmethod
def save(data: Dict):
"""保存数据到文件"""
try:
with open(Config.DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"保存数据失败: {e}")
# ===== Windows API 工具类 =====
class WindowsEffects:
"""封装所有 Windows API 调用,统一管理窗口效果"""
@staticmethod
def set_dpi_awareness():
"""适配高DPI显示器,使界面更清晰"""
try:
# Windows 8.1+ (System DPI Aware)
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
try:
# Windows Vista/7/8
ctypes.windll.user32.SetProcessDPIAware()
except Exception:
pass
@staticmethod
def get_window_handle(widget):
"""获取窗口句柄(Windows API)"""
# 对于 overrideredirect 窗口,需要获取父窗口句柄
hwnd = ctypes.windll.user32.GetParent(widget.winfo_id())
if not hwnd:
hwnd = widget.winfo_id()
return hwnd
@staticmethod
def apply_blur_effect(hwnd):
"""应用Windows模糊效果(毛玻璃)- 主窗口使用"""
try:
# 设置模糊效果(使用和菜单一样的Acrylic效果)
accent = ACCENT_POLICY()
accent.AccentState = ACCENT_ENABLE_ACRYLICBLURBEHIND # 使用Acrylic模糊
# 和右键菜单相同的颜色设置
accent.GradientColor = 0x992B2B2B # 60%透明度的深灰色
data = WINDOWCOMPOSITIONATTRIBDATA()
data.Attrib = 19 # WCA_ACCENT_POLICY
data.pvData = ctypes.pointer(accent)
data.cbData = ctypes.sizeof(accent)
# 调用SetWindowCompositionAttribute
try:
ctypes.windll.user32.SetWindowCompositionAttribute(hwnd, ctypes.byref(data))
except:
# Windows 10/11可能需要不同的API
pass
except Exception as e:
print(f"应用模糊效果失败: {e}")
@staticmethod
def apply_rounded_corners(hwnd):
"""应用圆角效果(Windows 11)"""
try:
# 尝试设置圆角(Windows 11)
corner_preference = ctypes.c_int(DWMWCP_ROUND) # 使用标准圆角
try:
ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd,
DWMWA_WINDOW_CORNER_PREFERENCE,
ctypes.byref(corner_preference),
ctypes.sizeof(corner_preference)
)
except Exception as e:
# Windows 10 不支持,忽略错误
pass
except Exception as e:
print(f"应用圆角效果失败: {e}")
@staticmethod
def apply_menu_effects(hwnd):
"""应用菜单的模糊和圆角效果"""
try:
# 圆角
corner_preference = ctypes.c_int(DWMWCP_ROUND)
ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd, DWMWA_WINDOW_CORNER_PREFERENCE,
ctypes.byref(corner_preference), ctypes.sizeof(corner_preference)
)
# 模糊 (Acrylic)
accent = ACCENT_POLICY()
accent.AccentState = ACCENT_ENABLE_ACRYLICBLURBEHIND
accent.GradientColor = 0x992B2B2B
data = WINDOWCOMPOSITIONATTRIBDATA()
data.Attrib = 19
data.pvData = ctypes.pointer(accent)
data.cbData = ctypes.sizeof(accent)
ctypes.windll.user32.SetWindowCompositionAttribute(hwnd, ctypes.byref(data))
except:
pass
@staticmethod
def embed_to_desktop(hwnd):
"""将窗口嵌入到桌面底层"""
try:
HWND_BOTTOM = 1
SWP_NOSIZE = 0x0001
SWP_NOMOVE = 0x0002
SWP_NOACTIVATE = 0x0010
ctypes.windll.user32.SetWindowPos(
hwnd, HWND_BOTTOM,
0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE
)
except Exception as e:
print(f"嵌入桌面失败: {e}")
# ===== 待办事项组件 =====
class TodoItem(tk.Frame):
"""单个待办事项的UI组件"""
def __init__(self, parent, item_data: Dict, on_change_callback, on_delete_callback, on_add_callback, on_swap_callback=None, on_focus_callback=None, font_size=13, **kwargs):
super().__init__(parent, bg=Config.COLOR_BG, **kwargs)
self.item_data = item_data
self.on_change = on_change_callback
self.on_delete = on_delete_callback
self.on_add = on_add_callback
self.on_swap = on_swap_callback
self.on_focus = on_focus_callback
self.font_size = font_size
self._resizing = False # 防止Configure事件循环的标志
# 拖拽相关变量
self._drag_start_time = None
self._is_dragging = False
# 标点处理防抖定时器
self._punctuation_timer = None
# 创建UI
self._create_widgets()
def _create_widgets(self):
"""创建复选框和文本"""
# 自定义复选框(使用Canvas绘制)
self.checkbox = tk.Canvas(
self,
width=Config.CHECKBOX_SIZE,
height=Config.CHECKBOX_SIZE,
bg=Config.COLOR_BG,
highlightthickness=0,
cursor='hand2'
)
# 计算固定的pady,使复选框中心与第一行文本视觉中心严格对齐
# 使用tkfont获取准确的字体度量
font_obj = tkfont.Font(family=Config.FONT_FAMILY, size=self.font_size)
# 获取字体度量
ascent = font_obj.metrics('ascent') # 基线到顶部的距离
descent = font_obj.metrics('descent') # 基线到底部的距离
# 中文字符的视觉重心在距顶部约 67% ascent 位置
# (考虑到中文字符笔画主要分布在中下部)
# 注意:Text widget 有 spacing1=2 的段落前间距
text_visual_center = Config.TEXT_PADY + 2 + ascent * 0.67
# 复选框顶部偏移 = 第一行文本视觉中心 - 复选框中心
checkbox_top_offset = max(0, int(text_visual_center - Config.CHECKBOX_CENTER))
# 使用 anchor='n' 并固定pady,确保无论文本多长都保持顶部对齐
self.checkbox.pack(side='left', anchor='n', padx=(8, 5), pady=(checkbox_top_offset, 0))
# 绘制复选框
self._draw_checkbox()
# 绑定点击事件(短按:切换,长按:拖拽)
self.checkbox.bind('<Button-1>', self._on_checkbox_press)
self.checkbox.bind('<ButtonRelease-1>', self._on_checkbox_release)
# 文本输入框(改用Text支持多行和自动换行)
text_color = Config.COLOR_TEXT_DIM if self.item_data.get('completed') else Config.COLOR_TEXT
font_style = self._get_font_style()
# 计算文本应该占用的行数(不限制最大行数)
text_content = self.item_data.get('text', '')
initial_height = max(1, text_content.count('\n') + 1)
self.text_entry = tk.Text(
self,
bg=Config.COLOR_BG,
fg=text_color,
insertbackground=Config.COLOR_TEXT,
bd=0,
highlightthickness=0,
font=font_style,
wrap='char', # 按字符换行,更适合中文
width=1, # 关键:设置较小宽度,允许pack/fill控制实际宽度
height=initial_height, # 根据内容设置初始高度
relief='flat',
padx=2,
pady=2,
spacing1=2, # 段落前间距
spacing2=1, # 段落内行间距
spacing3=2, # 段落后间距
undo=True # 开启撤销功能
)
self.text_entry.config(insertofftime=600, insertontime=600) # 亮600ms,灭600ms
self.text_entry.insert('1.0', text_content)
# 使用 anchor='n' 确保文本框顶部对齐
self.text_entry.pack(side='left', fill='both', expand=True, padx=5, anchor='n')
# 配置Text widget的tag来实现加粗删除线效果
# 创建两个overstrike tag叠加,模拟更粗的删除线
self.text_entry.tag_configure('strikethrough1', overstrike=True, foreground=Config.COLOR_TEXT_DIM)
self.text_entry.tag_configure('strikethrough2', overstrike=True, foreground=Config.COLOR_TEXT_DIM)
# 初始加载时也应用标点规则
if text_content:
self.after(10, self._fix_punctuation_wrapping)
# 绑定文本变化事件,自动调整高度
self.text_entry.bind('<<Modified>>', self._on_text_modified)
self.text_entry.bind('<Configure>', self._on_text_configure) # 宽度改变时重新计算高度和标点
# 绑定事件
self.text_entry.bind('<FocusOut>', self._on_text_change)
self.text_entry.bind('<Return>', self._on_enter_key)
self.text_entry.bind('<BackSpace>', self._on_backspace)
# 新增快捷键绑定
self.text_entry.bind('<Up>', self._on_up)
self.text_entry.bind('<Down>', self._on_down)
self.text_entry.bind('<Control-Up>', self._on_ctrl_up)
self.text_entry.bind('<Control-Down>', self._on_ctrl_down)
self.text_entry.bind('<Control-d>', self._on_ctrl_d)
self.text_entry.bind('<Control-Return>', self._on_ctrl_enter)
# 添加分隔线(在底部)
self.separator = tk.Frame(
self,
bg='#3a3a3a', # 很浅的灰色分隔线
height=1
)
self.separator.pack(side='bottom', fill='x', pady=(5, 0))
def _get_font_style(self):
"""获取文本字体样式(不使用系统overstrike,使用自定义绘制)"""
return (Config.FONT_FAMILY, self.font_size)
def _draw_checkbox(self):
"""绘制复选框(带圆角)"""
self.checkbox.delete('all')
if self.item_data.get('completed', False):
# 已完成:绿色填充的圆角矩形 + 白色对勾
self._draw_rounded_rect(2, 2, 24, 24, Config.CHECKBOX_RADIUS, fill=Config.COLOR_ACCENT, outline='')
# 绘制对勾 ✓
self.checkbox.create_line(
7, 13, 11, 18,
fill='white',
width=3,
capstyle='round',
smooth=True
)
self.checkbox.create_line(
11, 18, 20, 8,
fill='white',
width=3,
capstyle='round',
smooth=True
)
else:
# 未完成:灰色边框的圆角矩形
self._draw_rounded_rect(3, 3, 23, 23, Config.CHECKBOX_RADIUS, fill='', outline=Config.COLOR_CHECKBOX, width=3)
def _draw_rounded_rect(self, x1, y1, x2, y2, radius, **kwargs):
"""在Canvas上绘制圆角矩形"""
points = [
x1+radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y1+radius,
x1, y1
]
return self.checkbox.create_polygon(points, smooth=True, **kwargs)
def _on_text_modified(self, event=None):
"""文本被修改时的处理"""
# 先调整高度
self._auto_resize_text()
# 然后处理标点换行(使用防抖)
self._schedule_punctuation_fix()
def _on_text_configure(self, event=None):
"""Text组件大小改变时的处理(窗口宽度改变导致重新换行)"""
# 先调整高度
self._auto_resize_text()
# 然后重新处理标点换行(因为宽度改变可能导致重新换行,使用防抖)
self._schedule_punctuation_fix()
def _schedule_punctuation_fix(self):
"""使用防抖机制调度标点处理(避免频繁处理)"""
# 取消之前的定时器
if self._punctuation_timer:
self.after_cancel(self._punctuation_timer)
# 设置新的定时器(300ms后执行)
self._punctuation_timer = self.after(300, self._fix_punctuation_wrapping)
def _fix_punctuation_wrapping(self):
"""防止标点符号单独成行 - 中文排版避头尾规则"""
try:
# 定义不应该出现在行首的中文标点(避尾字符)
line_end_punctuation = ',。!?、;:""'')】》」}'
# 定义不应该出现在行尾的中文标点(避头字符)
line_start_punctuation = '""''(【《「{'
# 零宽不换行空格(Word Joiner)- 最强的不换行字符
WORD_JOINER = '\u2060'
content = self.text_entry.get('1.0', 'end-1c')
if not content or len(content) < 2:
return
# 第一步:在避尾标点前插入零宽不换行空格
new_content = []
for i, char in enumerate(content):
# 如果当前是避尾标点(不应该在行首)
if char in line_end_punctuation:
# 移除前面的普通空格
while len(new_content) > 0 and new_content[-1] == ' ':
new_content.pop()
# 在标点前插入零宽不换行空格
if len(new_content) > 0:
last_char = new_content[-1]
if last_char not in (WORD_JOINER, '\n', '\t'):
new_content.append(WORD_JOINER)
# 如果当前是避头标点(不应该在行尾),在其后面插入零宽不换行空格
new_content.append(char)
if char in line_start_punctuation:
# 查看下一个字符,如果不是零宽不换行空格,就插入一个
if i + 1 < len(content):
next_char = content[i + 1]
if next_char not in (WORD_JOINER, '\n', '\t', ' '):
new_content.append(WORD_JOINER)
new_text = ''.join(new_content)
# 第二步:检查并修复行首的标点
lines = new_text.split('\n')
fixed_lines = []
for line in lines:
# 如果行首是避尾标点,移除开头的空白并添加零宽不换行空格
if line and line.lstrip() and line.lstrip()[0] in line_end_punctuation:
# 这种情况不应该发生,但如果发生了,我们修复它
stripped = line.lstrip()
fixed_lines.append(WORD_JOINER + stripped)
else:
fixed_lines.append(line)
final_text = '\n'.join(fixed_lines)
# 只有内容真的改变了才更新
if final_text != content:
# 保存光标位置
try:
cursor_pos = self.text_entry.index(tk.INSERT)
except:
cursor_pos = '1.0'
# 更新文本
self.text_entry.delete('1.0', 'end')
self.text_entry.insert('1.0', final_text)
# 恢复光标位置
try:
self.text_entry.mark_set(tk.INSERT, cursor_pos)
except:
pass
# 重置修改标志
self.text_entry.edit_modified(False)
except Exception as e:
# print(f"Fix punctuation error: {e}")
pass
def _auto_resize_text(self, event=None):
"""自动调整Text组件高度"""
# 防止Configure事件导致的递归调用
if self._resizing:
return
try:
self._resizing = True
# 获取显示行数(包括自动换行)
display_lines = self.text_entry.count("1.0", "end", "displaylines")
if display_lines is None:
display_lines = 1
else:
display_lines = int(display_lines[0])
# 设置高度(不限制最大行数)
new_height = max(1, display_lines)
if new_height != int(self.text_entry.cget('height')):
self.text_entry.config(height=new_height)
# 重置修改标志
self.text_entry.edit_modified(False)
except Exception as e:
# print(f"Resize error: {e}")
pass
finally:
self._resizing = False
# 文本高度改变后,更新删除线位置
if self.item_data.get('completed', False):
self.after(10, self._draw_strikethrough)
def _on_toggle(self):
"""切换完成状态(带动画效果)"""
# 先保存当前文本(防止文字丢失)
self._on_text_change()
# 切换完成状态
old_completed = self.item_data.get('completed', False)
self.item_data['completed'] = not old_completed
# 如果是标记为完成,添加短暂的闪烁动画
if self.item_data['completed']:
self._play_complete_animation()
else:
# 取消完成,直接更新样式
self._update_toggle_style()
# 不重新加载列表,保持原位置
self.on_change(reload=False)
def _play_complete_animation(self):
"""播放完成动画(快速淡入淡出效果)"""
# 动画参数
steps = 5
delay = 30 # 毫秒
current_step = [0] # 使用列表包装以便在闭包中修改
def animate():
if current_step[0] < steps:
# 淡出阶段
alpha = 1.0 - (current_step[0] / steps) * 0.3
fade_color = self._interpolate_color(Config.COLOR_TEXT, Config.COLOR_TEXT_DIM, 1 - alpha)
self.text_entry.config(fg=fade_color)
current_step[0] += 1
self.after(delay, animate)
else:
# 动画结束,应用最终样式
self._update_toggle_style()
animate()
def _interpolate_color(self, color1, color2, t):
"""在两个颜色之间插值"""
# 解析十六进制颜色
r1, g1, b1 = int(color1[1:3], 16), int(color1[3:5], 16), int(color1[5:7], 16)
r2, g2, b2 = int(color2[1:3], 16), int(color2[3:5], 16), int(color2[5:7], 16)
# 插值
r = int(r1 + (r2 - r1) * t)
g = int(g1 + (g2 - g1) * t)
b = int(b1 + (b2 - b1) * t)
return f"#{r:02x}{g:02x}{b:02x}"
def _update_toggle_style(self):
"""更新切换后的样式"""
# 重新绘制复选框
self._draw_checkbox()
# 更新样式
text_color = Config.COLOR_TEXT_DIM if self.item_data['completed'] else Config.COLOR_TEXT
self.text_entry.config(fg=text_color, font=self._get_font_style())
# 更新自定义删除线
self._draw_strikethrough()
def _draw_strikethrough(self):
"""应用自定义删除线样式(使用Text tag)"""
# 移除现有的删除线tag
self.text_entry.tag_remove('strikethrough1', '1.0', 'end')
self.text_entry.tag_remove('strikethrough2', '1.0', 'end')
# 只在已完成时应用删除线
if self.item_data.get('completed', False):
# 应用删除线tag到整个文本(使用双层tag模拟更粗的删除线)
self.text_entry.tag_add('strikethrough1', '1.0', 'end-1c')
self.text_entry.tag_add('strikethrough2', '1.0', 'end-1c')
def _on_text_change(self, event=None):
"""文本改变时保存"""
# Text组件用get('1.0', 'end-1c')获取文本
new_text = self.text_entry.get('1.0', 'end-1c')
# 总是保存当前文本(不管是否改变)
if new_text != self.item_data.get('text'):
self.item_data['text'] = new_text
# 只在文本真正改变时触发回调
if event is not None: # 用户触发的保存
self.on_change(reload=False) # 文本改变不重新加载列表
def _on_enter_key(self, event=None):
"""回车键处理"""
if event and (event.state & 0x1): # Shift pressed
# 软回车:插入换行符,允许 Text 默认行为(或者手动插入)
# 这里让它执行默认行为,即插入换行
return None
"""回车键新增下一项(在当前项之后)"""
# 先保存当前文本
self._on_text_change()
# 触发新增,传递当前项的id
self.on_add(after_id=self.item_data['id'])
return 'break'
def _on_ctrl_enter(self, event=None):
"""Ctrl+Enter 切换完成状态"""
self._on_toggle()
return 'break'
def _on_ctrl_d(self, event=None):
"""Ctrl+D 删除当前项"""
self._on_delete()
return 'break'
def _on_up(self, event=None):
"""上键:如果光标在第一行,移动焦点到上一项"""
# 检查光标是否在第一行
if self.text_entry.index(tk.INSERT).split('.')[0] == '1':
if self.on_focus:
self.on_focus(self.item_data['id'], -1)
return 'break'
return None
def _on_down(self, event=None):
"""下键:如果光标在最后一行,移动焦点到下一项"""
# 检查光标是否在最后一行
# 获取总行数
last_line_index = self.text_entry.index('end-1c').split('.')[0]
current_line_index = self.text_entry.index(tk.INSERT).split('.')[0]
if current_line_index == last_line_index:
if self.on_focus:
self.on_focus(self.item_data['id'], 1)
return 'break'
return None
def _on_ctrl_up(self, event=None):
"""Ctrl+Up:向上移动当前项"""
if self.on_swap:
self.on_swap(self.item_data['id'], -1)
return 'break'
def _on_ctrl_down(self, event=None):
"""Ctrl+Down:向下移动当前项"""
if self.on_swap:
self.on_swap(self.item_data['id'], 1)
return 'break'
def _on_backspace(self, event=None):
"""Backspace键:如果文本为空,删除整行"""
current_text = self.text_entry.get('1.0', 'end-1c')
# 如果文本为空且按下Backspace,删除整行
if not current_text or current_text.strip() == '':
self.on_delete(self.item_data['id'])
return 'break' # 阻止默认的backspace行为
# 否则允许正常删除文字
return None
def _on_delete(self):
"""删除本项"""
self.on_delete(self.item_data['id'])
def _find_parent_with_method(self, method_name):
"""查找具有指定方法的父窗口"""
parent = self.master
while parent and not hasattr(parent, method_name):
parent = parent.master
return parent
def _update_checkbox_alignment(self):
"""更新复选框对齐(当字体大小改变时调用)"""
# 重新计算复选框对齐
font_obj = tkfont.Font(family=Config.FONT_FAMILY, size=self.font_size)
ascent = font_obj.metrics('ascent')
# 中文字符的视觉重心在距顶部约 67% ascent 位置
# 注意:Text widget 有 spacing1=2 的段落前间距
text_visual_center = Config.TEXT_PADY + 2 + ascent * 0.67
checkbox_top_offset = max(0, int(text_visual_center - Config.CHECKBOX_CENTER))
# 使用 pack_configure 直接修改 pady,不破坏布局顺序
self.checkbox.pack_configure(pady=(checkbox_top_offset, 0))
def update_item_data(self, new_item_data: Dict, font_size=None):
"""更新待办事项的数据和UI(优化:减少不必要的更新)"""
old_completed = self.item_data.get('completed', False)
old_font_size = self.font_size
self.item_data = new_item_data
font_size_changed = False
if font_size is not None and font_size != self.font_size:
self.font_size = font_size
font_size_changed = True
new_completed = self.item_data.get('completed', False)
completed_changed = (old_completed != new_completed)
# 更新文本内容 (如果不同)
new_text = self.item_data.get('text', '')
current_text = self.text_entry.get('1.0', 'end-1c')
if current_text != new_text:
# 保存光标位置和选中范围
current_focus = self.focus_get()
try:
cursor_pos = self.text_entry.index(tk.INSERT)
sel_start = self.text_entry.index(tk.SEL_FIRST) if tk.SEL_FIRST in self.text_entry.tag_names() else None
sel_end = self.text_entry.index(tk.SEL_LAST) if tk.SEL_LAST in self.text_entry.tag_names() else None
except:
cursor_pos = '1.0'
sel_start = sel_end = None
self.text_entry.delete('1.0', 'end')
self.text_entry.insert('1.0', new_text)
# 恢复光标位置和选中范围
if current_focus == self.text_entry:
try:
self.text_entry.mark_set(tk.INSERT, cursor_pos)
if sel_start and sel_end:
self.text_entry.tag_add(tk.SEL, sel_start, sel_end)
self.text_entry.mark_set(tk.INSERT, sel_end) # 光标移到选中区末尾
except:
pass
# 只有在完成状态改变时才更新复选框
if completed_changed:
self._draw_checkbox()
# 同时更新删除线
self.after(10, self._draw_strikethrough)
# 只有在颜色或字体需要改变时才更新配置
if completed_changed or font_size_changed:
text_color = Config.COLOR_TEXT_DIM if new_completed else Config.COLOR_TEXT
self.text_entry.config(fg=text_color, font=self._get_font_style())
self.text_entry.edit_modified(False) # 确保字体更新后刷新显示
# 如果字体大小改变了,重新计算复选框对齐
if font_size_changed:
self._update_checkbox_alignment()
# 重新调整高度和处理标点 (只在文本或字体改变时)
if current_text != new_text or font_size_changed:
self._auto_resize_text()
self.after(50, self._fix_punctuation_wrapping)
def _on_checkbox_press(self, event):
"""复选框按下:启动长按检测"""
self._drag_start_time = self.after(Config.DRAG_THRESHOLD_MS, self._start_dragging)
# 绑定移动事件
self.checkbox.bind('<B1-Motion>', self._on_dragging)
def _on_checkbox_release(self, event):
"""复选框释放:短按切换或结束拖拽"""
# 取消长按定时器
if self._drag_start_time:
self.after_cancel(self._drag_start_time)
self._drag_start_time = None
# 解绑移动事件
self.checkbox.unbind('<B1-Motion>')
if self._is_dragging:
# 结束拖拽
self._end_dragging()
else:
# 短按:切换完成状态
self._on_toggle()
def _start_dragging(self):
"""开始拖拽"""
self._is_dragging = True
self.config(cursor='hand2')
# 改变背景色表示正在拖拽
self.config(bg='#3a3a3a')
def _on_dragging(self, event):
"""拖拽中"""
if not self._is_dragging:
return
# 通知父窗口处理拖拽
parent = self._find_parent_with_method('_handle_item_drag')
if parent:
parent._handle_item_drag(self, event.y_root)
def _end_dragging(self):
"""结束拖拽"""
self._is_dragging = False
self.config(cursor='')
self.config(bg=Config.COLOR_BG)
# 通知父窗口完成拖拽
parent = self._find_parent_with_method('_handle_item_drop')
if parent:
parent._handle_item_drop(self)
# ===== 自定义菜单组件 =====
class CustomMenu(tk.Toplevel):
"""自定义风格的右键菜单"""
def __init__(self, parent, close_callback=None, **kwargs):
super().__init__(parent, **kwargs)
self.withdraw() # 初始隐藏
self.overrideredirect(True) # 无边框
self.attributes('-topmost', True) # 置顶
# 视觉样式
self.bg_color = "#2b2b2b"
self.fg_color = "#e0e0e0"
self.hover_color = "#3a3a3a"
self.border_color = "#454545"
self.separator_color = "#404040"
self.font = (Config.FONT_FAMILY, 10)
self.shortcut_font = (Config.FONT_FAMILY, 9)
self.shortcut_fg = "#808080"
# 内部状态
self.active_submenu = None # 当前激活的子菜单
self.parent_menu = None # 父菜单(如果是子菜单的话)
self.close_callback = close_callback # 菜单关闭时的回调
self.config(bg=self.border_color) # 边框颜色通过背景实现
# 内容容器(带有1像素内边距,形成边框效果)
self.container = tk.Frame(self, bg=self.bg_color)
self.container.pack(fill='both', expand=True, padx=1, pady=1)
self.items = [] # 存储菜单项组件
self.commands = [] # 存储回调函数
# 失去焦点时关闭
self.bind('<FocusOut>', self._on_focus_out)
self.bind('<Button-1>', self._on_click_bg)
self.bind('<Escape>', self._on_escape) # ESC 键关闭菜单
# 应用视觉效果
self.after(10, self._apply_effects)
def _apply_effects(self):
"""应用圆角和模糊效果"""
hwnd = WindowsEffects.get_window_handle(self)
WindowsEffects.apply_menu_effects(hwnd)
def add_command(self, label, command, accelerator=None, state=tk.NORMAL):
"""添加菜单项"""
self._add_item(label, command, accelerator, state, is_submenu=False)
def add_cascade(self, label, menu):
"""添加子菜单"""
# menu 应该是一个 CustomMenu 实例,但还没有 show
menu.parent_menu = self
self._add_item(label, menu, accelerator="›", state=tk.NORMAL, is_submenu=True)
def _add_item(self, label, command_or_menu, accelerator, state, is_submenu):
"""内部添加项逻辑"""
item_frame = tk.Frame(self.container, bg=self.bg_color, cursor='hand2')
item_frame.pack(fill='x')
fg = self.fg_color if state == tk.NORMAL else self.shortcut_fg
# 左侧标签
lbl_text = tk.Label(
item_frame,
text=f" {label}",
bg=self.bg_color,
fg=fg,
font=self.font,
anchor='w',
padx=10,
pady=6
)
lbl_text.pack(side='left', fill='x', expand=True)
# 右侧快捷键或箭头
if accelerator:
lbl_acc = tk.Label(
item_frame,
text=f"{accelerator} ",
bg=self.bg_color,
fg=self.shortcut_fg if state == tk.NORMAL else "#505050",
font=self.shortcut_font,
anchor='e',
padx=10
)
lbl_acc.pack(side='right')
else:
lbl_acc = None
if state == tk.NORMAL:
widgets = [item_frame, lbl_text]
if lbl_acc: widgets.append(lbl_acc)
# 绑定事件
for w in widgets:
# 悬停事件
w.bind('<Enter>', lambda e, f=item_frame, lt=lbl_text, la=lbl_acc, cmd=command_or_menu, is_sub=is_submenu:
self._on_item_hover(f, lt, la, cmd, is_sub))
# 点击事件
if not is_submenu: # 子菜单点击无效,只响应悬停
# 关键修复:command必须在此时绑定,否则循环中的闭包会出错
# 这里 command_or_menu 就是回调函数
w.bind('<Button-1>', lambda e, cmd=command_or_menu: self._on_click(cmd))
self.items.append(item_frame)
def add_separator(self):
"""添加分隔线"""
sep = tk.Frame(self.container, bg=self.separator_color, height=1)
sep.pack(fill='x', pady=4)
def _on_item_hover(self, frame, lbl_text, lbl_acc, command_or_menu, is_submenu):
"""鼠标悬停处理"""
# 1. 恢复所有项的背景色
for child in self.container.winfo_children():
if isinstance(child, tk.Frame) and child.winfo_height() > 1: # 排除分隔线
color = self.bg_color
child.config(bg=color)
for w in child.winfo_children():
w.config(bg=color)
# 2. 高亮当前项
frame.config(bg=self.hover_color)
lbl_text.config(bg=self.hover_color)
if lbl_acc: lbl_acc.config(bg=self.hover_color)
# 3. 处理子菜单
if is_submenu:
# 显示子菜单
self._open_submenu(frame, command_or_menu)
else:
# 如果悬停在普通项上,延迟关闭已打开的子菜单
if self.active_submenu:
# 给一点延迟,防止鼠标斜向移动时意外关闭
self.after(300, self._check_close_submenu)
def _open_submenu(self, item_frame, submenu):
"""打开子菜单"""
if self.active_submenu == submenu:
return # 已经打开
if self.active_submenu:
self.active_submenu.hide()
self.active_submenu = submenu