docxide-pdf 0.16.3

Library and CLI for converting DOCX files to PDF, matching Microsoft Word's output as closely as possible
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
use std::collections::HashMap;
use std::sync::LazyLock;

use crate::fonts::{FontEntry, font_key_buf};

static EMPTY_INLINE_IMAGE_MAP: LazyLock<HashMap<usize, String>> =
    LazyLock::new(HashMap::new);
static EMPTY_EFFECT_MAP: LazyLock<HashMap<usize, super::images::EffectXObjs>> =
    LazyLock::new(HashMap::new);
use crate::model::{
    Alignment, Block, CellMargins, HorizontalPosition, Table, TextDirection, VMerge,
    VerticalPosition, WrapType,
};

use super::RenderContext;
use super::header_footer::substitute_hf_runs;
use super::layout::{TextLine, build_paragraph_lines, build_tabbed_line, is_text_empty, tallest_run_metrics};
use super::resolve_line_h;

pub(super) fn cell_span_width(col_widths: &[f32], grid_col: usize, span: usize) -> f32 {
    // Clamp the start too: malformed tables (missing tblGrid, gridSpan
    // overrun) can push grid_col past the grid — yield 0 instead of panicking.
    let start = grid_col.min(col_widths.len());
    col_widths[start..col_widths.len().min(grid_col + span)]
        .iter()
        .sum()
}

/// Scale column widths so the table occupies its `w:tblW type="pct"` share
/// of the available content width. tcW pct values are mis-read as twips at
/// parse time, but their proportions survive — only the total needs fixing.
/// Only applies to inferred grids: when a real tblGrid exists, Word renders
/// its widths as-is even when the pct preferred width disagrees (observed
/// with pct values of 100.4–115% alongside grids matching the content width).
pub(super) fn apply_pct_width(table: &Table, widths: &mut [f32], available_w: f32) {
    if !table.grid_inferred {
        return;
    }
    let Some(pct) = table.width_pct else { return };
    // Word caps a table's width at the text column width.
    let target = available_w * pct.min(1.0);
    let total: f32 = widths.iter().sum();
    if total > 0.0 && target > 0.0 {
        let scale = target / total;
        for w in widths {
            *w *= scale;
        }
    }
}

pub(super) fn cell_x_offset(col_widths: &[f32], table_left: f32, grid_col: usize) -> f32 {
    table_left
        + col_widths[..grid_col.min(col_widths.len())]
            .iter()
            .sum::<f32>()
}

/// Height of a paragraph's text content, matching the layout computation in
/// `compute_row_layouts`. Empty paragraphs (no lines) still occupy one line
/// height unless they carry an explicit `content_height` (e.g. from an image).
pub(super) fn para_block_height(p: &CellParagraphLayout) -> f32 {
    if p.lines.is_empty() {
        if p.paragraph_mark_vanish {
            0.0
        } else if p.content_height > 0.0 {
            p.content_height
        } else {
            p.line_h
        }
    } else {
        p.lines.len() as f32 * p.line_h
    }
}

/// Auto-fit column widths so that the longest non-breakable word in each column
/// fits within the cell (including padding). Columns that need more space grow;
/// other columns shrink proportionally. Total width is preserved.
/// When `available_width` is provided and the table exceeds it, all columns
/// are scaled down proportionally to fit (matching Word's behavior).
/// For nested auto-fit tables (`available_width` is Some and not fixed layout),
/// Word shrinks columns to content-based minimum widths rather than using the
/// gridCol preferred widths.
/// Per-column natural (unwrapped, single-line) content width including cell
/// horizontal padding. This is the "max" width input to Word's AutoFit.
fn natural_widths(table: &Table, fonts: &HashMap<String, FontEntry>, cm: &crate::model::CellMargins) -> Vec<f32> {
    let ncols = table.col_widths.len();
    let mut natural = vec![0.0f32; ncols];
    for row in &table.rows {
        let mut grid_col = 0usize;
        for cell in &row.cells {
            let span = cell.grid_span.max(1) as usize;
            if grid_col >= ncols || span > 1 {
                grid_col += span;
                continue;
            }
            let ecm = cell.cell_margins.as_ref().unwrap_or(cm);
            let h_pad = ecm.left + ecm.right;
            let mut key_buf = String::new();
            for para in cell.all_paragraphs() {
                let mut para_w = 0.0f32;
                for run in &para.runs {
                    let key = font_key_buf(run, &mut key_buf);
                    let Some(entry) = fonts.get(key) else { continue };
                    let fs = run.font_size;
                    let text = if run.caps {
                        std::borrow::Cow::Owned(run.text.to_uppercase())
                    } else {
                        std::borrow::Cow::Borrowed(&run.text)
                    };
                    if run.small_caps {
                        para_w += super::layout::smallcaps_segments(&text, fs).iter().map(|(seg, seg_fs)| {
                            let kern = run.kern_threshold.is_some_and(|t| *seg_fs >= t);
                            entry.word_width(seg, *seg_fs, kern)
                        }).sum::<f32>();
                    } else {
                        let kern = run.kern_threshold.is_some_and(|t| fs >= t);
                        para_w += entry.word_width(&text, fs, kern);
                    }
                }
                natural[grid_col] = natural[grid_col].max(para_w + h_pad);
            }
            grid_col += span;
        }
    }
    natural
}

/// Raise each column's natural width to fit any directly nested table at its
/// own content-fitted width (plus the host cell's h-padding). The flattened
/// paragraph widths from `natural_widths` can't see the nested grid: three
/// side-by-side nested columns need their *sum*, not the widest paragraph.
fn raise_natural_for_nested_tables(
    table: &Table,
    fonts: &HashMap<String, FontEntry>,
    cm: &CellMargins,
    natural: &mut [f32],
) {
    let ncols = natural.len();
    for row in &table.rows {
        let mut grid_col = 0usize;
        for cell in &row.cells {
            let span = cell.grid_span.max(1) as usize;
            if grid_col >= ncols || span > 1 {
                grid_col += span;
                continue;
            }
            let ecm = cell.cell_margins.as_ref().unwrap_or(cm);
            let h_pad = ecm.left + ecm.right;
            for block in &cell.content {
                if let Block::Table(nt) = block {
                    let ncm = &nt.cell_margins;
                    let mut nat = natural_widths(nt, fonts, ncm);
                    raise_natural_for_nested_tables(nt, fonts, ncm, &mut nat);
                    let min_cell = ncm.left + ncm.right;
                    let w: f32 = nat.iter().map(|&x| x.max(min_cell)).sum();
                    natural[grid_col] = natural[grid_col].max(w + h_pad);
                }
            }
            grid_col += span;
        }
    }
}

/// Distribute `avail` across columns proportionally to their natural ("max")
/// width, floored at each column's minimum width. Columns that would fall
/// below their minimum are pinned and the remaining width is re-shared among
/// the rest (Word's AutoFit-to-Window behavior). If the minimums alone exceed
/// `avail`, everything is scaled down to fit.
fn distribute_autofit(minw: &[f32], maxw: &[f32], avail: f32) -> Vec<f32> {
    let n = minw.len();
    let mut widths = vec![0.0f32; n];
    let mut pinned = vec![false; n];
    loop {
        let rem_avail: f32 = avail - (0..n).filter(|&i| pinned[i]).map(|i| widths[i]).sum::<f32>();
        let active_max: f32 = (0..n).filter(|&i| !pinned[i]).map(|i| maxw[i]).sum();
        if active_max <= 0.0 {
            break;
        }
        let mut newly_pinned = false;
        for i in 0..n {
            if pinned[i] {
                continue;
            }
            let w = rem_avail * maxw[i] / active_max;
            if w < minw[i] {
                widths[i] = minw[i];
                pinned[i] = true;
                newly_pinned = true;
            }
        }
        if !newly_pinned {
            for i in 0..n {
                if !pinned[i] {
                    widths[i] = rem_avail * maxw[i] / active_max;
                }
            }
            break;
        }
    }
    let total: f32 = widths.iter().sum();
    if total > avail && total > 0.0 {
        let scale = avail / total;
        for w in &mut widths {
            *w *= scale;
        }
    }
    widths
}

/// `fill_width`, when `Some`, is the content width a top-level AutoFit-to-Window
/// table should fill. It is kept separate from `available_width` (which drives
/// the nested-table shrink path) so passing a fill target does not accidentally
/// push a top-level table onto the shrink path.
pub(super) fn auto_fit_columns(table: &Table, fonts: &HashMap<String, FontEntry>, available_width: Option<f32>, fill_width: Option<f32>) -> Vec<f32> {
    let ncols = table.col_widths.len();
    if ncols == 0 {
        return table.col_widths.clone();
    }

    let cm = &table.cell_margins;
    let mut min_widths = vec![0.0f32; ncols];

    for row in &table.rows {
        let mut grid_col = 0usize;
        for cell in &row.cells {
            let span = cell.grid_span.max(1) as usize;
            if grid_col >= ncols || span > 1 {
                grid_col += span;
                continue;
            }
            if cell.text_direction != TextDirection::LrTb {
                grid_col += span;
                continue;
            }
            let ecm = cell.cell_margins.as_ref().unwrap_or(cm);
            let h_pad = ecm.left + ecm.right;
            let mut key_buf = String::new();
            for para in cell.all_paragraphs() {
                for run in &para.runs {
                    let key = font_key_buf(run, &mut key_buf);
                    let Some(entry) = fonts.get(key) else {
                        continue;
                    };
                    let text = if run.caps {
                        std::borrow::Cow::Owned(run.text.to_uppercase())
                    } else {
                        std::borrow::Cow::Borrowed(&run.text)
                    };
                    let fs = run.font_size;
                    for word in text.split_whitespace() {
                        let ww = if run.small_caps {
                            super::layout::smallcaps_segments(word, fs).iter().map(|(seg, seg_fs)| {
                                let kern = run.kern_threshold.is_some_and(|t| *seg_fs >= t);
                                entry.word_width(seg, *seg_fs, kern)
                            }).sum::<f32>() + h_pad
                        } else {
                            let kern = run.kern_threshold.is_some_and(|t| fs >= t);
                            entry.word_width(word, fs, kern) + h_pad
                        };
                        min_widths[grid_col] = min_widths[grid_col].max(ww);
                    }
                }
            }
            grid_col += span;
        }
    }

    // Word's AutoFit (tblLayout=autofit, the default) ignores the stored
    // gridCol widths for a `tblW type="auto"` table and re-derives column
    // widths from cell *content*, filling the available width (AutoFit to
    // Window). OOXML §17.18.87: "uses the contents of each cell to determine
    // final column widths."
    //
    // We only apply this to a uniform-grid `type="auto"` table whose cells
    // directly hold a nested table. A Word-saved autofit table stores
    // content-derived (unequal) gridCol widths, so honoring those reproduces
    // Word — recomputing from our own font metrics would only drift. The narrow
    // case where the stored grid is provably meaningless is an equal-column grid
    // wrapping a nested table (case51's 4680/4680 outer tables): the nested
    // table establishes a hard content width that the equal split ignores, so
    // Word sizes purely to content. Gating on a directly-nested table keeps
    // ordinary text tables (which legitimately keep ~equal columns) on the
    // gridCol path and avoids the corpus-wide redistribution regressions.
    let grid_uniform = ncols >= 2
        && table.col_widths.iter().all(|&w| w > 0.0)
        && {
            let first = table.col_widths[0];
            table.col_widths.iter().all(|&w| (w - first).abs() <= first * 0.02 + 0.5)
        };
    let has_nested_table = table.rows.iter().any(|r| {
        r.cells
            .iter()
            .any(|c| c.content.iter().any(|b| matches!(b, Block::Table(_))))
    });
    if table.auto_width && !table.fixed_layout && grid_uniform && has_nested_table {
        if let Some(avail) = fill_width.filter(|a| *a > 0.0) {
            let mut natural = natural_widths(table, fonts, cm);
            raise_natural_for_nested_tables(table, fonts, cm, &mut natural);
            let min_cell = cm.left + cm.right;
            let maxw: Vec<f32> = (0..ncols)
                .map(|i| natural[i].max(min_widths[i]).max(min_cell))
                .collect();
            // AutoFit to Contents: when every column fits at max-content
            // width, Word leaves the table narrower than the window rather
            // than stretching it to fill.
            if maxw.iter().sum::<f32>() <= avail {
                return maxw;
            }
            let minw: Vec<f32> = (0..ncols).map(|i| min_widths[i].max(min_cell)).collect();
            return distribute_autofit(&minw, &maxw, avail);
        }
    }

    // For nested auto-fit tables, Word shrinks columns to content-based widths
    // rather than preserving the gridCol total. Each column is sized based on
    // a blend of the minimum width (longest word) and the natural width
    // (longest single-line paragraph), capped by the gridCol preferred width.
    if available_width.is_some() && !table.fixed_layout {
        let natural_widths = natural_widths(table, fonts, cm);
        // Word's auto-fit for nested tables produces column widths slightly
        // below the full natural paragraph width. Scale down by 0.9 to
        // approximate Word's sizing, ensuring text wraps where Word wraps it.
        let min_cell = cm.left + cm.right;
        let avail = available_width.unwrap_or(0.0);
        let preferred_total: f32 = table.col_widths.iter().sum();
        // When the nested table has an explicit tblInd and the gridCol
        // preferred widths fit inside the parent cell, Word uses those
        // preferred widths rather than shrinking to content. An explicit
        // tblInd signals the author deliberately sized and positioned the
        // nested table, so its column hints should be honored.
        let mut widths: Vec<f32> = if table.table_indent_explicit
            && preferred_total > 0.0
            && preferred_total <= avail
        {
            (0..ncols)
                .map(|i| {
                    let pref = table.col_widths.get(i).copied().unwrap_or(0.0);
                    let mw = min_widths[i].max(min_cell);
                    pref.max(mw)
                })
                .collect()
        } else {
            // At full natural width the table fits the parent cell → Word
            // keeps the content-fitted widths (AutoFit to Contents), ignoring
            // the stored gridCol hints (§17.18.87 derives purely from cell
            // content). Only when it overflows does Word squeeze below
            // natural width; the 0.9 factor approximates that squeeze.
            let full: Vec<f32> = (0..ncols)
                .map(|i| natural_widths[i].max(min_widths[i].max(min_cell)))
                .collect();
            if full.iter().sum::<f32>() <= avail {
                full
            } else {
                (0..ncols)
                    .map(|i| {
                        let mw = min_widths[i].max(min_cell);
                        let nw = natural_widths[i].max(mw);
                        let fitted = (nw * 0.9).max(mw);
                        fitted.min(table.col_widths.get(i).copied().unwrap_or(f32::MAX))
                    })
                    .collect()
            }
        };
        let total: f32 = widths.iter().sum();
        if total > avail && avail > 0.0 {
            let scale = avail / total;
            for w in &mut widths {
                *w *= scale;
            }
        }
        return widths;
    }

    // Per OOXML §17.18.87: the fixed-width base (used by auto-fit too)
    // sets each grid column to the maximum preferred width (tcW) from
    // all cells at that column, then scales proportionally if the total
    // exceeds the table width.
    let total: f32 = table.col_widths.iter().sum();
    let mut preferred = table.col_widths.clone();
    for row in &table.rows {
        let mut grid_col = 0usize;
        for cell in &row.cells {
            let span = cell.grid_span.max(1) as usize;
            if grid_col >= ncols {
                break;
            }
            if span == 1 {
                preferred[grid_col] = preferred[grid_col].max(cell.width);
            } else {
                // Distribute multi-span cell width proportionally across
                // the spanned grid columns.
                let grid_sum: f32 = table.col_widths[grid_col..ncols.min(grid_col + span)]
                    .iter()
                    .sum();
                if grid_sum > 0.0 && cell.width > grid_sum {
                    for g in grid_col..ncols.min(grid_col + span) {
                        let share = cell.width * (table.col_widths[g] / grid_sum);
                        preferred[g] = preferred[g].max(share);
                    }
                }
            }
            grid_col += span;
        }
    }
    let pref_total: f32 = preferred.iter().sum();
    let mut widths = if pref_total > total && total > 0.0 {
        let scale = total / pref_total;
        preferred.iter().map(|&w| w * scale).collect::<Vec<_>>()
    } else {
        preferred
    };

    // Apply content minimums: ensure each column fits its longest word.
    // If any column needed boosting, shrink others proportionally.
    let mut extra_needed: f32 = 0.0;
    let mut shrinkable: f32 = 0.0;
    for i in 0..ncols {
        if min_widths[i] > widths[i] {
            extra_needed += min_widths[i] - widths[i];
            widths[i] = min_widths[i];
        } else {
            shrinkable += widths[i] - min_widths[i];
        }
    }
    if extra_needed > 0.0 && shrinkable > 0.0 {
        let factor = extra_needed.min(shrinkable) / shrinkable;
        for i in 0..ncols {
            if widths[i] > min_widths[i] {
                let available = widths[i] - min_widths[i];
                widths[i] -= available * factor;
            }
        }
        let new_total: f32 = widths.iter().sum();
        if (new_total - total).abs() > 0.01 {
            let scale = total / new_total;
            for w in &mut widths {
                *w *= scale;
            }
        }
    }

    if let Some(avail) = available_width {
        let final_total: f32 = widths.iter().sum();
        if final_total > avail && avail > 0.0 {
            let scale = avail / final_total;
            for w in &mut widths {
                *w *= scale;
            }
        }
    }

    widths
}

pub(super) struct CellFloatingImageLayout {
    pub(super) pdf_name: String,
    pub(super) display_width: f32,
    pub(super) display_height: f32,
    pub(super) h_offset: f32,
    pub(super) v_offset: f32,
    /// In-plane rotation in degrees (OOXML clockwise). Cell-anchored floats must
    /// carry this just like body floats, else e.g. a 90°-rotated vertical label
    /// renders horizontally.
    pub(super) rotation_deg: f32,
    #[allow(dead_code)]
    pub(super) behind_doc: bool,
}

pub(super) struct CellParagraphLayout {
    pub(super) lines: Vec<TextLine>,
    pub(super) line_h: f32,
    pub(super) font_size: f32,
    #[allow(dead_code)]
    pub(super) ascender_ratio: f32,
    pub(super) descender_ratio: f32,
    pub(super) font_substituted: bool,
    pub(super) alignment: Alignment,
    pub(super) space_before: f32,
    pub(super) indent_left: f32,
    #[allow(dead_code)]
    pub(super) indent_right: f32,
    pub(super) indent_hanging: f32,
    pub(super) indent_first_line: f32,
    /// Extra left indent from wrapSquare/Tight floating images in this paragraph.
    /// Text lines are laid out narrower and rendered further right to avoid the image.
    pub(super) float_indent_left: f32,
    pub(super) list_label: String,
    pub(super) list_label_font: Option<String>,
    pub(super) label_color: Option<[u8; 3]>,
    pub(super) first_run_font_key: String,
    pub(super) image_name: Option<String>,
    pub(super) image_width: f32,
    pub(super) image_height: f32,
    pub(super) image_stroke_color: Option<[u8; 3]>,
    pub(super) image_stroke_width: f32,
    pub(super) image_shadow: Option<crate::model::ImageShadow>,
    pub(super) image_shadow_xobj: Option<String>,
    pub(super) image_glow: Option<crate::model::ImageGlow>,
    pub(super) image_glow_xobj: Option<String>,
    pub(super) image_clip: Option<crate::model::ShapeGeometry>,
    pub(super) content_height: f32,
    pub(super) paragraph_mark_vanish: bool,
    pub(super) floating_images: Vec<CellFloatingImageLayout>,
    pub(super) space_after: f32,
    pub(super) has_textboxes: bool,
    pub(super) has_connectors: bool,
}

pub(super) enum CellContentItem {
    Paragraph(CellParagraphLayout),
    NestedTable { height: f32 },
}

pub(super) struct CellLayout {
    pub(super) items: Vec<CellContentItem>,
    #[allow(dead_code)]
    pub(super) total_height: f32,
    pub(super) text_direction: TextDirection,
}

pub(super) struct RowLayout {
    pub(super) height: f32,
    pub(super) cells: Vec<CellLayout>,
}

/// When provided, field codes in header/footer table runs are substituted with
/// their resolved values before layout.
pub(super) struct HfSubstitution<'a> {
    pub(super) page_num: usize,
    pub(super) total_pages: usize,
    pub(super) styleref_values: &'a HashMap<String, String>,
    pub(super) page_num_format: Option<&'a str>,
}

pub(super) fn compute_row_layouts(
    table: &Table,
    col_widths: &[f32],
    ctx: &RenderContext,
    hf_sub: Option<&HfSubstitution>,
) -> Vec<RowLayout> {
    let cm = &table.cell_margins;
    table
        .rows
        .iter()
        .map(|row| {
            let mut max_h: f32 = 0.0;
            let mut grid_col = 0usize;
            let cells: Vec<CellLayout> = row
                .cells
                .iter()
                .map(|cell| {
                    let span = cell.grid_span.max(1) as usize;
                    let span_w = cell_span_width(col_widths, grid_col, span);
                    // For auto-fit tables the resolved grid width is what the
                    // renderer draws borders and content at, so the layout must
                    // use the same width — a larger tcW preference otherwise wraps
                    // text past the drawn cell border (#115). Fixed-layout tables
                    // keep honoring the cell's preferred width (their gridCol can
                    // be narrower than Word's effective column).
                    let col_w = if table.fixed_layout {
                        span_w.max(cell.width)
                    } else {
                        span_w
                    };
                    grid_col += span;

                    if cell.v_merge == VMerge::Continue {
                        return CellLayout {
                            items: vec![],
                            total_height: 14.4,
                            text_direction: TextDirection::LrTb,
                        };
                    }

                    let ecm = cell.cell_margins.as_ref().unwrap_or(cm);
                    let is_rotated = cell.text_direction != TextDirection::LrTb;
                    let cell_text_w = if is_rotated {
                        10000.0
                    } else {
                        (col_w - ecm.left - ecm.right).max(0.0)
                    };
                    let mut total_h: f32 = ecm.top + ecm.bottom;
                    let mut max_rotated_line_w: f32 = 0.0;
                    let mut items: Vec<CellContentItem> = Vec::new();
                    let mut prev_space_after = 0.0f32;
                    let mut para_idx = 0usize;
                    let mut prev_was_nested_table = false;

                    let block_count = cell.content.len();
                    for (block_idx, block) in cell.content.iter().enumerate() {
                        match block {
                            Block::Paragraph(para) => {
                                let substituted;
                                let runs = if let Some(sub) = hf_sub {
                                    substituted = substitute_hf_runs(
                                        &para.runs,
                                        sub.page_num,
                                        sub.total_pages,
                                        sub.styleref_values,
                                        sub.page_num_format,
                                    );
                                    &substituted
                                } else {
                                    &para.runs
                                };
                                // Size the cell line from the tallest run, not the
                                // first — a small leading run (e.g. padding spaces)
                                // must not pull the baseline up. Math runs are
                                // clamped inside tallest_run_metrics so a header
                                // cell leading with math doesn't balloon the row.
                                // Cell metrics come from the first run carrying
                                // real text — a leading padding-spaces run must
                                // not set the baseline (Word sizes the line from
                                // the content run; observed in header cells like
                                // "                g" where g is larger).
                                let metric_run = runs
                                    .iter()
                                    .find(|r| {
                                        r.is_tab
                                            || r.text.is_empty()
                                            || !r.text.trim().is_empty()
                                    })
                                    .or(runs.first());
                                let font_size = metric_run.map_or(12.0, |r| r.font_size);
                                // A math run uses a math font (e.g. Cambria Math)
                                // whose tall ascent/descent must not set the cell
                                // line height (mirrors the is_math clamp in
                                // tallest_run_metrics) — otherwise a header cell
                                // whose metric run is math balloons the row.
                                let mut kb0 = String::new();
                                let metric_font = metric_run
                                    .filter(|r| !r.is_math)
                                    .map(|r| font_key_buf(r, &mut kb0).to_owned())
                                    .and_then(|k| ctx.fonts.get(&k));
                                let tallest_lhr = metric_font.and_then(|e| e.line_h_ratio);
                                let tallest_ar = metric_font.and_then(|e| e.ascender_ratio);
                                let effective_ls =
                                    para.line_spacing.unwrap_or(ctx.doc_line_spacing);
                                let line_h =
                                    resolve_line_h(effective_ls, font_size, tallest_lhr);

                                let space_before = if para_idx > 0 {
                                    f32::max(prev_space_after, para.space_before)
                                } else {
                                    para.space_before
                                };
                                total_h += space_before;

                                let ascender_ratio = tallest_ar.unwrap_or(0.75);
                                // Win-path metrics identity: line_h_ratio −
                                // ascender_ratio = usWinDescent/units. Fallback
                                // 0.2 pairs with the 1.2 default line ratio so
                                // standard fonts get zero trailing leading.
                                let descender_ratio = tallest_lhr
                                    .zip(tallest_ar)
                                    .map(|(lh, ar)| (lh - ar).max(0.0))
                                    .unwrap_or(0.2);
                                let font_substituted =
                                    metric_font.is_some_and(|e| e.is_substituted);

                                // Compute extra left indent from left-aligned
                                // wrapSquare/Tight floating images so text wraps
                                // to the right of the image within the cell.
                                let float_indent_left: f32 = para
                                    .floating_images
                                    .iter()
                                    .filter(|fi| {
                                        matches!(
                                            fi.wrap_type,
                                            WrapType::Square | WrapType::Tight | WrapType::Through
                                        ) && matches!(
                                            fi.h_position,
                                            HorizontalPosition::AlignLeft
                                                | HorizontalPosition::Offset(_)
                                        )
                                    })
                                    .map(|fi| {
                                        let left_edge = match fi.h_position {
                                            HorizontalPosition::Offset(o) => o,
                                            _ => 0.0,
                                        };
                                        left_edge + fi.image.display_width + fi.dist_right
                                    })
                                    .fold(0.0f32, f32::max);

                                // An inline-image paragraph whose only other run
                                // is a trailing line break (Word's logo-in-cell
                                // idiom) is NOT text-empty, but its row height must
                                // come from the image's content_height, not a stray
                                // text line — otherwise the cell collapses and a
                                // tall header logo fails to push the body down.
                                let image_only = para.content_height > 0.0
                                    && runs.iter().all(|r| r.text.is_empty() && !r.is_tab);
                                let lines = if !is_text_empty(runs) && !image_only {
                                    let para_text_w = (cell_text_w
                                        - para.indent_left
                                        - para.indent_right
                                        - float_indent_left)
                                        .max(0.0);
                                    // Match the rendering's first_line_hanging: when a
                                    // list label is present, the label is drawn separately
                                    // and the text starts at indent_left, so the first
                                    // line has no extra hanging width.
                                    let hanging = if !para.list_label.is_empty() {
                                        if para.indent_first_line > 0.0
                                            && para.indent_hanging == 0.0
                                        {
                                            -para.indent_first_line
                                        } else {
                                            0.0
                                        }
                                    } else {
                                        para.indent_hanging
                                    };
                                    let has_tabs = runs.iter().any(|r| r.is_tab);
                                    let lines = if has_tabs {
                                        build_tabbed_line(
                                            runs,
                                            ctx.fonts,
                                            &para.tab_stops,
                                            para.indent_left,
                                            para_text_w,
                                            para.indent_right,
                                            hanging,
                                            &EMPTY_INLINE_IMAGE_MAP,
                                            &EMPTY_EFFECT_MAP,
                                            ctx.default_tab_stop,
                                            &[],
                                        )
                                    } else {
                                        build_paragraph_lines(
                                            runs,
                                            ctx.fonts,
                                            para_text_w,
                                            hanging,
                                            &EMPTY_INLINE_IMAGE_MAP,
                                            &EMPTY_EFFECT_MAP,
                                            None,
                                            None,
                                            None,
                                            para.auto_space_de || para.auto_space_dn,
                                        )
                                    };
                                    if is_rotated {
                                        for line in &lines {
                                            max_rotated_line_w =
                                                max_rotated_line_w.max(line.total_width);
                                        }
                                    }
                                    total_h += lines.len() as f32 * line_h;
                                    lines
                                } else {
                                    if para.paragraph_mark_vanish {
                                        // vanished paragraph mark: zero height
                                    } else if cell.hide_mark
                                        && block_idx == block_count - 1
                                    {
                                        // hideMark: last empty paragraph in cell
                                        // contributes no height
                                    } else if prev_was_nested_table
                                        && block_idx == block_count - 1
                                        && para.content_height == 0.0
                                    {
                                        // End-of-cell mark directly after a nested
                                        // table: Word hides it. The mark glyph
                                        // height is covered by the +0.5pt row
                                        // addition; space_after is suppressed in
                                        // the trailing-space block below.
                                    } else if para.content_height > 0.0 {
                                        // Image paragraph: the image is line 1; each
                                        // trailing w:br adds a further blank line
                                        // (matches the non-table header height path).
                                        let br_count = runs
                                            .iter()
                                            .filter(|r| r.is_line_break)
                                            .count();
                                        total_h += para.content_height
                                            + br_count as f32 * line_h;
                                    } else {
                                        total_h += line_h;
                                    }
                                    vec![]
                                };

                                let first_run_font_key = runs
                                    .first()
                                    .map(|r| {
                                        let mut kb2 = String::new();
                                        font_key_buf(r, &mut kb2).to_owned()
                                    })
                                    .unwrap_or_default();

                                let image_name = para.image.as_ref().and_then(|img| {
                                    let key = std::sync::Arc::as_ptr(&img.data) as usize;
                                    ctx.table_cell_image_names.get(&key).cloned()
                                });
                                let (image_width, image_height, img_stroke_color, img_stroke_width, img_shadow) = para
                                    .image
                                    .as_ref()
                                    .map(|img| (img.display_width, img.display_height, img.stroke_color, img.stroke_width, img.shadow.clone()))
                                    .unwrap_or((0.0, 0.0, None, 0.0, None));
                                let table_fx = para.image.as_ref().and_then(|img| {
                                    let key = std::sync::Arc::as_ptr(&img.data) as usize;
                                    ctx.effect_table_names.get(&key)
                                });
                                let img_shadow_xobj = table_fx.and_then(|fx| fx.shadow.clone());
                                let img_glow = para.image.as_ref().and_then(|img| img.glow.clone());
                                let img_glow_xobj = table_fx.and_then(|fx| fx.glow.clone());

                                let cell_floats: Vec<CellFloatingImageLayout> = para
                                    .floating_images
                                    .iter()
                                    .filter_map(|fi| {
                                        let key =
                                            std::sync::Arc::as_ptr(&fi.image.data) as usize;
                                        let pdf_name =
                                            ctx.table_cell_image_names.get(&key)?.clone();
                                        let h_offset = match fi.h_position {
                                            HorizontalPosition::Offset(o) => o,
                                            HorizontalPosition::AlignCenter => {
                                                (col_w - fi.image.display_width) / 2.0
                                            }
                                            HorizontalPosition::AlignRight => {
                                                col_w - fi.image.display_width
                                            }
                                            HorizontalPosition::AlignLeft => 0.0,
                                        };
                                        let v_offset = match fi.v_position {
                                            VerticalPosition::Offset(o) => o,
                                            _ => 0.0,
                                        };
                                        Some(CellFloatingImageLayout {
                                            pdf_name,
                                            display_width: fi.image.display_width,
                                            display_height: fi.image.display_height,
                                            h_offset,
                                            v_offset,
                                            rotation_deg: fi.rotation_deg,
                                            behind_doc: fi.behind_doc,
                                        })
                                    })
                                    .collect();

                                items.push(CellContentItem::Paragraph(CellParagraphLayout {
                                    lines,
                                    line_h,
                                    font_size,
                                    ascender_ratio,
                                    descender_ratio,
                                    font_substituted,
                                    alignment: para.alignment,
                                    space_before,
                                    indent_left: para.indent_left,
                                    indent_right: para.indent_right,
                                    indent_hanging: para.indent_hanging,
                                    indent_first_line: para.indent_first_line,
                                    float_indent_left,
                                    list_label: para.list_label.clone(),
                                    list_label_font: para.list_label_font.clone(),
                                    label_color: para.runs.first().and_then(|r| r.color),
                                    first_run_font_key,
                                    image_name,
                                    image_width,
                                    image_height,
                                    image_stroke_color: img_stroke_color,
                                    image_stroke_width: img_stroke_width,
                                    image_shadow: img_shadow,
                                    image_shadow_xobj: img_shadow_xobj,
                                    image_glow: img_glow,
                                    image_glow_xobj: img_glow_xobj,
                                    image_clip: para.image.as_ref().and_then(|img| img.clip_geometry.clone()),
                                    content_height: para.content_height,
                                    paragraph_mark_vanish: para.paragraph_mark_vanish,
                                    floating_images: cell_floats,
                                    space_after: para.space_after,
                                    has_textboxes: !para.textboxes.is_empty(),
                                    has_connectors: !para.connectors.is_empty(),
                                }));

                                prev_space_after = para.space_after;
                                prev_was_nested_table = false;
                                para_idx += 1;
                            }
                            Block::Table(nested_table) => {
                                let nested_cw = auto_fit_columns(nested_table, ctx.fonts, Some(cell_text_w), None);
                                let nested_layouts =
                                    compute_row_layouts(nested_table, &nested_cw, ctx, hf_sub);
                                let nested_h: f32 =
                                    nested_layouts.iter().map(|rl| rl.height).sum();
                                total_h += nested_h;
                                items.push(CellContentItem::NestedTable { height: nested_h });
                                prev_space_after = 0.0;
                                prev_was_nested_table = true;
                                para_idx += 1;
                            }
                        }
                    }

                    // When a cell ends with a nested table plus the mandatory
                    // end-of-cell paragraph mark (empty, no text), Word does
                    // not count the trailing paragraph's space_after toward
                    // the row height — the mark glyph height and line_h are
                    // already suppressed above via prev_was_nested_table.
                    let trailing_mark_after_table = items.len() >= 2
                        && matches!(items.get(items.len() - 2), Some(CellContentItem::NestedTable { .. }))
                        && matches!(items.last(), Some(CellContentItem::Paragraph(p)) if p.lines.is_empty() && p.image_name.is_none() && p.floating_images.is_empty());
                    if !trailing_mark_after_table {
                        total_h += prev_space_after;
                    }
                    if is_rotated {
                        total_h = ecm.top + ecm.bottom + max_rotated_line_w;
                    }
                    if cell.v_merge != VMerge::Restart {
                        max_h = max_h.max(total_h);
                    }
                    CellLayout {
                        items,
                        total_height: total_h,
                        text_direction: cell.text_direction,
                    }
                })
                .collect();

            // Word's row height includes the end-of-cell paragraph mark glyph,
            // adding roughly 0.5pt beyond the content metrics.
            let content_h = max_h + 0.5;
            let height = match (row.height, row.height_exact) {
                (Some(h), true) => h,
                (Some(h), false) => content_h.max(h),
                _ => content_h,
            };


            RowLayout { height, cells }
        })
        .collect()
}

/// Pre-compute how much extra height each vMerge Restart cell spans beyond its own row.
/// Returns a map from (row_idx, grid_col) to the sum of Continue row heights below.
pub(super) fn compute_merge_spans(table: &Table, row_layouts: &[RowLayout]) -> HashMap<(usize, usize), f32> {
    // Build a grid index: vmerge_grid[row][grid_col] = VMerge value
    let max_cols = table.rows.iter().map(|r| {
        r.cells.iter().map(|c| c.grid_span.max(1) as usize).sum::<usize>()
    }).max().unwrap_or(0);
    let mut vmerge_grid: Vec<Vec<VMerge>> = Vec::with_capacity(table.rows.len());
    for row in &table.rows {
        let mut row_vmerge = vec![VMerge::None; max_cols];
        let mut col = 0usize;
        for cell in &row.cells {
            if col < max_cols {
                row_vmerge[col] = cell.v_merge;
            }
            col += cell.grid_span.max(1) as usize;
        }
        vmerge_grid.push(row_vmerge);
    }

    let mut spans = HashMap::new();
    for (ri, row) in table.rows.iter().enumerate() {
        let mut grid_col = 0usize;
        for cell in &row.cells {
            let span = cell.grid_span.max(1) as usize;
            if cell.v_merge == VMerge::Restart {
                let mut extra = 0.0f32;
                for next_ri in (ri + 1)..table.rows.len() {
                    if grid_col >= max_cols || vmerge_grid[next_ri][grid_col] != VMerge::Continue {
                        break;
                    }
                    extra += row_layouts[next_ri].height;
                }
                if extra > 0.0 {
                    spans.insert((ri, grid_col), extra);
                }
            }
            grid_col += span;
        }
    }
    spans
}

/// Find how many items (from `start`) fit within `available_h`.
/// Always includes at least one item to guarantee progress.
pub(super) fn find_cell_split(cell: &CellLayout, start: usize, available_h: f32, cm: &CellMargins) -> usize {
    if start >= cell.items.len() {
        return cell.items.len();
    }
    let mut h = cm.top + cm.bottom;
    for pi in start..cell.items.len() {
        let item_h = match &cell.items[pi] {
            CellContentItem::Paragraph(para) => {
                let sb = if pi == start { 0.0 } else { para.space_before };
                sb + para_block_height(para)
            }
            CellContentItem::NestedTable { height } => *height,
        };
        if h + item_h > available_h && pi > start {
            return pi;
        }
        h += item_h;
    }
    cell.items.len()
}

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

    #[test]
    fn test_cell_span_width_single() {
        let widths = vec![100.0, 200.0, 300.0];
        assert_eq!(cell_span_width(&widths, 0, 1), 100.0);
        assert_eq!(cell_span_width(&widths, 1, 1), 200.0);
        assert_eq!(cell_span_width(&widths, 2, 1), 300.0);
    }

    #[test]
    fn test_cell_span_width_multi() {
        let widths = vec![100.0, 200.0, 300.0];
        assert_eq!(cell_span_width(&widths, 0, 2), 300.0);
        assert_eq!(cell_span_width(&widths, 0, 3), 600.0);
        assert_eq!(cell_span_width(&widths, 1, 2), 500.0);
    }

    #[test]
    fn test_cell_span_width_clamps_to_len() {
        let widths = vec![100.0, 200.0];
        // span=5 but only 2 columns from index 0
        assert_eq!(cell_span_width(&widths, 0, 5), 300.0);
    }

    #[test]
    fn test_cell_span_width_start_past_end() {
        // Missing tblGrid (empty widths) or gridSpan overrun must not panic.
        assert_eq!(cell_span_width(&[], 1, 1), 0.0);
        let widths = vec![100.0, 200.0];
        assert_eq!(cell_span_width(&widths, 5, 2), 0.0);
    }

    #[test]
    fn test_cell_x_offset() {
        let widths = vec![100.0, 200.0, 300.0];
        assert_eq!(cell_x_offset(&widths, 50.0, 0), 50.0);
        assert_eq!(cell_x_offset(&widths, 50.0, 1), 150.0);
        assert_eq!(cell_x_offset(&widths, 50.0, 2), 350.0);
        assert_eq!(cell_x_offset(&widths, 50.0, 3), 650.0);
    }
}