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},
15    hit::{point_in_path, point_in_stroke},
16};
17use crate::{
18    geometry::{Bounds, Corners, Percentage, Point, Points, Radians, ScaledPixels, Size, px},
19    js::{
20        canvas::*,
21        host::{HostInput, HostList},
22        ops::{JsOps, OpArg, OpReader, OpsError},
23    },
24    style::{Color, FontVariant},
25    ui::{PropEnum, TsTypes},
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
257/// `fillStyle` / `strokeStyle`.
258#[derive(Debug, Clone, PartialEq)]
259pub enum Paint {
260    /// A color.
261    Color(Color),
262    /// The current value of an animated value interpolating colors.
263    Slot(u16),
264    /// A gradient.
265    Gradient(Arc<CanvasGradient>),
266}
267
268/// `globalCompositeOperation`.
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
270#[allow(missing_docs)]
271pub enum Composite {
272    #[default]
273    SourceOver,
274    SourceIn,
275    SourceOut,
276    SourceAtop,
277    DestinationOver,
278    DestinationIn,
279    DestinationOut,
280    DestinationAtop,
281    Lighter,
282    Copy,
283    Xor,
284    Multiply,
285    Screen,
286    Overlay,
287    Darken,
288    Lighten,
289    ColorDodge,
290    ColorBurn,
291    HardLight,
292    SoftLight,
293    Difference,
294    Exclusion,
295    Hue,
296    Saturation,
297    Color,
298    Luminosity,
299}
300
301impl Composite {
302    /// Parses a `globalCompositeOperation` name.
303    pub fn parse(name: &str) -> Option<Composite> {
304        use Composite::*;
305        Some(match name {
306            "source-over" => SourceOver,
307            "source-in" => SourceIn,
308            "source-out" => SourceOut,
309            "source-atop" => SourceAtop,
310            "destination-over" => DestinationOver,
311            "destination-in" => DestinationIn,
312            "destination-out" => DestinationOut,
313            "destination-atop" => DestinationAtop,
314            "lighter" => Lighter,
315            "copy" => Copy,
316            "xor" => Xor,
317            "multiply" => Multiply,
318            "screen" => Screen,
319            "overlay" => Overlay,
320            "darken" => Darken,
321            "lighten" => Lighten,
322            "color-dodge" => ColorDodge,
323            "color-burn" => ColorBurn,
324            "hard-light" => HardLight,
325            "soft-light" => SoftLight,
326            "difference" => Difference,
327            "exclusion" => Exclusion,
328            "hue" => Hue,
329            "saturation" => Saturation,
330            "color" => Color,
331            "luminosity" => Luminosity,
332            _ => return None,
333        })
334    }
335}
336
337/// `font` (the CSS shorthand).
338#[derive(Debug, Clone, PartialEq)]
339pub struct CanvasFont {
340    /// Size.
341    pub size: Points,
342    /// 100..900.
343    pub weight: u16,
344    /// Italic.
345    pub italic: bool,
346    /// The first family; `None` is the system font (also for
347    /// `system-ui` / `sans-serif`).
348    pub family: Option<Arc<str>>,
349    /// OpenType features: `small-caps` and (beyond CSS, which only has
350    /// them in `font-variant-numeric`) `tabular-nums`, `oldstyle-nums`,
351    /// `lining-nums` and `proportional-nums` in the shorthand.
352    pub variant: FontVariant,
353}
354
355impl Default for CanvasFont {
356    /// The canvas default, `10px sans-serif`.
357    fn default() -> Self {
358        Self {
359            size: px(10.0),
360            weight: 400,
361            italic: false,
362            family: None,
363            variant: FontVariant::default(),
364        }
365    }
366}
367
368impl CanvasFont {
369    /// Parses the CSS `font` shorthand (`italic bold 14px Inter`,
370    /// `600 12px/1.2 system-ui`, `tabular-nums 13px system-ui`); `None` if
371    /// it is invalid (canvas keeps the previous font then).
372    pub fn parse(s: &str) -> Option<CanvasFont> {
373        let mut font = CanvasFont {
374            size: Points::ZERO,
375            ..CanvasFont::default()
376        };
377        let mut rest = s.trim();
378        // Style / variant / weight / stretch keywords until the size.
379        loop {
380            let (word, tail) = match rest.split_once(char::is_whitespace) {
381                Some((w, t)) => (w, t.trim_start()),
382                None => (rest, ""),
383            };
384            if let Some(size) = font_size(word) {
385                font.size = size;
386                rest = tail;
387                break;
388            }
389            match word {
390                "italic" | "oblique" => font.italic = true,
391                "normal" | "condensed" | "expanded" => {}
392                w if let Some(v) = FontVariant::parse(w) => font.variant.0 |= v.0,
393                "bold" | "bolder" => font.weight = 700,
394                "lighter" => font.weight = 300,
395                w => match w.parse::<u16>() {
396                    Ok(n) if (1..=1000).contains(&n) => font.weight = n,
397                    _ => return None,
398                },
399            }
400            if tail.is_empty() {
401                return None;
402            }
403            rest = tail;
404        }
405        let family = rest
406            .split(',')
407            .next()
408            .map(|f| f.trim().trim_matches(['"', '\'']))
409            .filter(|f| !f.is_empty())?;
410        font.family = match family {
411            "system-ui" | "sans-serif" | "-apple-system" | "ui-sans-serif" => None,
412            f => Some(f.into()),
413        };
414        Some(font)
415    }
416}
417
418/// `14px` / `14px/1.2` / `1.5rem` / `12pt`: the size.
419fn font_size(word: &str) -> Option<Points> {
420    let word = word.split('/').next()?;
421    let (num, scale) = if let Some(n) = word.strip_suffix("px") {
422        (n, 1.0)
423    } else if let Some(n) = word.strip_suffix("rem").or_else(|| word.strip_suffix("em")) {
424        (n, 16.0)
425    } else {
426        (word.strip_suffix("pt")?, 4.0 / 3.0)
427    };
428    num.parse::<f32>()
429        .ok()
430        .filter(|v| *v > 0.0)
431        .map(|v| Points(v * scale))
432}
433
434impl CanvasFont {
435    /// This font with the numeric forms of `numeric` (`fontVariantNumeric`)
436    /// in place of its own, unless `numeric` is `normal`.
437    pub fn with_numeric(&self, numeric: FontVariant) -> CanvasFont {
438        let mut font = self.clone();
439        if numeric.0 != 0 {
440            font.variant = FontVariant(font.variant.0 & FontVariant::SMALL_CAPS | numeric.0);
441        }
442        font
443    }
444
445    /// The text style of this font.
446    pub fn text_style(&self) -> crate::text::ResolvedTextStyle {
447        crate::text::ResolvedTextStyle {
448            font_size: self.size,
449            font_weight: self.weight,
450            italic: self.italic,
451            font_variant: self.variant,
452            font_family: self.family.as_deref().map(crate::style::FontFamily::new),
453            ..Default::default()
454        }
455    }
456}
457
458/// The width of `text` on one line in `font` (canvas `measureText`).
459pub fn measure_line(
460    engine: &impl crate::text::TextEngine,
461    font: &CanvasFont,
462    text: &str,
463) -> Points {
464    let mut attributed = crate::text::AttributedText {
465        no_wrap: true,
466        max_lines: 1,
467        ..Default::default()
468    };
469    attributed.push(text, font.text_style());
470    if attributed.text.is_empty() {
471        return Points::ZERO;
472    }
473    let prepared = engine.prepare(&attributed);
474    engine.measure(&prepared, None).width
475}
476
477/// Where text sits horizontally relative to its x (`textAlign`).
478#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
479pub enum CanvasTextAlign {
480    /// `start` (left, or right right to left).
481    #[default]
482    Start,
483    /// `end`.
484    End,
485    /// `left`.
486    Left,
487    /// `right`.
488    Right,
489    /// `center`.
490    Center,
491}
492
493/// Where text sits vertically relative to its y (`textBaseline`).
494#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
495pub enum CanvasTextBaseline {
496    /// `alphabetic`.
497    #[default]
498    Alphabetic,
499    /// `top` (the em box's top: the ascent).
500    Top,
501    /// `hanging`.
502    Hanging,
503    /// `middle`.
504    Middle,
505    /// `ideographic`.
506    Ideographic,
507    /// `bottom`.
508    Bottom,
509}
510
511/// What `drawImage` draws: a URL or an imported asset.
512#[derive(Debug, Clone, PartialEq)]
513pub struct CanvasImage {
514    /// URL or `asset:/path`.
515    pub uri: Arc<str>,
516}
517
518/// One recorded operation. The methods and properties without `method` /
519/// `property` are written in `canvas.ts` (overloads, the state stack,
520/// gradients, images).
521#[derive(Debug, Clone, PartialEq, JsOps)]
522#[ops(cx = Drawing)]
523pub enum CanvasOp {
524    /// `save()`.
525    #[op(code = CV_SAVE)]
526    Save,
527    /// `restore()`.
528    #[op(code = CV_RESTORE)]
529    Restore,
530    /// `translate(x, y)`: moves the origin.
531    #[op(code = CV_TRANSLATE, method = "translate", params = "x, y")]
532    Translate(Num, Num),
533    /// `scale(x, y)`: scales the axes.
534    #[op(code = CV_SCALE, method = "scale", params = "x, y")]
535    Scale(Num, Num),
536    /// `rotate(angle)`: rotates the axes; radians, clockwise.
537    #[op(code = CV_ROTATE, method = "rotate", params = "angle")]
538    Rotate(Num),
539    /// `transform(a, b, c, d, e, f)`: multiplies the transform by the matrix
540    /// [a c e; b d f].
541    #[op(code = CV_TRANSFORM, method = "transform", params = "a, b, c, d, e, f")]
542    Transform([Num; 6]),
543    /// `setTransform(a, b, c, d, e, f)`: replaces the transform by the matrix
544    /// [a c e; b d f].
545    ///
546    /// Relative to the view, not the device.
547    #[op(code = CV_SET_TRANSFORM, method = "setTransform", params = "a, b, c, d, e, f")]
548    SetTransform([Num; 6]),
549    /// `beginPath()`: starts a new current path.
550    #[op(code = CV_BEGIN_PATH, method = "beginPath")]
551    BeginPath,
552    /// Adds to the current path.
553    #[op(nested)]
554    Path(PathOp),
555    /// `fill(path?, rule)`: the current path when `None`.
556    #[op(code = CV_FILL)]
557    Fill(Option<Path>, FillRule),
558    /// `stroke(path?)`.
559    #[op(code = CV_STROKE)]
560    Stroke(Option<Path>),
561    /// `clip(path?, rule)`.
562    #[op(code = CV_CLIP)]
563    Clip(Option<Path>, FillRule),
564    /// `fillRect(x, y, w, h)`: fills a rectangle with `fillStyle` (the
565    /// current path stays).
566    #[op(code = CV_FILL_RECT, method = "fillRect", params = "x, y, w, h")]
567    FillRect([Num; 4]),
568    /// `strokeRect(x, y, w, h)`: strokes a rectangle with `strokeStyle`.
569    #[op(code = CV_STROKE_RECT, method = "strokeRect", params = "x, y, w, h")]
570    StrokeRect([Num; 4]),
571    /// `clearRect(x, y, w, h)`: makes a rectangle transparent.
572    #[op(code = CV_CLEAR_RECT, method = "clearRect", params = "x, y, w, h")]
573    ClearRect([Num; 4]),
574    /// `fillStyle`.
575    #[op(code = CV_FILL_STYLE)]
576    FillStyle(Paint),
577    /// `strokeStyle`.
578    #[op(code = CV_STROKE_STYLE)]
579    StrokeStyle(Paint),
580    /// `lineWidth`: stroke width in points.
581    #[op(code = CV_LINE_WIDTH, property = "lineWidth", initial = "1")]
582    LineWidth(Num),
583    /// `lineCap`: how strokes end.
584    #[op(code = CV_LINE_CAP, property = "lineCap", initial = "\"butt\"")]
585    LineCap(LineCap),
586    /// `lineJoin`: how stroke segments join.
587    #[op(code = CV_LINE_JOIN, property = "lineJoin", initial = "\"miter\"")]
588    LineJoin(LineJoin),
589    /// `miterLimit`: miter joins longer than this (in line widths) are
590    /// beveled.
591    #[op(code = CV_MITER_LIMIT, property = "miterLimit", initial = "10", min = 1.0)]
592    MiterLimit(f32),
593    /// `setLineDash(segments)`: an odd count is repeated, as in canvas.
594    #[op(code = CV_LINE_DASH, with = crate::js::canvas::line_dash)]
595    LineDash(Arc<[Points]>),
596    /// `lineDashOffset`: where the dash pattern starts.
597    #[op(code = CV_LINE_DASH_OFFSET, property = "lineDashOffset", initial = "0")]
598    LineDashOffset(Num),
599    /// `globalAlpha`: opacity of what is drawn next, 0..1.
600    #[op(code = CV_GLOBAL_ALPHA, property = "globalAlpha", initial = "1")]
601    GlobalAlpha(Num),
602    /// `globalCompositeOperation`: how what is drawn next combines with the
603    /// canvas (`source-over`, `multiply`, ...).
604    #[op(
605        code = CV_COMPOSITE,
606        property = "globalCompositeOperation",
607        initial = "\"source-over\""
608    )]
609    Composite(Composite),
610    /// `shadowColor`: the color of shadows (transparent: none).
611    #[op(code = CV_SHADOW_COLOR, property = "shadowColor", initial = "\"rgba(0,0,0,0)\"")]
612    ShadowColor(Color),
613    /// `shadowBlur`: shadow blur in points.
614    #[op(code = CV_SHADOW_BLUR, property = "shadowBlur", initial = "0", min = 0.0)]
615    ShadowBlur(Points),
616    /// `shadowOffsetX` / `shadowOffsetY`.
617    #[op(code = CV_SHADOW_OFFSET)]
618    ShadowOffset(Point<Points>),
619    /// `font`: CSS `font` shorthand, e.g. `"600 14px Inter"` (sizes in px, pt
620    /// or rem).
621    #[op(code = CV_FONT, property = "font", initial = "\"10px sans-serif\"")]
622    Font(CanvasFont),
623    /// `fontVariantNumeric` (CSS's `font-variant-numeric`, which HTML
624    /// Canvas lacks): `"tabular-nums"` for figures of equal width,
625    /// `oldstyle-nums`, `lining-nums`, `proportional-nums` or `"normal"`
626    /// (the font's own); kept apart from `font`, which does not reset it.
627    #[op(
628        code = CV_FONT_VARIANT_NUMERIC,
629        property = "fontVariantNumeric",
630        initial = "\"normal\""
631    )]
632    FontVariantNumeric(FontVariant),
633    /// `textAlign`: where text sits horizontally relative to its x.
634    #[op(code = CV_TEXT_ALIGN, property = "textAlign", initial = "\"start\"")]
635    TextAlign(CanvasTextAlign),
636    /// `textBaseline`: where text sits vertically relative to its y.
637    #[op(code = CV_TEXT_BASELINE, property = "textBaseline", initial = "\"alphabetic\"")]
638    TextBaseline(CanvasTextBaseline),
639    /// `fillText(text, x, y, maxWidth?)`.
640    #[op(code = CV_FILL_TEXT)]
641    FillText {
642        /// The text.
643        text: Arc<str>,
644        /// Where it starts.
645        x: Num,
646        /// Its baseline.
647        y: Num,
648        /// Narrowed to fit.
649        max_width: Option<Points>,
650    },
651    /// `strokeText(text, x, y, maxWidth?)`.
652    #[op(code = CV_STROKE_TEXT)]
653    StrokeText {
654        /// The text.
655        text: Arc<str>,
656        /// Where it starts.
657        x: Num,
658        /// Its baseline.
659        y: Num,
660        /// Narrowed to fit.
661        max_width: Option<Points>,
662    },
663    /// `drawImage(image, [sx, sy, sw, sh,] dx, dy, dw, dh)`.
664    #[op(code = CV_DRAW_IMAGE)]
665    DrawImage {
666        /// The image.
667        image: CanvasImage,
668        /// The part of it, in the image's pixels.
669        source: Option<Bounds<ScaledPixels>>,
670        /// Where it goes.
671        dest: [Num; 4],
672    },
673}
674
675/// One `draw` of a canvas.
676#[derive(Debug, Clone, PartialEq, Default)]
677pub struct Drawing {
678    /// The operations, in order.
679    pub ops: Vec<CanvasOp>,
680    /// The animated values the operations read, by slot.
681    pub slots: Vec<crate::animation::NodeId>,
682}
683
684impl Drawing {
685    /// The slot of animated value `node`, adding it if new.
686    pub fn slot(&mut self, node: crate::animation::NodeId) -> u16 {
687        match self.slots.iter().position(|&n| n == node) {
688            Some(i) => i as u16,
689            None => {
690                self.slots.push(node);
691                (self.slots.len() - 1) as u16
692            }
693        }
694    }
695
696    /// The images it draws.
697    pub fn images(&self) -> impl Iterator<Item = &CanvasImage> {
698        self.ops.iter().filter_map(|op| match op {
699            CanvasOp::DrawImage { image, .. } => Some(image),
700            _ => None,
701        })
702    }
703}
704
705/// A length: values of another type are zero (as `f32`'s).
706impl<Cx> OpArg<Cx> for Points {
707    fn read<L: HostList<Item: HostInput>>(
708        r: &mut OpReader<'_, L>,
709        cx: &mut Cx,
710    ) -> Result<Option<Self>, OpsError> {
711        Ok(<f32 as OpArg<Cx>>::read(r, cx)?.map(Points))
712    }
713
714    fn ts(types: &mut TsTypes) -> String {
715        <f32 as OpArg<Cx>>::ts(types)
716    }
717}
718
719/// A length, or nothing (`maxWidth`).
720impl<Cx> OpArg<Cx> for Option<Points> {
721    fn read<L: HostList<Item: HostInput>>(
722        r: &mut OpReader<'_, L>,
723        cx: &mut Cx,
724    ) -> Result<Option<Self>, OpsError> {
725        Ok(<Option<f32> as OpArg<Cx>>::read(r, cx)?.map(|v| v.map(Points)))
726    }
727
728    fn ts(types: &mut TsTypes) -> String {
729        <Option<f32> as OpArg<Cx>>::ts(types)
730    }
731}
732
733/// A point: two arguments, `x` then `y`.
734impl<Cx> OpArg<Cx> for Point<Points> {
735    const ARITY: usize = 2;
736
737    fn read<L: HostList<Item: HostInput>>(
738        r: &mut OpReader<'_, L>,
739        cx: &mut Cx,
740    ) -> Result<Option<Self>, OpsError> {
741        let x = <Points as OpArg<Cx>>::read(r, cx)?;
742        let y = <Points as OpArg<Cx>>::read(r, cx)?;
743        Ok(x.zip(y).map(|(x, y)| Point { x, y }))
744    }
745
746    fn ts(types: &mut TsTypes) -> String {
747        <Points as OpArg<Cx>>::ts(types)
748    }
749}
750
751/// The signed sweep of `arc` / `ellipse` from `start` to `end`, as the
752/// Canvas spec defines it: a full turn when the angles are a turn or more
753/// apart in the drawing direction, else the angle between them going that
754/// way.
755pub fn arc_sweep(start: Radians, end: Radians, ccw: bool) -> Radians {
756    Radians(sweep(start.0, end.0, ccw))
757}
758
759pub(crate) fn sweep(start: f32, end: f32, ccw: bool) -> f32 {
760    use std::f32::consts::TAU;
761    if !ccw {
762        if end - start >= TAU {
763            TAU
764        } else {
765            (end - start).rem_euclid(TAU)
766        }
767    } else if start - end >= TAU {
768        -TAU
769    } else {
770        -(start - end).rem_euclid(TAU)
771    }
772}
773
774/// Corner radii of `roundRect` scaled down to fit a box of `size` (CSS
775/// rule: all by the same factor when two on one side overlap); a negative
776/// size is a box drawn the other way.
777pub fn fit_radii(size: Size<Points>, radii: Corners<Points>) -> Corners<Points> {
778    let [tl, tr, br, bl] = fit(
779        size.width.0,
780        size.height.0,
781        [
782            radii.top_left.0,
783            radii.top_right.0,
784            radii.bottom_right.0,
785            radii.bottom_left.0,
786        ],
787    );
788    Corners {
789        top_left: Points(tl),
790        top_right: Points(tr),
791        bottom_right: Points(br),
792        bottom_left: Points(bl),
793    }
794}
795
796/// [`fit_radii`] on bare numbers: top left, top right, bottom right,
797/// bottom left.
798pub(crate) fn fit(w: f32, h: f32, radii: [f32; 4]) -> [f32; 4] {
799    let r = radii.map(|r| r.max(0.0));
800    let (w, h) = (w.abs(), h.abs());
801    let sides = [r[0] + r[1], r[2] + r[3], r[0] + r[3], r[1] + r[2]];
802    let limits = [w, w, h, h];
803    let scale = sides
804        .iter()
805        .zip(limits)
806        .filter(|(s, _)| **s > 0.0)
807        .map(|(s, l)| l / s)
808        .fold(1.0f32, f32::min);
809    r.map(|r| r * scale)
810}
811
812// --- SVG path data (`new Path2D("M0 0 L10 10")`) ----------------------------
813
814/// SVG path data as a path to fill, stroke or clip (TS: `new
815/// Path2D(d)`), parsed by [`parse_svg_path`].
816pub fn svg_path(d: &str) -> Path {
817    parse_svg_path(d).into()
818}
819
820/// Parses SVG path data into path operations (absolute coordinates;
821/// smooth curves made explicit, arcs as cubic Béziers). Parsing stops at
822/// the first error, keeping what came before, as SVG renderers do.
823pub fn parse_svg_path(d: &str) -> Vec<PathOp> {
824    let mut out = Vec::new();
825    let mut p = PathParser {
826        s: d.as_bytes(),
827        pos: 0,
828    };
829    let (mut x, mut y) = (0f32, 0f32);
830    let (mut sx, mut sy) = (0f32, 0f32);
831    // The last control point, for S / T.
832    let mut last_cubic: Option<(f32, f32)> = None;
833    let mut last_quad: Option<(f32, f32)> = None;
834    let mut command = 0u8;
835    let c = |v: f32| Num::Const(v);
836    loop {
837        p.skip_separators();
838        if p.pos >= p.s.len() {
839            break;
840        }
841        let b = p.s[p.pos];
842        if b.is_ascii_alphabetic() {
843            command = b;
844            p.pos += 1;
845        } else if command == 0 {
846            break;
847        } else if command == b'M' {
848            // Coordinates after a moveto are linetos.
849            command = b'L';
850        } else if command == b'm' {
851            command = b'l';
852        }
853        let rel = command.is_ascii_lowercase();
854        let (ox, oy) = if rel { (x, y) } else { (0.0, 0.0) };
855        let upper = command.to_ascii_uppercase();
856        let ok = (|| -> Option<()> {
857            match upper {
858                b'M' => {
859                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
860                    out.push(PathOp::MoveTo(c(nx), c(ny)));
861                    (x, y, sx, sy) = (nx, ny, nx, ny);
862                    last_cubic = None;
863                    last_quad = None;
864                }
865                b'L' => {
866                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
867                    out.push(PathOp::LineTo(c(nx), c(ny)));
868                    (x, y) = (nx, ny);
869                    last_cubic = None;
870                    last_quad = None;
871                }
872                b'H' => {
873                    x = p.number()? + ox;
874                    out.push(PathOp::LineTo(c(x), c(y)));
875                    last_cubic = None;
876                    last_quad = None;
877                }
878                b'V' => {
879                    y = p.number()? + oy;
880                    out.push(PathOp::LineTo(c(x), c(y)));
881                    last_cubic = None;
882                    last_quad = None;
883                }
884                b'C' | b'S' => {
885                    let (x1, y1) = if upper == b'C' {
886                        (p.number()? + ox, p.number()? + oy)
887                    } else {
888                        // The reflection of the last control point.
889                        last_cubic.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
890                    };
891                    let (x2, y2) = (p.number()? + ox, p.number()? + oy);
892                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
893                    out.push(PathOp::CubicTo([x1, y1, x2, y2, nx, ny].map(c)));
894                    last_cubic = Some((x2, y2));
895                    last_quad = None;
896                    (x, y) = (nx, ny);
897                }
898                b'Q' | b'T' => {
899                    let (x1, y1) = if upper == b'Q' {
900                        (p.number()? + ox, p.number()? + oy)
901                    } else {
902                        last_quad.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
903                    };
904                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
905                    out.push(PathOp::QuadTo([x1, y1, nx, ny].map(c)));
906                    last_quad = Some((x1, y1));
907                    last_cubic = None;
908                    (x, y) = (nx, ny);
909                }
910                b'A' => {
911                    let rx = p.number()?.abs();
912                    let ry = p.number()?.abs();
913                    let rotation = p.number()?;
914                    let large = p.flag()?;
915                    let sweep = p.flag()?;
916                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
917                    arc_to_cubics(&mut out, (x, y), (rx, ry), rotation, large, sweep, (nx, ny));
918                    (x, y) = (nx, ny);
919                    last_cubic = None;
920                    last_quad = None;
921                }
922                b'Z' => {
923                    out.push(PathOp::Close);
924                    (x, y) = (sx, sy);
925                    last_cubic = None;
926                    last_quad = None;
927                    // Z takes no numbers: a number after it starts nothing.
928                    command = 0;
929                }
930                _ => return None,
931            }
932            Some(())
933        })();
934        if ok.is_none() {
935            break;
936        }
937    }
938    out
939}
940
941struct PathParser<'a> {
942    s: &'a [u8],
943    pos: usize,
944}
945
946impl PathParser<'_> {
947    fn skip_separators(&mut self) {
948        while self.pos < self.s.len()
949            && (self.s[self.pos].is_ascii_whitespace() || self.s[self.pos] == b',')
950        {
951            self.pos += 1;
952        }
953    }
954
955    fn number(&mut self) -> Option<f32> {
956        self.skip_separators();
957        let start = self.pos;
958        let s = self.s;
959        let mut i = self.pos;
960        if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
961            i += 1;
962        }
963        let mut digits = false;
964        while i < s.len() && s[i].is_ascii_digit() {
965            i += 1;
966            digits = true;
967        }
968        if i < s.len() && s[i] == b'.' {
969            i += 1;
970            while i < s.len() && s[i].is_ascii_digit() {
971                i += 1;
972                digits = true;
973            }
974        }
975        if !digits {
976            return None;
977        }
978        if i < s.len() && (s[i] == b'e' || s[i] == b'E') {
979            let mut j = i + 1;
980            if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
981                j += 1;
982            }
983            if j < s.len() && s[j].is_ascii_digit() {
984                while j < s.len() && s[j].is_ascii_digit() {
985                    j += 1;
986                }
987                i = j;
988            }
989        }
990        self.pos = i;
991        std::str::from_utf8(&s[start..i]).ok()?.parse().ok()
992    }
993
994    /// Arc flags may be written without separators (`a1 1 0 0110 10`).
995    fn flag(&mut self) -> Option<bool> {
996        self.skip_separators();
997        let b = *self.s.get(self.pos)?;
998        self.pos += 1;
999        match b {
1000            b'0' => Some(false),
1001            b'1' => Some(true),
1002            _ => None,
1003        }
1004    }
1005}
1006
1007/// An SVG elliptical arc as cubic Béziers (SVG implementation notes,
1008/// F.6.5 and F.6.6).
1009fn arc_to_cubics(
1010    out: &mut Vec<PathOp>,
1011    from: (f32, f32),
1012    radii: (f32, f32),
1013    rotation_deg: f32,
1014    large: bool,
1015    sweep: bool,
1016    to: (f32, f32),
1017) {
1018    let c = |v: f64| Num::Const(v as f32);
1019    let (x1, y1) = (from.0 as f64, from.1 as f64);
1020    let (x2, y2) = (to.0 as f64, to.1 as f64);
1021    let (mut rx, mut ry) = (radii.0 as f64, radii.1 as f64);
1022    if (x1 == x2 && y1 == y2) || rx == 0.0 || ry == 0.0 {
1023        if x1 != x2 || y1 != y2 {
1024            out.push(PathOp::LineTo(c(x2), c(y2)));
1025        }
1026        return;
1027    }
1028    let phi = (rotation_deg as f64).to_radians();
1029    let (sin, cos) = phi.sin_cos();
1030    let dx = (x1 - x2) / 2.0;
1031    let dy = (y1 - y2) / 2.0;
1032    let x1p = cos * dx + sin * dy;
1033    let y1p = -sin * dx + cos * dy;
1034    // Radii too small to reach: scale them up.
1035    let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
1036    if lambda > 1.0 {
1037        let s = lambda.sqrt();
1038        rx *= s;
1039        ry *= s;
1040    }
1041    let num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
1042    let den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
1043    let mut coef = (num / den).max(0.0).sqrt();
1044    if large == sweep {
1045        coef = -coef;
1046    }
1047    let cxp = coef * rx * y1p / ry;
1048    let cyp = -coef * ry * x1p / rx;
1049    let cx = cos * cxp - sin * cyp + (x1 + x2) / 2.0;
1050    let cy = sin * cxp + cos * cyp + (y1 + y2) / 2.0;
1051    let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
1052    let theta1 = angle(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
1053    let mut delta = angle(
1054        (x1p - cxp) / rx,
1055        (y1p - cyp) / ry,
1056        (-x1p - cxp) / rx,
1057        (-y1p - cyp) / ry,
1058    );
1059    if !sweep && delta > 0.0 {
1060        delta -= std::f64::consts::TAU;
1061    } else if sweep && delta < 0.0 {
1062        delta += std::f64::consts::TAU;
1063    }
1064    // At most a quarter turn per segment.
1065    let segments = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
1066    let step = delta / segments as f64;
1067    let k = 4.0 / 3.0 * (step / 4.0).tan();
1068    let point = |t: f64| {
1069        let (s, co) = t.sin_cos();
1070        (
1071            cx + rx * co * cos - ry * s * sin,
1072            cy + rx * co * sin + ry * s * cos,
1073        )
1074    };
1075    let derivative = |t: f64| {
1076        let (s, co) = t.sin_cos();
1077        (-rx * s * cos - ry * co * sin, -rx * s * sin + ry * co * cos)
1078    };
1079    let mut t = theta1;
1080    for i in 0..segments {
1081        let t2 = t + step;
1082        let (p1x, p1y) = point(t);
1083        let (d1x, d1y) = derivative(t);
1084        let (p2x, p2y) = if i + 1 == segments {
1085            (x2, y2)
1086        } else {
1087            point(t2)
1088        };
1089        let (d2x, d2y) = derivative(t2);
1090        out.push(PathOp::CubicTo([
1091            c(p1x + k * d1x),
1092            c(p1y + k * d1y),
1093            c(p2x - k * d2x),
1094            c(p2y - k * d2y),
1095            c(p2x),
1096            c(p2y),
1097        ]));
1098        t = t2;
1099    }
1100}
1101
1102#[cfg(test)]
1103mod tests {
1104    use super::*;
1105
1106    fn consts(op: &PathOp) -> Vec<f32> {
1107        let v = |n: &Num| match n {
1108            Num::Const(v) => *v,
1109            Num::Slot(_) => f32::NAN,
1110        };
1111        match op {
1112            PathOp::MoveTo(a, b) | PathOp::LineTo(a, b) => vec![v(a), v(b)],
1113            PathOp::QuadTo(n) => n.iter().map(v).collect(),
1114            PathOp::CubicTo(n) => n.iter().map(v).collect(),
1115            _ => vec![],
1116        }
1117    }
1118
1119    #[test]
1120    fn svg_paths_parse_to_absolute_ops() {
1121        let ops = parse_svg_path("M10 20 l5-5 H30 v10 z m1 1 2 2");
1122        assert_eq!(ops.len(), 7);
1123        assert_eq!(consts(&ops[1]), vec![15.0, 15.0]);
1124        assert_eq!(consts(&ops[2]), vec![30.0, 15.0]);
1125        assert_eq!(consts(&ops[3]), vec![30.0, 25.0]);
1126        assert_eq!(ops[4], PathOp::Close);
1127        // After Z the current point is the subpath's start.
1128        assert_eq!(consts(&ops[5]), vec![11.0, 21.0]);
1129        // Implicit lineto after a moveto.
1130        assert_eq!(consts(&ops[6]), vec![13.0, 23.0]);
1131        // Compact numbers: `.5.5` is two numbers, `1e2` an exponent.
1132        let ops = parse_svg_path("M.5.5L1e1-2");
1133        assert_eq!(consts(&ops[0]), vec![0.5, 0.5]);
1134        assert_eq!(consts(&ops[1]), vec![10.0, -2.0]);
1135    }
1136
1137    #[test]
1138    fn smooth_curves_reflect_control_points() {
1139        let ops = parse_svg_path("M0 0 C0 10 10 10 10 0 S20 -10 20 0");
1140        assert_eq!(consts(&ops[2]), vec![10.0, -10.0, 20.0, -10.0, 20.0, 0.0]);
1141    }
1142
1143    #[test]
1144    fn arcs_become_cubics_ending_on_the_point() {
1145        // A half circle of radius 10, flags without separators.
1146        let ops = parse_svg_path("M0 0 A10 10 0 0120 0");
1147        assert_eq!(ops.len(), 3);
1148        let last = consts(&ops[2]);
1149        assert!((last[4] - 20.0).abs() < 1e-4 && last[5].abs() < 1e-4);
1150        // Its top: the end of the first quarter, 10 above the center.
1151        let mid = consts(&ops[1]);
1152        assert!((mid[4] - 10.0).abs() < 1e-3 && (mid[5] + 10.0).abs() < 1e-3);
1153    }
1154
1155    #[test]
1156    fn bad_path_data_keeps_what_parsed() {
1157        let ops = parse_svg_path("M0 0 L10 10 L oops");
1158        assert_eq!(ops.len(), 2);
1159    }
1160
1161    #[test]
1162    fn arc_sweeps_follow_the_canvas_spec() {
1163        use std::f32::consts::{PI, TAU};
1164
1165        use crate::geometry::{radians, size};
1166        let sweep = |a, b, ccw| arc_sweep(radians(a), radians(b), ccw).0;
1167        assert_eq!(sweep(0.0, PI, false), PI);
1168        // Backwards clockwise: the long way round.
1169        assert!((sweep(PI, 0.0, false) - PI).abs() < 1e-6);
1170        assert!((sweep(0.0, -PI / 2.0, false) - 1.5 * PI).abs() < 1e-5);
1171        assert_eq!(sweep(0.0, 3.0 * TAU, false), TAU);
1172        assert!((sweep(0.0, PI / 2.0, true) + 1.5 * PI).abs() < 1e-5);
1173        assert_eq!(sweep(TAU, 0.0, true), -TAU);
1174        let corners = |[top_left, top_right, bottom_right, bottom_left]: [f32; 4]| Corners {
1175            top_left: px(top_left),
1176            top_right: px(top_right),
1177            bottom_right: px(bottom_right),
1178            bottom_left: px(bottom_left),
1179        };
1180        assert_eq!(
1181            fit_radii(size(px(10.0), px(100.0)), corners([8.0, 8.0, 0.0, 0.0])),
1182            corners([5.0, 5.0, 0.0, 0.0])
1183        );
1184    }
1185
1186    #[test]
1187    fn fonts_parse_the_css_shorthand() {
1188        let f = CanvasFont::parse("italic bold 14px \"Inter\", sans-serif").unwrap();
1189        assert_eq!((f.size, f.weight, f.italic), (px(14.0), 700, true));
1190        assert_eq!(f.family.as_deref(), Some("Inter"));
1191        let f = CanvasFont::parse("600 12px/1.5 system-ui").unwrap();
1192        assert_eq!((f.size, f.weight, f.family), (px(12.0), 600, None));
1193        let f = CanvasFont::parse("small-caps tabular-nums 13px system-ui").unwrap();
1194        assert_eq!(
1195            f.variant.0,
1196            FontVariant::SMALL_CAPS | FontVariant::TABULAR_NUMS
1197        );
1198        let numeric = f.with_numeric(FontVariant(FontVariant::OLDSTYLE_NUMS));
1199        assert_eq!(
1200            numeric.variant.0,
1201            FontVariant::SMALL_CAPS | FontVariant::OLDSTYLE_NUMS
1202        );
1203        assert_eq!(f.with_numeric(FontVariant::default()), f);
1204        assert!(CanvasFont::parse("wide 13px system-ui").is_none());
1205        assert!(CanvasFont::parse("bold").is_none());
1206        assert!(CanvasFont::parse("14px").is_none());
1207    }
1208}