Skip to main content

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