rdocx-layout 0.1.0

Layout engine for converting DOCX flow model to positioned frames
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
//! Layout engine orchestrator: ties all phases together.

use rdocx_oxml::document::{BodyContent, CT_SectPr};
use rdocx_oxml::header_footer::HdrFtrType;
use rdocx_oxml::properties::CT_PPr;
use rdocx_oxml::shared::ST_HighlightColor;
use rdocx_oxml::styles::CT_Styles;
use rdocx_oxml::text::{BreakType, CT_P, FieldType, RunContent};

use crate::block::{self, LayoutBlock, ParagraphBlock};
use crate::error::Result;
use crate::font::FontManager;
use crate::input::LayoutInput;
use crate::line::{self, InlineItem, LineBreakParams, LineItem, TextSegment};
use crate::output::{
    Color, DocumentMetadata, FieldKind, GlyphRun, LayoutResult, PageFrame, Point,
    PositionedElement, Rect,
};
use crate::paginator::{self, HeaderFooterContent, PageGeometry};
use crate::style_resolver::{self, NumberingState};
use crate::table;

/// The layout engine.
pub struct Engine {
    font_manager: FontManager,
}

impl Default for Engine {
    fn default() -> Self {
        Self::new()
    }
}

impl Engine {
    pub fn new() -> Self {
        Engine {
            font_manager: FontManager::new(),
        }
    }

    /// Lay out the entire document.
    pub fn layout(&mut self, input: &LayoutInput) -> Result<LayoutResult> {
        // Load user-provided / DOCX-embedded fonts (highest priority)
        if !input.fonts.is_empty() {
            self.font_manager.load_additional_fonts(&input.fonts);
        }

        let styles = &input.styles;
        let mut num_state = NumberingState::new();

        // Get final section properties (body-level sectPr)
        let final_sect_pr = input
            .document
            .body
            .sect_pr
            .as_ref()
            .cloned()
            .unwrap_or_else(CT_SectPr::default_letter);

        // Build sections: each section has blocks + geometry + header/footer
        let mut sections: Vec<paginator::Section> = Vec::new();
        let mut current_blocks: Vec<LayoutBlock> = Vec::new();
        let mut current_sect_pr: Option<CT_SectPr> = None; // Will be set from paragraph sect_pr

        for content in &input.document.body.content {
            match content {
                BodyContent::Paragraph(para) => {
                    // Check if this paragraph ends a section (has sect_pr)
                    let para_sect_pr = para.properties.as_ref().and_then(|p| p.sect_pr.clone());

                    let sect_pr_for_layout = para_sect_pr
                        .as_ref()
                        .or(current_sect_pr.as_ref())
                        .unwrap_or(&final_sect_pr);
                    let geometry = sect_pr_to_geometry(sect_pr_for_layout);

                    let mut para_block = layout_paragraph(
                        para,
                        geometry.content_width(),
                        styles,
                        input,
                        &mut self.font_manager,
                        &mut num_state,
                    )?;

                    // Detect heading style for outline generation
                    if let Some(level) = detect_heading_level(para, styles) {
                        para_block.heading_level = Some(level);
                        para_block.heading_text = Some(para.text());
                    }

                    current_blocks.push(LayoutBlock::Paragraph(para_block));

                    // If this paragraph has sect_pr, it ends a section
                    if let Some(sect_pr) = para_sect_pr {
                        let geometry = sect_pr_to_geometry(&sect_pr);
                        let header_footer = layout_header_footer(
                            &sect_pr,
                            input,
                            styles,
                            &mut self.font_manager,
                            &mut num_state,
                        )?;
                        let title_pg = sect_pr.title_pg.unwrap_or(false);
                        sections.push(paginator::Section {
                            blocks: std::mem::take(&mut current_blocks),
                            geometry,
                            header_footer,
                            title_pg,
                        });
                        current_sect_pr = Some(sect_pr);
                    }
                }
                BodyContent::Table(tbl) => {
                    let sect_pr_for_layout = current_sect_pr.as_ref().unwrap_or(&final_sect_pr);
                    let geometry = sect_pr_to_geometry(sect_pr_for_layout);

                    let table_block = table::layout_table(
                        tbl,
                        geometry.content_width(),
                        styles,
                        input,
                        &mut self.font_manager,
                        &mut num_state,
                    )?;
                    current_blocks.push(LayoutBlock::Table(table_block));
                }
                _ => {} // Skip RawXml elements during layout
            }
        }

        // Remaining blocks belong to the final section
        let final_geometry = sect_pr_to_geometry(&final_sect_pr);
        let final_hf = layout_header_footer(
            &final_sect_pr,
            input,
            styles,
            &mut self.font_manager,
            &mut num_state,
        )?;
        let final_title_pg = final_sect_pr.title_pg.unwrap_or(false);
        sections.push(paginator::Section {
            blocks: current_blocks,
            geometry: final_geometry,
            header_footer: final_hf,
            title_pg: final_title_pg,
        });

        // Paginate across all sections
        let (mut pages, outlines) = paginator::paginate_sections(&sections, &self.font_manager);

        // Post-pagination pass: substitute field placeholders
        let total_pages = pages.len();
        for page in &mut pages {
            let page_num = page.page_number;
            substitute_fields(
                &mut page.elements,
                page_num,
                total_pages,
                &mut self.font_manager,
            );
        }

        // Post-pagination pass: apply page background color
        apply_page_background(&mut pages, input);

        // Post-pagination pass: resolve anchor (background) images
        resolve_anchor_images(&mut pages, input);

        // Post-pagination pass: resolve inline image data
        resolve_inline_images(&mut pages, input);

        // Post-pagination pass: render footnotes at page bottoms
        if input.footnotes.is_some() || input.endnotes.is_some() {
            render_page_footnotes(
                &mut pages,
                input,
                styles,
                &final_geometry,
                &mut self.font_manager,
                &mut num_state,
            )?;
        }

        // Collect font data
        let fonts = self.font_manager.all_font_data();

        // Convert core properties to document metadata
        let metadata = input.core_properties.as_ref().map(|cp| DocumentMetadata {
            title: cp.title.clone(),
            author: cp.creator.clone(),
            subject: cp.subject.clone(),
            keywords: cp.keywords.clone(),
            creator: Some("rdocx".to_string()),
        });

        Ok(LayoutResult {
            pages,
            fonts,
            metadata,
            outlines,
        })
    }
}

/// Apply page background color from `w:background` element to all pages.
fn apply_page_background(pages: &mut [PageFrame], input: &LayoutInput) {
    let bg_xml = match &input.document.background_xml {
        Some(xml) => xml,
        None => return,
    };

    // Parse w:color attribute from background XML
    let xml_str = std::str::from_utf8(bg_xml).unwrap_or("");
    let color = extract_background_color(xml_str);
    let color = match color {
        Some(c) => c,
        None => return,
    };

    // Insert a full-page FilledRect at position 0 on every page (renders underneath everything)
    for page in pages.iter_mut() {
        page.elements.insert(
            0,
            PositionedElement::FilledRect {
                rect: Rect {
                    x: 0.0,
                    y: 0.0,
                    width: page.width,
                    height: page.height,
                },
                color,
            },
        );
    }
}

/// Extract the background color hex from w:background XML.
fn extract_background_color(xml: &str) -> Option<Color> {
    // Look for w:color="RRGGBB" or color="RRGGBB"
    for attr in ["w:color=\"", "color=\""] {
        if let Some(start) = xml.find(attr) {
            let val_start = start + attr.len();
            if let Some(end) = xml[val_start..].find('"') {
                let hex = &xml[val_start..val_start + end];
                if hex.len() == 6 && hex != "auto" {
                    return Some(Color::from_hex(hex));
                }
            }
        }
    }
    None
}

/// Resolve anchor (floating) images from the document and inject them into page frames.
///
/// For `behind_doc=true` images: inserts at the START of page elements (renders underneath).
/// For `behind_doc=false` images: inserts at the END (renders on top).
fn resolve_anchor_images(pages: &mut [PageFrame], input: &LayoutInput) {
    use crate::output::Rect;
    use rdocx_oxml::text::RunContent;

    // Collect all anchor drawings from body content
    let mut anchor_images: Vec<(bool, f64, f64, f64, f64, String)> = Vec::new();

    for content in &input.document.body.content {
        if let BodyContent::Paragraph(p) = content {
            for run in &p.runs {
                for rc in &run.content {
                    if let RunContent::Drawing(drawing) = rc {
                        if let Some(ref anchor) = drawing.anchor {
                            let behind = anchor.behind_doc;
                            // Convert EMU positions and extents to points
                            let x = anchor.pos_h_offset.to_pt();
                            let y = anchor.pos_v_offset.to_pt();
                            let w = anchor.extent_cx.to_pt();
                            let h = anchor.extent_cy.to_pt();
                            anchor_images.push((behind, x, y, w, h, anchor.embed_id.clone()));
                        }
                    }
                }
            }
        }
    }

    if anchor_images.is_empty() {
        return;
    }

    // For each anchor image, resolve image data and add to pages
    for (behind, x, y, w, h, embed_id) in &anchor_images {
        let (data, content_type) = if let Some(img) = input.images.get(embed_id) {
            (img.data.clone(), img.content_type.clone())
        } else {
            continue;
        };

        let element = PositionedElement::Image {
            rect: Rect {
                x: *x,
                y: *y,
                width: *w,
                height: *h,
            },
            data,
            content_type,
            embed_id: None, // Already resolved
        };

        if *behind {
            // Behind-doc images go on the first page only
            // (proper page association would require paragraph-to-page mapping)
            if let Some(page) = pages.first_mut() {
                page.elements.insert(0, element);
            }
        } else if let Some(page) = pages.first_mut() {
            // Foreground anchor images go on the first page only
            page.elements.push(element);
        }
    }
}

/// Resolve inline image data from input.images by embed_id.
///
/// During pagination, inline images are created with empty data and an embed_id.
/// This pass fills in the actual image bytes and content type.
fn resolve_inline_images(pages: &mut [PageFrame], input: &LayoutInput) {
    for page in pages.iter_mut() {
        for element in &mut page.elements {
            if let PositionedElement::Image {
                data,
                content_type,
                embed_id: Some(eid),
                ..
            } = element
            {
                if data.is_empty() {
                    if let Some(img) = input.images.get(eid.as_str()) {
                        *data = img.data.clone();
                        *content_type = img.content_type.clone();
                    }
                }
            }
        }
    }
}

/// Replace field placeholder GlyphRuns with actual values.
fn substitute_fields(
    elements: &mut [PositionedElement],
    page_number: usize,
    total_pages: usize,
    fm: &mut crate::font::FontManager,
) {
    for element in elements.iter_mut() {
        if let PositionedElement::Text(run) = element {
            if let Some(fk) = run.field_kind {
                let value = match fk {
                    FieldKind::Page => page_number.to_string(),
                    FieldKind::NumPages => total_pages.to_string(),
                };
                // Re-shape the text with the actual value
                if let Ok(shaped) = fm.shape_text(run.font_id, &value, run.font_size) {
                    run.text = value;
                    run.glyph_ids = shaped.glyph_ids;
                    run.advances = shaped.advances;
                }
            }
        }
    }
}

/// Render footnote/endnote content at the bottom of each page.
///
/// For each page, collects footnote IDs from glyph runs, then
/// renders a separator line and the footnote text in a smaller font.
fn render_page_footnotes(
    pages: &mut [PageFrame],
    input: &LayoutInput,
    styles: &CT_Styles,
    geometry: &paginator::PageGeometry,
    fm: &mut FontManager,
    num_state: &mut NumberingState,
) -> Result<()> {
    let footnote_font_size = 8.0; // Standard footnote font size
    let separator_offset = 6.0; // Space above separator
    let separator_width_frac = 0.33; // Separator is 1/3 of content width

    for page in pages.iter_mut() {
        // Collect footnote IDs referenced on this page (in order, deduplicated)
        let mut footnote_ids: Vec<i32> = Vec::new();
        for element in &page.elements {
            if let PositionedElement::Text(run) = element {
                if let Some(fn_id) = run.footnote_id {
                    if !footnote_ids.contains(&fn_id) {
                        footnote_ids.push(fn_id);
                    }
                }
            }
        }

        if footnote_ids.is_empty() {
            continue;
        }

        // Find the footnote paragraphs to render
        let mut footnote_blocks: Vec<(i32, Vec<block::ParagraphBlock>)> = Vec::new();
        for &fn_id in &footnote_ids {
            // Check footnotes first, then endnotes
            let paragraphs = input
                .footnotes
                .as_ref()
                .and_then(|fns| fns.get_by_id(fn_id))
                .or_else(|| input.endnotes.as_ref().and_then(|ens| ens.get_by_id(fn_id)));

            if let Some(footnote) = paragraphs {
                let mut fn_blocks = Vec::new();
                for para in &footnote.paragraphs {
                    if let Ok(pb) = layout_paragraph(
                        para,
                        geometry.content_width(),
                        styles,
                        input,
                        fm,
                        num_state,
                    ) {
                        fn_blocks.push(pb);
                    }
                }
                footnote_blocks.push((fn_id, fn_blocks));
            }
        }

        if footnote_blocks.is_empty() {
            continue;
        }

        // Calculate total footnote height
        let total_fn_height: f64 = footnote_blocks
            .iter()
            .flat_map(|(_, blocks)| blocks.iter())
            .map(|b| b.content_height())
            .sum();

        // Position footnotes at page bottom, above bottom margin
        let footnote_area_top =
            page.height - geometry.margin_bottom - total_fn_height - separator_offset;

        // Draw separator line
        let sep_y = footnote_area_top;
        let sep_width = geometry.content_width() * separator_width_frac;
        page.elements.push(PositionedElement::Line {
            start: Point {
                x: geometry.margin_left,
                y: sep_y,
            },
            end: Point {
                x: geometry.margin_left + sep_width,
                y: sep_y,
            },
            width: 0.5,
            color: Color::BLACK,
            dash_pattern: None,
        });

        // Render each footnote
        let mut cursor_y = sep_y + separator_offset;
        for (fn_id, blocks) in &footnote_blocks {
            for pb in blocks {
                let baseline_y = cursor_y + pb.lines.first().map(|l| l.ascent).unwrap_or(0.0);

                // Render the footnote number marker as superscript
                let marker_text = fn_id.to_string();
                let marker_size = footnote_font_size * 0.58;
                if let Ok(font_id) = fm.resolve_font(Some("serif"), false, false) {
                    if let Ok(shaped) = fm.shape_text(font_id, &marker_text, marker_size) {
                        page.elements.push(PositionedElement::Text(GlyphRun {
                            origin: Point {
                                x: geometry.margin_left,
                                y: baseline_y - footnote_font_size * 0.33,
                            },
                            font_id,
                            font_size: marker_size,
                            glyph_ids: shaped.glyph_ids,
                            advances: shaped.advances,
                            text: marker_text,
                            color: Color::BLACK,
                            bold: false,
                            italic: false,
                            field_kind: None,
                            footnote_id: None,
                        }));
                    }
                }

                // Render footnote paragraph lines
                let indent = 12.0; // Indent after marker
                for line in &pb.lines {
                    let line_baseline = cursor_y + line.ascent;
                    for item in &line.items {
                        if let LineItem::Text(seg) | LineItem::Marker(seg) = item {
                            page.elements.push(PositionedElement::Text(GlyphRun {
                                origin: Point {
                                    x: geometry.margin_left + indent,
                                    y: line_baseline - seg.baseline_offset,
                                },
                                font_id: seg.font_id,
                                font_size: seg.font_size,
                                glyph_ids: seg.glyph_ids.clone(),
                                advances: seg.advances.clone(),
                                text: seg.text.clone(),
                                color: seg.color,
                                bold: seg.bold,
                                italic: seg.italic,
                                field_kind: None,
                                footnote_id: None,
                            }));
                        }
                    }
                    cursor_y += line.height;
                }
            }
        }
    }

    Ok(())
}

/// Detect if a paragraph has a heading style, returning the level (1-9).
fn detect_heading_level(para: &CT_P, styles: &CT_Styles) -> Option<u32> {
    let style_id = para.properties.as_ref()?.style_id.as_deref()?;
    // Check if style ID matches "Heading1" .. "Heading9"
    if let Some(rest) = style_id.strip_prefix("Heading") {
        return rest.parse::<u32>().ok().filter(|n| (1..=9).contains(n));
    }
    // Also check style name in the styles definitions
    if let Some(style_def) = styles.get_by_id(style_id) {
        if let Some(ref name) = style_def.name {
            if let Some(rest) = name.strip_prefix("heading ") {
                return rest.parse::<u32>().ok().filter(|n| (1..=9).contains(n));
            }
        }
    }
    None
}

/// Lay out a single paragraph into a ParagraphBlock.
pub fn layout_paragraph(
    para: &CT_P,
    available_width: f64,
    styles: &CT_Styles,
    input: &LayoutInput,
    fm: &mut FontManager,
    num_state: &mut NumberingState,
) -> Result<ParagraphBlock> {
    // Resolve paragraph properties
    let para_style_id = para.properties.as_ref().and_then(|p| p.style_id.as_deref());

    let resolved_ppr = style_resolver::resolve_paragraph_properties(para_style_id, styles);

    // Merge direct paragraph properties
    let mut effective_ppr = resolved_ppr;
    if let Some(ref direct_ppr) = para.properties {
        merge_direct_ppr(&mut effective_ppr, direct_ppr);
    }

    // Convert paragraph properties to layout values
    let space_before = effective_ppr.space_before.map(|t| t.to_pt()).unwrap_or(0.0);
    let space_after = effective_ppr.space_after.map(|t| t.to_pt()).unwrap_or(0.0);
    let ind_left = effective_ppr.ind_left.map(|t| t.to_pt()).unwrap_or(0.0);
    let ind_right = effective_ppr.ind_right.map(|t| t.to_pt()).unwrap_or(0.0);
    let ind_first_line = effective_ppr
        .ind_first_line
        .map(|t| t.to_pt())
        .unwrap_or(0.0);
    let ind_hanging = effective_ppr.ind_hanging.map(|t| t.to_pt()).unwrap_or(0.0);

    let keep_next = effective_ppr.keep_next.unwrap_or(false);
    let keep_lines = effective_ppr.keep_lines.unwrap_or(false);
    let page_break_before = effective_ppr.page_break_before.unwrap_or(false);
    let widow_control = effective_ppr.widow_control.unwrap_or(true);
    let jc = effective_ppr.jc;

    // Collect tab stops
    let tab_stops = effective_ppr
        .tabs
        .as_ref()
        .map(|t| t.tabs.clone())
        .unwrap_or_default();

    // Parse shading color
    let shading = effective_ppr
        .shading
        .as_ref()
        .and_then(|shd| shd.fill.as_ref())
        .filter(|f| f != &"auto")
        .map(|f| Color::from_hex(f));

    // Convert runs to inline items
    let mut inline_items = Vec::new();

    // Handle numbering marker
    if let (Some(num_id), Some(numbering)) = (effective_ppr.num_id, input.numbering.as_ref()) {
        let ilvl = effective_ppr.num_ilvl.unwrap_or(0);
        if let Some(marker) = style_resolver::generate_marker(num_id, ilvl, numbering, num_state) {
            // Shape the marker text
            let marker_rpr = marker.marker_rpr;
            let marker_font_size = marker_rpr.sz.map(|hp| hp.to_pt()).unwrap_or_else(|| {
                style_resolver::resolve_run_properties(para_style_id, None, styles)
                    .sz
                    .map(|hp| hp.to_pt())
                    .unwrap_or(11.0)
            });
            let marker_bold = marker_rpr.bold.unwrap_or(false);
            let marker_italic = marker_rpr.italic.unwrap_or(false);
            let marker_font_family = marker_rpr.font_ascii.as_deref();

            if let Ok(font_id) = fm.resolve_font(marker_font_family, marker_bold, marker_italic) {
                if let Ok(shaped) = fm.shape_text(font_id, &marker.marker_text, marker_font_size) {
                    let metrics = fm.metrics(font_id, marker_font_size)?;
                    let color = marker_rpr
                        .color
                        .as_ref()
                        .map(|c| Color::from_hex(c))
                        .unwrap_or(Color::BLACK);

                    inline_items.push(InlineItem::Marker(TextSegment {
                        text: marker.marker_text,
                        font_id,
                        font_size: marker_font_size,
                        glyph_ids: shaped.glyph_ids,
                        advances: shaped.advances,
                        width: shaped.width,
                        ascent: metrics.ascent,
                        descent: metrics.descent,
                        color,
                        bold: marker_bold,
                        italic: marker_italic,
                        underline: None,
                        strike: false,
                        dstrike: false,
                        highlight: None,
                        baseline_offset: 0.0,
                        hyperlink_url: None,
                        field_kind: None,
                        footnote_id: None,
                    }));

                    // Add a space/tab after the marker
                    inline_items.push(InlineItem::Tab);
                }
            }
        }
    }

    // Build hyperlink URL map: run index → URL
    let mut run_hyperlink_url: std::collections::HashMap<usize, String> =
        std::collections::HashMap::new();
    for hl in &para.hyperlinks {
        if let Some(ref rel_id) = hl.rel_id {
            if let Some(url) = input.hyperlink_urls.get(rel_id) {
                for run_idx in hl.run_start..hl.run_end {
                    run_hyperlink_url.insert(run_idx, url.clone());
                }
            }
        }
    }

    // Process runs
    for (run_idx, run) in para.runs.iter().enumerate() {
        let current_hyperlink_url = run_hyperlink_url.get(&run_idx).cloned();

        let run_style_id = run.properties.as_ref().and_then(|p| p.style_id.as_deref());

        let resolved_rpr =
            style_resolver::resolve_run_properties(para_style_id, run_style_id, styles);

        // Merge direct run properties
        let mut effective_rpr = resolved_rpr;
        if let Some(ref direct_rpr) = run.properties {
            effective_rpr.merge_from(direct_rpr);
        }

        // Skip hidden text
        if effective_rpr.vanish == Some(true) {
            continue;
        }

        let mut font_size = effective_rpr.sz.map(|hp| hp.to_pt()).unwrap_or(11.0);
        let bold = effective_rpr.bold.unwrap_or(false);
        let italic = effective_rpr.italic.unwrap_or(false);

        // Resolve font family: theme font takes priority when no explicit font is set
        let font_family = resolve_font_family(&effective_rpr, input.theme.as_ref());

        // Resolve color: theme color takes priority over literal color value
        let color = resolve_run_color(&effective_rpr, input.theme.as_ref());

        // Decoration properties
        let underline = effective_rpr.underline;
        let strike = effective_rpr.strike.unwrap_or(false);
        let dstrike = effective_rpr.dstrike.unwrap_or(false);
        let highlight = effective_rpr.highlight.and_then(highlight_to_color);

        // Superscript/subscript handling
        let mut baseline_offset = 0.0;
        if let Some(ref va) = effective_rpr.vert_align {
            match va.as_str() {
                "superscript" => {
                    // Reduce font size to ~58% and raise baseline
                    let original_size = font_size;
                    font_size *= 0.58;
                    baseline_offset = original_size * 0.33; // raise by 1/3 of original size
                }
                "subscript" => {
                    // Reduce font size to ~58% and lower baseline
                    let original_size = font_size;
                    font_size *= 0.58;
                    baseline_offset = -(original_size * 0.14); // lower
                }
                _ => {}
            }
        }

        // Position offset (in half-points, positive=raise)
        if let Some(pos) = effective_rpr.position {
            baseline_offset += pos as f64 / 2.0; // half-points to points
        }

        let font_id = fm.resolve_font(font_family.as_deref(), bold, italic)?;
        let metrics = fm.metrics(font_id, font_size)?;

        for content in &run.content {
            match content {
                RunContent::Text(ct_text) => {
                    let text = if effective_rpr.caps == Some(true) {
                        ct_text.text.to_uppercase()
                    } else {
                        ct_text.text.clone()
                    };

                    if text.is_empty() {
                        continue;
                    }

                    let mut shaped = fm.shape_text(font_id, &text, font_size)?;

                    // Apply character spacing from run properties (in twips)
                    if let Some(spacing) = effective_rpr.spacing {
                        let extra = spacing.to_pt();
                        for advance in &mut shaped.advances {
                            *advance += extra;
                        }
                        shaped.width += extra * shaped.advances.len() as f64;
                    }

                    inline_items.push(InlineItem::Text(TextSegment {
                        text,
                        font_id,
                        font_size,
                        glyph_ids: shaped.glyph_ids,
                        advances: shaped.advances,
                        width: shaped.width,
                        ascent: metrics.ascent,
                        descent: metrics.descent,
                        color,
                        bold,
                        italic,
                        underline,
                        strike,
                        dstrike,
                        highlight,
                        baseline_offset,
                        hyperlink_url: current_hyperlink_url.clone(),
                        field_kind: None,
                        footnote_id: None,
                    }));
                }
                RunContent::Tab => {
                    inline_items.push(InlineItem::Tab);
                }
                RunContent::Break(bt) => match bt {
                    BreakType::Line => inline_items.push(InlineItem::LineBreak),
                    BreakType::Page => inline_items.push(InlineItem::PageBreak),
                    BreakType::Column => inline_items.push(InlineItem::ColumnBreak),
                },
                RunContent::Drawing(drawing) => {
                    if let Some(ref inline) = drawing.inline {
                        let width = inline.extent_cx.to_pt();
                        let height = inline.extent_cy.to_pt();
                        inline_items.push(InlineItem::Image {
                            width,
                            height,
                            embed_id: inline.embed_id.clone(),
                        });
                    }
                }
                RunContent::Field { field_type } => {
                    // Shape a placeholder ("99") for estimated width
                    let placeholder = "99";
                    let fk = match field_type {
                        FieldType::Page => FieldKind::Page,
                        FieldType::NumPages => FieldKind::NumPages,
                        FieldType::Other(_) => continue, // skip unsupported fields
                    };
                    let shaped = fm.shape_text(font_id, placeholder, font_size)?;
                    inline_items.push(InlineItem::Text(TextSegment {
                        text: placeholder.to_string(),
                        font_id,
                        font_size,
                        glyph_ids: shaped.glyph_ids,
                        advances: shaped.advances,
                        width: shaped.width,
                        ascent: metrics.ascent,
                        descent: metrics.descent,
                        color,
                        bold,
                        italic,
                        underline: None,
                        strike: false,
                        dstrike: false,
                        highlight: None,
                        baseline_offset,
                        hyperlink_url: None,
                        field_kind: Some(fk),
                        footnote_id: None,
                    }));
                }
                RunContent::FootnoteRef { id } | RunContent::EndnoteRef { id } => {
                    // Render as superscript number
                    let marker = id.to_string();
                    let sup_size = font_size * 0.58;
                    let sup_offset = font_size * 0.33; // raise baseline
                    let shaped = fm.shape_text(font_id, &marker, sup_size)?;
                    let sup_metrics = fm.metrics(font_id, sup_size)?;
                    inline_items.push(InlineItem::Text(TextSegment {
                        text: marker,
                        font_id,
                        font_size: sup_size,
                        glyph_ids: shaped.glyph_ids,
                        advances: shaped.advances,
                        width: shaped.width,
                        ascent: sup_metrics.ascent,
                        descent: sup_metrics.descent,
                        color,
                        bold,
                        italic,
                        underline: None,
                        strike: false,
                        dstrike: false,
                        highlight: None,
                        baseline_offset: sup_offset,
                        hyperlink_url: None,
                        field_kind: None,
                        footnote_id: Some(*id),
                    }));
                }
            }
        }
    }

    // Line breaking
    let line_params = LineBreakParams {
        available_width,
        ind_left,
        ind_right,
        ind_first_line,
        ind_hanging,
        tab_stops,
        line_spacing: effective_ppr.line_spacing,
        line_rule: effective_ppr.line_rule,
        jc,
    };

    let lines = line::break_into_lines(&inline_items, &line_params, fm)?;

    Ok(block::build_paragraph_block(
        lines,
        space_before,
        space_after,
        effective_ppr.borders,
        shading,
        ind_left,
        ind_right,
        jc,
        keep_next,
        keep_lines,
        page_break_before,
        widow_control,
    ))
}

/// Merge direct paragraph properties (only fields explicitly set in the XML).
fn merge_direct_ppr(effective: &mut CT_PPr, direct: &CT_PPr) {
    // Don't merge style_id — that was already used for resolution
    if direct.jc.is_some() {
        effective.jc = direct.jc;
    }
    if direct.space_before.is_some() {
        effective.space_before = direct.space_before;
    }
    if direct.space_after.is_some() {
        effective.space_after = direct.space_after;
    }
    if direct.line_spacing.is_some() {
        effective.line_spacing = direct.line_spacing;
    }
    if direct.line_rule.is_some() {
        effective.line_rule = direct.line_rule.clone();
    }
    if direct.ind_left.is_some() {
        effective.ind_left = direct.ind_left;
    }
    if direct.ind_right.is_some() {
        effective.ind_right = direct.ind_right;
    }
    if direct.ind_first_line.is_some() {
        effective.ind_first_line = direct.ind_first_line;
    }
    if direct.ind_hanging.is_some() {
        effective.ind_hanging = direct.ind_hanging;
    }
    if direct.keep_next.is_some() {
        effective.keep_next = direct.keep_next;
    }
    if direct.keep_lines.is_some() {
        effective.keep_lines = direct.keep_lines;
    }
    if direct.page_break_before.is_some() {
        effective.page_break_before = direct.page_break_before;
    }
    if direct.widow_control.is_some() {
        effective.widow_control = direct.widow_control;
    }
    if direct.borders.is_some() {
        effective.borders = direct.borders.clone();
    }
    if direct.tabs.is_some() {
        effective.tabs = direct.tabs.clone();
    }
    if direct.shading.is_some() {
        effective.shading = direct.shading.clone();
    }
    if direct.num_id.is_some() {
        effective.num_id = direct.num_id;
    }
    if direct.num_ilvl.is_some() {
        effective.num_ilvl = direct.num_ilvl;
    }
}

/// Convert section properties to page geometry.
fn sect_pr_to_geometry(sect_pr: &CT_SectPr) -> PageGeometry {
    PageGeometry {
        page_width: sect_pr.page_width.map(|t| t.to_pt()).unwrap_or(612.0),
        page_height: sect_pr.page_height.map(|t| t.to_pt()).unwrap_or(792.0),
        margin_top: sect_pr.margin_top.map(|t| t.to_pt()).unwrap_or(72.0),
        margin_right: sect_pr.margin_right.map(|t| t.to_pt()).unwrap_or(72.0),
        margin_bottom: sect_pr.margin_bottom.map(|t| t.to_pt()).unwrap_or(72.0),
        margin_left: sect_pr.margin_left.map(|t| t.to_pt()).unwrap_or(72.0),
        header_distance: sect_pr.header_distance.map(|t| t.to_pt()).unwrap_or(36.0),
        footer_distance: sect_pr.footer_distance.map(|t| t.to_pt()).unwrap_or(36.0),
    }
}

/// Lay out header and footer content (both Default and First-page).
fn layout_header_footer(
    sect_pr: &CT_SectPr,
    input: &LayoutInput,
    styles: &CT_Styles,
    fm: &mut FontManager,
    num_state: &mut NumberingState,
) -> Result<Option<HeaderFooterContent>> {
    let mut has_content = false;
    let mut header_blocks = Vec::new();
    let mut footer_blocks = Vec::new();
    let mut first_header_blocks = Vec::new();
    let mut first_footer_blocks = Vec::new();

    let geometry = sect_pr_to_geometry(sect_pr);
    let width = geometry.content_width();

    for href in &sect_pr.header_refs {
        let target_blocks = match href.hdr_ftr_type {
            HdrFtrType::Default => &mut header_blocks,
            HdrFtrType::First => &mut first_header_blocks,
            _ => continue, // skip Even for now
        };
        if let Some(hdr) = input.headers.get(&href.rel_id) {
            for para in &hdr.paragraphs {
                let block = layout_paragraph(para, width, styles, input, fm, num_state)?;
                target_blocks.push(block);
            }
            has_content = true;
        }
    }

    for fref in &sect_pr.footer_refs {
        let target_blocks = match fref.hdr_ftr_type {
            HdrFtrType::Default => &mut footer_blocks,
            HdrFtrType::First => &mut first_footer_blocks,
            _ => continue, // skip Even for now
        };
        if let Some(ftr) = input.footers.get(&fref.rel_id) {
            for para in &ftr.paragraphs {
                let block = layout_paragraph(para, width, styles, input, fm, num_state)?;
                target_blocks.push(block);
            }
            has_content = true;
        }
    }

    if has_content {
        Ok(Some(HeaderFooterContent {
            header_blocks,
            footer_blocks,
            first_header_blocks,
            first_footer_blocks,
        }))
    } else {
        Ok(None)
    }
}

/// Resolve the effective font family for a run, considering theme fonts.
///
/// Priority: explicit font_ascii > theme font > None (use default).
fn resolve_font_family(
    rpr: &rdocx_oxml::properties::CT_RPr,
    theme: Option<&rdocx_oxml::theme::Theme>,
) -> Option<String> {
    // Explicit font name takes priority
    if rpr.font_ascii.is_some() {
        return rpr.font_ascii.clone();
    }

    // Resolve theme font reference
    if let (Some(theme_ref), Some(theme)) = (&rpr.font_ascii_theme, theme) {
        let font = match theme_ref.as_str() {
            "majorAscii" | "majorHAnsi" | "majorBidi" | "majorEastAsia" => {
                theme.major_font.as_deref()
            }
            "minorAscii" | "minorHAnsi" | "minorBidi" | "minorEastAsia" => {
                theme.minor_font.as_deref()
            }
            _ => None,
        };
        if let Some(f) = font {
            return Some(f.to_string());
        }
    }

    None
}

/// Resolve the effective color for a run, considering theme colors.
///
/// Priority: literal color (non-auto) > theme color > black.
fn resolve_run_color(
    rpr: &rdocx_oxml::properties::CT_RPr,
    theme: Option<&rdocx_oxml::theme::Theme>,
) -> Color {
    // If theme color is specified, resolve it from the theme
    if let Some(ref theme_name) = rpr.color_theme {
        if let Some(theme) = theme {
            if let Some(hex) = theme.colors.get(theme_name) {
                return Color::from_hex(hex);
            }
        }
    }

    // Fall back to literal color value
    rpr.color
        .as_ref()
        .filter(|c| c.as_str() != "auto")
        .map(|c| Color::from_hex(c))
        .unwrap_or(Color::BLACK)
}

/// Convert a highlight color enum to an RGBA Color.
fn highlight_to_color(h: ST_HighlightColor) -> Option<Color> {
    match h {
        ST_HighlightColor::None => None,
        ST_HighlightColor::Black => Some(Color {
            r: 0.0,
            g: 0.0,
            b: 0.0,
            a: 1.0,
        }),
        ST_HighlightColor::Blue => Some(Color {
            r: 0.0,
            g: 0.0,
            b: 1.0,
            a: 1.0,
        }),
        ST_HighlightColor::Cyan => Some(Color {
            r: 0.0,
            g: 1.0,
            b: 1.0,
            a: 1.0,
        }),
        ST_HighlightColor::DarkBlue => Some(Color {
            r: 0.0,
            g: 0.0,
            b: 0.545,
            a: 1.0,
        }),
        ST_HighlightColor::DarkCyan => Some(Color {
            r: 0.0,
            g: 0.545,
            b: 0.545,
            a: 1.0,
        }),
        ST_HighlightColor::DarkGray => Some(Color {
            r: 0.663,
            g: 0.663,
            b: 0.663,
            a: 1.0,
        }),
        ST_HighlightColor::DarkGreen => Some(Color {
            r: 0.0,
            g: 0.392,
            b: 0.0,
            a: 1.0,
        }),
        ST_HighlightColor::DarkMagenta => Some(Color {
            r: 0.545,
            g: 0.0,
            b: 0.545,
            a: 1.0,
        }),
        ST_HighlightColor::DarkRed => Some(Color {
            r: 0.545,
            g: 0.0,
            b: 0.0,
            a: 1.0,
        }),
        ST_HighlightColor::DarkYellow => Some(Color {
            r: 0.545,
            g: 0.545,
            b: 0.0,
            a: 1.0,
        }),
        ST_HighlightColor::Green => Some(Color {
            r: 0.0,
            g: 1.0,
            b: 0.0,
            a: 1.0,
        }),
        ST_HighlightColor::LightGray => Some(Color {
            r: 0.827,
            g: 0.827,
            b: 0.827,
            a: 1.0,
        }),
        ST_HighlightColor::Magenta => Some(Color {
            r: 1.0,
            g: 0.0,
            b: 1.0,
            a: 1.0,
        }),
        ST_HighlightColor::Red => Some(Color {
            r: 1.0,
            g: 0.0,
            b: 0.0,
            a: 1.0,
        }),
        ST_HighlightColor::White => Some(Color {
            r: 1.0,
            g: 1.0,
            b: 1.0,
            a: 1.0,
        }),
        ST_HighlightColor::Yellow => Some(Color {
            r: 1.0,
            g: 1.0,
            b: 0.0,
            a: 1.0,
        }),
    }
}

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

    fn make_input_with_text(text: &str) -> LayoutInput {
        let mut doc = rdocx_oxml::document::CT_Document::new();
        let mut p = CT_P::new();
        p.add_run(text);
        doc.body.add_paragraph(p);

        LayoutInput {
            document: doc,
            styles: CT_Styles::new_default(),
            numbering: None,
            headers: HashMap::new(),
            footers: HashMap::new(),
            images: HashMap::new(),
            core_properties: None,
            hyperlink_urls: HashMap::new(),
            footnotes: None,
            endnotes: None,
            theme: None,
            fonts: Vec::new(),
        }
    }

    #[test]
    fn layout_simple_document() {
        let input = make_input_with_text("Hello World");
        let result = Engine::new().layout(&input);
        // On systems without fonts, this may fail — that's OK
        if let Ok(result) = result {
            assert!(!result.pages.is_empty());
            assert_eq!(result.pages[0].page_number, 1);
            assert!((result.pages[0].width - 612.0).abs() < 0.01);
        }
    }

    #[test]
    fn layout_empty_document() {
        let mut doc = rdocx_oxml::document::CT_Document::new();
        doc.body.add_paragraph(CT_P::new());

        let input = LayoutInput {
            document: doc,
            styles: CT_Styles::new_default(),
            numbering: None,
            headers: HashMap::new(),
            footers: HashMap::new(),
            images: HashMap::new(),
            core_properties: None,
            hyperlink_urls: HashMap::new(),
            footnotes: None,
            endnotes: None,
            theme: None,
            fonts: Vec::new(),
        };

        let result = Engine::new().layout(&input);
        if let Ok(result) = result {
            assert_eq!(result.pages.len(), 1);
        }
    }

    #[test]
    fn layout_with_heading_style() {
        let mut doc = rdocx_oxml::document::CT_Document::new();
        let mut p = CT_P::new();
        p.properties = Some(CT_PPr {
            style_id: Some("Heading1".to_string()),
            ..Default::default()
        });
        p.add_run("Chapter 1");
        doc.body.add_paragraph(p);

        let input = LayoutInput {
            document: doc,
            styles: CT_Styles::new_default(),
            numbering: None,
            headers: HashMap::new(),
            footers: HashMap::new(),
            images: HashMap::new(),
            core_properties: None,
            hyperlink_urls: HashMap::new(),
            footnotes: None,
            endnotes: None,
            theme: None,
            fonts: Vec::new(),
        };

        let result = Engine::new().layout(&input);
        if let Ok(result) = result {
            assert!(!result.pages.is_empty());
            // Should produce one outline entry for Heading1
            assert_eq!(result.outlines.len(), 1);
            assert_eq!(result.outlines[0].title, "Chapter 1");
            assert_eq!(result.outlines[0].level, 1);
            assert_eq!(result.outlines[0].page_index, 0);
        }
    }

    #[test]
    fn layout_nested_headings_produce_outlines() {
        let mut doc = rdocx_oxml::document::CT_Document::new();

        // H1
        let mut h1 = CT_P::new();
        h1.properties = Some(CT_PPr {
            style_id: Some("Heading1".to_string()),
            ..Default::default()
        });
        h1.add_run("Chapter 1");
        doc.body.add_paragraph(h1);

        // H2 under H1
        let mut h2 = CT_P::new();
        h2.properties = Some(CT_PPr {
            style_id: Some("Heading2".to_string()),
            ..Default::default()
        });
        h2.add_run("Section 1.1");
        doc.body.add_paragraph(h2);

        // Another H1
        let mut h1b = CT_P::new();
        h1b.properties = Some(CT_PPr {
            style_id: Some("Heading1".to_string()),
            ..Default::default()
        });
        h1b.add_run("Chapter 2");
        doc.body.add_paragraph(h1b);

        let input = LayoutInput {
            document: doc,
            styles: CT_Styles::new_default(),
            numbering: None,
            headers: HashMap::new(),
            footers: HashMap::new(),
            images: HashMap::new(),
            core_properties: None,
            hyperlink_urls: HashMap::new(),
            footnotes: None,
            endnotes: None,
            theme: None,
            fonts: Vec::new(),
        };

        let result = Engine::new().layout(&input);
        if let Ok(result) = result {
            assert_eq!(result.outlines.len(), 3);
            assert_eq!(result.outlines[0].level, 1);
            assert_eq!(result.outlines[0].title, "Chapter 1");
            assert_eq!(result.outlines[1].level, 2);
            assert_eq!(result.outlines[1].title, "Section 1.1");
            assert_eq!(result.outlines[2].level, 1);
            assert_eq!(result.outlines[2].title, "Chapter 2");
        }
    }

    #[test]
    fn sect_pr_geometry_conversion() {
        let sect = CT_SectPr::default_letter();
        let geom = sect_pr_to_geometry(&sect);
        assert!((geom.page_width - 612.0).abs() < 0.01);
        assert!((geom.page_height - 792.0).abs() < 0.01);
        assert!((geom.margin_top - 72.0).abs() < 0.01);
        assert!((geom.content_width() - 468.0).abs() < 0.01);
    }

    #[test]
    fn sect_pr_a4_geometry() {
        let sect = CT_SectPr::default_a4();
        let geom = sect_pr_to_geometry(&sect);
        // A4: 210mm = 595.3pt, 297mm = 841.9pt
        assert!((geom.page_width - 595.3).abs() < 0.5);
        assert!((geom.page_height - 841.9).abs() < 0.5);
    }
}