f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! Room for an outlined inline VML shape: a rectangle with an anchor lock, or on the targets
//! that say so each rectangle, oval and rounded rectangle.

use f_office_drawingml::shape::Geometry;
use f_office_units::Length;
use f_office_units::scale::LINE;

use crate::body::InlineDrawing;
use crate::layout::{Layout, decisions};
use crate::lines::{DrawingIndex, Line};
use crate::params;
use crate::props::LineSpacing;

use super::height::LineBox;
use super::height::holds_glyph_besides_white_space;

/// The room above and below the shape's bottom, and its twip-rounded painted height.
pub(super) struct Room {
    pub(super) above: Length,
    pub(super) below: Length,
    pub(super) height: Length,
}

impl Layout<'_> {
    /// The exact bottom of the single line's room, before multiple spacing.
    pub(super) fn anchor_bottom(
        &self,
        line: &Line,
        rule: LineSpacing,
        size: &LineBox,
    ) -> Option<Length> {
        self.anchor_line(line, rule).then(|| {
            self.y
                + size.ascent
                + size.descent
                + self.object_excess(line, rule, size.ascent, size.descent)
        })
    }

    /// Whether an outlined VML shape is placed from the bottom of its outline's room on this
    /// line: automatic spacing at least single, without a document grid, and without text
    /// (`VmlObjectSize::TakesAnchorStrokeRoom`) or with or without it (`TakesStrokeRoom`). On
    /// other lines it stands on the line as other drawings do.
    pub(super) fn anchor_line(&self, line: &Line, rule: LineSpacing) -> bool {
        decisions::anchor_stroke_room(&self.context.quirks, line).is_some_and(|line| {
            self.grid_pitch.is_none()
                && matches!(rule, LineSpacing::Auto(n) if n >= LINE)
                && (decisions::outline_stroke_room(&self.context.quirks, line).is_some()
                    || !holds_glyph_besides_white_space(line))
        })
    }

    /// The room down of the outlined VML shape at `index` ([`Self::stroke_weight`]). Other
    /// kinds of drawing keep the size of their style.
    pub(super) fn anchor_room(&self, index: DrawingIndex) -> Option<Room> {
        let drawing = self.output.drawing(index)?;
        let weight = self.stroke_weight(drawing)?;
        Some(stroke_room(drawing.height, weight))
    }

    /// The room that the outlined inline VML shape `drawing` takes on its line, across and
    /// down, where every outlined shape takes the room of its outline
    /// (`VmlObjectSize::TakesStrokeRoom`). `None` for other drawings and on other targets.
    pub(in crate::layout) fn outline_room(
        &self,
        drawing: &InlineDrawing,
    ) -> Option<(Length, Length)> {
        let drawing = decisions::outline_stroke_room(&self.context.quirks, drawing)?;
        let weight = self.stroke_weight(drawing)?;
        Some((
            stroke_side(drawing.width, weight),
            stroke_side(drawing.height, weight),
        ))
    }

    /// The weight of the outline of `drawing` where it takes the room of its outline: an
    /// empty VML rectangle with an anchor lock (`VmlObjectSize::TakesAnchorStrokeRoom`), or
    /// each empty VML rectangle, oval and rounded rectangle (`TakesStrokeRoom`), whose outline
    /// is wider than nothing.
    fn stroke_weight(&self, drawing: &InlineDrawing) -> Option<Length> {
        let quirks = &self.context.quirks;
        let drawing = decisions::anchor_stroke_room(quirks, drawing)?;
        let look = drawing.shape.look.as_ref()?;
        let shape = match decisions::outline_stroke_room(quirks, &look.geometry) {
            // A VML shape other than a horizontal rule drops on its line.
            Some(Geometry::Rect | Geometry::Ellipse | Geometry::RoundRect(_)) => drawing.drops,
            Some(_) => false,
            None => drawing.anchor_locked && look.geometry == Geometry::Rect,
        };
        if !shape || !drawing.shape.blocks.is_empty() {
            return None;
        }
        let (_, _, weight) = look.line(&self.shaper.theme().shapes)?;
        (weight > Length::ZERO).then_some(weight)
    }
}

/// The room of one side of an outlined shape, `size` long with an outline `weight` wide: the
/// half outline before the side and the side with the half outline after it, each in whole
/// dots, rounded up, after the side's rounding to twips ([`stroke_room`]).
fn stroke_side(size: Length, weight: Length) -> Length {
    let room = stroke_room(size, weight);
    room.above + room.below
}

/// First round the height to twips, then allocate the outline's bounds on a 96 dpi grid.
/// The minimum allocation weight is one dot; the painted outline keeps its declared weight.
fn stroke_room(height: Length, weight: Length) -> Room {
    let dot = Length::from_units(Length::UNITS_PER_INCH / params::VML_ANCHOR_DOTS_PER_INCH);
    let weight = weight.max(dot);
    let height = height.nearest_whole(Length::UNITS_PER_TWIP);
    // The whole dots that half of a length fills, rounded up.
    let half_dots = |length: Length| {
        let halves = dot.units() * 2;
        dot * ((length.units() + halves - 1) / halves)
    };
    Room {
        above: half_dots(weight),
        below: half_dots(height * 2 + weight),
        height,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::testing::{NORMAL, find, on_base, on_base_with, pass_with, shape_top};
    use crate::numbering::Numbering;
    use crate::quirks::VmlObjectSize;

    #[test]
    fn rounds_the_height_before_allocating_its_outline() {
        let length = |milli: i64| {
            Length::from_units(f_office_units::div_round(
                milli * Length::UNITS_PER_POINT,
                1_000,
            ))
        };
        for (height, weight, above, below, painted) in [
            (1_100, 100, 750, 1_500, 1_100),
            (1_300, 250, 750, 2_250, 1_300),
            (1_125, 750, 750, 2_250, 1_150),
            (1_524, 1_500, 750, 2_250, 1_500),
            (1_526, 1_500, 750, 3_000, 1_550),
            (19_400, 2_400, 1_500, 21_000, 19_400),
        ] {
            let room = stroke_room(length(height), length(weight));
            assert_eq!(
                (room.above, room.below, room.height),
                (length(above), length(below), length(painted))
            );
        }
    }

    #[test]
    fn gives_an_anchor_locked_vml_rectangle_room_for_its_outline() {
        let body = |lock: &str| {
            format!(
                r#"<w:p><w:pPr><w:spacing w:line="240" w:after="0"/></w:pPr><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word"><v:rect style="width:100pt;height:30pt" filled="f" strokeweight="2.4pt">{lock}</v:rect></w:pict></w:r></w:p><w:p><w:r><w:t>a</w:t></w:r></w:p>"#
            )
        };
        let plain = on_base();
        let with_room =
            on_base_with(|p| p.with_variant(crate::quirks::VmlObjectSize::TakesAnchorStrokeRoom));
        let pass = |lock: &str, target| {
            pass_with(
                &body(lock),
                (NORMAL, Some(15)),
                None,
                Numbering::default(),
                target,
            )
        };
        let lock = "<w10:anchorlock/>";
        let sized = pass(lock, plain);
        let stroked = pass(lock, with_room);
        // A 30 pt box with a 2.4 pt outline takes 1.5 + 31.5 pt, rather than 30 pt.
        let three_pt = 3 * Length::UNITS_PER_POINT;
        assert_eq!(
            (stroked.lines[0].height - sized.lines[0].height).units(),
            three_pt
        );
        assert_eq!(
            (stroked.lines[1].top - sized.lines[1].top).units(),
            three_pt
        );
        assert_eq!(
            shape_top(&stroked.list) - shape_top(&sized.list),
            three_pt / 2
        );
        // A rectangle without an anchor lock takes the same place and room on both targets.
        assert_eq!(pass("", plain).list, pass("", with_room).list);
    }

    #[test]
    fn gives_each_outlined_vml_shape_room_for_its_outline_across_and_down() {
        let body = |lock: &str| {
            format!(
                r#"<w:p><w:pPr><w:spacing w:line="240" w:after="0"/></w:pPr><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word"><v:rect style="width:100pt;height:30pt" filled="f" strokeweight="2.4pt">{lock}</v:rect></w:pict></w:r><w:r><w:t>b</w:t></w:r></w:p><w:p><w:r><w:t>a</w:t></w:r></w:p>"#
            )
        };
        let pass = |lock: &str, size| {
            pass_with(
                &body(lock),
                (NORMAL, Some(15)),
                None,
                Numbering::default(),
                on_base_with(|p| p.with_variant(size)),
            )
        };
        let sized = pass("", VmlObjectSize::TakesAnchorStrokeRoom);
        let stroked = pass("", VmlObjectSize::TakesStrokeRoom);
        // A 100 by 30 pt box with a 2.4 pt outline takes 1.5 + 101.25 pt across and
        // 1.5 + 31.5 pt down, also without an anchor lock and with text on its line.
        let points = |hundredths: i64| hundredths * Length::UNITS_PER_POINT / 100;
        assert_eq!(
            (stroked.lines[0].height - sized.lines[0].height).units(),
            points(300)
        );
        assert_eq!(
            find(&stroked.list, 'b').1 - find(&sized.list, 'b').1,
            points(275)
        );
        // It stands at the top left corner of its room, within the dot (0.12 pt) to which the
        // taller line's baseline rounds.
        let dot = points(12);
        assert!((shape_top(&stroked.list) - shape_top(&sized.list)).abs() <= dot);
        // With an anchor lock it stands half its outline lower, placed from the room's bottom.
        let locked = pass("<w10:anchorlock/>", VmlObjectSize::TakesStrokeRoom);
        assert_eq!(locked.lines[0].height, stroked.lines[0].height);
        let lower = shape_top(&locked.list) - shape_top(&stroked.list);
        assert!((lower - points(150)).abs() <= dot, "{lower}");
    }
}