f-office-docx 0.3.0

DOCX model and Word's layout rules.
Documentation
//! Floating tables, which lie at their own place while the text flows around them.

use f_office_units::{Edges, Length};

use super::{Paging, Shape, TableGrid};
use crate::floating::WrapSides;
use crate::layout::floating::{Square, StartPastWrap, keep_wrap};
use crate::layout::{Column, Layout, decisions};
use crate::params::NARROWEST_WRAP;
use crate::props::{Align, Anchor};
use crate::styles::TableStyle;
use crate::table::{Table, TablePlacement};

impl Layout<'_> {
    /// Lays out a floating table at its place without moving the text, and keeps the text
    /// away from the table's box and the distances around it.
    pub(super) fn floating_table(
        &mut self,
        table: &Table,
        style: TableStyle,
        place: TablePlacement,
    ) {
        let early = place.vertical != Anchor::Text
            && self.column.cell.is_none()
            && self.story.is_none()
            && self.page.is_none();
        self.advance_held_table(early);
        let rules = self.settings.mode_rules;
        let outer = self.column.clone();
        let least = self.least_widths_for(table, &style);
        let probe = TableGrid::new(table, style.clone(), &outer, self.shape_context(), &least);
        // The grid of a right-to-left table runs the other way, so its edges are the smallest
        // and the largest grid line.
        let (outer_left, outer_width) = (outer.left, outer.width);
        let start = probe.lines.iter().copied().min().unwrap_or(outer_left);
        let total = probe.lines.iter().copied().max().unwrap_or(start) - start;
        let section = self.section;
        let page = (section.width, section.height);
        let (left, width) = match across(place.horizontal, outer.cell.is_some()) {
            Anchor::Page => (Length::ZERO, page.0),
            Anchor::Margin => (section.left, page.0 - section.left - section.right),
            Anchor::Text => (outer_left, outer_width),
        };
        // A nested table takes the edge rule of mode 15 in every mode, also when it floats.
        let edge_rules = rules.for_table(outer.cell.is_some());
        let x = self.floating_table_x(&probe, place, (left, width, total), edge_rules);
        let column = Column {
            left: outer_left + x - start,
            ..outer.clone()
        };
        let mut shape = Shape::new(table, style, &column, &self.shape_context(), &least);
        let Edges {
            left: before,
            top: above,
            right: after,
            bottom: below,
        } = place.distance;
        let room = (x - before - outer_left).max(outer_left + outer_width - x - total - after);
        let no_side_room = place.vertical == Anchor::Text && room < NARROWEST_WRAP;
        // On targets whose floating tables break across pages, a full-width body/cell table
        // hanging on the text with vertical room above it (`tblpY > topFromText`) still floats so
        // following paragraphs can fit into that room above the table.
        let floats_above = place.y > above
            && self.story.is_none()
            && self.fragment.is_none()
            && decisions::floating_breaks(&self.context.quirks, || ()).is_some();
        if no_side_room && !floats_above {
            self.table_in_flow(&mut shape, (column, outer), (place.y, below));
            return;
        }
        // A floating table in a cell of a row that splits stays in one part of the row: its
        // cells start side by side, so their lines do not tell where a page is full.
        let held = self.hold_parts();
        let previous = self.previous.clone();
        if no_side_room {
            self.after_break = false;
            if let Some(prev) = self.previous.take() {
                self.y += prev.after;
            }
            self.place_column_top();
        }
        let flow = self.y;
        let (anchor, room) = match place.vertical {
            Anchor::Page => (Length::ZERO, page.1),
            Anchor::Margin => (section.top, page.1 - section.top - section.bottom),
            // The text anchor lies below the space after the paragraph before the table.
            Anchor::Text => {
                let after = self.previous.as_ref().map_or(Length::ZERO, |p| p.after);
                (flow + after, Length::ZERO)
            }
        };
        self.column = column;
        let raw_top =
            self.floating_table_top(&mut shape, place, (anchor, room), (outer_left, x, start));
        let top = self.clear_overlapping_table_wraps(
            raw_top,
            (x - before, x + total + after),
            no_side_room,
        );
        // The text after a narrow table keeps the space after the paragraph before it, which the
        // table's own paragraphs do not replace; a full-width table consumes that space above it.
        let table_prev = previous
            .as_ref()
            .map_or_else(|| self.cell_prev_style.clone(), |p| p.style.clone());
        let outer_table_prev = std::mem::replace(&mut self.table_prev_style, table_prev);
        let start_page = self.output.pages.len();
        let start_bottom = self.body_bottom_of(start_page);
        let (end_top, bottom, broke) =
            self.placed_rows(&mut shape, (top, flow), outer, place.vertical);
        self.table_prev_style = outer_table_prev;
        self.previous = if no_side_room { None } else { previous };
        // In a table cell, the cell's content reaches down to the table's bottom.
        self.cell_floor = self.cell_floor.map(|floor| floor.lowered(bottom, true));
        if no_side_room && broke {
            // A broken full-width table starts at the top of its final column/page, leaving no
            // room above or beside it; continue directly below its bottom distance.
            self.move_to(bottom + below);
        } else {
            // The text flows on both sides of a floating table where there is room, and above it
            // where vertical room precedes `top - above`.
            self.record_floating_table_wrap(
                (start_page, early, broke),
                (x - before, x + total + after),
                (top - above, start_bottom + below),
                (end_top - above, bottom + below),
            );
        }
        self.release_parts(held);
    }

    /// Advances to a new page when an earlier pass found that a page- or margin-anchored floating
    /// table's wrap pushed preceding text onto a later page so the table itself starts there.
    fn advance_held_table(&mut self, early: bool) {
        let held = early
            && self
                .context
                .earlier
                .wraps
                .held
                .squares
                .get(self.output.found.squares.len())
                .is_some_and(|&page| page > self.output.pages.len())
            && !self.page_has_no_line();
        if held {
            self.new_page();
            self.previous = None;
        }
    }

    /// Records the wrap box of a floating table, participating in early-pass page wraps when
    /// `early` is set (page- or margin-anchored body table) so preceding text on the page wraps
    /// around it and moves the table to the next page when its wrap overflows the page.
    fn record_floating_table_wrap(
        &mut self,
        (start_page, early, broke): (usize, bool, bool),
        (left, right): (Length, Length),
        (start_top, start_bottom): (Length, Length),
        (end_top, end_bottom): (Length, Length),
    ) {
        let make_square = |top: Length, bottom: Length| Square {
            top,
            bottom,
            left,
            right,
            below: bottom,
            sides: Some(WrapSides::Both),
            line_steps: false,
            polygon: false,
            outline: None,
            narrowest: NARROWEST_WRAP,
            start_past: StartPastWrap::Whole,
            table: true,
        };
        let end_square = make_square(end_top, end_bottom);
        if broke {
            self.squares.push(end_square);
            if early {
                self.output
                    .found
                    .squares
                    .push((start_page, make_square(start_top, start_bottom)));
            }
        } else {
            keep_wrap(
                (start_page, early),
                end_square,
                &mut self.squares,
                &mut self.output.found.squares,
                &self.context.earlier.wraps.squares,
            );
        }
    }

    /// Pushes `top` below any earlier floating-table wrap on the page that overlaps `top` across
    /// `[left, right]` when `no_side_room` is set, so back-to-back full-width floating tables
    /// stack instead of overlapping.
    fn clear_overlapping_table_wraps(
        &self,
        mut top: Length,
        (left, right): (Length, Length),
        no_side_room: bool,
    ) -> Length {
        if !no_side_room {
            return top;
        }
        while let Some(next) = self
            .squares
            .iter()
            .filter(|sq| sq.table && sq.right > left && sq.left < right)
            .filter(|sq| sq.top <= top && top < sq.bottom)
            .map(|sq| sq.below)
            .max()
        {
            top = next;
        }
        top
    }

    /// Vertical top of a floating table from its anchor, offset, and alignment. An alignment
    /// down has nothing to align in when the table hangs on the text: the table stands at its
    /// anchor. An alignment wins over the offset down.
    fn floating_table_top(
        &mut self,
        shape: &mut Shape,
        place: TablePlacement,
        (anchor, room): (Length, Length),
        (outer_left, x, start): (Length, Length, Length),
    ) -> Length {
        let offset = place.y_align.map_or(place.y, |_| Length::ZERO);
        let aligned = place.y_align.filter(|_| place.vertical != Anchor::Text);
        match aligned {
            None => {
                anchor + offset
                    - decisions::floating_table_rise(&self.context.quirks, place.vertical)
            }
            Some(Align::Start | Align::Inside) => anchor + offset,
            Some(align) => {
                let mark = self.mark();
                self.move_to(Length::ZERO);
                self.rows(shape, (Paging::Whole, None));
                let height = self.y;
                self.rewind(&mark);
                self.column = Column {
                    left: outer_left + x - start,
                    ..self.column.clone()
                };
                if align == Align::Center {
                    anchor + (room - height).div_toward_zero(2)
                } else {
                    anchor + room - height
                }
            }
        }
    }

    /// Lays out a table that hangs on the text and leaves no room beside it in the flow, `y`
    /// below the space after the paragraph before it, in `column`, and goes back to `outer`
    /// `below` under the table's bottom. It breaks as a table in the flow does: across pages in
    /// the body, and between the parts of a row that splits in a cell.
    fn table_in_flow(
        &mut self,
        shape: &mut Shape,
        (column, outer): (Column, Column),
        (y, below): (Length, Length),
    ) {
        self.after_break = false;
        let prev_before_table = self.previous.take();
        if let Some(previous) = &prev_before_table {
            self.y += previous.after;
        }
        self.place_column_top();
        let table_prev =
            prev_before_table.map_or_else(|| self.cell_prev_style.clone(), |p| p.style);
        let outer_table_prev = std::mem::replace(&mut self.table_prev_style, table_prev);
        self.y += y;
        let paging = if outer.cell.is_none() {
            Paging::ByBottom
        } else {
            Paging::Whole
        };
        self.column = column;
        self.rows(shape, (paging, None));
        self.table_prev_style = outer_table_prev;
        self.y += below;
        self.column = outer;
        self.previous = None;
    }

    /// Lays out the rows of a floating table from `top` down, and goes back to `flow`, the
    /// place of the text, in the column `outer`. Returns the top and the bottom of the table's
    /// part in the column where it ends. On a target where a floating table breaks across
    /// pages, one of the body breaks at the body's end, and its rest starts at the top of the
    /// next column or page; the paragraphs after it then go on in the column of its last part,
    /// from the top of that column, around its part there.
    fn placed_rows(
        &mut self,
        shape: &mut Shape,
        (top, flow): (Length, Length),
        outer: Column,
        vertical: Anchor,
    ) -> (Length, Length, bool) {
        let breaks = decisions::floating_breaks(&self.context.quirks, || {
            self.story.is_none() && outer.cell.is_none()
        })
        .unwrap_or(false);
        let by_bottom =
            vertical == Anchor::Text || self.settings.mode_rules.fits_floating_rows_by_bottom();
        let paging = match (breaks, by_bottom) {
            (false, _) => Paging::Whole,
            (true, true) => Paging::ByBottom,
            (true, false) => Paging::ByTop,
        };
        let area = (self.output.pages.len(), self.column_index);
        self.move_to(top);
        self.rows(shape, (paging, None));
        let bottom = self.y;
        self.column = outer;
        if (self.output.pages.len(), self.column_index) == area {
            self.move_to(flow);
            return (top, bottom, false);
        }
        if let Some(&(left, width)) = self.columns.get(self.column_index) {
            self.column.left = left;
            self.column.origin = left;
            self.column.width = width;
        }
        self.move_to(self.column_top);
        (self.column_top, bottom, true)
    }

    /// Horizontal visual left grid edge of a floating table placed by `place` in `(left, width)`.
    fn floating_table_x(
        &self,
        probe: &TableGrid,
        place: TablePlacement,
        (left, width, total): (Length, Length, Length),
        edge_rules: crate::mode::ModeRules,
    ) -> Length {
        if let Some(align) = place
            .x_align
            .map(|align| align.on_page(self.current_page_is_even()))
        {
            let base = match align {
                Align::Start | Align::Inside => left,
                Align::Center => left + (width - total).div_toward_zero(2),
                Align::End | Align::Outside => left + width - total,
            };
            base + probe.align_shift(align, true, edge_rules)
        } else {
            let offset = place.x.map_or(Length::ZERO, |x| {
                x - decisions::floating_table_shift_left(&self.context.quirks)
            });
            left + offset + probe.offset_shift(edge_rules)
        }
    }
}

/// The anchor across that a floating table counts from: in a table cell, the page and the
/// margin count as the cell's text column.
const fn across(anchor: Anchor, in_cell: bool) -> Anchor {
    if in_cell { Anchor::Text } else { anchor }
}