Truly independent web browser
LibWeb: Answer SVG geometry queries from the Rust shape builders
Aliaksandr Kalenikc3a8e511c4a5
diff --git a/Libraries/LibWeb/Layout/LayoutRustBridge.cpp b/Libraries/LibWeb/Layout/LayoutRustBridge.cppindex 5b21d44640c..c60d76032da 100644--- a/Libraries/LibWeb/Layout/LayoutRustBridge.cpp+++ b/Libraries/LibWeb/Layout/LayoutRustBridge.cpp@@ -158,6 +158,40 @@ static Array<CSS::StyleAtomID, 4> svg_style_reference_atoms(DOM::Element& elemen};}+RustFFI::FfiSvgAttributeFacts svg_geometry_facts(DOM::Element const& element)+{+ RustFFI::FfiSvgAttributeFacts facts {};+ if (is<SVG::SVGPathElement>(element))+ facts.geometry_kind = RustFFI::SVG_GEOMETRY_KIND_PATH;+ else if (is<SVG::SVGRectElement>(element))+ facts.geometry_kind = RustFFI::SVG_GEOMETRY_KIND_RECT;+ else if (is<SVG::SVGCircleElement>(element))+ facts.geometry_kind = RustFFI::SVG_GEOMETRY_KIND_CIRCLE;+ else if (is<SVG::SVGEllipseElement>(element))+ facts.geometry_kind = RustFFI::SVG_GEOMETRY_KIND_ELLIPSE;+ else if (is<SVG::SVGPolylineElement>(element))+ facts.geometry_kind = RustFFI::SVG_GEOMETRY_KIND_POLYLINE;+ else if (is<SVG::SVGPolygonElement>(element))+ facts.geometry_kind = RustFFI::SVG_GEOMETRY_KIND_POLYGON;+ else if (auto const* line_element = as_if<SVG::SVGLineElement>(element)) {+ facts.geometry_kind = RustFFI::SVG_GEOMETRY_KIND_LINE;+ facts.line_x1 = to_ffi_number_percentage(line_element->x1_value());+ facts.line_y1 = to_ffi_number_percentage(line_element->y1_value());+ facts.line_x2 = to_ffi_number_percentage(line_element->x2_value());+ facts.line_y2 = to_ffi_number_percentage(line_element->y2_value());+ }+ return facts;+}++ReadonlySpan<Gfx::FloatPoint> svg_shape_points(DOM::Element const& element)+{+ if (auto const* polygon = as_if<SVG::SVGPolygonElement>(element))+ return polygon->points();+ if (auto const* polyline = as_if<SVG::SVGPolylineElement>(element))+ return polyline->points();+ return {};+}+// The SVG attributes an element parses, as the layout stage reads them.static RustFFI::FfiSvgAttributeFacts build_svg_attribute_facts(DOM::Element& dom_node){@@ -203,31 +237,7 @@ static RustFFI::FfiSvgAttributeFacts build_svg_attribute_facts(DOM::Element& dompattern_height = pattern_element->pattern_height();}- auto geometry_kind = RustFFI::SVG_GEOMETRY_KIND_NONE;- if (is<SVG::SVGPathElement>(dom_node))- geometry_kind = RustFFI::SVG_GEOMETRY_KIND_PATH;- else if (is<SVG::SVGRectElement>(dom_node))- geometry_kind = RustFFI::SVG_GEOMETRY_KIND_RECT;- else if (is<SVG::SVGCircleElement>(dom_node))- geometry_kind = RustFFI::SVG_GEOMETRY_KIND_CIRCLE;- else if (is<SVG::SVGEllipseElement>(dom_node))- geometry_kind = RustFFI::SVG_GEOMETRY_KIND_ELLIPSE;- else if (is<SVG::SVGPolylineElement>(dom_node))- geometry_kind = RustFFI::SVG_GEOMETRY_KIND_POLYLINE;- else if (is<SVG::SVGPolygonElement>(dom_node))- geometry_kind = RustFFI::SVG_GEOMETRY_KIND_POLYGON;-- SVG::NumberPercentage line_x1 = SVG::NumberPercentage::create_number(0);- SVG::NumberPercentage line_y1 = SVG::NumberPercentage::create_number(0);- SVG::NumberPercentage line_x2 = SVG::NumberPercentage::create_number(0);- SVG::NumberPercentage line_y2 = SVG::NumberPercentage::create_number(0);- if (auto const* line_element = as_if<SVG::SVGLineElement>(dom_node)) {- geometry_kind = RustFFI::SVG_GEOMETRY_KIND_LINE;- line_x1 = line_element->x1_value();- line_y1 = line_element->y1_value();- line_x2 = line_element->x2_value();- line_y2 = line_element->y2_value();- }+ auto geometry = svg_geometry_facts(dom_node);SVG::SVGTextPositioningElement::ParsedTextPositioning text_positioning;if (auto const* text_positioning_element = as_if<SVG::SVGTextPositioningElement>(dom_node))@@ -287,11 +297,11 @@ static RustFFI::FfiSvgAttributeFacts build_svg_attribute_facts(DOM::Element& dom.mask_y = to_ffi_number_percentage(mask_y),.mask_width = to_ffi_number_percentage(mask_width),.mask_height = to_ffi_number_percentage(mask_height),- .geometry_kind = geometry_kind,- .line_x1 = to_ffi_number_percentage(line_x1),- .line_y1 = to_ffi_number_percentage(line_y1),- .line_x2 = to_ffi_number_percentage(line_x2),- .line_y2 = to_ffi_number_percentage(line_y2),+ .geometry_kind = geometry.geometry_kind,+ .line_x1 = geometry.line_x1,+ .line_y1 = geometry.line_y1,+ .line_x2 = geometry.line_x2,+ .line_y2 = geometry.line_y2,.text_x = to_ffi_svg_length_value(text_positioning.x),.text_y = to_ffi_svg_length_value(text_positioning.y),.text_dx = to_ffi_svg_length_value(text_positioning.dx),@@ -369,11 +379,7 @@ void publish_table_spans(DOM::Element const& element)void publish_svg_attribute_facts(DOM::Element& element){VERIFY(element.style_node_id() != 0);- ReadonlySpan<Gfx::FloatPoint> points;- if (auto const* polygon = as_if<SVG::SVGPolygonElement>(element))- points = polygon->points();- else if (auto const* polyline = as_if<SVG::SVGPolylineElement>(element))- points = polyline->points();+ auto points = svg_shape_points(element);static_assert(sizeof(Gfx::FloatPoint) == sizeof(RustFFI::FfiFloatPoint));RustFFI::render_state_set_svg_attribute_facts(element.document().layout_node_arena().host(),diff --git a/Libraries/LibWeb/Layout/LayoutRustBridge.h b/Libraries/LibWeb/Layout/LayoutRustBridge.hindex c8553344b5f..3829f308131 100644--- a/Libraries/LibWeb/Layout/LayoutRustBridge.h+++ b/Libraries/LibWeb/Layout/LayoutRustBridge.h@@ -39,6 +39,13 @@ WEB_API void register_layout_host(NodeArena&, DOM::Document&);void publish_svg_attribute_facts(DOM::Element&);void publish_svg_style_references(DOM::Element&);+// Which shape an SVG geometry element draws, and the endpoints a <line> parses. The other fields keep their defaults.+// Layout reads these from the published facts, and the DOM's geometry queries pass them to the same shape builders.+RustFFI::FfiSvgAttributeFacts svg_geometry_facts(DOM::Element const&);++// The points a <polygon> or <polyline> parses. Every other element has none.+ReadonlySpan<Gfx::FloatPoint> svg_shape_points(DOM::Element const&);+// Publishes whether a row built for the node sits in the user agent shadow tree of the focused text control, which is// what a caret is painted inside. The overflow pass reserves a pixel for the caret, so it reads the published answer// rather than asking the document who has focus.diff --git a/Libraries/LibWeb/Rust/src/css/css_path.rs b/Libraries/LibWeb/Rust/src/css/css_path.rsindex 7149437ebd6..252a649c893 100644--- a/Libraries/LibWeb/Rust/src/css/css_path.rs+++ b/Libraries/LibWeb/Rust/src/css/css_path.rs@@ -92,11 +92,6 @@ impl std::fmt::Debug for CssPath {}}-#[unsafe(no_mangle)]-pub extern "C" fn rust_css_path_to_gfx_path(path: &CssPath) -> *mut std::ffi::c_void {- path.to_gfx_path().into_raw()-}-#[cfg(test)]mod tests {use super::*;diff --git a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rsindex b2f22f27d6e..7ba5ade7e2d 100644--- a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs@@ -688,7 +688,17 @@ impl<'pass> SvgFormattingContext<'pass> {fn node_kind(&self, node: Node) -> NodeKind {self.run.callbacks.node_data(node).kind.get()}+}+/// The viewport a shape's geometry resolves its lengths against. Layout and the DOM's geometry+/// queries both build a shape's path through it, so the two cannot disagree on a shape.+#[derive(Clone, Copy)]+struct SvgShapeGeometry {+ viewport_width: CssPixels,+ viewport_height: CssPixels,+}++impl SvgShapeGeometry {// https://svgwg.org/svg2-draft/shapes.html#RectElement// The used values for rx and ry are determined from the computed values by following these// steps in order.@@ -972,18 +982,9 @@ impl<'pass> SvgFormattingContext<'pass> {path}- /// The geometry a shape element draws, in the user units of the viewport it sits in.- fn svg_geometry_path(&self, node: Node) -> libgfx_rust::path::OwnedPath {- let points = self.run.callbacks.arena().svg_points(node);- self.svg_geometry_path_of(self.svg_attributes(node), self.style(node), points.as_deref())- }-- /// As above, from an element's published attributes and computed style rather than from its- /// box.- // FIXME: The DOM's getTotalLength() still builds the same geometry from the C++- // SVG*Element::get_path() implementations. Route it through this, so a fix to one copy- // cannot miss the other.- fn svg_geometry_path_of(+ /// The geometry a shape element draws, in the user units of this viewport, from the shape its+ /// attributes name and its computed style.+ fn path(&self,attributes: FfiSvgAttributeFacts,style: StyleValues<'_>,@@ -1020,6 +1021,57 @@ impl<'pass> SvgFormattingContext<'pass> {path.set_fill_type(i32::from(shape.fill_rule));path}+}++/// The geometry a shape element draws, in the user units of a viewport of `viewport_size`, from+/// the shape `geometry` names and the computed style in `payloads`. The DOM's geometry queries+/// measure this path. Only the `geometry_kind` and `line_*` fields of `geometry` are read.+/// Returns a heap-allocated `Gfx::Path` that the caller owns.+///+/// # Safety+///+/// `payloads` must point at `payload_count` live style group payloads, and `points` at+/// `point_count` points.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn svg_geometry_element_path(+ geometry: FfiSvgAttributeFacts,+ payloads: *const *const c_void,+ payload_count: usize,+ points: *const FfiFloatPoint,+ point_count: usize,+ viewport_size: FfiCssPixelSize,+) -> *mut c_void {+ assert!(!payloads.is_null(), "style group payload array is null");+ let mut style_payloads = FfiStylePayloads::default();+ // SAFETY: Guaranteed by the caller.+ style_payloads+ .groups+ .copy_from_slice(unsafe { ak::slice_from_raw_parts(payloads, payload_count) });+ // SAFETY: Guaranteed by the caller.+ let points = unsafe { ak::slice_from_raw_parts(points, point_count) };+ let shape_geometry = SvgShapeGeometry {+ viewport_width: viewport_size.width,+ viewport_height: viewport_size.height,+ };+ shape_geometry+ .path(geometry, StyleValues::new(&style_payloads), Some(points))+ .into_raw()+}++impl<'pass> SvgFormattingContext<'pass> {+ fn shape_geometry(&self) -> SvgShapeGeometry {+ SvgShapeGeometry {+ viewport_width: self.viewport_width,+ viewport_height: self.viewport_height,+ }+ }++ /// The geometry a shape element draws, in the user units of the viewport it sits in.+ fn svg_geometry_path(&self, node: Node) -> libgfx_rust::path::OwnedPath {+ let points = self.run.callbacks.arena().svg_points(node);+ self.shape_geometry()+ .path(self.svg_attributes(node), self.style(node), points.as_deref())+ }/// The pixel value one of the text positioning attributes resolves to. A relative length is/// absolutized against the element's own style, exactly as the attribute's parse used to be.@@ -1449,7 +1501,10 @@ impl<'pass> SvgFormattingContext<'pass> {}let payloads = arena.style_node_style_payloads(shape)?;let points = arena.style_node_svg_points(shape);- Some(self.svg_geometry_path_of(attributes, StyleValues::new(&payloads), points.as_deref()))+ Some(+ self.shape_geometry()+ .path(attributes, StyleValues::new(&payloads), points.as_deref()),+ )}fn svg_attributes(&self, node: Node) -> FfiSvgAttributeFacts {diff --git a/Libraries/LibWeb/SVG/SVGCircleElement.cpp b/Libraries/LibWeb/SVG/SVGCircleElement.cppindex 97111103957..7b8d97372e7 100644--- a/Libraries/LibWeb/SVG/SVGCircleElement.cpp+++ b/Libraries/LibWeb/SVG/SVGCircleElement.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGfx/Path.h>#include <LibWeb/CSS/Parser/Parser.h>#include <LibWeb/CSS/PropertyID.h>#include <LibWeb/Layout/Node.h>@@ -21,45 +20,4 @@ SVGCircleElement::SVGCircleElement(DOM::Document& document, DOM::QualifiedName q{}-static CSSPixels normalized_diagonal_length(CSSPixelSize viewport_size)-{- if (viewport_size.width() == viewport_size.height())- return viewport_size.width();- return sqrt(((viewport_size.width() * viewport_size.width()) + (viewport_size.height() * viewport_size.height())) / 2);-}--Gfx::Path SVGCircleElement::get_path(CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values)-{- auto cx = float(computed_values.cx().to_px(viewport_size.width()));- auto cy = float(computed_values.cy().to_px(viewport_size.height()));- // Percentages refer to the normalized diagonal of the current SVG viewport- // (see Units: https://svgwg.org/svg2-draft/coords.html#Units)- auto r = float(computed_values.r().to_px(normalized_diagonal_length(viewport_size)));-- // A zero radius disables rendering.- if (r == 0)- return {};-- Gfx::Path path;- bool large_arc = false;- bool sweep = true;-- // 1. A move-to command to the point cx+r,cy;- path.move_to({ cx + r, cy });-- // 2. arc to cx,cy+r;- path.arc_to({ cx, cy + r }, r, large_arc, sweep);-- // 3. arc to cx-r,cy;- path.arc_to({ cx - r, cy }, r, large_arc, sweep);-- // 4. arc to cx,cy-r;- path.arc_to({ cx, cy - r }, r, large_arc, sweep);-- // 5. arc with a segment-completing close path operation.- path.arc_to({ cx + r, cy }, r, large_arc, sweep);-- return path;-}-}diff --git a/Libraries/LibWeb/SVG/SVGCircleElement.h b/Libraries/LibWeb/SVG/SVGCircleElement.hindex 57c7099f973..2e818bb995b 100644--- a/Libraries/LibWeb/SVG/SVGCircleElement.h+++ b/Libraries/LibWeb/SVG/SVGCircleElement.h@@ -17,8 +17,6 @@ class SVGCircleElement final : public SVGGeometryElement {public:virtual ~SVGCircleElement() override = default;- virtual Gfx::Path get_path(CSSPixelSize viewport_size, CSS::ComputedValues const&) override;-// AD-HOC: The spec states that the cx, cy and r IDL attributes reflect the respective computed values and their// corresponding presentation attributes but other browsers reflect the attribute values instead - see// https://github.com/w3c/svgwg/issues/1153diff --git a/Libraries/LibWeb/SVG/SVGEllipseElement.cpp b/Libraries/LibWeb/SVG/SVGEllipseElement.cppindex 68a38c1ab95..696cec85484 100644--- a/Libraries/LibWeb/SVG/SVGEllipseElement.cpp+++ b/Libraries/LibWeb/SVG/SVGEllipseElement.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGfx/Path.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/SVG/AttributeNames.h>#include <LibWeb/SVG/AttributeParsing.h>@@ -19,62 +18,4 @@ SVGEllipseElement::SVGEllipseElement(DOM::Document& document, DOM::QualifiedName{}-Gfx::Path SVGEllipseElement::get_path(CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values)-{- auto computed_rx = computed_values.rx();- auto computed_ry = computed_values.ry();-- float rx = computed_rx.to_px_or_zero(viewport_size.width()).to_float();- float ry = computed_ry.to_px_or_zero(viewport_size.height()).to_float();-- // https://svgwg.org/svg2-draft/geometry.html#RxProperty- // When the computed value of ‘rx’ is auto, the used radius is equal to the absolute length used for ry, creating a- // circular arc. If both ‘rx’ and ‘ry’ have a computed value of auto, the used value is 0.- if (computed_rx.is_auto())- rx = computed_ry.to_px_or_zero(viewport_size.height()).to_float();-- // When the computed value of ‘ry’ is auto, the used radius is equal to the absolute length used for rx, creating a- // circular arc. If both ‘rx’ and ‘ry’ have a computed value of auto, the used value is 0.- if (computed_ry.is_auto())- ry = computed_rx.to_px_or_zero(viewport_size.width()).to_float();-- float cx = computed_values.cx().to_px(viewport_size.width()).to_float();- float cy = computed_values.cy().to_px(viewport_size.height()).to_float();- Gfx::Path path;-- // A negative radius is invalid. If only one radius is invalid, SVG uses- // the other valid radius for both axes; if both are invalid, rendering is- // disabled. A computed value of zero for either dimension also disables- // rendering.- if (rx < 0 && ry >= 0)- rx = ry;- else if (ry < 0 && rx >= 0)- ry = rx;-- if (rx <= 0 || ry <= 0)- return path;-- Gfx::FloatSize radii = { rx, ry };- double x_axis_rotation = 0;- bool large_arc = false;- bool sweep = true; // Note: Spec says it should be false, but it's wrong. https://github.com/w3c/svgwg/issues/765-- // 1. A move-to command to the point cx+rx,cy;- path.move_to({ cx + rx, cy });-- // 2. arc to cx,cy+ry;- path.elliptical_arc_to({ cx, cy + ry }, radii, x_axis_rotation, large_arc, sweep);-- // 3. arc to cx-rx,cy;- path.elliptical_arc_to({ cx - rx, cy }, radii, x_axis_rotation, large_arc, sweep);-- // 4. arc to cx,cy-ry;- path.elliptical_arc_to({ cx, cy - ry }, radii, x_axis_rotation, large_arc, sweep);-- // 5. arc with a segment-completing close path operation.- path.elliptical_arc_to({ cx + rx, cy }, radii, x_axis_rotation, large_arc, sweep);-- return path;-}-}diff --git a/Libraries/LibWeb/SVG/SVGEllipseElement.h b/Libraries/LibWeb/SVG/SVGEllipseElement.hindex 4abd4cd7e98..eb0afa90d35 100644--- a/Libraries/LibWeb/SVG/SVGEllipseElement.h+++ b/Libraries/LibWeb/SVG/SVGEllipseElement.h@@ -18,8 +18,6 @@ class SVGEllipseElement final : public SVGGeometryElement {public:virtual ~SVGEllipseElement() override = default;- virtual Gfx::Path get_path(CSSPixelSize viewport_size, CSS::ComputedValues const&) override;-// AD-HOC: The spec states that the cx, cy, rx and ry IDL attributes reflect the respective computed values and their// corresponding presentation attributes but other browsers reflect the attribute values instead - see// https://github.com/w3c/svgwg/issues/1153diff --git a/Libraries/LibWeb/SVG/SVGGeometryElement.cpp b/Libraries/LibWeb/SVG/SVGGeometryElement.cppindex 48f7181d906..ddc9472f138 100644--- a/Libraries/LibWeb/SVG/SVGGeometryElement.cpp+++ b/Libraries/LibWeb/SVG/SVGGeometryElement.cpp@@ -15,6 +15,7 @@#include <LibWeb/DOM/Document.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Window.h>+#include <LibWeb/Layout/LayoutRustBridge.h>#include <LibWeb/SVG/SVGGeometryElement.h>#include <LibWeb/WebIDL/DOMException.h>@@ -77,9 +78,6 @@ bool SVGGeometryElement::with_computed_values(Function<void(CSSPixelSize viewpor// separately from the layout update above since it may have been skipped if the element was display: none.document().update_style_for_element(*this);- // FIXME: Layout builds each shape's geometry in Rust (svg_geometry_path_of() in svg_formatting_context.rs), while- // this reads the get_path() implementations, which duplicate it. Answer from the Rust builders instead, so- // a fix to one copy cannot miss the other.if (auto computed_values = computed_style()) {callback({ viewport_size.width(), viewport_size.height() }, *computed_values);return true;@@ -108,11 +106,32 @@ bool SVGGeometryElement::with_computed_values(Function<void(CSSPixelSize viewporreturn true;}+// The geometry the element draws, built by the same shape builders layout uses, from what the element parses and from+// the given computed values.+static Gfx::Path geometry_path(SVGGeometryElement const& element, CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values)+{+ Array<void const*, to_underlying(CSS::StyleGroupIndex::Count)> payloads;+ for (size_t index = 0; index < payloads.size(); ++index)+ payloads[index] = computed_values.style_group_payload(static_cast<CSS::StyleGroupIndex>(index));+ auto points = Layout::svg_shape_points(element);+ static_assert(sizeof(Gfx::FloatPoint) == sizeof(Layout::RustFFI::FfiFloatPoint));+ auto* native_path = static_cast<Gfx::Path*>(Layout::RustFFI::svg_geometry_element_path(+ Layout::svg_geometry_facts(element),+ payloads.data(),+ payloads.size(),+ reinterpret_cast<Layout::RustFFI::FfiFloatPoint const*>(points.data()),+ points.size(),+ viewport_size));+ auto path = move(*native_path);+ delete native_path;+ return path;+}+Gfx::Path SVGGeometryElement::computed_path(){Gfx::Path path;with_computed_values([&](CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values) {- path = get_path(viewport_size, computed_values);+ path = geometry_path(*this, viewport_size, computed_values);});return path;}@@ -137,7 +156,7 @@ WebIDL::ExceptionOr<bool> SVGGeometryElement::is_point_in_fill(Bindings::DOMPoinbool is_point_in_fill = false;auto has_geometry = with_computed_values([&](CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values) {auto winding_rule = computed_values.fill_rule() == CSS::FillRule::Evenodd ? Gfx::WindingRule::EvenOdd : Gfx::WindingRule::Nonzero;- is_point_in_fill = get_path(viewport_size, computed_values).contains({ point.x, point.y }, winding_rule);+ is_point_in_fill = geometry_path(*this, viewport_size, computed_values).contains({ point.x, point.y }, winding_rule);});if (!has_geometry)return WebIDL::InvalidStateError::create(HTML::relevant_realm(*this), "The element's geometry cannot be computed"_utf16);diff --git a/Libraries/LibWeb/SVG/SVGGeometryElement.h b/Libraries/LibWeb/SVG/SVGGeometryElement.hindex 503ba194921..ea86e416930 100644--- a/Libraries/LibWeb/SVG/SVGGeometryElement.h+++ b/Libraries/LibWeb/SVG/SVGGeometryElement.h@@ -20,7 +20,6 @@ public:virtual CSS::ElementBoxKind box_kind() const override;- virtual Gfx::Path get_path(CSSPixelSize viewport_size, CSS::ComputedValues const&) = 0;Gfx::Path computed_path();WebIDL::ExceptionOr<bool> is_point_in_fill(Bindings::DOMPointInit const&);diff --git a/Libraries/LibWeb/SVG/SVGLineElement.cpp b/Libraries/LibWeb/SVG/SVGLineElement.cppindex bbbaadc7b49..de4fdd8784c 100644--- a/Libraries/LibWeb/SVG/SVGLineElement.cpp+++ b/Libraries/LibWeb/SVG/SVGLineElement.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGfx/Path.h>#include <LibWeb/Layout/Node.h>#include <LibWeb/SVG/AttributeNames.h>#include <LibWeb/SVG/AttributeParsing.h>@@ -37,24 +36,4 @@ void SVGLineElement::attribute_changed(Utf16FlyString const& name, Optional<Utf1set_needs_layout_update(DOM::SetNeedsLayoutReason::StyleChange);}-Gfx::Path SVGLineElement::get_path(CSSPixelSize viewport_size, CSS::ComputedValues const&)-{- auto const viewport_width = viewport_size.width().to_float();- auto const viewport_height = viewport_size.height().to_float();-- Gfx::Path path;- float const x1 = m_x1.value_or({ 0, false }).resolve_relative_to(viewport_width);- float const y1 = m_y1.value_or({ 0, false }).resolve_relative_to(viewport_height);- float const x2 = m_x2.value_or({ 0, false }).resolve_relative_to(viewport_width);- float const y2 = m_y2.value_or({ 0, false }).resolve_relative_to(viewport_height);-- // 1. perform an absolute moveto operation to absolute location (x1,y1)- path.move_to({ x1, y1 });-- // 2. perform an absolute lineto operation to absolute location (x2,y2)- path.line_to({ x2, y2 });-- return path;-}-}diff --git a/Libraries/LibWeb/SVG/SVGLineElement.h b/Libraries/LibWeb/SVG/SVGLineElement.hindex 7369e41e308..0e00cdde5b1 100644--- a/Libraries/LibWeb/SVG/SVGLineElement.h+++ b/Libraries/LibWeb/SVG/SVGLineElement.h@@ -19,8 +19,6 @@ public:virtual void attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_) override;- virtual Gfx::Path get_path(CSSPixelSize viewport_size, CSS::ComputedValues const&) override;-// The parsed endpoint attributes, as the element publishes them to layout.NumberPercentage x1_value() const { return m_x1.value_or({ 0, false }); }NumberPercentage y1_value() const { return m_y1.value_or({ 0, false }); }diff --git a/Libraries/LibWeb/SVG/SVGPathElement.cpp b/Libraries/LibWeb/SVG/SVGPathElement.cppindex 63352175a0b..bd1a35f66b6 100644--- a/Libraries/LibWeb/SVG/SVGPathElement.cpp+++ b/Libraries/LibWeb/SVG/SVGPathElement.cpp@@ -5,7 +5,6 @@*/#include <AK/Optional.h>-#include <LibGfx/Path.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Event.h>#include <LibWeb/Layout/Box.h>@@ -21,25 +20,4 @@ SVGPathElement::SVGPathElement(DOM::Document& document, DOM::QualifiedName quali{}-Gfx::Path SVGPathElement::get_path(CSSPixelSize, CSS::ComputedValues const& computed_values)-{- auto computed_d = computed_values.d();-- if (computed_d->is_keyword()) {- VERIFY(computed_d->as_keyword().keyword() == CSS::Keyword::None);- return {};- }-- VERIFY(computed_d->is_basic_shape());- auto const& shape = *computed_d->rust_style_value_data()->basic_shape.shape.pointer;- VERIFY(shape.kind == 6);- auto* native_path = static_cast<Gfx::Path*>(CSS::StyleValueFFI::rust_css_path_to_gfx_path(&shape.path));- auto path = move(*native_path);- delete native_path;- static_assert(to_underlying(Gfx::WindingRule::Nonzero) == 0);- static_assert(to_underlying(Gfx::WindingRule::EvenOdd) == 1);- path.set_fill_type(static_cast<Gfx::WindingRule>(shape.fill_rule));- return path;-}-}diff --git a/Libraries/LibWeb/SVG/SVGPathElement.h b/Libraries/LibWeb/SVG/SVGPathElement.hindex b10673fa258..188daec7441 100644--- a/Libraries/LibWeb/SVG/SVGPathElement.h+++ b/Libraries/LibWeb/SVG/SVGPathElement.h@@ -18,8 +18,6 @@ class SVGPathElement final : public SVGGeometryElement {public:virtual ~SVGPathElement() override = default;- virtual Gfx::Path get_path(CSSPixelSize viewport_size, CSS::ComputedValues const&) override;-private:virtual bool is_svg_path_element() const final { return true; }diff --git a/Libraries/LibWeb/SVG/SVGPolygonElement.cpp b/Libraries/LibWeb/SVG/SVGPolygonElement.cppindex bc7f2e6a72c..5ca2978ade6 100644--- a/Libraries/LibWeb/SVG/SVGPolygonElement.cpp+++ b/Libraries/LibWeb/SVG/SVGPolygonElement.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGfx/Path.h>#include <LibWeb/Layout/Node.h>#include <LibWeb/SVG/AttributeNames.h>#include <LibWeb/SVG/AttributeParsing.h>@@ -29,24 +28,4 @@ void SVGPolygonElement::attribute_changed(Utf16FlyString const& name, Optional<U}}-Gfx::Path SVGPolygonElement::get_path(CSSPixelSize, CSS::ComputedValues const&)-{- Gfx::Path path;-- if (m_points.is_empty())- return path;-- // 1. perform an absolute moveto operation to the first coordinate pair in the list of points- path.move_to(m_points.first());-- // 2. for each subsequent coordinate pair, perform an absolute lineto operation to that coordinate pair.- for (size_t point_index = 1; point_index < m_points.size(); ++point_index)- path.line_to(m_points[point_index]);-- // 3. perform a closepath command- path.close();-- return path;-}-}diff --git a/Libraries/LibWeb/SVG/SVGPolygonElement.h b/Libraries/LibWeb/SVG/SVGPolygonElement.hindex 96805ca5d9b..22efacdb64a 100644--- a/Libraries/LibWeb/SVG/SVGPolygonElement.h+++ b/Libraries/LibWeb/SVG/SVGPolygonElement.h@@ -19,8 +19,6 @@ public:virtual void attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_) override;- virtual Gfx::Path get_path(CSSPixelSize viewport_size, CSS::ComputedValues const&) override;-// The parsed `points` list, as the element publishes it to layout.ReadonlySpan<Gfx::FloatPoint> points() const { return m_points; }diff --git a/Libraries/LibWeb/SVG/SVGPolylineElement.cpp b/Libraries/LibWeb/SVG/SVGPolylineElement.cppindex d83a24ccae5..9c77ca2728e 100644--- a/Libraries/LibWeb/SVG/SVGPolylineElement.cpp+++ b/Libraries/LibWeb/SVG/SVGPolylineElement.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGfx/Path.h>#include <LibWeb/Layout/Node.h>#include <LibWeb/SVG/AttributeNames.h>#include <LibWeb/SVG/AttributeParsing.h>@@ -29,21 +28,4 @@ void SVGPolylineElement::attribute_changed(Utf16FlyString const& name, Optional<}}-Gfx::Path SVGPolylineElement::get_path(CSSPixelSize, CSS::ComputedValues const&)-{- Gfx::Path path;-- if (m_points.is_empty())- return path;-- // 1. perform an absolute moveto operation to the first coordinate pair in the list of points- path.move_to(m_points.first());-- // 2. for each subsequent coordinate pair, perform an absolute lineto operation to that coordinate pair.- for (size_t point_index = 1; point_index < m_points.size(); ++point_index)- path.line_to(m_points[point_index]);-- return path;-}-}diff --git a/Libraries/LibWeb/SVG/SVGPolylineElement.h b/Libraries/LibWeb/SVG/SVGPolylineElement.hindex 75fd42cf734..f3651a925ba 100644--- a/Libraries/LibWeb/SVG/SVGPolylineElement.h+++ b/Libraries/LibWeb/SVG/SVGPolylineElement.h@@ -19,8 +19,6 @@ public:virtual void attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_) override;- virtual Gfx::Path get_path(CSSPixelSize viewport_size, CSS::ComputedValues const&) override;-// The parsed `points` list, as the element publishes it to layout.ReadonlySpan<Gfx::FloatPoint> points() const { return m_points; }diff --git a/Libraries/LibWeb/SVG/SVGRectElement.cpp b/Libraries/LibWeb/SVG/SVGRectElement.cppindex 11b6a74c07c..326b8e550dc 100644--- a/Libraries/LibWeb/SVG/SVGRectElement.cpp+++ b/Libraries/LibWeb/SVG/SVGRectElement.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGfx/Path.h>#include <LibWeb/SVG/SVGRectElement.h>namespace Web::SVG {@@ -16,139 +15,6 @@ SVGRectElement::SVGRectElement(DOM::Document& document, DOM::QualifiedName quali{}-Gfx::Path SVGRectElement::get_path(CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values)-{- auto computed_width = computed_values.width();- auto computed_height = computed_values.height();-- // FIXME: to_px rounds prematurely here - we shouldn't round to fixed point CSSPixels until converting to CSS pixel- // space from SVG user space - this likely extends to other SVG geometry elements as well.- auto width = computed_width.is_length_percentage() ? computed_width.length_percentage().to_px(viewport_size.width()).to_double() : 0.0;- auto height = computed_height.is_length_percentage() ? computed_height.length_percentage().to_px(viewport_size.height()).to_double() : 0.0;-- auto x = computed_values.x().to_px(viewport_size.width()).to_double();- auto y = computed_values.y().to_px(viewport_size.height()).to_double();-- Gfx::Path path;- // Non-positive dimensions disable rendering. In particular, a negative- // width or height is an invalid geometry value rather than a rectangle- // extending in the opposite direction.- if (width <= 0 || height <= 0)- return path;-- auto corner_radii = calculate_used_corner_radius_values(computed_values, width, height);- float rx = corner_radii.width();- float ry = corner_radii.height();-- // 1. perform an absolute moveto operation to location (x+rx,y);- path.move_to({ x + rx, y });-- // 2, perform an absolute horizontal lineto with parameter x+width-rx;- path.horizontal_line_to(x + width - rx);-- // 3. if both rx and ry are greater than zero,- // perform an absolute elliptical arc operation to coordinate (x+width,y+ry),- // where rx and ry are used as the equivalent parameters to the elliptical arc command,- // the x-axis-rotation and large-arc-flag are set to zero,- // the sweep-flag is set to one;- double x_axis_rotation = 0;- bool large_arc_flag = false;- bool sweep_flag = true;- if (rx > 0 && ry > 0)- path.elliptical_arc_to({ x + width, y + ry }, corner_radii, x_axis_rotation, large_arc_flag, sweep_flag);-- // 4. perform an absolute vertical lineto parameter y+height-ry;- path.vertical_line_to(y + height - ry);-- // 5. if both rx and ry are greater than zero,- // perform an absolute elliptical arc operation to coordinate (x+width-rx,y+height),- // using the same parameters as previously;- if (rx > 0 && ry > 0)- path.elliptical_arc_to({ x + width - rx, y + height }, corner_radii, x_axis_rotation, large_arc_flag, sweep_flag);-- // 6. perform an absolute horizontal lineto parameter x+rx;- path.horizontal_line_to(x + rx);-- // 7. if both rx and ry are greater than zero,- // perform an absolute elliptical arc operation to coordinate (x,y+height-ry),- // using the same parameters as previously;- if (rx > 0 && ry > 0)- path.elliptical_arc_to({ x, y + height - ry }, corner_radii, x_axis_rotation, large_arc_flag, sweep_flag);-- // 8. perform an absolute vertical lineto parameter y+ry- path.vertical_line_to(y + ry);-- // 9. if both rx and ry are greater than zero,- // perform an absolute elliptical arc operation with a segment-completing close path operation,- // using the same parameters as previously.- if (rx > 0 && ry > 0)- path.elliptical_arc_to({ x + rx, y }, corner_radii, x_axis_rotation, large_arc_flag, sweep_flag);-- path.close();-- return path;-}--Gfx::FloatSize SVGRectElement::calculate_used_corner_radius_values(CSS::ComputedValues const& computed_values, float used_width, float used_height) const-{- // The used values for rx and ry are determined from the computed values by following these steps in order:-- auto computed_rx = computed_values.rx();- auto computed_ry = computed_values.ry();-- // 1. If both rx and ry have a computed value of auto (since auto is the initial value for both properties, this- // will also occur if neither are specified by the author or if all author-supplied values are invalid), then- // the used value of both rx and ry is 0. (This will result in square corners.)- if (computed_rx.is_auto() && computed_ry.is_auto())- return { 0, 0 };-- // 2. Otherwise, convert specified values to absolute values as follows:- float used_rx;- float used_ry;-- {- // 1. If rx is set to a length value or a percentage, but ry is auto, calculate an absolute length equivalent- // for rx, resolving percentages against the used width of the rectangle; the absolute value for ry is the- // same.- if (!computed_rx.is_auto() && computed_ry.is_auto()) {- used_rx = computed_rx.to_px_or_zero(CSSPixels { used_width }).to_float();- used_ry = used_rx;- }-- // 2. If ry is set to a length value or a percentage, but rx is auto, calculate the absolute length equivalent- // for ry, resolving percentages against the used height of the rectangle; the absolute value for rx is the- // same.- if (!computed_ry.is_auto() && computed_rx.is_auto()) {- used_ry = computed_ry.to_px_or_zero(CSSPixels { used_height }).to_float();- used_rx = used_ry;- }-- // 3. If both rx and ry were set to lengths or percentages, absolute values are generated individually,- // resolving rx percentages against the used width, and resolving ry percentages against the used height.- if (!computed_rx.is_auto() && !computed_ry.is_auto()) {- used_rx = computed_rx.to_px_or_zero(CSSPixels { used_width }).to_float();- used_ry = computed_ry.to_px_or_zero(CSSPixels { used_height }).to_float();- }- }-- // 3. Finally, apply clamping to generate the used values:- {- // 1. If the absolute rx (after the above steps) is greater than half of the used width, then the used value of- // rx is half of the used width.- if (used_rx > used_width / 2)- used_rx = used_width / 2;-- // 2. If the absolute ry (after the above steps) is greater than half of the used height, then the used value of- // ry is half of the used height.- if (used_ry > used_height / 2)- used_ry = used_height / 2;-- // 3. Otherwise, the used values of rx and ry are the absolute values computed previously.- }-- return { used_rx, used_ry };-}-// Reflected length accessors are generated by SVGElement's reflection macro.}diff --git a/Libraries/LibWeb/SVG/SVGRectElement.h b/Libraries/LibWeb/SVG/SVGRectElement.hindex 509c0bbbdba..ec0dffba468 100644--- a/Libraries/LibWeb/SVG/SVGRectElement.h+++ b/Libraries/LibWeb/SVG/SVGRectElement.h@@ -18,8 +18,6 @@ class SVGRectElement final : public SVGGeometryElement {public:virtual ~SVGRectElement() override = default;- virtual Gfx::Path get_path(CSSPixelSize viewport_size, CSS::ComputedValues const&) override;-// AD-HOC: The spec states that the x, y, width, height, rx and ry IDL attributes reflect the respective computed values// and their corresponding presentation attributes but other browsers reflect the attribute values instead - see// https://github.com/w3c/svgwg/issues/1153@@ -46,8 +44,6 @@ private:virtual bool is_svg_rect_element() const final { return true; }SVGRectElement(DOM::Document&, DOM::QualifiedName);-- Gfx::FloatSize calculate_used_corner_radius_values(CSS::ComputedValues const&, float used_width, float used_height) const;};}diff --git a/Tests/LibWeb/Text/expected/SVG/svg-geometry-queries-all-shapes.txt b/Tests/LibWeb/Text/expected/SVG/svg-geometry-queries-all-shapes.txtnew file mode 100644index 00000000000..c9442b3aa80--- /dev/null+++ b/Tests/LibWeb/Text/expected/SVG/svg-geometry-queries-all-shapes.txt@@ -0,0 +1,31 @@+rect: length=240 point=(90, 10) fill=1011+rect with rx and ry: length=228.42 point=(90, 19.03) fill=1011+rect with percentage rx and auto ry: length=262.81 point=(116.89, 12.76) fill=1110+rect with oversized ry and auto rx: length=198.62 point=(88.47, 36.31) fill=1010+rect with zero width: length=0 fill=0000+circle: length=125.61 point=(90, 67.32) fill=0100+circle with percentages: length=99.21 point=(92.1, 63.68) fill=0100+circle with zero r: length=0 fill=0000+ellipse: length=193.74 point=(83.97, 68.32) fill=0100+ellipse with percentages: length=193.74 point=(83.97, 68.32) fill=0100+ellipse with auto rx: length=125.61 point=(90, 67.32) fill=0100+ellipse with auto radii: length=0 fill=0000+ellipse with negative ry: length=188.46 point=(85, 75.98) fill=0100+line: length=100 point=(36.67, 40) fill=0000+line with percentages: length=170.88 point=(73.33, 40) fill=0000+polyline: length=130 point=(53.33, 10) fill=1001+polygon: length=224.34 point=(84.78, 10) fill=1001+polygon without points: length=0 fill=0000+path: length=209.44 point=(79.81, 10) fill=1001+path with evenodd fill: length=600 point=(100, 100) fill=0101+path with nonzero fill: length=600 point=(100, 100) fill=1111+path with d property: length=100 point=(30, 36.67) fill=0000+path without d: length=0 fill=0000+circle in viewBox: length=49.66 point=(46.05, 31.85) fill=1000+line in viewBox: length=111.8 point=(33.33, 16.67) fill=0100+detached rect: length=91.37 point=(30, 7.61) fill=0001+detached circle: length=62.81 point=(45, 38.66) fill=1000+detached ellipse: length=96.85 point=(41.98, 39.16) fill=1000+detached line: length=50 point=(10, 13.33) fill=0000+detached polygon: length=224.34 point=(84.78, 10) fill=1001+detached path: length=209.44 point=(79.81, 10) fill=1001diff --git a/Tests/LibWeb/Text/input/SVG/svg-geometry-queries-all-shapes.html b/Tests/LibWeb/Text/input/SVG/svg-geometry-queries-all-shapes.htmlnew file mode 100644index 00000000000..de8749d0065--- /dev/null+++ b/Tests/LibWeb/Text/input/SVG/svg-geometry-queries-all-shapes.html@@ -0,0 +1,70 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<svg id="viewport" width="200" height="100">+ <rect id="rect" x="10" y="10" width="80" height="40"/>+ <rect id="rect with rx and ry" x="10" y="10" width="80" height="40" rx="10" ry="5"/>+ <rect id="rect with percentage rx and auto ry" x="10%" y="10" width="50%" height="40" rx="10%"/>+ <rect id="rect with oversized ry and auto rx" x="10" y="10" width="80" height="40" ry="30"/>+ <rect id="rect with zero width" width="0" height="40"/>+ <circle id="circle" cx="100" cy="50" r="20"/>+ <circle id="circle with percentages" cx="50%" cy="50%" r="10%"/>+ <circle id="circle with zero r" cx="20" cy="20" r="0"/>+ <ellipse id="ellipse" cx="100" cy="50" rx="40" ry="20"/>+ <ellipse id="ellipse with percentages" cx="50%" cy="50%" rx="20%" ry="20%"/>+ <ellipse id="ellipse with auto rx" cx="100" cy="50" ry="20"/>+ <ellipse id="ellipse with auto radii" cx="100" cy="50"/>+ <ellipse id="ellipse with negative ry" cx="100" cy="50" rx="30" style="ry: -5px"/>+ <line id="line" x1="10" y1="20" x2="90" y2="80"/>+ <line id="line with percentages" x1="10%" y1="20%" x2="90%" y2="80%"/>+ <polyline id="polyline" points="10,10 90,10 90,60"/>+ <polygon id="polygon" points="10,10 90,10 90,60"/>+ <polygon id="polygon without points"/>+ <path id="path" d="M 10 10 h 80 v 40 z"/>+ <path id="path with evenodd fill" d="M 0 0 h 100 v 100 h -100 z M 25 25 h 50 v 50 h -50 z" fill-rule="evenodd"/>+ <path id="path with nonzero fill" d="M 0 0 h 100 v 100 h -100 z M 25 25 h 50 v 50 h -50 z"/>+ <path id="path with d property" style="d: path('M 10 10 L 70 90')"/>+ <path id="path without d"/>+</svg>+<svg id="viewbox" width="400" height="400" viewBox="0 0 100 50">+ <circle id="circle in viewBox" cx="50%" cy="50%" r="10%"/>+ <line id="line in viewBox" x1="0" y1="0" x2="100%" y2="100%"/>+</svg>+<script>+ test(() => {+ const round = value => Math.round(value * 100) / 100;+ const probes = [+ [50, 30],+ [100, 50],+ [50, 50],+ [15, 12],+ ];+ const describe = element => {+ const length = element.getTotalLength();+ let line = `${element.id}: length=${round(length)}`;+ if (length > 0) {+ const point = element.getPointAtLength(length / 3);+ line += ` point=(${round(point.x)}, ${round(point.y)})`;+ }+ const fill = probes.map(([x, y]) => (element.isPointInFill({ x, y }) ? "1" : "0")).join("");+ println(`${line} fill=${fill}`);+ };++ for (const element of document.querySelectorAll("svg > *"))+ describe(element);++ const ns = "http://www.w3.org/2000/svg";+ const create = (name, attributes) => {+ const element = document.createElementNS(ns, name);+ element.id = `detached ${name}`;+ for (const [attribute, value] of Object.entries(attributes))+ element.setAttribute(attribute, value);+ return element;+ };+ describe(create("rect", { width: 30, height: 20, rx: 5 }));+ describe(create("circle", { cx: 50, cy: 30, r: 10 }));+ describe(create("ellipse", { cx: 50, cy: 30, rx: 20, ry: 10 }));+ describe(create("line", { x1: 0, y1: 0, x2: 30, y2: 40 }));+ describe(create("polygon", { points: "10,10 90,10 90,60" }));+ describe(create("path", { d: "M 10 10 h 80 v 40 z" }));+ });+</script>