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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5f13be
 
 
 
 
 
 
 
 
 
 
 
 
dccd280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae59d0c
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
using Echodict;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Printing;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;
using Path = System.IO.Path;
using Point = System.Windows.Point;
using Rect = System.Windows.Rect;
using Size = System.Windows.Size;
using Window = System.Windows.Window;

namespace WpfEditor
{
    public class TextEditorControl : Control
    {
        private Window _imageWindow = null;
        private bool _isCut = false;
        public EditorMode _mode = EditorMode.ImageOCR; // 默认模式为图片OCR

        public JObject _jsn_OpenImg;  // for 校对
        public string _md5_OpenImg;
        public Dictionary<string, string> _dic_deleted_char = new Dictionary<string, string>();  // 被删除的字符存它的 guid,保存的时侯标记它逻辑删除

        public string _pthimg; // 当前打开的图片路径
        
        // 添加MainWindow引用
        public MainWindow _mainWindow;

        public static BitmapSource MatToBitmapSource(Mat mat)
        {
            // Detect pixel format (BGR24 for color, Gray8 for grayscale)
            var pixelFormat = mat.Channels() == 1 ? PixelFormats.Gray8 : PixelFormats.Bgr24;

            // Create BitmapSource with stride = mat.Step (handles 4-byte alignment)
            return BitmapSource.Create(
                mat.Width, mat.Height,
                96, 96, // Default DPI
                pixelFormat,
                null,
                mat.Data,
                (int)mat.Step() * mat.Height, // Buffer size
                (int)mat.Step() // Stride (critical for alignment)
            );
        }

        public void ShowDraggableImageControl(Mat image, Mat image_orig)
        {
            var mainWindow = Window.GetWindow(this) as MainWindow;

            // 将Mat转换为BitmapSource
            BitmapSource bitmapSource = MatToBitmapSource(image); // OpenCvSharp.Extensions.BitmapSourceConverter.ToBitmapSource(image);
            BitmapSource bitmapSource2 = MatToBitmapSource(image_orig);

            // 如果窗口已存在,则更新图片内容
            if (_imageWindow != null)  //  && _imageWindow.IsLoaded
            {
                var brdr = _imageWindow.Content as Border;
                var stckpnl = brdr.Child as StackPanel; //  as System.Windows.Controls.Image;
                var img_ctl = stckpnl.Children[1] as System.Windows.Controls.Image;

                //var img_ctl = _imageWindow.Content as System.Windows.Controls.Image;
                if (img_ctl != null)
                {
                    img_ctl.Source = bitmapSource;
                    
                    // 根据新图片调整窗口大小
                    AdjustWindowSizeBasedOnImage(_imageWindow, bitmapSource.PixelWidth, bitmapSource.PixelHeight);

                    mainWindow?.ShowImageInPanel(bitmapSource2);
                }
                return;
            }

            // 创建一个新窗口
            _imageWindow = new Window
            {
                WindowStyle = WindowStyle.None,
                AllowsTransparency = true,
                Background = Brushes.Transparent,
                ShowInTaskbar = false,
                Topmost = true,
                Focusable = false,
                ResizeMode = ResizeMode.NoResize,
                SizeToContent = SizeToContent.WidthAndHeight,
                Owner = Window.GetWindow(this) // 设置主窗口为所有者,这样主窗口关闭时,图片窗口也会关闭
            };
            
            // 创建一个边框和图片控件
            Border border = new Border
            {
                Background = new SolidColorBrush(Color.FromArgb(200, 30, 30, 30)),
                BorderBrush = Brushes.LightGray,
                BorderThickness = new Thickness(1),
                CornerRadius = new CornerRadius(3),
                Padding = new Thickness(5)
            };
            
            // 创建一个StackPanel来包含图片和标题栏
            StackPanel stackPanel = new StackPanel {
                HorizontalAlignment = HorizontalAlignment.Left
            };
            
            // 添加一个简单的标题栏
            Grid titleBar = new Grid { Height = 20, Margin = new Thickness(0, 0, 0, 5) };
            titleBar.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            titleBar.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
            
            TextBlock titleText = new TextBlock
            {
                Text = "图片预览",
                Foreground = Brushes.White,
                VerticalAlignment = VerticalAlignment.Center
            };
            
            Button closeButton = new Button
            {
                Content = "X",
                Width = 20,
                Height = 20,
                Padding = new Thickness(0),
                Background = Brushes.Transparent,
                Foreground = Brushes.White,
                BorderThickness = new Thickness(0)
            };
            closeButton.Click += (s, e) => _imageWindow.Close();
            
            Grid.SetColumn(titleText, 0);
            Grid.SetColumn(closeButton, 1);
            titleBar.Children.Add(titleText);
            titleBar.Children.Add(closeButton);
            
            // 创建图片控件
            System.Windows.Controls.Image imageControl = new System.Windows.Controls.Image
            {
                Source = bitmapSource,
                Stretch = Stretch.None,
                HorizontalAlignment = HorizontalAlignment.Left
            };
            
            // 添加到StackPanel
            stackPanel.Children.Add(titleBar);
            stackPanel.Children.Add(imageControl);
            
            // 设置边框内容
            border.Child = stackPanel;
            
            // 设置窗口内容
            _imageWindow.Content = border;
            
            // 添加拖动功能
            border.MouseLeftButtonDown += (s, e) =>
            {
                if (e.ClickCount == 1)
                {
                    _imageWindow.DragMove();
                }
            };
            
            // 添加右键菜单
            ContextMenu contextMenu = new ContextMenu();
            MenuItem closeMenuItem = new MenuItem { Header = "关闭" };
            closeMenuItem.Click += (s, e) => _imageWindow.Close();
            contextMenu.Items.Add(closeMenuItem);
            border.ContextMenu = contextMenu;
            
            // 显示窗口
            _imageWindow.Show();  // 单行文本图

            // 根据图片大小调整窗口尺寸
            AdjustWindowSizeBasedOnImage(_imageWindow, bitmapSource.PixelWidth, bitmapSource.PixelHeight);
            
            // 设置初始位置(居中显示)
            if (mainWindow != null)
            {
                _imageWindow.Left = 0; // mainWindow.Left + (mainWindow.Width - _imageWindow.ActualWidth) / 2;
                _imageWindow.Top = mainWindow.Top + (mainWindow.Height - _imageWindow.ActualHeight) / 2;
            }

            if (mainWindow != null)
            {
                //if (true || mainWindow.ImageViewer.Source == null)
                //{
                //    mainWindow.ShowImageInPanel(bitmapSource2);  // 全图
                //}
            }


        }
        
        // 根据图片大小调整窗口尺寸的辅助方法
        private void AdjustWindowSizeBasedOnImage(Window window, int imageWidth, int imageHeight)
        {
            // 获取当前屏幕的工作区大小
            double screenWidth = SystemParameters.WorkArea.Width;
            double screenHeight = SystemParameters.WorkArea.Height;
            
            // 设置窗口最大尺寸(考虑到标题栏、边框等UI元素的额外空间)
            double maxWidth = screenWidth * 0.8; // 最大宽度为屏幕工作区的80%
            double maxHeight = screenHeight * 0.8; // 最大高度为屏幕工作区的80%
            
            // 计算额外UI元素的空间(标题栏、边框、内边距等)
            const double uiExtraWidth = 30; // 估计的水平方向额外空间
            const double uiExtraHeight = 50; // 估计的垂直方向额外空间(包括标题栏)
            
            // 计算实际需要的窗口尺寸
            double requiredWidth = imageWidth + uiExtraWidth;
            double requiredHeight = imageHeight + uiExtraHeight;
            
            // 如果图片尺寸超过最大限制,则应用缩放
            if (requiredWidth > maxWidth || requiredHeight > maxHeight)
            {
                // 计算需要的缩放比例
                double scaleX = maxWidth / requiredWidth;
                double scaleY = maxHeight / requiredHeight;
                double scale = Math.Min(scaleX, scaleY); // 取较小的缩放比例,确保完全适应
                
                // 应用缩放
                var image = ((window.Content as Border).Child as StackPanel).Children[1] as System.Windows.Controls.Image;
                if (image != null)
                {
                    // 更改图片的缩放模式
                    image.Stretch = Stretch.Uniform;
                    image.MaxWidth = maxWidth - uiExtraWidth;
                    image.MaxHeight = maxHeight - uiExtraHeight;
                }
            }
            
            // 更新窗口布局
            window.UpdateLayout();
        }

        #region 依赖属性

        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(TextEditorControl),
                new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnTextChanged));

        public static readonly DependencyProperty IsReadOnlyProperty =
            DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(TextEditorControl),
                new PropertyMetadata(false));

        public static readonly DependencyProperty TabSizeProperty =
            DependencyProperty.Register("TabSize", typeof(int), typeof(TextEditorControl),
                new PropertyMetadata(4));

        public static readonly DependencyProperty LineNumbersVisibleProperty =
            DependencyProperty.Register("LineNumbersVisible", typeof(bool), typeof(TextEditorControl),
                new PropertyMetadata(true));

        public static readonly DependencyProperty ShowWhitespacesProperty =
            DependencyProperty.Register("ShowWhitespaces", typeof(bool), typeof(TextEditorControl),
                new PropertyMetadata(true));

        public static readonly DependencyProperty HighlightCurrentLineProperty =
            DependencyProperty.Register("HighlightCurrentLine", typeof(bool), typeof(TextEditorControl),
                new PropertyMetadata(true));

        #endregion
    
    // 创建右键菜单的方法
    private void CreateContextMenu()
    {
        ContextMenu = new ContextMenu();
        
        // 复制菜单项
        MenuItem copyMenuItem = new MenuItem
        {
            Header = "复制",
            Command = ApplicationCommands.Copy
        };
        ContextMenu.Items.Add(copyMenuItem);
        
        // 剪切菜单项
        MenuItem cutMenuItem = new MenuItem
        {
            Header = "剪切",
            Command = ApplicationCommands.Cut
        };
        ContextMenu.Items.Add(cutMenuItem);
        
        // 粘贴菜单项
        MenuItem pasteMenuItem = new MenuItem
        {
            Header = "粘贴",
            Command = ApplicationCommands.Paste
        };
        ContextMenu.Items.Add(pasteMenuItem);
        
        // 分隔符
        ContextMenu.Items.Add(new Separator());
        
        // 全选菜单项
        MenuItem selectAllMenuItem = new MenuItem
        {
            Header = "全选",
            Command = ApplicationCommands.SelectAll
        };
        ContextMenu.Items.Add(selectAllMenuItem);


        // jisho查询菜单项
        MenuItem jishoMenuItem = new MenuItem
        {
            Header = "jisho"
        };
        jishoMenuItem.Click += OnjishoMenuItemClick;
        ContextMenu.Items.Add(jishoMenuItem);

        // naverja查询菜单项
        MenuItem naverjaMenuItem = new MenuItem
        {
            Header = "naverja"
        };
        naverjaMenuItem.Click += OnnaverjaMenuItemMenuItemClick;
        ContextMenu.Items.Add(naverjaMenuItem);

        // 查询菜单项
        MenuItem QeryMenuItem = new MenuItem
        {
            Header = "查询"
        };
        QeryMenuItem.Click += OnQueryMenuItemClick;
        ContextMenu.Items.Add(QeryMenuItem);

        // 翻译菜单项
        MenuItem translateMenuItem = new MenuItem
        {
            Header = "翻译"
        };
        translateMenuItem.Click += OnTranslateMenuItemClick;
        ContextMenu.Items.Add(translateMenuItem);

        // 设置菜单打开前的事件处理,用于控制菜单项的可用性
        ContextMenu.Opened += OnContextMenuOpened;
    }

    // 右键菜单打开时的事件处理
    private void OnContextMenuOpened(object sender, RoutedEventArgs e)
    {
        bool hasSelection = HasSelection();
        bool hasClipboardText = Clipboard.ContainsText() || Clipboard.ContainsData("TextEditorCustomFormat"); 
        
        // 根据当前状态设置菜单项的可用性
        foreach (var item in ContextMenu.Items)
        {
            if (item is MenuItem menuItem)
            {
                if (menuItem.Command == ApplicationCommands.Copy || 
                    menuItem.Command == ApplicationCommands.Cut)
                {
                    menuItem.IsEnabled = hasSelection;
                }
                else if (menuItem.Command == ApplicationCommands.Paste)
                {
                    menuItem.IsEnabled = !IsReadOnly && hasClipboardText;
                }
                else if (menuItem.Command == ApplicationCommands.SelectAll)
                {
                    menuItem.IsEnabled = _lines.Count > 0 && 
                        _lines.Any(line => line.Characters.Count > 0);
                }
            }
        }
    }

        // "翻译"菜单项点击事件处理
        private async void OnTranslateMenuItemClick(object sender, RoutedEventArgs e)
        {

            if (HasSelection()) {
                string text = GetSelectedText();
                string res = await DeepSeek.translate(text);
                if (res != "")
                {
                    JObject jsn = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(res);
                    string zh = jsn["choices"][0]["message"]["content"].Value<string>();
                    var win = new TranslationResultWindow(zh);
                    win.Owner = Window.GetWindow(this);
                    win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    win.ShowDialog();
                }
            }
        }

        private async void OnjishoMenuItemClick(object sender, RoutedEventArgs e)
        {
            if (HasSelection())
            {
                string text = GetSelectedText();
                var content = System.Web.HttpUtility.UrlEncode(text);
                String url = $"https://jisho.org/search/{content}";

                var win = Echodict.EchodictWindow.Instance;
                win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                win.OpenUrl(url);
            }
        }

        private async void OnnaverjaMenuItemMenuItemClick(object sender, RoutedEventArgs e)
        {
            if (HasSelection())
            {
                string text = GetSelectedText();
                var content = System.Web.HttpUtility.UrlEncode(text);
                String url = $"https://ja.dict.naver.com/#/search?query={content}&range=all";

                var win = Echodict.EchodictWindow.Instance;
                win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                win.OpenUrl(url);
            }
        }

        // "查询"菜单项点击事件处理
        private async void OnQueryMenuItemClick(object sender, RoutedEventArgs e)
        {
            if (HasSelection())
            {
                string text = GetSelectedText();

                //var win = Echodict.EchodictWindow.Instance;
                //win.Owner = Window.GetWindow(this);
                //win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                //win.ShowWord(text);
                var win = Echodict.EchodictWindow.Instance;
                // Without an Owner, CenterOwner behaves like Manual. Use CenterScreen instead.
                win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                win.ShowWord(text);
            }
        }

        #region 属性

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        public bool IsReadOnly
        {
            get { return (bool)GetValue(IsReadOnlyProperty); }
            set { SetValue(IsReadOnlyProperty, value); }
        }

        public int TabSize
        {
            get { return (int)GetValue(TabSizeProperty); }
            set { SetValue(TabSizeProperty, value); }
        }

        public bool LineNumbersVisible
        {
            get { return (bool)GetValue(LineNumbersVisibleProperty); }
            set { SetValue(LineNumbersVisibleProperty, value); }
        }

        public bool ShowWhitespaces
        {
            get { return (bool)GetValue(ShowWhitespacesProperty); }
            set { SetValue(ShowWhitespacesProperty, value); }
        }

        public bool HighlightCurrentLine
        {
            get { return (bool)GetValue(HighlightCurrentLineProperty); }
            set { SetValue(HighlightCurrentLineProperty, value); }
        }

        #endregion

        #region 内部数据结构

        public List<TextLine> _lines = new List<TextLine>();
        public int _cursorLine = 0;
        public int _cursorColumn = 0;
        public int _selectionStartLine = -1;
        public int _selectionStartColumn = -1;
        public int _selectionEndLine = -1;
        public int _selectionEndColumn = -1;
        public List<UndoAction> _undoBuffer = new List<UndoAction>();
        public int _undoIndex = -1;
        public bool _textChanged = false;
        public int _scrollOffset = 0; // 添加滚动偏移量变量

        // 查找相关字段
        private FindDialog _findDialog = null;
        private string _lastSearchText = "";
        private bool _lastMatchCase = false;
        private bool _lastWholeWord = false;
        private int _lastFoundLine = -1;
        private int _lastFoundColumn = -1;
        private List<(int line, int column, int length)> _findResults = new List<(int, int, int)>();
        private int _currentFindIndex = -1;

        #endregion

        #region 构造函数

        static TextEditorControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TextEditorControl),
                new FrameworkPropertyMetadata(typeof(TextEditorControl)));
        }

        public TextEditorControl()
        {
            this.Focusable = true;
            this.FocusVisualStyle = null;
            this.ClipToBounds = true;
            
            // 设置MainWindow引用
            //_mainWindow = mainWindow;

            // 初始化一个空行
            _lines.Add(new TextLine());

            // 注册命令绑定
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, OnCopy));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Cut, OnCut));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, OnPaste));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo, OnUndo));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo, OnRedo));
            CommandBindings.Add(new CommandBinding(ApplicationCommands.SelectAll, OnSelectAll));
        
            // 创建右键菜单
            CreateContextMenu();
        
        }

        #endregion

        #region 事件处理

        public static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = (TextEditorControl)d;
            if (e.NewValue is string)
            {
                //control.SetText((string)e.NewValue);
            }
            else if (e.NewValue is JObject)
            {
                //control.SetText((JObject)e.NewValue, "");
            }
            
            
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            RenderEditor(drawingContext);
        }

        protected override void OnMouseWheel(MouseWheelEventArgs e)
        {
            base.OnMouseWheel(e);
            
            // 计算字体度量
            double lineHeight = FontSize * 1.2;
            
            // 根据滚轮方向调整滚动偏移量
            // 向上滚动(e.Delta > 0)时,减小偏移量,向下滚动时增加偏移量
            int scrollLines = e.Delta > 0 ? -3 : 3;
            _scrollOffset += scrollLines;
            
            // 限制滚动范围
            int maxVisibleLines = (int)(ActualHeight / lineHeight);
            int maxScrollOffset = Math.Max(0, _lines.Count - maxVisibleLines + 1);
            _scrollOffset = Math.Max(0, Math.Min(_scrollOffset, maxScrollOffset));
            
            // 完全移除对光标位置的限制,允许自由滚动查看文档
            
            e.Handled = true;
            InvalidateVisual();
        }

        protected override void OnTextInput(TextCompositionEventArgs e)
        {
            base.OnTextInput(e);
            if (!IsReadOnly)
            {
                //InsertText(e.Text);
                InsertTextCharacters(e.Text);

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

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

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

                // 重绘编辑器
                InvalidateVisual();

                e.Handled = true;
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            HandleKeyDown(e);
        }

        public void showCurrChar()
        {
            TextCharacter chr = GetCharacterAfterCursor();
            if (chr != null)
            {
                string m5 = chr.ImageMD5;
                if (m5 != "")
                {
                    //var (pth_img, pth_json) = Global.get_img_json_pth(m5);
                    var (pth_img, pth_json) = Global.get_img_json_pthv2(_pthimg);
                    if (Path.Exists(pth_json) && Path.Exists(pth_img))
                    {
                        string jsn_str = File.ReadAllText(pth_json, Encoding.UTF8);
                        JObject jsn = (JObject)JsonConvert.DeserializeObject(jsn_str);


                        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);

                        int width = jsn.Value<int>("width");
                        int height = jsn.Value<int>("height");

                        var prism_wordsInfo = jsn["prism_wordsInfo"].Value<JArray>();
                        bool found = false;
                        foreach (var item in prism_wordsInfo)
                        {
                            JArray charInfo = item["charInfo"].Value<JArray>();
                            string line_word = item["word"].Value<string>();
                            int line_x = item["x"].Value<int>();
                            int line_y = item["y"].Value<int>();
                            int line_width = item["width"].Value<int>();
                            int line_height = item["height"].Value<int>();

                            foreach (var item2 in charInfo)
                            {
                                string oneChar = item2["word"].Value<string>();
                                int x = item2["x"].Value<int>();
                                int y = item2["y"].Value<int>();
                                int w = item2["w"].Value<int>();
                                int h = item2["h"].Value<int>();

                                //if (oneChar == chr.Character.ToString())
                                if (true)  // 修改字符后它就可以不等了。有相同坐标宽高的字符只有一种情况,就是它们都是某个“单词”的一部分
                                {
                                    if (chr.x == x)
                                    {
                                        if (chr.y == y)
                                        {



                                            Cv2.Rectangle(im_orig, new OpenCvSharp.Rect(chr.x, chr.y, chr.w, chr.h), new OpenCvSharp.Scalar(0, 0, 255));

                                            Mat cut = im_orig.Clone(new OpenCvSharp.Rect(0, line_y, im_orig.Width, line_height));

                                            // 显示图片预览窗口
                                            ShowDraggableImageControl(cut, im_orig);

                                            // 转换坐标到显示坐标系
                                            var displayPos = ConvertOriginalToDisplayCoordinates(chr.x, chr.y);
                                            var displaySize = ConvertOriginalToDisplaySize(chr.w, chr.h);

                                            var x_y_ = ConvertDisplayToOriginalCoordinates(displayPos.X, displayPos.Y);

                                            var w_h_ = ConvertDisplayToOriginalSize(displaySize.Width, displaySize.Height);

                                            // 调用MainWindow显示选框
                                            _mainWindow?.ShowCharacterSelection(displayPos.X, displayPos.Y, displaySize.Width, displaySize.Height);

                                            found = true;
                                            break;
                                        }
                                    }
                                }

                            }

                            if (found)
                            {
                                break;
                            }


                        }





                    }
                }

                System.Diagnostics.Debug.WriteLine($"光标后字符: {chr.Character}");
            }
        }

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);
            Focus();
            Point position = e.GetPosition(this);
            SetCursorPositionFromPoint(position);
            if (Keyboard.Modifiers != ModifierKeys.Shift)
            {
                ClearSelection();
            }
            else
            {
                UpdateSelection();
            }

            // 图片中框选光标后面的第一个字符
            if (e.ChangedButton == MouseButton.Left && e.ButtonState == MouseButtonState.Pressed)
            {
                showCurrChar();
            }

            e.Handled = true;
            InvalidateVisual();
        }

        // 重写右键按下事件
        protected override void OnMouseRightButtonDown(MouseButtonEventArgs e)
        {
            base.OnMouseRightButtonDown(e);
            
            // 设置焦点
            Focus();
            
            // 获取鼠标位置并设置光标位置
            Point position = e.GetPosition(this);
            
            // 如果右键点击的位置不在当前选择区域内,则移动光标到点击位置
            // 但不清除选择区域,这样在选中文本上右键点击时不会丢失选择
            if (!IsPositionInSelection(position))
            {
                //SetCursorPositionFromPoint(position);
                // 移除以下行,不再清除选择区域
                // ClearSelection();
                InvalidateVisual();
            }
            
            e.Handled = true;
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                Point position = e.GetPosition(this);
                SetCursorPositionFromPoint(position);
                UpdateSelection();
                InvalidateVisual();
            }
        }

        #endregion

        #region 命令处理

        // 将原图坐标转换为显示坐标
        public Point ConvertOriginalToDisplayCoordinates(int originalX, int originalY)
        {
            if (_mainWindow?.ViewModel?.Image == null)
                return new Point(originalX, originalY);

            // 获取图片控件
            var imageElement = _mainWindow.image;
            if (imageElement == null)
                return new Point(originalX, originalY);

            // 获取原图尺寸
            double originalWidth = _mainWindow.ViewModel.Image.PixelWidth;
            double originalHeight = _mainWindow.ViewModel.Image.PixelHeight;

            // 获取显示尺寸
            double displayWidth = imageElement.ActualWidth;
            double displayHeight = imageElement.ActualHeight;

            // 计算缩放比例
            double scaleX = displayWidth / originalWidth;
            double scaleY = displayHeight / originalHeight;

            // 转换坐标
            double displayX = originalX * scaleX;
            double displayY = originalY * scaleY;

            return new Point(displayX, displayY);
        }

        // 将显示坐标转换为原图坐标
        public Point ConvertDisplayToOriginalCoordinates(double displayX, double displayY)
        {
            if (_mainWindow?.ViewModel?.Image == null)
                return new Point(displayX, displayY);

            // 获取图片控件
            var imageElement = _mainWindow.image;
            if (imageElement == null)
                return new Point(displayX, displayY);

            // 获取原图尺寸
            double originalWidth = _mainWindow.ViewModel.Image.PixelWidth;
            double originalHeight = _mainWindow.ViewModel.Image.PixelHeight;

            // 获取显示尺寸
            double displayWidth = imageElement.ActualWidth;
            double displayHeight = imageElement.ActualHeight;

            // 计算缩放比例
            double scaleX = displayWidth / originalWidth;
            double scaleY = displayHeight / originalHeight;

            // 反向转换坐标(除法操作)
            double originalX = displayX / scaleX;
            double originalY = displayY / scaleY;

            return new Point(originalX, originalY);
        }

        // 将原图尺寸转换为显示尺寸
        public Size ConvertOriginalToDisplaySize(int originalWidth, int originalHeight)
        {
            if (_mainWindow?.ViewModel?.Image == null)
                return new Size(originalWidth, originalHeight);

            // 获取图片控件
            var imageElement = _mainWindow.image;
            if (imageElement == null)
                return new Size(originalWidth, originalHeight);

            // 获取原图尺寸
            double imgOriginalWidth = _mainWindow.ViewModel.Image.PixelWidth;
            double imgOriginalHeight = _mainWindow.ViewModel.Image.PixelHeight;

            // 获取显示尺寸
            double displayWidth = imageElement.ActualWidth;
            double displayHeight = imageElement.ActualHeight;

            // 计算缩放比例
            double scaleX = displayWidth / imgOriginalWidth;
            double scaleY = displayHeight / imgOriginalHeight;

            // 转换尺寸
            double scaledWidth = originalWidth * scaleX;
            double scaledHeight = originalHeight * scaleY;

            return new Size(scaledWidth, scaledHeight);
        }

        // 将显示尺寸转换为原图尺寸
        public Size ConvertDisplayToOriginalSize(double displayWidth, double displayHeight)
        {
            if (_mainWindow?.ViewModel?.Image == null)
                return new Size(displayWidth, displayHeight);

            // 获取图片控件
            var imageElement = _mainWindow.image;
            if (imageElement == null)
                return new Size(displayWidth, displayHeight);

            // 获取原图尺寸
            double imgOriginalWidth = _mainWindow.ViewModel.Image.PixelWidth;
            double imgOriginalHeight = _mainWindow.ViewModel.Image.PixelHeight;

            // 获取显示尺寸
            double imgDisplayWidth = imageElement.ActualWidth;
            double imgDisplayHeight = imageElement.ActualHeight;

            // 计算缩放比例
            double scaleX = imgDisplayWidth / imgOriginalWidth;
            double scaleY = imgDisplayHeight / imgOriginalHeight;

            // 反向转换尺寸(除法操作)
            double originalWidth = displayWidth / scaleX;
            double originalHeight = displayHeight / scaleY;

            return new Size(originalWidth, originalHeight);
        }

        private void OnCopy(object sender, ExecutedRoutedEventArgs e)
        {
            if (HasSelection())
            {
                _isCut = false;
                
                // 创建DataObject来同时设置多种格式
                DataObject dataObject = new DataObject();
                
                // 设置标准文本格式(供其他程序使用)
                dataObject.SetText(GetSelectedText());
                
                // 序列化TextCharacter列表并保存自定义格式
                try
                {
                    var characters = GetSelectedTextCharacters();
                    if (characters.Count > 0)
                    {
                        string json = Newtonsoft.Json.JsonConvert.SerializeObject(characters);
                        dataObject.SetData("TextEditorCustomFormat", json);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"复制到剪贴板时出错: {ex.Message}");
                }
                
                // 一次性设置到剪贴板
                Clipboard.SetDataObject(dataObject);
            }
            e.Handled = true;
        }



        private void OnCut(object sender, ExecutedRoutedEventArgs e)
        {
            if (!IsReadOnly && HasSelection())
            {
                _isCut = true;

                // 创建DataObject来同时设置多种格式
                DataObject dataObject = new DataObject();
                
                // 设置标准文本格式(供其他程序使用)
                dataObject.SetText(GetSelectedText());

                // 序列化TextCharacter列表并保存自定义格式
                try
                {
                    var characters = GetSelectedTextCharacters();
                    if (characters.Count > 0)
                    {
                        // 序列化
                        string json = Newtonsoft.Json.JsonConvert.SerializeObject(characters);
                        dataObject.SetData("TextEditorCustomFormat", json);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"剪切到剪贴板时出错: {ex.Message}");
                }
                
                // 一次性设置到剪贴板
                Clipboard.SetDataObject(dataObject);

                DeleteSelection();
                InvalidateVisual();
            }
            e.Handled = true;
        }

        private void OnPaste(object sender, ExecutedRoutedEventArgs e)
        {
            if (!IsReadOnly)
            {
                List<TextCharacter> characters_selected = GetSelectedTextCharacters();
                
                // 尝试从剪贴板获取自定义格式数据
                bool customDataPasted = false;
                if (Clipboard.ContainsData("TextEditorCustomFormat"))
                {
                    try
                    {
                        // 反序列化
                        string json = Clipboard.GetData("TextEditorCustomFormat") as string;
                        //List<TextCharacter> characters = (List<TextCharacter>)Newtonsoft.Json.JsonConvert.DeserializeObject<List<TextCharacter>>(json);

                        List<TextCharacter> characters = new List<TextCharacter>();

                        List<JObject> ls = Newtonsoft.Json.JsonConvert.DeserializeObject<List<JObject>>(json);
                        // System.Text.Rune 字段不支持直接序列化,所以需要转换

                        foreach (var item in ls)
                        {
                            var Character = item["Character"].Value<JObject>();
                            var Value = Character["Value"].Value<int>();
                            System.Text.Rune rune = new System.Text.Rune(Value);

                            // 反序列化每个字符
                            var chr = new TextCharacter(
                                rune, // 获取第一个字符
                                item["guid"].Value<string>(),
                                item["x"].Value<int>(),
                                item["y"].Value<int>(),
                                item["w"].Value<int>(),
                                item["h"].Value<int>(),
                                item["ImageMD5"].Value<string>()
                            );
                            characters.Add(chr);
                        }

                        if (characters != null && characters.Count > 0)
                        {
                            InsertTextCharacters(characters);
                            customDataPasted = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"从剪贴板粘贴时出错: {ex.Message}");
                        customDataPasted = false;
                    }
                }

                // 如果是复制的普通文本
                if (!customDataPasted && Clipboard.ContainsText())
                {
                    string text = Clipboard.GetText();
                    if (text.Length > 0)
                    {
                        //List<TextCharacter> characters = new List<TextCharacter>();

                        //TextCharacter c = null;
                        //if (characters_selected.Count > 0)
                        //{
                        //    c = characters_selected[0];
                        //}

                        //for (int i = 0; i < text.Length;)
                        //{
                        //    Rune rune = Rune.GetRuneAt(text, i);

                        //    var chr = new TextCharacter(
                        //        rune,
                        //        c.guid,
                        //        c.x,
                        //        c.y,
                        //        c.w,
                        //        c.h,
                        //        c.ImageMD5
                        //    );
                        //    characters.Add(chr);

                        //    i += rune.Utf16SequenceLength;
                        //}

                        //if (characters != null && characters.Count > 0)
                        //{
                        //    InsertTextCharacters(characters);
                        //}

                        InsertTextCharacters(text);

                    }
                }

                if (_isCut)
                {
                    Clipboard.Clear();
                    _isCut = false; // 重置剪切状态
                }

                InvalidateVisual();
            }

            if (HasSelection())
            {
                DeleteSelection();
            }

            e.Handled = true;
        }


       public void InsertTextCharacters(string text)
       {
            if (text.Length > 0)
            {
                List<TextCharacter> characters = new List<TextCharacter>();

                TextCharacter c = null;
                if (HasSelection())
                {
                    List<TextCharacter> characters_selected = GetSelectedTextCharacters();
                    if (characters_selected.Count > 0)
                    {
                        c = characters_selected[0];
                    }
                } else
                {
                    c = GetCharacterAfterCursor();
                    if (c == null)
                    {
                        c = GetCharacterBeforeCursor();
                    }
                }

                for (int i = 0; i < text.Length;)
                {
                    Rune rune = Rune.GetRuneAt(text, i);

                    if (c != null)
                    {
                        var chr = new TextCharacter(
                            rune,
                            c.guid,
                            c.x,
                            c.y,
                            c.w,
                            c.h,
                            c.ImageMD5
                        );
                        characters.Add(chr);

                    }
                    else 
                    {
                        var chr = new TextCharacter(
                            rune,
                            Guid.NewGuid().ToString(),
                            - 1,
                            -1,
                            -1,
                            -1,
                            ""
                        );
                        characters.Add(chr);
                    }
                    i += rune.Utf16SequenceLength;
                }

                if (characters != null && characters.Count > 0)
                {
                    InsertTextCharacters(characters);
                }
            }
        }

       private void InsertTextCharacters(List<TextCharacter> characters)
        {
            if (characters == null || characters.Count == 0)
                return;
                
            // 如果有选中的文本,先删除它
            if (HasSelection())
            {
                DeleteSelection();
            }

            // 记录撤销操作
            var undoAction = new UndoAction
            {
                CursorBeforeLine = _cursorLine,
                CursorBeforeColumn = _cursorColumn
            };
            
            // 将字符插入到当前行的光标位置
            var line = _lines[_cursorLine];
            line.Characters.InsertRange(_cursorColumn, characters);
            _cursorColumn += characters.Count;
            
            // 记录添加的文本信息
            undoAction.AddedText = string.Concat(characters.Select(c => c.Character.ToString()));
            undoAction.AddedStartLine = _cursorLine;
            undoAction.AddedStartColumn = _cursorColumn - characters.Count;
            undoAction.AddedEndLine = _cursorLine;
            undoAction.AddedEndColumn = _cursorColumn;
            
            // 记录撤销操作后的光标位置
            undoAction.CursorAfterLine = _cursorLine;
            undoAction.CursorAfterColumn = _cursorColumn;

            // 添加到撤销缓冲区
            if (_undoIndex < _undoBuffer.Count - 1)
            {
                _undoBuffer.RemoveRange(_undoIndex + 1, _undoBuffer.Count - _undoIndex - 1);
            }
            _undoBuffer.Add(undoAction);
            _undoIndex = _undoBuffer.Count - 1;

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

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

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

        private void OnUndo(object sender, ExecutedRoutedEventArgs e)
        {
            if (!IsReadOnly && CanUndo())
            {
                Undo();
                InvalidateVisual();
            }
            e.Handled = true;
        }

        private void OnRedo(object sender, ExecutedRoutedEventArgs e)
        {
            if (!IsReadOnly && CanRedo())
            {
                Redo();
                InvalidateVisual();
            }
            e.Handled = true;
        }

        private void OnSelectAll(object sender, ExecutedRoutedEventArgs e)
        {
            SelectAll();
            InvalidateVisual();
            e.Handled = true;
        }

        #endregion

        #region 辅助方法

        public void SetText(string text)
        {
            _lines.Clear();
            _undoBuffer.Clear();
            _undoIndex = -1;

            if (string.IsNullOrEmpty(text))
            {
                _lines.Add(new TextLine());
            }
            else
            {
                var lines = text.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
                foreach (var line in lines)
                {
                    var textLine = new TextLine();
                    foreach (var c in line)
                    {
                        textLine.Characters.Add(new TextCharacter(c));
                    }
                    _lines.Add(textLine);
                }
            }

            _cursorLine = 0;
            _cursorColumn = 0;
            ClearSelection();
            _textChanged = true;
            InvalidateVisual();
            
            // 触发文本改变事件
            OnTextChanged();
        }

        public void SetText(JObject jsn, string md5)
        {
            _lines.Clear();
            _undoBuffer.Clear();
            _undoIndex = -1;

            if (jsn == null)
            {
                SetText(string.Empty);
            }
            else
            {
                int width = jsn.Value<int>("width");
                int height = jsn.Value<int>("height");

                var prism_wordsInfo = jsn["prism_wordsInfo"].Value<JArray>();
                foreach (var item in prism_wordsInfo) 
                {
                    JArray charInfo = item["charInfo"].Value<JArray>();
                    string line_word = item["word"].Value<string>();

                    var textLine = new TextLine();
                    foreach (var item2 in charInfo)
                    {
                        string oneChar = item2["word"].Value<string>();
                        string guid = item2["guid"].Value<string>();
                        int isDeleted = item2["isDeleted"].Value<int>();
                            // 就算是阿里云的 json ,也要先给它加入 guid
                        //if (item2["guid"] != null)
                        //{
                        //    guid = item2["guid"].Value<string>();
                        //} else
                        //{
                        //    guid = Guid.NewGuid().ToString();
                        //}

                        if (isDeleted == 1)
                        {
                            continue;
                        }

                        int x = item2["x"].Value<int>();
                        int y = item2["y"].Value<int>();
                        int w = item2["w"].Value<int>();
                        int h = item2["h"].Value<int>();

                        // 遍历 oneChar 中的每个字符
                        for (int i = 0; i < oneChar.Length;)
                        {
                            // 获取当前位置的 Rune
                            Rune rune = Rune.GetRuneAt(oneChar, i);  // 4 个字节表示单个字符

                            // 将 Rune 添加到字符列表中
                            textLine.Characters.Add(new TextCharacter(rune, guid, x, y, w, h, md5));

                            // 移动到下一个 Rune 的位置
                            i += rune.Utf16SequenceLength;
                        }

                        //Rune rune = Rune.GetRuneAt(oneChar, 0); // 4 个字节表示单个字符

                        //textLine.Characters.Add(new TextCharacter(rune, x, y, w, h, md5));
                    }

                    _lines.Add(textLine);

                }

            }

            _cursorLine = 0;
            _cursorColumn = 0;
            ClearSelection();
            _textChanged = true;
            InvalidateVisual();

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


        public List<TextLine> get_text_lines(JObject jsn, string md5)
        {
            List<TextLine> lines = new List<TextLine>();

            int width = jsn.Value<int>("width");
            int height = jsn.Value<int>("height");

            var prism_wordsInfo = jsn["prism_wordsInfo"].Value<JArray>();
            foreach (var item in prism_wordsInfo)
            {
                JObject selected_rectange = new JObject();
                if (_mode == EditorMode.ReviseEdit) // 校对模式才有选框
                {
                    selected_rectange = item["selected_rectange"].Value<JObject>();
                }

                JArray pos = item["pos"].Value<JArray>();
                JArray charInfo = item["charInfo"].Value<JArray>();


                string line_word = item["word"].Value<string>();

                var textLine = new TextLine(pos, selected_rectange);
                foreach (var item2 in charInfo)
                {
                    string oneChar = item2["word"].Value<string>();
                    string guid = item2["guid"].Value<string>();
                    // 就算是阿里云的 json ,也要先给它加入 guid
                    //if (item2["guid"] != null)
                    //{
                    //    guid = item2["guid"].Value<string>();
                    //} else
                    //{
                    //    guid = Guid.NewGuid().ToString();
                    //}
                    int x = item2["x"].Value<int>();
                    int y = item2["y"].Value<int>();
                    int w = item2["w"].Value<int>();
                    int h = item2["h"].Value<int>();

                    // 遍历 oneChar 中的每个字符
                    for (int i = 0; i < oneChar.Length;)
                    {
                        // 获取当前位置的 Rune
                        Rune rune = Rune.GetRuneAt(oneChar, i);  // 4 个字节表示单个字符

                        // 将 Rune 添加到字符列表中
                        textLine.Characters.Add(new TextCharacter(rune, guid, x, y, w, h, md5));

                        // 移动到下一个 Rune 的位置
                        i += rune.Utf16SequenceLength;
                    }

                    //Rune rune = Rune.GetRuneAt(oneChar, 0); // 4 个字节表示单个字符

                    //textLine.Characters.Add(new TextCharacter(rune, x, y, w, h, md5));
                }

                lines.Add(textLine);

            }

            return lines;
        }

        public void InsertText(JObject jsn, string md5)
        {
            _undoBuffer.Clear();
            _undoIndex = -1;

            if (jsn == null)
            {
                SetText(string.Empty);
            }
            else
            {
                //int width = jsn.Value<int>("width");
                //int height = jsn.Value<int>("height");

                //var prism_wordsInfo = jsn["prism_wordsInfo"].Value<JArray>();
                //foreach (var item in prism_wordsInfo)
                //{
                //    JObject selected_rectange = new JObject(); 
                //    if (_mode == EditorMode.ReviseEdit) // 校对模式才有选框
                //    {
                //        selected_rectange = item["selected_rectange"].Value<JObject>();
                //    }

                //    JArray pos = item["pos"].Value<JArray>();
                //    JArray charInfo = item["charInfo"].Value<JArray>();


                //    string line_word = item["word"].Value<string>();

                //    var textLine = new TextLine(pos, selected_rectange);
                //    foreach (var item2 in charInfo)
                //    {
                //        string oneChar = item2["word"].Value<string>();
                //        string guid = item2["guid"].Value<string>();
                //        // 就算是阿里云的 json ,也要先给它加入 guid
                //        //if (item2["guid"] != null)
                //        //{
                //        //    guid = item2["guid"].Value<string>();
                //        //} else
                //        //{
                //        //    guid = Guid.NewGuid().ToString();
                //        //}
                //        int x = item2["x"].Value<int>();
                //        int y = item2["y"].Value<int>();
                //        int w = item2["w"].Value<int>();
                //        int h = item2["h"].Value<int>();

                //        // 遍历 oneChar 中的每个字符
                //        for (int i = 0; i < oneChar.Length;)
                //        {
                //            // 获取当前位置的 Rune
                //            Rune rune = Rune.GetRuneAt(oneChar, i);  // 4 个字节表示单个字符

                //            // 将 Rune 添加到字符列表中
                //            textLine.Characters.Add(new TextCharacter(rune, guid, x, y, w, h, md5));

                //            // 移动到下一个 Rune 的位置
                //            i += rune.Utf16SequenceLength;
                //        }

                //        //Rune rune = Rune.GetRuneAt(oneChar, 0); // 4 个字节表示单个字符

                //        //textLine.Characters.Add(new TextCharacter(rune, x, y, w, h, md5));
                //    }

                //    _lines.Add(textLine);

                //}

                var lines = get_text_lines(jsn, md5);
                foreach(var line in lines)
                {
                    _lines.Add(line);
                }

            }

            //_cursorLine = 0;
            //_cursorColumn = 0;
            ClearSelection();
            _textChanged = true;
            InvalidateVisual();

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


        public bool saveJson(string pth_img_)
        {

            bool isModify = false;

            string m5 = MD5.ComputeFileHash(pth_img_);

            var (pth_img, pth_json) = Global.get_img_json_pthv2(pth_img_);

            if (!Path.Exists(pth_json) || !Path.Exists(pth_img))
            {
                return false;
            }

            if (_mode == EditorMode.ReviseEdit)
            {
                Global.saveJsonReviseEdit(pth_json, _lines);
                return false;
            }

            if (_mode == EditorMode.MenuSplit)
            {
                Global.saveJsonReviseEdit(pth_json, _lines);
                return false;
            }


            var jsonstr = File.ReadAllText(pth_json, new System.Text.UTF8Encoding(false));

            JObject jsn = null;
            try
            {
                jsn = JObject.Parse(jsonstr);
            }
            catch (Exception ex)
            {
                MessageBox.Show("json 解析失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            int width = jsn.Value<int>("width");
            int height = jsn.Value<int>("height");

            var prism_wordsInfo = jsn["prism_wordsInfo"].Value<JArray>();
            foreach (var item in prism_wordsInfo)
            {
                JArray charInfo = item["charInfo"].Value<JArray>();
                string line_word = item["word"].Value<string>();

                var textLine = new TextLine();
                foreach (var item2 in charInfo)
                {
                    string oneChar = item2["word"].Value<string>();
                    string guid = item2["guid"].Value<string>();
                    int x = item2["x"].Value<int>();
                    int y = item2["y"].Value<int>();
                    int w = item2["w"].Value<int>();
                    int h = item2["h"].Value<int>();

                    // 遍历 oneChar 中的每个字符
                    for (int i = 0; i < oneChar.Length;)
                    {
                        Rune rune = Rune.GetRuneAt(oneChar, i);  // 4 个字节表示单个字符

                        // 移动到下一个 Rune 的位置
                        i += rune.Utf16SequenceLength;
                    }

                    if ( _dic_deleted_char.ContainsKey(guid) ) {
                        // 是被标记逻辑删除的字符
                        item2["isDeleted"] = 1;
                        isModify = true;
                    }

                    foreach (TextLine line in _lines)
                    {
                        bool line_modify = false;
                        foreach (TextCharacter c in line.Characters)
                        {
                            string ImageMD5 = c.ImageMD5;
                            if (ImageMD5 == m5)
                            {
                                if (guid == c.guid)
                                {
                                    string c_str = c.Character.ToString();
                                    if (c_str != oneChar)
                                    {
                                        item2["word"] = c_str;
                                        line_modify = true;
                                        isModify = true;
                                    }


                                }
                            }
                        }

                        if (line_modify)
                        {
                            string new_line_word = string.Concat(line.Characters.Select(c => c.Character.ToString()));
                            item["word"] = new_line_word;
                        }
                    }

                }

            }

            if (isModify)
            {
                string jsn_str = jsn.ToString(Formatting.Indented).Replace("\r\n", "\n");
                File.WriteAllText(pth_json, jsn_str);
            }

            return isModify;
        }

        private void RenderEditor(DrawingContext drawingContext)
        {
            // 绘制背景
            drawingContext.DrawRectangle(Brushes.White, null, new Rect(0, 0, ActualWidth, ActualHeight));
            
            // 计算字体度量
            var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
            double lineHeight = FontSize * 1.2;
            double defaultCharWidth = FontSize * 0.6; // 默认字符宽度(英文)
            
            // 计算行号区域宽度
            double lineNumberWidth = LineNumbersVisible ? 40 : 0;
            
            // 绘制行号区域背景
            if (LineNumbersVisible)
            {
                drawingContext.DrawRectangle(Brushes.LightGray, null, new Rect(0, 0, lineNumberWidth, ActualHeight));
            }
            
            double textStartX = lineNumberWidth + 5; // 文本起始X坐标
            
            // 计算可见行范围
            int visibleLineCount = (int)Math.Ceiling(ActualHeight / lineHeight);
            int startLine = _scrollOffset;
            int endLine = Math.Min(_scrollOffset + visibleLineCount, _lines.Count - 1);
            
            // 高亮当前行
            if (HighlightCurrentLine && _cursorLine >= startLine && _cursorLine <= endLine)
            {
                drawingContext.DrawRectangle(Brushes.LightYellow, null, 
                    new Rect(lineNumberWidth, (_cursorLine - _scrollOffset) * lineHeight, ActualWidth - lineNumberWidth, lineHeight));
            }
            
            // 绘制文本和行号
            for (int i = startLine; i <= endLine; i++)
            {
                double y = (i - _scrollOffset) * lineHeight;
                
                // 绘制行号
                if (LineNumbersVisible)
                {
                    var lineNumberText = new FormattedText(
                        (i + 1).ToString(),
                        System.Globalization.CultureInfo.CurrentCulture,
                        FlowDirection.LeftToRight,
                        typeface,
                        FontSize,
                        Brushes.Gray,
                        VisualTreeHelper.GetDpi(this).PixelsPerDip);
                    
                    drawingContext.DrawText(lineNumberText, new Point(5, y));
                }
                
                // 绘制文本
                var line = _lines[i];
                double x = textStartX;
                
                for (int j = 0; j < line.Characters.Count; j++)
                {
                    var character = line.Characters[j];
                    
                    // 绘制选中区域背景
                    double charWidth = IsFullWidthCharacter(character.Character) ? defaultCharWidth * 2 : defaultCharWidth;
                    
                    if (HasSelection() && IsPositionSelected(i, j))
                    {
                        drawingContext.DrawRectangle(Brushes.LightBlue, null, new Rect(x, y, charWidth, lineHeight));
                    }
                    
                    // 绘制字符
                    var formattedText = new FormattedText(
                        character.Character.ToString(),
                        System.Globalization.CultureInfo.CurrentCulture,
                        FlowDirection.LeftToRight,
                        typeface,
                        FontSize,
                        character.Foreground,
                        VisualTreeHelper.GetDpi(this).PixelsPerDip);
                    
                    drawingContext.DrawText(formattedText, new Point(x, y));
                    
                    // 显示空白字符
                    if (ShowWhitespaces && character.Character.Value == ' ')
                    {
                        drawingContext.DrawLine(
                            new Pen(Brushes.LightGray, 1),
                            new Point(x + charWidth / 2, y + lineHeight / 2),
                            new Point(x + charWidth / 2, y + lineHeight / 2));
                    }
                    
                    x += charWidth;
                }
            }
            
            // 绘制光标
            if (IsFocused && _cursorLine >= startLine && _cursorLine <= endLine)
            {
                // 计算光标X坐标,考虑前面字符的宽度
                double cursorX = textStartX;
                var line = _lines[_cursorLine];
                for (int j = 0; j < _cursorColumn && j < line.Characters.Count; j++)
                {
                    cursorX += IsFullWidthCharacter(line.Characters[j].Character) ? defaultCharWidth * 2 : defaultCharWidth;
                }
                
                double cursorY = (_cursorLine - _scrollOffset) * lineHeight;
                
                drawingContext.DrawLine(
                    new Pen(Brushes.Black, 1),
                    new Point(cursorX, cursorY),
                    new Point(cursorX, cursorY + lineHeight));
            }
        }

        // 判断是否是全角字符(如中文、日文等)
        private bool IsFullWidthCharacter(System.Text.Rune r)
        {
            int value = r.Value;
            // 中文字符范围
            if (value >= 0x4E00 && value <= 0x9FFF) return true;  // CJK统一汉字
            if (value >= 0x3400 && value <= 0x4DBF) return true;  // CJK扩展A
            if (value >= 0x20000 && value <= 0x2A6DF) return true; // CJK扩展B
            if (value >= 0x2A700 && value <= 0x2B73F) return true; // CJK扩展C
            if (value >= 0x2B740 && value <= 0x2B81F) return true; // CJK扩展D
            if (value >= 0x2B820 && value <= 0x2CEAF) return true; // CJK扩展E
            if (value >= 0xF900 && value <= 0xFAFF) return true;  // CJK兼容汉字
        
            // 日文假名等
            if (value >= 0x3040 && value <= 0x309F) return true;  // 平假名
            if (value >= 0x30A0 && value <= 0x30FF) return true;  // 片假名
        
            // 全角标点和符号
            if (value >= 0xFF00 && value <= 0xFFEF) return true;  // 全角ASCII、全角标点
        
            // 其他全角字符
            if (value >= 0x3000 && value <= 0x303F) return true;  // CJK符号和标点
        
            return false;
        }

        private bool IsPositionSelected(int line, int column)
        {
            if (!HasSelection())
                return false;
                
            int startLine = Math.Min(_selectionStartLine, _selectionEndLine);
            int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn;
            int endLine = Math.Max(_selectionStartLine, _selectionEndLine);
            int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn;
            
            if (line < startLine || line > endLine)
                return false;
                
            if (line == startLine && line == endLine)
                return column >= startColumn && column < endColumn;
                
            if (line == startLine)
                return column >= startColumn;
                
            if (line == endLine)
                return column < endColumn;
                
            return true;
        }
        
        // 检查位置是否在选择区域内的辅助方法
        private bool IsPositionInSelection(Point position)
        {
            if (!HasSelection())
                return false;
                
            // 计算字体度量
            var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
            var formattedText = new FormattedText("M", System.Globalization.CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight, typeface, FontSize, Brushes.Black, VisualTreeHelper.GetDpi(this).PixelsPerDip);
            double charWidth = formattedText.Width;
            double lineHeight = formattedText.Height;
            
            // 计算点击位置对应的行列
            int clickLine = Math.Max(0, Math.Min((int)(position.Y / lineHeight) + _scrollOffset, _lines.Count - 1));
            int clickColumn = Math.Max(0, (int)((position.X - 50) / charWidth)); // 50是行号区域宽度
            
            // 获取选择区域的起始和结束位置
            int startLine = Math.Min(_selectionStartLine, _selectionEndLine);
            int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn;
            int endLine = Math.Max(_selectionStartLine, _selectionEndLine);
            int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn;
            
            // 检查点击位置是否在选择区域内
            if (clickLine < startLine || clickLine > endLine)
                return false;
                
            if (clickLine == startLine && clickLine == endLine)
            {
                return clickColumn >= startColumn && clickColumn <= endColumn;
            }
            else if (clickLine == startLine)
            {
                return clickColumn >= startColumn;
            }
            else if (clickLine == endLine)
            {
                return clickColumn <= endColumn;
            }
            else
            {
                return true; // 在中间行
            }
        }
        private void SetCursorPositionFromPoint(Point point)
        {
            if (_lines.Count <= 0)
            {
                return;
            }

            // 计算字体度量
            double lineHeight = FontSize * 1.2;
            double defaultCharWidth = FontSize * 0.6; // 默认字符宽度
            
            // 计算行号区域宽度
            double lineNumberWidth = LineNumbersVisible ? 40 : 0;
            double textStartX = lineNumberWidth + 5; // 文本起始X坐标
            
            // 计算行号,考虑滚动偏移量
            int line = (int)(point.Y / lineHeight) + _scrollOffset;
            line = Math.Max(0, Math.Min(line, _lines.Count - 1));
            
            // 计算列号,考虑字符宽度
            double x = textStartX;
            int column = 0;
            var textLine = _lines[line];
            
            // 找到光标应该在的位置
            while (column < textLine.Characters.Count && x < point.X)
            {
                x += IsFullWidthCharacter(textLine.Characters[column].Character) ? defaultCharWidth * 2 : defaultCharWidth;
                if (x > point.X)
                {
                    // 如果点击位置在字符的前半部分,光标放在字符前面
                    // 如果在后半部分,光标放在字符后面
                    double charWidth = IsFullWidthCharacter(textLine.Characters[column].Character) ? defaultCharWidth * 2 : defaultCharWidth;
                    if (point.X > x - charWidth / 2)
                        column++;
                    break;
                }
                column++;
            }
            
            // 设置光标位置
            _cursorLine = line;
            _cursorColumn = column;
            
            // 触发光标位置改变事件
            OnCursorPositionChanged(_cursorLine, _cursorColumn);
        }
        private void HandleKeyDown(KeyEventArgs e)
        {
            if (IsReadOnly)
            {
                e.Handled = true;
                return;
            }
            
            // 处理组合键
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                switch (e.Key)
                {
                    case Key.F:
                        ShowFindDialog();
                        e.Handled = true;
                        return;
                }
            }
            
            switch (e.Key)
            {
                case Key.Left:
                    if (_cursorColumn > 0)
                    {
                        _cursorColumn--;
                        showCurrChar();
                    }
                    else if (_cursorLine > 0)
                    {
                        _cursorLine--;
                        _cursorColumn = _lines[_cursorLine].Characters.Count;
                        showCurrChar();
                    }
                    break;
                    
                case Key.Right:
                    if (_cursorColumn < _lines[_cursorLine].Characters.Count)
                    {
                        _cursorColumn++;
                        showCurrChar();
                    }
                    else if (_cursorLine < _lines.Count - 1)
                    {
                        _cursorLine++;
                        _cursorColumn = 0;
                        showCurrChar();
                    }
                    break;
                    
                case Key.Up:
                    if (_cursorLine > 0)
                    {
                        _cursorLine--;
                        _cursorColumn = Math.Min(_cursorColumn, _lines[_cursorLine].Characters.Count);
                        
                        // 检查光标是否在可见区域内,如果不在则向上滚动一行
                        if (_cursorLine < _scrollOffset)
                        {
                            _scrollOffset--;
                        }
                        showCurrChar();
                    }
                    break;
                    
                case Key.Down:
                    if (_cursorLine < _lines.Count - 1)
                    {
                        _cursorLine++;
                        _cursorColumn = Math.Min(_cursorColumn, _lines[_cursorLine].Characters.Count);
                        
                        // 计算可见行数
                        double lineHeight = FontSize * 1.2;
                        int visibleLineCount = (int)(ActualHeight / lineHeight);
                        
                        // 检查光标是否在可见区域内,如果不在则向下滚动一行
                        if (_cursorLine >= _scrollOffset + visibleLineCount)
                        {
                            _scrollOffset++;
                        }
                        showCurrChar();
                    }
                    break;
                    
                case Key.Home:
                    _cursorColumn = 0;
                    break;
                    
                case Key.End:
                    _cursorColumn = _lines[_cursorLine].Characters.Count;
                    break;
                    
                case Key.Delete:
                    if (HasSelection())
                    {
                        DeleteSelection();
                    }
                    else if (_cursorColumn < _lines[_cursorLine].Characters.Count)
                    {
                        // 删除当前字符
                        TextCharacter c = _lines[_cursorLine].Characters[_cursorColumn];
                        if (c.guid != "")
                        {
                            _dic_deleted_char[c.guid] = c.Character.Value.ToString();
                        }
                        _lines[_cursorLine].Characters.RemoveAt(_cursorColumn);
                        _textChanged = true;
                        OnTextChanged();
                    }
                    else if (_cursorLine < _lines.Count - 1)
                    {
                        // 合并当前行和下一行
                        var nextLine = _lines[_cursorLine + 1];
                        _lines[_cursorLine].Characters.AddRange(nextLine.Characters);
                        _lines.RemoveAt(_cursorLine + 1);
                        _textChanged = true;
                        OnTextChanged();
                    }
                    break;
                    
                case Key.Back:
                    if (HasSelection())
                    {
                        DeleteSelection();
                    }
                    else if (_cursorColumn > 0)
                    {
                        // 删除前一个字符
                        _cursorColumn--;
                        TextCharacter c = _lines[_cursorLine].Characters[_cursorColumn];
                        if (c.guid != "")
                        {
                            _dic_deleted_char[c.guid] = c.Character.Value.ToString();
                        }
                        _lines[_cursorLine].Characters.RemoveAt(_cursorColumn);
                        _textChanged = true;
                        OnTextChanged();
                    }
                    else if (_cursorLine > 0)
                    {
                        // 合并当前行和上一行
                        _cursorColumn = _lines[_cursorLine - 1].Characters.Count;
                        _lines[_cursorLine - 1].Characters.AddRange(_lines[_cursorLine].Characters);
                        _lines.RemoveAt(_cursorLine);
                        _cursorLine--;
                        _textChanged = true;
                        OnTextChanged();
                    }
                    break;
                    
                case Key.Enter:
                    // 插入新行
                    var currentLine = _lines[_cursorLine];
                    var newLine = new TextLine();
                    
                    // 将当前行光标后的字符移到新行
                    if (_cursorColumn < currentLine.Characters.Count)
                    {
                        var remainingChars = currentLine.Characters.GetRange(_cursorColumn, currentLine.Characters.Count - _cursorColumn);
                        newLine.Characters.AddRange(remainingChars);
                        currentLine.Characters.RemoveRange(_cursorColumn, remainingChars.Count);
                    }
                    
                    _lines.Insert(_cursorLine + 1, newLine);
                    _cursorLine++;
                    _cursorColumn = 0;
                    _textChanged = true;
                    OnTextChanged();
                    break;
                    
                case Key.Tab:
                    // 插入Tab(空格)
                    for (int i = 0; i < TabSize; i++)
                    {
                        InsertText(" ");
                    }
                    break;
                    
                default:
                    e.Handled = false;
                    return;
            }
            
            // 如果按下Shift键,更新选择区域
            if (Keyboard.Modifiers == ModifierKeys.Shift)
            {
                UpdateSelection();
            }
            else
            {
                ClearSelection();
            }
            
            // 触发光标位置改变事件
            OnCursorPositionChanged(_cursorLine, _cursorColumn);
            
            // 重绘编辑器
            InvalidateVisual();
            
            e.Handled = true;
        }

        private void DeleteSelection()
        {
            if (!HasSelection())
                return;

            // 确保起始位置在结束位置之前
            int startLine = Math.Min(_selectionStartLine, _selectionEndLine);
            int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn;
            int endLine = Math.Max(_selectionStartLine, _selectionEndLine);
            int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn;

            if (startLine == endLine)
            {
                // 单行删除
                int start = Math.Min(startColumn, endColumn);
                int end = Math.Max(startColumn, endColumn);
                var line = _lines[startLine];
                if (start < line.Characters.Count)
                {
                    int length = Math.Min(end - start, line.Characters.Count - start);
                    line.Characters.RemoveRange(start, length);
                }
            }
            else
            {
                // 多行删除
                // 保留第一行开始部分
                var firstLine = _lines[startLine];
                if (startColumn < firstLine.Characters.Count)
                {
                    firstLine.Characters.RemoveRange(startColumn, firstLine.Characters.Count - startColumn);
                }

                // 保留最后一行结束部分
                var lastLine = _lines[endLine];
                List<TextCharacter> lastLineRemaining = new List<TextCharacter>();
                if (endColumn < lastLine.Characters.Count)
                {
                    lastLineRemaining = lastLine.Characters.GetRange(endColumn, lastLine.Characters.Count - endColumn);
                }

                // 删除中间行
                _lines.RemoveRange(startLine + 1, endLine - startLine);

                // 将最后一行剩余部分添加到第一行
                firstLine.Characters.AddRange(lastLineRemaining);
            }

            // 设置光标位置到选择的开始位置
            _cursorLine = startLine;
            _cursorColumn = startColumn;

            // 清除选择
            ClearSelection();
            
            // 标记文本已更改
            _textChanged = true;
            
            // 触发文本改变事件
            OnTextChanged();
            
            // 触发光标位置改变事件
            OnCursorPositionChanged(_cursorLine, _cursorColumn);
        }

        public string GetSelectedText()
        {
            if (!HasSelection())
                return string.Empty;

            // 确保起始位置在结束位置之前
            int startLine = Math.Min(_selectionStartLine, _selectionEndLine);
            int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn;
            int endLine = Math.Max(_selectionStartLine, _selectionEndLine);
            int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn;

            if (startLine == endLine)
            {
                // 单行选择
                int start = Math.Min(startColumn, endColumn);
                int end = Math.Max(startColumn, endColumn);
                var line = _lines[startLine];
                if (start < line.Characters.Count)
                {
                    int length = Math.Min(end - start, line.Characters.Count - start);
                    return string.Concat(line.Characters.GetRange(start, length).Select(c => c.Character.ToString()));
                }
                return string.Empty;
            }
            else
            {
                // 多行选择
                StringBuilder sb = new StringBuilder();

                // 第一行
                var firstLine = _lines[startLine];
                if (startColumn < firstLine.Characters.Count)
                {
                    sb.Append(string.Concat(firstLine.Characters.GetRange(startColumn, firstLine.Characters.Count - startColumn).Select(c => c.Character.ToString())));
                }
                sb.Append("\n");

                // 中间行
                for (int i = startLine + 1; i < endLine; i++)
                {
                    sb.Append(string.Concat(_lines[i].Characters.Select(c => c.Character.ToString())));
                    sb.Append("\n");
                }

                // 最后一行
                var lastLine = _lines[endLine];
                if (endColumn > 0 && lastLine.Characters.Count > 0)
                {
                    sb.Append(string.Concat(lastLine.Characters.GetRange(0, Math.Min(endColumn, lastLine.Characters.Count)).Select(c => c.Character.ToString())));
                }

                return sb.ToString();
            }
        }
        
        private List<TextCharacter> GetSelectedTextCharacters()
        {
            if (!HasSelection())
                return new List<TextCharacter>();

            // 确保起始位置在结束位置之前
            int startLine = Math.Min(_selectionStartLine, _selectionEndLine);
            int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn;
            int endLine = Math.Max(_selectionStartLine, _selectionEndLine);
            int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn;

            List<TextCharacter> result = new List<TextCharacter>();
            
            if (startLine == endLine)
            {
                // 单行选择
                int start = Math.Min(startColumn, endColumn);
                int end = Math.Max(startColumn, endColumn);
                var line = _lines[startLine];
                if (start < line.Characters.Count)
                {
                    int length = Math.Min(end - start, line.Characters.Count - start);
                    result.AddRange(line.Characters.GetRange(start, length));
                }
            }
            else
            {
                // 多行选择
                // 第一行
                var firstLine = _lines[startLine];
                if (startColumn < firstLine.Characters.Count)
                {
                    result.AddRange(firstLine.Characters.GetRange(startColumn, firstLine.Characters.Count - startColumn));
                }
                
                // 中间行
                for (int i = startLine + 1; i < endLine; i++)
                {
                    result.AddRange(_lines[i].Characters);
                }
                
                // 最后一行
                var lastLine = _lines[endLine];
                if (endColumn > 0 && lastLine.Characters.Count > 0)
                {
                    result.AddRange(lastLine.Characters.GetRange(0, Math.Min(endColumn, lastLine.Characters.Count)));
                }
            }
            
            return result;
        }

        private bool HasSelection()
        {
            // 判断是否有选中的文本
            return _selectionStartLine >= 0 && _selectionEndLine >= 0;
        }

        private bool IsSingleSelection()
        {
            if (_selectionStartColumn >= 0  && _selectionEndColumn >= 0)
            {
                return _selectionStartColumn + 1 == _selectionEndColumn;
            }

            return false;
        }

        public void ClearSelection()
        {
            // 清除选择
            _selectionStartLine = -1;
            _selectionStartColumn = -1;
            _selectionEndLine = -1;
            _selectionEndColumn = -1;
        }

        private void UpdateSelection()
        {
            // 更新选择区域
            if (_selectionStartLine < 0)
            {
                _selectionStartLine = _cursorLine;
                _selectionStartColumn = _cursorColumn;
            }
            _selectionEndLine = _cursorLine;
            _selectionEndColumn = _cursorColumn;
        }

        private void SelectAll()
        {
            // 全选
            _selectionStartLine = 0;
            _selectionStartColumn = 0;
            _selectionEndLine = _lines.Count - 1;
            _selectionEndColumn = _lines[_selectionEndLine].Characters.Count;
        }

        private bool CanUndo()
        {
            // 判断是否可以撤销
            return _undoIndex >= 0;
        }

        private bool CanRedo()
        {
            // 判断是否可以重做
            return _undoIndex < _undoBuffer.Count - 1;
        }

        private void Undo()
        {
            if (!CanUndo())
                return;

            var action = _undoBuffer[_undoIndex];

            // 恢复光标位置到操作前
            _cursorLine = action.CursorBeforeLine;
            _cursorColumn = action.CursorBeforeColumn;

            // 如果有添加的文本,需要删除它
            if (!string.IsNullOrEmpty(action.AddedText))
            {
                // 设置选择区域为添加的文本
                _selectionStartLine = action.AddedStartLine;
                _selectionStartColumn = action.AddedStartColumn;
                _selectionEndLine = action.AddedEndLine;
                _selectionEndColumn = action.AddedEndColumn;

                // 删除添加的文本
                DeleteSelection();
            }

            // 如果有删除的文本,需要恢复它
            if (!string.IsNullOrEmpty(action.RemovedText))
            {
                // 设置光标位置到删除的起始位置
                _cursorLine = action.RemovedStartLine;
                _cursorColumn = action.RemovedStartColumn;

                // 插入被删除的文本
                InsertText(action.RemovedText);

                // 恢复光标位置
                _cursorLine = action.CursorBeforeLine;
                _cursorColumn = action.CursorBeforeColumn;
            }

            // 清除选择
            ClearSelection();

            // 更新撤销索引
            _undoIndex--;

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

        private void Redo()
        {
            if (!CanRedo())
                return;

            // 更新撤销索引
            _undoIndex++;

            var action = _undoBuffer[_undoIndex];

            // 恢复光标位置到操作前
            _cursorLine = action.CursorBeforeLine;
            _cursorColumn = action.CursorBeforeColumn;

            // 如果有删除的文本,需要再次删除它
            if (!string.IsNullOrEmpty(action.RemovedText))
            {
                // 设置选择区域为删除的文本
                _selectionStartLine = action.RemovedStartLine;
                _selectionStartColumn = action.RemovedStartColumn;
                _selectionEndLine = action.RemovedEndLine;
                _selectionEndColumn = action.RemovedEndColumn;

                // 删除文本
                DeleteSelection();
            }

            // 如果有添加的文本,需要再次添加它
            if (!string.IsNullOrEmpty(action.AddedText))
            {
                // 设置光标位置到添加的起始位置
                _cursorLine = action.AddedStartLine;
                _cursorColumn = action.AddedStartColumn;

                // 插入文本
                InsertText(action.AddedText);
            }

            // 恢复光标位置到操作后
            _cursorLine = action.CursorAfterLine;
            _cursorColumn = action.CursorAfterColumn;

            // 清除选择
            ClearSelection();

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

        #endregion

        public event EventHandler TextChanged;
        public event EventHandler<CursorPositionChangedEventArgs> CursorPositionChanged;

        public virtual void OnTextChanged()
        {
            // 从_lines集合构建文本并更新TextProperty
            UpdateTextProperty();
            
            TextChanged?.Invoke(this, EventArgs.Empty);
        }

        private void UpdateTextProperty()
        {
            // 从_lines集合构建完整的文本
            StringBuilder sb = new StringBuilder();
            
            for (int i = 0; i < _lines.Count; i++)
            {
                sb.Append(string.Concat(_lines[i].Characters.Select(c => c.Character.ToString())));
                
                // 除了最后一行,每行后面都添加换行符
                if (i < _lines.Count - 1)
                    sb.Append("\n");
            }
            
            // 保存当前光标位置
            int savedCursorLine = _cursorLine;
            int savedCursorColumn = _cursorColumn;
            bool textChangedFlag = _textChanged;
            
            // 更新TextProperty,但不触发OnTextChanged回调
            SetValue(TextProperty, sb.ToString());
            
            // 恢复光标位置
            _cursorLine = savedCursorLine;
            _cursorColumn = savedCursorColumn;
            _textChanged = textChangedFlag;
        }

        public virtual void OnCursorPositionChanged(int line, int column)
        {
            CursorPositionChanged?.Invoke(this, new CursorPositionChangedEventArgs(line, column));
        }

        // 获取光标后面的第一个字符
        private TextCharacter GetCharacterAfterCursor()
        {
            if (_cursorLine >= 0 && _cursorLine < _lines.Count)
            {
                var line = _lines[_cursorLine];
                if (_cursorColumn >= 0 && _cursorColumn < line.Characters.Count)
                {
                    // 返回光标位置的字符(即光标后面的第一个字符)
                    return line.Characters[_cursorColumn];
                }
                else if (_cursorColumn == line.Characters.Count && _cursorLine + 1 < _lines.Count)
                {
                    // 如果光标在行尾,返回下一行的第一个字符
                    //var nextLine = _lines[_cursorLine + 1];
                    //if (nextLine.Characters.Count > 0)
                    //{
                    //    return nextLine.Characters[0];
                    //}
                    return null;
                }
            }
            return null; // 如果没有找到字符,返回null
        }

        private TextCharacter GetCharacterBeforeCursor()
        {
            if (_cursorLine >= 0 && _cursorLine < _lines.Count)
            {
                var line = _lines[_cursorLine];
                if (_cursorColumn > 0 && _cursorColumn <= line.Characters.Count)
                {
                    // 返回光标位置的字符(即光标后面的第一个字符)
                    return line.Characters[_cursorColumn - 1];
                }
                else
                {
                    return null;
                }
            }
            return null; // 如果没有找到字符,返回null
        }

        public void InsertText(string text)
        {
            if (string.IsNullOrEmpty(text))
                return;

            // 如果有选中的文本,先删除或修改它
            if (HasSelection())
            {
                if ( IsSingleSelection() )  // 选中了单个字符
                {
                    if (text.Length == 1)
                    {
                        // 此处是修改单个字符的情况
                        var line = _lines[_cursorLine];
                        TextCharacter c = line.Characters[_cursorColumn-1];
                        c.Character = System.Text.Rune.GetRuneAt(text, 0); // 修改字符

                        // 清除选择
                        ClearSelection();

                        _cursorColumn = _cursorColumn - 1;
                        // 触发光标位置改变事件
                        OnCursorPositionChanged(_cursorLine, _cursorColumn);

                        // 重绘编辑器
                        InvalidateVisual();

                        return;
                    }


                }

                DeleteSelection();
            }

            // 记录撤销操作
            var undoAction = new UndoAction
            {
                CursorBeforeLine = _cursorLine,
                CursorBeforeColumn = _cursorColumn
            };

            // 处理多行文本
            var lines = text.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');

            if (lines.Length == 1)
            {
                // 单行文本
                var line = _lines[_cursorLine];
                var chars = lines[0].EnumerateRunes().Select(r => new TextCharacter(r)).ToList();
                line.Characters.InsertRange(_cursorColumn, chars);
                _cursorColumn += chars.Count;

                // 记录添加的文本信息
                undoAction.AddedText = text;
                undoAction.AddedStartLine = _cursorLine;
                undoAction.AddedStartColumn = _cursorColumn - chars.Count;
                undoAction.AddedEndLine = _cursorLine;
                undoAction.AddedEndColumn = _cursorColumn;
            }
            else
            {
                // 多行文本
                var currentLine = _lines[_cursorLine];
                var remainingChars = currentLine.Characters.GetRange(_cursorColumn, currentLine.Characters.Count - _cursorColumn).ToList();
                currentLine.Characters.RemoveRange(_cursorColumn, remainingChars.Count);

                // 添加第一行
                var firstLineChars = lines[0].EnumerateRunes().Select(r => new TextCharacter(r)).ToList();
                currentLine.Characters.AddRange(firstLineChars);

                // 添加中间行
                for (int i = 1; i < lines.Length - 1; i++)
                {
                    var newLine = new TextLine();
                    newLine.Characters.AddRange(lines[i].EnumerateRunes().Select(r => new TextCharacter(r)));
                    _lines.Insert(_cursorLine + i, newLine);
                }

                // 添加最后一行和剩余字符
                var lastLine = new TextLine();
                lastLine.Characters.AddRange(lines[lines.Length - 1].EnumerateRunes().Select(r => new TextCharacter(r)));
                lastLine.Characters.AddRange(remainingChars);
                _lines.Insert(_cursorLine + lines.Length - 1, lastLine);

                // 更新光标位置
                _cursorLine += lines.Length - 1;
                _cursorColumn = lastLine.Characters.Count - remainingChars.Count;

                // 记录添加的文本信息
                undoAction.AddedText = text;
                undoAction.AddedStartLine = _cursorLine - (lines.Length - 1);
                undoAction.AddedStartColumn = _cursorColumn - firstLineChars.Count;
                undoAction.AddedEndLine = _cursorLine;
                undoAction.AddedEndColumn = _cursorColumn;
            }

            // 记录撤销操作后的光标位置
            undoAction.CursorAfterLine = _cursorLine;
            undoAction.CursorAfterColumn = _cursorColumn;

            // 添加到撤销缓冲区
            if (_undoIndex < _undoBuffer.Count - 1)
            {
                _undoBuffer.RemoveRange(_undoIndex + 1, _undoBuffer.Count - _undoIndex - 1);
            }
            _undoBuffer.Add(undoAction);
            _undoIndex = _undoBuffer.Count - 1;

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

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

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

            // 重绘编辑器
            InvalidateVisual();
        }

        #region 查找功能

        /// <summary>
        /// 显示查找对话框
        /// </summary>
        public void ShowFindDialog()
        {
            if (_findDialog == null || !_findDialog.IsLoaded)
            {
                _findDialog = new FindDialog(this);
                _findDialog.Owner = Window.GetWindow(this);
            }
            
            _findDialog.Show();
            _findDialog.Activate();
        }

        /// <summary>
        /// 获取当前选中的文本
        /// </summary>
        /// <returns></returns>
        //public string GetSelectedText()
        //{
        //    if (!HasSelection())
        //        return string.Empty;

        //    var selectedChars = GetSelectedTextCharacters();
        //    return string.Join("", selectedChars.Select(c => c.Character.ToString()));
        //}

        /// <summary>
        /// 查找下一个匹配项
        /// </summary>
        /// <param name="searchText">要查找的文本</param>
        /// <param name="matchCase">是否区分大小写</param>
        /// <param name="wholeWord">是否全字匹配</param>
        /// <returns>是否找到</returns>
        public bool FindNext(string searchText, bool matchCase, bool wholeWord)
        {
            if (string.IsNullOrEmpty(searchText))
                return false;

            // 如果搜索条件改变,重新搜索
            if (searchText != _lastSearchText || matchCase != _lastMatchCase || wholeWord != _lastWholeWord)
            {
                SearchAll(searchText, matchCase, wholeWord);
            }

            if (_findResults.Count == 0)
                return false;

            // 找到下一个匹配项
            _currentFindIndex = (_currentFindIndex + 1) % _findResults.Count;
            var result = _findResults[_currentFindIndex];
            
            // 移动光标到匹配位置
            _cursorLine = result.line;
            _cursorColumn = result.column;
            
            // 设置选择区域
            _selectionStartLine = result.line;
            _selectionStartColumn = result.column;
            _selectionEndLine = result.line;
            _selectionEndColumn = result.column + result.length;

            // 确保匹配项在可见区域内
            EnsureCursorVisible();
            
            // 重绘编辑器
            InvalidateVisual();
            
            return true;
        }

        /// <summary>
        /// 查找上一个匹配项
        /// </summary>
        /// <param name="searchText">要查找的文本</param>
        /// <param name="matchCase">是否区分大小写</param>
        /// <param name="wholeWord">是否全字匹配</param>
        /// <returns>是否找到</returns>
        public bool FindPrevious(string searchText, bool matchCase, bool wholeWord)
        {
            if (string.IsNullOrEmpty(searchText))
                return false;

            // 如果搜索条件改变,重新搜索
            if (searchText != _lastSearchText || matchCase != _lastMatchCase || wholeWord != _lastWholeWord)
            {
                SearchAll(searchText, matchCase, wholeWord);
            }

            if (_findResults.Count == 0)
                return false;

            // 找到上一个匹配项
            _currentFindIndex = (_currentFindIndex - 1 + _findResults.Count) % _findResults.Count;
            var result = _findResults[_currentFindIndex];
            
            // 移动光标到匹配位置
            _cursorLine = result.line;
            _cursorColumn = result.column;
            
            // 设置选择区域
            _selectionStartLine = result.line;
            _selectionStartColumn = result.column;
            _selectionEndLine = result.line;
            _selectionEndColumn = result.column + result.length;

            // 确保匹配项在可见区域内
            EnsureCursorVisible();
            
            // 重绘编辑器
            InvalidateVisual();
            
            return true;
        }

        /// <summary>
        /// 搜索所有匹配项
        /// </summary>
        /// <param name="searchText">要查找的文本</param>
        /// <param name="matchCase">是否区分大小写</param>
        /// <param name="wholeWord">是否全字匹配</param>
        private void SearchAll(string searchText, bool matchCase, bool wholeWord)
        {
            _findResults.Clear();
            _currentFindIndex = -1;
            _lastSearchText = searchText;
            _lastMatchCase = matchCase;
            _lastWholeWord = wholeWord;

            if (string.IsNullOrEmpty(searchText))
                return;

            StringComparison comparison = matchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;

            for (int lineIndex = 0; lineIndex < _lines.Count; lineIndex++)
            {
                var line = _lines[lineIndex];
                string lineText = string.Join("", line.Characters.Select(c => c.Character.ToString()));

                int startIndex = 0;
                while (startIndex < lineText.Length)
                {
                    int foundIndex = lineText.IndexOf(searchText, startIndex, comparison);
                    if (foundIndex == -1)
                        break;

                    // 检查全字匹配
                    if (wholeWord)
                    {
                        bool isWholeWord = true;
                        
                        // 检查前一个字符
                        if (foundIndex > 0)
                        {
                            char prevChar = lineText[foundIndex - 1];
                            if (char.IsLetterOrDigit(prevChar) || prevChar == '_')
                                isWholeWord = false;
                        }
                        
                        // 检查后一个字符
                        if (foundIndex + searchText.Length < lineText.Length)
                        {
                            char nextChar = lineText[foundIndex + searchText.Length];
                            if (char.IsLetterOrDigit(nextChar) || nextChar == '_')
                                isWholeWord = false;
                        }
                        
                        if (!isWholeWord)
                        {
                            startIndex = foundIndex + 1;
                            continue;
                        }
                    }

                    _findResults.Add((lineIndex, foundIndex, searchText.Length));
                    startIndex = foundIndex + 1;
                }
            }

            // 找到当前光标位置之后的第一个匹配项
            for (int i = 0; i < _findResults.Count; i++)
            {
                var result = _findResults[i];
                if (result.line > _cursorLine || 
                    (result.line == _cursorLine && result.column >= _cursorColumn))
                {
                    _currentFindIndex = i - 1; // 设置为前一个,因为FindNext会+1
                    return;
                }
            }
            
            // 如果没找到,设置为最后一个
            if (_findResults.Count > 0)
                _currentFindIndex = _findResults.Count - 1;
        }

        /// <summary>
        /// 确保光标在可见区域内
        /// </summary>
        private void EnsureCursorVisible()
        {
            double lineHeight = FontSize * 1.2;
            int visibleLineCount = (int)(ActualHeight / lineHeight);
            
            // 如果光标在可见区域上方
            if (_cursorLine < _scrollOffset)
            {
                _scrollOffset = _cursorLine;
            }
            // 如果光标在可见区域下方
            else if (_cursorLine >= _scrollOffset + visibleLineCount)
            {
                _scrollOffset = _cursorLine - visibleLineCount + 1;
            }
            
            // 确保滚动偏移量不为负数
            _scrollOffset = Math.Max(0, _scrollOffset);
        }

        /// <summary>
        /// 清除查找高亮
        /// </summary>
        public void ClearFindHighlight()
        {
            _findResults.Clear();
            _currentFindIndex = -1;
            InvalidateVisual();
        }

        #endregion

    }

    [Serializable]
    public class TextCharacter
    {
        [JsonIgnore]
        public System.Text.Rune Character { get; set; }                                      // 对应图中的原始字符
        
        // 用于 JSON 序列化的属性
        [JsonProperty("Character")]
        public int CharacterValue
        {
            get => Character.Value;
            set => Character = new System.Text.Rune(value);
        }
        
        public Brush Foreground { get; set; } = Brushes.Black;
        public bool IsComment { get; set; } = false;
        public bool IsKeyword { get; set; } = false;
        public bool IsString { get; set; } = false;
        public bool IsNumber { get; set; } = false;

        // 字符在图片上的坐标和宽高
        public int x { get; set; } = -1;
        public int y { get; set; } = -1;
        public int w { get; set; } = -1;
        public int h { get; set; } = -1;
        
        public string ImageMD5 { get; set; } = "";
        public string guid { get; set; } = "";

        // 添加无参构造函数用于JSON反序列化
        public TextCharacter()
        {
        }

        public TextCharacter(System.Text.Rune c)
        {
            Character = c;
        }

        public TextCharacter(System.Text.Rune c, string guid, int x, int y, int w, int h, string imageMd5)
        {
            Character = c;
            this.guid = guid;
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
            ImageMD5 = imageMd5;
        }

        // 添加一个接受char的构造函数,方便兼容现有代码
        public TextCharacter(char c)
        {
            Character = new System.Text.Rune(c);
        }
    }

    public class TextLine
    {
        public TextLine()
        {

        }

        public TextLine(JArray po, JObject rectange)
        {
            this.pos = po;
            this.selected_rectange = rectange;
        }

        public JArray pos { get; set; } = new JArray();
        public JObject selected_rectange { get; set; } = new JObject();

        public List<TextCharacter> Characters { get; set; } = new List<TextCharacter>();
    }

    public class UndoAction
    {
        public string AddedText { get; set; } = string.Empty;
        public int AddedStartLine { get; set; }
        public int AddedStartColumn { get; set; }
        public int AddedEndLine { get; set; }
        public int AddedEndColumn { get; set; }

        public string RemovedText { get; set; } = string.Empty;
        public int RemovedStartLine { get; set; }
        public int RemovedStartColumn { get; set; }
        public int RemovedEndLine { get; set; }
        public int RemovedEndColumn { get; set; }

        public int CursorBeforeLine { get; set; }
        public int CursorBeforeColumn { get; set; }
        public int CursorAfterLine { get; set; }
        public int CursorAfterColumn { get; set; }
    }
   
}