Truly independent web browser
LibWeb: Implement Path2D in Rust
Andreas Kling4f464bb98667
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.rsnew file mode 100644index 00000000000..ae0a4a81080--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_point_read_only.rs@@ -0,0 +1,16 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * 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,+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rsindex 7dd23b6751d..ecce97b0194 100644--- a/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/mod.rs@@ -8,3 +8,4 @@//! are LibWeb's C++.pub(crate) mod dom_matrix_read_only;+pub(crate) mod dom_point_read_only;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rsindex 62f0bac38c0..d6152cd445b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_path.rs@@ -15,6 +15,44 @@ use core::fmt::LowerExp;use libgfx_rust::{AffineTransform, FloatPoint, FloatSize};+use crate::geometry::dom_point_read_only::DOMPointInit;++/// The union (unrestricted double or DOMPointInit) of HTML/Canvas/CanvasPath.idl, a radius of roundRect(), whose+/// members the bindings convert.+pub(crate) enum UnrestrictedDoubleOrDOMPointInit {+ UnrestrictedDouble(f64),+ DOMPointInit(DOMPointInit),+}++/// The union (unrestricted double or DOMPointInit or sequence<(unrestricted double or DOMPointInit)>) of+/// HTML/Canvas/CanvasPath.idl, the radii of roundRect(), whose members the bindings convert.+pub(crate) enum UnrestrictedDoubleOrDOMPointInitOrUnrestrictedDoubleOrDOMPointInitSequence {+ UnrestrictedDouble(f64),+ DOMPointInit(DOMPointInit),+ Sequence(Vec<UnrestrictedDoubleOrDOMPointInit>),+}++impl From<UnrestrictedDoubleOrDOMPointInit> for RoundRectRadius {+ fn from(radius: UnrestrictedDoubleOrDOMPointInit) -> Self {+ match radius {+ UnrestrictedDoubleOrDOMPointInit::UnrestrictedDouble(radius) => Self { x: radius, y: radius },+ UnrestrictedDoubleOrDOMPointInit::DOMPointInit(point) => Self { x: point.x, y: point.y },+ }+ }+}++/// The radii of roundRect() as a list, which step 2 of its steps makes of a single radius.+pub(crate) fn round_rect_radii(+ radii: UnrestrictedDoubleOrDOMPointInitOrUnrestrictedDoubleOrDOMPointInitSequence,+) -> Vec<RoundRectRadius> {+ use UnrestrictedDoubleOrDOMPointInitOrUnrestrictedDoubleOrDOMPointInitSequence as Radii;+ match radii {+ Radii::UnrestrictedDouble(radius) => vec![UnrestrictedDoubleOrDOMPointInit::UnrestrictedDouble(radius).into()],+ Radii::DOMPointInit(point) => vec![UnrestrictedDoubleOrDOMPointInit::DOMPointInit(point).into()],+ Radii::Sequence(radii) => radii.into_iter().map(RoundRectRadius::from).collect(),+ }+}+/// What the operations build on, which is a Gfx::Path, or what the crate tests record.pub(crate) trait PathSink {/// Whether the path has no current point.diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 7af403f7b18..ac3549a0631 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -22,6 +22,7 @@ use libjs_rust::api::Vm;use super::canvas_gradient::CanvasGradient;use super::canvas_path::{self, CanvasPathError, RoundRectRadius};use super::canvas_pattern::CanvasPattern;+use super::path2d::Path2D;use super::text_metrics::{TextMeasurements, TextMetrics};use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi};@@ -405,3 +406,16 @@ pub unsafe extern "C" fn web_canvas_path_ellipse().into()}++/// The Gfx::Path of the Path2D, which the caller borrows.+///+/// # Safety+///+/// `path` must be a live cell, which outlives the use of the Gfx::Path, and nothing may change the path meanwhile.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_path2d_path(path: *mut c_void) -> *const c_void {+ // SAFETY: The caller passes a live cell.+ let path: &Path2D = unsafe { object_from_abi(path) };+ // SAFETY: The caller keeps the path from changing while it reads it.+ unsafe { path.path_unguarded() }.as_raw()+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rsindex 3eeae4b7590..273e495abf4 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs@@ -4,8 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The objects that the 2D canvas contexts create and draw with. The contexts are still LibWeb's C++, which creates-//! and reads these objects through the C ABI of `exports`.+//! The objects that the 2D canvas contexts draw with, and the operations of a path that Path2D and the contexts+//! share. The contexts are still LibWeb's C++, which creates and reads these objects and builds its paths through the+//! C ABI of `exports`.pub(crate) mod canvas_path;pub(crate) mod color_stops;@@ -18,4 +19,6 @@ pub(crate) mod canvas_pattern;#[cfg(not(test))]pub(crate) mod exports;#[cfg(not(test))]+pub(crate) mod path2d;+#[cfg(not(test))]pub(crate) mod text_metrics;diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/path2d.rs b/Libraries/LibWeb/Bindings/Rust/src/html/path2d.rsnew file mode 100644index 00000000000..2d91987b339--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/html/path2d.rs@@ -0,0 +1,275 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://html.spec.whatwg.org/multipage/canvas.html#path2d++use core::cell::RefCell;++use ak::Utf16String;+use libgfx_rust::AffineTransform;+use libgfx_rust::path::{OwnedPath, PathBuilder, PathMut};+use libjs_rust::api::Trace;++use super::canvas_path::{+ self, UnrestrictedDoubleOrDOMPointInitOrUnrestrictedDoubleOrDOMPointInitSequence, round_rect_radii,+};+use crate::bindings::interface::{Ref, Wrappable};+use crate::bindings::{CallContext, WebIdlResult};+use crate::geometry::dom_matrix_read_only::{DOMMatrix2DInit, validate_and_fixup_2d};++/// The union (Path2D or DOMString) of HTML/Path2D.idl, whose members the bindings convert.+pub(crate) enum Path2DOrDOMString {+ Path2D(Ref<Path2D>),+ DOMString(Utf16String),+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Path2D {+ #[gc(untraced)]+ path: RefCell<OwnedPath>,+}++impl Wrappable for Path2D {}++#[allow(+ clippy::cast_possible_truncation,+ reason = "these operations take floats, as the C++ did"+)]+fn float(number: f64) -> f32 {+ number as f32+}++impl Path2D {+ /// The path, which the 2D contexts fill, stroke and clip with.+ ///+ /// # Safety+ ///+ /// Nothing may change the path while the reference is in use.+ pub(crate) unsafe fn path_unguarded(&self) -> &OwnedPath {+ // SAFETY: The caller keeps the path from changing while it reads it.+ unsafe { self.path.try_borrow_unguarded() }.expect("nothing changes the path meanwhile")+ }++ fn build<R>(&self, function: impl FnOnce(&mut PathMut<'_>) -> R) -> R {+ let mut path = self.path.borrow_mut();+ function(&mut path.as_path_mut())+ }++ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-path2d+ pub(crate) fn construct(_: &mut CallContext, path: Option<Path2DOrDOMString>) -> WebIdlResult<Self> {+ // 1. Let output be a new Path2D object.+ let output = Self {+ path: RefCell::new(PathBuilder::new().build()),+ };++ // 2. If path is not given, then return output.+ let Some(path) = path else {+ return Ok(output);+ };++ let path = match path {+ // 3. If path is a Path2D object, then add all subpaths of path to output and return output.+ // (In other words, it returns a copy of the argument.)+ Path2DOrDOMString::Path2D(path) => {+ output.path.replace(path.path.borrow().clone());+ return Ok(output);+ }+ Path2DOrDOMString::DOMString(path) => path,+ };++ // 4. Let svgPath be the result of parsing and interpreting path according to SVG 2's rules for path data.+ // [SVG]+ let svg_path = libweb_rust::gfx_path_from_path_data(path.as_units());++ if !svg_path.is_empty() {+ // 5. Let (x, y) be the last point in svgPath.+ let xy = svg_path.last_point();++ // 6. Add all the subpaths, if any, from svgPath to output.+ output.path.replace(svg_path);++ // 7. Create a new subpath in output with (x, y) as the only point in the subpath.+ output.build(|path| canvas_path::move_to(path, xy.x, xy.y));+ }++ // 8. Return output.+ Ok(output)+ }++ /// https://html.spec.whatwg.org/multipage/canvas.html#dom-path2d-addpath+ pub(crate) fn add_path(+ &self,+ _: &mut CallContext,+ path: Ref<Path2D>,+ transform: DOMMatrix2DInit,+ ) -> WebIdlResult<()> {+ // The addPath(path, transform) method, when invoked on a Path2D object a, must run these steps:++ // 1. If the Path2D object path has no subpaths, then return.+ if path.path.borrow().is_empty() {+ return Ok(());+ }++ // 2. Let matrix be the result of creating a DOMMatrix from the 2D dictionary transform.+ let matrix = validate_and_fixup_2d(&transform)?;++ // 3. 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(());+ }++ // 4. Create a copy of all the subpaths in path. Let c be this copy.+ // 5. Transform all the coordinates and lines in c by the transform matrix matrix.+ let copy = path.path.borrow().copy_transformed(matrix.to_affine_transform().values);++ // 6. Let (x, y) be the last point in the last subpath of c.+ let xy = copy.last_point();++ // 7. Add all the subpaths in c to a.+ // FIXME: Is this correct?+ self.build(|path| path.append_path(©));++ // 8. Create a new subpath in a with (x, y) as the only point in the subpath.+ self.build(|path| canvas_path::move_to(path, xy.x, xy.y));++ Ok(())+ }++ // The operations of the CanvasPath mixin, whose steps are in canvas_path.rs.++ pub(crate) fn close_path(&self, _: &mut CallContext) -> WebIdlResult<()> {+ self.build(|path| canvas_path::close_path(path));+ Ok(())+ }++ pub(crate) fn move_to(&self, _: &mut CallContext, x: f64, y: f64) -> WebIdlResult<()> {+ self.build(|path| canvas_path::move_to(path, float(x), float(y)));+ Ok(())+ }++ pub(crate) fn line_to(&self, _: &mut CallContext, x: f64, y: f64) -> WebIdlResult<()> {+ self.build(|path| canvas_path::line_to(path, float(x), float(y)));+ Ok(())+ }++ pub(crate) fn quadratic_curve_to(+ &self,+ _: &mut CallContext,+ cpx: f64,+ cpy: f64,+ x: f64,+ y: f64,+ ) -> WebIdlResult<()> {+ self.build(|path| canvas_path::quadratic_curve_to(path, float(cpx), float(cpy), float(x), float(y)));+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ pub(crate) fn bezier_curve_to(+ &self,+ _: &mut CallContext,+ cp1x: f64,+ cp1y: f64,+ cp2x: f64,+ cp2y: f64,+ x: f64,+ y: f64,+ ) -> WebIdlResult<()> {+ self.build(|path| canvas_path::bezier_curve_to(path, cp1x, cp1y, cp2x, cp2y, x, y));+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ pub(crate) fn arc_to(+ &self,+ _: &mut CallContext,+ x1: f64,+ y1: f64,+ x2: f64,+ y2: f64,+ radius: f64,+ ) -> WebIdlResult<()> {+ // NB: A Path2D has no transformation matrix, so its points are in the coordinates that it was given.+ self.build(|path| canvas_path::arc_to(path, AffineTransform::identity(), x1, y1, x2, y2, radius))?;+ Ok(())+ }++ pub(crate) fn rect(&self, _: &mut CallContext, x: f64, y: f64, w: f64, h: f64) -> WebIdlResult<()> {+ self.build(|path| canvas_path::rect(path, x, y, w, h));+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ pub(crate) fn round_rect(+ &self,+ _: &mut CallContext,+ x: f64,+ y: f64,+ w: f64,+ h: f64,+ radii: UnrestrictedDoubleOrDOMPointInitOrUnrestrictedDoubleOrDOMPointInitSequence,+ ) -> WebIdlResult<()> {+ let radii = round_rect_radii(radii);+ self.build(|path| canvas_path::round_rect(path, x, y, w, h, &radii))?;+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ pub(crate) fn arc(+ &self,+ _: &mut CallContext,+ x: f64,+ y: f64,+ radius: f64,+ start_angle: f64,+ end_angle: f64,+ counterclockwise: bool,+ ) -> WebIdlResult<()> {+ self.build(|path| {+ canvas_path::arc(+ path,+ float(x),+ float(y),+ float(radius),+ float(start_angle),+ float(end_angle),+ counterclockwise,+ )+ })?;+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ pub(crate) fn ellipse(+ &self,+ _: &mut CallContext,+ x: f64,+ y: f64,+ radius_x: f64,+ radius_y: f64,+ rotation: f64,+ start_angle: f64,+ end_angle: f64,+ counterclockwise: bool,+ ) -> WebIdlResult<()> {+ self.build(|path| {+ canvas_path::ellipse(+ path,+ float(x),+ float(y),+ float(radius_x),+ float(radius_y),+ float(rotation),+ float(start_angle),+ float(end_angle),+ counterclockwise,+ )+ })?;+ Ok(())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex a86fd28f173..ebb0cdba843 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -88,7 +88,7 @@ mod webgl_proxy;#[path = "../generate/webgl_wire_model.rs"]mod webgl_wire_model;-// NB: Only C++ calls into libweb_rust, so nothing in this crate names it. Linking it keeps its extern "C" functions in-// the static library.+// NB: Little in this crate names libweb_rust, which C++ calls into. Linking it keeps its extern "C" functions in the+// static library.#[cfg(not(test))]extern crate libweb_rust;diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cppindex 73c9fafd06a..3d512c1f14d 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp@@ -1084,7 +1084,7 @@ Canvas2DContextBase::PreparedText Canvas2DContextBase::prepare_text(Utf16View tereturn prepared_text;}-void Canvas2DContextBase::clip_internal(Gfx::Path& path, Gfx::WindingRule winding_rule)+void Canvas2DContextBase::clip_internal(Gfx::Path const& path, Gfx::WindingRule winding_rule){auto* recorder = canvas_recorder();if (!recorder)diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.hindex 33b19f38bec..8b031e1cb36 100644--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.h@@ -168,7 +168,7 @@ protected:void stroke_internal(Gfx::Path);void fill_internal(Gfx::Path, Gfx::WindingRule);- void clip_internal(Gfx::Path&, Gfx::WindingRule);+ void clip_internal(Gfx::Path const&, Gfx::WindingRule);void paint_shadow_for_fill_internal(Gfx::Path const&, Gfx::WindingRule);void paint_shadow_for_stroke_internal(Gfx::Path const&, Gfx::Path::CapStyle, Gfx::Path::JoinStyle, Vector<float> const&);diff --git a/Libraries/LibWeb/HTML/Path2D.cpp b/Libraries/LibWeb/HTML/Path2D.cppindex 1dc1066e5e1..950feeb2a17 100644--- a/Libraries/LibWeb/HTML/Path2D.cpp+++ b/Libraries/LibWeb/HTML/Path2D.cpp@@ -6,93 +6,17 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/DOMMatrixReadOnly.h>-#include <LibWeb/Geometry/DOMMatrix.h>+#include <LibGfx/Path.h>#include <LibWeb/HTML/Path2D.h>-#include <LibWeb/SVG/Path.h>namespace Web::HTML {-GC_DEFINE_ALLOCATOR(Path2D);+// Defined in Bindings/Rust/src/html/exports.rs.+extern "C" Gfx::Path const* web_path2d_path(void* path);-GC::Ref<Path2D> Path2D::create(Optional<Variant<GC::Ref<Path2D>, Utf16String>> const& path)+Gfx::Path const& Path2D::path() const{- return GC::Heap::the().allocate<Path2D>(path);-}--// https://html.spec.whatwg.org/multipage/canvas.html#dom-path2d-Path2D::Path2D(Optional<Variant<GC::Ref<Path2D>, Utf16String>> const& path)-{- // 1. Let output be a new Path2D object.- // 2. If path is not given, then return output.- if (!path.has_value())- return;-- // 3. If path is a Path2D object, then add all subpaths of path to output and return output.- // (In other words, it returns a copy of the argument.)- if (path->has<GC::Ref<Path2D>>()) {- this->path() = path->get<GC::Ref<Path2D>>()->path();- return;- }-- // 4. Let svgPath be the result of parsing and interpreting path according to SVG 2's rules for path data. [SVG]- auto path_instructions = SVG::parse_path_data(path->get<Utf16String>());- auto svg_path = path_instructions.to_gfx_path();-- if (!svg_path.is_empty()) {- // 5. Let (x, y) be the last point in svgPath.- auto xy = svg_path.last_point();-- // 6. Add all the subpaths, if any, from svgPath to output.- this->path() = move(svg_path);-- // 7. Create a new subpath in output with (x, y) as the only point in the subpath.- this->move_to(xy.x(), xy.y());- }-- // 8. Return output.-}--Path2D::~Path2D() = default;--// https://html.spec.whatwg.org/multipage/canvas.html#dom-path2d-addpath-WebIDL::ExceptionOr<void> Path2D::add_path(GC::Ref<Path2D> path, GC::Ref<Geometry::DOMMatrix> matrix)-{- // The addPath(path, transform) method, when invoked on a Path2D object a, must run these steps:-- // 1. If the Path2D object path has no subpaths, then return.- if (path->path().is_empty())- return {};-- // 2. 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.-- // 3. 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 {};-- // 4. Create a copy of all the subpaths in path. Let c be this copy.- // 5. Transform all the coordinates and lines in c by the transform matrix matrix.- auto copy = path->path().copy_transformed(Gfx::AffineTransform { static_cast<float>(matrix->m11()), static_cast<float>(matrix->m12()), static_cast<float>(matrix->m21()), static_cast<float>(matrix->m22()), static_cast<float>(matrix->m41()), static_cast<float>(matrix->m42()) });-- // 6. Let (x, y) be the last point in the last subpath of c.- auto xy = copy.last_point();-- // 7. Add all the subpaths in c to a.- // FIXME: Is this correct?- this->path().append_path(copy);-- // 8. Create a new subpath in a with (x, y) as the only point in the subpath.- this->move_to(xy.x(), xy.y());-- return {};-}--WebIDL::ExceptionOr<void> Path2D::add_path(GC::Ref<Path2D> path, 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 add_path(path, matrix);+ return *web_path2d_path(const_cast<Path2D*>(this));}}diff --git a/Libraries/LibWeb/HTML/Path2D.h b/Libraries/LibWeb/HTML/Path2D.hindex 3d12657d942..f799c862399 100644--- a/Libraries/LibWeb/HTML/Path2D.h+++ b/Libraries/LibWeb/HTML/Path2D.h@@ -6,42 +6,22 @@#pragma once-#include <AK/RefCounted.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/HTML/Canvas/CanvasPath.h>--namespace Web::Bindings {--struct DOMMatrix2DInit;--}--namespace Web::Geometry {--class DOMMatrix;--}+#include <LibGfx/Forward.h>+#include <LibWeb/Bindings/Path2D.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Export.h>namespace Web::HTML {// https://html.spec.whatwg.org/multipage/canvas.html#path2d-class Path2D final- : public Bindings::GCAllocatedWrappable- , public CanvasPath {-- WEB_WRAPPABLE(Path2D, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(Path2D);+// The C++ side of a Path2D, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/html): what the 2D+// contexts fill, stroke and clip with.+class WEB_API Path2D final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(Path2D, path2d)public:- static GC::Ref<Path2D> create(Optional<Variant<GC::Ref<Path2D>, Utf16String>> const& path);-- virtual ~Path2D() override;-- WebIDL::ExceptionOr<void> add_path(GC::Ref<Path2D> path, GC::Ref<Geometry::DOMMatrix> transform);- WebIDL::ExceptionOr<void> add_path(GC::Ref<Path2D> path, Bindings::DOMMatrix2DInit const& transform);--private:- explicit Path2D(Optional<Variant<GC::Ref<Path2D>, Utf16String>> const&);+ // The path, which changes only when script calls a method of the Path2D.+ Gfx::Path const& path() const;};}diff --git a/Libraries/LibWeb/HTML/Path2D.idl b/Libraries/LibWeb/HTML/Path2D.idlindex c33466faaf7..2157af2ca45 100644--- a/Libraries/LibWeb/HTML/Path2D.idl+++ b/Libraries/LibWeb/HTML/Path2D.idl@@ -1,5 +1,5 @@// https://html.spec.whatwg.org/multipage/canvas.html#path2d-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface Path2D {constructor(optional (Path2D or DOMString) path);diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rsindex 861e59e7ff1..f411a4c5b84 100644--- a/Libraries/LibWeb/Rust/src/lib.rs+++ b/Libraries/LibWeb/Rust/src/lib.rs@@ -30,6 +30,9 @@ pub(crate) mod stage;pub(crate) mod stage_thread;pub(crate) mod svg;+// What libweb_bindings_rust, whose interfaces are implemented in Rust, uses of this crate.+pub use svg::gfx_path_from_path_data;+// NB: Only C++ calls into the HTML tokenizer and parser, so nothing in this crate names them. Linking the crate keeps// their extern "C" functions in the static library.extern crate libweb_html_tokenizer;diff --git a/Libraries/LibWeb/Rust/src/svg/path_parser.rs b/Libraries/LibWeb/Rust/src/svg/path_parser.rsindex 0a2480836c7..d4b162e6acc 100644--- a/Libraries/LibWeb/Rust/src/svg/path_parser.rs+++ b/Libraries/LibWeb/Rust/src/svg/path_parser.rs@@ -855,6 +855,17 @@ pub(super) fn svg_input(view: FfiUtf16View<'_>) -> Option<Input<'_>> {})}+/// The path that the path data describes, as SVG parses it, with its error recovery: what parsing a string of path+/// data gives Path2D's constructor, which is an empty path where the data describes none.+pub fn gfx_path_from_path_data(input: ak::Utf16StringUnits<'_>) -> OwnedPath {+ let input = match input {+ ak::Utf16StringUnits::Ascii(units) => Input::Ascii(units),+ ak::Utf16StringUnits::Utf16(units) => Input::Utf16(units),+ };+ let instructions = Parser::new(input).parse(true).unwrap_or_default();+ ParsedPath { instructions }.to_gfx_path()+}+/// The path `input` describes, as a new path C++ owns, or null where it describes none.#[unsafe(no_mangle)]pub extern "C" fn rust_parse_svg_path_data(input: FfiUtf16View<'_>) -> *mut ParsedPath {diff --git a/Tests/LibWeb/Text/expected/canvas/path2d-in-rust.txt b/Tests/LibWeb/Text/expected/canvas/path2d-in-rust.txtnew file mode 100644index 00000000000..08ec410b1e1--- /dev/null+++ b/Tests/LibWeb/Text/expected/canvas/path2d-in-rust.txt@@ -0,0 +1,40 @@+Path2D: [object Path2D], instanceof true+rect: inside true, outside false+copy has the original's subpaths: true+copy is independent: copy true, original false+empty: false, undefined: false+SVG: true+SVG with an error after a subpath: true+SVG that does not start with a move: false+SVG from a number: false+SVG from an object: true+SVG ends in a new subpath at its last point: true+addPath with a translation: true, false+addPath with a DOMMatrix: true+addPath with a NaN member: false+addPath of itself: true, true+addPath of a path: TypeError+addPath of an empty path: no exception+addPath of not a path: TypeError+roundRect(undefined): corner true, center true+roundRect(3): corner false, center true+roundRect("3"): corner false, center true+roundRect({"x":3,"y":3}): corner false, center true+roundRect([3]): corner false, center true+roundRect([1,2,3]): corner true, center true+roundRect([{"x":1,"y":2},3]): corner true, center true+roundRect(null): corner true, center true+roundRect([1,2,3,4,5]): RangeError+roundRect(-1): RangeError+roundRect([null]): corner false, center false+curves: true, true+arcs: true, true, false+arcTo: false, true+fill rules: nonzero true, evenodd false+arc: DOMException IndexSizeError: The radius provided (-1) is negative.+ellipse: DOMException IndexSizeError: The minor-axis radius provided (-1) is negative.+arcTo: DOMException IndexSizeError: The radius provided (-1) is negative.+roundRect: RangeError: roundRect: Can have between 1 and 4 radii+fill: 0,255,0,255, stroke: 0,0,255,255+clip: 255,0,0,255, 0,255,0,255+isPointInPath without a path: falsediff --git a/Tests/LibWeb/Text/input/canvas/path2d-in-rust.html b/Tests/LibWeb/Text/input/canvas/path2d-in-rust.htmlnew file mode 100644index 00000000000..9dd9bfb52f2--- /dev/null+++ b/Tests/LibWeb/Text/input/canvas/path2d-in-rust.html@@ -0,0 +1,114 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ const canvas = document.createElement("canvas");+ canvas.width = canvas.height = 20;+ const context = canvas.getContext("2d");+ const inside = (path, x, y, rule) => rule === undefined ? context.isPointInPath(path, x, y) : context.isPointInPath(path, x, y, rule);++ const square = new Path2D();+ square.rect(0, 0, 10, 10);+ println(`Path2D: ${Object.prototype.toString.call(square)}, instanceof ${square instanceof Path2D}`);+ println(`rect: inside ${inside(square, 5, 5)}, outside ${inside(square, 15, 5)}`);++ const copy = new Path2D(square);+ copy.rect(10, 10, 5, 5);+ println(`copy has the original's subpaths: ${inside(copy, 5, 5)}`);+ println(`copy is independent: copy ${inside(copy, 12, 12)}, original ${inside(square, 12, 12)}`);++ println(`empty: ${inside(new Path2D(), 0, 0)}, undefined: ${inside(new Path2D(undefined), 0, 0)}`);+ println(`SVG: ${inside(new Path2D("M 0 0 h 10 v 10 h -10 z"), 5, 5)}`);+ println(`SVG with an error after a subpath: ${inside(new Path2D("M 0 0 h 10 v 10 h -10 z L"), 5, 5)}`);+ println(`SVG that does not start with a move: ${inside(new Path2D("L 10 10 L 0 10 z"), 5, 7)}`);+ println(`SVG from a number: ${inside(new Path2D(5), 0, 0)}`);+ println(`SVG from an object: ${inside(new Path2D({ toString: () => "M 0 0 h 10 v 10 h -10 z" }), 5, 5)}`);+ const svgThenLine = new Path2D("M 0 0 L 10 0");+ svgThenLine.lineTo(10, 10);+ svgThenLine.lineTo(0, 10);+ println(`SVG ends in a new subpath at its last point: ${inside(svgThenLine, 7, 3)}`);++ const added = new Path2D();+ added.addPath(square, { e: 5, f: 5 });+ println(`addPath with a translation: ${inside(added, 12, 12)}, ${inside(added, 2, 2)}`);+ const scaled = new Path2D();+ scaled.addPath(square, new DOMMatrix([2, 0, 0, 2, 0, 0]));+ println(`addPath with a DOMMatrix: ${inside(scaled, 15, 15)}`);+ const ignored = new Path2D();+ ignored.addPath(square, { a: NaN });+ println(`addPath with a NaN member: ${inside(ignored, 5, 5)}`);+ const self = new Path2D();+ self.rect(0, 0, 2, 2);+ self.addPath(self, { e: 10 });+ println(`addPath of itself: ${inside(self, 1, 1)}, ${inside(self, 11, 1)}`);+ for (const [description, path, transform] of [["a path", square, { a: 1, m11: 2 }], ["an empty path", new Path2D(), { a: 1, m11: 2 }], ["not a path", {}, {}]]) {+ try {+ new Path2D().addPath(path, transform);+ println(`addPath of ${description}: no exception`);+ } catch (e) {+ println(`addPath of ${description}: ${e.constructor.name}`);+ }+ }++ for (const radii of [undefined, 3, "3", { x: 3, y: 3 }, [3], [1, 2, 3], [{ x: 1, y: 2 }, 3], null, [1, 2, 3, 4, 5], -1, [NaN]]) {+ const path = new Path2D();+ try {+ path.roundRect(0, 0, 10, 10, radii);+ println(`roundRect(${JSON.stringify(radii)}): corner ${inside(path, 0.5, 0.5)}, center ${inside(path, 5, 5)}`);+ } catch (e) {+ println(`roundRect(${JSON.stringify(radii)}): ${e.constructor.name}`);+ }+ }++ const shapes = new Path2D();+ shapes.moveTo(0, 0);+ shapes.lineTo(10, 0);+ shapes.quadraticCurveTo(15, 5, 10, 10);+ shapes.bezierCurveTo(8, 12, 2, 12, 0, 10);+ shapes.closePath();+ println(`curves: ${inside(shapes, 12, 5)}, ${inside(shapes, 5, 10.5)}`);+ const arcs = new Path2D();+ arcs.arc(5, 5, 4, 0, Math.PI * 2);+ arcs.ellipse(15, 5, 4, 2, Math.PI / 2, 0, Math.PI * 2);+ println(`arcs: ${inside(arcs, 5, 5)}, ${inside(arcs, 15, 8)}, ${inside(arcs, 18, 5)}`);+ const corner = new Path2D();+ corner.moveTo(0, 0);+ corner.arcTo(10, 0, 10, 10, 5);+ corner.lineTo(0, 10);+ println(`arcTo: ${inside(corner, 9.5, 0.5)}, ${inside(corner, 5, 5)}`);++ const ring = new Path2D();+ ring.rect(0, 0, 10, 10);+ ring.rect(2, 2, 6, 6);+ println(`fill rules: nonzero ${inside(ring, 5, 5, "nonzero")}, evenodd ${inside(ring, 5, 5, "evenodd")}`);++ for (const [description, operation] of [+ ["arc", () => new Path2D().arc(0, 0, -1, 0, 1)],+ ["ellipse", () => new Path2D().ellipse(0, 0, 1, -1, 0, 0, 1)],+ ["arcTo", () => new Path2D().arcTo(0, 0, 1, 1, -1)],+ ["roundRect", () => new Path2D().roundRect(0, 0, 1, 1, [])],+ ]) {+ try {+ operation();+ println(`${description}: no exception`);+ } catch (e) {+ const kind = e instanceof DOMException ? `DOMException ${e.name}` : e.constructor.name;+ println(`${description}: ${kind}: ${e.message}`);+ }+ }++ context.fillStyle = "lime";+ context.fill(square);+ context.strokeStyle = "blue";+ context.lineWidth = 2;+ context.stroke(copy);+ println(`fill: ${context.getImageData(5, 5, 1, 1).data}, stroke: ${context.getImageData(15, 10, 1, 1).data}`);+ context.save();+ context.clip(new Path2D("M 0 0 h 4 v 4 h -4 z"));+ context.fillStyle = "red";+ context.fillRect(0, 0, 20, 20);+ context.restore();+ println(`clip: ${context.getImageData(2, 2, 1, 1).data}, ${context.getImageData(6, 6, 1, 1).data}`);+ println(`isPointInPath without a path: ${context.isPointInPath(5, 5)}`);+ });+</script>