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