f-office-paint 0.2.3

Display list: the contract between layout and output.
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
//! Curves and lines as filled outlines, for the formats that draw them.
//!
//! The display list fills paths only, so a line becomes filled quadrilaterals: each straight
//! piece is `half` thick on each side and longer by `half` at each end, so that the pieces of a
//! line overlap at their joints. A curve is drawn in [`CURVE_PIECES`] straight pieces.
//!
//! A curve of a picture is one curve, with no piece count of its own: [`CURVE_PIECES`] is
//! F-Office's approximation of it.

use crate::{PathCommand, Point};
use f_office_units::Length;
use f_office_units::scale::DRAWING_WHOLE;

/// The number of straight pieces that stand for one curve in a stroke.
pub const CURVE_PIECES: i64 = 16;

/// The distance of the control points of a quarter ellipse from its ends, as a share of the
/// radius, of which [`DRAWING_WHOLE`] is the whole: 4/3 (√2 − 1).
pub const KAPPA: i64 = 55_228;

/// The distance of the control points of a quarter ellipse of radius `radius` from its ends.
#[must_use]
pub fn kappa(radius: Length) -> Length {
    (radius * KAPPA).div_toward_zero(DRAWING_WHOLE)
}

/// The points of a cubic Bézier curve after its start, `controls[0]`, in [`CURVE_PIECES`]
/// straight pieces; the last is the curve's end. Each point mixes the four controls in `i128`.
#[must_use]
pub fn cubic_points(controls: [Point; 4]) -> Vec<Point> {
    let n = i128::from(CURVE_PIECES).pow(3);
    let at = |k: i64| {
        let (t, s) = (i128::from(k), i128::from(CURVE_PIECES - k));
        let mix = |a: Length, b: Length, c: Length, d: Length| {
            let sum = s * s * s * i128::from(a.units())
                + 3 * s * s * t * i128::from(b.units())
                + 3 * s * t * t * i128::from(c.units())
                + t * t * t * i128::from(d.units());
            // A weighted mean of four `i64` values, whose weights sum to `n`, lies between
            // them, so it fits in `i64` and the 0 is never taken.
            Length::from_units(i64::try_from(sum / n).unwrap_or(0))
        };
        let [p0, p1, p2, p3] = controls;
        Point {
            x: mix(p0.x, p1.x, p2.x, p3.x),
            y: mix(p0.y, p1.y, p2.y, p3.y),
        }
    };
    (1..=CURVE_PIECES).map(at).collect()
}

/// The cubic curve of a quadratic one from `start` through `control` to `end`: its controls lie
/// two thirds of the way from each end to `control`, to the nearest half-EMU, as
/// [`Length::div_round`] rounds. The fill and the stroke of a curve both take it, so that they
/// follow one curve.
#[must_use]
pub fn quad_as_cubic(start: Point, control: Point, end: Point) -> [Point; 4] {
    let third = |from: Point| Point {
        x: from.x + ((control.x - from.x) * 2).div_round(3),
        y: from.y + ((control.y - from.y) * 2).div_round(3),
    };
    [start, third(start), third(end), end]
}

/// The outlines of a line through `points`, `half` thick on each side.
#[must_use]
pub fn line_pieces(points: &[Point], half: Length) -> Vec<PathCommand> {
    points
        .windows(2)
        .filter_map(|pair| match pair {
            [a, b] => piece(*a, *b, half),
            _ => None,
        })
        .flatten()
        .collect()
}

/// The outlines of a line through `points`, `half` thick on each side, with round caps and round
/// joins: each straight piece without its ends, and a disc of radius `half` at each point. Every
/// outline turns the same way, so that their overlaps stay filled under the nonzero rule.
#[must_use]
pub fn round_line(points: &[Point], half: Length) -> Vec<PathCommand> {
    let pieces = points.windows(2).filter_map(|pair| match pair {
        [a, b] => band(*a, *b, half),
        _ => None,
    });
    let mut commands: Vec<PathCommand> = pieces.flatten().collect();
    for point in points {
        commands.extend(disc(*point, half));
    }
    commands
}

/// How the ends of each dash of a dashed stroke are shaped.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StrokeCap {
    /// Flat (butt) ends flush with each dash's start and end points.
    #[default]
    Flat,
    /// Semicircular caps of radius `half` around each dash's start and end points.
    Round,
    /// Square caps extending `half` past each dash's start and end points along its tangent.
    Square,
}

/// The outlines of a dashed line through `points`, `half` thick on each side: `pattern` gives
/// the lengths along the line that are on and off in turn, from a dash at the first point, and
/// the pattern starts again after its last length. Each dash is a [`round_line`] through its
/// start, the points inside it and its end, so that a dash of length 0 is a disc. `None` when the
/// pattern has no length, a length below 0 or more than `limit` dashes.
#[must_use]
pub fn round_dashes(
    points: &[Point],
    half: Length,
    pattern: &[Length],
    limit: usize,
) -> Option<Vec<PathCommand>> {
    dashes(points, half, pattern, StrokeCap::Round, limit)
}

/// Like [`round_dashes`], shaping each dash's ends with `cap` (`Flat`, `Round`, or `Square`) and
/// rounding any interior bends inside a dash.
#[must_use]
pub fn dashes(
    points: &[Point],
    half: Length,
    pattern: &[Length],
    cap: StrokeCap,
    limit: usize,
) -> Option<Vec<PathCommand>> {
    let period: i64 = pattern.iter().map(|length| length.units()).sum();
    if period <= 0 || pattern.iter().any(|length| length.units() < 0) {
        return None;
    }
    let mut walk = DashWalk {
        commands: Vec::new(),
        dash: points.first().copied().into_iter().collect(),
        on: true,
        index: 0,
        left: *pattern.first()?,
        dashes: 0,
        cap,
        last_dir: None,
    };
    for pair in points.windows(2) {
        if let [a, b] = pair {
            walk.segment(*a, *b, (half, pattern, limit))?;
        }
    }
    if walk.on {
        walk.flush(half);
    }
    Some(walk.commands)
}

/// The state of [`dashes`] along its line.
struct DashWalk {
    /// The outlines of the dashes so far.
    commands: Vec<PathCommand>,
    /// The points of the dash that is on, from its start.
    dash: Vec<Point>,
    /// Whether a dash is on, else a gap.
    on: bool,
    /// The place of the current length in the pattern.
    index: usize,
    /// What is left of the current length.
    left: Length,
    /// The count of the dashes so far.
    dashes: usize,
    /// End-cap shape for each dash.
    cap: StrokeCap,
    /// Half-width tangent step of the most recent non-degenerate segment (used for 0-length
    /// square-capped dots).
    last_dir: Option<(Length, Length)>,
}

impl DashWalk {
    /// Appends the filled outline of the current dash (`self.dash`) using `self.cap`.
    fn flush(&mut self, half: Length) {
        match self.cap {
            StrokeCap::Round => self.commands.extend(round_line(&self.dash, half)),
            StrokeCap::Flat => emit_flat_dash(&self.dash, half, &mut self.commands),
            StrokeCap::Square => {
                emit_square_dash(&self.dash, half, self.last_dir, &mut self.commands);
            }
        }
    }

    /// Goes along the straight piece from `a` to `b`, ending each length of the pattern that
    /// ends on it. `None` past `limit` dashes.
    fn segment(
        &mut self,
        a: Point,
        b: Point,
        (half, pattern, limit): (Length, &[Length], usize),
    ) -> Option<()> {
        if let Some(dir) = along(a, b, half) {
            self.last_dir = Some(dir);
        }
        let (dx, dy) = (
            i128::from((b.x - a.x).units()),
            i128::from((b.y - a.y).units()),
        );
        let length = (dx * dx + dy * dy).isqrt();
        let mut done = 0_i128;
        while i128::from(self.left.units()) <= length - done {
            if !self.on && i128::from(self.left.units()) == length - done {
                self.left = Length::ZERO;
                return Some(());
            }
            done += i128::from(self.left.units());
            // `done` is at most `length`, so each share is at most the piece's own step.
            let share =
                |d: i128| Length::from_units(i64::try_from(d * done / length.max(1)).unwrap_or(0));
            let at = Point {
                x: a.x + share(dx),
                y: a.y + share(dy),
            };
            if self.on {
                self.dash.push(at);
                self.flush(half);
                self.dashes += 1;
                if self.dashes > limit {
                    return None;
                }
            }
            self.dash.clear();
            self.dash.push(at);
            self.on = !self.on;
            self.index = (self.index + 1) % pattern.len();
            self.left = *pattern.get(self.index)?;
        }
        let rest = i64::try_from(length - done).ok()?;
        self.left -= Length::from_units(rest);
        if self.on {
            self.dash.push(b);
        }
        Some(())
    }
}

/// Emits a flat-capped dash through `points` with round interior joins.
fn emit_flat_dash(points: &[Point], half: Length, out: &mut Vec<PathCommand>) {
    let mut non_empty = 0_usize;
    let mut last_end = None;
    for pair in points.windows(2) {
        if let [a, b] = pair
            && let Some(quad) = band(*a, *b, half)
        {
            if non_empty > 0
                && let Some(joint) = last_end
            {
                out.extend(disc(joint, half));
            }
            out.extend(quad);
            last_end = Some(*b);
            non_empty += 1;
        }
    }
}

/// Emits a square-capped dash through `points` with round interior joins; a zero-length dash
/// becomes a square aligned with `fallback_dir`.
fn emit_square_dash(
    points: &[Point],
    half: Length,
    fallback_dir: Option<(Length, Length)>,
    out: &mut Vec<PathCommand>,
) {
    let segments: Vec<(Point, Point, (Length, Length))> = points
        .windows(2)
        .filter_map(|pair| match pair {
            [a, b] => along(*a, *b, half).map(|dir| (*a, *b, dir)),
            _ => None,
        })
        .collect();
    if segments.is_empty() {
        if let (Some(&center), Some((ux, uy))) = (points.first(), fallback_dir) {
            let start = Point {
                x: center.x - ux,
                y: center.y - uy,
            };
            let end = Point {
                x: center.x + ux,
                y: center.y + uy,
            };
            out.extend(quadrilateral(start, end, (ux, uy)));
        }
        return;
    }
    let last_index = segments.len() - 1;
    for (idx, &(a, b, (ux, uy))) in segments.iter().enumerate() {
        let start = if idx == 0 {
            Point {
                x: a.x - ux,
                y: a.y - uy,
            }
        } else {
            out.extend(disc(a, half));
            a
        };
        let end = if idx == last_index {
            Point {
                x: b.x + ux,
                y: b.y + uy,
            }
        } else {
            b
        };
        out.extend(quadrilateral(start, end, (ux, uy)));
    }
}

/// The outline of a closed polygon through `corners`, `half` thick on each side, with round
/// joins: [`round_line`] through the corners and back to the first.
#[must_use]
pub fn round_outline(corners: &[Point], half: Length) -> Vec<PathCommand> {
    let mut points = corners.to_vec();
    points.extend(corners.first().copied());
    round_line(&points, half)
}

/// A circle of radius `radius` around `center` in four quarter curves, turning as [`piece`]
/// turns.
#[must_use]
pub fn disc(center: Point, radius: Length) -> [PathCommand; 6] {
    let k = kappa(radius);
    let (x, y) = (center.x, center.y);
    [
        PathCommand::MoveTo(at(x, y - radius)),
        PathCommand::CubicTo(
            at(x - k, y - radius),
            at(x - radius, y - k),
            at(x - radius, y),
        ),
        PathCommand::CubicTo(
            at(x - radius, y + k),
            at(x - k, y + radius),
            at(x, y + radius),
        ),
        PathCommand::CubicTo(
            at(x + k, y + radius),
            at(x + radius, y + k),
            at(x + radius, y),
        ),
        PathCommand::CubicTo(
            at(x + radius, y - k),
            at(x + k, y - radius),
            at(x, y - radius),
        ),
        PathCommand::Close,
    ]
}

/// The quadrilateral of one straight piece from `a` to `b`, `half` thick on each side and ending
/// flat at `a` and `b`, or `None` for a piece without length.
#[must_use]
pub fn band(a: Point, b: Point, half: Length) -> Option<[PathCommand; 5]> {
    let (ux, uy) = along(a, b, half)?;
    Some(quadrilateral(a, b, (ux, uy)))
}

/// The quadrilateral of one straight piece from `a` to `b`, `half` thick on each side and longer
/// by `half` at each end, or `None` for a piece without length.
#[must_use]
pub fn piece(a: Point, b: Point, half: Length) -> Option<[PathCommand; 5]> {
    let (ux, uy) = along(a, b, half)?;
    let start = Point {
        x: a.x - ux,
        y: a.y - uy,
    };
    let end = Point {
        x: b.x + ux,
        y: b.y + uy,
    };
    Some(quadrilateral(start, end, (ux, uy)))
}

/// The step of length `half` along the line from `a` to `b`, or `None` for a line without
/// length.
fn along(a: Point, b: Point, half: Length) -> Option<(Length, Length)> {
    // The direction's share of `half` multiplies two lengths, in `i128`.
    let (dx, dy) = (
        i128::from((b.x - a.x).units()),
        i128::from((b.y - a.y).units()),
    );
    let length = (dx * dx + dy * dy).isqrt();
    if length == 0 {
        return None;
    }
    // `|d|` is at most `length`, so the share is at most `|half|` and fits in `i64`, and the 0
    // is never taken.
    let scale = |d: i128| {
        Length::from_units(i64::try_from(d * i128::from(half.units()) / length).unwrap_or(0))
    };
    Some((scale(dx), scale(dy)))
}

/// The point at `x` across and `y` down.
const fn at(x: Length, y: Length) -> Point {
    Point { x, y }
}

/// The quadrilateral from `start` to `end` whose sides lie the step `(ux, uy)`, turned across
/// the line, on each side of it.
fn quadrilateral(start: Point, end: Point, (ux, uy): (Length, Length)) -> [PathCommand; 5] {
    let (nx, ny) = (-uy, ux);
    [
        PathCommand::MoveTo(at(start.x + nx, start.y + ny)),
        PathCommand::LineTo(at(end.x + nx, end.y + ny)),
        PathCommand::LineTo(at(end.x - nx, end.y - ny)),
        PathCommand::LineTo(at(start.x - nx, start.y - ny)),
        PathCommand::Close,
    ]
}

#[cfg(test)]
mod tests {
    use super::{
        CURVE_PIECES, cubic_points, kappa, line_pieces, piece, quad_as_cubic, round_dashes,
        round_line,
    };
    use crate::{PathCommand, Point};
    use f_office_units::Length;

    fn at(x: i64, y: i64) -> Point {
        Point {
            x: Length::from_units(x),
            y: Length::from_units(y),
        }
    }

    /// Twice the signed area of an outline's corners, which gives the way it turns.
    fn turn(commands: &[PathCommand]) -> i128 {
        let corners: Vec<Point> = commands
            .iter()
            .filter_map(|c| match c {
                PathCommand::MoveTo(p) | PathCommand::LineTo(p) | PathCommand::CubicTo(_, _, p) => {
                    Some(*p)
                }
                _ => None,
            })
            .collect();
        corners
            .iter()
            .zip(corners.iter().cycle().skip(1))
            .map(|(a, b)| {
                i128::from(a.x.units()) * i128::from(b.y.units())
                    - i128::from(b.x.units()) * i128::from(a.y.units())
            })
            .sum()
    }

    #[test]
    fn a_round_line_is_its_pieces_without_ends_and_a_disc_at_each_point() {
        let commands = round_line(
            &[at(0, 0), at(1000, 0), at(1000, 600)],
            Length::from_units(50),
        );
        // Two pieces of five commands and three discs of six.
        assert_eq!(commands.len(), 2 * 5 + 3 * 6);
        assert_eq!(
            commands[..5],
            [
                PathCommand::MoveTo(at(0, 50)),
                PathCommand::LineTo(at(1000, 50)),
                PathCommand::LineTo(at(1000, -50)),
                PathCommand::LineTo(at(0, -50)),
                PathCommand::Close,
            ]
        );
        assert_eq!(commands[10], PathCommand::MoveTo(at(0, -50)));
        // The pieces and the discs turn the same way, so that the nonzero rule fills their
        // overlaps.
        let piece_turn = turn(&commands[..5]);
        let disc_turn = turn(&commands[10..16]);
        assert!(piece_turn != 0 && piece_turn.signum() == disc_turn.signum());
    }

    #[test]
    fn a_curve_ends_at_its_end_in_the_pieces_of_one_count() {
        let points = cubic_points([at(0, 0), at(0, 100), at(100, 100), at(100, 0)]);
        assert_eq!(points.len(), usize::try_from(CURVE_PIECES).unwrap());
        assert_eq!(points.last(), Some(&at(100, 0)));
        // The middle of a symmetric curve lies on its axis, three quarters of the way up.
        assert_eq!(points[points.len() / 2 - 1], at(50, 75));
    }

    #[test]
    fn a_straight_curve_stays_on_its_line() {
        let points = cubic_points([at(0, 0), at(30, 0), at(60, 0), at(90, 0)]);
        assert!(points.iter().all(|p| p.y == Length::ZERO));
        assert!(points.windows(2).all(|pair| pair[0].x < pair[1].x));
    }

    #[test]
    fn a_quadratic_curve_takes_controls_two_thirds_of_the_way() {
        assert_eq!(
            quad_as_cubic(at(0, 0), at(30, 60), at(90, 0)),
            [at(0, 0), at(20, 40), at(50, 40), at(90, 0)]
        );
    }

    #[test]
    fn a_quadratic_curve_takes_its_controls_to_the_nearest_half_emu_as_its_fill_does() {
        // Two thirds of 1 and 2 are 0.67 and 1.33, so the first control is (1, 1), not (0, 1)
        // toward zero; from the end, two thirds of -2 and 2 are -1.33 and 1.33.
        let curve = quad_as_cubic(at(0, 0), at(1, 2), at(3, 0));
        assert_eq!(curve, [at(0, 0), at(1, 1), at(2, 1), at(3, 0)]);
        let [_, first, second, end] = curve;
        assert_eq!(
            crate::fill_commands(&[
                PathCommand::MoveTo(at(0, 0)),
                PathCommand::QuadTo(at(1, 2), end)
            ]),
            [
                PathCommand::MoveTo(at(0, 0)),
                PathCommand::CubicTo(first, second, end)
            ]
        );
    }

    #[test]
    fn the_control_of_a_quarter_circle_lies_at_its_share_of_the_radius() {
        assert_eq!(
            kappa(Length::from_units(100_000)),
            Length::from_units(55_228)
        );
    }

    #[test]
    fn a_piece_grows_by_half_at_each_end_and_on_each_side() {
        let quad = piece(at(0, 0), at(100, 0), Length::from_units(10)).unwrap();
        assert_eq!(
            quad,
            [
                PathCommand::MoveTo(at(-10, 10)),
                PathCommand::LineTo(at(110, 10)),
                PathCommand::LineTo(at(110, -10)),
                PathCommand::LineTo(at(-10, -10)),
                PathCommand::Close,
            ]
        );
        assert_eq!(piece(at(5, 5), at(5, 5), Length::from_units(10)), None);
    }

    #[test]
    fn a_line_has_one_quadrilateral_for_each_piece_with_length() {
        let commands = line_pieces(
            &[at(0, 0), at(10, 0), at(10, 0), at(10, 10)],
            Length::from_units(1),
        );
        assert_eq!(commands.len(), 10);
    }

    /// The count of outlines in `commands`.
    fn outlines(commands: &[PathCommand]) -> usize {
        commands
            .iter()
            .filter(|command| matches!(command, PathCommand::MoveTo(_)))
            .count()
    }

    fn lengths(units: &[i64]) -> Vec<Length> {
        units.iter().copied().map(Length::from_units).collect()
    }

    #[test]
    fn a_dashed_line_draws_each_whole_dash_as_a_round_line() {
        let half = Length::from_units(1);
        // Dashes start at 0, 8, ..., 96, and the last ends at 98 inside the line.
        let dashes = round_dashes(&[at(0, 0), at(100, 0)], half, &lengths(&[2, 6]), 100).unwrap();
        assert_eq!(outlines(&dashes), 13 * 3);
        assert_eq!(
            dashes[..5],
            round_line(&[at(0, 0), at(2, 0)], half)[..5],
            "the first dash's piece"
        );
    }

    #[test]
    fn a_dash_goes_round_a_corner_with_a_round_join() {
        let half = Length::from_units(1);
        let dashes = round_dashes(
            &[at(0, 0), at(10, 0), at(10, 10)],
            half,
            &lengths(&[15, 100]),
            100,
        )
        .unwrap();
        assert_eq!(dashes, round_line(&[at(0, 0), at(10, 0), at(10, 5)], half));
    }

    #[test]
    fn a_dash_of_length_zero_is_a_disc() {
        let half = Length::from_units(1);
        let dots = round_dashes(&[at(0, 0), at(25, 0)], half, &lengths(&[0, 10]), 100).unwrap();
        // Dots at 0, 10 and 20, each two discs on one place.
        assert_eq!(outlines(&dots), 3 * 2);
    }

    #[test]
    fn a_pattern_without_length_or_with_too_many_dashes_gives_no_line() {
        let half = Length::from_units(1);
        let line = [at(0, 0), at(1_000, 0)];
        assert_eq!(round_dashes(&line, half, &lengths(&[0, 0]), 100), None);
        assert_eq!(round_dashes(&line, half, &lengths(&[]), 100), None);
        assert_eq!(round_dashes(&line, half, &lengths(&[4, -1]), 100), None);
        assert_eq!(round_dashes(&line, half, &lengths(&[0, 1]), 100), None);
        assert!(round_dashes(&line, half, &lengths(&[0, 10]), 101).is_some());
    }

    #[test]
    fn flat_and_square_caps_shape_dashes_and_square_dots() {
        use super::{StrokeCap, band, dashes};
        let half = Length::from_units(2);
        let flat = dashes(
            &[at(0, 0), at(25, 0)],
            half,
            &lengths(&[10, 10]),
            StrokeCap::Flat,
            100,
        )
        .unwrap();
        // First dash [0..10], second dash [20..25]: two flat bands, no end discs.
        assert_eq!(outlines(&flat), 2);
        assert_eq!(flat[..5], band(at(0, 0), at(10, 0), half).unwrap());
        // Square-capped zero-length dots at 0, 10, 20: three squares extending half on each side.
        let sq_dots = dashes(
            &[at(0, 0), at(25, 0)],
            half,
            &lengths(&[0, 10]),
            StrokeCap::Square,
            100,
        )
        .unwrap();
        assert_eq!(outlines(&sq_dots), 3);
        assert_eq!(sq_dots[..5], band(at(-2, 0), at(2, 0), half).unwrap());
        // A gap that ends exactly at the line's end does not start a trailing zero-length dot.
        let exact = dashes(
            &[at(0, 0), at(20, 0)],
            half,
            &lengths(&[0, 10]),
            StrokeCap::Square,
            100,
        )
        .unwrap();
        assert_eq!(outlines(&exact), 2);
    }
}