f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
use f_office_paint::{
    Group, GroupPlaces, ImageFormat, Item, Opacity, PathCommand, Point, Rgb, Turn,
};
use f_office_units::Length;

use super::{DevicePlace, at, item};
use crate::text::{DrawnShadow, Face, ShadowForm};
use crate::{ChosenFace, FaceMetrics, FamilyName, Fonts, OutlineCommand, OutlineError};

/// A font whose glyph 1 is a square of 500 units from the origin up and right, whose glyph 2
/// has no outline, and whose em is 1,000 units.
struct Squares;

impl Fonts for Squares {
    fn face(&self, _: &FamilyName, _: bool, _: bool) -> Option<ChosenFace> {
        None
    }

    fn glyph(&self, _: f_office_fonts::FontId, _: char) -> Option<u32> {
        None
    }

    fn advance(&self, _: f_office_fonts::FontId, _: u32) -> Option<u16> {
        None
    }

    fn outline(
        &self,
        _: f_office_fonts::FontId,
        glyph: u32,
    ) -> Result<Vec<OutlineCommand>, OutlineError> {
        match glyph {
            1 => Ok(vec![
                OutlineCommand::MoveTo([0, 0]),
                OutlineCommand::LineTo([500, 0]),
                OutlineCommand::LineTo([500, 500]),
                OutlineCommand::LineTo([0, 500]),
                OutlineCommand::Close,
            ]),
            _ => Err(OutlineError::NoOutlines),
        }
    }
}

fn units(value: i64) -> Length {
    Length::from_units(value)
}

fn face() -> Face {
    Face {
        font: f_office_fonts::FontId::from_index(0),
        metrics: FaceMetrics {
            units_per_em: 1_000,
            ..FaceMetrics::default()
        },
        size: units(10_000),
        line_size: units(10_000),
        single_line: crate::text::SingleLine::of(crate::quirks::LineHeight::TakesHheaLine),
        color: Rgb::BLACK,
        lines: crate::text::RunLines::default(),
        background: None,
        rise: Length::ZERO,
        raised: Length::ZERO,
        math: crate::text::MathFace::default(),
        outline: None,
        text_fill: crate::text::DrawnTextFill::Solid,
        effect: false,
        shadow_room: crate::text::ShadowRoom::default(),
        shadow: None,
        glow: None,
        reflection: None,
        relief: None,
        kerned: false,
        east_asian_script: None,
        ligatures: false,
        scale: None,
        border: crate::text::RunBorder::None,
        standing: crate::text::Standing::default(),
    }
}

fn point(x: i64, y: i64) -> Point {
    Point {
        x: units(x),
        y: units(y),
    }
}

#[test]
fn places_an_outline_point_at_the_size_down_the_page_and_turned() {
    // 10,000 units over an em of 1,000: a unit of the font is 10 units of length, and y grows
    // up in the font and down on the page.
    let origin = (units(1_000), units(2_000));
    assert_eq!(
        at([100, 50], origin, (10_000, 1_000), None),
        point(2_000, 1_500)
    );
    // Half again as wide across, and leaning: a step down goes a quarter of it right.
    let turn = Turn {
        xx: 1_500_000,
        yx: 0,
        xy: 250_000,
        yy: 1_000_000,
    };
    assert_eq!(
        at([100, -40], origin, (10_000, 1_000), Some(turn)),
        point(2_600, 2_400)
    );
}

#[test]
fn draws_the_glyphs_moved_by_the_offset_as_one_path_that_the_writer_leaves_in_place() {
    let shadow = DrawnShadow {
        across: units(30),
        down: units(-20),
        color: Rgb {
            r: 68,
            g: 114,
            b: 196,
        },
        form: ShadowForm::Paths,
    };
    let places = [
        DevicePlace {
            glyph: 1,
            x: units(0),
            y: units(10_000),
        },
        DevicePlace {
            glyph: 2,
            x: units(5_000),
            y: units(10_000),
        },
        DevicePlace {
            glyph: 1,
            x: units(6_000),
            y: units(10_000),
        },
    ];
    let face = face();
    let drawn = item((&Squares, &face, units(10_000), None), shadow, &places);
    let Some(Item::Group(Group {
        items,
        clip: None,
        places: GroupPlaces::Own,
    })) = drawn
    else {
        panic!("one group of the shadow's own places: {drawn:?}");
    };
    let [Item::Path(path)] = items.as_slice() else {
        panic!("one path: {items:?}");
    };
    assert_eq!(path.color, shadow.color);
    // Two squares of 5,000 units, each moved 30 right and 20 up; the glyph without an outline
    // draws nothing.
    let starts: Vec<Point> = (path.commands.iter())
        .filter_map(|command| match *command {
            PathCommand::MoveTo(p) => Some(p),
            _ => None,
        })
        .collect();
    assert_eq!(starts, [point(30, 9_980), point(6_030, 9_980)]);
    assert!(
        path.commands
            .contains(&PathCommand::LineTo(point(5_030, 4_980)))
    );
    // No glyph draws, no path.
    let none = [DevicePlace {
        glyph: 2,
        x: Length::ZERO,
        y: Length::ZERO,
    }];
    assert_eq!(
        item((&Squares, &face, units(10_000), None), shadow, &none),
        None
    );
}

#[test]
fn draws_an_outlined_run_shadow_as_an_effect_picture() {
    let shadow = DrawnShadow {
        across: Length::from_points(1).unwrap(),
        down: Length::from_points(1).unwrap(),
        color: Rgb {
            r: 68,
            g: 114,
            b: 196,
        },
        form: ShadowForm::Picture {
            blur: Length::ZERO,
            opacity: Opacity::FULL,
            outline_width: Length::from_points(1).unwrap(),
        },
    };
    let size = Length::from_points(20).unwrap();
    let places = [DevicePlace {
        glyph: 1,
        x: Length::from_points(72).unwrap(),
        y: Length::from_points(90).unwrap(),
    }];
    let face = face();
    let Some(Item::Image(image)) = item((&Squares, &face, size, None), shadow, &places) else {
        panic!("expected an effect picture image item");
    };
    assert_eq!(image.image.format, ImageFormat::EffectPicture);
    // Square glyph of 10 x 10 pt at (72, 80) to (82, 90), moved (+1, +1) -> (73, 81) to (83, 91),
    // grown by half the 1 pt line -> (72.5, 80.5) to (83.5, 91.5), rounded to 0.12 pt ->
    // (72.48, 80.52) to (83.52, 91.56), grown by 0.12 pt -> (72.36, 80.40) to (83.64, 91.68).
    let pts = |l: Length| l.units() * 100 / Length::UNITS_PER_POINT;
    assert_eq!(
        [
            pts(image.x),
            pts(image.y),
            pts(image.x + image.width),
            pts(image.y + image.height),
        ],
        [7_236, 8_040, 8_364, 9_168]
    );
    let drawn = f_office_effects::draw(&image.image.load_bytes().unwrap(), u64::MAX).unwrap();
    assert_eq!((drawn.width, drawn.height), (31, 31));
    // Center pixel is fully opaque in the shadow color.
    let mid = ((15 * 31 + 15) * 4) as usize;
    assert_eq!(&drawn.pixels[mid..mid + 4], &[68, 114, 196, 255]);
}