f-office-drawingml 0.2.2

DrawingML shapes, pictures, fills, lines, themes and colors.
Documentation
use f_office_paint::{GradientStop, PathCommand, Point, Rgb};
use f_office_units::Length;
use f_office_warnings::Warnings;
use f_office_xml::{Document, Limits};

use super::LinearGradient;
use crate::A;
use crate::color::SchemeColors;

/// Three stops of pure colors, at 0, 30 and 100 %.
const THREE: &str = r#"<a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs><a:gs pos="30000"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst>"#;

/// The gradient fill `markup` (`a:gradFill`) as [`LinearGradient::read`] reads it.
fn gradient(markup: &str) -> Option<LinearGradient> {
    let doc = Document::parse(
        format!(r#"<a:gradFill xmlns:a="{A}" {markup}</a:gradFill>"#).as_bytes(),
        &Limits::default(),
    )
    .unwrap();
    LinearGradient::read(&doc, doc.root().unwrap(), &mut Warnings::new())
}

/// A point at `x` and `y` points.
fn at(x: i64, y: i64) -> Point {
    Point {
        x: Length::from_points(x).unwrap(),
        y: Length::from_points(y).unwrap(),
    }
}

/// The axis of `gradient` over the box from `top_left` to `bottom_right`.
fn axis(gradient: &LinearGradient, corners: (Point, Point)) -> (Point, Point) {
    let item = gradient.item(corners, &SchemeColors::default()).unwrap();
    (item.start, item.end)
}

#[test]
fn reads_a_linear_gradient_of_three_stops_and_fills_its_box() {
    let gradient = gradient(&format!(
        r#"rotWithShape="1">{THREE}<a:lin ang="5400000" scaled="0"/>"#
    ))
    .unwrap();
    let item = gradient
        .item((at(10, 20), at(30, 120)), &SchemeColors::default())
        .unwrap();
    let rgb = |r, g, b| Rgb { r, g, b };
    assert_eq!(
        item.stops,
        [
            GradientStop::new(0, rgb(255, 0, 0)),
            GradientStop::new(300_000, rgb(0, 255, 0)),
            GradientStop::new(1_000_000, rgb(0, 0, 255)),
        ]
    );
    // At 90° the axis runs from the top to the bottom through the middle.
    assert_eq!((item.start, item.end), (at(20, 20), at(20, 120)));
    assert_eq!(
        item.commands,
        [
            PathCommand::MoveTo(at(10, 20)),
            PathCommand::LineTo(at(30, 20)),
            PathCommand::LineTo(at(30, 120)),
            PathCommand::LineTo(at(10, 120)),
            PathCommand::Close,
        ]
    );
}

/// The stops of the gradient `stops` (`a:gsLst`) at 0°, over a box of 10 by 10 points.
fn stops_of(stops: &str) -> Vec<GradientStop> {
    let gradient = gradient(&format!(r#">{stops}<a:lin ang="0"/>"#)).unwrap();
    gradient
        .item((at(0, 0), at(10, 10)), &SchemeColors::default())
        .unwrap()
        .stops
}

/// A list of stops (`a:gsLst`), each a place in thousandths of a percent and a color element.
fn list(stops: &[(u32, &str)]) -> String {
    let each = stops
        .iter()
        .map(|(place, color)| format!(r#"<a:gs pos="{place}">{color}</a:gs>"#))
        .collect::<Vec<_>>()
        .concat();
    format!("<a:gsLst>{each}</a:gsLst>")
}

/// The stops of `stops` at the indexes `picked`.
fn picked(stops: &[GradientStop], picked: &[usize]) -> Vec<GradientStop> {
    picked
        .iter()
        .filter_map(|&i| stops.get(i).copied())
        .collect()
}

/// Word's samples of red to blue, written from the end: 256 colors along the curve, sample j
/// at (2j + 1) / 511 of the axis, the places of the second of two tiles.
#[test]
fn samples_a_gradient_of_two_stops_as_word_does() {
    let rgb = |r, g, b| Rgb { r, g, b };
    let red_blue = stops_of(&list(&[
        (100_000, r#"<a:srgbClr val="0000FF"/>"#),
        (0, r#"<a:srgbClr val="FF0000"/>"#),
    ]));
    assert_eq!(red_blue.len(), 256);
    assert_eq!(
        picked(&red_blue, &[0, 15, 128, 255]),
        [
            GradientStop::new(1_957, rgb(255, 0, 0)),
            GradientStop::new(60_665, rgb(0xFD, 0, 0x28)),
            GradientStop::new(502_935, rgb(0xBA, 0, 0xBB)),
            GradientStop::new(1_000_000, rgb(0, 0, 255)),
        ]
    );
}

/// Word's samples of the cyan band with `a:gamma`: 511 colors along the curve, with the
/// middle color in the middle whatever its written place.
#[test]
fn samples_three_stops_with_equal_ends_as_word_does() {
    let rgb = |r, g, b| Rgb { r, g, b };
    let white =
        r#"<a:srgbClr val="FFFFFF"><a:gamma/><a:tint val="43922"/><a:invGamma/></a:srgbClr>"#;
    let band = stops_of(&list(&[
        (0, white),
        (30_000, r#"<a:srgbClr val="00CCFF"/>"#),
        (100_000, white),
    ]));
    assert_eq!(band.len(), 511);
    assert_eq!(
        picked(&band, &[254, 255, 256, 510]),
        [
            GradientStop::new(498_531, rgb(0x0B, 0xCC, 0xFF)),
            GradientStop::new(500_490, rgb(0, 0xCC, 0xFF)),
            GradientStop::new(502_449, rgb(0x0B, 0xCC, 0xFF)),
            GradientStop::new(1_000_000, rgb(255, 255, 255)),
        ]
    );
}

/// The gradients next to the two forms that Word samples, which it joins by straight lines.
#[test]
fn joins_other_gradients_by_straight_lines() {
    let rgb = |r, g, b| Rgb { r, g, b };
    let (red, blue) = (
        r#"<a:srgbClr val="FF0000"/>"#,
        r#"<a:srgbClr val="0000FF"/>"#,
    );
    assert_eq!(
        stops_of(&list(&[(20_000, red), (80_000, blue)])),
        [
            GradientStop::new(200_000, rgb(255, 0, 0)),
            GradientStop::new(800_000, rgb(0, 0, 255)),
        ]
    );
    assert_eq!(
        stops_of(&list(&[(0, red), (50_000, blue), (90_000, red)])).len(),
        3
    );
    assert_eq!(
        stops_of(&list(&[(0, red), (50_000, red), (100_000, blue)])).len(),
        3
    );
    let (white, cyan) = (
        r#"<a:srgbClr val="FFFFFF"/>"#,
        r#"<a:srgbClr val="00CCFF"/>"#,
    );
    let darker = r#"<a:srgbClr val="FEFEFE"/>"#;
    assert_eq!(
        stops_of(&list(&[(0, white), (50_000, cyan), (100_000, darker)])).len(),
        3
    );
    assert_eq!(
        stops_of(&list(&[
            (0, white),
            (33_000, cyan),
            (67_000, cyan),
            (100_000, white)
        ]))
        .len(),
        4
    );
}

#[test]
fn sorts_the_stops_by_their_places() {
    let reversed = r#"<a:gsLst><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs><a:gs pos="30000"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs></a:gsLst>"#;
    assert_eq!(
        gradient(&format!(r#">{reversed}<a:lin ang="0"/>"#)),
        gradient(&format!(r#">{THREE}<a:lin ang="0"/>"#)),
    );
}

#[test]
fn runs_the_axis_from_the_corner_where_the_direction_starts() {
    let box_ = (at(0, 0), at(100, 200));
    let lin = |angle: &str, scaled: &str| {
        gradient(&format!(
            r#">{THREE}<a:lin ang="{angle}" scaled="{scaled}"/>"#
        ))
        .unwrap()
    };
    // 0° from the left edge to the right, 270° from the bottom to the top.
    assert_eq!(axis(&lin("0", "0"), box_), (at(0, 100), at(100, 100)));
    assert_eq!(axis(&lin("16200000", "0"), box_), (at(50, 200), at(50, 0)));
    // At 45° the ends lie on the lines across the axis through the top left and bottom right
    // corners: (300 / 2) pt from the middle (50, 100) along (1, 1) / √2 is (75, 75).
    assert_eq!(
        axis(&lin("2700000", "0"), box_),
        (at(-25, 25), at(125, 175))
    );
    // Scaled, the direction is (1 / 100, 1 / 200), so (2, 1), and the ends lie on the lines
    // across it through the same corners: 400 / 10 times (2, 1) from the middle.
    assert_eq!(
        axis(&lin("2700000", "1"), box_),
        (at(-30, 60), at(130, 140))
    );
    // At 0° the scaled direction is the angle's.
    assert_eq!(axis(&lin("0", "1"), box_), axis(&lin("0", "0"), box_));
}

#[test]
fn reads_a_missing_angle_as_zero_and_a_missing_scaled_as_false() {
    assert_eq!(
        gradient(&format!(">{THREE}<a:lin/>")),
        gradient(&format!(r#">{THREE}<a:lin ang="0" scaled="0"/>"#)),
    );
}

#[test]
fn paints_no_gradient_that_word_paints_in_another_way() {
    let one = r#"<a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs></a:gsLst>"#;
    let hue = r#"<a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"><a:hueOff val="60000"/></a:srgbClr></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst>"#;
    let alpha = r#"<a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"><a:alpha val="50000"/></a:srgbClr></a:gs><a:gs pos="50000"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst>"#;
    let beyond = r#"<a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs><a:gs pos="50000"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100001"><a:srgbClr val="0000FF"/></a:gs></a:gsLst>"#;
    let lin = r#"<a:lin ang="0"/>"#;
    for markup in [
        format!(">{one}{lin}"),
        format!(">{hue}{lin}"),
        format!(">{alpha}{lin}"),
        format!(">{beyond}{lin}"),
        format!(r#">{THREE}<a:path path="circle"/>"#),
        format!(">{THREE}"),
        format!(r#">{THREE}<a:lin ang="21600000"/>"#),
        format!(r#" flip="x">{THREE}{lin}"#),
        format!(r#">{THREE}{lin}<a:tileRect r="-10000"/>"#),
    ] {
        assert_eq!(gradient(&markup), None, "{markup}");
    }
    // An opaque alpha, a tile of the whole box and no flip paint.
    let whole = r#"<a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"><a:alpha val="100000"/></a:srgbClr></a:gs><a:gs pos="50000"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst>"#;
    assert!(gradient(&format!(r#" flip="none">{whole}{lin}<a:tileRect/>"#)).is_some());
}

#[test]
fn reads_no_more_than_the_most_stops() {
    let stops = |count: usize| {
        let each = r#"<a:gs pos="50000"><a:srgbClr val="00FF00"/></a:gs>"#.repeat(count);
        format!(r#"><a:gsLst>{each}</a:gsLst><a:lin ang="0"/>"#)
    };
    assert!(gradient(&stops(super::MOST_STOPS)).is_some());
    assert_eq!(gradient(&stops(super::MOST_STOPS + 1)), None);
}

#[test]
fn needs_the_theme_colors_of_its_stops() {
    let scheme = r#"<a:gsLst><a:gs pos="0"><a:schemeClr val="accent1"/></a:gs><a:gs pos="50000"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst>"#;
    let gradient = gradient(&format!(r#">{scheme}<a:lin ang="0"/>"#)).unwrap();
    assert_eq!(
        gradient.item((at(0, 0), at(10, 10)), &SchemeColors::default()),
        None
    );
}

#[test]
fn reads_word2010_linear_text_gradients_and_rejects_path_shades() {
    let w14 = crate::color::WORD_2010;
    let parse = |inner: &str| {
        let xml = format!(r#"<w14:gradFill xmlns:w14="{w14}">{inner}</w14:gradFill>"#);
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let mut warnings = Warnings::new();
        let got = LinearGradient::read_word2010(&doc, doc.root().unwrap(), &mut warnings);
        (got, warnings)
    };
    let linear = concat!(
        r#"<w14:gsLst>"#,
        r#"<w14:gs w14:pos="0"><w14:srgbClr w14:val="FF0000"/></w14:gs>"#,
        r#"<w14:gs w14:pos="100000"><w14:srgbClr w14:val="0000FF"/></w14:gs>"#,
        r#"</w14:gsLst><w14:lin w14:ang="5400000" w14:scaled="0"/>"#,
    );
    let (grad, warnings) = parse(linear);
    assert!(warnings.is_empty());
    let grad = grad.unwrap();
    let item = grad
        .fill_path(
            vec![PathCommand::MoveTo(at(0, 0)), PathCommand::Close],
            f_office_paint::FillRule::EvenOdd,
            (at(10, 20), at(110, 60)),
            &SchemeColors::default(),
        )
        .unwrap();
    assert_eq!(item.fill_rule, f_office_paint::FillRule::EvenOdd);
    assert_eq!((item.start, item.end), (at(60, 20), at(60, 60)));

    let radial = concat!(
        r#"<w14:gsLst>"#,
        r#"<w14:gs w14:pos="0"><w14:srgbClr w14:val="FF0000"/></w14:gs>"#,
        r#"<w14:gs w14:pos="100000"><w14:srgbClr w14:val="0000FF"/></w14:gs>"#,
        r#"</w14:gsLst><w14:path w14:path="circle"/>"#,
    );
    assert_eq!(parse(radial).0, None);
}