f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! A table in a cell of a row that splits. Its rows fill the parts of the cell, one part for
//! each page, as the rows of a table of the body fill pages: a row that has room stays, a
//! row without room splits between its lines, and a row that cannot split starts the next
//! part. A header row of such a table does not repeat.

use std::ops::Range;

use f_office_units::Length;

use super::borders::RowTop;
use super::merges::Merges;
use super::split::{Fragment, Part, SplitCell, keeps_lines};
use super::{Shape, Slot, align};
use crate::layout::{Layout, PlacedLine, decisions};

impl Layout<'_> {
    /// Lays out row `index` of a table in a cell of a row that splits, whose fragment is
    /// `holder`.
    pub(super) fn carried_row(
        &mut self,
        shape: &Shape,
        index: usize,
        merges: &mut Merges,
        holder: &mut Fragment,
    ) {
        let limit = self.part_limits_of(holder).limit;
        let mark = self.mark();
        let open = merges.open.clone();
        let top = self.y;
        let new = self.part_is_new(holder);
        let height = self.row_at(shape, index, top, merges, holder.moved_on());
        if top + height + shape.foot_border(index) <= limit {
            self.move_to(top + height);
            holder.keep_inner_row();
            return;
        }
        self.rewind(&mark);
        merges.open.clone_from(&open);
        // A row at the top of a part for a later page splits also with `w:cantSplit`: it is
        // taller than the page. A row with vertically merged cells stays whole.
        let slots = shape.slots(index);
        let joined = !open.is_empty() || slots.iter().any(|s| s.merged_above() || s.merged_below);
        let whole = shape
            .grid
            .table
            .rows
            .get(index)
            .is_none_or(|row| row.cant_split);
        // On a target where a row moves whole when its minimum height does not fit, as a row of
        // the body does, it splits only when that height fits in the part.
        let fits = || top + Self::minimum(shape, index) + shape.bottom_border(index) <= limit;
        let minimum =
            new || decisions::whole_nested_rows(&self.context.quirks, fits).unwrap_or(true);
        if !joined
            && (new || !whole)
            && minimum
            && self.split_carried_row(shape, (index, top), holder)
        {
            return;
        }
        self.rewind(&mark);
        merges.open = open;
        if new {
            // Nothing of the row has room in a whole part: it stays and runs over.
            let height = self.row_at(shape, index, top, merges, holder.moved_on());
            self.move_to(top + height);
            return;
        }
        // The row above, now the last of its part, draws the bottom border of its outer edge.
        if let Some(above) = index
            .checked_sub(1)
            .filter(|_| shape.grid.spacing().is_none())
        {
            for slot in shape.slots(above) {
                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 part 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.end_turned_regions(shape, merges, top);
        self.end_part(holder, self.output.placed.len());
        // The part after it fills page items of its own: each region that goes on resets its
        // bounds to this part's top (so its closing row measures from this part rather than the
        // previous page's bottom) and opens a fills entry before the row for its later cells.
        let base = self.y + Shape::top_part(shape.slots(index));
        for open in &mut merges.open {
            open.fills = Some(self.items.open_fills());
            let start = self.items.len();
            open.bottom = base;
            open.items = start..start;
        }
        self.carried_row(shape, index, merges, holder);
    }

    /// Splits row `index` of a table in a cell between the part of the cell that is being
    /// filled and the parts after it, as [`Self::split_row`] splits a row between pages.
    /// Says whether a line of each cell that goes on stays in the part being filled.
    fn split_carried_row(
        &mut self,
        shape: &Shape,
        (index, top): (usize, Length),
        holder: &mut Fragment,
    ) -> bool {
        let holder_limits = self.part_limits_of(holder);
        let records = self.output.placed.len();
        let slots = shape.slots(index);
        let border = Shape::top_part(slots);
        let below = shape.bottom_border(index);
        // Only `NO_LIMIT` reaches the bound, and it stays there.
        let row_limits = super::split::PartLimits {
            limit: holder_limits.limit - below,
            next_top: holder_limits.next_top + border,
            later_limit: holder_limits.later_limit.saturating_sub(below),
            top_inset: holder_limits.top_inset.map(|i| i + border),
            bottom_inset: holder_limits.bottom_inset + below,
            base_step: holder_limits.base_step,
        };
        let mut carried = Vec::new();
        let mut cells = Vec::new();
        let mut spans = Vec::new();
        let moved_on = holder.moved_on();
        for slot in slots {
            let from = self.output.placed.len();
            let bounds = (top + border, row_limits);
            cells.push(self.split_cell(slot, bounds, &mut carried, moved_on));
            spans.push(from..self.output.placed.len());
        }
        if !keeps_lines(&cells) {
            return false;
        }
        let min_end = (top + Self::minimum(shape, index)).min(row_limits.limit);
        let end = self.first_part(slots, &cells, (top, min_end));
        self.move_to(end);
        let mut bounds = self.order_records(records, &cells, &spans).into_iter();
        self.end_part(holder, bounds.next().unwrap_or(records));
        let mut top = self.y;
        self.items.append(&mut carried);
        let mut end = cells.iter().map(|cell| cell.next_end).max().unwrap_or(top);
        let parts = cells.iter().map(|c| c.later.len()).max().unwrap_or(0);
        for part in 0..parts {
            for slot in slots {
                self.cell_borders(slot, (RowTop::without_rest(top), end), true);
            }
            self.move_to(end);
            self.end_part(holder, bounds.next().unwrap_or(records));
            top = self.y;
            end = self.later_part_of(&mut cells, part, top);
        }
        let end = end.max(top + Self::minimum(shape, index));
        let last = index + 1 == shape.grid.table.rows.len();
        for slot in slots {
            self.cell_borders(slot, (RowTop::without_rest(top), end), last);
        }
        self.move_to(end);
        true
    }

    /// Ends the part of a row that splits in the part of the cell that is being filled: a
    /// cell that stays whole takes its vertical alignment there, and the cells get their
    /// borders. Gives the bottom of the part.
    fn first_part(
        &mut self,
        slots: &[Slot],
        cells: &[SplitCell],
        (top, min_end): (Length, Length),
    ) -> Length {
        let end = cells
            .iter()
            .map(|cell| cell.end)
            .max()
            .unwrap_or(top)
            .max(min_end);
        for (slot, cell) in slots.iter().zip(cells) {
            if let Some((range, bottom)) = cell.page_part.clone() {
                let shift = align(slot.align(), end - bottom);
                self.shift(range, self.device.snap(shift));
            }
        }
        for slot in slots {
            self.cell_borders(slot, (RowTop::without_rest(top), end), true);
        }
        end
    }

    /// Puts the part `part` of each cell of a row that splits into the part of the outer
    /// cell that starts at `top`, and gives the lowest bottom.
    fn later_part_of(&mut self, cells: &mut [SplitCell], part: usize, top: Length) -> Length {
        let mut end = top;
        for cell in cells {
            if let Some(Part { items, bottom, .. }) = cell.later.get_mut(part) {
                self.items.append(items);
                end = end.max(*bottom);
            }
        }
        end
    }

    /// Puts the line records from `first` on, those of the cells of a row that split, in the
    /// order of the parts that they belong to: the cells lay out their lines one cell after
    /// the other, and the cell of the outer row keeps the records of each part together.
    /// `spans` are the records of each cell. Gives the number of records at the end of each
    /// part but the last.
    fn order_records(
        &mut self,
        first: usize,
        cells: &[SplitCell],
        spans: &[Range<usize>],
    ) -> Vec<usize> {
        let lines = self.output.placed.split_off(first);
        let mut parts = vec![0_usize; lines.len()];
        for (cell, span) in cells.iter().zip(spans).filter(|(cell, _)| cell.continues) {
            let later = cell.later.iter().map(|part| part.records.start);
            let starts: Vec<usize> = std::iter::once(cell.carried_from).chain(later).collect();
            for (part, start) in starts.iter().enumerate() {
                let stop = starts.get(part + 1).copied().unwrap_or(span.end);
                for record in *start..stop {
                    if let Some(slot) = record.checked_sub(first).and_then(|i| parts.get_mut(i)) {
                        *slot = part + 1;
                    }
                }
            }
        }
        let count = parts.iter().copied().max().unwrap_or(0);
        let mut tagged: Vec<(usize, PlacedLine)> = parts.into_iter().zip(lines).collect();
        tagged.sort_by_key(|(part, _)| *part);
        let mut bounds = Vec::new();
        for part in 0..count {
            let size = tagged.iter().filter(|(of, _)| *of <= part).count();
            bounds.push(first + size);
        }
        self.output
            .placed
            .extend(tagged.into_iter().map(|(_, line)| line));
        bounds
    }
}