use super::{CustomGeometry, OutOfRange, Place, Segment, circle_arc, items, read, turned};
use crate::{A, COORDINATE_LIMIT};
use f_office_paint::{FillRule, Item, PathCommand, Point, Rgb, stroke};
use f_office_units::{Edges, Length};
use f_office_warnings::Warnings;
use f_office_xml::{Document, Limits};
fn frame([x, y, width, height]: [i64; 4]) -> Edges<Length> {
let units = Length::from_units;
Edges::placed(units(x), units(y), units(width), units(height)).unwrap()
}
fn paths(inner: &str) -> Option<CustomGeometry> {
paths_warned(inner).0
}
fn paths_warned(inner: &str) -> (Option<CustomGeometry>, Vec<(&'static str, u32)>) {
geometry_warned("", inner)
}
fn geometry_warned(
guides: &str,
inner: &str,
) -> (Option<CustomGeometry>, Vec<(&'static str, u32)>) {
let xml = format!(
r#"<a:custGeom xmlns:a="{A}"><a:avLst/><a:gdLst>{guides}</a:gdLst><a:pathLst>{inner}</a:pathLst></a:custGeom>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut warnings = Warnings::new();
let found = read(&doc, doc.root().unwrap(), &mut warnings);
let kinds = warnings
.iter()
.map(|(warning, count)| (warning.kind(), count))
.collect();
(found, kinds)
}
#[test]
fn fills_a_lighter_or_darker_path_as_it_is_with_a_warning() {
let filled = |fill: &str| {
let path = TRIANGLE.replacen(r#"h="100""#, &format!(r#"h="100" fill="{fill}""#), 1);
let (found, warnings) = paths_warned(&path);
(found.unwrap().paths[0].filled, warnings)
};
assert_eq!(filled("none"), (false, vec![]));
assert_eq!(filled("norm"), (true, vec![]));
assert_eq!(
filled("darken"),
(true, vec![("drawingml-value-not-supported", 1)])
);
assert_eq!(filled("dark"), (true, vec![("drawingml-invalid-value", 1)]));
}
const TRIANGLE: &str = r#"<a:path w="100" h="100"><a:moveTo><a:pt x="0" y="100"/></a:moveTo><a:lnTo><a:pt x="50" y="0"/></a:lnTo><a:lnTo><a:pt x="100" y="100"/></a:lnTo><a:close/></a:path>"#;
fn ends(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) => Some((p.x.units(), p.y.units())),
_ => None,
})
.collect()
}
#[test]
fn fills_a_path_scaled_into_its_box() {
let paths = paths(TRIANGLE).unwrap();
let place = Place {
frame: frame([1_000, 2_000, 200, 400]),
flip: [false, false],
quarters: 0,
};
let red = Rgb { r: 255, g: 0, b: 0 };
let items = items(&paths, &place, Some(red), None).unwrap();
assert_eq!(items.len(), 1);
assert_eq!(
ends(&items[0]),
[(1_000, 2_400), (1_100, 2_000), (1_200, 2_400)]
);
assert!(matches!(&items[0], Item::Path(p) if p.fill_rule == FillRule::EvenOdd));
let flipped = Place {
flip: [false, true],
..place
};
let items = super::items(&paths, &flipped, Some(red), None).unwrap();
assert_eq!(ends(&items[0])[1], (1_100, 2_400));
}
#[test]
fn strokes_each_piece_and_each_curve_in_pieces() {
let curve = r#"<a:path w="10" h="10" fill="none"><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:cubicBezTo><a:pt x="0" y="10"/><a:pt x="10" y="10"/><a:pt x="10" y="0"/></a:cubicBezTo></a:path>"#;
let place = Place {
frame: frame([0, 0, 1_000, 1_000]),
flip: [false, false],
quarters: 0,
};
let black = Rgb::BLACK;
let items = items(
&paths(curve).unwrap(),
&place,
Some(black),
Some((black, Length::from_units(10))),
)
.unwrap();
assert_eq!(items.len(), 1);
let Item::Path(stroke) = &items[0] else {
panic!();
};
let closes = stroke
.commands
.iter()
.filter(|c| matches!(c, PathCommand::Close))
.count();
assert_eq!(closes, usize::try_from(stroke::CURVE_PIECES).unwrap());
}
fn triangle(w: i64, x: i64) -> String {
TRIANGLE
.replacen(r#"w="100""#, &format!(r#"w="{w}""#), 1)
.replacen(r#"x="0""#, &format!(r#"x="{x}""#), 1)
}
#[test]
fn reads_sizes_and_points_within_the_range_of_a_coordinate_only() {
let limit = COORDINATE_LIMIT;
for (w, x) in [(limit, limit), (limit, -limit), (0, 0)] {
assert_eq!(paths_warned(&triangle(w, x)).1, [], "{w} {x}");
}
for (w, x) in [(limit + 1, 0), (-1, 0), (100, limit + 1), (100, -limit - 1)] {
assert_eq!(
paths_warned(&triangle(w, x)),
(None, vec![("drawingml-invalid-value", 1)]),
"{w} {x}"
);
}
}
#[test]
fn refuses_a_point_that_maps_beyond_the_range_of_a_length() {
let place = |width| Place {
frame: frame([0, 0, width, 100]),
flip: [false, false],
quarters: 0,
};
let red = Rgb { r: 255, g: 0, b: 0 };
let far = paths(&triangle(1, COORDINATE_LIMIT)).unwrap();
assert!(items(&far, &place(1), Some(red), None).is_ok());
assert_eq!(items(&far, &place(3), Some(red), None), Err(OutOfRange));
assert_eq!(
items(&far, &place(3), None, Some((red, Length::from_units(10)))),
Err(OutOfRange)
);
assert_eq!(items(&far, &place(3), None, None), Ok(Vec::new()));
}
fn segments(geometry: &CustomGeometry, width: i64, height: i64) -> Vec<Segment> {
let mut paths = geometry
.paths(frame([0, 0, width, height]), |_| true)
.unwrap();
paths.remove(0).segments
}
#[test]
fn reads_a_value_that_names_a_guide_before_it() {
let guide = r#"<a:gd name="myGuide" fmla="*/ h 2 3"/>"#;
let path = r#"<a:path><a:moveTo><a:pt x="l" y="myGuide"/></a:moveTo><a:lnTo><a:pt x="r" y="myGuide"/></a:lnTo><a:lnTo><a:pt x="hc" y="0"/></a:lnTo><a:close/></a:path>"#;
let (found, warnings) = geometry_warned(guide, path);
assert_eq!(warnings, []);
assert_eq!(
segments(&found.unwrap(), 1_200, 600),
[
Segment::Move([0, 400]),
Segment::Line([1_200, 400]),
Segment::Line([600, 0]),
Segment::Close
]
);
}
#[test]
fn leaves_out_a_path_whose_point_does_not_read_with_a_warning() {
let point = |x: &str| {
paths_warned(&format!(
r#"<a:path w="10" h="10"><a:moveTo><a:pt x="{x}" y="0"/></a:moveTo></a:path>"#
))
};
let invalid = vec![("drawingml-invalid-value", 1)];
assert_eq!(point("T0"), (None, invalid.clone()));
assert_eq!(point("connsiteX0"), (None, invalid.clone()));
assert!(point("wd2").0.is_some());
for text in ["99999999999999999999", "-1.5", "+", ""] {
assert_eq!(point(text), (None, invalid.clone()), "{text}");
}
let missing = r#"<a:path w="10" h="10"><a:moveTo><a:pt y="0"/></a:moveTo></a:path>"#;
assert_eq!(paths_warned(missing), (None, invalid));
}
#[test]
fn leaves_out_a_geometry_whose_elements_do_not_read_with_a_warning() {
let children = vec![("drawingml-invalid-children", 1)];
for path in [
"<a:path><a:moveTo/></a:path>",
r#"<a:path><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:quadBezTo><a:pt x="1" y="1"/></a:quadBezTo></a:path>"#,
r#"<a:path><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:arc/></a:path>"#,
] {
assert_eq!(paths_warned(path), (None, children.clone()), "{path}");
}
let xml = format!(r#"<a:custGeom xmlns:a="{A}"><a:avLst/></a:custGeom>"#);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut warnings = Warnings::new();
assert_eq!(read(&doc, doc.root().unwrap(), &mut warnings), None);
let read: Vec<_> = warnings
.iter()
.map(|(w, count)| (w.to_string(), count))
.collect();
assert_eq!(
read,
[(
"the children of element custGeom do not read as the schema gives them, and the \
element counts as missing"
.to_owned(),
1
)]
);
assert_eq!(paths_warned(""), (None, vec![]));
}
#[test]
fn leaves_out_a_geometry_whose_formula_does_not_read_with_a_warning() {
let invalid = vec![("drawingml-invalid-value", 1)];
for size in ["wd2", "1.5"] {
let sized = TRIANGLE.replacen(r#"w="100""#, &format!(r#"w="{size}""#), 1);
let (found, warnings) = paths_warned(&sized);
assert_eq!(found.unwrap().paths[0].size, [0, 100], "{size}");
assert_eq!(warnings, invalid, "{size}");
}
for guide in [
r#"<a:gd name="g" fmla="*/ w 2"/>"#,
r#"<a:gd name="g"/>"#,
r#"<a:gd name="g" fmla="val later"/>"#,
] {
assert_eq!(geometry_warned(guide, TRIANGLE), (None, invalid.clone()));
}
}
#[test]
fn leaves_out_an_arc_whose_value_does_not_read_with_a_warning() {
let invalid = vec![("drawingml-invalid-value", 1)];
let arc = |swing: &str| {
paths_warned(&format!(
r#"<a:path><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:arcTo wR="5" hR="5" stAng="0" swAng="{swing}"/></a:path>"#
))
};
assert_eq!(arc("cd4").1, []);
assert_eq!(arc("nothing"), (None, invalid.clone()));
let short = r#"<a:path><a:moveTo><a:pt x="0" y="0"/></a:moveTo><a:arcTo wR="5" hR="5" stAng="0"/></a:path>"#;
assert_eq!(paths_warned(short), (None, invalid));
}
fn arc_path(start: [i64; 2], arc: &str) -> CustomGeometry {
let [x, y] = start;
paths(&format!(
r#"<a:path w="100" h="100"><a:moveTo><a:pt x="{x}" y="{y}"/></a:moveTo><a:arcTo {arc}/></a:path>"#
))
.unwrap()
}
#[test]
fn draws_an_arc_from_the_pen_clockwise_in_curves_of_a_quarter_turn_at_most() {
let quarter = arc_path([100, 50], r#"wR="50" hR="50" stAng="0" swAng="5400000""#);
assert_eq!(
segments(&quarter, 100, 100)[1],
Segment::Cubic([[100, 78], [78, 100], [50, 100]])
);
let back = arc_path([100, 50], r#"wR="50" hR="50" stAng="0" swAng="-5400000""#);
assert_eq!(
segments(&back, 100, 100)[1],
Segment::Cubic([[100, 22], [78, 0], [50, 0]])
);
let half = arc_path([100, 50], r#"wR="50" hR="50" stAng="0" swAng="10800000""#);
assert_eq!(segments(&half, 100, 100).len(), 3);
assert_eq!(
segments(&half, 100, 100)[2],
Segment::Cubic([[22, 100], [0, 78], [0, 50]])
);
let none = arc_path([100, 50], r#"wR="50" hR="50" stAng="0" swAng="0""#);
assert_eq!(segments(&none, 100, 100).len(), 1);
}
#[test]
fn ends_an_arc_at_the_angle_seen_from_the_center_of_its_ellipse() {
let arc = paths(r#"<a:path w="600" h="400"><a:moveTo><a:pt x="500" y="200"/></a:moveTo><a:arcTo wR="200" hR="100" stAng="0" swAng="2700000"/></a:path>"#).unwrap();
let Segment::Cubic([_, _, end]) = segments(&arc, 600, 400)[1] else {
panic!();
};
assert_eq!(end, [389, 289]);
}
#[test]
fn refuses_an_arc_of_more_than_a_full_turn() {
let red = Rgb { r: 255, g: 0, b: 0 };
let place = Place {
frame: frame([0, 0, 100, 100]),
flip: [false, false],
quarters: 0,
};
let full = arc_path([100, 50], r#"wR="50" hR="50" stAng="0" swAng="21600000""#);
assert!(items(&full, &place, Some(red), None).is_ok());
let more = arc_path([100, 50], r#"wR="50" hR="50" stAng="0" swAng="21600001""#);
assert_eq!(items(&more, &place, Some(red), None), Err(OutOfRange));
}
#[test]
fn keeps_the_place_of_a_whole_number_of_a_small_path_and_rounds_others_finely() {
let path = paths(r#"<a:path w="3" h="3"><a:moveTo><a:pt x="1" y="0"/></a:moveTo><a:arcTo wR="1" hR="1" stAng="cd2" swAng="cd4"/></a:path>"#).unwrap();
let place = Place {
frame: frame([0, 0, 1_000, 1_000]),
flip: [false, false],
quarters: 0,
};
let red = Rgb { r: 255, g: 0, b: 0 };
let items = items(&path, &place, Some(red), None).unwrap();
let Item::Path(fill) = &items[0] else {
panic!();
};
assert_eq!(
fill.commands[0],
PathCommand::MoveTo(f_office_paint::Point {
x: Length::from_units(333),
y: Length::ZERO
})
);
let PathCommand::CubicTo(_, _, end) = fill.commands[1] else {
panic!();
};
assert_eq!((end.x.units(), end.y.units()), (666, -333));
}
#[test]
fn turns_a_point_clockwise_about_the_center() {
let at = |x, y| (Length::from_units(x), Length::from_units(y));
let center = at(100, 50);
let turns: Vec<_> = (0..4).map(|q| turned(at(110, 50), center, q)).collect();
assert_eq!(turns, [at(110, 50), at(100, 60), at(90, 50), at(100, 40)]);
}
fn point_at(x: i64, y: i64) -> Point {
Point {
x: Length::from_units(x),
y: Length::from_units(y),
}
}
#[test]
fn draws_an_arc_of_a_circle_from_its_angle() {
let at = point_at;
let (start, curves) = circle_arc(
at(1_000, 1_000),
Length::from_units(100),
[-5_400_000, 5_400_000],
)
.unwrap();
assert_eq!(start, at(1_000, 900));
let [PathCommand::CubicTo(c1, c2, end)] = curves.as_slice() else {
panic!("not one curve");
};
assert_eq!(*end, at(1_100, 1_000));
assert_eq!((*c1, *c2), (at(1_055, 900), at(1_100, 945)));
}
#[test]
fn draws_a_full_circle_and_no_more() {
let at = point_at;
let (_, full) = circle_arc(at(0, 0), Length::from_units(100), [0, 21_600_000]).unwrap();
assert_eq!(full.len(), 4);
assert!(matches!(full.last(), Some(PathCommand::CubicTo(_, _, end)) if *end == at(100, 0)));
assert!(circle_arc(at(0, 0), Length::from_units(100), [0, 21_600_001]).is_none());
}