Truly independent web browser
LibJS+LibWeb: Implement the geometry interfaces in Rust
Andreas Kling2f21d9a167c8
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex 875805d2376..0be07108e71 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -47,6 +47,7 @@ pub use crate::runtime::typed_array::{Kind as TypedArrayKind, TypedArrayBase, TypedArrayWithBufferWitness, create_typed_array_on_buffer,is_typed_array_out_of_bounds, make_typed_array_with_buffer_witness_record, typed_array_byte_length,};+pub use crate::runtime::value::number_to_string;pub use crate::utf16::{Utf16Display, to_well_formed};/// Derives Trace for a type of the embedder, which marks the type `#[gc(crate = libjs_rust)]`.pub use libjs_runtime_macros::Trace;diff --git a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rsindex ce9c660dc7b..26befbc7482 100644--- a/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/canvas_2d/canvas.rs@@ -13,9 +13,9 @@ use core::ptr::NonNull;use ak::Utf16String;use libcompositing_rust::filter_bytes::FfiFilterFunction;+use libgfx_rust::Color;use libgfx_rust::font::FontCascadeListHandle;use libgfx_rust::image_frame::ImageFrameHandle;-use libgfx_rust::{AffineTransform, Color};use libjs_rust::api::{Gc, Object, Realm};use super::host::CppTransport;@@ -56,7 +56,6 @@ unsafe extern "C" {fn web_canvas_2d_parse_length(length: usize, out_serialized: *mut usize) -> *const c_void;fn web_canvas_2d_style_value_ref(style_value: *const c_void);fn web_canvas_2d_style_value_unref(style_value: *const c_void);- fn web_canvas_2d_create_dom_matrix(realm: *mut c_void, transform: *const AffineTransform) -> *mut c_void;fn web_canvas_2d_image_frame_from_pixels(first_row: *const u8,pitch: usize,@@ -344,15 +343,6 @@ pub(crate) fn parse_length(length: &Utf16String) -> Option<(StyleValue, Utf16StrSome((style_value, unsafe { Utf16String::from_raw_owned(serialized) }))}-/// A new DOMMatrix with the transform, in the realm.-pub(crate) fn create_dom_matrix(realm: Gc<Realm>, transform: AffineTransform) -> CppInterface {- // SAFETY: The realm is live, and the transform is lent for the call.- let wrapper = unsafe { web_canvas_2d_create_dom_matrix(realm.as_ptr().cast(), &raw const transform) };- let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns the wrapper of the matrix");- // SAFETY: LibWeb returns a live wrapper of a DOMMatrix.- unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }-}-/// A frame of a copy of `height` rows of `width` RGBA8888 pixels that are unpremultiplied, `pitch` bytes apart, or/// None if there is no memory for it.///diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dictionaries.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dictionaries.rsnew file mode 100644index 00000000000..89ee7012de5--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dictionaries.rs@@ -0,0 +1,336 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The dictionaries of the geometry interfaces, which the modules of the interfaces name, and the steps that validate+//! the matrix dictionaries, https://drafts.fxtf.org/geometry/#DOMMatrixInit-dictionary++use libgfx_rust::AffineTransform;++/// https://drafts.fxtf.org/geometry/#dictdef-dompointinit+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct DOMPointInit {+ pub(crate) x: f64,+ pub(crate) y: f64,+ pub(crate) z: f64,+ pub(crate) w: f64,+}++impl Default for DOMPointInit {+ fn default() -> Self {+ Self {+ x: 0.0,+ y: 0.0,+ z: 0.0,+ w: 1.0,+ }+ }+}++/// https://drafts.fxtf.org/geometry/#dictdef-domrectinit+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub(crate) struct DOMRectInit {+ pub(crate) x: f64,+ pub(crate) y: f64,+ pub(crate) width: f64,+ pub(crate) height: f64,+}++/// https://drafts.fxtf.org/geometry/#dictdef-domquadinit+#[derive(Clone, Copy, Debug, Default)]+pub(crate) struct DOMQuadInit {+ pub(crate) p1: Option<DOMPointInit>,+ pub(crate) p2: Option<DOMPointInit>,+ pub(crate) p3: Option<DOMPointInit>,+ pub(crate) p4: Option<DOMPointInit>,+}++/// https://drafts.fxtf.org/geometry/#dictdef-dommatrix2dinit+#[derive(Clone, Copy, Debug, Default)]+pub(crate) struct DOMMatrix2DInit {+ pub(crate) a: Option<f64>,+ pub(crate) b: Option<f64>,+ pub(crate) c: Option<f64>,+ pub(crate) d: Option<f64>,+ pub(crate) e: Option<f64>,+ pub(crate) f: Option<f64>,+ pub(crate) m11: Option<f64>,+ pub(crate) m12: Option<f64>,+ pub(crate) m21: Option<f64>,+ pub(crate) m22: Option<f64>,+ pub(crate) m41: Option<f64>,+ pub(crate) m42: Option<f64>,+}++/// https://drafts.fxtf.org/geometry/#dictdef-dommatrixinit+#[derive(Clone, Copy, Debug)]+pub(crate) struct DOMMatrixInit {+ pub(crate) parent: DOMMatrix2DInit,+ pub(crate) m13: f64,+ pub(crate) m14: f64,+ pub(crate) m23: f64,+ pub(crate) m24: f64,+ pub(crate) m31: f64,+ pub(crate) m32: f64,+ pub(crate) m33: f64,+ pub(crate) m34: f64,+ pub(crate) m43: f64,+ pub(crate) m44: f64,+ pub(crate) is2d: Option<bool>,+}++/// The six elements of a 2D matrix, which validating and fixing up a DOMMatrix2DInit gives.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct Matrix2D {+ pub(crate) m11: f64,+ pub(crate) m12: f64,+ pub(crate) m21: f64,+ pub(crate) m22: f64,+ pub(crate) m41: f64,+ pub(crate) m42: f64,+}++impl Matrix2D {+ /// Whether none of the elements is infinite or NaN.+ pub(crate) fn is_finite(&self) -> bool {+ [self.m11, self.m12, self.m21, self.m22, self.m41, self.m42]+ .iter()+ .all(|element| element.is_finite())+ }++ /// The transform of the matrix in floats, as Gfx::AffineTransform takes the elements of a DOMMatrix.+ #[allow(clippy::cast_possible_truncation, reason = "Gfx::AffineTransform is in floats")]+ pub(crate) fn to_affine_transform(self) -> AffineTransform {+ AffineTransform::new(+ self.m11 as f32,+ self.m12 as f32,+ self.m21 as f32,+ self.m22 as f32,+ self.m41 as f32,+ self.m42 as f32,+ )+ }+}++/// The TypeError of validating a dictionary whose members disagree, with its message.+#[derive(Debug, PartialEq, Eq)]+pub(crate) struct InconsistentMembers(pub(crate) &'static str);++#[cfg(not(test))]+impl From<InconsistentMembers> for crate::bindings::Exception {+ fn from(InconsistentMembers(message): InconsistentMembers) -> Self {+ Self::TypeError(ak::Utf16String::from_ascii(message.as_bytes()))+ }+}++/// SameValueZero() of two numbers, https://tc39.es/ecma262/#sec-samevaluezero+fn same_value_zero(x: f64, y: f64) -> bool {+ (x.is_nan() && y.is_nan()) || x == y+}++/// https://drafts.fxtf.org/geometry/#matrix-validate-and-fixup-2d+pub(crate) fn validate_and_fixup_2d(init: &DOMMatrix2DInit) -> Result<Matrix2D, InconsistentMembers> {+ // 1. If if at least one of the following conditions are true for dict, then throw a TypeError exception and+ // abort these steps.+ let disagree = |member: Option<f64>, matrix_member: Option<f64>| matches!((member, matrix_member), (Some(member), Some(matrix_member)) if !same_value_zero(member, matrix_member));+ // - a and m11 are both present and SameValueZero(a, m11) is false.+ if disagree(init.a, init.m11) {+ return Err(InconsistentMembers(+ "DOMMatrix2DInit.a and DOMMatrix2DInit.m11 must have the same value if they are both present",+ ));+ }+ // - b and m12 are both present and SameValueZero(b, m12) is false.+ if disagree(init.b, init.m12) {+ return Err(InconsistentMembers(+ "DOMMatrix2DInit.b and DOMMatrix2DInit.m12 must have the same value if they are both present",+ ));+ }+ // - c and m21 are both present and SameValueZero(c, m21) is false.+ if disagree(init.c, init.m21) {+ return Err(InconsistentMembers(+ "DOMMatrix2DInit.c and DOMMatrix2DInit.m21 must have the same value if they are both present",+ ));+ }+ // - d and m22 are both present and SameValueZero(d, m22) is false.+ if disagree(init.d, init.m22) {+ return Err(InconsistentMembers(+ "DOMMatrix2DInit.d and DOMMatrix2DInit.m22 must have the same value if they are both present",+ ));+ }+ // - e and m41 are both present and SameValueZero(e, m41) is false.+ if disagree(init.e, init.m41) {+ return Err(InconsistentMembers(+ "DOMMatrix2DInit.e and DOMMatrix2DInit.m41 must have the same value if they are both present",+ ));+ }+ // - f and m42 are both present and SameValueZero(f, m42) is false.+ if disagree(init.f, init.m42) {+ return Err(InconsistentMembers(+ "DOMMatrix2DInit.f and DOMMatrix2DInit.m42 must have the same value if they are both present",+ ));+ }++ // 2. If m11 is not present then set it to the value of member a, or value 1 if a is also not present.+ // 3. If m12 is not present then set it to the value of member b, or value 0 if b is also not present.+ // 4. If m21 is not present then set it to the value of member c, or value 0 if c is also not present.+ // 5. If m22 is not present then set it to the value of member d, or value 1 if d is also not present.+ // 6. If m41 is not present then set it to the value of member e, or value 0 if e is also not present.+ // 7. If m42 is not present then set it to the value of member f, or value 0 if f is also not present.+ Ok(Matrix2D {+ m11: init.m11.or(init.a).unwrap_or(1.0),+ m12: init.m12.or(init.b).unwrap_or(0.0),+ m21: init.m21.or(init.c).unwrap_or(0.0),+ m22: init.m22.or(init.d).unwrap_or(1.0),+ m41: init.m41.or(init.e).unwrap_or(0.0),+ m42: init.m42.or(init.f).unwrap_or(0.0),+ })+}++/// A DOMMatrixInit after validating and fixing it up: its sixteen elements, and whether it is 2D.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct FixedUpMatrixInit {+ pub(crate) matrix_2d: Matrix2D,+ pub(crate) init: [f64; 10],+ pub(crate) is_2d: bool,+}++/// https://drafts.fxtf.org/geometry/#matrix-validate-and-fixup+pub(crate) fn validate_and_fixup(init: &DOMMatrixInit) -> Result<FixedUpMatrixInit, InconsistentMembers> {+ // 1. Validate and fixup (2D) dict.+ let matrix_2d = validate_and_fixup_2d(&init.parent)?;++ let is_3d = [+ init.m13, init.m14, init.m23, init.m24, init.m31, init.m32, init.m34, init.m43,+ ]+ .iter()+ .any(|element| *element != 0.0)+ || init.m33 != 1.0+ || init.m44 != 1.0;++ // 2. If is2D is true and: at least one of m13, m14, m23, m24, m31, m32, m34, m43 are present with a value other+ // than 0 or -0, or at least one of m33, m44 are present with a value other than 1, then throw a TypeError+ // exception and abort these steps.+ if init.is2d == Some(true) && is_3d {+ return Err(InconsistentMembers(+ "DOMMatrixInit.is2D is true, but the given matrix is not a 2D matrix",+ ));+ }++ // 3. If is2D is not present and at least one of m13, m14, m23, m24, m31, m32, m34, m43 are present with a value+ // other than 0 or -0, or at least one of m33, m44 are present with a value other than 1, set is2D to false.+ // 4. If is2D is still not present, set it to true.+ let is_2d = init.is2d.unwrap_or(!is_3d);++ Ok(FixedUpMatrixInit {+ matrix_2d,+ init: [+ init.m13, init.m14, init.m23, init.m24, init.m31, init.m32, init.m33, init.m34, init.m43, init.m44,+ ],+ is_2d,+ })+}++#[cfg(test)]+mod tests {+ use super::{+ DOMMatrix2DInit, DOMMatrixInit, InconsistentMembers, Matrix2D, validate_and_fixup, validate_and_fixup_2d,+ };++ fn identity_init() -> DOMMatrixInit {+ DOMMatrixInit {+ parent: DOMMatrix2DInit::default(),+ m13: 0.0,+ m14: 0.0,+ m23: 0.0,+ m24: 0.0,+ m31: 0.0,+ m32: 0.0,+ m33: 1.0,+ m34: 0.0,+ m43: 0.0,+ m44: 1.0,+ is2d: None,+ }+ }++ #[test]+ fn an_empty_dictionary_is_the_identity() {+ assert_eq!(+ validate_and_fixup_2d(&DOMMatrix2DInit::default()),+ Ok(Matrix2D {+ m11: 1.0,+ m12: 0.0,+ m21: 0.0,+ m22: 1.0,+ m41: 0.0,+ m42: 0.0,+ })+ );+ }++ #[test]+ fn matrix_members_win_over_their_aliases() {+ let init = DOMMatrix2DInit {+ a: Some(2.0),+ m22: Some(3.0),+ e: Some(4.0),+ m41: Some(4.0),+ f: Some(5.0),+ ..DOMMatrix2DInit::default()+ };+ let matrix = validate_and_fixup_2d(&init).expect("the members agree");+ assert_eq!((matrix.m11, matrix.m22, matrix.m41, matrix.m42), (2.0, 3.0, 4.0, 5.0));+ }++ #[test]+ fn members_that_disagree_are_a_type_error() {+ let init = DOMMatrix2DInit {+ b: Some(1.0),+ m12: Some(2.0),+ ..DOMMatrix2DInit::default()+ };+ assert_eq!(+ validate_and_fixup_2d(&init),+ Err(InconsistentMembers(+ "DOMMatrix2DInit.b and DOMMatrix2DInit.m12 must have the same value if they are both present"+ ))+ );+ }++ #[test]+ fn members_are_compared_with_same_value_zero() {+ let init = DOMMatrix2DInit {+ a: Some(f64::NAN),+ m11: Some(f64::NAN),+ c: Some(0.0),+ m21: Some(-0.0),+ ..DOMMatrix2DInit::default()+ };+ let matrix = validate_and_fixup_2d(&init).expect("the members agree");+ assert!(matrix.m11.is_nan());+ assert!(!matrix.is_finite());+ assert!(matrix.m21.is_sign_negative());+ }++ #[test]+ fn a_3d_element_makes_the_dictionary_3d() {+ let init = DOMMatrixInit {+ m34: -0.5,+ ..identity_init()+ };+ assert!(!validate_and_fixup(&init).expect("the members agree").is_2d);+ assert!(validate_and_fixup(&identity_init()).expect("the members agree").is_2d);+ }++ #[test]+ fn a_2d_dictionary_with_a_3d_element_is_a_type_error() {+ let init = DOMMatrixInit {+ m33: 2.0,+ is2d: Some(true),+ ..identity_init()+ };+ assert!(validate_and_fixup(&init).is_err());+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix.rsnew file mode 100644index 00000000000..a9cf3e3aeda--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix.rs@@ -0,0 +1,426 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://drafts.fxtf.org/geometry/#dommatrix++use ak::Utf16String;+use libjs_rust::api::{Gc, Trace, TypedArrayBase};++use super::dom_matrix_read_only::{+ DOMMatrixInit, DOMMatrixReadOnly, DOMStringOrUnrestrictedDoubleSequence, deserialize_matrix, parse_transform_list,+ serialize_matrix,+};+use super::matrix::ColumnMajor;+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};+use crate::bindings::{CallContext, WebIdlResult};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DOMMatrix {+ matrix: DOMMatrixReadOnly,+}++impl Wrappable for DOMMatrix {}++impl Inherits<DOMMatrixReadOnly> for DOMMatrix {+ fn parent(&self) -> &DOMMatrixReadOnly {+ &self.matrix+ }+}++impl DOMMatrix {+ pub(crate) fn from_read_only(matrix: DOMMatrixReadOnly) -> Self {+ Self { matrix }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-dommatrix+ pub(crate) fn construct(+ cx: &mut CallContext,+ init: Option<DOMStringOrUnrestrictedDoubleSequence>,+ ) -> WebIdlResult<Self> {+ Ok(Self::from_read_only(DOMMatrixReadOnly::from_init(cx, init)?))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-frommatrix+ pub(crate) fn from_matrix(cx: &mut CallContext, other: DOMMatrixInit) -> WebIdlResult<Ref<Self>> {+ // The fromMatrix(other) static method on DOMMatrix must create a DOMMatrix from the dictionary other.+ Ok(allocate(cx.vm(), Self::from_dictionary(&other)?))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-fromfloat32array+ pub(crate) fn from_float32_array(cx: &mut CallContext, array32: Gc<TypedArrayBase>) -> WebIdlResult<Ref<Self>> {+ let matrix = DOMMatrixReadOnly::from_typed_array(array32)?;+ Ok(allocate(cx.vm(), Self::from_read_only(matrix)))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-fromfloat64array+ pub(crate) fn from_float64_array(cx: &mut CallContext, array64: Gc<TypedArrayBase>) -> WebIdlResult<Ref<Self>> {+ let matrix = DOMMatrixReadOnly::from_typed_array(array64)?;+ Ok(allocate(cx.vm(), Self::from_read_only(matrix)))+ }++ /// https://drafts.fxtf.org/geometry/#create-a-dommatrix-from-the-dictionary+ pub(crate) fn from_dictionary(other: &DOMMatrixInit) -> WebIdlResult<Self> {+ Ok(Self::from_read_only(DOMMatrixReadOnly::from_dictionary(other)?))+ }++ /// Sets the element mRC of the 2D matrix to the value, as the setter of its attribute does.+ fn set_element(&self, row: usize, column: usize, value: f64) {+ let mut matrix = self.matrix.matrix();+ matrix.set_element(row, column, value);+ self.matrix.set_matrix(matrix);+ }++ /// Sets an element outside of the 2D matrix: the element to the new value and, if the new value is not the value+ /// of the identity matrix, is 2D to false.+ fn set_3d_element(&self, row: usize, column: usize, value: f64) {+ self.set_element(row, column, value);+ let identity_value = if row == column { 1.0 } else { 0.0 };+ if value != identity_value {+ self.matrix.set_is_2d(false);+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-a+ pub(crate) fn set_a(&self, cx: &mut CallContext, value: f64) -> WebIdlResult<()> {+ self.set_m11(cx, value)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-b+ pub(crate) fn set_b(&self, cx: &mut CallContext, value: f64) -> WebIdlResult<()> {+ self.set_m12(cx, value)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-c+ pub(crate) fn set_c(&self, cx: &mut CallContext, value: f64) -> WebIdlResult<()> {+ self.set_m21(cx, value)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-d+ pub(crate) fn set_d(&self, cx: &mut CallContext, value: f64) -> WebIdlResult<()> {+ self.set_m22(cx, value)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-e+ pub(crate) fn set_e(&self, cx: &mut CallContext, value: f64) -> WebIdlResult<()> {+ self.set_m41(cx, value)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-f+ pub(crate) fn set_f(&self, cx: &mut CallContext, value: f64) -> WebIdlResult<()> {+ self.set_m42(cx, value)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m11+ pub(crate) fn set_m11(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m11 or the a attribute must set the m11 element to the new value.+ self.set_element(1, 1, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m12+ pub(crate) fn set_m12(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m12 or the b attribute must set the m12 element to the new value.+ self.set_element(1, 2, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m13+ pub(crate) fn set_m13(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m13 attribute must set the m13 element to the new value and, if the+ // new value is not 0 or -0, set is 2D to false.+ self.set_3d_element(1, 3, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m14+ pub(crate) fn set_m14(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m14 attribute must set the m14 element to the new value and, if the+ // new value is not 0 or -0, set is 2D to false.+ self.set_3d_element(1, 4, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m21+ pub(crate) fn set_m21(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m21 or the c attribute must set the m21 element to the new value.+ self.set_element(2, 1, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m22+ pub(crate) fn set_m22(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m22 or the d attribute must set the m22 element to the new value.+ self.set_element(2, 2, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m23+ pub(crate) fn set_m23(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m23 attribute must set the m23 element to the new value and, if the+ // new value is not 0 or -0, set is 2D to false.+ self.set_3d_element(2, 3, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m24+ pub(crate) fn set_m24(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m24 attribute must set the m24 element to the new value and, if the+ // new value is not 0 or -0, set is 2D to false.+ self.set_3d_element(2, 4, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m31+ pub(crate) fn set_m31(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m31 attribute must set the m31 element to the new value and, if the+ // new value is not 0 or -0, set is 2D to false.+ self.set_3d_element(3, 1, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m32+ pub(crate) fn set_m32(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m32 attribute must set the m32 element to the new value and, if the+ // new value is not 0 or -0, set is 2D to false.+ self.set_3d_element(3, 2, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m33+ pub(crate) fn set_m33(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m33 attribute must set the m33 element to the new value and, if the+ // new value is not 1, set is 2D to false.+ self.set_3d_element(3, 3, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m34+ pub(crate) fn set_m34(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m34 attribute must set the m34 element to the new value and, if the+ // new value is not 0 or -0, set is 2D to false.+ self.set_3d_element(3, 4, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m41+ pub(crate) fn set_m41(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m41 or the e attribute must set the m41 element to the new value.+ self.set_element(4, 1, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m42+ pub(crate) fn set_m42(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m42 or the f attribute must set the m42 element to the new value.+ self.set_element(4, 2, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m43+ pub(crate) fn set_m43(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m43 attribute must set the m43 element to the new value and, if the+ // new value is not 0 or -0, set is 2D to false.+ self.set_3d_element(4, 3, value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m44+ pub(crate) fn set_m44(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMMatrix interface, setting the m44 attribute must set the m44 element to the new value and, if the+ // new value is not 1, set is 2D to false.+ self.set_3d_element(4, 4, value);+ Ok(())+ }++ // NB: The mutable transformation methods return the current matrix, so they receive the object that they run on,+ // which the bindings pass as they pass `&self` to the other methods.++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-multiplyself+ pub(crate) fn multiply_self(+ this: &Ref<Self>,+ _: &mut CallContext,+ other: DOMMatrixInit,+ ) -> WebIdlResult<Ref<Self>> {+ // 1. Let otherObject be the result of invoking create a DOMMatrix from the dictionary other.+ let other_object = Self::from_dictionary(&other)?;++ // 2. The otherObject matrix gets post-multiplied to the current matrix.+ // 3. If is 2D of otherObject is false, set is 2D of the current matrix to false.+ this.matrix.multiply_self_steps(&other_object.matrix);++ // 4. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-premultiplyself+ pub(crate) fn pre_multiply_self(+ this: &Ref<Self>,+ _: &mut CallContext,+ other: DOMMatrixInit,+ ) -> WebIdlResult<Ref<Self>> {+ // 1. Let otherObject be the result of invoking create a DOMMatrix from the dictionary other.+ let other_object = Self::from_dictionary(&other)?;++ // 2. The otherObject matrix gets pre-multiplied to the current matrix.+ // 3. If is 2D of otherObject is false, set is 2D of the current matrix to false.+ this.matrix.pre_multiply_self_steps(&other_object.matrix);++ // 4. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-translateself+ pub(crate) fn translate_self(+ this: &Ref<Self>,+ _: &mut CallContext,+ tx: f64,+ ty: f64,+ tz: f64,+ ) -> WebIdlResult<Ref<Self>> {+ this.matrix.translate_self_steps(tx, ty, tz);++ // 3. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-scaleself+ #[allow(clippy::too_many_arguments, reason = "the operation has six arguments")]+ pub(crate) fn scale_self(+ this: &Ref<Self>,+ _: &mut CallContext,+ scale_x: f64,+ scale_y: Option<f64>,+ scale_z: f64,+ origin_x: f64,+ origin_y: f64,+ origin_z: f64,+ ) -> WebIdlResult<Ref<Self>> {+ this.matrix+ .scale_self_steps(scale_x, scale_y, scale_z, origin_x, origin_y, origin_z);++ // 7. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-scale3dself+ pub(crate) fn scale3d_self(+ this: &Ref<Self>,+ _: &mut CallContext,+ scale: f64,+ origin_x: f64,+ origin_y: f64,+ origin_z: f64,+ ) -> WebIdlResult<Ref<Self>> {+ this.matrix.scale3d_self_steps(scale, origin_x, origin_y, origin_z);++ // 5. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-rotateself+ pub(crate) fn rotate_self(+ this: &Ref<Self>,+ _: &mut CallContext,+ rot_x: f64,+ rot_y: Option<f64>,+ rot_z: Option<f64>,+ ) -> WebIdlResult<Ref<Self>> {+ this.matrix.rotate_self_steps(rot_x, rot_y, rot_z);++ // 8. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-rotatefromvectorself+ pub(crate) fn rotate_from_vector_self(+ this: &Ref<Self>,+ _: &mut CallContext,+ x: f64,+ y: f64,+ ) -> WebIdlResult<Ref<Self>> {+ this.matrix.rotate_from_vector_self_steps(x, y);++ // 2. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-rotateaxisangleself+ pub(crate) fn rotate_axis_angle_self(+ this: &Ref<Self>,+ _: &mut CallContext,+ x: f64,+ y: f64,+ z: f64,+ angle: f64,+ ) -> WebIdlResult<Ref<Self>> {+ this.matrix.rotate_axis_angle_self_steps(x, y, z, angle);++ // 3. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-skewxself+ pub(crate) fn skew_x_self(this: &Ref<Self>, _: &mut CallContext, sx: f64) -> WebIdlResult<Ref<Self>> {+ this.matrix.skew_x_self_steps(sx);++ // 2. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-skewyself+ pub(crate) fn skew_y_self(this: &Ref<Self>, _: &mut CallContext, sy: f64) -> WebIdlResult<Ref<Self>> {+ this.matrix.skew_y_self_steps(sy);++ // 2. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-invertself+ pub(crate) fn invert_self(this: &Ref<Self>, _: &mut CallContext) -> WebIdlResult<Ref<Self>> {+ this.matrix.invert_self_steps();++ // 3. Return the current matrix.+ Ok(*this)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-setmatrixvalue+ pub(crate) fn set_matrix_value(+ this: &Ref<Self>,+ _: &mut CallContext,+ transform_list: Utf16String,+ ) -> WebIdlResult<Ref<Self>> {+ // 1. Parse transformList into an abstract matrix, and let matrix and 2dTransform be the result. If the result+ // is failure, then throw a "SyntaxError" DOMException.+ let (matrix, is_2d_transform) = parse_transform_list(&transform_list)?;++ // 2. Set is 2D to the value of 2dTransform.+ // 3. Set m11 element through m44 element to the element values of matrix in column-major order.+ this.matrix.set_matrix_value_steps(matrix, is_2d_transform);++ // 4. Return the current matrix.+ Ok(*this)+ }+}++impl Serializable for DOMMatrix {+ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn serialization_steps(+ &self,+ _: &mut CallContext,+ serialized: &mut SerializationWriter,+ _for_storage: bool,+ ) -> WebIdlResult<()> {+ serialize_matrix(&self.matrix, serialized);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {+ Ok(Self::from_read_only(deserialize_matrix(serialized)?))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix_read_only.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix_read_only.rsindex bcf176a7950..4dec1b81c7b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix_read_only.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix_read_only.rs@@ -4,194 +4,1117 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The 2D matrix dictionary of Geometry/DOMMatrixReadOnly.idl, https://drafts.fxtf.org/geometry/#dictdef-dommatrix2dinit--use libgfx_rust::AffineTransform;--/// The dictionary DOMMatrix2DInit of Geometry/DOMMatrixReadOnly.idl, whose members the bindings convert.-#[derive(Clone, Copy, Debug, Default)]-pub(crate) struct DOMMatrix2DInit {- pub(crate) a: Option<f64>,- pub(crate) b: Option<f64>,- pub(crate) c: Option<f64>,- pub(crate) d: Option<f64>,- pub(crate) e: Option<f64>,- pub(crate) f: Option<f64>,- pub(crate) m11: Option<f64>,- pub(crate) m12: Option<f64>,- pub(crate) m21: Option<f64>,- pub(crate) m22: Option<f64>,- pub(crate) m41: Option<f64>,- pub(crate) m42: Option<f64>,+//! https://drafts.fxtf.org/geometry/#dommatrixreadonly++use core::cell::Cell;++use ak::Utf16String;+use libjs_rust::api::{+ ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, Gc, Trace, TypedArrayBase, TypedArrayKind,+ create_typed_array_on_buffer, is_typed_array_out_of_bounds, make_typed_array_with_buffer_witness_record,+ number_to_string, typed_array_byte_length,+};++#[cfg_attr(+ not(web_idl_bindings),+ allow(unused_imports, reason = "the generated bindings name the dictionaries here")+)]+pub(crate) use super::dictionaries::DOMMatrix2DInit;+pub(crate) use super::dictionaries::DOMMatrixInit;+use super::dictionaries::{FixedUpMatrixInit, Matrix2D, validate_and_fixup};+use super::dom_matrix::DOMMatrix;+use super::dom_point::DOMPoint;+use super::dom_point_read_only::{DOMPointInit, DOMPointReadOnly};+use super::matrix::{ColumnMajor, Matrix4, to_radians};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, realm_is_window};+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};+use crate::bindings::{CallContext, Exception, WebIdlResult};++unsafe extern "C" {+ // Defined in Libraries/LibWeb/Geometry/DOMMatrixReadOnly.cpp, which parses the string with LibWeb's CSS parser.+ fn web_dom_matrix_parse_transform_list(+ transform_list: usize,+ out_elements: &mut [f64; 16],+ out_is_2d: &mut bool,+ ) -> bool;}-/// The six elements of a 2D matrix, which validating and fixing up a DOMMatrix2DInit gives.-#[derive(Clone, Copy, Debug, PartialEq)]-pub(crate) struct Matrix2D {- pub(crate) m11: f64,- pub(crate) m12: f64,- pub(crate) m21: f64,- pub(crate) m22: f64,- pub(crate) m41: f64,- pub(crate) m42: f64,+/// The union (DOMString or sequence<unrestricted double>) of the constructors of DOMMatrixReadOnly and DOMMatrix.+pub(crate) enum DOMStringOrUnrestrictedDoubleSequence {+ DOMString(Utf16String),+ Sequence(Vec<f64>),}-impl Matrix2D {- /// Whether none of the elements is infinite or NaN.- pub(crate) fn is_finite(&self) -> bool {- [self.m11, self.m12, self.m21, self.m22, self.m41, self.m42]+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DOMMatrixReadOnly {+ #[gc(untraced)]+ matrix: Cell<Matrix4>,+ #[gc(untraced)]+ is_2d: Cell<bool>,+}++impl Wrappable for DOMMatrixReadOnly {}++impl DOMMatrixReadOnly {+ pub(crate) fn new(matrix: Matrix4, is_2d: bool) -> Self {+ Self {+ matrix: Cell::new(matrix),+ is_2d: Cell::new(is_2d),+ }+ }++ /// https://drafts.fxtf.org/geometry/#create-a-2d-matrix+ pub(crate) fn create_2d_matrix([m11, m12, m21, m22, m41, m42]: [f64; 6]) -> Self {+ // 1. Let matrix be a new instance of type.+ // 2. Set m11 element, m12 element, m21 element, m22 element, m41 element and m42 element to the values of+ // init in order starting with the first value.+ // 3. Set m13 element, m14 element, m23 element, m24 element, m31 element, m32 element, m34 element, and m43+ // element to 0.+ // 4. Set m33 element and m44 element to 1.+ let matrix = Matrix4::from_column_major([+ m11, m12, 0.0, 0.0, m21, m22, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, m41, m42, 0.0, 1.0,+ ]);++ // 5. Set is 2D to true.+ // 6. Return matrix+ Self::new(matrix, true)+ }++ /// https://drafts.fxtf.org/geometry/#create-a-3d-matrix+ pub(crate) fn create_3d_matrix(init: [f64; 16]) -> Self {+ // 1. Let matrix be a new instance of type.+ // 2. Set m11 element to m44 element to the values of init in column-major order.+ // 3. Set is 2D to false.+ // 4. Return matrix+ Self::new(Matrix4::from_column_major(init), false)+ }++ /// The steps of the constructors of DOMMatrixReadOnly and DOMMatrix,+ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-dommatrixreadonly+ pub(crate) fn from_init(+ cx: &CallContext,+ init: Option<DOMStringOrUnrestrictedDoubleSequence>,+ ) -> WebIdlResult<Self> {+ match init {+ // -> If init is omitted+ None => {+ // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as+ // appropriate, with the sequence [1, 0, 0, 1, 0, 0].+ Ok(Self::create_2d_matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]))+ }+ // -> If init is a DOMString+ Some(DOMStringOrUnrestrictedDoubleSequence::DOMString(init)) => {+ // 1. If current global object is not a Window object, then throw a TypeError exception.+ if !realm_is_window(cx.realm()) {+ return Err(Exception::TypeError(Utf16String::from_ascii(+ b"This can only be used in a Window context",+ )));+ }++ // 2. Parse init into an abstract matrix, and let matrix and 2dTransform be the result. If the result+ // is failure, then throw a "SyntaxError" DOMException.+ let (matrix, is_2d_transform) = parse_transform_list(&init)?;++ // -> If 2dTransform is true+ if is_2d_transform {+ // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as+ // appropriate, with a sequence of numbers, the values being the elements m11, m12, m21, m22, m41+ // and m42 of matrix.+ return Ok(Self::create_2d_matrix([+ matrix.element(1, 1),+ matrix.element(1, 2),+ matrix.element(2, 1),+ matrix.element(2, 2),+ matrix.element(4, 1),+ matrix.element(4, 2),+ ]));+ }++ // -> Otherwise+ // Return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as+ // appropriate, with a sequence of numbers, the values being the 16 elements of matrix.+ Ok(Self::create_3d_matrix(matrix.to_column_major()))+ }+ Some(DOMStringOrUnrestrictedDoubleSequence::Sequence(init)) => {+ Self::from_sequence(&init).ok_or_else(|| {+ // -> Otherwise+ // Throw a TypeError exception.+ Exception::TypeError(Utf16String::from_ascii(+ format!(+ "Sequence must contain exactly 6 or 16 elements, got {} element(s)",+ init.len()+ )+ .as_bytes(),+ ))+ })+ }+ }+ }++ /// The matrix of a sequence of 6 or 16 elements, of which the constructors and fromFloat32Array() and+ /// fromFloat64Array() create a 2d or a 3d matrix.+ fn from_sequence(init: &[f64]) -> Option<Self> {+ match init.len() {+ // -> If init is a sequence with 6 elements+ // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate,+ // with the sequence init.+ 6 => Some(Self::create_2d_matrix(+ init.try_into().expect("the sequence has 6 elements"),+ )),+ // -> If init is a sequence with 16 elements+ // Return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate,+ // with the sequence init.+ 16 => Some(Self::create_3d_matrix(+ init.try_into().expect("the sequence has 16 elements"),+ )),+ _ => None,+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-dommatrixreadonly+ pub(crate) fn construct(+ cx: &mut CallContext,+ init: Option<DOMStringOrUnrestrictedDoubleSequence>,+ ) -> WebIdlResult<Self> {+ Self::from_init(cx, init)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-frommatrix+ pub(crate) fn from_matrix(cx: &mut CallContext, other: DOMMatrixInit) -> WebIdlResult<Ref<Self>> {+ // The fromMatrix(other) static method on DOMMatrixReadOnly must create a DOMMatrixReadOnly from the dictionary+ // other.+ Ok(allocate(cx.vm(), Self::from_dictionary(&other)?))+ }++ /// https://drafts.fxtf.org/geometry/#create-a-dommatrixreadonly-from-the-dictionary+ pub(crate) fn from_dictionary(other: &DOMMatrixInit) -> WebIdlResult<Self> {+ // 1. Validate and fixup other.+ let FixedUpMatrixInit {+ matrix_2d:+ Matrix2D {+ m11,+ m12,+ m21,+ m22,+ m41,+ m42,+ },+ init: [m13, m14, m23, m24, m31, m32, m33, m34, m43, m44],+ is_2d,+ } = validate_and_fixup(other)?;++ // 2. If the is2D dictionary member of other is true+ if is_2d {+ // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate,+ // with a sequence of numbers, the values being the 6 elements m11, m12, m21, m22, m41 and m42 of other in+ // the given order.+ return Ok(Self::create_2d_matrix([m11, m12, m21, m22, m41, m42]));+ }++ // Otherwise+ // Return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with+ // a sequence of numbers, the values being the 16 elements m11, m12, m13, ..., m44 of other in the given order.+ Ok(Self::create_3d_matrix([+ m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44,+ ]))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-fromfloat32array+ pub(crate) fn from_float32_array(cx: &mut CallContext, array32: Gc<TypedArrayBase>) -> WebIdlResult<Ref<Self>> {+ Ok(allocate(cx.vm(), Self::from_typed_array(array32)?))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-fromfloat64array+ pub(crate) fn from_float64_array(cx: &mut CallContext, array64: Gc<TypedArrayBase>) -> WebIdlResult<Ref<Self>> {+ Ok(allocate(cx.vm(), Self::from_typed_array(array64)?))+ }++ /// The steps of fromFloat32Array() and fromFloat64Array() on DOMMatrixReadOnly and DOMMatrix, for a Float32Array+ /// or a Float64Array.+ pub(crate) fn from_typed_array(array: Gc<TypedArrayBase>) -> WebIdlResult<Self> {+ // -> If array32 has 6 elements+ // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate,+ // with a sequence of numbers taking the values from array32 in the provided order.+ // -> If array32 has 16 elements+ // Return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate,+ // with a sequence of numbers taking the values from array32 in the provided order.+ // -> Otherwise+ // Throw a TypeError exception.+ Self::from_sequence(&typed_array_elements(array)).ok_or_else(|| {+ Exception::TypeError(Utf16String::from_ascii(+ b"Sequence must contain exactly 6 or 16 elements",+ ))+ })+ }++ pub(crate) fn matrix(&self) -> Matrix4 {+ self.matrix.get()+ }++ pub(crate) fn is_2d(&self) -> bool {+ self.is_2d.get()+ }++ pub(super) fn set_matrix(&self, matrix: Matrix4) {+ self.matrix.set(matrix);+ }++ pub(super) fn set_is_2d(&self, is_2d: bool) {+ self.is_2d.set(is_2d);+ }++ fn element(&self, row: usize, column: usize) -> f64 {+ self.matrix.get().element(row, column)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-a+ pub(crate) fn a(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The a attribute is an alias to the m11 attribute.+ Ok(self.element(1, 1))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-b+ pub(crate) fn b(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The b attribute is an alias to the m12 attribute.+ Ok(self.element(1, 2))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-c+ pub(crate) fn c(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The c attribute is an alias to the m21 attribute.+ Ok(self.element(2, 1))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-d+ pub(crate) fn d(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The d attribute is an alias to the m22 attribute.+ Ok(self.element(2, 2))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-e+ pub(crate) fn e(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The e attribute is an alias to the m41 attribute.+ Ok(self.element(4, 1))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-f+ pub(crate) fn f(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The f attribute is an alias to the m42 attribute.+ Ok(self.element(4, 2))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m11+ pub(crate) fn m11(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(1, 1))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m12+ pub(crate) fn m12(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(1, 2))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m13+ pub(crate) fn m13(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(1, 3))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m14+ pub(crate) fn m14(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(1, 4))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m21+ pub(crate) fn m21(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(2, 1))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m22+ pub(crate) fn m22(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(2, 2))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m23+ pub(crate) fn m23(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(2, 3))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m24+ pub(crate) fn m24(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(2, 4))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m31+ pub(crate) fn m31(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(3, 1))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m32+ pub(crate) fn m32(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(3, 2))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m33+ pub(crate) fn m33(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(3, 3))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m34+ pub(crate) fn m34(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(3, 4))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m41+ pub(crate) fn m41(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(4, 1))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m42+ pub(crate) fn m42(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(4, 2))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m43+ pub(crate) fn m43(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(4, 3))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m44+ pub(crate) fn m44(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.element(4, 4))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-is2d+ pub(crate) fn is2d(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ // The is2D attribute must return the value of is 2D.+ Ok(self.is_2d.get())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-isidentity+ pub(crate) fn is_identity(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ // The isIdentity attribute must return true if m12 element, m13 element, m14 element, m21 element, m23+ // element, m24 element, m31 element, m32 element, m34 element, m41 element, m42 element, m43 element are 0 or+ // -0 and m11 element, m22 element, m33 element, m44 element are 1. Otherwise it must return false.+ Ok(self.matrix.get() == Matrix4::identity())+ }++ /// A new DOMMatrix initialized to the values of the current matrix, which the immutable transformation methods+ /// transform and return.+ fn copy(&self) -> DOMMatrix {+ DOMMatrix::from_read_only(DOMMatrixReadOnly::new(self.matrix.get(), self.is_2d.get()))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-translate+ pub(crate) fn translate(&self, cx: &mut CallContext, tx: f64, ty: f64, tz: f64) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a translateSelf() transformation on result with the arguments tx, ty, tz.+ result.parent().translate_self_steps(tx, ty, tz);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-scale+ #[allow(clippy::too_many_arguments, reason = "the operation has six arguments")]+ pub(crate) fn scale(+ &self,+ cx: &mut CallContext,+ scale_x: f64,+ scale_y: Option<f64>,+ scale_z: f64,+ origin_x: f64,+ origin_y: f64,+ origin_z: f64,+ ) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. If scaleY is missing, set scaleY to the value of scaleX.+ let scale_y = scale_y.unwrap_or(scale_x);++ // 2. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 3. Perform a scaleSelf() transformation on result with the arguments scaleX, scaleY, scaleZ, originX,+ // originY, originZ.+ result+ .parent()+ .scale_self_steps(scale_x, Some(scale_y), scale_z, origin_x, origin_y, origin_z);++ // 4. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-scalenonuniform+ pub(crate) fn scale_non_uniform(+ &self,+ cx: &mut CallContext,+ scale_x: f64,+ scale_y: f64,+ ) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a scaleSelf() transformation on result with the arguments scaleX, scaleY, 1, 0, 0, 0.+ result+ .parent()+ .scale_self_steps(scale_x, Some(scale_y), 1.0, 0.0, 0.0, 0.0);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-scale3d+ pub(crate) fn scale3d(+ &self,+ cx: &mut CallContext,+ scale: f64,+ origin_x: f64,+ origin_y: f64,+ origin_z: f64,+ ) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a scale3dSelf() transformation on result with the arguments scale, originX, originY, originZ.+ result.parent().scale3d_self_steps(scale, origin_x, origin_y, origin_z);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-rotate+ pub(crate) fn rotate(+ &self,+ cx: &mut CallContext,+ rot_x: f64,+ rot_y: Option<f64>,+ rot_z: Option<f64>,+ ) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a rotateSelf() transformation on result with the arguments rotX, rotY, rotZ.+ result.parent().rotate_self_steps(rot_x, rot_y, rot_z);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-rotatefromvector+ pub(crate) fn rotate_from_vector(&self, cx: &mut CallContext, x: f64, y: f64) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a rotateFromVectorSelf() transformation on result with the arguments x, y.+ result.parent().rotate_from_vector_self_steps(x, y);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-rotateaxisangle+ pub(crate) fn rotate_axis_angle(+ &self,+ cx: &mut CallContext,+ x: f64,+ y: f64,+ z: f64,+ angle: f64,+ ) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a rotateAxisAngleSelf() transformation on result with the arguments x, y, z, angle.+ result.parent().rotate_axis_angle_self_steps(x, y, z, angle);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-skewx+ pub(crate) fn skew_x(&self, cx: &mut CallContext, sx: f64) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a skewXSelf() transformation on result with the argument sx.+ result.parent().skew_x_self_steps(sx);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-skewy+ pub(crate) fn skew_y(&self, cx: &mut CallContext, sy: f64) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a skewYSelf() transformation on result with the argument sy.+ result.parent().skew_y_self_steps(sy);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-multiply+ pub(crate) fn multiply(&self, cx: &mut CallContext, other: DOMMatrixInit) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a multiplySelf() transformation on result with the argument other.+ let other_object = DOMMatrix::from_dictionary(&other)?;+ result.parent().multiply_self_steps(other_object.parent());++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-flipx+ pub(crate) fn flip_x(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Post-multiply result with new DOMMatrix([-1, 0, 0, 1, 0, 0]).+ let matrix = result.parent().matrix().multiplied(Matrix4::scale(-1.0, 1.0, 1.0));+ result.parent().set_matrix(matrix);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-flipy+ pub(crate) fn flip_y(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Post-multiply result with new DOMMatrix([1, 0, 0, -1, 0, 0]).+ let matrix = result.parent().matrix().multiplied(Matrix4::scale(1.0, -1.0, 1.0));+ result.parent().set_matrix(matrix);++ // 3. Return result.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-inverse+ pub(crate) fn inverse(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMMatrix>> {+ // 1. Let result be the resulting matrix initialized to the values of the current matrix.+ let result = self.copy();++ // 2. Perform a invertSelf() transformation on result.+ result.parent().invert_self_steps();++ // 3. Return result.+ // The current matrix is not modified.+ Ok(allocate(cx.vm(), result))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-transformpoint+ pub(crate) fn transform_point(&self, cx: &mut CallContext, point: DOMPointInit) -> WebIdlResult<Ref<DOMPoint>> {+ // Let pointObject be the result of invoking create a DOMPoint from the dictionary point. Return the result of+ // invoking transform a point with a matrix, given pointObject and the current matrix. The passed argument+ // does not get modified.+ let point_object = DOMPointReadOnly::from_dictionary(&point);+ Ok(allocate(cx.vm(), self.transform_point_steps(&point_object)))+ }++ /// https://drafts.fxtf.org/geometry/#transform-a-point-with-a-matrix+ pub(crate) fn transform_point_steps(&self, point: &DOMPointReadOnly) -> DOMPoint {+ // 1. Let x be point’s x coordinate.+ // 2. Let y be point’s y coordinate.+ // 3. Let z be point’s z coordinate.+ // 4. Let w be point’s w perspective.+ // 5. Let pointVector be a new column vector with the elements being x, y, z, and w, respectively.+ let point_vector = point.coordinates();++ // 6. Set pointVector to pointVector pre-multiplied by matrix.+ let [x, y, z, w] = self.matrix.get().map_vector4(point_vector);++ // 7. Let transformedPoint be a new DOMPoint object.+ // 8. Set transformedPoint’s x coordinate to pointVector’s first element.+ // 9. Set transformedPoint’s y coordinate to pointVector’s second element.+ // 10. Set transformedPoint’s z coordinate to pointVector’s third element.+ // 11. Set transformedPoint’s w perspective to pointVector’s fourth element.+ // 12. Return transformedPoint.+ DOMPoint::new(x, y, z, w)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-tofloat32array+ #[allow(clippy::cast_possible_truncation, reason = "a Float32Array holds floats")]+ pub(crate) fn to_float32_array(&self, cx: &mut CallContext) -> WebIdlResult<Gc<TypedArrayBase>> {+ // Returns the serialized 16 elements m11 to m44 of the current matrix in column-major order as Float32Array.+ let bytes: Vec<u8> = self+ .matrix+ .get()+ .to_column_major().iter()- .all(|element| element.is_finite())+ .flat_map(|element| (*element as f32).to_ne_bytes())+ .collect();+ create_typed_array(cx, TypedArrayKind::Float32Array, &bytes)}- /// The transform of the matrix in floats, as Gfx::AffineTransform takes the elements of a DOMMatrix.- #[allow(clippy::cast_possible_truncation, reason = "Gfx::AffineTransform is in floats")]- pub(crate) fn to_affine_transform(self) -> AffineTransform {- AffineTransform::new(- self.m11 as f32,- self.m12 as f32,- self.m21 as f32,- self.m22 as f32,- self.m41 as f32,- self.m42 as f32,- )+ /// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-tofloat64array+ pub(crate) fn to_float64_array(&self, cx: &mut CallContext) -> WebIdlResult<Gc<TypedArrayBase>> {+ // Returns the serialized 16 elements m11 to m44 of the current matrix in column-major order as Float64Array.+ let bytes: Vec<u8> = self+ .matrix+ .get()+ .to_column_major()+ .iter()+ .flat_map(|element| element.to_ne_bytes())+ .collect();+ create_typed_array(cx, TypedArrayKind::Float64Array, &bytes)+ }++ /// https://drafts.fxtf.org/geometry/#dommatrixreadonly-stringification-behavior+ pub(crate) fn to_string(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ self.stringify().ok_or_else(|| {+ Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"Cannot stringify non-finite matrix values"),+ )+ })+ }++ /// The stringification behavior, which has no string for a matrix with a non-finite element.+ pub(crate) fn stringify(&self) -> Option<Utf16String> {+ let matrix = self.matrix.get();++ // 1. If one or more of m11 element through m44 element are a non-finite value, then throw an+ // "InvalidStateError" DOMException.+ // NOTE: The CSS syntax cannot represent NaN or Infinity values.+ if !matrix.to_column_major().iter().all(|element| element.is_finite()) {+ return None;+ }++ // 2. Let string be the empty string.+ // 3. If is 2D is true, then:+ // 1. Append "matrix(" to string.+ // 2. Append ! ToString(m11 element) to string.+ // 3. Append ", " to string.+ // 4. Append ! ToString(m12 element) to string.+ // 5. Append ", " to string.+ // 6. Append ! ToString(m21 element) to string.+ // 7. Append ", " to string.+ // 8. Append ! ToString(m22 element) to string.+ // 9. Append ", " to string.+ // 10. Append ! ToString(m41 element) to string.+ // 11. Append ", " to string.+ // 12. Append ! ToString(m42 element) to string.+ // 13. Append ")" to string.+ // 4. Otherwise:+ // 1. Append "matrix3d(" to string.+ // 2. Append ! ToString(m11 element) to string.+ // 3. Append ", " to string.+ // 4. Append ! ToString(m12 element) to string.+ // 5. Append ", " to string.+ // 6. Append ! ToString(m13 element) to string.+ // 7. Append ", " to string.+ // 8. Append ! ToString(m14 element) to string.+ // 9. Append ", " to string.+ // 10. Append ! ToString(m21 element) to string.+ // 11. Append ", " to string.+ // 12. Append ! ToString(m22 element) to string.+ // 13. Append ", " to string.+ // 14. Append ! ToString(m23 element) to string.+ // 15. Append ", " to string.+ // 16. Append ! ToString(m24 element) to string.+ // 17. Append ", " to string.+ // 18. Append ! ToString(m41 element) to string.+ // 19. Append ", " to string.+ // 20. Append ! ToString(m42 element) to string.+ // 21. Append ", " to string.+ // 22. Append ! ToString(m43 element) to string.+ // 23. Append ", " to string.+ // 24. Append ! ToString(m44 element) to string.+ // 25. Append ")" to string.+ // NB: The steps leave out m31 to m34, which matrix3d() requires, so they are appended after m24.+ let (function, elements) = if self.is_2d.get() {+ let m = |row, column| matrix.element(row, column);+ ("matrix(", vec![m(1, 1), m(1, 2), m(2, 1), m(2, 2), m(4, 1), m(4, 2)])+ } else {+ ("matrix3d(", matrix.to_column_major().to_vec())+ };+ let numbers: Vec<String> = elements.into_iter().map(number_to_string).collect();+ let string = format!("{function}{})", numbers.join(", "));++ // 5. Return string.+ Some(Utf16String::from_ascii(string.as_bytes()))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-multiplyself, from step 2 on.+ pub(super) fn multiply_self_steps(&self, other_object: &DOMMatrixReadOnly) {+ // 2. The otherObject matrix gets post-multiplied to the current matrix.+ self.matrix.set(self.matrix.get().multiplied(other_object.matrix.get()));++ // 3. If is 2D of otherObject is false, set is 2D of the current matrix to false.+ if !other_object.is_2d.get() {+ self.is_2d.set(false);+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-premultiplyself, from step 2 on.+ pub(super) fn pre_multiply_self_steps(&self, other_object: &DOMMatrixReadOnly) {+ // 2. The otherObject matrix gets pre-multiplied to the current matrix.+ self.matrix.set(other_object.matrix.get().multiplied(self.matrix.get()));++ // 3. If is 2D of otherObject is false, set is 2D of the current matrix to false.+ if !other_object.is_2d.get() {+ self.is_2d.set(false);+ }}-}-/// The TypeError of validating a dictionary whose members disagree, with its message.-#[derive(Debug, PartialEq, Eq)]-pub(crate) struct InconsistentMembers(pub(crate) &'static str);+ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-translateself+ pub(crate) fn translate_self_steps(&self, tx: f64, ty: f64, tz: f64) {+ // 1. Post-multiply a translation transformation on the current matrix. The 3D translation matrix is described+ // in CSS Transforms. [CSS3-TRANSFORMS]+ self.matrix+ .set(self.matrix.get().multiplied(Matrix4::translation(tx, ty, tz)));-#[cfg(not(test))]-impl From<InconsistentMembers> for crate::bindings::Exception {- fn from(InconsistentMembers(message): InconsistentMembers) -> Self {- Self::TypeError(ak::Utf16String::from_ascii(message.as_bytes()))+ // 2. If tz is specified and not 0 or -0, set is 2D of the current matrix to false.+ if tz != 0.0 {+ self.is_2d.set(false);+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-scaleself+ pub(crate) fn scale_self_steps(+ &self,+ scale_x: f64,+ scale_y: Option<f64>,+ scale_z: f64,+ origin_x: f64,+ origin_y: f64,+ origin_z: f64,+ ) {+ // 1. Perform a translateSelf() transformation on the current matrix with the arguments originX, originY,+ // originZ.+ self.translate_self_steps(origin_x, origin_y, origin_z);++ // 2. If scaleY is missing, set scaleY to the value of scaleX.+ let scale_y = scale_y.unwrap_or(scale_x);++ // 3. Post-multiply a non-uniform scale transformation on the current matrix. The 3D scale matrix is described+ // in CSS Transforms with sx = scaleX, sy = scaleY and sz = scaleZ. [CSS3-TRANSFORMS]+ self.matrix+ .set(self.matrix.get().multiplied(Matrix4::scale(scale_x, scale_y, scale_z)));++ // 4. Negate originX, originY and originZ.+ // 5. Perform a translateSelf() transformation on the current matrix with the arguments originX, originY,+ // originZ.+ self.translate_self_steps(-origin_x, -origin_y, -origin_z);++ // 6. If scaleZ is not 1, set is 2D of the current matrix to false.+ if scale_z != 1.0 {+ self.is_2d.set(false);+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-scale3dself+ pub(super) fn scale3d_self_steps(&self, scale: f64, origin_x: f64, origin_y: f64, origin_z: f64) {+ // 1. Apply a translateSelf() transformation to the current matrix with the arguments originX, originY,+ // originZ.+ self.translate_self_steps(origin_x, origin_y, origin_z);++ // 2. Post-multiply a uniform 3D scale transformation (m11 = m22 = m33 = scale) on the current matrix. The 3D+ // scale matrix is described in CSS Transforms with sx = sy = sz = scale. [CSS3-TRANSFORMS]+ self.matrix+ .set(self.matrix.get().multiplied(Matrix4::scale(scale, scale, scale)));++ // 3. Apply a translateSelf() transformation to the current matrix with the arguments -originX, -originY,+ // -originZ.+ self.translate_self_steps(-origin_x, -origin_y, -origin_z);++ // 4. If scale is not 1, set is 2D of the current matrix to false.+ if scale != 1.0 {+ self.is_2d.set(false);+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-rotateself+ pub(super) fn rotate_self_steps(&self, rot_x: f64, rot_y: Option<f64>, rot_z: Option<f64>) {+ // 1. If rotY and rotZ are both missing, set rotZ to the value of rotX and set rotX and rotY to 0.+ let (rot_x, rot_y, rot_z) = match (rot_y, rot_z) {+ (None, None) => (0.0, Some(0.0), Some(rot_x)),+ _ => (rot_x, rot_y, rot_z),+ };++ // 2. If rotY is still missing, set rotY to 0.+ let rot_y = rot_y.unwrap_or(0.0);++ // 3. If rotZ is still missing, set rotZ to 0.+ let rot_z = rot_z.unwrap_or(0.0);++ // 4. If rotX or rotY are not 0 or -0, set is 2D of the current matrix to false.+ if rot_x != 0.0 || rot_y != 0.0 {+ self.is_2d.set(false);+ }++ let mut matrix = self.matrix.get();++ // 5. Post-multiply a rotation transformation on the current matrix around the vector 0, 0, 1 by the specified+ // rotation rotZ in degrees. The 3D rotation matrix is described in CSS Transforms with alpha = rotZ in+ // degrees. [CSS3-TRANSFORMS]+ matrix = matrix.multiplied(Matrix4::rotation([0.0, 0.0, 1.0], to_radians(rot_z)));++ // 6. Post-multiply a rotation transformation on the current matrix around the vector 0, 1, 0 by the specified+ // rotation rotY in degrees. The 3D rotation matrix is described in CSS Transforms with alpha = rotY in+ // degrees. [CSS3-TRANSFORMS]+ matrix = matrix.multiplied(Matrix4::rotation([0.0, 1.0, 0.0], to_radians(rot_y)));++ // 7. Post-multiply a rotation transformation on the current matrix around the vector 1, 0, 0 by the specified+ // rotation rotX in degrees. The 3D rotation matrix is described in CSS Transforms with alpha = rotX in+ // degrees. [CSS3-TRANSFORMS]+ matrix = matrix.multiplied(Matrix4::rotation([1.0, 0.0, 0.0], to_radians(rot_x)));++ self.matrix.set(matrix);+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-rotatefromvectorself+ pub(super) fn rotate_from_vector_self_steps(&self, x: f64, y: f64) {+ // 1. Post-multiply a rotation transformation on the current matrix. The rotation angle is determined by the+ // angle between the vector (1,0)T and (x,y)T in the clockwise direction. If x and y should both be 0 or -0,+ // the angle is specified as 0. The 2D rotation matrix is described in CSS Transforms where alpha is the+ // angle between the vector (1,0)T and (x,y)T in degrees. [CSS3-TRANSFORMS]+ let angle = if x == 0.0 && y == 0.0 { 0.0 } else { y.atan2(x) };+ self.matrix+ .set(self.matrix.get().multiplied(Matrix4::rotation([0.0, 0.0, 1.0], angle)));+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-rotateaxisangleself+ pub(crate) fn rotate_axis_angle_self_steps(&self, x: f64, y: f64, z: f64, angle: f64) {+ // 1. Post-multiply a rotation transformation on the current matrix around the specified vector x, y, z by the+ // specified rotation angle in degrees. The 3D rotation matrix is described in CSS Transforms with alpha =+ // angle in degrees. [CSS3-TRANSFORMS]+ // https://drafts.csswg.org/css-transforms-2/#funcdef-rotate3d+ // "A direction vector that cannot be normalized, such as [0,0,0], will cause the rotation to not be applied."+ let length = (x * x + y * y + z * z).sqrt();+ if length != 0.0 {+ let inverse_length = 1.0 / length;+ let axis = [x * inverse_length, y * inverse_length, z * inverse_length];+ self.matrix+ .set(self.matrix.get().multiplied(Matrix4::rotation(axis, to_radians(angle))));+ }++ // 2. If x or y are not 0 or -0, set is 2D of the current matrix to false.+ if x != 0.0 || y != 0.0 {+ self.is_2d.set(false);+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-skewxself+ pub(super) fn skew_x_self_steps(&self, sx: f64) {+ // 1. Post-multiply a skewX transformation on the current matrix by the specified angle sx in degrees. The 2D+ // skewX matrix is described in CSS Transforms with alpha = sx in degrees. [CSS3-TRANSFORMS]+ let mut skew = Matrix4::identity();+ skew.set_element(2, 1, to_radians(sx).tan());+ self.matrix.set(self.matrix.get().multiplied(skew));+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-skewyself+ pub(super) fn skew_y_self_steps(&self, sy: f64) {+ // 1. Post-multiply a skewX transformation on the current matrix by the specified angle sy in degrees. The 2D+ // skewY matrix is described in CSS Transforms with beta = sy in degrees. [CSS3-TRANSFORMS]+ let mut skew = Matrix4::identity();+ skew.set_element(1, 2, to_radians(sy).tan());+ self.matrix.set(self.matrix.get().multiplied(skew));+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-invertself+ pub(super) fn invert_self_steps(&self) {+ // 1. Invert the current matrix.+ match self.matrix.get().inverse() {+ Some(inverse) => self.matrix.set(inverse),+ // 2. If the current matrix is not invertible set all attributes to NaN and set is 2D to false.+ None => {+ self.matrix.set(Matrix4 {+ elements: [[f64::NAN; 4]; 4],+ });+ self.is_2d.set(false);+ }+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dommatrix-setmatrixvalue, from step 2 on.+ pub(super) fn set_matrix_value_steps(&self, matrix: Matrix4, is_2d_transform: bool) {+ // 2. Set is 2D to the value of 2dTransform.+ self.is_2d.set(is_2d_transform);++ // 3. Set m11 element through m44 element to the element values of matrix in column-major order.+ self.matrix.set(matrix);}}-/// SameValueZero() of two numbers, https://tc39.es/ecma262/#sec-samevaluezero-fn same_value_zero(x: f64, y: f64) -> bool {- (x.is_nan() && y.is_nan()) || x == y+/// The elements of a Float32Array or a Float64Array, none for one that is detached or out of bounds.+fn typed_array_elements(array: Gc<TypedArrayBase>) -> Vec<f64> {+ let record = make_typed_array_with_buffer_witness_record(&array, ArrayBufferOrder::SeqCst);+ // NB: The offset of a view of a detached buffer, or of one that a resize left out of bounds, can be past the end of+ // the buffer.+ if is_typed_array_out_of_bounds(&record) {+ return Vec::new();+ }+ let byte_length = typed_array_byte_length(&record) as usize;+ let mut bytes = vec![0; byte_length];+ let byte_offset = array.byte_offset() as usize;+ array+ .viewed_array_buffer()+ .with_data_block(|data_block| data_block.copy_to(byte_offset, &mut bytes));+ if array.kind() == TypedArrayKind::Float32Array {+ let (elements, _) = bytes.as_chunks::<4>();+ elements+ .iter()+ .map(|element| f64::from(f32::from_ne_bytes(*element)))+ .collect()+ } else {+ let (elements, _) = bytes.as_chunks::<8>();+ elements.iter().map(|element| f64::from_ne_bytes(*element)).collect()+ }}-/// https://drafts.fxtf.org/geometry/#matrix-validate-and-fixup-2d-pub(crate) fn validate_and_fixup_2d(init: &DOMMatrix2DInit) -> Result<Matrix2D, InconsistentMembers> {- // 1. If at least one of the following conditions are true for dict, then throw a TypeError exception and abort- // these steps.- let disagree = |member: Option<f64>, matrix_member: Option<f64>| matches!((member, matrix_member), (Some(member), Some(matrix_member)) if !same_value_zero(member, matrix_member));- // - a and m11 are both present and SameValueZero(a, m11) is false.- if disagree(init.a, init.m11) {- return Err(InconsistentMembers(- "DOMMatrix2DInit.a and DOMMatrix2DInit.m11 must have the same value if they are both present",- ));- }- // - b and m12 are both present and SameValueZero(b, m12) is false.- if disagree(init.b, init.m12) {- return Err(InconsistentMembers(- "DOMMatrix2DInit.b and DOMMatrix2DInit.m12 must have the same value if they are both present",- ));- }- // - c and m21 are both present and SameValueZero(c, m21) is false.- if disagree(init.c, init.m21) {- return Err(InconsistentMembers(- "DOMMatrix2DInit.c and DOMMatrix2DInit.m21 must have the same value if they are both present",- ));- }- // - d and m22 are both present and SameValueZero(d, m22) is false.- if disagree(init.d, init.m22) {- return Err(InconsistentMembers(- "DOMMatrix2DInit.d and DOMMatrix2DInit.m22 must have the same value if they are both present",- ));- }- // - e and m41 are both present and SameValueZero(e, m41) is false.- if disagree(init.e, init.m41) {- return Err(InconsistentMembers(- "DOMMatrix2DInit.e and DOMMatrix2DInit.m41 must have the same value if they are both present",- ));- }- // - f and m42 are both present and SameValueZero(f, m42) is false.- if disagree(init.f, init.m42) {- return Err(InconsistentMembers(- "DOMMatrix2DInit.f and DOMMatrix2DInit.m42 must have the same value if they are both present",- ));- }-- // 2. If m11 is not present then set it to the value of member a, or value 1 if a is also not present.- // 3. If m12 is not present then set it to the value of member b, or value 0 if b is also not present.- // 4. If m21 is not present then set it to the value of member c, or value 0 if c is also not present.- // 5. If m22 is not present then set it to the value of member d, or value 1 if d is also not present.- // 6. If m41 is not present then set it to the value of member e, or value 0 if e is also not present.- // 7. If m42 is not present then set it to the value of member f, or value 0 if f is also not present.- Ok(Matrix2D {- m11: init.m11.or(init.a).unwrap_or(1.0),- m12: init.m12.or(init.b).unwrap_or(0.0),- m21: init.m21.or(init.c).unwrap_or(0.0),- m22: init.m22.or(init.d).unwrap_or(1.0),- m41: init.m41.or(init.e).unwrap_or(0.0),- m42: init.m42.or(init.f).unwrap_or(0.0),- })+/// A new typed array of the kind in the realm of the call context, which holds the bytes.+fn create_typed_array(cx: &CallContext, kind: TypedArrayKind, bytes: &[u8]) -> WebIdlResult<Gc<TypedArrayBase>> {+ let buffer = ArrayBuffer::create(cx.vm(), cx.realm(), bytes.len(), ArrayBufferShared::No)?;+ buffer.with_data_block(|data_block| data_block.overwrite(0, bytes));+ let element_count = 16;+ Ok(create_typed_array_on_buffer(+ cx.vm(),+ cx.realm(),+ kind,+ element_count,+ buffer,+ ))}-#[cfg(test)]-mod tests {- use super::{DOMMatrix2DInit, InconsistentMembers, Matrix2D, validate_and_fixup_2d};-- #[test]- fn an_empty_dictionary_is_the_identity() {- assert_eq!(- validate_and_fixup_2d(&DOMMatrix2DInit::default()),- Ok(Matrix2D {- m11: 1.0,- m12: 0.0,- m21: 0.0,- m22: 1.0,- m41: 0.0,- m42: 0.0,- })- );- }-- #[test]- fn matrix_members_win_over_their_aliases() {- let init = DOMMatrix2DInit {- a: Some(2.0),- m22: Some(3.0),- e: Some(4.0),- m41: Some(4.0),- f: Some(5.0),- ..DOMMatrix2DInit::default()- };- let matrix = validate_and_fixup_2d(&init).expect("the members agree");- assert_eq!((matrix.m11, matrix.m22, matrix.m41, matrix.m42), (2.0, 3.0, 4.0, 5.0));+/// https://drafts.fxtf.org/geometry/#parse-a-string-into-an-abstract-matrix, which throws a "SyntaxError"+/// DOMException for failure.+pub(crate) fn parse_transform_list(transform_list: &Utf16String) -> WebIdlResult<(Matrix4, bool)> {+ let mut elements = [0.0; 16];+ let mut is_2d_transform = true;+ // SAFETY: The string is lent for the call.+ let parsed = unsafe {+ web_dom_matrix_parse_transform_list(transform_list.raw_identity(), &mut elements, &mut is_2d_transform)+ };+ if !parsed {+ return Err(Exception::syntax_error(Utf16String::from_ascii(+ b"Failed to parse CSS transform string.",+ )));}+ Ok((Matrix4::from_column_major(elements), is_2d_transform))+}- #[test]- fn members_that_disagree_are_a_type_error() {- let init = DOMMatrix2DInit {- b: Some(1.0),- m12: Some(2.0),- ..DOMMatrix2DInit::default()- };- assert_eq!(- validate_and_fixup_2d(&init),- Err(InconsistentMembers(- "DOMMatrix2DInit.b and DOMMatrix2DInit.m12 must have the same value if they are both present"- ))- );+impl Serializable for DOMMatrixReadOnly {+ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn serialization_steps(+ &self,+ _: &mut CallContext,+ serialized: &mut SerializationWriter,+ _for_storage: bool,+ ) -> WebIdlResult<()> {+ serialize_matrix(self, serialized);+ Ok(())}- #[test]- fn members_are_compared_with_same_value_zero() {- let init = DOMMatrix2DInit {- a: Some(f64::NAN),- m11: Some(f64::NAN),- c: Some(0.0),- m21: Some(-0.0),- ..DOMMatrix2DInit::default()- };- let matrix = validate_and_fixup_2d(&init).expect("the members agree");- assert!(matrix.m11.is_nan());- assert!(!matrix.is_finite());- assert!(matrix.m21.is_sign_negative());+ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {+ deserialize_matrix(serialized)+ }+}++/// The serialization steps for DOMMatrixReadOnly and DOMMatrix, https://drafts.fxtf.org/geometry/#structured-serialization+pub(crate) fn serialize_matrix(matrix: &DOMMatrixReadOnly, serialized: &mut SerializationWriter) {+ // NB: Is 2D is serialized first, so that the deserialization steps know how many elements follow.+ serialized.write_bool(matrix.is_2d.get());++ let elements = matrix.matrix.get();+ let m = |row, column| elements.element(row, column);++ // 1. If value’s is 2D is true:+ if matrix.is_2d.get() {+ // 1. Set serialized.[[M11]] to value’s m11 element.+ // 2. Set serialized.[[M12]] to value’s m12 element.+ // 3. Set serialized.[[M21]] to value’s m21 element.+ // 4. Set serialized.[[M22]] to value’s m22 element.+ // 5. Set serialized.[[M41]] to value’s m41 element.+ // 6. Set serialized.[[M42]] to value’s m42 element.+ // 7. Set serialized.[[Is2D]] to true.+ for element in [m(1, 1), m(1, 2), m(2, 1), m(2, 2), m(4, 1), m(4, 2)] {+ serialized.write_f64(element);+ }+ }+ // 2. Otherwise:+ else {+ // 1. Set serialized.[[M11]] to value’s m11 element.+ // 2. Set serialized.[[M12]] to value’s m12 element.+ // 3. Set serialized.[[M13]] to value’s m13 element.+ // 4. Set serialized.[[M14]] to value’s m14 element.+ // 5. Set serialized.[[M21]] to value’s m21 element.+ // 6. Set serialized.[[M22]] to value’s m22 element.+ // 7. Set serialized.[[M23]] to value’s m23 element.+ // 8. Set serialized.[[M24]] to value’s m24 element.+ // 9. Set serialized.[[M31]] to value’s m31 element.+ // 10. Set serialized.[[M32]] to value’s m32 element.+ // 11. Set serialized.[[M33]] to value’s m33 element.+ // 12. Set serialized.[[M34]] to value’s m34 element.+ // 13. Set serialized.[[M41]] to value’s m41 element.+ // 14. Set serialized.[[M42]] to value’s m42 element.+ // 15. Set serialized.[[M43]] to value’s m43 element.+ // 16. Set serialized.[[M44]] to value’s m44 element.+ // 17. Set serialized.[[Is2D]] to false.+ for element in elements.to_column_major() {+ serialized.write_f64(element);+ }+ }+}++/// The deserialization steps of DOMMatrixReadOnly and DOMMatrix, which give the matrix of the new object.+pub(crate) fn deserialize_matrix(serialized: &mut SerializationReader) -> WebIdlResult<DOMMatrixReadOnly> {+ let is_2d = serialized.read_bool()?;++ // 1. If serialized.[[Is2D]] is true:+ if is_2d {+ // 1. Set value’s m11 element to serialized.[[M11]].+ // 2. Set value’s m12 element to serialized.[[M12]].+ // 3. Set value’s m13 element to 0.+ // 4. Set value’s m14 element to 0.+ // 5. Set value’s m21 element to serialized.[[M21]].+ // 6. Set value’s m22 element to serialized.[[M22]].+ // 7. Set value’s m23 element to 0.+ // 8. Set value’s m24 element to 0.+ // 9. Set value’s m31 element to 0.+ // 10. Set value’s m32 element to 0.+ // 11. Set value’s m33 element to 1.+ // 12. Set value’s m34 element to 0.+ // 13. Set value’s m41 element to serialized.[[M41]].+ // 14. Set value’s m42 element to serialized.[[M42]].+ // 15. Set value’s m43 element to 0.+ // 16. Set value’s m44 element to 1.+ // 17. Set value’s is 2D to true.+ let mut elements = [0.0; 6];+ for element in &mut elements {+ *element = serialized.read_f64()?;+ }+ return Ok(DOMMatrixReadOnly::create_2d_matrix(elements));+ }++ // 2. Otherwise:+ // 1. Set value’s m11 element to serialized.[[M11]].+ // 2. Set value’s m12 element to serialized.[[M12]].+ // 3. Set value’s m13 element to serialized.[[M13]].+ // 4. Set value’s m14 element to serialized.[[M14]].+ // 5. Set value’s m21 element to serialized.[[M21]].+ // 6. Set value’s m22 element to serialized.[[M22]].+ // 7. Set value’s m23 element to serialized.[[M23]].+ // 8. Set value’s m24 element to serialized.[[M24]].+ // 9. Set value’s m31 element to serialized.[[M31]].+ // 10. Set value’s m32 element to serialized.[[M32]].+ // 11. Set value’s m33 element to serialized.[[M33]].+ // 12. Set value’s m34 element to serialized.[[M34]].+ // 13. Set value’s m41 element to serialized.[[M41]].+ // 14. Set value’s m42 element to serialized.[[M42]].+ // 15. Set value’s m43 element to serialized.[[M43]].+ // 16. Set value’s m44 element to serialized.[[M44]].+ // 17. Set value’s is 2D to false.+ let mut elements = [0.0; 16];+ for element in &mut elements {+ *element = serialized.read_f64()?;}+ Ok(DOMMatrixReadOnly::create_3d_matrix(elements))}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_point.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_point.rsnew file mode 100644index 00000000000..efc042e2d08--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_point.rs@@ -0,0 +1,104 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://drafts.fxtf.org/geometry/#dompoint++use libjs_rust::api::Trace;++use super::dom_point_read_only::{DOMPointInit, DOMPointReadOnly, deserialize_point, serialize_point};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};+use crate::bindings::{CallContext, WebIdlResult};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DOMPoint {+ point: DOMPointReadOnly,+}++impl Wrappable for DOMPoint {}++impl Inherits<DOMPointReadOnly> for DOMPoint {+ fn parent(&self) -> &DOMPointReadOnly {+ &self.point+ }+}++impl DOMPoint {+ pub(crate) fn new(x: f64, y: f64, z: f64, w: f64) -> Self {+ Self {+ point: DOMPointReadOnly::new(x, y, z, w),+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompoint-dompoint+ pub(crate) fn construct(cx: &mut CallContext, x: f64, y: f64, z: f64, w: f64) -> WebIdlResult<Self> {+ Ok(Self {+ point: DOMPointReadOnly::construct(cx, x, y, z, w)?,+ })+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompoint-frompoint+ pub(crate) fn from_point(cx: &mut CallContext, other: DOMPointInit) -> WebIdlResult<Ref<Self>> {+ // The fromPoint(other) static method on DOMPoint must create a DOMPoint from the dictionary other.+ Ok(allocate(cx.vm(), Self::from_dictionary(&other)))+ }++ /// https://drafts.fxtf.org/geometry/#create-a-dompoint-from-the-dictionary+ pub(crate) fn from_dictionary(other: &DOMPointInit) -> Self {+ Self {+ point: DOMPointReadOnly::from_dictionary(other),+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-x+ pub(crate) fn set_x(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMPoint interface, setting the x attribute must set the x coordinate to the new value.+ self.point.set_x_coordinate(value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-y+ pub(crate) fn set_y(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMPoint interface, setting the y attribute must set the y coordinate to the new value.+ self.point.set_y_coordinate(value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-z+ pub(crate) fn set_z(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMPoint interface, setting the z attribute must set the z coordinate to the new value.+ self.point.set_z_coordinate(value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-w+ pub(crate) fn set_w(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMPoint interface, setting the w attribute must set the w perspective to the new value.+ self.point.set_w_perspective(value);+ Ok(())+ }+}++impl Serializable for DOMPoint {+ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn serialization_steps(+ &self,+ _: &mut CallContext,+ serialized: &mut SerializationWriter,+ _for_storage: bool,+ ) -> WebIdlResult<()> {+ serialize_point(&self.point, serialized);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {+ Ok(Self {+ point: deserialize_point(serialized)?,+ })+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_point_read_only.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_point_read_only.rsindex ae0a4a81080..e5050a5aca2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_point_read_only.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_point_read_only.rs@@ -4,13 +4,167 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The point dictionary of Geometry/DOMPointReadOnly.idl, https://drafts.fxtf.org/geometry/#dictdef-dompointinit--/// The dictionary DOMPointInit of Geometry/DOMPointReadOnly.idl, whose members the bindings convert.-#[derive(Clone, Copy, Debug, PartialEq)]-pub(crate) struct DOMPointInit {- pub(crate) x: f64,- pub(crate) y: f64,- pub(crate) z: f64,- pub(crate) w: f64,+//! https://drafts.fxtf.org/geometry/#dompointreadonly++use core::cell::Cell;++use libjs_rust::api::Trace;++pub(crate) use super::dictionaries::DOMPointInit;+use super::dom_matrix::DOMMatrix;+use super::dom_matrix_read_only::DOMMatrixInit;+use super::dom_point::DOMPoint;+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};+use crate::bindings::{CallContext, WebIdlResult};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DOMPointReadOnly {+ #[gc(untraced)]+ x: Cell<f64>,+ #[gc(untraced)]+ y: Cell<f64>,+ #[gc(untraced)]+ z: Cell<f64>,+ #[gc(untraced)]+ w: Cell<f64>,+}++impl Wrappable for DOMPointReadOnly {}++impl DOMPointReadOnly {+ pub(crate) fn new(x: f64, y: f64, z: f64, w: f64) -> Self {+ Self {+ x: Cell::new(x),+ y: Cell::new(y),+ z: Cell::new(z),+ w: Cell::new(w),+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-dompointreadonly+ pub(crate) fn construct(_: &mut CallContext, x: f64, y: f64, z: f64, w: f64) -> WebIdlResult<Self> {+ // 1. Let point be a new DOMPointReadOnly or DOMPoint object as appropriate.+ // 2. Set point’s variables x coordinate to x, y coordinate to y, z coordinate to z and w perspective to w.+ // 3. Return point.+ Ok(Self::new(x, y, z, w))+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-frompoint+ pub(crate) fn from_point(cx: &mut CallContext, other: DOMPointInit) -> WebIdlResult<Ref<Self>> {+ // The fromPoint(other) static method on DOMPointReadOnly must create a DOMPointReadOnly from the dictionary+ // other.+ Ok(allocate(cx.vm(), Self::from_dictionary(&other)))+ }++ /// https://drafts.fxtf.org/geometry/#create-a-dompointreadonly-from-the-dictionary+ pub(crate) fn from_dictionary(other: &DOMPointInit) -> Self {+ // 1. Let point be a new DOMPointReadOnly or DOMPoint as appropriate.+ // 2. Set point’s variables x coordinate to other’s x dictionary member, y coordinate to other’s y dictionary+ // member, z coordinate to other’s z dictionary member and w perspective to other’s w dictionary member.+ // 3. Return point.+ Self::new(other.x, other.y, other.z, other.w)+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-x+ pub(crate) fn x(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.x.get())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-y+ pub(crate) fn y(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.y.get())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-z+ pub(crate) fn z(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.z.get())+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-w+ pub(crate) fn w(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.w.get())+ }++ /// The coordinates x, y, z and w, in that order.+ pub(crate) fn coordinates(&self) -> [f64; 4] {+ [self.x.get(), self.y.get(), self.z.get(), self.w.get()]+ }++ pub(super) fn set_x_coordinate(&self, value: f64) {+ self.x.set(value);+ }++ pub(super) fn set_y_coordinate(&self, value: f64) {+ self.y.set(value);+ }++ pub(super) fn set_z_coordinate(&self, value: f64) {+ self.z.set(value);+ }++ pub(super) fn set_w_perspective(&self, value: f64) {+ self.w.set(value);+ }++ /// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-matrixtransform+ pub(crate) fn matrix_transform(&self, cx: &mut CallContext, matrix: DOMMatrixInit) -> WebIdlResult<Ref<DOMPoint>> {+ // 1. Let matrixObject be the result of invoking create a DOMMatrix from the dictionary matrix.+ let matrix_object = DOMMatrix::from_dictionary(&matrix)?;++ // 2. Return the result of invoking transform a point with a matrix, given the current point and matrixObject.+ // The current point does not get modified.+ Ok(allocate(cx.vm(), matrix_object.parent().transform_point_steps(self)))+ }+}++impl Serializable for DOMPointReadOnly {+ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn serialization_steps(+ &self,+ _: &mut CallContext,+ serialized: &mut SerializationWriter,+ _for_storage: bool,+ ) -> WebIdlResult<()> {+ serialize_point(self, serialized);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {+ deserialize_point(serialized)+ }+}++/// The serialization steps for DOMPointReadOnly and DOMPoint, https://drafts.fxtf.org/geometry/#structured-serialization+pub(crate) fn serialize_point(point: &DOMPointReadOnly, serialized: &mut SerializationWriter) {+ // 1. Set serialized.[[X]] to value’s x coordinate.+ serialized.write_f64(point.x.get());++ // 2. Set serialized.[[Y]] to value’s y coordinate.+ serialized.write_f64(point.y.get());++ // 3. Set serialized.[[Z]] to value’s z coordinate.+ serialized.write_f64(point.z.get());++ // 4. Set serialized.[[W]] to value’s w perspective.+ serialized.write_f64(point.w.get());+}++/// The deserialization steps of DOMPointReadOnly and DOMPoint, which give the coordinates of the new point.+pub(crate) fn deserialize_point(serialized: &mut SerializationReader) -> WebIdlResult<DOMPointReadOnly> {+ // 1. Set value’s x coordinate to serialized.[[X]].+ let x = serialized.read_f64()?;++ // 2. Set value’s y coordinate to serialized.[[Y]].+ let y = serialized.read_f64()?;++ // 3. Set value’s z coordinate to serialized.[[Z]].+ let z = serialized.read_f64()?;++ // 4. Set value’s w perspective to serialized.[[W]].+ let w = serialized.read_f64()?;++ Ok(DOMPointReadOnly::new(x, y, z, w))}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_quad.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_quad.rsnew file mode 100644index 00000000000..f8d89914f8c--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_quad.rs@@ -0,0 +1,245 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://drafts.fxtf.org/geometry/#domquad++use libjs_rust::api::{Trace, Vm};++use super::dictionaries::DOMPointInit;+pub(crate) use super::dictionaries::DOMQuadInit;+use super::dictionaries::DOMRectInit;+use super::dom_point::DOMPoint;+use super::dom_rect::DOMRect;+use super::{nan_safe_maximum, nan_safe_minimum};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};+use crate::bindings::{CallContext, WebIdlResult};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DOMQuad {+ p1: Ref<DOMPoint>,+ p2: Ref<DOMPoint>,+ p3: Ref<DOMPoint>,+ p4: Ref<DOMPoint>,+}++impl Wrappable for DOMQuad {}++/// A new DOMPoint object with its attributes set to the values of the namesake dictionary members in the dictionary.+fn new_point(vm: &Vm, init: &DOMPointInit) -> Ref<DOMPoint> {+ allocate(vm, DOMPoint::from_dictionary(init))+}++impl DOMQuad {+ /// https://drafts.fxtf.org/geometry/#dom-domquad-domquad+ pub(crate) fn construct(+ cx: &mut CallContext,+ p1: DOMPointInit,+ p2: DOMPointInit,+ p3: DOMPointInit,+ p4: DOMPointInit,+ ) -> WebIdlResult<Self> {+ let vm = cx.vm();++ // 1. Let point1 be a new DOMPoint object with its attributes set to the values of the namesake dictionary+ // members in p1.+ let point1 = new_point(vm, &p1);++ // 2. Let point2 be a new DOMPoint object with its attributes set to the values of the namesake dictionary+ // members in p2.+ let point2 = new_point(vm, &p2);++ // 3. Let point3 be a new DOMPoint object with its attributes set to the values of the namesake dictionary+ // members in p3.+ let point3 = new_point(vm, &p3);++ // 4. Let point4 be a new DOMPoint object with its attributes set to the values of the namesake dictionary+ // members in p4.+ let point4 = new_point(vm, &p4);++ // 5. Return a new DOMQuad with point 1 set to point1, point 2 set to point2, point 3 set to point3 and point 4+ // set to point4.+ Ok(Self {+ p1: point1,+ p2: point2,+ p3: point3,+ p4: point4,+ })+ }++ /// https://drafts.fxtf.org/geometry/#dom-domquad-fromrect+ pub(crate) fn from_rect(cx: &mut CallContext, other: DOMRectInit) -> WebIdlResult<Ref<Self>> {+ // The fromRect(other) static method on DOMQuad must create a DOMQuad from the DOMRectInit dictionary other.+ let quad = Self::from_rect_dictionary(cx.vm(), &other);+ Ok(allocate(cx.vm(), quad))+ }++ /// https://drafts.fxtf.org/geometry/#create-a-domquad-from-the-domrectinit-dictionary+ fn from_rect_dictionary(vm: &Vm, other: &DOMRectInit) -> Self {+ // 1. Let x, y, width and height be the value of other’s x, y, width and height dictionary members,+ // respectively.+ let DOMRectInit { x, y, width, height } = *other;++ // 2. Let point1 be a new DOMPoint object with x coordinate set to x, y coordinate set to y, z coordinate set+ // to 0 and w perspective set to 1.+ let point1 = allocate(vm, DOMPoint::new(x, y, 0.0, 1.0));++ // 3. Let point2 be a new DOMPoint object with x coordinate set to x + width, y coordinate set to y, z+ // coordinate set to 0 and w perspective set to 1.+ let point2 = allocate(vm, DOMPoint::new(x + width, y, 0.0, 1.0));++ // 4. Let point3 be a new DOMPoint object with x coordinate set to x + width, y coordinate set to y + height, z+ // coordinate set to 0 and w perspective set to 1.+ let point3 = allocate(vm, DOMPoint::new(x + width, y + height, 0.0, 1.0));++ // 5. Let point4 be a new DOMPoint object with x coordinate set to x, y coordinate set to y + height, z+ // coordinate set to 0 and w perspective set to 1.+ let point4 = allocate(vm, DOMPoint::new(x, y + height, 0.0, 1.0));++ // 6. Return a new DOMQuad with point 1 set to point1, point 2 set to point2, point 3 set to point3 and point 4+ // set to point4.+ Self {+ p1: point1,+ p2: point2,+ p3: point3,+ p4: point4,+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-domquad-fromquad+ pub(crate) fn from_quad(cx: &mut CallContext, other: DOMQuadInit) -> WebIdlResult<Ref<Self>> {+ // The fromQuad(other) static method on DOMQuad must create a DOMQuad from the DOMQuadInit dictionary other.+ let vm = cx.vm();++ // https://drafts.fxtf.org/geometry/#create-a-domquad-from-the-domquadinit-dictionary+ // 1. Let point1 be the result of invoking create a DOMPoint from the dictionary p1 dictionary member of other,+ // if it exists.+ let point1 = new_point(vm, &other.p1.unwrap_or_default());++ // 2. Let point2 be the result of invoking create a DOMPoint from the dictionary p2 dictionary member of other,+ // if it exists.+ let point2 = new_point(vm, &other.p2.unwrap_or_default());++ // 3. Let point3 be the result of invoking create a DOMPoint from the dictionary p3 dictionary member of other,+ // if it exists.+ let point3 = new_point(vm, &other.p3.unwrap_or_default());++ // 4. Let point4 be the result of invoking create a DOMPoint from the dictionary p4 dictionary member of other,+ // if it exists.+ let point4 = new_point(vm, &other.p4.unwrap_or_default());++ // 5. Return a new DOMQuad with point 1 set to point1, point 2 set to point2, point 3 set to point3 and point 4+ // set to point4.+ Ok(allocate(+ vm,+ Self {+ p1: point1,+ p2: point2,+ p3: point3,+ p4: point4,+ },+ ))+ }++ /// https://drafts.fxtf.org/geometry/#dom-domquad-p1+ pub(crate) fn p1(&self, _: &mut CallContext) -> WebIdlResult<Ref<DOMPoint>> {+ // The p1 attribute must return point 1.+ Ok(self.p1)+ }++ /// https://drafts.fxtf.org/geometry/#dom-domquad-p2+ pub(crate) fn p2(&self, _: &mut CallContext) -> WebIdlResult<Ref<DOMPoint>> {+ // The p2 attribute must return point 2.+ Ok(self.p2)+ }++ /// https://drafts.fxtf.org/geometry/#dom-domquad-p3+ pub(crate) fn p3(&self, _: &mut CallContext) -> WebIdlResult<Ref<DOMPoint>> {+ // The p3 attribute must return point 3.+ Ok(self.p3)+ }++ /// https://drafts.fxtf.org/geometry/#dom-domquad-p4+ pub(crate) fn p4(&self, _: &mut CallContext) -> WebIdlResult<Ref<DOMPoint>> {+ // The p4 attribute must return point 4.+ Ok(self.p4)+ }++ /// https://drafts.fxtf.org/geometry/#dom-domquad-getbounds+ pub(crate) fn get_bounds(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMRect>> {+ let [x1, y1, ..] = self.p1.parent().coordinates();+ let [x2, y2, ..] = self.p2.parent().coordinates();+ let [x3, y3, ..] = self.p3.parent().coordinates();+ let [x4, y4, ..] = self.p4.parent().coordinates();++ // 1. Let bounds be a DOMRect object.+ // 2. Let left be the NaN-safe minimum of point 1’s x coordinate, point 2’s x coordinate, point 3’s x+ // coordinate and point 4’s x coordinate.+ let left = nan_safe_minimum(&[x1, x2, x3, x4]);++ // 3. Let top be the NaN-safe minimum of point 1’s y coordinate, point 2’s y coordinate, point 3’s y coordinate+ // and point 4’s y coordinate.+ let top = nan_safe_minimum(&[y1, y2, y3, y4]);++ // 4. Let right be the NaN-safe maximum of point 1’s x coordinate, point 2’s x coordinate, point 3’s x+ // coordinate and point 4’s x coordinate.+ let right = nan_safe_maximum(&[x1, x2, x3, x4]);++ // 5. Let bottom be the NaN-safe maximum of point 1’s y coordinate, point 2’s y coordinate, point 3’s y+ // coordinate and point 4’s y coordinate.+ let bottom = nan_safe_maximum(&[y1, y2, y3, y4]);++ // 6. Set x coordinate of bounds to left, y coordinate of bounds to top, width dimension of bounds to right -+ // left and height dimension of bounds to bottom - top.+ // 7. Return bounds.+ Ok(allocate(cx.vm(), DOMRect::new(left, top, right - left, bottom - top)))+ }+}++impl Serializable for DOMQuad {+ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn serialization_steps(+ &self,+ cx: &mut CallContext,+ serialized: &mut SerializationWriter,+ for_storage: bool,+ ) -> WebIdlResult<()> {+ // NB: The points are serialized in place, as they were before DOMQuad was implemented in Rust, so that stored+ // values keep the positions that their objects have in the memory of the serialization.++ // 1. Set serialized.[[P1]] to the sub-serialization of value’s point 1.+ serialized.write_object_in_place::<DOMPoint>(cx, &self.p1, for_storage)?;++ // 2. Set serialized.[[P2]] to the sub-serialization of value’s point 2.+ serialized.write_object_in_place::<DOMPoint>(cx, &self.p2, for_storage)?;++ // 3. Set serialized.[[P3]] to the sub-serialization of value’s point 3.+ serialized.write_object_in_place::<DOMPoint>(cx, &self.p3, for_storage)?;++ // 4. Set serialized.[[P4]] to the sub-serialization of value’s point 4.+ serialized.write_object_in_place::<DOMPoint>(cx, &self.p4, for_storage)?;++ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn deserialization_steps(cx: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {+ // 1. Set value’s point 1 to the sub-deserialization of serialized.[[P1]].+ let p1 = allocate(cx.vm(), serialized.read_object_in_place::<DOMPoint>(cx)?);++ // 2. Set value’s point 2 to the sub-deserialization of serialized.[[P2]].+ let p2 = allocate(cx.vm(), serialized.read_object_in_place::<DOMPoint>(cx)?);++ // 3. Set value’s point 3 to the sub-deserialization of serialized.[[P3]].+ let p3 = allocate(cx.vm(), serialized.read_object_in_place::<DOMPoint>(cx)?);++ // 4. Set value’s point 4 to the sub-deserialization of serialized.[[P4]].+ let p4 = allocate(cx.vm(), serialized.read_object_in_place::<DOMPoint>(cx)?);++ Ok(Self { p1, p2, p3, p4 })+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_rect.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_rect.rsnew file mode 100644index 00000000000..92326235cd4--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_rect.rs@@ -0,0 +1,103 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://drafts.fxtf.org/geometry/#domrect++use libjs_rust::api::Trace;++use super::dom_rect_read_only::{DOMRectInit, DOMRectReadOnly, deserialize_rect, serialize_rect};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};+use crate::bindings::{CallContext, WebIdlResult};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DOMRect {+ rect: DOMRectReadOnly,+}++impl Wrappable for DOMRect {}++impl Inherits<DOMRectReadOnly> for DOMRect {+ fn parent(&self) -> &DOMRectReadOnly {+ &self.rect+ }+}++impl DOMRect {+ pub(crate) fn new(x: f64, y: f64, width: f64, height: f64) -> Self {+ Self {+ rect: DOMRectReadOnly::new(x, y, width, height),+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrect-domrect+ pub(crate) fn construct(cx: &mut CallContext, x: f64, y: f64, width: f64, height: f64) -> WebIdlResult<Self> {+ Ok(Self {+ rect: DOMRectReadOnly::construct(cx, x, y, width, height)?,+ })+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrect-fromrect+ pub(crate) fn from_rect(cx: &mut CallContext, other: DOMRectInit) -> WebIdlResult<Ref<Self>> {+ // The fromRect(other) static method on DOMRect must create a DOMRect from the dictionary other.+ Ok(allocate(+ cx.vm(),+ Self {+ rect: DOMRectReadOnly::from_dictionary(&other),+ },+ ))+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrect-x+ pub(crate) fn set_x(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMRect interface, setting the x attribute must set the x coordinate to the new value.+ self.rect.set_x_coordinate(value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrect-y+ pub(crate) fn set_y(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMRect interface, setting the y attribute must set the y coordinate to the new value.+ self.rect.set_y_coordinate(value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrect-width+ pub(crate) fn set_width(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMRect interface, setting the width attribute must set the width dimension to the new value.+ self.rect.set_width_dimension(value);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrect-height+ pub(crate) fn set_height(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {+ // For the DOMRect interface, setting the height attribute must set the height dimension value to the new+ // value.+ self.rect.set_height_dimension(value);+ Ok(())+ }+}++impl Serializable for DOMRect {+ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn serialization_steps(+ &self,+ _: &mut CallContext,+ serialized: &mut SerializationWriter,+ _for_storage: bool,+ ) -> WebIdlResult<()> {+ serialize_rect(&self.rect, serialized);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {+ Ok(Self {+ rect: deserialize_rect(serialized)?,+ })+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_rect_list.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_rect_list.rsnew file mode 100644index 00000000000..de3f9d76396--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_rect_list.rs@@ -0,0 +1,41 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://drafts.fxtf.org/geometry/#domrectlist++use libjs_rust::api::Trace;++use super::dom_rect::DOMRect;+use crate::bindings::interface::{Ref, Wrappable};+use crate::bindings::{CallContext, WebIdlResult};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DOMRectList {+ rects: Vec<Ref<DOMRect>>,+}++impl Wrappable for DOMRectList {}++impl DOMRectList {+ pub(crate) fn new(rects: Vec<Ref<DOMRect>>) -> Self {+ Self { rects }+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectlist-length+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {+ // The length attribute must return the total number of DOMRect objects associated with the object.+ Ok(u32::try_from(self.rects.len()).expect("a list has fewer than 2^32 rectangles"))+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectlist-item+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Option<Ref<DOMRect>>> {+ // The item(index) method, when invoked, must return null when index is greater than or equal to the number of+ // DOMRect objects associated with the DOMRectList. Otherwise, the DOMRect object at index must be returned.+ // Indices are zero-based.+ Ok(self.rects.get(index as usize).copied())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_rect_read_only.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_rect_read_only.rsnew file mode 100644index 00000000000..f6e167d3831--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_rect_read_only.rs@@ -0,0 +1,182 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://drafts.fxtf.org/geometry/#domrectreadonly++use core::cell::Cell;++use libjs_rust::api::Trace;++pub(crate) use super::dictionaries::DOMRectInit;+use super::{nan_safe_maximum, nan_safe_minimum};+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};+use crate::bindings::{CallContext, WebIdlResult};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct DOMRectReadOnly {+ #[gc(untraced)]+ x: Cell<f64>,+ #[gc(untraced)]+ y: Cell<f64>,+ #[gc(untraced)]+ width: Cell<f64>,+ #[gc(untraced)]+ height: Cell<f64>,+}++impl Wrappable for DOMRectReadOnly {}++impl DOMRectReadOnly {+ pub(crate) fn new(x: f64, y: f64, width: f64, height: f64) -> Self {+ Self {+ x: Cell::new(x),+ y: Cell::new(y),+ width: Cell::new(width),+ height: Cell::new(height),+ }+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-domrectreadonly+ pub(crate) fn construct(_: &mut CallContext, x: f64, y: f64, width: f64, height: f64) -> WebIdlResult<Self> {+ // 1. Let rect be a new DOMRectReadOnly or DOMRect object as appropriate.+ // 2. Set rect’s variables x coordinate to x, y coordinate to y, width dimension to width and height dimension+ // to height.+ // 3. Return rect.+ Ok(Self::new(x, y, width, height))+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-fromrect+ pub(crate) fn from_rect(cx: &mut CallContext, other: DOMRectInit) -> WebIdlResult<Ref<Self>> {+ // The fromRect(other) static method on DOMRectReadOnly must create a DOMRectReadOnly from the dictionary other.+ Ok(allocate(cx.vm(), Self::from_dictionary(&other)))+ }++ /// https://drafts.fxtf.org/geometry/#create-a-domrectreadonly-from-the-dictionary+ pub(crate) fn from_dictionary(other: &DOMRectInit) -> Self {+ // 1. Let rect be a new DOMRectReadOnly or DOMRect as appropriate.+ // 2. Set rect’s variables x coordinate to other’s x dictionary member, y coordinate to other’s y dictionary+ // member, width dimension to other’s width dictionary member and height dimension to other’s height+ // dictionary member.+ // 3. Return rect.+ Self::new(other.x, other.y, other.width, other.height)+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-x+ pub(crate) fn x(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.x.get())+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-y+ pub(crate) fn y(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.y.get())+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-width+ pub(crate) fn width(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.width.get())+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-height+ pub(crate) fn height(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.height.get())+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-top+ pub(crate) fn top(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The top attribute, on getting, must return the NaN-safe minimum of the y coordinate and the sum of the y+ // coordinate and the height dimension.+ Ok(nan_safe_minimum(&[self.y.get(), self.y.get() + self.height.get()]))+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-right+ pub(crate) fn right(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The right attribute, on getting, must return the NaN-safe maximum of the x coordinate and the sum of the x+ // coordinate and the width dimension.+ Ok(nan_safe_maximum(&[self.x.get(), self.x.get() + self.width.get()]))+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-bottom+ pub(crate) fn bottom(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The bottom attribute, on getting, must return the NaN-safe maximum of the y coordinate and the sum of the y+ // coordinate and the height dimension.+ Ok(nan_safe_maximum(&[self.y.get(), self.y.get() + self.height.get()]))+ }++ /// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-left+ pub(crate) fn left(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // The left attribute, on getting, must return the NaN-safe minimum of the x coordinate and the sum of the x+ // coordinate and the width dimension.+ Ok(nan_safe_minimum(&[self.x.get(), self.x.get() + self.width.get()]))+ }++ pub(super) fn set_x_coordinate(&self, value: f64) {+ self.x.set(value);+ }++ pub(super) fn set_y_coordinate(&self, value: f64) {+ self.y.set(value);+ }++ pub(super) fn set_width_dimension(&self, value: f64) {+ self.width.set(value);+ }++ pub(super) fn set_height_dimension(&self, value: f64) {+ self.height.set(value);+ }+}++impl Serializable for DOMRectReadOnly {+ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn serialization_steps(+ &self,+ _: &mut CallContext,+ serialized: &mut SerializationWriter,+ _for_storage: bool,+ ) -> WebIdlResult<()> {+ serialize_rect(self, serialized);+ Ok(())+ }++ /// https://drafts.fxtf.org/geometry/#structured-serialization+ fn deserialization_steps(_: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {+ deserialize_rect(serialized)+ }+}++/// The serialization steps for DOMRectReadOnly and DOMRect, https://drafts.fxtf.org/geometry/#structured-serialization+pub(crate) fn serialize_rect(rect: &DOMRectReadOnly, serialized: &mut SerializationWriter) {+ // 1. Set serialized.[[X]] to value’s x coordinate.+ serialized.write_f64(rect.x.get());++ // 2. Set serialized.[[Y]] to value’s y coordinate.+ serialized.write_f64(rect.y.get());++ // 3. Set serialized.[[Width]] to value’s width dimension.+ serialized.write_f64(rect.width.get());++ // 4. Set serialized.[[Height]] to value’s height dimension.+ serialized.write_f64(rect.height.get());+}++/// The deserialization steps of DOMRectReadOnly and DOMRect, which give the dimensions of the new rectangle.+pub(crate) fn deserialize_rect(serialized: &mut SerializationReader) -> WebIdlResult<DOMRectReadOnly> {+ // 1. Set value’s x coordinate to serialized.[[X]].+ let x = serialized.read_f64()?;++ // 2. Set value’s y coordinate to serialized.[[Y]].+ let y = serialized.read_f64()?;++ // 3. Set value’s width dimension to serialized.[[Width]].+ let width = serialized.read_f64()?;++ // 4. Set value’s height dimension to serialized.[[Height]].+ let height = serialized.read_f64()?;++ Ok(DOMRectReadOnly::new(x, y, width, height))+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/exports.rsnew file mode 100644index 00000000000..d5135079094--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/exports.rs@@ -0,0 +1,238 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The C ABI through which LibWeb's C++ creates the geometry objects that it returns to script, and reads and changes+//! the matrices of CSS Typed OM, which the headers in Libraries/LibWeb/Geometry declare. A cell is the cell of an+//! object of the interface that the name of the function says; a DOMMatrixReadOnly cell can be that of a DOMMatrix.++use core::ffi::c_void;++use libjs_rust::api::{MarkedVec, Vm};++use super::dom_matrix::DOMMatrix;+use super::dom_matrix_read_only::DOMMatrixReadOnly;+use super::dom_point::DOMPoint;+use super::dom_point_read_only::DOMPointReadOnly;+use super::dom_rect::DOMRect;+use super::dom_rect_list::DOMRectList;+use super::dom_rect_read_only::DOMRectReadOnly;+use super::matrix::{ColumnMajor, Matrix4};+use crate::bindings::interface::{Inherits, Interface, Ref, allocate, cell_from_abi, cell_if_abi, cell_into_abi};++/// # Safety+///+/// `vm` must be the live VM.+unsafe fn vm_from_abi<'vm>(vm: *mut c_void) -> &'vm Vm {+ assert!(!vm.is_null(), "C++ passes the VM");+ // SAFETY: The caller passes the live VM.+ unsafe { &*vm.cast::<Vm>() }+}++/// The implementation of the object whose cell C++ lends, for as long as C++ keeps the cell alive.+///+/// # Safety+///+/// `cell` must be the live cell of an object of the interface, and it must outlive `'a`.+unsafe fn object_from_abi<'a, T: Interface>(cell: *mut c_void) -> &'a T {+ // SAFETY: The caller passes a live cell of the interface.+ let object: Ref<T> = unsafe { cell_from_abi(cell) };+ // SAFETY: The caller keeps the cell alive for 'a.+ unsafe { &*object.as_ptr() }+}++/// The matrix of a DOMMatrixReadOnly or a DOMMatrix whose cell C++ lends.+///+/// # Safety+///+/// `cell` must be the live cell of a DOMMatrixReadOnly or a DOMMatrix, and it must outlive `'a`.+unsafe fn matrix_from_abi<'a>(cell: *mut c_void) -> &'a DOMMatrixReadOnly {+ // SAFETY: The caller passes a live cell.+ if let Some(matrix) = unsafe { cell_if_abi::<DOMMatrixReadOnly>(cell) } {+ // SAFETY: The caller keeps the cell alive for 'a.+ return unsafe { &*matrix.as_ptr() };+ }+ // SAFETY: The caller passes the cell of a DOMMatrix, which it keeps alive for 'a.+ unsafe { object_from_abi::<DOMMatrix>(cell) }.parent()+}++/// # Safety+///+/// `vm` must be the live VM.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_point_read_only_create(+ vm: *mut c_void,+ x: f64,+ y: f64,+ z: f64,+ w: f64,+) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ cell_into_abi(allocate(vm, DOMPointReadOnly::new(x, y, z, w)))+}++/// # Safety+///+/// `vm` must be the live VM.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_point_create(vm: *mut c_void, x: f64, y: f64, z: f64, w: f64) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ cell_into_abi(allocate(vm, DOMPoint::new(x, y, z, w)))+}++/// # Safety+///+/// `vm` must be the live VM.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_rect_read_only_create(+ vm: *mut c_void,+ x: f64,+ y: f64,+ width: f64,+ height: f64,+) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ cell_into_abi(allocate(vm, DOMRectReadOnly::new(x, y, width, height)))+}++/// # Safety+///+/// `vm` must be the live VM.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_rect_create(vm: *mut c_void, x: f64, y: f64, width: f64, height: f64) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ cell_into_abi(allocate(vm, DOMRect::new(x, y, width, height)))+}++/// Sets the x coordinate, y coordinate, width dimension and height dimension of the rectangle.+///+/// # Safety+///+/// `rect` must be the live cell of a DOMRect.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_rect_set(rect: *mut c_void, x: f64, y: f64, width: f64, height: f64) {+ // SAFETY: The caller passes a live cell.+ let rect = unsafe { object_from_abi::<DOMRect>(rect) }.parent();+ rect.set_x_coordinate(x);+ rect.set_y_coordinate(y);+ rect.set_width_dimension(width);+ rect.set_height_dimension(height);+}++/// A new DOMRectList of new DOMRects, whose x, y, width and height are the groups of four values of `rects`.+///+/// # Safety+///+/// `vm` must be the live VM.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_rect_list_create(vm: *mut c_void, rects: ak::Span<'_, [f64; 4]>) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ // NB: Creating a rectangle can collect, so the rectangles created before it are kept in a MarkedVec until the+ // list holds them.+ let created = MarkedVec::with_capacity(vm, rects.as_slice().len());+ for &[x, y, width, height] in rects.as_slice() {+ created.push(allocate(vm, DOMRect::new(x, y, width, height)));+ }+ let list = DOMRectList::new(created.to_vec());+ cell_into_abi(allocate(vm, list))+}++/// A new DOMMatrix whose elements m11, m12, m13, m14, m21, ..., m44 are the values, in that order.+///+/// # Safety+///+/// `vm` must be the live VM.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_matrix_create(vm: *mut c_void, elements: &[f64; 16], is_2d: bool) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ let matrix = DOMMatrixReadOnly::new(Matrix4::from_column_major(*elements), is_2d);+ cell_into_abi(allocate(vm, DOMMatrix::from_read_only(matrix)))+}++/// A new DOMMatrix initialized to the values of the matrix.+///+/// # Safety+///+/// `vm` must be the live VM, and `matrix` the live cell of a DOMMatrixReadOnly or a DOMMatrix.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_matrix_create_from_read_only(vm: *mut c_void, matrix: *mut 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 cell.+ let matrix = unsafe { matrix_from_abi(matrix) };+ let copy = DOMMatrixReadOnly::new(matrix.matrix(), matrix.is_2d());+ cell_into_abi(allocate(vm, DOMMatrix::from_read_only(copy)))+}++/// Stores the elements m11, m12, m13, m14, m21, ..., m44 of the matrix, in that order.+///+/// # Safety+///+/// `matrix` must be the live cell of a DOMMatrixReadOnly or a DOMMatrix.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_matrix_read_only_elements(matrix: *mut c_void, out_elements: &mut [f64; 16]) {+ // SAFETY: The caller passes a live cell.+ *out_elements = unsafe { matrix_from_abi(matrix) }.matrix().to_column_major();+}++/// # Safety+///+/// `matrix` must be the live cell of a DOMMatrixReadOnly or a DOMMatrix.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_matrix_read_only_is_2d(matrix: *mut c_void) -> bool {+ // SAFETY: The caller passes a live cell.+ unsafe { matrix_from_abi(matrix) }.is_2d()+}++/// Stores the stringification of the matrix, an AK::Utf16String that the caller adopts, unless an element of the+/// matrix is not finite, which has none.+///+/// # Safety+///+/// `matrix` must be the live cell of a DOMMatrixReadOnly or a DOMMatrix.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_matrix_read_only_to_string(matrix: *mut c_void, out_string: &mut usize) -> bool {+ // SAFETY: The caller passes a live cell.+ let Some(string) = unsafe { matrix_from_abi(matrix) }.stringify() else {+ return false;+ };+ *out_string = string.into_raw();+ true+}++/// Post-multiplies the other matrix to the matrix, as multiplySelf() does with the DOMMatrix of a dictionary.+///+/// # Safety+///+/// `matrix` must be the live cell of a DOMMatrix, and `other` that of a DOMMatrixReadOnly or a DOMMatrix.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_matrix_multiply_self(matrix: *mut c_void, other: *mut c_void) {+ // SAFETY: The caller passes live cells.+ let (matrix, other) = unsafe { (object_from_abi::<DOMMatrix>(matrix), matrix_from_abi(other)) };+ matrix.parent().multiply_self_steps(other);+}++/// # Safety+///+/// `matrix` must be the live cell of a DOMMatrix.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_dom_matrix_rotate_axis_angle_self(+ matrix: *mut c_void,+ x: f64,+ y: f64,+ z: f64,+ angle: f64,+) {+ // SAFETY: The caller passes a live cell.+ unsafe { object_from_abi::<DOMMatrix>(matrix) }+ .parent()+ .rotate_axis_angle_self_steps(x, y, z, angle);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/matrix.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/matrix.rsnew file mode 100644index 00000000000..f4260d19d9b--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/matrix.rs@@ -0,0 +1,81 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The 4x4 matrices of the geometry interfaces, https://drafts.fxtf.org/geometry/#4x4-abstract-matrix, whose+//! arithmetic is that of LibGfx, in doubles.++pub(crate) use libgfx_rust::DoubleMatrix4x4 as Matrix4;++/// The elements of a matrix as the specification names them. A Matrix4 stores its elements row by row, and the matrix+/// of the specification is column-major, so its element mRC is in row C and column R: m12 is in the first column of+/// the second row.+pub(crate) trait ColumnMajor {+ /// The matrix whose elements m11, m12, m13, m14, m21, ..., m44 are the values, in that order.+ fn from_column_major(elements: [f64; 16]) -> Self;++ /// The elements m11, m12, m13, m14, m21, ..., m44, in that order.+ fn to_column_major(&self) -> [f64; 16];++ /// The element mRC, for a row R and a column C from 1 to 4.+ fn element(&self, row: usize, column: usize) -> f64;++ fn set_element(&mut self, row: usize, column: usize, value: f64);+}++impl ColumnMajor for Matrix4 {+ fn from_column_major(elements: [f64; 16]) -> Self {+ let mut matrix = Self::identity();+ for (index, element) in elements.into_iter().enumerate() {+ matrix.elements[index % 4][index / 4] = element;+ }+ matrix+ }++ fn to_column_major(&self) -> [f64; 16] {+ core::array::from_fn(|index| self.elements[index % 4][index / 4])+ }++ fn element(&self, row: usize, column: usize) -> f64 {+ self.elements[column - 1][row - 1]+ }++ fn set_element(&mut self, row: usize, column: usize, value: f64) {+ self.elements[column - 1][row - 1] = value;+ }+}++/// Degrees in radians, as AK::to_radians() converts them.+pub(crate) fn to_radians(degrees: f64) -> f64 {+ degrees * core::f64::consts::PI / 180.0+}++#[cfg(test)]+mod tests {+ use super::{ColumnMajor, Matrix4};++ #[test]+ fn column_major_elements_round_trip() {+ let elements: [f64; 16] = core::array::from_fn(|index| index as f64);+ let matrix = Matrix4::from_column_major(elements);+ // NB: The elements are numbered from 0 in column-major order, so m12, the second, is 1, and m21, the fifth, is+ // 4.+ assert_eq!(matrix.element(1, 2), 1.0);+ assert_eq!(matrix.element(2, 1), 4.0);+ assert_eq!(matrix.to_column_major(), elements);+ }++ #[test]+ fn the_inverse_undoes_the_matrix() {+ let matrix = Matrix4::translation(10.0, 20.0, 30.0).multiplied(Matrix4::scale(2.0, 4.0, 8.0));+ let inverse = matrix.inverse().expect("the matrix is invertible");+ assert_eq!(matrix.multiplied(inverse), Matrix4::identity());+ }++ #[test]+ fn a_singular_matrix_has_no_inverse() {+ assert_eq!(Matrix4::scale(0.0, 1.0, 1.0).inverse(), None);+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rsindex ecce97b0194..fa36a2925a2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rs@@ -4,8 +4,53 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The dictionaries of the geometry interfaces that interfaces implemented in Rust take. The interfaces themselves-//! are LibWeb's C++.+//! The geometry interfaces, https://drafts.fxtf.org/geometry/+pub(crate) mod dictionaries;+#[cfg(not(test))]+pub(crate) mod dom_matrix;+#[cfg(not(test))]pub(crate) mod dom_matrix_read_only;+#[cfg(not(test))]+pub(crate) mod dom_point;+#[cfg(not(test))]pub(crate) mod dom_point_read_only;+#[cfg(not(test))]+pub(crate) mod dom_quad;+#[cfg(not(test))]+pub(crate) mod dom_rect;+#[cfg(not(test))]+pub(crate) mod dom_rect_list;+#[cfg(not(test))]+pub(crate) mod dom_rect_read_only;+#[cfg(not(test))]+mod exports;+pub(crate) mod matrix;++/// https://drafts.fxtf.org/geometry/#nan-safe-minimum+pub(crate) fn nan_safe_minimum(values: &[f64]) -> f64 {+ // The NaN-safe minimum of a non-empty list of unrestricted double values is NaN if any member of the list is NaN,+ // or the minimum of the list otherwise.+ if values.iter().any(|value| value.is_nan()) {+ return f64::NAN;+ }+ // NB: The minimum of equal values is the one first in the list, as AK::min() gives it to C++, so that the sign of+ // a zero does not change.+ let (last, rest) = values.split_last().expect("the list is not empty");+ rest.iter()+ .rev()+ .fold(*last, |minimum, value| if minimum < *value { minimum } else { *value })+}++/// https://drafts.fxtf.org/geometry/#nan-safe-maximum+pub(crate) fn nan_safe_maximum(values: &[f64]) -> f64 {+ // Analogously, the NaN-safe maximum of a non-empty list of unrestricted double values is NaN if any member of the+ // list is NaN, or the maximum of the list otherwise.+ if values.iter().any(|value| value.is_nan()) {+ return f64::NAN;+ }+ let (last, rest) = values.split_last().expect("the list is not empty");+ rest.iter()+ .rev()+ .fold(*last, |maximum, value| if *value < maximum { maximum } else { *value })+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rsindex 82d29f350d0..8c6468329ee 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rs@@ -15,7 +15,7 @@ use libgfx_rust::{FloatPoint, FloatSize};use crate::ak_format::ak_formatted;-use crate::geometry::dom_point_read_only::DOMPointInit;+use crate::geometry::dictionaries::DOMPointInit;/// The union (unrestricted double or DOMPointInit) of HTML/Canvas/CanvasPath.idl, a radius of roundRect(), whose/// members the bindings convert.diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rsindex 8b6cc7d685b..e1ef0574caf 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs@@ -22,7 +22,7 @@ use crate::bindings::interface::{Ref, Wrappable, allocate};use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::canvas_2d::canvas::{CanvasImageSourceKind, capture_video_frame, video_transport};use crate::canvas_2d::host::LentVideoFrameHold;-use crate::geometry::dom_matrix_read_only::{DOMMatrix2DInit, validate_and_fixup_2d};+use crate::geometry::dictionaries::{DOMMatrix2DInit, validate_and_fixup_2d};/// The repetition that a value of the repetition argument of createPattern() names exactly, if it names one.fn parse_repetition(repetition: &Utf16String) -> Option<Canvas2DPatternRepetition> {diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rsindex 4d264503dc2..ac0011ff203 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_transform.rs@@ -11,12 +11,13 @@use libgfx_rust::AffineTransform;-use crate::bindings::conversions::CppInterface;+use crate::bindings::interface::{Ref, allocate};use crate::bindings::{CallContext, WebIdlResult};-use crate::canvas_2d::canvas::create_dom_matrix;use crate::canvas_2d::context::{CanvasKind, RenderingContext2D, multiply_transforms, rotated, scaled, translated};use crate::canvas_2d::float;-use crate::geometry::dom_matrix_read_only::{DOMMatrix2DInit, validate_and_fixup_2d};+use crate::geometry::dictionaries::{DOMMatrix2DInit, validate_and_fixup_2d};+use crate::geometry::dom_matrix::DOMMatrix;+use crate::geometry::dom_matrix_read_only::DOMMatrixReadOnly;fn all_finite(values: &[f64]) -> bool {values.iter().all(|value| value.is_finite())@@ -135,9 +136,13 @@ impl<K: CanvasKind> RenderingContext2D<K> {}/// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-gettransform- pub(crate) fn get_transform(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ pub(crate) fn get_transform(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMMatrix>> {+ // The getTransform() method, when invoked, must return a newly created DOMMatrix representing a copy of the+ // current transformation matrix matrix of the context.let transform = self.drawing_state().transform;- Ok(create_dom_matrix(cx.realm(), transform))+ let elements = transform.values.map(f64::from);+ let matrix = DOMMatrix::from_read_only(DOMMatrixReadOnly::create_2d_matrix(elements));+ Ok(allocate(cx.vm(), matrix))}/// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-settransformdiff --git a/Libraries/LibWeb/Bindings/Rust/src/html/path2d.rs b/Libraries/LibWeb/Bindings/Rust/src/html/path2d.rsindex 4b7002910de..0cec65d9568 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/path2d.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/path2d.rs@@ -17,7 +17,7 @@ use super::canvas_path::{};use crate::bindings::interface::{Ref, Wrappable};use crate::bindings::{CallContext, WebIdlResult};-use crate::geometry::dom_matrix_read_only::{DOMMatrix2DInit, validate_and_fixup_2d};+use crate::geometry::dictionaries::{DOMMatrix2DInit, validate_and_fixup_2d};/// The union (Path2D or DOMString) of HTML/Path2D.idl, whose members the bindings convert.pub(crate) enum Path2DOrDOMString {diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 9e1593eb4a6..24f0413b914 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -48,6 +48,10 @@ pub(crate) mod encoding;not(web_idl_bindings),allow(dead_code, reason = "only the generated bindings use the interfaces"))]+#[allow(+ clippy::unnecessary_wraps,+ reason = "the bindings call every attribute and operation as one that can throw"+)]pub(crate) mod geometry;#[cfg_attr(not(web_idl_bindings),diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex dcc73e647d5..93185c3acd7 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -419,7 +419,6 @@ set(SOURCESGeometry/DOMMatrixReadOnly.cppGeometry/DOMPoint.cppGeometry/DOMPointReadOnly.cpp- Geometry/DOMQuad.cppGeometry/DOMRect.cppGeometry/DOMRectList.cppGeometry/DOMRectReadOnly.cppdiff --git a/Libraries/LibWeb/CSS/CSSMatrixComponent.cpp b/Libraries/LibWeb/CSS/CSSMatrixComponent.cppindex 493a9211703..3193c6829a1 100644--- a/Libraries/LibWeb/CSS/CSSMatrixComponent.cpp+++ b/Libraries/LibWeb/CSS/CSSMatrixComponent.cpp@@ -66,7 +66,7 @@ WebIDL::ExceptionOr<Utf16String> CSSMatrixComponent::to_string() const{// 1. Return the serialization of this’s matrix internal slot.// FIXME: This means we ignore our is_2d state. https://github.com/w3c/css-houdini-drafts/issues/1155- return Utf16String::from_utf8(TRY(m_matrix->to_string()));+ return m_matrix->to_string();}WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSMatrixComponent::to_matrix() const@@ -86,37 +86,19 @@ WebIDL::ExceptionOr<void> CSSMatrixComponent::set_matrix(GC::Ref<Geometry::DOMMaWebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> CSSMatrixComponent::create_style_value(PropertyNameAndID const& property) const{+ // NB: The elements are m11, m12, m13, m14, m21, ..., m44, and the elements a to f of a 2D matrix are m11, m12, m21,+ // m22, m41 and m42.+ auto elements = m_matrix->elements();+ StyleValueVector values;if (is_2d()) {- return TransformationStyleValue::create(property.id(), TransformFunction::Matrix,- {- NumberStyleValue::create(m_matrix->a()),- NumberStyleValue::create(m_matrix->b()),- NumberStyleValue::create(m_matrix->c()),- NumberStyleValue::create(m_matrix->d()),- NumberStyleValue::create(m_matrix->e()),- NumberStyleValue::create(m_matrix->f()),- });+ for (auto index : { 0, 1, 4, 5, 12, 13 })+ values.append(NumberStyleValue::create(elements[index]));+ return TransformationStyleValue::create(property.id(), TransformFunction::Matrix, move(values));}- return TransformationStyleValue::create(property.id(), TransformFunction::Matrix3d,- {- NumberStyleValue::create(m_matrix->m11()),- NumberStyleValue::create(m_matrix->m12()),- NumberStyleValue::create(m_matrix->m13()),- NumberStyleValue::create(m_matrix->m14()),- NumberStyleValue::create(m_matrix->m21()),- NumberStyleValue::create(m_matrix->m22()),- NumberStyleValue::create(m_matrix->m23()),- NumberStyleValue::create(m_matrix->m24()),- NumberStyleValue::create(m_matrix->m31()),- NumberStyleValue::create(m_matrix->m32()),- NumberStyleValue::create(m_matrix->m33()),- NumberStyleValue::create(m_matrix->m34()),- NumberStyleValue::create(m_matrix->m41()),- NumberStyleValue::create(m_matrix->m42()),- NumberStyleValue::create(m_matrix->m43()),- NumberStyleValue::create(m_matrix->m44()),- });+ for (auto element : elements)+ values.append(NumberStyleValue::create(element));+ return TransformationStyleValue::create(property.id(), TransformFunction::Matrix3d, move(values));}}diff --git a/Libraries/LibWeb/CSS/CSSMatrixComponent.h b/Libraries/LibWeb/CSS/CSSMatrixComponent.hindex b5953e6da30..00f00a5530a 100644--- a/Libraries/LibWeb/CSS/CSSMatrixComponent.h+++ b/Libraries/LibWeb/CSS/CSSMatrixComponent.h@@ -23,7 +23,6 @@ class CSSMatrixComponent final : public CSSTransformComponent {GC_DECLARE_ALLOCATOR(CSSMatrixComponent);public:- static constexpr size_t matrix_offset() { return offsetof(CSSMatrixComponent, m_matrix); }[[nodiscard]] static GC::Ref<CSSMatrixComponent> create(Is2D, GC::Ref<Geometry::DOMMatrix>);static WebIDL::ExceptionOr<GC::Ref<CSSMatrixComponent>> create_from_dom_matrix_read_only(GC::Ref<Geometry::DOMMatrixReadOnly>, Optional<bool> is_2d = {});static WebIDL::ExceptionOr<GC::Ref<CSSMatrixComponent>> create_for_constructor(GC::Ref<Geometry::DOMMatrixReadOnly>, Bindings::CSSMatrixComponentOptions const&);diff --git a/Libraries/LibWeb/CSS/CSSMatrixComponent.idl b/Libraries/LibWeb/CSS/CSSMatrixComponent.idlindex 0fbdf89348c..d9a797f5461 100644--- a/Libraries/LibWeb/CSS/CSSMatrixComponent.idl+++ b/Libraries/LibWeb/CSS/CSSMatrixComponent.idl@@ -2,7 +2,7 @@[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]interface CSSMatrixComponent : CSSTransformComponent {constructor(DOMMatrixReadOnly matrix, optional CSSMatrixComponentOptions options = {});- [DirectGetter] attribute DOMMatrix matrix;+ attribute DOMMatrix matrix;};// https://drafts.css-houdini.org/css-typed-om-1/#dictdef-cssmatrixcomponentoptionsdiff --git a/Libraries/LibWeb/CSS/CSSPerspective.cpp b/Libraries/LibWeb/CSS/CSSPerspective.cppindex ef5f1c695f9..64bf470695b 100644--- a/Libraries/LibWeb/CSS/CSSPerspective.cpp+++ b/Libraries/LibWeb/CSS/CSSPerspective.cpp@@ -109,13 +109,14 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSPerspective::to_matrix() co// As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in// generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a// TypeError.- auto matrix = Geometry::DOMMatrix::create();+ auto matrix = Gfx::DoubleMatrix4x4::identity();TRY(m_length.visit([&matrix](GC::Ref<CSSNumericValue> const& numeric_value) -> WebIDL::ExceptionOr<void> {// NB: to() throws a TypeError if the conversion can't be done.auto distance = TRY(numeric_value->to("px"_utf16_fly_string))->value();- matrix->set_m34(-1 / max(distance, 1));+ // NB: Gfx::Matrix4x4 is row by row, so the element m34 is in the fourth row and the third column.+ matrix[3, 2] = -1 / max(distance, 1);return {};},[](GC::Ref<CSSKeywordValue> const&) -> WebIDL::ExceptionOr<void> {@@ -123,8 +124,7 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSPerspective::to_matrix() coreturn {};}));- // 2. Return matrix.- return matrix;+ return Geometry::DOMMatrix::create(matrix, is_2d());}CSSPerspectiveValue CSSPerspective::length() constdiff --git a/Libraries/LibWeb/CSS/CSSRotate.cpp b/Libraries/LibWeb/CSS/CSSRotate.cppindex 524ffb50bde..b3ed60a06aa 100644--- a/Libraries/LibWeb/CSS/CSSRotate.cpp+++ b/Libraries/LibWeb/CSS/CSSRotate.cpp@@ -150,19 +150,22 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSRotate::to_matrix() const// TypeError.// 2. Return matrix.- auto matrix = Geometry::DOMMatrix::create();+ auto matrix = Geometry::DOMMatrix::create(Gfx::DoubleMatrix4x4::identity(), is_2d());// NB: to() throws a TypeError if the conversion can't be done.auto angle = TRY(m_angle->to("deg"_utf16_fly_string))->value();- if (is_2d())- return matrix->rotate_axis_angle_self(0, 0, 1, angle);+ if (is_2d()) {+ matrix->rotate_axis_angle_self(0, 0, 1, angle);+ return matrix;+ }auto x = TRY(m_x->to("number"_utf16_fly_string))->value();auto y = TRY(m_y->to("number"_utf16_fly_string))->value();auto z = TRY(m_z->to("number"_utf16_fly_string))->value();- return matrix->rotate_axis_angle_self(x, y, z, angle);+ matrix->rotate_axis_angle_self(x, y, z, angle);+ return matrix;}// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-xdiff --git a/Libraries/LibWeb/CSS/CSSScale.cpp b/Libraries/LibWeb/CSS/CSSScale.cppindex 5b3e796467e..a8ea7765d59 100644--- a/Libraries/LibWeb/CSS/CSSScale.cpp+++ b/Libraries/LibWeb/CSS/CSSScale.cpp@@ -140,17 +140,15 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSScale::to_matrix() const// TypeError.// 2. Return matrix.- auto matrix = Geometry::DOMMatrix::create();-// NB: to() throws a TypeError if the conversion can't be done.auto x = TRY(m_x->to("number"_utf16_fly_string))->value();auto y = TRY(m_y->to("number"_utf16_fly_string))->value();- if (is_2d())- return matrix->scale_self(x, y, {}, {}, {}, {});+ double z = 1;+ if (!is_2d())+ z = TRY(m_z->to("number"_utf16_fly_string))->value();- auto z = TRY(m_z->to("number"_utf16_fly_string))->value();- return matrix->scale_self(x, y, z, {}, {}, {});+ return Geometry::DOMMatrix::create(Gfx::scale_matrix(Vector3<double> { x, y, z }), is_2d());}// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssscale-xdiff --git a/Libraries/LibWeb/CSS/CSSSkew.cpp b/Libraries/LibWeb/CSS/CSSSkew.cppindex 7fc6da8e6dc..4c14e0a74a8 100644--- a/Libraries/LibWeb/CSS/CSSSkew.cpp+++ b/Libraries/LibWeb/CSS/CSSSkew.cpp@@ -92,17 +92,15 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSSkew::to_matrix() const// As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in// generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a// TypeError.- auto matrix = Geometry::DOMMatrix::create();-- // NB: to() throws a TypeError if the conversion can't be done.auto ax_rad = TRY(m_ax->to("rad"_utf16_fly_string))->value();auto ay_rad = TRY(m_ay->to("rad"_utf16_fly_string))->value();- matrix->set_m21(tanf(ax_rad));- matrix->set_m12(tanf(ay_rad));+ // NB: Gfx::Matrix4x4 is row by row, so the element m21 is in the first row and m12 in the second.+ auto matrix = Gfx::DoubleMatrix4x4::identity();+ matrix[0, 1] = tanf(ax_rad);+ matrix[1, 0] = tanf(ay_rad);- // 2. Return matrix.- return matrix;+ return Geometry::DOMMatrix::create(matrix, is_2d());}WebIDL::ExceptionOr<void> CSSSkew::set_ax(GC::Ref<CSSNumericValue> ax)diff --git a/Libraries/LibWeb/CSS/CSSSkewX.cpp b/Libraries/LibWeb/CSS/CSSSkewX.cppindex 25d3ceb8d9e..f59bdd308b5 100644--- a/Libraries/LibWeb/CSS/CSSSkewX.cpp+++ b/Libraries/LibWeb/CSS/CSSSkewX.cpp@@ -75,14 +75,13 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSSkewX::to_matrix() const// As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in// generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a// TypeError.- auto matrix = Geometry::DOMMatrix::create();-- // NB: to() throws a TypeError if the conversion can't be done.auto ax_rad = TRY(m_ax->to("rad"_utf16_fly_string))->value();- matrix->set_m21(tanf(ax_rad));- // 2. Return matrix.- return matrix;+ // NB: Gfx::Matrix4x4 is row by row, so the element m21 is in the first row.+ auto matrix = Gfx::DoubleMatrix4x4::identity();+ matrix[0, 1] = tanf(ax_rad);++ return Geometry::DOMMatrix::create(matrix, is_2d());}WebIDL::ExceptionOr<void> CSSSkewX::set_ax(GC::Ref<CSSNumericValue> ax)diff --git a/Libraries/LibWeb/CSS/CSSSkewY.cpp b/Libraries/LibWeb/CSS/CSSSkewY.cppindex 07e119e385f..9ecc87c8057 100644--- a/Libraries/LibWeb/CSS/CSSSkewY.cpp+++ b/Libraries/LibWeb/CSS/CSSSkewY.cpp@@ -75,14 +75,13 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSSkewY::to_matrix() const// As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in// generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a// TypeError.- auto matrix = Geometry::DOMMatrix::create();-- // NB: to() throws a TypeError if the conversion can't be done.auto ay_rad = TRY(m_ay->to("rad"_utf16_fly_string))->value();- matrix->set_m12(tanf(ay_rad));- // 2. Return matrix.- return matrix;+ // NB: Gfx::Matrix4x4 is row by row, so the element m12 is in the second row.+ auto matrix = Gfx::DoubleMatrix4x4::identity();+ matrix[1, 0] = tanf(ay_rad);++ return Geometry::DOMMatrix::create(matrix, is_2d());}WebIDL::ExceptionOr<void> CSSSkewY::set_ay(GC::Ref<CSSNumericValue> ay)diff --git a/Libraries/LibWeb/CSS/CSSTranslate.cpp b/Libraries/LibWeb/CSS/CSSTranslate.cppindex a05cc0411b2..57e5259406b 100644--- a/Libraries/LibWeb/CSS/CSSTranslate.cpp+++ b/Libraries/LibWeb/CSS/CSSTranslate.cpp@@ -131,16 +131,14 @@ WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSTranslate::to_matrix() cons// As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in// generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a// TypeError.- auto matrix = Geometry::DOMMatrix::create();+ auto x = TRY(m_x->to("px"_utf16_fly_string))->value();+ auto y = TRY(m_y->to("px"_utf16_fly_string))->value();- // NB: to() throws a TypeError if the conversion can't be done.- matrix->set_m41(TRY(m_x->to("px"_utf16_fly_string))->value());- matrix->set_m42(TRY(m_y->to("px"_utf16_fly_string))->value());+ double z = 0;if (!is_2d())- matrix->set_m43(TRY(m_z->to("px"_utf16_fly_string))->value());+ z = TRY(m_z->to("px"_utf16_fly_string))->value();- // 2. Return matrix.- return matrix;+ return Geometry::DOMMatrix::create(Gfx::translation_matrix(Vector3<double> { x, y, z }), is_2d());}WebIDL::ExceptionOr<void> CSSTranslate::set_x(GC::Ref<CSSNumericValue> x)diff --git a/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.cppindex 0912cf620f1..779ace7ed92 100644--- a/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.cpp+++ b/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.cpp@@ -58,26 +58,16 @@ GC::Ptr<CSSTransformComponent> TransformationStyleValue::reify_a_transform_functif (!ComputedValuesFFI::rust_transform_list_to_abstract_matrix(rust_style_value_data(), transform_as_matrix.data(), &is_2d_matrix))return nullptr;- auto matrix = Geometry::DOMMatrix::create();- matrix->set_m11(transform_as_matrix[0]);- matrix->set_m12(transform_as_matrix[4]);- matrix->set_m13(transform_as_matrix[8]);- matrix->set_m14(transform_as_matrix[12]);- matrix->set_m21(transform_as_matrix[1]);- matrix->set_m22(transform_as_matrix[5]);- matrix->set_m23(transform_as_matrix[9]);- matrix->set_m24(transform_as_matrix[13]);- matrix->set_m31(transform_as_matrix[2]);- matrix->set_m32(transform_as_matrix[6]);- matrix->set_m33(transform_as_matrix[10]);- matrix->set_m34(transform_as_matrix[14]);- matrix->set_m41(transform_as_matrix[3]);- matrix->set_m42(transform_as_matrix[7]);- matrix->set_m43(transform_as_matrix[11]);- matrix->set_m44(transform_as_matrix[15]);+ // NB: The matrix is row by row, as Gfx::Matrix4x4 takes it.+ Gfx::FloatMatrix4x4 matrix {+ transform_as_matrix[0], transform_as_matrix[1], transform_as_matrix[2], transform_as_matrix[3],+ transform_as_matrix[4], transform_as_matrix[5], transform_as_matrix[6], transform_as_matrix[7],+ transform_as_matrix[8], transform_as_matrix[9], transform_as_matrix[10], transform_as_matrix[11],+ transform_as_matrix[12], transform_as_matrix[13], transform_as_matrix[14], transform_as_matrix[15]+ };auto is_2d = transform_function() == TransformFunction::Matrix ? CSSTransformComponent::Is2D::Yes : CSSTransformComponent::Is2D::No;- return CSSMatrixComponent::create(is_2d, matrix);+ return CSSMatrixComponent::create(is_2d, Geometry::DOMMatrix::create(matrix));}// -> translate()diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex 5804bc76ec2..8680a4d01a5 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -4604,15 +4604,15 @@ void scroll_a_target_into_view(Layout::BegunRead const& read, ScrollIntoViewTarg[](Range* range) {// AD-HOC: Text-fragment scrolling centers the beginning of a match. Using the union// of every client rect can put the beginning of a long passage outside the viewport.- auto rects = range->get_client_rects();- auto const* rect = rects->length() > 0 ? rects->item(0) : nullptr;- if (!rect)+ auto rects = range->client_rects();+ if (rects.is_empty())return CSSPixelRect {};+ auto const& rect = rects.first();return CSSPixelRect {- CSSPixels::nearest_value_for(rect->x()),- CSSPixels::nearest_value_for(rect->y()),- CSSPixels::nearest_value_for(rect->width()),- CSSPixels::nearest_value_for(rect->height()),+ CSSPixels::nearest_value_for(rect.x()),+ CSSPixels::nearest_value_for(rect.y()),+ CSSPixels::nearest_value_for(rect.width()),+ CSSPixels::nearest_value_for(rect.height()),};});};@@ -7193,11 +7193,11 @@ GC::Ref<Geometry::DOMRect> get_bounding_client_rect(DOM::Element const& element)GC::Ref<Geometry::DOMRectList> get_client_rects(DOM::Element const& element){- Vector<GC::Root<Geometry::DOMRect>> rects;+ Vector<Gfx::DoubleRect> rects;for (auto const& rect : element.get_client_rects())- rects.append(create_dom_rect(rect));+ rects.append(rect.to_type<double>());- return Geometry::DOMRectList::create(move(rects));+ return Geometry::DOMRectList::create(rects);}GC::Ref<WebIDL::Promise> request_pointer_lock(DOM::Element& element, Optional<PointerLockOptions> const& options)diff --git a/Libraries/LibWeb/DOM/Range.cpp b/Libraries/LibWeb/DOM/Range.cppindex f40f5dd542d..40cae6bf905 100644--- a/Libraries/LibWeb/DOM/Range.cpp+++ b/Libraries/LibWeb/DOM/Range.cpp@@ -8,6 +8,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/AllOf.h>#include <LibGC/Heap.h>#include <LibWeb/DOM/Comment.h>#include <LibWeb/DOM/Document.h>@@ -1292,16 +1293,21 @@ WebIDL::ExceptionOr<void> Range::delete_contents()// https://drafts.csswg.org/cssom-view/#dom-element-getclientrects// https://drafts.csswg.org/cssom-view/#extensions-to-the-range-interfaceGC::Ref<Geometry::DOMRectList> Range::get_client_rects()+{+ return Geometry::DOMRectList::create(client_rects());+}++Vector<Gfx::DoubleRect> Range::client_rects(){// 1. return an empty DOMRectList object if the range is not in the documentif (!start_container()->document().navigable())- return Geometry::DOMRectList::create({});+ return {};auto& document = start_container()->document();document.update_layout(DOM::UpdateLayoutReason::RangeGetClientRects);document.update_paint_and_hit_testing_properties_if_needed();Layout::ForcedReadScope read { document };- Vector<GC::Root<Geometry::DOMRect>> rects;+ Vector<Gfx::DoubleRect> rects;Optional<Compositing::AccumulatedVisualContextTree> visual_context_tree;auto rect_to_viewport_transform = Painting::identity_rect_to_viewport_transform();@@ -1362,9 +1368,8 @@ GC::Ref<Geometry::DOMRectList> Range::get_client_rects()if (contains_node(*node) && (!node->parent() || !contains_node(*node->parent()))) {auto const& element = static_cast<DOM::Element const&>(*node);auto const element_rects = element.get_client_rects();- for (auto& rect : element_rects) {- rects.append(Geometry::DOMRect::create(static_cast<double>(rect.x()), static_cast<double>(rect.y()), static_cast<double>(rect.width()), static_cast<double>(rect.height())));- }+ for (auto& rect : element_rects)+ rects.append(rect.to_type<double>());}} else if (node_type == NodeType::TEXT_NODE) {// 2. For each Text node selected or partially selected by the range (including when the boundary-points@@ -1408,46 +1413,43 @@ GC::Ref<Geometry::DOMRectList> Range::get_client_rects()layout_node->document_host(), Layout::Node::slot_id(layout_node),to_underlying(selection_state), start_offset(), end_offset(), filter_dom_start, filter_dom_end,rect_to_viewport_transform, &rects, [](void* context, CSSPixelRect rect) {- static_cast<Vector<GC::Root<Geometry::DOMRect>>*>(context)->append(Geometry::DOMRect::create(rect.to_type<float>()));+ static_cast<Vector<Gfx::DoubleRect>*>(context)->append(rect.to_type<float>().to_type<double>());});}}- return Geometry::DOMRectList::create(move(rects));+ return rects;}// https://w3c.github.io/csswg-drafts/cssom-view/#dom-range-getboundingclientrectGC::Ref<Geometry::DOMRect> Range::get_bounding_client_rect()+{+ auto rect = bounding_client_rect();+ return Geometry::DOMRect::create(rect.x(), rect.y(), rect.width(), rect.height());+}++Gfx::DoubleRect Range::bounding_client_rect(){// 1. Let list be the result of invoking getClientRects() on element.- auto list = get_client_rects();+ auto list = client_rects();// 2. If the list is empty return a DOMRect object whose x, y, width and height members are zero.- if (list->length() == 0)- return Geometry::DOMRect::create(0, 0, 0, 0);+ if (list.is_empty())+ return {};// 3. If all rectangles in list have zero width or height, return the first rectangle in list.- auto all_rectangle_has_zero_width_or_height = true;- for (auto i = 0u; i < list->length(); ++i) {- auto const& rect = list->item(i);- if (rect->width() != 0 && rect->height() != 0) {- all_rectangle_has_zero_width_or_height = false;- break;- }- }+ auto all_rectangle_has_zero_width_or_height = all_of(list, [](auto const& rect) { return rect.width() == 0 || rect.height() == 0; });if (all_rectangle_has_zero_width_or_height)- return GC::Ref { *const_cast<Geometry::DOMRect*>(list->item(0)) };+ return list[0];// 4. Otherwise, return a DOMRect object describing the smallest rectangle that includes all of the rectangles in// list of which the height or width is not zero.- auto const* first_rect = list->item(0);- auto bounding_rect = Gfx::Rect { first_rect->x(), first_rect->y(), first_rect->width(), first_rect->height() };- for (auto i = 1u; i < list->length(); ++i) {- auto const& rect = list->item(i);- if (rect->width() == 0 || rect->height() == 0)+ auto bounding_rect = list[0];+ for (auto const& rect : list.span().slice(1)) {+ if (rect.width() == 0 || rect.height() == 0)continue;- bounding_rect.unite({ rect->x(), rect->y(), rect->width(), rect->height() });+ bounding_rect.unite(rect);}- return Geometry::DOMRect::create(bounding_rect.to_type<float>());+ return bounding_rect.to_type<float>().to_type<double>();}WebIDL::ExceptionOr<GC::Ref<DocumentFragment>> Range::create_contextual_fragment(TrustedTypes::TrustedHTMLOrString const& string)diff --git a/Libraries/LibWeb/DOM/Range.h b/Libraries/LibWeb/DOM/Range.hindex 60ec520c224..a64667f2e27 100644--- a/Libraries/LibWeb/DOM/Range.h+++ b/Libraries/LibWeb/DOM/Range.h@@ -10,6 +10,7 @@#pragma once#include <AK/IntrusiveList.h>+#include <LibGfx/Rect.h>#include <LibJS/Forward.h>#include <LibWeb/DOM/AbstractRange.h>#include <LibWeb/DOM/Node.h>@@ -96,6 +97,10 @@ public:GC::Ref<Geometry::DOMRectList> get_client_rects();GC::Ref<Geometry::DOMRect> get_bounding_client_rect();+ // The rectangles of getClientRects() and getBoundingClientRect().+ Vector<Gfx::DoubleRect> client_rects();+ Gfx::DoubleRect bounding_client_rect();+bool contains_node(GC::Ref<Node>) const;void set_associated_selection(Badge<Selection::Selection>, GC::Ptr<Selection::Selection>);diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 4c7f0ee1418..6205d19aa65 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -645,7 +645,6 @@ class DOMMatrix;class DOMMatrixReadOnly;class DOMPoint;class DOMPointReadOnly;-class DOMQuad;class DOMRect;class DOMRectList;class DOMRectReadOnly;diff --git a/Libraries/LibWeb/Geometry/DOMMatrix.cpp b/Libraries/LibWeb/Geometry/DOMMatrix.cppindex 5fa06977b18..051e878d11b 100644--- a/Libraries/LibWeb/Geometry/DOMMatrix.cpp+++ b/Libraries/LibWeb/Geometry/DOMMatrix.cpp@@ -5,580 +5,60 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/TypeCasts.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/TypedArray.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Geometry/DOMMatrix.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Geometry {-GC_DEFINE_ALLOCATOR(DOMMatrix);+extern "C" {-// https://drafts.fxtf.org/geometry/#dom-dommatrix-dommatrix-WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> DOMMatrix::create_from_constructor(Optional<Variant<Utf16String, Vector<double>>> const& init, DOMMatrixStringContext string_context)-{- // -> If init is omitted- if (!init.has_value()) {- // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with the sequence [1, 0, 0, 1, 0, 0].- return GC::Heap::the().allocate<DOMMatrix>(1, 0, 0, 1, 0, 0);- }-- auto const& init_value = init.value();-- // -> If init is a DOMString- if (init_value.has<Utf16String>()) {- // 1. If current global object is not a Window object, then throw a TypeError exception.- if (string_context != DOMMatrixStringContext::Window)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "This can only be used in a Window context"_utf16 };-- // 2. Parse init into an abstract matrix, and let matrix and 2dTransform be the result. If the result is failure, then throw a "SyntaxError" DOMException.- auto transform_list = init_value.get<Utf16String>().to_utf8();- auto result = TRY(parse_dom_matrix_init_string(transform_list));- auto& m = result.matrix;-- // If 2dTransform is true- if (result.is_2d_transform) {- // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers, the values being the elements m11, m12, m21, m22, m41 and m42 of matrix.- return GC::Heap::the().allocate<DOMMatrix>(m[0, 0], m[1, 0], m[0, 1], m[1, 1], m[0, 3], m[1, 3]);- }-- // Otherwise, return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers, the values being the 16 elements of matrix.- return GC::Heap::the().allocate<DOMMatrix>(- m[0, 0], m[1, 0], m[2, 0], m[3, 0],- m[0, 1], m[1, 1], m[2, 1], m[3, 1],- m[0, 2], m[1, 2], m[2, 2], m[3, 2],- m[0, 3], m[1, 3], m[2, 3], m[3, 3]);- }-- auto const& double_sequence = init_value.get<Vector<double>>();-- // -> If init is a sequence with 6 elements- if (double_sequence.size() == 6) {- // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with the sequence init.- return GC::Heap::the().allocate<DOMMatrix>(double_sequence[0], double_sequence[1], double_sequence[2], double_sequence[3], double_sequence[4], double_sequence[5]);- }-- // -> If init is a sequence with 16 elements- if (double_sequence.size() == 16) {- // Return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with the sequence init.- return GC::Heap::the().allocate<DOMMatrix>(- double_sequence[0], double_sequence[1], double_sequence[2], double_sequence[3],- double_sequence[4], double_sequence[5], double_sequence[6], double_sequence[7],- double_sequence[8], double_sequence[9], double_sequence[10], double_sequence[11],- double_sequence[12], double_sequence[13], double_sequence[14], double_sequence[15]);- }-- // -> Otherwise, throw a TypeError exception.- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Sequence must contain exactly 6 or 16 elements, got {} element(s)", double_sequence.size()) };-}--WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> DOMMatrix::create_for_constructor(JS::Object& relevant_global_object, Optional<Variant<Utf16String, Vector<double>>> const& init)-{- return create_from_constructor(init, dom_matrix_string_context(relevant_global_object));+// Defined in Bindings/Rust/src/geometry/exports.rs.+void* web_dom_matrix_create(JSVM*, Array<double, 16> const* elements, bool is_2d);+void* web_dom_matrix_create_from_read_only(JSVM*, void const* matrix);+void web_dom_matrix_multiply_self(void* matrix, void const* other);+void web_dom_matrix_rotate_axis_angle_self(void* matrix, double x, double y, double z, double angle);}-// https://drafts.fxtf.org/geometry/#create-a-dommatrix-from-the-2d-dictionary-GC::Ref<DOMMatrix> DOMMatrix::create_from_dom_matrix_2d_init(DOMMatrix2DInit const& init)+GC::Ref<DOMMatrix> DOMMatrix::create(){- // 2. Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers,- // the values being the 6 elements m11, m12, m21, m22, m41 and m42 of other in the given order.- return GC::Heap::the().allocate<DOMMatrix>(init.m11, init.m12, init.m21, init.m22, init.m41, init.m42);+ return create(Gfx::DoubleMatrix4x4::identity(), true);}-// https://drafts.fxtf.org/geometry/#create-a-dommatrix-from-the-dictionary-GC::Ref<DOMMatrix> DOMMatrix::create_from_dom_matrix_init(DOMMatrixInit const& init)+GC::Ref<DOMMatrix> DOMMatrix::create(Gfx::DoubleMatrix4x4 const& matrix, bool is_2d){- // 2. If the is2D dictionary member of other is true.- if (init.is_2d) {- // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers, the values being the 6 elements m11, m12, m21, m22, m41 and m42 of other in the given order.- return GC::Heap::the().allocate<DOMMatrix>(init.m11, init.m12, init.m21, init.m22, init.m41, init.m42);+ // NB: Gfx::Matrix4x4 is row by row, so the element mRC of the matrix is in row C and column R.+ Array<double, 16> elements;+ for (size_t row = 0; row < 4; ++row) {+ for (size_t column = 0; column < 4; ++column)+ elements[(column * 4) + row] = matrix[row, column];}-- // Otherwise, Return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers, the values being the 16 elements m11, m12, m13, ..., m44 of other in the given order.- return GC::Heap::the().allocate<DOMMatrix>(init.m11, init.m12, init.m13, init.m14,- init.m21, init.m22, init.m23, init.m24,- init.m31, init.m32, init.m33, init.m34,- init.m41, init.m42, init.m43, init.m44);-}--WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> DOMMatrix::from_matrix(Bindings::DOMMatrixInit& other)-{- return create_from_dom_matrix_init(TRY(validate_and_fixup_dom_matrix_init(other)));-}--GC::Ref<DOMMatrix> DOMMatrix::create_from_dom_matrix_read_only(DOMMatrixReadOnly const& read_only_matrix)-{- return GC::Heap::the().allocate<DOMMatrix>(read_only_matrix);+ return GC::Ref { *static_cast<DOMMatrix*>(web_dom_matrix_create(JS::HostABI::vm_to_abi(JS::VM::the()), &elements, is_2d)) };}GC::Ref<DOMMatrix> DOMMatrix::create(Gfx::FloatMatrix4x4 const& matrix){- return GC::Heap::the().allocate<DOMMatrix>(matrix);-}--GC::Ref<DOMMatrix> DOMMatrix::create(Gfx::DoubleMatrix4x4 const& matrix)-{- return GC::Heap::the().allocate<DOMMatrix>(matrix);-}--GC::Ref<DOMMatrix> DOMMatrix::create()-{- return GC::Heap::the().allocate<DOMMatrix>();-}--DOMMatrix::DOMMatrix(double m11, double m12, double m21, double m22, double m41, double m42)- : DOMMatrixReadOnly(m11, m12, m21, m22, m41, m42)-{-}--DOMMatrix::DOMMatrix(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double m41, double m42, double m43, double m44)- : DOMMatrixReadOnly(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44)-{-}--DOMMatrix::DOMMatrix(DOMMatrixReadOnly const& read_only_matrix)- : DOMMatrixReadOnly(read_only_matrix)-{-}--DOMMatrix::DOMMatrix()- : DOMMatrixReadOnly()-{-}--DOMMatrix::~DOMMatrix() = default;--// https://drafts.fxtf.org/geometry/#dom-dommatrix-fromfloat32array-WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> DOMMatrix::from_float32_array(GC::Root<JS::Float32Array> const& array)-{- ReadonlySpan<float> elements { reinterpret_cast<float const*>(array->viewed_array_buffer()->data_at(array->byte_offset())), array->byte_length().length() / sizeof(float) };-- // If array32 has 6 elements, return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers taking the values from array32 in the provided order.- if (elements.size() == 6)- return GC::Heap::the().allocate<DOMMatrix>(elements.at(0), elements.at(1), elements.at(2), elements.at(3), elements.at(4), elements.at(5));-- // If array32 has 16 elements, return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers taking the values from array32 in the provided order.- if (elements.size() == 16)- return GC::Heap::the().allocate<DOMMatrix>(elements.at(0), elements.at(1), elements.at(2), elements.at(3),- elements.at(4), elements.at(5), elements.at(6), elements.at(7),- elements.at(8), elements.at(9), elements.at(10), elements.at(11),- elements.at(12), elements.at(13), elements.at(14), elements.at(15));- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Sequence must contain exactly 6 or 16 elements"_utf16 };-}--// https://drafts.fxtf.org/geometry/#dom-dommatrix-fromfloat64array-WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> DOMMatrix::from_float64_array(GC::Root<JS::Float64Array> const& array)-{- ReadonlySpan<double> elements { reinterpret_cast<double const*>(array->viewed_array_buffer()->data_at(array->byte_offset())), array->byte_length().length() / sizeof(double) };-- // If array64 has 6 elements, return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers taking the values from array64 in the provided order.- if (elements.size() == 6)- return GC::Heap::the().allocate<DOMMatrix>(elements.at(0), elements.at(1), elements.at(2), elements.at(3), elements.at(4), elements.at(5));-- // If array64 has 16 elements, return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers taking the values from array64 in the provided order.- if (elements.size() == 16)- return GC::Heap::the().allocate<DOMMatrix>(elements.at(0), elements.at(1), elements.at(2), elements.at(3),- elements.at(4), elements.at(5), elements.at(6), elements.at(7),- elements.at(8), elements.at(9), elements.at(10), elements.at(11),- elements.at(12), elements.at(13), elements.at(14), elements.at(15));- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Sequence must contain exactly 6 or 16 elements"_utf16 };-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m11-void DOMMatrix::set_m11(double value)-{- // For the DOMMatrix interface, setting the m11 or the a attribute must set the m11 element to the new value.- m_matrix[0, 0] = value;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m12-void DOMMatrix::set_m12(double value)-{- // For the DOMMatrix interface, setting the m12 or the b attribute must set the m12 element to the new value.- m_matrix[1, 0] = value;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m13-void DOMMatrix::set_m13(double value)-{- // For the DOMMatrix interface, setting the m13 attribute must set the m13 element to the new value and, if the new value is not 0 or -0, set is 2D to false.- m_matrix[2, 0] = value;- if (value != 0.0 && value != -0.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m14-void DOMMatrix::set_m14(double value)-{- // For the DOMMatrix interface, setting the m14 attribute must set the m14 element to the new value and, if the new value is not 0 or -0, set is 2D to false.- m_matrix[3, 0] = value;- if (value != 0.0 && value != -0.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m21-void DOMMatrix::set_m21(double value)-{- // For the DOMMatrix interface, setting the m21 or the c attribute must set the m21 element to the new value.- m_matrix[0, 1] = value;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m22-void DOMMatrix::set_m22(double value)-{- // For the DOMMatrix interface, setting the m22 or the d attribute must set the m22 element to the new value.- m_matrix[1, 1] = value;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m23-void DOMMatrix::set_m23(double value)-{- // For the DOMMatrix interface, setting the m23 attribute must set the m23 element to the new value and, if the new value is not 0 or -0, set is 2D to false.- m_matrix[2, 1] = value;- if (value != 0.0 && value != -0.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m24-void DOMMatrix::set_m24(double value)-{- // For the DOMMatrix interface, setting the m24 attribute must set the m24 element to the new value and, if the new value is not 0 or -0, set is 2D to false.- m_matrix[3, 1] = value;- if (value != 0.0 && value != -0.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m31-void DOMMatrix::set_m31(double value)-{- // For the DOMMatrix interface, setting the m31 attribute must set the m31 element to the new value and, if the new value is not 0 or -0, set is 2D to false.- m_matrix[0, 2] = value;- if (value != 0.0 && value != -0.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m32-void DOMMatrix::set_m32(double value)-{- // For the DOMMatrix interface, setting the m32 attribute must set the m32 element to the new value and, if the new value is not 0 or -0, set is 2D to false.- m_matrix[1, 2] = value;- if (value != 0.0 && value != -0.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m33-void DOMMatrix::set_m33(double value)-{- // For the DOMMatrix interface, setting the m33 attribute must set the m33 element to the new value and, if the new value is not 1, set is 2D to false.- m_matrix[2, 2] = value;- if (value != 1.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m34-void DOMMatrix::set_m34(double value)-{- // For the DOMMatrix interface, setting the m34 attribute must set the m34 element to the new value and, if the new value is not 0 or -0, set is 2D to false.- m_matrix[3, 2] = value;- if (value != 0.0 && value != -0.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m41-void DOMMatrix::set_m41(double value)-{- // For the DOMMatrix interface, setting the m41 or the e attribute must set the m41 element to the new value.- m_matrix[0, 3] = value;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m42-void DOMMatrix::set_m42(double value)-{- // For the DOMMatrix interface, setting the m42 or the f attribute must set the m42 element to the new value.- m_matrix[1, 3] = value;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m43-void DOMMatrix::set_m43(double value)-{- // For the DOMMatrix interface, setting the m43 attribute must set the m43 element to the new value and, if the new value is not 0 or -0, set is 2D to false.- m_matrix[2, 3] = value;- if (value != 0.0 && value != -0.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-m44-void DOMMatrix::set_m44(double value)-{- // For the DOMMatrix interface, setting the m44 attribute must set the m44 element to the new value and, if the new value is not 1, set is 2D to false.- m_matrix[3, 3] = value;- if (value != 1.0)- m_is_2d = false;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-a-void DOMMatrix::set_a(double value)-{- // For the DOMMatrix interface, setting the m11 or the a attribute must set the m11 element to the new value.- set_m11(value);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-b-void DOMMatrix::set_b(double value)-{- // For the DOMMatrix interface, setting the m12 or the b attribute must set the m12 element to the new value.- set_m12(value);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-c-void DOMMatrix::set_c(double value)-{- // For the DOMMatrix interface, setting the m21 or the c attribute must set the m21 element to the new value.- set_m21(value);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-d-void DOMMatrix::set_d(double value)-{- // For the DOMMatrix interface, setting the m22 or the d attribute must set the m22 element to the new value.- set_m22(value);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-e-void DOMMatrix::set_e(double value)-{- // For the DOMMatrix interface, setting the m41 or the e attribute must set the m41 element to the new value.- set_m41(value);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-f-void DOMMatrix::set_f(double value)-{- // For the DOMMatrix interface, setting the m42 or the f attribute must set the m42 element to the new value.- set_m42(value);-}--GC::Ref<DOMMatrix> DOMMatrix::multiply_self(GC::Ref<DOMMatrix> other)-{- m_matrix = m_matrix * other->m_matrix;- if (!other->m_is_2d)- m_is_2d = false;- return GC::Ref<DOMMatrix>(*this);-}--WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> DOMMatrix::multiply_self(Bindings::DOMMatrixInit& other)-{- auto other_object = DOMMatrix::create_from_dom_matrix_init(TRY(validate_and_fixup_dom_matrix_init(other)));- return multiply_self(other_object);-}--GC::Ref<DOMMatrix> DOMMatrix::pre_multiply_self(GC::Ref<DOMMatrix> other)-{- m_matrix = other->m_matrix * m_matrix;- if (!other->m_is_2d)- m_is_2d = false;- return GC::Ref<DOMMatrix>(*this);-}--WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> DOMMatrix::pre_multiply_self(Bindings::DOMMatrixInit& other)-{- auto other_object = DOMMatrix::create_from_dom_matrix_init(TRY(validate_and_fixup_dom_matrix_init(other)));- return pre_multiply_self(other_object);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrix-translateself-GC::Ref<DOMMatrix> DOMMatrix::translate_self(Optional<double> tx, Optional<double> ty, Optional<double> tz)-{- // 1. Post-multiply a translation transformation on the current matrix. The 3D translation matrix is described in CSS Transforms.- m_matrix = m_matrix * Gfx::translation_matrix(Vector3<double> { tx.value_or(0), ty.value_or(0), tz.value_or(0) });-- // 2. If tz is specified and not 0 or -0, set is 2D of the current matrix to false.- if (tz.has_value() && (tz != 0 && tz != -0))- m_is_2d = false;-- // 3. Return the current matrix.- return *this;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrix-scaleself-GC::Ref<DOMMatrix> DOMMatrix::scale_self(Optional<double> scale_x, Optional<double> scale_y, Optional<double> scale_z, Optional<double> origin_x, Optional<double> origin_y, Optional<double> origin_z)-{- // 1. Perform a translateSelf() transformation on the current matrix with the arguments originX, originY, originZ.- translate_self(origin_x, origin_y, origin_z);-- // 2. If scaleY is missing, set scaleY to the value of scaleX.- if (!scale_y.has_value())- scale_y = scale_x.value_or(1);-- // 3. Post-multiply a non-uniform scale transformation on the current matrix. The 3D scale matrix is described in CSS Transforms with sx = scaleX, sy = scaleY and sz = scaleZ. [CSS3-TRANSFORMS]- m_matrix = m_matrix * Gfx::scale_matrix(Vector3<double> { scale_x.value_or(1), scale_y.value(), scale_z.value_or(1) });-- // 4. Negate originX, originY and originZ.- // 5. Perform a translateSelf() transformation on the current matrix with the arguments originX, originY, originZ.- translate_self(-origin_x.value_or(0), -origin_y.value_or(0), -origin_z.value_or(0));-- // 6. If scaleZ is not 1, set is 2D of the current matrix to false.- if (scale_z != 1)- m_is_2d = false;-- // 7. Return the current matrix.- return *this;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrix-scale3dself-GC::Ref<DOMMatrix> DOMMatrix::scale3d_self(Optional<double> scale, Optional<double> origin_x, Optional<double> origin_y, Optional<double> origin_z)-{- // 1. Apply a translateSelf() transformation to the current matrix with the arguments originX, originY, originZ.- translate_self(origin_x, origin_y, origin_z);-- // 2. Post-multiply a uniform 3D scale transformation (m11 = m22 = m33 = scale) on the current matrix. The 3D scale matrix is described in CSS Transforms with sx = sy = sz = scale. [CSS3-TRANSFORMS]- m_matrix = m_matrix * Gfx::scale_matrix(Vector3<double> { scale.value_or(1), scale.value_or(1), scale.value_or(1) });-- // 3. Apply a translateSelf() transformation to the current matrix with the arguments -originX, -originY, -originZ.- translate_self(-origin_x.value_or(0), -origin_y.value_or(0), -origin_z.value_or(0));-- // 4. If scale is not 1, set is 2D of the current matrix to false.- if (scale != 1)- m_is_2d = false;-- // 5. Return the current matrix.- return *this;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrix-rotateself-GC::Ref<DOMMatrix> DOMMatrix::rotate_self(Optional<double> rot_x, Optional<double> rot_y, Optional<double> rot_z)-{- // 1. If rotY and rotZ are both missing, set rotZ to the value of rotX and set rotX and rotY to 0.- if (!rot_y.has_value() && !rot_z.has_value()) {- rot_z = rot_x;- rot_x = 0;- rot_y = 0;+ Gfx::DoubleMatrix4x4 double_matrix;+ for (size_t row = 0; row < 4; ++row) {+ for (size_t column = 0; column < 4; ++column)+ double_matrix[row, column] = matrix[row, column];}-- // 2. If rotY is still missing, set rotY to 0.- if (!rot_y.has_value())- rot_y = 0;-- // 3. If rotZ is still missing, set rotZ to 0.- if (!rot_z.has_value())- rot_z = 0;-- // 4. If rotX or rotY are not 0 or -0, set is 2D of the current matrix to false.- if ((rot_x != 0 && rot_x != -0) || (rot_y != 0 && rot_y != -0))- m_is_2d = false;-- // 5. Post-multiply a rotation transformation on the current matrix around the vector 0, 0, 1 by the specified rotation rotZ in degrees. The 3D rotation matrix is described in CSS Transforms with alpha = rotZ in degrees. [CSS3-TRANSFORMS]- m_matrix = m_matrix * Gfx::rotation_matrix<double>(Vector3<double> { 0.0, 0.0, 1.0 }, AK::to_radians(rot_z.value()));-- // 6. Post-multiply a rotation transformation on the current matrix around the vector 0, 1, 0 by the specified rotation rotY in degrees. The 3D rotation matrix is described in CSS Transforms with alpha = rotY in degrees. [CSS3-TRANSFORMS]- m_matrix = m_matrix * Gfx::rotation_matrix<double>(Vector3<double> { 0.0, 1.0, 0.0 }, AK::to_radians(rot_y.value()));-- // 7. Post-multiply a rotation transformation on the current matrix around the vector 1, 0, 0 by the specified rotation rotX in degrees. The 3D rotation matrix is described in CSS Transforms with alpha = rotX in degrees. [CSS3-TRANSFORMS]- m_matrix = m_matrix * Gfx::rotation_matrix<double>(Vector3<double> { 1.0, 0.0, 0.0 }, AK::to_radians(rot_x.value()));-- // 8. Return the current matrix.- return *this;-}--GC::Ref<DOMMatrix> DOMMatrix::rotate_from_vector_self(Optional<double> x, Optional<double> y)-{- // 1. Post-multiply a rotation transformation on the current matrix.- // The rotation angle is determined by the angle between the vector (1,0)T and (x,y)T in the clockwise direction. If x and y should both be 0 or -0, the angle is specified as 0.- double angle = (x == 0 || x == -0) && (y == 0 || y == -0) ? 0.0 : atan2(y.value_or(0), x.value_or(0));-- // The 2D rotation matrix is described in CSS Transforms where alpha is the angle between the vector (1,0)T and (x,y)T in degrees. [CSS3-TRANSFORMS]- m_matrix = m_matrix * Gfx::rotation_matrix<double>(Vector3<double> { 0.0, 0.0, 1.0 }, angle);-- // 2. Return the current matrix.- return *this;-}--GC::Ref<DOMMatrix> DOMMatrix::rotate_axis_angle_self(Optional<double> x, Optional<double> y, Optional<double> z, Optional<double> angle)-{- // 1. Post-multiply a rotation transformation on the current matrix around the specified vector x, y, z by the specified rotation angle in degrees. The 3D rotation matrix is described in CSS Transforms with alpha = angle in degrees. [CSS3-TRANSFORMS]- auto axis = Vector3<double> { x.value_or(0), y.value_or(0), z.value_or(0) };- // https://drafts.csswg.org/css-transforms-2/#funcdef-rotate3d- // "A direction vector that cannot be normalized, such as [0,0,0], will cause the rotation to not be applied."- if (axis.length() != 0)- m_matrix = m_matrix * Gfx::rotation_matrix<double>(axis.normalized(), AK::to_radians(angle.value()));-- // 2. If x or y are not 0 or -0, set is 2D of the current matrix to false.- if ((x != 0 && x != -0) || (y != 0 && y != -0))- m_is_2d = false;-- // 3. Return the current matrix.- return *this;+ return create(double_matrix, Gfx::is_2d_affine_transform(matrix));}-// https://drafts.fxtf.org/geometry/#dom-dommatrix-skewxself-GC::Ref<DOMMatrix> DOMMatrix::skew_x_self(double sx)+GC::Ref<DOMMatrix> DOMMatrix::create_from_dom_matrix_read_only(DOMMatrixReadOnly const& matrix){- // 1. Post-multiply a skewX transformation on the current matrix by the specified angle sx in degrees. The 2D skewX matrix is described in CSS Transforms with alpha = sx in degrees. [CSS3-TRANSFORMS]- Gfx::DoubleMatrix4x4 skew_matrix = {- 1, tan(AK::to_radians(sx)), 0, 0,- 0, 1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1- };- m_matrix = m_matrix * skew_matrix;-- // 3. Return the current matrix.- return *this;+ return GC::Ref { *static_cast<DOMMatrix*>(web_dom_matrix_create_from_read_only(JS::HostABI::vm_to_abi(JS::VM::the()), &matrix)) };}-// https://drafts.fxtf.org/geometry/#dom-dommatrix-skewyself-GC::Ref<DOMMatrix> DOMMatrix::skew_y_self(double sy)+void DOMMatrix::multiply_self(DOMMatrixReadOnly const& other){- // 1. Post-multiply a skewX transformation on the current matrix by the specified angle sy in degrees. The 2D skewY matrix is described in CSS Transforms with beta = sy in degrees. [CSS3-TRANSFORMS]- Gfx::DoubleMatrix4x4 skew_matrix = {- 1, 0, 0, 0,- tan(AK::to_radians(sy)), 1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1- };- m_matrix = m_matrix * skew_matrix;-- // 3. Return the current matrix.- return *this;+ web_dom_matrix_multiply_self(this, &other);}-// https://drafts.fxtf.org/geometry/#dom-dommatrix-invertself-GC::Ref<DOMMatrix> DOMMatrix::invert_self()+void DOMMatrix::rotate_axis_angle_self(double x, double y, double z, double angle){- // 1. Invert the current matrix.- auto inverse = m_matrix.inverse();- if (inverse.has_value()) {- m_matrix = inverse.release_value();- } else {- // 2. If the current matrix is not invertible set all attributes to NaN and set is 2D to false.- for (u8 i = 0; i < 4; i++) {- for (u8 j = 0; j < 4; j++)- m_matrix[j, i] = NAN;- }- m_is_2d = false;- }-- // 3. Return the current matrix.- return *this;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrix-setmatrixvalue-WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> DOMMatrix::set_matrix_value(Utf16String const& transform_list)-{- // 1. Parse transformList into an abstract matrix, and let matrix and 2dTransform be the result. If the result is failure, then throw a "SyntaxError" DOMException.- auto transform_list_utf8 = transform_list.to_utf8();- auto result = TRY(parse_dom_matrix_init_string(transform_list_utf8));-- // 2. Set is 2D to the value of 2dTransform.- m_is_2d = result.is_2d_transform;-- // 3. Set m11 element through m44 element to the element values of matrix in column-major order.- m_matrix = result.matrix;-- // 4. Return the current matrix.- return GC::Ref<DOMMatrix>(*this);+ web_dom_matrix_rotate_axis_angle_self(this, x, y, z, angle);}}diff --git a/Libraries/LibWeb/Geometry/DOMMatrix.h b/Libraries/LibWeb/Geometry/DOMMatrix.hindex 35c03c5c367..2535e23ca79 100644--- a/Libraries/LibWeb/Geometry/DOMMatrix.h+++ b/Libraries/LibWeb/Geometry/DOMMatrix.h@@ -7,83 +7,36 @@#pragma once+#include <LibGfx/Matrix4x4.h>+#include <LibWeb/Bindings/DOMMatrix.h>#include <LibWeb/Geometry/DOMMatrixReadOnly.h>-#include <LibWeb/WebIDL/Buffers.h>namespace Web::Geometry {// https://drafts.fxtf.org/geometry/#dommatrix-class WEB_API DOMMatrix : public DOMMatrixReadOnly {- WEB_WRAPPABLE(DOMMatrix, DOMMatrixReadOnly);- GC_DECLARE_ALLOCATOR(DOMMatrix);+// The C++ side of a DOMMatrix, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/geometry): what CSS+// Typed OM and SVG create and transform.+class WEB_API DOMMatrix final : public DOMMatrixReadOnly {+ WEB_RUST_INTERFACE(DOMMatrix, dom_matrix)public:- static WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> create_from_constructor(Optional<Variant<Utf16String, Vector<double>>> const& init, DOMMatrixStringContext);- static GC::Ref<DOMMatrix> create_from_dom_matrix_2d_init(DOMMatrix2DInit const& init);- static GC::Ref<DOMMatrix> create_from_dom_matrix_init(DOMMatrixInit const& init);- static GC::Ref<DOMMatrix> create_from_dom_matrix_read_only(DOMMatrixReadOnly const& read_only_matrix);- static GC::Ref<DOMMatrix> create(Gfx::FloatMatrix4x4 const&);- static GC::Ref<DOMMatrix> create(Gfx::DoubleMatrix4x4 const&);+ // A new identity matrix, which is 2D.static GC::Ref<DOMMatrix> create();- static WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> create_for_constructor(JS::Object&, Optional<Variant<Utf16String, Vector<double>>> const& init);- static WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> from_matrix(Bindings::DOMMatrixInit&);-- virtual ~DOMMatrix() override;-- static WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> from_float32_array(GC::Root<JS::Float32Array> const&);- static WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> from_float64_array(GC::Root<JS::Float64Array> const&);- void set_m11(double value);- void set_m12(double value);- void set_m13(double value);- void set_m14(double value);- void set_m21(double value);- void set_m22(double value);- void set_m23(double value);- void set_m24(double value);- void set_m31(double value);- void set_m32(double value);- void set_m33(double value);- void set_m34(double value);- void set_m41(double value);- void set_m42(double value);- void set_m43(double value);- void set_m44(double value);+ // A new matrix with the elements of the matrix, whose is 2D is the value.+ static GC::Ref<DOMMatrix> create(Gfx::DoubleMatrix4x4 const&, bool is_2d);- void set_a(double value);- void set_b(double value);- void set_c(double value);- void set_d(double value);- void set_e(double value);- void set_f(double value);-- GC::Ref<DOMMatrix> multiply_self(GC::Ref<DOMMatrix>);- WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> multiply_self(Bindings::DOMMatrixInit&);- GC::Ref<DOMMatrix> pre_multiply_self(GC::Ref<DOMMatrix>);- WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> pre_multiply_self(Bindings::DOMMatrixInit&);- GC::Ref<DOMMatrix> translate_self(Optional<double> tx, Optional<double> ty, Optional<double> tz);- GC::Ref<DOMMatrix> scale_self(Optional<double> scale_x, Optional<double> scale_y, Optional<double> scale_z, Optional<double> origin_x, Optional<double> origin_y, Optional<double> origin_z);- GC::Ref<DOMMatrix> scale3d_self(Optional<double> scale, Optional<double> origin_x, Optional<double> origin_y, Optional<double> origin_z);- GC::Ref<DOMMatrix> rotate_self(Optional<double> rot_x, Optional<double> rot_y, Optional<double> rot_z);- GC::Ref<DOMMatrix> rotate_from_vector_self(Optional<double> x, Optional<double> y);- GC::Ref<DOMMatrix> rotate_axis_angle_self(Optional<double> x, Optional<double> y, Optional<double> z, Optional<double> angle);- GC::Ref<DOMMatrix> skew_x_self(double sx = 0);- GC::Ref<DOMMatrix> skew_y_self(double sy = 0);- GC::Ref<DOMMatrix> invert_self();+ // A new matrix with the elements of the matrix, which is 2D if the matrix is a 2D affine transform.+ static GC::Ref<DOMMatrix> create(Gfx::FloatMatrix4x4 const&);- WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> set_matrix_value(Utf16String const& transform_list);+ // A new matrix initialized to the values of the matrix.+ static GC::Ref<DOMMatrix> create_from_dom_matrix_read_only(DOMMatrixReadOnly const&);-private:- DOMMatrix(double m11, double m12, double m21, double m22, double m41, double m42);- DOMMatrix(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double m41, double m42, double m43, double m44);- explicit DOMMatrix(DOMMatrixReadOnly const& read_only_matrix);- DOMMatrix();+ // Post-multiplies the other matrix to this one, https://drafts.fxtf.org/geometry/#dom-dommatrix-multiplyself+ void multiply_self(DOMMatrixReadOnly const&);- template<typename T>- explicit DOMMatrix(Gfx::Matrix4x4<T> const& matrix)- : DOMMatrixReadOnly(matrix)- {- }+ // https://drafts.fxtf.org/geometry/#dom-dommatrix-rotateaxisangleself+ void rotate_axis_angle_self(double x, double y, double z, double angle);};}diff --git a/Libraries/LibWeb/Geometry/DOMMatrix.idl b/Libraries/LibWeb/Geometry/DOMMatrix.idlindex 91920451bc9..a979fc01665 100644--- a/Libraries/LibWeb/Geometry/DOMMatrix.idl+++ b/Libraries/LibWeb/Geometry/DOMMatrix.idl@@ -1,5 +1,5 @@// https://drafts.fxtf.org/geometry/#dommatrix-[Exposed=(Window,Worker), Serializable, LegacyWindowAlias=(SVGMatrix, WebKitCSSMatrix)]+[Exposed=(Window,Worker), Serializable, LegacyWindowAlias=(SVGMatrix, WebKitCSSMatrix), ImplementedIn=Rust]interface DOMMatrix : DOMMatrixReadOnly {constructor(optional (DOMString or sequence<unrestricted double>) init);diff --git a/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.cpp b/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.cppindex 8f71fff9967..c82d2f66334 100644--- a/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.cpp+++ b/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.cpp@@ -6,961 +6,87 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/TypeCasts.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/TypedArray.h>-#include <LibJS/Runtime/VM.h>-#include <LibWeb/Bindings/DOMMatrixReadOnly.h>-#include <LibWeb/Bindings/DOMPointReadOnly.h>+#include <LibJS/HostClassBuilder.h>#include <LibWeb/CSS/Parser/Parser.h>#include <LibWeb/CSS/PropertyID.h>#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>-#include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>#include <LibWeb/ComputedValuesRustFFI.h>-#include <LibWeb/Geometry/DOMMatrix.h>#include <LibWeb/Geometry/DOMMatrixReadOnly.h>-#include <LibWeb/Geometry/DOMPoint.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/ExceptionOr.h>+#include <LibWeb/WebIDL/DOMException.h>namespace Web::Geometry {-GC_DEFINE_ALLOCATOR(DOMMatrixReadOnly);+extern "C" {-DOMMatrixStringContext dom_matrix_string_context(JS::Object& relevant_global_object)-{- auto& global_scope = HTML::relevant_window_or_worker_global_scope(relevant_global_object);- return is<HTML::Window>(global_scope.this_impl())- ? DOMMatrixStringContext::Window- : DOMMatrixStringContext::Worker;-}--// https://drafts.fxtf.org/geometry/#matrix-validate-and-fixup-2d-WebIDL::ExceptionOr<DOMMatrix2DInit> validate_and_fixup_dom_matrix_2d_init(Bindings::DOMMatrix2DInit const& init)-{- // 1. If at least one of the following conditions are true for dict, then throw a TypeError exception and abort these steps.- // - a and m11 are both present and SameValueZero(a, m11) is false.- if (init.a.has_value() && init.m11.has_value() && !JS::same_value_zero(JS::Value(init.a.value()), JS::Value(init.m11.value())))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "DOMMatrix2DInit.a and DOMMatrix2DInit.m11 must have the same value if they are both present"_utf16 };-- // - b and m12 are both present and SameValueZero(b, m12) is false.- if (init.b.has_value() && init.m12.has_value() && !JS::same_value_zero(JS::Value(init.b.value()), JS::Value(init.m12.value())))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "DOMMatrix2DInit.b and DOMMatrix2DInit.m12 must have the same value if they are both present"_utf16 };-- // - c and m21 are both present and SameValueZero(c, m21) is false.- if (init.c.has_value() && init.m21.has_value() && !JS::same_value_zero(JS::Value(init.c.value()), JS::Value(init.m21.value())))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "DOMMatrix2DInit.c and DOMMatrix2DInit.m21 must have the same value if they are both present"_utf16 };-- // - d and m22 are both present and SameValueZero(d, m22) is false.- if (init.d.has_value() && init.m22.has_value() && !JS::same_value_zero(JS::Value(init.d.value()), JS::Value(init.m22.value())))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "DOMMatrix2DInit.d and DOMMatrix2DInit.m22 must have the same value if they are both present"_utf16 };-- // - e and m41 are both present and SameValueZero(e, m41) is false.- if (init.e.has_value() && init.m41.has_value() && !JS::same_value_zero(JS::Value(init.e.value()), JS::Value(init.m41.value())))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "DOMMatrix2DInit.e and DOMMatrix2DInit.m41 must have the same value if they are both present"_utf16 };-- // - f and m42 are both present and SameValueZero(f, m42) is false.- if (init.f.has_value() && init.m42.has_value() && !JS::same_value_zero(JS::Value(init.f.value()), JS::Value(init.m42.value())))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "DOMMatrix2DInit.f and DOMMatrix2DInit.m42 must have the same value if they are both present"_utf16 };+// Defined in Bindings/Rust/src/geometry/exports.rs.+void web_dom_matrix_read_only_elements(void const* matrix, Array<double, 16>* out_elements);+bool web_dom_matrix_read_only_is_2d(void const* matrix);+bool web_dom_matrix_read_only_to_string(void const* matrix, FlatPtr* out_string);- return DOMMatrix2DInit {- .m11 = init.m11.value_or(init.a.value_or(1.0)),- .m12 = init.m12.value_or(init.b.value_or(0.0)),- .m21 = init.m21.value_or(init.c.value_or(0.0)),- .m22 = init.m22.value_or(init.d.value_or(1.0)),- .m41 = init.m41.value_or(init.e.value_or(0.0)),- .m42 = init.m42.value_or(init.f.value_or(0.0)),- };-}+// What Bindings/Rust/src/geometry/dom_matrix_read_only.rs asks of LibWeb.+bool web_dom_matrix_parse_transform_list(FlatPtr transform_list, Array<double, 16>* out_elements, bool* out_is_2d);-// https://drafts.fxtf.org/geometry/#matrix-validate-and-fixup-WebIDL::ExceptionOr<DOMMatrixInit> validate_and_fixup_dom_matrix_init(Bindings::DOMMatrixInit const& init)+// https://drafts.fxtf.org/geometry/#parse-a-string-into-an-abstract-matrix, which stores the elements m11, m12, m13,+// m14, m21, ..., m44 of the matrix, in that order, and 2dTransform, or returns false for failure.+bool web_dom_matrix_parse_transform_list(FlatPtr transform_list_raw, Array<double, 16>* out_elements, bool* out_is_2d){- // 1. Validate and fixup (2D) dict.- auto fixed_2d = TRY(validate_and_fixup_dom_matrix_2d_init(init));-- auto is_2d = init.is2d;-- // 2. If is2D is true and: at least one of m13, m14, m23, m24, m31, m32, m34, m43 are present with a value other than 0 or -0,- // or at least one of m33, m44 are present with a value other than 1, then throw a TypeError exception and abort these steps.- if (is_2d.has_value() && is_2d.value()) {- if ((init.m13 != 0.0 && init.m13 != -0.0)- || (init.m14 != 0.0 && init.m14 != -0.0)- || (init.m23 != 0.0 && init.m23 != -0.0)- || (init.m24 != 0.0 && init.m24 != -0.0)- || (init.m31 != 0.0 && init.m31 != -0.0)- || (init.m32 != 0.0 && init.m32 != -0.0)- || (init.m34 != 0.0 && init.m34 != -0.0)- || (init.m43 != 0.0 && init.m43 != -0.0)- || init.m33 != 1.0- || init.m44 != 1.0) {- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "DOMMatrixInit.is2D is true, but the given matrix is not a 2D matrix"_utf16 };- }- }-- // If is2D is not present and at least one of m13, m14, m23, m24, m31, m32, m34, m43 are present with a value other than 0 or -0,- // or at least one of m33, m44 are present with a value other than 1, set is2D to false.- if (!is_2d.has_value()) {- if ((init.m13 != 0.0 && init.m13 != -0.0)- || (init.m14 != 0.0 && init.m14 != -0.0)- || (init.m23 != 0.0 && init.m23 != -0.0)- || (init.m24 != 0.0 && init.m24 != -0.0)- || (init.m31 != 0.0 && init.m31 != -0.0)- || (init.m32 != 0.0 && init.m32 != -0.0)- || (init.m34 != 0.0 && init.m34 != -0.0)- || (init.m43 != 0.0 && init.m43 != -0.0)- || init.m33 != 1.0- || init.m44 != 1.0) {- is_2d = false;- }- }-- // 4. If is2D is still not present, set it to true.- if (!is_2d.has_value())- is_2d = true;-- return DOMMatrixInit {- { fixed_2d },- init.m13,- init.m14,- init.m23,- init.m24,- init.m31,- init.m32,- init.m33,- init.m34,- init.m43,- init.m44,- is_2d.value(),- };-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-dommatrixreadonly-WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> DOMMatrixReadOnly::create_from_constructor(Optional<Variant<Utf16String, Vector<double>>> const& init, DOMMatrixStringContext string_context)-{- // -> If init is omitted- if (!init.has_value()) {- // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with the sequence [1, 0, 0, 1, 0, 0].- return GC::Heap::the().allocate<DOMMatrixReadOnly>(1, 0, 0, 1, 0, 0);- }-- auto const& init_value = init.value();-- // -> If init is a DOMString- if (init_value.has<Utf16String>()) {- // 1. If current global object is not a Window object, then throw a TypeError exception.- if (string_context != DOMMatrixStringContext::Window)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "This can only be used in a Window context"_utf16 };-- // 2. Parse init into an abstract matrix, and let matrix and 2dTransform be the result. If the result is failure, then throw a "SyntaxError" DOMException.- auto transform_list = init_value.get<Utf16String>().to_utf8();- auto result = TRY(parse_dom_matrix_init_string(transform_list));- auto& m = result.matrix;-- // If 2dTransform is true- if (result.is_2d_transform) {- // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers, the values being the elements m11, m12, m21, m22, m41 and m42 of matrix.- return GC::Heap::the().allocate<DOMMatrixReadOnly>(m[0, 0], m[1, 0], m[0, 1], m[1, 1], m[0, 3], m[1, 3]);- }-- // Otherwise, return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers, the values being the 16 elements of matrix.- return GC::Heap::the().allocate<DOMMatrixReadOnly>(- m[0, 0], m[1, 0], m[2, 0], m[3, 0],- m[0, 1], m[1, 1], m[2, 1], m[3, 1],- m[0, 2], m[1, 2], m[2, 2], m[3, 2],- m[0, 3], m[1, 3], m[2, 3], m[3, 3]);- }-- auto const& double_sequence = init_value.get<Vector<double>>();-- // -> If init is a sequence with 6 elements- if (double_sequence.size() == 6) {- // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with the sequence init.- return GC::Heap::the().allocate<DOMMatrixReadOnly>(double_sequence[0], double_sequence[1], double_sequence[2], double_sequence[3], double_sequence[4], double_sequence[5]);- }-- // -> If init is a sequence with 16 elements- if (double_sequence.size() == 16) {- // Return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with the sequence init.- return GC::Heap::the().allocate<DOMMatrixReadOnly>(- double_sequence[0], double_sequence[1], double_sequence[2], double_sequence[3],- double_sequence[4], double_sequence[5], double_sequence[6], double_sequence[7],- double_sequence[8], double_sequence[9], double_sequence[10], double_sequence[11],- double_sequence[12], double_sequence[13], double_sequence[14], double_sequence[15]);- }-- // -> Otherwise, throw a TypeError exception.- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Sequence must contain exactly 6 or 16 elements, got {} element(s)", double_sequence.size()) };-}--WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> DOMMatrixReadOnly::create_for_constructor(JS::Object& relevant_global_object, Optional<Variant<Utf16String, Vector<double>>> const& init)-{- return create_from_constructor(init, dom_matrix_string_context(relevant_global_object));-}--// https://drafts.fxtf.org/geometry/#create-a-dommatrixreadonly-from-the-2d-dictionary-GC::Ref<DOMMatrixReadOnly> DOMMatrixReadOnly::create_from_dom_matrix_2d_init(DOMMatrix2DInit const& init)-{- // 2. Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers,- // the values being the 6 elements m11, m12, m21, m22, m41 and m42 of other in the given order.- return GC::Heap::the().allocate<DOMMatrixReadOnly>(init.m11, init.m12, init.m21, init.m22, init.m41, init.m42);-}--// https://drafts.fxtf.org/geometry/#create-a-dommatrixreadonly-from-the-dictionary-GC::Ref<DOMMatrixReadOnly> DOMMatrixReadOnly::create_from_dom_matrix_init(DOMMatrixInit const& init)-{- // 2. If the is2D dictionary member of other is true.- if (init.is_2d) {- // Return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers, the values being the 6 elements m11, m12, m21, m22, m41 and m42 of other in the given order.- return GC::Heap::the().allocate<DOMMatrixReadOnly>(init.m11, init.m12, init.m21, init.m22, init.m41, init.m42);- }-- // Otherwise, Return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers, the values being the 16 elements m11, m12, m13, ..., m44 of other in the given order.- return GC::Heap::the().allocate<DOMMatrixReadOnly>(init.m11, init.m12, init.m13, init.m14,- init.m21, init.m22, init.m23, init.m24,- init.m31, init.m32, init.m33, init.m34,- init.m41, init.m42, init.m43, init.m44);-}--WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> DOMMatrixReadOnly::from_matrix(Bindings::DOMMatrixInit& other)-{- return create_from_dom_matrix_init(TRY(validate_and_fixup_dom_matrix_init(other)));-}--GC::Ref<DOMMatrixReadOnly> DOMMatrixReadOnly::create(Gfx::FloatMatrix4x4 const& matrix)-{- return GC::Heap::the().allocate<DOMMatrixReadOnly>(matrix);-}--GC::Ref<DOMMatrixReadOnly> DOMMatrixReadOnly::create(Gfx::DoubleMatrix4x4 const& matrix)-{- return GC::Heap::the().allocate<DOMMatrixReadOnly>(matrix);-}--GC::Ref<DOMMatrixReadOnly> DOMMatrixReadOnly::create()-{- return GC::Heap::the().allocate<DOMMatrixReadOnly>();-}--DOMMatrixReadOnly::DOMMatrixReadOnly(double m11, double m12, double m21, double m22, double m41, double m42)-{- initialize_from_create_2d_matrix(m11, m12, m21, m22, m41, m42);-}--DOMMatrixReadOnly::DOMMatrixReadOnly(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double m41, double m42, double m43, double m44)-{- initialize_from_create_3d_matrix(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44);-}--DOMMatrixReadOnly::DOMMatrixReadOnly(DOMMatrixReadOnly const& other)- : m_matrix(other.m_matrix)- , m_is_2d(other.m_is_2d)-{-}--DOMMatrixReadOnly::DOMMatrixReadOnly()-{-}+ auto transform_list = Utf16String::from_raw(transform_list_raw).to_utf8();-DOMMatrixReadOnly::~DOMMatrixReadOnly() = default;--// https://drafts.fxtf.org/geometry/#create-a-2d-matrix-void DOMMatrixReadOnly::initialize_from_create_2d_matrix(double m11, double m12, double m21, double m22, double m41, double m42)-{- // NOTE: The matrix used in the spec is column-major (https://drafts.fxtf.org/geometry/#4x4-abstract-matrix) but Gfx::Matrix4x4 is row-major so we need to transpose the values.-- // 1. Let matrix be a new instance of type.- // 2. Set m11 element, m12 element, m21 element, m22 element, m41 element and m42 element to the values of init in order starting with the first value.- m_matrix[0, 0] = m11;- m_matrix[1, 0] = m12;- m_matrix[0, 1] = m21;- m_matrix[1, 1] = m22;- m_matrix[0, 3] = m41;- m_matrix[1, 3] = m42;-- // 3. Set m13 element, m14 element, m23 element, m24 element, m31 element, m32 element, m34 element, and m43 element to 0.- m_matrix[2, 0] = 0.0;- m_matrix[3, 0] = 0.0;- m_matrix[2, 1] = 0.0;- m_matrix[3, 1] = 0.0;- m_matrix[0, 2] = 0.0;- m_matrix[1, 2] = 0.0;- m_matrix[3, 2] = 0.0;- m_matrix[2, 3] = 0.0;-- // 4. Set m33 element and m44 element to 1.- m_matrix[2, 2] = 1.0;- m_matrix[3, 3] = 1.0;-- // 5. Set is 2D to true.- m_is_2d = true;-- // 6. Return matrix-}--// https://drafts.fxtf.org/geometry/#create-a-3d-matrix-void DOMMatrixReadOnly::initialize_from_create_3d_matrix(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double m41, double m42, double m43, double m44)-{- // NOTE: The matrix used in the spec is column-major (https://drafts.fxtf.org/geometry/#4x4-abstract-matrix) but Gfx::Matrix4x4 is row-major so we need to transpose the values.-- // 1. Let matrix be a new instance of type.- // 2. Set m11 element to m44 element to the values of init in column-major order.- m_matrix[0, 0] = m11;- m_matrix[1, 0] = m12;- m_matrix[2, 0] = m13;- m_matrix[3, 0] = m14;- m_matrix[0, 1] = m21;- m_matrix[1, 1] = m22;- m_matrix[2, 1] = m23;- m_matrix[3, 1] = m24;- m_matrix[0, 2] = m31;- m_matrix[1, 2] = m32;- m_matrix[2, 2] = m33;- m_matrix[3, 2] = m34;- m_matrix[0, 3] = m41;- m_matrix[1, 3] = m42;- m_matrix[2, 3] = m43;- m_matrix[3, 3] = m44;-- // 3. Set is 2D to false.- m_is_2d = false;-- // 4. Return matrix-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-fromfloat32array-WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> DOMMatrixReadOnly::from_float32_array(GC::Root<JS::Float32Array> const& array)-{- ReadonlySpan<float> elements { reinterpret_cast<float const*>(array->viewed_array_buffer()->data_at(array->byte_offset())), array->byte_length().length() / sizeof(float) };-- // If array32 has 6 elements, return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers taking the values from array32 in the provided order.- if (elements.size() == 6)- return GC::Heap::the().allocate<DOMMatrixReadOnly>(elements.at(0), elements.at(1), elements.at(2), elements.at(3), elements.at(4), elements.at(5));-- // If array32 has 16 elements, return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers taking the values from array32 in the provided order.- if (elements.size() == 16)- return GC::Heap::the().allocate<DOMMatrixReadOnly>(elements.at(0), elements.at(1), elements.at(2), elements.at(3),- elements.at(4), elements.at(5), elements.at(6), elements.at(7),- elements.at(8), elements.at(9), elements.at(10), elements.at(11),- elements.at(12), elements.at(13), elements.at(14), elements.at(15));- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Sequence must contain exactly 6 or 16 elements"_utf16 };-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-fromfloat64array-WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> DOMMatrixReadOnly::from_float64_array(GC::Root<JS::Float64Array> const& array)-{- ReadonlySpan<double> elements { reinterpret_cast<double const*>(array->viewed_array_buffer()->data_at(array->byte_offset())), array->byte_length().length() / sizeof(double) };-- // If array64 has 6 elements, return the result of invoking create a 2d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers taking the values from array64 in the provided order.- if (elements.size() == 6)- return GC::Heap::the().allocate<DOMMatrixReadOnly>(elements.at(0), elements.at(1), elements.at(2), elements.at(3), elements.at(4), elements.at(5));-- // If array64 has 16 elements, return the result of invoking create a 3d matrix of type DOMMatrixReadOnly or DOMMatrix as appropriate, with a sequence of numbers taking the values from array64 in the provided order.- if (elements.size() == 16)- return GC::Heap::the().allocate<DOMMatrixReadOnly>(elements.at(0), elements.at(1), elements.at(2), elements.at(3),- elements.at(4), elements.at(5), elements.at(6), elements.at(7),- elements.at(8), elements.at(9), elements.at(10), elements.at(11),- elements.at(12), elements.at(13), elements.at(14), elements.at(15));- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Sequence must contain exactly 6 or 16 elements"_utf16 };-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-isidentity-bool DOMMatrixReadOnly::is_identity() const-{- // The isIdentity attribute must return true if- // m12 element, m13 element, m14 element,- // m21 element, m23 element, m24 element,- // m31 element, m32 element, m34 element- // m41 element, m42 element, m43 element- // are 0 or -0 and- // m11 element, m22 element, m33 element, m44 element are 1.- // Otherwise it must return false.- if (m12() != 0.0 && m12() != -0.0)- return false;-- if (m13() != 0.0 && m13() != -0.0)- return false;-- if (m14() != 0.0 && m14() != -0.0)- return false;-- if (m21() != 0.0 && m21() != -0.0)- return false;-- if (m23() != 0.0 && m24() != -0.0)- return false;-- if (m31() != 0.0 && m32() != -0.0)- return false;-- if (m34() != 0.0 && m34() != -0.0)- return false;-- if (m41() != 0.0 && m42() != -0.0)- return false;-- if (m43() != 0.0 && m43() != -0.0)- return false;-- if (m11() != 1.0)- return false;-- if (m22() != 1.0)- return false;+ // 1. If transformList is the empty string, set it to the string "matrix(1, 0, 0, 1, 0, 0)".+ if (transform_list.is_empty())+ transform_list = "matrix(1, 0, 0, 1, 0, 0)"_string;- if (m33() != 1.0)+ // 2. Parse transformList into parsedValue given the grammar for the CSS transform property. The result will be a+ // <transform-list>, the keyword none, or failure. If parsedValue is failure, or any <transform-function> has+ // <length> values without absolute length units, or any keyword other than none is used, then return failure.+ // [CSS3-SYNTAX] [CSS3-TRANSFORMS]+ CSS::Parser::ParsingParams parsing_params {};+ parsing_params.value_context = { CSS::Parser::SpecialContext::DOMMatrixInitString };+ auto transform_style_value = parse_css_value(parsing_params, transform_list, CSS::PropertyID::Transform);+ if (!transform_style_value || (transform_style_value->is_keyword() && transform_style_value->to_keyword() != CSS::Keyword::None) || transform_style_value->is_unresolved())return false;- if (m44() != 1.0)+ // 3. If parsedValue is none, set parsedValue to a <transform-list> containing a single identity matrix.+ // 4. Let 2dTransform track the 2D/3D dimension status of parsedValue.+ // 5. Transform all <transform-function>s to 4x4 abstract matrices by following the “Mathematical Description of+ // Transform Functions”. [CSS3-TRANSFORMS]+ // 6. Let matrix be a 4x4 abstract matrix as shown in the initial figure of this section. Post-multiply all+ // matrices from left to right and set matrix to this product.+ // NB: A <length> without an absolute unit is a failure as well, which Rust reports when it cannot resolve a function.+ Array<float, 16> matrix;+ bool is_2d_transform = true;+ if (!CSS::ComputedValuesFFI::rust_transform_list_to_abstract_matrix(transform_style_value->rust_style_value_data(), matrix.data(), &is_2d_transform))return false;+ // 7. Return matrix and 2dTransform.+ // NB: The matrix is row by row, so its element mRC is in row C and column R.+ for (size_t row = 0; row < 4; ++row) {+ for (size_t column = 0; column < 4; ++column)+ (*out_elements)[(column * 4) + row] = matrix[(row * 4) + column];+ }+ *out_is_2d = is_2d_transform;return true;}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-translate-GC::Ref<DOMMatrix> DOMMatrixReadOnly::translate(Optional<double> const& tx, Optional<double> const& ty, Optional<double> const& tz) const-{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Perform a translateSelf() transformation on result with the arguments tx, ty, tz.- // 3. Return result.- return result->translate_self(tx, ty, tz);}-// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-scale-GC::Ref<DOMMatrix> DOMMatrixReadOnly::scale(Optional<double> scale_x, Optional<double> scale_y, Optional<double> scale_z, Optional<double> origin_x, Optional<double> origin_y, Optional<double> origin_z)+Array<double, 16> DOMMatrixReadOnly::elements() const{- // 1. If scaleY is missing, set scaleY to the value of scaleX.- if (!scale_y.has_value())- scale_y = scale_x;-- // 2. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 3. Perform a scaleSelf() transformation on result with the arguments scaleX, scaleY, scaleZ, originX, originY, originZ.- // 4. Return result.- return result->scale_self(scale_x, scale_y, scale_z, origin_x, origin_y, origin_z);+ Array<double, 16> elements;+ web_dom_matrix_read_only_elements(this, &elements);+ return elements;}-// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-scalenonuniform-GC::Ref<DOMMatrix> DOMMatrixReadOnly::scale_non_uniform(Optional<double> scale_x, Optional<double> scale_y)+bool DOMMatrixReadOnly::is2d() const{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Perform a scaleSelf() transformation on result with the arguments scaleX, scaleY, 1, 0, 0, 0.- // 3. Return result.- return result->scale_self(scale_x, scale_y, 1, 0, 0, 0);+ return web_dom_matrix_read_only_is_2d(this);}-// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-scale3d-GC::Ref<DOMMatrix> DOMMatrixReadOnly::scale3d(Optional<double> scale, Optional<double> origin_x, Optional<double> origin_y, Optional<double> origin_z)+WebIDL::ExceptionOr<Utf16String> DOMMatrixReadOnly::to_string() const{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Perform a scale3dSelf() transformation on result with the arguments scale, originX, originY, originZ.- // 3. Return result.- return result->scale3d_self(scale, origin_x, origin_y, origin_z);-}--GC::Ref<DOMMatrix> DOMMatrixReadOnly::rotate(Optional<double> rot_x, Optional<double> rot_y, Optional<double> rot_z)-{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Perform a rotateSelf() transformation on result with the arguments rotX, rotY, rotZ.- // 3. Return result.- return result->rotate_self(rot_x, rot_y, rot_z);-}--GC::Ref<DOMMatrix> DOMMatrixReadOnly::rotate_from_vector(Optional<double> x, Optional<double> y)-{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Perform a rotateFromVectorSelf() transformation on result with the arguments x, y.- // 3. Return result.- return result->rotate_from_vector_self(x, y);-}--GC::Ref<DOMMatrix> DOMMatrixReadOnly::rotate_axis_angle(Optional<double> x, Optional<double> y, Optional<double> z, Optional<double> angle)-{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Perform a rotateAxisAngleSelf() transformation on result with the arguments x, y, z, angle.- // 3. Return result.- return result->rotate_axis_angle_self(x, y, z, angle);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-skewx-GC::Ref<DOMMatrix> DOMMatrixReadOnly::skew_x(double sx) const-{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Perform a skewXSelf() transformation on result with the argument sx.- // 3. Return result.- return result->skew_x_self(sx);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-skewy-GC::Ref<DOMMatrix> DOMMatrixReadOnly::skew_y(double sy) const-{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Perform a skewYSelf() transformation on result with the argument sy.- // 3. Return result.- return result->skew_y_self(sy);-}--WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> DOMMatrixReadOnly::multiply(Bindings::DOMMatrixInit& other) const-{- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);- auto other_object = DOMMatrix::create_from_dom_matrix_init(TRY(validate_and_fixup_dom_matrix_init(other)));- return result->multiply_self(other_object);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-flipx-GC::Ref<DOMMatrix> DOMMatrixReadOnly::flip_x()-{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Post-multiply result with new DOMMatrix([-1, 0, 0, 1, 0, 0]).- Gfx::DoubleMatrix4x4 flip_matrix = {- -1, 0, 0, 0,- 0, 1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1- };- result->m_matrix = result->m_matrix * flip_matrix;-- // 3. Return result.- return result;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-flipy-GC::Ref<DOMMatrix> DOMMatrixReadOnly::flip_y()-{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Post-multiply result with new DOMMatrix([1, 0, 0, -1, 0, 0]).- Gfx::DoubleMatrix4x4 flip_matrix = {- 1, 0, 0, 0,- 0, -1, 0, 0,- 0, 0, 1, 0,- 0, 0, 0, 1- };- result->m_matrix = result->m_matrix * flip_matrix;-- // 3. Return result.- return result;-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-inverse-GC::Ref<DOMMatrix> DOMMatrixReadOnly::inverse() const-{- // 1. Let result be the resulting matrix initialized to the values of the current matrix.- auto result = DOMMatrix::create_from_dom_matrix_read_only(*this);-- // 2. Perform a invertSelf() transformation on result.- // 3. Return result.- // The current matrix is not modified.- return result->invert_self();-}--// https://drafts.fxtf.org/geometry/#transform-a-point-with-a-matrix-GC::Ref<DOMPoint> DOMMatrixReadOnly::transform_point(DOMPointReadOnly const& point) const-{- // 1. Let x be point’s x coordinate.- // 2. Let y be point’s y coordinate.- // 3. Let z be point’s z coordinate.- // 4. Let w be point’s w perspective.- // 5. Let pointVector be a new column vector with the elements being x, y, z, and w, respectively.- Vector4<double> point_vector { point.x(), point.y(), point.z(), point.w() };-- // 6. Set pointVector to pointVector pre-multiplied by matrix.- // This is really a post multiply because of the transposed m_matrix.- point_vector = m_matrix * point_vector;-- // 7. Let transformedPoint be a new DOMPoint object.- // 8. Set transformedPoint’s x coordinate to pointVector’s first element.- // 9. Set transformedPoint’s y coordinate to pointVector’s second element.- // 10. Set transformedPoint’s z coordinate to pointVector’s third element.- // 11. Set transformedPoint’s w perspective to pointVector’s fourth element.- // 12. Return transformedPoint.- return DOMPoint::create(point_vector.x(), point_vector.y(), point_vector.z(), point_vector.w());-}--GC::Ref<DOMPoint> DOMMatrixReadOnly::transform_point(Bindings::DOMPointInit const& point) const-{- auto point_object = DOMPoint::create(point.x, point.y, point.z, point.w);- return transform_point(point_object);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-tofloat32array-GC::Ref<JS::Float32Array> DOMMatrixReadOnly::to_float32_array(JS::Object const& relevant_global_object) const-{- auto& target = HTML::relevant_realm(relevant_global_object);-- // Returns the serialized 16 elements m11 to m44 of the current matrix in column-major order as Float32Array.- float elements[16] = { static_cast<float>(m11()), static_cast<float>(m12()), static_cast<float>(m13()), static_cast<float>(m14()),- static_cast<float>(m21()), static_cast<float>(m22()), static_cast<float>(m23()), static_cast<float>(m24()),- static_cast<float>(m31()), static_cast<float>(m32()), static_cast<float>(m33()), static_cast<float>(m34()),- static_cast<float>(m41()), static_cast<float>(m42()), static_cast<float>(m43()), static_cast<float>(m44()) };- auto bytes = MUST(ByteBuffer::copy(elements, sizeof(elements)));- auto array_buffer = JS::ArrayBuffer::create(target, move(bytes));- return JS::Float32Array::create(target, sizeof(elements) / sizeof(float), array_buffer);-}--// https://drafts.fxtf.org/geometry/#dom-dommatrixreadonly-tofloat64array-GC::Ref<JS::Float64Array> DOMMatrixReadOnly::to_float64_array(JS::Object const& relevant_global_object) const-{- auto& target = HTML::relevant_realm(relevant_global_object);-- // Returns the serialized 16 elements m11 to m44 of the current matrix in column-major order as Float64Array.- double elements[16] = { m11(), m12(), m13(), m14(),- m21(), m22(), m23(), m24(),- m31(), m32(), m33(), m34(),- m41(), m42(), m43(), m44() };- auto bytes = MUST(ByteBuffer::copy(elements, sizeof(elements)));- auto array_buffer = JS::ArrayBuffer::create(target, move(bytes));- return JS::Float64Array::create(target, sizeof(elements) / sizeof(double), array_buffer);-}--// https://drafts.fxtf.org/geometry/#dommatrixreadonly-stringification-behavior-WebIDL::ExceptionOr<String> DOMMatrixReadOnly::to_string() const-{- auto& vm = JS::VM::the();-- // 1. If one or more of m11 element through m44 element are a non-finite value, then throw an "InvalidStateError" DOMException.- // Spec Note: The CSS syntax cannot represent NaN or Infinity values.- if (!isfinite(m11()) || !isfinite(m12()) || !isfinite(m13()) || !isfinite(m14())- || !isfinite(m21()) || !isfinite(m22()) || !isfinite(m23()) || !isfinite(m24())- || !isfinite(m31()) || !isfinite(m32()) || !isfinite(m33()) || !isfinite(m34())- || !isfinite(m41()) || !isfinite(m42()) || !isfinite(m43()) || !isfinite(m44())) {+ FlatPtr string = 0;+ if (!web_dom_matrix_read_only_to_string(this, &string))return WebIDL::InvalidStateError::create("Cannot stringify non-finite matrix values"_utf16);- }-- // 2. Let string be the empty string.- StringBuilder builder;-- // 3. If is 2D is true, then:- if (m_is_2d) {- // 1. Append "matrix(" to string.- TRY_OR_THROW_OOM(vm, builder.try_append("matrix("sv));-- // 2. Append ! ToString(m11 element) to string.- JS::number_to_string(builder, m11());-- // 3. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 4. Append ! ToString(m12 element) to string.- JS::number_to_string(builder, m12());-- // 5. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 6. Append ! ToString(m21 element) to string.- JS::number_to_string(builder, m21());-- // 7. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 8. Append ! ToString(m22 element) to string.- JS::number_to_string(builder, m22());-- // 9. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 10. Append ! ToString(m41 element) to string.- JS::number_to_string(builder, m41());-- // 11. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 12. Append ! ToString(m42 element) to string.- JS::number_to_string(builder, m42());-- // 13. Append ")" to string.- TRY_OR_THROW_OOM(vm, builder.try_append(")"sv));- } else {- // 1. Append "matrix3d(" to string.- TRY_OR_THROW_OOM(vm, builder.try_append("matrix3d("sv));-- // 2. Append ! ToString(m11 element) to string.- JS::number_to_string(builder, m11());-- // 3. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 4. Append ! ToString(m12 element) to string.- JS::number_to_string(builder, m12());-- // 5. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 6. Append ! ToString(m13 element) to string.- JS::number_to_string(builder, m13());-- // 7. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 8. Append ! ToString(m14 element) to string.- JS::number_to_string(builder, m14());-- // 9. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 10. Append ! ToString(m21 element) to string.- JS::number_to_string(builder, m21());-- // 11. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 12. Append ! ToString(m22 element) to string.- JS::number_to_string(builder, m22());-- // 13. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 14. Append ! ToString(m23 element) to string.- JS::number_to_string(builder, m23());-- // 15. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 16. Append ! ToString(m24 element) to string.- JS::number_to_string(builder, m24());-- // 17. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // NOTE: The spec doesn't include the steps to append m31 to m34, but they are required as matrix3d requires 16 elements.- JS::number_to_string(builder, m31());- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));- JS::number_to_string(builder, m32());- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));- JS::number_to_string(builder, m33());- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));- JS::number_to_string(builder, m34());- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 18. Append ! ToString(m41 element) to string.- JS::number_to_string(builder, m41());-- // 19. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 20. Append ! ToString(m42 element) to string.- JS::number_to_string(builder, m42());-- // 21. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 22. Append ! ToString(m43 element) to string.- JS::number_to_string(builder, m43());-- // 23. Append ", " to string.- TRY_OR_THROW_OOM(vm, builder.try_append(", "sv));-- // 24. Append ! ToString(m44 element) to string.- JS::number_to_string(builder, m44());-- // 25. Append ")" to string.- TRY_OR_THROW_OOM(vm, builder.try_append(")"sv));- }-- // 5. Return string.- return TRY_OR_THROW_OOM(vm, builder.to_string());-}--// https://drafts.fxtf.org/geometry/#structured-serialization-WebIDL::ExceptionOr<void> DOMMatrixReadOnly::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool, HTML::SerializationMemory&)-{- serialized.encode(m_is_2d);-- // 1. If value’s is 2D is true:- if (m_is_2d) {- // 1. Set serialized.[[M11]] to value’s m11 element.- serialized.encode(m11());- // 2. Set serialized.[[M12]] to value’s m12 element.- serialized.encode(m12());- // 3. Set serialized.[[M21]] to value’s m21 element.- serialized.encode(m21());- // 4. Set serialized.[[M22]] to value’s m22 element.- serialized.encode(m22());- // 5. Set serialized.[[M41]] to value’s m41 element.- serialized.encode(m41());- // 6. Set serialized.[[M42]] to value’s m42 element.- serialized.encode(m42());- // 7. Set serialized.[[Is2D]] to true.- // NOTE: This is set in the beginning of the function.- }- // 2. Otherwise:- else {- // 1. Set serialized.[[M11]] to value’s m11 element.- serialized.encode(m11());- // 2. Set serialized.[[M12]] to value’s m12 element.- serialized.encode(m12());- // 3. Set serialized.[[M13]] to value’s m13 element.- serialized.encode(m13());- // 4. Set serialized.[[M14]] to value’s m14 element.- serialized.encode(m14());- // 5. Set serialized.[[M21]] to value’s m21 element.- serialized.encode(m21());- // 6. Set serialized.[[M22]] to value’s m22 element.- serialized.encode(m22());- // 7. Set serialized.[[M23]] to value’s m23 element.- serialized.encode(m23());- // 8. Set serialized.[[M24]] to value’s m24 element.- serialized.encode(m24());- // 9. Set serialized.[[M31]] to value’s m31 element.- serialized.encode(m31());- // 10. Set serialized.[[M32]] to value’s m32 element.- serialized.encode(m32());- // 11. Set serialized.[[M33]] to value’s m33 element.- serialized.encode(m33());- // 12. Set serialized.[[M34]] to value’s m34 element.- serialized.encode(m34());- // 13. Set serialized.[[M41]] to value’s m41 element.- serialized.encode(m41());- // 14. Set serialized.[[M42]] to value’s m42 element.- serialized.encode(m42());- // 15. Set serialized.[[M43]] to value’s m43 element.- serialized.encode(m43());- // 16. Set serialized.[[M44]] to value’s m44 element.- serialized.encode(m44());- // 17. Set serialized.[[Is2D]] to false.- // NOTE: This is set in the beginning of the function.- }-- return {};-}--// https://drafts.fxtf.org/geometry/#structured-serialization-WebIDL::ExceptionOr<void> DOMMatrixReadOnly::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory&)-{- auto decode_double = [&]() {- return HTML::decode_or_throw_data_clone_error<double>(realm, serialized);- };-- bool is_2d = TRY(HTML::decode_or_throw_data_clone_error<bool>(realm, serialized));-- // 1. If serialized.[[Is2D]] is true:- if (is_2d) {- // 1. Set value’s m11 element to serialized.[[M11]].- auto m11 = TRY(decode_double());- // 2. Set value’s m12 element to serialized.[[M12]].- auto m12 = TRY(decode_double());- // 3. Set value’s m13 element to 0.- // 4. Set value’s m14 element to 0.- // 5. Set value’s m21 element to serialized.[[M21]].- auto m21 = TRY(decode_double());- // 6. Set value’s m22 element to serialized.[[M22]].- auto m22 = TRY(decode_double());- // 7. Set value’s m23 element to 0.- // 8. Set value’s m24 element to 0.- // 9. Set value’s m31 element to 0.- // 10. Set value’s m32 element to 0.- // 11. Set value’s m33 element to 1.- // 12. Set value’s m34 element to 0.- // 13. Set value’s m41 element to serialized.[[M41]].- auto m41 = TRY(decode_double());- // 14 Set value’s m42 element to serialized.[[M42]].- auto m42 = TRY(decode_double());- // 15. Set value’s m43 element to 0.- // 16. Set value’s m44 element to 1.- // 17. Set value’s is 2D to true.-- initialize_from_create_2d_matrix(m11, m12, m21, m22, m41, m42);- }- // 2. Otherwise:- else {- // 1. Set value’s m11 element to serialized.[[M11]].- auto m11 = TRY(decode_double());- // 2. Set value’s m12 element to serialized.[[M12]].- auto m12 = TRY(decode_double());- // 3. Set value’s m13 element to serialized.[[M13]].- auto m13 = TRY(decode_double());- // 4. Set value’s m14 element to serialized.[[M14]].- auto m14 = TRY(decode_double());- // 5. Set value’s m21 element to serialized.[[M21]].- auto m21 = TRY(decode_double());- // 6. Set value’s m22 element to serialized.[[M22]].- auto m22 = TRY(decode_double());- // 7. Set value’s m23 element to serialized.[[M23]].- auto m23 = TRY(decode_double());- // 8. Set value’s m24 element to serialized.[[M24]].- auto m24 = TRY(decode_double());- // 9. Set value’s m31 element to serialized.[[M31]].- auto m31 = TRY(decode_double());- // 10. Set value’s m32 element to serialized.[[M32]].- auto m32 = TRY(decode_double());- // 11. Set value’s m33 element to serialized.[[M33]].- auto m33 = TRY(decode_double());- // 12. Set value’s m34 element to serialized.[[M34]].- auto m34 = TRY(decode_double());- // 13. Set value’s m41 element to serialized.[[M41]].- auto m41 = TRY(decode_double());- // 14. Set value’s m42 element to serialized.[[M42]].- auto m42 = TRY(decode_double());- // 15. Set value’s m43 element to serialized.[[M43]].- auto m43 = TRY(decode_double());- // 16. Set value’s m44 element to serialized.[[M44]].- auto m44 = TRY(decode_double());- // 17. Set value’s is 2D to false.-- initialize_from_create_3d_matrix(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44);- }-- return {};-}--// https://drafts.fxtf.org/geometry/#parse-a-string-into-an-abstract-matrix-WebIDL::ExceptionOr<ParsedMatrix> parse_dom_matrix_init_string(StringView transform_list)-{- // 1. If transformList is the empty string, set it to the string "matrix(1, 0, 0, 1, 0, 0)".- if (transform_list.is_empty())- transform_list = "matrix(1, 0, 0, 1, 0, 0)"sv;-- // 2. Parse transformList into parsedValue given the grammar for the CSS transform property.- // The result will be a <transform-list>, the keyword none, or failure.- // If parsedValue is failure, or any <transform-function> has <length> values without absolute length units, or any keyword other than none is used, then return failure. [CSS3-SYNTAX] [CSS3-TRANSFORMS]- CSS::Parser::ParsingParams parsing_params {};- parsing_params.value_context = { CSS::Parser::SpecialContext::DOMMatrixInitString };-- auto transform_style_value = parse_css_value(parsing_params, transform_list, CSS::PropertyID::Transform);- if (!transform_style_value || (transform_style_value->is_keyword() && transform_style_value->to_keyword() != CSS::Keyword::None) || transform_style_value->is_unresolved())- return WebIDL::SyntaxError::create("Failed to parse CSS transform string."_utf16);-- // 3. If parsedValue is none, set parsedValue to a <transform-list> containing a single identity matrix.- // 4. Let 2dTransform track the 2D/3D dimension status of parsedValue.- // 5. Transform all <transform-function>s to 4x4 abstract matrices by following the “Mathematical Description of Transform Functions”. [CSS3-TRANSFORMS]- // 6. Let matrix be a 4x4 abstract matrix as shown in the initial figure of this section. Post-multiply all matrices from left to right and set matrix to this product.- // NB: A <length> without an absolute unit is a failure as well, which Rust reports when it cannot resolve a function.- Array<float, 16> matrix;- bool is_2d_transform = true;- if (!CSS::ComputedValuesFFI::rust_transform_list_to_abstract_matrix(transform_style_value->rust_style_value_data(), matrix.data(), &is_2d_transform))- return WebIDL::SyntaxError::create("Failed to parse CSS transform string."_utf16);-- // 7. Return matrix and 2dTransform.- Gfx::DoubleMatrix4x4 double_matrix {- matrix[0], matrix[1], matrix[2], matrix[3],- matrix[4], matrix[5], matrix[6], matrix[7],- matrix[8], matrix[9], matrix[10], matrix[11],- matrix[12], matrix[13], matrix[14], matrix[15]- };- return ParsedMatrix { double_matrix, is_2d_transform };+ return Utf16String::adopt_raw(string);}}diff --git a/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.h b/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.hindex 3c64ad869d6..fb1f152fdbd 100644--- a/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.h+++ b/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.h@@ -8,163 +8,29 @@#pragma once-#include <AK/Optional.h>-#include <AK/String.h>-#include <AK/Variant.h>-#include <AK/Vector.h>-#include <LibGfx/Matrix4x4.h>-#include <LibWeb/Bindings/Serializable.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/Buffers.h>+#include <AK/Array.h>+#include <AK/Utf16String.h>+#include <LibWeb/Bindings/DOMMatrixReadOnly.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>#include <LibWeb/WebIDL/ExceptionOr.h>-namespace Web::Bindings {--struct DOMMatrix2DInit;-struct DOMMatrixInit;--}-namespace Web::Geometry {-enum class DOMMatrixStringContext {- Window,- Worker,-};--DOMMatrixStringContext dom_matrix_string_context(JS::Object&);--struct DOMMatrix2DInit {- double m11 { 1.0 };- double m12 { 0.0 };- double m21 { 0.0 };- double m22 { 1.0 };- double m41 { 0.0 };- double m42 { 0.0 };-};--struct DOMMatrixInit : public DOMMatrix2DInit {- double m13 { 0.0 };- double m14 { 0.0 };- double m23 { 0.0 };- double m24 { 0.0 };- double m31 { 0.0 };- double m32 { 0.0 };- double m33 { 1.0 };- double m34 { 0.0 };- double m43 { 0.0 };- double m44 { 1.0 };- bool is_2d { true };-};-// https://drafts.fxtf.org/geometry/#dommatrixreadonly-class WEB_API DOMMatrixReadOnly- : public Bindings::GCAllocatedWrappable- , public Bindings::Serializable {- WEB_WRAPPABLE(DOMMatrixReadOnly, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(DOMMatrixReadOnly);+// The C++ side of a DOMMatrixReadOnly, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/geometry):+// what CSS Typed OM reads. A DOMMatrixReadOnly that C++ receives from script can be a DOMMatrix.+class WEB_API DOMMatrixReadOnly : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(DOMMatrixReadOnly, dom_matrix_read_only)public:- static WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> create_from_constructor(Optional<Variant<Utf16String, Vector<double>>> const& init, DOMMatrixStringContext);- static GC::Ref<DOMMatrixReadOnly> create_from_dom_matrix_2d_init(DOMMatrix2DInit const& init);- static GC::Ref<DOMMatrixReadOnly> create_from_dom_matrix_init(DOMMatrixInit const& init);- static GC::Ref<DOMMatrixReadOnly> create(Gfx::FloatMatrix4x4 const&);- static GC::Ref<DOMMatrixReadOnly> create(Gfx::DoubleMatrix4x4 const&);- static GC::Ref<DOMMatrixReadOnly> create();- static WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> create_for_constructor(JS::Object&, Optional<Variant<Utf16String, Vector<double>>> const& init);- static WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> from_matrix(Bindings::DOMMatrixInit&);-- virtual ~DOMMatrixReadOnly() override;-- static WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> from_float32_array(GC::Root<JS::Float32Array> const&);- static WebIDL::ExceptionOr<GC::Ref<DOMMatrixReadOnly>> from_float64_array(GC::Root<JS::Float64Array> const&);+ // The elements m11, m12, m13, m14, m21, ..., m44, in that order.+ Array<double, 16> elements() const;- // https://drafts.fxtf.org/geometry/#dommatrix-attributes- double m11() const { return m_matrix[0, 0]; }- double m12() const { return m_matrix[1, 0]; }- double m13() const { return m_matrix[2, 0]; }- double m14() const { return m_matrix[3, 0]; }- double m21() const { return m_matrix[0, 1]; }- double m22() const { return m_matrix[1, 1]; }- double m23() const { return m_matrix[2, 1]; }- double m24() const { return m_matrix[3, 1]; }- double m31() const { return m_matrix[0, 2]; }- double m32() const { return m_matrix[1, 2]; }- double m33() const { return m_matrix[2, 2]; }- double m34() const { return m_matrix[3, 2]; }- double m41() const { return m_matrix[0, 3]; }- double m42() const { return m_matrix[1, 3]; }- double m43() const { return m_matrix[2, 3]; }- double m44() const { return m_matrix[3, 3]; }+ bool is2d() const;- double a() const { return m11(); }- double b() const { return m12(); }- double c() const { return m21(); }- double d() const { return m22(); }- double e() const { return m41(); }- double f() const { return m42(); }-- bool is2d() const { return m_is_2d; }- bool is_identity() const;-- GC::Ref<DOMMatrix> translate(Optional<double> const& tx, Optional<double> const& ty, Optional<double> const& tz) const;- GC::Ref<DOMMatrix> scale(Optional<double> scale_x, Optional<double> scale_y, Optional<double> scale_z, Optional<double> origin_x, Optional<double> origin_y, Optional<double> origin_z);- GC::Ref<DOMMatrix> scale_non_uniform(Optional<double> scale_x, Optional<double> scale_y);- GC::Ref<DOMMatrix> scale3d(Optional<double> scale, Optional<double> origin_x, Optional<double> origin_y, Optional<double> origin_z);- GC::Ref<DOMMatrix> rotate(Optional<double> rot_x, Optional<double> rot_y, Optional<double> rot_z);- GC::Ref<DOMMatrix> rotate_from_vector(Optional<double> x, Optional<double> y);- GC::Ref<DOMMatrix> rotate_axis_angle(Optional<double> x, Optional<double> y, Optional<double> z, Optional<double> angle);- GC::Ref<DOMMatrix> skew_x(double sx = 0) const;- GC::Ref<DOMMatrix> skew_y(double sy = 0) const;- WebIDL::ExceptionOr<GC::Ref<DOMMatrix>> multiply(Bindings::DOMMatrixInit&) const;- GC::Ref<DOMMatrix> flip_x();- GC::Ref<DOMMatrix> flip_y();- GC::Ref<DOMMatrix> inverse() const;-- GC::Ref<DOMPoint> transform_point(DOMPointReadOnly const&) const;- GC::Ref<DOMPoint> transform_point(Bindings::DOMPointInit const&) const;- GC::Ref<JS::Float32Array> to_float32_array(JS::Object const& relevant_global_object) const;- GC::Ref<JS::Float64Array> to_float64_array(JS::Object const& relevant_global_object) const;-- WebIDL::ExceptionOr<String> to_string() const;-- 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;--protected:- DOMMatrixReadOnly(double m11, double m12, double m21, double m22, double m41, double m42);- DOMMatrixReadOnly(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double m41, double m42, double m43, double m44);- DOMMatrixReadOnly(DOMMatrixReadOnly const& other);- DOMMatrixReadOnly();-- template<typename T>- explicit DOMMatrixReadOnly(Gfx::Matrix4x4<T> const& matrix)- : m_is_2d(Gfx::is_2d_affine_transform(matrix))- {- for (size_t row = 0; row < 4; ++row) {- for (size_t column = 0; column < 4; ++column)- m_matrix[row, column] = matrix[row, column];- }- }-- // NOTE: The matrix used in the spec is column-major (https://drafts.fxtf.org/geometry/#4x4-abstract-matrix) but Gfx::Matrix4x4 is row-major so we need to transpose the values.- Gfx::DoubleMatrix4x4 m_matrix { Gfx::DoubleMatrix4x4::identity() };-- bool m_is_2d { true };--private:- void initialize_from_create_2d_matrix(double m11, double m12, double m21, double m22, double m41, double m42);- void initialize_from_create_3d_matrix(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double m41, double m42, double m43, double m44);+ // https://drafts.fxtf.org/geometry/#dommatrixreadonly-stringification-behavior+ WebIDL::ExceptionOr<Utf16String> to_string() const;};-struct ParsedMatrix {- Gfx::DoubleMatrix4x4 matrix;- bool is_2d_transform;-};--WebIDL::ExceptionOr<DOMMatrix2DInit> validate_and_fixup_dom_matrix_2d_init(Bindings::DOMMatrix2DInit const&);-WebIDL::ExceptionOr<DOMMatrixInit> validate_and_fixup_dom_matrix_init(Bindings::DOMMatrixInit const&);-WebIDL::ExceptionOr<ParsedMatrix> parse_dom_matrix_init_string(StringView transform_list);-}diff --git a/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.idl b/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.idlindex 80b6f92e284..deaffea5197 100644--- a/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.idl+++ b/Libraries/LibWeb/Geometry/DOMMatrixReadOnly.idl@@ -1,5 +1,5 @@// https://drafts.fxtf.org/geometry/#dommatrixreadonly-[Exposed=(Window,Worker), Serializable]+[Exposed=(Window,Worker), Serializable, ImplementedIn=Rust]interface DOMMatrixReadOnly {constructor(optional (DOMString or sequence<unrestricted double>) init);diff --git a/Libraries/LibWeb/Geometry/DOMPoint.cpp b/Libraries/LibWeb/Geometry/DOMPoint.cppindex d7e9b951d43..31b7a0b9b0d 100644--- a/Libraries/LibWeb/Geometry/DOMPoint.cpp+++ b/Libraries/LibWeb/Geometry/DOMPoint.cpp@@ -5,39 +5,21 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/DOMPointReadOnly.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Geometry/DOMPoint.h>namespace Web::Geometry {-GC_DEFINE_ALLOCATOR(DOMPoint);+extern "C" {-GC::Ref<DOMPoint> DOMPoint::create(double x, double y, double z, double w)-{- return GC::Heap::the().allocate<DOMPoint>(x, y, z, w);+// Defined in Bindings/Rust/src/geometry/exports.rs.+void* web_dom_point_create(JSVM*, double x, double y, double z, double w);}-GC::Ref<DOMPoint> DOMPoint::create()-{- return GC::Heap::the().allocate<DOMPoint>();-}--GC::Ref<DOMPoint> DOMPoint::dom_point_from_point(Bindings::DOMPointInit const& other)-{- return create(other.x, other.y, other.z, other.w);-}--DOMPoint::DOMPoint(double x, double y, double z, double w)- : DOMPointReadOnly(x, y, z, w)-{-}--DOMPoint::DOMPoint()- : DOMPointReadOnly()+GC::Ref<DOMPoint> DOMPoint::create(double x, double y, double z, double w){+ return GC::Ref { *static_cast<DOMPoint*>(web_dom_point_create(JS::HostABI::vm_to_abi(JS::VM::the()), x, y, z, w)) };}-DOMPoint::~DOMPoint() = default;-}diff --git a/Libraries/LibWeb/Geometry/DOMPoint.h b/Libraries/LibWeb/Geometry/DOMPoint.hindex 9d53d195c88..4185977b41f 100644--- a/Libraries/LibWeb/Geometry/DOMPoint.h+++ b/Libraries/LibWeb/Geometry/DOMPoint.h@@ -7,42 +7,20 @@#pragma once+#include <LibWeb/Bindings/DOMPoint.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Export.h>-#include <LibWeb/Geometry/DOMPointReadOnly.h>--namespace Web::Bindings {--struct DOMPointInit;--}namespace Web::Geometry {-// https://drafts.fxtf.org/geometry/#DOMPoint-class WEB_API DOMPoint final : public DOMPointReadOnly {- WEB_WRAPPABLE(DOMPoint, DOMPointReadOnly);- GC_DECLARE_ALLOCATOR(DOMPoint);+// https://drafts.fxtf.org/geometry/#dompoint+// The C++ side of a DOMPoint, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/geometry): what C+++// creates.+class WEB_API DOMPoint final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(DOMPoint, dom_point)public:- static GC::Ref<DOMPoint> create(double x, double y, double z, double w);- static GC::Ref<DOMPoint> create();- static GC::Ref<DOMPoint> dom_point_from_point(Bindings::DOMPointInit const&);-- virtual ~DOMPoint() override;-- double x() const { return m_x; }- double y() const { return m_y; }- double z() const { return m_z; }- double w() const { return m_w; }-- void set_x(double x) { m_x = x; }- void set_y(double y) { m_y = y; }- void set_z(double z) { m_z = z; }- void set_w(double w) { m_w = w; }--private:- DOMPoint(double x, double y, double z, double w);- DOMPoint();+ static GC::Ref<DOMPoint> create(double x = 0, double y = 0, double z = 0, double w = 1);};}diff --git a/Libraries/LibWeb/Geometry/DOMPoint.idl b/Libraries/LibWeb/Geometry/DOMPoint.idlindex b966615f5f5..a104ca60cc3 100644--- a/Libraries/LibWeb/Geometry/DOMPoint.idl+++ b/Libraries/LibWeb/Geometry/DOMPoint.idl@@ -1,11 +1,11 @@// https://drafts.fxtf.org/geometry/#dompoint-[Exposed=(Window,Worker), Serializable, LegacyWindowAlias=SVGPoint]+[Exposed=(Window,Worker), Serializable, LegacyWindowAlias=SVGPoint, ImplementedIn=Rust]interface DOMPoint : DOMPointReadOnly {constructor(optional unrestricted double x = 0, optional unrestricted double y = 0,optional unrestricted double z = 0, optional unrestricted double w = 1);- [ImplementedAs=dom_point_from_point, NewObject] static DOMPoint fromPoint(optional DOMPointInit other = {});+ [NewObject] static DOMPoint fromPoint(optional DOMPointInit other = {});inherit attribute unrestricted double x;inherit attribute unrestricted double y;diff --git a/Libraries/LibWeb/Geometry/DOMPointReadOnly.cpp b/Libraries/LibWeb/Geometry/DOMPointReadOnly.cppindex 7efb3e7e3c6..d55baf04f24 100644--- a/Libraries/LibWeb/Geometry/DOMPointReadOnly.cpp+++ b/Libraries/LibWeb/Geometry/DOMPointReadOnly.cpp@@ -6,93 +6,21 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/DOMMatrixReadOnly.h>-#include <LibWeb/Bindings/DOMPointReadOnly.h>-#include <LibWeb/Geometry/DOMMatrix.h>-#include <LibWeb/Geometry/DOMPoint.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Geometry/DOMPointReadOnly.h>-#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Geometry {-GC_DEFINE_ALLOCATOR(DOMPointReadOnly);+extern "C" {-GC::Ref<DOMPointReadOnly> DOMPointReadOnly::create(double x, double y, double z, double w)-{- return GC::Heap::the().allocate<DOMPointReadOnly>(x, y, z, w);-}--GC::Ref<DOMPointReadOnly> DOMPointReadOnly::create()-{- return GC::Heap::the().allocate<DOMPointReadOnly>();-}--GC::Ref<DOMPointReadOnly> DOMPointReadOnly::dom_point_read_only_from_point(Bindings::DOMPointInit const& other)-{- return create(other.x, other.y, other.z, other.w);-}--DOMPointReadOnly::DOMPointReadOnly(double x, double y, double z, double w)- : m_x(x)- , m_y(y)- , m_z(z)- , m_w(w)-{-}--DOMPointReadOnly::DOMPointReadOnly() = default;-DOMPointReadOnly::~DOMPointReadOnly() = default;--// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-matrixtransform-WebIDL::ExceptionOr<GC::Ref<DOMPoint>> DOMPointReadOnly::matrix_transform(GC::Ref<DOMMatrix> matrix_object) const-{- // 1. Let matrixObject be the result of invoking create a DOMMatrix from the dictionary matrix.- // NB: This is done by the binding helper before entering the implementation.-- // 2. Return the result of invoking transform a point with a matrix, given the current point and matrixObject. The current point does not get modified.- return matrix_object->transform_point(*this);+// Defined in Bindings/Rust/src/geometry/exports.rs.+void* web_dom_point_read_only_create(JSVM*, double x, double y, double z, double w);}-WebIDL::ExceptionOr<GC::Ref<DOMPoint>> DOMPointReadOnly::matrix_transform(Bindings::DOMMatrixInit const& matrix) const-{- auto matrix_object = DOMMatrix::create_from_dom_matrix_init(TRY(validate_and_fixup_dom_matrix_init(matrix)));- return matrix_transform(matrix_object);-}--WebIDL::ExceptionOr<void> DOMPointReadOnly::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool, HTML::SerializationMemory&)-{- // 1. Set serialized.[[X]] to value’s x coordinate.- serialized.encode(m_x);-- // 2. Set serialized.[[Y]] to value’s y coordinate.- serialized.encode(m_y);-- // 3. Set serialized.[[Z]] to value’s z coordinate.- serialized.encode(m_z);-- // 4. Set serialized.[[W]] to value’s w coordinate.- serialized.encode(m_w);-- return {};-}--WebIDL::ExceptionOr<void> DOMPointReadOnly::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory&)+GC::Ref<DOMPointReadOnly> DOMPointReadOnly::create(double x, double y, double z, double w){- // 1. Set value’s x coordinate to serialized.[[X]].- m_x = TRY(HTML::decode_or_throw_data_clone_error<double>(realm, serialized));-- // 2. Set value’s y coordinate to serialized.[[Y]].- m_y = TRY(HTML::decode_or_throw_data_clone_error<double>(realm, serialized));-- // 3. Set value’s z coordinate to serialized.[[Z]].- m_z = TRY(HTML::decode_or_throw_data_clone_error<double>(realm, serialized));-- // 4. Set value’s w coordinate to serialized.[[W]].- m_w = TRY(HTML::decode_or_throw_data_clone_error<double>(realm, serialized));-- return {};+ return GC::Ref { *static_cast<DOMPointReadOnly*>(web_dom_point_read_only_create(JS::HostABI::vm_to_abi(JS::VM::the()), x, y, z, w)) };}}diff --git a/Libraries/LibWeb/Geometry/DOMPointReadOnly.h b/Libraries/LibWeb/Geometry/DOMPointReadOnly.hindex 140c63e8446..c600ebb5662 100644--- a/Libraries/LibWeb/Geometry/DOMPointReadOnly.h+++ b/Libraries/LibWeb/Geometry/DOMPointReadOnly.h@@ -8,54 +8,20 @@#pragma once-#include <LibGfx/Point.h>-#include <LibWeb/Bindings/Serializable.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Bindings {--struct DOMMatrixInit;-struct DOMPointInit;--}+#include <LibWeb/Bindings/DOMPointReadOnly.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>namespace Web::Geometry {// https://drafts.fxtf.org/geometry/#dompointreadonly-class WEB_API DOMPointReadOnly- : public Bindings::GCAllocatedWrappable- , public Bindings::Serializable {- WEB_WRAPPABLE(DOMPointReadOnly, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(DOMPointReadOnly);+// The C++ side of a DOMPointReadOnly, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/geometry): what+// C++ creates.+class WEB_API DOMPointReadOnly final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(DOMPointReadOnly, dom_point_read_only)public:- static GC::Ref<DOMPointReadOnly> create(double x, double y, double z, double w);- static GC::Ref<DOMPointReadOnly> create();- static GC::Ref<DOMPointReadOnly> dom_point_read_only_from_point(Bindings::DOMPointInit const&);-- virtual ~DOMPointReadOnly() override;-- double x() const { return m_x; }- double y() const { return m_y; }- double z() const { return m_z; }- double w() const { return m_w; }-- WebIDL::ExceptionOr<GC::Ref<DOMPoint>> matrix_transform(GC::Ref<DOMMatrix>) const;- WebIDL::ExceptionOr<GC::Ref<DOMPoint>> matrix_transform(Bindings::DOMMatrixInit const&) const;-- 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;--protected:- DOMPointReadOnly(double x, double y, double z, double w);- DOMPointReadOnly();-- double m_x { 0 };- double m_y { 0 };- double m_z { 0 };- double m_w { 1 };+ static GC::Ref<DOMPointReadOnly> create(double x = 0, double y = 0, double z = 0, double w = 1);};}diff --git a/Libraries/LibWeb/Geometry/DOMPointReadOnly.idl b/Libraries/LibWeb/Geometry/DOMPointReadOnly.idlindex 837473d444d..fa9a6f385f6 100644--- a/Libraries/LibWeb/Geometry/DOMPointReadOnly.idl+++ b/Libraries/LibWeb/Geometry/DOMPointReadOnly.idl@@ -1,11 +1,11 @@// https://drafts.fxtf.org/geometry/#dompointreadonly-[Exposed=(Window,Worker), Serializable]+[Exposed=(Window,Worker), Serializable, ImplementedIn=Rust]interface DOMPointReadOnly {constructor(optional unrestricted double x = 0, optional unrestricted double y = 0,optional unrestricted double z = 0, optional unrestricted double w = 1);- [ImplementedAs=dom_point_read_only_from_point, NewObject] static DOMPointReadOnly fromPoint(optional DOMPointInit other = {});+ [NewObject] static DOMPointReadOnly fromPoint(optional DOMPointInit other = {});readonly attribute unrestricted double x;readonly attribute unrestricted double y;diff --git a/Libraries/LibWeb/Geometry/DOMQuad.cpp b/Libraries/LibWeb/Geometry/DOMQuad.cppdeleted file mode 100644index 3cdca3222ef..00000000000--- a/Libraries/LibWeb/Geometry/DOMQuad.cpp+++ /dev/null@@ -1,183 +0,0 @@-/*- * Copyright (c) 2023, Bastiaan van der Plaat <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Bindings/DOMPointReadOnly.h>-#include <LibWeb/Bindings/DOMQuad.h>-#include <LibWeb/Bindings/DOMRectReadOnly.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Geometry/DOMQuad.h>-#include <LibWeb/HTML/StructuredSerialize.h>--namespace Web::Geometry {--GC_DEFINE_ALLOCATOR(DOMQuad);--GC::Ref<DOMQuad> DOMQuad::create()-{- return GC::Heap::the().allocate<DOMQuad>(DOMPoint::create(), DOMPoint::create(), DOMPoint::create(), DOMPoint::create());-}--GC::Ref<DOMQuad> DOMQuad::create(GC::Ref<DOMPoint> p1, GC::Ref<DOMPoint> p2, GC::Ref<DOMPoint> p3, GC::Ref<DOMPoint> p4)-{- return GC::Heap::the().allocate<DOMQuad>(p1, p2, p3, p4);-}--static GC::Ref<DOMPoint> point_from_init(Bindings::DOMPointInit const& point)-{- return DOMPoint::create(point.x, point.y, point.z, point.w);-}--static GC::Ref<DOMPoint> point_from_coordinates(double x, double y)-{- return DOMPoint::create(x, y, 0, 1);-}--GC::Ref<DOMQuad> DOMQuad::create(Bindings::DOMPointInit const& p1, Bindings::DOMPointInit const& p2, Bindings::DOMPointInit const& p3, Bindings::DOMPointInit const& p4)-{- return create(point_from_init(p1), point_from_init(p2), point_from_init(p3), point_from_init(p4));-}--GC::Ref<DOMQuad> DOMQuad::dom_quad_from_rect(Bindings::DOMRectInit const& other)-{- return create(- point_from_coordinates(other.x, other.y),- point_from_coordinates(other.x + other.width, other.y),- point_from_coordinates(other.x + other.width, other.y + other.height),- point_from_coordinates(other.x, other.y + other.height));-}--GC::Ref<DOMQuad> DOMQuad::dom_quad_from_quad(Bindings::DOMQuadInit const& other)-{- return create(- point_from_init(other.p1.value_or(Bindings::DOMPointInit {})),- point_from_init(other.p2.value_or(Bindings::DOMPointInit {})),- point_from_init(other.p3.value_or(Bindings::DOMPointInit {})),- point_from_init(other.p4.value_or(Bindings::DOMPointInit {})));-}--DOMQuad::DOMQuad(GC::Ref<DOMPoint> p1, GC::Ref<DOMPoint> p2, GC::Ref<DOMPoint> p3, GC::Ref<DOMPoint> p4)- : m_p1(p1)- , m_p2(p2)- , m_p3(p3)- , m_p4(p4)-{-}--DOMQuad::~DOMQuad() = default;--// https://drafts.fxtf.org/geometry/#dom-domquad-getbounds-GC::Ref<DOMRect> DOMQuad::get_bounds() const-{- // The NaN-safe minimum of a non-empty list of unrestricted double values is NaN if any member of the list is NaN, or the minimum of the list otherwise.- auto nan_safe_minimum = [](double a, double b, double c, double d) -> double {- if (isnan(a) || isnan(b) || isnan(c) || isnan(d))- return NAN;- return min(a, min(b, min(c, d)));- };-- // Analogously, the NaN-safe maximum of a non-empty list of unrestricted double values is NaN if any member of the list is NaN, or the maximum of the list otherwise.- auto nan_safe_maximum = [](double a, double b, double c, double d) -> double {- if (isnan(a) || isnan(b) || isnan(c) || isnan(d))- return NAN;- return max(a, max(b, max(c, d)));- };-- // 1. Let bounds be a DOMRect object.- auto bounds = DOMRect::create({});-- // 2. Let left be the NaN-safe minimum of point 1’s x coordinate, point 2’s x coordinate, point 3’s x coordinate and point 4’s x coordinate.- auto left = nan_safe_minimum(m_p1->x(), m_p2->x(), m_p3->x(), m_p4->x());-- // 3. Let top be the NaN-safe minimum of point 1’s y coordinate, point 2’s y coordinate, point 3’s y coordinate and point 4’s y coordinate.- auto top = nan_safe_minimum(m_p1->y(), m_p2->y(), m_p3->y(), m_p4->y());-- // 4. Let right be the NaN-safe maximum of point 1’s x coordinate, point 2’s x coordinate, point 3’s x coordinate and point 4’s x coordinate.- auto right = nan_safe_maximum(m_p1->x(), m_p2->x(), m_p3->x(), m_p4->x());-- // 5. Let bottom be the NaN-safe maximum of point 1’s y coordinate, point 2’s y coordinate, point 3’s y coordinate and point 4’s y coordinate.- auto bottom = nan_safe_maximum(m_p1->y(), m_p2->y(), m_p3->y(), m_p4->y());-- // 6. Set x coordinate of bounds to left, y coordinate of bounds to top, width dimension of bounds to right - left and height dimension of bounds to bottom - top.- bounds->set_x(left);- bounds->set_y(top);- bounds->set_width(right - left);- bounds->set_height(bottom - top);-- // 7. Return bounds.- return bounds;-}--void DOMQuad::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_p1);- visitor.visit(m_p2);- visitor.visit(m_p3);- visitor.visit(m_p4);-}--// https://drafts.fxtf.org/geometry/#structured-serialization-WebIDL::ExceptionOr<void> DOMQuad::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool for_storage, HTML::SerializationMemory& memory)-{- auto serialize_point = [&](GC::Ref<DOMPointReadOnly> point) -> WebIDL::ExceptionOr<void> {- serialized.encode(to_underlying(HTML::ValueTag::SerializableObject));- serialized.encode(Bindings::InterfaceName::DOMPoint);- if (serialized.type() == HTML::SerializationType::Storage)- serialized.encode(u64 { 1 });- TRY(point->serialization_steps(serialized, for_storage, memory));- return {};- };-- // 1. Set serialized.[[P1]] to the sub-serialization of value’s point 1.- TRY(serialize_point(m_p1));-- // 2. Set serialized.[[P2]] to the sub-serialization of value’s point 2.- TRY(serialize_point(m_p2));-- // 3. Set serialized.[[P3]] to the sub-serialization of value’s point 3.- TRY(serialize_point(m_p3));-- // 4. Set serialized.[[P4]] to the sub-serialization of value’s point 4.- TRY(serialize_point(m_p4));-- return {};-}--// https://drafts.fxtf.org/geometry/#structured-serialization-WebIDL::ExceptionOr<void> DOMQuad::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory& memory)-{- auto deserialize_dom_point = [&](GC::Ref<DOMPoint>& storage) -> WebIDL::ExceptionOr<void> {- auto tag = TRY(HTML::decode_or_throw_data_clone_error<u8>(realm, serialized));- auto interface_name = TRY(HTML::decode_or_throw_data_clone_error<Bindings::InterfaceName>(realm, serialized));- if (tag != to_underlying(HTML::ValueTag::SerializableObject) || interface_name != Bindings::InterfaceName::DOMPoint)- return WebIDL::DataCloneError::create("Invalid DOMQuad point"_utf16);- if (serialized.type() == HTML::SerializationType::Storage) {- auto version = TRY(HTML::decode_or_throw_data_clone_error<u64>(realm, serialized));- if (version != 1)- return WebIDL::DataCloneError::create("Unsupported DOMQuad point version"_utf16);- }- storage = DOMPoint::create();- TRY(storage->deserialization_steps(realm, serialized, memory));- return {};- };-- // 1. Set value’s point 1 to the sub-deserialization of serialized.[[P1]].- TRY(deserialize_dom_point(m_p1));-- // 2. Set value’s point 2 to the sub-deserialization of serialized.[[P2]].- TRY(deserialize_dom_point(m_p2));-- // 3. Set value’s point 3 to the sub-deserialization of serialized.[[P3]].- TRY(deserialize_dom_point(m_p3));-- // 4. Set value’s point 4 to the sub-deserialization of serialized.[[P4]].- TRY(deserialize_dom_point(m_p4));-- return {};-}--}diff --git a/Libraries/LibWeb/Geometry/DOMQuad.h b/Libraries/LibWeb/Geometry/DOMQuad.hdeleted file mode 100644index 26c38846449..00000000000--- a/Libraries/LibWeb/Geometry/DOMQuad.h+++ /dev/null@@ -1,67 +0,0 @@-/*- * Copyright (c) 2023, Bastiaan van der Plaat <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/Bindings/Serializable.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Geometry/DOMPoint.h>-#include <LibWeb/Geometry/DOMRect.h>-#include <LibWeb/Geometry/DOMRectReadOnly.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Bindings {--struct DOMPointInit;-struct DOMQuadInit;-struct DOMRectInit;--}--namespace Web::Geometry {--// https://drafts.fxtf.org/geometry/#domquad-class WEB_API DOMQuad- : public Bindings::GCAllocatedWrappable- , public Bindings::Serializable {- WEB_WRAPPABLE(DOMQuad, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(DOMQuad);--public:- static constexpr size_t p1_offset() { return offsetof(DOMQuad, m_p1); }- static constexpr size_t p2_offset() { return offsetof(DOMQuad, m_p2); }- static constexpr size_t p3_offset() { return offsetof(DOMQuad, m_p3); }- static constexpr size_t p4_offset() { return offsetof(DOMQuad, m_p4); }- static GC::Ref<DOMQuad> create(GC::Ref<DOMPoint> p1, GC::Ref<DOMPoint> p2, GC::Ref<DOMPoint> p3, GC::Ref<DOMPoint> p4);- static GC::Ref<DOMQuad> create(Bindings::DOMPointInit const& p1, Bindings::DOMPointInit const& p2, Bindings::DOMPointInit const& p3, Bindings::DOMPointInit const& p4);- static GC::Ref<DOMQuad> create();- static GC::Ref<DOMQuad> dom_quad_from_rect(Bindings::DOMRectInit const&);- static GC::Ref<DOMQuad> dom_quad_from_quad(Bindings::DOMQuadInit const&);-- virtual ~DOMQuad() override;-- GC::Ref<DOMPoint> p1() const { return m_p1; }- GC::Ref<DOMPoint> p2() const { return m_p2; }- GC::Ref<DOMPoint> p3() const { return m_p3; }- GC::Ref<DOMPoint> p4() const { return m_p4; }-- GC::Ref<DOMRect> get_bounds() const;-- 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:- DOMQuad(GC::Ref<DOMPoint> p1, GC::Ref<DOMPoint> p2, GC::Ref<DOMPoint> p3, GC::Ref<DOMPoint> p4);-- virtual void visit_edges(GC::Cell::Visitor&) override;-- GC::Ref<DOMPoint> m_p1;- GC::Ref<DOMPoint> m_p2;- GC::Ref<DOMPoint> m_p3;- GC::Ref<DOMPoint> m_p4;-};--}diff --git a/Libraries/LibWeb/Geometry/DOMQuad.idl b/Libraries/LibWeb/Geometry/DOMQuad.idlindex b8309391c94..175f611f57d 100644--- a/Libraries/LibWeb/Geometry/DOMQuad.idl+++ b/Libraries/LibWeb/Geometry/DOMQuad.idl@@ -1,16 +1,16 @@// https://drafts.fxtf.org/geometry/#domquad-[Exposed=(Window,Worker), Serializable]+[Exposed=(Window,Worker), Serializable, ImplementedIn=Rust]interface DOMQuad {constructor(optional DOMPointInit p1 = {}, optional DOMPointInit p2 = {},optional DOMPointInit p3 = {}, optional DOMPointInit p4 = {});- [ImplementedAs=dom_quad_from_rect, NewObject] static DOMQuad fromRect(optional DOMRectInit other = {});- [ImplementedAs=dom_quad_from_quad, NewObject] static DOMQuad fromQuad(optional DOMQuadInit other = {});+ [NewObject] static DOMQuad fromRect(optional DOMRectInit other = {});+ [NewObject] static DOMQuad fromQuad(optional DOMQuadInit other = {});- [DirectGetter, SameObject] readonly attribute DOMPoint p1;- [DirectGetter, SameObject] readonly attribute DOMPoint p2;- [DirectGetter, SameObject] readonly attribute DOMPoint p3;- [DirectGetter, SameObject] readonly attribute DOMPoint p4;+ [SameObject] readonly attribute DOMPoint p1;+ [SameObject] readonly attribute DOMPoint p2;+ [SameObject] readonly attribute DOMPoint p3;+ [SameObject] readonly attribute DOMPoint p4;[NewObject] DOMRect getBounds();[Default] object toJSON();diff --git a/Libraries/LibWeb/Geometry/DOMRect.cpp b/Libraries/LibWeb/Geometry/DOMRect.cppindex 458235552bc..46c6db14b6d 100644--- a/Libraries/LibWeb/Geometry/DOMRect.cpp+++ b/Libraries/LibWeb/Geometry/DOMRect.cpp@@ -4,45 +4,32 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/DOMRectReadOnly.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Geometry/DOMRect.h>-#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Geometry {-GC_DEFINE_ALLOCATOR(DOMRect);+extern "C" {-GC::Ref<DOMRect> DOMRect::create(double x, double y, double width, double height)-{- return GC::Heap::the().allocate<DOMRect>(x, y, width, height);-}--GC::Ref<DOMRect> DOMRect::create(Gfx::FloatRect const& rect)-{- return GC::Heap::the().allocate<DOMRect>(rect.x(), rect.y(), rect.width(), rect.height());+// Defined in Bindings/Rust/src/geometry/exports.rs.+void* web_dom_rect_create(JSVM*, double x, double y, double width, double height);+void web_dom_rect_set(void* rect, double x, double y, double width, double height);}-GC::Ref<DOMRect> DOMRect::create()-{- return GC::Heap::the().allocate<DOMRect>();-}--GC::Ref<DOMRect> DOMRect::dom_rect_from_rect(Bindings::DOMRectInit const& other)+GC::Ref<DOMRect> DOMRect::create(double x, double y, double width, double height){- return create(other.x, other.y, other.width, other.height);+ return GC::Ref { *static_cast<DOMRect*>(web_dom_rect_create(JS::HostABI::vm_to_abi(JS::VM::the()), x, y, width, height)) };}-DOMRect::DOMRect(double x, double y, double width, double height)- : DOMRectReadOnly(x, y, width, height)+GC::Ref<DOMRect> DOMRect::create(Gfx::FloatRect const& rect){+ return create(rect.x(), rect.y(), rect.width(), rect.height());}-DOMRect::DOMRect()- : DOMRectReadOnly()+void DOMRect::set(Gfx::DoubleRect const& rect){+ web_dom_rect_set(this, rect.x(), rect.y(), rect.width(), rect.height());}-DOMRect::~DOMRect() = default;-}diff --git a/Libraries/LibWeb/Geometry/DOMRect.h b/Libraries/LibWeb/Geometry/DOMRect.hindex e0f7179e894..1099df2c632 100644--- a/Libraries/LibWeb/Geometry/DOMRect.h+++ b/Libraries/LibWeb/Geometry/DOMRect.h@@ -6,42 +6,25 @@#pragma once-#include <LibWeb/Geometry/DOMRectReadOnly.h>--namespace Web::Bindings {--struct DOMRectInit;--}+#include <LibGfx/Rect.h>+#include <LibWeb/Bindings/DOMRect.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>namespace Web::Geometry {-// https://drafts.fxtf.org/geometry/#DOMRect-class WEB_API DOMRect final : public DOMRectReadOnly {- WEB_WRAPPABLE(DOMRect, DOMRectReadOnly);- GC_DECLARE_ALLOCATOR(DOMRect);+// https://drafts.fxtf.org/geometry/#domrect+// The C++ side of a DOMRect, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/geometry): what C+++// creates, and changes as script can.+class WEB_API DOMRect final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(DOMRect, dom_rect)public:- [[nodiscard]] static GC::Ref<DOMRect> create(double x, double y, double width, double height);- [[nodiscard]] static GC::Ref<DOMRect> create(Gfx::FloatRect const&);- [[nodiscard]] static GC::Ref<DOMRect> create();- [[nodiscard]] static GC::Ref<DOMRect> dom_rect_from_rect(Bindings::DOMRectInit const&);-- virtual ~DOMRect() override;-- double x() const { return m_rect.x(); }- double y() const { return m_rect.y(); }- double width() const { return m_rect.width(); }- double height() const { return m_rect.height(); }-- void set_x(double x) { m_rect.set_x(x); }- void set_y(double y) { m_rect.set_y(y); }- void set_width(double width) { m_rect.set_width(width); }- void set_height(double height) { m_rect.set_height(height); }+ static GC::Ref<DOMRect> create(double x = 0, double y = 0, double width = 0, double height = 0);+ static GC::Ref<DOMRect> create(Gfx::FloatRect const&);-private:- DOMRect(double x, double y, double width, double height);- DOMRect();+ // Sets the x coordinate, y coordinate, width dimension and height dimension to those of the rectangle.+ void set(Gfx::DoubleRect const&);};}diff --git a/Libraries/LibWeb/Geometry/DOMRect.idl b/Libraries/LibWeb/Geometry/DOMRect.idlindex fa796e9992b..1d40bfc2745 100644--- a/Libraries/LibWeb/Geometry/DOMRect.idl+++ b/Libraries/LibWeb/Geometry/DOMRect.idl@@ -1,13 +1,13 @@-// https://drafts.fxtf.org/geometry/#dompoint-[Exposed=(Window,Worker), Serializable, LegacyWindowAlias=SVGRect]+// https://drafts.fxtf.org/geometry/#domrect+[Exposed=(Window,Worker), Serializable, LegacyWindowAlias=SVGRect, ImplementedIn=Rust]interface DOMRect : DOMRectReadOnly {constructor(optional unrestricted double x = 0, optional unrestricted double y = 0,optional unrestricted double width = 0, optional unrestricted double height = 0);- [ImplementedAs=dom_rect_from_rect, NewObject] static DOMRect fromRect(optional DOMRectInit other = {});+ [NewObject] static DOMRect fromRect(optional DOMRectInit other = {});- attribute unrestricted double x;- attribute unrestricted double y;- attribute unrestricted double width;- attribute unrestricted double height;+ inherit attribute unrestricted double x;+ inherit attribute unrestricted double y;+ inherit attribute unrestricted double width;+ inherit attribute unrestricted double height;};diff --git a/Libraries/LibWeb/Geometry/DOMRectList.cpp b/Libraries/LibWeb/Geometry/DOMRectList.cppindex 29f8aaf8abc..5b9c9599dbd 100644--- a/Libraries/LibWeb/Geometry/DOMRectList.cpp+++ b/Libraries/LibWeb/Geometry/DOMRectList.cpp@@ -4,53 +4,26 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibGC/Root.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Geometry/DOMRect.h>+#include <AK/Vector.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Geometry/DOMRectList.h>-#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Geometry {-GC_DEFINE_ALLOCATOR(DOMRectList);+extern "C" {-GC::Ref<DOMRectList> DOMRectList::create(Vector<GC::Root<DOMRect>> rect_handles)-{- Vector<GC::Ref<DOMRect>> rects;- for (auto& rect : rect_handles)- rects.append(*rect);- return GC::Heap::the().allocate<DOMRectList>(move(rects));-}--DOMRectList::DOMRectList(Vector<GC::Ref<DOMRect>> rects)- : m_rects(move(rects))-{-}--DOMRectList::~DOMRectList() = default;--void DOMRectList::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_rects);-}--// https://drafts.fxtf.org/geometry-1/#dom-domrectlist-length-u32 DOMRectList::length() const-{- return m_rects.size();+// Defined in Bindings/Rust/src/geometry/exports.rs.+void* web_dom_rect_list_create(JSVM*, ReadonlySpan<Array<double, 4>> rects);}-// https://drafts.fxtf.org/geometry-1/#dom-domrectlist-item-DOMRect const* DOMRectList::item(u32 index) const+GC::Ref<DOMRectList> DOMRectList::create(ReadonlySpan<Gfx::DoubleRect> rects){- // The item(index) method, when invoked, must return null when- // index is greater than or equal to the number of DOMRect objects associated with the DOMRectList.- // Otherwise, the DOMRect object at index must be returned. Indices are zero-based.- if (index >= m_rects.size())- return nullptr;- return m_rects[index].ptr();+ Vector<Array<double, 4>> values;+ values.ensure_capacity(rects.size());+ for (auto const& rect : rects)+ values.unchecked_append({ rect.x(), rect.y(), rect.width(), rect.height() });+ return GC::Ref { *static_cast<DOMRectList*>(web_dom_rect_list_create(JS::HostABI::vm_to_abi(JS::VM::the()), values.span())) };}}diff --git a/Libraries/LibWeb/Geometry/DOMRectList.h b/Libraries/LibWeb/Geometry/DOMRectList.hindex 9a4c8cbb3da..c357e02992b 100644--- a/Libraries/LibWeb/Geometry/DOMRectList.h+++ b/Libraries/LibWeb/Geometry/DOMRectList.h@@ -7,32 +7,23 @@#pragma once-#include <AK/Vector.h>-#include <LibGC/Root.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Geometry/DOMRect.h>+#include <AK/Span.h>+#include <LibGfx/Rect.h>+#include <LibWeb/Bindings/DOMRectList.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>namespace Web::Geometry {-// https://drafts.fxtf.org/geometry-1/#DOMRectList-class DOMRectList final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(DOMRectList, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(DOMRectList);+// https://drafts.fxtf.org/geometry/#domrectlist+// The C++ side of a DOMRectList, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/geometry): what+// C++ creates.+class WEB_API DOMRectList final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(DOMRectList, dom_rect_list)public:- [[nodiscard]] static GC::Ref<DOMRectList> create(Vector<GC::Root<DOMRect>>);-- virtual ~DOMRectList() override;-- u32 length() const;- DOMRect const* item(u32 index) const;--private:- explicit DOMRectList(Vector<GC::Ref<DOMRect>>);-- virtual void visit_edges(GC::Cell::Visitor&) override;-- Vector<GC::Ref<DOMRect>> m_rects;+ // A new list of new DOMRects with the rectangles.+ static GC::Ref<DOMRectList> create(ReadonlySpan<Gfx::DoubleRect>);};}diff --git a/Libraries/LibWeb/Geometry/DOMRectList.idl b/Libraries/LibWeb/Geometry/DOMRectList.idlindex 04d3e46415f..71d32bf092d 100644--- a/Libraries/LibWeb/Geometry/DOMRectList.idl+++ b/Libraries/LibWeb/Geometry/DOMRectList.idl@@ -1,5 +1,5 @@// https://drafts.fxtf.org/geometry/#domrectlist-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface DOMRectList {getter DOMRect? item(unsigned long index);readonly attribute unsigned long length;diff --git a/Libraries/LibWeb/Geometry/DOMRectReadOnly.cpp b/Libraries/LibWeb/Geometry/DOMRectReadOnly.cppindex 7cb05ac05e5..ff42888ec40 100644--- a/Libraries/LibWeb/Geometry/DOMRectReadOnly.cpp+++ b/Libraries/LibWeb/Geometry/DOMRectReadOnly.cpp@@ -5,77 +5,21 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/DOMRectReadOnly.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Geometry/DOMRectReadOnly.h>-#include <LibWeb/HTML/StructuredSerialize.h>-#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Geometry {-GC_DEFINE_ALLOCATOR(DOMRectReadOnly);+extern "C" {-GC::Ref<DOMRectReadOnly> DOMRectReadOnly::create(double x, double y, double width, double height)-{- return GC::Heap::the().allocate<DOMRectReadOnly>(x, y, width, height);-}--GC::Ref<DOMRectReadOnly> DOMRectReadOnly::create()-{- return GC::Heap::the().allocate<DOMRectReadOnly>();-}--GC::Ref<DOMRectReadOnly> DOMRectReadOnly::dom_rect_read_only_from_rect(Bindings::DOMRectInit const& other)-{- return create(other.x, other.y, other.width, other.height);-}--DOMRectReadOnly::DOMRectReadOnly(double x, double y, double width, double height)- : m_rect(x, y, width, height)-{-}--DOMRectReadOnly::DOMRectReadOnly()-{+// Defined in Bindings/Rust/src/geometry/exports.rs.+void* web_dom_rect_read_only_create(JSVM*, double x, double y, double width, double height);}-DOMRectReadOnly::~DOMRectReadOnly() = default;--// https://drafts.fxtf.org/geometry/#structured-serialization-WebIDL::ExceptionOr<void> DOMRectReadOnly::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool, HTML::SerializationMemory&)-{- // 1. Set serialized.[[X]] to value’s x coordinate.- serialized.encode(x());-- // 2. Set serialized.[[Y]] to value’s y coordinate.- serialized.encode(y());-- // 3. Set serialized.[[Width]] to value’s width.- serialized.encode(width());-- // 4. Set serialized.[[Height]] to value’s height.- serialized.encode(height());-- return {};-}--// https://drafts.fxtf.org/geometry/#structured-serialization-WebIDL::ExceptionOr<void> DOMRectReadOnly::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory&)+GC::Ref<DOMRectReadOnly> DOMRectReadOnly::create(double x, double y, double width, double height){- // 1. Set value’s x coordinate to serialized.[[X]].- auto x = TRY(HTML::decode_or_throw_data_clone_error<double>(realm, serialized));-- // 2. Set value’s y coordinate to serialized.[[Y]].- auto y = TRY(HTML::decode_or_throw_data_clone_error<double>(realm, serialized));-- // 3. Set value’s width to serialized.[[Width]].- auto width = TRY(HTML::decode_or_throw_data_clone_error<double>(realm, serialized));-- // 4. Set value’s height to serialized.[[Height]].- auto height = TRY(HTML::decode_or_throw_data_clone_error<double>(realm, serialized));-- m_rect = Gfx::DoubleRect { x, y, width, height };- return {};+ return GC::Ref { *static_cast<DOMRectReadOnly*>(web_dom_rect_read_only_create(JS::HostABI::vm_to_abi(JS::VM::the()), x, y, width, height)) };}}diff --git a/Libraries/LibWeb/Geometry/DOMRectReadOnly.h b/Libraries/LibWeb/Geometry/DOMRectReadOnly.hindex effabba56e3..edcd7dbc678 100644--- a/Libraries/LibWeb/Geometry/DOMRectReadOnly.h+++ b/Libraries/LibWeb/Geometry/DOMRectReadOnly.h@@ -7,75 +7,20 @@#pragma once-#include <LibGfx/Rect.h>-#include <LibWeb/Bindings/Serializable.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Bindings {--struct DOMRectInit;--}+#include <LibWeb/Bindings/DOMRectReadOnly.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>namespace Web::Geometry {// https://drafts.fxtf.org/geometry/#domrectreadonly-class WEB_API DOMRectReadOnly- : public Bindings::GCAllocatedWrappable- , public Bindings::Serializable {- WEB_WRAPPABLE(DOMRectReadOnly, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(DOMRectReadOnly);+// The C++ side of a DOMRectReadOnly, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/geometry): what+// C++ creates and passes on. A DOMRectReadOnly that C++ receives from script can be a DOMRect.+class WEB_API DOMRectReadOnly final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(DOMRectReadOnly, dom_rect_read_only)public:- [[nodiscard]] static GC::Ref<DOMRectReadOnly> create(double x, double y, double width, double height);- static GC::Ref<DOMRectReadOnly> create();- [[nodiscard]] static GC::Ref<DOMRectReadOnly> dom_rect_read_only_from_rect(Bindings::DOMRectInit const&);-- virtual ~DOMRectReadOnly() override;-- double x() const { return m_rect.x(); }- double y() const { return m_rect.y(); }- double width() const { return m_rect.width(); }- double height() const { return m_rect.height(); }-- double top() const- {- if (isnan(y()) || isnan(height()))- return NAN;- return min(y(), y() + height());- }-- double right() const- {- if (isnan(x()) || isnan(width()))- return NAN;- return max(x(), x() + width());- }-- double bottom() const- {- if (isnan(y()) || isnan(height()))- return NAN;- return max(y(), y() + height());- }-- double left() const- {- if (isnan(x()) || isnan(width()))- return NAN;- return min(x(), x() + width());- }-- 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;--protected:- DOMRectReadOnly(double x, double y, double width, double height);- DOMRectReadOnly();-- Gfx::DoubleRect m_rect;+ static GC::Ref<DOMRectReadOnly> create(double x = 0, double y = 0, double width = 0, double height = 0);};}diff --git a/Libraries/LibWeb/Geometry/DOMRectReadOnly.idl b/Libraries/LibWeb/Geometry/DOMRectReadOnly.idlindex 2b66a70af66..2a7cab82e17 100644--- a/Libraries/LibWeb/Geometry/DOMRectReadOnly.idl+++ b/Libraries/LibWeb/Geometry/DOMRectReadOnly.idl@@ -1,10 +1,10 @@// https://drafts.fxtf.org/geometry/#domrectreadonly-[Exposed=(Window, Worker), Serializable]+[Exposed=(Window, Worker), Serializable, ImplementedIn=Rust]interface DOMRectReadOnly {constructor(optional unrestricted double x = 0, optional unrestricted double y = 0,optional unrestricted double width = 0, optional unrestricted double height = 0);- [ImplementedAs=dom_rect_read_only_from_rect, NewObject] static DOMRectReadOnly fromRect(optional DOMRectInit other = {});+ [NewObject] static DOMRectReadOnly fromRect(optional DOMRectInit other = {});readonly attribute unrestricted double x;readonly attribute unrestricted double y;diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cppindex 0d9cc9fbb7b..d867eae11e2 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp@@ -39,7 +39,6 @@#include <LibWeb/Compositor/CompositorHost.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Event.h>-#include <LibWeb/Geometry/DOMMatrix.h>#include <LibWeb/HTML/Canvas/Canvas2DContextBase.h>#include <LibWeb/HTML/Canvas/CanvasDrawImage.h>#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>@@ -158,7 +157,6 @@ CSS::StyleValue const* web_canvas_2d_parse_color(FlatPtr color);CSS::StyleValue const* web_canvas_2d_parse_length(FlatPtr length, FlatPtr* out_serialized);void web_canvas_2d_style_value_ref(CSS::StyleValue const*);void web_canvas_2d_style_value_unref(CSS::StyleValue const*);-void* web_canvas_2d_create_dom_matrix(void* realm, Gfx::AffineTransform const*);Gfx::DecodedImageFrame* web_canvas_2d_image_frame_from_pixels(u8 const* first_row, size_t pitch, i32 width, i32 height);u8 web_canvas_2d_check_usability_of_image(void* source_wrapper, CanvasImageSourceKind, FlatPtr* out_message);void web_canvas_2d_image_source_size(void* source_wrapper, CanvasImageSourceKind, i32* out_width, i32* out_height);@@ -627,15 +625,6 @@ void web_canvas_2d_style_value_unref(CSS::StyleValue const* style_value)style_value->unref();}-// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-gettransform-void* web_canvas_2d_create_dom_matrix(void* realm_pointer, Gfx::AffineTransform const* transform)-{- auto& realm = *static_cast<JS::Realm*>(realm_pointer);- Geometry::DOMMatrix2DInit init = { transform->a(), transform->b(), transform->c(), transform->d(), transform->e(), transform->f() };- auto matrix = Geometry::DOMMatrix::create_from_dom_matrix_2d_init(init);- return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, matrix).ptr();-}-Gfx::DecodedImageFrame* web_canvas_2d_image_frame_from_pixels(u8 const* first_row, size_t pitch, i32 width, i32 height){// NB: The bitmap is shareable, so that flushing to the Compositor passes the pixels by file descriptor instead ofdiff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cppindex 769ba2a2690..0e9ecb06d06 100644--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp@@ -66,13 +66,6 @@#include <LibWeb/FileAPI/Blob.h>#include <LibWeb/FileAPI/File.h>#include <LibWeb/FileAPI/FileList.h>-#include <LibWeb/Geometry/DOMMatrix.h>-#include <LibWeb/Geometry/DOMMatrixReadOnly.h>-#include <LibWeb/Geometry/DOMPoint.h>-#include <LibWeb/Geometry/DOMPointReadOnly.h>-#include <LibWeb/Geometry/DOMQuad.h>-#include <LibWeb/Geometry/DOMRect.h>-#include <LibWeb/Geometry/DOMRectReadOnly.h>#include <LibWeb/HTML/ImageBitmap.h>#include <LibWeb/HTML/ImageData.h>#include <LibWeb/HTML/MessagePort.h>diff --git a/Libraries/LibWeb/IntersectionObserver/IntersectionObserverEntry.h b/Libraries/LibWeb/IntersectionObserver/IntersectionObserverEntry.hindex 82db3e82e6c..871ee34f5e7 100644--- a/Libraries/LibWeb/IntersectionObserver/IntersectionObserverEntry.h+++ b/Libraries/LibWeb/IntersectionObserver/IntersectionObserverEntry.h@@ -8,7 +8,7 @@#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Forward.h>-#include <LibWeb/Geometry/DOMRect.h>+#include <LibWeb/Geometry/DOMRectReadOnly.h>#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>namespace Web::IntersectionObserver {@@ -18,8 +18,6 @@ class IntersectionObserverEntry final : public Bindings::GCAllocatedWrappable {GC_DECLARE_ALLOCATOR(IntersectionObserverEntry);public:- static constexpr size_t bounding_client_rect_offset() { return offsetof(IntersectionObserverEntry, m_bounding_client_rect); }- static constexpr size_t intersection_rect_offset() { return offsetof(IntersectionObserverEntry, m_intersection_rect); }static constexpr size_t target_offset() { return offsetof(IntersectionObserverEntry, m_target); }static GC::Ref<IntersectionObserverEntry> create(HighResolutionTime::DOMHighResTimeStamp time, GC::Ptr<Geometry::DOMRectReadOnly> root_bounds, GC::Ref<Geometry::DOMRectReadOnly> bounding_client_rect, GC::Ref<Geometry::DOMRectReadOnly> intersection_rect, bool is_intersecting, double intersection_ratio, GC::Ref<DOM::Element> target);@@ -27,7 +25,6 @@ public:HighResolutionTime::DOMHighResTimeStamp time() const { return m_time; }GC::Ptr<Geometry::DOMRectReadOnly> root_bounds() const { return m_root_bounds; }- static constexpr size_t root_bounds_offset() { return offsetof(IntersectionObserverEntry, m_root_bounds); }GC::Ref<Geometry::DOMRectReadOnly> bounding_client_rect() const { return m_bounding_client_rect; }GC::Ref<Geometry::DOMRectReadOnly> intersection_rect() const { return m_intersection_rect; }bool is_intersecting() const { return m_is_intersecting; }diff --git a/Libraries/LibWeb/IntersectionObserver/IntersectionObserverEntry.idl b/Libraries/LibWeb/IntersectionObserver/IntersectionObserverEntry.idlindex 9762d64e313..5cb6127a278 100644--- a/Libraries/LibWeb/IntersectionObserver/IntersectionObserverEntry.idl+++ b/Libraries/LibWeb/IntersectionObserver/IntersectionObserverEntry.idl@@ -3,9 +3,9 @@interface IntersectionObserverEntry {// FIXME: constructor(IntersectionObserverEntryInit intersectionObserverEntryInit);readonly attribute DOMHighResTimeStamp time;- [DirectGetter] readonly attribute DOMRectReadOnly? rootBounds;- [DirectGetter] readonly attribute DOMRectReadOnly boundingClientRect;- [DirectGetter] readonly attribute DOMRectReadOnly intersectionRect;+ readonly attribute DOMRectReadOnly? rootBounds;+ readonly attribute DOMRectReadOnly boundingClientRect;+ readonly attribute DOMRectReadOnly intersectionRect;readonly attribute boolean isIntersecting;readonly attribute double intersectionRatio;[DirectGetter] readonly attribute Element target;diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex fecc208d993..7b2d63b9d9c 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -7,6 +7,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <AK/AnyOf.h>#include <AK/Base64.h>#include <AK/Debug.h>#include <AK/Math.h>@@ -27,7 +28,6 @@#include <LibWeb/DOM/Text.h>#include <LibWeb/Editing/EditingHistory.h>#include <LibWeb/Editing/Internal/Algorithms.h>-#include <LibWeb/Geometry/DOMRectList.h>#include <LibWeb/GraphemeEdgeTracker.h>#include <LibWeb/HTML/CloseWatcherManager.h>#include <LibWeb/HTML/DataTransfer.h>@@ -3434,13 +3434,9 @@ void EventHandler::run_activation_behavior(GC::Ref<DOM::Node> node, unsigned butstatic bool range_contains_viewport_position(DOM::Range& range, CSSPixelPoint viewport_position){- auto rects = range.get_client_rects();- for (u32 index = 0; index < rects->length(); ++index) {- auto const* rect = rects->item(index);- if (Gfx::DoubleRect { rect->x(), rect->y(), rect->width(), rect->height() }.contains(viewport_position.to_type<double>()))- return true;- }- return false;+ return any_of(range.client_rects(), [&](auto const& rect) {+ return rect.contains(viewport_position.to_type<double>());+ });}// https://w3c.github.io/uievents/#maybe-show-context-menudiff --git a/Libraries/LibWeb/ResizeObserver/ResizeObserverEntry.h b/Libraries/LibWeb/ResizeObserver/ResizeObserverEntry.hindex 2a825044ee3..f2719d7d127 100644--- a/Libraries/LibWeb/ResizeObserver/ResizeObserverEntry.h+++ b/Libraries/LibWeb/ResizeObserver/ResizeObserverEntry.h@@ -20,7 +20,6 @@ class ResizeObserverEntry : public Bindings::GCAllocatedWrappable {public:static constexpr size_t target_offset() { return offsetof(ResizeObserverEntry, m_target); }- static constexpr size_t content_rect_offset() { return offsetof(ResizeObserverEntry, m_content_rect); }static WebIDL::ExceptionOr<GC::Ref<ResizeObserverEntry>> create_and_populate(Layout::BegunRead const& read, DOM::Element& target);GC::Ref<Geometry::DOMRectReadOnly> content_rect() const { return *m_content_rect; }diff --git a/Libraries/LibWeb/ResizeObserver/ResizeObserverEntry.idl b/Libraries/LibWeb/ResizeObserver/ResizeObserverEntry.idlindex ea9bcab3dbb..e7c3badcac1 100644--- a/Libraries/LibWeb/ResizeObserver/ResizeObserverEntry.idl+++ b/Libraries/LibWeb/ResizeObserver/ResizeObserverEntry.idl@@ -2,7 +2,7 @@[Exposed=Window]interface ResizeObserverEntry {[DirectGetter] readonly attribute Element target;- [DirectGetter] readonly attribute DOMRectReadOnly contentRect;+ readonly attribute DOMRectReadOnly contentRect;readonly attribute FrozenArray<ResizeObserverSize> borderBoxSize;readonly attribute FrozenArray<ResizeObserverSize> contentBoxSize;readonly attribute FrozenArray<ResizeObserverSize> devicePixelContentBoxSize;diff --git a/Libraries/LibWeb/SVG/SVGAnimatedRect.cpp b/Libraries/LibWeb/SVG/SVGAnimatedRect.cppindex 9edf1719c48..6299feb1879 100644--- a/Libraries/LibWeb/SVG/SVGAnimatedRect.cpp+++ b/Libraries/LibWeb/SVG/SVGAnimatedRect.cpp@@ -52,18 +52,12 @@ void SVGAnimatedRect::set_nulled(bool nulled)void SVGAnimatedRect::set_base_val(Gfx::DoubleRect const& rect){- m_base_val->set_x(rect.x());- m_base_val->set_y(rect.y());- m_base_val->set_width(rect.width());- m_base_val->set_height(rect.height());+ m_base_val->set(rect);}void SVGAnimatedRect::set_anim_val(Gfx::DoubleRect const& rect){- m_anim_val->set_x(rect.x());- m_anim_val->set_y(rect.y());- m_anim_val->set_width(rect.width());- m_anim_val->set_height(rect.height());+ m_anim_val->set(rect);}}diff --git a/Libraries/LibWeb/SVG/SVGSVGElement.h b/Libraries/LibWeb/SVG/SVGSVGElement.hindex 1f435082087..417b19c3d7b 100644--- a/Libraries/LibWeb/SVG/SVGSVGElement.h+++ b/Libraries/LibWeb/SVG/SVGSVGElement.h@@ -10,6 +10,9 @@#include <LibWeb/CSS/Sizing.h>#include <LibWeb/Geometry/DOMMatrix.h>#include <LibWeb/Geometry/DOMPoint.h>+#include <LibWeb/Geometry/DOMPointReadOnly.h>+#include <LibWeb/Geometry/DOMRect.h>+#include <LibWeb/Geometry/DOMRectReadOnly.h>#include <LibWeb/SVG/AttributeParsing.h>#include <LibWeb/SVG/SVGFitToViewBox.h>#include <LibWeb/SVG/SVGGraphicsElement.h>diff --git a/Libraries/LibWeb/WebDriver/ElementReference.cpp b/Libraries/LibWeb/WebDriver/ElementReference.cppindex fe7ac2904e7..d81d04a2aae 100644--- a/Libraries/LibWeb/WebDriver/ElementReference.cpp+++ b/Libraries/LibWeb/WebDriver/ElementReference.cpp@@ -11,7 +11,6 @@#include <LibWeb/DOM/Node.h>#include <LibWeb/DOM/ShadowRoot.h>#include <LibWeb/Geometry/DOMRect.h>-#include <LibWeb/Geometry/DOMRectList.h>#include <LibWeb/HTML/BrowsingContext.h>#include <LibWeb/HTML/HTMLBodyElement.h>#include <LibWeb/HTML/HTMLInputElement.h>diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 7e1dd08403f..dc665c3a256 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -50,10 +50,9 @@ ALLOWED_REALM_MENTIONS = {"Fetch bodies, headers, requests, responses, and controllers still materialize JS values/streams; the body receiver's delivery and close tasks carry the realm its stream is enqueued and closed in",),"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": (64,- 203,+ 202,"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/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex fa2eb50b0b1..1da8b1c7ffb 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -59,7 +59,6 @@#include <LibWeb/Fetch/Fetching/Fetching.h>#include <LibWeb/FileAPI/BlobURLStore.h>#include <LibWeb/Gamepad/GamepadRegistry.h>-#include <LibWeb/Geometry/DOMRect.h>#include <LibWeb/HTML/AutoplaySettings.h>#include <LibWeb/HTML/BroadcastChannel.h>#include <LibWeb/HTML/BrowsingContext.h>@@ -2876,14 +2875,14 @@ static Optional<Gfx::IntPoint> dictionary_lookup_baseline_origin_for_range(Web::if (!navigable)return {};- auto rect = range.get_bounding_client_rect();- if (rect->width() <= 0 || rect->height() <= 0)+ auto rect = range.bounding_client_rect();+ if (rect.width() <= 0 || rect.height() <= 0)return {};auto const& font = layout_node.first_available_font();Web::CSSPixelPoint baseline_origin {- Web::CSSPixels::nearest_value_for(rect->x()),- Web::CSSPixels::nearest_value_for(rect->y() + font.pixel_metrics().ascent),+ Web::CSSPixels::nearest_value_for(rect.x()),+ Web::CSSPixels::nearest_value_for(rect.y() + font.pixel_metrics().ascent),};return page.css_to_device_point(navigable->to_page_position(baseline_origin)).to_type<int>();}diff --git a/Tests/LibWeb/StructuredSerializeTestHelpers.h b/Tests/LibWeb/StructuredSerializeTestHelpers.hindex 8378b2f5d9e..d57e6eeebf0 100644--- a/Tests/LibWeb/StructuredSerializeTestHelpers.h+++ b/Tests/LibWeb/StructuredSerializeTestHelpers.h@@ -243,6 +243,26 @@ inline Web::HTML::IPCSerializationRecord structured_serialize(JS::VM& vm, GC::Rereturn MUST(Web::HTML::structured_serialize(vm, JS::Value(wrapper.ptr())));}+template<Web::Bindings::RustInterfaceHandle T>+inline Web::HTML::IPCSerializationRecord structured_serialize(JS::VM& vm, 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(vm, JS::Value(static_cast<JS::Object*>(wrapper.ptr()))));+}++// The value of the property of the object, which is a wrapper that the test reads as script would.+inline JS::Value property_of(JS::Value object, StringView name)+{+ VERIFY(object.is_object());+ return MUST(object.as_object().get(Utf16FlyString::from_utf8(name)));+}++inline double number_property(JS::Value object, StringView name)+{+ return property_of(object, name).as_double();+}+inline Web::WebIDL::ExceptionOr<JS::Value> storage_deserialize(Web::HTML::StorageSerializationRecord const& record){auto& realm = test_realm();@@ -321,7 +341,7 @@ inline ByteBuffer serialized_object_body(GC::Ref<JS::Object> object)}template<typename T>-requires(IsConvertible<T*, Web::Bindings::Wrappable*>)+requires(IsConvertible<T*, Web::Bindings::Wrappable*> || Web::Bindings::RustInterfaceHandle<T>)inline ByteBuffer serialized_object_body(GC::Ref<T> object){auto header_size = 6uz;diff --git a/Tests/LibWeb/TestStructuredSerializeDurability.cpp b/Tests/LibWeb/TestStructuredSerializeDurability.cppindex 7c18d8aef41..492b0e23f1f 100644--- a/Tests/LibWeb/TestStructuredSerializeDurability.cpp+++ b/Tests/LibWeb/TestStructuredSerializeDurability.cpp@@ -28,7 +28,6 @@#include <LibWeb/Geometry/DOMMatrix.h>#include <LibWeb/Geometry/DOMMatrixReadOnly.h>#include <LibWeb/Geometry/DOMPointReadOnly.h>-#include <LibWeb/Geometry/DOMQuad.h>#include <LibWeb/Geometry/DOMRect.h>#include <LibWeb/Geometry/DOMRectReadOnly.h>#include <LibWeb/HTML/ImageBitmap.h>@@ -44,18 +43,14 @@ TEST_CASE(serializable_objects_round_trip_through_storage){(void)test_realm();{- auto point = Web::Geometry::DOMPoint::create();- point->set_x(1.5);- point->set_y(-2.5);- point->set_z(3.25);- point->set_w(4.75);+ auto point = Web::Geometry::DOMPoint::create(1.5, -2.5, 3.25, 4.75);auto value = MUST(storage_deserialize(storage_serialize(point)));- auto& decoded = unwrap_wrappable<Web::Geometry::DOMPoint>(value);- EXPECT_EQ(decoded.x(), 1.5);- EXPECT_EQ(decoded.y(), -2.5);- EXPECT_EQ(decoded.z(), 3.25);- EXPECT_EQ(decoded.w(), 4.75);+ (void)unwrap_wrappable<Web::Geometry::DOMPoint>(value);+ EXPECT_EQ(number_property(value, "x"sv), 1.5);+ EXPECT_EQ(number_property(value, "y"sv), -2.5);+ EXPECT_EQ(number_property(value, "z"sv), 3.25);+ EXPECT_EQ(number_property(value, "w"sv), 4.75);}{@@ -72,8 +67,7 @@ TEST_CASE(storage_round_trips_serializable_with_nested_sub_value_before_more_fie{(void)test_realm();// Nested sub-values must not trigger the outer full-consumption check.- auto point = Web::Geometry::DOMPoint::create();- point->set_x(7.0);+ auto point = Web::Geometry::DOMPoint::create(7.0);auto point_body = serialized_object_body(point);Vector<u8> quad_body;@@ -394,16 +388,18 @@ TEST_CASE(geometry_serializables_round_trip)append_little_endian_double(point_body, -4.5);{- auto& point = unwrap_wrappable<Web::Geometry::DOMPointReadOnly>(MUST(storage_deserialize(serializable_storage_record("DOMPointReadOnly"sv, 1, point_body))));- EXPECT_EQ(point.x(), 1.5);- EXPECT_EQ(point.y(), -2.5);- EXPECT_EQ(point.z(), 3.5);- EXPECT_EQ(point.w(), -4.5);+ auto point = MUST(storage_deserialize(serializable_storage_record("DOMPointReadOnly"sv, 1, point_body)));+ (void)unwrap_wrappable<Web::Geometry::DOMPointReadOnly>(point);+ EXPECT_EQ(number_property(point, "x"sv), 1.5);+ EXPECT_EQ(number_property(point, "y"sv), -2.5);+ EXPECT_EQ(number_property(point, "z"sv), 3.5);+ EXPECT_EQ(number_property(point, "w"sv), -4.5);}{- auto& point = unwrap_wrappable<Web::Geometry::DOMPoint>(MUST(storage_deserialize(serializable_storage_record("DOMPoint"sv, 1, point_body))));- EXPECT_EQ(point.x(), 1.5);- EXPECT_EQ(point.w(), -4.5);+ auto point = MUST(storage_deserialize(serializable_storage_record("DOMPoint"sv, 1, point_body)));+ (void)unwrap_wrappable<Web::Geometry::DOMPoint>(point);+ EXPECT_EQ(number_property(point, "x"sv), 1.5);+ EXPECT_EQ(number_property(point, "w"sv), -4.5);}Vector<u8> rect_body;@@ -413,16 +409,18 @@ TEST_CASE(geometry_serializables_round_trip)append_little_endian_double(rect_body, 40.0);{- auto& rect = unwrap_wrappable<Web::Geometry::DOMRectReadOnly>(MUST(storage_deserialize(serializable_storage_record("DOMRectReadOnly"sv, 1, rect_body))));- EXPECT_EQ(rect.x(), 10.0);- EXPECT_EQ(rect.y(), 20.0);- EXPECT_EQ(rect.width(), 30.0);- EXPECT_EQ(rect.height(), 40.0);+ auto rect = MUST(storage_deserialize(serializable_storage_record("DOMRectReadOnly"sv, 1, rect_body)));+ (void)unwrap_wrappable<Web::Geometry::DOMRectReadOnly>(rect);+ EXPECT_EQ(number_property(rect, "x"sv), 10.0);+ EXPECT_EQ(number_property(rect, "y"sv), 20.0);+ EXPECT_EQ(number_property(rect, "width"sv), 30.0);+ EXPECT_EQ(number_property(rect, "height"sv), 40.0);}{- auto& rect = unwrap_wrappable<Web::Geometry::DOMRect>(MUST(storage_deserialize(serializable_storage_record("DOMRect"sv, 1, rect_body))));- EXPECT_EQ(rect.width(), 30.0);- EXPECT_EQ(rect.height(), 40.0);+ auto rect = MUST(storage_deserialize(serializable_storage_record("DOMRect"sv, 1, rect_body)));+ (void)unwrap_wrappable<Web::Geometry::DOMRect>(rect);+ EXPECT_EQ(number_property(rect, "width"sv), 30.0);+ EXPECT_EQ(number_property(rect, "height"sv), 40.0);}{@@ -430,22 +428,22 @@ TEST_CASE(geometry_serializables_round_trip)body.append(1);for (double element : { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 })append_little_endian_double(body, element);- auto& matrix = unwrap_wrappable<Web::Geometry::DOMMatrixReadOnly>(MUST(storage_deserialize(serializable_storage_record("DOMMatrixReadOnly"sv, 1, body))));- EXPECT(matrix.is2d());- EXPECT_EQ(matrix.m11(), 1.0);- EXPECT_EQ(matrix.m22(), 4.0);- EXPECT_EQ(matrix.m42(), 6.0);+ auto matrix = MUST(storage_deserialize(serializable_storage_record("DOMMatrixReadOnly"sv, 1, body)));+ EXPECT(unwrap_wrappable<Web::Geometry::DOMMatrixReadOnly>(matrix).is2d());+ EXPECT_EQ(number_property(matrix, "m11"sv), 1.0);+ EXPECT_EQ(number_property(matrix, "m22"sv), 4.0);+ EXPECT_EQ(number_property(matrix, "m42"sv), 6.0);}{Vector<u8> body;body.append(0);for (int i = 1; i <= 16; ++i)append_little_endian_double(body, static_cast<double>(i));- auto& matrix = unwrap_wrappable<Web::Geometry::DOMMatrix>(MUST(storage_deserialize(serializable_storage_record("DOMMatrix"sv, 1, body))));- EXPECT(!matrix.is2d());- EXPECT_EQ(matrix.m11(), 1.0);- EXPECT_EQ(matrix.m22(), 6.0);- EXPECT_EQ(matrix.m44(), 16.0);+ auto matrix = MUST(storage_deserialize(serializable_storage_record("DOMMatrix"sv, 1, body)));+ EXPECT(!unwrap_wrappable<Web::Geometry::DOMMatrix>(matrix).is2d());+ EXPECT_EQ(number_property(matrix, "m11"sv), 1.0);+ EXPECT_EQ(number_property(matrix, "m22"sv), 6.0);+ EXPECT_EQ(number_property(matrix, "m44"sv), 16.0);}{Vector<u8> body;@@ -457,10 +455,10 @@ TEST_CASE(geometry_serializables_round_trip)append_little_endian_double(nested_point, (k * 4) + 4.0);frozen_serializable_value(body, "DOMPoint"sv, 1, nested_point);}- auto& quad = unwrap_wrappable<Web::Geometry::DOMQuad>(MUST(storage_deserialize(serializable_storage_record("DOMQuad"sv, 1, body))));- EXPECT_EQ(quad.p1()->x(), 1.0);- EXPECT_EQ(quad.p2()->x(), 5.0);- EXPECT_EQ(quad.p4()->w(), 16.0);+ auto quad = MUST(storage_deserialize(serializable_storage_record("DOMQuad"sv, 1, body)));+ EXPECT_EQ(number_property(property_of(quad, "p1"sv), "x"sv), 1.0);+ EXPECT_EQ(number_property(property_of(quad, "p2"sv), "x"sv), 5.0);+ EXPECT_EQ(number_property(property_of(quad, "p4"sv), "w"sv), 16.0);}}diff --git a/Tests/LibWeb/TestStructuredSerializeFormat.cpp b/Tests/LibWeb/TestStructuredSerializeFormat.cppindex 5ef460e210e..0cad10e018f 100644--- a/Tests/LibWeb/TestStructuredSerializeFormat.cpp+++ b/Tests/LibWeb/TestStructuredSerializeFormat.cpp@@ -17,9 +17,7 @@#include <LibWeb/FileAPI/File.h>#include <LibWeb/FileAPI/FileList.h>#include <LibWeb/Geometry/DOMMatrix.h>-#include <LibWeb/Geometry/DOMMatrixReadOnly.h>#include <LibWeb/Geometry/DOMPointReadOnly.h>-#include <LibWeb/Geometry/DOMQuad.h>#include <LibWeb/Geometry/DOMRect.h>#include <LibWeb/Geometry/DOMRectReadOnly.h>#include <LibWeb/HTML/ImageBitmap.h>@@ -427,11 +425,7 @@ TEST_CASE(record_wrappers_round_trip_through_ipc)TEST_CASE(storage_serializable_object_is_framed_with_interface_then_version){(void)test_realm();- auto point = Web::Geometry::DOMPoint::create();- point->set_x(1.0);- point->set_y(2.0);- point->set_z(3.0);- point->set_w(4.0);+ auto point = Web::Geometry::DOMPoint::create(1.0, 2.0, 3.0, 4.0);auto record = storage_serialize(point);@@ -455,11 +449,7 @@ TEST_CASE(storage_serializable_object_is_framed_with_interface_then_version)TEST_CASE(ipc_serializable_object_has_no_version_framing){- auto point = Web::Geometry::DOMPoint::create();- point->set_x(1.0);- point->set_y(2.0);- point->set_z(3.0);- point->set_w(4.0);+ auto point = Web::Geometry::DOMPoint::create(1.0, 2.0, 3.0, 4.0);auto record = structured_serialize(test_realm().vm(), point);Web::HTML::StructuredSerializeReader reader { record };@@ -538,11 +528,7 @@ TEST_CASE(geometry_serializables_encode_to_frozen_bytes){(void)test_realm();{- auto point = Web::Geometry::DOMPoint::create();- point->set_x(1.5);- point->set_y(-2.5);- point->set_z(3.5);- point->set_w(-4.5);+ auto point = Web::Geometry::DOMPoint::create(1.5, -2.5, 3.5, -4.5);Vector<u8> body;for (double element : { 1.5, -2.5, 3.5, -4.5 })append_little_endian_double(body, element);@@ -553,11 +539,7 @@ TEST_CASE(geometry_serializables_encode_to_frozen_bytes)}{- auto rect = Web::Geometry::DOMRect::create();- rect->set_x(10.0);- rect->set_y(20.0);- rect->set_width(30.0);- rect->set_height(40.0);+ auto rect = Web::Geometry::DOMRect::create(10.0, 20.0, 30.0, 40.0);Vector<u8> body;for (double element : { 10.0, 20.0, 30.0, 40.0 })append_little_endian_double(body, element);@@ -569,12 +551,12 @@ TEST_CASE(geometry_serializables_encode_to_frozen_bytes){// Identity 2D matrices serialize six components.- auto matrix = Web::Geometry::DOMMatrixReadOnly::create();Vector<u8> body;body.append(1);for (double element : { 1.0, 0.0, 0.0, 1.0, 0.0, 0.0 })append_little_endian_double(body, element);- expect_storage_encoding(matrix, serializable_storage_record("DOMMatrixReadOnly"sv, 1, body));+ auto record = serializable_storage_record("DOMMatrixReadOnly"sv, 1, body);+ expect_storage_encoding(GC::Ref { MUST(storage_deserialize(record)).as_object() }, record);auto mutable_matrix = Web::Geometry::DOMMatrix::create();expect_storage_encoding(mutable_matrix, serializable_storage_record("DOMMatrix"sv, 1, body));@@ -582,17 +564,15 @@ TEST_CASE(geometry_serializables_encode_to_frozen_bytes){// DOMQuad serializes its four corner points as nested DOMPoint sub-values.- auto quad = Web::Geometry::DOMQuad::create();Vector<u8> body;- for (auto point : Array { quad->p1(), quad->p2(), quad->p3(), quad->p4() }) {+ for (int i = 0; i < 4; ++i) {Vector<u8> point_body;- append_little_endian_double(point_body, point->x());- append_little_endian_double(point_body, point->y());- append_little_endian_double(point_body, point->z());- append_little_endian_double(point_body, point->w());+ for (double coordinate : { 1.0 + i, 2.0, 3.0, 4.0 })+ append_little_endian_double(point_body, coordinate);frozen_serializable_value(body, "DOMPoint"sv, 1, point_body);}- expect_storage_encoding(quad, serializable_storage_record("DOMQuad"sv, 1, body));+ auto record = serializable_storage_record("DOMQuad"sv, 1, body);+ expect_storage_encoding(GC::Ref { MUST(storage_deserialize(record)).as_object() }, record);}}diff --git a/Tests/LibWeb/Text/expected/css/typed-om-transform-component-to-matrix-is-2d.txt b/Tests/LibWeb/Text/expected/css/typed-om-transform-component-to-matrix-is-2d.txtnew file mode 100644index 00000000000..7c66ca41151--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/typed-om-transform-component-to-matrix-is-2d.txt@@ -0,0 +1,8 @@+CSSScale(2, 3): is2D true, toMatrix().is2D true+CSSScale(2, 3, 1): is2D false, toMatrix().is2D false+CSSTranslate(1px, 2px): is2D true, toMatrix().is2D true+CSSTranslate(1px, 2px, 0px): is2D false, toMatrix().is2D false+CSSRotate(45deg): is2D true, toMatrix().is2D true+CSSRotate(0, 0, 1, 45deg): is2D false, toMatrix().is2D false+CSSSkew(10deg, 20deg): is2D true, toMatrix().is2D true+CSSPerspective(none): is2D false, toMatrix().is2D falsediff --git a/Tests/LibWeb/Text/expected/geometry/dommatrix-from-detached-typed-array.txt b/Tests/LibWeb/Text/expected/geometry/dommatrix-from-detached-typed-array.txtnew file mode 100644index 00000000000..17f13850583--- /dev/null+++ b/Tests/LibWeb/Text/expected/geometry/dommatrix-from-detached-typed-array.txt@@ -0,0 +1,6 @@+detached, Float32Array: TypeError+detached, Float64Array: TypeError+out of bounds after a resize, Float32Array: TypeError+out of bounds after a resize, Float64Array: TypeError+six elements, Float32Array: no exception+six elements, Float64Array: no exceptiondiff --git a/Tests/LibWeb/Text/expected/geometry/dommatrix-is-identity.txt b/Tests/LibWeb/Text/expected/geometry/dommatrix-is-identity.txtnew file mode 100644index 00000000000..76611507676--- /dev/null+++ b/Tests/LibWeb/Text/expected/geometry/dommatrix-is-identity.txt@@ -0,0 +1,29 @@+identity: true+m12 = 2: false+m12 = -0: true+m13 = 2: false+m13 = -0: true+m14 = 2: false+m14 = -0: true+m21 = 2: false+m21 = -0: true+m23 = 2: false+m23 = -0: true+m24 = 2: false+m24 = -0: true+m31 = 2: false+m31 = -0: true+m32 = 2: false+m32 = -0: true+m34 = 2: false+m34 = -0: true+m41 = 2: false+m41 = -0: true+m42 = 2: false+m42 = -0: true+m43 = 2: false+m43 = -0: true+m11 = 2: false+m22 = 2: false+m33 = 2: false+m44 = 2: falsediff --git a/Tests/LibWeb/Text/input/css/typed-om-transform-component-to-matrix-is-2d.html b/Tests/LibWeb/Text/input/css/typed-om-transform-component-to-matrix-is-2d.htmlnew file mode 100644index 00000000000..191170de54c--- /dev/null+++ b/Tests/LibWeb/Text/input/css/typed-om-transform-component-to-matrix-is-2d.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ // The matrix of a component has the is2D of the component.+ const components = {+ "CSSScale(2, 3)": new CSSScale(2, 3),+ "CSSScale(2, 3, 1)": new CSSScale(2, 3, 1),+ "CSSTranslate(1px, 2px)": new CSSTranslate(CSS.px(1), CSS.px(2)),+ "CSSTranslate(1px, 2px, 0px)": new CSSTranslate(CSS.px(1), CSS.px(2), CSS.px(0)),+ "CSSRotate(45deg)": new CSSRotate(CSS.deg(45)),+ "CSSRotate(0, 0, 1, 45deg)": new CSSRotate(CSS.number(0), CSS.number(0), CSS.number(1), CSS.deg(45)),+ "CSSSkew(10deg, 20deg)": new CSSSkew(CSS.deg(10), CSS.deg(20)),+ "CSSPerspective(none)": new CSSPerspective(new CSSKeywordValue("none")),+ };+ for (const [name, component] of Object.entries(components))+ println(`${name}: is2D ${component.is2D}, toMatrix().is2D ${component.toMatrix().is2D}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/geometry/dommatrix-from-detached-typed-array.html b/Tests/LibWeb/Text/input/geometry/dommatrix-from-detached-typed-array.htmlnew file mode 100644index 00000000000..a3bbf1a117d--- /dev/null+++ b/Tests/LibWeb/Text/input/geometry/dommatrix-from-detached-typed-array.html@@ -0,0 +1,34 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ function check(name, make) {+ try {+ DOMMatrix.fromFloat32Array(make(Float32Array));+ println(`${name}, Float32Array: no exception`);+ } catch (e) {+ println(`${name}, Float32Array: ${e.name}`);+ }+ try {+ DOMMatrixReadOnly.fromFloat64Array(make(Float64Array));+ println(`${name}, Float64Array: no exception`);+ } catch (e) {+ println(`${name}, Float64Array: ${e.name}`);+ }+ }++ check("detached", type => {+ const buffer = new ArrayBuffer(256);+ const array = new type(buffer, 16, 6);+ buffer.transfer();+ return array;+ });+ check("out of bounds after a resize", type => {+ const buffer = new ArrayBuffer(256, { maxByteLength: 512 });+ const array = new type(buffer, 64, 6);+ buffer.resize(16);+ return array;+ });+ check("six elements", type => new type(6));+ });+</script>diff --git a/Tests/LibWeb/Text/input/geometry/dommatrix-is-identity.html b/Tests/LibWeb/Text/input/geometry/dommatrix-is-identity.htmlnew file mode 100644index 00000000000..4e1c0231534--- /dev/null+++ b/Tests/LibWeb/Text/input/geometry/dommatrix-is-identity.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ println(`identity: ${new DOMMatrix().isIdentity}`);+ for (const element of ["m12", "m13", "m14", "m21", "m23", "m24", "m31", "m32", "m34", "m41", "m42", "m43"]) {+ const matrix = new DOMMatrix();+ matrix[element] = 2;+ println(`${element} = 2: ${matrix.isIdentity}`);+ matrix[element] = -0;+ println(`${element} = -0: ${matrix.isIdentity}`);+ }+ for (const element of ["m11", "m22", "m33", "m44"]) {+ const matrix = new DOMMatrix();+ matrix[element] = 2;+ println(`${element} = 2: ${matrix.isIdentity}`);+ }+ });+</script>