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 base::id::{ImageBitmapId, ImageBitmapIndex};
9use constellation_traits::SerializableImageBitmap;
10use dom_struct::dom_struct;
11use euclid::default::{Point2D, Rect, Size2D};
12use pixels::{CorsStatus, Snapshot, SnapshotAlphaMode, SnapshotPixelFormat};
13use rustc_hash::FxHashMap;
14use script_bindings::error::{Error, Fallible};
15use script_bindings::realms::{AlreadyInRealm, InRealm};
16
17use crate::dom::bindings::cell::DomRefCell;
18use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
19 ImageBitmapMethods, ImageBitmapOptions, ImageBitmapSource, ImageOrientation, PremultiplyAlpha,
20 ResizeQuality,
21};
22use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
23use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
24use crate::dom::bindings::root::DomRoot;
25use crate::dom::bindings::serializable::Serializable;
26use crate::dom::bindings::structuredclone::StructuredData;
27use crate::dom::bindings::transferable::Transferable;
28use crate::dom::globalscope::GlobalScope;
29use crate::dom::types::Promise;
30use crate::script_runtime::CanGc;
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 global: &GlobalScope,
55 bitmap_data: Snapshot,
56 can_gc: CanGc,
57 ) -> DomRoot<ImageBitmap> {
58 reflect_dom_object(
59 Box::new(ImageBitmap::new_inherited(bitmap_data)),
60 global,
61 can_gc,
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 can_gc: CanGc,
288 ) -> Rc<Promise> {
289 let in_realm_proof = AlreadyInRealm::assert::<crate::DomTypeHolder>();
290 let p = Promise::new_in_current_realm(InRealm::Already(&in_realm_proof), can_gc);
291
292 // Step 1. If either sw or sh is given and is 0, then return a promise rejected with a RangeError.
293 if sw.is_some_and(|w| w == 0) {
294 p.reject_error(
295 Error::Range("'sw' must be a non-zero value".to_owned()),
296 can_gc,
297 );
298 return p;
299 }
300
301 if sh.is_some_and(|h| h == 0) {
302 p.reject_error(
303 Error::Range("'sh' must be a non-zero value".to_owned()),
304 can_gc,
305 );
306 return p;
307 }
308
309 // Step 2. If either options's resizeWidth or options's resizeHeight is present and is 0,
310 // then return a promise rejected with an "InvalidStateError" DOMException.
311 if options.resizeWidth.is_some_and(|w| w == 0) {
312 p.reject_error(Error::InvalidState(None), can_gc);
313 return p;
314 }
315
316 if options.resizeHeight.is_some_and(|h| h == 0) {
317 p.reject_error(Error::InvalidState(None), can_gc);
318 return p;
319 }
320
321 // The promise with image bitmap should be fulfilled on the bitmap task source.
322 let fullfill_promise_on_bitmap_task_source =
323 |promise: &Rc<Promise>, image_bitmap: &ImageBitmap| {
324 let trusted_promise = TrustedPromise::new(promise.clone());
325 let trusted_image_bitmap = Trusted::new(image_bitmap);
326
327 global_scope.task_manager().bitmap_task_source().queue(
328 task!(resolve_promise: move || {
329 let promise = trusted_promise.root();
330 let image_bitmap = trusted_image_bitmap.root();
331
332 promise.resolve_native(&image_bitmap, CanGc::note());
333 }),
334 );
335 };
336
337 // The promise with "InvalidStateError" DOMException should be rejected
338 // on the bitmap task source.
339 let reject_promise_on_bitmap_task_source = |promise: &Rc<Promise>| {
340 let trusted_promise = TrustedPromise::new(promise.clone());
341
342 global_scope
343 .task_manager()
344 .bitmap_task_source()
345 .queue(task!(reject_promise: move || {
346 let promise = trusted_promise.root();
347
348 promise.reject_error(Error::InvalidState(None), CanGc::note());
349 }));
350 };
351
352 // Step 3. Check the usability of the image argument. If this throws an exception or returns bad,
353 // then return a promise rejected with an "InvalidStateError" DOMException.
354 // Step 6. Switch on image:
355 match image {
356 ImageBitmapSource::HTMLImageElement(ref image) => {
357 // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
358 if !image.is_usable().is_ok_and(|u| u) {
359 p.reject_error(Error::InvalidState(None), can_gc);
360 return p;
361 }
362
363 // If no ImageBitmap object can be constructed, then the promise
364 // is rejected instead.
365 let Some(snapshot) = image.get_raster_image_data() else {
366 p.reject_error(Error::InvalidState(None), can_gc);
367 return p;
368 };
369
370 // Step 6.3. Set imageBitmap's bitmap data to a copy of image's media data,
371 // cropped to the source rectangle with formatting.
372 let Some(bitmap_data) =
373 ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
374 else {
375 p.reject_error(Error::InvalidState(None), can_gc);
376 return p;
377 };
378
379 let image_bitmap = Self::new(global_scope, bitmap_data, can_gc);
380 // Step 6.4. If image is not origin-clean, then set the origin-clean flag
381 // of imageBitmap's bitmap to false.
382 image_bitmap.set_origin_clean(image.same_origin(GlobalScope::entry().origin()));
383
384 // Step 6.5. Queue a global task, using the bitmap task source,
385 // to resolve promise with imageBitmap.
386 fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
387 },
388 ImageBitmapSource::HTMLVideoElement(ref video) => {
389 // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
390 if !video.is_usable() {
391 p.reject_error(Error::InvalidState(None), can_gc);
392 return p;
393 }
394
395 // Step 6.1. If image's networkState attribute is NETWORK_EMPTY, then return
396 // a promise rejected with an "InvalidStateError" DOMException.
397 if video.is_network_state_empty() {
398 p.reject_error(Error::InvalidState(None), can_gc);
399 return p;
400 }
401
402 // If no ImageBitmap object can be constructed, then the promise is rejected instead.
403 let Some(snapshot) = video.get_current_frame_data() else {
404 p.reject_error(Error::InvalidState(None), can_gc);
405 return p;
406 };
407
408 // Step 6.2. Set imageBitmap's bitmap data to a copy of the frame at the current
409 // playback position, at the media resource's natural width and natural height
410 // (i.e., after any aspect-ratio correction has been applied),
411 // cropped to the source rectangle with formatting.
412 let Some(bitmap_data) =
413 ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
414 else {
415 p.reject_error(Error::InvalidState(None), can_gc);
416 return p;
417 };
418
419 let image_bitmap = Self::new(global_scope, bitmap_data, can_gc);
420 // Step 6.3. If image is not origin-clean, then set the origin-clean flag
421 // of imageBitmap's bitmap to false.
422 image_bitmap.set_origin_clean(video.origin_is_clean());
423
424 // Step 6.4. Queue a global task, using the bitmap task source,
425 // to resolve promise with imageBitmap.
426 fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
427 },
428 ImageBitmapSource::HTMLCanvasElement(ref canvas) => {
429 // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
430 if canvas.get_size().is_empty() {
431 p.reject_error(Error::InvalidState(None), can_gc);
432 return p;
433 }
434
435 // If no ImageBitmap object can be constructed, then the promise is rejected instead.
436 let Some(snapshot) = canvas.get_image_data() else {
437 p.reject_error(Error::InvalidState(None), can_gc);
438 return p;
439 };
440
441 // Step 6.1. Set imageBitmap's bitmap data to a copy of image's bitmap data,
442 // cropped to the source rectangle with formatting.
443 let Some(bitmap_data) =
444 ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
445 else {
446 p.reject_error(Error::InvalidState(None), can_gc);
447 return p;
448 };
449
450 let image_bitmap = Self::new(global_scope, bitmap_data, can_gc);
451 // Step 6.2. Set the origin-clean flag of the imageBitmap's bitmap to the same value
452 // as the origin-clean flag of image's bitmap.
453 image_bitmap.set_origin_clean(canvas.origin_is_clean());
454
455 // Step 6.3. Queue a global task, using the bitmap task source,
456 // to resolve promise with imageBitmap.
457 fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
458 },
459 ImageBitmapSource::ImageBitmap(ref bitmap) => {
460 // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
461 if bitmap.is_detached() {
462 p.reject_error(Error::InvalidState(None), can_gc);
463 return p;
464 }
465
466 // If no ImageBitmap object can be constructed, then the promise is rejected instead.
467 let Some(snapshot) = bitmap.bitmap_data().clone() else {
468 p.reject_error(Error::InvalidState(None), can_gc);
469 return p;
470 };
471
472 // Step 6.1. Set imageBitmap's bitmap data to a copy of image's bitmap data,
473 // cropped to the source rectangle with formatting.
474 let Some(bitmap_data) =
475 ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
476 else {
477 p.reject_error(Error::InvalidState(None), can_gc);
478 return p;
479 };
480
481 let image_bitmap = Self::new(global_scope, bitmap_data, can_gc);
482 // Step 6.2. Set the origin-clean flag of imageBitmap's bitmap to the same value
483 // as the origin-clean flag of image's bitmap.
484 image_bitmap.set_origin_clean(bitmap.origin_is_clean());
485
486 // Step 6.3. Queue a global task, using the bitmap task source,
487 // to resolve promise with imageBitmap.
488 fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
489 },
490 ImageBitmapSource::OffscreenCanvas(ref canvas) => {
491 // <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
492 if canvas.get_size().is_empty() {
493 p.reject_error(Error::InvalidState(None), can_gc);
494 return p;
495 }
496
497 // If no ImageBitmap object can be constructed, then the promise is rejected instead.
498 let Some(snapshot) = canvas.get_image_data() else {
499 p.reject_error(Error::InvalidState(None), can_gc);
500 return p;
501 };
502
503 // Step 6.1. Set imageBitmap's bitmap data to a copy of image's bitmap data,
504 // cropped to the source rectangle with formatting.
505 let Some(bitmap_data) =
506 ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
507 else {
508 p.reject_error(Error::InvalidState(None), can_gc);
509 return p;
510 };
511
512 let image_bitmap = Self::new(global_scope, bitmap_data, can_gc);
513 // Step 6.2. Set the origin-clean flag of the imageBitmap's bitmap to the same value
514 // as the origin-clean flag of image's bitmap.
515 image_bitmap.set_origin_clean(canvas.origin_is_clean());
516
517 // Step 6.3. Queue a global task, using the bitmap task source,
518 // to resolve promise with imageBitmap.
519 fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
520 },
521 ImageBitmapSource::Blob(ref blob) => {
522 // Step 6.1. Let imageData be the result of reading image's data.
523 // If an error occurs during reading of the object, then queue
524 // a global task, using the bitmap task source, to reject promise
525 // with an "InvalidStateError" DOMException and abort these steps.
526 let Ok(bytes) = blob.get_bytes() else {
527 reject_promise_on_bitmap_task_source(&p);
528 return p;
529 };
530
531 // Step 6.2. Apply the image sniffing rules to determine the file
532 // format of imageData, with MIME type of image (as given by
533 // image's type attribute) giving the official type.
534 // Step 6.3. If imageData is not in a supported image file format
535 // (e.g., it's not an image at all), or if imageData is corrupted
536 // in some fatal way such that the image dimensions cannot be obtained
537 // (e.g., a vector graphic with no natural size), then queue
538 // a global task, using the bitmap task source, to reject promise
539 // with an "InvalidStateError" DOMException and abort these steps.
540 let Some(raster_image) = pixels::load_from_memory(&bytes, CorsStatus::Safe) else {
541 reject_promise_on_bitmap_task_source(&p);
542 return p;
543 };
544
545 // Step 6.4. Set imageBitmap's bitmap data to imageData, cropped
546 // to the source rectangle with formatting.
547 let snapshot = raster_image.as_snapshot();
548 let Some(bitmap_data) =
549 ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
550 else {
551 reject_promise_on_bitmap_task_source(&p);
552 return p;
553 };
554
555 let image_bitmap = Self::new(global_scope, bitmap_data, can_gc);
556
557 // Step 6.5. Queue a global task, using the bitmap task source,
558 // to resolve promise with imageBitmap.
559 fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
560 },
561 ImageBitmapSource::ImageData(ref image_data) => {
562 // Step 6.1. Let buffer be image's data attribute value's [[ViewedArrayBuffer]] internal slot.
563 // Step 6.2. If IsDetachedBuffer(buffer) is true, then return a promise rejected
564 // with an "InvalidStateError" DOMException.
565 if image_data.is_detached() {
566 p.reject_error(Error::InvalidState(None), can_gc);
567 return p;
568 }
569
570 let alpha_mode = SnapshotAlphaMode::Transparent {
571 premultiplied: false,
572 };
573
574 let snapshot = Snapshot::from_vec(
575 image_data.get_size().cast(),
576 SnapshotPixelFormat::RGBA,
577 alpha_mode,
578 image_data.to_vec(),
579 );
580
581 // Step 6.3. Set imageBitmap's bitmap data to image's image data,
582 // cropped to the source rectangle with formatting.
583 let Some(bitmap_data) =
584 ImageBitmap::crop_and_transform_bitmap_data(snapshot, sx, sy, sw, sh, options)
585 else {
586 p.reject_error(Error::InvalidState(None), can_gc);
587 return p;
588 };
589
590 let image_bitmap = Self::new(global_scope, bitmap_data, can_gc);
591
592 // Step 6.4. Queue a global task, using the bitmap task source,
593 // to resolve promise with imageBitmap.
594 fullfill_promise_on_bitmap_task_source(&p, &image_bitmap);
595 },
596 ImageBitmapSource::CSSStyleValue(_) => {
597 // TODO: CSSStyleValue is not part of ImageBitmapSource
598 // <https://html.spec.whatwg.org/multipage/#imagebitmapsource>
599 p.reject_error(Error::NotSupported, can_gc);
600 },
601 }
602
603 // Step 7. Return promise.
604 p
605 }
606}
607
608impl Serializable for ImageBitmap {
609 type Index = ImageBitmapIndex;
610 type Data = SerializableImageBitmap;
611
612 /// <https://html.spec.whatwg.org/multipage/#the-imagebitmap-interface:serialization-steps>
613 fn serialize(&self) -> Result<(ImageBitmapId, Self::Data), ()> {
614 // <https://html.spec.whatwg.org/multipage/#structuredserializeinternal>
615 // Step 19.1. If value has a [[Detached]] internal slot whose value is
616 // true, then throw a "DataCloneError" DOMException.
617 if self.is_detached() {
618 return Err(());
619 }
620
621 // Step 1. If value's origin-clean flag is not set, then throw a
622 // "DataCloneError" DOMException.
623 if !self.origin_is_clean() {
624 return Err(());
625 }
626
627 let Some(bitmap_data) = &*self.bitmap_data.borrow() else {
628 return Err(());
629 };
630
631 // Step 2. Set serialized.[[BitmapData]] to a copy of value's bitmap data.
632 let serialized = SerializableImageBitmap {
633 bitmap_data: bitmap_data.to_shared(),
634 };
635
636 Ok((ImageBitmapId::new(), serialized))
637 }
638
639 /// <https://html.spec.whatwg.org/multipage/#the-imagebitmap-interface:deserialization-steps>
640 fn deserialize(
641 owner: &GlobalScope,
642 serialized: Self::Data,
643 can_gc: CanGc,
644 ) -> Result<DomRoot<Self>, ()> {
645 // Step 1. Set value's bitmap data to serialized.[[BitmapData]].
646 Ok(ImageBitmap::new(
647 owner,
648 serialized.bitmap_data.to_owned(),
649 can_gc,
650 ))
651 }
652
653 fn serialized_storage<'a>(
654 data: StructuredData<'a, '_>,
655 ) -> &'a mut Option<FxHashMap<ImageBitmapId, Self::Data>> {
656 match data {
657 StructuredData::Reader(r) => &mut r.image_bitmaps,
658 StructuredData::Writer(w) => &mut w.image_bitmaps,
659 }
660 }
661}
662
663impl Transferable for ImageBitmap {
664 type Index = ImageBitmapIndex;
665 type Data = SerializableImageBitmap;
666
667 /// <https://html.spec.whatwg.org/multipage/#the-imagebitmap-interface:transfer-steps>
668 fn transfer(&self) -> Fallible<(ImageBitmapId, SerializableImageBitmap)> {
669 // <https://html.spec.whatwg.org/multipage/#structuredserializewithtransfer>
670 // Step 5.2. If transferable has a [[Detached]] internal slot and
671 // transferable.[[Detached]] is true, then throw a "DataCloneError"
672 // DOMException.
673 if self.is_detached() {
674 return Err(Error::DataClone(None));
675 }
676
677 // Step 1. If value's origin-clean flag is not set, then throw a
678 // "DataCloneError" DOMException.
679 if !self.origin_is_clean() {
680 return Err(Error::DataClone(None));
681 }
682
683 let Some(bitmap_data) = self.bitmap_data.borrow_mut().take() else {
684 return Err(Error::DataClone(None));
685 };
686
687 // Step 2. Set dataHolder.[[BitmapData]] to value's bitmap data.
688 // Step 3. Unset value's bitmap data.
689 let transferred = SerializableImageBitmap {
690 bitmap_data: bitmap_data.to_shared(),
691 };
692
693 Ok((ImageBitmapId::new(), transferred))
694 }
695
696 /// <https://html.spec.whatwg.org/multipage/#the-imagebitmap-interface:transfer-receiving-steps>
697 fn transfer_receive(
698 owner: &GlobalScope,
699 _: ImageBitmapId,
700 transferred: SerializableImageBitmap,
701 ) -> Result<DomRoot<Self>, ()> {
702 // Step 1. Set value's bitmap data to serialized.[[BitmapData]].
703 Ok(ImageBitmap::new(
704 owner,
705 transferred.bitmap_data.to_owned(),
706 CanGc::note(),
707 ))
708 }
709
710 fn serialized_storage<'a>(
711 data: StructuredData<'a, '_>,
712 ) -> &'a mut Option<FxHashMap<ImageBitmapId, Self::Data>> {
713 match data {
714 StructuredData::Reader(r) => &mut r.transferred_image_bitmaps,
715 StructuredData::Writer(w) => &mut w.transferred_image_bitmaps,
716 }
717 }
718}
719
720impl ImageBitmapMethods<crate::DomTypeHolder> for ImageBitmap {
721 /// <https://html.spec.whatwg.org/multipage/#dom-imagebitmap-height>
722 fn Height(&self) -> u32 {
723 // Step 1. If this's [[Detached]] internal slot's value is true, then return 0.
724 if self.is_detached() {
725 return 0;
726 }
727
728 // Step 2. Return this's height, in CSS pixels.
729 self.bitmap_data
730 .borrow()
731 .as_ref()
732 .unwrap()
733 .size()
734 .cast()
735 .height
736 }
737
738 /// <https://html.spec.whatwg.org/multipage/#dom-imagebitmap-width>
739 fn Width(&self) -> u32 {
740 // Step 1. If this's [[Detached]] internal slot's value is true, then return 0.
741 if self.is_detached() {
742 return 0;
743 }
744
745 // Step 2. Return this's width, in CSS pixels.
746 self.bitmap_data
747 .borrow()
748 .as_ref()
749 .unwrap()
750 .size()
751 .cast()
752 .width
753 }
754
755 /// <https://html.spec.whatwg.org/multipage/#dom-imagebitmap-close>
756 fn Close(&self) {
757 // Step 1. Set this's [[Detached]] internal slot value to true.
758 // Step 2. Unset this's bitmap data.
759 // NOTE: The existence of the bitmap data is the internal slot in our implementation
760 self.bitmap_data.borrow_mut().take();
761 }
762}