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 (ascent, descent, height) = laid_line(engine, font, text);
606    let width = if text.is_empty() {
607        Points::ZERO
608    } else {
609        advance(engine, font, text)
610    };
611    TextMetrics {
612        width,
613        ascent,
614        descent,
615        height,
616    }
617}
618
619/// The ascent and descent [`line_metrics`] gives, without measuring the
620/// width.
621pub fn line_extent(
622    engine: &impl crate::text::TextEngine,
623    font: &CanvasFont,
624    text: &str,
625) -> (Points, Points) {
626    let (ascent, descent, _) = laid_line(engine, font, text);
627    (ascent, descent)
628}
629
630/// One line of `text` laid out: its ascent, descent and height.
631fn laid_line(
632    engine: &impl crate::text::TextEngine,
633    font: &CanvasFont,
634    text: &str,
635) -> (Points, Points, Points) {
636    let mut attributed = crate::text::AttributedText {
637        no_wrap: true,
638        max_lines: 1,
639        ..Default::default()
640    };
641    // An empty line still has the font's extent.
642    attributed.push(if text.is_empty() { " " } else { text }, font.text_style());
643    let prepared = engine.prepare(&attributed);
644    let size = engine.measure(&prepared, None);
645    let layout = engine.layout(&prepared, size);
646    match engine.lines(&layout).first() {
647        Some(line) => (line.ascender, line.descender, line.height),
648        None => (
649            Points(font.size.0 * 0.8),
650            Points(font.size.0 * 0.2),
651            size.height,
652        ),
653    }
654}
655
656/// Where text sits horizontally relative to its x (`textAlign`).
657#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
658pub enum CanvasTextAlign {
659    /// `start` (left, or right right to left).
660    #[default]
661    Start,
662    /// `end`.
663    End,
664    /// `left`.
665    Left,
666    /// `right`.
667    Right,
668    /// `center`.
669    Center,
670}
671
672/// Where text sits vertically relative to its y (`textBaseline`).
673#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
674pub enum CanvasTextBaseline {
675    /// `alphabetic`.
676    #[default]
677    Alphabetic,
678    /// `top` (the em box's top: the ascent).
679    Top,
680    /// `hanging`.
681    Hanging,
682    /// `middle`.
683    Middle,
684    /// `ideographic`.
685    Ideographic,
686    /// `bottom`.
687    Bottom,
688}
689
690/// What `drawImage` draws: a URL or an imported asset.
691#[derive(Debug, Clone, PartialEq)]
692pub struct CanvasImage {
693    /// URL or `asset:/path`.
694    pub uri: Arc<str>,
695}
696
697impl CanvasImage {
698    /// The pixels per point its file name declares (`logo@3x.png` → 3; 1
699    /// without), as an `Image`'s: `drawImage` without a destination size
700    /// draws it at its pixels over this many points, on every screen.
701    pub fn density(&self) -> f32 {
702        crate::image::density(&self.uri)
703    }
704}
705
706/// One recorded operation. The methods and properties without `method` /
707/// `property` are written in `canvas.ts` (overloads, the state stack,
708/// gradients, images).
709#[derive(Debug, Clone, PartialEq, JsOps)]
710#[ops(cx = Drawing)]
711pub enum CanvasOp {
712    /// `save()`.
713    #[op(code = CV_SAVE)]
714    Save,
715    /// `restore()`.
716    #[op(code = CV_RESTORE)]
717    Restore,
718    /// `translate(x, y)`: moves the origin.
719    #[op(code = CV_TRANSLATE, method = "translate", params = "x, y")]
720    Translate(Num, Num),
721    /// `scale(x, y)`: scales the axes.
722    #[op(code = CV_SCALE, method = "scale", params = "x, y")]
723    Scale(Num, Num),
724    /// `rotate(angle)`: rotates the axes; radians, clockwise.
725    #[op(code = CV_ROTATE, method = "rotate", params = "angle")]
726    Rotate(Num),
727    /// `transform(a, b, c, d, e, f)`: multiplies the transform by the matrix
728    /// [a c e; b d f].
729    #[op(code = CV_TRANSFORM, method = "transform", params = "a, b, c, d, e, f")]
730    Transform([Num; 6]),
731    /// `setTransform(a, b, c, d, e, f)`: replaces the transform by the matrix
732    /// [a c e; b d f].
733    ///
734    /// Relative to the view, not the device.
735    #[op(code = CV_SET_TRANSFORM, method = "setTransform", params = "a, b, c, d, e, f")]
736    SetTransform([Num; 6]),
737    /// `beginPath()`: starts a new current path.
738    #[op(code = CV_BEGIN_PATH, method = "beginPath")]
739    BeginPath,
740    /// Adds to the current path.
741    #[op(nested)]
742    Path(PathOp),
743    /// `fill(path?, rule)`: the current path when `None`.
744    #[op(code = CV_FILL)]
745    Fill(Option<Path>, FillRule),
746    /// `stroke(path?)`.
747    #[op(code = CV_STROKE)]
748    Stroke(Option<Path>),
749    /// `clip(path?, rule)`.
750    #[op(code = CV_CLIP)]
751    Clip(Option<Path>, FillRule),
752    /// `fillRect(x, y, w, h)`: fills a rectangle with `fillStyle` (the
753    /// current path stays).
754    #[op(code = CV_FILL_RECT, method = "fillRect", params = "x, y, w, h")]
755    FillRect([Num; 4]),
756    /// `strokeRect(x, y, w, h)`: strokes a rectangle with `strokeStyle`.
757    #[op(code = CV_STROKE_RECT, method = "strokeRect", params = "x, y, w, h")]
758    StrokeRect([Num; 4]),
759    /// `clearRect(x, y, w, h)`: makes a rectangle transparent.
760    #[op(code = CV_CLEAR_RECT, method = "clearRect", params = "x, y, w, h")]
761    ClearRect([Num; 4]),
762    /// `fillStyle`.
763    #[op(code = CV_FILL_STYLE)]
764    FillStyle(Paint),
765    /// `strokeStyle`.
766    #[op(code = CV_STROKE_STYLE)]
767    StrokeStyle(Paint),
768    /// `lineWidth`: stroke width in points.
769    #[op(code = CV_LINE_WIDTH, property = "lineWidth", initial = "1")]
770    LineWidth(Num),
771    /// `lineCap`: how strokes end.
772    #[op(code = CV_LINE_CAP, property = "lineCap", initial = "\"butt\"")]
773    LineCap(LineCap),
774    /// `lineJoin`: how stroke segments join.
775    #[op(code = CV_LINE_JOIN, property = "lineJoin", initial = "\"miter\"")]
776    LineJoin(LineJoin),
777    /// `miterLimit`: miter joins longer than this (in line widths) are
778    /// beveled.
779    #[op(code = CV_MITER_LIMIT, property = "miterLimit", initial = "10", min = 1.0)]
780    MiterLimit(f32),
781    /// `setLineDash(segments)`: an odd count is repeated, as in canvas.
782    #[op(code = CV_LINE_DASH, with = crate::js::canvas::line_dash)]
783    LineDash(Arc<[Points]>),
784    /// `lineDashOffset`: where the dash pattern starts.
785    #[op(code = CV_LINE_DASH_OFFSET, property = "lineDashOffset", initial = "0")]
786    LineDashOffset(Num),
787    /// `globalAlpha`: opacity of what is drawn next, 0..1.
788    #[op(code = CV_GLOBAL_ALPHA, property = "globalAlpha", initial = "1")]
789    GlobalAlpha(Num),
790    /// `globalCompositeOperation`: how what is drawn next combines with the
791    /// canvas (`source-over`, `multiply`, ...).
792    #[op(
793        code = CV_COMPOSITE,
794        property = "globalCompositeOperation",
795        initial = "\"source-over\""
796    )]
797    Composite(Composite),
798    /// `shadowColor`: the color of shadows (transparent: none).
799    #[op(code = CV_SHADOW_COLOR, property = "shadowColor", initial = "\"rgba(0,0,0,0)\"")]
800    ShadowColor(Color),
801    /// `shadowBlur`: shadow blur in points.
802    #[op(code = CV_SHADOW_BLUR, property = "shadowBlur", initial = "0", min = 0.0)]
803    ShadowBlur(Points),
804    /// `shadowOffsetX` / `shadowOffsetY`.
805    #[op(code = CV_SHADOW_OFFSET)]
806    ShadowOffset(Point<Points>),
807    /// `font`: CSS `font` shorthand, e.g. `"600 14px Inter"` (sizes in px, pt
808    /// or rem).
809    #[op(code = CV_FONT, property = "font", initial = "\"10px sans-serif\"")]
810    Font(CanvasFont),
811    /// `fontVariantNumeric` (CSS's `font-variant-numeric`, which HTML
812    /// Canvas lacks): `"tabular-nums"` for figures of equal width,
813    /// `oldstyle-nums`, `lining-nums`, `proportional-nums` or `"normal"`
814    /// (the font's own); kept apart from `font`, which does not reset it.
815    #[op(
816        code = CV_FONT_VARIANT_NUMERIC,
817        property = "fontVariantNumeric",
818        initial = "\"normal\""
819    )]
820    FontVariantNumeric(FontVariant),
821    /// `textAlign`: where text sits horizontally relative to its x.
822    #[op(code = CV_TEXT_ALIGN, property = "textAlign", initial = "\"start\"")]
823    TextAlign(CanvasTextAlign),
824    /// `textBaseline`: where text sits vertically relative to its y.
825    #[op(code = CV_TEXT_BASELINE, property = "textBaseline", initial = "\"alphabetic\"")]
826    TextBaseline(CanvasTextBaseline),
827    /// `fillText(text, x, y, maxWidth?)`.
828    #[op(code = CV_FILL_TEXT)]
829    FillText {
830        /// The text.
831        text: Arc<str>,
832        /// Where it starts.
833        x: Num,
834        /// Its baseline.
835        y: Num,
836        /// Narrowed to fit.
837        max_width: Option<Points>,
838    },
839    /// `strokeText(text, x, y, maxWidth?)`.
840    #[op(code = CV_STROKE_TEXT)]
841    StrokeText {
842        /// The text.
843        text: Arc<str>,
844        /// Where it starts.
845        x: Num,
846        /// Its baseline.
847        y: Num,
848        /// Narrowed to fit.
849        max_width: Option<Points>,
850    },
851    /// `drawImage(image, [sx, sy, sw, sh,] dx, dy, dw, dh)`.
852    #[op(code = CV_DRAW_IMAGE)]
853    DrawImage {
854        /// The image.
855        image: CanvasImage,
856        /// The part of it, in the image's pixels.
857        source: Option<Bounds<ScaledPixels>>,
858        /// Where it goes.
859        dest: [Num; 4],
860    },
861}
862
863impl CanvasOp {
864    /// Whether it paints (rather than setting the state: transforms,
865    /// styles, paths, clips).
866    pub fn paints(&self) -> bool {
867        matches!(
868            self,
869            CanvasOp::Fill(..)
870                | CanvasOp::Stroke(_)
871                | CanvasOp::FillRect(_)
872                | CanvasOp::StrokeRect(_)
873                | CanvasOp::ClearRect(_)
874                | CanvasOp::FillText { .. }
875                | CanvasOp::StrokeText { .. }
876                | CanvasOp::DrawImage { .. }
877        )
878    }
879}
880
881/// One `draw` of a canvas.
882#[derive(Debug, Clone, PartialEq, Default)]
883pub struct Drawing {
884    /// The operations, in order.
885    pub ops: Vec<CanvasOp>,
886    /// The animated values the operations read, by slot.
887    pub slots: Vec<crate::animation::NodeId>,
888    /// The parts of what it draws that are elements of their own to
889    /// assistive technologies and UI tests ([`CanvasNode`]), in reading
890    /// order.
891    pub nodes: Vec<CanvasNode>,
892    /// The operations whose value is the canvas view's style rather than
893    /// one of their own, by index in `ops`: the core gives them the
894    /// view's paint properties ([`crate::style::PaintStyle`], inherited
895    /// from the views around it) before a platform gets the drawing
896    /// ([`Drawing::painted`]), so what a Rust component draws follows the
897    /// app's `fill-*` / `stroke-*` classes and the appearance without
898    /// being recorded again.
899    pub view_paints: Vec<(u32, ViewPaint)>,
900}
901
902/// An operation of a [`Drawing`] that takes its value from the canvas
903/// view's paint properties ([`Drawing::view_paints`]).
904#[derive(Debug, Clone, Copy, PartialEq)]
905pub enum ViewPaint {
906    /// `fillStyle` is the view's `fill`; where nothing sets one, this.
907    Fill(crate::style::SvgPaint),
908    /// `strokeStyle` is the view's `stroke`; where nothing sets one, this.
909    Stroke(crate::style::SvgPaint),
910    /// `lineWidth` is the view's `strokeWidth` (1 where nothing sets one,
911    /// CSS's initial value).
912    StrokeWidth,
913    /// The line dash is the view's `strokeDasharray` (solid where nothing
914    /// sets one).
915    StrokeDasharray,
916    /// `fillStyle` is the view's text color: a shape filled with
917    /// `currentColor` (an SVG's, [`crate::element::svg`]), which follows
918    /// the text color whatever the view's `fill`.
919    FillCurrentColor,
920    /// `strokeStyle` is the view's text color
921    /// ([`ViewPaint::FillCurrentColor`]).
922    StrokeCurrentColor,
923    /// `transform` maps a view box onto the canvas's box: the operations
924    /// after it draw in the view box's coordinates, and the canvas lays
925    /// out at its natural size ([`ViewBoxFit`]).
926    Fit(ViewBoxFit),
927    /// Fills the current path by `rule` with the view's background: its
928    /// `backgroundColor`, then its `backgroundImage` layers over it (the
929    /// last one first, as CSS stacks them), each positioned over `area`
930    /// (canvas coordinates) as over a box of that size
931    /// ([`CanvasGradient::from_css`]); the canvas's state is kept around
932    /// it. The view draws no background of its own behind the drawing: it
933    /// shows where this fills, as with CSS's `clip-path` (an area under a
934    /// chart's line that fades out, in the app's `bg-linear-*` classes).
935    Background {
936        /// The box the background is positioned over.
937        area: Bounds<Points>,
938        /// Which parts of the path are inside.
939        rule: FillRule,
940    },
941}
942
943/// How a drawing in the coordinates of a view box fills its canvas, as
944/// SVG's `viewBox` and `preserveAspectRatio` fit an `<svg>` into its box
945/// ([`ViewPaint::Fit`]). The canvas lays out as an image does: at
946/// [`Self::size`] where its style sets no size, keeping that aspect ratio
947/// where it sets one side; the core maps the view box onto the box it gets
948/// and sends the drawing again when that box changes.
949#[derive(Debug, Clone, Copy, PartialEq)]
950pub struct ViewBoxFit {
951    /// The view box (`viewBox`), of a positive width and height.
952    pub view_box: Bounds<Points>,
953    /// Where the view box sits in the box along each axis, its aspect
954    /// ratio kept: 0 at the start, 0.5 in the middle, 1 at the end
955    /// (`xMidYMid` is 50% and 50%). `None` (`none`) stretches it to the
956    /// box.
957    pub align: Option<(Percentage, Percentage)>,
958    /// It covers the box (`slice`) rather than fits inside it (`meet`).
959    pub slice: bool,
960    /// The natural size: the `<svg>`'s `width` and `height`.
961    pub size: Size<Points>,
962}
963
964impl ViewBoxFit {
965    /// The matrix `[a, b, c, d, e, f]` (`transform`'s) mapping the view box
966    /// onto a box of `size` at the origin.
967    pub fn transform(&self, size: Size<Points>) -> [f32; 6] {
968        let Size { width, height } = self.view_box.size;
969        let (vw, vh) = (width.0, height.0);
970        let (w, h) = (size.width.0.max(0.0), size.height.0.max(0.0));
971        if !(vw > 0.0 && vh > 0.0) {
972            return [0.0; 6];
973        }
974        let (mut sx, mut sy) = (w / vw, h / vh);
975        let (ax, ay) = match self.align {
976            None => (0.0, 0.0),
977            Some((x, y)) => {
978                let s = if self.slice { sx.max(sy) } else { sx.min(sy) };
979                (sx, sy) = (s, s);
980                (x.0, y.0)
981            }
982        };
983        let origin = self.view_box.origin;
984        [
985            sx,
986            0.0,
987            0.0,
988            sy,
989            (w - vw * sx) * ax - origin.x.0 * sx,
990            (h - vh * sy) * ay - origin.y.0 * sy,
991        ]
992    }
993}
994
995/// A part of a canvas's drawing that assistive technologies and UI tests
996/// see as an element of its own: a cell of a grid, a bar of a chart. It
997/// is the canvas's child at `bounds` (points from the canvas's top left),
998/// with its own role, name and test id; a press on it is a press at its
999/// center, as a pointer there makes it, which goes to whatever view is
1000/// under that point and takes presses. The GPUI backend and the headless
1001/// driver show them; the other backends do not yet.
1002#[derive(Debug, Clone, PartialEq, Default)]
1003#[non_exhaustive]
1004pub struct CanvasNode {
1005    /// Where it is in the canvas.
1006    pub bounds: Bounds<Points>,
1007    /// What it is to assistive technologies.
1008    pub role: crate::AccessibilityRole,
1009    /// Its accessible name: the text it shows.
1010    pub label: Arc<str>,
1011    /// `testID`: an identifier for UI tests.
1012    pub test_id: Option<Arc<str>>,
1013    /// It is selected (a grid's selected cells).
1014    pub selected: bool,
1015}
1016
1017impl CanvasNode {
1018    /// A node at `bounds` with `role`, named `label`.
1019    pub fn new(
1020        bounds: Bounds<Points>,
1021        role: crate::AccessibilityRole,
1022        label: impl Into<Arc<str>>,
1023    ) -> Self {
1024        Self {
1025            bounds,
1026            role,
1027            label: label.into(),
1028            ..Self::default()
1029        }
1030    }
1031
1032    /// With the test id `id`.
1033    pub fn test_id(mut self, id: impl Into<Arc<str>>) -> Self {
1034        self.test_id = Some(id.into());
1035        self
1036    }
1037
1038    /// Selected, or not.
1039    pub fn selected(mut self, selected: bool) -> Self {
1040        self.selected = selected;
1041        self
1042    }
1043}
1044
1045impl Drawing {
1046    /// Whether it fills with its view's background
1047    /// ([`ViewPaint::Background`]), which the view then does not draw.
1048    pub fn paints_background(&self) -> bool {
1049        self.view_paints
1050            .iter()
1051            .any(|(_, v)| matches!(v, ViewPaint::Background { .. }))
1052    }
1053
1054    /// The view box it fits into its canvas ([`ViewPaint::Fit`]), if any.
1055    pub fn fit(&self) -> Option<ViewBoxFit> {
1056        self.view_paints.iter().find_map(|&(_, v)| match v {
1057            ViewPaint::Fit(fit) => Some(fit),
1058            _ => None,
1059        })
1060    }
1061
1062    /// The drawing as a platform replays it: its [`Drawing::view_paints`]
1063    /// given the paint properties `paint` of its view, whose text color is
1064    /// `current` (`currentColor`), its background, the color `background`
1065    /// under the gradients `images` (top layer first), and the size of its
1066    /// box, `size` (what a view box fits into). `none` paints nothing (a
1067    /// transparent paint). Its own `view_paints` are resolved, so it has
1068    /// none.
1069    pub fn painted(
1070        &self,
1071        paint: &crate::style::PaintStyle,
1072        current: Color,
1073        background: Color,
1074        images: &[crate::effects::Gradient],
1075        size: Size<Points>,
1076    ) -> Drawing {
1077        use crate::style::SvgPaint;
1078        let color = |p: SvgPaint| {
1079            Paint::Color(match p {
1080                SvgPaint::None => Color::TRANSPARENT,
1081                SvgPaint::CurrentColor => current,
1082                SvgPaint::Color(c) => c,
1083            })
1084        };
1085        let mut out = self.clone();
1086        for &(at, view) in &self.view_paints {
1087            let Some(op) = out.ops.get_mut(at as usize) else {
1088                continue;
1089            };
1090            *op = match view {
1091                ViewPaint::Fill(initial) => {
1092                    CanvasOp::FillStyle(color(paint.fill.unwrap_or(initial)))
1093                }
1094                ViewPaint::Stroke(initial) => {
1095                    CanvasOp::StrokeStyle(color(paint.stroke.unwrap_or(initial)))
1096                }
1097                ViewPaint::StrokeWidth => {
1098                    CanvasOp::LineWidth(Num::Const(paint.stroke_width.map_or(1.0, |w| w.0)))
1099                }
1100                ViewPaint::StrokeDasharray => CanvasOp::LineDash(
1101                    paint
1102                        .stroke_dasharray
1103                        .clone()
1104                        .unwrap_or_else(|| Arc::from([])),
1105                ),
1106                ViewPaint::FillCurrentColor => CanvasOp::FillStyle(Paint::Color(current)),
1107                ViewPaint::StrokeCurrentColor => CanvasOp::StrokeStyle(Paint::Color(current)),
1108                ViewPaint::Fit(fit) => CanvasOp::Transform(fit.transform(size).map(Num::Const)),
1109                // Expanded below: its place holds the fill it becomes.
1110                ViewPaint::Background { .. } => continue,
1111            };
1112        }
1113        out.view_paints = Vec::new();
1114        if !self.paints_background() {
1115            return out;
1116        }
1117        let ops = std::mem::take(&mut out.ops);
1118        let mut backgrounds = self.view_paints.iter().filter_map(|&(at, v)| match v {
1119            ViewPaint::Background { area, rule } => Some((at as usize, area, rule)),
1120            _ => None,
1121        });
1122        let mut next = backgrounds.next();
1123        for (i, op) in ops.into_iter().enumerate() {
1124            let Some((_, area, rule)) = next.filter(|&(at, ..)| at == i) else {
1125                out.ops.push(op);
1126                continue;
1127            };
1128            next = backgrounds.next();
1129            out.ops.push(CanvasOp::Save);
1130            if !background.is_transparent() {
1131                out.ops.push(CanvasOp::FillStyle(Paint::Color(background)));
1132                out.ops.push(CanvasOp::Fill(None, rule));
1133            }
1134            for image in images.iter().rev() {
1135                let Some(gradient) = CanvasGradient::from_css(image, area) else {
1136                    log::warn!("an elliptical `radial-gradient()` fills no canvas shape");
1137                    continue;
1138                };
1139                out.ops
1140                    .push(CanvasOp::FillStyle(Paint::Gradient(Arc::new(gradient))));
1141                out.ops.push(CanvasOp::Fill(None, rule));
1142            }
1143            out.ops.push(CanvasOp::Restore);
1144        }
1145        out
1146    }
1147
1148    /// The slot of animated value `node`, adding it if new.
1149    pub fn slot(&mut self, node: crate::animation::NodeId) -> u16 {
1150        match self.slots.iter().position(|&n| n == node) {
1151            Some(i) => i as u16,
1152            None => {
1153                self.slots.push(node);
1154                (self.slots.len() - 1) as u16
1155            }
1156        }
1157    }
1158
1159    /// The images it draws.
1160    pub fn images(&self) -> impl Iterator<Item = &CanvasImage> {
1161        self.ops.iter().filter_map(|op| match op {
1162            CanvasOp::DrawImage { image, .. } => Some(image),
1163            _ => None,
1164        })
1165    }
1166}
1167
1168/// A length: values of another type are zero (as `f32`'s).
1169impl<Cx> OpArg<Cx> for Points {
1170    fn read<L: HostList<Item: HostInput>>(
1171        r: &mut OpReader<'_, L>,
1172        cx: &mut Cx,
1173    ) -> Result<Option<Self>, OpsError> {
1174        Ok(<f32 as OpArg<Cx>>::read(r, cx)?.map(Points))
1175    }
1176
1177    fn ts(types: &mut TsTypes) -> String {
1178        <f32 as OpArg<Cx>>::ts(types)
1179    }
1180}
1181
1182/// A length, or nothing (`maxWidth`).
1183impl<Cx> OpArg<Cx> for Option<Points> {
1184    fn read<L: HostList<Item: HostInput>>(
1185        r: &mut OpReader<'_, L>,
1186        cx: &mut Cx,
1187    ) -> Result<Option<Self>, OpsError> {
1188        Ok(<Option<f32> as OpArg<Cx>>::read(r, cx)?.map(|v| v.map(Points)))
1189    }
1190
1191    fn ts(types: &mut TsTypes) -> String {
1192        <Option<f32> as OpArg<Cx>>::ts(types)
1193    }
1194}
1195
1196/// A point: two arguments, `x` then `y`.
1197impl<Cx> OpArg<Cx> for Point<Points> {
1198    const ARITY: usize = 2;
1199
1200    fn read<L: HostList<Item: HostInput>>(
1201        r: &mut OpReader<'_, L>,
1202        cx: &mut Cx,
1203    ) -> Result<Option<Self>, OpsError> {
1204        let x = <Points as OpArg<Cx>>::read(r, cx)?;
1205        let y = <Points as OpArg<Cx>>::read(r, cx)?;
1206        Ok(x.zip(y).map(|(x, y)| Point { x, y }))
1207    }
1208
1209    fn ts(types: &mut TsTypes) -> String {
1210        <Points as OpArg<Cx>>::ts(types)
1211    }
1212}
1213
1214/// The signed sweep of `arc` / `ellipse` from `start` to `end`, as the
1215/// Canvas spec defines it: a full turn when the angles are a turn or more
1216/// apart in the drawing direction, else the angle between them going that
1217/// way.
1218pub fn arc_sweep(start: Radians, end: Radians, ccw: bool) -> Radians {
1219    Radians(sweep(start.0, end.0, ccw))
1220}
1221
1222pub(crate) fn sweep(start: f32, end: f32, ccw: bool) -> f32 {
1223    use std::f32::consts::TAU;
1224    if !ccw {
1225        if end - start >= TAU {
1226            TAU
1227        } else {
1228            (end - start).rem_euclid(TAU)
1229        }
1230    } else if start - end >= TAU {
1231        -TAU
1232    } else {
1233        -(start - end).rem_euclid(TAU)
1234    }
1235}
1236
1237/// Corner radii of `roundRect` scaled down to fit a box of `size` (CSS
1238/// rule: all by the same factor when two on one side overlap); a negative
1239/// size is a box drawn the other way.
1240pub fn fit_radii(size: Size<Points>, radii: Corners<Points>) -> Corners<Points> {
1241    let [tl, tr, br, bl] = fit(
1242        size.width.0,
1243        size.height.0,
1244        [
1245            radii.top_left.0,
1246            radii.top_right.0,
1247            radii.bottom_right.0,
1248            radii.bottom_left.0,
1249        ],
1250    );
1251    Corners {
1252        top_left: Points(tl),
1253        top_right: Points(tr),
1254        bottom_right: Points(br),
1255        bottom_left: Points(bl),
1256    }
1257}
1258
1259/// [`fit_radii`] on bare numbers: top left, top right, bottom right,
1260/// bottom left.
1261pub(crate) fn fit(w: f32, h: f32, radii: [f32; 4]) -> [f32; 4] {
1262    let r = radii.map(|r| r.max(0.0));
1263    let (w, h) = (w.abs(), h.abs());
1264    let sides = [r[0] + r[1], r[2] + r[3], r[0] + r[3], r[1] + r[2]];
1265    let limits = [w, w, h, h];
1266    let scale = sides
1267        .iter()
1268        .zip(limits)
1269        .filter(|(s, _)| **s > 0.0)
1270        .map(|(s, l)| l / s)
1271        .fold(1.0f32, f32::min);
1272    r.map(|r| r * scale)
1273}
1274
1275// --- SVG path data (`new Path2D("M0 0 L10 10")`) ----------------------------
1276
1277/// SVG path data as a path to fill, stroke or clip (TS: `new
1278/// Path2D(d)`), parsed by [`parse_svg_path`].
1279pub fn svg_path(d: &str) -> Path {
1280    parse_svg_path(d).into()
1281}
1282
1283/// Parses SVG path data into path operations (absolute coordinates;
1284/// smooth curves made explicit, arcs as cubic Béziers). Parsing stops at
1285/// the first error, keeping what came before, as SVG renderers do.
1286pub fn parse_svg_path(d: &str) -> Vec<PathOp> {
1287    let mut out = Vec::new();
1288    let mut p = PathParser {
1289        s: d.as_bytes(),
1290        pos: 0,
1291    };
1292    let (mut x, mut y) = (0f32, 0f32);
1293    let (mut sx, mut sy) = (0f32, 0f32);
1294    // The last control point, for S / T.
1295    let mut last_cubic: Option<(f32, f32)> = None;
1296    let mut last_quad: Option<(f32, f32)> = None;
1297    let mut command = 0u8;
1298    let c = |v: f32| Num::Const(v);
1299    loop {
1300        p.skip_separators();
1301        if p.pos >= p.s.len() {
1302            break;
1303        }
1304        let b = p.s[p.pos];
1305        if b.is_ascii_alphabetic() {
1306            command = b;
1307            p.pos += 1;
1308        } else if command == 0 {
1309            break;
1310        } else if command == b'M' {
1311            // Coordinates after a moveto are linetos.
1312            command = b'L';
1313        } else if command == b'm' {
1314            command = b'l';
1315        }
1316        let rel = command.is_ascii_lowercase();
1317        let (ox, oy) = if rel { (x, y) } else { (0.0, 0.0) };
1318        let upper = command.to_ascii_uppercase();
1319        let ok = (|| -> Option<()> {
1320            match upper {
1321                b'M' => {
1322                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1323                    out.push(PathOp::MoveTo(c(nx), c(ny)));
1324                    (x, y, sx, sy) = (nx, ny, nx, ny);
1325                    last_cubic = None;
1326                    last_quad = None;
1327                }
1328                b'L' => {
1329                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1330                    out.push(PathOp::LineTo(c(nx), c(ny)));
1331                    (x, y) = (nx, ny);
1332                    last_cubic = None;
1333                    last_quad = None;
1334                }
1335                b'H' => {
1336                    x = p.number()? + ox;
1337                    out.push(PathOp::LineTo(c(x), c(y)));
1338                    last_cubic = None;
1339                    last_quad = None;
1340                }
1341                b'V' => {
1342                    y = p.number()? + oy;
1343                    out.push(PathOp::LineTo(c(x), c(y)));
1344                    last_cubic = None;
1345                    last_quad = None;
1346                }
1347                b'C' | b'S' => {
1348                    let (x1, y1) = if upper == b'C' {
1349                        (p.number()? + ox, p.number()? + oy)
1350                    } else {
1351                        // The reflection of the last control point.
1352                        last_cubic.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1353                    };
1354                    let (x2, y2) = (p.number()? + ox, p.number()? + oy);
1355                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1356                    out.push(PathOp::CubicTo([x1, y1, x2, y2, nx, ny].map(c)));
1357                    last_cubic = Some((x2, y2));
1358                    last_quad = None;
1359                    (x, y) = (nx, ny);
1360                }
1361                b'Q' | b'T' => {
1362                    let (x1, y1) = if upper == b'Q' {
1363                        (p.number()? + ox, p.number()? + oy)
1364                    } else {
1365                        last_quad.map_or((x, y), |(cx, cy)| (2.0 * x - cx, 2.0 * y - cy))
1366                    };
1367                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1368                    out.push(PathOp::QuadTo([x1, y1, nx, ny].map(c)));
1369                    last_quad = Some((x1, y1));
1370                    last_cubic = None;
1371                    (x, y) = (nx, ny);
1372                }
1373                b'A' => {
1374                    let rx = p.number()?.abs();
1375                    let ry = p.number()?.abs();
1376                    let rotation = p.number()?;
1377                    let large = p.flag()?;
1378                    let sweep = p.flag()?;
1379                    let (nx, ny) = (p.number()? + ox, p.number()? + oy);
1380                    arc_to_cubics(&mut out, (x, y), (rx, ry), rotation, large, sweep, (nx, ny));
1381                    (x, y) = (nx, ny);
1382                    last_cubic = None;
1383                    last_quad = None;
1384                }
1385                b'Z' => {
1386                    out.push(PathOp::Close);
1387                    (x, y) = (sx, sy);
1388                    last_cubic = None;
1389                    last_quad = None;
1390                    // Z takes no numbers: a number after it starts nothing.
1391                    command = 0;
1392                }
1393                _ => return None,
1394            }
1395            Some(())
1396        })();
1397        if ok.is_none() {
1398            break;
1399        }
1400    }
1401    out
1402}
1403
1404struct PathParser<'a> {
1405    s: &'a [u8],
1406    pos: usize,
1407}
1408
1409impl PathParser<'_> {
1410    fn skip_separators(&mut self) {
1411        while self.pos < self.s.len()
1412            && (self.s[self.pos].is_ascii_whitespace() || self.s[self.pos] == b',')
1413        {
1414            self.pos += 1;
1415        }
1416    }
1417
1418    fn number(&mut self) -> Option<f32> {
1419        self.skip_separators();
1420        let start = self.pos;
1421        let s = self.s;
1422        let mut i = self.pos;
1423        if i < s.len() && (s[i] == b'+' || s[i] == b'-') {
1424            i += 1;
1425        }
1426        let mut digits = false;
1427        while i < s.len() && s[i].is_ascii_digit() {
1428            i += 1;
1429            digits = true;
1430        }
1431        if i < s.len() && s[i] == b'.' {
1432            i += 1;
1433            while i < s.len() && s[i].is_ascii_digit() {
1434                i += 1;
1435                digits = true;
1436            }
1437        }
1438        if !digits {
1439            return None;
1440        }
1441        if i < s.len() && (s[i] == b'e' || s[i] == b'E') {
1442            let mut j = i + 1;
1443            if j < s.len() && (s[j] == b'+' || s[j] == b'-') {
1444                j += 1;
1445            }
1446            if j < s.len() && s[j].is_ascii_digit() {
1447                while j < s.len() && s[j].is_ascii_digit() {
1448                    j += 1;
1449                }
1450                i = j;
1451            }
1452        }
1453        self.pos = i;
1454        std::str::from_utf8(&s[start..i]).ok()?.parse().ok()
1455    }
1456
1457    /// Arc flags may be written without separators (`a1 1 0 0110 10`).
1458    fn flag(&mut self) -> Option<bool> {
1459        self.skip_separators();
1460        let b = *self.s.get(self.pos)?;
1461        self.pos += 1;
1462        match b {
1463            b'0' => Some(false),
1464            b'1' => Some(true),
1465            _ => None,
1466        }
1467    }
1468}
1469
1470/// An SVG elliptical arc as cubic Béziers (SVG implementation notes,
1471/// F.6.5 and F.6.6).
1472fn arc_to_cubics(
1473    out: &mut Vec<PathOp>,
1474    from: (f32, f32),
1475    radii: (f32, f32),
1476    rotation_deg: f32,
1477    large: bool,
1478    sweep: bool,
1479    to: (f32, f32),
1480) {
1481    let c = |v: f64| Num::Const(v as f32);
1482    let (x1, y1) = (from.0 as f64, from.1 as f64);
1483    let (x2, y2) = (to.0 as f64, to.1 as f64);
1484    let (mut rx, mut ry) = (radii.0 as f64, radii.1 as f64);
1485    if (x1 == x2 && y1 == y2) || rx == 0.0 || ry == 0.0 {
1486        if x1 != x2 || y1 != y2 {
1487            out.push(PathOp::LineTo(c(x2), c(y2)));
1488        }
1489        return;
1490    }
1491    let phi = (rotation_deg as f64).to_radians();
1492    let (sin, cos) = phi.sin_cos();
1493    let dx = (x1 - x2) / 2.0;
1494    let dy = (y1 - y2) / 2.0;
1495    let x1p = cos * dx + sin * dy;
1496    let y1p = -sin * dx + cos * dy;
1497    // Radii too small to reach: scale them up.
1498    let lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
1499    if lambda > 1.0 {
1500        let s = lambda.sqrt();
1501        rx *= s;
1502        ry *= s;
1503    }
1504    let num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
1505    let den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
1506    let mut coef = (num / den).max(0.0).sqrt();
1507    if large == sweep {
1508        coef = -coef;
1509    }
1510    let cxp = coef * rx * y1p / ry;
1511    let cyp = -coef * ry * x1p / rx;
1512    let cx = cos * cxp - sin * cyp + (x1 + x2) / 2.0;
1513    let cy = sin * cxp + cos * cyp + (y1 + y2) / 2.0;
1514    let angle = |ux: f64, uy: f64, vx: f64, vy: f64| (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
1515    let theta1 = angle(1.0, 0.0, (x1p - cxp) / rx, (y1p - cyp) / ry);
1516    let mut delta = angle(
1517        (x1p - cxp) / rx,
1518        (y1p - cyp) / ry,
1519        (-x1p - cxp) / rx,
1520        (-y1p - cyp) / ry,
1521    );
1522    if !sweep && delta > 0.0 {
1523        delta -= std::f64::consts::TAU;
1524    } else if sweep && delta < 0.0 {
1525        delta += std::f64::consts::TAU;
1526    }
1527    // At most a quarter turn per segment.
1528    let segments = (delta.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
1529    let step = delta / segments as f64;
1530    let k = 4.0 / 3.0 * (step / 4.0).tan();
1531    let point = |t: f64| {
1532        let (s, co) = t.sin_cos();
1533        (
1534            cx + rx * co * cos - ry * s * sin,
1535            cy + rx * co * sin + ry * s * cos,
1536        )
1537    };
1538    let derivative = |t: f64| {
1539        let (s, co) = t.sin_cos();
1540        (-rx * s * cos - ry * co * sin, -rx * s * sin + ry * co * cos)
1541    };
1542    let mut t = theta1;
1543    for i in 0..segments {
1544        let t2 = t + step;
1545        let (p1x, p1y) = point(t);
1546        let (d1x, d1y) = derivative(t);
1547        let (p2x, p2y) = if i + 1 == segments {
1548            (x2, y2)
1549        } else {
1550            point(t2)
1551        };
1552        let (d2x, d2y) = derivative(t2);
1553        out.push(PathOp::CubicTo([
1554            c(p1x + k * d1x),
1555            c(p1y + k * d1y),
1556            c(p2x - k * d2x),
1557            c(p2y - k * d2y),
1558            c(p2x),
1559            c(p2y),
1560        ]));
1561        t = t2;
1562    }
1563}
1564
1565#[cfg(test)]
1566mod tests {
1567    use super::*;
1568    use crate::text::{AttributedText, TextEngine, TextLayout};
1569
1570    #[test]
1571    fn an_image_density_is_its_file_name_s() {
1572        let density = |uri: &str| CanvasImage { uri: uri.into() }.density();
1573        assert_eq!(density("asset:/logo@3x.png"), 3.0);
1574        assert_eq!(density("https://example.com/a/b@2x.jpg"), 2.0);
1575        assert_eq!(density("asset:/logo.png"), 1.0);
1576    }
1577
1578    /// A CSS gradient as the background of a box: the line through the
1579    /// box's center at the gradient's angle, as long as CSS makes it, and
1580    /// its stops; a repeating one's stops repeated over the whole line, the
1581    /// ends cut at the colors there; an elliptical radial one not drawn.
1582    #[test]
1583    fn css_gradients_become_canvas_gradients_over_a_box() {
1584        use crate::geometry::{bounds, point, size};
1585        let area = bounds(point(px(10.0), px(20.0)), size(px(100.0), px(50.0)));
1586        let one = |css: &str| crate::css::gradients(css).unwrap().remove(0);
1587        let gradient = |css: &str| CanvasGradient::from_css(&one(css), area);
1588        let down = gradient("linear-gradient(to bottom, #ff0000, #0000ff)").unwrap();
1589        assert_eq!(
1590            down.shape,
1591            GradientShape::Linear {
1592                start: point(px(60.0), px(20.0)),
1593                end: point(px(60.0), px(70.0)),
1594            }
1595        );
1596        assert_eq!(down.stops[0], (Percentage(0.0), Color(0xff00_00ff)));
1597        assert_eq!(
1598            down.stops[down.stops.len() - 1],
1599            (Percentage(1.0), Color(0x0000_ffff))
1600        );
1601        let right = gradient("linear-gradient(90deg, #ff0000, #0000ff)").unwrap();
1602        let GradientShape::Linear { start, end } = right.shape else {
1603            panic!("{right:?}")
1604        };
1605        assert!((start.x.0 - 10.0).abs() < 1e-3 && (start.y.0 - 45.0).abs() < 1e-3);
1606        assert!((end.x.0 - 110.0).abs() < 1e-3 && (end.y.0 - 45.0).abs() < 1e-3);
1607        // Repeating every quarter: the stops again at each quarter, all
1608        // within the line.
1609        let stripes =
1610            gradient("repeating-linear-gradient(to bottom, #ff0000 0%, #0000ff 25%)").unwrap();
1611        let at = |o: f32| {
1612            stripes
1613                .stops
1614                .iter()
1615                .filter(|(p, _)| (p.0 - o).abs() < 1e-4)
1616                .count()
1617        };
1618        assert!(
1619            at(0.25) >= 2 && at(0.5) >= 2 && at(0.75) >= 2,
1620            "{stripes:?}"
1621        );
1622        assert!(
1623            stripes
1624                .stops
1625                .iter()
1626                .all(|(p, _)| (0.0..=1.0).contains(&p.0))
1627        );
1628        // Stops past the end: cut there, at the color between.
1629        let cut = gradient("linear-gradient(to bottom, #000000 0%, #ffffff 200%)").unwrap();
1630        assert_eq!(
1631            cut.stops[cut.stops.len() - 1],
1632            (Percentage(1.0), Color(0x8080_80ff))
1633        );
1634        assert!(gradient("radial-gradient(#ff0000, #0000ff)").is_none());
1635        let circle = gradient("radial-gradient(circle, #ff0000, #0000ff)").unwrap();
1636        assert!(matches!(circle.shape, GradientShape::Radial { .. }));
1637    }
1638
1639    /// A drawing filling with its view's background: the color, then each
1640    /// gradient from the bottom layer up, filling the path, the canvas's
1641    /// state kept around them.
1642    #[test]
1643    fn a_drawing_fills_with_its_views_background() {
1644        use crate::geometry::{bounds, point, size};
1645        let area = bounds(point(px(0.0), px(0.0)), size(px(10.0), px(10.0)));
1646        let drawing = crate::element::Painter::new()
1647            .begin_path()
1648            .fill_background_from_view(area)
1649            .finish();
1650        assert!(drawing.paints_background());
1651        let images = crate::css::gradients("linear-gradient(#ff0000, #0000ff)").unwrap();
1652        let none = crate::style::PaintStyle::default();
1653        let painted = drawing.painted(
1654            &none,
1655            Color::TRANSPARENT,
1656            Color(0x00ff_00ff),
1657            &images,
1658            Size::default(),
1659        );
1660        assert!(painted.view_paints.is_empty());
1661        let ops = &painted.ops[1..];
1662        assert_eq!(ops[0], CanvasOp::Save);
1663        assert_eq!(
1664            ops[1],
1665            CanvasOp::FillStyle(Paint::Color(Color(0x00ff_00ff)))
1666        );
1667        assert_eq!(ops[2], CanvasOp::Fill(None, FillRule::NonZero));
1668        assert!(matches!(ops[3], CanvasOp::FillStyle(Paint::Gradient(_))));
1669        assert_eq!(ops[4], CanvasOp::Fill(None, FillRule::NonZero));
1670        assert_eq!(ops[5], CanvasOp::Restore);
1671        // No background: nothing fills.
1672        let bare = drawing.painted(
1673            &none,
1674            Color::TRANSPARENT,
1675            Color::TRANSPARENT,
1676            &[],
1677            Size::default(),
1678        );
1679        assert_eq!(&bare.ops[1..], [CanvasOp::Save, CanvasOp::Restore]);
1680    }
1681
1682    /// Lays a line out as text engines do: 10 points a character, without
1683    /// the white space at its end.
1684    struct Hanging;
1685
1686    impl TextEngine for Hanging {
1687        type Prepared = String;
1688
1689        fn prepare(&self, text: &AttributedText) -> String {
1690            text.text.to_string()
1691        }
1692
1693        fn prepare_aligned(
1694            &self,
1695            text: &AttributedText,
1696            _: &crate::text::AttachmentAlignments,
1697        ) -> String {
1698            self.prepare(text)
1699        }
1700
1701        fn measure(&self, text: &String, _: Option<Points>) -> Size<Points> {
1702            let shown = text.trim_end_matches(|c: char| c.is_whitespace());
1703            Size::new(Points(10.0 * shown.chars().count() as f32), Points(12.0))
1704        }
1705
1706        fn layout(&self, _: &String, _: Size<Points>) -> TextLayout {
1707            TextLayout(std::sync::Arc::new(()))
1708        }
1709    }
1710
1711    #[test]
1712    fn trailing_white_space_advances_as_canvas_measures_it() {
1713        let font = CanvasFont::default();
1714        for (text, width) in [
1715            ("", 0.0),
1716            ("ab", 20.0),
1717            (" ", 10.0),
1718            ("   ", 30.0),
1719            ("  items: ", 90.0),
1720            ("a\t", 20.0),
1721            // Chinese and its ideographic space, a character each.
1722            ("名字\u{3000}", 30.0),
1723            ("你好 ", 30.0),
1724            // A line break ends the line.
1725            ("ab\n", 20.0),
1726        ] {
1727            assert_eq!(
1728                measure_line(&Hanging, &font, text),
1729                Points(width),
1730                "{text:?}"
1731            );
1732            assert_eq!(
1733                line_metrics(&Hanging, &font, text).width,
1734                Points(width),
1735                "{text:?}"
1736            );
1737        }
1738    }
1739
1740    fn consts(op: &PathOp) -> Vec<f32> {
1741        let v = |n: &Num| match n {
1742            Num::Const(v) => *v,
1743            Num::Slot(_) => f32::NAN,
1744        };
1745        match op {
1746            PathOp::MoveTo(a, b) | PathOp::LineTo(a, b) => vec![v(a), v(b)],
1747            PathOp::QuadTo(n) => n.iter().map(v).collect(),
1748            PathOp::CubicTo(n) => n.iter().map(v).collect(),
1749            _ => vec![],
1750        }
1751    }
1752
1753    #[test]
1754    fn svg_paths_parse_to_absolute_ops() {
1755        let ops = parse_svg_path("M10 20 l5-5 H30 v10 z m1 1 2 2");
1756        assert_eq!(ops.len(), 7);
1757        assert_eq!(consts(&ops[1]), vec![15.0, 15.0]);
1758        assert_eq!(consts(&ops[2]), vec![30.0, 15.0]);
1759        assert_eq!(consts(&ops[3]), vec![30.0, 25.0]);
1760        assert_eq!(ops[4], PathOp::Close);
1761        // After Z the current point is the subpath's start.
1762        assert_eq!(consts(&ops[5]), vec![11.0, 21.0]);
1763        // Implicit lineto after a moveto.
1764        assert_eq!(consts(&ops[6]), vec![13.0, 23.0]);
1765        // Compact numbers: `.5.5` is two numbers, `1e2` an exponent.
1766        let ops = parse_svg_path("M.5.5L1e1-2");
1767        assert_eq!(consts(&ops[0]), vec![0.5, 0.5]);
1768        assert_eq!(consts(&ops[1]), vec![10.0, -2.0]);
1769    }
1770
1771    #[test]
1772    fn smooth_curves_reflect_control_points() {
1773        let ops = parse_svg_path("M0 0 C0 10 10 10 10 0 S20 -10 20 0");
1774        assert_eq!(consts(&ops[2]), vec![10.0, -10.0, 20.0, -10.0, 20.0, 0.0]);
1775    }
1776
1777    #[test]
1778    fn arcs_become_cubics_ending_on_the_point() {
1779        // A half circle of radius 10, flags without separators.
1780        let ops = parse_svg_path("M0 0 A10 10 0 0120 0");
1781        assert_eq!(ops.len(), 3);
1782        let last = consts(&ops[2]);
1783        assert!((last[4] - 20.0).abs() < 1e-4 && last[5].abs() < 1e-4);
1784        // Its top: the end of the first quarter, 10 above the center.
1785        let mid = consts(&ops[1]);
1786        assert!((mid[4] - 10.0).abs() < 1e-3 && (mid[5] + 10.0).abs() < 1e-3);
1787    }
1788
1789    #[test]
1790    fn bad_path_data_keeps_what_parsed() {
1791        let ops = parse_svg_path("M0 0 L10 10 L oops");
1792        assert_eq!(ops.len(), 2);
1793    }
1794
1795    #[test]
1796    fn arc_sweeps_follow_the_canvas_spec() {
1797        use std::f32::consts::{PI, TAU};
1798
1799        use crate::geometry::{radians, size};
1800        let sweep = |a, b, ccw| arc_sweep(radians(a), radians(b), ccw).0;
1801        assert_eq!(sweep(0.0, PI, false), PI);
1802        // Backwards clockwise: the long way round.
1803        assert!((sweep(PI, 0.0, false) - PI).abs() < 1e-6);
1804        assert!((sweep(0.0, -PI / 2.0, false) - 1.5 * PI).abs() < 1e-5);
1805        assert_eq!(sweep(0.0, 3.0 * TAU, false), TAU);
1806        assert!((sweep(0.0, PI / 2.0, true) + 1.5 * PI).abs() < 1e-5);
1807        assert_eq!(sweep(TAU, 0.0, true), -TAU);
1808        let corners = |[top_left, top_right, bottom_right, bottom_left]: [f32; 4]| Corners {
1809            top_left: px(top_left),
1810            top_right: px(top_right),
1811            bottom_right: px(bottom_right),
1812            bottom_left: px(bottom_left),
1813        };
1814        assert_eq!(
1815            fit_radii(size(px(10.0), px(100.0)), corners([8.0, 8.0, 0.0, 0.0])),
1816            corners([5.0, 5.0, 0.0, 0.0])
1817        );
1818    }
1819
1820    #[test]
1821    fn fonts_parse_the_css_shorthand() {
1822        let f = CanvasFont::parse("italic bold 14px \"Inter\", sans-serif").unwrap();
1823        assert_eq!((f.size, f.weight, f.italic), (px(14.0), 700, true));
1824        assert_eq!(f.family.as_deref(), Some("\"Inter\", sans-serif"));
1825        assert_eq!(
1826            crate::style::font_families(f.family.as_deref().unwrap()).collect::<Vec<_>>(),
1827            vec![
1828                crate::style::FamilyName::Named("Inter"),
1829                crate::style::FamilyName::System,
1830            ]
1831        );
1832        let single = CanvasFont::parse("14px \"Inter\"").unwrap();
1833        assert_eq!(single.family.as_deref(), Some("Inter"));
1834        let quoted_generic = CanvasFont::parse("14px \"serif\"").unwrap();
1835        assert_eq!(
1836            crate::style::font_families(quoted_generic.family.as_deref().unwrap())
1837                .collect::<Vec<_>>(),
1838            vec![crate::style::FamilyName::Named("serif")]
1839        );
1840        let f = CanvasFont::parse("600 12px/1.5 system-ui").unwrap();
1841        assert_eq!((f.size, f.weight, f.family), (px(12.0), 600, None));
1842        let f = CanvasFont::parse("small-caps tabular-nums 13px system-ui").unwrap();
1843        assert_eq!(
1844            f.variant.0,
1845            FontVariant::SMALL_CAPS | FontVariant::TABULAR_NUMS
1846        );
1847        let numeric = f.with_numeric(FontVariant(FontVariant::OLDSTYLE_NUMS));
1848        assert_eq!(
1849            numeric.variant.0,
1850            FontVariant::SMALL_CAPS | FontVariant::OLDSTYLE_NUMS
1851        );
1852        assert_eq!(f.with_numeric(FontVariant::default()), f);
1853        assert!(CanvasFont::parse("wide 13px system-ui").is_none());
1854        assert!(CanvasFont::parse("bold").is_none());
1855        assert!(CanvasFont::parse("14px").is_none());
1856        assert!(CanvasFont::parse("14px , ").is_none());
1857    }
1858}