Skip to content

Truly independent web browser

LibWeb: Measure SVG geometry in Rust instead of through Gfx::Path

Aliaksandr Kalenik21cdb4bdf103
diff --git a/Libraries/LibGfx/Rust/src/path.rs b/Libraries/LibGfx/Rust/src/path.rs
index fdec2e3599b..00104934183 100644
--- a/Libraries/LibGfx/Rust/src/path.rs
+++ b/Libraries/LibGfx/Rust/src/path.rs
@@ -11,6 +11,7 @@ use crate::geometry::{FloatPoint, FloatSize};
use crate::matrix::AffineTransform;
use crate::paint_enums::WindingRule;
use geometry::PathGeometry;
+pub use measure::PathVertex;
mod arcs;
mod curves;
@@ -214,6 +215,11 @@ impl Path {
.map(|(point, tangent)| [point.x, point.y, tangent.x, tangent.y])
}
+ /// The vertices of polylines through the path, with their distance along it (see [`measure::vertices`]).
+ pub fn vertices(&self) -> Vec<PathVertex> {
+ measure::vertices(&self.geometry)
+ }
+
pub fn contains(&self, x: f32, y: f32, winding_rule: WindingRule) -> bool {
hit_test::contains(&self.geometry, x, y, winding_rule)
}
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index 79637423c69..7908aecf095 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -2934,9 +2934,13 @@ fn main() -> Result<(), Box<dyn Error>> {
layout_config
.includes
.push("LibWeb/Layout/TreeBuilderRustFFI.h".to_string());
- // A compositor animation effect state is opaque to C++, which holds it by pointer, and so is the paint server an
- // SVG paint resource callback fills.
- for name in ["CompositorAnimationEffectState", "PublishedSvgPaintServer"] {
+ // A compositor animation effect state is opaque to C++, which holds it by pointer, and so are the paint server an
+ // SVG paint resource callback fills and a parsed SVG path.
+ for name in [
+ "CompositorAnimationEffectState",
+ "PublishedSvgPaintServer",
+ "ParsedPath",
+ ] {
layout_config.export.rename.insert(name.to_string(), "void".to_string());
layout_config.export.exclude.push(name.to_string());
}
diff --git a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs
index b59516aecca..b2784b1369c 100644
--- a/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/svg_formatting_context.rs
@@ -1071,111 +1071,212 @@ impl SvgShapeGeometry {
}
}
-/// 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.
-/// Calls `append` once with the byte form of the path, which `Gfx::Path` reads.
+/// A shape element whose geometry the DOM measures: the shape `geometry` names, the computed style in `payloads`, the
+/// points of a polyline or polygon, and the size of the viewport the element sits in. Only the `geometry_kind` and
+/// `line_*` fields of `geometry` are read.
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct FfiSvgGeometryElementShape {
+ pub geometry: FfiSvgAttributeFacts,
+ pub payloads: *const *const c_void,
+ pub payload_count: usize,
+ pub points: *const FfiFloatPoint,
+ pub point_count: usize,
+ pub viewport_size: FfiCssPixelSize,
+}
+
+impl FfiSvgGeometryElementShape {
+ /// What `measure` answers of the geometry the element draws, in the user units of its viewport, built by the same
+ /// shape builders layout uses, and of the element's style.
+ ///
+ /// # Safety
+ /// `payloads` must point to `payload_count` live style group payloads, and `points` to `point_count` points.
+ unsafe fn measure<R>(&self, measure: impl FnOnce(&libgfx_rust::path::Path, StyleValues<'_>) -> R) -> R {
+ assert!(!self.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(self.payloads, self.payload_count) });
+ // SAFETY: Guaranteed by the caller.
+ let points = unsafe { ak::slice_from_raw_parts(self.points, self.point_count) };
+ let shape_geometry = SvgShapeGeometry {
+ viewport_width: self.viewport_size.width,
+ viewport_height: self.viewport_size.height,
+ };
+ let style = StyleValues::new(&style_payloads);
+ measure(&shape_geometry.path(self.geometry, style, Some(points)), style)
+ }
+}
+
+/// A vertex of polylines through a path, at `distance` along it, where the path heads in `direction`.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+#[repr(C)]
+pub struct FfiPathVertex {
+ pub point: FfiFloatPoint,
+ pub distance: f32,
+ pub direction: FfiFloatPoint,
+}
+
+/// Calls `push` once with the vertices of polylines through `path`, as close to its curves as its length is measured.
///
/// # Safety
-///
-/// `payloads` must point at `payload_count` live style group payloads, and `points` at
-/// `point_count` points. `context` must be valid for `append` for the duration of this call.
-#[allow(clippy::too_many_arguments)]
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn svg_geometry_element_encode_path(
- geometry: FfiSvgAttributeFacts,
- payloads: *const *const c_void,
- payload_count: usize,
- points: *const FfiFloatPoint,
- point_count: usize,
- viewport_size: FfiCssPixelSize,
+/// `context` must be valid for `push` for the duration of this call.
+unsafe fn push_path_vertices(
+ path: &libgfx_rust::path::Path,
context: *mut c_void,
- append: unsafe extern "C" fn(*mut c_void, *const u8, usize),
+ push: unsafe extern "C" fn(*mut c_void, *const FfiPathVertex, usize),
) {
- assert!(!payloads.is_null(), "style group payload array is null");
- let mut style_payloads = FfiStylePayloads::default();
+ let vertices: Vec<FfiPathVertex> = path
+ .vertices()
+ .into_iter()
+ .map(|vertex| FfiPathVertex {
+ point: FfiFloatPoint {
+ x: vertex.point.x,
+ y: vertex.point.y,
+ },
+ distance: vertex.distance,
+ direction: FfiFloatPoint {
+ x: vertex.direction.x,
+ y: vertex.direction.y,
+ },
+ })
+ .collect();
+ // SAFETY: Guaranteed by the caller.
+ unsafe { push(context, vertices.as_ptr(), vertices.len()) };
+}
+
+/// Whether the point is inside the geometry of a shape element, as the winding rule its `fill-rule` names counts it.
+/// Open subpaths are closed for the test, and points on the path count as inside.
+///
+/// # Safety
+/// As for [`FfiSvgGeometryElementShape::measure`].
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn svg_geometry_element_fill_contains(
+ shape: &FfiSvgGeometryElementShape,
+ x: f32,
+ y: f32,
+) -> bool {
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ shape.measure(|path, style| {
+ let winding_rule = if style.inherited_svg().fill_rule == crate::css::css_enums::fill_rule::EVENODD {
+ libgfx_rust::WindingRule::EvenOdd
+ } else {
+ libgfx_rust::WindingRule::Nonzero
+ };
+ path.contains(x, y, winding_rule)
+ })
+ }
+}
+
+/// The length of the geometry of a shape element.
+///
+/// # Safety
+/// As for [`FfiSvgGeometryElementShape::measure`].
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn svg_geometry_element_total_length(shape: &FfiSvgGeometryElementShape) -> f32 {
// SAFETY: Guaranteed by the caller.
- style_payloads
- .groups
- .copy_from_slice(unsafe { ak::slice_from_raw_parts(payloads, payload_count) });
+ unsafe { shape.measure(|path, _| path.length()) }
+}
+
+/// Writes the point at `distance` along the geometry of a shape element to `point`, with the distance clamped to the
+/// ends of the geometry. Answers false, writing nothing, for a geometry without segments.
+///
+/// # Safety
+/// As for [`FfiSvgGeometryElementShape::measure`].
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn svg_geometry_element_point_at_length(
+ shape: &FfiSvgGeometryElementShape,
+ distance: f32,
+ point: &mut FfiFloatPoint,
+) -> bool {
// 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,
+ let Some([x, y, _, _]) = (unsafe { shape.measure(|path, _| path.point_at_length(distance)) }) else {
+ return false;
};
- let bytes = shape_geometry
- .path(geometry, StyleValues::new(&style_payloads), Some(points))
- .serialize_to_bytes();
+ *point = FfiFloatPoint { x, y };
+ true
+}
+
+/// Calls `push` once with the vertices of polylines through the geometry of a shape element (see
+/// [`push_path_vertices`]).
+///
+/// # Safety
+/// As for [`FfiSvgGeometryElementShape::measure`]. `context` must be valid for `push` for the duration of this call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn svg_geometry_element_vertices(
+ shape: &FfiSvgGeometryElementShape,
+ context: *mut c_void,
+ push: unsafe extern "C" fn(*mut c_void, *const FfiPathVertex, usize),
+) {
// SAFETY: Guaranteed by the caller.
- unsafe { append(context, bytes.as_ptr(), bytes.len()) };
+ unsafe { shape.measure(|path, _| push_path_vertices(path, context, push)) }
+}
+
+/// Calls `push` once with the vertices of polylines through the path that `path` draws (see [`push_path_vertices`]).
+///
+/// # Safety
+/// `context` must be valid for `push` for the duration of this call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn svg_path_data_vertices(
+ path: &crate::svg::ParsedPath,
+ context: *mut c_void,
+ push: unsafe extern "C" fn(*mut c_void, *const FfiPathVertex, usize),
+) {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { push_path_vertices(&path.to_gfx_path(), context, push) }
}
/// Whether the point is inside the area that stroking the geometry of a shape element covers, with the stroke drawn
-/// from the element's computed style, in the user units of the viewport of the given size. Distances along the path are
-/// scaled by the dash scale. The host scale is the scale from the element's user space to its host coordinate space,
-/// in which a non-scaling stroke is drawn.
+/// from the element's computed style. Distances along the path are scaled by the dash scale. The host scale is the
+/// scale from the element's user space to its host coordinate space, in which a non-scaling stroke is drawn.
///
/// # Safety
-/// `payloads` must point to `payload_count` style group payloads, and `points` to `point_count` points.
+/// As for [`FfiSvgGeometryElementShape::measure`].
#[unsafe(no_mangle)]
-#[allow(clippy::too_many_arguments)]
pub unsafe extern "C" fn svg_geometry_element_stroke_contains(
- geometry: FfiSvgAttributeFacts,
- payloads: *const *const c_void,
- payload_count: usize,
- points: *const FfiFloatPoint,
- point_count: usize,
- viewport_size: FfiCssPixelSize,
+ shape: &FfiSvgGeometryElementShape,
dash_scale: f32,
host_scale: f32,
x: f32,
y: f32,
) -> bool {
- assert!(!payloads.is_null(), "style group payload array is null");
- let mut style_payloads = FfiStylePayloads::default();
+ let viewport_size = shape.viewport_size;
// 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,
- };
- let style = StyleValues::new(&style_payloads);
- let path = shape_geometry.path(geometry, style, Some(points));
-
- // The same basis that layout resolves the stroke's percentages against.
- // FIXME: The spec formula is the normalized diagonal sqrt((width² + height²) / 2), as for layout.
- let basis = (viewport_size.width + viewport_size.height) * CssPixels::nearest_value_for(0.5);
- let stroke = crate::painting::record::paint::svg::svg_stroke_style_for_percentage_basis(&style, basis);
- // https://svgwg.org/svg2-draft/painting.html#PaintingVectorEffects
- // With the non-scaling-stroke vector effect, stroke outline shall be calculated in the "host" coordinate space
- // instead of user coordinate system.
- let stroke_scale = if stroke.non_scaling_stroke && host_scale > 0.0 {
- 1.0 / host_scale
- } else {
- 1.0
- };
- let stroke_style = libgfx_rust::path::StrokeStyle {
- thickness: stroke.width * stroke_scale,
- cap_style: stroke.cap_style,
- join_style: stroke.join_style,
- miter_limit: stroke.miter_limit,
- dash_array: stroke
- .dash_array
- .iter()
- .map(|dash| dash * dash_scale * stroke_scale)
- .collect(),
- dash_offset: stroke.dash_offset * dash_scale * stroke_scale,
- };
- if stroke_style.thickness <= 0.0 {
- return false;
+ unsafe {
+ shape.measure(|path, style| {
+ // The same basis that layout resolves the stroke's percentages against.
+ // FIXME: The spec formula is the normalized diagonal sqrt((width² + height²) / 2), as for layout.
+ let basis = (viewport_size.width + viewport_size.height) * CssPixels::nearest_value_for(0.5);
+ let stroke = crate::painting::record::paint::svg::svg_stroke_style_for_percentage_basis(&style, basis);
+ // https://svgwg.org/svg2-draft/painting.html#PaintingVectorEffects
+ // With the non-scaling-stroke vector effect, stroke outline shall be calculated in the "host" coordinate
+ // space instead of user coordinate system.
+ let stroke_scale = if stroke.non_scaling_stroke && host_scale > 0.0 {
+ 1.0 / host_scale
+ } else {
+ 1.0
+ };
+ let stroke_style = libgfx_rust::path::StrokeStyle {
+ thickness: stroke.width * stroke_scale,
+ cap_style: stroke.cap_style,
+ join_style: stroke.join_style,
+ miter_limit: stroke.miter_limit,
+ dash_array: stroke
+ .dash_array
+ .iter()
+ .map(|dash| dash * dash_scale * stroke_scale)
+ .collect(),
+ dash_offset: stroke.dash_offset * dash_scale * stroke_scale,
+ };
+ if stroke_style.thickness <= 0.0 {
+ return false;
+ }
+ path.stroke_to_fill(&stroke_style)
+ .contains(x, y, libgfx_rust::WindingRule::Nonzero)
+ })
}
- path.stroke_to_fill(&stroke_style)
- .contains(x, y, libgfx_rust::WindingRule::Nonzero)
}
impl<'pass> SvgFormattingContext<'pass> {
diff --git a/Libraries/LibWeb/Rust/src/svg/path_parser.rs b/Libraries/LibWeb/Rust/src/svg/path_parser.rs
index 210d6673011..6c3d564e842 100644
--- a/Libraries/LibWeb/Rust/src/svg/path_parser.rs
+++ b/Libraries/LibWeb/Rust/src/svg/path_parser.rs
@@ -1371,20 +1371,6 @@ pub unsafe extern "C" fn rust_svg_path_serialize(
unsafe { append(context, serialized.as_ptr(), serialized.len()) };
}
-/// Calls `append` once with the byte form of the path that `path` draws, which `Gfx::Path` reads.
-///
-/// # Safety
-/// `context` must be valid for `append` for the duration of this call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_svg_path_encode_gfx_path(
- path: &ParsedPath,
- context: *mut c_void,
- append: unsafe extern "C" fn(*mut c_void, *const u8, usize),
-) {
- let bytes = path.to_gfx_path().serialize_to_bytes();
- unsafe { append(context, bytes.as_ptr(), bytes.len()) };
-}
-
#[cfg(test)]
mod tests {
use super::{Input, ParsedPath, Parser, PathInstruction};
diff --git a/Libraries/LibWeb/SVG/Path.cpp b/Libraries/LibWeb/SVG/Path.cpp
index 56bce4bc723..4331c20c2df 100644
--- a/Libraries/LibWeb/SVG/Path.cpp
+++ b/Libraries/LibWeb/SVG/Path.cpp
@@ -8,7 +8,7 @@
*/
#include <AK/StringBuilder.h>
-#include <LibGfx/Path.h>
+#include <LibWeb/Layout/LayoutRustFFI.h>
#include <LibWeb/SVG/ParserRustFFI.h>
#include <LibWeb/SVG/Path.h>
@@ -23,6 +23,14 @@ static RustFFI::FfiUtf16View ffi_svg_input(Utf16View input)
};
}
+void append_path_vertices(void* context, Layout::RustFFI::FfiPathVertex const* vertices, size_t count)
+{
+ auto& path_vertices = *static_cast<Vector<PathVertex>*>(context);
+ path_vertices.ensure_capacity(path_vertices.size() + count);
+ for (auto const& vertex : ReadonlySpan<Layout::RustFFI::FfiPathVertex> { vertices, count })
+ path_vertices.unchecked_append({ { vertex.point.x, vertex.point.y }, vertex.distance, { vertex.direction.x, vertex.direction.y } });
+}
+
Path parse_path_data(Utf16View input)
{
auto* path = RustFFI::rust_parse_svg_path_data(ffi_svg_input(input));
@@ -72,14 +80,11 @@ Path& Path::operator=(Path&& other)
return *this;
}
-Gfx::Path Path::to_gfx_path() const
+Vector<PathVertex> Path::vertices() const
{
- Vector<u8> bytes;
- auto append = [](void* context, u8 const* data, size_t length) {
- static_cast<Vector<u8>*>(context)->append(data, length);
- };
- RustFFI::rust_svg_path_encode_gfx_path(m_rust_path, &bytes, append);
- return Gfx::Path::from_serialized_bytes(bytes);
+ Vector<PathVertex> vertices;
+ Layout::RustFFI::svg_path_data_vertices(m_rust_path, &vertices, append_path_vertices);
+ return vertices;
}
String Path::serialize() const
diff --git a/Libraries/LibWeb/SVG/Path.h b/Libraries/LibWeb/SVG/Path.h
index 47bdb78f133..cbcd42554ec 100644
--- a/Libraries/LibWeb/SVG/Path.h
+++ b/Libraries/LibWeb/SVG/Path.h
@@ -11,10 +11,28 @@
#include <AK/String.h>
#include <AK/Utf16View.h>
-#include <LibGfx/Forward.h>
+#include <AK/Vector.h>
+#include <LibGfx/Point.h>
+#include <LibGfx/Vector2.h>
+
+namespace Web::Layout::RustFFI {
+
+struct FfiPathVertex;
+
+}
namespace Web::SVG {
+// A vertex of polylines through a path, at `distance` along it, where the path heads in `direction`.
+struct PathVertex {
+ Gfx::FloatPoint point;
+ float distance { 0 };
+ Gfx::FloatVector2 direction;
+};
+
+// Appends the `count` vertices of a path that Rust measured to the Vector<PathVertex> `context` points to.
+void append_path_vertices(void* context, Layout::RustFFI::FfiPathVertex const*, size_t count);
+
class Path;
Path parse_path_data(Utf16View);
@@ -28,7 +46,8 @@ public:
Path& operator=(Path const&);
Path& operator=(Path&&);
- [[nodiscard]] Gfx::Path to_gfx_path() const;
+ // The vertices of polylines through the path, as close to its curves as its length is measured.
+ Vector<PathVertex> vertices() const;
String serialize() const;
bool operator==(Path const&) const;
diff --git a/Libraries/LibWeb/SVG/SVGAnimateMotionElement.cpp b/Libraries/LibWeb/SVG/SVGAnimateMotionElement.cpp
index e7ffb4fc98f..75189fb48ec 100644
--- a/Libraries/LibWeb/SVG/SVGAnimateMotionElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGAnimateMotionElement.cpp
@@ -5,7 +5,6 @@
*/
#include <AK/CharacterTypes.h>
-#include <LibGfx/Path.h>
#include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
#include <LibWeb/CSS/StyleValues/StyleValue.h>
@@ -47,10 +46,10 @@ void SVGAnimateMotionElement::update_referenced_motion_path()
// NB: Only the first mpath child counts, as the content model allows one. Without a shape element that it refers to,
// the attributes of this element define the motion path.
// FIXME: Follow changes to the geometry of the referenced element.
- m_referenced_motion_path.clear();
+ m_referenced_motion_path_vertices.clear();
if (auto* mpath_element = is_connected() ? first_child_of_type<SVGMPathElement>() : nullptr) {
if (auto* geometry_element = as_if<SVGGeometryElement>(mpath_element->referenced_element().ptr()))
- m_referenced_motion_path = geometry_element->computed_path();
+ m_referenced_motion_path_vertices = geometry_element->equivalent_path_vertices();
}
update_animation();
}
@@ -189,13 +188,12 @@ static MotionRotation motion_rotation(DOM::Element const& element)
}
// https://svgwg.org/specs/animations/#AnimateMotionElement
-Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes_along_motion_path(Gfx::Path const& motion_path, CSS::PropertyID property_id) const
+Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes_along_motion_path(ReadonlySpan<PathVertex> vertices, CSS::PropertyID property_id) const
{
// NB: Follow polylines through the motion path, with enough points along its curves to stay as close to them as the
// length of the motion path is measured.
// FIXME: Animate a position along the motion path rather than points along it, so that the target follows its curves
// exactly, as other engines do.
- auto vertices = motion_path.vertices();
if (vertices.is_empty())
return {};
@@ -240,10 +238,10 @@ Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes(SVGElement c
// ‘values’, which overrides ‘from’, ‘by’ and ‘to’.
// FIXME: Take the motion path from the values and by attributes.
// FIXME: Apply the keyPoints attribute.
- if (m_referenced_motion_path.has_value())
- return keyframes_along_motion_path(*m_referenced_motion_path, property_id);
+ if (m_referenced_motion_path_vertices.has_value())
+ return keyframes_along_motion_path(*m_referenced_motion_path_vertices, property_id);
if (auto path = get_attribute(AttributeNames::path); path.has_value())
- return keyframes_along_motion_path(parse_path_data(*path).to_gfx_path(), property_id);
+ return keyframes_along_motion_path(parse_path_data(*path).vertices(), property_id);
auto to = get_attribute(AttributeNames::to);
auto to_translation = to.has_value() ? parse_coordinate_pair_as_translation(target, *to) : nullptr;
diff --git a/Libraries/LibWeb/SVG/SVGAnimateMotionElement.h b/Libraries/LibWeb/SVG/SVGAnimateMotionElement.h
index cf89e728577..f86caa75465 100644
--- a/Libraries/LibWeb/SVG/SVGAnimateMotionElement.h
+++ b/Libraries/LibWeb/SVG/SVGAnimateMotionElement.h
@@ -6,7 +6,7 @@
#pragma once
-#include <LibGfx/Path.h>
+#include <LibWeb/SVG/Path.h>
#include <LibWeb/SVG/SVGAnimationElement.h>
namespace Web::SVG {
@@ -26,9 +26,9 @@ private:
virtual Optional<CSS::PropertyID> target_property() const override;
virtual Vector<Animations::BaseKeyframe> keyframes(SVGElement const& target, CSS::PropertyID) const override;
- Vector<Animations::BaseKeyframe> keyframes_along_motion_path(Gfx::Path const&, CSS::PropertyID) const;
+ Vector<Animations::BaseKeyframe> keyframes_along_motion_path(ReadonlySpan<PathVertex> motion_path_vertices, CSS::PropertyID) const;
- Optional<Gfx::Path> m_referenced_motion_path;
+ Optional<Vector<PathVertex>> m_referenced_motion_path_vertices;
};
}
diff --git a/Libraries/LibWeb/SVG/SVGGeometryElement.cpp b/Libraries/LibWeb/SVG/SVGGeometryElement.cpp
index fb39bbb0ec4..1e5144ec93a 100644
--- a/Libraries/LibWeb/SVG/SVGGeometryElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGGeometryElement.cpp
@@ -109,35 +109,36 @@ bool SVGGeometryElement::with_computed_values(Function<void(CSSPixelSize viewpor
return 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)
+// The shape element whose geometry `measure` measures, with what the element parses and the given computed values,
+// which Rust builds the geometry from with the same shape builders layout uses.
+template<typename Measure>
+static auto measure_geometry(SVGGeometryElement const& element, CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values, Measure measure)
{
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));
- Vector<u8> path_bytes;
- Layout::RustFFI::svg_geometry_element_encode_path(
- Layout::svg_geometry_facts(element),
- payloads.data(),
- payloads.size(),
- reinterpret_cast<Layout::RustFFI::FfiFloatPoint const*>(points.data()),
- points.size(),
- viewport_size,
- &path_bytes,
- [](void* context, u8 const* data, size_t length) { static_cast<Vector<u8>*>(context)->append(data, length); });
- return Gfx::Path::from_serialized_bytes(path_bytes);
+ Layout::RustFFI::FfiSvgGeometryElementShape shape {
+ .geometry = Layout::svg_geometry_facts(element),
+ .payloads = payloads.data(),
+ .payload_count = payloads.size(),
+ .points = reinterpret_cast<Layout::RustFFI::FfiFloatPoint const*>(points.data()),
+ .point_count = points.size(),
+ .viewport_size = viewport_size,
+ };
+ return measure(shape);
}
-Gfx::Path SVGGeometryElement::computed_path()
+Vector<PathVertex> SVGGeometryElement::equivalent_path_vertices()
{
- Gfx::Path path;
+ Vector<PathVertex> vertices;
with_computed_values([&](CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values) {
- path = geometry_path(*this, viewport_size, computed_values);
+ measure_geometry(*this, viewport_size, computed_values, [&](auto const& shape) {
+ Layout::RustFFI::svg_geometry_element_vertices(&shape, &vertices, append_path_vertices);
+ });
});
- return path;
+ return vertices;
}
// https://svgwg.org/svg2-draft/types.html#__svg__SVGGeometryElement__isPointInFill
@@ -148,7 +149,7 @@ WebIDL::ExceptionOr<bool> SVGGeometryElement::is_point_in_fill(Bindings::DOMPoin
// the fill-rule property of an element; and must return false otherwise. Open subpaths must be implicitly closed
// when computing the area inside the path, without affecting the actual subpaths. Points on the path itself must be
// considered to be inside the path.
- // NB: Gfx::Path::contains() closes open subpaths and counts points on the path as inside.
+ // NB: svg_geometry_element_fill_contains() closes open subpaths and counts points on the path as inside.
// The returned value is independent of any visual CSS property but fill-rule
// If either of the x or y properties on point are infinite or NaN, then the method must return false.
@@ -159,8 +160,9 @@ WebIDL::ExceptionOr<bool> SVGGeometryElement::is_point_in_fill(Bindings::DOMPoin
// then throw an InvalidStateError.
bool 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 = geometry_path(*this, viewport_size, computed_values).contains({ point.x, point.y }, winding_rule);
+ is_point_in_fill = measure_geometry(*this, viewport_size, computed_values, [&](auto const& shape) {
+ return Layout::RustFFI::svg_geometry_element_fill_contains(&shape, static_cast<float>(point.x), static_cast<float>(point.y));
+ });
});
if (!has_geometry)
return WebIDL::InvalidStateError::create(HTML::relevant_realm(*this), "The element's geometry cannot be computed"_utf16);
@@ -193,30 +195,16 @@ WebIDL::ExceptionOr<bool> SVGGeometryElement::is_point_in_stroke(Bindings::DOMPo
// then throw an InvalidStateError.
bool is_point_in_stroke = false;
auto has_geometry = with_computed_values([&](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));
-
- // https://svgwg.org/svg2-draft/paths.html#PathLengthAttribute
- // The user agent will scale all distance-along-a-path computations by the ratio of ‘pathLength’ to the user
- // agent's own computed value for total path length.
- // FIXME: A value of zero must be treated as a scaling factor of infinity.
- float dash_scale = 1;
- if (auto path_length = parse_number(get_attribute_value(AttributeNames::pathLength)); path_length.has_value() && *path_length > 0)
- dash_scale = geometry_path(*this, viewport_size, computed_values).length() / *path_length;
-
- auto points = Layout::svg_shape_points(*this);
- is_point_in_stroke = Layout::RustFFI::svg_geometry_element_stroke_contains(
- Layout::svg_geometry_facts(*this),
- payloads.data(),
- payloads.size(),
- reinterpret_cast<Layout::RustFFI::FfiFloatPoint const*>(points.data()),
- points.size(),
- viewport_size,
- dash_scale,
- host_scale,
- static_cast<float>(point.x),
- static_cast<float>(point.y));
+ is_point_in_stroke = measure_geometry(*this, viewport_size, computed_values, [&](auto const& shape) {
+ // https://svgwg.org/svg2-draft/paths.html#PathLengthAttribute
+ // The user agent will scale all distance-along-a-path computations by the ratio of ‘pathLength’ to the
+ // user agent's own computed value for total path length.
+ // FIXME: A value of zero must be treated as a scaling factor of infinity.
+ float dash_scale = 1;
+ if (auto path_length = parse_number(get_attribute_value(AttributeNames::pathLength)); path_length.has_value() && *path_length > 0)
+ dash_scale = Layout::RustFFI::svg_geometry_element_total_length(&shape) / *path_length;
+ return Layout::RustFFI::svg_geometry_element_stroke_contains(&shape, dash_scale, host_scale, static_cast<float>(point.x), static_cast<float>(point.y));
+ });
});
if (!has_geometry)
return WebIDL::InvalidStateError::create(HTML::relevant_realm(*this), "The element's geometry cannot be computed"_utf16);
@@ -228,29 +216,40 @@ WebIDL::ExceptionOr<float> SVGGeometryElement::get_total_length()
{
// When getTotalLength() is called, the user agent's computed value for the total length of the path, in user units,
// is returned.
- return computed_path().length();
+ float total_length = 0;
+ with_computed_values([&](CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values) {
+ total_length = measure_geometry(*this, viewport_size, computed_values, [](auto const& shape) {
+ return Layout::RustFFI::svg_geometry_element_total_length(&shape);
+ });
+ });
+ return total_length;
}
// https://w3c.github.io/svgwg/svg2-draft/types.html#__svg__SVGGeometryElement__getPointAtLength
WebIDL::ExceptionOr<GC::Ref<Geometry::DOMPoint>> SVGGeometryElement::get_point_at_length(float distance)
{
// When getPointAtLength(distance) is called, the following steps are run:
- auto path = computed_path();
-
// 1. If current element is a non-rendered element, and the UA is not able to compute the total length of the path,
// then throw an InvalidStateError.
// NB: Like other engines, throw for an empty path whether or not the element is rendered.
- auto point_along_path = path.point_at_length(distance);
+ Optional<Gfx::FloatPoint> point_along_path;
+ with_computed_values([&](CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values) {
+ measure_geometry(*this, viewport_size, computed_values, [&](auto const& shape) {
+ Layout::RustFFI::FfiFloatPoint point;
+ if (Layout::RustFFI::svg_geometry_element_point_at_length(&shape, distance, &point))
+ point_along_path = Gfx::FloatPoint { point.x, point.y };
+ });
+ });
if (!point_along_path.has_value())
return WebIDL::InvalidStateError::create(HTML::relevant_realm(*this), "The element's path is empty"_utf16);
// 2. Let length be the user agent's computed value for the total length of the path, in user units.
// 3. Clamp distance to [0, length].
// 4. Let (x, y) be the point on the path at distance distance.
- // NB: Gfx::Path::point_at_length() clamps the distance to the ends of the path.
+ // NB: svg_geometry_element_point_at_length() clamps the distance to the ends of the path.
// 5. Return a newly created, detached DOMPoint object representing the point (x, y).
- return Geometry::DOMPoint::create(point_along_path->point.x(), point_along_path->point.y(), 0, 1);
+ return Geometry::DOMPoint::create(point_along_path->x(), point_along_path->y(), 0, 1);
}
GC::Ref<SVGAnimatedNumber> SVGGeometryElement::path_length()
diff --git a/Libraries/LibWeb/SVG/SVGGeometryElement.h b/Libraries/LibWeb/SVG/SVGGeometryElement.h
index 48baae3b25a..89e5057a68b 100644
--- a/Libraries/LibWeb/SVG/SVGGeometryElement.h
+++ b/Libraries/LibWeb/SVG/SVGGeometryElement.h
@@ -7,6 +7,7 @@
#pragma once
#include <LibWeb/Geometry/DOMPoint.h>
+#include <LibWeb/SVG/Path.h>
#include <LibWeb/SVG/SVGGraphicsElement.h>
namespace Web::SVG {
@@ -20,7 +21,8 @@ public:
virtual CSS::ElementBoxKind box_kind() const override;
- Gfx::Path computed_path();
+ // https://svgwg.org/svg2-draft/paths.html#TermEquivalentPath
+ Vector<PathVertex> equivalent_path_vertices();
WebIDL::ExceptionOr<bool> is_point_in_fill(Bindings::DOMPointInit const&);
WebIDL::ExceptionOr<bool> is_point_in_stroke(Bindings::DOMPointInit const&);