f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
//! The device's decisions on how a paragraph reads its borders, where its border lines and its
//! fill land on the device's dots, what room the borders hold in the line boxes next to them,
//! how a page's borders are drawn, and what room an inline drawing takes on its line.

use f_office_units::Length;
use f_office_units::scale::LINE;

use super::{Device, LineRounding};
use crate::props::{Border, LineSpacing, ParaProps};
use crate::quirks::{
    BorderSpace, BorderTextEdge, BorderWidthUnit, BottomBorderParts, FillAtLines, InlineRoom,
    NoneBorders, PageBorderLines, SectionEndBorders, ThreeDBorders, TopBorderPlace,
};

impl Device {
    /// The room that a paragraph's top and bottom borders hold in the boxes of its first and
    /// last lines as space, under `BorderSpace::Held`: the top border's room `top`, and the
    /// bottom border's space and width, outside table cells (`in_cell`). Both are 0 otherwise.
    #[must_use]
    pub fn held_border_room(
        self,
        in_cell: bool,
        (top, bottom): (Length, Option<Border>),
    ) -> (Length, Length) {
        // quirk: BorderSpace::Held (src/quirks.rs)
        if self.quirks.border_space == BorderSpace::Held && !in_cell {
            (top, bottom.map_or(Length::ZERO, |b| b.space + b.width))
        } else {
            (Length::ZERO, Length::ZERO)
        }
    }

    /// The box of the line next to a paragraph's top or bottom border, `size`, when the border
    /// line lies from the rounded text edge: under `BorderTextEdge::Rounded`, on a paragraph of
    /// the line spacing `line` that is single or at least. `None` otherwise.
    #[must_use]
    pub fn text_edge_line<T>(self, line: LineSpacing, size: Option<T>) -> Option<T> {
        // quirk: BorderTextEdge::Rounded (src/quirks.rs)
        let rounded = self.quirks.border_text_edge == BorderTextEdge::Rounded
            && matches!(line, LineSpacing::Auto(LINE) | LineSpacing::AtLeast(_));
        size.filter(|_| rounded)
    }

    /// The top of a paragraph's top border `border` as its stacked lines are drawn, under
    /// `TopBorderPlace::FromContentStart`, from the place `y` before it: the place after the
    /// border's width and space rounded up to a dot, less the lines and gaps as drawn, `parts`,
    /// and the border's space rounded down to a dot. `None` under the other variant.
    #[must_use]
    pub fn content_start_top(self, y: Length, border: Border, parts: &[Length]) -> Option<Length> {
        // quirk: TopBorderPlace::FromContentStart (src/quirks.rs)
        if self.quirks.top_border_place != TopBorderPlace::FromContentStart {
            return None;
        }
        let room = parts.iter().copied().sum::<Length>() + self.floor(border.space);
        Some(self.ceil(y + border.width + border.space) - room)
    }

    /// The top of a paragraph's bottom border of `parts` lines and gaps when its lines are
    /// stacked down from the place `y` after its space, under `BottomBorderParts::Stacked`:
    /// that place rounded to the nearest dot, for a border of more than one line. `None` for a
    /// border of one line and under the other variant.
    #[must_use]
    pub fn stacked_bottom_top(self, y: Length, parts: usize) -> Option<Length> {
        // quirk: BottomBorderParts::Stacked (src/quirks.rs)
        (parts > 1 && self.quirks.bottom_border_parts == BottomBorderParts::Stacked)
            .then(|| self.snap(y))
    }

    /// The edge where a shaded paragraph's fill stops next to its own top or bottom border
    /// line, whose edge on the text's side as drawn is `inner`: that edge under
    /// `FillAtLines::Inside`, in the body outside table cells (`in_body`). `None` otherwise,
    /// where the fill runs under the line.
    #[must_use]
    pub fn fill_edge(self, inner: Length, in_body: bool) -> Option<Length> {
        // quirk: FillAtLines::Inside (src/quirks.rs)
        (self.quirks.fill_at_lines == FillAtLines::Inside && in_body).then_some(inner)
    }

    /// Gives a paragraph's resolved borders `props` the device's rules for them.
    pub fn read_paragraph_borders(self, props: &mut ParaProps) {
        // A device that drops a border of `none` reads none of its space.
        // quirk: NoneBorders::Dropped (src/quirks.rs)
        if self.quirks.none_borders == NoneBorders::Dropped {
            props.drop_none_borders();
        }
        // A device that holds the width of a paragraph's border in whole twips cuts each
        // side's line to them before it takes its lines and gaps from it.
        // quirk: BorderWidthUnit::WholeTwips (src/quirks.rs)
        if self.quirks.border_width_unit == BorderWidthUnit::WholeTwips {
            props.cut_border_widths();
        }
        // A device that draws a side of a 3-D style as one line draws it as a `single` line.
        // quirk: ThreeDBorders::OneLine (src/quirks.rs)
        if self.quirks.three_d_borders == ThreeDBorders::OneLine {
            props.draw_three_d_borders_as_lines();
        }
        // A device that draws no border for the empty paragraph that ends a section before a
        // new page leaves that paragraph without one.
        // quirk: SectionEndBorders::Dropped (src/quirks.rs)
        if props.flags().section_end
            && self.quirks.section_end_borders == SectionEndBorders::Dropped
        {
            props.drop_borders();
        }
    }

    /// The thickness of a line of a page border `width` thick as the device draws it: on whole
    /// dots, at least one, rounded to the nearest dot under `PageBorderLines::Nearest` and down
    /// under `Down`.
    #[must_use]
    pub fn page_border_line(self, width: Length) -> Length {
        // quirk: PageBorderLines (src/quirks.rs), whose variant the device carries.
        let rounding = match self.quirks.page_border_lines {
            PageBorderLines::Nearest => LineRounding::Nearest,
            PageBorderLines::Down => LineRounding::Down,
        };
        self.line_thickness(width, rounding)
    }

    /// The lines of a page border's side `border` on the device, each as its offset from the
    /// side's top or left edge and its thickness, for a side `width` wide on the device whose
    /// outer edge is its top or left when `outer_first`. Under `PageBorderLines::Nearest` each
    /// line lies at its exact offset on the nearest dot, as thick as
    /// [`Self::page_border_line`] makes it. Under `Down` every part, each line and each gap, is
    /// rounded down to whole dots, at least one, as a paragraph border's parts are, and the
    /// parts lie one after the other from the side's outer edge.
    #[must_use]
    pub fn page_border_lines(
        self,
        border: Border,
        width: Length,
        outer_first: bool,
    ) -> Vec<(Length, Length)> {
        match self.quirks.page_border_lines {
            PageBorderLines::Nearest => border
                .lines()
                .into_iter()
                .map(|(offset, thickness)| (self.snap(offset), self.page_border_line(thickness)))
                .collect(),
            // quirk: PageBorderLines::Down (src/quirks.rs)
            PageBorderLines::Down => {
                let parts: Vec<Length> = border
                    .parts
                    .sizes()
                    .iter()
                    .map(|size| self.line_thickness(*size, LineRounding::Down))
                    .collect();
                let stacked: Length = parts.iter().copied().sum();
                let start = if outer_first {
                    Length::ZERO
                } else {
                    width - stacked
                };
                parts
                    .iter()
                    .scan(start, |at, size| {
                        let line = (*at, *size);
                        *at += *size;
                        Some(line)
                    })
                    .step_by(2)
                    .collect()
            }
        }
    }

    /// A side `border` of a page's borders as the device draws it: a side of a 3-D style as one
    /// line of its width, a `single` line, under `ThreeDBorders::OneLine`
    /// ([`Border::as_one_line`]); every side as it is under `Bands`.
    #[must_use]
    pub fn drawn_border(self, border: Border) -> Border {
        // quirk: ThreeDBorders::OneLine (src/quirks.rs)
        match self.quirks.three_d_borders {
            ThreeDBorders::OneLine => border.as_one_line(),
            ThreeDBorders::Bands => border,
        }
    }

    /// The height that an inline object of `height` takes on its line: under
    /// `InlineRoom::WholeTwips`, a drawing with a DrawingML extent of the height `extent` takes
    /// the extent in whole twips, cut toward zero, and the rest of its height, the effect
    /// extent above and below it, as it is; else the height as it is.
    #[must_use]
    pub fn inline_room_height(self, height: Length, extent: Option<Length>) -> Length {
        match (self.quirks.inline_room, extent) {
            // quirk: InlineRoom::WholeTwips (src/quirks.rs)
            (InlineRoom::WholeTwips, Some(extent)) => {
                let whole = extent.toward_zero_whole(Length::UNITS_PER_TWIP);
                (height - (extent - whole)).max(Length::ZERO)
            }
            (InlineRoom::Exact | InlineRoom::WholeTwips, _) => height,
        }
    }
}