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