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