f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! The letters of a line of text that fills its box, a VML text path such as a watermark's.

use f_office_drawingml::shape::turned_clockwise;
use f_office_paint::{FillRule, Item, PathCommand, PathItem, Point, Rgb};
use f_office_units::scale::QUARTER_TURN;
use f_office_units::{Edges, Length};

use crate::OutlineCommand;

/// One letter of the line: its advance and its outline, in whole font units.
pub(super) struct Letter {
    /// The letter's advance without kerning.
    pub(super) advance: u16,
    /// The letter's outline, with y growing upwards from the baseline.
    pub(super) outline: Vec<OutlineCommand>,
}

/// The measures of the face that place the line, in font units: its em and its descent below
/// the baseline.
#[derive(Clone, Copy)]
pub(super) struct Em {
    pub(super) units_per_em: u16,
    pub(super) descent: u16,
}

/// The filled paths of `letters`, one for each letter with an outline, in `color`, as the line
/// fills its box `frame` turned clockwise by `rotation`, in 60,000ths of a degree, about the
/// box's center. The line's advances, without kerning, stretch across the whole width of the
/// box, and its em is as tall as the box, with the baseline `em`'s descent above the box's
/// bottom. `None` when a point lands beyond the range of a length.
pub(super) fn letter_items(
    letters: &[Letter],
    em: Em,
    frame: Edges<Length>,
    (rotation, color): (i64, Rgb),
) -> Option<Vec<Item>> {
    let total: i64 = letters.iter().map(|letter| i64::from(letter.advance)).sum();
    let units_per_em = i64::from(em.units_per_em);
    if total == 0 || units_per_em == 0 {
        return Some(Vec::new());
    }
    let (left, top, right, bottom) = (
        frame.left.units(),
        frame.top.units(),
        frame.right.units(),
        frame.bottom.units(),
    );
    let (width, height) = (i128::from(right - left), i128::from(bottom - top));
    let center = [left + (right - left) / 2, top + (bottom - top) / 2];
    let mut items = Vec::new();
    let mut pen = 0;
    for letter in letters {
        let place = |[u, v]: [i32; 2]| -> Option<Point> {
            let across = i128::from(pen) + i128::from(u);
            let up = i128::from(em.descent) + i128::from(v);
            let x = i128::from(left) + f_office_units::div_round_i128(across * width, total.into());
            let y = i128::from(bottom)
                - f_office_units::div_round_i128(up * height, units_per_em.into());
            let [x, y] = turned_clockwise(
                [i64::try_from(x).ok()?, i64::try_from(y).ok()?],
                center,
                rotation,
            )?;
            Some(Point {
                x: Length::from_units(x),
                y: Length::from_units(y),
            })
        };
        let commands = letter
            .outline
            .iter()
            .map(|command| {
                Some(match *command {
                    OutlineCommand::MoveTo(p) => PathCommand::MoveTo(place(p)?),
                    OutlineCommand::LineTo(p) => PathCommand::LineTo(place(p)?),
                    OutlineCommand::QuadTo(c, p) => PathCommand::QuadTo(place(c)?, place(p)?),
                    OutlineCommand::CubicTo(c, d, p) => {
                        PathCommand::CubicTo(place(c)?, place(d)?, place(p)?)
                    }
                    OutlineCommand::Close => PathCommand::Close,
                })
            })
            .collect::<Option<Vec<_>>>()?;
        if !commands.is_empty() {
            items.push(Item::Path(PathItem {
                commands,
                color,
                fill_rule: FillRule::NonZero,
            }));
        }
        pen += i64::from(letter.advance);
    }
    Some(items)
}

/// How far the box that an alignment of the line aligns reaches past the shape's box `frame`
/// on each side, in place of the shape's effect extent: the box that holds both the line's
/// letters `items`, as [`letter_items`] turns them by `rotation`, and `frame` turned by the
/// nearest whole quarter turn of `rotation`, a half to the next turn, so that its width and
/// height swap from 45 degrees up to 135 and from 225 degrees up to 315. A side of that box
/// inside the frame reaches a negative length. The letters count by their ink: a quadratic
/// curve by its furthest point, and a cubic curve by its control points, which hold it.
pub(super) fn aligned_extents(
    items: &[Item],
    frame: Edges<Length>,
    rotation: i64,
) -> Edges<Length> {
    let (left, top, right, bottom) = (
        frame.left.units(),
        frame.top.units(),
        frame.right.units(),
        frame.bottom.units(),
    );
    let center = [left + (right - left) / 2, top + (bottom - top) / 2];
    let (width, height) = (right - left, bottom - top);
    let (across, down) = if swaps_sides(rotation) {
        (height, width)
    } else {
        (width, height)
    };
    let mut ink = Ink {
        left: center[0] - across / 2,
        top: center[1] - down / 2,
        right: center[0] - across / 2 + across,
        bottom: center[1] - down / 2 + down,
    };
    for item in items {
        let Item::Path(path) = item else {
            continue;
        };
        let mut at = None;
        for command in &path.commands {
            if let PathCommand::QuadTo(control, end) = *command {
                // A quadratic curve counts by its ends and its furthest point, not its control.
                if let Some(start) = at {
                    ink.take_curve(start, control, end);
                }
                ink.take(end);
                at = Some(end);
                continue;
            }
            for point in command.points() {
                ink.take(point);
                at = Some(point);
            }
        }
    }
    Edges {
        left: Length::from_units(left - ink.left),
        top: Length::from_units(top - ink.top),
        right: Length::from_units(ink.right - right),
        bottom: Length::from_units(ink.bottom - bottom),
    }
}

/// Whether the nearest whole quarter turn of `rotation`, in 60,000ths of a degree, a half to the
/// next turn, is an odd one, which swaps a box's width and height.
const fn swaps_sides(rotation: i64) -> bool {
    (rotation.rem_euclid(2 * QUARTER_TURN) + QUARTER_TURN / 2) / QUARTER_TURN == 1
}

/// The box of the ink found so far, in half-EMUs.
struct Ink {
    left: i64,
    top: i64,
    right: i64,
    bottom: i64,
}

impl Ink {
    /// Takes the point `point`.
    fn take(&mut self, point: Point) {
        let (x, y) = (point.x.units(), point.y.units());
        self.left = self.left.min(x);
        self.right = self.right.max(x);
        self.top = self.top.min(y);
        self.bottom = self.bottom.max(y);
    }

    /// Takes the furthest point along each axis of the quadratic curve from `start` through
    /// `control` to `end`, where it lies between the ends.
    fn take_curve(&mut self, start: Point, control: Point, end: Point) {
        if let Some(x) = curve_extreme([start.x.units(), control.x.units(), end.x.units()]) {
            self.left = self.left.min(x);
            self.right = self.right.max(x);
        }
        if let Some(y) = curve_extreme([start.y.units(), control.y.units(), end.y.units()]) {
            self.top = self.top.min(y);
            self.bottom = self.bottom.max(y);
        }
    }
}

/// The value at the turning point of the quadratic curve through `[p0, p1, p2]` along one axis,
/// to the nearest half-EMU, where that point lies strictly between the ends; `None` where the
/// curve turns at no point between them.
pub(super) fn curve_extreme([p0, p1, p2]: [i64; 3]) -> Option<i64> {
    let (p0, p1, p2) = (i128::from(p0), i128::from(p1), i128::from(p2));
    let bend = p0 - 2 * p1 + p2;
    let lead = p0 - p1;
    // The curve turns at t = lead / bend, which lies strictly between 0 and 1.
    let inside = (bend > 0 && 0 < lead && lead < bend) || (bend < 0 && bend < lead && lead < 0);
    if !inside {
        return None;
    }
    // There it reaches (p0 p2 - p1^2) / bend, rounded with a positive divisor.
    let (reach, bend) = if bend < 0 {
        (p1 * p1 - p0 * p2, -bend)
    } else {
        (p0 * p2 - p1 * p1, bend)
    };
    i64::try_from(f_office_units::div_round_i128(reach, bend)).ok()
}

#[cfg(test)]
mod tests {
    use super::{Em, Letter, aligned_extents, curve_extreme, letter_items, swaps_sides};
    use crate::OutlineCommand;
    use f_office_paint::{Item, PathCommand, Point, Rgb};
    use f_office_units::scale::QUARTER_TURN;
    use f_office_units::{Edges, Length};

    /// Two letters, each a square of 100 font units on the baseline, with an advance of 200.
    fn squares() -> Vec<Letter> {
        let square = vec![
            OutlineCommand::MoveTo([0, 0]),
            OutlineCommand::LineTo([100, 0]),
            OutlineCommand::LineTo([100, 100]),
            OutlineCommand::Close,
        ];
        (0..2)
            .map(|_| Letter {
                advance: 200,
                outline: square.clone(),
            })
            .collect()
    }

    /// The points of each path of `items`, in points.
    fn points(items: &[Item]) -> Vec<Vec<(i64, i64)>> {
        let point = |p: Point| (p.x.units() / 25_400, p.y.units() / 25_400);
        items
            .iter()
            .map(|item| match item {
                Item::Path(path) => path
                    .commands
                    .iter()
                    .flat_map(PathCommand::points)
                    .map(point)
                    .collect(),
                _ => Vec::new(),
            })
            .collect()
    }

    fn frame() -> Edges<Length> {
        let pt = |points: i64| Length::from_units(points * 25_400);
        Edges {
            left: pt(100),
            top: pt(200),
            right: pt(500),
            bottom: pt(300),
        }
    }

    #[test]
    fn stretches_the_advances_across_the_box_and_the_em_to_its_height() {
        // An em of 1,000 units in a box 100 pt tall: 1 unit is 0.1 pt down, and the advances
        // of 400 units fill 400 pt, 1 pt each. The baseline lies 200 units, 20 pt, above the
        // box's bottom.
        let em = Em {
            units_per_em: 1_000,
            descent: 200,
        };
        let items = letter_items(&squares(), em, frame(), (0, Rgb::BLACK));
        assert_eq!(
            points(&items.unwrap_or_default()),
            [
                vec![(100, 280), (200, 280), (200, 270)],
                vec![(300, 280), (400, 280), (400, 270)],
            ]
        );
    }

    #[test]
    fn turns_the_line_clockwise_about_the_center_of_the_box() {
        let em = Em {
            units_per_em: 1_000,
            descent: 200,
        };
        // The box's center is (300, 250); a quarter turn clockwise takes (100, 280) to (270, 50).
        let items = letter_items(&squares(), em, frame(), (QUARTER_TURN, Rgb::BLACK));
        let points = points(&items.unwrap_or_default());
        assert_eq!(points[0][0], (270, 50));
        assert_eq!(points[1][1], (270, 350));
    }

    /// The extents of `edges` in whole points: left, top, right and bottom.
    fn in_points(edges: Edges<Length>) -> [i64; 4] {
        [edges.left, edges.top, edges.right, edges.bottom].map(|side| side.units() / 25_400)
    }

    #[test]
    fn aligns_a_line_inside_its_box_by_the_box() {
        let em = Em {
            units_per_em: 1_000,
            descent: 200,
        };
        let items = letter_items(&squares(), em, frame(), (0, Rgb::BLACK)).unwrap_or_default();
        assert_eq!(in_points(aligned_extents(&items, frame(), 0)), [0, 0, 0, 0]);
        // A letter 1,100 units tall reaches 30 pt above the box.
        let tall = [Letter {
            advance: 200,
            outline: vec![
                OutlineCommand::MoveTo([0, 0]),
                OutlineCommand::LineTo([0, 1_100]),
                OutlineCommand::Close,
            ],
        }];
        let items = letter_items(&tall, em, frame(), (0, Rgb::BLACK)).unwrap_or_default();
        assert_eq!(
            in_points(aligned_extents(&items, frame(), 0)),
            [0, 30, 0, 0]
        );
        // An arch whose control point lies 2,300 units up reaches 1,150 units, 135 pt above
        // the box's bottom with the descent: 35 pt above the box, not the control's 150.
        let arch = [Letter {
            advance: 200,
            outline: vec![
                OutlineCommand::MoveTo([0, 0]),
                OutlineCommand::QuadTo([50, 2_300], [100, 0]),
                OutlineCommand::Close,
            ],
        }];
        let items = letter_items(&arch, em, frame(), (0, Rgb::BLACK)).unwrap_or_default();
        assert_eq!(
            in_points(aligned_extents(&items, frame(), 0)),
            [0, 35, 0, 0]
        );
    }

    #[test]
    fn swaps_the_box_from_the_nearest_odd_quarter_turn() {
        let em = Em {
            units_per_em: 1_000,
            descent: 200,
        };
        // Turned by a quarter turn, the 400 by 100 pt box aligns as 100 by 400 pt about its
        // center, and the letters lie inside that.
        let items = letter_items(&squares(), em, frame(), (QUARTER_TURN, Rgb::BLACK));
        let extents = aligned_extents(&items.unwrap_or_default(), frame(), QUARTER_TURN);
        assert_eq!(in_points(extents), [-150, 150, -150, 150]);
        let degrees = |degrees: i64| swaps_sides(degrees * QUARTER_TURN / 90);
        assert_eq!(
            [44, 45, 134, 135, 224, 225, 314, 315, -45, -46].map(degrees),
            [
                false, true, true, false, false, true, true, false, false, true
            ]
        );
    }

    #[test]
    fn counts_a_quadratic_curve_by_its_furthest_point() {
        assert_eq!(curve_extreme([0, 10, 0]), Some(5));
        assert_eq!(curve_extreme([10, -10, 10]), Some(0));
        // It reaches 120 / 9 at two thirds of the way.
        assert_eq!(curve_extreme([0, 20, 10]), Some(13));
        // A curve that turns at no point between its ends.
        assert_eq!(curve_extreme([0, 5, 10]), None);
        assert_eq!(curve_extreme([0, 8, 10]), None);
    }
}