Truly independent web browser
LibWeb: Implement CanvasPattern in Rust
Andreas Kling88bcaafb0ec0
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.rsnew file mode 100644index 00000000000..bcf176a7950--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix_read_only.rs@@ -0,0 +1,197 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * 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>,+}++/// 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 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),+ })+}++#[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));+ }++ #[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());+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rsnew file mode 100644index 00000000000..7dd23b6751d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rs@@ -0,0 +1,10 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * 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++.++pub(crate) mod dom_matrix_read_only;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rsnew file mode 100644index 00000000000..52a025aede5--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_pattern.rs@@ -0,0 +1,77 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://html.spec.whatwg.org/multipage/canvas.html#canvaspattern++use core::cell::Cell;++use libcompositing_rust::display_list::commands::Canvas2DPatternRepetition;+use libgfx_rust::AffineTransform;+use libgfx_rust::image_frame::ImageFrameHandle;+use libjs_rust::api::{Trace, Vm};++use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::geometry::dom_matrix_read_only::{DOMMatrix2DInit, validate_and_fixup_2d};++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CanvasPattern {+ /// The frame of the image when createPattern() was called, if the image had one.+ #[gc(untraced)]+ image: Option<ImageFrameHandle>,+ #[gc(untraced)]+ repetition: Canvas2DPatternRepetition,+ #[gc(untraced)]+ transform: Cell<Option<AffineTransform>>,+}++impl Wrappable for CanvasPattern {}++impl CanvasPattern {+ /// The pattern of createPattern(), whose image and repetition the context has checked,+ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createpattern+ pub(crate) fn create(vm: &Vm, image: Option<ImageFrameHandle>, repetition: Canvas2DPatternRepetition) -> Ref<Self> {+ allocate(+ vm,+ Self {+ image,+ repetition,+ transform: Cell::new(None),+ },+ )+ }++ pub(crate) fn image(&self) -> Option<&ImageFrameHandle> {+ self.image.as_ref()+ }++ pub(crate) fn repetition(&self) -> Canvas2DPatternRepetition {+ self.repetition+ }++ /// The transformation matrix of the pattern, which it has once setTransform() gave it one.+ pub(crate) fn transform(&self) -> Option<AffineTransform> {+ self.transform.get()+ }++ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-canvaspattern-settransform+ pub(crate) fn set_transform(&self, _: &mut CallContext, transform: DOMMatrix2DInit) -> WebIdlResult<()> {+ // 1. Let matrix be the result of creating a DOMMatrix from the 2D dictionary transform.+ let matrix = validate_and_fixup_2d(&transform)?;++ // 2. If one or more of matrix's m11 element, m12 element, m21 element, m22 element, m41 element, or m42+ // element are infinite or NaN, then return.+ if !matrix.is_finite() {+ return Ok(());+ }++ // 3. Reset the pattern's transformation matrix to matrix.+ self.transform.set(Some(matrix.to_affine_transform()));++ Ok(())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 8459d015719..bd5eb44521c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -12,10 +12,12 @@ use core::ffi::c_void;use libcompositing_rust::display_list::canvas_2d::Paint;use libcompositing_rust::display_list::canvas_2d_recorder::FfiCanvas2DPaint;-use libcompositing_rust::display_list::commands::Canvas2DPaintKind;+use libcompositing_rust::display_list::commands::{Canvas2DPaintKind, Canvas2DPatternRepetition};+use libgfx_rust::image_frame::ImageFrameHandle;use libjs_rust::api::Vm;use super::canvas_gradient::CanvasGradient;+use super::canvas_pattern::CanvasPattern;use super::text_metrics::{TextMeasurements, TextMetrics};use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi};@@ -171,3 +173,39 @@ pub unsafe extern "C" fn web_text_metrics_create(vm: *mut c_void, measurements:let vm = unsafe { vm_from_abi(vm) };cell_into_abi(TextMetrics::create(vm, *measurements))}++/// `frame` is a Gfx::DecodedImageFrame that the caller lends for the call, which the pattern keeps a copy of, or null.+///+/// # Safety+///+/// `vm` must be the live VM, and `frame` a live frame or null.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_canvas_pattern_create(+ vm: *mut c_void,+ frame: *const c_void,+ repetition: Canvas2DPatternRepetition,+) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { vm_from_abi(vm) };+ // SAFETY: The caller passes a live frame.+ let image = (!frame.is_null()).then(|| unsafe { ImageFrameHandle::retain(frame) });+ cell_into_abi(CanvasPattern::create(vm, image, repetition))+}++/// Lends the recorder the image, the repetition and the transformation matrix of the pattern.+///+/// # Safety+///+/// `pattern` must be a live cell, which outlives the use of the paint.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_canvas_pattern_lend_paint(pattern: *mut c_void, out_paint: &mut FfiCanvas2DPaint<'_>) {+ // SAFETY: The caller passes a live cell, which keeps the image alive while the paint is in use.+ let pattern: &CanvasPattern = unsafe { object_from_abi(pattern) };+ out_paint.kind = Canvas2DPaintKind::Pattern;+ out_paint.pattern_repetition = pattern.repetition();+ out_paint.pattern_image = pattern.image().map_or(core::ptr::null(), ImageFrameHandle::as_raw);+ if let Some(transform) = pattern.transform() {+ out_paint.has_pattern_transform = true;+ out_paint.pattern_transform = transform;+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex e8b12848d10..8f908106ebd 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -13,6 +13,8 @@ pub(crate) mod color_stops;#[cfg(not(test))]pub(crate) mod canvas_gradient;#[cfg(not(test))]+pub(crate) mod canvas_pattern;+#[cfg(not(test))]pub(crate) mod exports;#[cfg(not(test))]pub(crate) mod text_metrics;diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 1c8a38e42ba..a86fd28f173 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -38,6 +38,11 @@ pub(crate) mod encoding;not(web_idl_bindings),allow(dead_code, reason = "only the generated bindings use the interfaces"))]+pub(crate) mod geometry;+#[cfg_attr(+ 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"diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cppindex 7449282684a..81a81d006b2 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DRecorder.cpp@@ -5,7 +5,6 @@*/#include <AK/Noncopyable.h>-#include <AK/TypeCasts.h>#include <AK/Vector.h>#include <LibCompositing/DisplayList/DisplayListCommandsGenerated.h>#include <LibCompositing/RustFFI.h>@@ -13,7 +12,6 @@#include <LibGfx/DecodedImageFrame.h>#include <LibGfx/Filter.h>#include <LibGfx/Font/Font.h>-#include <LibGfx/PaintStyle.h>#include <LibWeb/HTML/Canvas/Canvas2DRecorder.h>#include <LibWeb/HTML/Canvas/DrawingState.h>#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>@@ -28,11 +26,6 @@ using Compositing::RustFFI::FfiCanvas2DStroke;static_assert(to_underlying(Gfx::AlphaType::Premultiplied) == 0);static_assert(to_underlying(Gfx::AlphaType::Unpremultiplied) == 1);-static_assert(to_underlying(Compositing::Canvas2DPatternRepetition::Repeat) == to_underlying(Gfx::CanvasPatternPaintStyle::Repetition::Repeat));-static_assert(to_underlying(Compositing::Canvas2DPatternRepetition::RepeatX) == to_underlying(Gfx::CanvasPatternPaintStyle::Repetition::RepeatX));-static_assert(to_underlying(Compositing::Canvas2DPatternRepetition::RepeatY) == to_underlying(Gfx::CanvasPatternPaintStyle::Repetition::RepeatY));-static_assert(to_underlying(Compositing::Canvas2DPatternRepetition::NoRepeat) == to_underlying(Gfx::CanvasPatternPaintStyle::Repetition::NoRepeat));-// The C ABI of Libraries/LibWeb/Bindings/Rust/src/canvas_2d/exports.rs.extern "C" {RustCanvas2DRecorder* web_canvas_2d_recorder_create(void* transport);@@ -60,12 +53,13 @@ void web_canvas_2d_recorder_clear_canvas(RustCanvas2DRecorder*, Gfx::Color);// Defined in Bindings/Rust/src/html/exports.rs.void web_canvas_gradient_lend_paint(void* gradient, FfiCanvas2DPaint* out_paint);+void web_canvas_pattern_lend_paint(void* pattern, FfiCanvas2DPaint* out_paint);}namespace {-// A fill or stroke style as the recorder borrows it, with the pattern image it lends kept alive. A gradient lends its-// color stops, which do not change while the recorder borrows them.+// A fill or stroke style as the recorder borrows it. A gradient lends its color stops and a pattern its image, which+// stay as they are while the recorder borrows them.class LentPaint {AK_MAKE_NONCOPYABLE(LentPaint);AK_MAKE_NONMOVABLE(LentPaint);@@ -87,18 +81,8 @@ public:[&](GC::Ref<CanvasGradient> gradient) {web_canvas_gradient_lend_paint(gradient.ptr(), &m_paint);},- [&](GC::Ref<CanvasPattern> canvas_pattern) {- auto paint_style = canvas_pattern->to_gfx_paint_style();- auto const& pattern = as<Gfx::CanvasPatternPaintStyle>(*paint_style);- m_paint.kind = Compositing::Canvas2DPaintKind::Pattern;- m_paint.pattern_repetition = static_cast<Compositing::Canvas2DPatternRepetition>(to_underlying(pattern.repetition()));- m_pattern_image = pattern.image();- if (m_pattern_image.has_value())- m_paint.pattern_image = &m_pattern_image.value();- if (auto const& transform = pattern.transform(); transform.has_value()) {- m_paint.has_pattern_transform = true;- m_paint.pattern_transform = *transform;- }+ [&](GC::Ref<CanvasPattern> pattern) {+ web_canvas_pattern_lend_paint(pattern.ptr(), &m_paint);});}@@ -120,7 +104,6 @@ private:.pattern_image = nullptr,.pattern_transform = {},};- Optional<Gfx::DecodedImageFrame> m_pattern_image;};}diff --git a/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp b/Libraries/LibWeb/HTML/Canvas/DrawingState.cppindex 3c0389e2e61..fd01273fab8 100644--- a/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp+++ b/Libraries/LibWeb/HTML/Canvas/DrawingState.cpp@@ -13,7 +13,7 @@ bool FillOrStrokeStyle::is_visible() constreturn m_fill_or_stroke_style.visit([](Gfx::Color color) { return color.alpha() > 0; },[](GC::Ref<CanvasGradient> gradient) { return gradient->is_visible(); },- [](GC::Ref<CanvasPattern> pattern) { return pattern->to_gfx_paint_style()->is_visible(); });+ [](GC::Ref<CanvasPattern>) { return true; });}Gfx::Color FillOrStrokeStyle::to_color_but_fixme_should_accept_any_paint_style() constdiff --git a/Libraries/LibWeb/HTML/CanvasPattern.cpp b/Libraries/LibWeb/HTML/CanvasPattern.cppindex 2f8b3689d8c..54ee2410015 100644--- a/Libraries/LibWeb/HTML/CanvasPattern.cpp+++ b/Libraries/LibWeb/HTML/CanvasPattern.cpp@@ -6,12 +6,10 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>#include <LibGfx/DecodedImageFrame.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/VM.h>-#include <LibWeb/Bindings/DOMMatrixReadOnly.h>#include <LibWeb/Compositor/CompositorHost.h>-#include <LibWeb/Geometry/DOMMatrix.h>#include <LibWeb/HTML/Canvas/Canvas2DRecorder.h>#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>#include <LibWeb/HTML/CanvasPattern.h>@@ -21,15 +19,12 @@namespace Web::HTML {-GC_DEFINE_ALLOCATOR(CanvasPattern);+extern "C" {-CanvasPattern::CanvasPattern(Gfx::CanvasPatternPaintStyle& pattern)- : m_pattern(pattern)-{+// Defined in Bindings/Rust/src/html/exports.rs.+void* web_canvas_pattern_create(JSVM*, Gfx::DecodedImageFrame const* frame, Compositing::Canvas2DPatternRepetition);}-CanvasPattern::~CanvasPattern() = default;-// A pattern outlives any one video frame, so it reads the frame back instead of holding it.static Optional<Gfx::DecodedImageFrame> read_back_current_video_frame(HTMLVideoElement& video){@@ -61,15 +56,15 @@ static Optional<Gfx::DecodedImageFrame> read_back_current_video_frame(HTMLVideoE// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createpatternWebIDL::ExceptionOr<GC::Ptr<CanvasPattern>> CanvasPattern::create(CanvasImageSource const& image, Utf16FlyString const& repetition){- auto parse_repetition = [&](auto value) -> Optional<Gfx::CanvasPatternPaintStyle::Repetition> {+ auto parse_repetition = [&](auto value) -> Optional<Compositing::Canvas2DPatternRepetition> {if (value == u"repeat"sv)- return Gfx::CanvasPatternPaintStyle::Repetition::Repeat;+ return Compositing::Canvas2DPatternRepetition::Repeat;if (value == u"repeat-x"sv)- return Gfx::CanvasPatternPaintStyle::Repetition::RepeatX;+ return Compositing::Canvas2DPatternRepetition::RepeatX;if (value == u"repeat-y"sv)- return Gfx::CanvasPatternPaintStyle::Repetition::RepeatY;+ return Compositing::Canvas2DPatternRepetition::RepeatY;if (value == u"no-repeat"sv)- return Gfx::CanvasPatternPaintStyle::Repetition::NoRepeat;+ return Compositing::Canvas2DPatternRepetition::NoRepeat;return {};};@@ -98,35 +93,12 @@ WebIDL::ExceptionOr<GC::Ptr<CanvasPattern>> CanvasPattern::create(CanvasImageSouframe = read_back_current_video_frame(*video);elseframe = canvas_image_source_frame(image);- auto paint_style = TRY_OR_THROW_OOM(JS::VM::the(), Gfx::CanvasPatternPaintStyle::create(frame, *repetition_value));+ auto* pattern = static_cast<CanvasPattern*>(web_canvas_pattern_create(JS::HostABI::vm_to_abi(JS::VM::the()), frame.has_value() ? &frame.value() : nullptr, *repetition_value));// FIXME: 7. If image is not origin-clean, then mark pattern as not origin-clean.// 8. Return pattern.- return GC::Heap::the().allocate<CanvasPattern>(*paint_style);-}--// https://html.spec.whatwg.org/multipage/canvas.html#dom-canvaspattern-settransform-WebIDL::ExceptionOr<void> CanvasPattern::set_transform(GC::Ref<Geometry::DOMMatrix> matrix)-{- // 1. Let matrix be the result of creating a DOMMatrix from the 2D dictionary transform.- // NB: This is done by the binding helper before entering the implementation.-- // 2. If one or more of matrix's m11 element, m12 element, m21 element, m22 element, m41 element, or m42 element are infinite or NaN, then return.- if (!isfinite(matrix->m11()) || !isfinite(matrix->m12()) || !isfinite(matrix->m21()) || !isfinite(matrix->m22()) || !isfinite(matrix->m41()) || !isfinite(matrix->m42()))- return {};-- // 3. Reset the pattern's transformation matrix to matrix.- Gfx::AffineTransform affine_transform(matrix->a(), matrix->b(), matrix->c(), matrix->d(), matrix->e(), matrix->f());- m_pattern->set_transform(affine_transform);-- return {};-}--WebIDL::ExceptionOr<void> CanvasPattern::set_transform(Bindings::DOMMatrix2DInit const& transform)-{- auto matrix = Geometry::DOMMatrix::create_from_dom_matrix_2d_init(TRY(Geometry::validate_and_fixup_dom_matrix_2d_init(transform)));- return set_transform(matrix);+ return GC::Ptr { pattern };}}diff --git a/Libraries/LibWeb/HTML/CanvasPattern.h b/Libraries/LibWeb/HTML/CanvasPattern.hindex 7ae0bf0f9c0..088e41468fe 100644--- a/Libraries/LibWeb/HTML/CanvasPattern.h+++ b/Libraries/LibWeb/HTML/CanvasPattern.h@@ -9,42 +9,21 @@#pragma once#include <AK/Utf16FlyString.h>-#include <LibGfx/PaintStyle.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/CanvasPattern.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Export.h>#include <LibWeb/HTML/Canvas/CanvasDrawImage.h>-namespace Web::Bindings {--struct DOMMatrix2DInit;--}--namespace Web::Geometry {--class DOMMatrix;--}-namespace Web::HTML {-class CanvasPattern final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(CanvasPattern, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(CanvasPattern);+// https://html.spec.whatwg.org/multipage/canvas.html#canvaspattern+// The C++ side of a CanvasPattern, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what the+// 2D contexts create and paint with.+class WEB_API CanvasPattern final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(CanvasPattern, canvas_pattern)public:static WebIDL::ExceptionOr<GC::Ptr<CanvasPattern>> create(CanvasImageSource const& image, Utf16FlyString const& repetition);-- ~CanvasPattern();-- NonnullRefPtr<Gfx::PaintStyle> to_gfx_paint_style() { return m_pattern; }- WebIDL::ExceptionOr<void> set_transform(GC::Ref<Geometry::DOMMatrix> transform);- WebIDL::ExceptionOr<void> set_transform(Bindings::DOMMatrix2DInit const& transform);--private:- CanvasPattern(Gfx::CanvasPatternPaintStyle&);-- NonnullRefPtr<Gfx::CanvasPatternPaintStyle> m_pattern;};}diff --git a/Libraries/LibWeb/HTML/CanvasPattern.idl b/Libraries/LibWeb/HTML/CanvasPattern.idlindex 8bfec9dc0a3..066b4c0eac2 100644--- a/Libraries/LibWeb/HTML/CanvasPattern.idl+++ b/Libraries/LibWeb/HTML/CanvasPattern.idl@@ -1,5 +1,5 @@// https://html.spec.whatwg.org/multipage/canvas.html#canvaspattern-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface CanvasPattern {// opaque objectundefined setTransform(optional DOMMatrix2DInit transform = {});diff --git a/Tests/LibWeb/Text/expected/canvas/pattern-set-transform.txt b/Tests/LibWeb/Text/expected/canvas/pattern-set-transform.txtnew file mode 100644index 00000000000..f53fce71074--- /dev/null+++ b/Tests/LibWeb/Text/expected/canvas/pattern-set-transform.txt@@ -0,0 +1,21 @@+pattern is a CanvasPattern: true+toString tag: [object CanvasPattern]+untransformed: x=0: 0,255,0,255; x=2: 0,0,0,0+translated by e: x=0: 0,0,0,0; x=2: 0,255,0,255+translated by m41 and e: x=0: 0,0,0,0; x=2: 0,255,0,255+after a NaN member: x=0: 0,0,0,0; x=2: 0,255,0,255+after no transform: x=0: 0,255,0,255; x=2: 0,0,0,0+after an identity DOMMatrix: x=0: 0,255,0,255; x=2: 0,0,0,0+setTransform({"a":1,"m11":2}): TypeError: DOMMatrix2DInit.a and DOMMatrix2DInit.m11 must have the same value if they are both present+setTransform({"f":1,"m42":0}): TypeError: DOMMatrix2DInit.f and DOMMatrix2DInit.m42 must have the same value if they are both present+setTransform("not a dictionary"): TypeError: Not an object of type DOMMatrix2DInit+setTransform with NaN members that agree: no exception+createPattern(source, ""): [object CanvasPattern]+createPattern(source, null): [object CanvasPattern]+createPattern(source, "repeat-x"): [object CanvasPattern]+createPattern(source, "repeat-y"): [object CanvasPattern]+createPattern(source, "no-repeat"): [object CanvasPattern]+createPattern(source, "REPEAT"): DOMException SyntaxError+createPattern(source, "round"): DOMException SyntaxError+createPattern of an empty canvas: DOMException InvalidStateError+createPattern of a canvas without a size: nulldiff --git a/Tests/LibWeb/Text/input/canvas/pattern-set-transform.html b/Tests/LibWeb/Text/input/canvas/pattern-set-transform.htmlnew file mode 100644index 00000000000..3a67ed6defa--- /dev/null+++ b/Tests/LibWeb/Text/input/canvas/pattern-set-transform.html@@ -0,0 +1,76 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ const source = document.createElement("canvas");+ source.width = source.height = 4;+ const sourceContext = source.getContext("2d");+ sourceContext.fillStyle = "lime";+ sourceContext.fillRect(0, 0, 2, 4);++ const canvas = document.createElement("canvas");+ canvas.width = canvas.height = 8;+ const context = canvas.getContext("2d");++ function pixelsAfterFillingWith(pattern) {+ context.clearRect(0, 0, 8, 8);+ context.fillStyle = pattern;+ context.fillRect(0, 0, 8, 8);+ return `x=0: ${context.getImageData(0, 0, 1, 1).data}; x=2: ${context.getImageData(2, 0, 1, 1).data}`;+ }++ const pattern = context.createPattern(source, "repeat");+ println(`pattern is a CanvasPattern: ${pattern instanceof CanvasPattern}`);+ println(`toString tag: ${Object.prototype.toString.call(pattern)}`);+ println(`untransformed: ${pixelsAfterFillingWith(pattern)}`);++ pattern.setTransform({ e: 2 });+ println(`translated by e: ${pixelsAfterFillingWith(pattern)}`);++ pattern.setTransform({ m41: 2, e: 2 });+ println(`translated by m41 and e: ${pixelsAfterFillingWith(pattern)}`);++ pattern.setTransform({ e: NaN });+ println(`after a NaN member: ${pixelsAfterFillingWith(pattern)}`);++ pattern.setTransform();+ println(`after no transform: ${pixelsAfterFillingWith(pattern)}`);++ pattern.setTransform({ e: 2 });+ pattern.setTransform(new DOMMatrix([1, 0, 0, 1, 0, 0]));+ println(`after an identity DOMMatrix: ${pixelsAfterFillingWith(pattern)}`);++ for (const transform of [{ a: 1, m11: 2 }, { f: 1, m42: 0 }, "not a dictionary"]) {+ try {+ pattern.setTransform(transform);+ println(`setTransform(${JSON.stringify(transform)}): no exception`);+ } catch (e) {+ println(`setTransform(${JSON.stringify(transform)}): ${e.constructor.name}: ${e.message}`);+ }+ }+ try {+ pattern.setTransform({ a: NaN, m11: NaN, c: 0, m21: -0 });+ println("setTransform with NaN members that agree: no exception");+ } catch (e) {+ println(`setTransform with NaN members that agree: ${e.constructor.name}`);+ }++ for (const repetition of ["", null, "repeat-x", "repeat-y", "no-repeat", "REPEAT", "round"]) {+ try {+ const created = context.createPattern(source, repetition);+ println(`createPattern(source, ${JSON.stringify(repetition)}): ${Object.prototype.toString.call(created)}`);+ } catch (e) {+ println(`createPattern(source, ${JSON.stringify(repetition)}): DOMException ${e.name}`);+ }+ }++ const empty = document.createElement("canvas");+ empty.width = 0;+ try {+ context.createPattern(empty, "repeat");+ } catch (e) {+ println(`createPattern of an empty canvas: DOMException ${e.name}`);+ }+ println(`createPattern of a canvas without a size: ${context.createPattern(new Image(), "repeat")}`);+ });+</script>