mgui-text 0.2.0

平台无关文本服务:parley 排版 / swash 字形栅格化 / glyph atlas / TextField 布局
Documentation
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
//! TextRenderObject + parley 富文本布局 + swash 栅格化 + 字形图集
//!
//! 阶段 4-P(parley):
//! - 用 `parley::FontContext` + `LayoutContext` 替代 cosmic-text 的 `FontSystem` + `Buffer`
//! - `swash::scale::ScaleContext` 栅格化(re-exported by parley)
//! - R8 灰度 glyph atlas,按行打包,key = 自造 GlyphKey
//! - paint 时按 glyph 提交 `PaintCommand::TexturedRect`
//!
//! 设计取舍:
//! - 整个 UI 层是单线程的(refs + Rc),不需要 Mutex 包裹 FontState
//! - `parley::FontContext` 不是 `Sync`,所以用 `thread_local!` 是最自然的做法
//! - **公共 API 不变**:measure_text_width / text_visual_height / paint_text_line 签名与行为保持一致

use std::cell::RefCell;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

use mgui_core::{
    BoxConstraints, Color, ElementId, LayoutContext, PaintCommand, PaintList, Point, Rect, RenderObject, Size,
};

/// Atlas 尺寸(单侧);足够装 200+ 256px glyph,或 2000+ 64px glyph
const ATLAS_SIZE: u32 = 1024;
/// glyph 之间的 padding(防止双线性采样溢出)
const ATLAS_PADDING: u32 = 1;
/// 找不到字形时的回退尺寸(占位)
const FALLBACK_ADVANCE_X: f32 = 8.0;
/// atlas 最大尺寸(再扩就清 atlas,让 glyph 重新栅格化)
const MAX_ATLAS_SIZE: u32 = 8192;

/// 默认字体栈(CSS 格式):覆盖特殊符号、CJK、emoji 的 fallback 链。
/// 旧版文本 API 的隐式默认值;`*_styled` 版 API 可显式传入自定义字体栈
/// (代码编辑器用等宽字体栈,UI 组件沿用此默认)。
pub const DEFAULT_FONT_STACK: &str =
    "system-ui, 'Segoe UI', Tahoma, 'Arial', 'Segoe UI Symbol', 'Microsoft YaHei UI', 'Segoe UI Emoji', sans-serif";

// =============================================================================
// Atlas
// =============================================================================

/// 单个 glyph 在 atlas 中的位置
#[derive(Clone, Copy, Debug)]
#[allow(dead_code)]
pub struct AtlasEntry {
    /// 归一化纹理坐标 (u0, v0, u1, v1),左下角原点(WGPU 约定)
    pub uv: [f32; 4],
    pub width: u32,
    pub height: u32,
}

/// 简单的行式(Row-based)glyph atlas
///
/// - 维护当前行 y 位置 + 行内 x 位置
/// - 放不下当前行就换行(y += row_height, x = 0, row_height = 0)
/// - 整个 atlas 满了就 `panic`(阶段 3 简化;后续 LRU/扩容)
/// - `dirty` 标记:从上次 `clear_dirty` 起,是否有新像素写入
pub struct Atlas {
    width: u32,
    height: u32,
    /// 下一个空位的 x
    next_x: u32,
    /// 当前行底部的 y
    next_y: u32,
    /// 当前行最高 glyph 的高度
    row_height: u32,
    /// 单通道灰度像素
    pixels: Vec<u8>,
    /// glyph → atlas entry
    entries: HashMap<GlyphKey, AtlasEntry>,
    /// 自上次 `clear_dirty` 起是否有新写入
    dirty: bool,
    /// 本次 dirty 的行区间 `[top, bottom)`。glyph 写入只影响少数行,
    /// 上传时整行宽度(行宽保持 atlas 宽度,满足 256 字节对齐)只发这一段,
    /// 避免每写一个 glyph 就整张(最大 64 MiB)拷贝 + 上传。
    dirty_rows: Option<(u32, u32)>,
    /// 内容版本:写 glyph / 扩容 / 清空时 +1。CPU 侧(软件光栅器)用它
    /// 判断是否需要重新读取 atlas,不参与 GPU 上传的 dirty 语义。
    generation: u64,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct GlyphKey(pub u64);

impl GlyphKey {
    /// 从 parley run + glyph 派生:font_blob_id + glyph_id + size_bits + x_bin + y_bin
    pub fn new(
        font_blob_id: usize,
        glyph_id: u16,
        size_px_bits: u32,
        x_bin: i32,
        y_bin: i32,
        subpixel_bits: u8,
    ) -> Self {
        let mut h = DefaultHasher::new();
        font_blob_id.hash(&mut h);
        glyph_id.hash(&mut h);
        size_px_bits.hash(&mut h);
        x_bin.hash(&mut h);
        y_bin.hash(&mut h);
        subpixel_bits.hash(&mut h);
        GlyphKey(h.finish())
    }
}

impl Atlas {
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            next_x: 0,
            next_y: 0,
            row_height: 0,
            pixels: vec![0; (width * height) as usize],
            entries: HashMap::new(),
            dirty: false,
            dirty_rows: None,
            generation: 1,
        }
    }

    /// 扩容到 2× 尺寸,旧 glyph 保持在左上角象限。
    /// 已有 entry 的 uv 都除以 2(归一化到新尺寸)。
    fn expand_2x(&mut self) {
        let new_w = (self.width * 2).min(MAX_ATLAS_SIZE);
        let new_h = (self.height * 2).min(MAX_ATLAS_SIZE);
        if new_w == self.width && new_h == self.height {
            return; // 已经封顶,不该走到这(外层已拦截)
        }
        let old_w = self.width;
        let old_h = self.height;
        let new_size = (new_w * new_h) as usize;
        let mut new_pixels = vec![0u8; new_size];
        // 把旧像素复制到新 buffer 的左上角
        for row in 0..old_h as usize {
            let src_start = row * old_w as usize;
            let dst_start = row * new_w as usize;
            new_pixels[dst_start..dst_start + old_w as usize]
                .copy_from_slice(&self.pixels[src_start..src_start + old_w as usize]);
        }
        self.pixels = new_pixels;
        // 所有 entry 的 uv 都除以 2(归一化到新尺寸,旧 glyph 保持左上角相对位置)
        let scale_u = old_w as f32 / new_w as f32; // = 0.5 when 2x
        let scale_v = old_h as f32 / new_h as f32;
        for entry in self.entries.values_mut() {
            entry.uv[0] *= scale_u;
            entry.uv[1] *= scale_v;
            entry.uv[2] *= scale_u;
            entry.uv[3] *= scale_v;
        }
        self.width = new_w;
        self.height = new_h;
        self.dirty = true;
        self.dirty_rows = Some((0, new_h));
        self.generation += 1;
        // 归一化 UV 变了:所有 layer 缓存的 PaintList 必须重画
        mgui_core::element::request_full_repaint();
    }

    /// atlas 已满且无法再扩:清空所有 glyph,让后续按需重新栅格化。
    /// 触发条件只有极端情况(8K atlas 也装不下),此时性能比 panic 重要。
    fn clear_atlas(&mut self) {
        self.entries.clear();
        self.pixels.fill(0);
        self.next_x = 0;
        self.next_y = 0;
        self.row_height = 0;
        self.dirty = true;
        self.dirty_rows = Some((0, self.height));
        self.generation += 1;
        mgui_core::element::request_full_repaint();
    }

    /// 查询或插入一个 glyph
    ///
    /// `bitmap` 是 R8 灰度数据,长度 = `w * h`
    pub fn get_or_insert(&mut self, key: GlyphKey, bitmap: &[u8], w: u32, h: u32) -> AtlasEntry {
        if let Some(&e) = self.entries.get(&key) {
            return e;
        }
        // 申请空间:加 padding 防止双线性采样溢出
        let alloc_w = w + ATLAS_PADDING * 2;
        let alloc_h = h + ATLAS_PADDING * 2;
        // 放不下当前行 → 换行
        if self.next_x + alloc_w > self.width {
            self.next_x = 0;
            self.next_y += self.row_height;
            self.row_height = 0;
        }
        if self.next_y + alloc_h > self.height {
            // atlas 满了:自动扩容 2×,若已到 MAX 则清空(性能 > panic)
            if self.width >= MAX_ATLAS_SIZE && self.height >= MAX_ATLAS_SIZE {
                self.clear_atlas();
            } else {
                self.expand_2x();
            }
            // 扩容/清空后重试(递归一次,再满就是 bug)
            return self.get_or_insert(key, bitmap, w, h);
        }
        let dst_x = self.next_x + ATLAS_PADDING;
        let dst_y = self.next_y + ATLAS_PADDING;

        // 写入像素(R8)
        for row in 0..h {
            let src_start = (row * w) as usize;
            let src_end = src_start + w as usize;
            let dst_row = (dst_y + row) as usize * self.width as usize + dst_x as usize;
            self.pixels[dst_row..dst_row + w as usize].copy_from_slice(&bitmap[src_start..src_end]);
        }

        // 归一化坐标(WGPU 纹理坐标 v 朝上,所以我们用 (0,0) = 左下)
        let u0 = dst_x as f32 / self.width as f32;
        let v0 = dst_y as f32 / self.height as f32;
        let u1 = (dst_x + w) as f32 / self.width as f32;
        let v1 = (dst_y + h) as f32 / self.height as f32;

        let entry = AtlasEntry { uv: [u0, v0, u1, v1], width: w, height: h };
        self.entries.insert(key, entry);
        self.next_x += alloc_w;
        if alloc_h > self.row_height {
            self.row_height = alloc_h;
        }
        // 写入了新像素 → 标 dirty 行区间(renderer 只上传这几行)
        self.mark_rows_written(dst_y, h);
        self.generation += 1;
        entry
    }

    /// 记录一次 glyph 写入影响的行区间(与已有区间合并)
    fn mark_rows_written(&mut self, y: u32, h: u32) {
        self.dirty = true;
        let end = (y + h).min(self.height);
        self.dirty_rows = Some(match self.dirty_rows {
            Some((top, bottom)) => (top.min(y), bottom.max(end)),
            None => (y, end),
        });
    }

    /// 整个 atlas 像素(用于上传到 GPU)
    pub fn pixels(&self) -> &[u8] {
        &self.pixels
    }

    /// 已有 glyph 数量
    #[allow(dead_code)]
    pub fn glyph_count(&self) -> usize {
        self.entries.len()
    }

    /// 是否有新像素写入(自上次 `clear_dirty` 以来)
    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// 清 dirty 标记(GPU 已上传后调用)
    pub fn clear_dirty(&mut self) {
        self.dirty = false;
        self.dirty_rows = None;
    }
}

// =============================================================================
// FontState(全局 thread_local) — parley 版
// =============================================================================

/// 栅格化后的 glyph 位图(缓存,避免每次重 rasterize)
#[derive(Clone)]
struct RasterGlyph {
    data: Vec<u8>,
    width: u32,
    height: u32,
    /// 栅格化时 glyph 相对 baseline 的 left/top offset(物理像素)
    left: i32,
    top: i32,
    /// 最近一次被绘制/插入的时钟(LRU 预算用)
    last_used: u64,
}

/// shaped-line 缓存 key:
/// `(text, raster_px_bits, max_width_bits, font_stack_hash)`。
type LineCacheKey = (TextKey, u32, Option<u32>, u64);

/// shaped-line 缓存条目(带访问时钟,用于 LRU 淘汰)。
struct LineCacheEntry {
    line: std::rc::Rc<ShapedLine>,
    last_used: u64,
}

/// 文字渲染所需全局状态 — parley + swash 版
pub struct FontState {
    pub font_cx: parley::FontContext,
    pub layout_cx: parley::LayoutContext<()>,
    pub scale_cx: swash::scale::ScaleContext,
    pub atlas: Atlas,
    /// 栅格化缓存:GlyphKey → 位图
    raster_cache: HashMap<GlyphKey, RasterGlyph>,
    /// 位图缓存当前总字节(增量维护,预算判断 O(1))
    raster_cache_bytes: usize,
    /// shaped-line 缓存(fps 优化):shape 一次,之后每帧只查表。
    ///
    /// **为什么必须有**:parley shaping 也不是零成本(每行 0.05~0.5ms+),
    /// UI 文本几乎不变 — 每帧重 shape 纯浪费。debug build 放大 10-30 倍。
    /// key = (TextKey, raster_px_bits, max_width_bits, font_stack_hash);
    /// raster_px 已含 dpr → dpr 变化自动 miss;font_stack hash → 不同字体栈互不串缓存
    line_cache: HashMap<LineCacheKey, LineCacheEntry>,
    /// 富文本 shaped-line 缓存(P3-3)
    rich_cache: HashMap<RichCacheKey, RichCacheEntry>,
    /// 富文本缓存访问时钟
    rich_clock: u64,
    /// 全局访问时钟(LRU)
    line_clock: u64,
    /// glyph 位图缓存的访问时钟(LRU 预算)
    glyph_clock: u64,
    /// shaping 执行次数(测试观测缓存命中用)
    pub shape_calls: usize,
}

impl FontState {
    fn new() -> Self {
        Self {
            font_cx: parley::FontContext::new(),
            layout_cx: parley::LayoutContext::<()>::new(),
            scale_cx: swash::scale::ScaleContext::new(),
            atlas: Atlas::new(ATLAS_SIZE, ATLAS_SIZE),
            raster_cache: HashMap::new(),
            raster_cache_bytes: 0,
            line_cache: HashMap::new(),
            rich_cache: HashMap::new(),
            rich_clock: 0,
            line_clock: 0,
            glyph_clock: 0,
            shape_calls: 0,
        }
    }
}

thread_local! {
    static FONT_STATE: RefCell<Option<FontState>> = const { RefCell::new(None) };    /// 文字栅格化 DPR(物理/逻辑像素比)。
    ///
    /// **模糊修复**:glyph 必须按物理分辨率栅格化,否则 dpr=1.25/1.5 的
    /// Windows 缩放下,低分辨率位图被 GPU 拉伸 → 文字发虚。
    /// runtime 在每次 CPU paint 前调 `set_text_dpr(gpu.scale_factor)`。
    static TEXT_DPR: std::cell::Cell<f32> = const { std::cell::Cell::new(1.0) };
}

/// 设置文字栅格化 DPR(在 CPU paint 之前调用;≤0 视为 1.0)
pub fn set_text_dpr(dpr: f32) {
    TEXT_DPR.with(|c| c.set(if dpr > 0.0 { dpr } else { 1.0 }));
}

fn text_dpr() -> f32 {
    TEXT_DPR.with(|c| c.get())
}

/// 在全局 FontState 上执行操作(惰性初始化)
pub fn with_font<F, R>(f: F) -> R
where
    F: FnOnce(&mut FontState) -> R,
{
    FONT_STATE.with(|cell| {
        let mut opt = cell.borrow_mut();
        if opt.is_none() {
            *opt = Some(FontState::new());
        }
        f(opt.as_mut().unwrap())
    })
}

// =============================================================================
// Shaped-line 缓存(fps 优化)
// =============================================================================

/// 缓存条目上限。超过按 LRU 淘汰最旧 1/4(不是整体 clear)。
///
/// 整体 clear 会让下一次所有可见行全部重新 shape,造成周期性卡顿;
/// 只淘汰最久未用条目可以保留仍在上屏的文本。
const LINE_CACHE_LIMIT: usize = 4096;

/// 超限时回收到本上限(LRU 保留最近 3/4)。
const LINE_CACHE_TARGET: usize = LINE_CACHE_LIMIT - LINE_CACHE_LIMIT / 4;

/// 淘汰最久未访问的条目,使缓存回到 `LINE_CACHE_TARGET`。
fn evict_line_cache_lru(fs: &mut FontState) {
    if fs.line_cache.len() <= LINE_CACHE_TARGET {
        return;
    }
    let mut by_age: Vec<(u64, LineCacheKey)> = fs.line_cache.iter().map(|(k, v)| (v.last_used, k.clone())).collect();
    by_age.sort_unstable_by_key(|&(last_used, _)| last_used);
    let remove = fs.line_cache.len().saturating_sub(LINE_CACHE_TARGET);
    for (_, key) in by_age.into_iter().take(remove) {
        fs.line_cache.remove(&key);
    }
}

/// glyph 位图缓存预算(CPU 内存)。条目可在缺字时按需重建,因此可以安全淘汰。
const RASTER_CACHE_BUDGET_BYTES: usize = 32 * 1024 * 1024;
/// 回收目标水位(留 headroom,避免每插入一个 glyph 都触发全表扫描)。
const RASTER_CACHE_TARGET_BYTES: usize = RASTER_CACHE_BUDGET_BYTES * 3 / 4;

/// 插入一个栅格化位图并维护字节计数/预算。
fn insert_raster_glyph(fs: &mut FontState, key: GlyphKey, mut glyph: RasterGlyph) {
    fs.glyph_clock += 1;
    glyph.last_used = fs.glyph_clock;
    let bytes = glyph.data.len();
    if let Some(old) = fs.raster_cache.insert(key, glyph) {
        fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(old.data.len());
    }
    fs.raster_cache_bytes += bytes;
    trim_raster_cache(fs);
}

/// 超预算时按 LRU 淘汰 glyph 位图。
///
/// paint 路径在缺字时可以用 `ShapedRun` 里的字体上下文重新栅格化,
/// 所以淘汰不会导致文字缺失。
fn trim_raster_cache(fs: &mut FontState) {
    if fs.raster_cache_bytes <= RASTER_CACHE_BUDGET_BYTES {
        return;
    }
    let mut candidates: Vec<(u64, GlyphKey, usize)> =
        fs.raster_cache.iter().map(|(&key, g)| (g.last_used, key, g.data.len())).collect();
    candidates.sort_unstable_by_key(|&(last_used, _, _)| last_used);
    for (_, key, bytes) in candidates {
        if fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES {
            break;
        }
        fs.raster_cache.remove(&key);
        fs.raster_cache_bytes = fs.raster_cache_bytes.saturating_sub(bytes);
    }
}

/// shaped-line 缓存 key 的文本部分。
///
/// - `Owned`:普通 `&str` 调用方(每次查询克隆一份,与旧行为一致)
/// - `Shared`:命令携带整串 `Rc<str>` + 可选字节区间 —— 命中路径只 bump
///   引用计数,编辑器逐语法 span 绘制(整行共享)时零字符串分配
#[derive(Clone, PartialEq, Eq, Hash)]
enum TextKey {
    Owned(String),
    Shared(std::rc::Rc<str>, Option<(usize, usize)>),
}

impl TextKey {
    fn owned(text: &str) -> Self {
        TextKey::Owned(text.to_string())
    }
}

/// 缓存后的单个 glyph(shaping 结果,物理像素坐标系)
struct ShapedGlyph {
    /// 自造栅格化 key(font_blob_id + glyph_id + size + subpixel)
    raster_key: GlyphKey,
    /// 原始 glyph id(栅格化缓存被预算淘汰后按需重建用)
    glyph_id: u16,
    /// pen x(parley positioned_glyphs 的 g.x,物理像素)
    x: f32,
    /// advance 宽度(物理像素)
    w: f32,
    /// baseline y(parley positioned_glyphs 的 g.y,物理像素)
    #[allow(dead_code)]
    y: f32,
    /// ascent(该行/该 run 向上延伸的物理像素)
    ascent: f32,
    /// descent(该 run 向下延伸的物理像素)
    descent: f32,
    /// 该 glyph 所属 cluster 的起始字节偏移(相对 shape_text 的完整输入文本)。
    /// glyph → 源文本字节映射,编辑器光标/选区的字节偏移 ↔ x 坐标换算依赖它。
    cluster: u32,
}

/// 缓存后的一行(单行文本 = 1 个 run)
struct ShapedRun {
    glyphs: Vec<ShapedGlyph>,
    /// 该行 baseline y(物理像素)— 行间定位不可缺:缺了它多行会塌到同一 y 重叠
    baseline_y: f32,
    /// 本 run 的字体(栅格化缓存 miss 时按需重建 glyph 位图)
    font: parley::Font,
    /// 字体变体坐标(同上)
    norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
    /// 物理字号(同上)
    raster_size: f32,
}

/// 缓存后的一整段 shaped 文本
struct ShapedLine {
    runs: Vec<ShapedRun>,
    /// max(x + w)(物理像素);无 glyph = 0
    max_x: f32,
    /// max(baseline_y + descent)(物理像素);多行总视觉高
    #[allow(dead_code)]
    max_y: f32,
    /// soft wrap 后的每条视觉行字节区间(相对输入文本);空文本 = [(0,0)]
    visual_lines: Vec<(usize, usize)>,
}

/// 取 shaped line(带缓存):命中 O(1),miss 时 parley shaping 后插入。
///
/// `raster_px` 是物理字号(= 逻辑字号 × dpr);key 含它 → dpr 变化自动 miss。
/// `max_width_px` 是逻辑像素宽度上限(soft wrap);0 或 None = 单行不换行。
fn shape_text(
    fs: &mut FontState,
    text: &str,
    raster_px: f32,
    max_width_px: Option<f32>,
    font_stack: &str,
) -> std::rc::Rc<ShapedLine> {
    shape_text_keyed(fs, text, TextKey::owned(text), raster_px, max_width_px, font_stack)
}

/// `shape_text` 的显式 key 版本:共享文本(Rc + 区间)由调用方直接传 key,
/// 缓存命中路径不再克隆全文。
fn shape_text_keyed(
    fs: &mut FontState,
    text: &str,
    text_key: TextKey,
    raster_px: f32,
    max_width_px: Option<f32>,
    font_stack: &str,
) -> std::rc::Rc<ShapedLine> {
    let font_stack_hash = {
        let mut h = DefaultHasher::new();
        font_stack.hash(&mut h);
        h.finish()
    };
    let key = (text_key, raster_px.to_bits(), max_width_px.map(|w| w.to_bits()), font_stack_hash);
    if let Some(entry) = fs.line_cache.get_mut(&key) {
        fs.line_clock += 1;
        entry.last_used = fs.line_clock;
        return std::rc::Rc::clone(&entry.line);
    }

    fs.shape_calls += 1;
    let dpr = text_dpr();

    // parley 坐标系:scale=1.0, FontSize=逻辑像素,layout 输出=逻辑像素
    // 后续 glyph 坐标 × dpr 转回物理像素(栅格化需要)
    let scale = 1.0f32;
    let font_size_px = raster_px / dpr;

    // parley:单行或软换行。wrap_opt 用逻辑像素,和 layout 输出坐标系一致
    let wrap_opt = max_width_px.filter(|&w| w > 0.0);

    let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, scale, true);
    builder.push_default(parley::StyleProperty::FontSize(font_size_px));
    builder.push_default(parley::StyleProperty::LineHeight(1.2));
    // CSS 格式字体栈:fontique 会按顺序 fallback(CJK/symbol 字符能落到后备字体)
    builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
        font_stack,
    ))));
    // KeepAll:CJK 字间不拆(只在空格/标点处断);OverflowWrap::Anywhere 防止超长拉丁词撑破容器
    builder.push_default(parley::StyleProperty::WordBreak(parley::swash::text::WordBreakStrength::KeepAll));
    builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
    let mut layout: parley::Layout<()> = builder.build(text);
    layout.break_all_lines(wrap_opt);
    layout.align(wrap_opt, parley::Alignment::Start, parley::AlignmentOptions::default());

    // 遍历 parley 的 lines → GlyphRun → positioned_glyphs
    // 注意:parley 现在输出逻辑像素坐标(scale=dpr, FontSize=逻辑像素)
    // 我们后面 pipeline 全用物理像素,所以这里统一 × dpr
    let mut runs = Vec::new();
    let mut max_x = 0.0f32;
    let mut max_y = 0.0f32;
    let mut visual_lines = Vec::new();

    for line in layout.lines() {
        // 视觉行覆盖的源文本字节区间(用于 TextField soft wrap 的光标/命中映射)
        let mut line_start = usize::MAX;
        let mut line_end = 0usize;
        for run in line.runs() {
            let range = run.text_range();
            line_start = line_start.min(range.start);
            line_end = line_end.max(range.end);
        }
        visual_lines.push(if line_start == usize::MAX { (0, 0) } else { (line_start, line_end) });

        let line_m = line.metrics();
        let baseline_y = line_m.baseline * dpr; // 逻辑 → 物理

        for item in line.items() {
            let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
                continue;
            };

            // 每个 run 有自己的 ascent/descent(字体 fallback 时不同 run 字体不同)
            let run_metrics = gr.run().metrics();
            let ascent = run_metrics.ascent * dpr;
            let descent = run_metrics.descent * dpr;
            let font_size_logical = gr.run().font_size(); // 逻辑像素
            let font_size_phys = font_size_logical * dpr; // 物理像素(栅格化用)
            let font_blob_id = gr.run().font().data.id() as usize; // Blob<u8>::id() 全局唯一

            // 每个 glyph 拿 x/y/advance + 自造 raster key + 所属 cluster 字节偏移。
            // 遍历 visual clusters(GlyphRun::glyphs() 的内部实现即
            // run.visual_clusters().flat_map(cluster.glyphs());单一默认样式时
            // GlyphRun 覆盖整个 run,skip/take 不生效)。glyph x = cluster 相对 x + pen,
            // pen 按逐 glyph advance 累计 —— 与 positioned_glyphs 语义逐位一致,
            // 额外获得 glyph → 源文本字节偏移映射(cluster.text_range().start)。
            let mut run_glyphs: Vec<ShapedGlyph> = Vec::new();
            // 预先拿 normalized coords 供栅格化用(按 run 共享,供缓存淘汰后重建)
            let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> = gr.run().normalized_coords().to_vec().into();
            let run_font = gr.run().font().clone();
            let mut pen_x = gr.offset();
            let run_baseline = gr.baseline();
            for cluster in gr.run().visual_clusters() {
                let cluster_byte = cluster.text_range().start as u32;
                for g in cluster.glyphs() {
                    let glyph_id = g.id; // parley 0.4 GlyphId = u16
                    let size_bits = font_size_phys.to_bits(); // raster key 用物理像素
                    let x_bin = 0; // 暂时不用 subpixel precision(后续优化)
                    let y_bin = 0;
                    let raster_key = GlyphKey::new(font_blob_id, glyph_id, size_bits, x_bin, y_bin, 0);
                    // 栅格化缓存 miss 时即时栅格化
                    if !fs.raster_cache.contains_key(&raster_key) {
                        if let Some(rg) =
                            rasterize_one_glyph(&run_font, font_size_phys, glyph_id, &norm_coords, &mut fs.scale_cx)
                        {
                            insert_raster_glyph(fs, raster_key, rg);
                        }
                    }
                    let gx = pen_x + g.x;
                    run_glyphs.push(ShapedGlyph {
                        raster_key,
                        glyph_id,
                        x: gx * dpr,                   // 逻辑 → 物理
                        w: g.advance * dpr,            // 逻辑 → 物理
                        y: (run_baseline + g.y) * dpr, // 逻辑 → 物理
                        ascent,
                        descent,
                        cluster: cluster_byte,
                    });
                    max_x = max_x.max((gx + g.advance) * dpr);
                    max_y = max_y.max(baseline_y + descent);
                    pen_x += g.advance;
                }
            }

            if !run_glyphs.is_empty() {
                runs.push(ShapedRun {
                    glyphs: run_glyphs,
                    baseline_y,
                    font: run_font,
                    norm_coords,
                    raster_size: font_size_phys,
                });
            }
        }
    }

    // 无任何 glyph(纯空白文本):给合理的兜底 max_y
    if max_y == 0.0 {
        max_y = raster_px * 1.2;
    }

    let line = std::rc::Rc::new(ShapedLine { runs, max_x, max_y, visual_lines });
    if fs.line_cache.len() >= LINE_CACHE_LIMIT {
        evict_line_cache_lru(fs);
    }
    fs.line_clock += 1;
    let entry = LineCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.line_clock };
    fs.line_cache.insert(key, entry);
    line
}

/// Atlas 当前状态快照
///
/// Renderer 拿到 snapshot 后决定:
/// - size 变化 → 重建 GPU texture
/// - dirty 变化 → `write_texture` 上传 `dirty_y` 行区间(`pixels` 已按
///   整行宽度打包,行宽 = atlas 宽度 → 满足 256 字节对齐)
/// - 否则 → 复用 cache 的 view/sampler
#[derive(Clone)]
pub struct AtlasSnapshot {
    pub width: u32,
    pub height: u32,
    pub dirty: bool,
    /// 本次 dirty 的行区间 `[top, bottom)`(整行宽度);其余行 GPU 侧保持原值。
    /// `dirty=false` 时为 `(0, 0)`。
    pub dirty_y: (u32, u32),
    /// 像素数据:`dirty_y` 区间内的整行(长度 = width × 行数),不 dirty 时 None
    pub pixels: Option<Vec<u8>>,
}

/// 拿到 atlas 快照
pub fn atlas_snapshot() -> AtlasSnapshot {
    with_font(|fs| {
        let dirty = fs.atlas.is_dirty();
        let (y0, y1) = if dirty {
            let (a, b) = fs.atlas.dirty_rows.unwrap_or((0, fs.atlas.height));
            (a.min(fs.atlas.height), b.min(fs.atlas.height))
        } else {
            (0, 0)
        };
        let pixels = if dirty {
            let w = fs.atlas.width as usize;
            Some(fs.atlas.pixels()[(y0 as usize * w)..(y1 as usize * w)].to_vec())
        } else {
            None
        };
        AtlasSnapshot { width: fs.atlas.width, height: fs.atlas.height, dirty, dirty_y: (y0, y1), pixels }
    })
}

/// 清 atlas dirty 标记(GPU 上传后调用)
pub fn atlas_clear_dirty() {
    with_font(|fs| {
        fs.atlas.clear_dirty();
    })
}

/// atlas 内容版本(写 glyph/扩容/清空时递增,与 GPU dirty 独立)
pub fn atlas_generation() -> u64 {
    with_font(|fs| fs.atlas.generation)
}

/// atlas 汇总(Inspector/诊断用;不拷贝像素)
#[derive(Clone, Copy, Debug, Default)]
pub struct AtlasStats {
    pub width: u32,
    pub height: u32,
    pub glyph_count: usize,
    /// 已分配到的最底行(包含当前行的行高)
    pub used_height: u32,
    pub dirty: bool,
}

pub fn atlas_stats() -> AtlasStats {
    with_font(|fs| {
        let atlas = &fs.atlas;
        AtlasStats {
            width: atlas.width,
            height: atlas.height,
            glyph_count: atlas.entries.len(),
            used_height: (atlas.next_y + atlas.row_height).min(atlas.height),
            dirty: atlas.dirty,
        }
    })
}

/// CPU 侧直接访问 atlas 像素(R8,行优先,左上原点,零拷贝)。
///
/// 软件光栅器逐 glyph 采样用:闭包内**不得**再调用 shaping / 栅格化 API
/// (`with_font` 的 RefCell 正被借用,重入会 panic)。
pub fn with_atlas<R>(f: impl FnOnce(u32, u32, &[u8]) -> R) -> R {
    with_font(|fs| {
        let atlas = &fs.atlas;
        f(atlas.width, atlas.height, &atlas.pixels)
    })
}

// =============================================================================
// TextRenderObject
// =============================================================================

pub struct TextRenderObject {
    text: String,
    size_px: f32,
    color: Color,
    /// soft wrap 最大宽度(逻辑像素);None = 单行不换行
    max_width: Option<f32>,
    /// max_width 是否用户显式设置(true = 布局不刷新;false = 每轮 layout 用
    /// 当前约束刷新,避免"第一次遇到的窄约束"永久粘滞导致意外折行叠影)
    max_width_explicit: bool,
    /// layout 阶段算的尺寸
    size: Size,
    element_id: Option<ElementId>,
}

impl TextRenderObject {
    pub fn new(text: String, size_px: f32, color: Color) -> Self {
        Self { text, size_px, color, max_width: None, max_width_explicit: false, size: Size::ZERO, element_id: None }
    }

    pub fn with_max_width(mut self, max_width: f32) -> Self {
        self.max_width = Some(max_width);
        self.max_width_explicit = true;
        self
    }

    pub fn set_max_width(&mut self, max_width: Option<f32>) {
        self.max_width = max_width;
        self.max_width_explicit = max_width.is_some();
    }

    /// 内部:测文字尺寸(走 shape_text 缓存,与 paint 同源)
    fn measure(&self) -> Size {
        let dpr = text_dpr();
        let raster_px = self.size_px * dpr;
        let width = with_font(|fs| {
            let line = shape_text(fs, &self.text, raster_px, self.max_width, DEFAULT_FONT_STACK);
            let max_x = line.max_x / dpr;
            if max_x == 0.0 && !self.text.is_empty() {
                self.text.chars().count() as f32 * FALLBACK_ADVANCE_X
            } else {
                max_x
            }
        });
        // height 用 text_visual_height(同源于 paint_text_line 的 row_max_top 对齐)
        // ——单行/多行都走这里,容器居中永不漂
        let height = text_visual_height(&self.text, self.size_px, self.max_width);
        Size::new(width, height)
    }
}

/// 阶段 2-E:测一段文本的宽度(shaping 后,逻辑像素)
///
/// TextField 光标定位用:光标 x = 文本起点 + `measure_text_width(value[..cursor])`
pub fn measure_text_width(text: &str, size_px: f32) -> f32 {
    measure_text_width_styled(text, size_px, DEFAULT_FONT_STACK)
}

/// `measure_text_width` 的字体栈参数化版本(编辑器等宽字体栈用)
pub fn measure_text_width_styled(text: &str, size_px: f32, font_stack: &str) -> f32 {
    if text.is_empty() {
        return 0.0;
    }
    with_font(|fs| {
        // 与 paint_text_line 同一 shape 缓存 → 宽度恒一致(TextField 光标依赖)
        let dpr = text_dpr();
        let raster_px = size_px * dpr;
        let line = shape_text(fs, text, raster_px, None, font_stack);
        let w = line.max_x / dpr;
        if w == 0.0 {
            text.chars().count() as f32 * FALLBACK_ADVANCE_X
        } else {
            w
        }
    })
}

/// 单行文本真实视觉高度(parley 版)
///
/// TextField/ButtonRO 等容器用它算垂直居中,保证 paint 出来后 glyph visual center
/// 跟容器 center 对齐。
///
/// parley 直接给 ascent/descent/baseline:
///   视觉顶 = baseline_y - ascent  (第一行)
///   视觉底 = baseline_y + descent (每行 max)
/// 不需要 cosmic-text 时代的"去栅格化拿 placement.top"那套 hack。
pub fn text_visual_height(text: &str, size_px: f32, max_width_px: Option<f32>) -> f32 {
    text_visual_height_styled(text, size_px, max_width_px, DEFAULT_FONT_STACK)
}

/// `text_visual_height` 的字体栈参数化版本
pub fn text_visual_height_styled(text: &str, size_px: f32, max_width_px: Option<f32>, font_stack: &str) -> f32 {
    if text.is_empty() {
        return size_px;
    }
    with_font(|fs| {
        let dpr = text_dpr();
        let raster_px = size_px * dpr;
        let line = shape_text(fs, text, raster_px, max_width_px, font_stack);

        if line.runs.is_empty() {
            return size_px;
        }

        // 首行视觉顶 = baseline - ascent
        let first_run = &line.runs[0];
        let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
        let first_baseline = first_run.baseline_y;
        let visual_top = first_baseline - first_ascent;

        // 所有 run 算视觉底 = max(baseline_y + descent)
        let mut visual_bottom = 0.0f32;
        for run in &line.runs {
            for sg in &run.glyphs {
                let bottom = run.baseline_y + sg.descent;
                visual_bottom = visual_bottom.max(bottom);
            }
        }

        if visual_bottom > visual_top {
            (visual_bottom - visual_top) / dpr
        } else {
            size_px
        }
    })
}

/// 阶段 2-E:画一行/多行文字(glyph → scale → atlas → TexturedRect)
///
/// 从 `TextRenderObject::paint` 抽出,TextField 复用。
/// 返回最大宽度(shaping 后)。
/// `max_width_px` = 软换行宽度上限;None = 单行
pub fn paint_text_line(
    text: &str,
    size_px: f32,
    color: Color,
    offset: Point,
    list: &mut PaintList,
    max_width_px: Option<f32>,
) -> f32 {
    paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, DEFAULT_FONT_STACK)
}

/// `paint_text_line` 的字体栈参数化版本(编辑器语法着色逐 token 绘制用)
#[allow(clippy::too_many_arguments)]
pub fn paint_text_line_styled(
    text: &str,
    size_px: f32,
    color: Color,
    offset: Point,
    list: &mut PaintList,
    max_width_px: Option<f32>,
    font_stack: &str,
) -> f32 {
    paint_text_line_impl(text, TextKey::owned(text), size_px, color, offset, list, max_width_px, font_stack)
}

/// 共享整串 + 可选字节区间绘制(编辑器逐语法 span 复用整行 `Rc<str>`)。
///
/// shaping 缓存 key 直接携带 `Rc<str>` + 区间 → 命中路径零字符串分配;
/// 区间越界/落在字符中间时夹取到合法边界(高亮防抖期间 span 可能滞后于文档)。
#[allow(clippy::too_many_arguments)]
pub fn paint_text_span(
    text: &std::rc::Rc<str>,
    range: Option<(usize, usize)>,
    size_px: f32,
    color: Color,
    offset: Point,
    list: &mut PaintList,
    max_width_px: Option<f32>,
) -> f32 {
    let (start, end) = match range {
        Some(r) => clamp_char_range(text, r),
        None => (0, text.len()),
    };
    paint_text_line_impl(
        &text[start..end],
        TextKey::Shared(std::rc::Rc::clone(text), range),
        size_px,
        color,
        offset,
        list,
        max_width_px,
        DEFAULT_FONT_STACK,
    )
}

/// 文本首行字体 ascent(逻辑像素)。
///
/// 语法高亮按 span 分别绘制时,不同 fallback 字体(中文 vs 拉丁)的 ascent
/// 不同;直接把同一个 y 传给每个 span 会让基线错位。调用方用
/// `origin.y + (canonical - span_ascent)` 对齐到同一条基线。
pub fn text_ascent(text: &str, size_px: f32) -> f32 {
    if text.is_empty() {
        return size_px;
    }
    with_font(|fs| {
        let dpr = text_dpr();
        let shaped = shape_text(fs, text, size_px * dpr, None, DEFAULT_FONT_STACK);
        first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
    })
}

/// 共享整串 + 区间的首行字体 ascent(逻辑像素)。
/// 与 `paint_text_span` 使用同一 shape 缓存 key,不产生额外 shaping。
pub fn text_span_ascent(text: &std::rc::Rc<str>, range: Option<(usize, usize)>, size_px: f32) -> f32 {
    let (start, end) = match range {
        Some(r) => clamp_char_range(text, r),
        None => (0, text.len()),
    };
    if start >= end {
        return size_px;
    }
    with_font(|fs| {
        let dpr = text_dpr();
        let shaped = shape_text_keyed(
            fs,
            &text[start..end],
            TextKey::Shared(std::rc::Rc::clone(text), range),
            size_px * dpr,
            None,
            DEFAULT_FONT_STACK,
        );
        first_glyph_ascent(&shaped).map(|a| a / dpr).unwrap_or(size_px)
    })
}

fn first_glyph_ascent(shaped: &ShapedLine) -> Option<f32> {
    shaped.runs.first().and_then(|r| r.glyphs.first()).map(|g| g.ascent)
}

/// 把字节区间夹到 `text` 的合法字符边界内(滞后 span 防御)
fn clamp_char_range(text: &str, range: (usize, usize)) -> (usize, usize) {
    let mut start = range.0.min(text.len());
    let mut end = range.1.min(text.len());
    while !text.is_char_boundary(start) {
        start += 1;
    }
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    if end < start {
        end = start;
    }
    (start, end)
}

/// paint 共享实现(公开 API 的字体栈/key 在此收敛)
#[allow(clippy::too_many_arguments)]
fn paint_text_line_impl(
    text: &str,
    text_key: TextKey,
    size_px: f32,
    color: Color,
    offset: Point,
    list: &mut PaintList,
    max_width_px: Option<f32>,
    font_stack: &str,
) -> f32 {
    if text.is_empty() {
        return 0.0;
    }
    let width = with_font(|fs| {
        let dpr = text_dpr();
        let raster_px = size_px * dpr;
        let shaped = shape_text_keyed(fs, text, text_key, raster_px, max_width_px, font_stack);

        // ===== Step 1:栅格化 + 锚定 =====
        // 首行视觉顶 = baseline - ascent — 锚定 offset.y 到视觉顶
        // 后续行用各自的 baseline 差保持行距(parley 自动给 baseline 间距)
        let first_run = match shaped.runs.first() {
            Some(r) => r,
            None => return 0.0,
        };
        let first_ascent = first_run.glyphs.first().map(|g| g.ascent).unwrap_or(raster_px);
        let first_baseline = first_run.baseline_y;
        let anchor = first_baseline - first_ascent; // 首行视觉顶(物理像素)

        let mut max_x = 0.0f32;
        for run in &shaped.runs {
            for sg in &run.glyphs {
                // 栅格化通常在 shape_text 完成;若位图被预算淘汰,这里用 run 携带的
                // 字体上下文按需重建(line cache 命中时不会再走 shape_text)。
                if !fs.raster_cache.contains_key(&sg.raster_key) {
                    if let Some(rg) =
                        rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
                    {
                        insert_raster_glyph(fs, sg.raster_key, rg);
                    }
                }
                // 性能:禁止 clone RasterGlyph(位图 Vec<u8> 每 glyph 每帧全量克隆,
                // 编辑器大文本量 3000+ glyph/帧 时是首要 CPU 热点)——
                // raster_cache(&mut)与 atlas(&mut)是 disjoint 字段借用,可零拷贝共存。
                let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
                    continue;
                };
                if r.width == 0 || r.height == 0 {
                    continue;
                }
                fs.glyph_clock += 1;
                r.last_used = fs.glyph_clock;
                let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);

                // x = offset + (pen_x + placement_left) / dpr
                let x = offset.x + (sg.x + r.left as f32) / dpr;
                // y = offset + (glyph_visual_top - anchor) / dpr
                //   glyph_visual_top = baseline_y - ascent_of_this_glyph_row + placement_top
                //   但 run 级 ascent 与 glyph 级栅格化的 placement.top 可能不同,
                //   所以用 run.baseline_y - placement.top 作为 glyph 在 layout 内的视觉顶
                let glyph_visual_top = run.baseline_y - r.top as f32;
                let y = offset.y + (glyph_visual_top - anchor) / dpr;

                let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
                list.push(PaintCommand::TexturedRect {
                    rect,
                    color,
                    uv: entry.uv,
                    texture_id: 0,
                    mode: mgui_core::paint::TextureMode::Mask,
                });
                max_x = max_x.max((sg.x + sg.w) / dpr);
            }
        }
        if max_x == 0.0 {
            max_x = text.chars().count() as f32 * FALLBACK_ADVANCE_X;
        }
        max_x
    });
    width
}

/// 测单行文本每个字符的起始 x(前缀宽度,逻辑像素)
///
/// 编辑器光标/选区的字节偏移 ↔ x 坐标换算用:
/// - 返回 `vec.len() == char_count + 1`
/// - `widths[i]` = 第 i 个字符的**起始** x(= 前 i 个字符的前缀宽度)
/// - `widths[char_count]` = 整行宽度
/// - 光标落在字符 i 前 → `x = widths[i]`;选区 `[a, b)` → `[widths[a], widths[b])`
/// - 无 glyph 的字符(合字/零宽)沿用前一个字符的起始 x
/// - 空文本返回 `vec![0.0]`
///
/// 单行 shape(不换行);多行文本请按行分别调用。
/// soft wrap 后的视觉行字节区间(相对传入文本)。
///
/// TextField 用它对每条硬换行行做布局映射;空文本返回 `[(0, 0)]`。
pub fn wrapped_line_ranges(text: &str, size_px: f32, max_width: f32) -> Vec<(usize, usize)> {
    if text.is_empty() {
        return vec![(0, 0)];
    }
    if max_width <= 0.0 {
        return vec![(0, text.len())];
    }
    with_font(|fs| {
        let dpr = text_dpr();
        let raster_px = size_px * dpr;
        let shaped = shape_text(fs, text, raster_px, Some(max_width), DEFAULT_FONT_STACK);
        shaped.visual_lines.clone()
    })
}

pub fn measure_char_prefix_widths(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
    if text.is_empty() {
        return vec![0.0];
    }
    with_font(|fs| {
        let dpr = text_dpr();
        let raster_px = size_px * dpr;
        let shaped = shape_text(fs, text, raster_px, None, font_stack);

        let char_count = text.chars().count();
        let mut widths = vec![0.0f32; char_count + 1];

        // cluster 起始字节 → 该 cluster 首个 glyph 的 x(物理像素);
        // 合字/组合序列的多个 glyph 同属一个 cluster,只记首 glyph 位置
        let mut byte_x: Vec<(u32, f32)> = Vec::new();
        for run in &shaped.runs {
            for sg in &run.glyphs {
                match byte_x.last_mut() {
                    Some((b, _)) if *b == sg.cluster => {}
                    _ => byte_x.push((sg.cluster, sg.x)),
                }
            }
        }

        // 前缀宽度(逻辑像素):字符 i 的起始 x = 最后一个 cluster 起始字节 ≤
        // 该字符字节位置的 glyph x;落单字符(无 glyph)沿用前值
        let mut prev = 0.0f32;
        let mut bi = 0usize;
        for (ci, (byte_pos, _)) in text.char_indices().enumerate() {
            while bi < byte_x.len() && byte_x[bi].0 <= byte_pos as u32 {
                prev = byte_x[bi].1 / dpr;
                bi += 1;
            }
            widths[ci] = prev;
        }
        widths[char_count] = shaped.max_x / dpr;
        widths
    })
}

/// 从 parley Font 拿原始 bytes,栅格化一个 glyph
fn rasterize_one_glyph(
    font: &parley::Font,
    font_size: f32,
    glyph_id: u16,
    norm_coords: &[swash::NormalizedCoord],
    scale_cx: &mut swash::scale::ScaleContext,
) -> Option<RasterGlyph> {
    // parley::Font = peniko::Font = FontData { data: Blob<u8>, index: u32 }
    let bytes = font.data.data();
    if bytes.is_empty() {
        return None;
    }
    let font_ref = swash::FontRef::from_index(bytes, font.index as usize)?;
    let mut scaler =
        scale_cx.builder(font_ref).size(font_size).normalized_coords(norm_coords.iter()).hint(true).build();
    let image = swash::scale::Render::new(&[
        swash::scale::Source::ColorOutline(0),
        swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
        swash::scale::Source::Outline,
    ])
    .render(&mut scaler, glyph_id)?;
    if image.placement.width == 0 || image.placement.height == 0 {
        // 零尺寸 glyph(空格等无 ink 字符)必须缓存占位:直接返回 None 会让
        // 每次 shape/paint 都重新走 swash(实测一次 ~80µs,而空格占代码行
        // 多数 glyph)—— 100k 行滚动实测每行 15 次 miss 几乎全是空格。
        // paint 见到 width/height == 0 直接跳过,不会进 atlas。
        return Some(RasterGlyph { data: Vec::new(), width: 0, height: 0, left: 0, top: 0, last_used: 0 });
    }
    Some(RasterGlyph {
        data: image.data.to_vec(),
        width: image.placement.width,
        height: image.placement.height,
        left: image.placement.left,
        top: image.placement.top,
        last_used: 0,
    })
}

impl RenderObject for TextRenderObject {
    fn layout(&mut self, _bc: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
        // 自动 soft wrap:非显式 max_width 时用当前约束刷新。
        // 单行 TextWidget 不应被 Flex 的 BoxConstraints 给误开 soft-wrap —— 但 Button 的
        // tight constraint(明确是要约束内容)仍应传递。区分:explicit max_width 不覆盖。
        // if !self.max_width_explicit {
        //     self.max_width = if bc.max_width.is_finite() && bc.max_width > 0.0 {
        //         Some(bc.max_width)
        //     } else {
        //         None
        //     };
        // }
        let s = self.measure();
        self.size = s;
        s
    }

    fn content_size(&self) -> Size {
        self.size
    }

    fn paint(&self, offset: Point, list: &mut PaintList) {
        paint_text_line(&self.text, self.size_px, self.color, offset, list, self.max_width);
    }

    fn set_element_id(&mut self, id: ElementId) {
        self.element_id = Some(id);
    }

    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        // bugfix(双击标题无效):文本默认不参与 hit_test → 点击标题落穿,
        // 事件冒泡链上没有 GestureDetector,双击永远无法识别。
        // 文本整块 layout 尺寸作为命中区。
        let r = Rect::new(offset.x, offset.y, self.size.width, self.size.height);
        if r.contains(position) {
            self.element_id
        } else {
            None
        }
    }
}

// =============================================================================
// 测试
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn mk_key(id: u32) -> GlyphKey {
        GlyphKey(id as u64)
    }

    #[test]
    fn atlas_get_or_insert_dedupes() {
        let mut a = Atlas::new(64, 64);
        let k = mk_key(1);
        let e1 = a.get_or_insert(k, &[255; 8], 2, 4);
        let e2 = a.get_or_insert(k, &[0; 8], 2, 4);
        assert_eq!(e1.uv, e2.uv, "重复 key 必须返回同一 entry");
        assert_eq!(a.glyph_count(), 1);
    }

    #[test]
    fn atlas_wraps_to_next_row() {
        let mut a = Atlas::new(20, 20);
        // 第一个 16x4 占了 row 0
        let k1 = mk_key(1);
        a.get_or_insert(k1, &[1; 64], 16, 4);
        // 第二个 16x4 必须换行(放不下 16+padding)
        let k2 = mk_key(2);
        let e2 = a.get_or_insert(k2, &[2; 64], 16, 4);
        assert!(e2.uv[1] > 0.0, "第二个 glyph 应该换行,uv.v0 > 0");
    }

    #[test]
    fn atlas_dirty_flag_lifecycle() {
        let mut a = Atlas::new(64, 64);
        // 新建 atlas 不脏
        assert!(!a.is_dirty());
        // 写入后变脏
        a.get_or_insert(mk_key(1), &[255; 8], 2, 4);
        assert!(a.is_dirty(), "get_or_insert 后应该 dirty");
        // 清掉 dirty
        a.clear_dirty();
        assert!(!a.is_dirty());
        // 重复 key 不重新写入,不触发 dirty
        a.get_or_insert(mk_key(1), &[0; 8], 2, 4);
        assert!(!a.is_dirty(), "重复 key 不应触发 dirty");
        // 新 key 再次 dirty
        a.get_or_insert(mk_key(2), &[0; 8], 2, 4);
        assert!(a.is_dirty());
    }

    /// GPU 上传只覆盖本次写入的行区间:避免每写一个 glyph 就整张拷贝/上传
    /// (4096² = 16 MiB,8192² 封顶时 64 MiB)。
    #[test]
    fn atlas_snapshot_uploads_only_dirty_rows() {
        // 每个测试线程有独立 FontState;先复位 atlas 排除前序 shape 的条目
        let width = with_font(|fs| {
            fs.atlas = Atlas::new(ATLAS_SIZE, ATLAS_SIZE);
            fs.atlas.width
        });
        with_font(|fs| {
            fs.atlas.get_or_insert(GlyphKey::new(7, 7, 0, 0, 0, 0), &[9u8; 16], 4, 4);
            fs.atlas.get_or_insert(GlyphKey::new(7, 8, 0, 0, 0, 0), &[9u8; 16], 4, 4);
            assert_eq!(fs.atlas.dirty_rows, Some((1, 5)), "同一行的写入应合并为单行带");
        });
        let snap = atlas_snapshot();
        assert!(snap.dirty);
        assert_eq!(snap.dirty_y, (1, 5));
        assert_eq!(snap.pixels.as_ref().map(Vec::len), Some(width as usize * 4), "快照只拷贝 dirty 行");
        atlas_clear_dirty();
        let clean = atlas_snapshot();
        assert!(!clean.dirty);
        assert_eq!(clean.dirty_y, (0, 0));
        assert!(clean.pixels.is_none());
    }

    /// atlas 自动扩容:塞满 32×32 小 atlas,不应 panic,而是自动扩到 64×64
    #[test]
    fn atlas_auto_expands_when_full() {
        let mut a = Atlas::new(32, 32);
        // 先塞 1 个 glyph 当参照(记录它的 uv,扩容后要能除以 2)
        let e_before = a.get_or_insert(mk_key(1), &[100; 9], 3, 3);
        let uv_scalar_before = e_before.uv[0]; // 单轴归一化值

        // 塞满 atlas — 每行放 14×14 的 glyph(= 196px + padding),大约 2 行就满
        // 用大 glyph 加速测试:20×20 会每行只能放 1 个,很快就触发扩容
        let big: Vec<u8> = vec![200; 400]; // 20×20
        for i in 2..10 {
            a.get_or_insert(mk_key(i), &big, 20, 20);
        }
        // 不该 panic,如果没扩容,最多只能放 ~3 个 20×20 glyph
        assert!(a.width >= 32, "atlas 应保持原尺寸或扩容");
        assert!(a.glyph_count() >= 8, "扩容后应能放下 8+ glyphs,实际 {}", a.glyph_count());

        // 扩容了(至少一次):参照 glyph 的 uv 应该被缩放
        if a.width > 32 {
            // 新 atlas 宽度翻倍到 64,所以原 uv 应该 ≈ 原来的一半
            let e_after = a.get_or_insert(mk_key(1), &[0; 9], 3, 3);
            // 归一化坐标用像素位置 / atlas.width 计算,
            // 扩容把 width 翻倍,所以原像素位置的 uv 值 = 旧值 / 2
            let expected = uv_scalar_before / 2.0;
            assert!((e_after.uv[0] - expected).abs() < 0.01, "扩容后 uv.u0 应为 {expected}, 实际 {}", e_after.uv[0]);
        }
    }

    /// 边界:扩容后新 glyph 继续能放下
    #[test]
    fn atlas_accepts_new_glyphs_after_expansion() {
        let mut a = Atlas::new(16, 16);
        // 先塞一个 12×12 的,占满 atlas 高度
        a.get_or_insert(mk_key(1), &[50; 144], 12, 12);
        // 再塞一个 12×12 的 — 会扩容(不能放同一行也没换行空间)
        let e2 = a.get_or_insert(mk_key(2), &[100; 144], 12, 12);
        assert!(a.width > 16 || a.height > 16, "应该扩容了");
        // 第二次的 uv.v0 应该 > 第一次(换到第二行)
        let e1 = a.get_or_insert(mk_key(1), &[0; 144], 12, 12);
        assert!(e2.uv[1] >= e1.uv[1], "第二个 glyph 应在第一个下方");
    }

    #[test]
    fn text_measure_produces_nonzero_size() {
        let t = TextRenderObject::new("Hello".into(), 24.0, Color::WHITE);
        let s = t.measure();
        assert!(s.width > 0.0, "width should be > 0 for 'Hello'");
        assert!(s.height > 0.0, "height should be > 0");
    }

    #[test]
    fn text_paint_emits_textured_rects() {
        let t = TextRenderObject::new("Hi".into(), 24.0, Color::WHITE);
        let mut list = PaintList::new();
        t.paint(Point::new(0.0, 0.0), &mut list);
        // "Hi" 2 个 ASCII 字符,应该 2 个 TexturedRect
        assert!(!list.is_empty(), "paint should emit at least 1 textured rect");
        for cmd in &list.commands {
            match cmd {
                PaintCommand::TexturedRect { texture_id, uv, .. } => {
                    assert_eq!(*texture_id, 0);
                    assert!(uv[0] < uv[2]);
                    assert!(uv[1] < uv[3]);
                }
                _ => panic!("expected TexturedRect, got Rect"),
            }
        }
    }

    #[test]
    fn text_paint_with_offset_shifts_rects() {
        let t = TextRenderObject::new("X".into(), 24.0, Color::WHITE);
        let mut list = PaintList::new();
        t.paint(Point::new(100.0, 50.0), &mut list);
        // 所有 rect 的 x/y 应该 >= offset
        for cmd in &list.commands {
            if let PaintCommand::TexturedRect { rect, .. } = cmd {
                assert!(rect.x >= 100.0 - 1.0, "x={}", rect.x);
                assert!(rect.y >= 50.0 - 1.0, "y={}", rect.y);
            }
        }
    }

    /// 缓存命中:同一文本第二次 paint 不再 shape(输出仍一致)
    #[test]
    fn shape_line_cache_hits_second_paint() {
        let mut list1 = PaintList::new();
        paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::ZERO, &mut list1, None);
        let calls_1 = with_font(|fs| fs.shape_calls);

        let mut list2 = PaintList::new();
        paint_text_line("cache-hit-test", 20.0, Color::WHITE, Point::new(5.0, 5.0), &mut list2, None);
        let calls_2 = with_font(|fs| fs.shape_calls);

        assert_eq!(calls_1, calls_2, "第二次 paint 应命中缓存,不再 shape");
        assert_eq!(list1.commands.len(), list2.commands.len(), "缓存命中的绘制输出数量应一致");
    }

    /// 防膨胀:超过 LINE_CACHE_LIMIT 时按 LRU 回收,热条目保留
    #[test]
    fn shape_line_cache_evicts_lru_at_limit() {
        let fake_line =
            || std::rc::Rc::new(ShapedLine { runs: Vec::new(), max_x: 0.0, max_y: 0.0, visual_lines: Vec::new() });
        let hot_key = (TextKey::Owned("hot-entry".to_string()), 0, None, 0);
        let oldest_key = (TextKey::Owned("fake-entry-0".to_string()), 0, None, 0);
        with_font(|fs| {
            fs.line_cache.clear();
            fs.line_clock = 0;
            fs.line_clock += 1;
            fs.line_cache.insert(hot_key.clone(), LineCacheEntry { line: fake_line(), last_used: fs.line_clock });
            for i in 0..LINE_CACHE_LIMIT - 1 {
                fs.line_clock += 1;
                fs.line_cache.insert(
                    (TextKey::Owned(format!("fake-entry-{i}")), 0, None, 0),
                    LineCacheEntry { line: fake_line(), last_used: fs.line_clock },
                );
            }
            // 最旧条目刚被重新访问 → 淘汰时必须保留
            fs.line_clock += 1;
            fs.line_cache.get_mut(&hot_key).expect("hot entry").last_used = fs.line_clock;
        });
        // 新 paint 触发超限回收
        let mut list = PaintList::new();
        paint_text_line("trigger-evict", 14.0, Color::WHITE, Point::ZERO, &mut list, None);
        with_font(|fs| {
            assert!(fs.line_cache.len() <= LINE_CACHE_LIMIT, "超限后应回收到上限内");
            assert!(fs.line_cache.len() >= LINE_CACHE_TARGET, "LRU 只应淘汰最旧 1/4");
            assert!(fs.line_cache.contains_key(&hot_key), "刚访问过的热条目不应被淘汰");
            assert!(!fs.line_cache.contains_key(&oldest_key), "最久未访问的条目应被淘汰");
            fs.line_cache.clear();
        });
    }

    /// 位图被预算淘汰后,线缓存命中时 paint 路径必须能按需重建 glyph。
    #[test]
    fn paint_rebuilds_evicted_raster_glyphs() {
        let mut first = PaintList::new();
        paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut first, None);
        assert!(!first.commands.is_empty());

        with_font(|fs| {
            fs.raster_cache.clear();
            fs.raster_cache_bytes = 0;
        });

        let mut second = PaintList::new();
        paint_text_line("raster-rebuild-test", 18.0, Color::WHITE, Point::ZERO, &mut second, None);
        assert_eq!(first.commands.len(), second.commands.len(), "位图淘汰后应重建 glyph,而不是丢字");
        assert!(!second.commands.is_empty());
    }

    /// 零尺寸 glyph(空格等)也必须进 raster_cache:否则每次 shape 都重新
    /// 走 swash 栅格化(实测一次 ~80µs),代码行里空格占多数 glyph →
    /// 快速滚动时每行十几毫秒的重复栅格化。
    #[test]
    fn zero_size_glyphs_are_cached_not_rerasterized() {
        with_font(|fs| {
            fs.raster_cache.clear();
            fs.raster_cache_bytes = 0;
            let _ = shape_text(fs, "a b c", 13.0, None, DEFAULT_FONT_STACK);
            let cached = fs.raster_cache.len();
            assert!(
                fs.raster_cache.values().any(|g| g.width == 0 && g.height == 0),
                "空格等零尺寸 glyph 必须缓存占位,不能每次重栅格化"
            );
            // 新文本行(line cache miss)必须重新 shape:只有新字符 'd' 需要
            // 栅格化,空格不得再次进入栅格化流程
            let _ = shape_text(fs, "a b c d", 13.0, None, DEFAULT_FONT_STACK);
            assert_eq!(fs.raster_cache.len(), cached + 1, "除新字符外不得新增栅格化条目");
            fs.raster_cache.clear();
            fs.raster_cache_bytes = 0;
        });
    }

    /// glyph 位图缓存超预算时按 LRU 回收到目标水位。
    #[test]
    fn raster_cache_trims_to_budget() {
        with_font(|fs| {
            fs.raster_cache.clear();
            fs.raster_cache_bytes = 0;
            let chunk = vec![0u8; 8 * 1024 * 1024];
            for i in 0..5u16 {
                insert_raster_glyph(
                    fs,
                    GlyphKey::new(0, i, 0, 0, 0, 0),
                    RasterGlyph { data: chunk.clone(), width: 2048, height: 1024, left: 0, top: 0, last_used: 0 },
                );
            }
            // 5 × 8 MiB 超过 32 MiB 预算 → 淘汰最旧的两条,保留 3 × 8 MiB。
            assert!(fs.raster_cache_bytes <= RASTER_CACHE_TARGET_BYTES, "应回收到目标水位");
            assert_eq!(fs.raster_cache.len(), 3, "LRU 应保留最近的条目");
            assert!(!fs.raster_cache.contains_key(&GlyphKey::new(0, 0, 0, 0, 0, 0)), "最旧条目应被淘汰");
            assert!(fs.raster_cache.contains_key(&GlyphKey::new(0, 4, 0, 0, 0, 0)), "最新条目应保留");
            fs.raster_cache.clear();
            fs.raster_cache_bytes = 0;
        });
    }

    /// DPR 栅格化:rect 逻辑尺寸 dpr 无关;atlas 位图分辨率随 dpr 翻倍;
    /// paint 返回宽度与 measure_text_width 一致(TextField 光标定位依赖)
    #[test]
    fn paint_text_line_dpr_rasterizes_at_physical_resolution() {
        fn paint_once(dpr: f32) -> (f32, f32, f32) {
            set_text_dpr(dpr);
            let mut list = PaintList::new();
            let width = paint_text_line("H", 24.0, Color::WHITE, Point::ZERO, &mut list, None);
            let (rect_w, uv_span) = match &list.commands[0] {
                PaintCommand::TexturedRect { rect, uv, .. } => (rect.width, (uv[2] - uv[0]) * ATLAS_SIZE as f32),
                _ => panic!("expected TexturedRect"),
            };
            set_text_dpr(1.0); // 恢复默认,避免污染其它测试
            (rect_w, uv_span, width)
        }

        let (w1, span1, ret1) = paint_once(1.0);
        let (w2, span2, ret2) = paint_once(2.0);

        // 物理像素取整会让逻辑宽度差 1px(macOS 实测 dpr1=15 / dpr2=14),允许 ≤2px
        assert!((w1 - w2).abs() <= 2.0, "rect 逻辑尺寸应 dpr 无关(允许取整 ≤2px): dpr1={w1} vs dpr2={w2}");
        assert!((ret1 - ret2).abs() < 0.5 && ret1 > 0.0, "返回宽度(逻辑)应 dpr 无关: {ret1} vs {ret2}");
        assert!(span2 > span1 * 1.5, "atlas 位图分辨率应随 dpr 变大: dpr1={span1}px vs dpr2={span2}px");
        let mw = measure_text_width("H", 24.0);
        assert!((ret1 - mw).abs() < 0.5, "paint 宽度应与 measure 一致(TextField 光标定位依赖): {ret1} vs {mw}");
    }
}

// =============================================================================
// RTL(P3-5b):方向判定 + 方向感知的光标位置
// =============================================================================

/// 文本主方向是否 RTL(首个强方向字符决定;无强方向字符按 LTR)。
pub fn is_rtl_text(text: &str) -> bool {
    for ch in text.chars() {
        let code = ch as u32;
        let rtl = matches!(
            code,
            0x0590..=0x05FF   // Hebrew
            | 0x0600..=0x06FF // Arabic
            | 0x0700..=0x074F // Syriac
            | 0x0750..=0x077F // Arabic Supplement
            | 0x0780..=0x07BF // Thaana
            | 0x0860..=0x086F // Syriac Supplement
            | 0x08A0..=0x08FF // Arabic Extended-A
            | 0xFB1D..=0xFB4F // Hebrew presentation
            | 0xFB50..=0xFDFF // Arabic presentation A
            | 0xFE70..=0xFEFF // Arabic presentation B
        );
        if rtl {
            return true;
        }
        if ch.is_alphabetic() {
            return false;
        }
    }
    false
}

/// 把 LTR 前缀宽度表镜像为 RTL 光标表(纯函数,便于测试)。
///
/// 输入 `widths[i]` = 第 i 个字符的左缘 x(末项为整行宽)。
/// RTL 视觉顺序相反:`carets[0]` = 整行宽(最右),`carets[n]` = 最左字符左缘(≈0),
/// `carets[c] = widths[c-1]`。混合双向文本按首强方向整体镜像。
pub fn mirror_carets_for_rtl(widths: &[f32]) -> Vec<f32> {
    let chars = widths.len().saturating_sub(1);
    if chars == 0 {
        return widths.to_vec();
    }
    let mut carets = vec![0.0f32; chars + 1];
    carets[0] = widths[chars];
    carets[1..=chars].copy_from_slice(&widths[..chars]);
    carets
}

/// 方向感知的光标 x 表(逻辑字符边界,长度 = char_count + 1,单位逻辑像素)。
pub fn measure_caret_positions(text: &str, size_px: f32, font_stack: &str) -> Vec<f32> {
    let widths = measure_char_prefix_widths(text, size_px, font_stack);
    if is_rtl_text(text) {
        mirror_carets_for_rtl(&widths)
    } else {
        widths
    }
}

/// 光标表中离 `x` 最近的逻辑位置(LTR/RTL 通用;距离相同取较小下标)。
pub fn nearest_caret_index(carets: &[f32], x: f32) -> usize {
    carets
        .iter()
        .enumerate()
        .min_by(|(ia, a), (ib, b)| (**a - x).abs().total_cmp(&(**b - x).abs()).then_with(|| ia.cmp(ib)))
        .map(|(index, _)| index)
        .unwrap_or(0)
}

#[cfg(test)]
mod rtl_tests {
    use super::*;

    #[test]
    fn detects_base_direction() {
        assert!(is_rtl_text("مرحبا بالعالم"));
        assert!(is_rtl_text("שלום"));
        assert!(!is_rtl_text("hello مرحبا")); // 首个强字符是拉丁
        assert!(!is_rtl_text("123 !?"));
        assert!(is_rtl_text("123 مرحبا")); // 数字无方向,首个字母决定
    }

    #[test]
    fn rtl_caret_mirroring_and_nearest_index() {
        // 合成宽度:3 个字符,起点 0/10/25,整行 40
        let widths = [0.0, 10.0, 25.0, 40.0];
        let carets = mirror_carets_for_rtl(&widths);
        assert_eq!(carets, vec![40.0, 0.0, 10.0, 25.0]);
        assert_eq!(nearest_caret_index(&carets, 38.0), 0, "靠近右缘 → 文本起点");
        assert_eq!(nearest_caret_index(&carets, 2.0), 1);
        assert_eq!(nearest_caret_index(&carets, 24.0), 3, "靠近左缘 → 文本末尾");
        // LTR 表保持不变
        assert_eq!(mirror_carets_for_rtl(&[0.0]), vec![0.0]);
        assert_eq!(nearest_caret_index(&widths, 12.0), 1);
    }
}

// =============================================================================
// 富文本(P3-3 第一切片):同一段落内混排字号 / 颜色 / 字体栈
// =============================================================================

/// 富文本样式 span。颜色只影响绘制,不参与 shape 缓存 key。
#[derive(Clone, Debug, PartialEq)]
pub struct RichTextSpan {
    pub text: String,
    pub size_px: f32,
    /// 文字颜色;`None` = 跟随所在主题(RichTextWidget 使用 `theme.text.body.color`)
    pub color: Option<Color>,
    /// None = [`DEFAULT_FONT_STACK`]
    pub font_stack: Option<String>,
}

impl RichTextSpan {
    pub fn new(text: impl Into<String>) -> Self {
        Self { text: text.into(), size_px: 15.0, color: None, font_stack: None }
    }

    pub fn with_size(mut self, size_px: f32) -> Self {
        self.size_px = size_px;
        self
    }

    pub fn with_color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    pub fn with_font_stack(mut self, stack: impl Into<String>) -> Self {
        self.font_stack = Some(stack.into());
        self
    }
}

/// 内联项绘制回调(逻辑坐标 rect,相对 RichText 原点)。
pub type InlinePainter = std::rc::Rc<dyn Fn(&mut PaintList, Rect)>;

/// 内联项:固定尺寸、底部对齐到文本基线,绘制由调用方回调完成(绘制型,无命中/状态)。
#[derive(Clone)]
pub struct InlineItem {
    pub width: f32,
    pub height: f32,
    pub painter: InlinePainter,
}

impl InlineItem {
    pub fn new(width: f32, height: f32, painter: impl Fn(&mut PaintList, Rect) + 'static) -> Self {
        Self { width, height, painter: std::rc::Rc::new(painter) }
    }
}

impl std::fmt::Debug for InlineItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InlineItem").field("width", &self.width).field("height", &self.height).finish()
    }
}

impl PartialEq for InlineItem {
    fn eq(&self, other: &Self) -> bool {
        self.width == other.width && self.height == other.height && std::rc::Rc::ptr_eq(&self.painter, &other.painter)
    }
}

/// 富文本 item:文本 span 或内联绘制项。
#[derive(Clone, Debug, PartialEq)]
pub enum RichItem {
    Text(RichTextSpan),
    Inline(InlineItem),
}

/// 预处理后的富文本:拼接文本 + 文本 span 的字节区间 + 内联项(一次构造,多次测量/绘制)。
#[derive(Clone, Debug, PartialEq)]
pub struct RichText {
    text: std::rc::Rc<str>,
    spans: Vec<RichTextSpan>,
    ranges: Vec<(usize, usize)>,
    /// (字节偏移, 内联项);offset 即内联项在文本流中的位置
    inlines: Vec<(usize, InlineItem)>,
}

impl RichText {
    pub fn new(spans: Vec<RichTextSpan>) -> Self {
        Self::from_items(spans.into_iter().map(RichItem::Text).collect())
    }

    pub fn from_items(items: Vec<RichItem>) -> Self {
        let mut text = String::new();
        let mut spans = Vec::new();
        let mut ranges = Vec::new();
        let mut inlines = Vec::new();
        for item in items {
            match item {
                RichItem::Text(span) => {
                    let start = text.len();
                    text.push_str(&span.text);
                    spans.push(span);
                    ranges.push((start, text.len()));
                }
                RichItem::Inline(inline) => inlines.push((text.len(), inline)),
            }
        }
        Self { text: text.into(), spans, ranges, inlines }
    }

    /// 纯文本(a11y label / 测试断言用;内联项不含文本)
    pub fn plain_text(&self) -> &str {
        &self.text
    }

    pub fn spans(&self) -> &[RichTextSpan] {
        &self.spans
    }

    pub fn is_empty(&self) -> bool {
        self.text.is_empty() && self.inlines.is_empty()
    }
}

struct RichShapedGlyph {
    raster_key: GlyphKey,
    glyph_id: u16,
    x: f32,
    /// 所属 span 下标(绘制时取 color)
    span: u16,
}

struct RichShapedRun {
    glyphs: Vec<RichShapedGlyph>,
    baseline_y: f32,
    /// 本 run 的字体 ascent(混合字号时首行视觉顶取最大值)
    ascent: f32,
    font: parley::Font,
    norm_coords: std::rc::Rc<[swash::NormalizedCoord]>,
    raster_size: f32,
}

/// 布局后的内联项(parley 逻辑坐标,绘制时 ×dpr 再减锚点)
struct RichInlineBox {
    /// 对应 `rich.inlines` 下标
    id: u16,
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    /// 所在行的基线(物理像素),用于首行视觉顶计算
    line_baseline: f32,
}

struct RichShapedLine {
    runs: Vec<RichShapedRun>,
    inline_boxes: Vec<RichInlineBox>,
    max_x: f32,
    max_y: f32,
}

#[derive(Clone, PartialEq, Eq, Hash)]
struct RichCacheKey {
    text: std::rc::Rc<str>,
    /// (start, end, size_bits, font_stack_hash)
    styles: Vec<(usize, usize, u32, u64)>,
    /// (byte index, width_bits, height_bits)
    inlines: Vec<(usize, u32, u32)>,
    width_bits: Option<u32>,
    dpr_bits: u32,
}

struct RichCacheEntry {
    line: std::rc::Rc<RichShapedLine>,
    last_used: u64,
}

fn rich_style_signature(rich: &RichText) -> Vec<(usize, usize, u32, u64)> {
    rich.ranges
        .iter()
        .zip(&rich.spans)
        .map(|((start, end), span)| {
            let stack = span.font_stack.as_deref().unwrap_or(DEFAULT_FONT_STACK);
            let mut h = DefaultHasher::new();
            stack.hash(&mut h);
            (*start, *end, span.size_px.max(1.0).to_bits(), h.finish())
        })
        .collect()
}

fn span_index_at(ranges: &[(usize, usize)], byte: usize) -> u16 {
    ranges.iter().position(|(start, end)| byte >= *start && byte < *end).unwrap_or(0) as u16
}

/// 富文本 shaping(带缓存):混排 span 用 parley ranged style,字号/字体栈逐 span 生效。
fn shape_rich(fs: &mut FontState, rich: &RichText, max_width_px: Option<f32>) -> std::rc::Rc<RichShapedLine> {
    let dpr = text_dpr();
    let key = RichCacheKey {
        text: std::rc::Rc::clone(&rich.text),
        styles: rich_style_signature(rich),
        inlines: rich
            .inlines
            .iter()
            .map(|(index, inline)| (*index, inline.width.to_bits(), inline.height.to_bits()))
            .collect(),
        width_bits: max_width_px.map(|w| w.to_bits()),
        dpr_bits: dpr.to_bits(),
    };
    if let Some(entry) = fs.rich_cache.get_mut(&key) {
        fs.rich_clock += 1;
        entry.last_used = fs.rich_clock;
        return std::rc::Rc::clone(&entry.line);
    }

    let text: &str = &rich.text;
    let mut builder = fs.layout_cx.ranged_builder(&mut fs.font_cx, text, 1.0, true);
    builder.push_default(parley::StyleProperty::FontSize(15.0));
    builder.push_default(parley::StyleProperty::LineHeight(1.2));
    builder.push_default(parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(
        DEFAULT_FONT_STACK,
    ))));
    builder.push_default(parley::StyleProperty::WordBreak(parley::swash::text::WordBreakStrength::KeepAll));
    builder.push_default(parley::StyleProperty::OverflowWrap(parley::OverflowWrap::Anywhere));
    for ((start, end), span) in rich.ranges.iter().zip(&rich.spans) {
        if span.size_px > 0.0 {
            builder.push(parley::StyleProperty::FontSize(span.size_px), *start..*end);
        }
        if let Some(stack) = &span.font_stack {
            builder.push(
                parley::StyleProperty::FontStack(parley::FontStack::Source(std::borrow::Cow::Borrowed(stack))),
                *start..*end,
            );
        }
    }
    for (id, (index, inline)) in rich.inlines.iter().enumerate() {
        builder.push_inline_box(parley::InlineBox {
            id: id as u64,
            index: *index,
            width: inline.width,
            height: inline.height,
        });
    }
    let mut layout: parley::Layout<()> = builder.build(text);
    let wrap_opt = max_width_px.filter(|w| *w > 0.0);
    layout.break_all_lines(wrap_opt);
    layout.align(wrap_opt, parley::Alignment::Start, parley::AlignmentOptions::default());

    let mut runs = Vec::new();
    let mut inline_boxes = Vec::new();
    let mut max_x = 0.0f32;
    let mut max_y = 0.0f32;
    for line in layout.lines() {
        let line_m = line.metrics();
        let baseline_y = line_m.baseline * dpr;
        for item in line.items() {
            let parley::PositionedLayoutItem::GlyphRun(gr) = item else {
                if let parley::PositionedLayoutItem::InlineBox(b) = item {
                    inline_boxes.push(RichInlineBox {
                        id: b.id as u16,
                        x: b.x,
                        y: b.y,
                        width: b.width,
                        height: b.height,
                        line_baseline: baseline_y,
                    });
                    max_x = max_x.max((b.x + b.width) * dpr);
                    max_y = max_y.max((b.y + b.height) * dpr);
                }
                continue;
            };
            let run_metrics = gr.run().metrics();
            let ascent = run_metrics.ascent * dpr;
            let descent = run_metrics.descent * dpr;
            let font_size_phys = gr.run().font_size() * dpr;
            let font_blob_id = gr.run().font().data.id() as usize;
            let norm_coords: std::rc::Rc<[swash::NormalizedCoord]> = gr.run().normalized_coords().to_vec().into();
            let run_font = gr.run().font().clone();
            let mut pen_x = gr.offset();
            let mut run_glyphs = Vec::new();
            for cluster in gr.run().visual_clusters() {
                let cluster_byte = cluster.text_range().start;
                let span = span_index_at(&rich.ranges, cluster_byte);
                for g in cluster.glyphs() {
                    let raster_key = GlyphKey::new(font_blob_id, g.id, font_size_phys.to_bits(), 0, 0, 0);
                    if !fs.raster_cache.contains_key(&raster_key) {
                        if let Some(rg) =
                            rasterize_one_glyph(&run_font, font_size_phys, g.id, &norm_coords, &mut fs.scale_cx)
                        {
                            insert_raster_glyph(fs, raster_key, rg);
                        }
                    }
                    let gx = pen_x + g.x;
                    run_glyphs.push(RichShapedGlyph { raster_key, glyph_id: g.id, x: gx * dpr, span });
                    max_x = max_x.max((gx + g.advance) * dpr);
                    max_y = max_y.max(baseline_y + descent);
                    pen_x += g.advance;
                }
            }
            if !run_glyphs.is_empty() {
                runs.push(RichShapedRun {
                    glyphs: run_glyphs,
                    baseline_y,
                    ascent,
                    font: run_font,
                    norm_coords,
                    raster_size: font_size_phys,
                });
            }
        }
    }
    if max_y == 0.0 {
        max_y = rich.spans.iter().map(|s| s.size_px).fold(15.0, f32::max) * 1.2 * dpr;
    }

    let line = std::rc::Rc::new(RichShapedLine { runs, inline_boxes, max_x, max_y });
    if fs.rich_cache.len() >= LINE_CACHE_LIMIT {
        fs.rich_cache.clear();
    }
    fs.rich_clock += 1;
    fs.rich_cache.insert(key, RichCacheEntry { line: std::rc::Rc::clone(&line), last_used: fs.rich_clock });
    line
}

/// 测量富文本(逻辑像素)。`max_width` = soft wrap 宽度上限。
pub fn rich_text_size(rich: &RichText, max_width: Option<f32>) -> Size {
    if rich.is_empty() {
        return Size::ZERO;
    }
    with_font(|fs| {
        let dpr = text_dpr();
        let shaped = shape_rich(fs, rich, max_width);
        let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
        let (anchor, fallback_h) = match first_baseline {
            Some(baseline) => {
                // 首行视觉顶 = baseline − 首行最大 ascent;内联项更高时取内联项顶部
                let first_ascent =
                    shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
                let inline_top = shaped
                    .inline_boxes
                    .iter()
                    .filter(|b| b.line_baseline == baseline)
                    .map(|b| b.y * dpr)
                    .fold(f32::INFINITY, f32::min);
                // 布局坐标中的视觉顶:字形顶与内联项顶取更小者
                ((baseline - first_ascent).min(inline_top), 0.0)
            }
            None => (0.0, shaped.max_y),
        };
        let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { fallback_h / dpr };
        Size::new(shaped.max_x / dpr, height)
    })
}

/// 富文本布局结果:整体尺寸 + 每个内联项的相对矩形(逻辑像素,原点 = 文本视觉左上)。
#[derive(Clone, Debug, PartialEq)]
pub struct RichTextLayout {
    pub size: Size,
    pub inline_rects: Vec<Rect>,
}

/// 仅布局:供交互型内联 Widget 定位子元素(不绘制)。
pub fn rich_text_layout(rich: &RichText, max_width: Option<f32>) -> RichTextLayout {
    if rich.is_empty() {
        return RichTextLayout { size: Size::ZERO, inline_rects: Vec::new() };
    }
    with_font(|fs| {
        let dpr = text_dpr();
        let shaped = shape_rich(fs, rich, max_width);
        let first_baseline = shaped.runs.first().map(|r| r.baseline_y);
        let anchor = match first_baseline {
            Some(baseline) => {
                let first_ascent =
                    shaped.runs.iter().filter(|r| r.baseline_y == baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
                let inline_top = shaped
                    .inline_boxes
                    .iter()
                    .filter(|b| b.line_baseline == baseline)
                    .map(|b| b.y * dpr)
                    .fold(f32::INFINITY, f32::min);
                (baseline - first_ascent).min(inline_top)
            }
            None => 0.0,
        };
        let height = if shaped.max_y > anchor { (shaped.max_y - anchor) / dpr } else { 0.0 };
        let mut inline_rects = vec![Rect::new(0.0, 0.0, 0.0, 0.0); rich.inlines.len()];
        for b in &shaped.inline_boxes {
            if let Some(slot) = inline_rects.get_mut(b.id as usize) {
                *slot = Rect::new(b.x, (b.y * dpr - anchor) / dpr, b.width, b.height);
            }
        }
        RichTextLayout { size: Size::new(shaped.max_x / dpr, height), inline_rects }
    })
}

/// 绘制富文本,返回最大行宽(逻辑像素)。
pub fn paint_rich_text(rich: &RichText, offset: Point, list: &mut PaintList, max_width: Option<f32>) -> f32 {
    paint_rich_text_with_default(rich, Color::WHITE, offset, list, max_width)
}

/// 与 [`paint_rich_text`] 相同,但未显式设色的 span 使用 `default_color`。
pub fn paint_rich_text_with_default(
    rich: &RichText,
    default_color: Color,
    offset: Point,
    list: &mut PaintList,
    max_width: Option<f32>,
) -> f32 {
    if rich.is_empty() {
        return 0.0;
    }
    with_font(|fs| {
        let dpr = text_dpr();
        let shaped = shape_rich(fs, rich, max_width);
        let Some(first_run) = shaped.runs.first() else {
            return 0.0;
        };
        let first_baseline = first_run.baseline_y;
        let first_ascent =
            shaped.runs.iter().filter(|r| r.baseline_y == first_baseline).map(|r| r.ascent).fold(0.0f32, f32::max);
        let inline_top = shaped
            .inline_boxes
            .iter()
            .filter(|b| b.line_baseline == first_baseline)
            .map(|b| b.y * dpr)
            .fold(f32::INFINITY, f32::min);
        let anchor = (first_baseline - first_ascent).min(inline_top);

        for run in &shaped.runs {
            for sg in &run.glyphs {
                if !fs.raster_cache.contains_key(&sg.raster_key) {
                    if let Some(rg) =
                        rasterize_one_glyph(&run.font, run.raster_size, sg.glyph_id, &run.norm_coords, &mut fs.scale_cx)
                    {
                        insert_raster_glyph(fs, sg.raster_key, rg);
                    }
                }
                let Some(r) = fs.raster_cache.get_mut(&sg.raster_key) else {
                    continue;
                };
                if r.width == 0 || r.height == 0 {
                    continue;
                }
                fs.glyph_clock += 1;
                r.last_used = fs.glyph_clock;
                let entry = fs.atlas.get_or_insert(sg.raster_key, &r.data, r.width, r.height);

                let x = offset.x + (sg.x + r.left as f32) / dpr;
                let glyph_visual_top = run.baseline_y - r.top as f32;
                let y = offset.y + (glyph_visual_top - anchor) / dpr;
                let rect = Rect::new(x, y, r.width as f32 / dpr, r.height as f32 / dpr);
                let color = rich.spans.get(sg.span as usize).and_then(|s| s.color).unwrap_or(default_color);
                list.push(PaintCommand::TexturedRect {
                    rect,
                    color,
                    uv: entry.uv,
                    texture_id: 0,
                    mode: mgui_core::paint::TextureMode::Mask,
                });
            }
        }
        for b in &shaped.inline_boxes {
            if let Some((_, inline)) = rich.inlines.get(b.id as usize) {
                let rect = Rect::new(offset.x + b.x, offset.y + b.y - anchor / dpr, b.width, b.height);
                (inline.painter)(list, rect);
            }
        }
        shaped.max_x / dpr
    })
}

#[cfg(test)]
mod rich_text_tests {
    use super::*;

    #[test]
    fn mixed_styles_measure_and_paint_with_span_colors() {
        set_text_dpr(1.0);
        let red = Color::from_rgb8(255, 0, 0);
        let rich = RichText::new(vec![
            RichTextSpan::new("Hello ").with_size(18.0).with_color(Color::WHITE),
            RichTextSpan::new("World").with_size(30.0).with_color(red),
        ]);
        let size = rich_text_size(&rich, None);
        assert!(size.width > 0.0, "宽度必须 > 0");
        assert!(size.height >= 30.0, "高度应容纳 30px 字号: {size:?}");

        let mut list = PaintList::new();
        let width = paint_rich_text(&rich, Point::ZERO, &mut list, None);
        assert!((width - size.width).abs() < 0.5, "绘制宽度应与测量一致: {width} vs {}", size.width);
        let colors: Vec<Color> = list
            .commands
            .iter()
            .filter_map(|c| match c {
                PaintCommand::TexturedRect { color, .. } => Some(*color),
                _ => None,
            })
            .collect();
        assert!(colors.contains(&Color::WHITE), "应包含第一段白色字形");
        assert!(colors.contains(&red), "应包含第二段红色字形");
    }

    #[test]
    fn inline_item_measures_paints_and_sits_on_baseline() {
        use std::cell::RefCell;
        set_text_dpr(1.0);
        let captured: std::rc::Rc<RefCell<Option<Rect>>> = std::rc::Rc::new(RefCell::new(None));
        let cap = captured.clone();
        let rich = RichText::from_items(vec![
            RichItem::Text(RichTextSpan::new("A").with_size(16.0)),
            RichItem::Inline(InlineItem::new(30.0, 24.0, move |_list, rect| *cap.borrow_mut() = Some(rect))),
            RichItem::Text(RichTextSpan::new("B").with_size(16.0)),
        ]);
        let size = rich_text_size(&rich, None);
        assert!(size.width >= 30.0, "宽度应包含内联项: {size:?}");
        assert!(size.height >= 20.0, "高度应容纳内联项: {size:?}");

        let mut list = PaintList::new();
        let width = paint_rich_text(&rich, Point::new(10.0, 5.0), &mut list, None);
        assert!(width >= 30.0);
        let rect = captured.borrow().expect("内联项绘制回调应被调用");
        assert!((rect.width - 30.0).abs() < 0.01 && (rect.height - 24.0).abs() < 0.01, "{rect:?}");
        assert!(rect.x >= 10.0 && rect.y >= 5.0, "内联项应带 offset: {rect:?}");
    }

    #[test]
    fn inline_items_wrap_when_narrow() {
        set_text_dpr(1.0);
        let rich = RichText::from_items(vec![
            RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
            RichItem::Inline(InlineItem::new(40.0, 20.0, |_, _| {})),
        ]);
        let one_line = rich_text_size(&rich, None);
        let wrapped = rich_text_size(&rich, Some(50.0));
        assert!(one_line.width > wrapped.width, "窄宽度应减少行宽: {one_line:?} vs {wrapped:?}");
        assert!(
            wrapped.height > one_line.height * 1.5,
            "两个 40 宽内联项在 50 宽内应换行: {one_line:?} vs {wrapped:?}"
        );
    }

    #[test]
    fn soft_wrap_uses_max_width() {
        set_text_dpr(1.0);
        let rich = RichText::new(vec![RichTextSpan::new("word ".repeat(40)).with_size(16.0)]);
        let single = rich_text_size(&rich, None);
        let wrapped = rich_text_size(&rich, Some(120.0));
        assert!(single.height > 0.0 && wrapped.height > 0.0);
        assert!(wrapped.height > single.height * 2.0, "换行后高度应显著增加: {single:?} vs {wrapped:?}");
        assert!(wrapped.width <= 130.0, "换行后宽度应受 max_width 约束: {wrapped:?}");
    }
}

// =============================================================================
// 多行文本 y 定位回归测试
// =============================================================================

#[cfg(test)]
mod multiline_regression {
    use super::*;

    /// 显式换行符 → 两行 y 必须不同(修复前:两行 y 相同 → 完全重叠)
    #[test]
    fn multiline_text_lines_have_distinct_y() {
        let mut list = PaintList::new();
        paint_text_line("第一行AAA\n第二行BBB", 20.0, Color::WHITE, Point::new(50.0, 100.0), &mut list, None);
        let ys: Vec<f32> = list
            .commands
            .iter()
            .filter_map(|c| match c {
                PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
                _ => None,
            })
            .collect();
        assert!(!ys.is_empty(), "应画出 glyph");
        let y0 = ys[0];
        assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "多行文本各行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
    }

    /// 窄 max_width soft-wrap → 两行同样不能重叠
    #[test]
    fn wrapped_text_lines_have_distinct_y() {
        let mut list = PaintList::new();
        // "第一行文本内容比较长" 在 60px 宽下必然折行
        paint_text_line(
            "第一行文本内容比较长需要折行",
            20.0,
            Color::WHITE,
            Point::new(0.0, 0.0),
            &mut list,
            Some(60.0),
        );
        let ys: Vec<f32> = list
            .commands
            .iter()
            .filter_map(|c| match c {
                PaintCommand::TexturedRect { rect, .. } => Some((rect.y * 10.0).round() / 10.0),
                _ => None,
            })
            .collect();
        let y0 = ys[0];
        assert!(ys.iter().any(|&y| (y - y0).abs() > 20.0), "soft-wrap 多行 y 必须拉开,实际全部≈{}: {:?}", y0, ys);
    }
}