f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! Vertically merged cells: the regions that stay open below a row.

use std::ops::Range;

use f_office_paint::{Item, Point};
use f_office_units::Length;

use super::clips::RegionClip;
use super::shape::Above;
use super::{Slot, move_items};
use crate::layout::page_items::FillsEntry;
use crate::layout::{FirstItem, Layout, decisions};
use crate::table::VerticalAlign;

/// A merged region that is still open below the current row.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Open {
    /// The first grid column of the region.
    pub(super) first: usize,
    /// The bottom that the region needs for the content of its first cell.
    pub(super) bottom: Length,
    /// The places of the entries of that content on the current page.
    pub(super) items: Range<usize>,
    /// The fills entry before that content, where the fills of the region's later cells
    /// go, if it is among the page items.
    pub(super) fills: Option<FillsEntry>,
    /// The vertical alignment of the first cell.
    pub(super) align: Option<VerticalAlign>,
    /// The lines of that content that go on on the next page, when the page ends inside the
    /// region.
    pub(super) carried: Option<Carried>,
    /// The clip of the first cell, on a target that cuts what a cell draws, which the row
    /// that ends the region completes.
    pub(super) clip: Option<RegionClip>,
    /// For a first cell of turned text, which turns its text over the whole region, the index
    /// of the region's first row and that row's top below its border, from which the text is
    /// laid out once the region's bottom is known. Only the content of a region of upright
    /// text, without it, flows on over a page break.
    pub(super) turned: Option<(usize, Length)>,
    /// For a region of upright text whose content lies where it was laid out, the place of
    /// that layout, from which a target that lays the lines of a merged cell out from its
    /// aligned top lays them out again when the region ends.
    pub(super) start: Option<RegionStart>,
}

/// Where the content of a merged region was laid out: the region's first row, that row's top
/// below its border, and the count of the pages then.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct RegionStart {
    pub(super) row: usize,
    pub(super) top: Length,
    pub(super) pages: usize,
}

/// The part of a merged region's content that goes on on the next page.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Carried {
    /// The items, placed below `base`.
    pub(super) items: Vec<Item>,
    /// The top that the items were placed below: the top of the next page or column, without
    /// its header rows and the top border of the row that starts it.
    pub(super) base: Length,
    /// The bottom of the content below `base`, with the bottom margin of the cell.
    pub(super) bottom: Length,
    /// The records of the lines that the first cell placed, of which those of the carried
    /// lines wait for their page.
    pub(super) records: Range<usize>,
}

/// The merged regions that are open, the left edge and bottom of each vertical line of the
/// row above, which the next row's lines may continue, and whether the table breaks across
/// pages, so that the content of a region can go on on the next page.
#[derive(Debug, Default)]
pub(super) struct Merges {
    pub(super) open: Vec<Open>,
    pub(super) lines: Vec<Point>,
    pub(super) paginate: bool,
    /// Whether a row fits on its page when its top lies above the body's end, also when it
    /// runs below it, rather than when its bottom does.
    pub(super) fits_by_top: bool,
    /// The row that moved to a new page, below no row of its table or below the header rows
    /// that repeat there, with what stands above it, whose top border the content that open
    /// regions carry there stands below.
    pub(super) page_start: Option<(usize, Above)>,
    /// The items of the content of each region that the last row laid out ended, with how far
    /// that content moved down for its alignment, so that the trial of a row that does not fit
    /// can move it back.
    pub(super) aligned: Vec<(Range<usize>, Length)>,
    /// The regions of turned text that a page break ends, whose text is laid out over their
    /// part on the page when the page ends.
    pub(super) cut: Vec<Open>,
}

impl Merges {
    /// Ends the regions of turned text at a page break: no such region stays open over it, and
    /// each waits in `cut` for the end of the page.
    pub(super) fn cut_turned(&mut self) {
        let (upright, turned): (Vec<Open>, Vec<Open>) = std::mem::take(&mut self.open)
            .into_iter()
            .partition(|open| open.turned.is_none());
        self.open = upright;
        self.cut.extend(turned);
    }
}

/// What a row does with the merged regions.
#[derive(Default)]
pub(super) struct Regions {
    /// The cells, by their index in the row, that start a region, with the bottom of their
    /// content on this page.
    pub(super) started: Vec<(usize, Length)>,
    /// The regions that end in this row.
    pub(super) closed: Vec<Open>,
}

impl Merges {
    /// The height that a cell needs in its row, from the height of its own content. A cell
    /// with a merged cell below needs only the room of an empty cell, and its content goes on
    /// to the next row. The last cell of a merged region needs room for the content of the
    /// whole region.
    pub(super) fn needed(
        &mut self,
        (index, slot): (usize, &Slot),
        own: Length,
        inner: Length,
        regions: &mut Regions,
    ) -> Length {
        let empty = slot.margins.top + slot.margins.bottom;
        let open = self
            .open
            .iter()
            .position(|m| m.first == slot.first)
            .map(|i| self.open.remove(i));
        match open {
            Some(open) => {
                let needed = own.max(open.bottom - inner);
                if slot.merged_below {
                    self.open.push(open);
                    empty
                } else {
                    regions.closed.push(open);
                    needed
                }
            }
            None if slot.merged_below => {
                regions.started.push((index, inner + own));
                empty
            }
            None => own,
        }
    }

    /// Whether a row of `slots` ends a region whose content goes on on the next page, so
    /// that the row splits to hold the rest of it.
    pub(super) fn ends_carried(&self, slots: &[Slot]) -> bool {
        slots
            .iter()
            .filter(|slot| slot.merged_above() && !slot.merged_below)
            .any(|slot| {
                self.open
                    .iter()
                    .any(|open| open.first == slot.first && open.carried.is_some())
            })
    }
}

impl Layout<'_> {
    /// Places on this page the lines that the open regions carry on, below `base`, the top of
    /// the regions' part on this page, and gives each region its bottom there. A region that
    /// carries nothing needs no room on this page.
    pub(super) fn place_carried(&mut self, merges: &mut Merges, base: Length) {
        for open in &mut merges.open {
            open.fills = Some(self.items.open_fills());
            let start = self.items.len();
            let Some(carried) = open.carried.take() else {
                open.bottom = base;
                open.items = start..start;
                continue;
            };
            // The region's bottom, which sets the height of its rows, keeps the exact move.
            let exact = base - carried.base;
            let dy = decisions::carried_merge_move(&self.context.quirks, &self.device, exact);
            let mut items = carried.items;
            move_items(&mut items, dy);
            self.items.extend(items);
            self.carried_records(carried.records, dy);
            open.bottom = carried.bottom + exact;
            open.items = start..self.items.len();
        }
    }

    /// Gives the records of `records` whose lines a region carried on their place on this
    /// page, `dy` below the place where they were laid out.
    pub(super) fn carried_records(&mut self, records: Range<usize>, dy: Length) {
        let page = self.output.pages.len();
        for line in self.output.placed.get_mut(records).into_iter().flatten() {
            if line.item == FirstItem::Carried {
                line.page = page;
                line.move_down(dy);
            }
        }
    }
}