script/dom/canvas/2d/
canvas_state.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::cell::Cell;
6use std::fmt;
7use std::str::FromStr;
8use std::sync::Arc;
9
10use app_units::Au;
11use base::Epoch;
12use base::generic_channel::GenericSender;
13use canvas_traits::canvas::{
14    Canvas2dMsg, CanvasFont, CanvasId, CanvasMsg, CompositionOptions, CompositionOrBlending,
15    FillOrStrokeStyle, FillRule, GlyphAndPosition, LineCapStyle, LineJoinStyle, LineOptions,
16    LinearGradientStyle, Path, RadialGradientStyle, RepetitionStyle, ShadowOptions, TextRun,
17};
18use constellation_traits::ScriptToConstellationMessage;
19use cssparser::color::clamp_unit_f32;
20use cssparser::{Parser, ParserInput};
21use euclid::default::{Point2D, Rect, Size2D, Transform2D};
22use euclid::{Vector2D, vec2};
23use fonts::{
24    ByteIndex, FontBaseline, FontContext, FontGroup, FontIdentifier, FontMetrics, FontRef,
25    LAST_RESORT_GLYPH_ADVANCE, ShapingFlags, ShapingOptions,
26};
27use ipc_channel::ipc;
28use net_traits::image_cache::{ImageCache, ImageResponse};
29use net_traits::request::CorsSettings;
30use pixels::{Snapshot, SnapshotAlphaMode, SnapshotPixelFormat};
31use profile_traits::ipc as profiled_ipc;
32use range::Range;
33use servo_arc::Arc as ServoArc;
34use servo_url::{ImmutableOrigin, ServoUrl};
35use style::color::{AbsoluteColor, ColorFlags, ColorSpace};
36use style::context::QuirksMode;
37use style::parser::ParserContext;
38use style::properties::longhands::font_variant_caps::computed_value::T as FontVariantCaps;
39use style::properties::style_structs::Font;
40use style::stylesheets::{CssRuleType, Origin};
41use style::values::computed::font::FontStyle;
42use style::values::specified::color::Color;
43use style_traits::values::ToCss;
44use style_traits::{CssWriter, ParsingMode};
45use unicode_script::Script;
46use url::Url;
47use webrender_api::ImageKey;
48
49use crate::canvas_context::{CanvasContext, OffscreenRenderingContext, RenderingContext};
50use crate::conversions::Convert;
51use crate::dom::bindings::cell::DomRefCell;
52use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::{
53    CanvasDirection, CanvasFillRule, CanvasImageSource, CanvasLineCap, CanvasLineJoin,
54    CanvasTextAlign, CanvasTextBaseline, ImageDataMethods,
55};
56use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::DOMMatrix2DInit;
57use crate::dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPattern;
58use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
59use crate::dom::bindings::inheritance::Castable;
60use crate::dom::bindings::num::Finite;
61use crate::dom::bindings::root::{Dom, DomRoot};
62use crate::dom::bindings::str::DOMString;
63use crate::dom::canvasgradient::{CanvasGradient, CanvasGradientStyle, ToFillOrStrokeStyle};
64use crate::dom::canvaspattern::CanvasPattern;
65use crate::dom::dommatrix::DOMMatrix;
66use crate::dom::dommatrixreadonly::dommatrix2dinit_to_matrix;
67use crate::dom::element::Element;
68use crate::dom::globalscope::GlobalScope;
69use crate::dom::html::htmlcanvaselement::HTMLCanvasElement;
70use crate::dom::html::htmlimageelement::HTMLImageElement;
71use crate::dom::html::htmlvideoelement::HTMLVideoElement;
72use crate::dom::imagebitmap::ImageBitmap;
73use crate::dom::imagedata::ImageData;
74use crate::dom::node::{Node, NodeTraits};
75use crate::dom::offscreencanvas::OffscreenCanvas;
76use crate::dom::paintworkletglobalscope::PaintWorkletGlobalScope;
77use crate::dom::textmetrics::TextMetrics;
78use crate::script_runtime::CanGc;
79
80const HANGING_BASELINE_DEFAULT: f64 = 0.8;
81const IDEOGRAPHIC_BASELINE_DEFAULT: f64 = 0.5;
82
83#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
84#[derive(Clone, JSTraceable, MallocSizeOf)]
85pub(super) enum CanvasFillOrStrokeStyle {
86    Color(#[no_trace] AbsoluteColor),
87    Gradient(Dom<CanvasGradient>),
88    Pattern(Dom<CanvasPattern>),
89}
90
91impl CanvasFillOrStrokeStyle {
92    fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle {
93        match self {
94            CanvasFillOrStrokeStyle::Color(rgba) => FillOrStrokeStyle::Color(*rgba),
95            CanvasFillOrStrokeStyle::Gradient(gradient) => gradient.to_fill_or_stroke_style(),
96            CanvasFillOrStrokeStyle::Pattern(pattern) => pattern.to_fill_or_stroke_style(),
97        }
98    }
99}
100
101#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
102#[derive(Clone, JSTraceable, MallocSizeOf)]
103pub(super) struct CanvasContextState {
104    global_alpha: f64,
105    #[no_trace]
106    global_composition: CompositionOrBlending,
107    image_smoothing_enabled: bool,
108    fill_style: CanvasFillOrStrokeStyle,
109    stroke_style: CanvasFillOrStrokeStyle,
110    line_width: f64,
111    #[no_trace]
112    line_cap: LineCapStyle,
113    #[no_trace]
114    line_join: LineJoinStyle,
115    miter_limit: f64,
116    line_dash: Vec<f64>,
117    line_dash_offset: f64,
118    #[no_trace]
119    transform: Transform2D<f64>,
120    shadow_offset_x: f64,
121    shadow_offset_y: f64,
122    shadow_blur: f64,
123    #[no_trace]
124    shadow_color: AbsoluteColor,
125    #[no_trace]
126    #[conditional_malloc_size_of]
127    font_style: Option<ServoArc<Font>>,
128    text_align: CanvasTextAlign,
129    text_baseline: CanvasTextBaseline,
130    direction: CanvasDirection,
131    /// The number of clips pushed onto the context while in this state.
132    /// When restoring old state, same number of clips will be popped to restore state.
133    clips_pushed: usize,
134}
135
136impl CanvasContextState {
137    const DEFAULT_FONT_STYLE: &'static str = "10px sans-serif";
138
139    pub(super) fn new() -> CanvasContextState {
140        CanvasContextState {
141            global_alpha: 1.0,
142            global_composition: CompositionOrBlending::default(),
143            image_smoothing_enabled: true,
144            fill_style: CanvasFillOrStrokeStyle::Color(AbsoluteColor::BLACK),
145            stroke_style: CanvasFillOrStrokeStyle::Color(AbsoluteColor::BLACK),
146            line_width: 1.0,
147            line_cap: LineCapStyle::Butt,
148            line_join: LineJoinStyle::Miter,
149            miter_limit: 10.0,
150            transform: Transform2D::identity(),
151            shadow_offset_x: 0.0,
152            shadow_offset_y: 0.0,
153            shadow_blur: 0.0,
154            shadow_color: AbsoluteColor::TRANSPARENT_BLACK,
155            font_style: None,
156            text_align: CanvasTextAlign::Start,
157            text_baseline: CanvasTextBaseline::Alphabetic,
158            direction: CanvasDirection::Inherit,
159            line_dash: Vec::new(),
160            line_dash_offset: 0.0,
161            clips_pushed: 0,
162        }
163    }
164
165    fn composition_options(&self) -> CompositionOptions {
166        CompositionOptions {
167            alpha: self.global_alpha,
168            composition_operation: self.global_composition,
169        }
170    }
171
172    fn shadow_options(&self) -> ShadowOptions {
173        ShadowOptions {
174            offset_x: self.shadow_offset_x,
175            offset_y: self.shadow_offset_y,
176            blur: self.shadow_blur,
177            color: self.shadow_color,
178        }
179    }
180
181    fn line_options(&self) -> LineOptions {
182        LineOptions {
183            width: self.line_width,
184            cap_style: self.line_cap,
185            join_style: self.line_join,
186            miter_limit: self.miter_limit,
187            dash: self.line_dash.iter().map(|x| *x as f32).collect(),
188            dash_offset: self.line_dash_offset,
189        }
190    }
191}
192
193#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
194#[derive(JSTraceable, MallocSizeOf)]
195pub(super) struct CanvasState {
196    #[no_trace]
197    canvas_thread_sender: GenericSender<CanvasMsg>,
198    #[no_trace]
199    canvas_id: CanvasId,
200    #[no_trace]
201    size: Cell<Size2D<u64>>,
202    state: DomRefCell<CanvasContextState>,
203    origin_clean: Cell<bool>,
204    #[ignore_malloc_size_of = "ImageCache"]
205    #[no_trace]
206    image_cache: Arc<dyn ImageCache>,
207    /// The base URL for resolving CSS image URL values.
208    /// Needed because of <https://github.com/servo/servo/issues/17625>
209    #[no_trace]
210    base_url: ServoUrl,
211    #[no_trace]
212    origin: ImmutableOrigin,
213    /// Any missing image URLs.
214    #[no_trace]
215    missing_image_urls: DomRefCell<Vec<ServoUrl>>,
216    saved_states: DomRefCell<Vec<CanvasContextState>>,
217    /// <https://html.spec.whatwg.org/multipage/#current-default-path>
218    #[no_trace]
219    current_default_path: DomRefCell<Path>,
220}
221
222impl CanvasState {
223    pub(super) fn new(global: &GlobalScope, size: Size2D<u64>) -> Option<CanvasState> {
224        debug!("Creating new canvas rendering context.");
225        let (sender, receiver) =
226            profiled_ipc::channel(global.time_profiler_chan().clone()).unwrap();
227        let script_to_constellation_chan = global.script_to_constellation_chan();
228        debug!("Asking constellation to create new canvas thread.");
229        let size = adjust_canvas_size(size);
230        script_to_constellation_chan
231            .send(ScriptToConstellationMessage::CreateCanvasPaintThread(
232                size, sender,
233            ))
234            .unwrap();
235        let (canvas_thread_sender, canvas_id) = receiver.recv().ok()??;
236        debug!("Done.");
237        // Worklets always receive a unique origin. This messes with fetching
238        // cached images in the case of paint worklets, since the image cache
239        // is keyed on the origin requesting the image data.
240        let origin = if global.is::<PaintWorkletGlobalScope>() {
241            global.api_base_url().origin()
242        } else {
243            global.origin().immutable().clone()
244        };
245        Some(CanvasState {
246            canvas_thread_sender,
247            canvas_id,
248            size: Cell::new(size),
249            state: DomRefCell::new(CanvasContextState::new()),
250            origin_clean: Cell::new(true),
251            image_cache: global.image_cache(),
252            base_url: global.api_base_url(),
253            missing_image_urls: DomRefCell::new(Vec::new()),
254            saved_states: DomRefCell::new(Vec::new()),
255            origin,
256            current_default_path: DomRefCell::new(Path::new()),
257        })
258    }
259
260    pub(super) fn set_image_key(&self, image_key: ImageKey) {
261        self.send_canvas_2d_msg(Canvas2dMsg::SetImageKey(image_key));
262    }
263
264    pub(super) fn get_missing_image_urls(&self) -> &DomRefCell<Vec<ServoUrl>> {
265        &self.missing_image_urls
266    }
267
268    pub(super) fn get_canvas_id(&self) -> CanvasId {
269        self.canvas_id
270    }
271
272    pub(super) fn is_paintable(&self) -> bool {
273        !self.size.get().is_empty()
274    }
275
276    pub(super) fn send_canvas_2d_msg(&self, msg: Canvas2dMsg) {
277        if !self.is_paintable() {
278            return;
279        }
280
281        self.canvas_thread_sender
282            .send(CanvasMsg::Canvas2d(msg, self.get_canvas_id()))
283            .unwrap()
284    }
285
286    /// Updates WR image and blocks on completion
287    pub(super) fn update_rendering(&self, canvas_epoch: Option<Epoch>) -> bool {
288        if !self.is_paintable() {
289            return false;
290        }
291
292        self.canvas_thread_sender
293            .send(CanvasMsg::Canvas2d(
294                Canvas2dMsg::UpdateImage(canvas_epoch),
295                self.canvas_id,
296            ))
297            .unwrap();
298        true
299    }
300
301    /// <https://html.spec.whatwg.org/multipage/#concept-canvas-set-bitmap-dimensions>
302    pub(super) fn set_bitmap_dimensions(&self, size: Size2D<u64>) {
303        // Step 1. Reset the rendering context to its default state.
304        self.reset_to_initial_state();
305
306        // Step 2. Resize the output bitmap to the new width and height.
307        self.size.replace(adjust_canvas_size(size));
308
309        self.canvas_thread_sender
310            .send(CanvasMsg::Recreate(
311                Some(self.size.get()),
312                self.get_canvas_id(),
313            ))
314            .unwrap();
315    }
316
317    /// <https://html.spec.whatwg.org/multipage/#reset-the-rendering-context-to-its-default-state>
318    pub(super) fn reset(&self) {
319        self.reset_to_initial_state();
320
321        if !self.is_paintable() {
322            return;
323        }
324
325        // Step 1. Clear canvas's bitmap to transparent black.
326        self.canvas_thread_sender
327            .send(CanvasMsg::Recreate(None, self.get_canvas_id()))
328            .unwrap();
329    }
330
331    /// <https://html.spec.whatwg.org/multipage/#reset-the-rendering-context-to-its-default-state>
332    fn reset_to_initial_state(&self) {
333        // Step 2. Empty the list of subpaths in context's current default path.
334        *self.current_default_path.borrow_mut() = Path::new();
335
336        // Step 3. Clear the context's drawing state stack.
337        self.saved_states.borrow_mut().clear();
338
339        // Step 4. Reset everything that drawing state consists of to their initial values.
340        *self.state.borrow_mut() = CanvasContextState::new();
341
342        // <https://html.spec.whatwg.org/multipage/#security-with-canvas-elements>
343        // The flag can be reset in certain situations; for example, when changing the value of the
344        // width or the height content attribute of the canvas element to which a
345        // CanvasRenderingContext2D is bound, the bitmap is cleared and its origin-clean flag is
346        // reset.
347        self.set_origin_clean(true);
348    }
349
350    pub(super) fn reset_bitmap(&self) {
351        if !self.is_paintable() {
352            return;
353        }
354
355        self.send_canvas_2d_msg(Canvas2dMsg::ClearRect(
356            self.size.get().to_f32().into(),
357            self.state.borrow().transform,
358        ));
359    }
360
361    fn create_drawable_rect(&self, x: f64, y: f64, w: f64, h: f64) -> Option<Rect<f32>> {
362        if !([x, y, w, h].iter().all(|val| val.is_finite())) {
363            return None;
364        }
365
366        if w == 0.0 && h == 0.0 {
367            return None;
368        }
369
370        Some(Rect::new(
371            Point2D::new(x as f32, y as f32),
372            Size2D::new(w as f32, h as f32),
373        ))
374    }
375
376    pub(super) fn origin_is_clean(&self) -> bool {
377        self.origin_clean.get()
378    }
379
380    fn set_origin_clean(&self, origin_clean: bool) {
381        self.origin_clean.set(origin_clean);
382    }
383
384    /// <https://html.spec.whatwg.org/multipage/#the-image-argument-is-not-origin-clean>
385    fn is_origin_clean(&self, source: CanvasImageSource) -> bool {
386        match source {
387            CanvasImageSource::HTMLImageElement(image) => {
388                image.same_origin(GlobalScope::entry().origin())
389            },
390            CanvasImageSource::HTMLVideoElement(video) => video.origin_is_clean(),
391            CanvasImageSource::HTMLCanvasElement(canvas) => canvas.origin_is_clean(),
392            CanvasImageSource::ImageBitmap(bitmap) => bitmap.origin_is_clean(),
393            CanvasImageSource::OffscreenCanvas(canvas) => canvas.origin_is_clean(),
394            CanvasImageSource::CSSStyleValue(_) => true,
395        }
396    }
397
398    fn fetch_image_data(
399        &self,
400        url: ServoUrl,
401        cors_setting: Option<CorsSettings>,
402    ) -> Option<Snapshot> {
403        let raster_image = match self.request_image_from_cache(url, cors_setting) {
404            ImageResponse::Loaded(image, _) => {
405                if let Some(image) = image.as_raster_image() {
406                    image
407                } else {
408                    // TODO: https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
409                    warn!("Vector images are not supported as image source in canvas2d");
410                    return None;
411                }
412            },
413            ImageResponse::FailedToLoadOrDecode | ImageResponse::MetadataLoaded(_) => {
414                return None;
415            },
416        };
417
418        Some(raster_image.as_snapshot())
419    }
420
421    fn request_image_from_cache(
422        &self,
423        url: ServoUrl,
424        cors_setting: Option<CorsSettings>,
425    ) -> ImageResponse {
426        match self
427            .image_cache
428            .get_image(url.clone(), self.origin.clone(), cors_setting)
429        {
430            Some(image) => ImageResponse::Loaded(image, url),
431            None => {
432                // Rather annoyingly, we get the same response back from
433                // A load which really failed and from a load which hasn't started yet.
434                self.missing_image_urls.borrow_mut().push(url);
435                ImageResponse::FailedToLoadOrDecode
436            },
437        }
438    }
439
440    ///
441    /// drawImage coordinates explained
442    ///
443    /// ```
444    ///  Source Image      Destination Canvas
445    /// +-------------+     +-------------+
446    /// |             |     |             |
447    /// |(sx,sy)      |     |(dx,dy)      |
448    /// |   +----+    |     |   +----+    |
449    /// |   |    |    |     |   |    |    |
450    /// |   |    |sh  |---->|   |    |dh  |
451    /// |   |    |    |     |   |    |    |
452    /// |   +----+    |     |   +----+    |
453    /// |     sw      |     |     dw      |
454    /// |             |     |             |
455    /// +-------------+     +-------------+
456    /// ```
457    ///
458    /// The rectangle (sx, sy, sw, sh) from the source image
459    /// is copied on the rectangle (dx, dy, dh, dw) of the destination canvas
460    ///
461    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage>
462    #[allow(clippy::too_many_arguments)]
463    fn draw_image_internal(
464        &self,
465        htmlcanvas: Option<&HTMLCanvasElement>,
466        image: CanvasImageSource,
467        sx: f64,
468        sy: f64,
469        sw: Option<f64>,
470        sh: Option<f64>,
471        dx: f64,
472        dy: f64,
473        dw: Option<f64>,
474        dh: Option<f64>,
475    ) -> ErrorResult {
476        if !self.is_paintable() {
477            return Ok(());
478        }
479
480        let result = match image {
481            CanvasImageSource::HTMLImageElement(ref image) => {
482                // https://html.spec.whatwg.org/multipage/#drawing-images
483                // 2. Let usability be the result of checking the usability of image.
484                // 3. If usability is bad, then return (without drawing anything).
485                if !image.is_usable()? {
486                    return Ok(());
487                }
488
489                self.draw_html_image_element(image, htmlcanvas, sx, sy, sw, sh, dx, dy, dw, dh);
490                Ok(())
491            },
492            CanvasImageSource::HTMLVideoElement(ref video) => {
493                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
494                // Step 2. Let usability be the result of checking the usability of image.
495                // Step 3. If usability is bad, then return (without drawing anything).
496                if !video.is_usable() {
497                    return Ok(());
498                }
499
500                self.draw_html_video_element(video, htmlcanvas, sx, sy, sw, sh, dx, dy, dw, dh);
501                Ok(())
502            },
503            CanvasImageSource::HTMLCanvasElement(ref canvas) => {
504                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
505                if canvas.get_size().is_empty() {
506                    return Err(Error::InvalidState(None));
507                }
508
509                self.draw_html_canvas_element(canvas, htmlcanvas, sx, sy, sw, sh, dx, dy, dw, dh)
510            },
511            CanvasImageSource::ImageBitmap(ref bitmap) => {
512                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
513                if bitmap.is_detached() {
514                    return Err(Error::InvalidState(None));
515                }
516
517                self.draw_image_bitmap(bitmap, htmlcanvas, sx, sy, sw, sh, dx, dy, dw, dh);
518                Ok(())
519            },
520            CanvasImageSource::OffscreenCanvas(ref canvas) => {
521                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
522                if canvas.get_size().is_empty() {
523                    return Err(Error::InvalidState(None));
524                }
525
526                self.draw_offscreen_canvas(canvas, htmlcanvas, sx, sy, sw, sh, dx, dy, dw, dh)
527            },
528            CanvasImageSource::CSSStyleValue(ref value) => {
529                let url = value
530                    .get_url(self.base_url.clone())
531                    .ok_or(Error::InvalidState(None))?;
532                self.fetch_and_draw_image_data(
533                    htmlcanvas, url, None, sx, sy, sw, sh, dx, dy, dw, dh,
534                )
535            },
536        };
537
538        if result.is_ok() && !self.is_origin_clean(image) {
539            self.set_origin_clean(false);
540        }
541        result
542    }
543
544    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage>
545    #[allow(clippy::too_many_arguments)]
546    fn draw_html_image_element(
547        &self,
548        image: &HTMLImageElement,
549        canvas: Option<&HTMLCanvasElement>,
550        sx: f64,
551        sy: f64,
552        sw: Option<f64>,
553        sh: Option<f64>,
554        dx: f64,
555        dy: f64,
556        dw: Option<f64>,
557        dh: Option<f64>,
558    ) {
559        let Some(snapshot) = image.get_raster_image_data() else {
560            return;
561        };
562
563        // Step 4. Establish the source and destination rectangles.
564        let image_size = snapshot.size();
565        let dw = dw.unwrap_or(image_size.width as f64);
566        let dh = dh.unwrap_or(image_size.height as f64);
567        let sw = sw.unwrap_or(image_size.width as f64);
568        let sh = sh.unwrap_or(image_size.height as f64);
569
570        let (source_rect, dest_rect) =
571            self.adjust_source_dest_rects(image_size, sx, sy, sw, sh, dx, dy, dw, dh);
572
573        // Step 5. If one of the sw or sh arguments is zero, then return. Nothing is painted.
574        if !is_rect_valid(source_rect) || !is_rect_valid(dest_rect) {
575            return;
576        }
577
578        let smoothing_enabled = self.state.borrow().image_smoothing_enabled;
579
580        self.send_canvas_2d_msg(Canvas2dMsg::DrawImage(
581            snapshot.to_shared(),
582            dest_rect,
583            source_rect,
584            smoothing_enabled,
585            self.state.borrow().shadow_options(),
586            self.state.borrow().composition_options(),
587            self.state.borrow().transform,
588        ));
589
590        self.mark_as_dirty(canvas);
591    }
592
593    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage>
594    #[allow(clippy::too_many_arguments)]
595    fn draw_html_video_element(
596        &self,
597        video: &HTMLVideoElement,
598        canvas: Option<&HTMLCanvasElement>,
599        sx: f64,
600        sy: f64,
601        sw: Option<f64>,
602        sh: Option<f64>,
603        dx: f64,
604        dy: f64,
605        dw: Option<f64>,
606        dh: Option<f64>,
607    ) {
608        let Some(snapshot) = video.get_current_frame_data() else {
609            return;
610        };
611
612        // Step 4. Establish the source and destination rectangles.
613        let video_size = snapshot.size();
614        let dw = dw.unwrap_or(video_size.width as f64);
615        let dh = dh.unwrap_or(video_size.height as f64);
616        let sw = sw.unwrap_or(video_size.width as f64);
617        let sh = sh.unwrap_or(video_size.height as f64);
618
619        let (source_rect, dest_rect) =
620            self.adjust_source_dest_rects(video_size, sx, sy, sw, sh, dx, dy, dw, dh);
621
622        // Step 5. If one of the sw or sh arguments is zero, then return. Nothing is painted.
623        if !is_rect_valid(source_rect) || !is_rect_valid(dest_rect) {
624            return;
625        }
626
627        let smoothing_enabled = self.state.borrow().image_smoothing_enabled;
628
629        self.send_canvas_2d_msg(Canvas2dMsg::DrawImage(
630            snapshot.to_shared(),
631            dest_rect,
632            source_rect,
633            smoothing_enabled,
634            self.state.borrow().shadow_options(),
635            self.state.borrow().composition_options(),
636            self.state.borrow().transform,
637        ));
638
639        self.mark_as_dirty(canvas);
640    }
641
642    #[allow(clippy::too_many_arguments)]
643    fn draw_offscreen_canvas(
644        &self,
645        canvas: &OffscreenCanvas,
646        htmlcanvas: Option<&HTMLCanvasElement>,
647        sx: f64,
648        sy: f64,
649        sw: Option<f64>,
650        sh: Option<f64>,
651        dx: f64,
652        dy: f64,
653        dw: Option<f64>,
654        dh: Option<f64>,
655    ) -> ErrorResult {
656        let canvas_size = canvas
657            .context()
658            .map_or_else(|| canvas.get_size(), |context| context.size());
659
660        let dw = dw.unwrap_or(canvas_size.width as f64);
661        let dh = dh.unwrap_or(canvas_size.height as f64);
662        let sw = sw.unwrap_or(canvas_size.width as f64);
663        let sh = sh.unwrap_or(canvas_size.height as f64);
664
665        let image_size = Size2D::new(canvas_size.width, canvas_size.height);
666        // 2. Establish the source and destination rectangles
667        let (source_rect, dest_rect) =
668            self.adjust_source_dest_rects(image_size, sx, sy, sw, sh, dx, dy, dw, dh);
669
670        if !is_rect_valid(source_rect) || !is_rect_valid(dest_rect) {
671            return Ok(());
672        }
673
674        let smoothing_enabled = self.state.borrow().image_smoothing_enabled;
675
676        if let Some(context) = canvas.context() {
677            match *context {
678                OffscreenRenderingContext::Context2d(ref context) => {
679                    context.send_canvas_2d_msg(Canvas2dMsg::DrawImageInOther(
680                        self.get_canvas_id(),
681                        dest_rect,
682                        source_rect,
683                        smoothing_enabled,
684                        self.state.borrow().shadow_options(),
685                        self.state.borrow().composition_options(),
686                        self.state.borrow().transform,
687                    ));
688                },
689                OffscreenRenderingContext::BitmapRenderer(ref context) => {
690                    let Some(snapshot) = context.get_image_data() else {
691                        return Ok(());
692                    };
693
694                    self.send_canvas_2d_msg(Canvas2dMsg::DrawImage(
695                        snapshot.to_shared(),
696                        dest_rect,
697                        source_rect,
698                        smoothing_enabled,
699                        self.state.borrow().shadow_options(),
700                        self.state.borrow().composition_options(),
701                        self.state.borrow().transform,
702                    ));
703                },
704                OffscreenRenderingContext::Detached => return Err(Error::InvalidState(None)),
705            }
706        } else {
707            self.send_canvas_2d_msg(Canvas2dMsg::DrawEmptyImage(
708                image_size,
709                dest_rect,
710                source_rect,
711                self.state.borrow().shadow_options(),
712                self.state.borrow().composition_options(),
713                self.state.borrow().transform,
714            ));
715        }
716
717        self.mark_as_dirty(htmlcanvas);
718        Ok(())
719    }
720
721    #[allow(clippy::too_many_arguments)]
722    fn draw_html_canvas_element(
723        &self,
724        canvas: &HTMLCanvasElement,             // source canvas
725        htmlcanvas: Option<&HTMLCanvasElement>, // destination canvas
726        sx: f64,
727        sy: f64,
728        sw: Option<f64>,
729        sh: Option<f64>,
730        dx: f64,
731        dy: f64,
732        dw: Option<f64>,
733        dh: Option<f64>,
734    ) -> ErrorResult {
735        let canvas_size = canvas
736            .context()
737            .map_or_else(|| canvas.get_size(), |context| context.size());
738
739        let dw = dw.unwrap_or(canvas_size.width as f64);
740        let dh = dh.unwrap_or(canvas_size.height as f64);
741        let sw = sw.unwrap_or(canvas_size.width as f64);
742        let sh = sh.unwrap_or(canvas_size.height as f64);
743
744        let image_size = Size2D::new(canvas_size.width, canvas_size.height);
745        // 2. Establish the source and destination rectangles
746        let (source_rect, dest_rect) =
747            self.adjust_source_dest_rects(image_size, sx, sy, sw, sh, dx, dy, dw, dh);
748
749        if !is_rect_valid(source_rect) || !is_rect_valid(dest_rect) {
750            return Ok(());
751        }
752
753        let smoothing_enabled = self.state.borrow().image_smoothing_enabled;
754
755        if let Some(context) = canvas.context() {
756            match *context {
757                RenderingContext::Context2d(ref context) => {
758                    context.send_canvas_2d_msg(Canvas2dMsg::DrawImageInOther(
759                        self.get_canvas_id(),
760                        dest_rect,
761                        source_rect,
762                        smoothing_enabled,
763                        self.state.borrow().shadow_options(),
764                        self.state.borrow().composition_options(),
765                        self.state.borrow().transform,
766                    ));
767                },
768                RenderingContext::BitmapRenderer(ref context) => {
769                    let Some(snapshot) = context.get_image_data() else {
770                        return Ok(());
771                    };
772
773                    self.send_canvas_2d_msg(Canvas2dMsg::DrawImage(
774                        snapshot.to_shared(),
775                        dest_rect,
776                        source_rect,
777                        smoothing_enabled,
778                        self.state.borrow().shadow_options(),
779                        self.state.borrow().composition_options(),
780                        self.state.borrow().transform,
781                    ));
782                },
783                RenderingContext::Placeholder(ref context) => {
784                    let Some(context) = context.context() else {
785                        return Err(Error::InvalidState(None));
786                    };
787                    match *context {
788                        OffscreenRenderingContext::Context2d(ref context) => context
789                            .send_canvas_2d_msg(Canvas2dMsg::DrawImageInOther(
790                                self.get_canvas_id(),
791                                dest_rect,
792                                source_rect,
793                                smoothing_enabled,
794                                self.state.borrow().shadow_options(),
795                                self.state.borrow().composition_options(),
796                                self.state.borrow().transform,
797                            )),
798                        OffscreenRenderingContext::BitmapRenderer(ref context) => {
799                            let Some(snapshot) = context.get_image_data() else {
800                                return Ok(());
801                            };
802
803                            self.send_canvas_2d_msg(Canvas2dMsg::DrawImage(
804                                snapshot.to_shared(),
805                                dest_rect,
806                                source_rect,
807                                smoothing_enabled,
808                                self.state.borrow().shadow_options(),
809                                self.state.borrow().composition_options(),
810                                self.state.borrow().transform,
811                            ));
812                        },
813                        OffscreenRenderingContext::Detached => {
814                            return Err(Error::InvalidState(None));
815                        },
816                    }
817                },
818                _ => return Err(Error::InvalidState(None)),
819            }
820        } else {
821            self.send_canvas_2d_msg(Canvas2dMsg::DrawEmptyImage(
822                image_size,
823                dest_rect,
824                source_rect,
825                self.state.borrow().shadow_options(),
826                self.state.borrow().composition_options(),
827                self.state.borrow().transform,
828            ));
829        }
830
831        self.mark_as_dirty(htmlcanvas);
832        Ok(())
833    }
834
835    #[allow(clippy::too_many_arguments)]
836    fn fetch_and_draw_image_data(
837        &self,
838        canvas: Option<&HTMLCanvasElement>,
839        url: ServoUrl,
840        cors_setting: Option<CorsSettings>,
841        sx: f64,
842        sy: f64,
843        sw: Option<f64>,
844        sh: Option<f64>,
845        dx: f64,
846        dy: f64,
847        dw: Option<f64>,
848        dh: Option<f64>,
849    ) -> ErrorResult {
850        debug!("Fetching image {}.", url);
851        let snapshot = self
852            .fetch_image_data(url, cors_setting)
853            .ok_or(Error::InvalidState(None))?;
854        let image_size = snapshot.size();
855
856        let dw = dw.unwrap_or(image_size.width as f64);
857        let dh = dh.unwrap_or(image_size.height as f64);
858        let sw = sw.unwrap_or(image_size.width as f64);
859        let sh = sh.unwrap_or(image_size.height as f64);
860
861        // Establish the source and destination rectangles
862        let (source_rect, dest_rect) =
863            self.adjust_source_dest_rects(image_size, sx, sy, sw, sh, dx, dy, dw, dh);
864
865        if !is_rect_valid(source_rect) || !is_rect_valid(dest_rect) {
866            return Ok(());
867        }
868
869        let smoothing_enabled = self.state.borrow().image_smoothing_enabled;
870        self.send_canvas_2d_msg(Canvas2dMsg::DrawImage(
871            snapshot.to_shared(),
872            dest_rect,
873            source_rect,
874            smoothing_enabled,
875            self.state.borrow().shadow_options(),
876            self.state.borrow().composition_options(),
877            self.state.borrow().transform,
878        ));
879        self.mark_as_dirty(canvas);
880        Ok(())
881    }
882
883    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage>
884    #[allow(clippy::too_many_arguments)]
885    fn draw_image_bitmap(
886        &self,
887        bitmap: &ImageBitmap,
888        canvas: Option<&HTMLCanvasElement>,
889        sx: f64,
890        sy: f64,
891        sw: Option<f64>,
892        sh: Option<f64>,
893        dx: f64,
894        dy: f64,
895        dw: Option<f64>,
896        dh: Option<f64>,
897    ) {
898        let Some(snapshot) = bitmap.bitmap_data().clone() else {
899            return;
900        };
901
902        // Step 4. Establish the source and destination rectangles.
903        let bitmap_size = snapshot.size();
904        let dw = dw.unwrap_or(bitmap_size.width as f64);
905        let dh = dh.unwrap_or(bitmap_size.height as f64);
906        let sw = sw.unwrap_or(bitmap_size.width as f64);
907        let sh = sh.unwrap_or(bitmap_size.height as f64);
908
909        let (source_rect, dest_rect) =
910            self.adjust_source_dest_rects(bitmap_size, sx, sy, sw, sh, dx, dy, dw, dh);
911
912        // Step 5. If one of the sw or sh arguments is zero, then return. Nothing is painted.
913        if !is_rect_valid(source_rect) || !is_rect_valid(dest_rect) {
914            return;
915        }
916
917        let smoothing_enabled = self.state.borrow().image_smoothing_enabled;
918
919        self.send_canvas_2d_msg(Canvas2dMsg::DrawImage(
920            snapshot.to_shared(),
921            dest_rect,
922            source_rect,
923            smoothing_enabled,
924            self.state.borrow().shadow_options(),
925            self.state.borrow().composition_options(),
926            self.state.borrow().transform,
927        ));
928
929        self.mark_as_dirty(canvas);
930    }
931
932    pub(super) fn mark_as_dirty(&self, canvas: Option<&HTMLCanvasElement>) {
933        if let Some(canvas) = canvas {
934            canvas.mark_as_dirty();
935        }
936    }
937
938    /// It is used by DrawImage to calculate the size of the source and destination rectangles based
939    /// on the drawImage call arguments
940    /// source rectangle = area of the original image to be copied
941    /// destination rectangle = area of the destination canvas where the source image is going to be drawn
942    #[allow(clippy::too_many_arguments)]
943    fn adjust_source_dest_rects(
944        &self,
945        image_size: Size2D<u32>,
946        sx: f64,
947        sy: f64,
948        sw: f64,
949        sh: f64,
950        dx: f64,
951        dy: f64,
952        dw: f64,
953        dh: f64,
954    ) -> (Rect<f64>, Rect<f64>) {
955        let image_rect = Rect::new(
956            Point2D::zero(),
957            Size2D::new(image_size.width, image_size.height),
958        );
959
960        // The source rectangle is the rectangle whose corners are the four points (sx, sy),
961        // (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).
962        let source_rect = Rect::new(
963            Point2D::new(sx.min(sx + sw), sy.min(sy + sh)),
964            Size2D::new(sw.abs(), sh.abs()),
965        );
966
967        // When the source rectangle is outside the source image,
968        // the source rectangle must be clipped to the source image
969        let source_rect_clipped = source_rect
970            .intersection(&image_rect.to_f64())
971            .unwrap_or(Rect::zero());
972
973        // Width and height ratios between the non clipped and clipped source rectangles
974        let width_ratio: f64 = source_rect_clipped.size.width / source_rect.size.width;
975        let height_ratio: f64 = source_rect_clipped.size.height / source_rect.size.height;
976
977        // When the source rectangle is outside the source image,
978        // the destination rectangle must be clipped in the same proportion.
979        let dest_rect_width_scaled: f64 = dw * width_ratio;
980        let dest_rect_height_scaled: f64 = dh * height_ratio;
981
982        // The destination rectangle is the rectangle whose corners are the four points (dx, dy),
983        // (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh).
984        let dest_rect = Rect::new(
985            Point2D::new(
986                dx.min(dx + dest_rect_width_scaled),
987                dy.min(dy + dest_rect_height_scaled),
988            ),
989            Size2D::new(dest_rect_width_scaled.abs(), dest_rect_height_scaled.abs()),
990        );
991
992        let source_rect = Rect::new(
993            Point2D::new(source_rect_clipped.origin.x, source_rect_clipped.origin.y),
994            Size2D::new(
995                source_rect_clipped.size.width,
996                source_rect_clipped.size.height,
997            ),
998        );
999
1000        (source_rect, dest_rect)
1001    }
1002
1003    fn update_transform(&self, transform: Transform2D<f64>) {
1004        let mut state = self.state.borrow_mut();
1005        self.current_default_path
1006            .borrow_mut()
1007            .transform(state.transform.cast());
1008        state.transform = transform;
1009        if let Some(inverse) = transform.inverse() {
1010            self.current_default_path
1011                .borrow_mut()
1012                .transform(inverse.cast());
1013        }
1014    }
1015
1016    // https://html.spec.whatwg.org/multipage/#dom-context-2d-fillrect
1017    pub(super) fn fill_rect(&self, x: f64, y: f64, width: f64, height: f64) {
1018        if let Some(rect) = self.create_drawable_rect(x, y, width, height) {
1019            let style = self.state.borrow().fill_style.to_fill_or_stroke_style();
1020            self.send_canvas_2d_msg(Canvas2dMsg::FillRect(
1021                rect,
1022                style,
1023                self.state.borrow().shadow_options(),
1024                self.state.borrow().composition_options(),
1025                self.state.borrow().transform,
1026            ));
1027        }
1028    }
1029
1030    // https://html.spec.whatwg.org/multipage/#dom-context-2d-clearrect
1031    pub(super) fn clear_rect(&self, x: f64, y: f64, width: f64, height: f64) {
1032        if let Some(rect) = self.create_drawable_rect(x, y, width, height) {
1033            self.send_canvas_2d_msg(Canvas2dMsg::ClearRect(rect, self.state.borrow().transform));
1034        }
1035    }
1036
1037    // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokerect
1038    pub(super) fn stroke_rect(&self, x: f64, y: f64, width: f64, height: f64) {
1039        if let Some(rect) = self.create_drawable_rect(x, y, width, height) {
1040            let style = self.state.borrow().stroke_style.to_fill_or_stroke_style();
1041            self.send_canvas_2d_msg(Canvas2dMsg::StrokeRect(
1042                rect,
1043                style,
1044                self.state.borrow().line_options(),
1045                self.state.borrow().shadow_options(),
1046                self.state.borrow().composition_options(),
1047                self.state.borrow().transform,
1048            ));
1049        }
1050    }
1051
1052    // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
1053    pub(super) fn shadow_offset_x(&self) -> f64 {
1054        self.state.borrow().shadow_offset_x
1055    }
1056
1057    // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsetx
1058    pub(super) fn set_shadow_offset_x(&self, value: f64) {
1059        if !value.is_finite() || value == self.state.borrow().shadow_offset_x {
1060            return;
1061        }
1062        self.state.borrow_mut().shadow_offset_x = value;
1063    }
1064
1065    // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
1066    pub(super) fn shadow_offset_y(&self) -> f64 {
1067        self.state.borrow().shadow_offset_y
1068    }
1069
1070    // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowoffsety
1071    pub(super) fn set_shadow_offset_y(&self, value: f64) {
1072        if !value.is_finite() || value == self.state.borrow().shadow_offset_y {
1073            return;
1074        }
1075        self.state.borrow_mut().shadow_offset_y = value;
1076    }
1077
1078    // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
1079    pub(super) fn shadow_blur(&self) -> f64 {
1080        self.state.borrow().shadow_blur
1081    }
1082
1083    // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowblur
1084    pub(super) fn set_shadow_blur(&self, value: f64) {
1085        if !value.is_finite() || value < 0f64 || value == self.state.borrow().shadow_blur {
1086            return;
1087        }
1088        self.state.borrow_mut().shadow_blur = value;
1089    }
1090
1091    // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
1092    pub(super) fn shadow_color(&self) -> DOMString {
1093        let mut result = String::new();
1094        serialize(&self.state.borrow().shadow_color, &mut result).unwrap();
1095        DOMString::from(result)
1096    }
1097
1098    // https://html.spec.whatwg.org/multipage/#dom-context-2d-shadowcolor
1099    pub(super) fn set_shadow_color(&self, canvas: Option<&HTMLCanvasElement>, value: DOMString) {
1100        if let Ok(rgba) = parse_color(canvas, &value) {
1101            self.state.borrow_mut().shadow_color = rgba;
1102        }
1103    }
1104
1105    // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
1106    pub(super) fn stroke_style(&self) -> StringOrCanvasGradientOrCanvasPattern {
1107        match self.state.borrow().stroke_style {
1108            CanvasFillOrStrokeStyle::Color(ref rgba) => {
1109                let mut result = String::new();
1110                serialize(rgba, &mut result).unwrap();
1111                StringOrCanvasGradientOrCanvasPattern::String(DOMString::from(result))
1112            },
1113            CanvasFillOrStrokeStyle::Gradient(ref gradient) => {
1114                StringOrCanvasGradientOrCanvasPattern::CanvasGradient(DomRoot::from_ref(gradient))
1115            },
1116            CanvasFillOrStrokeStyle::Pattern(ref pattern) => {
1117                StringOrCanvasGradientOrCanvasPattern::CanvasPattern(DomRoot::from_ref(pattern))
1118            },
1119        }
1120    }
1121
1122    // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
1123    pub(super) fn set_stroke_style(
1124        &self,
1125        canvas: Option<&HTMLCanvasElement>,
1126        value: StringOrCanvasGradientOrCanvasPattern,
1127    ) {
1128        match value {
1129            StringOrCanvasGradientOrCanvasPattern::String(string) => {
1130                if let Ok(rgba) = parse_color(canvas, &string) {
1131                    self.state.borrow_mut().stroke_style = CanvasFillOrStrokeStyle::Color(rgba);
1132                }
1133            },
1134            StringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => {
1135                self.state.borrow_mut().stroke_style =
1136                    CanvasFillOrStrokeStyle::Gradient(Dom::from_ref(&*gradient));
1137            },
1138            StringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => {
1139                self.state.borrow_mut().stroke_style =
1140                    CanvasFillOrStrokeStyle::Pattern(Dom::from_ref(&*pattern));
1141                if !pattern.origin_is_clean() {
1142                    self.set_origin_clean(false);
1143                }
1144            },
1145        }
1146    }
1147
1148    // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
1149    pub(super) fn fill_style(&self) -> StringOrCanvasGradientOrCanvasPattern {
1150        match self.state.borrow().fill_style {
1151            CanvasFillOrStrokeStyle::Color(ref rgba) => {
1152                let mut result = String::new();
1153                serialize(rgba, &mut result).unwrap();
1154                StringOrCanvasGradientOrCanvasPattern::String(DOMString::from(result))
1155            },
1156            CanvasFillOrStrokeStyle::Gradient(ref gradient) => {
1157                StringOrCanvasGradientOrCanvasPattern::CanvasGradient(DomRoot::from_ref(gradient))
1158            },
1159            CanvasFillOrStrokeStyle::Pattern(ref pattern) => {
1160                StringOrCanvasGradientOrCanvasPattern::CanvasPattern(DomRoot::from_ref(pattern))
1161            },
1162        }
1163    }
1164
1165    // https://html.spec.whatwg.org/multipage/#dom-context-2d-strokestyle
1166    pub(super) fn set_fill_style(
1167        &self,
1168        canvas: Option<&HTMLCanvasElement>,
1169        value: StringOrCanvasGradientOrCanvasPattern,
1170    ) {
1171        match value {
1172            StringOrCanvasGradientOrCanvasPattern::String(string) => {
1173                if let Ok(rgba) = parse_color(canvas, &string) {
1174                    self.state.borrow_mut().fill_style = CanvasFillOrStrokeStyle::Color(rgba);
1175                }
1176            },
1177            StringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => {
1178                self.state.borrow_mut().fill_style =
1179                    CanvasFillOrStrokeStyle::Gradient(Dom::from_ref(&*gradient));
1180            },
1181            StringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => {
1182                self.state.borrow_mut().fill_style =
1183                    CanvasFillOrStrokeStyle::Pattern(Dom::from_ref(&*pattern));
1184                if !pattern.origin_is_clean() {
1185                    self.set_origin_clean(false);
1186                }
1187            },
1188        }
1189    }
1190
1191    // https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient
1192    pub(super) fn create_linear_gradient(
1193        &self,
1194        global: &GlobalScope,
1195        x0: Finite<f64>,
1196        y0: Finite<f64>,
1197        x1: Finite<f64>,
1198        y1: Finite<f64>,
1199        can_gc: CanGc,
1200    ) -> DomRoot<CanvasGradient> {
1201        CanvasGradient::new(
1202            global,
1203            CanvasGradientStyle::Linear(LinearGradientStyle::new(*x0, *y0, *x1, *y1, Vec::new())),
1204            can_gc,
1205        )
1206    }
1207
1208    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-createradialgradient>
1209    #[allow(clippy::too_many_arguments)]
1210    pub(super) fn create_radial_gradient(
1211        &self,
1212        global: &GlobalScope,
1213        x0: Finite<f64>,
1214        y0: Finite<f64>,
1215        r0: Finite<f64>,
1216        x1: Finite<f64>,
1217        y1: Finite<f64>,
1218        r1: Finite<f64>,
1219        can_gc: CanGc,
1220    ) -> Fallible<DomRoot<CanvasGradient>> {
1221        if *r0 < 0. || *r1 < 0. {
1222            return Err(Error::IndexSize(None));
1223        }
1224
1225        Ok(CanvasGradient::new(
1226            global,
1227            CanvasGradientStyle::Radial(RadialGradientStyle::new(
1228                *x0,
1229                *y0,
1230                *r0,
1231                *x1,
1232                *y1,
1233                *r1,
1234                Vec::new(),
1235            )),
1236            can_gc,
1237        ))
1238    }
1239
1240    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-createpattern>
1241    pub(super) fn create_pattern(
1242        &self,
1243        global: &GlobalScope,
1244        image: CanvasImageSource,
1245        mut repetition: DOMString,
1246        can_gc: CanGc,
1247    ) -> Fallible<Option<DomRoot<CanvasPattern>>> {
1248        let snapshot = match image {
1249            CanvasImageSource::HTMLImageElement(ref image) => {
1250                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
1251                if !image.is_usable()? {
1252                    return Ok(None);
1253                }
1254
1255                image
1256                    .get_raster_image_data()
1257                    .ok_or(Error::InvalidState(None))?
1258            },
1259            CanvasImageSource::HTMLVideoElement(ref video) => {
1260                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
1261                if !video.is_usable() {
1262                    return Ok(None);
1263                }
1264
1265                video
1266                    .get_current_frame_data()
1267                    .ok_or(Error::InvalidState(None))?
1268            },
1269            CanvasImageSource::HTMLCanvasElement(ref canvas) => {
1270                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
1271                if canvas.get_size().is_empty() {
1272                    return Err(Error::InvalidState(None));
1273                }
1274
1275                canvas.get_image_data().ok_or(Error::InvalidState(None))?
1276            },
1277            CanvasImageSource::ImageBitmap(ref bitmap) => {
1278                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
1279                if bitmap.is_detached() {
1280                    return Err(Error::InvalidState(None));
1281                }
1282
1283                bitmap
1284                    .bitmap_data()
1285                    .clone()
1286                    .ok_or(Error::InvalidState(None))?
1287            },
1288            CanvasImageSource::OffscreenCanvas(ref canvas) => {
1289                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
1290                if canvas.get_size().is_empty() {
1291                    return Err(Error::InvalidState(None));
1292                }
1293
1294                canvas.get_image_data().ok_or(Error::InvalidState(None))?
1295            },
1296            CanvasImageSource::CSSStyleValue(ref value) => value
1297                .get_url(self.base_url.clone())
1298                .and_then(|url| self.fetch_image_data(url, None))
1299                .ok_or(Error::InvalidState(None))?,
1300        };
1301
1302        if repetition.is_empty() {
1303            repetition.push_str("repeat");
1304        }
1305
1306        if let Ok(rep) = RepetitionStyle::from_str(&repetition.str()) {
1307            let size = snapshot.size();
1308            Ok(Some(CanvasPattern::new(
1309                global,
1310                snapshot,
1311                size.cast(),
1312                rep,
1313                self.is_origin_clean(image),
1314                can_gc,
1315            )))
1316        } else {
1317            Err(Error::Syntax(None))
1318        }
1319    }
1320
1321    // https://html.spec.whatwg.org/multipage/#dom-context-2d-save
1322    pub(super) fn save(&self) {
1323        self.saved_states
1324            .borrow_mut()
1325            .push(self.state.borrow().clone());
1326    }
1327
1328    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
1329    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-restore>
1330    pub(super) fn restore(&self) {
1331        let mut saved_states = self.saved_states.borrow_mut();
1332        if let Some(state) = saved_states.pop() {
1333            let clips_to_pop = self.state.borrow().clips_pushed;
1334            if clips_to_pop != 0 {
1335                self.send_canvas_2d_msg(Canvas2dMsg::PopClips(clips_to_pop));
1336            }
1337            self.state.borrow_mut().clone_from(&state);
1338        }
1339    }
1340
1341    // https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
1342    pub(super) fn global_alpha(&self) -> f64 {
1343        self.state.borrow().global_alpha
1344    }
1345
1346    // https://html.spec.whatwg.org/multipage/#dom-context-2d-globalalpha
1347    pub(super) fn set_global_alpha(&self, alpha: f64) {
1348        if !alpha.is_finite() || !(0.0..=1.0).contains(&alpha) {
1349            return;
1350        }
1351
1352        self.state.borrow_mut().global_alpha = alpha;
1353    }
1354
1355    // https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
1356    pub(super) fn global_composite_operation(&self) -> DOMString {
1357        match self.state.borrow().global_composition {
1358            CompositionOrBlending::Composition(op) => DOMString::from(op.to_string()),
1359            CompositionOrBlending::Blending(op) => DOMString::from(op.to_string()),
1360        }
1361    }
1362
1363    // https://html.spec.whatwg.org/multipage/#dom-context-2d-globalcompositeoperation
1364    pub(super) fn set_global_composite_operation(&self, op_str: DOMString) {
1365        if let Ok(op) = CompositionOrBlending::from_str(&op_str.str()) {
1366            self.state.borrow_mut().global_composition = op;
1367        }
1368    }
1369
1370    // https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
1371    pub(super) fn image_smoothing_enabled(&self) -> bool {
1372        self.state.borrow().image_smoothing_enabled
1373    }
1374
1375    // https://html.spec.whatwg.org/multipage/#dom-context-2d-imagesmoothingenabled
1376    pub(super) fn set_image_smoothing_enabled(&self, value: bool) {
1377        self.state.borrow_mut().image_smoothing_enabled = value;
1378    }
1379
1380    // https://html.spec.whatwg.org/multipage/#dom-context-2d-filltext
1381    pub(super) fn fill_text(
1382        &self,
1383        global_scope: &GlobalScope,
1384        canvas: Option<&HTMLCanvasElement>,
1385        text: DOMString,
1386        x: f64,
1387        y: f64,
1388        max_width: Option<f64>,
1389    ) {
1390        // Step 1: If any of the arguments are infinite or NaN, then return.
1391        if !x.is_finite() ||
1392            !y.is_finite() ||
1393            max_width.is_some_and(|max_width| !max_width.is_finite())
1394        {
1395            return;
1396        }
1397
1398        if self.state.borrow().font_style.is_none() {
1399            self.set_font(canvas, CanvasContextState::DEFAULT_FONT_STYLE.into())
1400        }
1401        // This may be `None` if if this is offscreen canvas, in which case just use
1402        // the initial values for the text style.
1403        let size = self.font_style().font_size.computed_size().px() as f64;
1404
1405        let Some((bounds, text_run)) = self.text_with_size(
1406            global_scope,
1407            &text.str(),
1408            Point2D::new(x, y),
1409            size,
1410            max_width,
1411        ) else {
1412            return;
1413        };
1414        self.send_canvas_2d_msg(Canvas2dMsg::FillText(
1415            bounds,
1416            text_run,
1417            self.state.borrow().fill_style.to_fill_or_stroke_style(),
1418            self.state.borrow().shadow_options(),
1419            self.state.borrow().composition_options(),
1420            self.state.borrow().transform,
1421        ));
1422    }
1423
1424    // https://html.spec.whatwg.org/multipage/#dom-context-2d-stroketext
1425    pub(super) fn stroke_text(
1426        &self,
1427        global_scope: &GlobalScope,
1428        canvas: Option<&HTMLCanvasElement>,
1429        text: DOMString,
1430        x: f64,
1431        y: f64,
1432        max_width: Option<f64>,
1433    ) {
1434        // Step 1: If any of the arguments are infinite or NaN, then return.
1435        if !x.is_finite() ||
1436            !y.is_finite() ||
1437            max_width.is_some_and(|max_width| !max_width.is_finite())
1438        {
1439            return;
1440        }
1441
1442        if self.state.borrow().font_style.is_none() {
1443            self.set_font(canvas, CanvasContextState::DEFAULT_FONT_STYLE.into())
1444        }
1445        // This may be `None` if if this is offscreen canvas, in which case just use
1446        // the initial values for the text style.
1447        let size = self.font_style().font_size.computed_size().px() as f64;
1448
1449        let Some((bounds, text_run)) = self.text_with_size(
1450            global_scope,
1451            &text.str(),
1452            Point2D::new(x, y),
1453            size,
1454            max_width,
1455        ) else {
1456            return;
1457        };
1458        self.send_canvas_2d_msg(Canvas2dMsg::StrokeText(
1459            bounds,
1460            text_run,
1461            self.state.borrow().stroke_style.to_fill_or_stroke_style(),
1462            self.state.borrow().line_options(),
1463            self.state.borrow().shadow_options(),
1464            self.state.borrow().composition_options(),
1465            self.state.borrow().transform,
1466        ));
1467    }
1468
1469    /// <https://html.spec.whatwg.org/multipage/#text-preparation-algorithm>
1470    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-measuretext>
1471    /// <https://html.spec.whatwg.org/multipage/#textmetrics>
1472    pub(super) fn measure_text(
1473        &self,
1474        global: &GlobalScope,
1475        canvas: Option<&HTMLCanvasElement>,
1476        text: DOMString,
1477        can_gc: CanGc,
1478    ) -> DomRoot<TextMetrics> {
1479        // > Step 1: If maxWidth was provided but is less than or equal to zero or equal to NaN, then return an empty array.0
1480        // Max width is not provided for `measureText()`.
1481
1482        // > Step 2: Replace all ASCII whitespace in text with U+0020 SPACE characters.
1483        let text = replace_ascii_whitespace(&text.str());
1484
1485        // > Step 3: Let font be the current font of target, as given by that object's font
1486        // > attribute.
1487        if self.state.borrow().font_style.is_none() {
1488            self.set_font(canvas, CanvasContextState::DEFAULT_FONT_STYLE.into());
1489        }
1490
1491        let Some(font_context) = global.font_context() else {
1492            warn!("Tried to paint to a canvas of GlobalScope without a FontContext.");
1493            return TextMetrics::default(global, can_gc);
1494        };
1495
1496        let font_style = self.font_style();
1497        let font_group = font_context.font_group(font_style.clone());
1498        let mut font_group = font_group.write();
1499        let font = font_group.first(font_context).expect("couldn't find font");
1500        let ascent = font.metrics.ascent.to_f64_px();
1501        let descent = font.metrics.descent.to_f64_px();
1502        let runs = self.build_unshaped_text_runs(font_context, &text, &mut font_group);
1503
1504        let mut total_advance = 0.0;
1505        let shaped_runs: Vec<_> = runs
1506            .into_iter()
1507            .filter_map(|unshaped_text_run| {
1508                let text_run = unshaped_text_run.into_shaped_text_run(total_advance)?;
1509                total_advance += text_run.advance;
1510                Some(text_run)
1511            })
1512            .collect();
1513
1514        let bounding_box = shaped_runs
1515            .iter()
1516            .map(|text_run| text_run.bounds)
1517            .reduce(|a, b| a.union(&b))
1518            .unwrap_or_default();
1519
1520        let baseline = font.baseline().unwrap_or_else(|| FontBaseline {
1521            hanging_baseline: (ascent * HANGING_BASELINE_DEFAULT) as f32,
1522            ideographic_baseline: (-descent * IDEOGRAPHIC_BASELINE_DEFAULT) as f32,
1523            alphabetic_baseline: 0.,
1524        });
1525        let ideographic_baseline = baseline.ideographic_baseline as f64;
1526        let alphabetic_baseline = baseline.alphabetic_baseline as f64;
1527        let hanging_baseline = baseline.hanging_baseline as f64;
1528
1529        let state = self.state.borrow();
1530        let anchor_x = match state.text_align {
1531            CanvasTextAlign::End => total_advance,
1532            CanvasTextAlign::Center => total_advance / 2.,
1533            CanvasTextAlign::Right => total_advance,
1534            _ => 0.,
1535        } as f64;
1536        let anchor_y = match state.text_baseline {
1537            CanvasTextBaseline::Top => ascent,
1538            CanvasTextBaseline::Hanging => hanging_baseline,
1539            CanvasTextBaseline::Ideographic => ideographic_baseline,
1540            CanvasTextBaseline::Middle => (ascent - descent) / 2.,
1541            CanvasTextBaseline::Alphabetic => alphabetic_baseline,
1542            CanvasTextBaseline::Bottom => -descent,
1543        };
1544
1545        TextMetrics::new(
1546            global,
1547            total_advance as f64,
1548            anchor_x - bounding_box.min_x(),
1549            bounding_box.max_x() - anchor_x,
1550            bounding_box.max_y() - anchor_y,
1551            anchor_y - bounding_box.min_y(),
1552            ascent - anchor_y,
1553            descent + anchor_y,
1554            ascent - anchor_y,
1555            descent + anchor_y,
1556            hanging_baseline - anchor_y,
1557            alphabetic_baseline - anchor_y,
1558            ideographic_baseline - anchor_y,
1559            can_gc,
1560        )
1561    }
1562
1563    // https://html.spec.whatwg.org/multipage/#dom-context-2d-font
1564    pub(super) fn set_font(&self, canvas: Option<&HTMLCanvasElement>, value: DOMString) {
1565        let canvas = match canvas {
1566            Some(element) => element,
1567            None => return, // offscreen canvas doesn't have a placeholder canvas
1568        };
1569        let node = canvas.upcast::<Node>();
1570        let window = canvas.owner_window();
1571
1572        let Some(resolved_font_style) = window.resolved_font_style_query(node, value.to_string())
1573        else {
1574            // This will happen when there is a syntax error.
1575            return;
1576        };
1577        self.state.borrow_mut().font_style = Some(resolved_font_style);
1578    }
1579
1580    fn font_style(&self) -> ServoArc<Font> {
1581        self.state
1582            .borrow()
1583            .font_style
1584            .clone()
1585            .unwrap_or_else(|| ServoArc::new(Font::initial_values()))
1586    }
1587
1588    // https://html.spec.whatwg.org/multipage/#dom-context-2d-font
1589    pub(super) fn font(&self) -> DOMString {
1590        self.state.borrow().font_style.as_ref().map_or_else(
1591            || CanvasContextState::DEFAULT_FONT_STYLE.into(),
1592            |style| {
1593                let mut result = String::new();
1594                serialize_font(style, &mut result).unwrap();
1595                DOMString::from(result)
1596            },
1597        )
1598    }
1599
1600    // https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign
1601    pub(super) fn text_align(&self) -> CanvasTextAlign {
1602        self.state.borrow().text_align
1603    }
1604
1605    // https://html.spec.whatwg.org/multipage/#dom-context-2d-textalign
1606    pub(super) fn set_text_align(&self, value: CanvasTextAlign) {
1607        self.state.borrow_mut().text_align = value;
1608    }
1609
1610    pub(super) fn text_baseline(&self) -> CanvasTextBaseline {
1611        self.state.borrow().text_baseline
1612    }
1613
1614    pub(super) fn set_text_baseline(&self, value: CanvasTextBaseline) {
1615        self.state.borrow_mut().text_baseline = value;
1616    }
1617
1618    // https://html.spec.whatwg.org/multipage/#dom-context-2d-direction
1619    pub(super) fn direction(&self) -> CanvasDirection {
1620        self.state.borrow().direction
1621    }
1622
1623    // https://html.spec.whatwg.org/multipage/#dom-context-2d-direction
1624    pub(super) fn set_direction(&self, value: CanvasDirection) {
1625        self.state.borrow_mut().direction = value;
1626    }
1627
1628    // https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
1629    pub(super) fn line_width(&self) -> f64 {
1630        self.state.borrow().line_width
1631    }
1632
1633    // https://html.spec.whatwg.org/multipage/#dom-context-2d-linewidth
1634    pub(super) fn set_line_width(&self, width: f64) {
1635        if !width.is_finite() || width <= 0.0 {
1636            return;
1637        }
1638
1639        self.state.borrow_mut().line_width = width;
1640    }
1641
1642    // https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
1643    pub(super) fn line_cap(&self) -> CanvasLineCap {
1644        match self.state.borrow().line_cap {
1645            LineCapStyle::Butt => CanvasLineCap::Butt,
1646            LineCapStyle::Round => CanvasLineCap::Round,
1647            LineCapStyle::Square => CanvasLineCap::Square,
1648        }
1649    }
1650
1651    // https://html.spec.whatwg.org/multipage/#dom-context-2d-linecap
1652    pub(super) fn set_line_cap(&self, cap: CanvasLineCap) {
1653        let line_cap = match cap {
1654            CanvasLineCap::Butt => LineCapStyle::Butt,
1655            CanvasLineCap::Round => LineCapStyle::Round,
1656            CanvasLineCap::Square => LineCapStyle::Square,
1657        };
1658        self.state.borrow_mut().line_cap = line_cap;
1659    }
1660
1661    // https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
1662    pub(super) fn line_join(&self) -> CanvasLineJoin {
1663        match self.state.borrow().line_join {
1664            LineJoinStyle::Round => CanvasLineJoin::Round,
1665            LineJoinStyle::Bevel => CanvasLineJoin::Bevel,
1666            LineJoinStyle::Miter => CanvasLineJoin::Miter,
1667        }
1668    }
1669
1670    // https://html.spec.whatwg.org/multipage/#dom-context-2d-linejoin
1671    pub(super) fn set_line_join(&self, join: CanvasLineJoin) {
1672        let line_join = match join {
1673            CanvasLineJoin::Round => LineJoinStyle::Round,
1674            CanvasLineJoin::Bevel => LineJoinStyle::Bevel,
1675            CanvasLineJoin::Miter => LineJoinStyle::Miter,
1676        };
1677        self.state.borrow_mut().line_join = line_join;
1678    }
1679
1680    // https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
1681    pub(super) fn miter_limit(&self) -> f64 {
1682        self.state.borrow().miter_limit
1683    }
1684
1685    // https://html.spec.whatwg.org/multipage/#dom-context-2d-miterlimit
1686    pub(super) fn set_miter_limit(&self, limit: f64) {
1687        if !limit.is_finite() || limit <= 0.0 {
1688            return;
1689        }
1690
1691        self.state.borrow_mut().miter_limit = limit;
1692    }
1693
1694    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-getlinedash>
1695    pub(super) fn line_dash(&self) -> Vec<f64> {
1696        // > return a sequence whose values are the values of
1697        // > the object's dash list, in the same order.
1698        self.state.borrow().line_dash.clone()
1699    }
1700
1701    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-setlinedash>
1702    pub(super) fn set_line_dash(&self, segments: Vec<f64>) {
1703        // > If any value in segments is not finite (e.g. an Infinity or a NaN value),
1704        // > or if any value is negative (less than zero), then return (without throwing
1705        // > an exception; user agents could show a message on a developer console,
1706        // > though, as that would be helpful for debugging).
1707        if segments
1708            .iter()
1709            .any(|segment| !segment.is_finite() || *segment < 0.0)
1710        {
1711            return;
1712        }
1713
1714        // > If the number of elements in segments is odd, then let segments
1715        // > be the concatenation of two copies of segments.
1716        let mut line_dash: Vec<_> = segments.clone();
1717        if segments.len() & 1 == 1 {
1718            line_dash.extend(line_dash.clone());
1719        }
1720
1721        // > Let the object's dash list be segments.
1722        self.state.borrow_mut().line_dash = line_dash.clone();
1723    }
1724
1725    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset>
1726    pub(super) fn line_dash_offset(&self) -> f64 {
1727        // > On getting, it must return the current value.
1728        self.state.borrow().line_dash_offset
1729    }
1730
1731    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-linedashoffset?
1732    pub(super) fn set_line_dash_offset(&self, offset: f64) {
1733        // > On setting, infinite and NaN values must be ignored,
1734        // > leaving the value unchanged;
1735        if !offset.is_finite() {
1736            return;
1737        }
1738
1739        // > other values must change the current value to the new value.
1740        self.state.borrow_mut().line_dash_offset = offset;
1741    }
1742
1743    // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
1744    pub(super) fn create_image_data(
1745        &self,
1746        global: &GlobalScope,
1747        sw: i32,
1748        sh: i32,
1749        can_gc: CanGc,
1750    ) -> Fallible<DomRoot<ImageData>> {
1751        if sw == 0 || sh == 0 {
1752            return Err(Error::IndexSize(None));
1753        }
1754        ImageData::new(global, sw.unsigned_abs(), sh.unsigned_abs(), None, can_gc)
1755    }
1756
1757    // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
1758    pub(super) fn create_image_data_(
1759        &self,
1760        global: &GlobalScope,
1761        imagedata: &ImageData,
1762        can_gc: CanGc,
1763    ) -> Fallible<DomRoot<ImageData>> {
1764        ImageData::new(global, imagedata.Width(), imagedata.Height(), None, can_gc)
1765    }
1766
1767    // https://html.spec.whatwg.org/multipage/#dom-context-2d-getimagedata
1768    #[allow(clippy::too_many_arguments)]
1769    pub(super) fn get_image_data(
1770        &self,
1771        canvas_size: Size2D<u32>,
1772        global: &GlobalScope,
1773        sx: i32,
1774        sy: i32,
1775        sw: i32,
1776        sh: i32,
1777        can_gc: CanGc,
1778    ) -> Fallible<DomRoot<ImageData>> {
1779        // FIXME(nox): There are many arithmetic operations here that can
1780        // overflow or underflow, this should probably be audited.
1781
1782        if sw == 0 || sh == 0 {
1783            return Err(Error::IndexSize(None));
1784        }
1785
1786        if !self.origin_is_clean() {
1787            return Err(Error::Security);
1788        }
1789
1790        let (origin, size) = adjust_size_sign(Point2D::new(sx, sy), Size2D::new(sw, sh));
1791        let read_rect = match pixels::clip(origin, size.to_u32(), canvas_size) {
1792            Some(rect) => rect,
1793            None => {
1794                // All the pixels are outside the canvas surface.
1795                return ImageData::new(global, size.width, size.height, None, can_gc);
1796            },
1797        };
1798
1799        let data = if self.is_paintable() {
1800            let (sender, receiver) = ipc::channel().unwrap();
1801            self.send_canvas_2d_msg(Canvas2dMsg::GetImageData(Some(read_rect), sender));
1802
1803            let mut snapshot = receiver.recv().unwrap().to_owned();
1804            snapshot.transform(
1805                SnapshotAlphaMode::Transparent {
1806                    premultiplied: false,
1807                },
1808                SnapshotPixelFormat::RGBA,
1809            );
1810            Some(snapshot.into())
1811        } else {
1812            None
1813        };
1814
1815        ImageData::new(global, size.width, size.height, data, can_gc)
1816    }
1817
1818    // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
1819    pub(super) fn put_image_data(
1820        &self,
1821        canvas_size: Size2D<u32>,
1822        imagedata: &ImageData,
1823        dx: i32,
1824        dy: i32,
1825    ) {
1826        self.put_image_data_(
1827            canvas_size,
1828            imagedata,
1829            dx,
1830            dy,
1831            0,
1832            0,
1833            imagedata.Width() as i32,
1834            imagedata.Height() as i32,
1835        )
1836    }
1837
1838    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata>
1839    #[allow(unsafe_code, clippy::too_many_arguments)]
1840    pub(super) fn put_image_data_(
1841        &self,
1842        canvas_size: Size2D<u32>,
1843        imagedata: &ImageData,
1844        dx: i32,
1845        dy: i32,
1846        dirty_x: i32,
1847        dirty_y: i32,
1848        dirty_width: i32,
1849        dirty_height: i32,
1850    ) {
1851        if !self.is_paintable() {
1852            return;
1853        }
1854
1855        // FIXME(nox): There are many arithmetic operations here that can
1856        // overflow or underflow, this should probably be audited.
1857
1858        let imagedata_size = Size2D::new(imagedata.Width(), imagedata.Height());
1859        if imagedata_size.area() == 0 {
1860            return;
1861        }
1862
1863        // Step 1.
1864        // Done later.
1865
1866        // Step 2.
1867        // TODO: throw InvalidState if buffer is detached.
1868
1869        // Steps 3-6.
1870        let (src_origin, src_size) = adjust_size_sign(
1871            Point2D::new(dirty_x, dirty_y),
1872            Size2D::new(dirty_width, dirty_height),
1873        );
1874        let src_rect = match pixels::clip(src_origin, src_size.to_u32(), imagedata_size.to_u32()) {
1875            Some(rect) => rect,
1876            None => return,
1877        };
1878        let (dst_origin, _) = adjust_size_sign(
1879            Point2D::new(dirty_x.saturating_add(dx), dirty_y.saturating_add(dy)),
1880            Size2D::new(dirty_width, dirty_height),
1881        );
1882        // By clipping to the canvas surface, we avoid sending any pixel
1883        // that would fall outside it.
1884        let dst_rect = match pixels::clip(dst_origin, src_rect.size, canvas_size) {
1885            Some(rect) => rect,
1886            None => return,
1887        };
1888
1889        // Step 7.
1890        let snapshot = imagedata.get_snapshot_rect(Rect::new(src_rect.origin, dst_rect.size));
1891        self.send_canvas_2d_msg(Canvas2dMsg::PutImageData(dst_rect, snapshot.to_shared()));
1892    }
1893
1894    // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
1895    pub(super) fn draw_image(
1896        &self,
1897        canvas: Option<&HTMLCanvasElement>,
1898        image: CanvasImageSource,
1899        dx: f64,
1900        dy: f64,
1901    ) -> ErrorResult {
1902        if !(dx.is_finite() && dy.is_finite()) {
1903            return Ok(());
1904        }
1905
1906        self.draw_image_internal(canvas, image, 0f64, 0f64, None, None, dx, dy, None, None)
1907    }
1908
1909    // https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage
1910    pub(super) fn draw_image_(
1911        &self,
1912        canvas: Option<&HTMLCanvasElement>,
1913        image: CanvasImageSource,
1914        dx: f64,
1915        dy: f64,
1916        dw: f64,
1917        dh: f64,
1918    ) -> ErrorResult {
1919        if !(dx.is_finite() && dy.is_finite() && dw.is_finite() && dh.is_finite()) {
1920            return Ok(());
1921        }
1922
1923        self.draw_image_internal(
1924            canvas,
1925            image,
1926            0f64,
1927            0f64,
1928            None,
1929            None,
1930            dx,
1931            dy,
1932            Some(dw),
1933            Some(dh),
1934        )
1935    }
1936
1937    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-drawimage>
1938    #[allow(clippy::too_many_arguments)]
1939    pub(super) fn draw_image__(
1940        &self,
1941        canvas: Option<&HTMLCanvasElement>,
1942        image: CanvasImageSource,
1943        sx: f64,
1944        sy: f64,
1945        sw: f64,
1946        sh: f64,
1947        dx: f64,
1948        dy: f64,
1949        dw: f64,
1950        dh: f64,
1951    ) -> ErrorResult {
1952        if !(sx.is_finite() &&
1953            sy.is_finite() &&
1954            sw.is_finite() &&
1955            sh.is_finite() &&
1956            dx.is_finite() &&
1957            dy.is_finite() &&
1958            dw.is_finite() &&
1959            dh.is_finite())
1960        {
1961            return Ok(());
1962        }
1963
1964        self.draw_image_internal(
1965            canvas,
1966            image,
1967            sx,
1968            sy,
1969            Some(sw),
1970            Some(sh),
1971            dx,
1972            dy,
1973            Some(dw),
1974            Some(dh),
1975        )
1976    }
1977
1978    // https://html.spec.whatwg.org/multipage/#dom-context-2d-beginpath
1979    pub(super) fn begin_path(&self) {
1980        *self.current_default_path.borrow_mut() = Path::new();
1981    }
1982
1983    // https://html.spec.whatwg.org/multipage/#dom-context-2d-fill
1984    pub(super) fn fill(&self, fill_rule: CanvasFillRule) {
1985        let path = self.current_default_path.borrow().clone();
1986        self.fill_(path, fill_rule);
1987    }
1988
1989    // https://html.spec.whatwg.org/multipage/#dom-context-2d-fill
1990    pub(super) fn fill_(&self, path: Path, fill_rule: CanvasFillRule) {
1991        let style = self.state.borrow().fill_style.to_fill_or_stroke_style();
1992        self.send_canvas_2d_msg(Canvas2dMsg::FillPath(
1993            style,
1994            path,
1995            fill_rule.convert(),
1996            self.state.borrow().shadow_options(),
1997            self.state.borrow().composition_options(),
1998            self.state.borrow().transform,
1999        ));
2000    }
2001
2002    // https://html.spec.whatwg.org/multipage/#dom-context-2d-stroke
2003    pub(super) fn stroke(&self) {
2004        let path = self.current_default_path.borrow().clone();
2005        self.stroke_(path);
2006    }
2007
2008    pub(super) fn stroke_(&self, path: Path) {
2009        let style = self.state.borrow().stroke_style.to_fill_or_stroke_style();
2010        self.send_canvas_2d_msg(Canvas2dMsg::StrokePath(
2011            path,
2012            style,
2013            self.state.borrow().line_options(),
2014            self.state.borrow().shadow_options(),
2015            self.state.borrow().composition_options(),
2016            self.state.borrow().transform,
2017        ));
2018    }
2019
2020    // https://html.spec.whatwg.org/multipage/#dom-context-2d-clip
2021    pub(super) fn clip(&self, fill_rule: CanvasFillRule) {
2022        let path = self.current_default_path.borrow().clone();
2023        self.clip_(path, fill_rule);
2024    }
2025
2026    // https://html.spec.whatwg.org/multipage/#dom-context-2d-clip
2027    pub(super) fn clip_(&self, path: Path, fill_rule: CanvasFillRule) {
2028        self.state.borrow_mut().clips_pushed += 1;
2029        self.send_canvas_2d_msg(Canvas2dMsg::ClipPath(
2030            path,
2031            fill_rule.convert(),
2032            self.state.borrow().transform,
2033        ));
2034    }
2035
2036    // https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath
2037    pub(super) fn is_point_in_path(
2038        &self,
2039        global: &GlobalScope,
2040        x: f64,
2041        y: f64,
2042        fill_rule: CanvasFillRule,
2043    ) -> bool {
2044        let mut path = self.current_default_path.borrow().clone();
2045        path.transform(self.state.borrow().transform.cast());
2046        self.is_point_in_path_(global, path, x, y, fill_rule)
2047    }
2048
2049    // https://html.spec.whatwg.org/multipage/#dom-context-2d-ispointinpath
2050    pub(super) fn is_point_in_path_(
2051        &self,
2052        _global: &GlobalScope,
2053        path: Path,
2054        x: f64,
2055        y: f64,
2056        fill_rule: CanvasFillRule,
2057    ) -> bool {
2058        let fill_rule = match fill_rule {
2059            CanvasFillRule::Nonzero => FillRule::Nonzero,
2060            CanvasFillRule::Evenodd => FillRule::Evenodd,
2061        };
2062        path.is_point_in_path(x, y, fill_rule)
2063    }
2064
2065    // https://html.spec.whatwg.org/multipage/#dom-context-2d-scale
2066    pub(super) fn scale(&self, x: f64, y: f64) {
2067        if !(x.is_finite() && y.is_finite()) {
2068            return;
2069        }
2070
2071        let transform = self.state.borrow().transform;
2072        self.update_transform(transform.pre_scale(x, y))
2073    }
2074
2075    // https://html.spec.whatwg.org/multipage/#dom-context-2d-rotate
2076    pub(super) fn rotate(&self, angle: f64) {
2077        if angle == 0.0 || !angle.is_finite() {
2078            return;
2079        }
2080
2081        let (sin, cos) = (angle.sin(), angle.cos());
2082        let transform = self.state.borrow().transform;
2083        self.update_transform(Transform2D::new(cos, sin, -sin, cos, 0.0, 0.0).then(&transform))
2084    }
2085
2086    // https://html.spec.whatwg.org/multipage/#dom-context-2d-translate
2087    pub(super) fn translate(&self, x: f64, y: f64) {
2088        if !(x.is_finite() && y.is_finite()) {
2089            return;
2090        }
2091
2092        let transform = self.state.borrow().transform;
2093        self.update_transform(transform.pre_translate(vec2(x, y)))
2094    }
2095
2096    // https://html.spec.whatwg.org/multipage/#dom-context-2d-transform
2097    pub(super) fn transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
2098        if !(a.is_finite() &&
2099            b.is_finite() &&
2100            c.is_finite() &&
2101            d.is_finite() &&
2102            e.is_finite() &&
2103            f.is_finite())
2104        {
2105            return;
2106        }
2107
2108        let transform = self.state.borrow().transform;
2109        self.update_transform(Transform2D::new(a, b, c, d, e, f).then(&transform))
2110    }
2111
2112    // https://html.spec.whatwg.org/multipage/#dom-context-2d-gettransform
2113    pub(super) fn get_transform(&self, global: &GlobalScope, can_gc: CanGc) -> DomRoot<DOMMatrix> {
2114        let transform = self.state.borrow_mut().transform;
2115        DOMMatrix::new(global, true, transform.to_3d(), can_gc)
2116    }
2117
2118    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform>
2119    pub(super) fn set_transform(&self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) {
2120        // Step 1. If any of the arguments are infinite or NaN, then return.
2121        if !a.is_finite() ||
2122            !b.is_finite() ||
2123            !c.is_finite() ||
2124            !d.is_finite() ||
2125            !e.is_finite() ||
2126            !f.is_finite()
2127        {
2128            return;
2129        }
2130
2131        // Step 2. Reset the current transformation matrix to the matrix described by:
2132        self.update_transform(Transform2D::new(a, b, c, d, e, f))
2133    }
2134
2135    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-settransform-matrix>
2136    pub(super) fn set_transform_(&self, transform: &DOMMatrix2DInit) -> ErrorResult {
2137        // Step 1. Let matrix be the result of creating a DOMMatrix from the 2D
2138        // dictionary transform.
2139        let matrix = dommatrix2dinit_to_matrix(transform)?;
2140
2141        // Step 2. If one or more of matrix's m11 element, m12 element, m21
2142        // element, m22 element, m41 element, or m42 element are infinite or
2143        // NaN, then return.
2144        if !matrix.m11.is_finite() ||
2145            !matrix.m12.is_finite() ||
2146            !matrix.m21.is_finite() ||
2147            !matrix.m22.is_finite() ||
2148            !matrix.m31.is_finite() ||
2149            !matrix.m32.is_finite()
2150        {
2151            return Ok(());
2152        }
2153
2154        // Step 3. Reset the current transformation matrix to matrix.
2155        self.update_transform(matrix.cast());
2156        Ok(())
2157    }
2158
2159    // https://html.spec.whatwg.org/multipage/#dom-context-2d-resettransform
2160    pub(super) fn reset_transform(&self) {
2161        self.update_transform(Transform2D::identity())
2162    }
2163
2164    // https://html.spec.whatwg.org/multipage/#dom-context-2d-closepath
2165    pub(super) fn close_path(&self) {
2166        self.current_default_path.borrow_mut().close_path();
2167    }
2168
2169    // https://html.spec.whatwg.org/multipage/#dom-context-2d-moveto
2170    pub(super) fn move_to(&self, x: f64, y: f64) {
2171        self.current_default_path.borrow_mut().move_to(x, y);
2172    }
2173
2174    // https://html.spec.whatwg.org/multipage/#dom-context-2d-lineto
2175    pub(super) fn line_to(&self, x: f64, y: f64) {
2176        self.current_default_path.borrow_mut().line_to(x, y);
2177    }
2178
2179    // https://html.spec.whatwg.org/multipage/#dom-context-2d-rect
2180    pub(super) fn rect(&self, x: f64, y: f64, width: f64, height: f64) {
2181        self.current_default_path
2182            .borrow_mut()
2183            .rect(x, y, width, height);
2184    }
2185
2186    // https://html.spec.whatwg.org/multipage/#dom-context-2d-quadraticcurveto
2187    pub(super) fn quadratic_curve_to(&self, cpx: f64, cpy: f64, x: f64, y: f64) {
2188        self.current_default_path
2189            .borrow_mut()
2190            .quadratic_curve_to(cpx, cpy, x, y);
2191    }
2192
2193    // https://html.spec.whatwg.org/multipage/#dom-context-2d-beziercurveto
2194    pub(super) fn bezier_curve_to(
2195        &self,
2196        cp1x: f64,
2197        cp1y: f64,
2198        cp2x: f64,
2199        cp2y: f64,
2200        x: f64,
2201        y: f64,
2202    ) {
2203        self.current_default_path
2204            .borrow_mut()
2205            .bezier_curve_to(cp1x, cp1y, cp2x, cp2y, x, y);
2206    }
2207
2208    // https://html.spec.whatwg.org/multipage/#dom-context-2d-arc
2209    pub(super) fn arc(
2210        &self,
2211        x: f64,
2212        y: f64,
2213        r: f64,
2214        start: f64,
2215        end: f64,
2216        ccw: bool,
2217    ) -> ErrorResult {
2218        self.current_default_path
2219            .borrow_mut()
2220            .arc(x, y, r, start, end, ccw)
2221            .map_err(|_| Error::IndexSize(None))
2222    }
2223
2224    // https://html.spec.whatwg.org/multipage/#dom-context-2d-arcto
2225    pub(super) fn arc_to(&self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, r: f64) -> ErrorResult {
2226        self.current_default_path
2227            .borrow_mut()
2228            .arc_to(cp1x, cp1y, cp2x, cp2y, r)
2229            .map_err(|_| Error::IndexSize(None))
2230    }
2231
2232    /// <https://html.spec.whatwg.org/multipage/#dom-context-2d-ellipse>
2233    #[allow(clippy::too_many_arguments)]
2234    pub(super) fn ellipse(
2235        &self,
2236        x: f64,
2237        y: f64,
2238        rx: f64,
2239        ry: f64,
2240        rotation: f64,
2241        start: f64,
2242        end: f64,
2243        ccw: bool,
2244    ) -> ErrorResult {
2245        self.current_default_path
2246            .borrow_mut()
2247            .ellipse(x, y, rx, ry, rotation, start, end, ccw)
2248            .map_err(|_| Error::IndexSize(None))
2249    }
2250
2251    fn text_with_size(
2252        &self,
2253        global_scope: &GlobalScope,
2254        text: &str,
2255        origin: Point2D<f64>,
2256        size: f64,
2257        max_width: Option<f64>,
2258    ) -> Option<(Rect<f64>, Vec<TextRun>)> {
2259        let Some(font_context) = global_scope.font_context() else {
2260            warn!("Tried to paint to a canvas of GlobalScope without a FontContext.");
2261            return None;
2262        };
2263
2264        // Step 1: If maxWidth was provided but is less than or equal to zero or equal to NaN, then return an empty array.
2265        if max_width.is_some_and(|max_width| max_width.is_nan() || max_width <= 0.) {
2266            return None;
2267        }
2268
2269        // > Step 2: Replace all ASCII whitespace in text with U+0020 SPACE characters.
2270        let text = replace_ascii_whitespace(text);
2271
2272        // > Step 3: Let font be the current font of target, as given by that object's font
2273        // > attribute.
2274        let font_style = self.font_style();
2275        let font_group = font_context.font_group_with_size(font_style, Au::from_f64_px(size));
2276        let mut font_group = font_group.write();
2277        let Some(first_font) = font_group.first(font_context) else {
2278            warn!("Could not render canvas text, because there was no first font.");
2279            return None;
2280        };
2281
2282        let runs = self.build_unshaped_text_runs(font_context, &text, &mut font_group);
2283
2284        // TODO: This doesn't do any kind of line layout at all. In particular, there needs
2285        // to be some alignment along a baseline and also support for bidi text.
2286        let mut total_advance = 0.0;
2287        let mut shaped_runs: Vec<_> = runs
2288            .into_iter()
2289            .filter_map(|unshaped_text_run| {
2290                let text_run = unshaped_text_run.into_shaped_text_run(total_advance)?;
2291                total_advance += text_run.advance;
2292                Some(text_run)
2293            })
2294            .collect();
2295
2296        // > Step 6: If maxWidth was provided and the hypothetical width of the inline box in the
2297        // > hypothetical line box is greater than maxWidth CSS pixels, then change font to have a
2298        // > more condensed font (if one is available or if a reasonably readable one can be
2299        // > synthesized by applying a horizontal scale factor to the font) or a smaller font, and
2300        // > return to the previous step.
2301        //
2302        // TODO: We only try decreasing the font size here. Eventually it would make sense to use
2303        // other methods to try to decrease the size, such as finding a narrower font or decreasing
2304        // spacing.
2305        let total_advance = total_advance as f64;
2306        if let Some(max_width) = max_width {
2307            let new_size = (max_width / total_advance * size).floor().max(5.);
2308            if total_advance > max_width && new_size != size {
2309                return self.text_with_size(global_scope, &text, origin, new_size, Some(max_width));
2310            }
2311        }
2312
2313        // > Step 7: Find the anchor point for the line of text.
2314        let start =
2315            self.find_anchor_point_for_line_of_text(origin, &first_font.metrics, total_advance);
2316
2317        // > Step 8: Let result be an array constructed by iterating over each glyph in the inline box
2318        // > from left to right (if any), adding to the array, for each glyph, the shape of the glyph
2319        // > as it is in the inline box, positioned on a coordinate space using CSS pixels with its
2320        // > origin is at the anchor point.
2321        let mut bounds = None;
2322        for text_run in shaped_runs.iter_mut() {
2323            for glyph_and_position in text_run.glyphs_and_positions.iter_mut() {
2324                glyph_and_position.point += Vector2D::new(start.x as f32, start.y as f32);
2325            }
2326            bounds
2327                .get_or_insert(text_run.bounds)
2328                .union(&text_run.bounds);
2329        }
2330
2331        Some((
2332            bounds
2333                .unwrap_or_default()
2334                .translate(start.to_vector().cast_unit()),
2335            shaped_runs,
2336        ))
2337    }
2338
2339    fn build_unshaped_text_runs<'text>(
2340        &self,
2341        font_context: &FontContext,
2342        text: &'text str,
2343        font_group: &mut FontGroup,
2344    ) -> Vec<UnshapedTextRun<'text>> {
2345        let mut runs = Vec::new();
2346        let mut current_text_run = UnshapedTextRun::default();
2347        let mut current_text_run_start_index = 0;
2348
2349        for (index, character) in text.char_indices() {
2350            // TODO: This should ultimately handle emoji variation selectors, but raqote does not yet
2351            // have support for color glyphs.
2352            let script = Script::from(character);
2353            let font = font_group.find_by_codepoint(font_context, character, None, None, None);
2354
2355            if !current_text_run.script_and_font_compatible(script, &font) {
2356                let previous_text_run = std::mem::replace(
2357                    &mut current_text_run,
2358                    UnshapedTextRun {
2359                        font: font.clone(),
2360                        script,
2361                        ..Default::default()
2362                    },
2363                );
2364                current_text_run_start_index = index;
2365                runs.push(previous_text_run)
2366            }
2367
2368            current_text_run.string =
2369                &text[current_text_run_start_index..index + character.len_utf8()];
2370        }
2371
2372        runs.push(current_text_run);
2373        runs
2374    }
2375
2376    /// Find the *anchor_point* for the given parameters of a line of text.
2377    /// See <https://html.spec.whatwg.org/multipage/#text-preparation-algorithm>.
2378    fn find_anchor_point_for_line_of_text(
2379        &self,
2380        origin: Point2D<f64>,
2381        metrics: &FontMetrics,
2382        width: f64,
2383    ) -> Point2D<f64> {
2384        let state = self.state.borrow();
2385        let is_rtl = match state.direction {
2386            CanvasDirection::Ltr => false,
2387            CanvasDirection::Rtl => true,
2388            CanvasDirection::Inherit => false, // TODO: resolve direction wrt to canvas element
2389        };
2390
2391        let text_align = match self.text_align() {
2392            CanvasTextAlign::Start if is_rtl => CanvasTextAlign::Right,
2393            CanvasTextAlign::Start => CanvasTextAlign::Left,
2394            CanvasTextAlign::End if is_rtl => CanvasTextAlign::Left,
2395            CanvasTextAlign::End => CanvasTextAlign::Right,
2396            text_align => text_align,
2397        };
2398        let anchor_x = match text_align {
2399            CanvasTextAlign::Center => -width / 2.,
2400            CanvasTextAlign::Right => -width,
2401            _ => 0.,
2402        };
2403
2404        let ascent = metrics.ascent.to_f64_px();
2405        let descent = metrics.descent.to_f64_px();
2406        let anchor_y = match self.text_baseline() {
2407            CanvasTextBaseline::Top => ascent,
2408            CanvasTextBaseline::Hanging => ascent * HANGING_BASELINE_DEFAULT,
2409            CanvasTextBaseline::Ideographic => -descent * IDEOGRAPHIC_BASELINE_DEFAULT,
2410            CanvasTextBaseline::Middle => (ascent - descent) / 2.,
2411            CanvasTextBaseline::Alphabetic => 0.,
2412            CanvasTextBaseline::Bottom => -descent,
2413        };
2414
2415        origin + Vector2D::new(anchor_x, anchor_y)
2416    }
2417}
2418
2419impl Drop for CanvasState {
2420    fn drop(&mut self) {
2421        if let Err(err) = self
2422            .canvas_thread_sender
2423            .send(CanvasMsg::Close(self.canvas_id))
2424        {
2425            warn!("Could not close canvas: {}", err)
2426        }
2427    }
2428}
2429
2430#[derive(Default)]
2431struct UnshapedTextRun<'a> {
2432    font: Option<FontRef>,
2433    script: Script,
2434    string: &'a str,
2435}
2436
2437impl UnshapedTextRun<'_> {
2438    fn script_and_font_compatible(&self, script: Script, other_font: &Option<FontRef>) -> bool {
2439        if self.script != script {
2440            return false;
2441        }
2442
2443        match (&self.font, other_font) {
2444            (Some(font_a), Some(font_b)) => font_a.identifier() == font_b.identifier(),
2445            (None, None) => true,
2446            _ => false,
2447        }
2448    }
2449
2450    fn into_shaped_text_run(self, previous_advance: f32) -> Option<TextRun> {
2451        let font = self.font?;
2452        if self.string.is_empty() {
2453            return None;
2454        }
2455
2456        let word_spacing = Au::from_f64_px(
2457            font.glyph_index(' ')
2458                .map(|glyph_id| font.glyph_h_advance(glyph_id))
2459                .unwrap_or(LAST_RESORT_GLYPH_ADVANCE),
2460        );
2461        let options = ShapingOptions {
2462            letter_spacing: None,
2463            word_spacing,
2464            script: self.script,
2465            flags: ShapingFlags::empty(),
2466        };
2467
2468        let glyphs = font.shape_text(self.string, &options);
2469
2470        let mut advance = 0.0;
2471        let mut bounds = None;
2472        let glyphs_and_positions = glyphs
2473            .iter_glyphs_for_byte_range(&Range::new(ByteIndex(0), glyphs.len()))
2474            .map(|glyph| {
2475                let glyph_offset = glyph.offset().unwrap_or(Point2D::zero());
2476                let glyph_and_position = GlyphAndPosition {
2477                    id: glyph.id(),
2478                    point: Point2D::new(previous_advance + advance, glyph_offset.y.to_f32_px()),
2479                };
2480
2481                let glyph_bounds = font
2482                    .typographic_bounds(glyph.id())
2483                    .translate(Vector2D::new(advance + previous_advance, 0.0));
2484                bounds = Some(bounds.get_or_insert(glyph_bounds).union(&glyph_bounds));
2485
2486                advance += glyph.advance().to_f32_px();
2487
2488                glyph_and_position
2489            })
2490            .collect();
2491
2492        let identifier = font.identifier();
2493        let font_data = match &identifier {
2494            FontIdentifier::Local(_) => None,
2495            FontIdentifier::Web(_) => Some(font.font_data_and_index().ok()?),
2496        }
2497        .cloned();
2498        let canvas_font = CanvasFont {
2499            identifier,
2500            data: font_data,
2501        };
2502
2503        Some(TextRun {
2504            font: canvas_font,
2505            pt_size: font.descriptor.pt_size.to_f32_px(),
2506            glyphs_and_positions,
2507            advance,
2508            bounds: bounds.unwrap_or_default().cast(),
2509        })
2510    }
2511}
2512
2513pub(super) fn parse_color(
2514    canvas: Option<&HTMLCanvasElement>,
2515    string: &DOMString,
2516) -> Result<AbsoluteColor, ()> {
2517    let string = string.str();
2518    let mut input = ParserInput::new(&string);
2519    let mut parser = Parser::new(&mut input);
2520    let url = Url::parse("about:blank").unwrap().into();
2521    let context = ParserContext::new(
2522        Origin::Author,
2523        &url,
2524        Some(CssRuleType::Style),
2525        ParsingMode::DEFAULT,
2526        QuirksMode::NoQuirks,
2527        /* namespaces = */ Default::default(),
2528        None,
2529        None,
2530    );
2531    match Color::parse_and_compute(&context, &mut parser, None) {
2532        Some(color) => {
2533            // TODO: https://github.com/whatwg/html/issues/1099
2534            // Reconsider how to calculate currentColor in a display:none canvas
2535
2536            // TODO: will need to check that the context bitmap mode is fixed
2537            // once we implement CanvasProxy
2538            let current_color = match canvas {
2539                // https://drafts.css-houdini.org/css-paint-api/#2d-rendering-context
2540                // Whenever "currentColor" is used as a color in the PaintRenderingContext2D API,
2541                // it is treated as opaque black.
2542                None => AbsoluteColor::BLACK,
2543                Some(canvas) => {
2544                    let canvas_element = canvas.upcast::<Element>();
2545                    match canvas_element.style() {
2546                        Some(ref s) if canvas_element.has_css_layout_box() => {
2547                            s.get_inherited_text().color
2548                        },
2549                        _ => AbsoluteColor::BLACK,
2550                    }
2551                },
2552            };
2553
2554            Ok(color.resolve_to_absolute(&current_color))
2555        },
2556        None => Err(()),
2557    }
2558}
2559
2560// Used by drawImage to determine if a source or destination rectangle is valid
2561// Origin coordinates and size cannot be negative. Size has to be greater than zero
2562pub(super) fn is_rect_valid(rect: Rect<f64>) -> bool {
2563    rect.size.width > 0.0 && rect.size.height > 0.0
2564}
2565
2566// https://html.spec.whatwg.org/multipage/#serialisation-of-a-color
2567pub(super) fn serialize<W>(color: &AbsoluteColor, dest: &mut W) -> fmt::Result
2568where
2569    W: fmt::Write,
2570{
2571    let srgb = match color.color_space {
2572        ColorSpace::Srgb if color.flags.contains(ColorFlags::IS_LEGACY_SRGB) => *color,
2573        ColorSpace::Hsl | ColorSpace::Hwb => color.into_srgb_legacy(),
2574        _ => return color.to_css(&mut CssWriter::new(dest)),
2575    };
2576    debug_assert!(srgb.flags.contains(ColorFlags::IS_LEGACY_SRGB));
2577    let red = clamp_unit_f32(srgb.components.0);
2578    let green = clamp_unit_f32(srgb.components.1);
2579    let blue = clamp_unit_f32(srgb.components.2);
2580    let alpha = srgb.alpha;
2581    if alpha == 1.0 {
2582        write!(
2583            dest,
2584            "#{:x}{:x}{:x}{:x}{:x}{:x}",
2585            red >> 4,
2586            red & 0xF,
2587            green >> 4,
2588            green & 0xF,
2589            blue >> 4,
2590            blue & 0xF
2591        )
2592    } else {
2593        write!(dest, "rgba({}, {}, {}, {})", red, green, blue, alpha)
2594    }
2595}
2596
2597pub(super) fn adjust_size_sign(
2598    mut origin: Point2D<i32>,
2599    mut size: Size2D<i32>,
2600) -> (Point2D<i32>, Size2D<u32>) {
2601    if size.width < 0 {
2602        size.width = -size.width;
2603        origin.x = origin.x.saturating_sub(size.width);
2604    }
2605    if size.height < 0 {
2606        size.height = -size.height;
2607        origin.y = origin.y.saturating_sub(size.height);
2608    }
2609    (origin, size.to_u32())
2610}
2611
2612fn serialize_font<W>(style: &Font, dest: &mut W) -> fmt::Result
2613where
2614    W: fmt::Write,
2615{
2616    if style.font_style == FontStyle::ITALIC {
2617        write!(dest, "{} ", style.font_style.to_css_string())?;
2618    }
2619    if style.font_weight.is_bold() {
2620        write!(dest, "{} ", style.font_weight.to_css_string())?;
2621    }
2622    if style.font_variant_caps == FontVariantCaps::SmallCaps {
2623        write!(dest, "{} ", style.font_variant_caps.to_css_string())?;
2624    }
2625    write!(
2626        dest,
2627        "{} {}",
2628        style.font_size.to_css_string(),
2629        style.font_family.to_css_string()
2630    )
2631}
2632
2633fn adjust_canvas_size(size: Size2D<u64>) -> Size2D<u64> {
2634    // Firefox limits width/height to 32767 pixels and Chromium to 65535 pixels,
2635    // but slows down dramatically before it reaches that limit.
2636    // We limit by area instead, giving us larger maximum dimensions,
2637    // in exchange for a smaller maximum canvas size.
2638    const MAX_CANVAS_AREA: u64 = 32768 * 8192;
2639    // Max width/height to 65535 in CSS pixels.
2640    const MAX_CANVAS_SIZE: u64 = 65535;
2641
2642    if !size.is_empty() &&
2643        size.greater_than(Size2D::new(MAX_CANVAS_SIZE, MAX_CANVAS_SIZE))
2644            .none() &&
2645        size.area() < MAX_CANVAS_AREA
2646    {
2647        size
2648    } else {
2649        Size2D::zero()
2650    }
2651}
2652
2653impl Convert<FillRule> for CanvasFillRule {
2654    fn convert(self) -> FillRule {
2655        match self {
2656            CanvasFillRule::Nonzero => FillRule::Nonzero,
2657            CanvasFillRule::Evenodd => FillRule::Evenodd,
2658        }
2659    }
2660}
2661
2662fn replace_ascii_whitespace(text: &str) -> String {
2663    text.chars()
2664        .map(|c| match c {
2665            ' ' | '\t' | '\n' | '\r' | '\x0C' => '\x20',
2666            _ => c,
2667        })
2668        .collect()
2669}