use std::collections::HashSet;
use super::{CompoundLine, Geometry, PRESETS, SHAPE_TYPES, ShapeLook};
use crate::theme::ShapeTheme;
use crate::{A, Feature};
use f_office_paint::{FillRule, Item, Opacity, PathCommand, Rgb};
use f_office_units::{Edges, Length};
use f_office_warnings::Warnings;
use f_office_xml::{Document, Limits};
const THEME: &str = r#"<a:theme><a:themeElements><a:clrScheme><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1><a:accent1><a:srgbClr val="4472C4"/></a:accent1></a:clrScheme><a:fmtScheme><a:lnStyleLst><a:ln w="6350"/><a:ln w="12700"/><a:ln w="19050"/></a:lnStyleLst></a:fmtScheme></a:themeElements></a:theme>"#;
/// Reads a shape from its `spPr` children and its style's children, with the theme above.
fn shape(props: &str, style: &str) -> (ShapeLook, ShapeTheme) {
let (look, theme, _) = shape_warned(props, style);
(look, theme)
}
/// [`shape`], with the kinds and counts of the warnings of the reading.
fn shape_warned(props: &str, style: &str) -> (ShapeLook, ShapeTheme, Vec<(&'static str, u32)>) {
shape_in(THEME, props, style)
}
/// [`shape_warned`] with the theme `theme`.
fn shape_in(
theme: &str,
props: &str,
style: &str,
) -> (ShapeLook, ShapeTheme, Vec<(&'static str, u32)>) {
let xml = format!(
r#"<a:x xmlns:a="{A}">{theme}<a:spPr>{props}</a:spPr><a:style>{style}</a:style></a:x>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let [theme, props, style] = {
let mut children = doc.child_elements(doc.root().unwrap());
[(); 3].map(|()| children.next().unwrap())
};
let style = (!doc.children(style).is_empty()).then_some(style);
let mut warnings = Warnings::new();
let look = ShapeLook::read(&doc, (Some(props), style), &mut warnings);
let theme = ShapeTheme::read(&doc, theme, &mut warnings);
let kinds = warnings
.iter()
.map(|(warning, count)| (warning.kind(), count))
.collect();
(look, theme, kinds)
}
const RECT: &str = r#"<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>"#;
const STYLE: &str = r#"<a:lnRef idx="2"><a:schemeClr val="accent1"><a:shade val="50000"/></a:schemeClr></a:lnRef><a:fillRef idx="1"><a:schemeClr val="accent1"/></a:fillRef>"#;
fn rgb(r: u8, g: u8, b: u8) -> Rgb {
Rgb { r, g, b }
}
#[test]
fn takes_the_fill_and_line_of_the_style_that_the_shape_leaves_out() {
let (look, theme) = shape(RECT, STYLE);
assert_eq!(look.geometry, Geometry::Rect);
assert_eq!(look.fill(&theme), Some((rgb(68, 114, 196), Opacity::FULL)));
let line = (
rgb(47, 82, 143),
Opacity::FULL,
Length::from_emus(12_700).unwrap(),
);
assert_eq!(look.line(&theme), Some(line));
}
#[test]
fn keeps_the_width_of_a_line_without_fill_for_text_insets() {
let props = format!(r#"{RECT}<a:ln w="9360"><a:noFill/></a:ln>"#);
let (look, theme) = shape(&props, STYLE);
assert_eq!(look.line(&theme), None);
assert_eq!(look.inset_line_width(&theme), Length::from_emus(9_360));
// A drawn line counts with its own width, and a shape without a line has none.
let (drawn, theme) = shape(RECT, STYLE);
assert_eq!(drawn.inset_line_width(&theme), Length::from_emus(12_700));
let (bare, theme) = shape(RECT, "");
assert_eq!(bare.inset_line_width(&theme), None);
}
#[test]
fn inherits_theme_line_width_for_no_fill_text_insets() {
// A no-fill line without an explicit w falls back to the shape's lnRef theme line width,
// while an explicit w="0", lnRef idx="0", or absent style leaves no theme width.
let no_fill = format!("{RECT}<a:ln><a:noFill/></a:ln>");
let (inherited, theme) = shape(&no_fill, STYLE);
assert_eq!(inherited.line(&theme), None);
assert_eq!(
inherited.inset_line_width(&theme),
Length::from_emus(12_700)
);
let zero_w = format!(r#"{RECT}<a:ln w="0"><a:noFill/></a:ln>"#);
let (zero, theme) = shape(&zero_w, STYLE);
assert_eq!(zero.inset_line_width(&theme), Some(Length::ZERO));
let (no_style, theme) = shape(&no_fill, "");
assert_eq!(no_style.inset_line_width(&theme), None);
let zero_ref = r#"<a:lnRef idx="0"><a:srgbClr val="000000"/></a:lnRef>"#;
let (idx_zero, theme) = shape(&no_fill, zero_ref);
assert_eq!(idx_zero.inset_line_width(&theme), None);
}
#[test]
fn reads_a_line_width_with_a_unit_and_one_with_a_fraction_as_missing() {
let drawn = |width: &str| {
format!(r#"{RECT}<a:ln{width}><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>"#)
};
let width = |props: &str| {
let (look, theme, warnings) = shape_warned(props, "");
(look.line(&theme).map(|line| line.2), warnings)
};
assert_eq!(
width(&drawn(r#" w="3pt""#)),
(Length::from_emus(38_100), vec![])
);
let (missing, _) = width(&drawn(""));
assert_eq!(
width(&drawn(r#" w="38100.7""#)),
(missing, vec![("drawingml-invalid-value", 1)])
);
let (look, theme, warnings) =
shape_warned(&format!(r#"{RECT}<a:ln w="1in"><a:noFill/></a:ln>"#), STYLE);
assert_eq!(
(look.inset_line_width(&theme), warnings),
(Length::from_emus(914_400), vec![])
);
}
#[test]
fn reads_a_rotation_only_within_the_range_of_its_type() {
let turned = |rot: &str| {
let (look, _, kinds) = shape_warned(&format!(r#"<a:xfrm rot="{rot}"/>{RECT}"#), "");
(look.rotation, kinds)
};
assert_eq!(turned("5400000"), (5_400_000, Vec::new()));
assert_eq!(turned("-5400000"), (-5_400_000, Vec::new()));
// A number beyond the range of `xsd:int` and `xsd:unsignedInt`, and text that is no whole
// number, count as no rotation, with a warning, as a picture's rotation does.
for rot in ["4294967296", "-2147483649", "5400000.5", "90deg"] {
assert_eq!(
turned(rot),
(0, vec![("drawingml-invalid-value", 1)]),
"{rot}"
);
}
}
#[test]
fn prefers_the_shape_own_fill_and_line() {
let props = format!(
r#"{RECT}<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill><a:ln w="25400"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln>"#
);
let (look, theme) = shape(&props, STYLE);
assert_eq!(look.fill(&theme), Some((rgb(255, 0, 0), Opacity::FULL)));
let line = (
rgb(255, 255, 255),
Opacity::FULL,
Length::from_emus(25_400).unwrap(),
);
assert_eq!(look.line(&theme), Some(line));
// A line without its own color takes the style's color and keeps its own width.
let props = format!(r#"{RECT}<a:noFill/><a:ln w="38100"/>"#);
let (look, theme) = shape(&props, STYLE);
assert_eq!(look.fill(&theme), None);
assert_eq!(
look.line(&theme).map(|l| (l.0, l.2)),
Some((rgb(47, 82, 143), Length::from_emus(38_100).unwrap()))
);
let props = format!("{RECT}<a:ln><a:noFill/></a:ln>");
assert_eq!(shape(&props, STYLE).0.line(&theme), None);
}
#[test]
fn draws_nothing_without_a_fill_or_line() {
let (look, theme) = shape(RECT, r#"<a:lnRef idx="0"/><a:fillRef idx="0"/>"#);
assert_eq!((look.fill(&theme), look.line(&theme)), (None, None));
let (look, theme) = shape(RECT, "");
assert_eq!((look.fill(&theme), look.line(&theme)), (None, None));
// A line without a style or a width of its own is 0.75 pt wide.
let props =
format!(r#"{RECT}<a:ln><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>"#);
let width = shape(&props, "").0.line(&theme).map(|l| l.2);
assert_eq!(width, Length::from_emus(9_525));
}
#[test]
fn reads_the_preset_geometries() {
let geometry = |preset: &str| shape(preset, "").0.geometry;
assert_eq!(
geometry(r#"<a:prstGeom prst="ellipse"/>"#),
Geometry::Ellipse
);
assert_eq!(
geometry(r#"<a:prstGeom prst="straightConnector1"/>"#),
Geometry::Line
);
assert_eq!(
geometry(r#"<a:prstGeom prst="roundRect"/>"#),
Geometry::RoundRect(16_667)
);
let adjusted = r#"<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 50000"/></a:avLst></a:prstGeom>"#;
assert_eq!(geometry(adjusted), Geometry::RoundRect(50_000));
assert_eq!(geometry("<a:custGeom/>"), Geometry::Other);
}
#[test]
fn warns_of_a_corner_formula_or_a_style_index_that_does_not_read() {
// A corner formula other than a value counts as missing, the preset's 16,667, and a style
// index that does not read counts as 0, each with a warning.
let (look, _, kinds) = shape_warned(
r#"<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="*/ w 1 2"/></a:avLst></a:prstGeom>"#,
r#"<a:effectRef idx="x"><a:schemeClr val="accent1"/></a:effectRef>"#,
);
assert_eq!(look.geometry, Geometry::RoundRect(16_667));
// One warning for the guide's formula and one for the reference's index.
assert_eq!(
kinds,
[
("drawingml-invalid-value", 1),
("drawingml-invalid-value", 1)
]
);
let (_, _, kinds) = shape_warned(
r#"<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 50000"/></a:avLst></a:prstGeom>"#,
r#"<a:effectRef idx="2"><a:schemeClr val="accent1"/></a:effectRef>"#,
);
assert_eq!(kinds, []);
}
/// The box `[x, y, width, height]` of a shape, from its edges in units.
/// The box whose top left corner is at `x` and `y` and whose size is `width` by `height`, in
/// units.
fn frame_of([x, y, width, height]: [i64; 4]) -> Edges<Length> {
let units = Length::from_units;
Edges::placed(units(x), units(y), units(width), units(height)).unwrap()
}
/// The points of the commands of a path, in units.
fn points(item: &Item) -> Vec<(i64, i64)> {
let Item::Path(path) = item else {
panic!("{item:?}");
};
path.commands
.iter()
.filter_map(|c| match c {
PathCommand::MoveTo(p) | PathCommand::LineTo(p) | PathCommand::CubicTo(_, _, p) => {
Some((p.x.units(), p.y.units()))
}
_ => None,
})
.collect()
}
#[test]
fn fills_a_rectangle_and_draws_its_line_as_a_ring() {
let (look, _) = shape(RECT, "");
let red = rgb(255, 0, 0);
let width = Length::from_units(20_000);
let items = look
.items(
frame_of([100_000, 200_000, 1_000_000, 500_000]),
Some(red),
Some((red, width)),
&[1],
)
.unwrap();
assert_eq!(items.len(), 2);
let corners = [
(100_000, 200_000),
(1_100_000, 200_000),
(1_100_000, 700_000),
(100_000, 700_000),
];
assert_eq!(points(&items[0]), corners);
// The line is centered on the outline: the outer edge 10,000 out, the inner 10,000 in.
let ring = points(&items[1]);
assert_eq!(ring[0], (90_000, 190_000));
assert_eq!(ring[4], (110_000, 210_000));
assert!(matches!(&items[1], Item::Path(p) if p.fill_rule == FillRule::EvenOdd));
}
#[test]
fn draws_a_line_shape_between_its_flipped_corners() {
let props = r#"<a:xfrm flipH="1"/><a:prstGeom prst="line"/>"#;
let (look, _) = shape(props, "");
let black = rgb(0, 0, 0);
let items = look
.items(
frame_of([0, 0, 1_000, 0]),
Some(black),
Some((black, Length::from_units(10_000))),
&[1],
)
.unwrap();
assert_eq!(items.len(), 1, "a line has no fill");
// A level line from right to left, 10,000 units thick.
assert_eq!(
points(&items[0]),
[(1_000, -5_000), (0, -5_000), (0, 5_000), (1_000, 5_000)]
);
}
#[test]
fn turns_a_shape_by_quarter_and_arbitrary_angles() {
let props = r#"<a:xfrm rot="5400000"/><a:prstGeom prst="ellipse"/>"#;
let (look, _) = shape(props, "");
let blue = rgb(0, 0, 255);
let items = look
.items(frame_of([0, 0, 400, 200]), Some(blue), None, &[1])
.unwrap();
// The ellipse turns about its center, so it is 200 wide and 400 high.
assert_eq!(points(&items[0])[0], (200, -100));
// Arbitrary angles, negative quarter turns, and full turns all draw without Feature::Turn.
for rot in ["2700000", "-2700000", "-16200000", "21600000"] {
let (look, _, warnings) = shape_warned(&format!(r#"<a:xfrm rot="{rot}"/>{RECT}"#), "");
assert_eq!(warnings, [], "{rot}");
let items = look
.items(frame_of([0, 0, 400, 200]), Some(blue), None, &[1])
.unwrap();
assert_ne!(items, Vec::new(), "{rot}");
}
// A 400x200 rect rotated 30 deg CW about center (200, 100): top-left (-200, -100) lands at
// (200 - 200*cos(30) + 100*sin(30), 100 - 200*sin(30) - 100*cos(30)) = (77, -86).
let (rot30, _) = shape(&format!(r#"<a:xfrm rot="1800000"/>{RECT}"#), "");
let items = rot30
.items(frame_of([0, 0, 400, 200]), Some(blue), None, &[1])
.unwrap();
assert_eq!(points(&items[0])[0], (77, -86));
}
#[test]
fn turns_a_plain_line_about_the_center_of_its_box() {
use f_office_units::scale::QUARTER_TURN;
// A level line 1,000 units long, such as a VML connector, turned a quarter turn.
let black = rgb(0, 0, 0);
let width = Length::from_units(10_000);
let look = ShapeLook::plain(Geometry::Line, None, Some((black, width)));
let bounds = |look: ShapeLook| {
let items = look
.items(frame_of([0, 0, 1_000, 0]), None, Some((black, width)), &[1])
.unwrap();
let points = points(&items[0]);
let xs = points.iter().map(|(x, _)| *x);
let ys = points.iter().map(|(_, y)| *y);
[xs.clone().min(), ys.clone().min(), xs.max(), ys.max()].map(Option::unwrap)
};
assert_eq!(bounds(look.clone()), [0, -5_000, 1_000, 5_000]);
// Upright, the line runs across; turned, it runs down through the same center, 500.
let down = [-4_500, -500, 5_500, 500];
assert_eq!(bounds(look.clone().turned(QUARTER_TURN)), down);
assert_eq!(bounds(look.turned(-QUARTER_TURN)), down);
}
#[test]
fn gives_whole_quarter_turns_clockwise_from_0_to_3() {
use f_office_units::scale::{FULL_TURN, QUARTER_TURN};
let cases = [
(0, Some(0)),
(QUARTER_TURN, Some(1)),
(-QUARTER_TURN, Some(3)),
(3 * FULL_TURN + 2 * QUARTER_TURN, Some(2)),
(QUARTER_TURN / 2, None),
(-1, None),
];
for (rotation, quarters) in cases {
assert_eq!(super::quarter_turns(rotation), quarters, "{rotation}");
}
}
#[test]
fn turns_a_point_clockwise_on_a_page_whose_y_grows_downwards() {
use f_office_units::scale::QUARTER_TURN;
let center = [1_000, 2_000];
// A point right of the center goes below it after a quarter turn clockwise.
let cases = [
(0, [1_100, 2_000]),
(QUARTER_TURN, [1_000, 2_100]),
(2 * QUARTER_TURN, [900, 2_000]),
(-QUARTER_TURN, [1_000, 1_900]),
// A seventh of a full turn, 360/7 degrees: 100·cos and 100·sin of it, rounded.
(QUARTER_TURN * 4 / 7, [1_062, 2_078]),
];
for (rotation, point) in cases {
assert_eq!(
super::turned_clockwise([1_100, 2_000], center, rotation),
Some(point),
"{rotation}"
);
}
}
#[test]
fn gives_the_whole_quarter_turns_of_its_own_rotation() {
let quarters = |xfrm: &str| shape(&format!("{xfrm}{RECT}"), "").0.quarter_turns();
assert_eq!(quarters(""), Some(0));
assert_eq!(quarters(r#"<a:xfrm rot="5400000"/>"#), Some(1));
assert_eq!(quarters(r#"<a:xfrm rot="-16200000"/>"#), Some(1));
assert_eq!(quarters(r#"<a:xfrm rot="10800000" flipV="1"/>"#), Some(2));
assert_eq!(quarters(r#"<a:xfrm rot="2700000"/>"#), None);
}
/// A fill element of each kind, in a shape's properties or a line.
const SOLID: &str = r#"<a:solidFill><a:srgbClr val="FF0000"/></a:solidFill>"#;
const GRADIENT: &str = r#"<a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst></a:gradFill>"#;
const PATH_GRADIENT: &str = r#"<a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst><a:path path="circle"/></a:gradFill>"#;
const FLIPPED_GRADIENT: &str = r#"<a:gradFill flip="xy"><a:gsLst><a:gs pos="0"><a:srgbClr val="00FF00"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst></a:gradFill>"#;
const PATTERN: &str = r#"<a:pattFill prst="pct5"><a:fgClr><a:srgbClr val="000000"/></a:fgClr><a:bgClr><a:srgbClr val="FFFFFF"/></a:bgClr></a:pattFill>"#;
const GROUP: &str = "<a:grpFill/>";
const PICTURE: &str = "<a:blipFill><a:blip/></a:blipFill>";
#[test]
fn warns_of_each_fill_of_an_area_that_it_does_not_draw() {
type FillCase<'a> = (&'a str, Option<Rgb>, &'a [(&'a str, u32)]);
let fill = |geometry: &str, element: &str| {
let (look, theme, warnings) = shape_warned(&format!("{geometry}{element}"), STYLE);
(look.fill(&theme).map(|(rgb, _)| rgb), warnings)
};
let cases: [FillCase<'_>; 7] = [
// A linear or path gradient draws without warning.
(GRADIENT, Some(rgb(0, 255, 0)), &[]),
(PATH_GRADIENT, Some(rgb(0, 255, 0)), &[]),
// A flipped gradient falls back to its first stop with a warning.
(
FLIPPED_GRADIENT,
Some(rgb(0, 255, 0)),
&[("drawingml-gradient-fill-not-supported", 1)],
),
(
PATTERN,
None,
&[("drawingml-pattern-fill-not-supported", 1)],
),
(GROUP, None, &[("drawingml-group-fill-not-supported", 1)]),
// The caller draws a picture fill or warns of it.
(PICTURE, None, &[]),
(SOLID, Some(rgb(255, 0, 0)), &[]),
];
for (element, expected_color, expected_warnings) in cases {
assert_eq!(
fill(RECT, element),
(expected_color, expected_warnings.to_vec()),
"{element}"
);
}
// A line has no area to fill, so its fill is no feature that F-Office leaves out.
let line = r#"<a:prstGeom prst="line"/>"#;
for element in [FLIPPED_GRADIENT, PATTERN, GROUP] {
assert_eq!(fill(line, element), (None, vec![]), "{element}");
}
}
#[test]
fn warns_of_each_fill_of_a_line_that_it_does_not_draw() {
let line = |element: &str| {
let (look, theme, warnings) =
shape_warned(&format!("{RECT}<a:noFill/><a:ln>{element}</a:ln>"), STYLE);
(look.line(&theme).map(|(rgb, _, _)| rgb), warnings)
};
assert_eq!(
line(GRADIENT),
(
Some(rgb(0, 255, 0)),
vec![("drawingml-gradient-fill-not-supported", 1)]
)
);
// A picture, pattern or group fill of a line takes the line color of the style.
for element in [PATTERN, GROUP, PICTURE] {
assert_eq!(
line(element),
(
Some(rgb(47, 82, 143)),
vec![("drawingml-line-fill-not-supported", 1)]
),
"{element}"
);
}
assert_eq!(line(SOLID), (Some(rgb(255, 0, 0)), vec![]));
assert_eq!(line("<a:noFill/>"), (None, vec![]));
}
/// A theme whose first fill, line and effect styles F-Office draws, and whose second are a
/// gradient fill, a double dashed line with an arrowhead, and a shadow.
const STYLED_THEME: &str = r#"<a:theme><a:themeElements><a:clrScheme><a:accent1><a:srgbClr val="4472C4"/></a:accent1></a:clrScheme><a:fmtScheme><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:gradFill/></a:fillStyleLst><a:lnStyleLst><a:ln w="6350"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln><a:ln w="12700" cmpd="dbl"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="dash"/><a:tailEnd type="arrow"/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw/></a:effectLst></a:effectStyle></a:effectStyleLst></a:fmtScheme></a:themeElements></a:theme>"#;
#[test]
fn says_whether_the_shape_takes_a_style_of_the_theme_that_it_does_not_draw() {
let references = |[fill, line, effect]: [u32; 3]| {
format!(
r#"<a:lnRef idx="{line}"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="{fill}"><a:schemeClr val="accent1"/></a:fillRef><a:effectRef idx="{effect}"><a:schemeClr val="accent1"/></a:effectRef>"#
)
};
let own = format!(
r#"{RECT}{SOLID}<a:ln>{SOLID}<a:prstDash val="solid"/><a:tailEnd/></a:ln><a:effectLst/>"#
);
let line = r#"<a:prstGeom prst="line"/>"#;
let style = Feature::ThemeStyle;
let cases = [
(RECT, [1, 1, 1], vec![]),
// Each style of the second column holds what F-Office does not draw; preset dashes and
// standard arrowheads are drawn without warning.
(RECT, [2, 1, 1], vec![style]),
(RECT, [1, 2, 1], vec![style]),
(RECT, [1, 1, 2], vec![style]),
(line, [1, 2, 1], vec![style]),
// The shape's own fill, line, dash, ends and effects take the place of the styles.
(own.as_str(), [2, 2, 2], vec![]),
// A line has no area to fill.
(line, [2, 1, 1], vec![]),
// An index of 0 names no style, and the scheme lacks the third.
(RECT, [0, 0, 0], vec![]),
(RECT, [3, 3, 3], vec![]),
];
for (props, indices, features) in cases {
let (look, theme, warnings) = shape_in(STYLED_THEME, props, &references(indices));
let got = (look.theme_features(&theme), warnings);
assert_eq!(got, (features, vec![]), "{props} {indices:?}");
}
let plain = ShapeLook::plain(Geometry::Rect, Some(rgb(0, 0, 0)), None);
assert_eq!(plain.theme_features(&ShapeTheme::default()), []);
}
#[test]
fn warns_of_unsupported_dashes_and_of_unsupported_line_ends_on_an_open_outline() {
type Case<'a> = (&'a str, String, &'a [(&'a str, u32)]);
let line = r#"<a:prstGeom prst="line"/>"#;
let dash = ("drawingml-line-dash-not-supported", 1);
let end = ("drawingml-line-end-not-supported", 1);
let cases: &[Case<'_>] = &[
(
RECT,
format!(r#"{SOLID}<a:prstDash val="dash"/><a:tailEnd type="arrow"/>"#),
&[],
),
(
line,
format!(r#"{SOLID}<a:prstDash val="dash"/><a:tailEnd type="arrow"/>"#),
&[],
),
(
line,
format!(
r#"{SOLID}<a:custDash><a:ds d="100000" sp="100000"/></a:custDash><a:headEnd type="none"/><a:tailEnd type="stealth"/>"#
),
&[],
),
(RECT, format!(r#"{SOLID}<a:tailEnd type="unknown"/>"#), &[]),
(
line,
format!(r#"{SOLID}<a:tailEnd type="unknown"/>"#),
&[end],
),
(RECT, format!("{SOLID}<a:custDash/>"), &[dash]),
// A solid dash, an end of type none and a line that is not drawn give no warning.
(
line,
format!(r#"{SOLID}<a:prstDash val="solid"/><a:headEnd type="none"/><a:tailEnd/>"#),
&[],
),
(line, "<a:noFill/><a:custDash/>".to_owned(), &[]),
];
for (geometry, ln, expected) in cases {
assert_eq!(
shape_warned(&format!("{geometry}<a:ln>{ln}</a:ln>"), "").2,
*expected
);
}
}
#[test]
fn reads_the_line_of_an_element_that_draws_only_a_line() {
let xml =
format!(r#"<a:spPr xmlns:a="{A}">{GRADIENT}<a:ln w="12700">{GRADIENT}</a:ln></a:spPr>"#);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut warnings = Warnings::new();
let look = ShapeLook::read_line(&doc, doc.root().ok(), &mut warnings);
assert_eq!(look.geometry, Geometry::Line);
// The fill of its properties is not drawn and gives no warning; its line's does.
let kinds: Vec<_> = warnings
.iter()
.map(|(w, count)| (w.kind(), count))
.collect();
assert_eq!(kinds, [("drawingml-gradient-fill-not-supported", 1)]);
}
#[test]
fn rounds_the_corners_by_a_share_of_the_shorter_side_from_none_to_half() {
let red = rgb(255, 0, 0);
// The first point of the outline lies one radius right of the top left corner.
let radius = |share: i64| {
let look = ShapeLook::plain(Geometry::RoundRect(share), Some(red), None);
let items = look
.items(frame_of([0, 0, 1_000, 400]), Some(red), None, &[1])
.unwrap();
points(&items[0])[0].0
};
assert_eq!(radius(25_000), 100);
assert_eq!(radius(50_000), 200);
// A share above a half gives half the side, also one whose product with the side leaves
// an `i64`, and a share below none gives square corners.
assert_eq!(radius(80_000), 200);
assert_eq!(radius(i64::MAX / 2), 200);
assert_eq!(radius(-5), 0);
}
#[test]
fn reads_explicit_compound_choices_without_changing_the_total_width() {
for (value, expected) in [
("sng", CompoundLine::Single),
("dbl", CompoundLine::Double),
("thickThin", CompoundLine::ThickThin),
("thinThick", CompoundLine::ThinThick),
("tri", CompoundLine::Triple),
("invalid", CompoundLine::Single),
] {
let props = format!(
r#"<a:prstGeom prst="line"/><a:ln w="57150" cmpd="{value}"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>"#
);
let (look, theme) = shape(&props, "");
assert_eq!(look.compound, expected);
assert_eq!(look.inset_line_width(&theme), Length::from_emus(57_150));
}
assert_eq!(shape(RECT, "").0.compound, CompoundLine::Single);
// Text outside the type is one line, as a missing name is, with a warning.
let props = r#"<a:prstGeom prst="line"/><a:ln cmpd="double"/>"#;
let (look, _, warnings) = shape_warned(props, "");
assert_eq!(look.compound, CompoundLine::Single);
assert_eq!(warnings, [("drawingml-invalid-value", 1)]);
}
#[test]
fn draws_another_preset_shape_from_its_definition() {
let (look, _, warnings) = shape_warned(r#"<a:prstGeom prst="rightArrow"/>"#, "");
assert!(matches!(look.geometry, Geometry::Custom(_)));
assert_eq!(warnings, []);
}
#[test]
fn draws_a_preset_geometry_without_its_name_as_nothing_with_a_warning() {
let (look, _, warnings) = shape_warned("<a:prstGeom/>", "");
assert_eq!(look.geometry, Geometry::Other);
assert_eq!(warnings, [("drawingml-invalid-value", 1)]);
}
/// A shape's own compound line is drawn in its parts on a straight line only: on a rectangle,
/// an ellipse or a custom geometry it is one line of the full width, which the format crate
/// warns of. A single line, an outline that is not drawn and a line give no warning.
#[test]
fn says_which_compound_lines_are_drawn_as_one_line() {
let triangle = r#"<a:custGeom><a:pathLst><a:path w="2" h="2"><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:lnTo><a:pt x="2" y="2"/></a:lnTo></a:path></a:pathLst></a:custGeom>"#;
let left_out = |geometry: &str, compound: &str| {
let line = format!(
r#"<a:ln w="38100" cmpd="{compound}"><a:solidFill><a:srgbClr val="000000"/></a:solidFill></a:ln>"#
);
shape(&format!("{geometry}{line}"), "")
.0
.compound_left_out()
};
let ellipse = r#"<a:prstGeom prst="ellipse"/>"#;
let rounded = r#"<a:prstGeom prst="roundRect"/>"#;
let line = r#"<a:prstGeom prst="line"/>"#;
// `upArrow` is not drawn, nor a shape turned by other than a quarter turn.
let other = r#"<a:prstGeom prst="upArrow"/>"#;
let (turned, quarter) = (
format!(r#"<a:xfrm rot="600000"/>{RECT}"#),
format!(r#"<a:xfrm rot="5400000"/>{RECT}"#),
);
let cases = [
(RECT, "dbl", false),
(ellipse, "thickThin", false),
(rounded, "thinThick", false),
(triangle, "tri", true),
(&quarter, "dbl", false),
(line, "dbl", false),
(line, "tri", false),
(RECT, "sng", false),
(other, "dbl", false),
(&turned, "dbl", false),
];
let got: Vec<bool> = cases
.iter()
.map(|(geometry, compound, _)| left_out(geometry, compound))
.collect();
let want: Vec<bool> = cases.iter().map(|case| case.2).collect();
assert_eq!(got, want);
}
#[test]
fn draws_a_preset_shape_without_a_definition_as_nothing_with_a_warning() {
// The standard's file has no definition of `upArrow`.
let (look, _, warnings) = shape_warned(r#"<a:prstGeom prst="upArrow"/>"#, "");
assert_eq!(look.geometry, Geometry::Other);
assert_eq!(warnings, [("drawingml-value-not-supported", 1)]);
let (look, _, warnings) = shape_warned(r#"<a:prstGeom prst="Rect"/>"#, "");
assert_eq!(look.geometry, Geometry::Other);
assert_eq!(warnings, [("drawingml-invalid-value", 1)]);
let (look, _, warnings) = shape_warned(r#"<a:prstGeom prst="straightConnector1"/>"#, "");
assert_eq!(look.geometry, Geometry::Line);
assert_eq!(warnings, []);
// Each name of `ST_ShapeType` once, and each drawn shape among them.
let names: HashSet<&str> = SHAPE_TYPES.iter().copied().collect();
assert_eq!(
(SHAPE_TYPES.len(), names.len(), PRESETS.names().len()),
(187, 187, 187)
);
}
#[test]
fn compound_bands_leave_gaps_inside_the_stated_width_and_flat_ends() {
let (look, _) = shape(r#"<a:prstGeom prst="line"/>"#, "");
let black = rgb(0, 0, 0);
for (parts, expected) in [
(vec![1, 1, 1], vec![(-30_000, -10_000), (10_000, 30_000)]),
(vec![3, 1, 1], vec![(-30_000, 6_000), (18_000, 30_000)]),
(vec![1, 1, 3], vec![(-30_000, -18_000), (-6_000, 30_000)]),
(
vec![1, 1, 2, 1, 1],
vec![(-30_000, -20_000), (-10_000, 10_000), (20_000, 30_000)],
),
] {
let items = look
.items(
frame_of([0, 0, 200_000, 0]),
None,
Some((black, Length::from_units(60_000))),
&parts,
)
.unwrap();
assert_eq!(items.len(), expected.len());
for (item, (top, bottom)) in items.iter().zip(expected) {
assert_eq!(
points(item),
[(0, top), (200_000, top), (200_000, bottom), (0, bottom)]
);
}
}
for (frame, parts) in [
([0, 0, 0, 0], vec![3, 1, 1]),
([0, 0, 200_000, 0], vec![0, 0, 0]),
([0, 0, 200_000, 0], vec![3, -1, 1]),
] {
assert_eq!(
look.items(
frame_of(frame),
None,
Some((black, Length::from_units(60_000))),
&parts
)
.unwrap(),
[]
);
}
}
#[test]
fn compound_bands_reflect_with_the_whole_outline_in_each_direction() {
let black = rgb(0, 0, 0);
let line = Some((black, Length::from_units(60_000)));
for frame in [
[0, 0, 200_000, 0],
[0, 0, 0, 100_000],
[0, 0, 200_000, 100_000],
] {
let (base, _) = shape(r#"<a:prstGeom prst="line"/>"#, "");
let original = base.items(frame_of(frame), None, line, &[3, 1, 1]).unwrap();
let [x, y, w, h] = frame;
let center = (x + w / 2, y + h / 2);
for flip in [[false, false], [true, false], [false, true], [true, true]] {
for quarters in 0..4 {
let mut look = base.clone().flipped(flip);
look.rotation = quarters * super::QUARTER_TURN;
let items = look.items(frame_of(frame), None, line, &[3, 1, 1]).unwrap();
assert_eq!(items.len(), original.len());
for (before, after) in original.iter().zip(&items) {
let mut expected: Vec<_> = points(before)
.into_iter()
.map(|(px, py)| {
let mut dx = (px - center.0) * if flip[0] { -1 } else { 1 };
let mut dy = (py - center.1) * if flip[1] { -1 } else { 1 };
for _ in 0..quarters {
(dx, dy) = (-dy, dx);
}
(center.0 + dx, center.1 + dy)
})
.collect();
let mut actual = points(after);
expected.sort_unstable();
actual.sort_unstable();
assert_eq!(actual, expected, "{frame:?} {flip:?} {quarters}");
}
}
}
}
}
/// The line that [`super::picture_properties`] reads from a picture's `spPr` children, resolved
/// with the theme above, and the kinds of the warnings of the reading.
fn picture_line(props: &str) -> (Option<(Rgb, Opacity, Length)>, Vec<&'static str>) {
let xml = format!(r#"<a:x xmlns:a="{A}">{THEME}<a:spPr>{props}</a:spPr></a:x>"#);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut children = doc.child_elements(doc.root().unwrap());
let (theme, props) = (children.next().unwrap(), children.next().unwrap());
let mut warnings = Warnings::new();
let line = super::picture_properties(&doc, props, &mut warnings).line;
let theme = ShapeTheme::read(&doc, theme, &mut warnings);
let kinds = warnings.iter().map(|(warning, _)| warning.kind()).collect();
(line.and_then(|line| line.resolve(&theme)), kinds)
}
/// Whether [`super::picture_properties`] keeps an outer shadow of a picture whose `spPr`
/// holds `xfrm` and an outer shadow with the attributes `shadow`, and the kinds of the
/// warnings of the reading.
fn picture_shadow(xfrm: &str, shadow: &str) -> (bool, Vec<&'static str>) {
let props = format!(
r#"<a:spPr xmlns:a="{A}">{xfrm}{RECT}<a:effectLst><a:outerShdw blurRad="50800" dist="38100" dir="2700000" {shadow}><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 = Warnings::new();
let look = super::picture_properties(&doc, doc.root().unwrap(), &mut warnings);
let kinds = warnings.iter().map(|(warning, _)| warning.kind()).collect();
(look.shadow.is_some(), kinds)
}
#[test]
fn keeps_a_picture_s_shadow_unless_it_turns_with_the_turned_picture() {
let fixed = r#"rotWithShape="0""#;
assert_eq!(picture_shadow("", fixed), (true, vec![]));
assert_eq!(picture_shadow("", ""), (true, vec![]));
let turned = r#"<a:xfrm rot="5400000"/>"#;
assert_eq!(picture_shadow(turned, fixed), (true, vec![]));
let left_out = (false, vec!["drawingml-shadow-not-supported"]);
assert_eq!(picture_shadow(turned, ""), left_out);
assert_eq!(picture_shadow(r#"<a:xfrm flipH="1"/>"#, ""), left_out);
assert_eq!(picture_shadow(r#"<a:xfrm rot="0"/>"#, ""), (true, vec![]));
}
#[test]
fn reads_picture_soft_edge_radius_and_clears_warning() {
let read = |effect: &str| {
let props =
format!(r#"<a:spPr xmlns:a="{A}">{RECT}<a:effectLst>{effect}</a:effectLst></a:spPr>"#);
let doc = Document::parse(props.as_bytes(), &Limits::default()).unwrap();
let mut warnings = Warnings::new();
let look = super::picture_properties(&doc, doc.root().unwrap(), &mut warnings);
let kinds: Vec<_> = warnings.iter().map(|(w, _)| w.kind()).collect();
(look.soft_edge, kinds)
};
assert_eq!(read(r#"<a:softEdge rad="0"/>"#), (None, vec![]));
assert_eq!(
read(r#"<a:softEdge rad="63500"/>"#),
(Length::from_emus(63_500), vec![])
);
}
#[test]
fn reads_shape_and_picture_glow_and_clears_warning() {
let read_shape = |effect: &str| {
let props =
format!(r#"<a:spPr xmlns:a="{A}">{RECT}<a:effectLst>{effect}</a:effectLst></a:spPr>"#);
let doc = Document::parse(props.as_bytes(), &Limits::default()).unwrap();
let mut warnings = Warnings::new();
let look = ShapeLook::read(&doc, (doc.root().ok(), None), &mut warnings);
let kinds: Vec<_> = warnings.iter().map(|(w, _)| w.kind()).collect();
(look.glow().map(|g| g.radius), kinds)
};
assert_eq!(read_shape(r#"<a:glow rad="0"/>"#), (None, vec![]));
assert_eq!(
read_shape(r#"<a:glow rad="101600"><a:srgbClr val="FF0000"/></a:glow>"#),
(Length::from_emus(101_600), vec![])
);
assert_eq!(
read_shape(r#"<a:glow rad="101600"/>"#),
(None, vec!["drawingml-glow-not-supported"])
);
}
#[test]
fn reads_closed_picture_geometries_and_builds_clip_and_outside_ring() {
let read = |geom: &str| {
let props = format!(r#"<a:spPr xmlns:a="{A}">{geom}</a:spPr>"#);
let doc = Document::parse(props.as_bytes(), &Limits::default()).unwrap();
let mut warnings = Warnings::new();
let look = super::picture_properties(&doc, doc.root().unwrap(), &mut warnings);
let kinds: Vec<_> = warnings.iter().map(|(w, _)| w.kind()).collect();
(look.geometry, kinds)
};
let frame = Edges::placed(
Length::ZERO,
Length::ZERO,
Length::from_emus(1_524_000).unwrap(),
Length::from_emus(1_016_000).unwrap(),
)
.unwrap();
let width = Length::from_emus(38_100).unwrap();
for geom_xml in [
r#"<a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom>"#,
r#"<a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 25000"/></a:avLst></a:prstGeom>"#,
r#"<a:prstGeom prst="octagon"><a:avLst/></a:prstGeom>"#,
] {
let (geom, kinds) = read(geom_xml);
assert_eq!(kinds, Vec::<&str>::new(), "{geom_xml}");
assert!(
super::picture_clip_path(&geom, frame).is_some(),
"{geom_xml}"
);
assert!(
super::picture_outside_ring(&geom, frame, width, rgb(204, 0, 0)).is_some(),
"{geom_xml}"
);
}
let (line, line_w) = read(r#"<a:prstGeom prst="line"><a:avLst/></a:prstGeom>"#);
assert_eq!(line, Geometry::Rect);
assert_eq!(line_w, vec!["drawingml-shaped-picture-not-supported"]);
assert!(super::picture_clip_path(&Geometry::Rect, frame).is_none());
}
#[test]
fn reads_a_single_solid_line_of_a_picture_and_warns_of_the_others() {
let solid = r#"<a:solidFill><a:srgbClr val="C00000"/></a:solidFill>"#;
let width = |emus| Length::from_emus(emus).unwrap();
assert_eq!(
picture_line(&format!(r#"{RECT}<a:ln w="12700">{solid}</a:ln>"#)),
(Some((rgb(192, 0, 0), Opacity::FULL, width(12_700))), vec![])
);
// A line without a width is 0.75 pt, and a scheme color takes the theme's.
assert_eq!(
picture_line(r#"<a:ln><a:solidFill><a:schemeClr val="accent1"/></a:solidFill></a:ln>"#),
(
Some((rgb(68, 114, 196), Opacity::FULL, width(9_525))),
vec![]
)
);
let left_out = (None, vec!["drawingml-picture-line-not-supported"]);
for line in [
format!(r#"<a:ln w="9525" cmpd="dbl">{solid}</a:ln>"#),
format!(r#"<a:ln w="9525">{solid}<a:prstDash val="dash"/></a:ln>"#),
r#"<a:ln><a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="C00000"/></a:gs></a:gsLst></a:gradFill></a:ln>"#.to_owned(),
] {
assert_eq!(picture_line(&line), left_out, "{line}");
}
assert_eq!(
picture_line(r#"<a:ln w="9525"><a:noFill/></a:ln>"#),
(None, vec![])
);
assert_eq!(picture_line(r#"<a:ln w="9525"/>"#), (None, vec![]));
}
#[test]
fn draws_a_picture_line_outside_the_box_with_round_outer_corners() {
let point = |p: i64| Length::from_units(p * Length::UNITS_PER_POINT);
let frame = Edges {
left: point(100),
top: point(100),
right: point(172),
bottom: point(127),
};
let Item::Path(ring) = super::outside_ring(frame, point(4), rgb(192, 0, 0)) else {
panic!("not a path");
};
assert_eq!(ring.fill_rule, FillRule::EvenOdd);
let ends: Vec<_> = ring
.commands
.iter()
.filter_map(|command| match command {
PathCommand::MoveTo(p) | PathCommand::LineTo(p) => Some(*p),
_ => None,
})
.collect();
let side = |of: fn(&f_office_paint::Point) -> Length| {
let lengths = ends.iter().map(of);
(lengths.clone().min().unwrap(), lengths.max().unwrap())
};
assert_eq!(side(|p| p.x), (point(96), point(176)));
assert_eq!(side(|p| p.y), (point(96), point(131)));
// The outer outline starts where its top left corner's curve of radius 2 pt ends.
assert_eq!(
ring.commands[0],
PathCommand::MoveTo(f_office_paint::Point {
x: point(98),
y: point(96)
})
);
// The inner outline is the box itself, with square corners.
assert!(
ring.commands
.contains(&PathCommand::MoveTo(f_office_paint::Point {
x: point(100),
y: point(100)
}))
);
}
#[test]
fn reads_canvas_background_fill_and_whole_outline() {
let xml = concat!(
r#"<wpc:wpc xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" "#,
r#"xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">"#,
r#"<wpc:bg><a:solidFill><a:srgbClr val="C0C0C0"><a:alpha val="44000"/></a:srgbClr></a:solidFill></wpc:bg>"#,
r#"<wpc:whole><a:ln w="38100"><a:solidFill><a:srgbClr val="C00000"/></a:solidFill></a:ln></wpc:whole>"#,
r#"</wpc:wpc>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let root = doc.root().unwrap();
let wpc = "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas";
let bg = doc.child(root, wpc, "bg");
let whole = doc.child(root, wpc, "whole");
let mut warnings = Warnings::new();
let look = ShapeLook::read_canvas(&doc, (bg, whole), &mut warnings);
assert!(warnings.is_empty());
let theme = ShapeTheme::default();
assert_eq!(
look.fill(&theme),
Some((
Rgb {
r: 0xC0,
g: 0xC0,
b: 0xC0
},
Opacity::clamped(44_000)
))
);
assert_eq!(
look.line(&theme),
Some((
Rgb {
r: 0xC0,
g: 0x00,
b: 0x00
},
Opacity::FULL,
Length::from_emus(38_100).unwrap(),
))
);
}
#[test]
fn resolves_theme_effect_ref_outer_shadows_with_phclr_and_overrides() {
let theme_xml = concat!(
r#"<a:theme><a:themeElements>"#,
r#"<a:clrScheme><a:accent2><a:srgbClr val="ED7D31"/></a:accent2></a:clrScheme>"#,
r#"<a:fmtScheme><a:effectStyleLst>"#,
r#"<a:effectStyle><a:effectLst><a:outerShdw blurRad="50800" dist="38100" dir="2700000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="43000"/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle>"#,
r#"<a:effectStyle><a:effectLst><a:outerShdw blurRad="50800" dist="50800" dir="5400000" rotWithShape="1"><a:schemeClr val="phClr"><a:alpha val="50000"/></a:schemeClr></a:outerShdw></a:effectLst></a:effectStyle>"#,
r#"<a:effectStyle><a:effectLst><a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"><a:srgbClr val="000000"><a:alpha val="35000"/></a:srgbClr></a:outerShdw></a:effectLst><a:sp3d><a:bevelT w="63500" h="25400"/></a:sp3d></a:effectStyle>"#,
r#"</a:effectStyleLst></a:fmtScheme></a:themeElements></a:theme>"#,
);
let check = |props: &str, style: &str| {
let (look, theme, _) = shape_in(
theme_xml,
&format!(r#"<a:prstGeom prst="rect"/>{props}"#),
style,
);
let color = look
.shadow_in(&theme)
.and_then(|s| s.color(&theme))
.map(|c| (c.rgb, c.opacity));
(color, look.theme_features(&theme))
};
assert_eq!(
[
check(
"",
r#"<a:effectRef idx="1"><a:schemeClr val="accent2"/></a:effectRef>"#
),
check(
"<a:effectLst/>",
r#"<a:effectRef idx="1"><a:schemeClr val="accent2"/></a:effectRef>"#
),
check(
"",
r#"<a:effectRef idx="2"><a:srgbClr val="C00000"><a:alpha val="80000"/></a:srgbClr></a:effectRef>"#
),
check(
r#"<a:xfrm flipH="1"/>"#,
r#"<a:effectRef idx="2"><a:schemeClr val="accent2"/></a:effectRef>"#
),
check(
"",
r#"<a:effectRef idx="3"><a:schemeClr val="accent2"/></a:effectRef>"#
),
],
[
(
Some((Rgb { r: 0, g: 0, b: 0 }, Opacity::clamped(43_000))),
vec![]
),
(None, vec![]),
(
Some((
Rgb {
r: 0xC0,
g: 0,
b: 0
},
Opacity::clamped(50_000)
)),
vec![]
),
(None, vec![Feature::Shadow]),
(
Some((Rgb { r: 0, g: 0, b: 0 }, Opacity::clamped(35_000))),
vec![Feature::ThemeStyle]
),
]
);
}
#[test]
fn draws_own_and_theme_linear_gradients_and_honors_rot_with_shape() {
let u = Length::from_units;
let theme_xml = concat!(
r#"<a:theme><a:themeElements>"#,
r#"<a:clrScheme><a:accent1><a:srgbClr val="4472C4"/></a:accent1></a:clrScheme>"#,
r#"<a:fmtScheme><a:fillStyleLst>"#,
r#"<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>"#,
r#"<a:gradFill rotWithShape="1"><a:gsLst><a:gs pos="0"><a:schemeClr val="phClr"><a:tint val="50000"/></a:schemeClr></a:gs><a:gs pos="100000"><a:schemeClr val="phClr"><a:shade val="80000"/></a:schemeClr></a:gs></a:gsLst><a:lin ang="5400000" scaled="0"/></a:gradFill>"#,
r#"</a:fillStyleLst></a:fmtScheme></a:themeElements></a:theme>"#,
);
let frame = frame_of([0, 0, 120, 48]);
let extract_axis = |props: &str, style: &str| {
let (look, theme, warnings) = shape_in(theme_xml, props, style);
assert_eq!(warnings, []);
assert_eq!(look.theme_features(&theme), []);
let items = look
.items_with_theme(&theme, frame, None, None, &[1])
.unwrap();
let [Item::Gradient(grad)] = items.as_slice() else {
panic!("expected single gradient item, got {items:?}");
};
(grad.start, grad.end, grad.stops.len())
};
// Theme fillRef idx="2" resolves phClr gradient without ThemeStyle warning.
let (start, end, count) = extract_axis(
RECT,
r#"<a:fillRef idx="2"><a:schemeClr val="accent1"/></a:fillRef>"#,
);
assert_eq!(count, 256);
assert_eq!(
(start.x, start.y, end.x, end.y),
(u(60), u(0), u(60), u(48))
);
// Omitted <a:lin> on a shape defaults to ang=0, rotWithShape=1: flipH reverses the axis,
// while rotWithShape="0" keeps the axis left-to-right in page coordinates.
let (fs, fe, _) = extract_axis(&format!(r#"<a:xfrm flipH="1"/>{RECT}{GRADIENT}"#), "");
assert_eq!((fs.x, fe.x), (u(120), u(0)));
let fixed = r#"<a:gradFill rotWithShape="0"><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst><a:lin ang="0" scaled="0"/></a:gradFill>"#;
let (ps, pe, _) = extract_axis(&format!(r#"<a:xfrm flipH="1"/>{RECT}{fixed}"#), "");
assert_eq!((ps.x, pe.x), (u(0), u(120)));
// 90° quarter turn: rotWithShape="1" turns horizontal axis vertical; rotWithShape="0" stays horizontal across rotated width (48).
let (qs, qe, _) = extract_axis(&format!(r#"<a:xfrm rot="5400000"/>{RECT}{GRADIENT}"#), "");
assert_eq!((qs.x, qs.y, qe.x, qe.y), (u(60), u(-36), u(60), u(84)));
let (ns, ne, _) = extract_axis(&format!(r#"<a:xfrm rot="5400000"/>{RECT}{fixed}"#), "");
assert_eq!((ns.x, ns.y, ne.x, ne.y), (u(36), u(24), u(84), u(24)));
}
#[test]
fn applies_theme_line_and_fill_style_phclr_modifiers_to_shapes() {
let theme_xml = concat!(
r#"<a:theme><a:themeElements>"#,
r#"<a:clrScheme><a:accent1><a:srgbClr val="4472C4"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2><a:accent6><a:srgbClr val="70AD47"/></a:accent6></a:clrScheme>"#,
r#"<a:fmtScheme>"#,
r#"<a:fillStyleLst>"#,
r#"<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>"#,
r#"<a:solidFill><a:schemeClr val="phClr"><a:tint val="50000"/></a:schemeClr></a:solidFill>"#,
r#"<a:solidFill><a:schemeClr val="phClr"><a:hueMod val="50000"/></a:schemeClr></a:solidFill>"#,
r#"</a:fillStyleLst>"#,
r#"<a:lnStyleLst>"#,
r#"<a:ln w="38100"><a:solidFill><a:schemeClr val="phClr"><a:shade val="95000"/><a:satMod val="105000"/></a:schemeClr></a:solidFill></a:ln>"#,
r#"<a:ln w="38100"><a:solidFill><a:schemeClr val="phClr"><a:tint val="50000"/></a:schemeClr></a:solidFill></a:ln>"#,
r#"<a:ln w="38100"><a:solidFill><a:schemeClr val="phClr"><a:hueMod val="50000"/></a:schemeClr></a:solidFill></a:ln>"#,
r#"</a:lnStyleLst>"#,
r#"<a:bgFillStyleLst>"#,
r#"<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>"#,
r#"<a:solidFill><a:schemeClr val="phClr"><a:tint val="50000"/></a:schemeClr></a:solidFill>"#,
r#"</a:bgFillStyleLst>"#,
r#"</a:fmtScheme></a:themeElements></a:theme>"#,
);
let hex = |rgb: Rgb| format!("{:02X}{:02X}{:02X}", rgb.r, rgb.g, rgb.b);
let check = |props: &str, style: &str| {
let (look, theme, warnings) = shape_in(theme_xml, props, style);
assert_eq!(warnings, []);
(
look.fill(&theme).map(|(c, _)| hex(c)),
look.line(&theme).map(|(c, _, w)| (hex(c), w)),
look.theme_features(&theme),
)
};
let w3 = Length::from_emus(38_100).unwrap();
let w4 = Length::from_emus(50_800).unwrap();
let cases = [
(
RECT.to_owned(),
r#"<a:lnRef idx="1"><a:schemeClr val="accent1"/></a:lnRef>"#,
None,
Some(("3F6EC3".to_owned(), w3)),
vec![],
),
(
format!(r#"{RECT}<a:ln w="50800"/>"#),
r#"<a:lnRef idx="2"><a:schemeClr val="accent2"/></a:lnRef>"#,
None,
Some(("F6CCBE".to_owned(), w4)),
vec![],
),
(
format!(
r#"{RECT}<a:ln w="38100"><a:solidFill><a:srgbClr val="C00000"/></a:solidFill></a:ln>"#
),
r#"<a:lnRef idx="1"><a:schemeClr val="accent1"/></a:lnRef>"#,
None,
Some(("C00000".to_owned(), w3)),
vec![],
),
(
RECT.to_owned(),
r#"<a:fillRef idx="2"><a:schemeClr val="accent1"/></a:fillRef>"#,
Some("C0C9E4".to_owned()),
None,
vec![],
),
(
RECT.to_owned(),
r#"<a:fillRef idx="1002"><a:schemeClr val="accent6"/></a:fillRef>"#,
Some("C9DBC1".to_owned()),
None,
vec![],
),
(
RECT.to_owned(),
r#"<a:lnRef idx="3"><a:schemeClr val="accent1"/></a:lnRef><a:fillRef idx="3"><a:schemeClr val="accent2"/></a:fillRef>"#,
Some("ED7D31".to_owned()),
Some(("4472C4".to_owned(), w3)),
vec![Feature::ThemeStyle],
),
];
for (props, style, want_fill, want_line, want_features) in cases {
assert_eq!(check(&props, style), (want_fill, want_line, want_features));
}
}
#[test]
fn draws_compound_outlines_on_closed_preset_shapes() {
let pt = |n: i64| Length::from_emus(n * 12_700).unwrap();
let frame = Edges {
left: pt(100),
top: pt(100),
right: pt(244),
bottom: pt(154),
};
let check_subpaths = |geom: &str, cmpd: &str, parts: &[i64]| {
let props = format!(
r#"{geom}<a:ln w="76200" cmpd="{cmpd}"><a:solidFill><a:srgbClr val="1F4E79"/></a:solidFill></a:ln>"#
);
let (look, _) = shape(&props, "");
assert!(!look.compound_left_out());
let items = look
.items(frame, None, Some((Rgb::BLACK, pt(6))), parts)
.unwrap();
let [Item::Path(path_item)] = items.as_slice() else {
panic!("expected single EvenOdd compound path, got {items:?}");
};
assert_eq!(path_item.fill_rule, FillRule::EvenOdd);
let closes = path_item
.commands
.iter()
.filter(|cmd| matches!(cmd, PathCommand::Close))
.count();
let curves = path_item
.commands
.iter()
.filter(|cmd| matches!(cmd, PathCommand::CubicTo(..)))
.count();
(closes, curves)
};
// Double (2 bands = 4 rings): outer band has both outer (+3pt) & inner (+1pt) rounded (8 curves),
// inner band has both square (-1pt, -3pt).
assert_eq!(check_subpaths(RECT, "dbl", &[1, 1, 1]), (4, 8));
// ThickThin (2 bands = 4 rings): only +3pt outer edge is positive (4 curves); -0.6/-1.8/-3.0 square.
assert_eq!(check_subpaths(RECT, "thickThin", &[3, 1, 1]), (4, 4));
// ThinThick (2 bands = 4 rings): +3.0/+1.8/+0.6 positive (12 curves); -3.0 square.
assert_eq!(check_subpaths(RECT, "thinThick", &[1, 1, 3]), (4, 12));
// Triple (3 bands = 6 rings): +3.0/+2.0/+1.0 positive (12 curves); -1.0/-2.0/-3.0 square.
assert_eq!(check_subpaths(RECT, "tri", &[1, 1, 2, 1, 1]), (6, 12));
// RoundRect and Ellipse compound outlines emit 4 concentric rings for 2-band compounds.
assert_eq!(
check_subpaths(r#"<a:prstGeom prst="roundRect"/>"#, "dbl", &[1, 1, 1]).0,
4
);
assert_eq!(
check_subpaths(r#"<a:prstGeom prst="ellipse"/>"#, "thickThin", &[3, 1, 1]).0,
4
);
}
#[test]
fn resolves_path_effect_gradients() {
use crate::gradient::ResolvedEffectGradientKind;
use f_office_paint::Point;
let pt = |points: i64| Length::from_emus(points * 12_700).unwrap();
let frame = Edges::placed(pt(60), pt(60), pt(120), pt(70)).unwrap();
let (look, theme, warnings) = shape_warned(&format!("{RECT}{PATH_GRADIENT}"), "");
assert_eq!(warnings, vec![]);
let resolved = look
.resolve_effect_gradient(&theme, frame)
.unwrap()
.unwrap();
let ResolvedEffectGradientKind::Radial { center, rx, ry } = resolved.kind else {
panic!("expected Radial, got {:?}", resolved.kind);
};
assert_eq!(
center,
Point {
x: pt(120),
y: pt(95)
}
);
assert_eq!(rx, ry);
assert_eq!(resolved.stops.len(), 256);
let rect_grad = r#"<a:gradFill><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="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst><a:path path="rect"><a:fillToRect l="20000" t="30000" r="80000" b="70000"/></a:path></a:gradFill>"#;
let (look, theme, warnings) = shape_warned(&format!("{RECT}{rect_grad}"), "");
assert_eq!(warnings, vec![]);
let resolved = look
.resolve_effect_gradient(&theme, frame)
.unwrap()
.unwrap();
assert_eq!(
resolved.kind,
ResolvedEffectGradientKind::Rect {
center: Point {
x: pt(84),
y: pt(81)
},
bounds: frame,
}
);
assert_eq!(resolved.stops.len(), 3);
}
#[test]
fn resolves_shape_and_translucent_effect_gradients() {
use crate::gradient::ResolvedEffectGradientKind;
use f_office_paint::Point;
let pt = |points: i64| Length::from_emus(points * 12_700).unwrap();
let frame = Edges::placed(pt(60), pt(60), pt(120), pt(70)).unwrap();
let shape_grad = r#"<a:gradFill><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="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst><a:path path="shape"/></a:gradFill>"#;
let (look, theme, warnings) =
shape_warned(&format!(r#"<a:prstGeom prst="ellipse"/>{shape_grad}"#), "");
assert_eq!(warnings, vec![]);
let resolved = look
.resolve_effect_gradient(&theme, frame)
.unwrap()
.unwrap();
assert_eq!(
resolved.kind,
ResolvedEffectGradientKind::Radial {
center: Point {
x: pt(120),
y: pt(95)
},
rx: pt(60),
ry: pt(35),
}
);
let alpha_lin = r#"<a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"><a:alpha val="100000"/></a:srgbClr></a:gs><a:gs pos="100000"><a:srgbClr val="FF0000"><a:alpha val="0"/></a:srgbClr></a:gs></a:gsLst><a:lin ang="0" scaled="0"/></a:gradFill>"#;
let (look, theme, warnings) = shape_warned(&format!("{RECT}{alpha_lin}"), "");
assert_eq!(warnings, vec![]);
let resolved = look
.resolve_effect_gradient(&theme, frame)
.unwrap()
.unwrap();
assert!(matches!(
resolved.kind,
ResolvedEffectGradientKind::Linear { .. }
));
assert_eq!(
resolved.stops,
vec![(0, [255, 0, 0, 255]), (1_000_000, [255, 0, 0, 0])]
);
}
fn parse_group_fill_pair(group_fill_xml: &str) -> Document {
let xml = format!(
r#"<root xmlns:a="{A}"><a:grpSpPr>{group_fill_xml}</a:grpSpPr><a:spPr>{RECT}<a:grpFill/></a:spPr></root>"#
);
Document::parse(xml.as_bytes(), &Limits::default()).unwrap()
}
#[test]
fn inherits_solid_and_absent_group_fill() {
let pt = |points: i64| Length::from_emus(points * 12_700).unwrap();
// Solid fill inherited without warning.
let doc = parse_group_fill_pair(r#"<a:solidFill><a:srgbClr val="3366CC"/></a:solidFill>"#);
let nodes = doc.children(doc.root().unwrap());
let mut warnings = Warnings::new();
let look = ShapeLook::read_in_group(
&doc,
(Some(nodes[1]), None),
super::GroupFill {
props: Some(nodes[0]),
frame: Edges::sized(pt(200), pt(50)),
},
&mut warnings,
);
assert!(warnings.iter().next().is_none());
assert_eq!(
look.fill(&ShapeTheme::default()),
Some((rgb(0x33, 0x66, 0xCC), Opacity::FULL))
);
// Absent group fill leaves child unfilled without warning; standalone grpFill still warns.
let doc = parse_group_fill_pair("");
let sp_props = doc.children(doc.root().unwrap())[1];
let mut warnings = Warnings::new();
let look = ShapeLook::read_in_group(
&doc,
(Some(sp_props), None),
super::GroupFill {
props: None,
frame: Edges::sized(pt(200), pt(50)),
},
&mut warnings,
);
assert!(warnings.iter().next().is_none());
assert_eq!(look.fill(&ShapeTheme::default()), None);
let mut standalone_warnings = Warnings::new();
let _ = ShapeLook::read(&doc, (Some(sp_props), None), &mut standalone_warnings);
let kinds: Vec<_> = standalone_warnings.iter().map(|(w, _)| w.kind()).collect();
assert_eq!(kinds, vec!["drawingml-group-fill-not-supported"]);
}
#[test]
fn inherits_group_box_gradient_from_group_fill() {
let pt = |points: i64| Length::from_emus(points * 12_700).unwrap();
let doc = parse_group_fill_pair(
r#"<a:gradFill><a:gsLst><a:gs pos="0"><a:srgbClr val="FF0000"/></a:gs><a:gs pos="100000"><a:srgbClr val="0000FF"/></a:gs></a:gsLst><a:lin ang="0" scaled="0"/></a:gradFill>"#,
);
let nodes = doc.children(doc.root().unwrap());
let mut warnings = Warnings::new();
let look = ShapeLook::read_in_group(
&doc,
(Some(nodes[1]), None),
super::GroupFill {
props: Some(nodes[0]),
frame: Edges {
left: -pt(120),
top: Length::ZERO,
right: pt(80),
bottom: pt(50),
},
},
&mut warnings,
);
assert!(warnings.iter().next().is_none());
let child_frame = Edges::placed(pt(180), pt(100), pt(80), pt(50)).unwrap();
let items = look
.items_with_theme(&ShapeTheme::default(), child_frame, None, None, &[])
.unwrap();
let Some(Item::Gradient(grad)) = items.first() else {
panic!("expected vector gradient item, got {items:?}");
};
assert_eq!(grad.start.x, pt(60));
assert_eq!(grad.end.x, pt(260));
}