dxpdf 0.2.25

A fast DOCX-to-PDF converter powered by Skia
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
use std::rc::Rc;

use crate::model::{
    Block, BorderStyle, FieldCharType, Inline, RunElement, RunProperties, TextRun, VerticalAlign,
};
use crate::render::dimension::Pt;
use crate::render::emoji::cluster::EmojiCluster;
use crate::render::geometry::PtSize;
use crate::render::resolve::color::RgbColor;

use super::segment::{build_inline_units, InlineUnit, SegmentPiece};
use super::text::{
    emit_emoji_or_fallback, emit_text_fragments, emit_text_words, resolve_highlight_color,
    TextRunStyle,
};
use super::{
    font_props_from_run, to_roman_lower, FontProps, Fragment, FragmentBorder, TextMetrics,
    SUBSCRIPT_HEIGHT_OFFSET_RATIO, SUPERSCRIPT_ASCENT_OFFSET_RATIO, SUPERSCRIPT_FONT_SIZE_RATIO,
};

/// §17.3.2.4: convert a run-level [`crate::model::Border`] into a render-side
/// [`FragmentBorder`], filtering out the spec's "no border" sentinel
/// ([`BorderStyle::None`]).
///
/// `<w:bdr w:val="nil"/>` and `<w:bdr w:val="none"/>` (§17.18.2 ST_Border)
/// both signal "no border"; the parser collapses them to `BorderStyle::None`
/// in a `Some(Border { ... })`. The model preserves the explicit `Some` so
/// it can override an inherited border in the §17.7.2 cascade — but at the
/// render boundary we drop the variant, otherwise the painter would draw
/// a hairline box around every word.
pub(super) fn run_border_to_fragment(
    border: Option<&crate::model::Border>,
) -> Option<FragmentBorder> {
    let b = border?;
    if b.style == BorderStyle::None {
        return None;
    }
    Some(FragmentBorder {
        width: Pt::from(b.width),
        color: crate::render::resolve::color::resolve_color(
            b.color,
            crate::render::resolve::color::ColorContext::Text,
        ),
        space: Pt::new(b.space.raw() as f32),
    })
}

/// §17.7.2: resolve the effective styling of a single run by walking the
/// cascade (direct → character style → paragraph run defaults), then
/// translating to render-side `FontProps` + `TextRunStyle`.
///
/// This is the single source of truth for run-level styling. Both the
/// per-run path (`Discrete TextRun`) and the per-segment-piece path
/// (cross-run cluster reassembly via `segment.rs`) call it — for cross-
/// run clusters, the *base run*'s styling drives the entire piece per
/// the design in `docs/cross-run-cluster-reassembly.md`.
#[allow(clippy::too_many_arguments)] // the cascade has many independent inputs by spec
fn resolve_run_styling<F>(
    tr: &TextRun,
    default_family: &str,
    default_size: Pt,
    default_color: RgbColor,
    resolved_styles: Option<
        &std::collections::HashMap<
            crate::model::StyleId,
            crate::render::resolve::styles::ResolvedStyle,
        >,
    >,
    paragraph_run_defaults: Option<&RunProperties>,
    theme: Option<&crate::model::Theme>,
    measure_text: &F,
) -> (FontProps, TextRunStyle)
where
    F: Fn(&str, &FontProps) -> (Pt, TextMetrics),
{
    let mut effective_props = tr.properties.clone();
    // §17.3.2.26: resolve theme font references before merging.
    if let Some(th) = theme {
        crate::render::resolve::fonts::resolve_font_set_themes(&mut effective_props.fonts, th);
    }
    if let (Some(ref style_id), Some(styles)) = (&tr.style_id, resolved_styles) {
        if let Some(resolved_style) = styles.get(style_id) {
            crate::render::resolve::properties::merge_run_properties(
                &mut effective_props,
                &resolved_style.run,
            );
        }
    }
    if let Some(para_run) = paragraph_run_defaults {
        crate::render::resolve::properties::merge_run_properties(&mut effective_props, para_run);
    }

    let mut font = font_props_from_run(&effective_props, default_family, default_size);
    let color = effective_props
        .color
        .map(|c| {
            crate::render::resolve::color::resolve_color(
                c,
                crate::render::resolve::color::ColorContext::Text,
            )
        })
        .unwrap_or(default_color);
    // §17.3.2.32 / §17.3.2.15: shading or highlight as background.
    let shading = effective_props
        .shading
        .as_ref()
        .map(|s| {
            crate::render::resolve::color::resolve_color(
                s.fill,
                crate::render::resolve::color::ColorContext::Background,
            )
        })
        // §17.18.40: HighlightColor::None is the explicit "no highlight"
        // override and yields no fill, so use `and_then` to thread the
        // Option through.
        .or_else(|| effective_props.highlight.and_then(resolve_highlight_color));

    // §17.3.2.42: vertical alignment (super/sub).
    let mut baseline_offset = match effective_props.vertical_align {
        Some(VerticalAlign::Superscript) => {
            let (_, base_m) = measure_text("X", &font);
            font.size = font.size * SUPERSCRIPT_FONT_SIZE_RATIO;
            -(base_m.ascent * SUPERSCRIPT_ASCENT_OFFSET_RATIO)
        }
        Some(VerticalAlign::Subscript) => {
            let (_, base_m) = measure_text("X", &font);
            font.size = font.size * SUPERSCRIPT_FONT_SIZE_RATIO;
            base_m.height() * SUBSCRIPT_HEIGHT_OFFSET_RATIO
        }
        _ => Pt::ZERO,
    };
    // §17.3.2.19: w:position — vertical baseline offset in half-points.
    if let Some(pos) = effective_props.position {
        baseline_offset += Pt::from(pos);
    }

    // §17.3.2.4: run-level border (filtered to drop BorderStyle::None).
    let border = run_border_to_fragment(effective_props.border.as_ref());

    let text_style = TextRunStyle {
        color,
        shading,
        border,
        baseline_offset,
    };
    (font, text_style)
}

/// §17.16.4.1: context for evaluating dynamic fields (PAGE, NUMPAGES).
#[derive(Clone, Copy, Default)]
pub struct FieldContext {
    /// Current page number (1-based).
    pub page_number: Option<usize>,
    /// Total page count in the document.
    pub num_pages: Option<usize>,
}

/// §17.16.4.1: evaluate a parsed field instruction against the current context.
/// Returns the substituted text for PAGE/NUMPAGES, or None for other fields
/// or when no context is available.
fn evaluate_field_instruction(
    instruction: &crate::field::FieldInstruction,
    ctx: FieldContext,
) -> Option<String> {
    match instruction {
        crate::field::FieldInstruction::Page { .. } => ctx.page_number.map(|n| n.to_string()),
        crate::field::FieldInstruction::NumPages { .. } => ctx.num_pages.map(|n| n.to_string()),
        _ => None,
    }
}

/// §17.16.19 MERGEFORMAT — source of formatting for a complex field's
/// substituted dynamic value. Resolved when the `Separate` fldChar is
/// reached so the lookup honors the OOXML "first result run wins" rule
/// regardless of how the inline-units pre-pass packaged the result zone:
/// an empty `<w:t></w:t>` placeholder run carries `<w:rPr>` but does not
/// surface as its own unit (segment joining drops it as 0 chars), yet
/// is still the spec's first-result-run for formatting purposes.
#[derive(Clone, Copy)]
pub(super) enum FieldFormatSource<'a> {
    /// First TextRun encountered between `Separate` and the matching
    /// `End` at the outer field's nesting level. Its `<w:rPr>` provides
    /// font family, size, bold, italic, color per §17.16.19.
    FirstResultRun(&'a TextRun),
    /// No result TextRun is present at the outer level. The
    /// substitution falls back to paragraph default font properties at
    /// emission time.
    ParagraphDefaults,
}

/// Locate the formatting source for the complex field whose `Separate`
/// fldChar sits at `inlines[separate_idx]`. Walks raw inlines (not
/// unit-packaged), tracking nesting via `Begin` / `End` counts, and
/// returns at the first top-level `TextRun` or at the matching `End`,
/// whichever comes first.
///
/// "Top level" = the depth of the field whose `Separate` triggered the
/// lookup. Text runs that sit inside a nested field's own result zone
/// belong to that nested field's substitution and are skipped — they
/// are not the outer field's first result run.
///
/// Malformed input (no matching `End`) returns `ParagraphDefaults`
/// rather than panicking.
pub(super) fn resolve_field_format_source(
    inlines: &[Inline],
    separate_idx: usize,
) -> FieldFormatSource<'_> {
    let mut depth: i32 = 0;
    for inline in &inlines[separate_idx + 1..] {
        match inline {
            Inline::FieldChar(fc) => match fc.field_char_type {
                FieldCharType::Begin => depth += 1,
                FieldCharType::End => {
                    if depth == 0 {
                        return FieldFormatSource::ParagraphDefaults;
                    }
                    depth -= 1;
                }
                FieldCharType::Separate => {
                    // Belongs to a nested field; the outer scan ignores it.
                }
            },
            Inline::TextRun(tr) if depth == 0 => {
                return FieldFormatSource::FirstResultRun(tr.as_ref());
            }
            _ => {}
        }
    }
    FieldFormatSource::ParagraphDefaults
}

/// Emit the substituted text of a complex field using the formatting
/// resolved at `Separate` (§17.16.19). When the source is
/// [`FieldFormatSource::FirstResultRun`] the substitution inherits font
/// family, size, bold, italic, color, etc. from that run's `<w:rPr>` —
/// matching what Word renders when it updates a dynamic field in place.
/// When no result run was present in the field zone the substitution
/// falls back to paragraph defaults.
#[allow(clippy::too_many_arguments)]
fn emit_field_substitution<F>(
    text: &str,
    source: Option<&FieldFormatSource<'_>>,
    default_family: &str,
    default_size: Pt,
    default_color: RgbColor,
    resolved_styles: Option<
        &std::collections::HashMap<
            crate::model::StyleId,
            crate::render::resolve::styles::ResolvedStyle,
        >,
    >,
    paragraph_run_defaults: Option<&RunProperties>,
    theme: Option<&crate::model::Theme>,
    hyperlink_url: Option<&str>,
    measure_text: &F,
    measurer: Option<&crate::render::layout::measurer::TextMeasurer<'_>>,
    fragments: &mut Vec<Fragment>,
) where
    F: Fn(&str, &FontProps) -> (Pt, TextMetrics),
{
    let (font, text_style) = match source {
        Some(FieldFormatSource::FirstResultRun(tr)) => resolve_run_styling(
            tr,
            default_family,
            default_size,
            default_color,
            resolved_styles,
            paragraph_run_defaults,
            theme,
            measure_text,
        ),
        _ => (
            FontProps {
                family: Rc::from(default_family),
                size: default_size,
                bold: false,
                italic: false,
                underline: false,
                char_spacing: Pt::ZERO,
                text_scale: 1.0,
                underline_position: Pt::ZERO,
                underline_thickness: Pt::ZERO,
            },
            TextRunStyle {
                color: default_color,
                shading: None,
                border: None,
                baseline_offset: Pt::ZERO,
            },
        ),
    };
    emit_text_fragments(
        text,
        &font,
        &text_style,
        hyperlink_url,
        measure_text,
        measurer,
        fragments,
    );
}

/// Build a text fragment for a substituted field value, using the paragraph's
/// default font properties.
fn make_field_text_fragment<F>(
    text: Rc<str>,
    default_family: &str,
    default_size: Pt,
    default_color: crate::render::resolve::color::RgbColor,
    measure_text: &F,
) -> Fragment
where
    F: Fn(&str, &FontProps) -> (Pt, TextMetrics),
{
    let font = FontProps {
        family: Rc::from(default_family),
        size: default_size,
        bold: false,
        italic: false,
        underline: false,
        char_spacing: Pt::ZERO,
        text_scale: 1.0,
        underline_position: Pt::ZERO,
        underline_thickness: Pt::ZERO,
    };
    let (w, m) = measure_text(&text, &font);
    Fragment::Text {
        text,
        font,
        color: default_color,
        shading: None,
        border: None,
        width: w,
        trimmed_width: w,
        metrics: m,
        hyperlink_url: None,
        baseline_offset: Pt::ZERO,
        text_offset: Pt::ZERO,
    }
}

/// Invariant context threaded through all recursive `collect_fragments` calls.
pub struct FragmentCtx<'a> {
    pub default_family: &'a str,
    pub default_size: Pt,
    pub default_color: RgbColor,
    pub resolved_styles: Option<
        &'a std::collections::HashMap<
            crate::model::StyleId,
            crate::render::resolve::styles::ResolvedStyle,
        >,
    >,
    pub paragraph_run_defaults: Option<&'a RunProperties>,
    pub theme: Option<&'a crate::model::Theme>,
    /// Measurer used by the emoji pipeline for typeface resolution and
    /// raster-backend metrics. `None` disables the emoji path entirely —
    /// callers without a font registry (most unit tests) pass `None` and
    /// emoji codepoints flow through the existing text path unchanged.
    pub measurer: Option<&'a crate::render::layout::measurer::TextMeasurer<'a>>,
}

/// Walk inline content and collect fragments.
/// `measure_text` is a callback that measures text width/height/ascent for a given font.
/// `resolved_styles` is used to look up character styles (w:rStyle) on text runs.
///
/// Returns fragments suitable for the line-fitting algorithm.
pub fn collect_fragments<F>(
    inlines: &[Inline],
    ctx: &FragmentCtx<'_>,
    hyperlink_url: Option<&str>,
    measure_text: &F,
    footnote_counter: &mut u32,
    endnote_counter: &mut u32,
    field_ctx: FieldContext,
) -> Vec<Fragment>
where
    F: Fn(&str, &FontProps) -> (Pt, TextMetrics), // (width, metrics)
{
    let default_family = ctx.default_family;
    let default_size = ctx.default_size;
    let default_color = ctx.default_color;
    let resolved_styles = ctx.resolved_styles;
    let paragraph_run_defaults = ctx.paragraph_run_defaults;
    let theme = ctx.theme;
    let mut fragments = Vec::new();
    let mut field_depth: i32 = 0; // tracks nested complex field state
    let mut field_instr = String::new(); // accumulated instruction text for current complex field
                                         // §17.16.19: field substitution state for complex fields.
                                         // Pending = substitution text waiting for the first result TextRun's formatting.
                                         // Emitted = substitution was rendered, skip remaining result TextRuns until End.
    let mut field_sub_pending: Option<String> = None;
    let mut field_sub_emitted = false;

    // §17.16.19 MERGEFORMAT — pre-resolve formatting for each complex
    // field's substitution against raw inlines, so empty placeholder
    // result runs (`<w:t></w:t>` — swallowed by `build_inline_units`
    // because they contribute 0 chars) still surface their `<w:rPr>`.
    // One entry per `Separate` fldChar, consumed in order.
    let field_format_sources: Vec<FieldFormatSource<'_>> = inlines
        .iter()
        .enumerate()
        .filter_map(|(idx, inl)| match inl {
            Inline::FieldChar(fc) if matches!(fc.field_char_type, FieldCharType::Separate) => {
                Some(resolve_field_format_source(inlines, idx))
            }
            _ => None,
        })
        .collect();
    let mut field_format_idx: usize = 0;
    let mut current_field_format: Option<FieldFormatSource<'_>> = None;
    // Pre-pass: join consecutive text-only TextRuns into segments so
    // UAX #29 grapheme clusters reassemble across `<w:rFonts>`-induced
    // run splits (keycap `1️⃣`, ZWJ family, modifier sequence, …).
    // See `docs/cross-run-cluster-reassembly.md`.
    let units = build_inline_units(inlines);
    for unit in units {
        match unit {
            InlineUnit::TextSegment(seg) => {
                // Field state (mirrors the per-run logic below). Field chars
                // appear as Discrete Inlines and break segment joining, so
                // a TextSegment is always entirely inside one field zone.
                if field_depth > 0 || field_sub_emitted {
                    continue;
                }

                // §17.16.19: pending substitution uses the segment's first run
                // for formatting (per cross-run cluster cascade rule).
                if let Some(sub) = field_sub_pending.take() {
                    let base_run = seg.char_runs()[0];
                    let (font, text_style) = resolve_run_styling(
                        base_run,
                        default_family,
                        default_size,
                        default_color,
                        resolved_styles,
                        paragraph_run_defaults,
                        theme,
                        measure_text,
                    );
                    field_sub_emitted = true;
                    emit_text_fragments(
                        &sub,
                        &font,
                        &text_style,
                        hyperlink_url,
                        measure_text,
                        ctx.measurer,
                        &mut fragments,
                    );
                    continue;
                }

                // Normal segment: classify and emit each piece using its
                // own (or for emoji, base) run's resolved styling.
                for piece in seg.classify() {
                    match piece {
                        SegmentPiece::Text { run, text } => {
                            let (font, text_style) = resolve_run_styling(
                                run,
                                default_family,
                                default_size,
                                default_color,
                                resolved_styles,
                                paragraph_run_defaults,
                                theme,
                                measure_text,
                            );
                            // Pre-classified text: bypass cluster::classify
                            // by going straight to the word-split path.
                            emit_text_words(
                                &text,
                                &font,
                                &text_style,
                                hyperlink_url,
                                measure_text,
                                &mut fragments,
                            );
                        }
                        SegmentPiece::Emoji {
                            base_run,
                            text,
                            presentation,
                            structure,
                        } => {
                            let (font, text_style) = resolve_run_styling(
                                base_run,
                                default_family,
                                default_size,
                                default_color,
                                resolved_styles,
                                paragraph_run_defaults,
                                theme,
                                measure_text,
                            );
                            if let Some(measurer) = ctx.measurer {
                                let cluster = EmojiCluster {
                                    text: &text,
                                    presentation,
                                    structure,
                                };
                                emit_emoji_or_fallback(
                                    &cluster,
                                    &font,
                                    &text_style,
                                    hyperlink_url,
                                    measure_text,
                                    measurer,
                                    &mut fragments,
                                );
                            } else {
                                // No measurer (test path): fall through to
                                // text — the cluster's codepoints survive
                                // in the PDF text stream verbatim.
                                emit_text_words(
                                    &text,
                                    &font,
                                    &text_style,
                                    hyperlink_url,
                                    measure_text,
                                    &mut fragments,
                                );
                            }
                        }
                    }
                }
            }
            InlineUnit::Discrete(inline) => match inline {
                Inline::TextRun(tr) => {
                    // A text-only TextRun would have been a TextSegment; this
                    // branch handles runs whose content includes Tab,
                    // LineBreak, PageBreak, ColumnBreak, or
                    // LastRenderedPageBreak.
                    if field_depth > 0 || field_sub_emitted {
                        continue;
                    }

                    let (font, text_style) = resolve_run_styling(
                        tr,
                        default_family,
                        default_size,
                        default_color,
                        resolved_styles,
                        paragraph_run_defaults,
                        theme,
                        measure_text,
                    );

                    if field_sub_pending.is_some() {
                        let sub = field_sub_pending.take().unwrap();
                        field_sub_emitted = true;
                        emit_text_fragments(
                            &sub,
                            &font,
                            &text_style,
                            hyperlink_url,
                            measure_text,
                            ctx.measurer,
                            &mut fragments,
                        );
                    } else {
                        for element in &tr.content {
                            match element {
                                RunElement::Text(text) => {
                                    emit_text_fragments(
                                        text,
                                        &font,
                                        &text_style,
                                        hyperlink_url,
                                        measure_text,
                                        ctx.measurer,
                                        &mut fragments,
                                    );
                                }
                                RunElement::Tab => {
                                    fragments.push(Fragment::Tab {
                                        line_height: font.size,
                                        fitting_width: None,
                                    });
                                }
                                RunElement::LineBreak(_) => {
                                    fragments.push(Fragment::LineBreak {
                                        line_height: font.size,
                                    });
                                }
                                RunElement::PageBreak => {
                                    fragments.push(Fragment::PageBreak {
                                        line_height: font.size,
                                    });
                                }
                                RunElement::ColumnBreak => {
                                    fragments.push(Fragment::ColumnBreak);
                                }
                                RunElement::LastRenderedPageBreak => {}
                            }
                        }
                    }
                }
                Inline::Image(img) => {
                    // Only render INLINE images as fragments.
                    // Anchor (floating) images are handled separately in build.rs.
                    if matches!(img.placement, crate::model::ImagePlacement::Inline { .. }) {
                        if let Some(rel_id) =
                            crate::render::resolve::images::extract_image_rel_id(img)
                        {
                            let w = Pt::from(img.extent.width);
                            let h = Pt::from(img.extent.height);
                            fragments.push(Fragment::Image {
                                size: PtSize::new(w, h),
                                rel_id: rel_id.as_str().to_string(),
                                image_data: None,
                            });
                        }
                    }
                }
                Inline::Hyperlink(link) => {
                    let url: Option<&str> = match &link.target {
                        crate::model::HyperlinkTarget::External(rel_id) => Some(rel_id.as_str()),
                        crate::model::HyperlinkTarget::Internal { anchor } => Some(anchor.as_str()),
                    };
                    let mut sub = collect_fragments(
                        &link.content,
                        ctx,
                        url,
                        measure_text,
                        footnote_counter,
                        endnote_counter,
                        field_ctx,
                    );
                    fragments.append(&mut sub);
                }
                Inline::Field(field) => {
                    // §17.16.18: simple field — check for dynamic substitution.
                    let substituted = evaluate_field_instruction(&field.instruction, field_ctx);
                    if let Some(text) = substituted {
                        fragments.push(make_field_text_fragment(
                            Rc::from(text.as_str()),
                            default_family,
                            default_size,
                            default_color,
                            measure_text,
                        ));
                    } else {
                        let mut sub = collect_fragments(
                            &field.content,
                            ctx,
                            hyperlink_url,
                            measure_text,
                            footnote_counter,
                            endnote_counter,
                            field_ctx,
                        );
                        fragments.append(&mut sub);
                    }
                }
                Inline::FieldChar(fc) => {
                    // §17.16.18: complex field state machine:
                    // Begin → InstrText... → Separate → result runs → End
                    match fc.field_char_type {
                        FieldCharType::Begin => {
                            field_depth += 1;
                            field_instr.clear();
                            field_sub_pending = None;
                            field_sub_emitted = false;
                        }
                        FieldCharType::Separate => {
                            // §17.16.4.1: parse accumulated instruction, evaluate
                            // PAGE/NUMPAGES if field context is available.
                            if let Ok(parsed) = crate::field::parse(&field_instr) {
                                field_sub_pending = evaluate_field_instruction(&parsed, field_ctx);
                            }
                            // §17.16.19: bind the formatting source resolved
                            // against raw inlines, so the End fallback path
                            // can recover an empty placeholder run's rPr
                            // even though it was dropped by segment joining.
                            current_field_format =
                                field_format_sources.get(field_format_idx).copied();
                            field_format_idx += 1;
                            field_depth -= 1; // now collect result runs (unless substituted)
                        }
                        FieldCharType::End => {
                            // Substitution still pending at End: the unit
                            // stream never carried a result run (either the
                            // placeholder was empty and got swallowed by
                            // segment joining, or the field has no result
                            // content at all). Use the pre-resolved format
                            // source — §17.16.19 first-result-run when
                            // present, paragraph defaults otherwise.
                            if let Some(text) = field_sub_pending.take() {
                                emit_field_substitution(
                                    &text,
                                    current_field_format.as_ref(),
                                    default_family,
                                    default_size,
                                    default_color,
                                    resolved_styles,
                                    paragraph_run_defaults,
                                    theme,
                                    hyperlink_url,
                                    measure_text,
                                    ctx.measurer,
                                    &mut fragments,
                                );
                            }
                            current_field_format = None;
                            field_sub_emitted = false;
                        }
                    }
                }
                Inline::InstrText(text) => {
                    // Accumulate instruction text for complex field parsing.
                    if field_depth > 0 {
                        field_instr.push_str(text);
                    }
                }
                Inline::AlternateContent(ac) => {
                    // §M.2.1 / §17.17.1: when a Choice carries a paragraph-
                    // anchored DrawingML wsp shape, that shape's `txbx`
                    // contents are laid out into shape-local commands by the
                    // floating-shape extractor and emitted on top of the
                    // shape's path. Walking the VML fallback here would
                    // duplicate the text into the host paragraph at the
                    // wrong y. Skip the fallback for that case.
                    //
                    // For Choices without a paragraph-anchored wsp (e.g. a
                    // page-anchored shape, or Choice we don't extract yet)
                    // we fall back to the legacy inline path so the user
                    // still sees the text — it lands at the host paragraph
                    // y as a Tier 0 placeholder.
                    if !choice_has_paragraph_anchored_wsp(&ac.choices) {
                        if let Some(ref fallback) = ac.fallback {
                            let mut sub = collect_fragments(
                                fallback,
                                ctx,
                                hyperlink_url,
                                measure_text,
                                footnote_counter,
                                endnote_counter,
                                field_ctx,
                            );
                            fragments.append(&mut sub);
                        }
                    }
                }
                Inline::Symbol(sym) => {
                    let font = FontProps {
                        family: Rc::from(sym.font.as_str()),
                        size: default_size,
                        bold: false,
                        italic: false,
                        underline: false,
                        char_spacing: Pt::ZERO,
                        text_scale: 1.0,
                        underline_position: Pt::ZERO,
                        underline_thickness: Pt::ZERO,
                    };
                    let ch = char::from_u32(sym.char_code as u32).unwrap_or('\u{FFFD}');
                    let text = ch.to_string();
                    let (w, m) = measure_text(&text, &font);
                    fragments.push(Fragment::Text {
                        text: Rc::from(text.as_str()),
                        font,
                        color: RgbColor::BLACK,
                        shading: None,
                        border: None,
                        width: w,
                        trimmed_width: w,
                        metrics: m,
                        hyperlink_url: hyperlink_url.map(String::from),
                        baseline_offset: Pt::ZERO,
                        text_offset: Pt::ZERO,
                    });
                }
                // Bookmark target — emit as zero-width named destination.
                Inline::BookmarkStart { name, .. } => {
                    fragments.push(Fragment::Bookmark { name: name.clone() });
                }
                // Non-visual inlines — skip
                Inline::BookmarkEnd(_)
                | Inline::Separator
                | Inline::ContinuationSeparator
                | Inline::FootnoteRefMark
                | Inline::EndnoteRefMark => {}
                // §17.11.12: footnote reference — render as superscript number.
                Inline::FootnoteRef(_note_id) => {
                    *footnote_counter += 1;
                    let num_text = format!("{}", *footnote_counter);
                    // §17.11.12: footnote reference uses superscript at 58% size.
                    let ref_size = default_size * 0.58;
                    let ref_font = FontProps {
                        family: std::rc::Rc::from(default_family),
                        size: ref_size,
                        bold: false,
                        italic: false,
                        underline: false,
                        char_spacing: Pt::ZERO,
                        text_scale: 1.0,
                        underline_position: Pt::ZERO,
                        underline_thickness: Pt::ZERO,
                    };
                    let (w, m) = measure_text(&num_text, &ref_font);
                    // Superscript baseline offset: raise by ~40% of the full-size ascent.
                    let baseline_offset = -(default_size * 0.4);
                    fragments.push(Fragment::Text {
                        text: Rc::from(num_text.as_str()),
                        font: ref_font,
                        color: default_color,
                        shading: None,
                        border: None,
                        width: w,
                        trimmed_width: w,
                        metrics: m,
                        hyperlink_url: None,
                        baseline_offset,
                        text_offset: Pt::ZERO,
                    });
                }
                // §17.11.2: endnote reference — render as superscript Roman numeral.
                Inline::EndnoteRef(_note_id) => {
                    *endnote_counter += 1;
                    let num_text = to_roman_lower(*endnote_counter);
                    let ref_size = default_size * 0.58;
                    let ref_font = FontProps {
                        family: std::rc::Rc::from(default_family),
                        size: ref_size,
                        bold: false,
                        italic: false,
                        underline: false,
                        char_spacing: Pt::ZERO,
                        text_scale: 1.0,
                        underline_position: Pt::ZERO,
                        underline_thickness: Pt::ZERO,
                    };
                    let (w, m) = measure_text(&num_text, &ref_font);
                    let baseline_offset = -(default_size * 0.4);
                    fragments.push(Fragment::Text {
                        text: Rc::from(num_text.as_str()),
                        font: ref_font,
                        color: default_color,
                        shading: None,
                        border: None,
                        width: w,
                        trimmed_width: w,
                        metrics: m,
                        hyperlink_url: None,
                        baseline_offset,
                        text_offset: Pt::ZERO,
                    });
                }
                Inline::Pict(pict) => {
                    // Render text content from VML text-box-bearing
                    // primitives inline. Every primitive variant
                    // (`<v:shape>`, `<v:rect>`, `<v:roundrect>`,
                    // `<v:oval>`, …) admits a `<v:textbox>` child via
                    // `VmlCommonAttrs.text_box`; the previous code
                    // only walked the `Shape` variant and silently
                    // dropped text from rect / roundrect / oval text
                    // boxes (the case footer3.xml of the vorlage doc
                    // exercised — the gray bar is a `<v:rect>`).
                    //
                    // Does not handle absolute positioning — text
                    // appears inline with the surrounding paragraph.
                    for primitive in &pict.primitives {
                        let common = primitive.common();
                        if let Some(ref text_box) = common.text_box {
                            for block in &text_box.content {
                                if let Block::Paragraph(p) = block {
                                    let pict_ctx = FragmentCtx {
                                        default_family,
                                        default_size,
                                        default_color,
                                        resolved_styles,
                                        paragraph_run_defaults: p.mark_run_properties.as_ref(),
                                        theme,
                                        measurer: ctx.measurer,
                                    };
                                    let mut sub = collect_fragments(
                                        &p.content,
                                        &pict_ctx,
                                        hyperlink_url,
                                        measure_text,
                                        footnote_counter,
                                        endnote_counter,
                                        field_ctx,
                                    );
                                    fragments.append(&mut sub);
                                }
                            }
                        }
                    }
                }
            },
        }
    }

    fragments
}

/// True when any choice in the AlternateContent contains a DrawingML
/// `wps:wsp` — the case where the floating-shape extractor lays the
/// shape's text out itself (so the inline collector must not also walk
/// the VML fallback's textbox content). Both paragraph- and page-
/// anchored wsp shapes now route through the typed sub-layout, so any
/// wsp in a Choice suppresses the fallback walk.
fn choice_has_paragraph_anchored_wsp(choices: &[crate::model::McChoice]) -> bool {
    use crate::model::{GraphicContent, ImagePlacement, Inline};

    fn walk(inlines: &[Inline]) -> bool {
        for inline in inlines {
            match inline {
                Inline::Image(img)
                    if matches!(img.placement, ImagePlacement::Anchor(_))
                        && matches!(img.graphic, Some(GraphicContent::WordProcessingShape(_))) =>
                {
                    return true;
                }
                Inline::Hyperlink(link) if walk(&link.content) => return true,
                Inline::Field(f) if walk(&f.content) => return true,
                _ => {}
            }
        }
        false
    }

    choices.iter().any(|c| walk(&c.content))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::dimension::{Dimension, HalfPoints};
    use crate::model::*;

    /// Dummy measurer: width = text.len() * 6.0, ascent = 10.0, descent = 2.0
    fn dummy_measure(text: &str, _font: &FontProps) -> (Pt, TextMetrics) {
        (
            Pt::new(text.len() as f32 * 6.0),
            TextMetrics {
                ascent: Pt::new(10.0),
                descent: Pt::new(2.0),
                leading: Pt::ZERO,
            },
        )
    }

    fn default_ctx(size: f32) -> FragmentCtx<'static> {
        FragmentCtx {
            default_family: "Default",
            default_size: Pt::new(size),
            default_color: RgbColor::BLACK,
            resolved_styles: None,
            paragraph_run_defaults: None,
            theme: None,
            measurer: None,
        }
    }

    // ── §17.3.2.4 / §17.18.2 run-level border tri-state ─────────────────
    //
    // The cascade may carry a child run whose `<w:bdr w:val="nil"/>`
    // (or "none") explicitly turns off an inherited border. The model
    // preserves this as `Some(Border { style: BorderStyle::None, .. })`
    // so the §17.7.2 merge can distinguish "explicit no border" from
    // "field absent → inherit". At the render boundary we must drop the
    // sentinel; otherwise the painter draws a hairline box around every
    // word in any Word-saved doc (Word emits `<w:bdr w:val="nil"/>` in
    // the default rPrDefault for the entire document).

    fn border_with_style(style: BorderStyle) -> crate::model::Border {
        crate::model::Border {
            style,
            width: Dimension::new(0),
            space: Dimension::new(0),
            color: crate::model::Color::Auto,
        }
    }

    #[test]
    fn run_border_absent_yields_no_fragment_border() {
        assert!(run_border_to_fragment(None).is_none());
    }

    #[test]
    fn run_border_explicit_none_yields_no_fragment_border() {
        let b = border_with_style(BorderStyle::None);
        assert!(
            run_border_to_fragment(Some(&b)).is_none(),
            "<w:bdr w:val=\"nil\"/> / \"none\" must NOT produce a render-side border"
        );
    }

    #[test]
    fn run_border_actual_style_yields_fragment_border() {
        let b = border_with_style(BorderStyle::Single);
        assert!(
            run_border_to_fragment(Some(&b)).is_some(),
            "explicit Single border must reach the painter"
        );
    }

    fn text_run(text: &str) -> Inline {
        Inline::TextRun(Box::new(TextRun {
            style_id: None,
            properties: RunProperties::default(),
            content: vec![RunElement::Text(text.into())],
            rsids: RevisionIds::default(),
        }))
    }

    fn text_run_with_font(text: &str, font: &str, size: i64) -> Inline {
        Inline::TextRun(Box::new(TextRun {
            style_id: None,
            properties: RunProperties {
                fonts: FontSet {
                    ascii: FontSlot::from_name(font),
                    ..Default::default()
                },
                font_size: Some(Dimension::<HalfPoints>::new(size)),
                ..Default::default()
            },
            content: vec![RunElement::Text(text.into())],
            rsids: RevisionIds::default(),
        }))
    }

    #[test]
    fn single_text_run() {
        let inlines = vec![text_run("hello")];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        assert_eq!(frags.len(), 1);
        assert_eq!(frags[0].width().raw(), 30.0); // 5 * 6
        assert_eq!(frags[0].height().raw(), 12.0);
    }

    #[test]
    fn text_run_uses_run_font() {
        let inlines = vec![text_run_with_font("hi", "Arial", 24)];
        let ctx = default_ctx(10.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        if let Fragment::Text { font, .. } = &frags[0] {
            assert_eq!(&*font.family, "Arial");
            assert_eq!(font.size.raw(), 12.0); // 24 half-points = 12pt
        } else {
            panic!("expected Text fragment");
        }
    }

    #[test]
    fn tab_produces_tab_fragment() {
        let inlines = vec![Inline::TextRun(Box::new(TextRun {
            style_id: None,
            properties: RunProperties::default(),
            content: vec![RunElement::Tab],
            rsids: RevisionIds::default(),
        }))];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        assert_eq!(frags.len(), 1);
        assert!(matches!(frags[0], Fragment::Tab { .. }));
    }

    #[test]
    fn line_break_produces_break_fragment() {
        let inlines = vec![Inline::TextRun(Box::new(TextRun {
            style_id: None,
            properties: RunProperties::default(),
            content: vec![RunElement::LineBreak(BreakKind::TextWrapping)],
            rsids: RevisionIds::default(),
        }))];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        assert_eq!(frags.len(), 1);
        assert!(frags[0].is_line_break());
    }

    #[test]
    fn hyperlink_recurses_into_content() {
        let inlines = vec![Inline::Hyperlink(Hyperlink {
            target: HyperlinkTarget::External(RelId::new("rId1")),
            content: vec![text_run("click me")],
        })];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        assert_eq!(frags.len(), 2, "split into 'click ' and 'me'");
        if let Fragment::Text {
            hyperlink_url,
            text,
            ..
        } = &frags[0]
        {
            assert_eq!(&**text, "click ");
            assert_eq!(hyperlink_url.as_deref(), Some("rId1"));
        } else {
            panic!("expected Text fragment");
        }
    }

    #[test]
    fn complex_field_skips_instructions_collects_result() {
        // FieldChar::Begin -> InstrText("PAGE") -> FieldChar::Separate -> TextRun("3") -> FieldChar::End
        let inlines = vec![
            Inline::FieldChar(FieldChar {
                field_char_type: FieldCharType::Begin,
                dirty: None,
                fld_lock: None,
            }),
            Inline::InstrText("PAGE".into()),
            Inline::FieldChar(FieldChar {
                field_char_type: FieldCharType::Separate,
                dirty: None,
                fld_lock: None,
            }),
            text_run("3"),
            Inline::FieldChar(FieldChar {
                field_char_type: FieldCharType::End,
                dirty: None,
                fld_lock: None,
            }),
        ];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        // Should only have the "3" result, not "PAGE"
        assert_eq!(frags.len(), 1);
        if let Fragment::Text { text, .. } = &frags[0] {
            assert_eq!(&**text, "3");
        }
    }

    #[test]
    fn bookmarks_and_separators_skipped() {
        let inlines = vec![
            Inline::BookmarkStart {
                id: BookmarkId::new(1),
                name: "bm1".into(),
            },
            text_run("visible"),
            Inline::BookmarkEnd(BookmarkId::new(1)),
            Inline::Separator,
            Inline::ContinuationSeparator,
            Inline::FootnoteRefMark,
            Inline::EndnoteRefMark,
            // LastRenderedPageBreak is now inside RunElement, not Inline
        ];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        // BookmarkStart produces a Bookmark fragment, text run produces a Text fragment.
        assert_eq!(
            frags.len(),
            2,
            "bookmark + text run should produce fragments"
        );
        assert!(matches!(frags[0], Fragment::Bookmark { .. }));
        assert!(matches!(frags[1], Fragment::Text { .. }));
    }

    #[test]
    fn alternate_content_uses_fallback() {
        let inlines = vec![Inline::AlternateContent(AlternateContent {
            choices: vec![McChoice {
                requires: McRequires::Wps,
                content: vec![text_run("choice")],
            }],
            fallback: Some(vec![text_run("fallback")]),
        })];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        assert_eq!(frags.len(), 1);
        if let Fragment::Text { text, .. } = &frags[0] {
            assert_eq!(&**text, "fallback");
        }
    }

    #[test]
    fn empty_text_run_produces_no_fragment() {
        let inlines = vec![Inline::TextRun(Box::new(TextRun {
            style_id: None,
            properties: RunProperties::default(),
            content: vec![RunElement::Text(String::new())],
            rsids: RevisionIds::default(),
        }))];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );
        assert!(frags.is_empty());
    }

    #[test]
    fn symbol_produces_text_fragment() {
        let inlines = vec![Inline::Symbol(Symbol {
            font: "Wingdings".into(),
            char_code: 0x46, // 'F'
        })];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        assert_eq!(frags.len(), 1);
        if let Fragment::Text { font, text, .. } = &frags[0] {
            assert_eq!(&*font.family, "Wingdings");
            assert_eq!(&**text, "F");
        }
    }

    #[test]
    fn simple_field_collects_content() {
        let inlines = vec![Inline::Field(Field {
            instruction: crate::field::FieldInstruction::Page {
                switches: Default::default(),
            },
            content: vec![text_run("5")],
        })];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        assert_eq!(frags.len(), 1);
        if let Fragment::Text { text, .. } = &frags[0] {
            assert_eq!(&**text, "5");
        }
    }

    #[test]
    fn multi_word_text_run_splits_into_fragments() {
        let inlines = vec![text_run("hello world foo")];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext::default(),
        );

        assert_eq!(frags.len(), 3);
        if let Fragment::Text { text, .. } = &frags[0] {
            assert_eq!(&**text, "hello ");
        }
        if let Fragment::Text { text, .. } = &frags[1] {
            assert_eq!(&**text, "world ");
        }
        if let Fragment::Text { text, .. } = &frags[2] {
            assert_eq!(&**text, "foo");
        }
    }

    // ── §17.16.19 MERGEFORMAT — field result format source ───────────────
    //
    // `resolve_field_format_source` walks raw inlines forward from a
    // `Separate` fldChar to locate the formatting that should be applied
    // to a substituted dynamic value (PAGE/NUMPAGES/...). Decoupling
    // this from `build_inline_units` is the key correctness property:
    // an empty `<w:t></w:t>` placeholder result run carries `<w:rPr>`
    // but is swallowed by segment joining (it contributes 0 chars), so
    // we cannot rely on units to surface it.

    fn fld_char(kind: FieldCharType) -> Inline {
        Inline::FieldChar(FieldChar {
            field_char_type: kind,
            dirty: None,
            fld_lock: None,
        })
    }

    fn bold_text_run(text: &str) -> Inline {
        Inline::TextRun(Box::new(TextRun {
            style_id: None,
            properties: RunProperties {
                bold: Some(true),
                ..Default::default()
            },
            content: vec![RunElement::Text(text.into())],
            rsids: RevisionIds::default(),
        }))
    }

    /// Helper: pull `&TextRun` out of `FieldFormatSource::FirstResultRun`,
    /// or panic with a descriptive message.
    fn expect_first_run<'a>(src: FieldFormatSource<'a>) -> &'a TextRun {
        match src {
            FieldFormatSource::FirstResultRun(tr) => tr,
            FieldFormatSource::ParagraphDefaults => {
                panic!("expected FirstResultRun, got ParagraphDefaults")
            }
        }
    }

    /// Extract the concatenated text from a TextRun's content. Lets the
    /// assertions read like prose without depending on `PartialEq` for
    /// the `RunElement` ADT.
    fn run_text(tr: &TextRun) -> String {
        tr.content
            .iter()
            .filter_map(|e| match e {
                RunElement::Text(t) => Some(t.as_str()),
                _ => None,
            })
            .collect()
    }

    /// Canonical complex field shape with a non-empty result run.
    /// Inline layout: `[Begin, InstrText, Separate, TextRun("3"), End]`.
    #[test]
    fn format_source_finds_text_run_after_separate() {
        let inlines = vec![
            fld_char(FieldCharType::Begin),
            Inline::InstrText("PAGE".into()),
            fld_char(FieldCharType::Separate),
            bold_text_run("3"),
            fld_char(FieldCharType::End),
        ];
        let src = resolve_field_format_source(&inlines, 2);
        let tr = expect_first_run(src);
        assert_eq!(run_text(tr), "3");
        assert_eq!(tr.properties.bold, Some(true));
    }

    /// The original bug: an empty `<w:t></w:t>` placeholder result run
    /// must still be discoverable as the format source, because its
    /// `<w:rPr>` is the only place the substitution can find its
    /// formatting.
    #[test]
    fn format_source_finds_empty_placeholder_result_run() {
        let inlines = vec![
            fld_char(FieldCharType::Begin),
            Inline::InstrText("PAGE".into()),
            fld_char(FieldCharType::Separate),
            bold_text_run(""), // empty placeholder, bold rPr
            fld_char(FieldCharType::End),
        ];
        let src = resolve_field_format_source(&inlines, 2);
        let tr = expect_first_run(src);
        assert!(run_text(tr).is_empty(), "expected empty text content");
        assert_eq!(
            tr.properties.bold,
            Some(true),
            "empty placeholder's bold rPr must be reachable"
        );
    }

    /// §17.16.19 — the FIRST result run wins when multiple are present.
    #[test]
    fn format_source_uses_first_when_multiple_result_runs() {
        let inlines = vec![
            fld_char(FieldCharType::Begin),
            Inline::InstrText("PAGE".into()),
            fld_char(FieldCharType::Separate),
            bold_text_run("first"),
            text_run("second"), // not bold
            fld_char(FieldCharType::End),
        ];
        let src = resolve_field_format_source(&inlines, 2);
        let tr = expect_first_run(src);
        assert_eq!(run_text(tr), "first");
        assert_eq!(tr.properties.bold, Some(true));
    }

    /// `Separate` immediately followed by `End` — no result run exists,
    /// so the resolver returns `ParagraphDefaults` and the substitution
    /// will fall back to paragraph defaults at emission time.
    #[test]
    fn format_source_returns_defaults_for_empty_result_zone() {
        let inlines = vec![
            fld_char(FieldCharType::Begin),
            Inline::InstrText("PAGE".into()),
            fld_char(FieldCharType::Separate),
            fld_char(FieldCharType::End),
        ];
        let src = resolve_field_format_source(&inlines, 2);
        assert!(matches!(src, FieldFormatSource::ParagraphDefaults));
    }

    /// Text runs inside a NESTED field's own result zone belong to that
    /// nested field's substitution, not the outer one's. The outer
    /// resolver must skip them and look for runs at its own nesting
    /// level — here, `outer_run` after the nested End.
    #[test]
    fn format_source_skips_runs_inside_nested_field() {
        let inlines = vec![
            fld_char(FieldCharType::Begin), // outer
            Inline::InstrText("OUTER".into()),
            fld_char(FieldCharType::Separate), // index 2
            // ── nested field at depth 1 ──
            fld_char(FieldCharType::Begin),
            Inline::InstrText("INNER".into()),
            fld_char(FieldCharType::Separate),
            bold_text_run("inner-result"), // inside nested zone — skip
            fld_char(FieldCharType::End),
            // ── back at outer's level ──
            bold_text_run("outer-result"), // this is the one we want
            fld_char(FieldCharType::End),
        ];
        let src = resolve_field_format_source(&inlines, 2);
        let tr = expect_first_run(src);
        assert_eq!(
            run_text(tr),
            "outer-result",
            "must skip runs inside nested field"
        );
    }

    /// Content past the matching `End` belongs to a later field (or to
    /// the surrounding paragraph). The resolver stops at `End` and does
    /// not leak formatting from outside.
    #[test]
    fn format_source_stops_at_matching_end() {
        let inlines = vec![
            fld_char(FieldCharType::Begin),
            Inline::InstrText("PAGE".into()),
            fld_char(FieldCharType::Separate), // index 2
            fld_char(FieldCharType::End),
            bold_text_run("trailing"), // outside the field — must not be picked up
        ];
        let src = resolve_field_format_source(&inlines, 2);
        assert!(
            matches!(src, FieldFormatSource::ParagraphDefaults),
            "trailing run after End must not become the source"
        );
    }

    /// Malformed inlines: no matching `End` after `Separate`. Treat as
    /// "no result" rather than panicking or returning a partial result.
    #[test]
    fn format_source_handles_missing_end_gracefully() {
        let inlines = vec![
            fld_char(FieldCharType::Begin),
            Inline::InstrText("PAGE".into()),
            fld_char(FieldCharType::Separate), // index 2
                                               // (no End — malformed)
        ];
        let src = resolve_field_format_source(&inlines, 2);
        // No TextRun present and no End either — defaults is correct.
        assert!(matches!(src, FieldFormatSource::ParagraphDefaults));
    }

    // ── End-to-end: empty-placeholder result run formatting ──────────────
    //
    // Mirrors the Fotodokumentation Test header structure:
    //   `Seite ` [Begin → InstrText("PAGE") → Separate → <w:t></w:t> bold → End]
    // The substituted page number must inherit bold from the empty
    // placeholder result run's `<w:rPr>`.

    #[test]
    fn page_field_with_empty_placeholder_inherits_bold() {
        let inlines = vec![
            bold_text_run("Seite "),
            fld_char(FieldCharType::Begin),
            Inline::InstrText("PAGE".into()),
            fld_char(FieldCharType::Separate),
            bold_text_run(""), // placeholder result with bold rPr
            fld_char(FieldCharType::End),
        ];
        let ctx = default_ctx(12.0);
        let frags = collect_fragments(
            &inlines,
            &ctx,
            None,
            &dummy_measure,
            &mut 0,
            &mut 0,
            FieldContext {
                page_number: Some(7),
                num_pages: None,
            },
        );
        // Two visible text fragments: "Seite " and the substituted "7".
        let texts: Vec<(&str, bool)> = frags
            .iter()
            .filter_map(|f| match f {
                Fragment::Text { text, font, .. } => Some((text.as_ref(), font.bold)),
                _ => None,
            })
            .collect();
        assert_eq!(
            texts,
            vec![("Seite ", true), ("7", true)],
            "PAGE substitution must inherit bold from empty placeholder run"
        );
    }
}