Skip to content

Truly independent web browser

LibWeb: Implement ImageData in Rust

Andreas Kling9262f5073255
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
index ac3549a0631..f13c6693e91 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
@@ -9,6 +9,7 @@
//! is the cell of an object of the interface that the name of the function says.
use core::ffi::c_void;
+use core::ptr::NonNull;
use ak::Utf16String;
use libcompositing_rust::display_list::canvas_2d::Paint;
@@ -17,14 +18,17 @@ use libcompositing_rust::display_list::commands::{Canvas2DPaintKind, Canvas2DPat
use libgfx_rust::AffineTransform;
use libgfx_rust::image_frame::ImageFrameHandle;
use libgfx_rust::path::PathMut;
-use libjs_rust::api::Vm;
+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_data::{ImageData, ImageDataSettings};
use super::path2d::Path2D;
+use super::predefined_color_space::PredefinedColorSpace;
use super::text_metrics::{TextMeasurements, TextMetrics};
-use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi};
+use crate::bindings::CallContext;
+use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments};
/// # Safety
///
@@ -419,3 +423,71 @@ pub unsafe extern "C" fn web_path2d_path(path: *mut c_void) -> *const c_void {
// SAFETY: The caller keeps the path from changing while it reads it.
unsafe { path.path_unguarded() }.as_raw()
}
+
+/// Creates an ImageData of the size, with transparent black pixels, in the realm, as the 2D contexts do, and stores
+/// its cell, or throws what initializing an ImageData throws.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `realm` a live realm.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_data_create(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ width: u32,
+ height: u32,
+ has_color_space: bool,
+ color_space: PredefinedColorSpace,
+ out_image_data: &mut *mut c_void,
+) -> RawNativeFunctionResult {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ let mut cx = CallContext::new(vm, realm);
+ let settings = ImageDataSettings {
+ color_space: has_color_space.then_some(color_space),
+ };
+ let result = ImageData::create(&mut cx, width, height, Some(&settings)).map(|image_data| {
+ *out_image_data = cell_into_abi(image_data);
+ Value::UNDEFINED
+ });
+ RawNativeFunctionResult::from_completion(result.map_err(|exception| exception.throw(&cx)))
+}
+
+/// # Safety
+///
+/// `image_data` must be a live cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_data_width(image_data: *mut c_void) -> u32 {
+ // SAFETY: The caller passes a live cell.
+ unsafe { object_from_abi::<ImageData>(image_data) }.size().0
+}
+
+/// # Safety
+///
+/// `image_data` must be a live cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_data_height(image_data: *mut c_void) -> u32 {
+ // SAFETY: The caller passes a live cell.
+ unsafe { object_from_abi::<ImageData>(image_data) }.size().1
+}
+
+/// # Safety
+///
+/// `image_data` must be a live cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_data_is_detached(image_data: *mut c_void) -> bool {
+ // SAFETY: The caller passes a live cell.
+ unsafe { object_from_abi::<ImageData>(image_data) }.is_detached()
+}
+
+/// The first byte of the pixels of the ImageData, or null if its buffer is detached or its data has no room for them.
+///
+/// # Safety
+///
+/// `image_data` must be a live cell. The pixels are valid until script runs.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_image_data_pixels(image_data: *mut c_void) -> *mut u8 {
+ // SAFETY: The caller passes a live cell.
+ let image_data = unsafe { object_from_abi::<ImageData>(image_data) };
+ image_data.pixels().map_or(core::ptr::null_mut(), NonNull::as_ptr)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/image_data.rs b/Libraries/LibWeb/Bindings/Rust/src/html/image_data.rs
new file mode 100644
index 00000000000..641687dc4ae
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/image_data.rs
@@ -0,0 +1,335 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagedata
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::{
+ ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, Gc, RawNativeFunctionResult, Trace, TypedArrayBase,
+ TypedArrayKind, Value, create_typed_array_on_buffer, is_typed_array_out_of_bounds,
+ make_typed_array_with_buffer_witness_record, typed_array_byte_length,
+};
+
+use super::predefined_color_space::PredefinedColorSpace;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+unsafe extern "C" {
+ // Defined in Libraries/LibWeb/HTML/ImageData.cpp, which encodes the color space as StructuredSerialize encodes a
+ // Web::Bindings::PredefinedColorSpace.
+ fn web_image_data_serialize_color_space(serialized: *mut c_void, color_space: PredefinedColorSpace);
+ fn web_image_data_deserialize_color_space(
+ serialized: *mut c_void,
+ out_color_space: &mut u8,
+ ) -> RawNativeFunctionResult;
+}
+
+/// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagedatasettings
+#[derive(Clone, Copy, Debug, Default)]
+pub(crate) struct ImageDataSettings {
+ pub(crate) color_space: Option<PredefinedColorSpace>,
+}
+
+/// The size of a pixel of an ImageData, whose pixels are RGBA8888.
+const BYTES_PER_PIXEL: u32 = 4;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ImageData {
+ /// The Uint8ClampedArray of the data attribute, in whose buffer the pixels are, RGBA8888 and unpremultiplied, row
+ /// by row. Script can detach the buffer, and shrink one that is resizable, at any time.
+ data: Gc<TypedArrayBase>,
+ #[gc(untraced)]
+ width: u32,
+ #[gc(untraced)]
+ height: u32,
+ #[gc(untraced)]
+ color_space: PredefinedColorSpace,
+}
+
+impl Wrappable for ImageData {}
+
+/// Whether the typed array has room for the pixels of an ImageData of the size, so that they can be read and written
+/// in it.
+fn can_hold_pixels(data: &TypedArrayBase, width: u32, height: u32) -> bool {
+ let data_record = make_typed_array_with_buffer_witness_record(data, ArrayBufferOrder::SeqCst);
+ if is_typed_array_out_of_bounds(&data_record) {
+ return false;
+ }
+ let Some(expected_byte_length) = (width as usize)
+ .checked_mul(height as usize)
+ .and_then(|pixels| pixels.checked_mul(BYTES_PER_PIXEL as usize))
+ else {
+ return false;
+ };
+ typed_array_byte_length(&data_record) as usize >= expected_byte_length
+}
+
+impl ImageData {
+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagedata
+ pub(crate) fn construct_with_size(
+ cx: &mut CallContext,
+ sw: u32,
+ sh: u32,
+ settings: ImageDataSettings,
+ ) -> WebIdlResult<Self> {
+ // 1. If one or both of sw and sh are zero, then throw an "IndexSizeError" DOMException.
+ if sw == 0 || sh == 0 {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"The source width and height must be greater than zero.",
+ )));
+ }
+
+ // 2. Initialize this given sw, sh, and settings set to settings.
+ // 3. Initialize the image data of this to transparent black.
+ Self::initialize(cx, sh, sw, Some(&settings), None, None)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagedata-with-data
+ pub(crate) fn construct_with_data(
+ cx: &mut CallContext,
+ data: Gc<TypedArrayBase>,
+ sw: u32,
+ sh: Option<u32>,
+ settings: ImageDataSettings,
+ ) -> WebIdlResult<Self> {
+ let data_record = make_typed_array_with_buffer_witness_record(&data, ArrayBufferOrder::SeqCst);
+ if is_typed_array_out_of_bounds(&data_record) {
+ return Err(invalid_state_error(b"Source data must not be out-of-bounds."));
+ }
+
+ // 1. Let length be the number of bytes in data.
+ let length = typed_array_byte_length(&data_record);
+
+ // 2. If length is not a nonzero integral multiple of four, then throw an "InvalidStateError" DOMException.
+ if length == 0 || !length.is_multiple_of(BYTES_PER_PIXEL) {
+ return Err(invalid_state_error(
+ b"Source data must have a non-sero length that is a multiple of four.",
+ ));
+ }
+
+ // 3. Let length be length divided by four.
+ let length = length / BYTES_PER_PIXEL;
+
+ // 4. If length is not an integral multiple of sw, then throw an "IndexSizeError" DOMException.
+ // NOTE: At this step, the length is guaranteed to be greater than zero (otherwise the second step above would
+ // have aborted the steps), so if sw is zero, this step will throw the exception and return.
+ if sw == 0 || !length.is_multiple_of(sw) {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"Source width must be a multiple of source data's length.",
+ )));
+ }
+
+ // 5. Let height be length divided by sw.
+ let height = length / sw;
+
+ // 6. If sh was given and its value is not equal to height, then throw an "IndexSizeError" DOMException.
+ if sh.is_some_and(|sh| sh != height) {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"Source height must be equal to the calculated height of the data.",
+ )));
+ }
+
+ // 7. Initialize this given sw, sh, settings set to settings, and source set to data.
+ // FIXME: This seems to be a spec issue, sh is an optional but height always have a value.
+ Self::initialize(cx, height, sw, Some(&settings), Some(data), None)
+ }
+
+ /// A new ImageData of the size, with transparent black pixels, as the 2D contexts create them: steps 2 to 4 of
+ /// createImageData() and steps 3 to 4 of getImageData().
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ width: u32,
+ height: u32,
+ settings: Option<&ImageDataSettings>,
+ ) -> WebIdlResult<Ref<Self>> {
+ let image_data = Self::initialize(cx, height, width, settings, None, None)?;
+ Ok(allocate(cx.vm(), image_data))
+ }
+
+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#initialize-an-imagedata-object
+ fn initialize(
+ cx: &mut CallContext,
+ rows: u32,
+ pixels_per_row: u32,
+ settings: Option<&ImageDataSettings>,
+ source: Option<Gc<TypedArrayBase>>,
+ default_color_space: Option<PredefinedColorSpace>,
+ ) -> WebIdlResult<Self> {
+ let data = match source {
+ // 1. If source was given, then initialize the data attribute of imageData to source.
+ Some(source) => source,
+ None => {
+ let Some(size) = rows
+ .checked_mul(pixels_per_row)
+ .and_then(|pixels| pixels.checked_mul(BYTES_PER_PIXEL))
+ else {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"The specified image size could not created",
+ )));
+ };
+
+ // 2. Otherwise (source was not given), initialize the data attribute of imageData to a new
+ // Uint8ClampedArray object. The Uint8ClampedArray object must use a new Canvas Pixel ArrayBuffer for
+ // its storage, and must have a zero start offset and a length equal to the length of its storage,
+ // in bytes. The Canvas Pixel ArrayBuffer must have the correct size to store rows × pixelsPerRow
+ // pixels.
+ // 3. If the Canvas Pixel ArrayBuffer cannot be allocated, then rethrow the RangeError thrown by
+ // JavaScript, and return.
+ let buffer = ArrayBuffer::create(cx.vm(), cx.realm(), size as usize, ArrayBufferShared::No)?;
+ create_typed_array_on_buffer(cx.vm(), cx.realm(), TypedArrayKind::Uint8ClampedArray, size, buffer)
+ }
+ };
+
+ // AD-HOC: Validate that the data has room for the pixels.
+ if !can_hold_pixels(&data, pixels_per_row, rows) {
+ return Err(invalid_state_error(
+ b"Source data must not be detached or out-of-bounds.",
+ ));
+ }
+
+ // 4. Initialize the width attribute of imageData to pixelsPerRow.
+ // 5. Initialize the height attribute of imageData to rows.
+ // 6. If settings was given and settings["colorSpace"] exists, then initialize the colorSpace attribute of
+ // imageData to settings["colorSpace"].
+ // 7. Otherwise, if defaultColorSpace was given, then initialize the colorSpace attribute of imageData to
+ // defaultColorSpace.
+ // 8. Otherwise, initialize the colorSpace attribute of imageData to "srgb".
+ let color_space = settings
+ .and_then(|settings| settings.color_space)
+ .or(default_color_space)
+ .unwrap_or(PredefinedColorSpace::Srgb);
+
+ Ok(Self {
+ data,
+ width: pixels_per_row,
+ height: rows,
+ color_space,
+ })
+ }
+
+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagedata-width
+ pub(crate) fn width(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.width)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagedata-height
+ pub(crate) fn height(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.height)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagedata-data
+ pub(crate) fn data(&self, _: &mut CallContext) -> WebIdlResult<Gc<TypedArrayBase>> {
+ Ok(self.data)
+ }
+
+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-imagedata-colorspace
+ pub(crate) fn color_space(&self, _: &mut CallContext) -> WebIdlResult<PredefinedColorSpace> {
+ Ok(self.color_space)
+ }
+
+ pub(crate) fn size(&self) -> (u32, u32) {
+ (self.width, self.height)
+ }
+
+ /// Whether the buffer of the data attribute is detached.
+ pub(crate) fn is_detached(&self) -> bool {
+ self.data.viewed_array_buffer().is_detached()
+ }
+
+ /// The first byte of the pixels, which are width × height × 4 bytes, unless the buffer of the data attribute is
+ /// detached or the data no longer has room for them. The pointer is valid until script runs: script can detach
+ /// or shrink the buffer, and write to it, so the pixels are read and written through the pointer, never as a
+ /// slice.
+ pub(crate) fn pixels(&self) -> Option<NonNull<u8>> {
+ if !can_hold_pixels(&self.data, self.width, self.height) {
+ return None;
+ }
+ let buffer = self.data.viewed_array_buffer();
+ let byte_offset = self.data.byte_offset() as usize;
+ NonNull::new(buffer.with_data_block(|data_block| data_block.data_at(byte_offset)))
+ }
+}
+
+fn invalid_state_error(message: &[u8]) -> Exception {
+ Exception::Dom("InvalidStateError", Utf16String::from_ascii(message))
+}
+
+impl Serializable for ImageData {
+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagedata-interface:serialization-steps
+ fn serialization_steps(
+ &self,
+ _: &mut CallContext,
+ serialized: &mut SerializationWriter,
+ _for_storage: bool,
+ ) -> WebIdlResult<()> {
+ // 1. Set serialized.[[Data]] to the sub-serialization of the value of value's data attribute.
+ serialized.write_value(Value::from_object(self.data))?;
+
+ // 2. Set serialized.[[Width]] to the value of value's width attribute.
+ serialized.write_u32(self.width);
+
+ // 3. Set serialized.[[Height]] to the value of value's height attribute.
+ serialized.write_u32(self.height);
+
+ // 4. Set serialized.[[ColorSpace]] to the value of value's colorSpace attribute.
+ // SAFETY: The writer is lent for the steps.
+ unsafe { web_image_data_serialize_color_space(serialized.as_raw(), self.color_space) };
+
+ // FIXME: 5. Set serialized.[[PixelFormat]] to the value of value's pixelFormat attribute.
+
+ Ok(())
+ }
+
+ /// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#the-imagedata-interface:deserialization-steps
+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {
+ // 1. Initialize value's data attribute to the sub-deserialization of serialized.[[Data]].
+ let data_value = serialized.read_value()?;
+ let data = data_value
+ .is_object()
+ .then(|| data_value.as_object().downcast::<TypedArrayBase>())
+ .flatten()
+ .filter(|data| data.kind() == TypedArrayKind::Uint8ClampedArray)
+ .ok_or_else(|| {
+ Exception::Dom(
+ "DataCloneError",
+ Utf16String::from_ascii(b"ImageData data must be a Uint8ClampedArray"),
+ )
+ })?;
+
+ // 2. Initialize value's width attribute to serialized.[[Width]].
+ let width = serialized.read_u32()?;
+
+ // 3. Initialize value's height attribute to serialized.[[Height]].
+ let height = serialized.read_u32()?;
+
+ // 4. Initialize value's colorSpace attribute to serialized.[[ColorSpace]].
+ let mut color_space = 0;
+ // SAFETY: The reader is lent for the steps.
+ unsafe { web_image_data_deserialize_color_space(serialized.as_raw(), &mut color_space) }.into_completion()?;
+ let color_space = PredefinedColorSpace::from_u8(color_space).expect("C++ decodes a color space");
+
+ // FIXME: 5. Initialize value's pixelFormat attribute to serialized.[[PixelFormat]].
+
+ // AD-HOC: Validate that the data has room for the pixels.
+ if !can_hold_pixels(&data, width, height) {
+ return Err(invalid_state_error(
+ b"Image data must not be detached or out-of-bounds.",
+ ));
+ }
+
+ Ok(Self {
+ data,
+ width,
+ height,
+ color_space,
+ })
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 273e495abf4..3a3776e339c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -4,12 +4,13 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The objects that the 2D canvas contexts draw with, 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`.
+//! 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
+//! reads these objects and builds its paths through the C ABI of `exports`.
pub(crate) mod canvas_path;
pub(crate) mod color_stops;
+pub(crate) mod predefined_color_space;
// What follows runs on the JS runtime, which the tests of the crate do not link.
#[cfg(not(test))]
@@ -19,6 +20,8 @@ pub(crate) mod canvas_pattern;
#[cfg(not(test))]
pub(crate) mod exports;
#[cfg(not(test))]
+pub(crate) mod image_data;
+#[cfg(not(test))]
pub(crate) mod path2d;
#[cfg(not(test))]
pub(crate) mod text_metrics;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/predefined_color_space.rs b/Libraries/LibWeb/Bindings/Rust/src/html/predefined_color_space.rs
new file mode 100644
index 00000000000..645a447b2db
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/predefined_color_space.rs
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! https://html.spec.whatwg.org/multipage/canvas.html#predefinedcolorspace
+
+/// In the order of Web::Bindings::PredefinedColorSpace, which C++ passes as its underlying value.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(u8)]
+pub(crate) enum PredefinedColorSpace {
+ #[default]
+ Srgb,
+ SrgbLinear,
+ DisplayP3,
+ DisplayP3Linear,
+}
+
+impl PredefinedColorSpace {
+ /// The color space whose underlying value C++ passes, if it is one.
+ pub(crate) fn from_u8(value: u8) -> Option<Self> {
+ match value {
+ 0 => Some(Self::Srgb),
+ 1 => Some(Self::SrgbLinear),
+ 2 => Some(Self::DisplayP3),
+ 3 => Some(Self::DisplayP3Linear),
+ _ => None,
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs
index 9d80bce1e04..3391d5fd4b0 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/canvas.rs
@@ -17,12 +17,11 @@ use super::host::Frame;
use super::pixel_unpacking::PixelUnpackState;
use crate::bindings::conversions::CppInterface;
-/// In the order of the C++ enum of the same name.
+/// The sources of texture images that are implemented in C++, in the order of the C++ enum of the same name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum TexImageSourceKind {
ImageBitmap,
- ImageData,
HTMLImageElement,
HTMLCanvasElement,
HTMLVideoElement,
@@ -56,6 +55,14 @@ unsafe extern "C" {
r#type: u32,
out_frame: *mut *mut c_void,
) -> u8;
+ fn web_webgl_read_tex_image_pixels(
+ pixels: *const u8,
+ width: u32,
+ height: u32,
+ format: u32,
+ r#type: u32,
+ out_frame: *mut *mut c_void,
+ ) -> u8;
fn web_webgl_make_xr_compatible(context: *mut c_void) -> *mut c_void;
}
@@ -139,6 +146,29 @@ pub(crate) fn read_tex_image_source(
&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.
+///
+/// # Safety
+///
+/// `pixels` must be the width × height RGBA8888 pixels of the ImageData, which no script may change during the call.
+pub(crate) unsafe fn read_tex_image_pixels(
+ pixels: NonNull<u8>,
+ width: u32,
+ height: u32,
+ format: u32,
+ r#type: u32,
+) -> TexImageSourceFrame {
+ let mut frame = core::ptr::null_mut();
+ // SAFETY: The caller passes the pixels, and the frame is stored when the function returns that there is one.
+ let result =
+ unsafe { web_webgl_read_tex_image_pixels(pixels.as_ptr(), width, height, format, r#type, &raw mut frame) };
+ tex_image_source_frame(result, frame)
+}
+
+fn tex_image_source_frame(result: u8, frame: *mut c_void) -> TexImageSourceFrame {
match result {
TEX_IMAGE_SOURCE_RESULT_FRAME => {
let frame = NonNull::new(frame).expect("LibWeb returns the frame");
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs
index 53972018e11..49454c46c63 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/state.rs
@@ -14,7 +14,7 @@ use core::ops::Deref;
use libjs_rust::api::{ForeignCellSlot, Gc, Realm, Trace, Visitor, Vm};
-use super::canvas::{Canvas, TexImageSourceFrame, TexImageSourceKind, read_tex_image_source};
+use super::canvas::{Canvas, TexImageSourceFrame, TexImageSourceKind, 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,
};
@@ -353,15 +353,38 @@ impl ContextState {
format: u32,
r#type: u32,
) -> Option<(Frame, FrameUpload)> {
- let (source_kind, source_object) = match *source {
- TexImageSource::ImageBitmap(object) => (TexImageSourceKind::ImageBitmap, object),
- TexImageSource::ImageData(object) => (TexImageSourceKind::ImageData, object),
- TexImageSource::HTMLImageElement(object) => (TexImageSourceKind::HTMLImageElement, object),
- TexImageSource::HTMLCanvasElement(object) => (TexImageSourceKind::HTMLCanvasElement, object),
- TexImageSource::HTMLVideoElement(object) => (TexImageSourceKind::HTMLVideoElement, object),
- TexImageSource::OffscreenCanvas(object) => (TexImageSourceKind::OffscreenCanvas, object),
+ // FIXME: If this function is called with an HTMLImageElement or HTMLVideoElement whose origin differs from the
+ // origin of the containing Document, or with an HTMLCanvasElement, ImageBitmap or OffscreenCanvas whose
+ // 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::ImageData(image_data) => match image_data.pixels() {
+ Some(pixels) => {
+ let (width, height) = image_data.size();
+ // SAFETY: Nothing runs script while the pixels are copied.
+ unsafe { read_tex_image_pixels(pixels, width, height, format, r#type) }
+ }
+ // If this function is called with an ImageData whose data attribute has been neutered, an
+ // INVALID_VALUE error is generated.
+ None => TexImageSourceFrame::InvalidValue,
+ },
+ TexImageSource::HTMLImageElement(object) => {
+ read_tex_image_source(object, TexImageSourceKind::HTMLImageElement, format, r#type)
+ }
+ TexImageSource::HTMLCanvasElement(object) => {
+ read_tex_image_source(object, TexImageSourceKind::HTMLCanvasElement, format, r#type)
+ }
+ TexImageSource::HTMLVideoElement(object) => {
+ read_tex_image_source(object, TexImageSourceKind::HTMLVideoElement, format, r#type)
+ }
+ TexImageSource::OffscreenCanvas(object) => {
+ read_tex_image_source(object, TexImageSourceKind::OffscreenCanvas, format, r#type)
+ }
};
- let frame = match read_tex_image_source(source_object, source_kind, format, r#type) {
+ let frame = match source_frame {
TexImageSourceFrame::Frame(frame) => frame,
TexImageSourceFrame::NoFrame => return None,
TexImageSourceFrame::InvalidValue => {
@@ -372,7 +395,7 @@ impl ContextState {
// The first pixel transferred from the source to the WebGL implementation corresponds to the upper left
// corner of the source. This behavior is modified by the UNPACK_FLIP_Y_WEBGL pixel storage parameter,
// except for ImageBitmap arguments, as described in the abovementioned section.
- let flip_y = self.unpack_flip_y.get() && source_kind != TexImageSourceKind::ImageBitmap;
+ let flip_y = self.unpack_flip_y.get() && !matches!(source, TexImageSource::ImageBitmap(_));
let upload = FrameUpload {
destination_size: None,
flip_y,
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.rs
index 47306f5bce7..87fa5c67906 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_data::ImageData;
/// https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.8
// FIXME: VideoFrame
pub(crate) enum TexImageSource {
ImageBitmap(CppInterface),
- ImageData(CppInterface),
+ ImageData(Ref<ImageData>),
HTMLImageElement(CppInterface),
HTMLCanvasElement(CppInterface),
HTMLVideoElement(CppInterface),
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
index 3d512c1f14d..a768fdfe3d6 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
@@ -19,7 +19,6 @@
#include <LibGfx/Rect.h>
#include <LibGfx/TextAlignment.h>
#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibJS/Runtime/TypedArray.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/DOMRectReadOnly.h>
#include <LibWeb/CSS/FontComputer.h>
@@ -791,15 +790,18 @@ WebIDL::ExceptionOr<GC::Ptr<ImageData>> Canvas2DContextBase::get_image_data(int
return image_data;
// 6. Set the pixel values of imageData to be the pixels of this's output bitmap in the area specified by the source rectangle in the bitmap's coordinate space units, converted from this's color space to imageData's colorSpace using 'relative-colorimetric' rendering intent.
- auto image_data_bitmap = TRY_OR_THROW_OOM(realm().vm(), image_data->bitmap());
- if (pixels->format() != image_data_bitmap->format() || pixels->alpha_type() != image_data_bitmap->alpha_type() || pixels->size() != source_rect_intersected.size())
+ // NB: The pixels of imageData are RGBA8888 and unpremultiplied.
+ auto* image_data_pixels = image_data->pixels();
+ VERIFY(image_data_pixels);
+ if (pixels->format() != Gfx::BitmapFormat::RGBA8888 || pixels->alpha_type() != Gfx::AlphaType::Unpremultiplied || pixels->size() != source_rect_intersected.size())
return image_data;
// The readback only covers the part of the source rectangle that is inside the output bitmap.
auto destination_location = source_rect_intersected.location() - source_rect.location();
+ auto destination_pitch = static_cast<size_t>(image_data->width()) * sizeof(u32);
auto row_size = static_cast<size_t>(pixels->width()) * sizeof(u32);
for (int y = 0; y < pixels->height(); ++y) {
- auto* destination_row = image_data_bitmap->scanline_u8(destination_location.y() + y) + destination_location.x() * sizeof(u32);
+ auto* destination_row = image_data_pixels + (destination_location.y() + y) * destination_pitch + destination_location.x() * sizeof(u32);
memcpy(destination_row, pixels->scanline_u8(y), row_size);
}
@@ -811,7 +813,7 @@ WebIDL::ExceptionOr<GC::Ptr<ImageData>> Canvas2DContextBase::get_image_data(int
}
// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-putimagedata-short
-WebIDL::ExceptionOr<void> Canvas2DContextBase::put_image_data(ImageData& image_data, float dx, float dy)
+WebIDL::ExceptionOr<void> Canvas2DContextBase::put_image_data(ImageData& image_data, int dx, int dy)
{
// The putImageData(imageData, dx, dy) method steps are to put pixels from an ImageData onto a bitmap,
// given imageData, this's output bitmap, dx, dy, 0, 0, imageData's width, and imageData's height.
@@ -822,7 +824,7 @@ WebIDL::ExceptionOr<void> Canvas2DContextBase::put_image_data(ImageData& image_d
}
// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-putimagedata
-WebIDL::ExceptionOr<void> Canvas2DContextBase::put_image_data(ImageData& image_data, float x, float y, float dirty_x, float dirty_y, float dirty_width, float dirty_height)
+WebIDL::ExceptionOr<void> Canvas2DContextBase::put_image_data(ImageData& image_data, int x, int y, int dirty_x, int dirty_y, int dirty_width, int dirty_height)
{
// The putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight) method steps are to put pixels
// from an ImageData onto a bitmap, given imageData, this's output bitmap, dx, dy, dirtyX, dirtyY, dirtyWidth, and
@@ -834,26 +836,31 @@ WebIDL::ExceptionOr<void> Canvas2DContextBase::put_image_data(ImageData& image_d
}
// https://html.spec.whatwg.org/multipage/canvas.html#dom-context2d-putimagedata-common
-WebIDL::ExceptionOr<void> Canvas2DContextBase::put_pixels_from_an_image_data_onto_a_bitmap(ImageData& image_data, Canvas2DRecorder& recorder, float dx, float dy, float dirty_x, float dirty_y, float dirty_width, float dirty_height)
+WebIDL::ExceptionOr<void> Canvas2DContextBase::put_pixels_from_an_image_data_onto_a_bitmap(ImageData& image_data, Canvas2DRecorder& recorder, int dx, int dy, int dirty_x_argument, int dirty_y_argument, int dirty_width_argument, int dirty_height_argument)
{
// 1. Let buffer be imageData's data attribute value's [[ViewedArrayBuffer]] internal slot.
- auto* buffer = image_data.data()->viewed_array_buffer();
-
// 2. If IsDetachedBuffer(buffer) is true, then throw an "InvalidStateError" DOMException
- if (buffer->is_detached())
+ if (image_data.is_detached())
return WebIDL::InvalidStateError::create("ImageData's underlying buffer is detached"_utf16);
+ // NB: The arguments are IDL longs. Do the arithmetic below in 64 bits, so that it neither overflows nor loses
+ // precision.
+ i64 dirty_x = dirty_x_argument;
+ i64 dirty_y = dirty_y_argument;
+ i64 dirty_width = dirty_width_argument;
+ i64 dirty_height = dirty_height_argument;
+
// 3. If dirtyWidth is negative, then let dirtyX be dirtyX+dirtyWidth, and let dirtyWidth be equal to the
// absolute magnitude of dirtyWidth.
if (dirty_width < 0) {
dirty_x += dirty_width;
- dirty_width = abs(dirty_width);
+ dirty_width = -dirty_width;
}
// If dirtyHeight is negative, then let dirtyY be dirtyY+dirtyHeight, and let dirtyHeight be equal to the absolute
// magnitude of dirtyHeight.
if (dirty_height < 0) {
dirty_y += dirty_height;
- dirty_height = abs(dirty_height);
+ dirty_height = -dirty_height;
}
// 4. If dirtyX is negative, then let dirtyWidth be dirtyWidth+dirtyX, and let dirtyX be 0.
@@ -888,19 +895,34 @@ WebIDL::ExceptionOr<void> Canvas2DContextBase::put_pixels_from_an_image_data_ont
// set the pixel with coordinate (dx+x, dy+y) in bitmap to the color of the pixel at coordinate (x, y) in the
// imageData data structure's bitmap, converted from imageData's colorSpace to the color space of bitmap using
// 'relative-colorimetric' rendering intent.
- auto dst_rect = Gfx::FloatRect { dx + dirty_x, dy + dirty_y, dirty_width, dirty_height };
+ auto* source_pixels = image_data.pixels();
+ if (!source_pixels)
+ return WebIDL::InvalidStateError::create("ImageData's underlying buffer is detached or out-of-bounds"_utf16);
+ // NB: Only the pixels that land inside the output bitmap are set, so only copy those. Also keep the source
+ // rectangle inside imageData here, whatever the steps above computed, before reading its pixels.
+ i64 source_left = max(max(dirty_x, -static_cast<i64>(dx)), static_cast<i64>(0));
+ i64 source_top = max(max(dirty_y, -static_cast<i64>(dy)), static_cast<i64>(0));
+ i64 source_right = min(min(dirty_x + dirty_width, static_cast<i64>(m_size.width()) - dx), static_cast<i64>(image_data.width()));
+ i64 source_bottom = min(min(dirty_y + dirty_height, static_cast<i64>(m_size.height()) - dy), static_cast<i64>(image_data.height()));
+ if (source_left >= source_right || source_top >= source_bottom)
+ return {};
+ // NB: The destination rectangle is inside the output bitmap, so its coordinates fit in an int.
+ auto destination_rect = Gfx::IntRect {
+ static_cast<int>(source_left + dx),
+ static_cast<int>(source_top + dy),
+ static_cast<int>(source_right - source_left),
+ static_cast<int>(source_bottom - source_top),
+ };
+
// NOTE: The ImageData buffer is mutable from script and the recorded draw is only
// serialized at flush time, so snapshot the dirty pixels at call time. The
// snapshot is shareable so that flushing to the Compositor passes the pixels
// by file descriptor instead of copying them again.
- auto source_rect = Gfx::IntRect { dirty_x, dirty_y, dirty_width, dirty_height };
- auto source_bitmap_or_error = image_data.bitmap();
- if (source_bitmap_or_error.is_error())
- return WebIDL::InvalidStateError::create("ImageData's underlying buffer is detached or out-of-bounds"_utf16);
- auto source_bitmap = source_bitmap_or_error.release_value();
- auto bitmap_snapshot = MUST(Gfx::Bitmap::create_shareable(source_bitmap->format(), source_bitmap->alpha_type(), source_rect.size()));
- for (int y = 0; y < source_rect.height(); ++y)
- __builtin_memcpy(bitmap_snapshot->scanline(y), source_bitmap->scanline(source_rect.y() + y) + source_rect.x(), static_cast<size_t>(source_rect.width()) * sizeof(Gfx::RawPixel));
+ auto source_pitch = static_cast<size_t>(image_data.width()) * sizeof(u32);
+ auto bitmap_snapshot = TRY_OR_THROW_OOM(realm().vm(), Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::RGBA8888, Gfx::AlphaType::Unpremultiplied, destination_rect.size()));
+ for (int y = 0; y < destination_rect.height(); ++y)
+ __builtin_memcpy(bitmap_snapshot->scanline(y), source_pixels + static_cast<size_t>(source_top + y) * source_pitch + static_cast<size_t>(source_left) * sizeof(u32), static_cast<size_t>(destination_rect.width()) * sizeof(Gfx::RawPixel));
+ auto dst_rect = destination_rect.to_type<float>();
recorder.save();
recorder.set_transform({});
// NB: Step 7 sets each destination pixel to the source pixel: putImageData replaces the pixels (including their
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h
index 8b031e1cb36..4bf0b5dd3f5 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h
@@ -81,9 +81,9 @@ public:
virtual WebIDL::ExceptionOr<GC::Ref<ImageData>> create_image_data(int width, int height, Optional<Bindings::ImageDataSettings> const& settings = {}) const override;
virtual WebIDL::ExceptionOr<GC::Ref<ImageData>> create_image_data(ImageData const& image_data) const override;
virtual WebIDL::ExceptionOr<GC::Ptr<ImageData>> get_image_data(int x, int y, int width, int height, Optional<Bindings::ImageDataSettings> const& settings = {}) override;
- virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, float x, float y) override;
- virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, float x, float y, float dirty_x, float dirty_y, float dirty_width, float dirty_height) override;
- WebIDL::ExceptionOr<void> put_pixels_from_an_image_data_onto_a_bitmap(ImageData&, Canvas2DRecorder&, float dx, float dy, float dirty_x, float dirty_y, float dirty_width, float dirty_height);
+ virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, int x, int y) override;
+ virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, int x, int y, int dirty_x, int dirty_y, int dirty_width, int dirty_height) override;
+ WebIDL::ExceptionOr<void> put_pixels_from_an_image_data_onto_a_bitmap(ImageData&, Canvas2DRecorder&, int dx, int dy, int dirty_x, int dirty_y, int dirty_width, int dirty_height);
virtual void reset_to_default_state() override;
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasImageData.h b/Libraries/LibWeb/HTML/Canvas/CanvasImageData.h
index c12ed367373..8d4b33d8b45 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasImageData.h
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasImageData.h
@@ -18,8 +18,8 @@ public:
virtual WebIDL::ExceptionOr<GC::Ref<ImageData>> create_image_data(int width, int height, Optional<ImageData::Settings> const& settings = {}) const = 0;
virtual WebIDL::ExceptionOr<GC::Ref<ImageData>> create_image_data(ImageData const&) const = 0;
virtual WebIDL::ExceptionOr<GC::Ptr<ImageData>> get_image_data(int x, int y, int width, int height, Optional<ImageData::Settings> const& settings = {}) = 0;
- virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, float x, float y) = 0;
- virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, float x, float y, float dirty_x, float dirty_y, float dirty_width, float dirty_height) = 0;
+ virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, int x, int y) = 0;
+ virtual WebIDL::ExceptionOr<void> put_image_data(ImageData&, int x, int y, int dirty_x, int dirty_y, int dirty_width, int dirty_height) = 0;
protected:
CanvasImageData() = default;
diff --git a/Libraries/LibWeb/HTML/ImageData.cpp b/Libraries/LibWeb/HTML/ImageData.cpp
index d8e61867d44..1bc8240113e 100644
--- a/Libraries/LibWeb/HTML/ImageData.cpp
+++ b/Libraries/LibWeb/HTML/ImageData.cpp
@@ -5,241 +5,84 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
#include <LibGfx/Bitmap.h>
-#include <LibJS/Runtime/TypedArray.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/RustSerialization.h>
#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/HTML/StructuredSerialize.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::HTML {
-GC_DEFINE_ALLOCATOR(ImageData);
+static_assert(to_underlying(Bindings::PredefinedColorSpace::Srgb) == 0);
+static_assert(to_underlying(Bindings::PredefinedColorSpace::SrgbLinear) == 1);
+static_assert(to_underlying(Bindings::PredefinedColorSpace::DisplayP3) == 2);
+static_assert(to_underlying(Bindings::PredefinedColorSpace::DisplayP3Linear) == 3);
-[[nodiscard]] static ErrorOr<void> validate_uint8_clamped_array_can_back_bitmap(u32 const width, u32 const height, JS::Uint8ClampedArray const& data)
-{
- auto data_record = JS::make_typed_array_with_buffer_witness_record(data, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(data_record))
- return Error::from_errno(EINVAL);
-
- Checked<size_t> expected_byte_length = width;
- expected_byte_length *= height;
- expected_byte_length *= sizeof(u32);
- if (expected_byte_length.has_overflow())
- return Error::from_errno(EINVAL);
-
- if (JS::typed_array_byte_length(data_record) < expected_byte_length.value())
- return Error::from_errno(EINVAL);
-
- return {};
-}
+extern "C" {
-[[nodiscard]] static ErrorOr<NonnullRefPtr<Gfx::Bitmap>> create_bitmap_backed_by_uint8_clamped_array(u32 const width, u32 const height, JS::Uint8ClampedArray& data)
-{
- TRY(validate_uint8_clamped_array_can_back_bitmap(width, height, data));
- return Gfx::Bitmap::create_wrapper(Gfx::BitmapFormat::RGBA8888, Gfx::AlphaType::Unpremultiplied, Gfx::IntSize(width, height), width * sizeof(u32), data.viewed_array_buffer()->data_at(data.byte_offset()));
-}
+// Defined in Bindings/Rust/src/html/exports.rs.
+JSCompletion web_image_data_create(JSVM*, void* realm, u32 width, u32 height, bool has_color_space, Bindings::PredefinedColorSpace, void** out_image_data);
+u32 web_image_data_width(void const* image_data);
+u32 web_image_data_height(void const* image_data);
+bool web_image_data_is_detached(void const* image_data);
+u8* web_image_data_pixels(void const* image_data);
-GC::Ref<ImageData> ImageData::create()
-{
- return GC::Heap::the().allocate<ImageData>();
-}
-
-GC::Ref<ImageData> ImageData::create(NonnullRefPtr<Gfx::Bitmap> bitmap, GC::Ref<JS::Uint8ClampedArray> data, PredefinedColorSpace color_space)
-{
- return GC::Heap::the().allocate<ImageData>(move(bitmap), data, color_space);
-}
+// What the serialization steps of Bindings/Rust/src/html/image_data.rs ask of C++: the color space, encoded as for
+// any other Bindings::PredefinedColorSpace.
+void web_image_data_serialize_color_space(Bindings::RustSerializationWriter*, Bindings::PredefinedColorSpace);
+JSCompletion web_image_data_deserialize_color_space(Bindings::RustSerializationReader*, Bindings::PredefinedColorSpace* out_color_space);
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-imagedata
-WebIDL::ExceptionOr<GC::Ref<ImageData>> ImageData::create(JS::Realm& realm, u32 sw, u32 sh, Optional<Settings> const& settings)
+void web_image_data_serialize_color_space(Bindings::RustSerializationWriter* writer, Bindings::PredefinedColorSpace color_space)
{
- // 1. If one or both of sw and sh are zero, then throw an "IndexSizeError" DOMException.
- if (sw == 0 || sh == 0)
- return WebIDL::IndexSizeError::create("The source width and height must be greater than zero."_utf16);
-
- // 2. Initialize this given sw, sh, and settings set to settings.
- // 3. Initialize the image data of this to transparent black.
- return initialize(realm, sh, sw, settings);
+ writer->serialized.encode(color_space);
}
-// https://html.spec.whatwg.org/multipage/canvas.html#dom-imagedata-with-data
-WebIDL::ExceptionOr<GC::Ref<ImageData>> ImageData::create(JS::Realm& realm, GC::Ref<JS::Uint8ClampedArray> uint8_clamped_array_data, u32 sw, Optional<u32> sh, Optional<Settings> const& settings)
+JSCompletion web_image_data_deserialize_color_space(Bindings::RustSerializationReader* reader, Bindings::PredefinedColorSpace* out_color_space)
{
- auto data_record = JS::make_typed_array_with_buffer_witness_record(*uint8_clamped_array_data, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(data_record))
- return WebIDL::InvalidStateError::create(realm, "Source data must not be out-of-bounds."_utf16);
-
- // 1. Let length be the number of bytes in data.
- auto length = JS::typed_array_length(data_record);
-
- // 2. If length is not a nonzero integral multiple of four, then throw an "InvalidStateError" DOMException.
- if (length == 0 || length % 4 != 0)
- return WebIDL::InvalidStateError::create("Source data must have a non-sero length that is a multiple of four."_utf16);
-
- // 3. Let length be length divided by four.
- length = length / 4;
-
- // 4. If length is not an integral multiple of sw, then throw an "IndexSizeError" DOMException.
- // NOTE: At this step, the length is guaranteed to be greater than zero (otherwise the second step above would have aborted the steps),
- // so if sw is zero, this step will throw the exception and return.
- if (sw == 0 || length % sw != 0)
- return WebIDL::IndexSizeError::create("Source width must be a multiple of source data's length."_utf16);
-
- // 5. Let height be length divided by sw.
- auto height = length / sw;
-
- // 6. If sh was given and its value is not equal to height, then throw an "IndexSizeError" DOMException.
- if (sh.has_value() && sh.value() != height)
- return WebIDL::IndexSizeError::create("Source height must be equal to the calculated height of the data."_utf16);
-
- // 7. Initialize this given sw, sh, settings set to settings, and source set to data.
- // FIXME: This seems to be a spec issue, sh is an optional but height always have a value.
- return initialize(realm, height, sw, settings, *uint8_clamped_array_data);
+ auto color_space = decode_or_throw_data_clone_error<Bindings::PredefinedColorSpace>(reader->realm, reader->serialized);
+ if (color_space.is_exception())
+ return Bindings::completion_to_abi(reader->realm, color_space.release_error());
+ *out_color_space = color_space.release_value();
+ return Bindings::completion_to_abi(reader->realm, JS::js_undefined());
}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#initialize-an-imagedata-object
-WebIDL::ExceptionOr<GC::Ref<ImageData>> ImageData::initialize(JS::Realm& realm, u32 rows, u32 pixels_per_row, Optional<Settings> const& settings, GC::Ptr<JS::Uint8ClampedArray> source, Optional<PredefinedColorSpace> default_color_space)
-{
- auto data = TRY([&]() -> WebIDL::ExceptionOr<GC::Ref<JS::Uint8ClampedArray>> {
- // 1. If source was given, then initialize the data attribute of imageData to source.
- if (source) {
- return GC::Ref<JS::Uint8ClampedArray> { *source };
- }
-
- Checked<u32> size = rows;
- size *= pixels_per_row;
- size *= sizeof(u32);
- if (size.has_overflow())
- return WebIDL::IndexSizeError::create("The specified image size could not created"_utf16);
-
- // 2. Otherwise (source was not given), initialize the data attribute of imageData to a new Uint8ClampedArray object.
- // The Uint8ClampedArray object must use a new Canvas Pixel ArrayBuffer for its storage, and must have a zero start
- // offset and a length equal to the length of its storage, in bytes. The Canvas Pixel ArrayBuffer must have the
- // correct size to store rows × pixelsPerRow pixels.
- // 3. If the Canvas Pixel ArrayBuffer cannot be allocated, then rethrow the RangeError thrown by JavaScript, and return.
- return TRY(JS::Uint8ClampedArray::create(realm, sizeof(u32) * rows * pixels_per_row));
- }());
-
- // AD-HOC: Validate that the bitmap can be backed by the Uint8ClampedArray.
- if (validate_uint8_clamped_array_can_back_bitmap(pixels_per_row, rows, *data).is_error())
- return WebIDL::InvalidStateError::create(realm, "Source data must not be detached or out-of-bounds."_utf16);
-
- // 4. Initialize the width attribute of imageData to pixelsPerRow.
- // 5. Initialize the height attribute of imageData to rows.
-
- // 6. If settings was given and settings["colorSpace"] exists, then initialize the colorSpace attribute of imageData to settings["colorSpace"].
- PredefinedColorSpace color_space {};
- if (settings.has_value() && settings->color_space.has_value())
- color_space = *settings->color_space;
- // 7. Otherwise, if defaultColorSpace was given, then initialize the colorSpace attribute of imageData to defaultColorSpace.
- else if (default_color_space.has_value())
- color_space = *default_color_space;
- // 8. Otherwise, initialize the colorSpace attribute of imageData to "srgb".
- else
- color_space = PredefinedColorSpace::Srgb;
-
- auto bitmap = MUST(create_bitmap_backed_by_uint8_clamped_array(pixels_per_row, rows, *data));
- return ImageData::create(move(bitmap), data, color_space);
}
-ImageData::ImageData()
+WebIDL::ExceptionOr<GC::Ref<ImageData>> ImageData::create(JS::Realm& realm, u32 width, u32 height, Optional<Settings> const& settings)
{
+ auto color_space = settings.has_value() ? settings->color_space : Optional<Bindings::PredefinedColorSpace> {};
+ void* image_data = nullptr;
+ TRY(JS::HostABI::completion_from_abi<void>(web_image_data_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, width, height, color_space.has_value(), color_space.value_or(Bindings::PredefinedColorSpace::Srgb), &image_data)));
+ return GC::Ref { *static_cast<ImageData*>(image_data) };
}
-ImageData::ImageData(NonnullRefPtr<Gfx::Bitmap> bitmap, GC::Ref<JS::Uint8ClampedArray> data, PredefinedColorSpace color_space)
- : m_bitmap(move(bitmap))
- , m_color_space(color_space)
- , m_data(move(data))
+u32 ImageData::width() const
{
+ return web_image_data_width(this);
}
-ImageData::~ImageData() = default;
-
-void ImageData::visit_edges(GC::Cell::Visitor& visitor)
+u32 ImageData::height() const
{
- Base::visit_edges(visitor);
- visitor.visit(m_data);
+ return web_image_data_height(this);
}
-WebIDL::UnsignedLong ImageData::width() const
+bool ImageData::is_detached() const
{
- return m_bitmap ? m_bitmap->width() : 0;
+ return web_image_data_is_detached(this);
}
-WebIDL::UnsignedLong ImageData::height() const
+u8* ImageData::pixels() const
{
- return m_bitmap ? m_bitmap->height() : 0;
+ return web_image_data_pixels(this);
}
-ErrorOr<NonnullRefPtr<Gfx::Bitmap>> ImageData::bitmap()
+ErrorOr<NonnullRefPtr<Gfx::Bitmap>> ImageData::bitmap() const
{
- if (!m_bitmap)
+ auto* pixels = this->pixels();
+ if (!pixels)
return Error::from_errno(EINVAL);
- return *m_bitmap;
-}
-
-JS::Uint8ClampedArray* ImageData::data()
-{
- return m_data.ptr();
-}
-
-JS::Uint8ClampedArray const* ImageData::data() const
-{
- return m_data.ptr();
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#pixel-manipulation:serialization-steps
-WebIDL::ExceptionOr<void> ImageData::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool for_storage, HTML::SerializationMemory& memory)
-{
- // 1. Set serialized.[[Data]] to the sub-serialization of the value of value's data attribute.
- if (m_data)
- TRY(structured_serialize_internal(m_data->vm(), serialized, JS::Value(m_data.ptr()), for_storage, memory));
- else
- serialized.encode(to_underlying(ValueTag::NullPrimitive));
-
- // 2. Set serialized.[[Width]] to the value of value's width attribute.
- serialized.encode(width());
-
- // 3. Set serialized.[[Height]] to the value of value's height attribute.
- serialized.encode(height());
-
- // 4. Set serialized.[[ColorSpace]] to the value of value's colorSpace attribute.
- serialized.encode(m_color_space);
-
- // FIXME:: 5. Set serialized.[[PixelFormat]] to the value of value's pixelFormat attribute.
-
- return {};
-}
-
-// https://html.spec.whatwg.org/multipage/canvas.html#pixel-manipulation:deserialization-steps
-WebIDL::ExceptionOr<void> ImageData::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory& memory)
-{
- auto data_value = TRY(structured_deserialize_internal(realm.vm(), serialized, realm, memory, CheckFullyConsumed::No));
- if (!data_value.is_object() || !is<JS::Uint8ClampedArray>(data_value.as_object()))
- return WebIDL::DataCloneError::create("ImageData data must be a Uint8ClampedArray"_utf16);
- m_data = &as<JS::Uint8ClampedArray>(data_value.as_object());
-
- // 2. Initialize value's width attribute to serialized.[[Width]].
- auto width = TRY(HTML::decode_or_throw_data_clone_error<u32>(realm, serialized));
-
- // 3. Initialize value's height attribute to serialized.[[Height]].
- auto height = TRY(HTML::decode_or_throw_data_clone_error<u32>(realm, serialized));
-
- // 4. Initialize value's colorSpace attribute to serialized.[[ColorSpace]].
- m_color_space = TRY(HTML::decode_or_throw_data_clone_error<PredefinedColorSpace>(realm, serialized));
-
- // FIXME: 5. Initialize value's pixelFormat attribute to serialized.[[PixelFormat]].
-
- // AD-HOC: Validate that the bitmap can be backed by the Uint8ClampedArray.
- if (validate_uint8_clamped_array_can_back_bitmap(width, height, *m_data).is_error())
- return WebIDL::InvalidStateError::create(realm, "Image data must not be detached or out-of-bounds."_utf16);
-
- m_bitmap = MUST(create_bitmap_backed_by_uint8_clamped_array(width, height, *m_data));
-
- return {};
+ Gfx::IntSize size { static_cast<int>(width()), static_cast<int>(height()) };
+ return Gfx::Bitmap::create_wrapper(Gfx::BitmapFormat::RGBA8888, Gfx::AlphaType::Unpremultiplied, size, size.width() * sizeof(u32), pixels);
}
}
diff --git a/Libraries/LibWeb/HTML/ImageData.h b/Libraries/LibWeb/HTML/ImageData.h
index ccb410b4dfb..496449a94b5 100644
--- a/Libraries/LibWeb/HTML/ImageData.h
+++ b/Libraries/LibWeb/HTML/ImageData.h
@@ -12,53 +12,37 @@
#include <LibGfx/Forward.h>
#include <LibJS/Forward.h>
#include <LibWeb/Bindings/ImageData.h>
-#include <LibWeb/Bindings/PredefinedColorSpace.h>
-#include <LibWeb/Bindings/Serializable.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWebCommon/WebIDL/Types.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::HTML {
-class WEB_API ImageData final
- : public Bindings::GCAllocatedWrappable
- , public Bindings::Serializable {
- WEB_WRAPPABLE(ImageData, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(ImageData);
+// https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagedata
+// The C++ side of an ImageData, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what the 2D
+// contexts create, read and write the pixels of, and createImageBitmap() reads.
+class WEB_API ImageData final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(ImageData, image_data)
public:
using Settings = Bindings::ImageDataSettings;
- [[nodiscard]] static GC::Ref<ImageData> create();
- [[nodiscard]] static GC::Ref<ImageData> create(NonnullRefPtr<Gfx::Bitmap>, GC::Ref<JS::Uint8ClampedArray>, PredefinedColorSpace);
- [[nodiscard]] static WebIDL::ExceptionOr<GC::Ref<ImageData>> create(JS::Realm&, u32 sw, u32 sh, Optional<Settings> const& settings = {});
- [[nodiscard]] static WebIDL::ExceptionOr<GC::Ref<ImageData>> create(JS::Realm&, GC::Ref<JS::Uint8ClampedArray> data, u32 sw, Optional<u32> sh = {}, Optional<Settings> const& settings = {});
+ // A new ImageData of the size, with transparent black pixels, https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#initialize-an-imagedata-object
+ static WebIDL::ExceptionOr<GC::Ref<ImageData>> create(JS::Realm&, u32 width, u32 height, Optional<Settings> const& = {});
- virtual ~ImageData() override;
+ u32 width() const;
+ u32 height() const;
- WebIDL::UnsignedLong width() const;
- WebIDL::UnsignedLong height() const;
+ // Whether the buffer of the data attribute is detached.
+ bool is_detached() const;
- ErrorOr<NonnullRefPtr<Gfx::Bitmap>> bitmap();
+ // The pixels, RGBA8888 and unpremultiplied, width() × 4 bytes per row, in the buffer of the data attribute; null if
+ // the buffer is detached or the data has no room for them. Script can detach the buffer, so they are valid until
+ // script runs.
+ u8* pixels() const;
- JS::Uint8ClampedArray* data();
- JS::Uint8ClampedArray const* data() const;
-
- PredefinedColorSpace color_space() const { return m_color_space; }
-
- 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;
-
-private:
- [[nodiscard]] static WebIDL::ExceptionOr<GC::Ref<ImageData>> initialize(JS::Realm&, u32 rows, u32 pixels_per_row, Optional<Settings> const&, GC::Ptr<JS::Uint8ClampedArray> = {}, Optional<PredefinedColorSpace> = {});
-
- ImageData();
- ImageData(NonnullRefPtr<Gfx::Bitmap>, GC::Ref<JS::Uint8ClampedArray>, PredefinedColorSpace);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- RefPtr<Gfx::Bitmap> m_bitmap;
- PredefinedColorSpace m_color_space { PredefinedColorSpace::Srgb };
- GC::Ptr<JS::Uint8ClampedArray> m_data;
+ // A bitmap that views the pixels, valid until script runs.
+ ErrorOr<NonnullRefPtr<Gfx::Bitmap>> bitmap() const;
};
}
diff --git a/Libraries/LibWeb/HTML/ImageData.idl b/Libraries/LibWeb/HTML/ImageData.idl
index e99e2f168ba..6321917f689 100644
--- a/Libraries/LibWeb/HTML/ImageData.idl
+++ b/Libraries/LibWeb/HTML/ImageData.idl
@@ -9,10 +9,10 @@ dictionary ImageDataSettings {
};
// https://html.spec.whatwg.org/multipage/canvas.html#imagedata
-[Exposed=(Window,Worker), Serializable]
+[Exposed=(Window,Worker), Serializable, ImplementedIn=Rust]
interface ImageData {
- constructor(unsigned long sw, unsigned long sh, optional ImageDataSettings settings = {});
- constructor(ImageDataArray data, unsigned long sw, optional unsigned long sh, optional ImageDataSettings settings = {});
+ [ImplementedAs=construct_with_size] constructor(unsigned long sw, unsigned long sh, optional ImageDataSettings settings = {});
+ [ImplementedAs=construct_with_data] constructor(ImageDataArray data, unsigned long sw, optional unsigned long sh, optional ImageDataSettings settings = {});
readonly attribute unsigned long width;
readonly attribute unsigned long height;
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index 3708c679a7c..3092c7c1f89 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -529,17 +529,21 @@ void WindowOrWorkerGlobalScopeMixin::create_image_bitmap_impl(JS::Realm& realm,
// -> ImageData
[&](GC::Ref<ImageData> image_data) -> void {
// 1. Let buffer be image's data attribute value's [[ViewedArrayBuffer]] internal slot.
- auto const buffer = image_data->data()->viewed_array_buffer();
-
// 2. If IsDetachedBuffer(buffer) is true, then return a promise rejected with an "InvalidStateError" DOMException.
- if (buffer->is_detached()) {
+ if (image_data->is_detached()) {
WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image data is detached"_utf16));
return;
}
+ if (!image_data->pixels()) {
+ WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image data is detached or out-of-bounds"_utf16));
+ return;
+ }
+
+ // AD-HOC: Reject promise with an "InvalidStateError" DOMException if the image data is too large for a bitmap
auto bitmap_or_error = image_data->bitmap();
if (bitmap_or_error.is_error()) {
- WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image data is detached or out-of-bounds"_utf16));
+ WebIDL::reject_promise(*p, WebIDL::InvalidStateError::create("Image size is too large"_utf16));
return;
}
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
index 7985e6e1706..3bee048d4e6 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
@@ -15,7 +15,6 @@
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/Realm.h>
-#include <LibJS/Runtime/TypedArray.h>
#include <LibWeb/Bindings/WebGLContextEvent.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/Compositor/CompositorHost.h>
@@ -26,7 +25,6 @@
#include <LibWeb/HTML/HTMLImageElement.h>
#include <LibWeb/HTML/HTMLVideoElement.h>
#include <LibWeb/HTML/ImageBitmap.h>
-#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/HTML/OffscreenCanvas.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
@@ -73,10 +71,10 @@ struct ContextCreationArguments {
ReadonlySpan<ReadonlyBytes> supported_extensions;
};
-// `TexImageSourceKind` and `TexImageSourceResult` of Bindings/Rust/src/web_gl/canvas.rs.
+// `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,
- ImageData,
HTMLImageElement,
HTMLCanvasElement,
HTMLVideoElement,
@@ -132,6 +130,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_pixels(u8 const* pixels, u32 width, u32 height, u32 format, u32 type, void** out_frame);
void* web_webgl_make_xr_compatible(void* context);
}
@@ -482,16 +481,26 @@ bool web_webgl_required_2d_texture_data_size(i32 width, i32 height, u32 format,
return true;
}
+// The frame that a texture image source uploads, which the recorder takes over, if this format and type upload one.
+static TexImageSourceResult tex_image_source_frame(Optional<Compositing::WebGL::ImageSourceFrame> frame, u32 format, u32 type, void** out_frame)
+{
+ if (!frame.has_value())
+ return TexImageSourceResult::NoFrame;
+
+ // Validate the combination before recording; the pixels travel to the host as shared
+ // memory and the host performs the conversion next to GL.
+ if (!texture_export_format(format, type).has_value())
+ return TexImageSourceResult::NoFrame;
+
+ // FIXME: Respect unpackColorSpace
+ *out_frame = new ImageSourceFrameOwnedByRecorder { frame.release_value() };
+ return TexImageSourceResult::Frame;
+}
+
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 ImageData whose data attribute has been neutered,
- // an INVALID_VALUE error is generated.
// FIXME: If this function is called with an ImageBitmap that has been neutered, an INVALID_VALUE
// error is generated.
- // FIXME: If this function is called with an HTMLImageElement or HTMLVideoElement whose origin
- // differs from the origin of the containing Document, or with an HTMLCanvasElement,
- // ImageBitmap or OffscreenCanvas whose bitmap's origin-clean flag is set to false,
- // a SECURITY_ERR exception must be thrown. See Origin Restrictions.
// 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;
@@ -515,36 +524,27 @@ TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexIm
case TexImageSourceKind::ImageBitmap:
frame = Gfx::DecodedImageFrame { *Bindings::impl_from<HTML::ImageBitmap>(wrapper).bitmap() };
break;
- case TexImageSourceKind::ImageData: {
- // ImageData keeps a cached bitmap for ordinary use, but its data
- // attribute can be detached independently. WebGL must reject that
- // source instead of uploading the stale cached pixels.
- auto& source = Bindings::impl_from<HTML::ImageData>(wrapper);
- auto data = source.data();
- if (!data)
- return TexImageSourceResult::NoFrame;
- auto data_record = JS::make_typed_array_with_buffer_witness_record(*data, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(data_record))
- return TexImageSourceResult::InvalidValue;
- auto bitmap = source.bitmap();
- if (bitmap.is_error())
- return TexImageSourceResult::InvalidValue;
- NonnullRefPtr<Gfx::Bitmap const> bitmap_ref = bitmap.release_value();
- frame = Gfx::DecodedImageFrame { move(bitmap_ref) };
- break;
- }
}
- if (!frame.has_value())
- return TexImageSourceResult::NoFrame;
+ return tex_image_source_frame(move(frame), format, type, out_frame);
+}
- // Validate the combination before recording; the pixels travel to the host as shared
- // memory and the host performs the conversion next to GL.
+// 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)
+{
+ // NB: Check the format first, so that pixels that are not uploaded are not copied.
if (!texture_export_format(format, type).has_value())
return TexImageSourceResult::NoFrame;
- // FIXME: Respect unpackColorSpace
- *out_frame = new ImageSourceFrameOwnedByRecorder { frame.release_value() };
- return TexImageSourceResult::Frame;
+ // NB: The bitmap is shareable, so that the recorder sends it to the host without copying the pixels again.
+ auto bitmap = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::RGBA8888, Gfx::AlphaType::Unpremultiplied, { static_cast<int>(width), static_cast<int>(height) });
+ if (bitmap.is_error())
+ return TexImageSourceResult::InvalidValue;
+ auto row_size = static_cast<size_t>(width) * sizeof(u32);
+ for (u32 y = 0; y < height; ++y)
+ memcpy(bitmap.value()->scanline_u8(static_cast<int>(y)), pixels + y * row_size, row_size);
+ NonnullRefPtr<Gfx::Bitmap const> pixels_bitmap = bitmap.release_value();
+ return tex_image_source_frame(Compositing::WebGL::ImageSourceFrame { Gfx::DecodedImageFrame { move(pixels_bitmap) } }, format, type, out_frame);
}
void* web_webgl_make_xr_compatible(void* context)
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index d9eac5d174e..b7835177622 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -53,7 +53,7 @@ ALLOWED_REALM_MENTIONS = {
"Geometry": (8, 8, "geometry constructors and structured clone still materialize JS-facing geometry objects"),
"HTML": (
71,
- 222,
+ 216,
"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/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.h
index 244192e0550..8378b2f5d9e 100644
--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h
+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h
@@ -31,6 +31,7 @@
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/PredefinedColorSpace.h>
#include <LibWeb/Bindings/PrincipalHostDefined.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/Crypto/CryptoKey.h>
@@ -202,7 +203,7 @@ inline JS::Realm& test_realm()
}
template<typename T>
-requires(IsBaseOf<Web::Bindings::Wrappable, T>)
+requires(IsBaseOf<Web::Bindings::Wrappable, T> || Web::Bindings::RustInterfaceHandle<T>)
inline T& unwrap_wrappable(JS::Value value)
{
VERIFY(value.is_object());
@@ -225,6 +226,14 @@ inline Web::HTML::StorageSerializationRecord storage_serialize(GC::Ref<T> object
return MUST(Web::HTML::structured_serialize_for_storage(realm.vm(), JS::Value(wrapper.ptr())));
}
+template<Web::Bindings::RustInterfaceHandle T>
+inline Web::HTML::StorageSerializationRecord storage_serialize(GC::Ref<T> object)
+{
+ auto& realm = test_realm();
+ auto wrapper = Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(realm), realm, object);
+ return MUST(Web::HTML::structured_serialize_for_storage(realm.vm(), JS::Value(static_cast<JS::Object*>(wrapper.ptr()))));
+}
+
template<typename T>
requires(IsConvertible<T*, Web::Bindings::Wrappable*>)
inline Web::HTML::IPCSerializationRecord structured_serialize(JS::VM& vm, GC::Ref<T> object)
diff --git a/Tests/LibWeb/TestImageData.cpp b/Tests/LibWeb/TestImageData.cpp
index f5a6279b815..921e081a098 100644
--- a/Tests/LibWeb/TestImageData.cpp
+++ b/Tests/LibWeb/TestImageData.cpp
@@ -11,10 +11,12 @@
#include <LibJS/Runtime/TypedArray.h>
#include <LibJS/Runtime/VM.h>
#include <LibTest/TestCase.h>
+#include <LibWeb/Bindings/DOMException.h>
+#include <LibWeb/Bindings/ImageData.h>
+#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace {
@@ -36,29 +38,47 @@ struct TestVM {
GC::Ref<JS::Realm> realm;
};
-GC::Ref<JS::Uint8ClampedArray> create_out_of_bounds_uint8_clamped_array(JS::Realm& realm)
+}
+
+// new ImageData(data, sw, sh), whose implementation is in Rust.
+static JS::ThrowCompletionOr<GC::Ref<JS::Object>> construct_image_data(JS::Realm& realm, JS::Value data, u32 sw, u32 sh)
{
- auto array_buffer = MUST(JS::ArrayBuffer::create(realm, 16));
- array_buffer->set_max_byte_length(16);
+ auto& constructor = Web::Bindings::ensure_web_constructor<Web::Bindings::ImageDataPrototype>(realm, "ImageData"_utf16_fly_string);
+ return JS::construct(realm.vm(), constructor, data, JS::Value(static_cast<i32>(sw)), JS::Value(static_cast<i32>(sh)));
+}
- auto typed_array = JS::TypedArrayBase::create_from_slots(realm, JS::TypedArrayBase::Kind::Uint8ClampedArray, array_buffer, JS::ByteLength { 4 }, JS::ByteLength { 4 }, 8);
- MUST(JS::call(realm.vm(), MUST(array_buffer->get(realm.vm().names.resize)), JS::Value { array_buffer.ptr() }, JS::Value(4)));
+TEST_CASE(construct_rejects_detached_uint8_clamped_array)
+{
+ TestVM test_vm;
+ auto& realm = *test_vm.realm;
+ auto data = MUST(JS::Uint8ClampedArray::create(realm, 4));
+ MUST(JS::detach_array_buffer(realm.vm(), *data->viewed_array_buffer()));
- return as<JS::Uint8ClampedArray>(*typed_array);
-}
+ auto result = construct_image_data(realm, JS::Value(static_cast<JS::Object*>(data.ptr())), 1, 1);
+ EXPECT(result.is_throw_completion());
+ auto thrown = result.throw_completion().value();
+ EXPECT(thrown.is_object());
+ auto* exception = Web::Bindings::impl_from<Web::WebIDL::DOMException>(&thrown.as_object());
+ EXPECT(exception);
+ EXPECT_EQ(exception->name(), "InvalidStateError"_fly_string);
}
-TEST_CASE(create_rejects_out_of_bounds_uint8_clamped_array)
+TEST_CASE(construct_views_the_pixels_of_its_data)
{
TestVM test_vm;
auto& realm = *test_vm.realm;
- auto data = create_out_of_bounds_uint8_clamped_array(realm);
+ auto data = MUST(JS::Uint8ClampedArray::create(realm, 8));
+
+ auto wrapper = MUST(construct_image_data(realm, JS::Value(static_cast<JS::Object*>(data.ptr())), 2, 1));
- auto result = Web::HTML::ImageData::create(realm, data, 1, 1);
+ auto* image_data = Web::Bindings::impl_from<Web::HTML::ImageData>(wrapper.ptr());
+ EXPECT(image_data);
+ EXPECT_EQ(image_data->width(), 2u);
+ EXPECT_EQ(image_data->height(), 1u);
+ EXPECT_EQ(image_data->pixels(), data->viewed_array_buffer()->data_at(0));
- EXPECT(result.is_exception());
- auto exception = result.exception();
- EXPECT(exception.has<GC::Ref<Web::WebIDL::DOMException>>());
- EXPECT_EQ(exception.get<GC::Ref<Web::WebIDL::DOMException>>()->name(), "InvalidStateError"_fly_string);
+ MUST(JS::detach_array_buffer(realm.vm(), *data->viewed_array_buffer()));
+ EXPECT(image_data->is_detached());
+ EXPECT_EQ(image_data->pixels(), nullptr);
}
diff --git a/Tests/LibWeb/TestStructuredSerializeDurability.cpp b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
index 8817db2afd8..7c18d8aef41 100644
--- a/Tests/LibWeb/TestStructuredSerializeDurability.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
@@ -9,6 +9,7 @@
#include <AK/FlyString.h>
#include <AK/NumericLimits.h>
#include <LibJS/Forward.h>
+#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/BigIntObject.h>
@@ -534,7 +535,7 @@ TEST_CASE(image_serializables_round_trip)
auto& image = unwrap_wrappable<Web::HTML::ImageData>(MUST(storage_deserialize(frozen_image_data_record({ pixels.data(), pixels.size() }, 1, 1, "srgb"sv))));
EXPECT_EQ(image.width(), 1u);
EXPECT_EQ(image.height(), 1u);
- EXPECT(image.data() != nullptr);
+ EXPECT(image.pixels() != nullptr);
}
{
@@ -545,6 +546,35 @@ TEST_CASE(image_serializables_round_trip)
}
}
+TEST_CASE(image_data_over_a_shrunk_resizable_buffer_has_no_pixels)
+{
+ auto& realm = test_realm();
+ auto& vm = realm.vm();
+
+ // An ImageData whose data views all of a resizable buffer, which script can shrink after it arrives.
+ Array<u8, 8> pixels { 1, 2, 3, 4, 5, 6, 7, 8 };
+ Vector<u8> body;
+ append_array_buffer_view_value(body, "Uint8ClampedArray"sv, BackingBuffer::Resizable, { pixels.data(), pixels.size() }, static_cast<u32>(pixels.size()), 0, static_cast<u32>(pixels.size()));
+ append_storage_signed_leb128(body, 2);
+ append_storage_signed_leb128(body, 1);
+ append_storage_string(body, "srgb"sv);
+ auto value = MUST(storage_deserialize(serializable_storage_record("ImageData"sv, 1, body)));
+ auto& image = unwrap_wrappable<Web::HTML::ImageData>(value);
+ EXPECT(image.pixels() != nullptr);
+ EXPECT(!image.bitmap().is_error());
+
+ auto data = MUST(value.as_object().get("data"_utf16_fly_string));
+ auto& buffer = *as<JS::TypedArrayBase>(data.as_object()).viewed_array_buffer();
+ EXPECT(!buffer.is_fixed_length());
+ MUST(JS::call(vm, MUST(buffer.get(vm.names.resize)), JS::Value { &buffer }, JS::Value(4)));
+
+ // The data no longer has room for the pixels, so they are not read: putImageData() and createImageBitmap() see
+ // no pixels, and WebGL uploads none.
+ EXPECT(!image.is_detached());
+ EXPECT_EQ(image.pixels(), nullptr);
+ EXPECT(image.bitmap().is_error());
+}
+
TEST_CASE(webassembly_module_decodes_from_frozen_bytes)
{
auto value = MUST(principal_storage_deserialize(webassembly_module_storage_record(s_minimal_webassembly_module_bytes.span())));
diff --git a/Tests/LibWeb/TestStructuredSerializeFormat.cpp b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
index ce3aad01d94..ae2604875f9 100644
--- a/Tests/LibWeb/TestStructuredSerializeFormat.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
@@ -601,8 +601,9 @@ TEST_CASE(image_serializables_encode_to_frozen_bytes)
auto& realm = test_realm();
{
- auto pixels = MUST(JS::Uint8ClampedArray::create(realm, 4));
- auto image = MUST(Web::HTML::ImageData::create(realm, pixels, 1));
+ auto image = MUST(Web::HTML::ImageData::create(realm, 1, 1));
+ auto image_wrapper = Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(realm), realm, image);
+ auto pixels = GC::Ref { MUST(image_wrapper->get("data"_utf16_fly_string)).as_object() };
// Build the data sub-value from the live typed array.
auto data_body = serialized_object_body(pixels);
diff --git a/Tests/LibWeb/Text/expected/canvas/image-data-in-rust.txt b/Tests/LibWeb/Text/expected/canvas/image-data-in-rust.txt
new file mode 100644
index 00000000000..c3ac6f04f43
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/canvas/image-data-in-rust.txt
@@ -0,0 +1,30 @@
+ImageData: [object ImageData], 2x1, srgb
+data: [object Uint8ClampedArray], 8 bytes, same object true
+settings: display-p3
+invalid color space: TypeError
+zero width: IndexSizeError
+zero height: IndexSizeError
+too large: IndexSizeError
+one argument: TypeError
+from data: 2x1, data is the array true
+from data with height: 2
+from data, wrong height: IndexSizeError
+from data, width not dividing: IndexSizeError
+from data, zero width: IndexSizeError
+from data, not a multiple of four: InvalidStateError
+from data, empty: InvalidStateError
+from detached data: InvalidStateError
+from a Uint8Array: IndexSizeError
+from shared data: TypeError
+wide: 70000x1, 280000 bytes
+wide getImageData: 70000x1, 10,20,30,255,10,20,30,255,0,0,0,0
+wide putImageData: 200,200,200,200,200,200,200,200
+wide putImageData, huge dirty rectangle: undefined
+wide createImageBitmap: InvalidStateError, Image size is too large
+tall putImageData past the end: 0,0,0,0
+clone: true, 2x1, display-p3, 255,0,0,255,0,255,0,128
+clone has its own data: true
+a cloned ImageData is cloned once: true
+texImage2D from ImageData: 255,0,0,255,0,255,0,128
+texImage2D keeps the pixels of the call: 1,2,3,4,5,6,7,8
+texImage2D from an ImageData with detached data: INVALID_VALUE
diff --git a/Tests/LibWeb/Text/input/canvas/image-data-in-rust.html b/Tests/LibWeb/Text/input/canvas/image-data-in-rust.html
new file mode 100644
index 00000000000..ea966bf879e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/canvas/image-data-in-rust.html
@@ -0,0 +1,123 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ function outcome(f) {
+ try {
+ const result = f();
+ return `${result}`;
+ } catch (error) {
+ return error.name;
+ }
+ }
+
+ 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 => {
+ // The constructors.
+ const imageData = new ImageData(2, 1);
+ println(`ImageData: ${Object.prototype.toString.call(imageData)}, ${imageData.width}x${imageData.height}, ${imageData.colorSpace}`);
+ println(`data: ${Object.prototype.toString.call(imageData.data)}, ${imageData.data.length} bytes, same object ${imageData.data === imageData.data}`);
+ println(`settings: ${new ImageData(1, 1, { colorSpace: "display-p3" }).colorSpace}`);
+ println(`invalid color space: ${outcome(() => new ImageData(1, 1, { colorSpace: "rec2020" }))}`);
+ println(`zero width: ${outcome(() => new ImageData(0, 1))}`);
+ println(`zero height: ${outcome(() => new ImageData(1, 0))}`);
+ println(`too large: ${outcome(() => new ImageData(65536, 65536))}`);
+ println(`one argument: ${outcome(() => new ImageData(1))}`);
+
+ const data = new Uint8ClampedArray([1, 2, 3, 4, 5, 6, 7, 8]);
+ const fromData = new ImageData(data, 2);
+ println(`from data: ${fromData.width}x${fromData.height}, data is the array ${fromData.data === data}`);
+ println(`from data with height: ${new ImageData(data, 1, 2).height}`);
+ println(`from data, wrong height: ${outcome(() => new ImageData(data, 2, 2))}`);
+ println(`from data, width not dividing: ${outcome(() => new ImageData(data, 3))}`);
+ println(`from data, zero width: ${outcome(() => new ImageData(data, 0))}`);
+ println(`from data, not a multiple of four: ${outcome(() => new ImageData(new Uint8ClampedArray(6), 1))}`);
+ println(`from data, empty: ${outcome(() => new ImageData(new Uint8ClampedArray(0), 1))}`);
+ const detached = new Uint8ClampedArray(4);
+ detached.buffer.transfer();
+ println(`from detached data: ${outcome(() => new ImageData(detached, 1))}`);
+ println(`from a Uint8Array: ${outcome(() => new ImageData(new Uint8Array(4), 1))}`);
+ println(`from shared data: ${outcome(() => new ImageData(new Uint8ClampedArray(new SharedArrayBuffer(4)), 1))}`);
+
+ // An ImageData wider than a bitmap can be.
+ const wide = new ImageData(70000, 1);
+ println(`wide: ${wide.width}x${wide.height}, ${wide.data.length} bytes`);
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = 2;
+ const context = canvas.getContext("2d");
+ context.fillStyle = "rgb(10, 20, 30)";
+ context.fillRect(0, 0, 2, 2);
+ const wideRead = context.getImageData(0, 0, 70000, 1);
+ println(`wide getImageData: ${wideRead.width}x${wideRead.height}, ${Array.from(wideRead.data.slice(0, 12)).join(",")}`);
+ context.putImageData(new ImageData(new Uint8ClampedArray(70000 * 4).fill(200), 70000, 1), -1, 1);
+ println(`wide putImageData: ${Array.from(context.getImageData(0, 1, 2, 1).data).join(",")}`);
+ println(`wide putImageData, huge dirty rectangle: ${outcome(() => context.putImageData(wide, 0, 0, -2147483648, -2147483648, 2147483647, 2147483647))}`);
+ try {
+ await createImageBitmap(wide);
+ println("wide createImageBitmap: resolved");
+ } catch (error) {
+ println(`wide createImageBitmap: ${error.name}, ${error.message}`);
+ }
+
+ // The dirty rectangle of putImageData() is clamped to the ImageData in integers. In floats, 16777219 rounds
+ // to 16777220, which left the dirty rectangle one row past the end of the pixels.
+ const tall = new ImageData(1, 16777219);
+ const tallCanvas = document.createElement("canvas");
+ tallCanvas.width = tallCanvas.height = 1;
+ const tallContext = tallCanvas.getContext("2d");
+ tallContext.putImageData(tall, 0, -16777219, 0, 16777219, 1, 1);
+ println(`tall putImageData past the end: ${Array.from(tallContext.getImageData(0, 0, 1, 1).data).join(",")}`);
+
+ // Structured cloning.
+ const original = new ImageData(new Uint8ClampedArray([255, 0, 0, 255, 0, 255, 0, 128]), 2, 1, { colorSpace: "display-p3" });
+ const clone = structuredClone(original);
+ println(`clone: ${clone instanceof ImageData}, ${clone.width}x${clone.height}, ${clone.colorSpace}, ${Array.from(clone.data).join(",")}`);
+ println(`clone has its own data: ${clone.data !== original.data}`);
+ const nested = structuredClone({ first: original, second: original });
+ println(`a cloned ImageData is cloned once: ${nested.first === nested.second}`);
+
+ // WebGL reads its pixels.
+ const gl = document.createElement("canvas").getContext("webgl");
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ println(`texImage2D from ImageData: ${uploadAndReadBack(gl, original)}`);
+ const changing = new ImageData(new Uint8ClampedArray([1, 2, 3, 4, 5, 6, 7, 8]), 2, 1);
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, changing);
+ changing.data.fill(9);
+ changing.data.buffer.transfer();
+ const framebuffer = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ const uploaded = new Uint8Array(8);
+ gl.readPixels(0, 0, 2, 1, gl.RGBA, gl.UNSIGNED_BYTE, uploaded);
+ println(`texImage2D keeps the pixels of the call: ${Array.from(uploaded).join(",")}`);
+ println(`texImage2D from an ImageData with detached data: ${uploadAndReadBack(gl, changing)}`);
+ done();
+ });
+</script>