File size: 125,267 Bytes
3db9552
3510ac4
21952dc
65f2ee1
f4ae1c5
9b2f915
21952dc
1c93269
21952dc
1c93269
21952dc
f4ae1c5
21952dc
d05282e
1c93269
65f2ee1
9b2f915
1c93269
f4ae1c5
 
21952dc
 
1c93269
3510ac4
60770a1
 
65f2ee1
21952dc
7a3311b
21952dc
1c93269
7a3311b
21952dc
 
 
f4ae1c5
9be1e74
 
 
 
 
 
68dd90e
 
 
9be1e74
 
f4ae1c5
 
1779b47
 
 
 
 
 
 
 
 
 
 
 
 
f985a6e
 
 
0a8b231
 
 
 
 
f985a6e
 
 
 
 
 
905c9a4
 
 
 
 
 
 
 
 
 
 
 
 
f985a6e
 
 
 
 
 
 
 
 
51e54a7
 
 
dccd280
 
51e54a7
 
3fefa46
 
 
7dd6a04
3fefa46
 
 
 
ba480e2
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
 
21952dc
 
 
 
51028f1
21952dc
 
 
 
 
 
 
 
75f2f4a
5919776
75f2f4a
f4ae1c5
 
7a3311b
 
ec88cef
 
7a3311b
 
 
 
 
ba480e2
 
cbf03e6
 
 
 
23fba3c
 
 
 
 
 
 
ed50718
21952dc
 
 
 
ed50718
88e9df2
 
51e54a7
f4ae1c5
 
51028f1
21952dc
 
 
 
f4ae1c5
 
8cd514d
21952dc
 
8cd514d
7a3311b
 
8cd514d
51e54a7
9b2f915
8cd514d
9b2f915
51e54a7
 
 
 
 
 
 
 
dccd280
 
 
f985a6e
cf6661d
8cd514d
598f5b2
0a8b231
dccd280
279340c
 
 
8cd514d
 
 
 
 
 
f4ae1c5
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46859da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46859da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e023998
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631cd41
 
a282b13
631cd41
 
 
 
 
 
 
 
 
a282b13
631cd41
 
a282b13
631cd41
a282b13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d20658
a282b13
9d20658
a282b13
 
 
 
 
 
631cd41
 
 
 
 
 
 
 
e023998
 
 
 
 
 
 
9d20658
21952dc
 
 
 
 
e023998
 
 
 
 
 
 
 
 
 
 
 
 
21952dc
 
 
 
 
 
 
 
 
d05282e
 
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
f5f13be
21952dc
 
 
 
 
 
d05282e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5f13be
d05282e
 
 
21952dc
e3fae40
21952dc
 
 
 
 
 
 
 
cdaa4a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51028f1
 
 
 
 
 
 
 
 
 
 
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60770a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21952dc
 
 
 
 
7a3311b
21952dc
 
 
 
 
 
 
60770a1
f4ae1c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b2f915
f4ae1c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed50718
25bccf9
ed50718
1779b47
 
293651f
 
25bccf9
293651f
5919776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293651f
1779b47
293651f
 
5919776
293651f
 
5919776
293651f
 
 
 
 
 
 
 
1779b47
293651f
1779b47
293651f
 
5919776
 
293651f
5919776
293651f
5919776
293651f
5919776
 
293651f
5919776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293651f
5919776
df39c73
 
 
 
 
 
 
1779b47
ed50718
 
75f2f4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a7645a
75f2f4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a7645a
75f2f4a
 
 
 
 
 
 
 
5a7645a
 
 
 
 
75f2f4a
5a7645a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75f2f4a
 
 
 
 
 
 
 
 
 
5a7645a
 
 
 
75f2f4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed50718
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
3510ac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25bccf9
f4ae1c5
 
 
 
 
 
 
cbf03e6
f4ae1c5
 
 
 
 
1779b47
5919776
f4ae1c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3890cfd
 
 
 
 
 
 
 
 
 
 
 
 
1779b47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3890cfd
f4ae1c5
 
25bccf9
f4ae1c5
5919776
 
0f5e3b4
5919776
 
21952dc
5919776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65f2ee1
cbf03e6
 
 
 
 
 
 
 
 
 
 
 
 
 
797c587
 
 
 
9f3cff9
9b2f915
f4ae1c5
9b2f915
 
3b39a01
9b2f915
0f5e3b4
3b39a01
9b2f915
 
 
 
 
 
 
 
3b39a01
 
f4ae1c5
9b2f915
f4ae1c5
cbf03e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89746cd
cbf03e6
 
3b39a01
cbf03e6
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
89746cd
 
 
 
 
 
3b39a01
f4ae1c5
 
cbf03e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b39a01
 
 
 
 
7a7f6ab
 
 
 
 
 
 
 
 
 
 
 
3719c11
88e9df2
3719c11
88e9df2
3719c11
 
 
 
88e9df2
3719c11
 
 
 
 
7a7f6ab
 
 
 
 
3b39a01
 
 
 
 
 
 
 
 
 
 
 
 
 
9b2f915
 
f4ae1c5
 
 
5c77b8a
fe710cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c77b8a
 
fe710cd
 
1c93269
fe710cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c77b8a
fe710cd
5c77b8a
fe710cd
 
5c77b8a
fe710cd
 
 
 
 
 
 
1c93269
 
 
 
fe710cd
 
 
 
 
 
 
 
 
5c77b8a
fe710cd
1c93269
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c77b8a
 
 
1c93269
 
fe710cd
1c93269
 
5c77b8a
 
 
fe710cd
1c93269
 
 
 
 
 
 
fe710cd
1c93269
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c77b8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c93269
 
 
 
5c77b8a
1c93269
 
 
 
 
 
 
 
 
 
5c77b8a
1c93269
 
 
 
 
 
fe710cd
 
1c93269
 
 
 
 
 
fe710cd
0a8b231
 
7a7f6ab
0a8b231
905c9a4
 
 
 
0a8b231
 
 
 
0821f20
0a8b231
 
 
 
 
 
 
 
 
 
 
 
 
 
0821f20
 
 
 
 
 
 
 
0a8b231
 
 
 
 
905c9a4
 
 
 
 
0a8b231
 
905c9a4
 
 
 
 
 
 
 
 
 
0821f20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
905c9a4
 
 
 
0a8b231
 
 
905c9a4
 
0a8b231
905c9a4
0a8b231
905c9a4
 
 
 
 
 
 
 
 
 
 
 
 
0a8b231
 
905c9a4
0a8b231
905c9a4
 
 
 
 
 
 
0a8b231
 
 
 
65f2ee1
 
9b2f915
f4ae1c5
 
 
 
9b2f915
f4ae1c5
 
 
 
9b2f915
f4ae1c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74ab69d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe710cd
74ab69d
 
 
 
 
 
 
ec88cef
74ab69d
7dd6a04
 
 
 
 
74ab69d
 
 
ec88cef
74ab69d
 
 
 
ec88cef
74ab69d
 
 
 
f4ae1c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a7f6ab
f4ae1c5
7a7f6ab
 
 
 
 
 
 
 
f4ae1c5
 
 
 
 
 
 
 
 
21952dc
 
 
 
 
 
 
 
 
f4ae1c5
51e54a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a3311b
 
 
 
 
 
21952dc
7a3311b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21952dc
 
 
23fba3c
21952dc
 
 
 
 
 
 
 
 
 
23fba3c
21952dc
 
 
 
 
23fba3c
21952dc
 
 
 
23fba3c
21952dc
 
 
 
23fba3c
21952dc
 
 
 
 
 
 
 
 
 
 
 
23fba3c
7a3311b
 
 
 
 
21952dc
23fba3c
21952dc
 
 
 
 
23fba3c
21952dc
 
 
 
23fba3c
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23fba3c
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23fba3c
21952dc
 
 
 
 
 
 
 
 
 
23fba3c
 
 
 
 
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a3311b
 
 
 
 
21952dc
 
 
76e3d4d
21952dc
 
 
 
 
76e3d4d
21952dc
 
 
 
 
 
 
 
7a3311b
21952dc
 
 
 
76e3d4d
21952dc
 
 
 
 
 
 
 
ba480e2
21952dc
 
 
7a3311b
 
 
 
 
 
 
 
 
 
 
 
 
ba480e2
 
 
 
 
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba480e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
 
 
 
23fba3c
76e3d4d
 
 
21952dc
cdaa4a4
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e3d4d
 
23fba3c
cdaa4a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21952dc
46859da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21952dc
 
cbf03e6
21952dc
 
 
 
cbf03e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3db9552
 
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
3db9552
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
3db9552
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
3db9552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
3db9552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
3db9552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
3db9552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
3db9552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
3db9552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdaa4a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f985a6e
df39c73
f985a6e
df39c73
f985a6e
d708663
df39c73
d708663
df39c73
d708663
df39c73
 
 
 
d708663
df39c73
d708663
df39c73
566b5a2
df39c73
566b5a2
df39c73
 
 
566b5a2
df39c73
88e9df2
df39c73
 
 
 
 
 
 
88e9df2
df39c73
 
88e9df2
df39c73
 
 
88e9df2
df39c73
 
 
 
 
 
 
88e9df2
 
df39c73
 
 
88e9df2
 
df39c73
 
 
566b5a2
df39c73
566b5a2
df39c73
566b5a2
df39c73
 
 
 
 
 
566b5a2
df39c73
 
 
 
 
 
598f5b2
f985a6e
566b5a2
df39c73
 
 
 
f985a6e
 
3db9552
21952dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
21952dc
3db9552
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
 
 
ba480e2
ed50718
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
using CommunityToolkit.Mvvm.DependencyInjection;
using iText.IO.Image;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenCvSharp;
using OpenCvSharp.WpfExtensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq; // 添加这个引用
using System.Reflection.Emit;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
//using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;
using Brushes = System.Windows.Media.Brush;
using Path = System.IO.Path;
using Point = System.Windows.Point;
using Rectangle = System.Windows.Shapes.Rectangle;
using Window = System.Windows.Window;

/*

    see huggingface/pdf_ocr/main.py

    see huggingface/ExtractPdfImage/Form1.cs

        # 图片导出

    see huggingface/project/ocr/ocrClient

        # 图片压缩

    see https://github.com/lellid/LediReader

        # epub wpf显示



*/

namespace WpfEditor
{
    // 添加图片文件信息类
    public class ImageFileInfo
    {
        public string Name { get; set; }
        public string FullPath { get; set; }
        
        public ImageFileInfo(string fullPath)
        {
            FullPath = fullPath;
            Name = Path.GetFileName(fullPath);
        }
    }

    // 添加树形目录节点信息类
    public class DirectoryTreeNode
    {

        public int level { get; set; }
        public TextLine line { get; set; }


        public string Name { get; set; }
        public string FullPath { get; set; }
        public string Icon { get; set; }
        public bool IsDirectory { get; set; }
        public List<DirectoryTreeNode> Children { get; set; }

        public DirectoryTreeNode(string Name, int level, TextLine textline)
        {
            FullPath = Name;
            //Name = Path.GetFileName(fullPath);
            //if (string.IsNullOrEmpty(Name))
            //    Name = fullPath; // 对于根目录
            //IsDirectory = isDirectory;
            //Icon = isDirectory ? "📁" : "📄";
            this.Name = Name;
            this.level = level;
            this.line = textline;
            Icon = "📄";
            IsDirectory = false;
            Children = new List<DirectoryTreeNode>();
        }

        public override string ToString()
        {
            return Name;
        }
    }

    public enum EditorMode
    {
        ImageOCR,
        ReviseEdit,
        MenuSplit
    }

    public enum OcrMode
    {
        WeChatOcr,
        ComicOcr,
        AliOCR,
        PPOCR
    }

    public class CursorPositionChangedEventArgs : EventArgs
    {
        public int Line { get; set; }
        public int Column { get; set; }

        public CursorPositionChangedEventArgs(int line, int column)
        {
            Line = line;
            Column = column;
        }
    }

    public partial class MainWindow : Window
    {

        /// <summary>
        /// 用于框选
        /// </summary>
        public ViewModel ViewModel { get; set; }
        private Mat? imgMat;
        private System.Windows.Point origin;
        private System.Windows.Point start;
        private bool isDragging = false;
        private bool isDrawingRectangle = false;
        private System.Windows.Point rectangleStartPoint;


        public string _book = "";
        public List<string> opened_image_pths = new List<string>();

        private string _currentFilePath = null;
        private bool _textChanged = false;
        private double _imageZoomFactor = 1.0;
        private EditorMode _mode = EditorMode.ImageOCR;
        public OcrMode _ocrMode = OcrMode.WeChatOcr;

        // 添加框选相关变量
        private bool _isSelecting = false;
        private Point _selectionStartPoint;
        private Rectangle _selectionRectangle;
        private Canvas _selectionCanvas;
        // 添加存储多个矩形选框的集合
        private List<Rectangle> _selectionRectangles = new List<Rectangle>();

        // 在类中添加一个字段来存储待处理的矩形数据
        private List<JObject> _pendingRectangles = new List<JObject>();  // 等图片显示后才能正确进行坐标转换

        // 添加调整大小相关变量
        private bool _isResizing = false;
        private Rectangle _resizingRectangle = null;
        private string _resizeDirection = ""; // "left", "right", "top", "bottom", "topleft", "topright", "bottomleft", "bottomright"
        private Point _resizeStartPoint;
        private double _originalLeft, _originalTop, _originalWidth, _originalHeight;
    
        private bool _isImageListVisible = true;
        
        // 添加图片尺寸变化处理方法
        private double _previousImageWidth = 0;
        private double _previousImageHeight = 0;

        public Dictionary<string, string> _dic_m5_imgname = new Dictionary<string, string>();

        public MainWindow(EditorMode mode = EditorMode.ImageOCR)
        {
            InitializeComponent();
            Editor._mainWindow = this;

            ViewModel = new ViewModel();
            DataContext = ViewModel;

            Editor.TextChanged += Editor_TextChanged;
            Editor.CursorPositionChanged += Editor_CursorPositionChanged;

            // 添加图片尺寸变化监听
            image.SizeChanged += Image_SizeChanged;

            // 初始化选择画布
            InitializeSelectionCanvas();

            this._mode = mode;
            Editor._mode = mode;


            if (this._mode == EditorMode.ImageOCR)
            {
                this.Title = "图片识别";
            }
            else if (this._mode == EditorMode.ReviseEdit)
            {
                this.Title = "整理校对";
            }
            else if (this._mode == EditorMode.MenuSplit)
            {
                this.Title = "目录拆解";
                this.BorderDirectoryTreeView.Visibility = Visibility.Visible;
                this.DirectoryTreeView.Visibility = Visibility.Visible;

                // 为目录拆解模式添加示例数据
                //InitializeDirectoryTreeData();
            }

            // 自动选择最佳的编程字体
            FontManager.SetProgrammingFont(Editor, 14);

            //GlobalHotKey.RegisterHotKey("Alt + S", () => {

            //    int a = 1;
            
            //});
        }


        private void OnOpenImage_Click(string FileName)
        {
            try
            {
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.UriSource = new Uri(FileName);
                bitmap.EndInit();

                ViewModel.Image = bitmap;
                ViewModel.ClearAllRectangles();
                
                // 重置图片尺寸记录
                _previousImageWidth = 0;
                _previousImageHeight = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法加载图片: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Grid_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            double zoom = e.Delta > 0 ? 0.2 : -0.2;
            double minScale = 0.5;
            double maxScale = 10.0;
            double newScale = scaleTransform.ScaleX + zoom;

            if (newScale < minScale) newScale = minScale;
            else if (newScale > maxScale) newScale = maxScale;

            if (Math.Abs(newScale - scaleTransform.ScaleX) < 0.001) return;

            var mousePos = e.GetPosition(image);
            var oldScale = scaleTransform.ScaleX;

            scaleTransform.ScaleX = newScale;
            scaleTransform.ScaleY = newScale;

            var deltaScale = newScale - oldScale;
            double newX = translateTransform.X - mousePos.X * deltaScale;
            double newY = translateTransform.Y - mousePos.Y * deltaScale;
            
            // 添加边界检查,防止缩放后图片移出可视区域
            if (image.ActualWidth > 0 && image.ActualHeight > 0)
            {
                var grid = sender as Grid;
                if (grid != null)
                {
                    double scaledWidth = image.ActualWidth * newScale;
                    double scaledHeight = image.ActualHeight * newScale;
                    double containerWidth = grid.ActualWidth;
                    double containerHeight = grid.ActualHeight;
                    
                    // 限制X坐标范围,确保图片至少有一部分可见
                    double minX = -scaledWidth + 50; // 至少保留50像素可见
                    double maxX = containerWidth - 50;
                    newX = Math.Max(minX, Math.Min(maxX, newX));
                    
                    // 限制Y坐标范围,确保图片至少有一部分可见
                    double minY = -scaledHeight + 50;
                    double maxY = containerHeight - 50;
                    newY = Math.Max(minY, Math.Min(maxY, newY));
                }
            }
            
            translateTransform.X = newX;
            translateTransform.Y = newY;

            if (Math.Abs(newScale - 1.0) < 0.001)
            {
                translateTransform.X = 0;
                translateTransform.Y = 0;
            }
        }


        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!isDrawingRectangle)
            {
                var grid = sender as Grid;
                if (grid != null)
                {
                    grid.CaptureMouse();
                    isDragging = true;
                    start = e.GetPosition(grid);
                    origin = new System.Windows.Point(translateTransform.X, translateTransform.Y);
                }
            }
        }

        private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging && e.LeftButton == MouseButtonState.Pressed &&
                (Keyboard.IsKeyUp(Key.LeftCtrl) && Keyboard.IsKeyUp(Key.RightCtrl)))
            {
                var grid = sender as Grid;
                if (grid != null)
                {
                    Vector v = start - e.GetPosition(grid);
                    double newX = origin.X - v.X;
                    double newY = origin.Y - v.Y;
                    
                    // 添加边界检查,确保图片不会完全移出可视区域
                    if (image.ActualWidth > 0 && image.ActualHeight > 0)
                    {
                        double scaledWidth = image.ActualWidth * scaleTransform.ScaleX;
                        double scaledHeight = image.ActualHeight * scaleTransform.ScaleY;
                        double containerWidth = grid.ActualWidth;
                        double containerHeight = grid.ActualHeight;
                        
                        // 限制X坐标范围,确保图片至少有一部分可见
                        double minX = -scaledWidth + 50; // 至少保留50像素可见
                        double maxX = containerWidth - 50;
                        newX = Math.Max(minX, Math.Min(maxX, newX));
                        
                        // 限制Y坐标范围,确保图片至少有一部分可见
                        double minY = -scaledHeight + 50;
                        double maxY = containerHeight - 50;
                        newY = Math.Max(minY, Math.Min(maxY, newY));
                    }
                    
                    translateTransform.X = newX;
                    translateTransform.Y = newY;
                }
            }
            else if (isDrawingRectangle && e.RightButton == MouseButtonState.Pressed)
            {
                var currentPoint = e.GetPosition(image);
                UpdateRectangle(rectangleStartPoint, currentPoint);
            }
        }

        private void Grid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var grid = sender as Grid;
            if (grid != null)
            {
                grid.ReleaseMouseCapture();
                isDragging = false;
            }
        }

        // 修改检测方法,返回被点击的具体选框
        private RectangleItem GetClickedRectangle(Point point)
        {
            // 只在校对模式下进行检测
            if (_mode != EditorMode.ReviseEdit)
                return null;

            // 检查点击位置是否在任何现有的绿色选框内部
            foreach (var rectangle in ViewModel.Rectangles)
            {
                if (rectangle.IsVisible &&
                    point.X >= rectangle.Left &&
                    point.X <= rectangle.Left + rectangle.Width &&
                    point.Y >= rectangle.Top &&
                    point.Y <= rectangle.Top + rectangle.Height)
                {
                    return rectangle;
                }
            }
            return null;
        }

        // 显示删除选框的右键菜单
        private void ShowDeleteContextMenu(RectangleItem rectangle, Point position)
        {
            var contextMenu = new ContextMenu();
            var deleteMenuItem = new MenuItem()
            {
                Header = "删除选框",
                Tag = rectangle
            };
            deleteMenuItem.Click += (s, e) =>
            {
                var rect = (RectangleItem)((MenuItem)s).Tag;

                // 先删除选框下的文字
                List<int> idxs = new List<int>();
                foreach (var (line, index) in Editor._lines.Select((line, index) => (line, index) ))
                {
                    if (line.selected_rectange == null || !line.selected_rectange.HasValues)
                    {
                        continue;
                    }
                    int Id = line.selected_rectange["Id"].Value<int>();
                    if (rect.Id == Id)
                    {
                        idxs.Add(index);
                    }
                }
                if (idxs.Count > 0)
                {
                    // 后面的 ID 全部减 1
                    foreach (var (line, index) in Editor._lines.Select((line, index) => (line, index)))
                    {
                        if (line.selected_rectange == null || !line.selected_rectange.HasValues)
                        {
                            continue;
                        }
                        int Id = Editor._lines[index].selected_rectange["Id"].Value<int>();
                        if (Id > rect.Id)
                        {
                            Editor._lines[index].selected_rectange["Id"] = Id - 1;
                        }
                    }

                    foreach(RectangleItem item in ViewModel.rectangles)
                    {
                        if (item.Id > rect.Id)
                        {
                            item.Id -= 1;
                        }
                    }

                    for (int i = idxs.Count - 1; i >= 0; i--)
                    {
                        Editor._lines.RemoveAt( idxs[i] );
                    }

                    // 删除选框
                    ViewModel.RemoveRectangle(rect);
                    ViewModel.rectangleCounter -= 1;

                }
                
                Editor.ClearSelection();
                _textChanged = true;
                Editor.InvalidateVisual();
                // 触发文本改变事件
                Editor.OnTextChanged();

            };
            
            contextMenu.Items.Add(deleteMenuItem);
            contextMenu.IsOpen = true;
            contextMenu.PlacementTarget = image;
            contextMenu.Placement = PlacementMode.MousePoint;
        }
        // 
        private void Grid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (ViewModel.Image != null)
            {
                rectangleStartPoint = e.GetPosition(image);
                
                // 在校对模式下,检查是否点击在现有绿色选框内部
                if (_mode == EditorMode.ReviseEdit)
                {
                    var clickedRectangle = GetClickedRectangle(rectangleStartPoint);
                    if (clickedRectangle != null)
                    {
                        // 如果点击在现有绿色选框内部,显示删除菜单
                        ShowDeleteContextMenu(clickedRectangle, rectangleStartPoint);
                        return;
                    }
                }
                
                isDrawingRectangle = true;
                ViewModel.IsDrawingRectangle = true;
                ViewModel.RectangleVisible = true;

                var grid = sender as Grid;
                grid?.CaptureMouse();
            }
        }


        // 框图出字
        private void Grid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (isDrawingRectangle)
            {
                var grid = sender as Grid;
                grid?.ReleaseMouseCapture();

                isDrawingRectangle = false;
                ViewModel.IsDrawingRectangle = false;

                // 完成矩形绘制,添加到集合中
                if (ViewModel.RectangleWidth > 5 && ViewModel.RectangleHeight > 5)
                {
                    // 添加新的矩形框到集合
                    int Id = ViewModel.AddRectangle(
                        ViewModel.RectangleLeft,
                        ViewModel.RectangleTop,
                        ViewModel.RectangleWidth,
                        ViewModel.RectangleHeight
                    );

                    var x_y_ = Editor.ConvertDisplayToOriginalCoordinates(ViewModel.RectangleLeft, ViewModel.RectangleTop);
                    var w_h_ = Editor.ConvertDisplayToOriginalSize(ViewModel.RectangleWidth, ViewModel.RectangleHeight);
                    var pth_img = Editor._pthimg;

                    Mat orig = new Mat(pth_img, ImreadModes.Color);
                    var rect = new OpenCvSharp.Rect
                    {
                        X = (int)(x_y_.X + 0.5),
                        Y = (int)(x_y_.Y + 0.5),
                        Width = (int)(w_h_.Width+0.5) > orig.Width ? orig.Width: (int)(w_h_.Width+0.5),
                        Height = (int)(w_h_.Height+0.5) > orig.Height ? orig.Height : (int)(w_h_.Height + 0.5),
                    };
                    orig.Rectangle(rect, Scalar.Red);

                    Cv2.ImShow("orig", orig);
                    Cv2.WaitKey();
                    orig.Dispose();

                    // 找出框选的文字
                    JObject jsn = (JObject)Editor._jsn_OpenImg.DeepClone();
                    jsn = Global.find_rectange_text(jsn, rect.X, rect.Y, rect.Width, rect.Height, Id);
                    Editor.InsertText(jsn, Editor._md5_OpenImg);


                    // 可选:仍然显示截图窗口
                    //CropAndShowImage();
                }

                // 清除临时矩形
                ViewModel.ClearRectangle();
            }
        }


        private void On_Rectangle_adjust(RectangleItem rectangle)
        {
            // 先找出选框调整前的行
            List<int> idxs = new List<int>();
            foreach (var (line, index) in Editor._lines.Select((line, index) => (line, index)))
            {
                if (line.selected_rectange == null || !line.selected_rectange.HasValues)
                {
                    continue;
                }
                int Id = line.selected_rectange["Id"].Value<int>();
                if (rectangle.Id == Id)
                {
                    idxs.Add(index);
                }
            }

            // 再找出当前选框框出的文字
            var x_y_ = Editor.ConvertDisplayToOriginalCoordinates(rectangle.Left, rectangle.Top);  // new System.Windows.Point(rectangle.Left, rectangle.Top);
            var w_h_ = Editor.ConvertDisplayToOriginalSize(rectangle.Width, rectangle.Height);     // new System.Windows.Size(rectangle.Width, rectangle.Height);
            var pth_img = Editor._pthimg;

            Mat orig = new Mat(pth_img, ImreadModes.Color);
            var rect = new OpenCvSharp.Rect
            {
                X = (int)(x_y_.X + 0.5),
                Y = (int)(x_y_.Y + 0.5),
                Width = (int)(w_h_.Width + 0.5) > orig.Width ? orig.Width : (int)(w_h_.Width + 0.5),
                Height = (int)(w_h_.Height + 0.5) > orig.Height ? orig.Height : (int)(w_h_.Height + 0.5),
            };

            JObject jsn = (JObject)Editor._jsn_OpenImg.DeepClone();
            jsn = Global.find_rectange_text(jsn, rect.X, rect.Y, rect.Width, rect.Height, rectangle.Id);
            if (jsn == null || !jsn.HasValues)
            {
                return;
            }
            var lines = Editor.get_text_lines(jsn, Editor._md5_OpenImg);


            if (idxs.Count > 0 && lines.Count > 0)
            {
                int start = idxs[0];
                //int end = idxs[idxs.Count - 1];
                Editor._lines.RemoveRange(start, idxs.Count);
                Editor._lines.InsertRange(start, lines);

                Editor.ClearSelection();
                _textChanged = true;
                Editor.InvalidateVisual();
                // 触发文本改变事件
                Editor.OnTextChanged();
            }
        }

        private void UpdateRectangle(System.Windows.Point startPoint, System.Windows.Point currentPoint)
        {
            double left = Math.Min(startPoint.X, currentPoint.X);
            double top = Math.Min(startPoint.Y, currentPoint.Y);
            double width = Math.Abs(currentPoint.X - startPoint.X);
            double height = Math.Abs(currentPoint.Y - startPoint.Y);

            ViewModel.RectangleLeft = left;
            ViewModel.RectangleTop = top;
            ViewModel.RectangleWidth = width;
            ViewModel.RectangleHeight = height;
        }

        private void CropAndShowImage()
        {
            try
            {
                if (ViewModel.Image == null) return;

                // 获取原图坐标
                var topLeft = GetScaledPosition(new System.Windows.Point(ViewModel.RectangleLeft, ViewModel.RectangleTop), image);
                var bottomRight = GetScaledPosition(new System.Windows.Point(
                    ViewModel.RectangleLeft + ViewModel.RectangleWidth,
                    ViewModel.RectangleTop + ViewModel.RectangleHeight), image);

                // 确保坐标在图片范围内
                int x = Math.Max(0, (int)topLeft.X);
                int y = Math.Max(0, (int)topLeft.Y);
                int width = Math.Min((int)(bottomRight.X - topLeft.X), ViewModel.Image.PixelWidth - x);
                int height = Math.Min((int)(bottomRight.Y - topLeft.Y), ViewModel.Image.PixelHeight - y);

                if (width <= 0 || height <= 0) return;

                // 使用OpenCV进行截图
                imgMat = ViewModel.Image.ToMat();
                var cropRect = new OpenCvSharp.Rect(x, y, width, height);
                var croppedMat = imgMat[cropRect];

                // 转换为BitmapSource
                var croppedBitmap = croppedMat.ToBitmapSource();

                // 显示截图窗口
                ShowCroppedImage(croppedBitmap, new System.Windows.Point(x, y), new System.Windows.Point(x + width, y + height));

                croppedMat.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"截图失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 显示字符选框
        public void ShowCharacterSelection(double left, double top, double width, double height)
        {
            // 使用ViewModel的临时矩形框功能
            ViewModel.RectangleLeft = left;
            ViewModel.RectangleTop = top;
            ViewModel.RectangleWidth = width;
            ViewModel.RectangleHeight = height;
            ViewModel.RectangleVisible = true;
        }

        private void ShowCroppedImage(BitmapSource croppedImage, System.Windows.Point topLeft, System.Windows.Point bottomRight)
        {
            var cropWindow = new Window
            {
                Title = "截图结果",
                Width = Math.Max(300, croppedImage.PixelWidth + 50),
                Height = Math.Max(200, croppedImage.PixelHeight + 100),
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = this,
                Background = new SolidColorBrush(Colors.Black)
            };

            var stackPanel = new StackPanel
            {
                Margin = new Thickness(10, 10, 10, 10)
            };

            var infoText = new TextBlock
            {
                Text = $"原图坐标: ({topLeft.X:F0}, {topLeft.Y:F0}) - ({bottomRight.X:F0}, {bottomRight.Y:F0})\n" +
                       $"截图尺寸: {croppedImage.PixelWidth} x {croppedImage.PixelHeight}",
                Foreground = new SolidColorBrush(Colors.White),
                FontSize = 12,
                Margin = new Thickness(0, 0, 0, 10),
                TextAlignment = TextAlignment.Center
            };

            var imageControl = new System.Windows.Controls.Image
            {
                Source = croppedImage,
                Stretch = Stretch.Uniform,
                MaxWidth = 800,
                MaxHeight = 600
            };

            var buttonPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 10, 0, 0)
            };

            var saveButton = new Button
            {
                Content = "保存图片",
                Padding = new Thickness(10, 5, 10, 5),
                Margin = new Thickness(5, 5, 5, 5),
                Background = new SolidColorBrush(Colors.DodgerBlue),
                Foreground = new SolidColorBrush(Colors.White)
            };

            saveButton.Click += (s, e) => SaveCroppedImage(croppedImage);

            var closeButton = new Button
            {
                Content = "关闭",
                Padding = new Thickness(10, 5, 10, 5),
                Margin = new Thickness(5, 5, 5, 5),
                Background = new SolidColorBrush(Colors.Gray),
                Foreground = new SolidColorBrush(Colors.White)
            };

            closeButton.Click += (s, e) => cropWindow.Close();

            buttonPanel.Children.Add(saveButton);
            buttonPanel.Children.Add(closeButton);

            stackPanel.Children.Add(infoText);
            stackPanel.Children.Add(imageControl);
            stackPanel.Children.Add(buttonPanel);

            cropWindow.Content = stackPanel;
            cropWindow.ShowDialog();
        }

        private void SaveCroppedImage(BitmapSource image)
        {
            var saveDialog = new SaveFileDialog
            {
                Title = "保存截图",
                Filter = "PNG图片|*.png|JPEG图片|*.jpg|所有文件|*.*",
                DefaultExt = "png"
            };

            if (saveDialog.ShowDialog() == true)
            {
                try
                {
                    using (var fileStream = new FileStream(saveDialog.FileName, FileMode.Create))
                    {
                        BitmapEncoder encoder = saveDialog.FileName.ToLower().EndsWith(".jpg") ||
                                              saveDialog.FileName.ToLower().EndsWith(".jpeg") ?
                                              new JpegBitmapEncoder() : new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(image));
                        encoder.Save(fileStream);
                    }
                    MessageBox.Show("图片保存成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void Image_MouseMove(object sender, MouseEventArgs e)
        {
            if (ViewModel.Image == null) return;

            try
            {
                imgMat = ViewModel.Image.ToMat();

                System.Windows.Point p = e.GetPosition(image);
                if (p.X >= 0 && p.X < image.ActualWidth &&
                    p.Y >= 0 && p.Y < image.ActualHeight)
                {
                    int x = (int)(p.X * (imgMat.Width / image.ActualWidth));
                    int y = (int)(p.Y * (imgMat.Height / image.ActualHeight));

                    x = Math.Max(0, Math.Min(x, imgMat.Width - 1));
                    y = Math.Max(0, Math.Min(y, imgMat.Height - 1));

                    Vec3b pixel = imgMat.At<Vec3b>(y, x);

                    Mat bgr = new Mat(1, 1, MatType.CV_8UC3, new Scalar(pixel.Item0, pixel.Item1, pixel.Item2));
                    Mat hsv = new Mat();
                    Cv2.CvtColor(bgr, hsv, ColorConversionCodes.BGR2HSV);

                    var hsvValues = hsv.Get<Vec3b>(0, 0);

                    //txtHSV.Text = $"坐标: ({x}, {y}) HSV: H={hsvValues.Item0}, S={hsvValues.Item1}, V={hsvValues.Item2}";

                    bgr.Dispose();
                    hsv.Dispose();
                }
            }
            catch (Exception ex)
            {
                //txtHSV.Text = $"错误: {ex.Message}";
            }
        }

        private System.Windows.Point GetScaledPosition(System.Windows.Point position, FrameworkElement element)
        {
            if (ViewModel.Image == null) return position;

            var actualWidth = element.ActualWidth;
            var actualHeight = element.ActualHeight;
            var imageWidth = ViewModel.Image.PixelWidth;
            var imageHeight = ViewModel.Image.PixelHeight;

            var xRatio = imageWidth / actualWidth;
            var yRatio = imageHeight / actualHeight;

            var scaledX = position.X * xRatio;
            var scaledY = position.Y * yRatio;

            return new System.Windows.Point(scaledX, scaledY);
        }

        // 添加鼠标滚轮事件处理
        private void ImageViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            // 检查Ctrl键是否按下
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                // 根据滚轮方向调整缩放因子
                if (e.Delta > 0)
                {
                    // 向上滚动,放大图片
                    _imageZoomFactor *= 1.1;
                }
                else
                {
                    // 向下滚动,缩小图片
                    _imageZoomFactor /= 1.1;
                }
                
                // 限制缩放范围
                _imageZoomFactor = Math.Max(0.1, Math.Min(_imageZoomFactor, 10.0));
                
                // 应用缩放
                ApplyImageZoom();
                
                // 标记事件已处理
                e.Handled = true;
            }
        }
        
        // 应用图片缩放
        private void ApplyImageZoom()
        {
            //if (ImageViewer.Source != null)
            //{
            //    // 创建缩放变换
            //    ScaleTransform scaleTransform = new ScaleTransform(_imageZoomFactor, _imageZoomFactor);
            //    ImageViewer.RenderTransform = scaleTransform;
                
            //    // 同时应用缩放到选择画布
            //    if (_selectionCanvas != null)
            //    {
            //        ScaleTransform canvasScaleTransform = new ScaleTransform(_imageZoomFactor, _imageZoomFactor);
            //        _selectionCanvas.RenderTransform = canvasScaleTransform;
            //    }
            //}
        }

        private void Editor_TextChanged(object sender, EventArgs e)
        {
            _textChanged = true;
            UpdateTitle();
        }

        private void Editor_CursorPositionChanged(object sender, CursorPositionChangedEventArgs e)
        {
            CursorPositionText.Text = $"行: {e.Line + 1}, 列: {e.Column + 1}";
        }

        private void UpdateTitle()
        {
            string fileName = _currentFilePath != null ? Path.GetFileName(_currentFilePath) : "无标题";
            Title = $"{fileName}{(_textChanged ? "*" : "")} - WPF Text Editor";
        }

        private void OnNewFile_Click(object sender, RoutedEventArgs e)
        {
            if (_textChanged)
            {
                var result = MessageBox.Show("当前文件已修改,是否保存?", "保存确认", MessageBoxButton.YesNoCancel);
                if (result == MessageBoxResult.Cancel)
                    return;
                if (result == MessageBoxResult.Yes)
                    SaveFile();
            }

            Editor.Text = string.Empty;
            _currentFilePath = null;
            _textChanged = false;
            UpdateTitle();
            StatusText.Text = "新建文件";
        }

        // 图片列表选择变化事件
        private async void ImageListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ImageListBox.SelectedItem is ImageFileInfo selectedImage)
            {
                string pthimg = selectedImage.FullPath;

                var (jsn, m5, pth_img, pth_json) = await Global.img_md5_jsn(pthimg, _ocrMode);


                // 加载原图
                string b64_str = File.ReadAllText(pth_img, Encoding.UTF8);
                byte[] img_bytes = Base64.Base64Decode(b64_str);
                Mat im_orig = Cv2.ImDecode(img_bytes, ImreadModes.Color);
                BitmapSource source = TextEditorControl.MatToBitmapSource(im_orig);
                ViewModel.Image = source;
                ViewModel.ClearAllRectangles();


                // 重置图片尺寸记录
                _previousImageWidth = 0;
                _previousImageHeight = 0;


                Editor._pthimg = pthimg;
                Editor._jsn_OpenImg = jsn;
                Editor._md5_OpenImg = m5;

                _currentFilePath = pthimg;
                if (this._mode == EditorMode.ImageOCR)
                {
                    try
                    {

                        Editor.SetText(jsn, m5);


                        _textChanged = false;
                        UpdateTitle();
                        StatusText.Text = $"已打开: {_currentFilePath}";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"打开文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else if (this._mode == EditorMode.ReviseEdit)
                {
                    // 整理校对模式要手动框选才出字

                    try
                    {

                        Editor._lines.Clear();

                        Editor._lines = Global.loadJsonReviseEdit_FromOriginalPath(pth_json);

                        // 恢复框选
                        ViewModel.ClearAllRectangles();

                        var dic_ = new Dictionary<string, bool>();
                        foreach (var item in Editor._lines)
                        {
                            if (item.Characters.Count == 0)
                            {
                                continue;
                            }

                            JObject selected_rectange = item.selected_rectange;
                            if (selected_rectange == null || !selected_rectange.HasValues)
                            {
                                continue;
                            }
                            int Id = selected_rectange["Id"].Value<int>();
                            int lft = selected_rectange["lft"].Value<int>();
                            int tp = selected_rectange["tp"].Value<int>();
                            int wdth = selected_rectange["wdth"].Value<int>();
                            int hght = selected_rectange["hght"].Value<int>();

                            if (!dic_.ContainsKey(Id.ToString()))
                            {
                                _pendingRectangles.Add(selected_rectange);  // 等图片显示后再处理 see Image_SizeChanged
                                dic_[Id.ToString()] = true;
                            }
                        }


                        Editor._undoBuffer.Clear();
                        Editor._undoIndex = -1;
                        Editor._cursorLine = 0;
                        Editor._cursorColumn = 0;
                        Editor.ClearSelection();
                        Editor._textChanged = true;
                        Editor.InvalidateVisual();

                        // 触发文本改变事件
                        Editor.OnTextChanged();

                        UpdateTitle();
                        StatusText.Text = $"已打开: {_currentFilePath}";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"打开文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }

                }
                else if (this._mode == EditorMode.MenuSplit)
                {
                    if (m5 != "")
                    {
                        await split_menu_openImage(m5);
                    }
                }
            }
        }

        private void SelectBookButton_Click(object sender, RoutedEventArgs e)
        {
            // 创建书籍管理弹窗
            var bookManagementWindow = new Window
            {
                Title = "书籍管理",
                Width = 500,
                Height = 600,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = this,
                ResizeMode = ResizeMode.CanResize,
                MinWidth = 400,
                MinHeight = 500
            };

            // 创建主容器
            var mainPanel = new Grid
            {
                Margin = new Thickness(20)
            };

            // 定义行
            mainPanel.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); // 标题
            mainPanel.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); // 按钮区域
            mainPanel.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); // 搜索框
            mainPanel.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); // 书籍列表
            mainPanel.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); // 底部按钮

            // 添加标题
            var titleText = new TextBlock
            {
                Text = "书籍管理",
                FontSize = 16,
                FontWeight = FontWeights.Bold,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 0, 0, 20)
            };
            Grid.SetRow(titleText, 0);
            mainPanel.Children.Add(titleText);

            // 创建操作按钮容器
            var buttonPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 0, 0, 20)
            };

            // 添加书籍按钮
            var addBookButton = new Button
            {
                Content = "添加书籍",
                Width = 100,
                Height = 30,
                Margin = new Thickness(5),
                //Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0x4C, 0xAF, 0x50)),
                //Foreground = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFF, 0xFF, 0xFF)),
                BorderThickness = new Thickness(0),
                FontSize = 12
            };

            // 删除书籍按钮
            var deleteBookButton = new Button
            {
                Content = "删除书籍",
                Width = 100,
                Height = 30,
                Margin = new Thickness(5),
                //Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xF4, 0x43, 0x36)),
                //Foreground = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFF, 0xFF, 0xFF)),
                BorderThickness = new Thickness(0),
                FontSize = 12
            };

            buttonPanel.Children.Add(addBookButton);
            buttonPanel.Children.Add(deleteBookButton);
            Grid.SetRow(buttonPanel, 1);
            mainPanel.Children.Add(buttonPanel);

            // 搜索框容器
            var searchPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Margin = new Thickness(0, 0, 0, 10)
            };

            var searchLabel = new TextBlock
            {
                Text = "搜索书籍:",
                VerticalAlignment = VerticalAlignment.Center,
                Margin = new Thickness(0, 0, 10, 0),
                FontSize = 12
            };

            var searchTextBox = new TextBox
            {
                Width = 200,
                Height = 25,
                VerticalAlignment = VerticalAlignment.Center,
                FontSize = 12
            };

            var searchButton = new Button
            {
                Content = "搜索",
                Width = 60,
                Height = 25,
                Margin = new Thickness(10, 0, 0, 0),
                //Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0x21, 0x96, 0xF3)),
                //Foreground = Brushes.White,
                BorderThickness = new Thickness(0),
                FontSize = 12
            };

            searchPanel.Children.Add(searchLabel);
            searchPanel.Children.Add(searchTextBox);
            searchPanel.Children.Add(searchButton);
            Grid.SetRow(searchPanel, 2);
            mainPanel.Children.Add(searchPanel);

            // 书籍列表
            var bookListBox = new ListBox
            {
                Margin = new Thickness(0, 0, 0, 20),
                BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xCC, 0xCC, 0xCC)),
                BorderThickness = new Thickness(1)
            };

            // 模拟书籍数据
            var allBooks = new List<string>
            {
                "《红楼梦》- 曹雪芹",
                "《西游记》- 吴承恩",
                "《水浒传》- 施耐庵",
                "《三国演义》- 罗贯中"
            };

            // 初始化书籍列表
            foreach (var book in allBooks)
            {
                bookListBox.Items.Add(book);
            }

            Grid.SetRow(bookListBox, 3);
            mainPanel.Children.Add(bookListBox);

            // 搜索功能实现
            searchButton.Click += (s, args) =>
            {
                var searchText = searchTextBox.Text.Trim().ToLower();
                bookListBox.Items.Clear();
                
                if (string.IsNullOrEmpty(searchText))
                {
                    // 如果搜索框为空,显示所有书籍
                    foreach (var book in allBooks)
                    {
                        bookListBox.Items.Add(book);
                    }
                }
                else
                {
                    // 根据搜索文本过滤书籍
                    var filteredBooks = allBooks.Where(book => 
                        book.ToLower().Contains(searchText)).ToList();
                    
                    foreach (var book in filteredBooks)
                    {
                        bookListBox.Items.Add(book);
                    }
                    
                    if (filteredBooks.Count == 0)
                    {
                        bookListBox.Items.Add("未找到匹配的书籍");
                    }
                }
            };

            // 支持回车键搜索
            searchTextBox.KeyDown += (s, args) =>
            {
                if (args.Key == Key.Enter)
                {
                    searchButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                }
            };

            // 底部按钮容器
            var bottomPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center
            };

            // 选择书籍按钮
            var selectBookButton = new Button
            {
                Content = "选择此书籍",
                Width = 100,
                Height = 35,
                Margin = new Thickness(5),
                Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFF, 0x98, 0x00)),
                BorderThickness = new Thickness(0),
                FontSize = 12
            };

            // 关闭按钮
            var closeButton = new Button
            {
                Content = "关闭",
                Width = 100,
                Height = 35,
                Margin = new Thickness(5),
                Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0x95, 0x95, 0x95)),
                BorderThickness = new Thickness(0),
                FontSize = 12
            };

            bottomPanel.Children.Add(selectBookButton);
            bottomPanel.Children.Add(closeButton);
            Grid.SetRow(bottomPanel, 4);
            mainPanel.Children.Add(bottomPanel);

            // 事件处理
            addBookButton.Click += (s, args) =>
            {
                var inputDialog = new Window
                {
                    Title = "添加书籍",
                    Width = 300,
                    Height = 180, // 增加高度以确保按钮显示
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    Owner = bookManagementWindow,
                    ResizeMode = ResizeMode.NoResize
                };

                var inputPanel = new StackPanel { Margin = new Thickness(20) };
                var inputLabel = new TextBlock { Text = "请输入书籍名称:", Margin = new Thickness(0, 0, 0, 10) };
                var inputTextBox = new TextBox { Height = 25, Margin = new Thickness(0, 0, 0, 15) };
                var inputButtonPanel = new StackPanel { 
                    Orientation = Orientation.Horizontal, 
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Margin = new Thickness(0, 10, 0, 0) // 添加上边距
                };
                
                var confirmButton = new Button { 
                    Content = "确定", 
                    Width = 60, 
                    Height = 25, 
                    Margin = new Thickness(5),
                    Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0x4C, 0xAF, 0x50)),
                    //Foreground = Brushes.White,
                    BorderThickness = new Thickness(0)
                };
                var cancelButton = new Button { 
                    Content = "取消", 
                    Width = 60, 
                    Height = 25, 
                    Margin = new Thickness(5),
                    Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0x95, 0x95, 0x95)),
                    //Foreground = Brushes.White,
                    BorderThickness = new Thickness(0)
                };

                confirmButton.Click += (ss, ee) =>
                {
                    var newBook = inputTextBox.Text.Trim();
                    if (!string.IsNullOrEmpty(newBook))
                    {
                        allBooks.Add(newBook);
                        bookListBox.Items.Add(newBook);
                        inputDialog.Close();
                    }
                    else
                    {
                        MessageBox.Show("请输入书籍名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                };
                cancelButton.Click += (ss, ee) => inputDialog.Close();

                inputButtonPanel.Children.Add(confirmButton);
                inputButtonPanel.Children.Add(cancelButton);
                inputPanel.Children.Add(inputLabel);
                inputPanel.Children.Add(inputTextBox);
                inputPanel.Children.Add(inputButtonPanel);
                inputDialog.Content = inputPanel;
                inputDialog.ShowDialog();
            };

            deleteBookButton.Click += (s, args) =>
            {
                if (bookListBox.SelectedItem != null)
                {
                    var selectedBook = bookListBox.SelectedItem.ToString();
                    if (MessageBox.Show($"确认删除书籍 { selectedBook} ?", "确认删除",
                        MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        allBooks.Remove(selectedBook);
                        bookListBox.Items.Remove(selectedBook);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择要删除的书籍", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            };

            selectBookButton.Click += (s, args) =>
            {
                if (bookListBox.SelectedItem != null)
                {
                    var selectedBook = bookListBox.SelectedItem.ToString();
                    MessageBox.Show($"已选择书籍:{selectedBook}", "选择成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    bookManagementWindow.Close();
                    // 这里可以添加将选中书籍应用到主界面的逻辑
                }
                else
                {
                    MessageBox.Show("请先选择一本书籍", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            };

            closeButton.Click += (s, args) => bookManagementWindow.Close();

            bookManagementWindow.Content = mainPanel;
            bookManagementWindow.ShowDialog();
        }


        // 切换图片列表显示/隐藏
        private void ToggleImageListButton_Click(object sender, RoutedEventArgs e)
        {
            _isImageListVisible = !_isImageListVisible;
            
            if (_isImageListVisible)
            {
                // 显示图片列表
                ImageListBox.Visibility = Visibility.Visible;
                ImageListTitle.Visibility = Visibility.Visible;
                ToggleImageListButton.Content = "▼";
                ToggleImageListButton.ToolTip = "隐藏图片列表";
                
                // 恢复列宽
                MainContentGrid.ColumnDefinitions[0].Width = new GridLength(200, GridUnitType.Pixel);
                MainContentGrid.ColumnDefinitions[0].MinWidth = 150;
                
                // 恢复边框
                ImageListBorder.BorderThickness = new Thickness(0, 0, 1, 0);
                ImageListBorder.Padding = new Thickness(0);
            }
            else
            {
                // 隐藏图片列表内容
                ImageListBox.Visibility = Visibility.Collapsed;
                ImageListTitle.Visibility = Visibility.Collapsed;
                ToggleImageListButton.Content = "▶";
                ToggleImageListButton.ToolTip = "显示图片列表";
                
                // 设置列宽为按钮宽度
                MainContentGrid.ColumnDefinitions[0].Width = new GridLength(30, GridUnitType.Pixel);
                MainContentGrid.ColumnDefinitions[0].MinWidth = 30;
                
                // 调整边框和内边距,让按钮居中
                ImageListBorder.BorderThickness = new Thickness(0, 0, 1, 0);
                ImageListBorder.Padding = new Thickness(5, 10, 5, 0);
            }
        }

        public async void handle_comicocr_open_img(string img_pth)
        {
            var (jsn, m5, pth_img, pth_json) = await Global.img_md5_jsn(img_pth, _ocrMode);

            ImageListBox.Items.Add(new ImageFileInfo(img_pth));

            // 加载原图
            string b64_str = File.ReadAllText(pth_img, Encoding.UTF8);
            byte[] img_bytes = Base64.Base64Decode(b64_str);
            Mat im_orig = Cv2.ImDecode(img_bytes, ImreadModes.Color);
            BitmapSource source = TextEditorControl.MatToBitmapSource(im_orig);
            ViewModel.Image = source;
            ViewModel.ClearAllRectangles();


            // 重置图片尺寸记录
            _previousImageWidth = 0;
            _previousImageHeight = 0;


            Editor._pthimg = img_pth;
            Editor._jsn_OpenImg = jsn;
            Editor._md5_OpenImg = m5;

            _currentFilePath = img_pth;

            try
            {

                Editor.SetText(jsn, m5);

                _textChanged = false;
                UpdateTitle();
                StatusText.Text = $"已打开: {_currentFilePath}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void OnOpenFile_Click(object sender, RoutedEventArgs e)
        {
            if (_textChanged)
            {
                var result = MessageBox.Show("当前文件已修改,是否保存?", "保存确认", MessageBoxButton.YesNoCancel);
                if (result == MessageBoxResult.Cancel)
                    return;
                if (result == MessageBoxResult.Yes)
                    _textChanged = false;
                    SaveFile();
            }

            OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.Filter = "图片文件 (*.jpg;*.jpeg;*.png;*.bmp)|*.jpg;*.jpeg;*.png;*.bmp|文本文件 (*.txt)|*.txt|C++ 文件 (*.cpp;*.h)|*.cpp;*.h|所有文件 (*.*)|*.*";
            openFileDialog.Filter = "图片文件 (*.jpg;*.jpeg;*.png;*.bmp)|*.jpg;*.jpeg;*.png;*.bmp|PDF文件 (*.pdf)|(*.pdf)|所有文件 (*.*)|*.*";// |文本文件 (*.txt)|*.txt|C++ 文件 (*.cpp;*.h)|*.cpp;*.h|所有文件 (*.*)|*.*
            openFileDialog.Multiselect = true;

            if (openFileDialog.ShowDialog() == true)
            {
                if ( openFileDialog.FileName.Contains(".txt") )
                {
                    try
                    {
                        //Editor.Text = File.ReadAllText(openFileDialog.FileName);
                        Editor.SetText(File.ReadAllText(openFileDialog.FileName));
                        _currentFilePath = openFileDialog.FileName;
                        _textChanged = false;
                        UpdateTitle();
                        StatusText.Text = $"已打开: {_currentFilePath}";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"打开文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else if (openFileDialog.FileName.Contains(".pdf"))
                {
                    // pdf 先拆成图片
                    // see huggingface\pdf_ocr\main.py

                    /*

                    

                    conda create -n pdfocr python==3.10 pip



                    */

                    string pth_pdf = openFileDialog.FileName;
                    
                    // 获取PDF文件所在目录
                    string pdfDirectory = Path.GetDirectoryName(pth_pdf);
                    
                    // 查找同目录下的所有JPG图片文件
                    var jpgFiles = Directory.GetFiles(pdfDirectory, "*.jpg", SearchOption.TopDirectoryOnly)
                        .Concat(Directory.GetFiles(pdfDirectory, "*.jpeg", SearchOption.TopDirectoryOnly))
                        .OrderBy(f => f)
                        .ToList();
                    
                    // 清空现有的图片列表
                    ImageListBox.Items.Clear();
                    
                    // 将JPG图片添加到列表中
                    foreach (string jpgFile in jpgFiles)
                    {
                        ImageListBox.Items.Add(new ImageFileInfo(jpgFile));
                    }
                    
                    // 更新状态栏
                    StatusText.Text = $"已加载PDF文件及同目录下的 {jpgFiles.Count} 个JPG图片";
                    
                    // 设置当前文件路径
                    _currentFilePath = pth_pdf;
                    UpdateTitle();
                }
                else
                {
                    var (jsn, m5, pth_img, pth_json) = await Global.img_md5_jsn(openFileDialog.FileName, _ocrMode);

                    //opened_image_pths.Clear();
                    //opened_image_pths.AddRange(openFileDialog.FileNames);

                    // 清空现有的图片列表
                    //ImageListBox.Items.Clear();

                    // 将选择的图片文件添加到图片列表中
                    foreach (string imagePath in openFileDialog.FileNames)
                    {
                        bool exist = false;
                        foreach(ImageFileInfo item in ImageListBox.Items )
                        {
                            if (item.FullPath == imagePath)
                            {
                                exist = true;
                                break;
                            }
                        }
                        if (!exist)
                        {
                            ImageListBox.Items.Add(new ImageFileInfo(imagePath));
                        }
                    }

                    // 加载原图
                    string b64_str = File.ReadAllText(pth_img, Encoding.UTF8);
                    byte[] img_bytes = Base64.Base64Decode(b64_str);
                    Mat im_orig = Cv2.ImDecode(img_bytes, ImreadModes.Color);
                    BitmapSource source = TextEditorControl.MatToBitmapSource(im_orig);
                    ViewModel.Image = source;
                    ViewModel.ClearAllRectangles();


                    // 重置图片尺寸记录
                    _previousImageWidth = 0;
                    _previousImageHeight = 0;


                    Editor._pthimg = openFileDialog.FileName;
                    Editor._jsn_OpenImg = jsn;
                    Editor._md5_OpenImg = m5;

                    _currentFilePath = openFileDialog.FileName;
                    if (this._mode == EditorMode.ImageOCR)
                    {
                        try
                        {

                            Editor.SetText(jsn, m5);


                            _textChanged = false;
                            UpdateTitle();
                            StatusText.Text = $"已打开: {_currentFilePath}";
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"打开文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    else if (this._mode == EditorMode.ReviseEdit)
                    {
                        // 整理校对模式要手动框选才出字

                        try
                        {
                            //string b64_str = File.ReadAllText(pth_img, Encoding.UTF8);
                            //byte[] img_bytes = Base64.Base64Decode(b64_str);

                            //Mat im_orig = Cv2.ImDecode(img_bytes, ImreadModes.Color);

                            //BitmapSource source = TextEditorControl.MatToBitmapSource(im_orig);

                            //this.ShowImageInPanel(source);


                            //Editor.SetText(jsn, m5);


                            Editor._lines.Clear();

                            Editor._lines = Global.loadJsonReviseEdit_FromOriginalPath(pth_json);

                            // 恢复框选
                            ViewModel.ClearAllRectangles();
                            //ViewModel.AddRectangle(int Id, double left, double top, double width, double height)

                            var dic_ = new Dictionary<string, bool>();
                            foreach (var item in Editor._lines)
                            {
                                if (item.Characters.Count == 0)
                                {
                                    continue;
                                }

                                JObject selected_rectange = item.selected_rectange;
                                if (selected_rectange == null || !selected_rectange.HasValues)
                                {
                                    continue;
                                }
                                int Id = selected_rectange["Id"].Value<int>();
                                int lft = selected_rectange["lft"].Value<int>();
                                int tp = selected_rectange["tp"].Value<int>();
                                int wdth = selected_rectange["wdth"].Value<int>();
                                int hght = selected_rectange["hght"].Value<int>();

                                if (!dic_.ContainsKey(Id.ToString()))
                                {
                                    _pendingRectangles.Add(selected_rectange);  // 等图片显示后再处理 see Image_SizeChanged
                                    dic_[Id.ToString()] = true;
                                }




                                //var displayPos = Editor.ConvertOriginalToDisplayCoordinates(lft, tp);
                                //var displaySize = Editor.ConvertOriginalToDisplaySize(wdth, hght);

                                //ViewModel.AddRectangle(Id, displayPos.X, displayPos.Y, displaySize.Width, displaySize.Height);

                            }


                            Editor._undoBuffer.Clear();
                            Editor._undoIndex = -1;
                            Editor._cursorLine = 0;
                            Editor._cursorColumn = 0;
                            Editor.ClearSelection();
                            Editor._textChanged = true;
                            Editor.InvalidateVisual();

                            // 触发文本改变事件
                            Editor.OnTextChanged();

                            UpdateTitle();
                            StatusText.Text = $"已打开: {_currentFilePath}";
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"打开文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }

                    } else if (this._mode == EditorMode.MenuSplit) {

                        Editor._lines.Clear();

                        Editor._lines = Global.loadJsonReviseEdit_FromOriginalPath(pth_json);

                        string dir = Path.GetDirectoryName(_currentFilePath);

                        var jpgs = Directory.EnumerateFiles(dir, "*.jpg", SearchOption.TopDirectoryOnly)
                            .Where(file => System.Text.RegularExpressions.Regex.IsMatch(Path.GetFileNameWithoutExtension(file), @"^\d+$"))
                            .OrderBy(f => f)
                            .ToList();


                        List<TextLine> ls = new List<TextLine>(); 
                        foreach (var pth in jpgs)
                        {
                            var (jsn_, m5_, pth_img_, pth_json_) = await Global.img_md5_jsn(pth, _ocrMode, false);

                            if (Path.Exists(pth_json_))
                            {
                                if (!_dic_m5_imgname.ContainsKey(m5_))
                                {
                                    _dic_m5_imgname[m5_] = pth;
                                }

                                List<TextLine> lines = Global.loadJsonReviseEdit_FromOriginalPath(pth_json_);
                                if (lines.Count > 0)
                                {
                                    ls.AddRange(lines);
                                }
                            }
                        }


                        InitializeDirectoryTreeData(ls);

                        Editor._undoBuffer.Clear();
                        Editor._undoIndex = -1;
                        Editor._cursorLine = 0;
                        Editor._cursorColumn = 0;
                        Editor.ClearSelection();
                        Editor._textChanged = true;
                        Editor.InvalidateVisual();

                        // 触发文本改变事件
                        Editor.OnTextChanged();

                        UpdateTitle();
                        StatusText.Text = $"已打开: {_currentFilePath}";
                    }
                }
            }
        }

        private void export_mdx(List<DirectoryTreeNode> ls, string parent_guid, List<Dictionary<string, string>> ls_info)
        {
            if (ls == null || ls.Count <= 0)
            {
                return;
            }

            foreach (DirectoryTreeNode tnode in ls)
            {
                string Name = tnode.Name;
                int level = tnode.level;
                List<DirectoryTreeNode> Children = tnode.Children;
                TextLine line = tnode.line;

                Dictionary<string, string> info = new Dictionary<string, string>();

                foreach (TextCharacter textcharacter in line.Characters)
                {
                    string ImageMD5 = textcharacter.ImageMD5;
                    if ( !_dic_m5_imgname.ContainsKey(ImageMD5) )
                    {
                        continue;
                    }

                    string pth = _dic_m5_imgname[ImageMD5];
                    string baseName = Path.GetFileNameWithoutExtension(pth);
                    string ext = Path.GetExtension(pth);
                    string dir = Path.GetDirectoryName(pth);

                    info["Guid"] = Guid.NewGuid().ToString();
                    info["parent_guid"] = parent_guid;
                    info["Name"] = Name;
                    info["level"] = level.ToString();
                    info["ImagebaseName"] = baseName;
                    info["ImageName"] = $"{baseName}{ext}";
                    info["ImageFullPath"] = pth;
                    

                    ls_info.Add(info);

                    break;

                }

                if (info.Count <= 0)
                {
                    throw new Exception("Error: something wrong.");
                }

                
                //Dictionary<string, string> clone = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(info, Formatting.Indented)).ToDictionary();

                //info["parent_info"] = JsonConvert.SerializeObject(parent_info, Formatting.Indented);
                    // 防止无限套娃

                export_mdx(Children, info["Guid"], ls_info);

            }

        }

        private void OnExportMDX_Click(object sender, RoutedEventArgs e)
        {
            // see huggingface/MDX/README.md
            // mdict -a "Times单挑1000.mdx.txt" "Times单挑1000.mdx"
            // mdict -a mdd "Times单挑1000.mdd"

            if (Editor._mode != EditorMode.MenuSplit)
            {
                return;
            }

            List<Dictionary<string, string>> ls_info = new List<Dictionary<string, string>>();

            var rootNodes = (List<DirectoryTreeNode>)DirectoryTreeView.ItemsSource;

            export_mdx(rootNodes, "", ls_info);

            string prefix_Name = "TIMESDT1K";

            string dest = "E:\\";
            string mdx_dir_name = "Times单挑1000";
            string mdx_dir = Path.Join(dest, mdx_dir_name);
            string mdx_pth = Path.Join(mdx_dir, $"{mdx_dir_name}.mdx.txt");
            string mdd_dir = Path.Join(dest, mdx_dir_name, "mdd");

            if (Directory.Exists(mdd_dir))
            {
                Directory.Delete(mdd_dir, true);
            }

            if (!Directory.Exists(mdd_dir))  // 目录不存在,创建
            {
                DirectoryInfo di = Directory.CreateDirectory(mdd_dir);
                if (!Directory.Exists(mdd_dir))
                {
                    throw new Exception($"创健目录失败:{mdd_dir}");
                }
            }

            string last_ImageBaseName_new = "";
            string last_ImageName_new = "";

            List<string> mdx_items_pic = new List<string>();
            List<string> mdx_items_word = new List<string>();
            Dictionary<string, bool> dic_key = new Dictionary<string, bool>();

            Dictionary<string, Dictionary<string, string>> dic_guid_info = new Dictionary<string, Dictionary<string, string>>();

            for (int i = 0; i < ls_info.Count; i++)
            {
                var info = ls_info[i];

                string Guid = info["Guid"];
                string parent_guid = info["parent_guid"];

                string Name = info["Name"];
                string level = info["level"];
                string ImagebaseName = info["ImagebaseName"];
                int Page = int.Parse(info["ImagebaseName"]);
                string ImageName = info["ImageName"];
                string ImageFullPath = info["ImageFullPath"];

                string next_ImageBaseName_new = "";
                

                string ImageBaseName_new = $"{prefix_Name}{ImagebaseName}";
                string ImageName_new = $"{prefix_Name}{ImageName}";

                next_ImageBaseName_new = ImageBaseName_new;

                for (int j = i + 1; j < ls_info.Count; j++)
                {
                    int p = int.Parse(ls_info[j]["ImagebaseName"]);
                    if (p > Page)
                    {
                        next_ImageBaseName_new = $"{prefix_Name}{ls_info[j]["ImagebaseName"]}";
                        break;
                    }
                }


                if (last_ImageBaseName_new == "")
                {
                    last_ImageBaseName_new = ImageBaseName_new;
                }

                if (last_ImageName_new == "")
                {
                    last_ImageName_new = ImageName_new;
                }

                info["ImageBaseName_new"] = ImageBaseName_new;
                info["ImageName_new"] = ImageName_new;
                info["last_ImageBaseName_new"] = last_ImageBaseName_new;
                info["next_ImageBaseName_new"] = next_ImageBaseName_new;


                if ( !dic_guid_info.ContainsKey(Guid) )
                {
                    dic_guid_info[Guid] = info;
                }


                List<Dictionary<string, string>> parent_all = new List<Dictionary<string, string>>();
                while(parent_guid != "")
                {
                    if (!dic_guid_info.ContainsKey(parent_guid))
                    {
                        throw new Exception("Error: something wrong.");
                    }

                    var parent_info = dic_guid_info[parent_guid];
                    parent_guid = parent_info["parent_guid"];
                    
                    parent_all.Add(parent_info);

                }

                List<string> nav_ls = new List<string>();

                string nav_string = "";  // 头部导航条

                nav_ls.Insert(0, $"<a href=\"entry://{ImageBaseName_new}\">{Name}</a>");

                foreach (var item in parent_all)
                {
                    string parent_Name = item["Name"];
                    string parent_ImageBaseName_new = item["ImageBaseName_new"];
                    string parent_nav_string = $"<a href=\"entry://{parent_ImageBaseName_new}\">{parent_Name}</a>";
                    nav_ls.Insert(0, parent_nav_string);
                }

                nav_string = $"<center>{string.Join(" > ", nav_ls)}</center><br>";

                if (!dic_key.ContainsKey(ImageBaseName_new))
                {
                    dic_key[ImageBaseName_new] = true;

                    string mdx_item = $"{ImageBaseName_new}\n{nav_string}<img src=\"{ImageName_new}\" width=\"100%\"><br><center> <a href=\"entry://{last_ImageBaseName_new}\">上一页</a> &nbsp;&nbsp;<a href=\"entry://{next_ImageBaseName_new}\">下一页</a> <br><br></center>\n</>";
                    mdx_items_pic.Add(mdx_item);

                    string dst_img = Path.Join(mdd_dir, ImageName_new);

                    File.Copy(ImageFullPath, dst_img, true);

                }

                if (level == "999")
                {
                    string mdx_item = $"{Name}\n{nav_string}<img src=\"{ImageName_new}\" width=\"100%\"><br><center> <a href=\"entry://{last_ImageBaseName_new}\">上一页</a> &nbsp;&nbsp;<a href=\"entry://{next_ImageBaseName_new}\">下一页</a> <br><br></center>\n</>";
                    mdx_items_word.Add(mdx_item);
                }


                last_ImageBaseName_new = ImageBaseName_new;
                last_ImageName_new = ImageName_new;
            }

            mdx_items_pic.AddRange(mdx_items_word);

            string mdx_string = string.Join("\n", mdx_items_pic);

            File.WriteAllText(mdx_pth, mdx_string, new UTF8Encoding(false));

        }
        private void InitializeDirectoryTreeData(List<TextLine> lines)
        {
            if (lines.Count <= 0) return;

            List<Tuple<int, string, TextLine>> ls = new List<Tuple<int, string, TextLine>>();

            List<DirectoryTreeNode> tree_ls = new List<DirectoryTreeNode>();

            foreach (var line in lines) 
            {
                List<string> leading = new List<string>();
                bool appear = false;
                bool appear2 = false;

                foreach (TextCharacter textcharacter in line.Characters)
                {
                    System.Text.Rune character = textcharacter.Character;

                    if (character.Value == '#')
                    {
                        if (!appear)
                        {
                            appear = true;
                        }

                        leading.Add("#");

                    } else if (character.Value == '*')
                    {
                        if (!appear2)
                        {
                            appear2 = true;
                        }
                    }
                    else
                    {
                        if (appear)
                        {
                            break;
                        }

                        if (character.Value != ' ')
                        {
                            break;
                        }
                    }
                }
                
                if (appear)
                {
                    int level = leading.Count;
                    string lineText = string.Concat(line.Characters.Select(tc => tc.Character.ToString()));
                    Tuple<int, string, TextLine> node = new Tuple<int, string, TextLine>(level, lineText, line);
                    ls.Add(node);

                    string Name = lineText.Replace("#", "").Trim();

                    DirectoryTreeNode tnode = new DirectoryTreeNode(Name, level, line);
                    tree_ls.Add(tnode);
                } else if (appear2)
                {
                    int level = 999;
                    string lineText = string.Concat(line.Characters.Select(tc => tc.Character.ToString()));
                    Tuple<int, string, TextLine> node = new Tuple<int, string, TextLine>(level, lineText, line);
                    ls.Add(node);

                    string[] Names = lineText.Replace("*", "").Trim().Split(' ');
                    string Name = "";
                    if (Names.Length > 0)
                    {
                        Name = Names[0];
                    } else
                    {
                        Name = lineText.Replace("*", "").Trim();
                    }

                    DirectoryTreeNode tnode = new DirectoryTreeNode(Name, level, line);
                    tree_ls.Add(tnode);
                }

            }


            for (int i = 0; i < tree_ls.Count; i++)
            {

                DirectoryTreeNode cur = tree_ls[i];

                for (int j = i - 1; j >= 0; j--)
                {
                    DirectoryTreeNode pre = tree_ls[j];

                    if (pre.level < cur.level)
                    {
                        pre.Children.Add(cur);
                        pre.IsDirectory = true;
                        pre.Icon = "📁";
                        break;
                    }
                }
            }


            var rootNodes = new List<DirectoryTreeNode>();

            foreach(var node in tree_ls)
            {
                if (node.level == 1)
                {
                    rootNodes.Add(node);
                }
            }

            // 设置TreeView的数据源
            DirectoryTreeView.ItemsSource = rootNodes;
        }


        private void OnSaveFile_Click(object sender, RoutedEventArgs e)
        {
            SaveFile();
        }

        private void OnSaveAsFile_Click(object sender, RoutedEventArgs e)
        {
            SaveFileAs();
        }

        private void OnExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void ToggleLineNumbers_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            Editor.LineNumbersVisible = menuItem.IsChecked;
        }

        private void ToggleWhitespaces_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            Editor.ShowWhitespaces = menuItem.IsChecked;
        }

        private void ToggleHighlightCurrentLine_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            Editor.HighlightCurrentLine = menuItem.IsChecked;
        }

        private void OnRecognitionMethod_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem clickedItem && clickedItem.Parent is MenuItem parentMenu)
            {
                // 取消同级所有菜单项的选中状态
                foreach (MenuItem item in parentMenu.Items)
                {
                    if (item.IsCheckable)
                    {
                        item.IsChecked = false;
                    }
                }
                
                // 设置当前点击的项为选中状态
                clickedItem.IsChecked = true;
                
                // 获取选中的识别方法
                string method = clickedItem.Tag?.ToString();
                
                // 处理识别方法切换逻辑
                HandleRecognitionMethodChange(method);
            }
        }


        private void HandleRecognitionMethodChange(string method)
        {
            switch (method)
            {
                case "wechat":
                    // 切换到微信OCR
                    StatusText.Text = "当前识别方法:微信OCR";
                    _ocrMode = OcrMode.WeChatOcr;
                    break;
                case "comicocr":
                    // 切换到微信OCR
                    StatusText.Text = "当前识别方法:ComicOcr";
                    _ocrMode = OcrMode.ComicOcr;
                    break;
                case "ppocr":
                    // 切换到PaddleOCR
                    StatusText.Text = "当前识别方法:PaddleOCR";
                    _ocrMode = OcrMode.PPOCR;
                    break;
                case "aliocr":
                    // 切换到阿里OCR
                    StatusText.Text = "当前识别方法:阿里OCR";
                    _ocrMode = OcrMode.AliOCR;
                    break;
            }
        }

        private bool SaveFile()
        {
            if (_currentFilePath == null)
            {
                //return SaveFileAs();
            }

            if (_currentFilePath != null)
            {
               return Editor.saveJson(_currentFilePath);
            }

            //try
            //{
            //    File.WriteAllText(_currentFilePath, Editor.Text);
            //    _textChanged = false;
            //    UpdateTitle();
            //    StatusText.Text = $"已保存: {_currentFilePath}";
            //    return true;
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show($"保存文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            //    return false;
            //}

            return false;
        }

        private bool SaveFileAs()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|C++ 文件 (*.cpp;*.h)|*.cpp;*.h|所有文件 (*.*)|*.*";
            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    File.WriteAllText(saveFileDialog.FileName, Editor.Text);
                    _currentFilePath = saveFileDialog.FileName;
                    _textChanged = false;
                    UpdateTitle();
                    StatusText.Text = $"已保存: {_currentFilePath}";
                    return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"保存文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            return false;
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (_textChanged)
            {
                if (_mode == EditorMode.ImageOCR || _mode == EditorMode.ReviseEdit)
                {
                    var result = MessageBox.Show("当前文件已修改,是否保存?", "保存确认", MessageBoxButton.YesNoCancel);
                    if (result == MessageBoxResult.Cancel)
                    {
                        e.Cancel = true;
                        return;
                    }
                    if (result == MessageBoxResult.Yes)
                        SaveFile();
                }
            }

            base.OnClosing(e);
        }

        // 添加一个公共方法,用于在右侧面板显示图片
        public void ShowImageInPanel(BitmapSource image)
        {
            //if (image != null)
            //{
            //    ImageViewer.Source = image;
            //    // 重置缩放因子
            //    //_imageZoomFactor = 1.0;
            //    ApplyImageZoom();
            //    // 确保图片容器可见
            //    ImageContainer.Visibility = Visibility.Visible;
            //}
        }
        
        // 工具栏按钮事件处理方法
        private void CopyButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void PasteButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void InsertSymbolButton_Click(object sender, RoutedEventArgs e)
        {
            // 创建符号选择窗口
            var symbolWindow = new Window
            {
                Title = "插入符号",
                Width = 400,
                Height = 300,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = this,
                ResizeMode = ResizeMode.NoResize
            };

            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

            // 常用符号列表
            var symbols = new string[]
            {
                "□", "▢", "■", "◻", "◼", "○", "●", "△", 
                "▲", "▽", "▼", "◇", "◆", "★", "☆",
                "→", "←", "↑", "↓", "↔", "⇒", "⇐", "⇔",
                "α", "β", "γ", "δ", "ε", "θ", "λ", "μ", "π", "σ", "φ", "ω",
                "Α", "Β", "Γ", "Δ", "Θ", "Λ", "Π", "Σ", "Φ", "Ω",
                "∞", "∑", "∏", "∫", "∂", "∇", "√", "∛", "∜",
                "≤", "≥", "≠", "≈", "≡", "∈", "∉", "⊂", "⊃", "∪", "∩",
                "°", "±", "×", "÷", "¼", "½", "¾", "²", "³", "⁴"
            };

            var listBox = new ListBox
            {
                ItemsSource = symbols,
                FontSize = 16,
                Margin = new Thickness(10)
            };

            var buttonPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Right,
                Margin = new Thickness(10)
            };

            var insertButton = new Button
            {
                Content = "插入",
                Width = 60,
                Height = 25,
                Margin = new Thickness(5, 0, 0, 0)
            };

            var cancelButton = new Button
            {
                Content = "取消",
                Width = 60,
                Height = 25
            };

            insertButton.Click += (s, args) =>
            {
                if (listBox.SelectedItem != null)
                {
                    string selectedSymbol = listBox.SelectedItem.ToString();
                    //Editor.InsertText(selectedSymbol);
                    StatusText.Text = $"已插入符号: {selectedSymbol}";
                    _textChanged = true;
                    UpdateTitle();
                    symbolWindow.Close();
                }
            };

            cancelButton.Click += (s, args) => symbolWindow.Close();

            listBox.MouseDoubleClick += (s, args) =>
            {
                if (listBox.SelectedItem != null)
                {
                    string selectedSymbol = listBox.SelectedItem.ToString();
                    //Editor.InsertText(selectedSymbol);

                    Editor.InsertTextCharacters(selectedSymbol);

                    // 标记文本已更改
                    _textChanged = true;

                    // 触发文本改变事件
                    Editor.OnTextChanged();


                    // 触发光标位置改变事件
                    Editor.OnCursorPositionChanged(Editor._cursorLine, Editor._cursorColumn);

                    // 重绘编辑器
                    InvalidateVisual();

                    e.Handled = true;

                    StatusText.Text = $"已插入符号: {selectedSymbol}";
                    _textChanged = true;
                    UpdateTitle();
                    symbolWindow.Close();
                }
            };

            buttonPanel.Children.Add(cancelButton);
            buttonPanel.Children.Add(insertButton);

            Grid.SetRow(listBox, 0);
            Grid.SetRow(buttonPanel, 1);
            grid.Children.Add(listBox);
            grid.Children.Add(buttonPanel);

            symbolWindow.Content = grid;
            symbolWindow.ShowDialog();
        }

        // 初始化选择画布
        private void InitializeSelectionCanvas()
        {
            _selectionCanvas = new Canvas()
            {
                Background = System.Windows.Media.Brushes.Transparent,
                IsHitTestVisible = false
            };
            
            // 将画布添加到ImageContainer中
            if (ImageContainer.Child is ScrollViewer scrollViewer)
            {
                var grid = new Grid();
                
                // 先获取原有内容并从ScrollViewer中移除
                var originalContent = scrollViewer.Content as UIElement;
                if (originalContent != null)
                {
                    scrollViewer.Content = null; // 先移除原有内容
                    grid.Children.Add(originalContent); // 再添加到新Grid中
                }
                
                grid.Children.Add(_selectionCanvas);
                scrollViewer.Content = grid;
            }
        }

        // 鼠标按下事件
        private void ImageViewer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //if (_mode == EditorMode.ReviseEdit && ImageViewer.Source != null)
            //{
            //    Point clickPoint = e.GetPosition(ImageViewer);
                
            //    // 首先检查是否点击在现有矩形的边框上(用于调整大小)
            //    foreach (Rectangle rect in _selectionRectangles)
            //    {
            //        string direction = GetResizeDirection(clickPoint, rect);
            //        if (!string.IsNullOrEmpty(direction))
            //        {
            //            _isResizing = true;
            //            _resizingRectangle = rect;
            //            _resizeDirection = direction;
            //            _resizeStartPoint = clickPoint;
                        
            //            // 保存原始尺寸和位置
            //            _originalLeft = Canvas.GetLeft(rect);
            //            _originalTop = Canvas.GetTop(rect);
            //            _originalWidth = rect.Width;
            //            _originalHeight = rect.Height;
                        
            //            ImageViewer.CaptureMouse();
            //            return;
            //        }
            //    }
                
            //    // 如果没有点击在边框上,则开始新的选择
            //    _isSelecting = true;
            //    _selectionStartPoint = clickPoint;
            //    ImageViewer.CaptureMouse();
        
            //    // 创建选择矩形
            //    _selectionRectangle = new Rectangle()
            //    {
            //        Stroke = Brushes.Red,
            //        StrokeThickness = 2,
            //        Fill = Brushes.Transparent
            //    };
        
            //    Canvas.SetLeft(_selectionRectangle, _selectionStartPoint.X);
            //    Canvas.SetTop(_selectionRectangle, _selectionStartPoint.Y);
            //    _selectionCanvas.Children.Add(_selectionRectangle);
            //}
        
        }

        // 鼠标移动事件
        private void ImageViewer_MouseMove(object sender, MouseEventArgs e)
        {
            //Point currentPoint = e.GetPosition(ImageViewer);
            
            //if (_isResizing && _resizingRectangle != null)
            //{
            //    // 调整大小逻辑
            //    double deltaX = currentPoint.X - _resizeStartPoint.X;
            //    double deltaY = currentPoint.Y - _resizeStartPoint.Y;
                
            //    double newLeft = _originalLeft;
            //    double newTop = _originalTop;
            //    double newWidth = _originalWidth;
            //    double newHeight = _originalHeight;
                
            //    switch (_resizeDirection)
            //    {
            //        case "left":
            //            newLeft = _originalLeft + deltaX;
            //            newWidth = _originalWidth - deltaX;
            //            break;
            //        case "right":
            //            newWidth = _originalWidth + deltaX;
            //            break;
            //        case "top":
            //            newTop = _originalTop + deltaY;
            //            newHeight = _originalHeight - deltaY;
            //            break;
            //        case "bottom":
            //            newHeight = _originalHeight + deltaY;
            //            break;
            //        case "topleft":
            //            newLeft = _originalLeft + deltaX;
            //            newTop = _originalTop + deltaY;
            //            newWidth = _originalWidth - deltaX;
            //            newHeight = _originalHeight - deltaY;
            //            break;
            //        case "topright":
            //            newTop = _originalTop + deltaY;
            //            newWidth = _originalWidth + deltaX;
            //            newHeight = _originalHeight - deltaY;
            //            break;
            //        case "bottomleft":
            //            newLeft = _originalLeft + deltaX;
            //            newWidth = _originalWidth - deltaX;
            //            newHeight = _originalHeight + deltaY;
            //            break;
            //        case "bottomright":
            //            newWidth = _originalWidth + deltaX;
            //            newHeight = _originalHeight + deltaY;
            //            break;
            //    }
                
            //    // 确保最小尺寸
            //    const double minSize = 10;
            //    if (newWidth >= minSize && newHeight >= minSize)
            //    {
            //        Canvas.SetLeft(_resizingRectangle, newLeft);
            //        Canvas.SetTop(_resizingRectangle, newTop);
            //        _resizingRectangle.Width = newWidth;
            //        _resizingRectangle.Height = newHeight;
            //    }
            //}
            //else if (_isSelecting && _selectionRectangle != null)
            //{
            //    // 原有的选择逻辑
            //    double left = Math.Min(_selectionStartPoint.X, currentPoint.X);
            //    double top = Math.Min(_selectionStartPoint.Y, currentPoint.Y);
            //    double width = Math.Abs(currentPoint.X - _selectionStartPoint.X);
            //    double height = Math.Abs(currentPoint.Y - _selectionStartPoint.Y);
        
            //    Canvas.SetLeft(_selectionRectangle, left);
            //    Canvas.SetTop(_selectionRectangle, top);
            //    _selectionRectangle.Width = width;
            //    _selectionRectangle.Height = height;
            //}
            //else
            //{
            //    // 更新鼠标光标样式
            //    UpdateCursor(currentPoint);
            //}
        }

        // 更新鼠标光标样式
        private void UpdateCursor(Point point)
        {
            //foreach (Rectangle rect in _selectionRectangles)
            //{
            //    string direction = GetResizeDirection(point, rect);
            //    switch (direction)
            //    {
            //        case "left":
            //        case "right":
            //            ImageViewer.Cursor = Cursors.SizeWE;
            //            return;
            //        case "top":
            //        case "bottom":
            //            ImageViewer.Cursor = Cursors.SizeNS;
            //            return;
            //        case "topleft":
            //        case "bottomright":
            //            ImageViewer.Cursor = Cursors.SizeNWSE;
            //            return;
            //        case "topright":
            //        case "bottomleft":
            //            ImageViewer.Cursor = Cursors.SizeNESW;
            //            return;
            //    }
            //}
            //ImageViewer.Cursor = Cursors.Arrow;
        }

        // 鼠标释放事件
        private void ImageViewer_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //if (_isResizing)
            //{
            //    _isResizing = false;
                
            //    // 调整大小结束后,提取矩形框内的文字
            //    if (_resizingRectangle != null)
            //    {
            //        ExtractTextFromRectangle(_resizingRectangle);
            //    }
                
            //    _resizingRectangle = null;
            //    _resizeDirection = "";
            //    ImageViewer.ReleaseMouseCapture();
            //}
            //else if (_isSelecting)
            //{
            //    _isSelecting = false;
            //    ImageViewer.ReleaseMouseCapture();

            //    if (_selectionRectangle != null && _selectionRectangle.Width > 5 && _selectionRectangle.Height > 5)
            //    {
            //        // 将矩形添加到集合中
            //        _selectionRectangles.Add(_selectionRectangle);
                    
            //        // 提取框选的文字
            //        ExtractTextFromRectangle(_selectionRectangle);
            //    }
            //    else if (_selectionRectangle != null)
            //    {
            //        // 如果矩形太小,则移除它
            //        _selectionCanvas.Children.Remove(_selectionRectangle);
            //    }
                
            //    // 重置当前选择矩形引用,准备下一次选择
            //    _selectionRectangle = null;
            //}
        }

        // 显示坐标弹窗
        private void ShowCoordinateDialog(double left, double top, double width, double height)
        {
            string message = $"选择区域坐标:\n" +
                            $"左上角: ({left:F0}, {top:F0})\n" +
                            $"右下角: ({left + width:F0}, {top + height:F0})\n" +
                            $"宽度: {width:F0}\n" +
                            $"高度: {height:F0}";

            MessageBox.Show(message, "矩形坐标信息", MessageBoxButton.OK, MessageBoxImage.Information);
        }


        // 鼠标右键按下事件
        private void ImageViewer_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            //if (_mode == EditorMode.ReviseEdit && _selectionRectangles.Count > 0)
            //{
            //    Point clickPoint = e.GetPosition(ImageViewer);
            //    Rectangle clickedRectangle = null;

            //    // 查找被点击的矩形选框
            //    foreach (Rectangle rect in _selectionRectangles)
            //    {
            //        if (IsPointOnRectangleBorder(clickPoint, rect))
            //        {
            //            clickedRectangle = rect;
            //            break;
            //        }
            //    }

            //    if (clickedRectangle != null)
            //    {
            //        // 创建右键菜单
            //        ContextMenu contextMenu = new ContextMenu();
            //        MenuItem deleteMenuItem = new MenuItem { Header = "删除" };
            //        deleteMenuItem.Click += (s, args) => DeleteRectangle(clickedRectangle);
            //        contextMenu.Items.Add(deleteMenuItem);

            //        // 显示菜单
            //        contextMenu.IsOpen = true;
            //        contextMenu.PlacementTarget = ImageViewer;
            //        contextMenu.Placement = PlacementMode.MousePoint;
            //    }
            //}
        }

        // 检查点击位置是否在矩形边线上
        private bool IsPointOnRectangleBorder(Point point, Rectangle rectangle)
        {
            double left = Canvas.GetLeft(rectangle);
            double top = Canvas.GetTop(rectangle);
            double right = left + rectangle.Width;
            double bottom = top + rectangle.Height;
            double tolerance = 5; // 边线容差

            // 检查是否在矩形边线附近
            bool onLeftBorder = Math.Abs(point.X - left) <= tolerance && point.Y >= top - tolerance && point.Y <= bottom + tolerance;
            bool onRightBorder = Math.Abs(point.X - right) <= tolerance && point.Y >= top - tolerance && point.Y <= bottom + tolerance;
            bool onTopBorder = Math.Abs(point.Y - top) <= tolerance && point.X >= left - tolerance && point.X <= right + tolerance;
            bool onBottomBorder = Math.Abs(point.Y - bottom) <= tolerance && point.X >= left - tolerance && point.X <= right + tolerance;

            return onLeftBorder || onRightBorder || onTopBorder || onBottomBorder;
        }

        // 删除指定的矩形选框
        //private void DeleteRectangle(Rectangle rectangle)
        //{
        //    _selectionCanvas.Children.Remove(rectangle);
        //    _selectionRectangles.Remove(rectangle);
        //}

        // 提取矩形框内的文字并插入到编辑器
        private void ExtractTextFromRectangle(Rectangle rectangle)
        {
            //if (rectangle == null || ImageViewer.Source == null) return;

            //// 获取图片的原始尺寸
            //var imageSource = ImageViewer.Source as BitmapSource;
            //if (imageSource != null)
            //{
            //    double imageOriginalWidth = imageSource.PixelWidth;
            //    double imageOriginalHeight = imageSource.PixelHeight;

            //    // 获取矩形在Canvas中的位置
            //    double canvasLeft = Canvas.GetLeft(rectangle);
            //    double canvasTop = Canvas.GetTop(rectangle);
            //    double canvasWidth = rectangle.Width;
            //    double canvasHeight = rectangle.Height;

            //    // 转换为图片显示区域的坐标
            //    double actualLeft = canvasLeft / _imageZoomFactor;
            //    double actualTop = canvasTop / _imageZoomFactor;
            //    double actualWidth = canvasWidth / _imageZoomFactor;
            //    double actualHeight = canvasHeight / _imageZoomFactor;

            //    // 确保坐标在有效范围内
            //    actualLeft = Math.Max(0, Math.Min(actualLeft, imageOriginalWidth));
            //    actualTop = Math.Max(0, Math.Min(actualTop, imageOriginalHeight));
            //    actualWidth = Math.Max(0, Math.Min(actualWidth, imageOriginalWidth - actualLeft));
            //    actualHeight = Math.Max(0, Math.Min(actualHeight, imageOriginalHeight - actualTop));

            //    // 找出框选的文字
            //    JObject jsn = (JObject)Editor._jsn_OpenImg.DeepClone();
            //    jsn = Global.find_rectange_text(jsn, (int)(actualLeft + 0.5), (int)(actualTop + 0.5), (int)(actualWidth + 0.5), (int)(actualHeight + 0.5));
            //    Editor.InsertText(jsn, Editor._md5_OpenImg);
            //}
        }

        // 获取调整大小的方向
        //private string GetResizeDirection(Point point, Rectangle rectangle)
        //{
        //    double left = Canvas.GetLeft(rectangle);
        //    double top = Canvas.GetTop(rectangle);
        //    double right = left + rectangle.Width;
        //    double bottom = top + rectangle.Height;
        //    double tolerance = 8; // 边框检测容差

        //    bool onLeft = Math.Abs(point.X - left) <= tolerance;
        //    bool onRight = Math.Abs(point.X - right) <= tolerance;
        //    bool onTop = Math.Abs(point.Y - top) <= tolerance;
        //    bool onBottom = Math.Abs(point.Y - bottom) <= tolerance;

        //    // 检查是否在矩形范围内
        //    bool inHorizontalRange = point.X >= left - tolerance && point.X <= right + tolerance;
        //    bool inVerticalRange = point.Y >= top - tolerance && point.Y <= bottom + tolerance;

        //    // 角落优先
        //    if (onLeft && onTop && inHorizontalRange && inVerticalRange) return "topleft";
        //    if (onRight && onTop && inHorizontalRange && inVerticalRange) return "topright";
        //    if (onLeft && onBottom && inHorizontalRange && inVerticalRange) return "bottomleft";
        //    if (onRight && onBottom && inHorizontalRange && inVerticalRange) return "bottomright";

        //    // 边框
        //    if (onLeft && inVerticalRange) return "left";
        //    if (onRight && inVerticalRange) return "right";
        //    if (onTop && inHorizontalRange) return "top";
        //    if (onBottom && inHorizontalRange) return "bottom";

        //    return "";
        //}

        // 添加重置图片位置的方法
        private void ResetImagePosition()
        {
            translateTransform.X = 0;
            translateTransform.Y = 0;
            scaleTransform.ScaleX = 1.0;
            scaleTransform.ScaleY = 1.0;
        }

        // 可以在双击时调用重置功能
        private void Grid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                ResetImagePosition();
            }
        }

        private void Image_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (ViewModel.Image == null) return;  // ViewModel.Rectangles.Count == 0

            var newWidth = e.NewSize.Width;
            var newHeight = e.NewSize.Height;

            // 校对模式打开图片需要恢复选框
            if (_pendingRectangles.Count > 0 && newWidth > 0 && newHeight > 0)
            {
                foreach(var selected_rectange in _pendingRectangles)
                {
                    int Id = selected_rectange["Id"].Value<int>();
                    int lft = selected_rectange["lft"].Value<int>();
                    int tp = selected_rectange["tp"].Value<int>();
                    int wdth = selected_rectange["wdth"].Value<int>();
                    int hght = selected_rectange["hght"].Value<int>();


                    var displayPos = Editor.ConvertOriginalToDisplayCoordinates(lft, tp);
                    var displaySize = Editor.ConvertOriginalToDisplaySize(wdth, hght);

                    ViewModel.AddRectangle(Id, displayPos.X, displayPos.Y, displaySize.Width, displaySize.Height);
                }

                _pendingRectangles.Clear();
                return;
            }

            // 如果是首次设置尺寸,记录初始值
            if (_previousImageWidth == 0 || _previousImageHeight == 0)
            {
                _previousImageWidth = newWidth;
                _previousImageHeight = newHeight;
                return;
            }

            // 计算缩放比例
            double scaleX = newWidth / _previousImageWidth;
            double scaleY = newHeight / _previousImageHeight;

            // 更新所有矩形框的坐标
            foreach (var rectangle in ViewModel.Rectangles)
            {
                rectangle.Left *= scaleX;
                rectangle.Top *= scaleY;
                rectangle.Width *= scaleX;
                rectangle.Height *= scaleY;
            }

            // 更新记录的尺寸
            _previousImageWidth = newWidth;
            _previousImageHeight = newHeight;
        }

        // 右下角调整大小事件处理
        private void ResizeThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                // 调整宽度和高度
                double newWidth = Math.Max(10, rectangle.Width + e.HorizontalChange);
                double newHeight = Math.Max(10, rectangle.Height + e.VerticalChange);
                
                rectangle.Width = newWidth;
                rectangle.Height = newHeight;

                //On_Rectangle_adjust(rectangle);
            }
        }

        // 右边中间调整大小事件处理
        private void ResizeRightThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                // 只调整宽度
                double newWidth = Math.Max(10, rectangle.Width + e.HorizontalChange);
                rectangle.Width = newWidth;

                //On_Rectangle_adjust(rectangle);
            }
        }

        // 下边中间调整大小事件处理
         private void ResizeBottomThumb_DragDelta(object sender, DragDeltaEventArgs e)
         {
             var thumb = sender as Thumb;
             if (thumb?.DataContext is RectangleItem rectangle)
             {
                 // 只调整高度
                 double newHeight = Math.Max(10, rectangle.Height + e.VerticalChange);
                 rectangle.Height = newHeight;

                //On_Rectangle_adjust(rectangle);
             }
         }

         // 左边中间调整大小事件处理
         private void ResizeLeftThumb_DragDelta(object sender, DragDeltaEventArgs e)
         {
             var thumb = sender as Thumb;
             if (thumb?.DataContext is RectangleItem rectangle)
             {
                 // 调整左边位置和宽度
                 double newLeft = rectangle.Left + e.HorizontalChange;
                 double newWidth = rectangle.Width - e.HorizontalChange;
                 
                 // 确保最小宽度
                 if (newWidth >= 10)
                 {
                     rectangle.Left = newLeft;
                     rectangle.Width = newWidth;
                 }

                //On_Rectangle_adjust(rectangle);
             }
         }

         // 上边中间调整大小事件处理
         private void ResizeTopThumb_DragDelta(object sender, DragDeltaEventArgs e)
         {
             var thumb = sender as Thumb;
             if (thumb?.DataContext is RectangleItem rectangle)
             {
                 // 调整上边位置和高度
                 double newTop = rectangle.Top + e.VerticalChange;
                 double newHeight = rectangle.Height - e.VerticalChange;
                 
                 // 确保最小高度
                 if (newHeight >= 10)
                 {
                     rectangle.Top = newTop;
                     rectangle.Height = newHeight;
                 }

                //On_Rectangle_adjust(rectangle);
             }
         }

         // 左上角调整大小事件处理
         private void ResizeTopLeftThumb_DragDelta(object sender, DragDeltaEventArgs e)
         {
             var thumb = sender as Thumb;
             if (thumb?.DataContext is RectangleItem rectangle)
             {
                 // 调整左上角位置和尺寸
                 double newLeft = rectangle.Left + e.HorizontalChange;
                 double newTop = rectangle.Top + e.VerticalChange;
                 double newWidth = rectangle.Width - e.HorizontalChange;
                 double newHeight = rectangle.Height - e.VerticalChange;
                 
                 // 确保最小尺寸
                 if (newWidth >= 10 && newHeight >= 10)
                 {
                     rectangle.Left = newLeft;
                     rectangle.Top = newTop;
                     rectangle.Width = newWidth;
                     rectangle.Height = newHeight;
                 }

                //On_Rectangle_adjust(rectangle);
             }
         }

         // 右上角调整大小事件处理
         private void ResizeTopRightThumb_DragDelta(object sender, DragDeltaEventArgs e)
         {
             var thumb = sender as Thumb;
             if (thumb?.DataContext is RectangleItem rectangle)
             {
                 // 调整右上角位置和尺寸
                 double newTop = rectangle.Top + e.VerticalChange;
                 double newWidth = rectangle.Width + e.HorizontalChange;
                 double newHeight = rectangle.Height - e.VerticalChange;
                 
                 // 确保最小尺寸
                 if (newWidth >= 10 && newHeight >= 10)
                 {
                     rectangle.Top = newTop;
                     rectangle.Width = newWidth;
                     rectangle.Height = newHeight;
                 }

                 //On_Rectangle_adjust(rectangle);
             }
         }

         // 左下角调整大小事件处理
         private void ResizeBottomLeftThumb_DragDelta(object sender, DragDeltaEventArgs e)
         {
             var thumb = sender as Thumb;
             if (thumb?.DataContext is RectangleItem rectangle)
             {
                 // 调整左下角位置和尺寸
                 double newLeft = rectangle.Left + e.HorizontalChange;
                 double newWidth = rectangle.Width - e.HorizontalChange;
                 double newHeight = rectangle.Height + e.VerticalChange;
                 
                 // 确保最小尺寸
                 if (newWidth >= 10 && newHeight >= 10)
                 {
                     rectangle.Left = newLeft;
                     rectangle.Width = newWidth;
                     rectangle.Height = newHeight;
                 }

                 //On_Rectangle_adjust(rectangle);
             }
         }

        // 鼠标进入矩形区域事件处理器
        private void RectangleGrid_MouseEnter(object sender, MouseEventArgs e)
        {
            if (sender is Grid grid && grid.DataContext is RectangleItem rectangle)
            {
                rectangle.IsHovered = true;
            }
        }

        // 鼠标离开矩形区域事件处理器
        private void RectangleGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            if (sender is Grid grid && grid.DataContext is RectangleItem rectangle)
            {
                rectangle.IsHovered = false;
            }
        }

        // 右下角调整完成事件处理
        private void ResizeThumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                OnRectangleAdjustCompleted(rectangle, "右下角");
            }
        }

        // 右边中间调整完成事件处理
        private void ResizeRightThumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                OnRectangleAdjustCompleted(rectangle, "右边");
            }
        }

        // 下边中间调整完成事件处理
        private void ResizeBottomThumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                OnRectangleAdjustCompleted(rectangle, "下边");
            }
        }

        // 左边中间调整完成事件处理
        private void ResizeLeftThumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                OnRectangleAdjustCompleted(rectangle, "左边");
            }
        }

        // 上边中间调整完成事件处理
        private void ResizeTopThumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                OnRectangleAdjustCompleted(rectangle, "上边");
            }
        }

        // 左上角调整完成事件处理
        private void ResizeTopLeftThumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                OnRectangleAdjustCompleted(rectangle, "左上角");
            }
        }

        // 右上角调整完成事件处理
        private void ResizeTopRightThumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                OnRectangleAdjustCompleted(rectangle, "右上角");
            }
        }

        // 左下角调整完成事件处理
        private void ResizeBottomLeftThumb_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            var thumb = sender as Thumb;
            if (thumb?.DataContext is RectangleItem rectangle)
            {
                OnRectangleAdjustCompleted(rectangle, "左下角");
            }
        }

        // 矩形调整完成的通用处理方法
        private void OnRectangleAdjustCompleted(RectangleItem rectangle, string adjustType)
        {
            On_Rectangle_adjust(rectangle);
        }

        private async Task split_menu_openImage(string ImageMD5)
        {
            if (ImageMD5 != "")
            {

                //_pthimg

                // 要先找出真实图片名

                if (!_dic_m5_imgname.ContainsKey(ImageMD5))
                {
                    throw new Exception("Error: somthing wrong.");
                }

                string image_pth = _dic_m5_imgname[ImageMD5];

                this._currentFilePath = image_pth;

                var (jsn, m5, pth_img, pth_json) = await Global.img_md5_jsn(image_pth, _ocrMode);

                if (Path.Exists(pth_json))
                {
                    Editor._lines.Clear();

                    Editor._lines = Global.loadJsonReviseEdit_FromOriginalPath(pth_json);

                    Editor._undoBuffer.Clear();
                    Editor._undoIndex = -1;
                    Editor._cursorLine = 0;
                    Editor._cursorColumn = 0;
                    Editor.ClearSelection();
                    Editor._textChanged = true;
                    Editor.InvalidateVisual();

                    // 触发文本改变事件
                    Editor.OnTextChanged();

                    UpdateTitle();
                    StatusText.Text = $"已打开: {_currentFilePath}";
                }

                // 加载原图
                string b64_str = File.ReadAllText(pth_img, Encoding.UTF8);
                byte[] img_bytes = Base64.Base64Decode(b64_str);
                Mat im_orig = Cv2.ImDecode(img_bytes, ImreadModes.Color);
                BitmapSource source = TextEditorControl.MatToBitmapSource(im_orig);
                ViewModel.Image = source;
                ViewModel.ClearAllRectangles();


                // 重置图片尺寸记录
                _previousImageWidth = 0;
                _previousImageHeight = 0;


                Editor._pthimg = image_pth;
                Editor._jsn_OpenImg = jsn;
                Editor._md5_OpenImg = ImageMD5;

            }

        }

        // 树形目录选择变化事件
        private async void DirectoryTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is DirectoryTreeNode selectedNode)
            {
                string ImageMD5 = "";

                foreach (TextCharacter c in selectedNode.line.Characters)
                {
                    if (c.ImageMD5 != "")
                    {
                        ImageMD5 = c.ImageMD5;
                        break;
                    }
                }

                if (ImageMD5 != "")
                {
                    await split_menu_openImage(ImageMD5);
                }
            }
        }
     }


    // 添加布尔值到可见性转换器
    public class BooleanToVisibilityConverter : IValueConverter
    {
        public static readonly BooleanToVisibilityConverter Instance = new BooleanToVisibilityConverter();

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return (bool)value ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return (Visibility)value == Visibility.Visible;
        }
    }

    // 多值转换器:同时检查IsVisible和IsHovered属性
    public class VisibilityAndHoverConverter : IMultiValueConverter
    {
        public static readonly VisibilityAndHoverConverter Instance = new VisibilityAndHoverConverter();

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values.Length >= 2 && values[0] is bool isVisible && values[1] is bool isHovered)
            {
                return (isVisible && isHovered) ? Visibility.Visible : Visibility.Collapsed;
            }
            return Visibility.Collapsed;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

}