Truly independent web browser
LibWeb: Implement ImageBitmap in Rust
Andreas Kling953e64b9172b
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex f13c6693e91..2de06231ceb 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -23,6 +23,7 @@ use libjs_rust::api::{RawNativeFunctionResult, Value, Vm};use super::canvas_gradient::CanvasGradient;use super::canvas_path::{self, CanvasPathError, RoundRectRadius};use super::canvas_pattern::CanvasPattern;+use super::image_bitmap::ImageBitmap;use super::image_data::{ImageData, ImageDataSettings};use super::path2d::Path2D;use super::predefined_color_space::PredefinedColorSpace;@@ -491,3 +492,65 @@ pub unsafe extern "C" fn web_image_data_pixels(image_data: *mut c_void) -> *mutlet image_data = unsafe { object_from_abi::<ImageData>(image_data) };image_data.pixels().map_or(core::ptr::null_mut(), NonNull::as_ptr)}++/// `frame` is a Gfx::DecodedImageFrame that the caller lends for the call, which the ImageBitmap keeps a copy of as its+/// bitmap data, or null for none.+///+/// # Safety+///+/// `vm` must be the live VM, and `frame` a live frame or null.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_image_bitmap_create(vm: *mut c_void, frame: *const c_void) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ // SAFETY: The caller passes a live frame.+ let frame = (!frame.is_null()).then(|| unsafe { ImageFrameHandle::retain(frame) });+ cell_into_abi(ImageBitmap::create(vm, frame))+}++/// # Safety+///+/// `image_bitmap` must be a live cell.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_image_bitmap_width(image_bitmap: *mut c_void) -> u32 {+ // SAFETY: The caller passes a live cell.+ unsafe { object_from_abi::<ImageBitmap>(image_bitmap) }.width_of_bitmap()+}++/// # Safety+///+/// `image_bitmap` must be a live cell.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_image_bitmap_height(image_bitmap: *mut c_void) -> u32 {+ // SAFETY: The caller passes a live cell.+ unsafe { object_from_abi::<ImageBitmap>(image_bitmap) }.height_of_bitmap()+}++/// # Safety+///+/// `image_bitmap` must be a live cell.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_image_bitmap_is_detached(image_bitmap: *mut c_void) -> bool {+ // SAFETY: The caller passes a live cell.+ unsafe { object_from_abi::<ImageBitmap>(image_bitmap) }.is_detached()+}++/// # Safety+///+/// `image_bitmap` must be a live cell.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_image_bitmap_close(image_bitmap: *mut c_void) {+ // SAFETY: The caller passes a live cell.+ unsafe { object_from_abi::<ImageBitmap>(image_bitmap) }.close_bitmap();+}++/// The Gfx::DecodedImageFrame of the bitmap data of the ImageBitmap, or null if it has none.+///+/// # Safety+///+/// `image_bitmap` must be a live cell. The frame is valid until the bitmap data is unset, by close() or a transfer.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_image_bitmap_frame(image_bitmap: *mut c_void) -> *const c_void {+ // SAFETY: The caller passes a live cell.+ unsafe { object_from_abi::<ImageBitmap>(image_bitmap) }.raw_frame()+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rsnew file mode 100644index 00000000000..0f3fda192db--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/image_bitmap.rs@@ -0,0 +1,232 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagebitmap++use core::cell::{Cell, RefCell};+use core::ffi::c_void;++use libgfx_rust::image_frame::ImageFrameHandle;+use libjs_rust::api::{RawNativeFunctionResult, Trace, Vm};++use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::structured_data::{+ Serializable, SerializationReader, SerializationWriter, TransferDataReader, TransferDataWriter, Transferable,+};+use crate::bindings::{CallContext, WebIdlResult};++unsafe extern "C" {+ // Defined in Libraries/LibWeb/HTML/ImageBitmap.cpp, which encodes and decodes the Gfx::Bitmap of a frame. A frame+ // that it hands over is a Gfx::DecodedImageFrame allocated with new, or null for none.+ fn web_image_bitmap_frame_size_in_bytes(frame: *const c_void) -> usize;+ fn web_image_bitmap_serialize_bitmap(serialized: *mut c_void, frame: *const c_void);+ fn web_image_bitmap_deserialize_bitmap(+ serialized: *mut c_void,+ out_frame: &mut *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_image_bitmap_transfer_bitmap(data_holder: *mut c_void, frame: *const c_void) -> RawNativeFunctionResult;+ fn web_image_bitmap_receive_bitmap(+ data_holder: *mut c_void,+ out_frame: &mut *mut c_void,+ ) -> RawNativeFunctionResult;+}++/// The bitmap data of an ImageBitmap: an image frame, which has the bitmap and keeps its id, so that each drawing of+/// the ImageBitmap names the same image.+struct BitmapData {+ frame: ImageFrameHandle,+ /// The size of the pixels of the bitmap, which the ImageBitmap counts as memory that it owns outside the heap.+ size_in_bytes: usize,+}++impl BitmapData {+ fn new(frame: ImageFrameHandle) -> Self {+ // SAFETY: The handle keeps the frame alive.+ let size_in_bytes = unsafe { web_image_bitmap_frame_size_in_bytes(frame.as_raw()) };+ Self { frame, size_in_bytes }+ }++ /// The bitmap data that C++ hands over, if any.+ ///+ /// # Safety+ ///+ /// `frame` must be a Gfx::DecodedImageFrame that C++ allocated with new for this, or null.+ unsafe fn from_handed_over_frame(frame: *mut c_void) -> Option<Self> {+ // SAFETY: The caller hands over a frame that C++ allocated with new, which nothing uses after this.+ (!frame.is_null()).then(|| Self::new(unsafe { ImageFrameHandle::adopt(frame) }))+ }+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct ImageBitmap {+ /// The bitmap data, which close() and the transfer steps unset.+ #[gc(untraced)]+ bitmap: RefCell<Option<BitmapData>>,+ /// The size of the bitmap data the ImageBitmap was created with, in CSS pixels.+ #[gc(untraced)]+ width: u32,+ #[gc(untraced)]+ height: u32,+ #[gc(untraced)]+ detached: Cell<bool>,+ // FIXME: An ImageBitmap object's bitmap has an origin-clean flag, which indicates whether the bitmap is tainted by+ // content from a different origin. The flag is initially set to true and may be changed to false by the+ // steps of createImageBitmap().+}++impl Wrappable for ImageBitmap {+ const OWNS_EXTERNAL_MEMORY: bool = true;++ fn external_memory_size(&self) -> usize {+ // NB: LibGC asks while it sweeps, when nothing borrows the bitmap data mutably.+ self.bitmap+ .try_borrow()+ .ok()+ .and_then(|bitmap| bitmap.as_ref().map(|bitmap| bitmap.size_in_bytes))+ .unwrap_or(0)+ }+}++impl ImageBitmap {+ fn new(bitmap: Option<BitmapData>) -> Self {+ let (width, height) = bitmap.as_ref().map_or((0, 0), |bitmap| {+ (+ u32::try_from(bitmap.frame.width()).expect("a bitmap has a width"),+ u32::try_from(bitmap.frame.height()).expect("a bitmap has a height"),+ )+ });+ Self {+ bitmap: RefCell::new(bitmap),+ width,+ height,+ detached: Cell::new(false),+ }+ }++ /// A new ImageBitmap whose bitmap data is the frame, or that has none.+ pub(crate) fn create(vm: &Vm, frame: Option<ImageFrameHandle>) -> Ref<Self> {+ allocate(vm, Self::new(frame.map(BitmapData::new)))+ }++ /// The frame of the bitmap data, unless the ImageBitmap has none, as when it is closed or transferred.+ pub(crate) fn frame(&self) -> Option<ImageFrameHandle> {+ self.bitmap.borrow().as_ref().map(|bitmap| bitmap.frame.clone())+ }++ /// The raw frame of the bitmap data, which stays valid until the bitmap data is unset.+ pub(crate) fn raw_frame(&self) -> *const c_void {+ self.bitmap+ .borrow()+ .as_ref()+ .map_or(core::ptr::null(), |bitmap| bitmap.frame.as_raw())+ }++ pub(crate) fn is_detached(&self) -> bool {+ self.detached.get()+ }++ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagebitmap-width+ pub(crate) fn width(&self, _: &mut CallContext) -> WebIdlResult<u32> {+ Ok(self.width_of_bitmap())+ }++ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagebitmap-height+ pub(crate) fn height(&self, _: &mut CallContext) -> WebIdlResult<u32> {+ Ok(self.height_of_bitmap())+ }++ pub(crate) fn width_of_bitmap(&self) -> u32 {+ // 1. If this's [[Detached]] internal slot's value is true, then return 0.+ if self.detached.get() {+ return 0;+ }+ // 2. Return this's width, in CSS pixels.+ self.width+ }++ pub(crate) fn height_of_bitmap(&self) -> u32 {+ // 1. If this's [[Detached]] internal slot's value is true, then return 0.+ if self.detached.get() {+ return 0;+ }+ // 2. Return this's height, in CSS pixels.+ self.height+ }++ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagebitmap-close+ pub(crate) fn close(&self, _: &mut CallContext) -> WebIdlResult<()> {+ self.close_bitmap();+ Ok(())+ }++ pub(crate) fn close_bitmap(&self) {+ // 1. Set this's [[Detached]] internal slot value to true.+ self.detached.set(true);++ // 2. Unset this's bitmap data.+ self.bitmap.replace(None);+ }+}++impl Serializable for ImageBitmap {+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:serialization-steps+ fn serialization_steps(+ &self,+ _: &mut CallContext,+ serialized: &mut SerializationWriter,+ _for_storage: bool,+ ) -> WebIdlResult<()> {+ // FIXME: 1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.++ // 2. Set serialized.[[BitmapData]] to a copy of value's bitmap data.+ // SAFETY: The writer is lent for the steps, and the frame lives while the bitmap data is set.+ unsafe { web_image_bitmap_serialize_bitmap(serialized.as_raw(), self.raw_frame()) };++ Ok(())+ }++ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:deserialization-steps+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {+ // 1. Set value's bitmap data to serialized.[[BitmapData]].+ let mut frame = core::ptr::null_mut();+ // SAFETY: The reader is lent for the steps.+ unsafe { web_image_bitmap_deserialize_bitmap(serialized.as_raw(), &mut frame) }.into_completion()?;+ // SAFETY: C++ hands over the frame it decoded, or null.+ Ok(Self::new(unsafe { BitmapData::from_handed_over_frame(frame) }))+ }+}++impl Transferable for ImageBitmap {+ fn detached(&self) -> &Cell<bool> {+ &self.detached+ }++ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:transfer-steps+ fn transfer_steps(&self, _: &mut CallContext, data_holder: &mut TransferDataWriter) -> WebIdlResult<()> {+ // FIXME: 1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.++ // 2. Set dataHolder.[[BitmapData]] to value's bitmap data.+ // NB: The pixels go to the shared memory of the transfer if there is room for them there, and inline otherwise.+ // SAFETY: The data holder is lent for the steps, and the frame lives while the bitmap data is set.+ unsafe { web_image_bitmap_transfer_bitmap(data_holder.as_raw(), self.raw_frame()) }.into_completion()?;++ // 3. Unset value's bitmap data.+ self.bitmap.replace(None);++ Ok(())+ }++ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:transfer-receiving-steps+ fn transfer_receiving_steps(_: &mut CallContext, data_holder: &mut TransferDataReader) -> WebIdlResult<Self> {+ // 1. Set value's bitmap data to dataHolder.[[BitmapData]].+ let mut frame = core::ptr::null_mut();+ // SAFETY: The data holder is lent for the steps.+ unsafe { web_image_bitmap_receive_bitmap(data_holder.as_raw(), &mut frame) }.into_completion()?;+ // SAFETY: C++ hands over the frame it decoded, or null.+ Ok(Self::new(unsafe { BitmapData::from_handed_over_frame(frame) }))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex 3a3776e339c..beca718088c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -4,8 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The objects that the 2D canvas contexts draw with, the image data that they and WebGL read and write the pixels of,-//! and the operations of a path that Path2D and the contexts share. The contexts are still LibWeb's C++, which creates and+//! The objects that the 2D canvas contexts draw with, the images that they and WebGL read and write the pixels of, and+//! the operations of a path that Path2D and the contexts share. The contexts are still LibWeb's C++, which creates and//! reads these objects and builds its paths through the C ABI of `exports`.pub(crate) mod canvas_path;@@ -20,6 +20,8 @@ pub(crate) mod canvas_pattern;#[cfg(not(test))]pub(crate) mod exports;#[cfg(not(test))]+pub(crate) mod image_bitmap;+#[cfg(not(test))]pub(crate) mod image_data;#[cfg(not(test))]pub(crate) mod path2d;diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rsindex 3391d5fd4b0..8526e595bfa 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs@@ -11,6 +11,7 @@use core::ffi::c_void;use core::ptr::NonNull;+use libgfx_rust::image_frame::ImageFrameHandle;use libjs_rust::api::{Gc, Object, Realm};use super::host::Frame;@@ -21,7 +22,6 @@ use crate::bindings::conversions::CppInterface;#[derive(Clone, Copy, Debug, PartialEq, Eq)]#[repr(u8)]pub(crate) enum TexImageSourceKind {- ImageBitmap,HTMLImageElement,HTMLCanvasElement,HTMLVideoElement,@@ -55,6 +55,12 @@ unsafe extern "C" {r#type: u32,out_frame: *mut *mut c_void,) -> u8;+ fn web_webgl_read_tex_image_frame(+ image_frame: *const c_void,+ format: u32,+ r#type: u32,+ out_frame: *mut *mut c_void,+ ) -> u8;fn web_webgl_read_tex_image_pixels(pixels: *const u8,width: u32,@@ -149,6 +155,15 @@ pub(crate) fn read_tex_image_source(tex_image_source_frame(result, frame)}+/// The frame of an image, a frame of an ImageBitmap, for the format and the type.+pub(crate) fn read_tex_image_frame(image_frame: &ImageFrameHandle, format: u32, r#type: u32) -> TexImageSourceFrame {+ let mut frame = core::ptr::null_mut();+ // SAFETY: The handle keeps the image frame alive, and the frame is stored when the function returns that there is+ // one.+ let result = unsafe { web_webgl_read_tex_image_frame(image_frame.as_raw(), format, r#type, &raw mut frame) };+ tex_image_source_frame(result, frame)+}+/// The frame of a copy of the pixels of an ImageData, for the format and the type.////// # Safetydiff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rsindex 49454c46c63..5b984fa18f5 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs@@ -14,7 +14,9 @@ use core::ops::Deref;use libjs_rust::api::{ForeignCellSlot, Gc, Realm, Trace, Visitor, Vm};-use super::canvas::{Canvas, TexImageSourceFrame, TexImageSourceKind, read_tex_image_pixels, read_tex_image_source};+use super::canvas::{+ Canvas, TexImageSourceFrame, TexImageSourceKind, read_tex_image_frame, read_tex_image_pixels, read_tex_image_source,+};use super::constants::{GL_BROWSER_DEFAULT_WEBGL, GL_CONTEXT_LOST_WEBGL, GL_INVALID_OPERATION, GL_INVALID_VALUE, GL_NO_ERROR,};@@ -358,9 +360,12 @@ impl ContextState {// bitmap's origin-clean flag is set to false, a SECURITY_ERR exception must be thrown. See Origin// Restrictions.let source_frame = match *source {- TexImageSource::ImageBitmap(object) => {- read_tex_image_source(object, TexImageSourceKind::ImageBitmap, format, r#type)- }+ TexImageSource::ImageBitmap(image_bitmap) => match image_bitmap.frame() {+ Some(image_frame) => read_tex_image_frame(&image_frame, format, r#type),+ // If this function is called with an ImageBitmap that has been neutered, an INVALID_VALUE error is+ // generated.+ None => TexImageSourceFrame::InvalidValue,+ },TexImageSource::ImageData(image_data) => match image_data.pixels() {Some(pixels) => {let (width, height) = image_data.size();diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_overloads.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_overloads.rsindex 87fa5c67906..2719a6c3a1f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_overloads.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/web_gl_rendering_context_overloads.rs@@ -23,12 +23,13 @@ use super::web_gl_uniform_location::WebGLUniformLocation;use crate::bindings::conversions::{ArrayBufferView, BufferSource, CppInterface};use crate::bindings::interface::Ref;use crate::bindings::{CallContext, WebIdlResult};+use crate::html::image_bitmap::ImageBitmap;use crate::html::image_data::ImageData;/// https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.8// FIXME: VideoFramepub(crate) enum TexImageSource {- ImageBitmap(CppInterface),+ ImageBitmap(Ref<ImageBitmap>),ImageData(Ref<ImageData>),HTMLImageElement(CppInterface),HTMLCanvasElement(CppInterface),diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cppindex a4437eb58f4..e4239d72c61 100644--- a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp+++ b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp@@ -85,10 +85,7 @@ Optional<Gfx::DecodedImageFrame> canvas_image_source_frame(CanvasImageSource conreturn Gfx::DecodedImageFrame { *bitmap };},[](GC::Ref<ImageBitmap> const& source) -> Optional<Gfx::DecodedImageFrame> {- auto bitmap = source->bitmap();- if (!bitmap)- return {};- return Gfx::DecodedImageFrame { *bitmap };+ return source->frame();},[](GC::Ref<OffscreenCanvas> const& source) -> Optional<Gfx::DecodedImageFrame> {auto bitmap = source->get_bitmap_from_surface();diff --git a/Libraries/LibWeb/HTML/ImageBitmap.cpp b/Libraries/LibWeb/HTML/ImageBitmap.cppindex d9e458cba5d..c82774ef555 100644--- a/Libraries/LibWeb/HTML/ImageBitmap.cpp+++ b/Libraries/LibWeb/HTML/ImageBitmap.cpp@@ -6,9 +6,11 @@#include <AK/Checked.h>#include <AK/NonnullOwnPtr.h>-#include <LibGC/Heap.h>#include <LibGfx/Bitmap.h>-#include <LibJS/Runtime/ExternalMemory.h>+#include <LibGfx/DecodedImageFrame.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>+#include <LibWeb/Bindings/RustSerialization.h>#include <LibWeb/HTML/ImageBitmap.h>#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWeb/WebIDL/DOMException.h>@@ -20,8 +22,6 @@namespace Web::HTML {-GC_DEFINE_ALLOCATOR(ImageBitmap);-static constexpr size_t shared_pixels_alignment = 64;[[nodiscard]] static WebIDL::ExceptionOr<void> validate_bitmap_layout(Gfx::BitmapFormat const format, Gfx::AlphaType const alpha_type, int const width, int const height)@@ -34,7 +34,7 @@ static constexpr size_t shared_pixels_alignment = 64;return {};}-[[nodiscard]] static WebIDL::ExceptionOr<NonnullRefPtr<Gfx::Bitmap>> create_bitmap_from_bitmap_data(JS::Realm& realm, Gfx::BitmapFormat const format, Gfx::AlphaType const alpha_type, int const width, int const height, size_t const pitch, ByteBuffer data)+[[nodiscard]] static WebIDL::ExceptionOr<NonnullRefPtr<Gfx::Bitmap>> create_bitmap_from_bitmap_data(JS::VM& vm, Gfx::BitmapFormat const format, Gfx::AlphaType const alpha_type, int const width, int const height, size_t const pitch, ByteBuffer data){TRY(validate_bitmap_layout(format, alpha_type, width, height));auto required_size = Checked<size_t> { pitch };@@ -42,9 +42,9 @@ static constexpr size_t shared_pixels_alignment = 64;if (pitch < Gfx::Bitmap::minimum_pitch(width, format) || required_size.has_overflow() || required_size.value() > data.size())return WebIDL::DataCloneError::create("Invalid ImageBitmap pixel buffer"_utf16);- auto bitmap_data = TRY_OR_THROW_OOM(realm.vm(), try_make<ByteBuffer>(move(data)));+ auto bitmap_data = TRY_OR_THROW_OOM(vm, try_make<ByteBuffer>(move(data)));auto* pixels = bitmap_data->data();- return TRY_OR_THROW_OOM(realm.vm(), Gfx::Bitmap::create_wrapper(format, alpha_type, Gfx::IntSize(width, height), pitch, pixels, [bitmap_data = move(bitmap_data)] { }));+ return TRY_OR_THROW_OOM(vm, Gfx::Bitmap::create_wrapper(format, alpha_type, Gfx::IntSize(width, height), pitch, pixels, [bitmap_data = move(bitmap_data)] { }));}template<typename T, typename Encoder>@@ -60,7 +60,7 @@ static WebIDL::ExceptionOr<void> encode_bitmap_value(Encoder& encoder, T const&}template<typename Encoder>-static WebIDL::ExceptionOr<void> serialize_bitmap(Encoder& encoder, RefPtr<Gfx::Bitmap> const& bitmap)+static WebIDL::ExceptionOr<void> serialize_bitmap(Encoder& encoder, Gfx::Bitmap const* bitmap){TRY(encode_bitmap_value(encoder, bitmap != nullptr));if (!bitmap)@@ -87,7 +87,7 @@ template<typename Decoder>auto const format = TRY(decode_or_throw_data_clone_error<Gfx::BitmapFormat>(realm, decoder));auto const alpha_type = TRY(decode_or_throw_data_clone_error<Gfx::AlphaType>(realm, decoder));auto data = TRY(decode_or_throw_data_clone_error<ByteBuffer>(realm, decoder));- return TRY(create_bitmap_from_bitmap_data(realm, format, alpha_type, width, height, pitch, move(data)));+ return TRY(create_bitmap_from_bitmap_data(realm.vm(), format, alpha_type, width, height, pitch, move(data)));}template<typename T>@@ -155,144 +155,152 @@ template<typename T>return TRY_OR_THROW_OOM(vm, Gfx::Bitmap::create_wrapper(format, alpha_type, size, pitch, pixels, [buffer = move(buffer)] { }));}-size_t ImageBitmap::shared_pixels_size(Gfx::Bitmap const& bitmap)+// 2. Set dataHolder.[[BitmapData]] to value's bitmap data, of+// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:transfer-steps+static WebIDL::ExceptionOr<void> transfer_bitmap(HTML::TransferDataEncoder& data_holder, ImageBitmapSharedPixels* shared_pixels, Gfx::Bitmap const* bitmap){- auto size = Gfx::Bitmap::size_in_bytes(Gfx::Bitmap::minimum_pitch(bitmap.width(), bitmap.format()), bitmap.height());- return round_up_to_power_of_two(size, shared_pixels_alignment);+ // NB: The pixels go to the shared memory if there is room for them there, and inline otherwise.+ if (shared_pixels && bitmap && ImageBitmap::shared_pixels_size(*bitmap) <= shared_pixels->buffer.size() - shared_pixels->used_size) {+ auto const pitch = Gfx::Bitmap::minimum_pitch(bitmap->width(), bitmap->format());+ auto* pixels = shared_pixels->buffer.data<u8>() + shared_pixels->used_size;+ for (int y = 0; y < bitmap->height(); ++y)+ memcpy(pixels + y * pitch, bitmap->scanline_u8(y), pitch);++ TRY(encode_bitmap_value(data_holder, true));+ TRY(encode_bitmap_value(data_holder, shared_pixels->buffer_index));+ TRY(encode_bitmap_value(data_holder, static_cast<u64>(shared_pixels->used_size)));+ TRY(encode_bitmap_value(data_holder, bitmap->width()));+ TRY(encode_bitmap_value(data_holder, bitmap->height()));+ TRY(encode_bitmap_value(data_holder, bitmap->format()));+ TRY(encode_bitmap_value(data_holder, bitmap->alpha_type()));+ shared_pixels->used_size += ImageBitmap::shared_pixels_size(*bitmap);+ } else {+ TRY(encode_bitmap_value(data_holder, false));+ TRY(serialize_bitmap(data_holder, bitmap));+ }+ return {};}-GC::Ref<ImageBitmap> ImageBitmap::create()+// 1. Set value's bitmap data to dataHolder.[[BitmapData]], of+// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:transfer-receiving-steps+static WebIDL::ExceptionOr<RefPtr<Gfx::Bitmap>> receive_bitmap(JS::Realm& realm, HTML::TransferDataDecoder& data_holder){- return GC::Heap::the().allocate<ImageBitmap>();+ auto const has_shared_pixels = TRY(decode_or_throw_data_clone_error<bool>(realm, data_holder));+ if (has_shared_pixels)+ return TRY(bitmap_from_shared_pixels(realm.vm(), data_holder));+ return TRY(deserialize_bitmap(realm, data_holder));}-ImageBitmap::ImageBitmap() = default;--ImageBitmap::~ImageBitmap() = default;--size_t ImageBitmap::external_memory_size() const+size_t ImageBitmap::shared_pixels_size(Gfx::Bitmap const& bitmap){- auto size = Base::external_memory_size();- if (m_bitmap)- size = JS::saturating_add_external_memory_size(size, m_bitmap->data_size());- return size;+ auto size = Gfx::Bitmap::size_in_bytes(Gfx::Bitmap::minimum_pitch(bitmap.width(), bitmap.format()), bitmap.height());+ return round_up_to_power_of_two(size, shared_pixels_alignment);}-// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:serialization-steps-WebIDL::ExceptionOr<void> ImageBitmap::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool, HTML::SerializationMemory&)+// Hands a decoded bitmap over to the Rust implementation as a frame that it takes over, or null for none.+static Gfx::DecodedImageFrame* frame_to_hand_over(RefPtr<Gfx::Bitmap> bitmap){- // FIXME: 1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.-- // 2. Set serialized.[[BitmapData]] to a copy of value's bitmap data.- TRY(serialize_bitmap(serialized, m_bitmap));-- return {};+ if (!bitmap)+ return nullptr;+ return new Gfx::DecodedImageFrame(*bitmap);}-// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:deserialization-steps-WebIDL::ExceptionOr<void> ImageBitmap::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory&)+extern "C" {++// Defined in Bindings/Rust/src/html/exports.rs.+void* web_image_bitmap_create(JSVM*, Gfx::DecodedImageFrame const* frame);+u32 web_image_bitmap_width(void const* image_bitmap);+u32 web_image_bitmap_height(void const* image_bitmap);+bool web_image_bitmap_is_detached(void const* image_bitmap);+void web_image_bitmap_close(void* image_bitmap);+Gfx::DecodedImageFrame const* web_image_bitmap_frame(void const* image_bitmap);++// What Bindings/Rust/src/html/image_bitmap.rs asks of C++, which owns the encoding of a Gfx::Bitmap: a bitmap that it+// is handed over is a Gfx::DecodedImageFrame allocated with new, or null for none.+size_t web_image_bitmap_frame_size_in_bytes(Gfx::DecodedImageFrame const*);+void web_image_bitmap_serialize_bitmap(Bindings::RustSerializationWriter*, Gfx::DecodedImageFrame const*);+JSCompletion web_image_bitmap_deserialize_bitmap(Bindings::RustSerializationReader*, Gfx::DecodedImageFrame** out_frame);+JSCompletion web_image_bitmap_transfer_bitmap(Bindings::RustTransferDataWriter*, Gfx::DecodedImageFrame const*);+JSCompletion web_image_bitmap_receive_bitmap(Bindings::RustTransferDataReader*, Gfx::DecodedImageFrame** out_frame);++size_t web_image_bitmap_frame_size_in_bytes(Gfx::DecodedImageFrame const* frame){- // 1. Set value's bitmap data to serialized.[[BitmapData]].- set_bitmap(TRY(deserialize_bitmap(realm, serialized)));-- return {};+ return frame->bitmap().data_size();}-// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:transfer-steps-WebIDL::ExceptionOr<void> ImageBitmap::transfer_steps(JS::Realm&, HTML::TransferDataEncoder& data_holder)+void web_image_bitmap_serialize_bitmap(Bindings::RustSerializationWriter* writer, Gfx::DecodedImageFrame const* frame){- return transfer_steps(data_holder, nullptr);+ MUST(serialize_bitmap(writer->serialized, frame ? &frame->bitmap() : nullptr));}-WebIDL::ExceptionOr<void> ImageBitmap::transfer_steps(HTML::TransferDataEncoder& data_holder, ImageBitmapSharedPixels* shared_pixels)+JSCompletion web_image_bitmap_deserialize_bitmap(Bindings::RustSerializationReader* reader, Gfx::DecodedImageFrame** out_frame){- // FIXME: 1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.-- // 2. Set dataHolder.[[BitmapData]] to value's bitmap data.- // NB: The pixels go to the shared memory if there is room for them there, and inline otherwise.- if (shared_pixels && m_bitmap && shared_pixels_size(*m_bitmap) <= shared_pixels->buffer.size() - shared_pixels->used_size) {- auto const pitch = Gfx::Bitmap::minimum_pitch(m_bitmap->width(), m_bitmap->format());- auto* pixels = shared_pixels->buffer.data<u8>() + shared_pixels->used_size;- for (int y = 0; y < m_bitmap->height(); ++y)- memcpy(pixels + y * pitch, m_bitmap->scanline_u8(y), pitch);-- TRY(encode_bitmap_value(data_holder, true));- TRY(encode_bitmap_value(data_holder, shared_pixels->buffer_index));- TRY(encode_bitmap_value(data_holder, static_cast<u64>(shared_pixels->used_size)));- TRY(encode_bitmap_value(data_holder, m_bitmap->width()));- TRY(encode_bitmap_value(data_holder, m_bitmap->height()));- TRY(encode_bitmap_value(data_holder, m_bitmap->format()));- TRY(encode_bitmap_value(data_holder, m_bitmap->alpha_type()));- shared_pixels->used_size += shared_pixels_size(*m_bitmap);- } else {- TRY(encode_bitmap_value(data_holder, false));- TRY(serialize_bitmap(data_holder, m_bitmap));- }-- // 3. Unset value's bitmap data.- m_bitmap = nullptr;-- return {};+ auto bitmap = deserialize_bitmap(reader->realm, reader->serialized);+ if (bitmap.is_exception())+ return Bindings::completion_to_abi(reader->realm, bitmap.release_error());+ *out_frame = frame_to_hand_over(bitmap.release_value());+ return Bindings::completion_to_abi(reader->realm, JS::js_undefined());}-// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagebitmap-interface:transfer-receiving-steps-WebIDL::ExceptionOr<void> ImageBitmap::transfer_receiving_steps(JS::Realm& realm, HTML::TransferDataDecoder& data_holder)+JSCompletion web_image_bitmap_transfer_bitmap(Bindings::RustTransferDataWriter* writer, Gfx::DecodedImageFrame const* frame){- // 1. Set value's bitmap data to dataHolder.[[BitmapData]].- auto const has_shared_pixels = TRY(decode_or_throw_data_clone_error<bool>(realm, data_holder));- if (has_shared_pixels)- set_bitmap(TRY(bitmap_from_shared_pixels(realm.vm(), data_holder)));- else- set_bitmap(TRY(deserialize_bitmap(realm, data_holder)));+ auto result = transfer_bitmap(writer->data_holder, writer->image_bitmap_pixels, frame ? &frame->bitmap() : nullptr);+ if (result.is_exception())+ return Bindings::completion_to_abi(writer->realm, result.release_error());+ return Bindings::completion_to_abi(writer->realm, JS::js_undefined());+}- return {};+JSCompletion web_image_bitmap_receive_bitmap(Bindings::RustTransferDataReader* reader, Gfx::DecodedImageFrame** out_frame)+{+ auto bitmap = receive_bitmap(reader->realm, reader->data_holder);+ if (bitmap.is_exception())+ return Bindings::completion_to_abi(reader->realm, bitmap.release_error());+ *out_frame = frame_to_hand_over(bitmap.release_value());+ return Bindings::completion_to_abi(reader->realm, JS::js_undefined());+}}-HTML::TransferType ImageBitmap::primary_interface() const+GC::Ref<ImageBitmap> ImageBitmap::create(RefPtr<Gfx::Bitmap const> bitmap){- return TransferType::ImageBitmap;+ Optional<Gfx::DecodedImageFrame> frame;+ if (bitmap)+ frame = Gfx::DecodedImageFrame { bitmap.release_nonnull() };+ auto* image_bitmap = web_image_bitmap_create(JS::HostABI::vm_to_abi(JS::VM::the()), frame.has_value() ? &frame.value() : nullptr);+ return GC::Ref { *static_cast<ImageBitmap*>(image_bitmap) };}-// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagebitmap-widthWebIDL::UnsignedLong ImageBitmap::width() const{- // 1. If this's [[Detached]] internal slot's value is true, then return 0.- if (is_detached())- return 0;- // 2. Return this's width, in CSS pixels.- return m_width;+ return web_image_bitmap_width(this);}-// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagebitmap-heightWebIDL::UnsignedLong ImageBitmap::height() const{- // 1. If this's [[Detached]] internal slot's value is true, then return 0.- if (is_detached())- return 0;- // 2. Return this's height, in CSS pixels.- return m_height;+ return web_image_bitmap_height(this);}-// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagebitmap-close-void ImageBitmap::close()+bool ImageBitmap::is_detached() const{- // 1. Set this's [[Detached]] internal slot value to true.- set_detached(true);+ return web_image_bitmap_is_detached(this);+}- // 2. Unset this's bitmap data.- m_bitmap = nullptr;+void ImageBitmap::close()+{+ web_image_bitmap_close(this);}-void ImageBitmap::set_bitmap(RefPtr<Gfx::Bitmap> bitmap)+Optional<Gfx::DecodedImageFrame> ImageBitmap::frame() const{- m_bitmap = move(bitmap);- m_width = m_bitmap ? m_bitmap->width() : 0;- m_height = m_bitmap ? m_bitmap->height() : 0;+ if (auto const* frame = web_image_bitmap_frame(this))+ return *frame;+ return {};}-Gfx::Bitmap* ImageBitmap::bitmap() const+Gfx::Bitmap const* ImageBitmap::bitmap() const{- return m_bitmap.ptr();+ if (auto const* frame = web_image_bitmap_frame(this))+ return &frame->bitmap();+ return nullptr;}}diff --git a/Libraries/LibWeb/HTML/ImageBitmap.h b/Libraries/LibWeb/HTML/ImageBitmap.hindex 475c709d775..abe846c3773 100644--- a/Libraries/LibWeb/HTML/ImageBitmap.h+++ b/Libraries/LibWeb/HTML/ImageBitmap.h@@ -6,16 +6,17 @@#pragma once-#include <AK/OwnPtr.h>+#include <AK/Optional.h>+#include <AK/RefPtr.h>#include <AK/Types.h>#include <LibCore/AnonymousBuffer.h>#include <LibGfx/Forward.h>#include <LibWeb/Bindings/ImageBitmap.h>-#include <LibWeb/Bindings/Serializable.h>-#include <LibWeb/Bindings/Transferable.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>#include <LibWeb/Forward.h>#include <LibWeb/HTML/Canvas/CanvasDrawImage.h>+#include <LibWebCommon/WebIDL/Types.h>namespace Web::HTML {@@ -35,53 +36,31 @@ struct ImageBitmapSharedPixels {size_t used_size { 0 };};-class WEB_API ImageBitmap final- : public Bindings::GCAllocatedWrappable- , public Web::Bindings::Serializable- , public Web::Bindings::Transferable {- WEB_WRAPPABLE(ImageBitmap, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(ImageBitmap);+// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagebitmap+// The C++ side of an ImageBitmap, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what+// createImageBitmap(), OffscreenCanvas and WebDriver create, and the 2D contexts draw. ImageBitmap.cpp encodes and+// decodes the bitmap data for the serialization and transfer steps of the Rust implementation.+class WEB_API ImageBitmap final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(ImageBitmap, image_bitmap)public:- static GC::Ref<ImageBitmap> create();- virtual ~ImageBitmap() override;-- // ^Web::Bindings::Serializable- virtual WebIDL::ExceptionOr<void> serialization_steps(HTML::StructuredSerializeWriter&, bool for_storage, HTML::SerializationMemory&) override;- virtual WebIDL::ExceptionOr<void> deserialization_steps(JS::Realm&, HTML::StructuredSerializeReader&, HTML::DeserializationMemory&) override;-- // ^Web::Bindings::Transferable- virtual WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, HTML::TransferDataEncoder&) override;- virtual WebIDL::ExceptionOr<void> transfer_receiving_steps(JS::Realm&, HTML::TransferDataDecoder&) override;- virtual HTML::TransferType primary_interface() const override;+ // A new ImageBitmap whose bitmap data is the bitmap, or that has none.+ static GC::Ref<ImageBitmap> create(RefPtr<Gfx::Bitmap const>);WebIDL::UnsignedLong width() const;WebIDL::UnsignedLong height() const;+ // https://html.spec.whatwg.org/multipage/structured-data.html#detached+ bool is_detached() const;++ // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagebitmap-closevoid close();- // Implementation specific:+ // The bitmap data, which the ImageBitmap keeps until it is closed or transferred.+ Optional<Gfx::DecodedImageFrame> frame() const;+ Gfx::Bitmap const* bitmap() const;static size_t shared_pixels_size(Gfx::Bitmap const&);- WebIDL::ExceptionOr<void> transfer_steps(HTML::TransferDataEncoder&, ImageBitmapSharedPixels*);-- void set_bitmap(RefPtr<Gfx::Bitmap>);- Gfx::Bitmap* bitmap() const;--private:- ImageBitmap();-- // FIXME: We don't implement this flag yet:- // An ImageBitmap object's bitmap has an origin-clean flag, which indicates whether the bitmap is tainted by content- // from a different origin. The flag is initially set to true and may be changed to false by the steps of- // createImageBitmap().-- virtual size_t external_memory_size() const override;-- WebIDL::UnsignedLong m_width = 0;- WebIDL::UnsignedLong m_height = 0;-- RefPtr<Gfx::Bitmap> m_bitmap;};}diff --git a/Libraries/LibWeb/HTML/ImageBitmap.idl b/Libraries/LibWeb/HTML/ImageBitmap.idlindex 7a5f91827e5..7b38cf596e8 100644--- a/Libraries/LibWeb/HTML/ImageBitmap.idl+++ b/Libraries/LibWeb/HTML/ImageBitmap.idl@@ -1,5 +1,5 @@// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#images-2-[Exposed=(Window,Worker), Serializable, Transferable]+[Exposed=(Window,Worker), Serializable, Transferable, ImplementedIn=Rust]interface ImageBitmap {readonly attribute unsigned long width;readonly attribute unsigned long height;diff --git a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp b/Libraries/LibWeb/HTML/OffscreenCanvas.cppindex 76dac9cd1ea..3ef263a6fc5 100644--- a/Libraries/LibWeb/HTML/OffscreenCanvas.cpp+++ b/Libraries/LibWeb/HTML/OffscreenCanvas.cpp@@ -217,8 +217,7 @@ WebIDL::ExceptionOr<GC::Ref<ImageBitmap>> OffscreenCanvas::transfer_to_image_bit}// 3. Let image be a newly created ImageBitmap object that references the same underlying bitmap data as this OffscreenCanvas object's bitmap.- auto image = ImageBitmap::create();- image->set_bitmap(get_bitmap_from_surface());+ auto image = ImageBitmap::create(get_bitmap_from_surface());// 4. Set this OffscreenCanvas object's bitmap to reference a newly created bitmap of the same dimensions and color space as the previous bitmap, and with its pixels initialized to transparent black, or opaque black if the rendering context' s alpha is false.if (auto* context = m_context.get_pointer<GC::Ref<OffscreenCanvasRenderingContext2D>>())diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cppindex b2f1cbbe710..a59a25d6f07 100644--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp@@ -2353,10 +2353,7 @@ WebIDL::ExceptionOr<SerializedTransferRecord> structured_serialize_with_transferMUST(data_holder.encode(interface_name));// 4. Perform the appropriate transfer steps for the interface identified by interfaceName, given transferable and dataHolder.- if (interface_name == TransferType::ImageBitmap)- TRY(Bindings::impl_from<ImageBitmap>(transferable.ptr())->transfer_steps(data_holder, image_bitmap_pixels.has_value() ? &image_bitmap_pixels.value() : nullptr));- else- TRY(transferable_object.transfer_steps(realm, data_holder, image_bitmap_pixels.has_value() ? &image_bitmap_pixels.value() : nullptr));+ TRY(transferable_object.transfer_steps(realm, data_holder, image_bitmap_pixels.has_value() ? &image_bitmap_pixels.value() : nullptr));// 5. Set transferable.[[Detached]] to true.transferable_object.set_detached();diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex 3092c7c1f89..4a056bf5f45 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -454,7 +454,8 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,return;// 5. Let imageBitmap be a new ImageBitmap object.- auto image_bitmap = ImageBitmap::create();+ // NB: Each case below creates imageBitmap once it has the bitmap data, which nothing can tell apart from setting the+ // bitmap data of an ImageBitmap that was created here.// 6. Switch on image:image.visit(@@ -491,7 +492,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,}));};- auto on_successful_decode = [image_bitmap = GC::Root(*image_bitmap), p = GC::Root(*p), sx, sy, sw, sh, options](Web::Platform::DecodedImage& result) -> ErrorOr<void> {+ auto on_successful_decode = [p = GC::Root(*p), sx, sy, sw, sh, options](Web::Platform::DecodedImage& result) -> ErrorOr<void> {if (Core::StatsLog::the())end_rendering_pending_operation(GC::as_cell(p.ptr()));// 4. Set imageBitmap's bitmap data to imageData, cropped to the source rectangle with formatting.@@ -510,7 +511,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,}));return {};}- image_bitmap->set_bitmap(cropped_bitmap_or_error.release_value());+ auto image_bitmap = ImageBitmap::create(cropped_bitmap_or_error.release_value());auto& realm = WebIDL::promise_realm(*p);@@ -555,7 +556,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image size is invalid"_utf16));return;}- image_bitmap->set_bitmap(cropped_bitmap_or_error.release_value());+ auto image_bitmap = ImageBitmap::create(cropped_bitmap_or_error.release_value());// 4. Queue a global task, using the bitmap task source, to resolve promise with imageBitmap.queue_global_task(Task::Source::BitmapTask, realm.global_object(), GC::create_function(GC::Heap::the(), [p, image_bitmap] {@@ -584,7 +585,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image size is invalid"_utf16));return;}- image_bitmap->set_bitmap(cropped_bitmap_or_error.release_value());+ auto image_bitmap = ImageBitmap::create(cropped_bitmap_or_error.release_value());// FIXME: 2. Set the origin-clean flag of the imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap.@@ -597,6 +598,13 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,},// -> ImageBitmap[&](GC::Ref<ImageBitmap> source_image_bitmap) {+ // AD-HOC: An ImageBitmap that is not detached has no bitmap data if the bitmap it was created from+ // had none, as that of an OffscreenCanvas that has no size.+ if (!source_image_bitmap->bitmap()) {+ WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image size is invalid"_utf16));+ return;+ }+// 1. Set imageBitmap's bitmap data to a copy of image's bitmap data, cropped to the source rectangle with formatting.auto cropped_bitmap_or_error = crop_to_the_source_rectangle_with_formatting(compositor_host_for(realm.global_object()), source_image_bitmap->bitmap(), sx, sy, sw, sh, options);// AD-HOC: Reject promise with an "InvalidStateError" DOMException on allocation failure@@ -605,7 +613,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image size is invalid"_utf16));return;}- image_bitmap->set_bitmap(cropped_bitmap_or_error.release_value());+ auto image_bitmap = ImageBitmap::create(cropped_bitmap_or_error.release_value());// FIXME: 2. Set the origin-clean flag of imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap.@@ -661,7 +669,7 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image size is invalid"_utf16));return;}- image_bitmap->set_bitmap(cropped_bitmap_or_error.release_value());+ auto image_bitmap = ImageBitmap::create(cropped_bitmap_or_error.release_value());// FIXME: 4. If image is not origin-clean, then set the origin-clean flag of imageBitmap's bitmap to false.diff --git a/Libraries/LibWeb/WebDriver/Screenshot.cpp b/Libraries/LibWeb/WebDriver/Screenshot.cppindex 0b10ec1b8b9..25486e6b4b2 100644--- a/Libraries/LibWeb/WebDriver/Screenshot.cpp+++ b/Libraries/LibWeb/WebDriver/Screenshot.cpp@@ -71,8 +71,7 @@ void draw_bounding_box_from_the_framebuffer(HTML::BrowsingContext& browsing_contbrowsing_context.active_document()->navigable()->render_screenshot(bitmap, paint_config, [bitmap, element = GC::make_root(element), canvas = GC::make_root(canvas), callback = move(callback)] mutable {HTML::TemporaryExecutionContext execution_context { element->document().relevant_settings_object() };- auto image_bitmap = HTML::ImageBitmap::create();- image_bitmap->set_bitmap(bitmap);+ auto image_bitmap = HTML::ImageBitmap::create(bitmap);if (canvas->canvas_rendering_context_2d()->draw_image(image_bitmap, 0, 0).is_exception()) {callback(Error::from_code(ErrorCode::UnableToCaptureScreen, "Failed to draw the screenshot to the canvas"sv));return;diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cppindex 3bee048d4e6..6a2e9e591f4 100644--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp@@ -24,7 +24,6 @@#include <LibWeb/HTML/HTMLCanvasElement.h>#include <LibWeb/HTML/HTMLImageElement.h>#include <LibWeb/HTML/HTMLVideoElement.h>-#include <LibWeb/HTML/ImageBitmap.h>#include <LibWeb/HTML/OffscreenCanvas.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>@@ -74,7 +73,6 @@ struct ContextCreationArguments {// `TexImageSourceKind` and `TexImageSourceResult` of Bindings/Rust/src/web_gl/canvas.rs. The kinds are the sources// that are implemented in C++.enum class TexImageSourceKind : u8 {- ImageBitmap,HTMLImageElement,HTMLCanvasElement,HTMLVideoElement,@@ -130,6 +128,7 @@ bool web_webgl_expose_experimental_interfaces();bool web_webgl_is_valid_2d_pixel_unpack_state(i32 width, PixelUnpackState const* unpack_state);bool web_webgl_required_2d_texture_data_size(i32 width, i32 height, u32 format, u32 type, PixelUnpackState const* unpack_state, size_t* out_size);TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexImageSourceKind, u32 format, u32 type, void** out_frame);+TexImageSourceResult web_webgl_read_tex_image_frame(Gfx::DecodedImageFrame const* image_frame, u32 format, u32 type, void** out_frame);TexImageSourceResult web_webgl_read_tex_image_pixels(u8 const* pixels, u32 width, u32 height, u32 format, u32 type, void** out_frame);void* web_webgl_make_xr_compatible(void* context);}@@ -499,8 +498,6 @@ static TexImageSourceResult tex_image_source_frame(Optional<Compositing::WebGL::TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexImageSourceKind source_kind, u32 format, u32 type, void** out_frame){- // FIXME: If this function is called with an ImageBitmap that has been neutered, an INVALID_VALUE- // error is generated.// FIXME: If source is null then an INVALID_VALUE error is generated.auto& wrapper = *static_cast<JS::Object*>(source_wrapper);Optional<Compositing::WebGL::ImageSourceFrame> frame;@@ -521,13 +518,16 @@ TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexImif (auto captured_frame = Bindings::impl_from<HTML::HTMLVideoElement>(wrapper).capture_current_video_frame(); captured_frame.has_value())frame = captured_frame.release_value();break;- case TexImageSourceKind::ImageBitmap:- frame = Gfx::DecodedImageFrame { *Bindings::impl_from<HTML::ImageBitmap>(wrapper).bitmap() };- break;}return tex_image_source_frame(move(frame), format, type, out_frame);}+// The bitmap data of an ImageBitmap.+TexImageSourceResult web_webgl_read_tex_image_frame(Gfx::DecodedImageFrame const* image_frame, u32 format, u32 type, void** out_frame)+{+ return tex_image_source_frame(Compositing::WebGL::ImageSourceFrame { *image_frame }, format, type, out_frame);+}+// The pixels of an ImageData, which are copied: script can change them, and detach or free their buffer, before the// recorder sends the frame.TexImageSourceResult web_webgl_read_tex_image_pixels(u8 const* pixels, u32 width, u32 height, u32 format, u32 type, void** out_frame)diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex f1e556085dd..27229f130df 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -52,8 +52,8 @@ ALLOWED_REALM_MENTIONS = {"FileAPI": (6, 11, "File/Blob/FileReader algorithms still create streams, buffers, and events in selected realms"),"Geometry": (8, 8, "geometry constructors and structured clone still materialize JS-facing geometry objects"),"HTML": (- 71,- 217,+ 70,+ 211,"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage",),"IndexedDB": (diff --git a/Tests/LibWeb/TestStructuredSerializeFormat.cpp b/Tests/LibWeb/TestStructuredSerializeFormat.cppindex ae2604875f9..5ef460e210e 100644--- a/Tests/LibWeb/TestStructuredSerializeFormat.cpp+++ b/Tests/LibWeb/TestStructuredSerializeFormat.cpp@@ -617,8 +617,7 @@ TEST_CASE(image_serializables_encode_to_frozen_bytes){auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, { 2, 2 }));- auto image_bitmap = Web::HTML::ImageBitmap::create();- image_bitmap->set_bitmap(bitmap);+ auto image_bitmap = Web::HTML::ImageBitmap::create(bitmap);// Use the bitmap's actual pitch and data size.ReadonlyBytes data { bitmap->scanline_u8(0), bitmap->data_size() };@@ -634,9 +633,13 @@ static GC::Ref<JS::Object> wrap_image_bitmap(JS::Realm& realm, GC::Ref<Web::HTMLstatic GC::Ref<Web::HTML::ImageBitmap> create_image_bitmap(NonnullRefPtr<Gfx::Bitmap> bitmap){- auto image_bitmap = Web::HTML::ImageBitmap::create();- image_bitmap->set_bitmap(move(bitmap));- return image_bitmap;+ return Web::HTML::ImageBitmap::create(move(bitmap));+}++// The transfer-receiving steps of an ImageBitmap, which create the ImageBitmap.+static Web::WebIDL::ExceptionOr<GC::Ref<JS::HostObject>> receive_image_bitmap(JS::Realm& realm, Web::HTML::TransferDataDecoder& decoder)+{+ return Web::Bindings::create_transferred_platform_object(Web::HTML::TransferType::ImageBitmap, realm, decoder);}static Vector<JS::Value> deserialize_transfer_data_holders(JS::Realm& realm, Web::HTML::SerializedTransferRecord& record)@@ -868,8 +871,7 @@ TEST_CASE(image_bitmap_transfer_rejects_invalid_shared_pixels)Web::HTML::TransferDataDecoder decoder { move(holder) };if (buffers)decoder.set_shared_buffers(*buffers);- auto receiver = Web::HTML::ImageBitmap::create();- return receiver->transfer_receiving_steps(realm, decoder);+ return receive_image_bitmap(realm, decoder);};EXPECT(!receive(&shared_buffers, 0, 0, Gfx::BitmapFormat::BGRA8888, 16).is_error());EXPECT(receive(nullptr, 0, 0, Gfx::BitmapFormat::BGRA8888, 16).is_error());@@ -884,8 +886,9 @@ TEST_CASE(image_bitmap_transfer_rejects_invalid_shared_pixels)TEST_CASE(image_bitmap_transfer_protects_against_backing_truncation){auto& realm = test_realm();- auto source = create_image_bitmap(MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, { 16, 1 })));- source->bitmap()->set_pixel(0, 0, Gfx::Color::Red);+ auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, { 16, 1 }));+ bitmap->set_pixel(0, 0, Gfx::Color::Red);+ auto source = create_image_bitmap(bitmap);auto wrapper = wrap_image_bitmap(realm, source);Array<GC::Ref<JS::Object>, 1> transfer { wrapper };auto record = MUST(Web::HTML::structured_serialize_with_transfer(realm, wrapper, transfer));@@ -904,8 +907,8 @@ TEST_CASE(image_bitmap_transfer_protects_against_backing_truncation)Web::HTML::TransferDataDecoder decoder { move(record.transfer_data_holders[0]) };EXPECT_EQ(MUST(decoder.decode<Web::HTML::TransferType>()), Web::HTML::TransferType::ImageBitmap);decoder.set_shared_buffers(record.shared_buffers);- auto receiver = Web::HTML::ImageBitmap::create();- MUST(receiver->transfer_receiving_steps(realm, decoder));+ auto received = MUST(receive_image_bitmap(realm, decoder));+ auto& receiver = unwrap_wrappable<Web::HTML::ImageBitmap>(JS::Value(static_cast<JS::Object*>(received.ptr())));# if defined(AK_OS_LINUX)auto const seals = fcntl(buffer.fd(), F_GET_SEALS);EXPECT(seals >= 0);@@ -917,8 +920,8 @@ TEST_CASE(image_bitmap_transfer_protects_against_backing_truncation)# elseEXPECT_EQ(ftruncate(buffer.fd(), 0), 0);# endif- EXPECT_EQ(receiver->bitmap()->get_pixel(0, 0), Gfx::Color::Red);- receiver->close();+ EXPECT_EQ(receiver.bitmap()->get_pixel(0, 0), Gfx::Color::Red);+ receiver.close();}#endif@@ -939,9 +942,7 @@ TEST_CASE(image_bitmap_transfer_rejects_unsealed_backing)MUST(holder.encode(Gfx::AlphaType::Premultiplied));Web::HTML::TransferDataDecoder decoder { move(holder) };decoder.set_shared_buffers(shared_buffers);- auto receiver = Web::HTML::ImageBitmap::create();- EXPECT(receiver->transfer_receiving_steps(realm, decoder).is_error());- EXPECT_EQ(receiver->bitmap(), nullptr);+ EXPECT(receive_image_bitmap(realm, decoder).is_error());EXPECT_EQ(ftruncate(shared_buffers[0].fd(), 0), 0);}#endif@@ -960,8 +961,7 @@ TEST_CASE(image_bitmap_transfer_rejects_invalid_inline_pixels)MUST(holder.encode(Gfx::AlphaType::Premultiplied));MUST(holder.encode(pixels));Web::HTML::TransferDataDecoder decoder { move(holder) };- auto receiver = Web::HTML::ImageBitmap::create();- return receiver->transfer_receiving_steps(realm, decoder);+ return receive_image_bitmap(realm, decoder);};Array<u8, 4> pixels {};EXPECT(!receive(Gfx::BitmapFormat::BGRA8888, 4, pixels).is_error());diff --git a/Tests/LibWeb/Text/expected/canvas/image-bitmap-in-rust.txt b/Tests/LibWeb/Text/expected/canvas/image-bitmap-in-rust.txtnew file mode 100644index 00000000000..063b4c0ebfc--- /dev/null+++ b/Tests/LibWeb/Text/expected/canvas/image-bitmap-in-rust.txt@@ -0,0 +1,10 @@+ImageBitmap: [object ImageBitmap], 2x1+cloned ImageBitmap: 2x1, 255,0,0,255,0,255,0,128+closed ImageBitmap: 0x0+clone of a closed ImageBitmap: 0x0+transfer of a closed ImageBitmap: DataCloneError+drawImage of a closed ImageBitmap: InvalidStateError+ImageBitmap without bitmap data: 0x0+createImageBitmap from it: InvalidStateError+texImage2D from ImageBitmap: 255,0,0,255,0,255,0,128+texImage2D from a closed ImageBitmap: INVALID_VALUEdiff --git a/Tests/LibWeb/Text/input/canvas/image-bitmap-in-rust.html b/Tests/LibWeb/Text/input/canvas/image-bitmap-in-rust.htmlnew file mode 100644index 00000000000..435465860e4--- /dev/null+++ b/Tests/LibWeb/Text/input/canvas/image-bitmap-in-rust.html@@ -0,0 +1,85 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ function outcome(f) {+ try {+ const result = f();+ return `${result}`;+ } catch (error) {+ return error.name;+ }+ }++ function pixelsOfBitmap(bitmap) {+ const canvas = document.createElement("canvas");+ canvas.width = bitmap.width;+ canvas.height = bitmap.height;+ const context = canvas.getContext("2d");+ context.drawImage(bitmap, 0, 0);+ return Array.from(context.getImageData(0, 0, canvas.width, canvas.height).data).join(",");+ }++ function errorName(gl, error) {+ for (const name of ["NO_ERROR", "INVALID_ENUM", "INVALID_VALUE", "INVALID_OPERATION"]) {+ if (gl[name] === error)+ return name;+ }+ return `0x${error.toString(16)}`;+ }++ // Uploads the source to a 2x1 texture and reads the texture back.+ function uploadAndReadBack(gl, source) {+ while (gl.getError() !== gl.NO_ERROR) {+ }+ const texture = gl.createTexture();+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);+ const error = errorName(gl, gl.getError());+ if (error !== "NO_ERROR")+ return error;+ const framebuffer = gl.createFramebuffer();+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);+ const pixels = new Uint8Array(8);+ gl.readPixels(0, 0, 2, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ return Array.from(pixels).join(",");+ }++ asyncTest(async done => {+ const canvas = document.createElement("canvas");+ canvas.width = canvas.height = 2;+ const context = canvas.getContext("2d");+ const original = new ImageData(new Uint8ClampedArray([255, 0, 0, 255, 0, 255, 0, 128]), 2, 1);++ const bitmap = await createImageBitmap(original);+ println(`ImageBitmap: ${Object.prototype.toString.call(bitmap)}, ${bitmap.width}x${bitmap.height}`);+ const clonedBitmap = structuredClone(bitmap);+ println(`cloned ImageBitmap: ${clonedBitmap.width}x${clonedBitmap.height}, ${pixelsOfBitmap(clonedBitmap)}`);+ const closed = await createImageBitmap(original);+ closed.close();+ println(`closed ImageBitmap: ${closed.width}x${closed.height}`);+ println(`clone of a closed ImageBitmap: ${outcome(() => { const c = structuredClone(closed); return `${c.width}x${c.height}`; })}`);+ println(`transfer of a closed ImageBitmap: ${outcome(() => structuredClone(closed, { transfer: [closed] }))}`);+ println(`drawImage of a closed ImageBitmap: ${outcome(() => context.drawImage(closed, 0, 0))}`);++ // An ImageBitmap of an OffscreenCanvas without pixels has no bitmap data.+ const empty = new OffscreenCanvas(0, 0);+ empty.getContext("2d");+ const emptyBitmap = empty.transferToImageBitmap();+ println(`ImageBitmap without bitmap data: ${emptyBitmap.width}x${emptyBitmap.height}`);+ try {+ await createImageBitmap(emptyBitmap);+ println("createImageBitmap from it: resolved");+ } catch (error) {+ println(`createImageBitmap from it: ${error.name}`);+ }++ // WebGL reads its pixels.+ const gl = document.createElement("canvas").getContext("webgl");+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ println(`texImage2D from ImageBitmap: ${uploadAndReadBack(gl, bitmap)}`);+ println(`texImage2D from a closed ImageBitmap: ${uploadAndReadBack(gl, closed)}`);+ done();+ });+</script>