f-office-drawingml 0.3.0

DrawingML shapes, pictures, fills, lines, themes and colors.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
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};

/// The box whose top left corner is at `x` and `y` and whose size is `width` by `height`,
/// in units.
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()
}

/// The geometry of the paths `inner`, without guides.
fn paths(inner: &str) -> Option<CustomGeometry> {
    paths_warned(inner).0
}

/// [`paths`], with the kinds and counts of the warnings of the reading.
fn paths_warned(inner: &str) -> (Option<CustomGeometry>, Vec<(&'static str, u32)>) {
    geometry_warned("", inner)
}

/// The geometry of the guides `guides` (`a:gd` elements of the `a:gdLst`) and the paths
/// `inner`, with the kinds and counts of the warnings of the reading.
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));
    // Mirrored down, the triangle stands on its tip.
    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();
    // The path is not filled, and its stroke has one quadrilateral per piece of the curve.
    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());
}

/// A path of the size and the points of [`TRIANGLE`], with `w` and the first point's `x`
/// replaced.
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();
    // A box one unit wide keeps the farthest point of a path one unit wide within the
    // range, and a box three units wide takes it beyond.
    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)
    );
    // A path that is neither filled nor stroked maps no point.
    assert_eq!(items(&far, &place(3), None, None), Ok(Vec::new()));
}

/// The segments of the first path of `geometry` in a box of `width` by `height` units.
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() {
    // The triangle of ECMA-376 Part 1, 20.1.9.11, whose base lies at 2/3 of the height. Its
    // path has no size, so its values are EMUs of the shape: two units of the box each.
    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());
    // Text that starts like a number and is no whole number of an `i64`, such as one too
    // long for it, and empty text are no guide's name: they do not read.
    for text in ["99999999999999999999", "-1.5", "+", ""] {
        assert_eq!(point(text), (None, invalid.clone()), "{text}");
    }
    // A point's `x` and `y` are required.
    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)];
    // A step with fewer points than the schema gives it, and a child of a path other than
    // its steps.
    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}");
    }
    // The path list is required.
    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
        )]
    );
    // An empty path list asks for no path, and gives no warning.
    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)];
    // A size names no guide, and a guide's name or a number that does not read there is 0,
    // as before, with a warning.
    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}");
    }
    // A guide whose formula does not read leaves the geometry out.
    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()));
    // Each of the four values of an arc is required.
    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));
}

/// A path of 100 by 100 that starts at `start` and draws the arc of `arc`, the attributes of
/// an `a:arcTo`.
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() {
    // A quarter of a circle from its right end down to its bottom end, clockwise on the page.
    // The control points lie 4/3 tan(22.5°) of the radius along the tangents.
    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]])
    );
    // A negative swing goes the other way, up to the top end.
    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]])
    );
    // A half turn is two quarter turns, and a swing of 0 draws nothing.
    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() {
    // An ellipse 200 wide and 100 high about (300, 200), from its right end through 45°: the
    // arc ends on the line at 45° from the center, (300 + 89.4, 200 + 89.4), and not at the
    // angle of its circle, which would be (300 + 141.4, 200 + 70.7).
    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() {
    // A path 3 units wide in a box 1,000 units wide: its whole numbers keep their exact share
    // of the box, and its other points are rounded to less than a unit of the box.
    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
        })
    );
    // The arc ends at (2, -1) of the path: x 2/3 of the box, y a third of it above.
    let PathCommand::CubicTo(_, _, end) = fill.commands[1] else {
        panic!();
    };
    assert_eq!((end.x.units(), end.y.units()), (666, -333));
}

/// A quarter turn on the page, whose y axis points down, takes a point right of the center
/// below it, and each further quarter turn goes on clockwise.
#[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;
    // A quarter turn from the top, clockwise, is one curve to the right.
    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));
    // The control points lie on the tangents, 4/3 tan(22.5°) of the radius from the ends.
    assert_eq!((*c1, *c2), (at(1_055, 900), at(1_100, 945)));
}

/// A full turn is four curves back to its start; more than that is out of range.
#[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());
}