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