f-office-docx 0.1.0

DOCX model and Word's layout rules.
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
//! The rows of a table: their cells, heights and page breaks.

use std::ops::Range;

use f_office_paint::{Item, Rect, Rgb};
use f_office_units::{Edges, Length};

use super::borders::{OutlineEnd, RowTop};
use super::merges::{Carried, Merges, Open, RegionStart, Regions};
use super::shape::{Above, HeaderRoom, PageEdges};
use super::{Shape, Sides, Slot, align, exact_row_margin, least_row_height, row_height, width};
use crate::layout::decisions;
use crate::layout::floating::Square;
use crate::layout::line::height::{REST_PARTS, twips_rest};
use crate::layout::page_items::FillsEntry;
use crate::layout::{CellRests, Layout, MovedTop, RowRests, TwipsRest};
use crate::quirks::Quirks;
use crate::table::{HeightRule, VerticalAlign};

/// The items and the bottom of the content of each cell of a row on this page, and the part
/// of each that goes on on the next page.
/// What [`Layout::contents`] gives for each cell of a row: its entries and its bottom, the
/// lines that go on on the next page, the fills entry before its content for a merged region
/// that it starts, and its rests.
type Contents = (
    Vec<(Range<usize>, Length)>,
    Vec<Option<Carried>>,
    Vec<Option<FillsEntry>>,
    Vec<CellRests>,
);

/// The lowest bottoms of the drawings anchored in a table cell that are placed from their
/// paragraph, which the cell's content reaches down to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum CellFloor {
    /// No such drawing yet: the content alone reaches down.
    Clear,
    /// Only drawings that do not wrap text: the lowest bottom of them.
    Unwrapped(Length),
    /// The lowest bottom of the drawings that wrap text, and that of all of them.
    Wrapped {
        /// The lowest bottom of the drawings that wrap text.
        wrapping: Length,
        /// The lowest bottom of all of them.
        every: Length,
    },
}

impl CellFloor {
    /// The floor with a drawing whose bottom is `bottom`, which wraps text or not.
    pub(in crate::layout) fn lowered(self, bottom: Length, wraps: bool) -> Self {
        match (self, wraps) {
            (Self::Clear, false) => Self::Unwrapped(bottom),
            (Self::Unwrapped(every), false) => Self::Unwrapped(every.max(bottom)),
            (Self::Wrapped { wrapping, every }, false) => Self::Wrapped {
                wrapping,
                every: every.max(bottom),
            },
            (Self::Clear, true) => Self::Wrapped {
                wrapping: bottom,
                every: bottom,
            },
            (Self::Unwrapped(every), true) => Self::Wrapped {
                wrapping: bottom,
                every: every.max(bottom),
            },
            (Self::Wrapped { wrapping, every }, true) => Self::Wrapped {
                wrapping: wrapping.max(bottom),
                every: every.max(bottom),
            },
        }
    }

    /// The bottom that the content reaches down to: that of the drawings that wrap text, or
    /// with `every`, that of all of them.
    pub(super) const fn reach(self, every: bool) -> Option<Length> {
        match self {
            Self::Clear => None,
            Self::Unwrapped(bottom) => {
                if every {
                    Some(bottom)
                } else {
                    None
                }
            }
            Self::Wrapped {
                wrapping,
                every: all,
            } => Some(if every { all } else { wrapping }),
        }
    }
}

/// What the content of a table cell starts afresh, and gives back to the flow that holds the
/// cell when it ends: the floor of its drawings, its place for the line records, the boxes
/// that its text flows beside, the bands that its text keeps below, and whether its lines are
/// carried lines because a cell that holds it has moved on.
struct CellState {
    floor: Option<CellFloor>,
    top: Option<Length>,
    sides: Option<(Length, Length)>,
    place: Option<crate::layout::CellPlace>,
    squares: Vec<Square>,
    bands: Vec<(Length, Length)>,
    carried: bool,
}

impl Layout<'_> {
    /// Lays out a row. A row that does not fit on the page moves to the next page, unless it
    /// is the first thing on the page. The header rows repeat above it there.
    pub(super) fn row(&mut self, shape: &Shape, index: usize, paginate: bool, merges: &mut Merges) {
        let mark = self.row_mark();
        let top = self.y;
        let rest = self.twips_here();
        // Whether the row is the first thing on its page, before its own lines stand there.
        let first = self.page_has_no_line();
        let open = merges.open.clone();
        // A row that ends a merged region whose content goes on on the next page splits, so
        // that its part there holds the rest of the content.
        let carries = merges.ends_carried(shape.slots(index));
        let trial = self.output.start_trial();
        let height = self.row_at(shape, index, top, merges, false);
        // A row that ends the page needs room for the line of its outer edge below it.
        let below = shape.foot_border(index);
        // A row ends above the footnotes of its page, as a line does.
        let end = self.body_end();
        let fits = !paginate
            || (!carries
                && if merges.fits_by_top {
                    top < end
                } else {
                    top + height + below <= end
                });
        self.output.end_trial(trial, fits);
        if fits {
            self.move_to(top + height);
            self.carry_row_twips();
            return;
        }
        // On a target that aligns a merged cell in its part on the page, the trial leaves the
        // content of the regions that the row ended where it stood before the row. Their
        // places are the trial's, which still holds the fills that the row put under them.
        let aligned = std::mem::take(&mut merges.aligned);
        if let Some(aligned) = decisions::page_part_merges(&self.context.quirks, aligned) {
            for (items, shift) in aligned {
                self.shift(items, -shift);
            }
        }
        self.back_to_row_mark(&mark);
        merges.open = open;
        // A region of turned text does not stay open over the page break: its text turns over
        // its part on this page, and its part on the next page holds none.
        merges.cut_turned();
        // From mode 15, `w:cantSplit` does not keep a row whole in a table with `w:tblpPr`.
        // A row that is the first thing on its page splits with `w:cantSplit` too: it is
        // taller than the page.
        let placed = shape.grid.table.props.placement.is_some()
            && self.settings.mode_rules.splits_placed_rows();
        let splits = shape
            .grid
            .table
            .rows
            .get(index)
            .is_some_and(|row| placed || first || !row.cant_split)
            && (first || self.minimum_fits(shape, index, top));
        if splits && self.split_row(shape, index, RowTop { at: top, rest }, merges) {
            return;
        }
        self.back_to_row_mark(&mark);
        if !first {
            self.row_to_next_page(shape, (index, top), merges);
            // A row that is taller than the page splits at the top of the new page, also
            // with `w:cantSplit`.
            if self.page_has_no_line() {
                return self.row(shape, index, paginate, merges);
            }
        }
        let top = self.y;
        let height = self.row_at(shape, index, top, merges, false);
        self.move_to(top + height);
        self.carry_row_twips();
    }

    /// The rests at a row's end, `end`, from the rests `top` at its top above its top border
    /// `border`, its parts entered one by one: an exact height adds the height and the largest
    /// margin that it leaves out to the twips rest, and keeps the top's height rest; a minimum
    /// that sets the height adds the border, the minimum and the largest pair of top and bottom
    /// margins; any other row takes the rests at the bottom of a cell that ends there
    /// (`cell_ends`, laid out as `laid`), also where its top has no rest and its cells started
    /// theirs anew: the twips rest of one, and the largest height rest of those whose content
    /// ends there. `None` where a part is not whole twips, an exact or set height has no rest
    /// at its top, or no such cell's twips rest is known.
    fn row_end_rest(
        &self,
        (top, border): (Option<RowRests>, Length),
        cells: &[(Length, Sides<Length>)],
        (laid, cell_ends): (&[(Range<usize>, Length)], &[CellRests]),
        (rule, end): (Option<(Length, HeightRule)>, Length),
    ) -> Option<RowRests> {
        let rest = |length| twips_rest(&self.device, length);
        let top_rest = top.map(|top| top.twips);
        let fixed = |twips: Option<i64>| {
            Some(RowRests {
                at: end,
                twips: twips?,
                height: top?.height,
            })
        };
        let content = cells.iter().map(|c| c.0).max().unwrap_or(Length::ZERO);
        let pair = cells
            .iter()
            .map(|c| (c.1.top + c.1.bottom, c.1.top, c.1.bottom))
            .max_by_key(|pair| pair.0);
        match rule {
            Some((height, HeightRule::Exact)) => {
                let margin = exact_row_margin(cells, &self.context.quirks);
                fixed([top_rest, rest(height), rest(margin)].into_iter().sum())
            }
            Some((height, HeightRule::AtLeast))
                if pair.is_some_and(|(both, _, _)| height + both >= content) =>
            {
                let (_, over, under) = pair?;
                let parts = [
                    top_rest,
                    rest(border),
                    rest(height),
                    rest(over),
                    rest(under),
                ];
                fixed(parts.into_iter().sum())
            }
            _ => {
                // quirk: LineHeightUnit::Whole4096ths (src/quirks.rs)
                let height = laid
                    .iter()
                    .zip(cell_ends)
                    .filter(|((_, bottom), _)| *bottom == end)
                    .map(|(_, cell)| cell.end_height.unwrap_or(0))
                    .max()
                    .unwrap_or(0);
                cell_ends
                    .iter()
                    .filter_map(|cell| cell.end)
                    .find(|cell| cell.at == end)
                    .map(|cell| RowRests {
                        at: end,
                        twips: cell.rest,
                        height,
                    })
            }
        }
    }

    /// Gives the cells of a row at `top` with the top border `border` the rests at their text
    /// top above their margins, and returns the rests at the row's top and the cells' rests of
    /// the row that holds the table, which [`Self::end_row_twips`] puts back. The rows of a
    /// table carry the cursor's twips rest down from the table's top, and its height rest with
    /// it.
    fn start_row_twips(
        &mut self,
        top: Length,
        border: Length,
    ) -> (Option<RowRests>, Option<RowRests>) {
        // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
        let height = if self.y == top { self.y_rest } else { 0 };
        let top_rests = self
            .y_twips
            .filter(|twips| twips.at == top)
            .map(|twips| RowRests {
                at: top,
                twips: twips.rest,
                height,
            });
        let row = top_rests
            .zip(twips_rest(&self.device, border))
            .map(|(above, own)| RowRests {
                at: top + border,
                twips: above.twips + own,
                height: above.height,
            });
        (top_rests, std::mem::replace(&mut self.table_twips.row, row))
    }

    /// Puts back the cells' rests `outer` of the row that holds the table, and keeps the rests
    /// `end` at the row's end. A row with cell spacing has none: the spacing adds lengths that
    /// the rests do not hold.
    fn end_row_twips(&mut self, outer: Option<RowRests>, end: Option<RowRests>) {
        self.table_twips.row = outer;
        self.table_twips.row_end = end;
    }

    /// Gives the cursor, at the end of the row laid out last, the row's rests there.
    fn carry_row_twips(&mut self) {
        if let Some(end) = self.table_twips.row_end.filter(|end| end.at == self.y) {
            self.set_twips(Some(end.twips));
            self.y_rest = end.height;
        }
    }

    /// How far each cell of a row moves down for its vertical alignment, from its bottom and its
    /// rests laid out at the row's text top `inner`, in a row that ends at `row_end` with the
    /// rests `end`, and the rests that its moved text top takes ([`Self::moved_top`]). A cell
    /// that starts a merged region does not move with its row.
    fn moves(
        &self,
        slots: &[Slot],
        (laid, cells): (&[(Range<usize>, Length)], &[CellRests]),
        (inner, row_end, end): (Length, Length, Option<RowRests>),
    ) -> Vec<(Length, Option<MovedTop>)> {
        slots
            .iter()
            .zip(laid)
            .zip(cells)
            .map(|((slot, &(_, bottom)), cell)| {
                let free = if slot.merged_below {
                    Length::ZERO
                } else {
                    row_end - bottom
                };
                let shift = align(slot.align(), free);
                let moved = self.moved_top(slot, (shift, bottom), cell, (inner, row_end, end));
                (shift, moved)
            })
            .collect()
    }

    /// The rests that the text top of a cell takes where it moves down by `shift` for its
    /// vertical alignment, from its rests (`cell`) and its bottom (`bottom`) before the move,
    /// in a row whose text top is `inner` and whose end, `row_end`, has the rests `end`. The
    /// content keeps the rests that it had and takes those of the move ([`moved_rest`]). A
    /// moved text top of whole twips starts its rest as one length instead, as an unmoved one
    /// does. `None` there, or where a rest is not known.
    fn moved_top(
        &self,
        slot: &Slot,
        (shift, bottom): (Length, Length),
        cell: &CellRests,
        (inner, row_end, end): (Length, Length, Option<RowRests>),
    ) -> Option<MovedTop> {
        if shift == Length::ZERO
            || self.device.in_twip_parts(()).is_none()
            || twips_rest(&self.device, inner + shift + slot.margins.top).is_some()
        {
            return None;
        }
        let dropped = row_end - bottom - shift - shift;
        let end = end?;
        let rest = moved_rest(slot.align(), end.twips + end.height - cell.bottom?, dropped)?;
        Some(MovedTop {
            twips: cell.top,
            rest: cell.top_height + rest,
        })
    }

    /// Ends the page at `top`, above row `index`, and starts the next page with the header
    /// rows and the content that the open regions carry, so that the row starts there.
    pub(super) fn row_to_next_page(
        &mut self,
        shape: &Shape,
        (index, top): (usize, Length),
        merges: &mut Merges,
    ) {
        // The row above, now the last on its page, draws the bottom border of its outer edge
        // below it, as the last row of the table does. The line that it drew there below a
        // cell with no cell below it in this row (`row_borders`) gives way to that line.
        if let Some(above) = index
            .checked_sub(1)
            .filter(|_| shape.grid.spacing().is_none())
        {
            for slot in shape.slots_at(above, PageEdges::default()).iter() {
                if slot.gaps.is_none() && shape.grid.open_below(above, slot) {
                    self.take_back_bottom_line(slot, top);
                }
            }
            let foot = PageEdges {
                foot: true,
                ..PageEdges::default()
            };
            for slot in shape.slots_at(above, foot).iter() {
                self.bottom_line(slot, top);
            }
        }
        // On a target that aligns a merged cell in its part on the page, the content of a
        // region that stays on this page takes its alignment in the region's rows here.
        if let Some(open) = decisions::page_part_merges(&self.context.quirks, &merges.open) {
            for open in open.iter().filter(|open| open.carried.is_none()) {
                let shift = align(open.align, top - open.bottom);
                self.shift(open.items.clone(), self.device.snap(shift));
            }
        }
        self.close_page_part(shape, index, top);
        self.end_turned_regions(shape, merges, top);
        self.next_column();
        self.headers(shape, index);
        // The content that the open regions carry goes on at the top of the row's part on the
        // new page.
        // The row and that content take the same top border, also when the content stands
        // on the page before the row. Below the header rows that repeat there, the row meets
        // the last of them.
        merges.page_start = match self.below_headers(shape, index) {
            Some(above) => Some((index, above)),
            None => (index > 0 && self.page_has_no_line()).then_some((index, Above::Nothing)),
        };
        let base = self.y + Shape::top_part(&shape.slots_at(index, self.page_edges(index, merges)));
        self.place_carried(merges, base);
    }

    /// In a table with cell spacing, closes the part of the table that the page's foot ends at
    /// `top`, below the row before row `index`, with the line that the target draws there
    /// (`TableGrid::page_part_lines`), where it draws one.
    fn close_page_part(&mut self, shape: &Shape, index: usize, top: Length) {
        if let Some(above) = index.checked_sub(1)
            && let Some((_, Some(line))) = shape.grid.page_part_lines(above)
        {
            let slots = shape.slots(above);
            let closing = (None, OutlineEnd::Page(Some(line)));
            self.table_outline(shape, (above, slots), (top, top), closing);
        }
    }

    /// Where row `index` stands: below the header rows that repeat at the top of the page it
    /// moved to; at the top of a page, below no row of its table, when no line stands on the
    /// page yet, or when the row moved to a page where only the content that open regions
    /// carry stands above it; else below the row before it.
    pub(super) fn page_edges(&self, index: usize, merges: &Merges) -> PageEdges {
        let above = match merges.page_start {
            Some((row, above)) if row == index => above,
            _ if index > 0 && self.page_has_no_line() => Above::Nothing,
            _ => Above::Row,
        };
        PageEdges { above, foot: false }
    }

    /// What row `index`, or the part of it, meets at the top of a new page below the header
    /// rows that repeat there, when it meets the last of them (`RowBelowHeaders::LastHeader`):
    /// that header row, with the room that the document's mode gives the line drawn there.
    /// None when the table has no header rows above the row, or when the target's row meets
    /// the row before it there (`RowBelowHeaders::RowBefore`).
    pub(super) fn below_headers(&self, shape: &Shape, index: usize) -> Option<Above> {
        if !shape.grid.has_headers_above(index) {
            return None;
        }
        decisions::last_header_above(&self.context.quirks, || {
            Above::Headers(if self.settings.mode_rules.gives_header_line_room() {
                HeaderRoom::Line
            } else {
                HeaderRoom::RowBefore
            })
        })
    }

    /// Whether the minimum height of a row, with its top at `top`, fits on the page. A row
    /// whose minimum height does not fit does not split there: it moves whole to the next
    /// page. At the top of a page the row has no other place, and it can split.
    pub(super) fn minimum_fits(&self, shape: &Shape, index: usize, top: Length) -> bool {
        let height = Self::minimum(shape, index);
        self.page_has_no_line() || top + height + shape.bottom_border(index) <= self.body_end()
    }

    /// The height that a row with a minimum height has without content: its top border, the
    /// minimum height and the cell margins. Zero for a row with another height rule.
    pub(super) fn minimum(shape: &Shape, index: usize) -> Length {
        let rule = shape.grid.table.rows.get(index).and_then(|row| row.height);
        let Some((height, HeightRule::AtLeast)) = rule else {
            return Length::ZERO;
        };
        let slots = shape.slots(index);
        let cells: Vec<(Length, Sides<Length>)> = slots
            .iter()
            .map(|slot| (Length::ZERO, slot.margins))
            .collect();
        least_row_height(Shape::top_part(slots), &cells, height)
    }

    /// Lays out the header rows at the top of a new page, above the row `index`, and returns
    /// their height. The rows warned where the table starts, so their repetition adds no
    /// warnings (**Warnings trial**). A cell merged over several header rows ends and aligns
    /// in the last of them, as it does where the table starts.
    pub(super) fn headers(&mut self, shape: &Shape, index: usize) -> Length {
        self.layout_without_warnings(|layout| {
            let top = layout.y;
            let mut merges = Merges::default();
            for header in 0..shape.grid.headers.min(index) {
                let row_top = layout.y;
                let height = layout.row_at(shape, header, row_top, &mut merges, false);
                layout.move_to(row_top + height);
                // The rows that repeat carry the rests to the next row, as the other rows do.
                // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
                layout.carry_row_twips();
            }
            layout.y - top
        })
    }

    /// Lays out the cells of a row with its top at `top`, draws its borders and returns its
    /// height. The top border comes first. Below it, the row is as tall as its tallest cell,
    /// within the limits of the row height rule. A cell that is not at the top of its column
    /// moves down for its vertical alignment, and is then laid out again. `moved_on` says that
    /// the cell that holds the table, in a row that splits, has moved on to a later part.
    pub(super) fn row_at(
        &mut self,
        shape: &Shape,
        index: usize,
        top: Length,
        merges: &mut Merges,
        moved_on: bool,
    ) -> Length {
        let edges = self.page_edges(index, merges);
        let slots = shape.slots_at(index, edges);
        let border = Shape::top_part(&slots);
        let inner = top + border;
        let (top_rests, outer) = self.start_row_twips(top, border);
        let row_top = RowTop {
            at: top,
            rest: top_rests.map(|rests| rests.twips),
        };
        let mark = self.row_mark();
        // The fills of the cells come after their content, and lie under it.
        let mut row_fills = self.items.open_fills();
        // The content of a merged region breaks at the page's foot as the lines of a row do,
        // and the lines below it go on on the next page.
        let carry = (merges.paginate && self.fragment.is_none()).then(|| {
            (
                self.body_end() - shape.bottom_border(index),
                self.next_area_top(),
            )
        });
        // A cell that moves for its vertical alignment is laid out again, which gives its
        // warnings again.
        let trial = self.output.start_trial();
        let (mut laid, mut carried, mut region_fills, cell_ends) =
            self.contents(&slots, inner, &[], (carry, moved_on));
        let mut regions = Regions::default();
        let cells: Vec<(Length, Sides<Length>)> = slots
            .iter()
            .enumerate()
            .zip(&laid)
            .map(|(slot, &(_, bottom))| {
                let needed = merges.needed(slot, bottom - inner, inner, &mut regions);
                (needed, slot.1.margins)
            })
            .collect();
        let rule = shape.grid.table.rows.get(index).and_then(|row| row.height);
        let height = row_height(border, &cells, rule, &self.context.quirks);
        let end = self.row_end_rest(
            (top_rests, border),
            &cells,
            (&laid, &cell_ends),
            (rule, top + height),
        );
        let moves = self.moves(&slots, (&laid, &cell_ends), (inner, top + height, end));
        let shifted = moves.iter().any(|(shift, _)| *shift != Length::ZERO);
        self.output.end_trial(trial, !shifted);
        if shifted {
            self.back_to_row_mark(&mark);
            row_fills = self.items.open_fills();
            (laid, carried, region_fills, _) =
                self.contents(&slots, inner, &moves, (carry, moved_on));
        }
        self.turned_contents(&slots, (inner, top + height));
        self.turned_regions(shape, merges, &regions.closed, top + height);
        // The fills of the cells lie under their content and their borders, below the line
        // that the row above draws at the top of the row. A cell that continues a merged
        // region has no line at its top: its fill starts at the top of the row and lies under
        // the region's content, which the region's first cell holds.
        let device = self.device;
        let (fills, under) = cell_fills(
            (&slots, &self.context.quirks, |place| device.snap(place)),
            (top, inner, top + height),
        );
        // While a row splits, the items of the next page take the place of this page's, and
        // the cells of the split row get no fill: their fills entries are not among them.
        self.items.put_fills(row_fills, fills);
        self.fill_under_regions(under, (merges, &regions));
        for (i, bottom) in regions.started {
            if let (Some(slot), Some((items, _))) = (slots.get(i), laid.get(i)) {
                merges.open.push(Open {
                    first: slot.first,
                    bottom,
                    items: items.clone(),
                    align: slot.align(),
                    carried: carried.get_mut(i).and_then(Option::take),
                    fills: region_fills.get(i).copied().flatten(),
                    clip: self.region_clip(slot, (row_top, inner)),
                    turned: (!slot.upright()).then_some((index, inner)),
                    start: slot.upright().then_some(RegionStart {
                        row: index,
                        top: inner,
                        pages: self.output.pages.len(),
                    }),
                });
            }
        }
        self.align_closed_regions(shape, merges, &regions.closed, (top + height, moved_on));
        let lines_from = self.items.len();
        // The bottom lines below the row round a half dot by the rests at its end.
        self.table_twips.row_end = end.filter(|_| slots.iter().all(|slot| slot.gaps.is_none()));
        self.row_borders(shape, index, &slots, (row_top, top + height));
        // The lines of the cells meet at junctions, unless cell spacing gives each cell a box
        // of its own.
        let above = std::mem::take(&mut merges.lines);
        if slots.iter().all(|slot| slot.gaps.is_none()) {
            merges.lines = self.split_at_junctions(lines_from, &above, &shape.grid.table.part);
        }
        // Word paints each filled cell's top margin again after the row's borders.
        self.top_bands(&slots, (row_top, inner), lines_from);
        // With cell spacing, the row also holds its cells' bottom lines and the spacing below
        // them.
        let bottoms = Shape::bottoms(&slots);
        let opening = shape.grid.opening_line(index, edges.above);
        self.table_outline(
            shape,
            (index, &slots),
            (top, top + height + bottoms),
            (opening, OutlineEnd::of_row(shape, index)),
        );
        // Each cell cuts what it draws at its clip, on a target that does.
        self.clip_row(
            (shape, index),
            (&slots, &laid),
            (row_top, inner, top + height),
            &regions.closed,
        );
        self.end_row_twips(outer, end.filter(|_| bottoms == Length::ZERO));
        height + bottoms
    }

    /// Draws the borders of the cells of row `index` from `top` to `bottom`. A cell with no
    /// cell below it draws its bottom border where the next row starts, because no top border
    /// of that row lies there.
    fn row_borders(
        &mut self,
        shape: &Shape,
        index: usize,
        slots: &[Slot],
        (top, bottom): (RowTop, Length),
    ) {
        let last = index + 1 == shape.grid.table.rows.len();
        for slot in slots {
            self.cell_borders(slot, (top, bottom), last);
            if !last && slot.gaps.is_none() && shape.grid.open_below(index, slot) {
                self.bottom_line(slot, bottom);
            }
        }
    }

    /// Lays out the text of each region of turned text of `regions` over the region, from the
    /// top of the region's first row to `bottom` ([`Self::turned_content`]).
    /// Moves the content of each merged region that ends in the row whose bottom is `bottom`
    /// for its alignment, and notes each move, which a trial of the row takes back.
    fn align_closed_regions(
        &mut self,
        shape: &Shape,
        merges: &mut Merges,
        closed: &[Open],
        (bottom, moved_on): (Length, bool),
    ) {
        merges.aligned.clear();
        for open in closed {
            let shift = align(open.align, bottom - open.bottom);
            for (items, dy) in self.region_moves(shape, merges, open, (shift, moved_on)) {
                self.shift(items.clone(), dy);
                merges.aligned.push((items, dy));
            }
        }
    }

    /// How the items of a merged region that ends move for its alignment, `shift` down from
    /// its top: as one block by the shift rounded to the dot, or, on a target whose profile
    /// names `MergedCellLines::FromAlignedTop`, each item to its place in a trial layout of
    /// the content from the exact aligned top. The trial counts only when it gives as many
    /// items as the region holds, each within a dot of the block's move.
    fn region_moves(
        &mut self,
        shape: &Shape,
        merges: &Merges,
        open: &Open,
        (shift, moved_on): (Length, bool),
    ) -> Vec<(Range<usize>, Length)> {
        let block = self.device.snap(shift);
        let whole = vec![(open.items.clone(), block)];
        if decisions::lines_from_aligned_top(&self.context.quirks, open).is_none()
            || shift == Length::ZERO
            || open.carried.is_some()
        {
            return whole;
        }
        let Some(start) = open
            .start
            .filter(|start| start.pages == self.output.pages.len())
        else {
            return whole;
        };
        let slots = shape.slots_at(start.row, self.page_edges(start.row, merges));
        let Some(slot) = slots.iter().find(|slot| slot.first == open.first) else {
            return whole;
        };
        let (mark, trial) = (self.row_mark(), self.output.start_trial());
        let (y, column, previous) = (self.y, self.column.clone(), self.previous.clone());
        let from = self.items.len();
        self.content(slot, start.top + shift, moved_on);
        let laid: Vec<Option<Length>> = self
            .items
            .placed(from..self.items.len())
            .map(|(_, item)| item.first_place().map(|place| place.y))
            .collect();
        self.back_to_row_mark(&mark);
        self.output.end_trial(trial, false);
        (self.y, self.column, self.previous) = (y, column, previous);
        let held: Vec<(usize, Option<Length>)> = self
            .items
            .placed(open.items.clone())
            .map(|(at, item)| (at, item.first_place().map(|place| place.y)))
            .collect();
        if laid.len() != held.len() {
            return whole;
        }
        let dot = self.device.dots(1);
        let mut moves: Vec<(Range<usize>, Length)> = Vec::new();
        for (new, &(at, old)) in laid.iter().zip(&held) {
            let dy = match (new, old) {
                (Some(new), Some(old)) => *new - old,
                _ => block,
            };
            if (dy - block).units().abs() > dot.units() {
                return whole;
            }
            // A move takes whole entries: the items of one entry move as one, and the places
            // before an item that paint nothing go with its move.
            let from = match moves.last_mut() {
                Some((range, last)) if *last == dy => {
                    range.end = at + 1;
                    continue;
                }
                Some((range, _)) if range.end > at => return whole,
                Some((range, _)) => range.end,
                None => open.items.start,
            };
            moves.push((from..at + 1, dy));
        }
        if let Some((range, _)) = moves.last_mut() {
            range.end = range.end.max(open.items.end);
        }
        moves
    }

    fn turned_regions(&mut self, shape: &Shape, merges: &Merges, regions: &[Open], bottom: Length) {
        for open in regions {
            let Some((row, top)) = open.turned else {
                continue;
            };
            let slots = shape.slots_at(row, self.page_edges(row, merges));
            if let Some(slot) = slots.iter().find(|slot| slot.first == open.first) {
                self.turned_content(slot, (top, bottom));
            }
        }
    }

    /// Lays out the text of the regions of turned text that a page break ended
    /// ([`Merges::cut_turned`]) over their part on the page, which ends at `bottom`.
    pub(super) fn end_turned_regions(
        &mut self,
        shape: &Shape,
        merges: &mut Merges,
        bottom: Length,
    ) {
        let cut = std::mem::take(&mut merges.cut);
        self.turned_regions(shape, merges, &cut, bottom);
    }

    /// Lays out the content of each cell of a row, moved down by its shift, and returns the
    /// items and the bottom of each on this page. With `carry`, the lowest bottom of a line on
    /// the page and the top of the next page, the first cell of a merged region keeps its
    /// lines down to that bottom on this page, and the part of its content that goes on on
    /// the next page comes back too. `moved_on` is as for [`Self::row_at`].
    fn contents(
        &mut self,
        slots: &[Slot],
        inner: Length,
        shifts: &[(Length, Option<MovedTop>)],
        (carry, moved_on): (Option<(Length, Length)>, bool),
    ) -> Contents {
        let mut contents: Contents = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
        for (i, slot) in slots.iter().enumerate() {
            // A cell that a merged region may go on below keeps a fills entry before its
            // content, for the fills of the region's later cells.
            contents
                .2
                .push(slot.merged_below.then(|| self.items.open_fills()));
            let start = self.items.len();
            let (shift, moved) = shifts.get(i).copied().unwrap_or((Length::ZERO, None));
            let starts_region = slot.merged_below && !slot.merged_above() && slot.upright();
            self.table_twips.cell = CellRests::default();
            self.table_twips.moved = moved;
            let (bottom, carried) = match carry.filter(|_| starts_region) {
                Some(limits) => self.region_content(slot, inner + shift, limits, moved_on),
                None => (self.content(slot, inner + shift, moved_on), None),
            };
            self.table_twips.moved = None;
            let cell = std::mem::take(&mut self.table_twips.cell);
            contents.3.push(CellRests {
                end: cell.end.filter(|end| end.at == bottom),
                ..cell
            });
            contents.0.push((start..self.items.len(), bottom));
            contents.1.push(carried);
        }
        contents
    }

    /// Lays out the content of a cell below `top` and its top margin, and returns the bottom
    /// of the content with the space after its last paragraph and its bottom margin. A cell
    /// that continues a merged region above it shows nothing. `moved_on` says that the cell
    /// that holds the cell's table, in a row that splits, has moved on to a later part.
    pub(super) fn content(&mut self, slot: &Slot, top: Length, moved_on: bool) -> Length {
        // A turned cell's text adds nothing to the row's height; it follows once the row has
        // its height, or once the region that it starts has its height.
        if slot.merged_above() || !slot.upright() {
            return top + slot.margins.top + slot.margins.bottom;
        }
        let origin = self.column.origin;
        self.column = slot.column(&self.context.quirks);
        self.column.origin = origin;
        let carried = self
            .table_twips
            .row
            .filter(|row| row.at == top)
            .zip(twips_rest(&self.device, slot.margins.top))
            .map(|(row, own)| (row.twips + own, row.height));
        let moved = self.table_twips.moved.take();
        self.move_to(top + slot.margins.top);
        // The cell's text top carries the rest of the row's top with its top margin's. Where
        // that rest is not known, the cell's text top, a length of whole twips from the page's
        // top, starts the cursor's twips rest, as the body's top does. A text top that the
        // cell's vertical alignment moved keeps the rests that it had before the move, with
        // the height rest of the move.
        // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
        match (moved, carried) {
            (Some(moved), _) => {
                self.set_twips(moved.twips);
                self.y_rest = moved.rest;
            }
            (None, Some((twips, height))) => {
                self.set_twips(Some(twips));
                self.y_rest = height;
            }
            (None, None) => self.start_twips(top + slot.margins.top),
        }
        let (top_rest, top_height) = (self.twips_here(), self.y_rest);
        // The single lines of a cell whose rest the row carries round their box tops with it.
        let outer_carried = std::mem::replace(
            &mut self.table_twips.carried,
            carried.is_some() || moved.is_some(),
        );
        self.previous = None;
        let (items, lines, page) = (
            self.items.len(),
            self.output.placed.len(),
            self.output.pages.len(),
        );
        // The text of a cell keeps out of the floating tables and the wraps of the drawings of
        // that cell only, and below the bands that the flow holding it keeps.
        let bands = self.bands.clone();
        let outer = self.swap_cell_state(CellState {
            floor: Some(CellFloor::Clear),
            top: Some(top + slot.margins.top),
            sides: Some(inner_sides(slot)),
            place: Some(crate::layout::CellPlace {
                table: self.table_number,
                row: slot.row + 1,
                column: slot.first + 1,
            }),
            squares: Vec::new(),
            bands,
            // The lines of a cell go with a cell that holds it once that cell has moved on to
            // a later part, also through the cells of tables between them.
            carried: moved_on || self.cell_carried,
        });
        // A deleted cell shows a balloon beside its first line.
        if let Some(deletion) = &slot.cell.deletion {
            self.note_deleted_cell(deletion, self.y);
        }
        // A cell that hides its end-of-cell mark leaves out an empty last paragraph.
        self.blocks(slot.cell.shown_blocks());
        // Automatic space after the last paragraph adds nothing to the cell, but where the
        // paragraph keeps it there.
        // Nor does the space after of a last paragraph of the default paragraph style with
        // contextual spacing, since the cell's end counts as a paragraph of that style.
        let default_style = self.styles.default_paragraph_style();
        let after = self
            .previous
            .take()
            .filter(|p| p.keeps_after_at_cell_end(&self.context.quirks))
            .filter(|p| !p.drops_after_before(default_style))
            .map_or(Length::ZERO, |p| p.after);
        // The content reaches down to the drawings anchored in the cell that wrap text, and,
        // in a cell aligned to the center or the bottom, to every drawing anchored in it.
        let own = self.swap_cell_state(outer);
        let every = matches!(
            slot.align(),
            Some(VerticalAlign::Center | VerticalAlign::Bottom)
        );
        let content = self.y + after;
        let floor = own.floor.and_then(|floor| floor.reach(every));
        let bottom = floor.map_or(content, |floor| content.max(floor)) + slot.margins.bottom;
        // The cell's bottom carries the rest of its last line with the space after kept there
        // and its bottom margin, where the content sets it.
        let sets = floor.is_none_or(|floor| floor <= content);
        let end = self
            .twips_here()
            .filter(|_| sets)
            .zip(twips_rest(&self.device, after))
            .zip(twips_rest(&self.device, slot.margins.bottom))
            .map(|((above, after), margin)| TwipsRest {
                at: bottom,
                rest: above + after + margin,
            });
        // A target may leave out a cell that lies wholly outside the page, such as one beyond
        // its right edge in a table wider than the page. The cell keeps its place and its
        // height in the row.
        let page_size = (self.section.width, self.section.height);
        let bounds = Edges {
            left: slot.left,
            top,
            right: slot.right,
            bottom,
        };
        let whole = self.output.pages.len() == page && self.fragment.is_none();
        if whole && !self.device.draws_object(bounds, page_size) {
            self.items.cut(items);
            self.output.placed.truncate(lines);
        }
        self.table_twips.cell = CellRests {
            end,
            top: top_rest,
            top_height,
            end_height: sets.then_some(self.y_rest),
            bottom: sets.then(|| self.y_rest + end.map_or(0, |end| end.rest)),
        };
        self.table_twips.carried = outer_carried;
        bottom
    }

    /// Puts `state` in the place of the state that a table cell starts afresh, and gives the
    /// state that was there.
    fn swap_cell_state(&mut self, state: CellState) -> CellState {
        CellState {
            floor: std::mem::replace(&mut self.cell_floor, state.floor),
            top: std::mem::replace(&mut self.cell_top, state.top),
            sides: std::mem::replace(&mut self.cell_sides, state.sides),
            place: std::mem::replace(&mut self.cell_place, state.place),
            squares: std::mem::replace(&mut self.squares, state.squares),
            bands: std::mem::replace(&mut self.bands, state.bands),
            carried: std::mem::replace(&mut self.cell_carried, state.carried),
        }
    }

    /// Puts the fills of the cells that continue merged regions, each with the region's
    /// first grid column, into the regions' fills entries, under the regions' content. A
    /// region whose fills entry is not among the page items, as while a row splits, gets
    /// none.
    fn fill_under_regions(
        &mut self,
        fills: Vec<(usize, Item)>,
        (merges, regions): (&Merges, &Regions),
    ) {
        for (first, fill) in fills {
            let entry = (merges.open.iter().chain(&regions.closed))
                .find(|open| open.first == first)
                .and_then(|open| open.fills);
            if let Some(entry) = entry {
                self.items.put_region_fill(entry, fill);
            }
        }
    }
}

/// The fills of a row's cells from `top`, or from `inner` below the row's top line, down to
/// `bottom`, each across as the target's `quirks` say ([`Slot::fill`]) and down on the dots
/// that `snap` gives where they say so ([`decisions::fill_row_edge`]): those that lie under the
/// row's own content, and those of cells that continue a merged region, with the region's
/// first grid column, which lie under the region's content.
pub(super) fn cell_fills(
    (slots, quirks, snap): (&[Slot], &Quirks, impl Fn(Length) -> Length),
    (top, inner, bottom): (Length, Length, Length),
) -> (Vec<Item>, Vec<(usize, Item)>) {
    let mut fills = Vec::new();
    let mut under = Vec::new();
    let edge = |place| decisions::fill_row_edge(quirks, place, &snap);
    for slot in slots {
        let Some(rgb) = cell_fill_color(slot) else {
            continue;
        };
        let from = edge(if slot.merged_above() { top } else { inner });
        let (left, right) = slot.fill(quirks);
        let fill = Item::Rect(Rect {
            x: left,
            y: from,
            width: right - left,
            height: edge(bottom) - from,
            color: rgb,
        });
        if slot.merged_above() {
            under.push((slot.first, fill));
        } else {
            fills.push(fill);
        }
    }
    (fills, under)
}

/// The color of a cell's fill, or `None` for no fill. A white fill is drawn too: it covers
/// what lies under the cell, such as a drawing behind the text, and the bands that Word paints
/// again after a cell's lines take the same color, since a white band still lightens the edge
/// of a line it touches.
pub(super) fn cell_fill_color(slot: &Slot) -> Option<Rgb> {
    slot.shading?.rgb()
}

/// The height rest that a cell's text top takes where the cell moves down for its vertical
/// alignment `align`, in 1/[`REST_PARTS`] of a half-EMU, where the twips rest at the row's end
/// lies `gap` past the sum of the rests at the cell's bottom before the move. Word moves the
/// content by its free room with those rests: a cell aligned to the bottom takes all of `gap`,
/// so that its bottom takes the row end's rest; a cell aligned to the center takes half of it,
/// and half of the length `dropped` that the half of the free room in half-EMUs leaves out.
/// `None` for a cell that does not move.
pub(super) fn moved_rest(align: Option<VerticalAlign>, gap: i64, dropped: Length) -> Option<i64> {
    match align {
        Some(VerticalAlign::Bottom) => Some(gap),
        Some(VerticalAlign::Center) => Some(f_office_units::div_round(
            dropped.units() * REST_PARTS + gap,
            2,
        )),
        Some(VerticalAlign::Top) | None => None,
    }
}

/// The inner edges of the side lines of the cell `slot`. Each side line of a cell is centered on
/// its grid line, so the inner edge of the left one lies half its width right of the cell's left
/// grid line, and that of the right one half its width left of the cell's right grid line.
fn inner_sides(slot: &Slot) -> (Length, Length) {
    (
        slot.left + width(slot.borders.left).div_toward_zero(2),
        slot.right - width(slot.borders.right).div_toward_zero(2),
    )
}