Skip to main content

script/dom/canvas/
imagebitmap.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::{Cell, Ref};
6use std::rc::Rc;
7
8use dom_struct::dom_struct;
9use euclid::default::{Point2D, Rect, Size2D};
10use js::context::JSContext;
11use js::realm::CurrentRealm;
12use pixels::{CorsStatus, Snapshot, SnapshotAlphaMode, SnapshotPixelFormat};
13use rustc_hash::FxHashMap;
14use script_bindings::cell::DomRefCell;
15use script_bindings::error::{Error, Fallible};
16use script_bindings::reflector::{Reflector, reflect_dom_object_with_cx};
17use servo_base::id::{ImageBitmapId, ImageBitmapIndex};
18use servo_constellation_traits::SerializableImageBitmap;
19
20use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
21    ImageBitmapMethods, ImageBitmapOptions, ImageBitmapSource, ImageOrientation, PremultiplyAlpha,
22    ResizeQuality,
23};
24use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
25use crate::dom::bindings::root::DomRoot;
26use crate::dom::bindings::serializable::Serializable;
27use crate::dom::bindings::structuredclone::StructuredData;
28use crate::dom::bindings::transferable::Transferable;
29use crate::dom::globalscope::GlobalScope;
30use crate::dom::types::Promise;
31
32#[dom_struct]
33pub(crate) struct ImageBitmap {
34    reflector_: Reflector,
35    /// The actual pixel data of the bitmap
36    ///
37    /// If this is `None`, then the bitmap data has been released by calling
38    /// [`close`](https://html.spec.whatwg.org/multipage/#dom-imagebitmap-close)
39    #[no_trace]
40    bitmap_data: DomRefCell<Option<Snapshot>>,
41    origin_clean: Cell<bool>,
42}
43
44impl ImageBitmap {
45    fn new_inherited(bitmap_data: Snapshot) -> ImageBitmap {
46        ImageBitmap {
47            reflector_: Reflector::new(),
48            bitmap_data: DomRefCell::new(Some(bitmap_data)),
49            origin_clean: Cell::new(true),
50        }
51    }
52
53    pub(crate) fn new(
54        cx: &mut JSContext,
55        global: &GlobalScope,
56        bitmap_data: Snapshot,
57    ) -> DomRoot<ImageBitmap> {
58        reflect_dom_object_with_cx(
59            Box::new(ImageBitmap::new_inherited(bitmap_data)),
60            global,
61            cx,
62        )
63    }
64
65    pub(crate) fn bitmap_data(&self) -> Ref<'_, Option<Snapshot>> {
66        self.bitmap_data.borrow()
67    }
68
69    pub(crate) fn origin_is_clean(&self) -> bool {
70        self.origin_clean.get()
71    }
72
73    pub(crate) fn set_origin_clean(&self, origin_is_clean: bool) {
74        self.origin_clean.set(origin_is_clean);
75    }
76
77    /// Return the value of the [`[[Detached]]`](https://html.spec.whatwg.org/multipage/#detached)
78    /// internal slot
79    pub(crate) fn is_detached(&self) -> bool {
80        self.bitmap_data.borrow().is_none()
81    }
82
83    /// <https://html.spec.whatwg.org/multipage/#cropped-to-the-source-rectangle-with-formatting>
84    pub(crate) fn crop_and_transform_bitmap_data(
85        input: Snapshot,
86        mut sx: i32,
87        mut sy: i32,
88        sw: Option<i32>,
89        sh: Option<i32>,
90        options: &ImageBitmapOptions,
91    ) -> Option<Snapshot> {
92        let input_size = input.size().to_i32();
93
94        // Step 2. If sx, sy, sw and sh are specified, let sourceRectangle be a rectangle whose corners
95        // are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh). Otherwise,
96        // let sourceRectangle be a rectangle whose corners are the four points (0, 0), (width of input, 0),
97        // (width of input, height of input), (0, height of input). If either sw or sh are negative,
98        // then the top-left corner of this rectangle will be to the left or above the (sx, sy) point.
99        let sw = sw.map_or(input_size.width, |width| {
100            if width < 0 {
101                sx = sx.saturating_add(width);
102                width.saturating_abs()
103            } else {
104                width
105            }
106        });
107
108        let sh = sh.map_or(input_size.height, |height| {
109            if height < 0 {
110                sy = sy.saturating_add(height);
111                height.saturating_abs()
112            } else {
113                height
114            }
115        });
116
117        let source_rect = Rect::new(Point2D::new(sx, sy), Size2D::new(sw, sh));
118
119        // Whether the byte length of the source bitmap exceeds the supported range.
120        // In the case the source is too large, we should fail, and that is not defined.
121        // <https://github.com/whatwg/html/issues/3323>
122        let Some(source_byte_length) = pixels::compute_rgba8_byte_length_if_within_limit(
123            source_rect.size.width as usize,
124            source_rect.size.height as usize,
125        ) else {
126            log::warn!(
127                "Failed to allocate bitmap of size {:?}, too large",
128                source_rect.size
129            );
130            return None;
131        };
132
133        // Step 3. Let outputWidth be determined as follows:
134        // Step 4. Let outputHeight be determined as follows:
135        let output_size = match (options.resizeWidth, options.resizeHeight) {
136            (Some(width), Some(height)) => Size2D::new(width, height),
137            (Some(width), None) => {
138                let height =
139                    source_rect.size.height as f64 * width as f64 / source_rect.size.width as f64;
140                Size2D::new(width, height.round() as u32)
141            },
142            (None, Some(height)) => {
143                let width =
144                    source_rect.size.width as f64 * height as f64 / source_rect.size.height as f64;
145                Size2D::new(width.round() as u32, height)
146            },
147            (None, None) => source_rect.size.to_u32(),
148        };
149
150        // Whether the byte length of the output bitmap exceeds the supported range.
151        // In the case the output is too large, we should fail, and that is not defined.
152        // <https://github.com/whatwg/html/issues/3323>
153        let Some(output_byte_length) = pixels::compute_rgba8_byte_length_if_within_limit(
154            output_size.width as usize,
155            output_size.height as usize,
156        ) else {
157            log::warn!(
158                "Failed to allocate bitmap of size {:?}, too large",
159                output_size
160            );
161            return None;
162        };
163
164        // TODO: Take into account the image orientation (such as EXIF metadata).
165
166        // Step 5. Place input on an infinite transparent black grid plane, positioned so that
167        // its top left corner is at the origin of the plane, with the x-coordinate increasing to the right,
168        // and the y-coordinate increasing down, and with each pixel in the input image data occupying a cell
169        // on the plane's grid.
170        let input_rect = Rect::new(Point2D::zero(), input_size);
171
172        let input_rect_cropped = source_rect
173            .intersection(&input_rect)
174            .unwrap_or(Rect::zero());
175
176        // Early out for empty tranformations.
177        if input_rect_cropped.is_empty() {
178            return Some(Snapshot::cleared(output_size));
179        }
180
181        // Step 6. Let output be the rectangle on the plane denoted by sourceRectangle.
182        let mut source: Snapshot = Snapshot::from_vec(
183            source_rect.size.cast(),
184            input.format(),
185            input.alpha_mode(),
186            vec![0; source_byte_length],
187        );
188
189        let source_rect_cropped = Rect::new(
190            Point2D::new(
191                input_rect_cropped.origin.x - source_rect.origin.x,
192                input_rect_cropped.origin.y - source_rect.origin.y,
193            ),
194            input_rect_cropped.size,
195        );
196
197        pixels::copy_rgba8_image(
198            input.size(),
199            input_rect_cropped.cast(),
200            input.as_raw_bytes(),
201            source.size(),
202            source_rect_cropped.cast(),
203            source.as_raw_bytes_mut(),
204        );
205
206        // Step 7. Scale output to the size specified by outputWidth and outputHeight.
207        let mut output = if source.size() != output_size {
208            let quality = match options.resizeQuality {
209                ResizeQuality::Pixelated => pixels::FilterQuality::None,
210                ResizeQuality::Low => pixels::FilterQuality::Low,
211                ResizeQuality::Medium => pixels::FilterQuality::Medium,
212                ResizeQuality::High => pixels::FilterQuality::High,
213            };
214
215            let Some(output_data) = pixels::scale_rgba8_image(
216                source.size(),
217                source.as_raw_bytes(),
218                output_size,
219                quality,
220            ) else {
221                log::warn!(
222                    "Failed to scale the bitmap of size {:?} to required size {:?}",
223                    source.size(),
224                    output_size
225                );
226                return None;
227            };
228
229            debug_assert_eq!(output_data.len(), output_byte_length);
230
231            Snapshot::from_vec(
232                output_size,
233                source.format(),
234                source.alpha_mode(),
235                output_data,
236            )
237        } else {
238            source
239        };
240
241        // Step 8. If the value of the imageOrientation member of options is "flipY",
242        // output must be flipped vertically, disregarding any image orientation metadata
243        // of the source (such as EXIF metadata), if any.
244        if options.imageOrientation == ImageOrientation::FlipY {
245            pixels::flip_y_rgba8_image_inplace(output.size(), output.as_raw_bytes_mut());
246        }
247
248        // TODO: Step 9. If image is an img element or a Blob object, let val be the value
249        // of the colorSpaceConversion member of options, and then run these substeps:
250
251        // Step 10. Let val be the value of premultiplyAlpha member of options,
252        // and then run these substeps:
253        // TODO: Preserve the original input pixel format and perform conversion on demand.
254        match options.premultiplyAlpha {
255            PremultiplyAlpha::Default | PremultiplyAlpha::Premultiply => {
256                output.transform(
257                    SnapshotAlphaMode::Transparent {
258                        premultiplied: true,
259                    },
260                    SnapshotPixelFormat::BGRA,
261                );
262            },
263            PremultiplyAlpha::None => {
264                output.transform(
265                    SnapshotAlphaMode::Transparent {
266                        premultiplied: false,
267                    },
268                    SnapshotPixelFormat::BGRA,
269                );
270            },
271        }
272
273        // Step 11. Return output.
274        Some(output)
275    }
276
277    /// <https://html.spec.whatwg.org/multipage/#dom-createimagebitmap>
278    #[allow(clippy::too_many_arguments)]
279    pub(crate) fn create_image_bitmap(
280        global_scope: &GlobalScope,
281        image: ImageBitmapSource,
282        sx: i32,
283        sy: i32,
284        sw: Option<i32>,
285        sh: Option<i32>,
286        options: &ImageBitmapOptions,
287        realm: &mut CurrentRealm,
288    ) -> Rc<Promise> {
289        let p = Promise::new_in_realm(realm);
290
291        // Step 1. If either sw or sh is given and is 0, then return a promise rejected with a RangeError.
292        if sw.is_some_and(|w| w == 0) {
293            p.reject_error_with_cx(
294                realm,
295                Error::Range(c"'sw' must be a non-zero value".to_owned()),
296            );
297            return p;
298        }
299
300        if sh.is_some_and(|h| h == 0) {
301            p.reject_error_with_cx(
302                realm,
303                Error::Range(c"'sh' must be a non-zero value".to_owned()),
304            );
305            return p;
306        }
307
308        // Step 2. If either options's resizeWidth or options's resizeHeight is present and is 0,
309        // then return a promise rejected with an "InvalidStateError" DOMException.
310        if options.resizeWidth.is_some_and(|w| w == 0) {
311            p.reject_error_with_cx(realm, Error::InvalidState(None));
312            return p;
313        }
314
315        if options.resizeHeight.is_some_and(|h| h == 0) {
316            p.reject_error_with_cx(realm, Error::InvalidState(None));
317            return p;
318        }
319
320        // The promise with image bitmap should be fulfilled on the bitmap task source.
321        let fullfill_promise_on_bitmap_task_source =
322            |promise: &Rc<Promise>, image_bitmap: &ImageBitmap| {
323                let trusted_promise = TrustedPromise::new(promise.clone());
324                let trusted_image_bitmap = Trusted::new(image_bitmap);
325
326                global_scope.task_manager().bitmap_task_source().queue(
327                    task!(resolve_promise: move |cx| {
328                        let promise = trusted_promise.root();
329                        let image_bitmap = trusted_image_bitmap.root();
330
331                        promise.resolve_native_with_cx(cx, &image_bitmap);
332                    }),
333                );
334            };
335
336        // The promise with "InvalidStateError" DOMException should be rejected
337        // on the bitmap task source.
338        let reject_promise_on_bitmap_task_source = |promise: &Rc<Promise>| {
339            let trusted_promise = TrustedPromise::new(promise.clone());
340
341            global_scope.task_manager().bitmap_task_source().queue(
342                task!(reject_promise: move |cx| {
343                    let promise = trusted_promise.root();
344
345                    promise.reject_error_with_cx(cx, Error::InvalidState(None));
346                }),
347            );
348        };
349
350        // Step 3. Check the usability of the image argument. If this throws an exception or returns bad,
351        // then return a promise rejected with an "InvalidStateError" DOMException.
352        // Step 6. Switch on image:
353        match image {
354            ImageBitmapSource::HTMLImageElement(ref image) => {
355                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
356                if !image.is_usable().is_ok_and(|u| u) {
357                    p.reject_error_with_cx(realm, Error::InvalidState(None));
358                    return p;
359                }
360
361                // If no ImageBitmap object can be constructed, then the promise
362                // is rejected instead.
363                let Some(snapshot) = image.get_raster_image_data() else {
364                    p.reject_error_with_cx(realm, Error::InvalidState(None));
365                    return p;
366                };
367
368                // Step 6.3. Set imageBitmap's bitmap data to a copy of image's media data,
369                // cropped to the source rectangle with formatting.
370                let Some(bitmap_data) =
371                    ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
372                else {
373                    p.reject_error_with_cx(realm, Error::InvalidState(None));
374                    return p;
375                };
376
377                let image_bitmap = Self::new(realm, global_scope, bitmap_data);
378                // Step 6.4. If image is not origin-clean, then set the origin-clean flag
379                // of imageBitmap's bitmap to false.
380                image_bitmap.set_origin_clean(image.same_origin(GlobalScope::entry().origin()));
381
382                // Step 6.5. Queue a global task, using the bitmap task source,
383                // to resolve promise with imageBitmap.
384                fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
385            },
386            ImageBitmapSource::HTMLVideoElement(ref video) => {
387                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
388                if !video.is_usable() {
389                    p.reject_error_with_cx(realm, Error::InvalidState(None));
390                    return p;
391                }
392
393                // Step 6.1. If image's networkState attribute is NETWORK_EMPTY, then return
394                // a promise rejected with an "InvalidStateError" DOMException.
395                if video.is_network_state_empty() {
396                    p.reject_error_with_cx(realm, Error::InvalidState(None));
397                    return p;
398                }
399
400                // If no ImageBitmap object can be constructed, then the promise is rejected instead.
401                let Some(snapshot) = video.get_current_frame_data() else {
402                    p.reject_error_with_cx(realm, Error::InvalidState(None));
403                    return p;
404                };
405
406                // Step 6.2. Set imageBitmap's bitmap data to a copy of the frame at the current
407                // playback position, at the media resource's natural width and natural height
408                // (i.e., after any aspect-ratio correction has been applied),
409                // cropped to the source rectangle with formatting.
410                let Some(bitmap_data) =
411                    ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
412                else {
413                    p.reject_error_with_cx(realm, Error::InvalidState(None));
414                    return p;
415                };
416
417                let image_bitmap = Self::new(realm, global_scope, bitmap_data);
418                // Step 6.3. If image is not origin-clean, then set the origin-clean flag
419                // of imageBitmap's bitmap to false.
420                image_bitmap.set_origin_clean(video.origin_is_clean());
421
422                // Step 6.4. Queue a global task, using the bitmap task source,
423                // to resolve promise with imageBitmap.
424                fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
425            },
426            ImageBitmapSource::HTMLCanvasElement(ref canvas) => {
427                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
428                if canvas.get_size().is_empty() {
429                    p.reject_error_with_cx(realm, Error::InvalidState(None));
430                    return p;
431                }
432
433                // If no ImageBitmap object can be constructed, then the promise is rejected instead.
434                let Some(snapshot) = canvas.get_image_data() else {
435                    p.reject_error_with_cx(realm, Error::InvalidState(None));
436                    return p;
437                };
438
439                // Step 6.1. Set imageBitmap's bitmap data to a copy of image's bitmap data,
440                // cropped to the source rectangle with formatting.
441                let Some(bitmap_data) =
442                    ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
443                else {
444                    p.reject_error_with_cx(realm, Error::InvalidState(None));
445                    return p;
446                };
447
448                let image_bitmap = Self::new(realm, global_scope, bitmap_data);
449                // Step 6.2. Set the origin-clean flag of the imageBitmap's bitmap to the same value
450                // as the origin-clean flag of image's bitmap.
451                image_bitmap.set_origin_clean(canvas.origin_is_clean());
452
453                // Step 6.3. Queue a global task, using the bitmap task source,
454                // to resolve promise with imageBitmap.
455                fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
456            },
457            ImageBitmapSource::ImageBitmap(ref bitmap) => {
458                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
459                if bitmap.is_detached() {
460                    p.reject_error_with_cx(realm, Error::InvalidState(None));
461                    return p;
462                }
463
464                // If no ImageBitmap object can be constructed, then the promise is rejected instead.
465                let Some(snapshot) = bitmap.bitmap_data().clone() else {
466                    p.reject_error_with_cx(realm, Error::InvalidState(None));
467                    return p;
468                };
469
470                // Step 6.1. Set imageBitmap's bitmap data to a copy of image's bitmap data,
471                // cropped to the source rectangle with formatting.
472                let Some(bitmap_data) =
473                    ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
474                else {
475                    p.reject_error_with_cx(realm, Error::InvalidState(None));
476                    return p;
477                };
478
479                let image_bitmap = Self::new(realm, global_scope, bitmap_data);
480                // Step 6.2. Set the origin-clean flag of imageBitmap's bitmap to the same value
481                // as the origin-clean flag of image's bitmap.
482                image_bitmap.set_origin_clean(bitmap.origin_is_clean());
483
484                // Step 6.3. Queue a global task, using the bitmap task source,
485                // to resolve promise with imageBitmap.
486                fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
487            },
488            ImageBitmapSource::OffscreenCanvas(ref canvas) => {
489                // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
490                if canvas.get_size().is_empty() {
491                    p.reject_error_with_cx(realm, Error::InvalidState(None));
492                    return p;
493                }
494
495                // If no ImageBitmap object can be constructed, then the promise is rejected instead.
496                let Some(snapshot) = canvas.get_image_data() else {
497                    p.reject_error_with_cx(realm, Error::InvalidState(None));
498                    return p;
499                };
500
501                // Step 6.1. Set imageBitmap's bitmap data to a copy of image's bitmap data,
502                // cropped to the source rectangle with formatting.
503                let Some(bitmap_data) =
504                    ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
505                else {
506                    p.reject_error_with_cx(realm, Error::InvalidState(None));
507                    return p;
508                };
509
510                let image_bitmap = Self::new(realm, global_scope, bitmap_data);
511                // Step 6.2. Set the origin-clean flag of the imageBitmap's bitmap to the same value
512                // as the origin-clean flag of image's bitmap.
513                image_bitmap.set_origin_clean(canvas.origin_is_clean());
514
515                // Step 6.3. Queue a global task, using the bitmap task source,
516                // to resolve promise with imageBitmap.
517                fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
518            },
519            ImageBitmapSource::Blob(ref blob) => {
520                // Step 6.1. Let imageData be the result of reading image's data.
521                // If an error occurs during reading of the object, then queue
522                // a global task, using the bitmap task source, to reject promise
523                // with an "InvalidStateError" DOMException and abort these steps.
524                let Ok(bytes) = blob.get_bytes() else {
525                    reject_promise_on_bitmap_task_source(&p);
526                    return p;
527                };
528
529                // Step 6.2. Apply the image sniffing rules to determine the file
530                // format of imageData, with MIME type of image (as given by
531                // image's type attribute) giving the official type.
532                // Step 6.3. If imageData is not in a supported image file format
533                // (e.g., it's not an image at all), or if imageData is corrupted
534                // in some fatal way such that the image dimensions cannot be obtained
535                // (e.g., a vector graphic with no natural size), then queue
536                // a global task, using the bitmap task source, to reject promise
537                // with an "InvalidStateError" DOMException and abort these steps.
538                let Some(raster_image) = pixels::load_from_memory(&bytes, CorsStatus::Safe) else {
539                    reject_promise_on_bitmap_task_source(&p);
540                    return p;
541                };
542
543                // Step 6.4. Set imageBitmap's bitmap data to imageData, cropped
544                // to the source rectangle with formatting.
545                let snapshot = raster_image.as_snapshot();
546                let Some(bitmap_data) =
547                    ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
548                else {
549                    reject_promise_on_bitmap_task_source(&p);
550                    return p;
551                };
552
553                let image_bitmap = Self::new(realm, global_scope, bitmap_data);
554
555                // Step 6.5. Queue a global task, using the bitmap task source,
556                // to resolve promise with imageBitmap.
557                fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
558            },
559            ImageBitmapSource::ImageData(ref image_data) => {
560                // Step 6.1. Let buffer be image's data attribute value's [[ViewedArrayBuffer]] internal slot.
561                // Step 6.2. If IsDetachedBuffer(buffer) is true, then return a promise rejected
562                // with an "InvalidStateError" DOMException.
563                if image_data.is_detached() {
564                    p.reject_error_with_cx(realm, Error::InvalidState(None));
565                    return p;
566                }
567
568                let alpha_mode = SnapshotAlphaMode::Transparent {
569                    premultiplied: false,
570                };
571
572                let snapshot = Snapshot::from_vec(
573                    image_data.get_size().cast(),
574                    SnapshotPixelFormat::RGBA,
575                    alpha_mode,
576                    image_data.to_vec(),
577                );
578
579                // Step 6.3. Set imageBitmap's bitmap data to image's image data,
580                // cropped to the source rectangle with formatting.
581                let Some(bitmap_data) =
582                    ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
583                else {
584                    p.reject_error_with_cx(realm, Error::InvalidState(None));
585                    return p;
586                };
587
588                let image_bitmap = Self::new(realm, global_scope, bitmap_data);
589
590                // Step 6.4. Queue a global task, using the bitmap task source,
591                // to resolve promise with imageBitmap.
592                fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
593            },
594            ImageBitmapSource::CSSStyleValue(_) => {
595                // TODO: CSSStyleValue is not part of ImageBitmapSource
596                // <https://html.spec.whatwg.org/multipage/#imagebitmapsource>
597                p.reject_error_with_cx(realm, Error::NotSupported(None));
598            },
599        }
600
601        // Step 7. Return promise.
602        p
603    }
604}
605
606impl Serializable for ImageBitmap {
607    type Index = ImageBitmapIndex;
608    type Data = SerializableImageBitmap;
609
610    /// <https://html.spec.whatwg.org/multipage/#the-imagebitmap-interface:serialization-steps>
611    fn serialize(&self) -> Result<(ImageBitmapId, Self::Data), ()> {
612        // <https://html.spec.whatwg.org/multipage/#structuredserializeinternal>
613        // Step 19.1. If value has a [[Detached]] internal slot whose value is
614        // true, then throw a "DataCloneError" DOMException.
615        if self.is_detached() {
616            return Err(());
617        }
618
619        // Step 1. If value's origin-clean flag is not set, then throw a
620        // "DataCloneError" DOMException.
621        if !self.origin_is_clean() {
622            return Err(());
623        }
624
625        let Some(bitmap_data) = &*self.bitmap_data.borrow() else {
626            return Err(());
627        };
628
629        // Step 2. Set serialized.[[BitmapData]] to a copy of value's bitmap data.
630        let serialized = SerializableImageBitmap {
631            bitmap_data: bitmap_data.to_shared(),
632        };
633
634        Ok((ImageBitmapId::new(), serialized))
635    }
636
637    /// <https://html.spec.whatwg.org/multipage/#the-imagebitmap-interface:deserialization-steps>
638    fn deserialize(
639        cx: &mut JSContext,
640        owner: &GlobalScope,
641        serialized: Self::Data,
642    ) -> Result<DomRoot<Self>, ()> {
643        // Step 1. Set value's bitmap data to serialized.[[BitmapData]].
644        Ok(ImageBitmap::new(
645            cx,
646            owner,
647            serialized.bitmap_data.to_owned(),
648        ))
649    }
650
651    fn serialized_storage<'a>(
652        data: StructuredData<'a, '_>,
653    ) -> &'a mut Option<FxHashMap<ImageBitmapId, Self::Data>> {
654        match data {
655            StructuredData::Reader(r) => &mut r.image_bitmaps,
656            StructuredData::Writer(w) => &mut w.image_bitmaps,
657        }
658    }
659}
660
661impl Transferable for ImageBitmap {
662    type Index = ImageBitmapIndex;
663    type Data = SerializableImageBitmap;
664
665    /// <https://html.spec.whatwg.org/multipage/#the-imagebitmap-interface:transfer-steps>
666    fn transfer(&self, _cx: &mut JSContext) -> Fallible<(ImageBitmapId, SerializableImageBitmap)> {
667        // <https://html.spec.whatwg.org/multipage/#structuredserializewithtransfer>
668        // Step 5.2. If transferable has a [[Detached]] internal slot and
669        // transferable.[[Detached]] is true, then throw a "DataCloneError"
670        // DOMException.
671        if self.is_detached() {
672            return Err(Error::DataClone(None));
673        }
674
675        // Step 1. If value's origin-clean flag is not set, then throw a
676        // "DataCloneError" DOMException.
677        if !self.origin_is_clean() {
678            return Err(Error::DataClone(None));
679        }
680
681        let Some(bitmap_data) = self.bitmap_data.borrow_mut().take() else {
682            return Err(Error::DataClone(None));
683        };
684
685        // Step 2. Set dataHolder.[[BitmapData]] to value's bitmap data.
686        // Step 3. Unset value's bitmap data.
687        let transferred = SerializableImageBitmap {
688            bitmap_data: bitmap_data.to_shared(),
689        };
690
691        Ok((ImageBitmapId::new(), transferred))
692    }
693
694    /// <https://html.spec.whatwg.org/multipage/#the-imagebitmap-interface:transfer-receiving-steps>
695    fn transfer_receive(
696        cx: &mut JSContext,
697        owner: &GlobalScope,
698        _: ImageBitmapId,
699        transferred: SerializableImageBitmap,
700    ) -> Result<DomRoot<Self>, ()> {
701        // Step 1. Set value's bitmap data to serialized.[[BitmapData]].
702        Ok(ImageBitmap::new(
703            cx,
704            owner,
705            transferred.bitmap_data.to_owned(),
706        ))
707    }
708
709    fn serialized_storage<'a>(
710        data: StructuredData<'a, '_>,
711    ) -> &'a mut Option<FxHashMap<ImageBitmapId, Self::Data>> {
712        match data {
713            StructuredData::Reader(r) => &mut r.transferred_image_bitmaps,
714            StructuredData::Writer(w) => &mut w.transferred_image_bitmaps,
715        }
716    }
717}
718
719impl ImageBitmapMethods<crate::DomTypeHolder> for ImageBitmap {
720    /// <https://html.spec.whatwg.org/multipage/#dom-imagebitmap-height>
721    fn Height(&self) -> u32 {
722        // Step 1. If this's [[Detached]] internal slot's value is true, then return 0.
723        if self.is_detached() {
724            return 0;
725        }
726
727        // Step 2. Return this's height, in CSS pixels.
728        self.bitmap_data
729            .borrow()
730            .as_ref()
731            .unwrap()
732            .size()
733            .cast()
734            .height
735    }
736
737    /// <https://html.spec.whatwg.org/multipage/#dom-imagebitmap-width>
738    fn Width(&self) -> u32 {
739        // Step 1. If this's [[Detached]] internal slot's value is true, then return 0.
740        if self.is_detached() {
741            return 0;
742        }
743
744        // Step 2. Return this's width, in CSS pixels.
745        self.bitmap_data
746            .borrow()
747            .as_ref()
748            .unwrap()
749            .size()
750            .cast()
751            .width
752    }
753
754    /// <https://html.spec.whatwg.org/multipage/#dom-imagebitmap-close>
755    fn Close(&self) {
756        // Step 1. Set this's [[Detached]] internal slot value to true.
757        // Step 2. Unset this's bitmap data.
758        // NOTE: The existence of the bitmap data is the internal slot in our implementation
759        self.bitmap_data.borrow_mut().take();
760    }
761}