Skip to main content

nsh_core/
canvas.rs

1//! `<canvas>` drawings: what a `draw` callback recorded through the 2D
2//! context (an HTML Canvas 2D subset), decoded in Rust into an immutable
3//! list of operations that platforms replay natively (CGContext, Android
4//! Canvas). Numbers may be animated values ([`Num::Slot`]): the platform
5//! reads them while replaying, so animations redraw on the UI thread
6//! without JS.
7
8mod damage;
9mod hit;
10
11use std::sync::Arc;
12
13pub use self::{
14    damage::{Damage, DamageScan, first_animated, prefix_path_needed},
15    hit::{point_in_path, point_in_stroke},
16};
17use crate::{
18    element::{PropEnum, TsTypes},
19    geometry::{Bounds, Corners, Percentage, Point, Points, Radians, ScaledPixels, Size, px},
20    js::{
21        canvas::*,
22        host::{HostInput, HostList},
23        ops::{JsOps, OpArg, OpReader, OpsError},
24    },
25    style::{Color, FontVariant},
26};
27
28/// A number of a drawing: a constant or the value of animated value slot
29/// `n` of the drawing ([`Drawing::slots`]).
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub enum Num {
32    /// A constant.
33    Const(f32),
34    /// The current value of an animated value.
35    Slot(u16),
36}
37
38impl Num {
39    /// The value, reading slots through `slot`.
40    #[inline]
41    pub fn get(self, slot: impl Fn(u16) -> f32) -> f32 {
42        match self {
43            Num::Const(v) => v,
44            Num::Slot(s) => slot(s),
45        }
46    }
47}
48
49impl Default for Num {
50    fn default() -> Self {
51        Num::Const(0.0)
52    }
53}
54
55/// One element of a path (`beginPath` … `closePath`, `Path2D`).
56#[derive(Debug, Clone, PartialEq, JsOps)]
57#[ops(cx = Drawing)]
58pub enum PathOp {
59    /// `moveTo(x, y)`: starts a subpath at (`x`, `y`).
60    #[op(code = CV_MOVE_TO, method = "moveTo", params = "x, y")]
61    MoveTo(Num, Num),
62    /// `lineTo(x, y)`: a straight line to (`x`, `y`).
63    #[op(code = CV_LINE_TO, method = "lineTo", params = "x, y")]
64    LineTo(Num, Num),
65    /// `quadraticCurveTo(cpx, cpy, x, y)`: a quadratic Bézier curve to (`x`,
66    /// `y`).
67    #[op(code = CV_QUAD_TO, method = "quadraticCurveTo", params = "cpx, cpy, x, y")]
68    QuadTo([Num; 4]),
69    /// `bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)`: a cubic Bézier curve to
70    /// (`x`, `y`).
71    #[op(
72        code = CV_CUBIC_TO,
73        method = "bezierCurveTo",
74        params = "cp1x, cp1y, cp2x, cp2y, x, y"
75    )]
76    CubicTo([Num; 6]),
77    /// `arc(x, y, radius, startAngle, endAngle, counterclockwise)`: a
78    /// circular arc; angles in radians, clockwise from the x axis.
79    #[op(
80        code = CV_ARC,
81        method = "arc",
82        params = "x, y, radius, startAngle, endAngle, counterclockwise = false"
83    )]
84    Arc {
85        /// Center x.
86        x: Num,
87        /// Center y.
88        y: Num,
89        /// Radius.
90        radius: Num,
91        /// Start angle.
92        start: Num,
93        /// End angle.
94        end: Num,
95        /// Counterclockwise.
96        ccw: bool,
97    },
98    /// `arcTo(x1, y1, x2, y2, radius)`: an arc tangent to the lines to (`x1`,
99    /// `y1`) and on to (`x2`, `y2`).
100    #[op(code = CV_ARC_TO, method = "arcTo", params = "x1, y1, x2, y2, radius")]
101    ArcTo([Num; 5]),
102    /// `ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle,
103    /// counterclockwise)`: an elliptical arc; angles in radians, clockwise.
104    #[op(
105        code = CV_ELLIPSE,
106        method = "ellipse",
107        params = "x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise = false"
108    )]
109    Ellipse {
110        /// Center and radii, rotation (radians).
111        geometry: [Num; 5],
112        /// Start angle.
113        start: Num,
114        /// End angle.
115        end: Num,
116        /// Counterclockwise.
117        ccw: bool,
118    },
119    /// `rect(x, y, w, h)`: a closed rectangle subpath.
120    #[op(code = CV_RECT, method = "rect", params = "x, y, w, h")]
121    Rect([Num; 4]),
122    /// `roundRect(x, y, w, h, radii)`: corner radii top-left, top-right,
123    /// bottom-right, bottom-left (`canvas.ts` spreads `radii`).
124    #[op(code = CV_ROUND_RECT)]
125    RoundRect([Num; 4], [Num; 4]),
126    /// `closePath()`: a straight line back to the subpath's start.
127    #[op(code = CV_CLOSE, method = "closePath")]
128    Close,
129}
130
131/// A path to fill, stroke or clip instead of the current one.
132pub type Path = Arc<[PathOp]>;
133
134/// Which areas a path fills (`fill` / `clip`'s rule).
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
136pub enum FillRule {
137    /// `nonzero`.
138    #[default]
139    #[prop(rename = "nonzero")]
140    NonZero,
141    /// `evenodd`.
142    #[prop(rename = "evenodd")]
143    EvenOdd,
144}
145
146/// How strokes end (`lineCap`).
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
148pub enum LineCap {
149    /// `butt`.
150    #[default]
151    Butt,
152    /// `round`.
153    Round,
154    /// `square`.
155    Square,
156}
157
158/// How stroke segments join (`lineJoin`).
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
160pub enum LineJoin {
161    /// `miter`.
162    #[default]
163    Miter,
164    /// `round`.
165    Round,
166    /// `bevel`.
167    Bevel,
168}
169
170/// The geometry of a gradient (canvas coordinates).
171#[derive(Debug, Clone, Copy, PartialEq)]
172pub enum GradientShape {
173    /// `createLinearGradient(x0, y0, x1, y1)`.
174    Linear {
175        /// Where it starts (`x0`, `y0`).
176        start: Point<Points>,
177        /// Where it ends (`x1`, `y1`).
178        end: Point<Points>,
179    },
180    /// `createRadialGradient(x0, y0, r0, x1, y1, r1)`.
181    Radial {
182        /// The center of the start circle (`x0`, `y0`).
183        start: Point<Points>,
184        /// Its radius (`r0`).
185        start_radius: Points,
186        /// The center of the end circle (`x1`, `y1`).
187        end: Point<Points>,
188        /// Its radius (`r1`).
189        end_radius: Points,
190    },
191    /// `createConicGradient(startAngle, x, y)`.
192    Conic {
193        /// Where it starts, clockwise from the x axis.
194        start_angle: Radians,
195        /// What it turns around.
196        center: Point<Points>,
197    },
198}
199
200/// A `CanvasGradient`.
201#[derive(Debug, Clone, PartialEq)]
202pub struct CanvasGradient {
203    /// Where it runs.
204    pub shape: GradientShape,
205    /// Offsets (0..1, ascending) and colors.
206    pub stops: Vec<(Percentage, Color)>,
207}
208
209impl CanvasGradient {
210    fn new(shape: GradientShape) -> Self {
211        Self {
212            shape,
213            stops: Vec::new(),
214        }
215    }
216
217    /// Along the line from `start` to `end` (`createLinearGradient`).
218    pub fn linear(start: Point<Points>, end: Point<Points>) -> Self {
219        Self::new(GradientShape::Linear { start, end })
220    }
221
222    /// From the circle around `start` of `start_radius` to the one around
223    /// `end` of `end_radius` (`createRadialGradient`).
224    pub fn radial(
225        start: Point<Points>,
226        start_radius: Points,
227        end: Point<Points>,
228        end_radius: Points,
229    ) -> Self {
230        Self::new(GradientShape::Radial {
231            start,
232            start_radius,
233            end,
234            end_radius,
235        })
236    }
237
238    /// Around `center`, from `start_angle` (clockwise from the x axis;
239    /// `createConicGradient`).
240    pub fn conic(start_angle: Radians, center: Point<Points>) -> Self {
241        Self::new(GradientShape::Conic {
242            start_angle,
243            center,
244        })
245    }
246
247    /// Adds `color` at `offset` (0..1, clamped; `addColorStop`): stops
248    /// apply in offset order, equal ones in the order added.
249    pub fn add_color_stop(mut self, offset: Percentage, color: impl Into<crate::Hsla>) -> Self {
250        let offset = offset.clamp(Percentage(0.0), Percentage(1.0));
251        let at = self.stops.partition_point(|(o, _)| *o <= offset);
252        self.stops.insert(at, (offset, Color::from(color.into())));
253        self
254    }
255
256    /// The CSS gradient `gradient` (a layer of `background-image`) as the
257    /// background of a box at `area` (canvas coordinates) draws it: the
258    /// gradient line and its stops resolved for the box's size as CSS
259    /// resolves them, a repeating gradient's stops repeated along the
260    /// whole line. `None` for an elliptical radial gradient, which a canvas
261    /// gradient (between circles) does not draw.
262    pub fn from_css(gradient: &crate::effects::Gradient, area: Bounds<Points>) -> Option<Self> {
263        use crate::{effects::GradientKind, geometry::point};
264        let size = area.size;
265        let (w, h) = (size.width.0, size.height.0);
266        let (left, top) = (area.origin.x.0, area.origin.y.0);
267        let at = |x: f32, y: f32| point(px(x), px(y));
268        let shape = match gradient.kind {
269            GradientKind::Radial { circle: false, .. } => return None,
270            GradientKind::Radial { x, y, .. } => {
271                let center = at(left + x.0 * w, top + y.0 * h);
272                GradientShape::Radial {
273                    start: center,
274                    start_radius: Points::ZERO,
275                    end: center,
276                    end_radius: gradient.line_length(size),
277                }
278            }
279            // CSS turns from the top, a canvas from the x axis; both
280            // clockwise.
281            GradientKind::Conic { from, x, y } => GradientShape::Conic {
282                start_angle: Radians(from.0 - std::f32::consts::FRAC_PI_2),
283                center: at(left + x.0 * w, top + y.0 * h),
284            },
285            kind => {
286                // Through the center at the angle, long enough that the
287                // corners get the end colors (CSS Images 3).
288                let angle = kind
289                    .linear_angle(size)
290                    .unwrap_or(Radians(std::f32::consts::PI));
291                // A quarter turn's sine and cosine exactly (`to bottom` is
292                // 180deg): float error would put the line a hair off the
293                // box's edges.
294                let exact = |v: f32| {
295                    if v.abs() < 1e-6 {
296                        0.0
297                    } else if (v.abs() - 1.0).abs() < 1e-6 {
298                        v.signum()
299                    } else {
300                        v
301                    }
302                };
303                let (sin, cos) = angle.sin_cos();
304                let (sin, cos) = (exact(sin), exact(cos));
305                // CSS's gradient line: |w sin| + |h cos| long.
306                let half = ((w * sin).abs() + (h * cos).abs()) / 2.0;
307                let (cx, cy) = (left + w / 2.0, top + h / 2.0);
308                GradientShape::Linear {
309                    start: at(cx - sin * half, cy + cos * half),
310                    end: at(cx + sin * half, cy - cos * half),
311                }
312            }
313        };
314        let mut stops = gradient.unrolled_stops(size, Percentage(1.0));
315        // A canvas gradient clamps offsets, which would squeeze stops past
316        // either end: they are cut there, at the color between.
317        if !stops.iter().all(|s| (0.0..=1.0).contains(&s.1.0)) {
318            stops = crate::effects::cut_stops(&stops, Percentage(1.0));
319        }
320        let mut out = Self::new(shape);
321        out.stops = stops.into_iter().map(|(color, at)| (at, color)).collect();
322        Some(out)
323    }
324}
325
326/// `fillStyle` / `strokeStyle`.
327#[derive(Debug, Clone, PartialEq)]
328pub enum Paint {
329    /// A color.
330    Color(Color),
331    /// The current value of an animated value interpolating colors.
332    Slot(u16),
333    /// A gradient.
334    Gradient(Arc<CanvasGradient>),
335}
336
337/// `globalCompositeOperation`.
338#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
339#[allow(missing_docs)]
340pub enum Composite {
341    #[default]
342    SourceOver,
343    SourceIn,
344    SourceOut,
345    SourceAtop,
346    DestinationOver,
347    DestinationIn,
348    DestinationOut,
349    DestinationAtop,
350    Lighter,
351    Copy,
352    Xor,
353    Multiply,
354    Screen,
355    Overlay,
356    Darken,
357    Lighten,
358    ColorDodge,
359    ColorBurn,
360    HardLight,
361    SoftLight,
362    Difference,
363    Exclusion,
364    Hue,
365    Saturation,
366    Color,
367    Luminosity,
368}
369
370impl Composite {
371    /// Parses a `globalCompositeOperation` name.
372    pub fn parse(name: &str) -> Option<Composite> {
373        use Composite::*;
374        Some(match name {
375            "source-over" => SourceOver,
376            "source-in" => SourceIn,
377            "source-out" => SourceOut,
378            "source-atop" => SourceAtop,
379            "destination-over" => DestinationOver,
380            "destination-in" => DestinationIn,
381            "destination-out" => DestinationOut,
382            "destination-atop" => DestinationAtop,
383            "lighter" => Lighter,
384            "copy" => Copy,
385            "xor" => Xor,
386            "multiply" => Multiply,
387            "screen" => Screen,
388            "overlay" => Overlay,
389            "darken" => Darken,
390            "lighten" => Lighten,
391            "color-dodge" => ColorDodge,
392            "color-burn" => ColorBurn,
393            "hard-light" => HardLight,
394            "soft-light" => SoftLight,
395            "difference" => Difference,
396            "exclusion" => Exclusion,
397            "hue" => Hue,
398            "saturation" => Saturation,
399            "color" => Color,
400            "luminosity" => Luminosity,
401            _ => return None,
402        })
403    }
404}
405
406/// `font` (the CSS shorthand).
407#[derive(Debug, Clone, PartialEq)]
408pub struct CanvasFont {
409    /// Size.
410    pub size: Points,
411    /// 100..900.
412    pub weight: u16,
413    /// Italic.
414    pub italic: bool,
415    /// The first family; `None` is the system font (also for
416    /// `system-ui` / `sans-serif`).
417    pub family: Option<Arc<str>>,
418    /// OpenType features: `small-caps` and (beyond CSS, which only has
419    /// them in `font-variant-numeric`) `tabular-nums`, `oldstyle-nums`,
420    /// `lining-nums` and `proportional-nums` in the shorthand.
421    pub variant: FontVariant,
422}
423
424impl Default for CanvasFont {
425    /// The canvas default, `10px sans-serif`.
426    fn default() -> Self {
427        Self {
428            size: px(10.0),
429            weight: 400,
430            italic: false,
431            family: None,
432            variant: FontVariant::default(),
433        }
434    }
435}
436
437impl CanvasFont {
438    /// Parses the CSS `font` shorthand (`italic bold 14px Inter`,
439    /// `600 12px/1.2 system-ui`, `tabular-nums 13px system-ui`); `None` if
440    /// it is invalid (canvas keeps the previous font then).
441    pub fn parse(s: &str) -> Option<CanvasFont> {
442        let mut font = CanvasFont {
443            size: Points::ZERO,
444            ..CanvasFont::default()
445        };
446        let mut rest = s.trim();
447        // Style / variant / weight / stretch keywords until the size.
448        loop {
449            let (word, tail) = match rest.split_once(char::is_whitespace) {
450                Some((w, t)) => (w, t.trim_start()),
451                None => (rest, ""),
452            };
453            if let Some(size) = font_size(word) {
454                font.size = size;
455                rest = tail;
456                break;
457            }
458            match word {
459                "italic" | "oblique" => font.italic = true,
460                "normal" | "condensed" | "expanded" => {}
461                w if let Some(v) = FontVariant::parse(w) => font.variant.0 |= v.0,
462                "bold" | "bolder" => font.weight = 700,
463                "lighter" => font.weight = 300,
464                w => match w.parse::<u16>() {
465                    Ok(n) if (1..=1000).contains(&n) => font.weight = n,
466                    _ => return None,
467                },
468            }
469            if tail.is_empty() {
470                return None;
471            }
472            rest = tail;
473        }
474        let family = rest
475            .split(',')
476            .next()
477            .map(|f| f.trim().trim_matches(['"', '\'']))
478            .filter(|f| !f.is_empty())?;
479        font.family = match family {
480            "system-ui" | "sans-serif" | "-apple-system" | "ui-sans-serif" => None,
481            f => Some(f.into()),
482        };
483        Some(font)
484    }
485}
486
487/// `14px` / `14px/1.2` / `1.5rem` / `12pt`: the size.
488fn font_size(word: &str) -> Option<Points> {
489    let word = word.split('/').next()?;
490    let (num, scale) = if let Some(n) = word.strip_suffix("px") {
491        (n, 1.0)
492    } else if let Some(n) = word.strip_suffix("rem").or_else(|| word.strip_suffix("em")) {
493        (n, 16.0)
494    } else {
495        (word.strip_suffix("pt")?, 4.0 / 3.0)
496    };
497    num.parse::<f32>()
498        .ok()
499        .filter(|v| *v > 0.0)
500        .map(|v| Points(v * scale))
501}
502
503impl CanvasFont {
504    /// This font with the numeric forms of `numeric` (`fontVariantNumeric`)
505    /// in place of its own, unless `numeric` is `normal`.
506    pub fn with_numeric(&self, numeric: FontVariant) -> CanvasFont {
507        let mut font = self.clone();
508        if numeric.0 != 0 {
509            font.variant = FontVariant(font.variant.0 & FontVariant::SMALL_CAPS | numeric.0);
510        }
511        font
512    }
513
514    /// The text style of this font.
515    pub fn text_style(&self) -> crate::text::ResolvedTextStyle {
516        crate::text::ResolvedTextStyle {
517            font_size: self.size,
518            font_weight: self.weight,
519            italic: self.italic,
520            font_variant: self.variant,
521            font_family: self.family.as_deref().map(crate::style::FontFamily::new),
522            ..Default::default()
523        }
524    }
525}
526
527/// The width of `text` on one line in `font` (canvas `measureText`).
528pub fn measure_line(
529    engine: &impl crate::text::TextEngine,
530    font: &CanvasFont,
531    text: &str,
532) -> Points {
533    if text.is_empty() {
534        return Points::ZERO;
535    }
536    advance(engine, font, text)
537}
538
539/// What closes a text ending in white space while it is measured.
540const MARK: &str = "x";
541
542/// How far `text` advances on one line in `font`, its trailing white space
543/// included, as canvas `measureText` counts it. Text engines lay a line
544/// out without the white space at its end (it hangs past the line, as in
545/// CSS), so a run of spaces measures 0 and `"a "` as `"a"`: such a text is
546/// measured with a mark after it, less the mark.
547fn advance(engine: &impl crate::text::TextEngine, font: &CanvasFont, text: &str) -> Points {
548    let width = |text: &str| {
549        let mut attributed = crate::text::AttributedText {
550            no_wrap: true,
551            max_lines: 1,
552            ..Default::default()
553        };
554        attributed.push(text, font.text_style());
555        let prepared = engine.prepare(&attributed);
556        engine.measure(&prepared, None).width
557    };
558    // A line break ends the line: what follows it is not on it.
559    let hangs = text.ends_with(|c: char| c.is_whitespace() && !is_line_break(c));
560    if !hangs {
561        return width(text);
562    }
563    let mut marked = String::with_capacity(text.len() + MARK.len());
564    marked.push_str(text);
565    marked.push_str(MARK);
566    (width(&marked) - width(MARK)).max(Points::ZERO)
567}
568
569/// Whether `c` breaks a line (Unicode's mandatory breaks).
570fn is_line_break(c: char) -> bool {
571    matches!(
572        c,
573        '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}'
574    )
575}
576
577/// How `text` sits on one line in a canvas font ([`line_metrics`]): its
578/// width, and the font's extent above and below the baseline, so a
579/// component can center text in a box or place a caret over it.
580#[derive(Debug, Clone, Copy, PartialEq, Default)]
581#[non_exhaustive]
582pub struct TextMetrics {
583    /// The advance width (canvas `measureText(text).width`).
584    pub width: Points,
585    /// Above the baseline (`fontBoundingBoxAscent`).
586    pub ascent: Points,
587    /// Below the baseline (`fontBoundingBoxDescent`).
588    pub descent: Points,
589    /// The line's height: ascent, descent and the font's leading.
590    pub height: Points,
591}
592
593/// [`TextMetrics`] of `text` on one line in `font`, by `engine`. Engines
594/// that do not report their lines give the em box's split of the size
595/// (0.8 above the baseline, 0.2 below) and the measured height.
596pub fn line_metrics(
597    engine: &impl crate::text::TextEngine,
598    font: &CanvasFont,
599    text: &str,
600) -> TextMetrics {
601    let mut attributed = crate::text::AttributedText {
602        no_wrap: true,
603        max_lines: 1,
604        ..Default::default()
605    };
606    // An empty line still has the font's extent.
607    attributed.push(if text.is_empty() { " " } else { text }, font.text_style());
608    let prepared = engine.prepare(&attributed);
609    let size = engine.measure(&prepared, None);
610    let width = if text.is_empty() {
611        Points::ZERO
612    } else {
613        advance(engine, font, text)
614    };
615    let layout = engine.layout(&prepared, size);
616    match engine.lines(&layout).first() {
617        Some(line) => TextMetrics {
618            width,
619            ascent: line.ascender,
620            descent: line.descender,
621            height: line.height,
622        },
623        None => TextMetrics {
624            width,
625            ascent: Points(font.size.0 * 0.8),
626            descent: Points(font.size.0 * 0.2),
627            height: size.height,
628        },
629    }
630}
631
632/// Where text sits horizontally relative to its x (`textAlign`).
633#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
634pub enum CanvasTextAlign {
635    /// `start` (left, or right right to left).
636    #[default]
637    Start,
638    /// `end`.
639    End,
640    /// `left`.
641    Left,
642    /// `right`.
643    Right,
644    /// `center`.
645    Center,
646}
647
648/// Where text sits vertically relative to its y (`textBaseline`).
649#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
650pub enum CanvasTextBaseline {
651    /// `alphabetic`.
652    #[default]
653    Alphabetic,
654    /// `top` (the em box's top: the ascent).
655    Top,
656    /// `hanging`.
657    Hanging,
658    /// `middle`.
659    Middle,
660    /// `ideographic`.
661    Ideographic,
662    /// `bottom`.
663    Bottom,
664}
665
666/// What `drawImage` draws: a URL or an imported asset.
667#[derive(Debug, Clone, PartialEq)]
668pub struct CanvasImage {
669    /// URL or `asset:/path`.
670    pub uri: Arc<str>,
671}
672
673/// One recorded operation. The methods and properties without `method` /
674/// `property` are written in `canvas.ts` (overloads, the state stack,
675/// gradients, images).
676#[derive(Debug, Clone, PartialEq, JsOps)]
677#[ops(cx = Drawing)]
678pub enum CanvasOp {
679    /// `save()`.
680    #[op(code = CV_SAVE)]
681    Save,
682    /// `restore()`.
683    #[op(code = CV_RESTORE)]
684    Restore,
685    /// `translate(x, y)`: moves the origin.
686    #[op(code = CV_TRANSLATE, method = "translate", params = "x, y")]
687    Translate(Num, Num),
688    /// `scale(x, y)`: scales the axes.
689    #[op(code = CV_SCALE, method = "scale", params = "x, y")]
690    Scale(Num, Num),
691    /// `rotate(angle)`: rotates the axes; radians, clockwise.
692    #[op(code = CV_ROTATE, method = "rotate", params = "angle")]
693    Rotate(Num),
694    /// `transform(a, b, c, d, e, f)`: multiplies the transform by the matrix
695    /// [a c e; b d f].
696    #[op(code = CV_TRANSFORM, method = "transform", params = "a, b, c, d, e, f")]
697    Transform([Num; 6]),
698    /// `setTransform(a, b, c, d, e, f)`: replaces the transform by the matrix
699    /// [a c e; b d f].
700    ///
701    /// Relative to the view, not the device.
702    #[op(code = CV_SET_TRANSFORM, method = "setTransform", params = "a, b, c, d, e, f")]
703    SetTransform([Num; 6]),
704    /// `beginPath()`: starts a new current path.
705    #[op(code = CV_BEGIN_PATH, method = "beginPath")]
706    BeginPath,
707    /// Adds to the current path.
708    #[op(nested)]
709    Path(PathOp),
710    /// `fill(path?, rule)`: the current path when `None`.
711    #[op(code = CV_FILL)]
712    Fill(Option<Path>, FillRule),
713    /// `stroke(path?)`.
714    #[op(code = CV_STROKE)]
715    Stroke(Option<Path>),
716    /// `clip(path?, rule)`.
717    #[op(code = CV_CLIP)]
718    Clip(Option<Path>, FillRule),
719    /// `fillRect(x, y, w, h)`: fills a rectangle with `fillStyle` (the
720    /// current path stays).
721    #[op(code = CV_FILL_RECT, method = "fillRect", params = "x, y, w, h")]
722    FillRect([Num; 4]),
723    /// `strokeRect(x, y, w, h)`: strokes a rectangle with `strokeStyle`.
724    #[op(code = CV_STROKE_RECT, method = "strokeRect", params = "x, y, w, h")]
725    StrokeRect([Num; 4]),
726    /// `clearRect(x, y, w, h)`: makes a rectangle transparent.
727    #[op(code = CV_CLEAR_RECT, method = "clearRect", params = "x, y, w, h")]
728    ClearRect([Num; 4]),
729    /// `fillStyle`.
730    #[op(code = CV_FILL_STYLE)]
731    FillStyle(Paint),
732    /// `strokeStyle`.
733    #[op(code = CV_STROKE_STYLE)]
734    StrokeStyle(Paint),
735    /// `lineWidth`: stroke width in points.
736    #[op(code = CV_LINE_WIDTH, property = "lineWidth", initial = "1")]
737    LineWidth(Num),
738    /// `lineCap`: how strokes end.
739    #[op(code = CV_LINE_CAP, property = "lineCap", initial = "\"butt\"")]
740    LineCap(LineCap),
741    /// `lineJoin`: how stroke segments join.
742    #[op(code = CV_LINE_JOIN, property = "lineJoin", initial = "\"miter\"")]
743    LineJoin(LineJoin),
744    /// `miterLimit`: miter joins longer than this (in line widths) are
745    /// beveled.
746    #[op(code = CV_MITER_LIMIT, property = "miterLimit", initial = "10", min = 1.0)]
747    MiterLimit(f32),
748    /// `setLineDash(segments)`: an odd count is repeated, as in canvas.
749    #[op(code = CV_LINE_DASH, with = crate::js::canvas::line_dash)]
750    LineDash(Arc<[Points]>),
751    /// `lineDashOffset`: where the dash pattern starts.
752    #[op(code = CV_LINE_DASH_OFFSET, property = "lineDashOffset", initial = "0")]
753    LineDashOffset(Num),
754    /// `globalAlpha`: opacity of what is drawn next, 0..1.
755    #[op(code = CV_GLOBAL_ALPHA, property = "globalAlpha", initial = "1")]
756    GlobalAlpha(Num),
757    /// `globalCompositeOperation`: how what is drawn next combines with the
758    /// canvas (`source-over`, `multiply`, ...).
759    #[op(
760        code = CV_COMPOSITE,
761        property = "globalCompositeOperation",
762        initial = "\"source-over\""
763    )]
764    Composite(Composite),
765    /// `shadowColor`: the color of shadows (transparent: none).
766    #[op(code = CV_SHADOW_COLOR, property = "shadowColor", initial = "\"rgba(0,0,0,0)\"")]
767    ShadowColor(Color),
768    /// `shadowBlur`: shadow blur in points.
769    #[op(code = CV_SHADOW_BLUR, property = "shadowBlur", initial = "0", min = 0.0)]
770    ShadowBlur(Points),
771    /// `shadowOffsetX` / `shadowOffsetY`.
772    #[op(code = CV_SHADOW_OFFSET)]
773    ShadowOffset(Point<Points>),
774    /// `font`: CSS `font` shorthand, e.g. `"600 14px Inter"` (sizes in px, pt
775    /// or rem).
776    #[op(code = CV_FONT, property = "font", initial = "\"10px sans-serif\"")]
777    Font(CanvasFont),
778    /// `fontVariantNumeric` (CSS's `font-variant-numeric`, which HTML
779    /// Canvas lacks): `"tabular-nums"` for figures of equal width,
780    /// `oldstyle-nums`, `lining-nums`, `proportional-nums` or `"normal"`
781    /// (the font's own); kept apart from `font`, which does not reset it.
782    #[op(
783        code = CV_FONT_VARIANT_NUMERIC,
784        property = "fontVariantNumeric",
785        initial = "\"normal\""
786    )]
787    FontVariantNumeric(FontVariant),
788    /// `textAlign`: where text sits horizontally relative to its x.
789    #[op(code = CV_TEXT_ALIGN, property = "textAlign", initial = "\"start\"")]
790    TextAlign(CanvasTextAlign),
791    /// `textBaseline`: where text sits vertically relative to its y.
792    #[op(code = CV_TEXT_BASELINE, property = "textBaseline", initial = "\"alphabetic\"")]
793    TextBaseline(CanvasTextBaseline),
794    /// `fillText(text, x, y, maxWidth?)`.
795    #[op(code = CV_FILL_TEXT)]
796    FillText {
797        /// The text.
798        text: Arc<str>,
799        /// Where it starts.
800        x: Num,
801        /// Its baseline.
802        y: Num,
803        /// Narrowed to fit.
804        max_width: Option<Points>,
805    },
806    /// `strokeText(text, x, y, maxWidth?)`.
807    #[op(code = CV_STROKE_TEXT)]
808    StrokeText {
809        /// The text.
810        text: Arc<str>,
811        /// Where it starts.
812        x: Num,
813        /// Its baseline.
814        y: Num,
815        /// Narrowed to fit.
816        max_width: Option<Points>,
817    },
818    /// `drawImage(image, [sx, sy, sw, sh,] dx, dy, dw, dh)`.
819    #[op(code = CV_DRAW_IMAGE)]
820    DrawImage {
821        /// The image.
822        image: CanvasImage,
823        /// The part of it, in the image's pixels.
824        source: Option<Bounds<ScaledPixels>>,
825        /// Where it goes.
826        dest: [Num; 4],
827    },
828}
829
830impl CanvasOp {
831    /// Whether it paints (rather than setting the state: transforms,
832    /// styles, paths, clips).
833    pub fn paints(&self) -> bool {
834        matches!(
835            self,
836            CanvasOp::Fill(..)
837                | CanvasOp::Stroke(_)
838                | CanvasOp::FillRect(_)
839                | CanvasOp::StrokeRect(_)
840                | CanvasOp::ClearRect(_)
841                | CanvasOp::FillText { .. }
842                | CanvasOp::StrokeText { .. }
843                | CanvasOp::DrawImage { .. }
844        )
845    }
846}
847
848/// One `draw` of a canvas.
849#[derive(Debug, Clone, PartialEq, Default)]
850pub struct Drawing {
851    /// The operations, in order.
852    pub ops: Vec<CanvasOp>,
853    /// The animated values the operations read, by slot.
854    pub slots: Vec<crate::animation::NodeId>,
855    /// The parts of what it draws that are elements of their own to
856    /// assistive technologies and UI tests ([`CanvasNode`]), in reading
857    /// order.
858    pub nodes: Vec<CanvasNode>,
859    /// The operations whose value is the canvas view's style rather than
860    /// one of their own, by index in `ops`: the core gives them the
861    /// view's paint properties ([`crate::style::PaintStyle`], inherited
862    /// from the views around it) before a platform gets the drawing
863    /// ([`Drawing::painted`]), so what a Rust component draws follows the
864    /// app's `fill-*` / `stroke-*` classes and the appearance without
865    /// being recorded again.
866    pub view_paints: Vec<(u32, ViewPaint)>,
867}
868
869/// An operation of a [`Drawing`] that takes its value from the canvas
870/// view's paint properties ([`Drawing::view_paints`]).
871#[derive(Debug, Clone, Copy, PartialEq)]
872pub enum ViewPaint {
873    /// `fillStyle` is the view's `fill`; where nothing sets one, this.
874    Fill(crate::style::SvgPaint),
875    /// `strokeStyle` is the view's `stroke`; where nothing sets one, this.
876    Stroke(crate::style::SvgPaint),
877    /// `lineWidth` is the view's `strokeWidth` (1 where nothing sets one,
878    /// CSS's initial value).
879    StrokeWidth,
880    /// The line dash is the view's `strokeDasharray` (solid where nothing
881    /// sets one).
882    StrokeDasharray,
883    /// `fillStyle` is the view's text color: a shape filled with
884    /// `currentColor` (an SVG's, [`crate::element::svg`]), which follows
885    /// the text color whatever the view's `fill`.
886    FillCurrentColor,
887    /// `strokeStyle` is the view's text color
888    /// ([`ViewPaint::FillCurrentColor`]).
889    StrokeCurrentColor,
890    /// `transform` maps a view box onto the canvas's box: the operations
891    /// after it draw in the view box's coordinates, and the canvas lays
892    /// out at its natural size ([`ViewBoxFit`]).
893    Fit(ViewBoxFit),
894    /// Fills the current path by `rule` with the view's background: its
895    /// `backgroundColor`, then its `backgroundImage` layers over it (the
896    /// last one first, as CSS stacks them), each positioned over `area`
897    /// (canvas coordinates) as over a box of that size
898    /// ([`CanvasGradient::from_css`]); the canvas's state is kept around
899    /// it. The view draws no background of its own behind the drawing: it
900    /// shows where this fills, as with CSS's `clip-path` (an area under a
901    /// chart's line that fades out, in the app's `bg-linear-*` classes).
902    Background {
903        /// The box the background is positioned over.
904        area: Bounds<Points>,
905        /// Which parts of the path are inside.
906        rule: FillRule,
907    },
908}
909
910/// How a drawing in the coordinates of a view box fills its canvas, as
911/// SVG's `viewBox` and `preserveAspectRatio` fit an `<svg>` into its box
912/// ([`ViewPaint::Fit`]). The canvas lays out as an image does: at
913/// [`Self::size`] where its style sets no size, keeping that aspect ratio
914/// where it sets one side; the core maps the view box onto the box it gets
915/// and sends the drawing again when that box changes.
916#[derive(Debug, Clone, Copy, PartialEq)]
917pub struct ViewBoxFit {
918    /// The view box (`viewBox`), of a positive width and height.
919    pub view_box: Bounds<Points>,
920    /// Where the view box sits in the box along each axis, its aspect
921    /// ratio kept: 0 at the start, 0.5 in the middle, 1 at the end
922    /// (`xMidYMid` is 50% and 50%). `None` (`none`) stretches it to the
923    /// box.
924    pub align: Option<(Percentage, Percentage)>,
925    /// It covers the box (`slice`) rather than fits inside it (`meet`).
926    pub slice: bool,
927    /// The natural size: the `<svg>`'s `width` and `height`.
928    pub size: Size<Points>,
929}
930
931impl ViewBoxFit {
932    /// The matrix `[a, b, c, d, e, f]` (`transform`'s) mapping the view box
933    /// onto a box of `size` at the origin.
934    pub fn transform(&self, size: Size<Points>) -> [f32; 6] {
935        let Size { width, height } = self.view_box.size;
936        let (vw, vh) = (width.0, height.0);
937        let (w, h) = (size.width.0.max(0.0), size.height.0.max(0.0));
938        if !(vw > 0.0 && vh > 0.0) {
939            return [0.0; 6];
940        }
941        let (mut sx, mut sy) = (w / vw, h / vh);
942        let (ax, ay) = match self.align {
943            None => (0.0, 0.0),
944            Some((x, y)) => {
945                let s = if self.slice { sx.max(sy) } else { sx.min(sy) };
946                (sx, sy) = (s, s);
947                (x.0, y.0)
948            }
949        };
950        let origin = self.view_box.origin;
951        [
952            sx,
953            0.0,
954            0.0,
955            sy,
956            (w - vw * sx) * ax - origin.x.0 * sx,
957            (h - vh * sy) * ay - origin.y.0 * sy,
958        ]
959    }
960}
961
962/// A part of a canvas's drawing that assistive technologies and UI tests
963/// see as an element of its own: a cell of a grid, a bar of a chart. It
964/// is the canvas's child at `bounds` (points from the canvas's top left),
965/// with its own role, name and test id; a press on it is a press at its
966/// center, as a pointer there makes it, which goes to whatever view is
967/// under that point and takes presses. The GPUI backend and the headless
968/// driver show them; the other backends do not yet.
969#[derive(Debug, Clone, PartialEq, Default)]
970#[non_exhaustive]
971pub struct CanvasNode {
972    /// Where it is in the canvas.
973    pub bounds: Bounds<Points>,
974    /// What it is to assistive technologies.
975    pub role: crate::AccessibilityRole,
976    /// Its accessible name: the text it shows.
977    pub label: Arc<str>,
978    /// `testID`: an identifier for UI tests.
979    pub test_id: Option<Arc<str>>,
980    /// It is selected (a grid's selected cells).
981    pub selected: bool,
982}
983
984impl CanvasNode {
985    /// A node at `bounds` with `role`, named `label`.
986    pub fn new(
987        bounds: Bounds<Points>,
988        role: crate::AccessibilityRole,
989        label: impl Into<Arc<str>>,
990    ) -> Self {
991        Self {
992            bounds,
993            role,
994            label: label.into(),
995            ..Self::default()
996        }
997    }
998
999    /// With the test id `id`.
1000    pub fn test_id(mut self, id: impl Into<Arc<str>>) -> Self {
1001        self.test_id = Some(id.into());
1002        self
1003    }
1004
1005    /// Selected, or not.
1006    pub fn selected(mut self, selected: bool) -> Self {
1007        self.selected = selected;
1008        self
1009    }
1010}
1011
1012impl Drawing {
1013    /// Whether it fills with its view's background
1014    /// ([`ViewPaint::Background`]), which the view then does not draw.
1015    pub fn paints_background(&self) -> bool {
1016        self.view_paints
1017            .iter()
1018            .any(|(_, v)| matches!(v, ViewPaint::Background { .. }))
1019    }
1020
1021    /// The view box it fits into its canvas ([`ViewPaint::Fit`]), if any.
1022    pub fn fit(&self) -> Option<ViewBoxFit> {
1023        self.view_paints.iter().find_map(|&(_, v)| match v {
1024            ViewPaint::Fit(fit) => Some(fit),
1025            _ => None,
1026        })
1027    }
1028
1029    /// The drawing as a platform replays it: its [`Drawing::view_paints`]
1030    /// given the paint properties `paint` of its view, whose text color is
1031    /// `current` (`currentColor`), its background, the color `background`
1032    /// under the gradients `images` (top layer first), and the size of its
1033    /// box, `size` (what a view box fits into). `none` paints nothing (a
1034    /// transparent paint). Its own `view_paints` are resolved, so it has
1035    /// none.
1036    pub fn painted(
1037        &self,
1038        paint: &crate::style::PaintStyle,
1039        current: Color,
1040        background: Color,
1041        images: &[crate::effects::Gradient],
1042        size: Size<Points>,
1043    ) -> Drawing {
1044        use crate::style::SvgPaint;
1045        let color = |p: SvgPaint| {
1046            Paint::Color(match p {
1047                SvgPaint::None => Color::TRANSPARENT,
1048                SvgPaint::CurrentColor => current,
1049                SvgPaint::Color(c) => c,
1050            })
1051        };
1052        let mut out = self.clone();
1053        for &(at, view) in &self.view_paints {
1054            let Some(op) = out.ops.get_mut(at as usize) else {
1055                continue;
1056            };
1057            *op = match view {
1058                ViewPaint::Fill(initial) => {
1059                    CanvasOp::FillStyle(color(paint.fill.unwrap_or(initial)))
1060                }
1061                ViewPaint::Stroke(initial) => {
1062                    CanvasOp::StrokeStyle(color(paint.stroke.unwrap_or(initial)))
1063                }
1064                ViewPaint::StrokeWidth => {
1065                    CanvasOp::LineWidth(Num::Const(paint.stroke_width.map_or(1.0, |w| w.0)))
1066                }
1067                ViewPaint::StrokeDasharray => CanvasOp::LineDash(
1068                    paint
1069                        .stroke_dasharray
1070                        .clone()
1071                        .unwrap_or_else(|| Arc::from([])),
1072                ),
1073                ViewPaint::FillCurrentColor => CanvasOp::FillStyle(Paint::Color(current)),
1074                ViewPaint::StrokeCurrentColor => CanvasOp::StrokeStyle(Paint::Color(current)),
1075                ViewPaint::Fit(fit) => CanvasOp::Transform(fit.transform(size).map(Num::Const)),
1076                // Expanded below: its place holds the fill it becomes.
1077                ViewPaint::Background { .. } => continue,
1078            };
1079        }
1080        out.view_paints = Vec::new();
1081        if !self.paints_background() {
1082            return out;
1083        }
1084        let ops = std::mem::take(&mut out.ops);
1085        let mut backgrounds = self.view_paints.iter().filter_map(|&(at, v)| match v {
1086            ViewPaint::Background { area, rule } => Some((at as usize, area, rule)),
1087            _ => None,
1088        });
1089        let mut next = backgrounds.next();
1090        for (i, op) in ops.into_iter().enumerate() {
1091            let Some((_, area, rule)) = next.filter(|&(at, ..)| at == i) else {
1092                out.ops.push(op);
1093                continue;
1094            };
1095            next = backgrounds.next();
1096            out.ops.push(CanvasOp::Save);
1097            if !background.is_transparent() {
1098                out.ops.push(CanvasOp::FillStyle(Paint::Color(background)));
1099                out.ops.push(CanvasOp::Fill(None, rule));
1100            }
1101            for image in images.iter().rev() {
1102                let Some(gradient) = CanvasGradient::from_css(image, area) else {
1103                    log::warn!("an elliptical `radial-gradient()` fills no canvas shape");
1104                    continue;
1105                };
1106                out.ops
1107                    .push(CanvasOp::FillStyle(Paint::Gradient(Arc::new(gradient))));
1108                out.ops.push(CanvasOp::Fill(None, rule));
1109            }
1110            out.ops.push(CanvasOp::Restore);
1111        }
1112        out
1113    }
1114
1115    /// The slot of animated value `node`, adding it if new.
1116    pub fn slot(&mut self, node: crate::animation::NodeId) -> u16 {
1117        match self.slots.iter().position(|&n| n == node) {
1118            Some(i) => i as u16,
1119            None => {
1120                self.slots.push(node);
1121                (self.slots.len() - 1) as u16
1122            }
1123        }
1124    }
1125
1126    /// The images it draws.
1127    pub fn images(&self) -> impl Iterator<Item = &CanvasImage> {
1128        self.ops.iter().filter_map(|op| match op {
1129            CanvasOp::DrawImage { image, .. } => Some(image),
1130            _ => None,
1131        })
1132    }
1133}
1134
1135/// A length: values of another type are zero (as `f32`'s).
1136impl<Cx> OpArg<Cx> for Points {
1137    fn read<L: HostList<Item: HostInput>>(
1138        r: &mut OpReader<'_, L>,
1139        cx: &mut Cx,
1140    ) -> Result<Option<Self>, OpsError> {
1141        Ok(<f32 as OpArg<Cx>>::read(r, cx)?.map(Points))
1142    }
1143
1144    fn ts(types: &mut TsTypes) -> String {
1145        <f32 as OpArg<Cx>>::ts(types)
1146    }
1147}
1148
1149/// A length, or nothing (`maxWidth`).
1150impl<Cx> OpArg<Cx> for Option<Points> {
1151    fn read<L: HostList<Item: HostInput>>(
1152        r: &mut OpReader<'_, L>,
1153        cx: &mut Cx,
1154    ) -> Result<Option<Self>, OpsError> {
1155        Ok(<Option<f32> as OpArg<Cx>>::read(r, cx)?.map(|v| v.map(Points)))
1156    }
1157
1158    fn ts(types: &mut TsTypes) -> String {
1159        <Option<f32> as OpArg<Cx>>::ts(types)
1160    }
1161}
1162
1163/// A point: two arguments, `x` then `y`.
1164impl<Cx> OpArg<Cx> for Point<Points> {
1165    const ARITY: usize = 2;
1166
1167    fn read<L: HostList<Item: HostInput>>(
1168        r: &mut OpReader<'_, L>,
1169        cx: &mut Cx,
1170    ) -> Result<Option<Self>, OpsError> {
1171        let x = <Points as OpArg<Cx>>::read(r, cx)?;
1172        let y = <Points as OpArg<Cx>>::read(r, cx)?;
1173        Ok(x.zip(y).map(|(x, y)| Point { x, y }))
1174    }
1175
1176    fn ts(types: &mut TsTypes) -> String {
1177        <Points as OpArg<Cx>>::ts(types)
1178    }
1179}
1180
1181/// The signed sweep of `arc` / `ellipse` from `start` to `end`, as the
1182/// Canvas spec defines it: a full turn when the angles are a turn or more
1183/// apart in the drawing direction, else the angle between them going that
1184/// way.
1185pub fn arc_sweep(start: Radians, end: Radians, ccw: bool) -> Radians {
1186    Radians(sweep(start.0, end.0, ccw))
1187}
1188
1189pub(crate) fn sweep(start: f32, end: f32, ccw: bool) -> f32 {
1190    use std::f32::consts::TAU;
1191    if !ccw {
1192        if end - start >= TAU {
1193            TAU
1194        } else {
1195            (end - start).rem_euclid(TAU)
1196        }
1197    } else if start - end >= TAU {
1198        -TAU
1199    } else {
1200        -(start - end).rem_euclid(TAU)
1201    }
1202}
1203
1204/// Corner radii of `roundRect` scaled down to fit a box of `size` (CSS
1205/// rule: all by the same factor when two on one side overlap); a negative
1206/// size is a box drawn the other way.
1207pub fn fit_radii(size: Size<Points>, radii: Corners<Points>) -> Corners<Points> {
1208    let [tl, tr, br, bl] = fit(
1209        size.width.0,
1210        size.height.0,
1211        [
1212            radii.top_left.0,
1213            radii.top_right.0,
1214            radii.bottom_right.0,
1215            radii.bottom_left.0,
1216        ],
1217    );
1218    Corners {
1219        top_left: Points(tl),
1220        top_right: Points(tr),
1221        bottom_right: Points(br),
1222        bottom_left: Points(bl),
1223    }
1224}
1225
1226/// [`fit_radii`] on bare numbers: top left, top right, bottom right,
1227/// bottom left.
1228pub(crate) fn fit(w: f32, h: f32, radii: [f32; 4]) -> [f32; 4] {
1229    let r = radii.map(|r| r.max(0.0));
1230    let (w, h) = (w.abs(), h.abs());
1231    let sides = [r[0] + r[1], r[2] + r[3], r[0] + r[3], r[1] + r[2]];
1232    let limits = [w, w, h, h];
1233    let scale = sides
1234        .iter()
1235        .zip(limits)
1236        .filter(|(s, _)| **s > 0.0)
1237        .map(|(s, l)| l / s)
1238        .fold(1.0f32, f32::min);
1239    r.map(|r| r * scale)
1240}
1241
1242// --- SVG path data (`new Path2D("M0 0 L10 10")`) ----------------------------
1243
1244/// SVG path data as a path to fill, stroke or clip (TS: `new
1245/// Path2D(d)`), parsed by [`parse_svg_path`].
1246pub fn svg_path(d: &str) -> Path {
1247    parse_svg_path(d).into()
1248}
1249
1250/// Parses SVG path data into path operations (absolute coordinates;
1251/// smooth curves made explicit, arcs as cubic Béziers). Parsing stops at
1252/// the first error, keeping what came before, as SVG renderers do.
1253pub fn parse_svg_path(d: &str) -> Vec<PathOp> {
1254    let mut out = Vec::new();
1255    let mut p = PathParser {
1256        s: d.as_bytes(),
1257        pos: 0,
1258    };
1259    let (mut x, mut y) = (0f32, 0f32);
1260    let (mut sx, mut sy) = (0f32, 0f32);
1261    // The last control point, for S / T.
1262    let mut last_cubic: Option<(f32, f32)> = None;
1263    let mut last_quad: Option<(f32, f32)> = None;
1264    let mut command = 0u8;
1265    let c = |v: f32| Num::Const(v);
1266    loop {
1267        p.skip_separators();
1268        if p.pos >= p.s.len() {
1269            break;
1270        }
1271        let b = p.s[p.pos];
1272        if b.is_ascii_alphabetic() {
1273            command = b;
1274            p.pos += 1;
1275        } else if command == 0 {
1276            break;
1277        } else if command == b'M' {
1278            // Coordinates after a moveto are linetos.
1279            command = b'L';
1280        } else if command == b'm' {
1281            command = b'l';
1282        }
1283        let rel = command.is_ascii_lowercase();
1284        let (ox, oy) = if rel { (x, y) } else { (0.0, 0.0) };
1285        let upper = command.to_ascii_uppercase();
1286        let ok = (|| -> Option<()> {
1287            match upper {
1288                b'M' => {
1289                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1290                    out.push(PathOp::MoveTo(c(nx), c(ny)));
1291                    (x, y, sx, sy) = (nx, ny, nx, ny);
1292                    last_cubic = None;
1293                    last_quad = None;
1294                }
1295                b'L' => {
1296                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1297                    out.push(PathOp::LineTo(c(nx), c(ny)));
1298                    (x, y) = (nx, ny);
1299                    last_cubic = None;
1300                    last_quad = None;
1301                }
1302                b'H' => {
1303                    x = p.number()? + ox;
1304                    out.push(PathOp::LineTo(c(x), c(y)));
1305                    last_cubic = None;
1306                    last_quad = None;
1307                }
1308                b'V' => {
1309                    y = p.number()? + oy;
1310                    out.push(PathOp::LineTo(c(x), c(y)));
1311                    last_cubic = None;
1312                    last_quad = None;
1313                }
1314                b'C' | b'S' => {
1315                    let (x1, y1) = if upper == b'C' {
1316                        (p.number()? + ox, p.number()? + oy)
1317                    } else {
1318                        // The reflection of the last control point.
1319                        last_cubic.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1320                    };
1321                    let (x2, y2) = (p.number()? + ox, p.number()? + oy);
1322                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1323                    out.push(PathOp::CubicTo([x1, y1, x2, y2, nx, ny].map(c)));
1324                    last_cubic = Some((x2, y2));
1325                    last_quad = None;
1326                    (x, y) = (nx, ny);
1327                }
1328                b'Q' | b'T' => {
1329                    let (x1, y1) = if upper == b'Q' {
1330                        (p.number()? + ox, p.number()? + oy)
1331                    } else {
1332                        last_quad.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1333                    };
1334                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1335                    out.push(PathOp::QuadTo([x1, y1, nx, ny].map(c)));
1336                    last_quad = Some((x1, y1));
1337                    last_cubic = None;
1338                    (x, y) = (nx, ny);
1339                }
1340                b'A' => {
1341                    let rx = p.number()?.abs();
1342                    let ry = p.number()?.abs();
1343                    let rotation = p.number()?;
1344                    let large = p.flag()?;
1345                    let sweep = p.flag()?;
1346                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1347                    arc_to_cubics(&mut out, (x, y), (rx, ry), rotation, large, sweep, (nx, ny));
1348                    (x, y) = (nx, ny);
1349                    last_cubic = None;
1350                    last_quad = None;
1351                }
1352                b'Z' => {
1353                    out.push(PathOp::Close);
1354                    (x, y) = (sx, sy);
1355                    last_cubic = None;
1356                    last_quad = None;
1357                    // Z takes no numbers: a number after it starts nothing.
1358                    command = 0;
1359                }
1360                _ => return None,
1361            }
1362            Some(())
1363        })();
1364        if ok.is_none() {
1365            break;
1366        }
1367    }
1368    out
1369}
1370
1371struct PathParser<'a> {
1372    s: &'a [u8],
1373    pos: usize,
1374}
1375
1376impl PathParser<'_> {
1377    fn skip_separators(&mut self) {
1378        while self.pos < self.s.len()
1379            && (self.s[self.pos].is_ascii_whitespace() || self.s[self.pos] == b',')
1380        {
1381            self.pos += 1;
1382        }
1383    }
1384
1385    fn number(&mut self) -> Option<f32> {
1386        self.skip_separators();
1387        let start = self.pos;
1388        let s = self.s;
1389        let mut i = self.pos;
1390        if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
1391            i += 1;
1392        }
1393        let mut digits = false;
1394        while i < s.len() && s[i].is_ascii_digit() {
1395            i += 1;
1396            digits = true;
1397        }
1398        if i < s.len() && s[i] == b'.' {
1399            i += 1;
1400            while i < s.len() && s[i].is_ascii_digit() {
1401                i += 1;
1402                digits = true;
1403            }
1404        }
1405        if !digits {
1406            return None;
1407        }
1408        if i < s.len() && (s[i] == b'e' || s[i] == b'E') {
1409            let mut j = i + 1;
1410            if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
1411                j += 1;
1412            }
1413            if j < s.len() && s[j].is_ascii_digit() {
1414                while j < s.len() && s[j].is_ascii_digit() {
1415                    j += 1;
1416                }
1417                i = j;
1418            }
1419        }
1420        self.pos = i;
1421        std::str::from_utf8(&s[start..i]).ok()?.parse().ok()
1422    }
1423
1424    /// Arc flags may be written without separators (`a1 1 0 0110 10`).
1425    fn flag(&mut self) -> Option<bool> {
1426        self.skip_separators();
1427        let b = *self.s.get(self.pos)?;
1428        self.pos += 1;
1429        match b {
1430            b'0' => Some(false),
1431            b'1' => Some(true),
1432            _ => None,
1433        }
1434    }
1435}
1436
1437/// An SVG elliptical arc as cubic Béziers (SVG implementation notes,
1438/// F.6.5 and F.6.6).
1439fn arc_to_cubics(
1440    out: &mut Vec<PathOp>,
1441    from: (f32, f32),
1442    radii: (f32, f32),
1443    rotation_deg: f32,
1444    large: bool,
1445    sweep: bool,
1446    to: (f32, f32),
1447) {
1448    let c = |v: f64| Num::Const(v as f32);
1449    let (x1, y1) = (from.0 as f64, from.1 as f64);
1450    let (x2, y2) = (to.0 as f64, to.1 as f64);
1451    let (mut rx, mut ry) = (radii.0 as f64, radii.1 as f64);
1452    if (x1 == x2 && y1 == y2) || rx == 0.0 || ry == 0.0 {
1453        if x1 != x2 || y1 != y2 {
1454            out.push(PathOp::LineTo(c(x2), c(y2)));
1455        }
1456        return;
1457    }
1458    let phi = (rotation_deg as f64).to_radians();
1459    let (sin, cos) = phi.sin_cos();
1460    let dx = (x1 - x2) / 2.0;
1461    let dy = (y1 - y2) / 2.0;
1462    let x1p = cos * dx + sin * dy;
1463    let y1p = -sin * dx + cos * dy;
1464    // Radii too small to reach: scale them up.
1465    let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
1466    if lambda > 1.0 {
1467        let s = lambda.sqrt();
1468        rx *= s;
1469        ry *= s;
1470    }
1471    let num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
1472    let den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
1473    let mut coef = (num / den).max(0.0).sqrt();
1474    if large == sweep {
1475        coef = -coef;
1476    }
1477    let cxp = coef * rx * y1p / ry;
1478    let cyp = -coef * ry * x1p / rx;
1479    let cx = cos * cxp - sin * cyp + (x1 + x2) / 2.0;
1480    let cy = sin * cxp + cos * cyp + (y1 + y2) / 2.0;
1481    let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
1482    let theta1 = angle(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
1483    let mut delta = angle(
1484        (x1p - cxp) / rx,
1485        (y1p - cyp) / ry,
1486        (-x1p - cxp) / rx,
1487        (-y1p - cyp) / ry,
1488    );
1489    if !sweep && delta > 0.0 {
1490        delta -= std::f64::consts::TAU;
1491    } else if sweep && delta < 0.0 {
1492        delta += std::f64::consts::TAU;
1493    }
1494    // At most a quarter turn per segment.
1495    let segments = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
1496    let step = delta / segments as f64;
1497    let k = 4.0 / 3.0 * (step / 4.0).tan();
1498    let point = |t: f64| {
1499        let (s, co) = t.sin_cos();
1500        (
1501            cx + rx * co * cos - ry * s * sin,
1502            cy + rx * co * sin + ry * s * cos,
1503        )
1504    };
1505    let derivative = |t: f64| {
1506        let (s, co) = t.sin_cos();
1507        (-rx * s * cos - ry * co * sin, -rx * s * sin + ry * co * cos)
1508    };
1509    let mut t = theta1;
1510    for i in 0..segments {
1511        let t2 = t + step;
1512        let (p1x, p1y) = point(t);
1513        let (d1x, d1y) = derivative(t);
1514        let (p2x, p2y) = if i + 1 == segments {
1515            (x2, y2)
1516        } else {
1517            point(t2)
1518        };
1519        let (d2x, d2y) = derivative(t2);
1520        out.push(PathOp::CubicTo([
1521            c(p1x + k * d1x),
1522            c(p1y + k * d1y),
1523            c(p2x - k * d2x),
1524            c(p2y - k * d2y),
1525            c(p2x),
1526            c(p2y),
1527        ]));
1528        t = t2;
1529    }
1530}
1531
1532#[cfg(test)]
1533mod tests {
1534    use super::*;
1535    use crate::text::{AttributedText, TextEngine, TextLayout};
1536
1537    /// A CSS gradient as the background of a box: the line through the
1538    /// box's center at the gradient's angle, as long as CSS makes it, and
1539    /// its stops; a repeating one's stops repeated over the whole line, the
1540    /// ends cut at the colors there; an elliptical radial one not drawn.
1541    #[test]
1542    fn css_gradients_become_canvas_gradients_over_a_box() {
1543        use crate::geometry::{bounds, point, size};
1544        let area = bounds(point(px(10.0), px(20.0)), size(px(100.0), px(50.0)));
1545        let one = |css: &str| crate::css::gradients(css).unwrap().remove(0);
1546        let gradient = |css: &str| CanvasGradient::from_css(&one(css), area);
1547        let down = gradient("linear-gradient(to bottom, #ff0000, #0000ff)").unwrap();
1548        assert_eq!(
1549            down.shape,
1550            GradientShape::Linear {
1551                start: point(px(60.0), px(20.0)),
1552                end: point(px(60.0), px(70.0)),
1553            }
1554        );
1555        assert_eq!(down.stops[0], (Percentage(0.0), Color(0xff00_00ff)));
1556        assert_eq!(
1557            down.stops[down.stops.len() - 1],
1558            (Percentage(1.0), Color(0x0000_ffff))
1559        );
1560        let right = gradient("linear-gradient(90deg, #ff0000, #0000ff)").unwrap();
1561        let GradientShape::Linear { start, end } = right.shape else {
1562            panic!("{right:?}")
1563        };
1564        assert!((start.x.0 - 10.0).abs() < 1e-3 && (start.y.0 - 45.0).abs() < 1e-3);
1565        assert!((end.x.0 - 110.0).abs() < 1e-3 && (end.y.0 - 45.0).abs() < 1e-3);
1566        // Repeating every quarter: the stops again at each quarter, all
1567        // within the line.
1568        let stripes =
1569            gradient("repeating-linear-gradient(to bottom, #ff0000 0%, #0000ff 25%)").unwrap();
1570        let at = |o: f32| {
1571            stripes
1572                .stops
1573                .iter()
1574                .filter(|(p, _)| (p.0 - o).abs() < 1e-4)
1575                .count()
1576        };
1577        assert!(
1578            at(0.25) >= 2 && at(0.5) >= 2 && at(0.75) >= 2,
1579            "{stripes:?}"
1580        );
1581        assert!(
1582            stripes
1583                .stops
1584                .iter()
1585                .all(|(p, _)| (0.0..=1.0).contains(&p.0))
1586        );
1587        // Stops past the end: cut there, at the color between.
1588        let cut = gradient("linear-gradient(to bottom, #000000 0%, #ffffff 200%)").unwrap();
1589        assert_eq!(
1590            cut.stops[cut.stops.len() - 1],
1591            (Percentage(1.0), Color(0x8080_80ff))
1592        );
1593        assert!(gradient("radial-gradient(#ff0000, #0000ff)").is_none());
1594        let circle = gradient("radial-gradient(circle, #ff0000, #0000ff)").unwrap();
1595        assert!(matches!(circle.shape, GradientShape::Radial { .. }));
1596    }
1597
1598    /// A drawing filling with its view's background: the color, then each
1599    /// gradient from the bottom layer up, filling the path, the canvas's
1600    /// state kept around them.
1601    #[test]
1602    fn a_drawing_fills_with_its_views_background() {
1603        use crate::geometry::{bounds, point, size};
1604        let area = bounds(point(px(0.0), px(0.0)), size(px(10.0), px(10.0)));
1605        let drawing = crate::element::Painter::new()
1606            .begin_path()
1607            .fill_background_from_view(area)
1608            .finish();
1609        assert!(drawing.paints_background());
1610        let images = crate::css::gradients("linear-gradient(#ff0000, #0000ff)").unwrap();
1611        let none = crate::style::PaintStyle::default();
1612        let painted = drawing.painted(
1613            &none,
1614            Color::TRANSPARENT,
1615            Color(0x00ff_00ff),
1616            &images,
1617            Size::default(),
1618        );
1619        assert!(painted.view_paints.is_empty());
1620        let ops = &painted.ops[1..];
1621        assert_eq!(ops[0], CanvasOp::Save);
1622        assert_eq!(
1623            ops[1],
1624            CanvasOp::FillStyle(Paint::Color(Color(0x00ff_00ff)))
1625        );
1626        assert_eq!(ops[2], CanvasOp::Fill(None, FillRule::NonZero));
1627        assert!(matches!(ops[3], CanvasOp::FillStyle(Paint::Gradient(_))));
1628        assert_eq!(ops[4], CanvasOp::Fill(None, FillRule::NonZero));
1629        assert_eq!(ops[5], CanvasOp::Restore);
1630        // No background: nothing fills.
1631        let bare = drawing.painted(
1632            &none,
1633            Color::TRANSPARENT,
1634            Color::TRANSPARENT,
1635            &[],
1636            Size::default(),
1637        );
1638        assert_eq!(&bare.ops[1..], [CanvasOp::Save, CanvasOp::Restore]);
1639    }
1640
1641    /// Lays a line out as text engines do: 10 points a character, without
1642    /// the white space at its end.
1643    struct Hanging;
1644
1645    impl TextEngine for Hanging {
1646        type Prepared = String;
1647
1648        fn prepare(&self, text: &AttributedText) -> String {
1649            text.text.to_string()
1650        }
1651
1652        fn prepare_aligned(
1653            &self,
1654            text: &AttributedText,
1655            _: &crate::text::AttachmentAlignments,
1656        ) -> String {
1657            self.prepare(text)
1658        }
1659
1660        fn measure(&self, text: &String, _: Option<Points>) -> Size<Points> {
1661            let shown = text.trim_end_matches(|c: char| c.is_whitespace());
1662            Size::new(Points(10.0 * shown.chars().count() as f32), Points(12.0))
1663        }
1664
1665        fn layout(&self, _: &String, _: Size<Points>) -> TextLayout {
1666            TextLayout(std::sync::Arc::new(()))
1667        }
1668    }
1669
1670    #[test]
1671    fn trailing_white_space_advances_as_canvas_measures_it() {
1672        let font = CanvasFont::default();
1673        for (text, width) in [
1674            ("", 0.0),
1675            ("ab", 20.0),
1676            (" ", 10.0),
1677            ("   ", 30.0),
1678            ("  items: ", 90.0),
1679            ("a\t", 20.0),
1680            // Chinese and its ideographic space, a character each.
1681            ("名字\u{3000}", 30.0),
1682            ("你好 ", 30.0),
1683            // A line break ends the line.
1684            ("ab\n", 20.0),
1685        ] {
1686            assert_eq!(
1687                measure_line(&Hanging, &font, text),
1688                Points(width),
1689                "{text:?}"
1690            );
1691            assert_eq!(
1692                line_metrics(&Hanging, &font, text).width,
1693                Points(width),
1694                "{text:?}"
1695            );
1696        }
1697    }
1698
1699    fn consts(op: &PathOp) -> Vec<f32> {
1700        let v = |n: &Num| match n {
1701            Num::Const(v) => *v,
1702            Num::Slot(_) => f32::NAN,
1703        };
1704        match op {
1705            PathOp::MoveTo(a, b) | PathOp::LineTo(a, b) => vec![v(a), v(b)],
1706            PathOp::QuadTo(n) => n.iter().map(v).collect(),
1707            PathOp::CubicTo(n) => n.iter().map(v).collect(),
1708            _ => vec![],
1709        }
1710    }
1711
1712    #[test]
1713    fn svg_paths_parse_to_absolute_ops() {
1714        let ops = parse_svg_path("M10 20 l5-5 H30 v10 z m1 1 2 2");
1715        assert_eq!(ops.len(), 7);
1716        assert_eq!(consts(&ops[1]), vec![15.0, 15.0]);
1717        assert_eq!(consts(&ops[2]), vec![30.0, 15.0]);
1718        assert_eq!(consts(&ops[3]), vec![30.0, 25.0]);
1719        assert_eq!(ops[4], PathOp::Close);
1720        // After Z the current point is the subpath's start.
1721        assert_eq!(consts(&ops[5]), vec![11.0, 21.0]);
1722        // Implicit lineto after a moveto.
1723        assert_eq!(consts(&ops[6]), vec![13.0, 23.0]);
1724        // Compact numbers: `.5.5` is two numbers, `1e2` an exponent.
1725        let ops = parse_svg_path("M.5.5L1e1-2");
1726        assert_eq!(consts(&ops[0]), vec![0.5, 0.5]);
1727        assert_eq!(consts(&ops[1]), vec![10.0, -2.0]);
1728    }
1729
1730    #[test]
1731    fn smooth_curves_reflect_control_points() {
1732        let ops = parse_svg_path("M0 0 C0 10 10 10 10 0 S20 -10 20 0");
1733        assert_eq!(consts(&ops[2]), vec![10.0, -10.0, 20.0, -10.0, 20.0, 0.0]);
1734    }
1735
1736    #[test]
1737    fn arcs_become_cubics_ending_on_the_point() {
1738        // A half circle of radius 10, flags without separators.
1739        let ops = parse_svg_path("M0 0 A10 10 0 0120 0");
1740        assert_eq!(ops.len(), 3);
1741        let last = consts(&ops[2]);
1742        assert!((last[4] - 20.0).abs() < 1e-4 && last[5].abs() < 1e-4);
1743        // Its top: the end of the first quarter, 10 above the center.
1744        let mid = consts(&ops[1]);
1745        assert!((mid[4] - 10.0).abs() < 1e-3 && (mid[5] + 10.0).abs() < 1e-3);
1746    }
1747
1748    #[test]
1749    fn bad_path_data_keeps_what_parsed() {
1750        let ops = parse_svg_path("M0 0 L10 10 L oops");
1751        assert_eq!(ops.len(), 2);
1752    }
1753
1754    #[test]
1755    fn arc_sweeps_follow_the_canvas_spec() {
1756        use std::f32::consts::{PI, TAU};
1757
1758        use crate::geometry::{radians, size};
1759        let sweep = |a, b, ccw| arc_sweep(radians(a), radians(b), ccw).0;
1760        assert_eq!(sweep(0.0, PI, false), PI);
1761        // Backwards clockwise: the long way round.
1762        assert!((sweep(PI, 0.0, false) - PI).abs() < 1e-6);
1763        assert!((sweep(0.0, -PI / 2.0, false) - 1.5 * PI).abs() < 1e-5);
1764        assert_eq!(sweep(0.0, 3.0 * TAU, false), TAU);
1765        assert!((sweep(0.0, PI / 2.0, true) + 1.5 * PI).abs() < 1e-5);
1766        assert_eq!(sweep(TAU, 0.0, true), -TAU);
1767        let corners = |[top_left, top_right, bottom_right, bottom_left]: [f32; 4]| Corners {
1768            top_left: px(top_left),
1769            top_right: px(top_right),
1770            bottom_right: px(bottom_right),
1771            bottom_left: px(bottom_left),
1772        };
1773        assert_eq!(
1774            fit_radii(size(px(10.0), px(100.0)), corners([8.0, 8.0, 0.0, 0.0])),
1775            corners([5.0, 5.0, 0.0, 0.0])
1776        );
1777    }
1778
1779    #[test]
1780    fn fonts_parse_the_css_shorthand() {
1781        let f = CanvasFont::parse("italic bold 14px \"Inter\", sans-serif").unwrap();
1782        assert_eq!((f.size, f.weight, f.italic), (px(14.0), 700, true));
1783        assert_eq!(f.family.as_deref(), Some("Inter"));
1784        let f = CanvasFont::parse("600 12px/1.5 system-ui").unwrap();
1785        assert_eq!((f.size, f.weight, f.family), (px(12.0), 600, None));
1786        let f = CanvasFont::parse("small-caps tabular-nums 13px system-ui").unwrap();
1787        assert_eq!(
1788            f.variant.0,
1789            FontVariant::SMALL_CAPS | FontVariant::TABULAR_NUMS
1790        );
1791        let numeric = f.with_numeric(FontVariant(FontVariant::OLDSTYLE_NUMS));
1792        assert_eq!(
1793            numeric.variant.0,
1794            FontVariant::SMALL_CAPS | FontVariant::OLDSTYLE_NUMS
1795        );
1796        assert_eq!(f.with_numeric(FontVariant::default()), f);
1797        assert!(CanvasFont::parse("wide 13px system-ui").is_none());
1798        assert!(CanvasFont::parse("bold").is_none());
1799        assert!(CanvasFont::parse("14px").is_none());
1800    }
1801}