f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
use super::*;
use f_office_paint::Rgb;

/// A length of `hundredths` hundredths of a point.
fn hundredths(hundredths: i64) -> Length {
    Length::from_units(hundredths * Length::UNITS_PER_POINT / 100)
}

/// The filled rectangle of 144 × 72 pt at 144 pt from the page's left and top edges.
fn shape() -> Vec<Item> {
    vec![Item::Path(PathItem {
        commands: vec![
            PathCommand::MoveTo(Point {
                x: hundredths(14_400),
                y: hundredths(14_400),
            }),
            PathCommand::LineTo(Point {
                x: hundredths(28_800),
                y: hundredths(14_400),
            }),
            PathCommand::LineTo(Point {
                x: hundredths(28_800),
                y: hundredths(21_600),
            }),
            PathCommand::LineTo(Point {
                x: hundredths(14_400),
                y: hundredths(21_600),
            }),
            PathCommand::Close,
        ],
        color: Rgb {
            r: 68,
            g: 114,
            b: 196,
        },
        fill_rule: FillRule::NonZero,
    })]
}

/// The offset of a shadow 3 pt away at 45 degrees, each part rounded.
fn offset() -> ShadowOffset {
    let part = Length::from_units(53_882);
    ShadowOffset {
        across: part,
        down: part,
    }
}

/// Black at the opacity of `alpha` 1,000ths of a percent.
fn black(alpha: i64) -> ShadowColor {
    ShadowColor {
        rgb: BLACK,
        opacity: Opacity::clamped(alpha),
    }
}

/// The box in hundredths of a point and the pixels of the one picture of `items`.
fn picture(items: &[Item]) -> ([i64; 4], (u32, u32), Vec<u8>) {
    let [Item::Image(image)] = items else {
        panic!("not one picture: {items:?}");
    };
    assert_eq!(image.image.format, ImageFormat::EffectPicture);
    let at = |length: Length| length.units() * 100 / Length::UNITS_PER_POINT;
    let drawn = f_office_effects::draw(&image.image.load_bytes().unwrap(), u64::MAX).unwrap();
    (
        [
            at(image.x),
            at(image.y),
            at(image.x + image.width),
            at(image.y + image.height),
        ],
        (drawn.width, drawn.height),
        drawn.pixels,
    )
}

const BLACK: Rgb = Rgb { r: 0, g: 0, b: 0 };

#[test]
fn places_a_blurred_shadow_in_the_box_and_pixels_of_word_s() {
    // Word's shadows of a rectangle of 144 x 72 pt at 144 pt: the box of a radius of 0.5 pt,
    // 145.44 to 290.88 pt across, at 200 pixels per inch, and of 23 pt, at 25 pixels per inch.
    let color = black(43_000);
    let small = items(hundredths(50), offset(), color, &shape()).unwrap();
    let (frame, size, pixels) = picture(&small);
    assert_eq!(frame, [14_544, 14_544, 29_088, 21_888]);
    assert_eq!(size, (404, 204));
    // In the middle the shadow covers its pixel fully: 255 times 43%, rounded.
    let middle = ((102 * 404 + 202) * 4 + 3) as usize;
    assert_eq!(pixels[middle], 110);
    assert_eq!(pixels[3], 0);
    let large = items(hundredths(2_300), offset(), color, &shape()).unwrap();
    let (frame, size, _) = picture(&large);
    assert_eq!(frame, [12_300, 12_300, 31_332, 24_132]);
    assert_eq!(size, (66, 41));
}

#[test]
fn takes_fewer_pixels_for_each_inch_as_the_blur_spans_more() {
    // Radii of 2.5, 3, 6, 10 and 16 pt at 200 / 1, 2, 3, 4 and 6 pixels per inch: the blur
    // spans at most 8 pixels.
    for (radius, parts) in [(250, 1), (300, 2), (600, 3), (1_000, 4), (1_600, 6)] {
        assert_eq!(blur_parts(hundredths(radius)), parts, "{radius}");
    }
}

#[test]
fn draws_a_sharp_shadow_below_opaque_as_a_picture_and_an_opaque_one_as_paths() {
    let sharp = items(Length::ZERO, offset(), black(50_000), &shape()).unwrap();
    let (frame, size, _) = picture(&sharp);
    assert_eq!(frame, [14_604, 14_604, 29_028, 21_828]);
    assert_eq!(size, (401, 201));
    let opaque = items(Length::ZERO, offset(), black(100_000), &shape()).unwrap();
    let [Item::Path(path)] = opaque.as_slice() else {
        panic!("not one path: {opaque:?}");
    };
    assert_eq!(path.color, BLACK);
    assert_eq!(
        path.commands.first(),
        Some(&PathCommand::MoveTo(Point {
            x: hundredths(14_400) + offset().across,
            y: hundredths(14_400) + offset().down,
        }))
    );
}

#[test]
fn casts_nothing_from_a_shape_without_filled_items() {
    assert_eq!(items(hundredths(400), offset(), black(100_000), &[]), None);
}

/// The bytes of a PNG file of 192 by 96 pixels with the color type `color_type` up to its
/// header, which is all that the layout reads of it.
fn png_header(color_type: u8) -> Vec<u8> {
    let mut file = b"\x89PNG\r\n\x1a\n".to_vec();
    file.extend_from_slice(&13_u32.to_be_bytes());
    file.extend_from_slice(b"IHDR");
    file.extend_from_slice(&192_u32.to_be_bytes());
    file.extend_from_slice(&96_u32.to_be_bytes());
    file.extend_from_slice(&[8, color_type, 0, 0, 0, 0, 0, 0, 0]);
    file
}

/// A picture of 72 by 36 pt of the file `file`, cropped by `crop`, with a black line of 3 pt
/// and an outer shadow with a blur radius of 4 pt, 3 pt away at 45 degrees, black at an alpha
/// of 43%.
fn shadowed_picture(file: Vec<u8>, crop: Edges<i64>) -> crate::picture::Picture {
    use crate::ns::A;
    use f_office_xml::{Document, Limits};
    let props = format!(
        r#"<a:spPr xmlns:a="{A}"><a:prstGeom prst="rect"/><a:ln w="38100"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln><a:effectLst><a:outerShdw blurRad="50800" dist="38100" dir="2700000" algn="tl" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="43000"/></a:srgbClr></a:outerShdw></a:effectLst></a:spPr>"#
    );
    let doc = Document::parse(props.as_bytes(), &Limits::default()).unwrap();
    let mut warnings = f_office_warnings::Warnings::new();
    let look =
        f_office_drawingml::shape::picture_properties(&doc, doc.root().unwrap(), &mut warnings);
    let point = |points: i64| Length::from_units(points * Length::UNITS_PER_POINT);
    let mut picture =
        crate::picture::Picture::new("rId1", Edges::sized(point(72), point(36)), crop);
    picture.image = Some(f_office_paint::Image::new(file));
    picture.line = look.line.map(Box::new);
    picture.shadow = look.shadow.map(|shadow| {
        Box::new(crate::picture::PictureShadow {
            shadow,
            part: f_office_warnings::Name::new("word/document.xml"),
        })
    });
    picture
}

/// The items of `picture` at the page's top left corner, with its line outside its box, on a
/// target whose `PictureShadows` is `shadows`, and whether the layout warned of a shadow that it
/// left out.
fn laid_picture(
    shadows: crate::quirks::PictureShadows,
    picture: &crate::picture::Picture,
) -> (Vec<Item>, bool) {
    use crate::layout::testing::with_layout_on;
    use crate::quirks::PictureLinePlace;
    use f_office_drawingml::{Feature, Warning as DrawingMlWarning};
    let mut out = (Vec::new(), false);
    let change = |profile: &crate::profile::Profile| {
        profile
            .with_variant(shadows)
            .with_variant(PictureLinePlace::Outside)
    };
    with_layout_on(change, |layout| {
        let items = layout.picture_items(picture, Length::ZERO, Length::ZERO);
        let warned = layout.output.warnings.iter().any(|(warning, _)| {
            matches!(
                warning,
                crate::Warning::DrawingMl {
                    warning: DrawingMlWarning::FeatureNotSupported {
                        feature: Feature::Shadow
                    },
                    ..
                }
            )
        });
        out = (items, warned);
    });
    out
}

/// A crop of `share` thousandths of a percent on each side.
fn crop_each_side(share: i64) -> Edges<i64> {
    Edges {
        left: share,
        top: share,
        right: share,
        bottom: share,
    }
}

#[test]
fn casts_an_opaque_picture_s_shadow_from_its_box_and_line_where_the_target_draws_it() {
    use crate::quirks::PictureShadows;
    let rgb = shadowed_picture(png_header(2), Edges::default());
    let (items, warned) = laid_picture(PictureShadows::Frame, &rgb);
    assert!(!warned);
    // The shadow's picture comes first, then the picture, then the line's ring, whose outer
    // edge bounds the frame that casts the shadow.
    let [Item::Image(shadow), Item::Image(_), Item::Path(ring)] = items.as_slice() else {
        panic!("not a shadow, a picture and a line: {items:?}");
    };
    assert_eq!(shadow.image.format, ImageFormat::EffectPicture);
    let frame = bounds(&[filled(&Item::Path(ring.clone())).unwrap()]).unwrap();
    let cast = picture_box(frame, offset(), hundredths(400)).unwrap();
    assert_eq!(
        (
            shadow.x,
            shadow.y,
            shadow.x + shadow.width,
            shadow.y + shadow.height
        ),
        (cast.left, cast.top, cast.right, cast.bottom)
    );
    // A picture of 72 by 36 pt with its line is 78 by 42 pt.
    assert_eq!(
        (frame.width(), frame.height()),
        (hundredths(7_800), hundredths(4_200))
    );
    // A cropped opaque picture casts too.
    let cropped = shadowed_picture(png_header(2), crop_each_side(10_000));
    assert_eq!(laid_picture(PictureShadows::Frame, &cropped).0.len(), 3);
}

#[test]
fn casts_alpha_masked_picture_shadows_and_warns_for_metafiles_or_other_targets() {
    use crate::quirks::PictureShadows;
    // A PNG with alpha, a negative crop, or picture opacity casts a masked shadow effect picture
    // on PictureShadows::Frame without warning.
    let alpha = shadowed_picture(png_header(6), Edges::default());
    let spaced = shadowed_picture(
        png_header(2),
        Edges {
            left: -10_000,
            ..Edges::default()
        },
    );
    let mut translucent = shadowed_picture(png_header(2), Edges::default());
    translucent.opacity = Opacity::clamped(50_000);
    for picture in [&alpha, &spaced, &translucent] {
        let (items, warned) = laid_picture(PictureShadows::Frame, picture);
        assert!(!warned);
        let [Item::Image(shadow), Item::Image(_), Item::Path(_)] = items.as_slice() else {
            panic!("not a shadow, a picture and a line: {items:?}");
        };
        assert_eq!(shadow.image.format, ImageFormat::EffectPicture);
    }
    // A metafile picture and a target that draws no picture's shadow still warn.
    let mut emf = shadowed_picture(Vec::new(), Edges::default());
    if let Some(image) = emf.image.as_mut() {
        image.format = ImageFormat::Emf;
    }
    let rgb = shadowed_picture(png_header(2), Edges::default());
    for (shadows, picture) in [
        (PictureShadows::Frame, &emf),
        (PictureShadows::Unknown, &rgb),
    ] {
        let (items, warned) = laid_picture(shadows, picture);
        assert!(warned);
        let effect_pictures = items
            .iter()
            .filter(|item| {
                matches!(item, Item::Image(image) if image.image.format == ImageFormat::EffectPicture)
            })
            .count();
        assert_eq!(effect_pictures, 0);
    }
}