f-office-docx 0.2.3

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};
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 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);
        if place.vertical == Anchor::Text && room < NARROWEST_WRAP {
            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 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;
        // 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.
        let offset = place.y_align.map_or(place.y, |_| Length::ZERO);
        let aligned = place.y_align.filter(|_| place.vertical != Anchor::Text);
        let top = 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(&mut shape, (Paging::Whole, None));
                let height = self.y;
                self.rewind(&mark);
                self.column = Column {
                    left: outer_left + x - start,
                    ..outer.clone()
                };
                if align == Align::Center {
                    anchor + (room - height).div_toward_zero(2)
                } else {
                    anchor + room - height
                }
            }
        };
        // The text after the table keeps the space after the paragraph before it, which the
        // table's own paragraphs do not replace.
        let previous = self.previous.clone();
        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 (top, bottom) = self.placed_rows(&mut shape, (top, flow), outer);
        self.table_prev_style = outer_table_prev;
        self.previous = 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));
        // The text flows on both sides of a floating table where there is room.
        self.squares.push(Square {
            top: top - above,
            bottom: bottom + below,
            left: x - before,
            right: x + total + after,
            below: bottom + below,
            sides: Some(WrapSides::Both),
            line_steps: false,
            outline: None,
            narrowest: NARROWEST_WRAP,
            start_past: StartPastWrap::Whole,
        });
        self.release_parts(held);
    }

    /// 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;
        }
        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,
    ) -> (Length, Length) {
        let breaks = decisions::floating_breaks(&self.context.quirks, || {
            self.story.is_none() && outer.cell.is_none()
        })
        .unwrap_or(false);
        let paging = match (
            breaks,
            self.settings.mode_rules.fits_floating_rows_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);
        }
        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)
    }

    /// 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 }
}