f-office-drawingml 0.2.2

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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
//! Custom geometry (`a:custGeom`, ECMA-376 Part 1, 20.1.9.8) and the geometry of the preset
//! shapes, which their definitions give in the same form: the guides of a geometry and its
//! paths in their own coordinates, filled and stroked in the shape's box.

use f_office_paint::{FillRule, Item, PathCommand, PathItem, Point, Rgb, stroke};
use f_office_units::{Edges, Length};
use f_office_warnings::{Name, Warnings};
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};

use crate::dash::{DashStyle, MAX_DASHES};
use crate::guide::{self, Formula, Guides, Operand};
use crate::line_end::{LineEnds, head_tangent, tail_tangent, trim_polyline};
use crate::{A, COORDINATE_LIMIT, Warning, element_name, enumeration};
use f_office_units::fixed::{
    self, FULL_TURN, HALF_TURN, ONE, QUARTER_TURN, UNIT, product, rounded,
};

/// `ST_PathFillMode`, whether a path is filled: F-Office fills the lighter and darker modes
/// with the shape's fill as it is.
pub(crate) const FILL: &Values<bool> = &Values::new(&[
    own("none", false),
    own("norm", true),
    another("lighten", true),
    another("lightenLess", true),
    another("darken", true),
    another("darkenLess", true),
]);

/// A geometry before the size of its shape gives the values of its guides: the formulas of the
/// guides and the paths of an `a:custGeom` or of the definition of a preset shape.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CustomGeometry {
    formulas: Vec<Formula>,
    paths: Vec<PathDefinition>,
}

/// One step of a literal-coordinate custom path without guide formulas.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LiteralStep {
    /// Starts a new contour at `[x, y]`.
    Move([i64; 2]),
    /// Straight segment to `[x, y]`.
    Line([i64; 2]),
    /// Cubic Bézier curve through two controls to an end point.
    Cubic([[i64; 2]; 3]),
    /// Elliptical quadrant starting horizontally tangent from the pen to `[x, y]`.
    QuadX([i64; 2]),
    /// Elliptical quadrant starting vertically tangent from the pen to `[x, y]`.
    QuadY([i64; 2]),
    /// Bounding-box elliptical arc (`[left, top, right, bottom]`, start ray, end ray).
    BoxArc {
        /// Bounding box `[left, top, right, bottom]`.
        bounds: [i64; 4],
        /// Start ray point `[x, y]`.
        start: [i64; 2],
        /// End ray point `[x, y]`.
        end: [i64; 2],
        /// Whether the arc sweeps clockwise on the page (y-down).
        clockwise: bool,
        /// Whether to move to the arc's start instead of drawing a line.
        move_to_start: bool,
    },
    /// Center/radii/angle ellipse arc (angles in 65,536ths of a degree, counterclockwise).
    AngleEllipse {
        /// Ellipse center `[cx, cy]`.
        center: [i64; 2],
        /// Ellipse radii `[rx, ry]`.
        radii: [i64; 2],
        /// Start angle in 65,536ths of a degree (0 at +x, positive counterclockwise).
        start_fd: i64,
        /// Sweep angle in 65,536ths of a degree (positive counterclockwise).
        sweep_fd: i64,
        /// Whether to move to the arc's start instead of drawing a line.
        move_to_start: bool,
    },
    /// Closes the current contour.
    Close,
}

/// One subpath of a literal-coordinate custom geometry in a box of `size`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LiteralPath {
    /// Positive `[width, height]` of the path's coordinate space.
    pub size: [i64; 2],
    /// Steps in the path's coordinates.
    pub steps: Vec<LiteralStep>,
    /// Whether this subpath is filled.
    pub filled: bool,
    /// Whether this subpath is stroked.
    pub stroked: bool,
}

/// A full turn, a quarter turn, and one degree in 60,000ths of a degree (DrawingML's angle unit).
const QUARTER_TURN_ANG: i64 = f_office_units::scale::QUARTER_TURN;
const FULL_TURN_ANG: i64 = f_office_units::scale::FULL_TURN;
const DEG_UNITS: i128 = f_office_units::scale::DEGREE as i128;

fn literal_operand(value: i64) -> Option<Operand> {
    (-COORDINATE_LIMIT..=COORDINATE_LIMIT)
        .contains(&value)
        .then_some(Operand::Number(value))
}

/// Accumulator while lowering [`LiteralStep`]s to [`Step`]s.
struct LiteralBuilder {
    pen: [i64; 2],
    start: [i64; 2],
    has_pen: bool,
    out: Vec<Step>,
}

impl LiteralBuilder {
    fn new(capacity: usize) -> Self {
        Self {
            pen: [0, 0],
            start: [0, 0],
            has_pen: false,
            out: Vec::with_capacity(capacity),
        }
    }

    fn push(&mut self, step: LiteralStep) -> Option<()> {
        let op = literal_operand;
        match step {
            LiteralStep::Move([x, y]) => self.move_or_line([x, y], true)?,
            LiteralStep::Line([x, y]) => self.move_or_line([x, y], false)?,
            LiteralStep::Cubic([[x1, y1], [x2, y2], [x3, y3]]) => {
                self.pen = [x3, y3];
                self.has_pen = true;
                self.out.push(Step::Cubic([
                    [op(x1)?, op(y1)?],
                    [op(x2)?, op(y2)?],
                    [op(x3)?, op(y3)?],
                ]));
            }
            LiteralStep::QuadX(end) => self.push_quad_arc(end, true)?,
            LiteralStep::QuadY(end) => self.push_quad_arc(end, false)?,
            LiteralStep::BoxArc {
                bounds,
                start,
                end,
                clockwise,
                move_to_start,
            } => self.push_box_arc(bounds, start, end, clockwise, move_to_start)?,
            LiteralStep::AngleEllipse {
                center,
                radii,
                start_fd,
                sweep_fd,
                move_to_start,
            } => self.push_angle_ellipse(center, radii, start_fd, sweep_fd, move_to_start)?,
            LiteralStep::Close => {
                self.pen = self.start;
                self.out.push(Step::Close);
            }
        }
        Some(())
    }

    fn move_or_line(&mut self, point: [i64; 2], as_move: bool) -> Option<()> {
        let ops = [literal_operand(point[0])?, literal_operand(point[1])?];
        self.pen = point;
        self.has_pen = true;
        if as_move {
            self.start = point;
            self.out.push(Step::Move(ops));
        } else {
            self.out.push(Step::Line(ops));
        }
        Some(())
    }

    /// Emits a 90° elliptical quadrant (`qx` when `horizontal_first`, `qy` otherwise).
    fn push_quad_arc(&mut self, to: [i64; 2], horizontal_first: bool) -> Option<()> {
        let dx = to[0].checked_sub(self.pen[0])?;
        let dy = to[1].checked_sub(self.pen[1])?;
        self.pen = to;
        if dx == 0 || dy == 0 {
            self.out.push(Step::Line([
                literal_operand(to[0])?,
                literal_operand(to[1])?,
            ]));
            return Some(());
        }
        let (start_angle, sweep_angle) = quad_arc_angles(dx, dy, horizontal_first);
        self.out.push(Step::Arc([
            literal_operand(dx.abs())?,
            literal_operand(dy.abs())?,
            Operand::Number(start_angle),
            Operand::Number(sweep_angle),
        ]));
        Some(())
    }

    fn push_box_arc(
        &mut self,
        bounds: [i64; 4],
        start_ray: [i64; 2],
        end_ray: [i64; 2],
        clockwise: bool,
        move_to_start: bool,
    ) -> Option<()> {
        let [left, top, right, bottom] = bounds;
        let center2 = [
            i128::from(left) + i128::from(right),
            i128::from(top) + i128::from(bottom),
        ];
        let rx = i64::try_from((i128::from(right) - i128::from(left)).abs() / 2).ok()?;
        let ry = i64::try_from((i128::from(bottom) - i128::from(top)).abs() / 2).ok()?;
        if rx == 0 || ry == 0 {
            return self.move_or_line(end_ray, move_to_start || !self.has_pen);
        }
        let ray_ang = |ray: [i64; 2]| -> Option<i64> {
            let raw = fixed::angle_of(
                2 * i128::from(ray[0]) - center2[0],
                2 * i128::from(ray[1]) - center2[1],
            );
            Some(
                i64::try_from(rounded(raw, ONE))
                    .ok()?
                    .rem_euclid(FULL_TURN_ANG),
            )
        };
        let (start_angle, end_angle) = (ray_ang(start_ray)?, ray_ang(end_ray)?);
        let sweep_angle = arc_swing(start_angle, end_angle, clockwise);
        self.push_ellipse_arc(center2, [rx, ry], start_angle, sweep_angle, move_to_start)
    }

    fn push_angle_ellipse(
        &mut self,
        center: [i64; 2],
        radii: [i64; 2],
        start_fd: i64,
        sweep_fd: i64,
        move_to_start: bool,
    ) -> Option<()> {
        let [rx, ry] = [radii[0].abs(), radii[1].abs()];
        if rx == 0 || ry == 0 {
            return self.move_or_line(center, move_to_start || !self.has_pen);
        }
        // VML ae/al angles are in 65,536ths of a degree counterclockwise; DrawingML is clockwise.
        let start_cw = -rounded(i128::from(start_fd) * DEG_UNITS, ONE);
        let sweep_cw = -rounded(i128::from(sweep_fd) * DEG_UNITS, ONE);
        let full = i128::from(FULL_TURN_ANG);
        let start_angle = i64::try_from(start_cw.rem_euclid(full)).ok()?;
        let sweep_angle = i64::try_from(sweep_cw.clamp(-full, full)).ok()?;
        let center2 = [i128::from(center[0]) * 2, i128::from(center[1]) * 2];
        self.push_ellipse_arc(center2, [rx, ry], start_angle, sweep_angle, move_to_start)
    }

    fn push_ellipse_arc(
        &mut self,
        center2: [i128; 2],
        radii: [i64; 2],
        start_angle: i64,
        sweep_angle: i64,
        move_to_start: bool,
    ) -> Option<()> {
        let start_pt = ellipse_point(center2, radii, start_angle)?;
        let end_pt = ellipse_point(
            center2,
            radii,
            (start_angle + sweep_angle).rem_euclid(FULL_TURN_ANG),
        )?;
        self.move_or_line(start_pt, move_to_start || !self.has_pen)?;
        self.out.push(Step::Arc([
            literal_operand(radii[0])?,
            literal_operand(radii[1])?,
            Operand::Number(start_angle),
            Operand::Number(sweep_angle),
        ]));
        self.pen = end_pt;
        Some(())
    }
}

fn quad_arc_angles(dx: i64, dy: i64, horizontal_first: bool) -> (i64, i64) {
    let same_sign = (dx > 0) == (dy > 0);
    if horizontal_first {
        let start = if dy > 0 {
            3 * QUARTER_TURN_ANG
        } else {
            QUARTER_TURN_ANG
        };
        let sweep = if same_sign {
            QUARTER_TURN_ANG
        } else {
            -QUARTER_TURN_ANG
        };
        (start, sweep)
    } else {
        let start = if dx > 0 { 2 * QUARTER_TURN_ANG } else { 0 };
        let sweep = if same_sign {
            -QUARTER_TURN_ANG
        } else {
            QUARTER_TURN_ANG
        };
        (start, sweep)
    }
}

fn arc_swing(start: i64, end: i64, clockwise: bool) -> i64 {
    if clockwise {
        let delta = (end - start).rem_euclid(FULL_TURN_ANG);
        if delta == 0 { FULL_TURN_ANG } else { delta }
    } else {
        let delta = (start - end).rem_euclid(FULL_TURN_ANG);
        -if delta == 0 { FULL_TURN_ANG } else { delta }
    }
}

/// Computes the point on an ellipse at `center2 / 2` with radii `radii` at geometric ray angle
/// `ang_deg60` (in 60,000ths of a degree, clockwise y-down).
fn ellipse_point(center2: [i128; 2], radii: [i64; 2], ang_deg60: i64) -> Option<[i64; 2]> {
    let [wr, hr] = [i128::from(radii[0]) * ONE, i128::from(radii[1]) * ONE];
    let t = parametric(i128::from(ang_deg60) * ONE, [wr, hr]);
    let [sin, cos] = fixed::sin_cos(t);
    let px = rounded(center2[0] * (ONE / 2) + product(wr, cos), ONE);
    let py = rounded(center2[1] * (ONE / 2) + product(hr, sin), ONE);
    Some([i64::try_from(px).ok()?, i64::try_from(py).ok()?])
}

impl CustomGeometry {
    /// Builds a [`CustomGeometry`] from literal-coordinate subpaths (such as parsed VML paths).
    /// Returns `None` when `paths` is empty, any size is not positive or exceeds
    /// [`COORDINATE_LIMIT`], or any coordinate lies outside `-COORDINATE_LIMIT..=COORDINATE_LIMIT`.
    #[must_use]
    pub fn from_literal_paths(paths: Vec<LiteralPath>) -> Option<Self> {
        if paths.is_empty() {
            return None;
        }
        let mut defs = Vec::with_capacity(paths.len());
        for path in paths {
            let [w, h] = path.size;
            if !(1..=COORDINATE_LIMIT).contains(&w) || !(1..=COORDINATE_LIMIT).contains(&h) {
                return None;
            }
            let mut builder = LiteralBuilder::new(path.steps.len());
            for step in path.steps {
                builder.push(step)?;
            }
            defs.push(PathDefinition {
                size: [w, h],
                steps: builder.out,
                filled: path.filled,
                stroked: path.stroked,
            });
        }
        Some(Self {
            formulas: Vec::new(),
            paths: defs,
        })
    }
}

/// One path of a geometry (`a:path`, ECMA-376 Part 1, 20.1.9.15), with operands for its values.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PathDefinition {
    /// The width and the height of the path's coordinates, which fill the shape's box; 0 for
    /// the shape's own width or height in EMUs, as the definitions of the presets have it.
    pub(crate) size: [i64; 2],
    pub(crate) steps: Vec<Step>,
    /// Whether the path is filled (`fill` other than `none`).
    pub(crate) filled: bool,
    /// Whether the path is stroked (`stroke` other than false).
    pub(crate) stroked: bool,
}

/// One step of a path, with operands for its values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Step {
    Move([Operand; 2]),
    Line([Operand; 2]),
    /// An arc (`a:arcTo`, ECMA-376 Part 1, 20.1.9.4): its width and height radii (`wR`, `hR`),
    /// then its start and swing angles (`stAng`, `swAng`).
    Arc([Operand; 4]),
    Quad([[Operand; 2]; 2]),
    Cubic([[Operand; 2]; 3]),
    Close,
}

/// One path of a geometry in a box, with its points in whole units of its coordinates.
#[derive(Clone, Debug, PartialEq, Eq)]
struct CustomPath {
    /// The width and the height of the path's coordinates, which fill the shape's box.
    size: [i64; 2],
    segments: Vec<Segment>,
    filled: bool,
    stroked: bool,
}

/// One segment of a path in a box, with its points in the path's coordinates.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Segment {
    Move([i64; 2]),
    Line([i64; 2]),
    Quad([[i64; 2]; 2]),
    Cubic([[i64; 2]; 3]),
    Close,
}

/// How a path's coordinates map onto the page: the box, the flips and the quarter turns.
#[derive(Clone, Copy, Debug)]
pub struct Place {
    /// The box of the shape on the page.
    pub frame: Edges<Length>,
    /// Whether the path is mirrored across and down.
    pub flip: [bool; 2],
    /// The number of clockwise quarter turns about the box's center.
    pub quarters: i64,
}

/// Reads an `a:custGeom`: its guides (`a:avLst`, then `a:gdLst`) and its paths, with the
/// warnings of their formulas, fill modes, sizes and values in `warnings`. A guide whose formula
/// does not read (`Guides::add`), a value that names no guide before it, or a size or a value
/// beyond the range of its type gives `None` with a warning, and a value that starts like a
/// number and is no whole number, or a step of another kind, gives `None`.
#[must_use]
pub fn read(
    doc: &Document,
    geometry: NodeId,
    warnings: &mut Warnings<Warning>,
) -> Option<CustomGeometry> {
    let mut guides = Guides::default();
    for list in ["avLst", "gdLst"].map(|name| doc.child(geometry, A, name)) {
        let entries = list.into_iter().flat_map(|list| doc.child_elements(list));
        for gd in entries.filter(|node| doc.is(*node, A, "gd")) {
            let name = doc.attribute(gd, None, "name").unwrap_or_default();
            let read = doc
                .attribute(gd, None, "fmla")
                .and_then(|formula| guides.add(name, formula));
            if read.is_none() {
                warnings.push(Warning::InvalidValue {
                    element: element_name(doc, gd),
                    attribute: Name::new("fmla"),
                });
                return None;
            }
        }
    }
    // The path list is required.
    let Some(list) = doc.child(geometry, A, "pathLst") else {
        warnings.push(Warning::InvalidChildren {
            element: element_name(doc, geometry),
        });
        return None;
    };
    let paths: Vec<PathDefinition> = doc
        .child_elements(list)
        .filter(|node| doc.is(*node, A, "path"))
        .map(|node| read_path(doc, node, &guides, warnings))
        .collect::<Option<_>>()?;
    (!paths.is_empty()).then(|| CustomGeometry::new(guides, paths))
}

fn read_path(
    doc: &Document,
    node: NodeId,
    guides: &Guides<'_>,
    warnings: &mut Warnings<Warning>,
) -> Option<PathDefinition> {
    // `w` and `h` are `ST_PositiveCoordinate`, which names no guide; one that is missing is 0,
    // the schema's default, and one that does not read is 0, with a warning.
    let mut size = |name: &str| match coordinate(doc, node, (name, 0), warnings) {
        Coordinate::Missing | Coordinate::Unreadable => Some(0),
        Coordinate::Guide(_) => {
            warnings.push(Warning::InvalidValue {
                element: element_name(doc, node),
                attribute: Name::new(name),
            });
            Some(0)
        }
        Coordinate::Value(value) => Some(value),
        Coordinate::Outside => None,
    };
    let size = [size("w")?, size("h")?];
    let steps = doc
        .child_elements(node)
        .map(|child| read_step(doc, child, guides, warnings))
        .collect::<Option<Vec<Step>>>()?;
    Some(PathDefinition {
        size,
        steps,
        filled: enumeration(doc, node, "fill", (FILL, warnings)).unwrap_or(true),
        stroked: stroked(doc.attribute(node, None, "stroke")),
    })
}

/// Whether a path whose attribute `stroke` is `value` is stroked: unless it is false.
pub(crate) fn stroked(value: Option<&str>) -> bool {
    !value.is_some_and(|value| ["0", "false"].contains(&value))
}

/// The elements of the steps of a path that have points, in the order of [`step_of`].
const POINT_STEPS: [&str; 5] = ["close", "moveTo", "lnTo", "quadBezTo", "cubicBezTo"];

/// Reads one step of a path. A value that does not read ([`operand`]), a step with fewer
/// points than the schema gives it, or a child of another kind, which the schema does not allow
/// in a path, gives `None`, each with a warning.
fn read_step(
    doc: &Document,
    child: NodeId,
    guides: &Guides<'_>,
    warnings: &mut Warnings<Warning>,
) -> Option<Step> {
    if doc.is(child, A, "arcTo") {
        let mut at = |name| operand(doc, child, name, guides, warnings);
        return Some(Step::Arc([
            at("wR")?,
            at("hR")?,
            at("stAng")?,
            at("swAng")?,
        ]));
    }
    let Some(kind) = POINT_STEPS.iter().position(|name| doc.is(child, A, name)) else {
        warnings.push(Warning::InvalidChildren {
            element: Name::new("path"),
        });
        return None;
    };
    let step = step_of(kind, &points(doc, child, guides, warnings)?);
    if step.is_none() {
        warnings.push(Warning::InvalidChildren {
            element: element_name(doc, child),
        });
    }
    step
}

/// The step of the element `POINT_STEPS[kind]` with the points `all`, or `None` when it has
/// too few.
fn step_of(kind: usize, all: &[[Operand; 2]]) -> Option<Step> {
    let at = |i: usize| all.get(i).copied();
    Some(match kind {
        0 => Step::Close,
        1 => Step::Move(at(0)?),
        2 => Step::Line(at(0)?),
        3 => Step::Quad([at(0)?, at(1)?]),
        _ => Step::Cubic([at(0)?, at(1)?, at(2)?]),
    })
}

/// The points (`a:pt`) of a step, each value of which must read ([`operand`]).
fn points(
    doc: &Document,
    step: NodeId,
    guides: &Guides<'_>,
    warnings: &mut Warnings<Warning>,
) -> Option<Vec<[Operand; 2]>> {
    doc.child_elements(step)
        .filter(|pt| doc.is(*pt, A, "pt"))
        .map(|pt| {
            let mut at = |name| operand(doc, pt, name, guides, warnings);
            Some([at("x")?, at("y")?])
        })
        .collect()
}

/// The operand of the attribute `name` of `node` (`ST_AdjCoordinate`, ECMA-376 Part 1,
/// 20.1.10.2, or `ST_AdjAngle`, 20.1.10.1): a whole number from `-COORDINATE_LIMIT` to
/// [`COORDINATE_LIMIT`], or the name of a guide before it or of a built-in guide. A name of no
/// such guide, a number beyond the range, text that starts like a number and is no whole number
/// and a missing attribute, which the schema requires of each point and arc, give `None` with
/// a warning.
fn operand(
    doc: &Document,
    node: NodeId,
    name: &str,
    guides: &Guides<'_>,
    warnings: &mut Warnings<Warning>,
) -> Option<Operand> {
    match coordinate(doc, node, (name, -COORDINATE_LIMIT), warnings) {
        Coordinate::Value(value) => Some(Operand::Number(value)),
        Coordinate::Guide(text) => {
            let found = guides.guide(text);
            if found.is_none() {
                warnings.push(Warning::InvalidValue {
                    element: element_name(doc, node),
                    attribute: Name::new(name),
                });
            }
            found
        }
        Coordinate::Missing => {
            warnings.push(Warning::InvalidValue {
                element: element_name(doc, node),
                attribute: Name::new(name),
            });
            None
        }
        Coordinate::Unreadable | Coordinate::Outside => None,
    }
}

/// A value of a custom path as its attribute gives it.
enum Coordinate<'a> {
    /// The attribute is missing.
    Missing,
    /// The attribute is text that starts like a number and is no whole number of an `i64`, such
    /// as a number too long for it or with a fraction, or empty text, which does not read.
    Unreadable,
    /// The attribute is text that does not start like a number, so the name of a guide: a
    /// value is a number or a guide's name (`ST_AdjCoordinate`, ECMA-376 Part 1, 20.1.10.2).
    Guide(&'a str),
    /// A whole number within the range of the value's type.
    Value(i64),
    /// A whole number outside the range, which does not read.
    Outside,
}

/// The whole number of the attribute `name` of `node`, in no namespace, from `low` to
/// [`COORDINATE_LIMIT`], with a warning that it does not read when it lies outside, or when it
/// is text that starts with a digit or a sign and is no whole number of an `i64`, such as a
/// number too long for it, or empty text.
fn coordinate<'a>(
    doc: &'a Document,
    node: NodeId,
    (name, low): (&str, i64),
    warnings: &mut Warnings<Warning>,
) -> Coordinate<'a> {
    let Some(text) = doc.attribute(node, None, name) else {
        return Coordinate::Missing;
    };
    let Ok(value) = text.parse::<i64>() else {
        let number_like = text
            .chars()
            .next()
            .is_none_or(|first| first.is_ascii_digit() || matches!(first, '+' | '-'));
        return if number_like {
            warnings.push(Warning::InvalidValue {
                element: element_name(doc, node),
                attribute: Name::new(name),
            });
            Coordinate::Unreadable
        } else {
            Coordinate::Guide(text)
        };
    };
    if (low..=COORDINATE_LIMIT).contains(&value) {
        return Coordinate::Value(value);
    }
    warnings.push(Warning::InvalidValue {
        element: element_name(doc, node),
        attribute: Name::new(name),
    });
    Coordinate::Outside
}

/// A place that a custom path's values give beyond [`Length::FILE_LIMIT`] from the shape's box,
/// which only a path with a tiny size and a far point maps to, a guide whose value lies beyond
/// 2^47 units (`fixed::LIMIT`) or is the root of a value below 0, or an arc that swings more than a full
/// turn: the shape is not drawn, and the format crate warns of it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OutOfRange;

/// The largest size of a point of a path in its scaled coordinates. A larger one lies beyond
/// [`Length::FILE_LIMIT`] from the box, and below it every sum and difference of the mapping
/// fits in an `i64`.
const POINT_LIMIT: i64 = 1 << 61;

impl CustomGeometry {
    /// The geometry of the formulas of `guides` and of `paths`.
    pub(crate) fn new(guides: Guides<'_>, paths: Vec<PathDefinition>) -> Self {
        Self {
            formulas: guides.into_formulas(),
            paths,
        }
    }

    /// The paths that `drawn` keeps, in the box `frame`: the built-in guides measure the box,
    /// and each point is rounded to a whole unit of its path's coordinates ([`Axis`]).
    fn paths(
        &self,
        frame: Edges<Length>,
        drawn: impl Fn(&PathDefinition) -> bool,
    ) -> Result<Vec<CustomPath>, OutOfRange> {
        let sides = [frame.width().units(), frame.height().units()];
        // A unit of a box is half an EMU, and the guides measure the box in EMUs.
        let size = sides.map(|side| i128::from(side) * ONE / 2);
        let values = guide::values(&self.formulas, size).ok_or(OutOfRange)?;
        self.paths
            .iter()
            .filter(|path| drawn(path))
            .map(|path| path.in_box(&values, sides))
            .collect()
    }
}

/// How one axis of a path's coordinates maps onto a side of the box: the extent of the
/// coordinates that fills the side, and the whole scale from the path's own units to them.
#[derive(Clone, Copy, Debug)]
struct Axis {
    extent: i64,
    scale: i64,
}

impl Axis {
    /// The axis of a path of `size` own units across a side of the box of `side` units. A size
    /// of 0 is the shape's own side in EMUs, two units of the box each. For another size, the
    /// scale is the smallest whole number that makes a unit of the coordinates at most a unit
    /// of the box: a whole number of the path keeps its exact place, and a point that a guide
    /// or an arc gives is rounded to less than a unit of the box.
    fn new(size: i64, box_side: i64) -> Result<Self, OutOfRange> {
        if size <= 0 {
            return Ok(Self {
                extent: box_side,
                scale: 2,
            });
        }
        let scale = ((box_side.max(0) + size - 1) / size).max(1);
        let extent = size.checked_mul(scale).ok_or(OutOfRange)?;
        Ok(Self { extent, scale })
    }

    /// The coordinate of `operand` with the values `values` of the geometry.
    fn place(self, values: &[i128], operand: Operand) -> Result<i64, OutOfRange> {
        match operand {
            Operand::Number(number) => number
                .checked_mul(self.scale)
                .filter(|place| place.abs() <= POINT_LIMIT)
                .ok_or(OutOfRange),
            Operand::Guide(_) => self.whole(guide::value(values, operand)),
        }
    }

    /// The coordinate of `value`, in 65,536ths of the path's own units, rounded to a whole
    /// unit of the coordinates.
    fn whole(self, value: i128) -> Result<i64, OutOfRange> {
        value
            .checked_mul(i128::from(self.scale))
            .map(|scaled| rounded(scaled, ONE))
            .and_then(|place| i64::try_from(place).ok())
            .filter(|place| place.abs() <= POINT_LIMIT)
            .ok_or(OutOfRange)
    }
}

impl PathDefinition {
    /// The path with the values `values` of its geometry, in a box whose sides are `sides`
    /// units.
    fn in_box(&self, values: &[i128], sides: [i64; 2]) -> Result<CustomPath, OutOfRange> {
        let axes = [
            Axis::new(self.size[0], sides[0])?,
            Axis::new(self.size[1], sides[1])?,
        ];
        let value = |operand| guide::value(values, operand);
        let place = |[x, y]: [Operand; 2]| -> Result<[i64; 2], OutOfRange> {
            Ok([axes[0].place(values, x)?, axes[1].place(values, y)?])
        };
        let whole = |[x, y]: [i128; 2]| -> Result<[i64; 2], OutOfRange> {
            Ok([axes[0].whole(x)?, axes[1].whole(y)?])
        };
        let mut segments = Vec::with_capacity(self.steps.len());
        // The pen and the start of the outline, values in the path's own units, where an arc
        // starts and a close goes back to.
        let (mut start, mut pen) = ([0; 2], [0; 2]);
        for step in &self.steps {
            match *step {
                Step::Move(p) => {
                    (start, pen) = (p.map(value), p.map(value));
                    segments.push(Segment::Move(place(p)?));
                }
                Step::Line(p) => {
                    pen = p.map(value);
                    segments.push(Segment::Line(place(p)?));
                }
                Step::Quad([c, p]) => {
                    pen = p.map(value);
                    segments.push(Segment::Quad([place(c)?, place(p)?]));
                }
                Step::Cubic([c1, c2, p]) => {
                    pen = p.map(value);
                    segments.push(Segment::Cubic([place(c1)?, place(c2)?, place(p)?]));
                }
                Step::Arc([wr, hr, angle, swing]) => {
                    let radii = [value(wr), value(hr)];
                    for [c1, c2, end] in arc(pen, radii, [value(angle), value(swing)])? {
                        segments.push(Segment::Cubic([whole(c1)?, whole(c2)?, whole(end)?]));
                        pen = end;
                    }
                }
                Step::Close => {
                    pen = start;
                    segments.push(Segment::Close);
                }
            }
        }
        Ok(CustomPath {
            size: [axes[0].extent, axes[1].extent],
            segments,
            filled: self.filled,
            stroked: self.stroked,
        })
    }
}

/// The cubic curves of an arc (`a:arcTo`, ECMA-376 Part 1, 20.1.9.4) that starts at `pen`, on
/// an ellipse of the radii `radii`, from the start angle through the swing of `angles`, in
/// 60,000ths of a degree, clockwise on the page, whose y axis points down; every number is a
/// value ([`fixed`]). Each angle is that of a point of the ellipse seen from its center, as the
/// definitions of the presets compute the ends of their arcs (`cat2` and `sat2`). The arc is cut
/// into curves of at most a quarter turn of the ellipse, each given by its two control points
/// and its end. A swing of 0 has no curve, and a swing of more than a full turn is out of range.
fn arc(
    pen: [i128; 2],
    radii: [i128; 2],
    [angle, swing]: [i128; 2],
) -> Result<Vec<[[i128; 2]; 3]>, OutOfRange> {
    if swing.abs() > FULL_TURN {
        return Err(OutOfRange);
    }
    if swing == 0 {
        return Ok(Vec::new());
    }
    let [wr, hr] = radii;
    let from = parametric(angle, radii);
    let sweep = parametric(angle + swing, radii) - from;
    let [sin, cos] = fixed::sin_cos(from);
    let center = [pen[0] - product(wr, cos), pen[1] - product(hr, sin)];
    // The point of the ellipse at the angle `t` and its tangent there: how the point moves
    // for a turn of `t` of one radian.
    let point_and_tangent = |t: i128| {
        let [sin, cos] = fixed::sin_cos(t);
        (
            [center[0] + product(wr, cos), center[1] + product(hr, sin)],
            [-product(wr, sin), product(hr, cos)],
        )
    };
    let count: i128 = match sweep.abs() {
        size if size <= QUARTER_TURN => 1,
        size if size <= HALF_TURN => 2,
        size if size <= 3 * QUARTER_TURN => 3,
        _ => 4,
    };
    Ok((0..count)
        .map(|k| {
            let a = from + rounded(sweep * k, count);
            let b = from + rounded(sweep * (k + 1), count);
            // The control points of a piece of an ellipse lie along its tangents at its ends,
            // 4/3 tan(θ/4) of the way for a piece of θ.
            let [sin, cos] = fixed::sin_cos(rounded(b - a, 4));
            let kappa = rounded(4 * sin * UNIT, 3 * cos);
            let ((start, out), (end, back)) = (point_and_tangent(a), point_and_tangent(b));
            [
                [
                    start[0] + product(kappa, out[0]),
                    start[1] + product(kappa, out[1]),
                ],
                [
                    end[0] - product(kappa, back[0]),
                    end[1] - product(kappa, back[1]),
                ],
                end,
            ]
        })
        .collect())
}

/// The point of the circle around `center` with the radius `radius` at `angle`, in 60,000ths
/// of a degree clockwise from the right on a page whose y axis points down, and after it the
/// cubic curves of its arc through the swing `swing` from there, cut as the arcs of a preset
/// shape are cut.
/// `None` when the swing is more than a full turn or a place leaves the range of a value.
#[must_use]
pub fn circle_arc(
    center: Point,
    radius: Length,
    [angle, swing]: [i64; 2],
) -> Option<(Point, Vec<PathCommand>)> {
    let value = |length: Length| {
        let units = i128::from(length.units());
        (units.abs() < fixed::LIMIT / ONE).then_some(units * ONE)
    };
    let point = |[x, y]: [i128; 2]| {
        Some(Point {
            x: Length::from_units(i64::try_from(rounded(x, ONE)).ok()?),
            y: Length::from_units(i64::try_from(rounded(y, ONE)).ok()?),
        })
    };
    let (r, x, y) = (value(radius)?, value(center.x)?, value(center.y)?);
    let from = i128::from(angle) * ONE;
    let [sin, cos] = fixed::sin_cos(from);
    let pen = [x + product(r, cos), y + product(r, sin)];
    let curves = arc(pen, [r, r], [from, i128::from(swing) * ONE]).ok()?;
    let commands = curves
        .into_iter()
        .map(|[c1, c2, end]| Some(PathCommand::CubicTo(point(c1)?, point(c2)?, point(end)?)))
        .collect::<Option<_>>()?;
    Some((point(pen)?, commands))
}

/// The angle `t` of the point (`wr` cos t, `hr` sin t) of an ellipse of the radii `[wr, hr]`
/// that is seen from the ellipse's center at `angle`, in 60,000ths of a degree, in the same
/// turn as `angle`: a value.
fn parametric(angle: i128, [wr, hr]: [i128; 2]) -> i128 {
    let [sin, cos] = fixed::sin_cos(angle);
    let t = fixed::angle_of(hr * cos, wr * sin);
    let gap = t - angle;
    angle + gap - FULL_TURN * rounded(gap, FULL_TURN)
}

impl Place {
    /// The point on the page of a point of `path`, as [`Place::map`] gives it.
    fn on_page(&self, path: &CustomPath, p: [i64; 2]) -> Result<Point, OutOfRange> {
        self.map(path.size, p).map(point)
    }

    /// The point on the page of a path point, or [`OutOfRange`] when its share of the box lies
    /// beyond [`Length::FILE_LIMIT`].
    fn map(&self, size: [i64; 2], [px, py]: [i64; 2]) -> Result<(Length, Length), OutOfRange> {
        let (x, y) = (self.frame.left, self.frame.top);
        let (w, h) = (self.frame.width(), self.frame.height());
        // A path coordinate's share of the box multiplies a number of the file by a length,
        // in `i128`. The coordinates and the size lie within `POINT_LIMIT`, so the flip fits.
        let along = |value: i64, length: Length, extent: i64, flip: bool| {
            let value = if flip { extent - value } else { value };
            if extent == 0 {
                return Ok(Length::ZERO);
            }
            let share = i128::from(value) * i128::from(length.units()) / i128::from(extent);
            i64::try_from(share)
                .ok()
                .filter(|share| (-Length::FILE_LIMIT..=Length::FILE_LIMIT).contains(share))
                .map(Length::from_units)
                .ok_or(OutOfRange)
        };
        let point = (
            x + along(px, w, size[0], self.flip[0])?,
            y + along(py, h, size[1], self.flip[1])?,
        );
        let center = (x + w.div_toward_zero(2), y + h.div_toward_zero(2));
        Ok(turned(point, center, self.quarters))
    }
}

/// A point turned clockwise by `quarters` quarter turns about `center`, on the page, whose y
/// axis points down.
pub(crate) fn turned(
    (x, y): (Length, Length),
    center: (Length, Length),
    quarters: i64,
) -> (Length, Length) {
    let (mut dx, mut dy) = (x - center.0, y - center.1);
    for _ in 0..quarters {
        (dx, dy) = (-dy, dx);
    }
    (center.0 + dx, center.1 + dy)
}

const fn point((x, y): (Length, Length)) -> Point {
    Point { x, y }
}

/// The items of a geometry in its place: the fills of the filled paths, then the strokes of
/// the stroked ones, or [`OutOfRange`] when a point maps beyond the range of a length. Only
/// the paths that are drawn map their points. A path is filled by the even-odd rule, so that
/// an inner outline cuts a hole. A stroke is made of straight pieces, `half` thick on each
/// side and longer by `half` at each end, so that they meet at the corners.
///
/// # Errors
///
/// [`OutOfRange`] when a point of a drawn path maps beyond [`Length::FILE_LIMIT`] from the box,
/// or an arc of a drawn path swings more than a full turn.
pub fn items(
    geometry: &CustomGeometry,
    place: &Place,
    fill: Option<Rgb>,
    line: Option<(Rgb, Length)>,
) -> Result<Vec<Item>, OutOfRange> {
    items_styled(geometry, place, fill, line, None, LineEnds::default())
}

/// Like [`items`], stroking each stroked subpath with `dash` and drawing `ends` on open subpaths.
pub(crate) fn items_styled(
    geometry: &CustomGeometry,
    place: &Place,
    fill: Option<Rgb>,
    line: Option<(Rgb, Length)>,
    dash: Option<&DashStyle>,
    ends: LineEnds,
) -> Result<Vec<Item>, OutOfRange> {
    let (filled, stroked) = fill_and_stroke(geometry, place, fill, line, dash, ends)?;
    Ok(filled.into_iter().chain(stroked).map(Item::Path).collect())
}

/// Like [`items_styled`], returning the filled path and stroked path separately so a caller can
/// replace the filled path with a gradient without confusing it with a stroke-only geometry.
pub(crate) fn fill_and_stroke(
    geometry: &CustomGeometry,
    place: &Place,
    fill: Option<Rgb>,
    line: Option<(Rgb, Length)>,
    dash: Option<&DashStyle>,
    ends: LineEnds,
) -> Result<(Option<PathItem>, Option<PathItem>), OutOfRange> {
    let paths = geometry.paths(place.frame, |path| {
        (path.filled && fill.is_some()) || (path.stroked && line.is_some())
    })?;
    let filled = if let Some(color) = fill {
        let mut commands = Vec::new();
        for path in paths.iter().filter(|p| p.filled) {
            commands.extend(outline(path, place)?);
        }
        (!commands.is_empty()).then_some(PathItem {
            commands,
            color,
            fill_rule: FillRule::EvenOdd,
        })
    } else {
        None
    };
    let stroked = if let Some((color, half)) = line {
        let mut commands = Vec::new();
        for path in paths.iter().filter(|p| p.stroked) {
            for (subpath, closed) in subpaths(path, place)? {
                stroke_subpath(&subpath, closed, half, dash, ends, &mut commands);
            }
        }
        (!commands.is_empty()).then_some(PathItem {
            commands,
            color,
            fill_rule: FillRule::NonZero,
        })
    } else {
        None
    };
    Ok((filled, stroked))
}

/// Strokes one flattened subpath solid or dashed, trimming open subpaths and appending arrowheads
/// when `ends` has any.
fn stroke_subpath(
    points: &[Point],
    closed: bool,
    half: Length,
    dash: Option<&DashStyle>,
    ends: LineEnds,
    out: &mut Vec<PathCommand>,
) {
    let width = half * 2;
    if !closed && ends.any() {
        let head_t = ends.head.and_then(|_| head_tangent(points));
        let tail_t = ends.tail.and_then(|_| tail_tangent(points));
        let head_trim = ends.head.map_or(Length::ZERO, |e| e.shorten(width));
        let tail_trim = ends.tail.map_or(Length::ZERO, |e| e.shorten(width));
        let trimmed = trim_polyline(points, head_trim, tail_trim);
        if !trimmed.is_empty() {
            stroke_flat_or_dashed(&trimmed, half, dash, out);
        }
        if let (Some(end), Some((from, tip))) = (ends.head, head_t) {
            out.extend(end.commands(from, tip, width));
        }
        if let (Some(end), Some((from, tip))) = (ends.tail, tail_t) {
            out.extend(end.commands(from, tip, width));
        }
        return;
    }
    if let Some(style) = dash
        && let Some(dashed) = stroke::dashes(points, half, &style.pattern, style.cap, MAX_DASHES)
    {
        out.extend(dashed);
        return;
    }
    for pair in points.windows(2) {
        if let [a, b] = pair {
            out.extend(stroke::piece(*a, *b, half).into_iter().flatten());
        }
    }
}

/// Strokes a trimmed shaft with `dash` when present, else flat-ended bands with round joins.
fn stroke_flat_or_dashed(
    points: &[Point],
    half: Length,
    dash: Option<&DashStyle>,
    out: &mut Vec<PathCommand>,
) {
    if let Some(style) = dash
        && let Some(dashed) = stroke::dashes(points, half, &style.pattern, style.cap, MAX_DASHES)
    {
        out.extend(dashed);
        return;
    }
    let mut prev_end = None;
    for pair in points.windows(2) {
        if let [a, b] = pair
            && let Some(band) = stroke::band(*a, *b, half)
        {
            if let Some(joint) = prev_end {
                out.extend(stroke::disc(joint, half));
            }
            out.extend(band);
            prev_end = Some(*b);
        }
    }
}

/// The outline of a path on the page.
fn outline(path: &CustomPath, place: &Place) -> Result<Vec<PathCommand>, OutOfRange> {
    path.segments
        .iter()
        .map(|segment| {
            Ok(match *segment {
                Segment::Move(p) => PathCommand::MoveTo(place.on_page(path, p)?),
                Segment::Line(p) => PathCommand::LineTo(place.on_page(path, p)?),
                Segment::Quad([c, p]) => {
                    PathCommand::QuadTo(place.on_page(path, c)?, place.on_page(path, p)?)
                }
                Segment::Cubic([c1, c2, p]) => PathCommand::CubicTo(
                    place.on_page(path, c1)?,
                    place.on_page(path, c2)?,
                    place.on_page(path, p)?,
                ),
                Segment::Close => PathCommand::Close,
            })
        })
        .collect()
}

/// The flattened subpaths of `path` on the page (with whether each closed via `Segment::Close`),
/// with each curve cut into [`stroke::CURVE_PIECES`] straight pieces.
fn subpaths(path: &CustomPath, place: &Place) -> Result<Vec<(Vec<Point>, bool)>, OutOfRange> {
    let mut all = Vec::new();
    let mut current: Vec<Point> = Vec::new();
    let origin = point((Length::ZERO, Length::ZERO));
    let (mut start, mut at) = (origin, origin);
    for segment in &path.segments {
        match *segment {
            Segment::Move(p) => {
                finish_subpath(&mut all, &mut current, false);
                start = place.on_page(path, p)?;
                at = start;
                current.push(start);
            }
            Segment::Close => {
                ensure_start(&mut current, at);
                current.push(start);
                at = start;
                finish_subpath(&mut all, &mut current, true);
            }
            other => {
                ensure_start(&mut current, at);
                at = extend_subpath(&mut current, at, other, path, place)?;
            }
        }
    }
    finish_subpath(&mut all, &mut current, false);
    Ok(all)
}

fn finish_subpath(all: &mut Vec<(Vec<Point>, bool)>, current: &mut Vec<Point>, closed: bool) {
    if current.len() >= 2 {
        all.push((std::mem::take(current), closed));
    } else {
        current.clear();
    }
}

fn ensure_start(current: &mut Vec<Point>, at: Point) {
    if current.is_empty() {
        current.push(at);
    }
}

fn extend_subpath(
    current: &mut Vec<Point>,
    at: Point,
    segment: Segment,
    path: &CustomPath,
    place: &Place,
) -> Result<Point, OutOfRange> {
    match segment {
        Segment::Line(p) => {
            let next = place.on_page(path, p)?;
            current.push(next);
            Ok(next)
        }
        Segment::Quad([c, p]) => {
            let end = place.on_page(path, p)?;
            current.extend(stroke::cubic_points(stroke::quad_as_cubic(
                at,
                place.on_page(path, c)?,
                end,
            )));
            Ok(end)
        }
        Segment::Cubic([c1, c2, p]) => {
            let end = place.on_page(path, p)?;
            current.extend(stroke::cubic_points([
                at,
                place.on_page(path, c1)?,
                place.on_page(path, c2)?,
                end,
            ]));
            Ok(end)
        }
        Segment::Move(_) | Segment::Close => Ok(at),
    }
}

#[cfg(test)]
mod tests;