nagisa-render 0.7.0

Nagisa typesetting engine: markup / builder documents to images (PNG / WebP)
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
//! 版式引擎 —— 把文档 IR 排成一份**显示列表**(带物理像素坐标的字形 / 矩形 / 图片),交给
//! `paint` 光栅化。纵向块流:维护游标 `y`,逐块测高、定位。行内排版交给 cosmic-text(整形 /
//! 断行 / 字体回退 / CJK+拉丁混排 / 对齐)。
//!
//! **单位**:所有逻辑尺寸(宽 / 内边距 / 字号)在此乘 `scale` 换成设备像素,即一切坐标都是
//! 物理像素。块容器(引用 / 列表项 / 栏 / 单元格)递归排版时收窄可用宽。

use cosmic_text::{Attrs, Buffer, Family, Metrics, Shaping, Style, Weight};

use crate::error::{Error, Result};
use crate::font::FontHandle;
use std::collections::HashMap;

use crate::model::{
    Align, Block, BlockImage, Cell, Color, Column, Columns, Document, FontRole, ImageBorder,
    ImageSource, Inline, Length, List, ListKind, Progress, Table, TextStyle,
};
use crate::theme::{RenderOptions, Theme};

/// 画布单边像素上限(防超大尺寸的整数溢出 / 巨幅分配)。
const MAX_DIM: u32 = 30_000;
/// 画布总像素上限(~40MP,约 160MB RGBA):防 OOM,也保证 i32 像素下标不溢出。
const MAX_AREA: u64 = 40_000_000;
/// 字号(设备像素)安全下限:必须 > 0,否则 cosmic-text 整形零步进会死循环。
const MIN_PX: f32 = 1.0;
/// 字号(设备像素)安全上限:防字形栅格(zeno)整数溢出与单字撑爆画布。
const MAX_PX: f32 = 2_000.0;
/// 图片来源单文件最大字节数(防 `/dev/zero` 之类无 EOF 文件被无界读 → OOM)。
const MAX_IMAGE_BYTES: u64 = 32 * 1024 * 1024;

/// 把字号(设备像素)夹到安全区间:非有限 → 下限;否则夹进 `[MIN_PX, MAX_PX]`。
/// 用户可经 `size` 倍率 / `Theme::base_size` / `heading_scale` 把字号推到 0 或天文数字,
/// 全在此一处兜住。
fn safe_px(px: f32) -> f32 {
    if px.is_finite() {
        px.clamp(MIN_PX, MAX_PX)
    } else {
        MIN_PX
    }
}

/// 排好版的一页:显示列表 + 画布尺寸 + 解码好的内嵌图。
pub(crate) struct Layout {
    pub items: Vec<DisplayItem>,
    pub width_px: u32,
    pub height_px: u32,
    pub images: Vec<image::RgbaImage>,
}

/// 一条绘制原语(坐标均为物理像素)。
pub(crate) enum DisplayItem {
    /// 一批字形(各自带颜色,可带文字阴影)。
    Glyphs(Vec<PlacedGlyph>),
    /// 实心(可圆角)矩形:背景 / 高亮 / 分割线 / 引用条 / 代码底 / 角标底板 / 下划删除等。
    /// 绘制层见 [`RectLayer`]。
    Rect { x: f32, y: f32, w: f32, h: f32, color: Color, radius: f32, layer: RectLayer },
    /// 一张图(`src` 是 `Layout::images` 的下标);`radius > 0` 时圆角裁切图面。
    Image { x: f32, y: f32, w: f32, h: f32, src: usize, radius: f32 },
    /// 投影:模糊圆角矩形,画在图片之前。
    Shadow(ShadowItem),
    /// 描边(可圆角)矩形:图片边框。画在图片之后、字形之前。
    StrokeRect(StrokeItem),
    /// 描边椭圆:文字圈注。画在图片之后、字形之前(与 [`Self::StrokeRect`] 同层)。
    Ellipse { cx: f32, cy: f32, rx: f32, ry: f32, width: f32, color: Color },
}

/// 投影绘制参数(均物理像素;`x`/`y` 已含偏移)。
pub(crate) struct ShadowItem {
    pub x: f32,
    pub y: f32,
    pub w: f32,
    pub h: f32,
    pub radius: f32,
    pub blur: f32,
    pub color: Color,
    /// 垫底影(面板投影):画在衬底矩形之前,免得压暗自家底色;普通影(图片)在衬底之后。
    pub under: bool,
}

/// 描边矩形绘制参数(图片边框;线宽沿路径居中)。
pub(crate) struct StrokeItem {
    pub x: f32,
    pub y: f32,
    pub w: f32,
    pub h: f32,
    pub radius: f32,
    pub width: f32,
    pub color: Color,
}

/// 实心矩形的绘制层:`Under` 在图片与字形之前(衬底:高亮 / 底色 / 分割线),
/// `Mid` 在图片之后、字形之前(角标底板),`Over` 在字形之后(下划 / 删除)。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RectLayer {
    Under,
    Mid,
    Over,
}

/// 定位好的字形:缓存键(给 SwashCache 取位图)+ 笔位(x)/基线(y)+ 颜色 + 可选阴影。
pub(crate) struct PlacedGlyph {
    pub cache_key: cosmic_text::CacheKey,
    pub x: i32,
    pub y: i32,
    pub color: Color,
    pub shadow: Option<GlyphShadow>,
}

/// 字形阴影(物理像素;由 `TextStyle::shadow` 按 scale 折算)。
#[derive(Clone, Copy, Debug)]
pub(crate) struct GlyphShadow {
    pub dx: i32,
    pub dy: i32,
    pub blur: f32,
    pub color: Color,
}

/// 把文档排成显示列表。
pub(crate) fn layout_document(doc: &Document, opts: &RenderOptions) -> Result<Layout> {
    let sc = opts.scale;
    if opts.width <= 0.0 || sc <= 0.0 || !opts.width.is_finite() || !sc.is_finite() {
        return Err(Error::Layout("宽度 / scale 必须为正且有限".into()));
    }
    let pad = opts.padding;
    if [pad.top, pad.right, pad.bottom, pad.left].iter().any(|v| !v.is_finite() || *v < 0.0) {
        return Err(Error::Layout("内边距必须为非负且有限".into()));
    }
    let th = &opts.theme;
    if !th.base_size.is_finite() || th.base_size <= 0.0 || !th.line_height.is_finite() || th.line_height <= 0.0
    {
        return Err(Error::Layout("基准字号 / 行高必须为正且有限".into()));
    }
    let content_w = ((opts.width - pad.left - pad.right) * sc).max(1.0);
    let x_left = pad.left * sc;

    let mut ctx = LayoutCtx { opts, sc, items: Vec::new(), images: Vec::new(), y: pad.top * sc };
    if let Some(c) = &opts.header {
        ctx.chrome_bar(c, x_left, content_w, true);
    }
    for (i, block) in doc.blocks.iter().enumerate() {
        ctx.block(block, x_left, content_w, i == 0);
    }
    // 页脚:色带形态时记下(插入位置, 带顶)——带要铺到画布底,总高得排完才知道。
    let mut footer_band: Option<(usize, f32)> = None;
    if let Some(c) = &opts.footer {
        let idx = ctx.items.len();
        if let Some(band_top) = ctx.chrome_bar(c, x_left, content_w, false) {
            footer_band = Some((idx, band_top));
        }
    }

    let height_f = ctx.y + pad.bottom * sc;
    if !height_f.is_finite() {
        return Err(Error::Layout("内容高度非有限(检查字号 / 图宽 / 内边距)".into()));
    }
    // 满幅色带收尾:贴边铺到画布底。插回页脚自身条目**之前**,免得盖住页脚文字的
    // 衬底装饰(高亮/码片底,同属 Under 层、按入列序绘制)。
    if let Some((idx, band_top)) = footer_band {
        let color = opts.footer.as_ref().and_then(|c| c.band).unwrap_or(opts.theme.border);
        ctx.items.insert(
            idx,
            DisplayItem::Rect {
                x: 0.0,
                y: band_top,
                w: opts.width * sc,
                h: (height_f - band_top).max(0.0),
                color,
                radius: 0.0,
                layer: RectLayer::Under,
            },
        );
    }
    let width_px = (opts.width * sc).round().max(1.0) as u32;
    let height_px = height_f.round().max(1.0) as u32;
    if width_px > MAX_DIM || height_px > MAX_DIM || width_px as u64 * height_px as u64 > MAX_AREA {
        return Err(Error::Layout(format!(
            "画布过大:{width_px}×{height_px}(超出 {MAX_DIM}px 单边 / {MAX_AREA} 像素上限,调小 width / scale 或拆分内容)"
        )));
    }
    Ok(Layout { items: ctx.items, width_px, height_px, images: ctx.images })
}

/// 排版游标 + 输出累积。块在内容区 `[x, x+w)` 内排,递归(引用 / 列表项)时收窄。
struct LayoutCtx<'a> {
    opts: &'a RenderOptions,
    sc: f32,
    items: Vec<DisplayItem>,
    images: Vec<image::RgbaImage>,
    y: f32,
}

impl LayoutCtx<'_> {
    /// 排一个块(`first` 控制是否抑制顶部间距)。
    fn block(&mut self, b: &Block, x: f32, w: f32, first: bool) {
        let base = self.opts.theme.base_size;
        let sc = self.sc;
        match b {
            Block::Heading { level, inlines, align } => {
                let k = self.opts.theme.heading_scale[(*level as usize).clamp(1, 6) - 1];
                let before = if first { 0.0 } else { base * sc * 0.6 };
                self.text_block(inlines, *align, base * k, true, x, w, before, base * sc * 0.3);
            }
            Block::Paragraph { inlines, align } => {
                self.text_block(inlines, *align, base, false, x, w, 0.0, base * sc * 0.55);
            }
            Block::Divider => {
                self.y += base * sc * 0.45;
                let th = (2.0 * sc).max(1.0);
                self.items.push(DisplayItem::Rect {
                    x,
                    y: self.y,
                    w,
                    h: th,
                    color: self.opts.theme.muted,
                    radius: 0.0,
                    layer: RectLayer::Under,
                });
                self.y += th + base * sc * 0.45;
            }
            Block::Quote(inner) => self.quote(inner, x, w),
            Block::Code { lang, text } => self.code(lang.as_deref(), text, x, w),
            Block::List(list) => self.list(list, x, w),
            Block::Image(bi) => self.image(bi, x, w),
            Block::Columns(c) => self.columns(c, x, w),
            Block::Table(t) => self.table(t, x, w),
            Block::Progress(p) => self.progress(p, x, w),
            Block::Panel(p) => {
                self.panel(p, x, w);
            }
        }
    }

    /// 文字块:间距 + 整形定位 + 推进游标。
    #[allow(clippy::too_many_arguments)]
    fn text_block(
        &mut self,
        inlines: &[Inline],
        align: Align,
        base_logical: f32,
        bold: bool,
        x: f32,
        w: f32,
        before: f32,
        after: f32,
    ) {
        self.y += before;
        let h = self.emit_text(inlines, align, base_logical, bold, x, self.y, w);
        self.y += h + after;
    }

    /// 在 `(x, y)` 起、宽 `w` 处整形一段行内内容,推入显示列表,返回其高度(不推进游标)。
    #[allow(clippy::too_many_arguments)]
    fn emit_text(
        &mut self,
        inlines: &[Inline],
        align: Align,
        base_logical: f32,
        bold: bool,
        x: f32,
        y: f32,
        w: f32,
    ) -> f32 {
        let (glyphs, decos, h) = shape_text(
            &self.opts.fonts,
            &self.opts.theme,
            inlines,
            align,
            base_logical,
            bold,
            self.sc,
            w,
            x,
            y,
        );
        self.items.extend(decos);
        if !glyphs.is_empty() {
            self.items.push(DisplayItem::Glyphs(glyphs));
        }
        h
    }

    /// 面板:底色 / 边框 / 圆角 / 内边距 / 投影的卡片容器,递归排内部块。装饰矩形排完
    /// 内容才知道高度,插回到内容条目之前(垫底);返回装饰条目区间起点与个数,
    /// 给并排栏拉齐卡片高度用([`Self::columns`])。
    fn panel(&mut self, p: &crate::model::Panel, x: f32, w: f32) -> (usize, usize) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        let d = &p.decor;
        let pad = safe_px(d.pad.unwrap_or(base * 0.6)) * sc;
        let radius = safe_px(d.radius.unwrap_or(12.0)) * sc;
        // bg 与 border 都缺省 → 主题默认卡片样(浅底 + 细边)。
        let plain = d.bg.is_none() && d.border.is_none();
        let bg = if plain { Some(self.opts.theme.code_bg) } else { d.bg };
        let border = if plain {
            Some(ImageBorder { width: 1.5, color: self.opts.theme.border })
        } else {
            d.border
        };

        self.y += base * sc * 0.35;
        let top = self.y;
        let insert_at = self.items.len();
        self.y += pad;
        for (i, b) in p.blocks.iter().enumerate() {
            self.block(b, x + pad, (w - 2.0 * pad).max(1.0), i == 0);
        }
        let h = (self.y + pad - top).max(2.0 * pad);

        // 装饰条目按固定顺序插回内容之前:影 → 底 → 框(columns 拉齐按此计数)。
        let mut decor: Vec<DisplayItem> = Vec::new();
        if let Some(sh) = &d.shadow {
            decor.push(DisplayItem::Shadow(ShadowItem {
                x: x + sh.dx * sc,
                y: top + sh.dy * sc,
                w,
                h,
                radius,
                blur: (sh.blur * sc).max(0.0),
                color: sh.color,
                under: true,
            }));
        }
        if let Some(c) = bg {
            decor.push(DisplayItem::Rect {
                x,
                y: top,
                w,
                h,
                color: c,
                radius,
                layer: RectLayer::Under,
            });
        }
        if let Some(b) = border {
            decor.push(DisplayItem::StrokeRect(StrokeItem {
                x,
                y: top,
                w,
                h,
                radius,
                width: (b.width * sc).max(1.0),
                color: b.color,
            }));
        }
        let count = decor.len();
        self.items.splice(insert_at..insert_at, decor);

        self.y = top + h + base * sc * 0.35;
        (insert_at, count)
    }

    /// 引用:左侧强调色竖条 + 内缩,递归排内部块;竖条高度按内容算(内容排完再补)。
    fn quote(&mut self, inner: &[Block], x: f32, w: f32) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        self.y += base * sc * 0.3;
        let bar_w = (4.0 * sc).max(2.0);
        let gap = base * sc * 0.45;
        let ix = x + bar_w + gap;
        let iw = (w - bar_w - gap).max(1.0);
        let y0 = self.y;
        for (i, b) in inner.iter().enumerate() {
            self.block(b, ix, iw, i == 0);
        }
        let h = (self.y - y0).max(0.0);
        self.items.push(DisplayItem::Rect {
            x,
            y: y0,
            w: bar_w,
            h,
            color: self.opts.theme.accent,
            radius: bar_w / 2.0,
            layer: RectLayer::Under,
        });
        self.y += base * sc * 0.3;
    }

    /// 代码块:等宽 + 圆角底色盒 + 内边距 + 软换行;有语言标签则在盒内右上角渲染成小字。
    fn code(&mut self, lang: Option<&str>, text: &str, x: f32, w: f32) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        self.y += base * sc * 0.4;
        let pad = base * sc * 0.45;
        let ix = x + pad;
        let iw = (w - 2.0 * pad).max(1.0);
        let y_bg = self.y;
        let mut y_text = y_bg + pad;
        if let Some(l) = lang.map(str::trim).filter(|l| !l.is_empty()) {
            let tag = vec![Inline::Text {
                text: l.to_string(),
                style: TextStyle {
                    font: FontRole::Mono,
                    color: Some(self.opts.theme.muted),
                    size: 0.72,
                    ..TextStyle::default()
                },
            }];
            let th = self.emit_text(&tag, Align::Right, base, false, ix, y_bg + pad * 0.5, iw);
            y_text = y_bg + pad * 0.5 + th + base * sc * 0.1;
        }
        // 语法上色:按语言切词,词上色、空当默认色;认不出的语言整块默认色。
        let mono = |seg: &str, color: Color| Inline::Text {
            text: seg.to_string(),
            style: TextStyle {
                font: FontRole::Mono,
                color: Some(color),
                ..TextStyle::default()
            },
        };
        let pal = self.opts.theme.code_palette;
        let deft = self.opts.theme.code_text;
        let mut inlines = Vec::new();
        let mut cur = 0usize;
        for (r, kind) in crate::highlight::tokenize(lang.unwrap_or(""), text) {
            if r.start > cur {
                inlines.push(mono(&text[cur..r.start], deft));
            }
            let color = match kind {
                crate::highlight::TokenKind::Keyword => pal.keyword,
                crate::highlight::TokenKind::Literal => pal.literal,
                crate::highlight::TokenKind::StringLit => pal.string,
                crate::highlight::TokenKind::Comment => pal.comment,
            };
            inlines.push(mono(&text[r.clone()], color));
            cur = r.end;
        }
        if cur < text.len() {
            inlines.push(mono(&text[cur..], deft));
        }
        if inlines.is_empty() {
            inlines.push(mono(text, deft));
        }
        let h = self.emit_text(&inlines, Align::Left, base, false, ix, y_text, iw);
        let bg_h = y_text + h + pad - y_bg;
        self.items.push(DisplayItem::Rect {
            x,
            y: y_bg,
            w,
            h: bg_h,
            color: self.opts.theme.code_bg,
            radius: 8.0 * sc,
            layer: RectLayer::Under,
        });
        self.y = y_bg + bg_h + base * sc * 0.4;
    }

    /// 列表:gutter 画标记(符号 / 序号 / 任务勾选),内容内缩递归(支持嵌套)。
    /// 标记区按最宽标记自适应(多位数序号不挤不折行),标记右对齐到内容侧。
    fn list(&mut self, list: &List, x: f32, w: f32) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        self.y += base * sc * 0.2;
        let markers: Vec<Vec<Inline>> = list
            .items
            .iter()
            .enumerate()
            .map(|(idx, item)| vec![marker_inline(list, idx, item.check, &self.opts.theme)])
            .collect();
        let zone = markers
            .iter()
            .map(|m| measure_natural(&self.opts.fonts, &self.opts.theme, m, base, false, sc))
            .fold(base * sc, f32::max)
            + 1.0; // 1px 余量,防舍入导致标记在区内折行
        let gap = base * sc * 0.5;
        let gutter = zone + gap;
        let ix = x + gutter;
        let iw = (w - gutter).max(1.0);
        for (item, marker) in list.items.iter().zip(&markers) {
            let y_item = self.y;
            // 标记与该项首行同基线:右对齐排在标记区,不推进游标。
            self.emit_text(marker, Align::Right, base, false, x, y_item, zone);
            for (i, b) in item.blocks.iter().enumerate() {
                self.block(b, ix, iw, i == 0);
            }
            // 空项也至少占一行,避免重叠。
            if self.y <= y_item {
                self.y = y_item + base * sc * self.opts.theme.line_height;
            }
        }
        self.y += base * sc * 0.2;
    }

    /// 块级图:解码 → 等比缩放到目标宽 → 按对齐定位 → 可挂图注。解码失败给个占位提示。
    fn image(&mut self, bi: &BlockImage, x: f32, w: f32) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        self.y += base * sc * 0.3;

        let Some(rgba) = decode_image(&bi.src, &self.opts.images) else {
            let ph = vec![Inline::Text {
                text: "⟨图片缺失⟩".to_string(),
                style: TextStyle { color: Some(self.opts.theme.muted), ..TextStyle::default() },
            }];
            let h = self.emit_text(&ph, Align::Left, base, false, x, self.y, w);
            self.y += h + base * sc * 0.4;
            return;
        };

        let (iw, ih) = (rgba.width() as f32, rgba.height() as f32);
        let req = match bi.width {
            Some(Length::Px(p)) => p * sc,
            Some(Length::Percent(pct)) => w * (pct / 100.0),
            None => iw.min(w), // 不放大超过原图,过宽则缩到内容宽
        };
        // 非有限(NaN/inf)请求宽退回自然宽,否则游标会变 NaN 让整页坍成 1px(静默丢内容)。
        let dw = if req.is_finite() { req } else { iw.min(w) }.clamp(1.0, w.max(1.0));
        let dh = if iw > 0.0 { dw * ih / iw } else { dw };

        let ix = match bi.align {
            Align::Center => x + (w - dw) / 2.0,
            Align::Right => x + (w - dw),
            _ => x,
        };
        let src = self.images.len();
        self.images.push(rgba);
        let radius = if bi.decor.radius.is_finite() { (bi.decor.radius * sc).max(0.0) } else { 0.0 };
        // 投影先于图片入列(画在衬底之后、图片之前),位置已含偏移。
        if let Some(sh) = &bi.decor.shadow {
            self.items.push(DisplayItem::Shadow(ShadowItem {
                x: ix + sh.dx * sc,
                y: self.y + sh.dy * sc,
                w: dw,
                h: dh,
                radius,
                blur: (sh.blur * sc).max(0.0),
                color: sh.color,
                under: false,
            }));
        }
        self.items.push(DisplayItem::Image { x: ix, y: self.y, w: dw, h: dh, src, radius });
        self.image_overlay(&bi.decor, ix, self.y, dw, dh, radius);
        self.y += dh;

        if let Some(cap) = &bi.caption {
            self.y += base * sc * 0.2;
            // 图注居中到图片正下方(不是整个内容宽)——图不居中时也不脱节;
            // 极窄图给个 4em 下限,免得图注一字一行。
            let cap_w = dw.max(base * sc * 4.0).min(w.max(1.0));
            let cap_x = (ix + dw / 2.0 - cap_w / 2.0).clamp(x, x + (w - cap_w).max(0.0));
            let h = self.emit_text(cap, Align::Center, base * 0.85, false, cap_x, self.y, cap_w);
            self.y += h;
        }
        self.y += base * sc * 0.4;
    }

    /// 页眉 / 页脚条:一行小字(可富文本,可带右对齐的行尾段)+ 可选细线 / 满幅色带。
    /// `top = true` 排在内容前(字在上、线在下),否则排在内容后(线在上、字在下)。
    /// 未显式上色的 span 染缺省色(主题次要色)。页脚设了 `band` 时不画细线、只记**带顶 y**
    /// 返回——色带矩形要铺到画布底,总高此刻未知,由 `layout_document` 收尾时补画。
    fn chrome_bar(&mut self, c: &crate::theme::PageChrome, x: f32, w: f32, top: bool) -> Option<f32> {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        let px = base * c.size;
        let ink = c.color.unwrap_or(self.opts.theme.muted);
        let hairline = (1.0 * sc).max(1.0);
        // 行盒的半行距(行高超出字号的部分,上下各摊一半):墨迹并不顶着行盒边沿,
        // 对称留白要按**墨迹**算,从间距里扣掉它。
        let line_pad = px * sc * (self.opts.theme.line_height - 1.0) / 2.0;
        if top {
            // 字带在「画布顶 → 细线」之间上下居中:字下间距取与顶边距相同(至少 0.35em)。
            let h = self.chrome_line(c, ink, px, x, w);
            self.y += h + (self.opts.padding.top * sc - line_pad).max(base * sc * 0.35);
            if c.rule {
                self.items.push(DisplayItem::Rect {
                    x,
                    y: self.y,
                    w,
                    h: hairline,
                    color: self.opts.theme.border,
                    radius: 0.0,
                    layer: RectLayer::Under,
                });
                self.y += hairline;
            }
            self.y += base * sc * 0.5;
            None
        } else if c.band.is_some() {
            // 色带式:与内容空 0.6em,带从这里铺到画布底;带内上沿留白取底边距
            // (与带下沿即画布底边距对称),文字坐在带的纵向正中。
            self.y += base * sc * 0.6;
            let band_top = self.y;
            self.y += (self.opts.padding.bottom * sc - line_pad).max(base * sc * 0.5);
            let h = self.chrome_line(c, ink, px, x, w);
            self.y += h;
            Some(band_top)
        } else {
            self.y += base * sc * 0.6;
            if c.rule {
                self.items.push(DisplayItem::Rect {
                    x,
                    y: self.y,
                    w,
                    h: hairline,
                    color: self.opts.theme.border,
                    radius: 0.0,
                    layer: RectLayer::Under,
                });
                self.y += hairline;
            }
            // 字带在「细线 → 画布底」之间上下居中:线下间距取与底边距相同(至少 0.35em)
            // ——否则字吊在线下、底下一大段留白,观感像没对齐。
            self.y += (self.opts.padding.bottom * sc - line_pad).max(base * sc * 0.35);
            let h = self.chrome_line(c, ink, px, x, w);
            self.y += h;
            None
        }
    }

    /// 页眉/页脚的一行:主段按 `c.align` 排,行尾段(若有)右对齐同一行;未显式上色的
    /// span 染 `ink`。返回行高(两段取高者),不推进游标。
    fn chrome_line(
        &mut self,
        c: &crate::theme::PageChrome,
        ink: Color,
        px: f32,
        x: f32,
        w: f32,
    ) -> f32 {
        let fill = |src: &[Inline]| -> Vec<Inline> {
            src.iter()
                .cloned()
                .map(|mut i| {
                    if let Inline::Text { style, .. } = &mut i {
                        if style.color.is_none() {
                            style.color = Some(ink);
                        }
                    }
                    i
                })
                .collect()
        };
        let main = fill(&c.inlines);
        let h1 = self.emit_text(&main, c.align, px, false, x, self.y, w);
        let h2 = match &c.trailing {
            Some(t) => {
                let t = fill(t);
                self.emit_text(&t, Align::Right, px, false, x, self.y, w)
            }
            None => 0.0,
        };
        h1.max(h2)
    }

    /// 图面装饰层:边框(描边随圆角)/ 角标(圆角底板 + 文字)/ 水印(半透明文字)。
    /// 全部叠在图面坐标系内,不动游标、不改布局尺寸。`radius` 已是物理像素。
    fn image_overlay(
        &mut self,
        decor: &crate::model::ImageDecor,
        ix: f32,
        iy: f32,
        dw: f32,
        dh: f32,
        radius: f32,
    ) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        let line_mult = self.opts.theme.line_height;

        if let Some(b) = &decor.border {
            self.items.push(DisplayItem::StrokeRect(StrokeItem {
                x: ix,
                y: iy,
                w: dw,
                h: dh,
                radius,
                width: (b.width * sc).max(1.0),
                color: b.color,
            }));
        }

        if let Some(badge) = &decor.badge {
            let px = base * badge.size; // 逻辑字号
            let inl = [Inline::Text {
                text: badge.text.clone(),
                style: TextStyle { color: Some(badge.fg), ..TextStyle::default() },
            }];
            let tw = measure_natural(&self.opts.fonts, &self.opts.theme, &inl, px, false, sc);
            let line_h = px * sc * line_mult;
            let (pad_x, pad_y) = (px * sc * 0.45, px * sc * 0.12);
            let (bw, bh) = (tw + pad_x * 2.0, line_h + pad_y * 2.0);
            let margin = px * sc * 0.5;
            let (bx, by) = anchor_pos(badge.anchor, (ix, iy, dw, dh), (bw, bh), margin);
            self.items.push(DisplayItem::Rect {
                x: bx,
                y: by,
                w: bw,
                h: bh,
                color: badge.bg,
                radius: bh * 0.25,
                layer: RectLayer::Mid,
            });
            // +2px 余量防舍入折行;字形阶段天然画在 Mid 底板之上。
            self.emit_text(&inl, Align::Left, px, false, bx + pad_x, by + pad_y, tw + 2.0);
        }

        if let Some(wm) = &decor.watermark {
            let px = base * wm.size;
            let inl = [Inline::Text {
                text: wm.text.clone(),
                style: TextStyle { color: Some(wm.color), ..TextStyle::default() },
            }];
            let tw = measure_natural(&self.opts.fonts, &self.opts.theme, &inl, px, false, sc);
            let line_h = px * sc * line_mult;
            let margin = px * sc * 0.5;
            let (wx, wy) = anchor_pos(wm.anchor, (ix, iy, dw, dh), (tw, line_h), margin);
            self.emit_text(&inl, Align::Left, px, false, wx, wy, tw + 2.0);
        }
    }

    /// 显式并排栏:按 `weight` 瓜分(减去栏间距后的)可用宽,每栏独立排块,行高取最高栏(顶对齐)。
    fn columns(&mut self, c: &Columns, x: f32, w: f32) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        let cols: Vec<&Column> = c.cols.iter().filter(|col| col.weight > 0.0).collect();
        if cols.is_empty() {
            return;
        }
        self.y += base * sc * 0.3;
        // 不套 safe_px:MIN_PX=1 会把合法的 gap=0 抬成 1;只拦非有限与负值。
        let gap = c.gap.filter(|g| g.is_finite() && *g >= 0.0).map(|g| g * sc).unwrap_or(base * sc * 0.6);
        let avail = (w - gap * (cols.len() - 1) as f32).max(1.0);
        let total_w: f32 = cols.iter().map(|col| col.weight).sum();

        let y_top = self.y;
        let mut cx = x;
        let mut max_h = 0.0f32;
        // (装饰条目区间起点, 个数, 影的纵向偏移):单面板栏记下,行高定了再拉齐。
        let mut stretch: Vec<(usize, usize, f32)> = Vec::new();
        for col in cols {
            let cw = (avail * col.weight / total_w).max(1.0);
            let offset = self.items.len();
            let (items, images, y_bottom) = self.sub_layout(&col.blocks, cx, y_top, cw);
            self.merge(items, images);
            // 整栏只有一个面板 → 卡片栏:装饰条目固定在该栏条目区间起点(面板先插装饰),
            // 个数与 [`Self::panel`] 的插入逻辑一致:影 → 底 → 框。
            if let [Block::Panel(p)] = col.blocks.as_slice() {
                let plain = p.decor.bg.is_none() && p.decor.border.is_none();
                let n = usize::from(p.decor.shadow.is_some())
                    + usize::from(plain || p.decor.bg.is_some())
                    + usize::from(plain || p.decor.border.is_some());
                let shadow_dy = p.decor.shadow.as_ref().map(|sh| sh.dy * sc).unwrap_or(0.0);
                stretch.push((offset, n, shadow_dy));
            }
            max_h = max_h.max(y_bottom - y_top);
            cx += cw + gap;
        }
        // 卡片拉齐:装饰盒底边对齐到本行最高栏的面板底(行底减面板的后间距)。
        let target_bottom = y_top + max_h - base * sc * 0.35;
        for (at, n, shadow_dy) in stretch {
            for item in self.items.iter_mut().skip(at).take(n) {
                match item {
                    DisplayItem::Shadow(s) => s.h = (target_bottom + shadow_dy - s.y).max(s.h),
                    DisplayItem::Rect { y, h, .. } => *h = (target_bottom - *y).max(*h),
                    DisplayItem::StrokeRect(s) => s.h = (target_bottom - s.y).max(s.h),
                    _ => {}
                }
            }
        }
        self.y = y_top + max_h + base * sc * 0.3;
    }

    /// 子布局:在 `(x, y_top)` 起、宽 `w`,把一段块排进一个独立累积,返回 `(绘制项, 解码图, 底部 y)`。
    /// 不动主游标;坐标已是绝对物理像素。
    fn sub_layout(
        &self,
        blocks: &[Block],
        x: f32,
        y_top: f32,
        w: f32,
    ) -> (Vec<DisplayItem>, Vec<image::RgbaImage>, f32) {
        let mut sub = LayoutCtx {
            opts: self.opts,
            sc: self.sc,
            items: Vec::new(),
            images: Vec::new(),
            y: y_top,
        };
        for (i, b) in blocks.iter().enumerate() {
            sub.block(b, x, w, i == 0);
        }
        (sub.items, sub.images, sub.y)
    }

    /// 把子布局结果并入主累积:图片 `src` 下标按当前图集长度偏移。
    fn merge(&mut self, items: Vec<DisplayItem>, images: Vec<image::RgbaImage>) {
        let offset = self.images.len();
        self.images.extend(images);
        for mut it in items {
            if let DisplayItem::Image { src, .. } = &mut it {
                *src += offset;
            }
            self.items.push(it);
        }
    }

    /// 表格:求列宽(自适应 + 手动限宽)→ 逐行排(表头加粗+浅底)→ 行底分隔线。
    fn table(&mut self, t: &Table, x: f32, w: f32) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        let ncols = t
            .header
            .as_ref()
            .map(|h| h.len())
            .into_iter()
            .chain(t.rows.iter().map(|r| r.len()))
            .chain(std::iter::once(t.cols.len()))
            .max()
            .unwrap_or(0);
        if ncols == 0 {
            return;
        }
        self.y += base * sc * 0.3;
        // 不套 safe_px(MIN_PX=1 吃掉合法的 0):只拦非有限与负值,缺省回主题口径。
        let pad = t.style.pad_x.filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(base * 0.32) * sc;
        let pad_v = t.style.pad_y.filter(|v| v.is_finite() && *v >= 0.0).unwrap_or(base * 0.26) * sc;
        let widths = self.solve_widths(t, ncols, w, pad);

        let table_w: f32 = widths.iter().sum();
        // 窄表水平对齐(铺满时没有富余,偏移自然为 0)。
        let x = x + match t.style.align {
            Align::Center => ((w - table_w) / 2.0).max(0.0),
            Align::Right => (w - table_w).max(0.0),
            Align::Left | Align::Justify => 0.0,
        };
        let mut col_x = Vec::with_capacity(ncols);
        let mut cx = x;
        for &cw in &widths {
            col_x.push(cx);
            cx += cw;
        }

        // 排各行,记录行间内部边界 y(用于横线)。
        let table_top = self.y;
        let mut inner = Vec::new();
        if let Some(h) = &t.header {
            self.table_row(h, t, &widths, &col_x, x, table_w, true, pad, pad_v);
            inner.push(self.y);
        }
        for row in &t.rows {
            self.table_row(row, t, &widths, &col_x, x, table_w, false, pad, pad_v);
            inner.push(self.y);
        }
        let table_bottom = self.y;
        inner.pop(); // 末行底边归外框,不算内部横线

        // 网格线(细、淡 border 色),按开关画。
        let line = (1.0 * sc).max(1.0);
        let border = self.opts.theme.border;
        let grid = t.style.grid;
        if grid.horizontal {
            for &yb in &inner {
                self.items.push(hrule(x, yb, table_w, line, border));
            }
        }
        if grid.outer {
            for yb in [table_top, table_bottom] {
                self.items.push(hrule(x, yb, table_w, line, border));
            }
        }
        if grid.vertical {
            for &vx in col_x.iter().skip(1) {
                self.items.push(vrule(vx, table_top, table_bottom, line, border));
            }
        }
        if grid.outer {
            for vx in [x, x + table_w] {
                self.items.push(vrule(vx, table_top, table_bottom, line, border));
            }
        }
        self.y += base * sc * 0.3;
    }

    /// 进度条:底槽 + 按 `value` 比例的填充,同半径两层圆角矩形;窄于内容宽时按对齐定位。
    fn progress(&mut self, p: &Progress, x: f32, w: f32) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        let bw = match p.width {
            Some(Length::Px(v)) => (safe_px(v) * sc).clamp(1.0, w.max(1.0)),
            Some(Length::Percent(pct)) => {
                let pct = if pct.is_finite() { pct.clamp(0.0, 100.0) } else { 100.0 };
                (w * pct / 100.0).clamp(1.0, w.max(1.0))
            }
            None => w.max(1.0),
        };
        let bx = match p.align {
            Align::Center => x + (w - bw) / 2.0,
            Align::Right => x + w - bw,
            Align::Left | Align::Justify => x,
        };
        let h = safe_px(p.height) * sc;
        // 显式半径只需非负有限(0 = 直角),上限由半高封顶;缺省即胶囊。
        let r = match p.radius {
            Some(v) if v.is_finite() && v > 0.0 => (v * sc).min(h / 2.0),
            Some(_) => 0.0,
            None => h / 2.0,
        };
        let value = if p.value.is_finite() { p.value.clamp(0.0, 1.0) } else { 0.0 };

        self.y += base * sc * 0.3;
        let track = p.track.unwrap_or(self.opts.theme.border);
        self.items.push(DisplayItem::Rect {
            x: bx,
            y: self.y,
            w: bw,
            h,
            color: track,
            radius: r,
            layer: RectLayer::Under,
        });
        if value > 0.0 {
            // 填充不短于两端圆角(更短的圆角矩形画出来破相),封顶条宽。
            let fw = (bw * value).max((2.0 * r).min(bw));
            let fill = p.fill.unwrap_or(self.opts.theme.accent);
            self.items.push(DisplayItem::Rect {
                x: bx,
                y: self.y,
                w: fw,
                h,
                color: fill,
                radius: r,
                layer: RectLayer::Under,
            });
        }
        self.y += h + base * sc * 0.55;
    }

    /// 排一行(表头或数据行):各单元格在列内按对齐排,行高取最高;表头浅底(可关)+ 单元格背景。
    /// 不画分隔线(交给 [`Self::table`] 统一按开关画);游标推进到行底。
    #[allow(clippy::too_many_arguments)]
    fn table_row(
        &mut self,
        cells: &[Cell],
        t: &Table,
        widths: &[f32],
        col_x: &[f32],
        table_x: f32,
        table_w: f32,
        header: bool,
        pad: f32,
        pad_v: f32,
    ) {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        let row_top = self.y;
        let y_text = row_top + pad_v;
        let insert_at = self.items.len(); // 行底色插回此处:垫在文字装饰(高亮/码底)之下
        let mut content_h = 0.0f32;
        for (k, cell) in cells.iter().enumerate() {
            if k >= widths.len() {
                break;
            }
            let align = t.cols.get(k).map(|c| c.align).unwrap_or(Align::Left);
            let cwidth = (widths[k] - 2.0 * pad).max(1.0);
            let h = self.emit_text(&cell.inlines, align, base, header, col_x[k] + pad, y_text, cwidth);
            content_h = content_h.max(h);
        }
        if content_h <= 0.0 {
            content_h = base * sc * self.opts.theme.line_height;
        }
        let row_bottom = y_text + content_h + pad_v;
        let mut fills: Vec<DisplayItem> = Vec::new();
        if header && t.style.header_fill {
            fills.push(DisplayItem::Rect {
                x: table_x,
                y: row_top,
                w: table_w,
                h: row_bottom - row_top,
                color: self.opts.theme.code_bg,
                radius: 0.0,
                layer: RectLayer::Under,
            });
        }
        // 单元格背景填色(盖在表头浅底之上、文字装饰之下)。
        for (k, cell) in cells.iter().enumerate() {
            if k >= widths.len() {
                break;
            }
            if let Some(bg) = cell.bg {
                fills.push(DisplayItem::Rect {
                    x: col_x[k],
                    y: row_top,
                    w: widths[k],
                    h: row_bottom - row_top,
                    color: bg,
                    radius: 0.0,
                    layer: RectLayer::Under,
                });
            }
        }
        self.items.splice(insert_at..insert_at, fills);
        self.y = row_bottom;
    }

    /// 求各列总宽(含内边距):手动限宽列固定;其余列取自然宽,总宽超出可用时按自然宽比例压缩。
    fn solve_widths(&self, t: &Table, ncols: usize, avail_w: f32, pad: f32) -> Vec<f32> {
        let (base, sc) = (self.opts.theme.base_size, self.sc);
        let min_w = 2.0 * pad + 1.0;

        // 各自动列的自然内容宽(表头按加粗测、更宽)。
        let mut natural = vec![0f32; ncols];
        let measure = |cells: &[Cell], bold: bool, natural: &mut [f32]| {
            for (k, cell) in cells.iter().enumerate() {
                if k < ncols {
                    let nw =
                        measure_natural(&self.opts.fonts, &self.opts.theme, &cell.inlines, base, bold, sc);
                    natural[k] = natural[k].max(nw);
                }
            }
        };
        if let Some(h) = &t.header {
            measure(h, true, &mut natural);
        }
        for row in &t.rows {
            measure(row, false, &mut natural);
        }

        let mut widths = vec![0f32; ncols];
        let mut auto = Vec::new();
        let (mut auto_sum, mut fixed_sum) = (0.0f32, 0.0f32);
        for (k, wid) in widths.iter_mut().enumerate() {
            match t.cols.get(k).and_then(|c| c.width) {
                // 非有限限宽值按自适应处理(否则污染总宽 / 越界)。
                Some(Length::Px(p)) if p.is_finite() => {
                    *wid = (p * sc).max(min_w);
                    fixed_sum += *wid;
                }
                Some(Length::Percent(pct)) if pct.is_finite() => {
                    *wid = (avail_w * pct / 100.0).clamp(min_w, avail_w.max(min_w));
                    fixed_sum += *wid;
                }
                _ => {
                    *wid = natural[k] + 2.0 * pad;
                    auto.push(k);
                    auto_sum += *wid;
                }
            }
        }
        let total: f32 = widths.iter().sum();
        if total > avail_w && !auto.is_empty() && auto_sum > 0.0 {
            // 先让自适应列吸收溢出。
            let remaining = (avail_w - fixed_sum).max(min_w * auto.len() as f32);
            for &k in &auto {
                widths[k] = (widths[k] / auto_sum * remaining).max(min_w);
            }
        }
        // 仍超出(固定列 / 百分比之和本就 > 可用宽)→ 整体等比缩回画布,
        // 否则超出部分会画到画布外、内容静默丢失。
        let total: f32 = widths.iter().sum();
        if total > avail_w && total > 0.0 {
            let factor = avail_w / total;
            for wid in widths.iter_mut() {
                *wid = (*wid * factor).max(1.0);
            }
        }
        // expand:列宽合计不足可用宽 → 富余按比例分给自适应列(全固定列则整体等比放大)。
        let total: f32 = widths.iter().sum();
        if t.style.expand && total > 0.0 && total < avail_w {
            if !auto.is_empty() {
                let auto_total: f32 = auto.iter().map(|&k| widths[k]).sum();
                if auto_total > 0.0 {
                    let extra = avail_w - total;
                    for &k in &auto {
                        widths[k] += extra * (widths[k] / auto_total);
                    }
                }
            } else {
                let factor = avail_w / total;
                for wid in widths.iter_mut() {
                    *wid *= factor;
                }
            }
        }
        widths
    }
}

/// 一个列表项的 gutter 标记:任务项 `✓`(强调色)/ `□`(次要色),无序 `•`,有序 `{n}.`。
/// 勾选符用内置字体确定覆盖的 `□`/`✓`(`☐`/`☑` 内置字体没有,裸环境会出 tofu)。
fn marker_inline(list: &List, idx: usize, check: Option<bool>, theme: &Theme) -> Inline {
    let (text, color) = match check {
        Some(true) => ("".to_string(), theme.accent),
        Some(false) => ("".to_string(), theme.muted),
        None => match list.kind {
            ListKind::Unordered => ("".to_string(), theme.accent),
            ListKind::Ordered => (format!("{}.", list.start as usize + idx), theme.accent),
        },
    };
    Inline::Text { text, style: TextStyle { color: Some(color), ..TextStyle::default() } }
}

/// 解码图片来源为 RGBA。`Named` 从 `images` 映射取字节,`Path` 读盘,`Bytes` 直接用。
fn decode_image(src: &ImageSource, images: &HashMap<String, Vec<u8>>) -> Option<image::RgbaImage> {
    let bytes: std::borrow::Cow<[u8]> = match src {
        ImageSource::Bytes(b) => std::borrow::Cow::Borrowed(b),
        ImageSource::Named(n) => std::borrow::Cow::Borrowed(images.get(n)?.as_slice()),
        ImageSource::Path(p) => std::borrow::Cow::Owned(read_image_file(p)?),
    };
    image::load_from_memory(&bytes).ok().map(|i| i.to_rgba8())
}

/// 安全读图片文件:只认普通文件,且至多读 [`MAX_IMAGE_BYTES`]。
/// `/dev/zero`、FIFO 等非普通或无 EOF 文件被拒,不会无界读爆内存。
fn read_image_file(p: &std::path::Path) -> Option<Vec<u8>> {
    use std::io::Read;
    if !std::fs::metadata(p).ok()?.is_file() {
        return None;
    }
    let mut buf = Vec::new();
    std::fs::File::open(p).ok()?.take(MAX_IMAGE_BYTES).read_to_end(&mut buf).ok()?;
    Some(buf)
}

/// 一个 span 的装饰信息(按 `Attrs::metadata` 下标索引回查)。
struct SpanDeco {
    underline: bool,
    strike: bool,
    highlight: Option<Color>,
    code_bg: Option<Color>,
    /// 圈注(颜色已解析、定径/线宽已折算物理像素;`None` = 无)。
    ring: Option<RingDeco>,
    /// 着重点(同上)。
    dot: Option<DotDeco>,
    ink: Color,
    /// 文字阴影(已折算成物理像素);字形定位时带走。
    shadow: Option<GlyphShadow>,
}

/// 已解析的圈注:`rx`/`ry`/`width` 为物理像素,`None` 分量在绘制时按字号自适应;
/// `each` = 逐字一圈。
struct RingDeco {
    color: Color,
    rx: Option<f32>,
    ry: Option<f32>,
    width: Option<f32>,
    each: bool,
}

/// 已解析的着重点:`radius` 为物理像素,`None` 在绘制时按字号自适应;`each` = 逐字一点。
struct DotDeco {
    color: Color,
    radius: Option<f32>,
    each: bool,
}

/// 用 cosmic-text 整形一段行内内容,产出定位好的字形、装饰矩形与该块高度(物理像素)。
#[allow(clippy::too_many_arguments)]
fn shape_text(
    fonts: &FontHandle,
    theme: &Theme,
    inlines: &[Inline],
    align: Align,
    base_logical: f32,
    base_bold: bool,
    sc: f32,
    width: f32,
    x_left: f32,
    y_top: f32,
) -> (Vec<PlacedGlyph>, Vec<DisplayItem>, f32) {
    let line_mult = theme.line_height;
    let default_px = safe_px(base_logical * sc);
    // metadata=usize::MAX ⇒ 无装饰(默认 / 换行用)。
    let default_attrs = base_attrs()
        .family(Family::Name(&theme.font_sans))
        .color(to_cosmic(theme.text))
        .metrics(Metrics::new(default_px, default_px * line_mult))
        .metadata(usize::MAX);

    // 边注与正文分离:边注不进主 buffer——行宽与居中 / 对齐都按正文算,边注另行
    // 整形后挂到首 / 末行内容盒外侧。整段只有边注没有正文时,边注失去锚点,按普通
    // 内容排(aside 标记被整形忽略,不致丢字)。
    use crate::model::AsideSide;
    let side_of = |i: &Inline| match i {
        Inline::Text { style, .. } => style.aside,
        _ => None,
    };
    let mut main_part: Vec<Inline> = Vec::new();
    let mut asides: [Vec<Inline>; 2] = [Vec::new(), Vec::new()]; // [左, 右]
    if inlines.iter().any(|i| side_of(i).is_some()) {
        for i in inlines {
            match side_of(i) {
                Some(AsideSide::Left) => asides[0].push(i.clone()),
                Some(AsideSide::Right) => asides[1].push(i.clone()),
                None => main_part.push(i.clone()),
            }
        }
        if main_part.is_empty() {
            main_part = inlines.to_vec();
            asides = [Vec::new(), Vec::new()];
        }
    } else {
        main_part = inlines.to_vec();
    }

    let (spans, decos) = build_spans(&main_part, theme, base_logical, base_bold, sc, &default_attrs);

    fonts.with_system(|fs| {
        let mut buf = Buffer::new(fs, Metrics::new(default_px, default_px * line_mult));
        buf.set_size(Some(width), None);
        buf.set_rich_text(
            spans.iter().map(|(t, a)| (*t, a.clone())),
            &default_attrs,
            Shaping::Advanced,
            Some(align_to_cosmic(align)),
        );
        buf.shape_until_scroll(fs, false);

        let xi = x_left.round() as i32;
        let mut glyphs = Vec::new();
        let mut deco_rects = Vec::new();
        let mut height = 0.0f32;
        // 首 / 末行的基线与内容盒横向边界(对齐偏移已含在字形坐标里),给边注锚定用。
        let mut first_line: Option<(f32, f32)> = None; // (line_y, 内容左缘)
        let mut last_line: Option<(f32, f32)> = None; // (line_y, 内容右缘)
        for run in buf.layout_runs() {
            let (mut lo, mut hi) = (f32::MAX, f32::MIN);
            for g in run.glyphs {
                let p = g.physical((0.0, 0.0), 1.0);
                let color = g.color_opt.map(from_cosmic).unwrap_or(theme.text);
                glyphs.push(PlacedGlyph {
                    cache_key: p.cache_key,
                    x: xi + p.x,
                    y: (y_top + run.line_y).round() as i32 + p.y,
                    color,
                    shadow: decos.get(g.metadata).and_then(|d| d.shadow),
                });
                lo = lo.min(g.x);
                hi = hi.max(g.x + g.w);
            }
            collect_decos(&run, &decos, x_left, y_top, &mut deco_rects);
            height = height.max(run.line_top + run.line_height);
            if !run.glyphs.is_empty() {
                first_line.get_or_insert((run.line_y, lo));
                last_line = Some((run.line_y, hi));
            }
        }

        // 边注:各侧单独整形(不限宽不换行),左挂首行、右挂末行,基线对齐锚行,
        // 与正文隔半个基准字号。只画不占位,溢出画布的部分由绘制层裁掉。
        let gap = default_px * 0.5;
        for (k, aside) in asides.iter().enumerate() {
            if aside.is_empty() {
                continue;
            }
            let anchor = if k == 0 { first_line } else { last_line };
            let Some((anchor_y, edge)) = anchor else { continue };
            let (aspans, adecos) =
                build_spans(aside, theme, base_logical, base_bold, sc, &default_attrs);
            let mut abuf = Buffer::new(fs, Metrics::new(default_px, default_px * line_mult));
            abuf.set_size(None, None);
            abuf.set_rich_text(
                aspans.iter().map(|(t, a)| (*t, a.clone())),
                &default_attrs,
                Shaping::Advanced,
                None,
            );
            abuf.shape_until_scroll(fs, false);
            let aw = abuf.layout_runs().map(|r| r.line_w).fold(0.0, f32::max);
            let ax_left = if k == 0 { x_left + edge - gap - aw } else { x_left + edge + gap };
            let axi = ax_left.round() as i32;
            // 首行基线对齐锚行基线;边注自带换行时后续行顺延其下。
            let Some(first_y) = abuf.layout_runs().next().map(|r| r.line_y) else { continue };
            let ay_top = y_top + anchor_y - first_y;
            for run in abuf.layout_runs() {
                for g in run.glyphs {
                    let p = g.physical((0.0, 0.0), 1.0);
                    let color = g.color_opt.map(from_cosmic).unwrap_or(theme.text);
                    glyphs.push(PlacedGlyph {
                        cache_key: p.cache_key,
                        x: axi + p.x,
                        y: (ay_top + run.line_y).round() as i32 + p.y,
                        color,
                        shadow: adecos.get(g.metadata).and_then(|d| d.shadow),
                    });
                }
                collect_decos(&run, &adecos, ax_left, ay_top, &mut deco_rects);
            }
        }
        (glyphs, deco_rects, height)
    })
}

/// 把行内序列构建成 cosmic-text 富文本跨段 + 各段装饰信息。shape_text 与自然宽测量共用。
#[allow(clippy::type_complexity)]
fn build_spans<'a>(
    inlines: &'a [Inline],
    theme: &'a Theme,
    base_logical: f32,
    base_bold: bool,
    sc: f32,
    default_attrs: &Attrs<'a>,
) -> (Vec<(&'a str, Attrs<'a>)>, Vec<SpanDeco>) {
    let line_mult = theme.line_height;
    let mut spans: Vec<(&str, Attrs)> = Vec::new();
    let mut decos: Vec<SpanDeco> = Vec::new();
    for inline in inlines {
        match inline {
            Inline::Text { text, style } => {
                let idx = decos.len();
                let px = safe_px(base_logical * style.size * sc);
                // 链接无显式色时用主题强调色。
                let fallback = if style.link { theme.accent } else { theme.text };
                let ink = style.color.unwrap_or(fallback);
                let mut a = base_attrs()
                    .family(family_of(&style.font, theme))
                    .color(to_cosmic(ink))
                    .metrics(Metrics::new(px, px * line_mult))
                    .metadata(idx);
                let mut weight = match style.weight {
                    Some(w) => Weight(w),
                    None if base_bold => Weight::BOLD,
                    None => Weight::NORMAL,
                };
                // 默认楷体字族(霞鹜文楷)只有 300/400/500 三档,而 cosmic-text 对族内
                // 没有的字重会跨族借字(比如 700 借到黑体 Bold),楷体语境就丢了楷体——
                // 故夹到族内范围:细 → 300,粗 → 500(族内最重,当楷体的「粗」)。
                if matches!(style.font, FontRole::Kai) {
                    weight = Weight(weight.0.clamp(300, 500));
                }
                a = a.weight(weight);
                if style.italic {
                    a = a.style(Style::Italic);
                }
                // emoji 表现序列切到彩色 emoji 字族——黑体自带一批 emoji 的单色字面,
                // 请求字族先命中会抢跑,同一行 emoji 一半黑白一半彩色;切段后统一彩色,
                // 字体缺失时按 cosmic-text 回退,不丢字。装饰共用同一条(metadata 同 idx)。
                for (seg, emoji) in emoji_runs(text) {
                    if emoji {
                        spans.push((seg, a.clone().family(Family::Name(&theme.font_emoji))));
                    } else {
                        spans.push((seg, a.clone()));
                    }
                }
                decos.push(SpanDeco {
                    underline: style.underline,
                    strike: style.strike,
                    highlight: resolve_highlight(style.highlight, theme),
                    code_bg: None,
                    ring: style.ring.map(|m| RingDeco {
                        color: m.color.unwrap_or(ink),
                        rx: m.rx.map(|v| safe_px(v) * sc),
                        ry: m.ry.map(|v| safe_px(v) * sc),
                        width: m.width.map(|v| safe_px(v) * sc),
                        each: m.each,
                    }),
                    dot: style.dot.map(|m| DotDeco {
                        color: m.color.unwrap_or(ink),
                        radius: m.radius.map(|v| safe_px(v) * sc),
                        each: m.each,
                    }),
                    ink,
                    shadow: style.shadow.map(|s| GlyphShadow {
                        dx: (s.dx * sc).round() as i32,
                        dy: (s.dy * sc).round() as i32,
                        blur: (s.blur * sc).max(0.0),
                        color: s.color,
                    }),
                });
            }
            Inline::Code(s) => {
                let idx = decos.len();
                let px = safe_px(base_logical * sc);
                let mut a = base_attrs()
                    .family(Family::Name(&theme.font_mono))
                    .color(to_cosmic(theme.code_text))
                    .metrics(Metrics::new(px, px * line_mult))
                    .metadata(idx);
                if base_bold {
                    a = a.weight(Weight::BOLD);
                }
                spans.push((s, a));
                decos.push(SpanDeco {
                    underline: false,
                    strike: false,
                    highlight: None,
                    code_bg: Some(theme.code_bg),
                    ring: None,
                    dot: None,
                    ink: theme.code_text,
                    shadow: None,
                });
            }
            Inline::LineBreak => spans.push(("\n", default_attrs.clone())),
        }
    }
    (spans, decos)
}

/// 测一段行内内容的「自然宽」(不换行时的最长行宽,物理像素),给表格列宽求解用。
fn measure_natural(
    fonts: &FontHandle,
    theme: &Theme,
    inlines: &[Inline],
    base_logical: f32,
    base_bold: bool,
    sc: f32,
) -> f32 {
    let px = safe_px(base_logical * sc);
    let line_mult = theme.line_height;
    let default_attrs = base_attrs()
        .family(Family::Name(&theme.font_sans))
        .metrics(Metrics::new(px, px * line_mult))
        .metadata(usize::MAX);
    let (spans, _) = build_spans(inlines, theme, base_logical, base_bold, sc, &default_attrs);
    fonts.with_system(|fs| {
        let mut buf = Buffer::new(fs, Metrics::new(px, px * line_mult));
        buf.set_size(None, None); // 不限宽 → 不换行
        buf.set_rich_text(
            spans.iter().map(|(t, a)| (*t, a.clone())),
            &default_attrs,
            Shaping::Advanced,
            None,
        );
        buf.shape_until_scroll(fs, false);
        buf.layout_runs().map(|r| r.line_w).fold(0.0, f32::max)
    })
}

/// 求覆盖件在图面内的停靠坐标:`frame` 是图面矩形 `(x, y, w, h)`,`size` 是覆盖件
/// `(宽, 高)`,`m` 是离边距。图面放不下时夹回左上,贴边呈现。
fn anchor_pos(
    a: crate::model::Anchor,
    frame: (f32, f32, f32, f32),
    size: (f32, f32),
    m: f32,
) -> (f32, f32) {
    use crate::model::Anchor;
    let (ix, iy, dw, dh) = frame;
    let (w, h) = size;
    let x = match a {
        Anchor::TopLeft | Anchor::BottomLeft => ix + m,
        Anchor::TopRight | Anchor::BottomRight => ix + dw - w - m,
        Anchor::Center => ix + (dw - w) / 2.0,
    };
    let y = match a {
        Anchor::TopLeft | Anchor::TopRight => iy + m,
        Anchor::BottomLeft | Anchor::BottomRight => iy + dh - h - m,
        Anchor::Center => iy + (dh - h) / 2.0,
    };
    (x.max(ix), y.max(iy))
}

/// 把主题高亮策略解析成具体色。
fn resolve_highlight(h: Option<crate::model::Highlight>, theme: &Theme) -> Option<Color> {
    use crate::model::Highlight;
    match h {
        Some(Highlight::Theme) => Some(theme.highlight),
        Some(Highlight::Custom(c)) => Some(c),
        None => None,
    }
}

/// 在一行内,把连续同 metadata 的字形归组,据其装饰信息产出装饰矩形。
fn collect_decos(
    run: &cosmic_text::LayoutRun,
    decos: &[SpanDeco],
    x_left: f32,
    y_top: f32,
    out: &mut Vec<DisplayItem>,
) {
    let glyphs = run.glyphs;
    let baseline = y_top + run.line_y;
    let line_top = y_top + run.line_top;
    let line_h = run.line_height;
    let mut i = 0;
    while i < glyphs.len() {
        let m = glyphs[i].metadata;
        let (mut x0, mut x1, mut fs) = (f32::MAX, f32::MIN, glyphs[i].font_size);
        let seg_start = i;
        let mut j = i;
        while j < glyphs.len() && glyphs[j].metadata == m {
            let g = &glyphs[j];
            x0 = x0.min(g.x);
            x1 = x1.max(g.x + g.w);
            fs = g.font_size;
            j += 1;
        }
        i = j;
        let seg = &glyphs[seg_start..j];
        let Some(d) = decos.get(m) else { continue };
        let ax = x_left + x0;
        let aw = (x1 - x0).max(0.0);
        if aw <= 0.0 {
            continue;
        }
        if let Some(c) = d.highlight {
            out.push(DisplayItem::Rect {
                x: ax - fs * 0.06,
                y: line_top,
                w: aw + fs * 0.12,
                h: line_h,
                color: c,
                radius: fs * 0.12,
                layer: RectLayer::Under,
            });
        }
        if let Some(c) = d.code_bg {
            out.push(DisplayItem::Rect {
                x: ax - fs * 0.18,
                y: line_top + line_h * 0.08,
                w: aw + fs * 0.36,
                h: line_h * 0.84,
                color: c,
                radius: fs * 0.22,
                layer: RectLayer::Under,
            });
        }
        if d.underline {
            out.push(DisplayItem::Rect {
                x: ax,
                y: baseline + fs * 0.12,
                w: aw,
                h: (fs * 0.06).max(1.0),
                color: d.ink,
                radius: 0.0,
                layer: RectLayer::Over,
            });
        }
        if d.strike {
            out.push(DisplayItem::Rect {
                x: ax,
                y: baseline - fs * 0.28,
                w: aw,
                h: (fs * 0.06).max(1.0),
                color: d.ink,
                radius: 0.0,
                layer: RectLayer::Over,
            });
        }
        // 标注盒序列:范围模式 = 整段一盒;逐字模式 = 每个字形簇一盒(空白簇跳过)。
        let mark_boxes = |each: bool| -> Vec<(f32, f32)> {
            if each {
                seg.iter()
                    .filter(|g| {
                        run.text.get(g.start..g.end).is_none_or(|t| !t.trim().is_empty())
                    })
                    .map(|g| (x_left + g.x, g.w))
                    .collect()
            } else {
                vec![(ax, aw)]
            }
        };
        if let Some(r) = &d.ring {
            // 椭圆描边以盒中心为心:定径分量直接用(与文字宽窄无关,多字单字同大),
            // 缺的分量按盒自适应(横向包住盒、纵向盖住字高);只给 rx 即正圆。
            // 画在字形之前,溢出到行距里、不动布局。
            for (bx, bw) in mark_boxes(r.each) {
                let cx = bx + bw / 2.0;
                let cy = baseline - fs * 0.35;
                let auto_rx = (bw / 2.0 + fs * 0.30).max(fs * 0.55);
                let (rx, ry) = match (r.rx, r.ry) {
                    (Some(rx), Some(ry)) => (rx, ry),
                    (Some(rx), None) => (rx, rx),
                    (None, Some(ry)) => (auto_rx, ry),
                    // 全自适应:逐字圈正圆(半径取横/纵需求大者——圈单字理应是圆,
                    // 不随汉字全角/数字半角的字宽变形),范围圈按整段做扁椭圆。
                    (None, None) if r.each => {
                        let rr = auto_rx.max(fs * 0.62);
                        (rr, rr)
                    }
                    (None, None) => (auto_rx, fs * 0.62),
                };
                out.push(DisplayItem::Ellipse {
                    cx,
                    cy,
                    rx,
                    ry,
                    width: r.width.unwrap_or((fs * 0.07).max(1.0)),
                    color: r.color,
                });
            }
        }
        if let Some(p) = &d.dot {
            // 着重点:盒中线正下方一枚实心圆(全圆角矩形即圆),落在行距里。
            let r = p.radius.unwrap_or((fs * 0.09).max(1.5));
            for (bx, bw) in mark_boxes(p.each) {
                out.push(DisplayItem::Rect {
                    x: bx + bw / 2.0 - r,
                    y: baseline + fs * 0.16,
                    w: r * 2.0,
                    h: r * 2.0,
                    color: p.color,
                    radius: r,
                    layer: RectLayer::Over,
                });
            }
        }
    }
}

/// 把文本切成(emoji 表现段, 是否 emoji)交替的连续段,字节区间零拷贝。
/// 判定:默认 emoji 表现的码位(含修饰基底)起段;VS16(U+FE0F)把前一个字符拉进段
/// (⛏︎ → ⛏️ 这类文本表现默认的码位靠它升级);肤色修饰与区域指示符天然在段内
/// (Emoji_Presentation=YES);键帽组合(U+20E3)连同前一字符入段;ZWJ 两侧都在段内
/// 时并入段(👨‍👩‍👦 这类合字序列整段交给 emoji 字体做 GSUB)。
fn emoji_runs(text: &str) -> Vec<(&str, bool)> {
    use unicode_properties::{EmojiStatus, UnicodeEmoji};
    let chars: Vec<(usize, char)> = text.char_indices().collect();
    let mut flags = vec![false; chars.len()];
    for (k, &(_, c)) in chars.iter().enumerate() {
        flags[k] = matches!(
            c.emoji_status(),
            EmojiStatus::EmojiPresentation
                | EmojiStatus::EmojiModifierBase
                | EmojiStatus::EmojiPresentationAndModifierBase
                | EmojiStatus::EmojiPresentationAndEmojiComponent
                | EmojiStatus::EmojiPresentationAndModifierAndEmojiComponent
        );
    }
    for (k, &(_, c)) in chars.iter().enumerate() {
        if (c == '\u{FE0F}' || c == '\u{20E3}') && k > 0 {
            flags[k] = true;
            flags[k - 1] = true;
        }
    }
    for (k, &(_, c)) in chars.iter().enumerate() {
        if c == '\u{200D}' && k > 0 && k + 1 < chars.len() && flags[k - 1] && flags[k + 1] {
            flags[k] = true;
        }
    }
    let mut runs = Vec::new();
    let mut start = 0usize;
    for k in 1..chars.len() {
        if flags[k] != flags[k - 1] {
            runs.push((&text[chars[start].0..chars[k].0], flags[start]));
            start = k;
        }
    }
    if !chars.is_empty() {
        runs.push((&text[chars[start].0..], flags[start]));
    }
    runs
}

/// 所有文字 Attrs 的起点:统一关闭 hinting。本引擎默认 2× 超采样,hinting 对画质无益;
/// 更要紧的是 swash 0.2 的 hint 实例缓存不按字号失效——共享 FontHandle 连续渲多张、
/// 或同文档多字号时,字形会按「上一次的字号」栅格化(表头叠字、巨字、字距开洞),
/// 关 hinting 直接绕开这条缓存。别改回 `Attrs::new()` 裸用。
fn base_attrs() -> Attrs<'static> {
    Attrs::new().cache_key_flags(cosmic_text::CacheKeyFlags::DISABLE_HINTING)
}

fn family_of<'a>(role: &'a FontRole, theme: &'a Theme) -> Family<'a> {
    match role {
        FontRole::Sans => Family::Name(&theme.font_sans),
        FontRole::Serif => Family::Name(&theme.font_serif),
        FontRole::Mono => Family::Name(&theme.font_mono),
        FontRole::Kai => Family::Name(&theme.font_kai),
        FontRole::Named(s) => Family::Name(s),
    }
}

fn align_to_cosmic(a: Align) -> cosmic_text::Align {
    match a {
        Align::Left => cosmic_text::Align::Left,
        Align::Center => cosmic_text::Align::Center,
        Align::Right => cosmic_text::Align::Right,
        Align::Justify => cosmic_text::Align::Justified,
    }
}

fn to_cosmic(c: Color) -> cosmic_text::Color {
    cosmic_text::Color::rgba(c.r, c.g, c.b, c.a)
}

fn from_cosmic(c: cosmic_text::Color) -> Color {
    Color::rgba(c.r(), c.g(), c.b(), c.a())
}

/// 水平规线(以 `y` 为中线)。
fn hrule(x: f32, y: f32, w: f32, line: f32, color: Color) -> DisplayItem {
    DisplayItem::Rect { x, y: y - line / 2.0, w, h: line, color, radius: 0.0, layer: RectLayer::Under }
}

/// 竖直规线(以 `vx` 为中线,从 `top` 到 `bottom`)。
fn vrule(vx: f32, top: f32, bottom: f32, line: f32, color: Color) -> DisplayItem {
    DisplayItem::Rect {
        x: vx - line / 2.0,
        y: top,
        w: line,
        h: bottom - top,
        color,
        radius: 0.0,
        layer: RectLayer::Under,
    }
}