Skip to main content

servo_canvas_traits/
canvas.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::default::Default;
6use std::f64::consts::{FRAC_PI_2, PI};
7use std::str::FromStr;
8
9use euclid::Angle;
10use euclid::approxeq::ApproxEq;
11use euclid::default::{Point2D, Rect, Size2D, Transform2D};
12use fonts_traits::{FontDataAndIndex, FontIdentifier};
13use kurbo::{BezPath, ParamCurveNearest as _, PathEl, Point, Shape, Triangle};
14use malloc_size_of::MallocSizeOf;
15use malloc_size_of_derive::MallocSizeOf;
16use pixels::SharedSnapshot;
17use serde::{Deserialize, Serialize};
18use servo_base::Epoch;
19use servo_base::generic_channel::GenericSender;
20use strum::{Display, EnumString};
21use style::color::AbsoluteColor;
22use webrender_api::ImageKey;
23
24#[derive(Clone, Debug, Default, Deserialize, Serialize)]
25pub struct Path(pub BezPath);
26
27impl MallocSizeOf for Path {
28    fn size_of(&self, _ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
29        std::mem::size_of_val(self.0.elements())
30    }
31}
32
33pub struct IndexSizeError;
34
35#[derive(Clone, Copy, Debug)]
36pub struct RoundRectRadius {
37    pub x: f64,
38    pub y: f64,
39}
40
41pub enum RangeError {
42    /// `radii` was not a list of size one, two, three, or four.
43    InvalidSize,
44    /// A radius was negative.
45    NegativeRadius,
46}
47
48impl Path {
49    pub fn new() -> Self {
50        Self(BezPath::new())
51    }
52
53    pub fn from_svg(s: &str) -> Self {
54        Self(BezPath::from_svg(s).unwrap_or_default())
55    }
56
57    pub fn transform(&mut self, transform: Transform2D<f64>) {
58        self.0.apply_affine(transform.into());
59    }
60
61    /// <https://html.spec.whatwg.org/multipage/#ensure-there-is-a-subpath>
62    pub fn ensure_there_is_a_subpath(&mut self, x: f64, y: f64) {
63        // The user agent must check to see if the path has its need new subpath flag set.
64        if self.0.elements().is_empty() {
65            // If it does, then the user agent must create a new subpath with the point (x, y)
66            // as its first (and only) point,
67            // as if the moveTo() method had been called,
68            // and must then unset the path's need new subpath flag.
69            self.0.move_to((x, y));
70        }
71    }
72
73    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-closepath>
74    pub fn close_path(&mut self) {
75        // must do nothing if the object's path has no subpaths
76        if matches!(self.0.elements().last(), None | Some(PathEl::ClosePath)) {
77            return;
78        }
79        // Otherwise, it must mark the last subpath as closed,
80        // create a new subpath whose first point is the same as the previous subpath's first point,
81        // and finally add this new subpath to the path.
82        self.0.close_path();
83    }
84
85    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto>
86    pub fn move_to(&mut self, x: f64, y: f64) {
87        // Step 1. If either of the arguments are infinite or NaN, then return.
88        if !(x.is_finite() && y.is_finite()) {
89            return;
90        }
91
92        // Step 2. Create a new subpath with the specified point as its first (and only) point.
93        self.0.move_to((x, y));
94    }
95
96    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-lineto>
97    pub fn line_to(&mut self, x: f64, y: f64) {
98        // Step 1. If either of the arguments are infinite or NaN, then return.
99        if !(x.is_finite() && y.is_finite()) {
100            return;
101        }
102
103        // Step 2. If the object's path has no subpaths, then ensure there is a subpath for (x, y).
104        self.ensure_there_is_a_subpath(x, y);
105
106        // Step 3. Otherwise, connect the last point in the subpath to the given point (x, y) using a straight line,
107        // and then add the given point (x, y) to the subpath.
108        self.0.line_to((x, y));
109    }
110
111    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-quadraticcurveto>
112    pub fn quadratic_curve_to(&mut self, cpx: f64, cpy: f64, x: f64, y: f64) {
113        // Step 1. If any of the arguments are infinite or NaN, then return.
114        if !(cpx.is_finite() && cpy.is_finite() && x.is_finite() && y.is_finite()) {
115            return;
116        }
117
118        // Step 2. Ensure there is a subpath for (cpx, cpy).
119        self.ensure_there_is_a_subpath(cpx, cpy);
120
121        // 3. Connect the last point in the subpath to the given point (x, y)
122        // using a quadratic Bézier curve with control point (cpx, cpy). [BEZIER]
123        // 4. Add the given point (x, y) to the subpath.
124        self.0.quad_to((cpx, cpy), (x, y));
125    }
126
127    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-beziercurveto>
128    pub fn bezier_curve_to(&mut self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) {
129        // Step 1. If any of the arguments are infinite or NaN, then return.
130        if !(cp1x.is_finite() &&
131            cp1y.is_finite() &&
132            cp2x.is_finite() &&
133            cp2y.is_finite() &&
134            x.is_finite() &&
135            y.is_finite())
136        {
137            return;
138        }
139
140        // Step 2. Ensure there is a subpath for (cp1x, cp1y).
141        self.ensure_there_is_a_subpath(cp1x, cp1y);
142
143        // Step 3. Connect the last point in the subpath to the given point (x, y)
144        // using a cubic Bézier curve with control points (cp1x, cp1y) and (cp2x, cp2y). [BEZIER]
145        // Step 4. Add the point (x, y) to the subpath.
146        self.0.curve_to((cp1x, cp1y), (cp2x, cp2y), (x, y));
147    }
148
149    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-arcto>
150    pub fn arc_to(
151        &mut self,
152        x1: f64,
153        y1: f64,
154        x2: f64,
155        y2: f64,
156        radius: f64,
157    ) -> Result<(), IndexSizeError> {
158        // Step 1. If any of the arguments are infinite or NaN, then return.
159        if !(x1.is_finite() &&
160            y1.is_finite() &&
161            x2.is_finite() &&
162            y2.is_finite() &&
163            radius.is_finite())
164        {
165            return Ok(());
166        }
167
168        // Step 2. Ensure there is a subpath for (x1, y1).
169        self.ensure_there_is_a_subpath(x1, y1);
170
171        // Step 3. If either radius is negative, then throw an "IndexSizeError" DOMException.
172        if radius < 0.0 {
173            return Err(IndexSizeError);
174        }
175
176        // Step 4. Let the point (x0, y0) be the last point in the subpath.
177        let Point { x: x0, y: y0 } = self.last_point().unwrap();
178
179        // Step 5. If the point (x0, y0) is equal to the point (x1, y1),
180        // or if the point (x1, y1) is equal to the point (x2, y2),
181        // or if radius is zero, then add the point (x1, y1) to the subpath,
182        // and connect that point to the previous point (x0, y0) by a straight line.
183        if ((x0, y0) == (x1, y1)) || ((x1, y1) == (x2, y2)) || radius.approx_eq(&0.0) {
184            self.0.line_to((x1, y1));
185            return Ok(());
186        }
187
188        // Step 6. Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2)
189        // all lie on a single straight line, then add the point (x1, y1) to the subpath,
190        // and connect that point to the previous point (x0, y0) by a straight line.
191        let direction = Triangle::from_coords((x0, y0), (x1, y1), (x2, y2)).area();
192        if direction.approx_eq(&0.0) {
193            self.0.line_to((x1, y1));
194            return Ok(());
195        }
196
197        // Step 7. Otherwise, let The Arc be the shortest arc given by circumference of the circle
198        // that has radius radius, and that has one point tangent to the half-infinite line
199        // that crosses the point (x0, y0) and ends at the point (x1, y1),
200        // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1)
201        // and crosses the point (x2, y2).
202        // The points at which this circle touches these two lines are called the start
203        // and end tangent points respectively.
204        // Connect the point (x0, y0) to the start tangent point by a straight line,
205        // adding the start tangent point to the subpath,
206        // and then connect the start tangent point to the end tangent point by The Arc,
207        // adding the end tangent point to the subpath.
208
209        let a2 = (x0 - x1).powi(2) + (y0 - y1).powi(2);
210        let b2 = (x1 - x2).powi(2) + (y1 - y2).powi(2);
211        let d = {
212            let c2 = (x0 - x2).powi(2) + (y0 - y2).powi(2);
213            let cosx = (a2 + b2 - c2) / (2.0 * (a2 * b2).sqrt());
214            let sinx = (1.0 - cosx.powi(2)).sqrt();
215            radius / ((1.0 - cosx) / sinx)
216        };
217
218        // first tangent point
219        let anx = (x1 - x0) / a2.sqrt();
220        let any = (y1 - y0) / a2.sqrt();
221        let tp1 = Point2D::new(x1 - anx * d, y1 - any * d);
222
223        // second tangent point
224        let bnx = (x1 - x2) / b2.sqrt();
225        let bny = (y1 - y2) / b2.sqrt();
226        let tp2 = Point2D::new(x1 - bnx * d, y1 - bny * d);
227
228        // arc center and angles
229        let anticlockwise = direction < 0.0;
230        let cx = tp1.x + any * radius * if anticlockwise { 1.0 } else { -1.0 };
231        let cy = tp1.y - anx * radius * if anticlockwise { 1.0 } else { -1.0 };
232        let angle_start = (tp1.y - cy).atan2(tp1.x - cx);
233        let angle_end = (tp2.y - cy).atan2(tp2.x - cx);
234
235        self.0.line_to((tp1.x, tp1.y));
236
237        self.arc(cx, cy, radius, angle_start, angle_end, anticlockwise)
238    }
239
240    pub fn last_point(&mut self) -> Option<Point> {
241        self.0.current_position()
242    }
243
244    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-arc>
245    pub fn arc(
246        &mut self,
247        x: f64,
248        y: f64,
249        radius: f64,
250        start_angle: f64,
251        end_angle: f64,
252        counterclockwise: bool,
253    ) -> Result<(), IndexSizeError> {
254        // ellipse() with both radii are equal and rotation is 0.
255        self.ellipse(
256            x,
257            y,
258            radius,
259            radius,
260            0.,
261            start_angle,
262            end_angle,
263            counterclockwise,
264        )
265    }
266
267    #[expect(clippy::too_many_arguments)]
268    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse>
269    pub fn ellipse(
270        &mut self,
271        x: f64,
272        y: f64,
273        radius_x: f64,
274        radius_y: f64,
275        rotation_angle: f64,
276        start_angle: f64,
277        end_angle: f64,
278        counterclockwise: bool,
279    ) -> Result<(), IndexSizeError> {
280        // Step 1. If any of the arguments are infinite or NaN, then return.
281        if !(x.is_finite() &&
282            y.is_finite() &&
283            radius_x.is_finite() &&
284            radius_y.is_finite() &&
285            rotation_angle.is_finite() &&
286            start_angle.is_finite() &&
287            end_angle.is_finite())
288        {
289            return Ok(());
290        }
291
292        // Step 2. If either radiusX or radiusY are negative, then throw an "IndexSizeError" DOMException.
293        if radius_x < 0.0 || radius_y < 0.0 {
294            return Err(IndexSizeError);
295        }
296
297        let start = Angle::radians(start_angle);
298        let end = Angle::radians(end_angle);
299
300        // The total sweep angle, positive in the given direction
301        let dir_sweep = if counterclockwise {
302            start - end
303        } else {
304            end - start
305        };
306
307        // Find the positive sweep angle in the given direction, in range [0, 2*PI].
308        let wrapped_sweep = if dir_sweep >= Angle::two_pi() {
309            Angle::two_pi()
310        } else if dir_sweep >= Angle::zero() {
311            dir_sweep
312        } else if dir_sweep.positive() != Angle::zero() {
313            // Wrap negative values that aren't exact multiples of -2*PI.
314            dir_sweep.positive()
315        } else {
316            Angle::two_pi()
317        };
318
319        // Wrap `start` and convert `wrapped_sweep` to clockwise-positive.
320        let start = start.positive();
321        let sweep = if counterclockwise {
322            -wrapped_sweep
323        } else {
324            wrapped_sweep
325        };
326
327        self.append_ellipse_arc(
328            (x, y),
329            (radius_x, radius_y),
330            start.radians,
331            sweep.radians,
332            rotation_angle,
333        );
334
335        Ok(())
336    }
337
338    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-rect>
339    pub fn rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
340        // Step 1. If any of the arguments are infinite or NaN, then return.
341        if !(x.is_finite() && y.is_finite() && w.is_finite() && h.is_finite()) {
342            return;
343        }
344
345        // Step 2. Create a new subpath containing just the four points
346        // (x, y), (x+w, y), (x+w, y+h), (x, y+h), in that order,
347        // with those four points connected by straight lines.
348        self.0.move_to((x, y));
349        self.0.line_to((x + w, y));
350        self.0.line_to((x + w, y + h));
351        self.0.line_to((x, y + h));
352
353        // Step 3. Mark the subpath as closed.
354        self.0.close_path();
355
356        // Step 4. Create a new subpath with the point (x, y) as the only point in the subpath.
357        self.0.move_to((x, y));
358    }
359
360    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-roundrect>
361    pub fn round_rect(
362        &mut self,
363        mut x: f64,
364        mut y: f64,
365        mut w: f64,
366        mut h: f64,
367        radii: &[RoundRectRadius],
368    ) -> Result<(), RangeError> {
369        // Step 1. If any of x, y, w, or h are infinite or NaN, then return.
370        if !(x.is_finite() && y.is_finite() && w.is_finite() && h.is_finite()) {
371            return Ok(());
372        }
373
374        // Step 3. If radii is not a list of size one, two, three, or four, then throw a
375        // RangeError.
376        if radii.is_empty() || radii.len() > 4 {
377            return Err(RangeError::InvalidSize);
378        }
379
380        // Steps 4 - 5. If any radius is infinite or NaN, then return; if any radius is negative,
381        // then throw a RangeError.
382        for radius in radii {
383            if !(radius.x.is_finite() && radius.y.is_finite()) {
384                return Ok(());
385            }
386            if radius.x < 0.0 || radius.y < 0.0 {
387                return Err(RangeError::NegativeRadius);
388            }
389        }
390        // From now on, radii is called normalizedRadii in spec.
391        let normalized_radii = radii;
392        // Steps 6 - 10. Assign upperLeft, upperRight, lowerRight and lowerLeft.
393        let (mut upper_left, mut upper_right, mut lower_right, mut lower_left) =
394            match normalized_radii {
395                // If normalizedRadii's size is 1, then set upperLeft, upperRight, lowerRight,
396                // and lowerLeft to normalizedRadii[0].
397                [a] => (*a, *a, *a, *a),
398                // If normalizedRadii's size is 2, then set upperLeft and lowerRight to
399                // normalizedRadii[0] and set upperRight and lowerLeft to normalizedRadii[1].
400                [a, b] => (*a, *b, *a, *b),
401                // If normalizedRadii's size is 3, then set upperLeft to normalizedRadii[0],
402                // set upperRight and lowerLeft to normalizedRadii[1],
403                // and set lowerRight to normalizedRadii[2].
404                [a, b, c] => (*a, *b, *c, *b),
405                // If normalizedRadii's size is 4, then set upperLeft to normalizedRadii[0],
406                // set upperRight to normalizedRadii[1], set lowerRight to normalizedRadii[2],
407                // and set lowerLeft to normalizedRadii[3].
408                [a, b, c, d] => (*a, *b, *c, *d),
409                _ => unreachable!(),
410            };
411
412        // Not explicitly stated in steps. See non-normative part of `roundRect` in
413        // <https://html.spec.whatwg.org/multipage/#building-paths>
414        // When w is negative, the rounded rectangle is flipped horizontally, which means that
415        // the radius values that normally apply to the left corners are used on the right and
416        // vice versa. Similarly, when h is negative, the rounded rect is flipped vertically.
417        let (orig_x, orig_y) = (x, y);
418        let counterclockwise = (w < 0.0) != (h < 0.0);
419        use std::mem::swap;
420        if w < 0.0 {
421            swap(&mut upper_left, &mut upper_right);
422            swap(&mut lower_left, &mut lower_right);
423            x += w;
424            w = -w;
425        }
426        if h < 0.0 {
427            swap(&mut upper_left, &mut lower_left);
428            swap(&mut upper_right, &mut lower_right);
429            y += h;
430            h = -h;
431        }
432
433        // Step 11. Corner curves must not overlap. Scale all radii to prevent this.
434        let top = upper_left.x + upper_right.x;
435        let right = upper_right.y + lower_right.y;
436        let bottom = lower_right.x + lower_left.x;
437        let left = upper_left.y + lower_left.y;
438        let scale = (w / top).min(h / right).min(w / bottom).min(h / left);
439        if scale < 1.0 {
440            upper_left.x *= scale;
441            upper_left.y *= scale;
442            upper_right.x *= scale;
443            upper_right.y *= scale;
444            lower_right.x *= scale;
445            lower_right.y *= scale;
446            lower_left.x *= scale;
447            lower_left.y *= scale;
448        }
449
450        // Step 12. Create a new subpath.
451        let mut subpath = Path::new();
452        // Step 12.1. Move to the point (x + upperLeft["x"], y).
453        subpath.0.move_to((x + upper_left.x, y));
454        // Step 12.2. Draw a straight line to the point (x + w − upperRight["x"], y).
455        subpath.0.line_to((x + w - upper_right.x, y));
456        // Step 12.3. Draw an arc to the point (x + w, y + upperRight["y"]).
457        subpath.round_rect_arc(
458            x + w - upper_right.x,
459            y + upper_right.y,
460            upper_right.x,
461            upper_right.y,
462            -FRAC_PI_2,
463        );
464        // Step 12.4. Draw a straight line to the point (x + w, y + h − lowerRight["y"]).
465        subpath.0.line_to((x + w, y + h - lower_right.y));
466        // Step 12.5. Draw an arc to the point (x + w − lowerRight["x"], y + h).
467        subpath.round_rect_arc(
468            x + w - lower_right.x,
469            y + h - lower_right.y,
470            lower_right.x,
471            lower_right.y,
472            0.0,
473        );
474        // Step 12.6. Draw a straight line to the point (x + lowerLeft["x"], y + h).
475        subpath.0.line_to((x + lower_left.x, y + h));
476        // Step 12.7. Draw an arc to the point (x, y + h − lowerLeft["y"]).
477        subpath.round_rect_arc(
478            x + lower_left.x,
479            y + h - lower_left.y,
480            lower_left.x,
481            lower_left.y,
482            FRAC_PI_2,
483        );
484        // Step 12.8. Draw a straight line to the point (x, y + upperLeft["y"]).
485        subpath.0.line_to((x, y + upper_left.y));
486        // Step 12.9. Draw an arc to the point (x + upperLeft["x"], y).
487        subpath.round_rect_arc(
488            x + upper_left.x,
489            y + upper_left.y,
490            upper_left.x,
491            upper_left.y,
492            PI,
493        );
494
495        // Step 13. Mark the subpath as closed.
496        subpath.0.close_path();
497
498        if counterclockwise {
499            subpath.0 = subpath.0.reverse_subpaths();
500        }
501        self.0.extend(subpath.0.elements().iter().cloned());
502
503        // Step 14. Create a new subpath with the original point (x, y) as the only point in the
504        // subpath.
505        self.0.move_to((orig_x, orig_y));
506
507        Ok(())
508    }
509
510    fn append_ellipse_arc(
511        &mut self,
512        center: (f64, f64),
513        radii: (f64, f64),
514        start_angle: f64,
515        sweep: f64,
516        rotation: f64,
517    ) {
518        let arc = kurbo::Arc::new(center, radii, start_angle, sweep, rotation);
519        let mut iter = arc.path_elements(0.01);
520
521        let Some(PathEl::MoveTo(start_point)) = iter.next() else {
522            unreachable!()
523        };
524        self.line_to(start_point.x, start_point.y);
525        if sweep.abs() > 1e-3 {
526            self.0.extend(iter);
527        }
528    }
529
530    /// Appends a quarter arc, sweeping clockwise by [`FRAC_PI_2`], for a `roundRect` corner.
531    #[inline]
532    fn round_rect_arc(&mut self, cx: f64, cy: f64, rx: f64, ry: f64, start_angle: f64) {
533        self.append_ellipse_arc((cx, cy), (rx, ry), start_angle, FRAC_PI_2, 0.0);
534    }
535
536    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath>
537    pub fn is_point_in_path(&self, x: f64, y: f64, fill_rule: FillRule) -> bool {
538        let p = Point::new(x, y);
539        // Step 1. If x or y are infinite or NaN, then return false.
540        if !p.is_finite() {
541            return false;
542        }
543
544        // Step 2. If the point given by the x and y coordinates,
545        // when treated as coordinates in the canvas coordinate space unaffected by the current transformation,
546        // is inside the intended path for path as determined by the fill rule indicated by fillRule,
547        // then return true.
548        // Open subpaths must be implicitly closed when computing the area inside the path,
549        // without affecting the actual subpaths.
550        let mut path = self.clone();
551        path.close_path();
552        let winding = path.0.winding(p);
553        let is_inside = match fill_rule {
554            FillRule::Nonzero => winding != 0,
555            FillRule::Evenodd => (winding % 2) != 0,
556        };
557        if is_inside {
558            return true;
559        }
560        // Points on the path itself must be considered to be inside the path.
561        path.0
562            .segments()
563            .any(|seg| seg.nearest(p, 0.00001).distance_sq < 0.00001)
564    }
565
566    pub fn bounding_box(&self) -> Rect<f64> {
567        self.0.control_box().into()
568    }
569}
570
571#[derive(Clone, Debug, Deserialize, Serialize, MallocSizeOf)]
572pub enum FillRule {
573    Nonzero,
574    Evenodd,
575}
576
577#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
578pub struct CanvasId(pub u64);
579
580#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)]
581pub struct CompositionOptions {
582    pub alpha: f64,
583    pub composition_operation: CompositionOrBlending,
584}
585
586#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
587pub struct ShadowOptions {
588    pub offset_x: f64,
589    pub offset_y: f64,
590    pub blur: f64,
591    pub color: AbsoluteColor,
592}
593
594impl ShadowOptions {
595    /// <https://html.spec.whatwg.org/multipage/#when-shadows-are-drawn>
596    pub fn need_to_draw_shadow(&self) -> bool {
597        // Shadows are only drawn if the opacity component of the alpha component of the shadow color is nonzero
598        self.color.alpha != 0.0 &&
599        // and either the shadowBlur is nonzero, or the shadowOffsetX is nonzero, or the shadowOffsetY is nonzero.
600            (self.offset_x != 0.0 ||
601                self.offset_y != 0.0 ||
602                self.blur != 0.0)
603    }
604}
605
606#[derive(Debug, Deserialize, MallocSizeOf, Serialize)]
607pub struct LineOptions {
608    pub width: f64,
609    pub cap_style: LineCapStyle,
610    pub join_style: LineJoinStyle,
611    pub miter_limit: f64,
612    pub dash: Vec<f32>,
613    pub dash_offset: f64,
614}
615
616pub type CanvasMsg = (CanvasId, CanvasCommand);
617
618#[derive(Debug, Deserialize, Serialize, Display, MallocSizeOf)]
619pub enum CanvasCommand {
620    /// This is used for resizing (when size is provided) or just clearing the canvas (when size is `None`).
621    Recreate(Option<Size2D<u64>>),
622    /// Destroy the canvas (its id will be invalidated).
623    Destroy,
624    SetImageKey(ImageKey),
625    DrawImage(
626        SharedSnapshot,
627        Rect<f64>,
628        Rect<f64>,
629        bool,
630        ShadowOptions,
631        CompositionOptions,
632        Transform2D<f64>,
633    ),
634    DrawEmptyImage(
635        Size2D<u32>,
636        Rect<f64>,
637        Rect<f64>,
638        ShadowOptions,
639        CompositionOptions,
640        Transform2D<f64>,
641    ),
642    DrawImageInOther(
643        CanvasId,
644        Rect<f64>,
645        Rect<f64>,
646        bool,
647        ShadowOptions,
648        CompositionOptions,
649        Transform2D<f64>,
650    ),
651    ClearRect(Rect<f32>, Transform2D<f64>),
652    ClipPath(Path, FillRule, Transform2D<f64>),
653    PopClips(usize),
654    FillPath(
655        FillOrStrokeStyle,
656        Path,
657        FillRule,
658        ShadowOptions,
659        CompositionOptions,
660        Transform2D<f64>,
661    ),
662    FillText(
663        Rect<f64>,
664        Vec<TextRun>,
665        FillOrStrokeStyle,
666        ShadowOptions,
667        CompositionOptions,
668        Transform2D<f64>,
669    ),
670    StrokeText(
671        Rect<f64>,
672        Vec<TextRun>,
673        FillOrStrokeStyle,
674        LineOptions,
675        ShadowOptions,
676        CompositionOptions,
677        Transform2D<f64>,
678    ),
679    FillRect(
680        Rect<f32>,
681        FillOrStrokeStyle,
682        ShadowOptions,
683        CompositionOptions,
684        Transform2D<f64>,
685    ),
686    GetImageData(Option<Rect<u32>>, GenericSender<SharedSnapshot>),
687    PutImageData(Rect<u32>, SharedSnapshot),
688    StrokeRect(
689        Rect<f32>,
690        FillOrStrokeStyle,
691        LineOptions,
692        ShadowOptions,
693        CompositionOptions,
694        Transform2D<f64>,
695    ),
696    StrokePath(
697        Path,
698        FillOrStrokeStyle,
699        LineOptions,
700        ShadowOptions,
701        CompositionOptions,
702        Transform2D<f64>,
703    ),
704    UpdateImage(Option<Epoch>),
705    ProcessBatchMessages(Vec<CanvasCommand>),
706}
707
708#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
709pub struct CanvasGradientStop {
710    pub offset: f64,
711    pub color: AbsoluteColor,
712}
713
714#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
715pub struct LinearGradientStyle {
716    pub x0: f64,
717    pub y0: f64,
718    pub x1: f64,
719    pub y1: f64,
720    pub stops: Vec<CanvasGradientStop>,
721}
722
723impl LinearGradientStyle {
724    pub fn new(
725        x0: f64,
726        y0: f64,
727        x1: f64,
728        y1: f64,
729        stops: Vec<CanvasGradientStop>,
730    ) -> LinearGradientStyle {
731        LinearGradientStyle {
732            x0,
733            y0,
734            x1,
735            y1,
736            stops,
737        }
738    }
739}
740
741#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
742pub struct RadialGradientStyle {
743    pub x0: f64,
744    pub y0: f64,
745    pub r0: f64,
746    pub x1: f64,
747    pub y1: f64,
748    pub r1: f64,
749    pub stops: Vec<CanvasGradientStop>,
750}
751
752impl RadialGradientStyle {
753    pub fn new(
754        x0: f64,
755        y0: f64,
756        r0: f64,
757        x1: f64,
758        y1: f64,
759        r1: f64,
760        stops: Vec<CanvasGradientStop>,
761    ) -> RadialGradientStyle {
762        RadialGradientStyle {
763            x0,
764            y0,
765            r0,
766            x1,
767            y1,
768            r1,
769            stops,
770        }
771    }
772}
773
774#[derive(Clone, Debug, Deserialize, Serialize, MallocSizeOf)]
775pub struct SurfaceStyle {
776    pub surface_data: SharedSnapshot,
777    pub surface_size: Size2D<u32>,
778    pub repeat_x: bool,
779    pub repeat_y: bool,
780    pub transform: Transform2D<f32>,
781}
782
783impl SurfaceStyle {
784    pub fn new(
785        surface_data: SharedSnapshot,
786        surface_size: Size2D<u32>,
787        repeat_x: bool,
788        repeat_y: bool,
789        transform: Transform2D<f32>,
790    ) -> Self {
791        Self {
792            surface_data,
793            surface_size,
794            repeat_x,
795            repeat_y,
796            transform,
797        }
798    }
799}
800
801#[derive(Clone, Debug, Deserialize, Serialize, MallocSizeOf)]
802pub enum FillOrStrokeStyle {
803    Color(AbsoluteColor),
804    LinearGradient(LinearGradientStyle),
805    RadialGradient(RadialGradientStyle),
806    Surface(SurfaceStyle),
807}
808
809impl FillOrStrokeStyle {
810    pub fn is_zero_size_gradient(&self) -> bool {
811        match self {
812            Self::RadialGradient(pattern) => {
813                let centers_equal = (pattern.x0, pattern.y0) == (pattern.x1, pattern.y1);
814                let radii_equal = pattern.r0 == pattern.r1;
815                (centers_equal && radii_equal) || pattern.stops.is_empty()
816            },
817            Self::LinearGradient(pattern) => {
818                (pattern.x0, pattern.y0) == (pattern.x1, pattern.y1) || pattern.stops.is_empty()
819            },
820            Self::Color(..) | Self::Surface(..) => false,
821        }
822    }
823
824    pub fn x_bound(&self) -> Option<u32> {
825        match self {
826            Self::Surface(pattern) => {
827                if pattern.repeat_x {
828                    None
829                } else {
830                    Some(pattern.surface_size.width)
831                }
832            },
833            Self::Color(..) | Self::LinearGradient(..) | Self::RadialGradient(..) => None,
834        }
835    }
836
837    pub fn y_bound(&self) -> Option<u32> {
838        match self {
839            Self::Surface(pattern) => {
840                if pattern.repeat_y {
841                    None
842                } else {
843                    Some(pattern.surface_size.height)
844                }
845            },
846            Self::Color(..) | Self::LinearGradient(..) | Self::RadialGradient(..) => None,
847        }
848    }
849}
850
851#[derive(
852    Clone, Copy, Debug, Display, Deserialize, EnumString, MallocSizeOf, PartialEq, Serialize,
853)]
854pub enum LineCapStyle {
855    Butt = 0,
856    Round = 1,
857    Square = 2,
858}
859
860#[derive(
861    Clone, Copy, Debug, Deserialize, Display, EnumString, MallocSizeOf, PartialEq, Serialize,
862)]
863pub enum LineJoinStyle {
864    Round = 0,
865    Bevel = 1,
866    Miter = 2,
867}
868
869#[derive(Clone, Copy, Debug, Deserialize, Display, EnumString, PartialEq, Serialize)]
870#[strum(serialize_all = "kebab-case")]
871pub enum RepetitionStyle {
872    Repeat,
873    RepeatX,
874    RepeatY,
875    NoRepeat,
876}
877
878/// <https://drafts.csswg.org/compositing/#compositemode>
879#[derive(
880    Clone, Copy, Debug, Deserialize, Display, EnumString, MallocSizeOf, PartialEq, Serialize,
881)]
882#[strum(serialize_all = "kebab-case")]
883pub enum CompositionStyle {
884    Clear,
885    Copy,
886    SourceOver,
887    DestinationOver,
888    SourceIn,
889    DestinationIn,
890    SourceOut,
891    DestinationOut,
892    SourceAtop,
893    DestinationAtop,
894    Xor,
895    Lighter,
896    // PlusDarker,
897    // PlusLighter,
898}
899
900/// <https://drafts.csswg.org/compositing/#ltblendmodegt>
901#[derive(
902    Clone, Copy, Debug, Deserialize, Display, EnumString, MallocSizeOf, PartialEq, Serialize,
903)]
904#[strum(serialize_all = "kebab-case")]
905pub enum BlendingStyle {
906    // Normal,
907    Multiply,
908    Screen,
909    Overlay,
910    Darken,
911    Lighten,
912    ColorDodge,
913    ColorBurn,
914    HardLight,
915    SoftLight,
916    Difference,
917    Exclusion,
918    Hue,
919    Saturation,
920    Color,
921    Luminosity,
922}
923
924#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
925pub enum CompositionOrBlending {
926    Composition(CompositionStyle),
927    Blending(BlendingStyle),
928}
929
930impl Default for CompositionOrBlending {
931    fn default() -> CompositionOrBlending {
932        CompositionOrBlending::Composition(CompositionStyle::SourceOver)
933    }
934}
935
936impl FromStr for CompositionOrBlending {
937    type Err = ();
938
939    fn from_str(string: &str) -> Result<CompositionOrBlending, ()> {
940        if let Ok(op) = CompositionStyle::from_str(string) {
941            return Ok(CompositionOrBlending::Composition(op));
942        }
943
944        if let Ok(op) = BlendingStyle::from_str(string) {
945            return Ok(CompositionOrBlending::Blending(op));
946        }
947
948        Err(())
949    }
950}
951
952#[derive(Debug, Deserialize, Serialize, MallocSizeOf)]
953pub struct GlyphAndPosition {
954    pub id: u32,
955    pub point: Point2D<f32>,
956}
957
958#[derive(Deserialize, Serialize, MallocSizeOf)]
959pub struct CanvasFont {
960    /// A [`FontIdentifier`] for this [`CanvasFont`], maybe either `Local` or `Web`.
961    pub identifier: FontIdentifier,
962    /// If this font is a web font, this field contains the data for the font. If
963    /// the font is a local font, it will be `None`.
964    pub data: Option<FontDataAndIndex>,
965}
966
967impl CanvasFont {
968    pub fn font_data_and_index(&self) -> Option<FontDataAndIndex> {
969        match &self.identifier {
970            FontIdentifier::Local(local_font_identifier) => {
971                local_font_identifier.font_data_and_index()
972            },
973            FontIdentifier::Web(_) => self.data.clone(),
974            FontIdentifier::ArrayBuffer(_) => self.data.clone(),
975        }
976    }
977}
978
979#[derive(Deserialize, Serialize, MallocSizeOf)]
980pub struct TextRun {
981    pub font: CanvasFont,
982    pub pt_size: f32,
983    pub glyphs_and_positions: Vec<GlyphAndPosition>,
984    pub advance: f32,
985    pub bounds: Rect<f64>,
986}
987
988impl std::fmt::Debug for TextRun {
989    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
990        f.debug_struct("TextRun")
991            .field("glyphs_and_positions", &self.glyphs_and_positions)
992            .field("size", &self.bounds)
993            .finish()
994    }
995}