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