Skip to content

Truly independent web browser

LibGfx: Add a path geometry to libgfx_rust

Aliaksandr Kalenikcb24790f22dd
diff --git a/Libraries/LibGfx/Rust/cbindgen.toml b/Libraries/LibGfx/Rust/cbindgen.toml
index bd4b907cd77..2e530d803ea 100644
--- a/Libraries/LibGfx/Rust/cbindgen.toml
+++ b/Libraries/LibGfx/Rust/cbindgen.toml
@@ -16,7 +16,7 @@ namespaces = ["Gfx", "FFI"]
# The byte layout the filter codec writes is defined by these enums, and the C++ reader that
# builds Skia filters from it decodes them from the same definitions.
[export]
-include = ["FilterOperationType", "ChannelSelector", "TurbulenceType"]
+include = ["FilterOperationType", "ChannelSelector", "TurbulenceType", "PathVerb"]
[parse]
parse_deps = false
diff --git a/Libraries/LibGfx/Rust/src/path.rs b/Libraries/LibGfx/Rust/src/path.rs
index ddf4f10653f..179bad9c386 100644
--- a/Libraries/LibGfx/Rust/src/path.rs
+++ b/Libraries/LibGfx/Rust/src/path.rs
@@ -11,6 +11,16 @@ use std::ptr::NonNull;
use crate::geometry::{FloatPoint, FloatSize};
+mod arcs;
+mod curves;
+mod encoding;
+pub mod ffi;
+mod geometry;
+mod hit_test;
+mod measure;
+mod stroke;
+mod svg_text;
+
unsafe extern "C" {
fn ladybird_gfx_process_next_path_identity() -> u64;
fn ladybird_gfx_path_destroy(path: *mut c_void);
diff --git a/Libraries/LibGfx/Rust/src/path/arcs.rs b/Libraries/LibGfx/Rust/src/path/arcs.rs
new file mode 100644
index 00000000000..74093367f42
--- /dev/null
+++ b/Libraries/LibGfx/Rust/src/path/arcs.rs
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Elliptical arcs as conics.
+//!
+//! https://www.w3.org/TR/SVG2/implnote.html#ArcConversionEndpointToCenter
+//!
+//! The arc goes from the endpoint parameterization of the SVG path command to a center, radii and
+//! a range of angles on the ellipse. A conic is exactly an arc of an ellipse: on the unit circle, the
+//! arc from angle a to angle a + d has its ends as the end points, the point where the tangents at
+//! the ends meet, (cos(a + d / 2), sin(a + d / 2)) / cos(d / 2), as the control point, and cos(d / 2)
+//! as the weight. Mapping the three points onto the ellipse keeps the weight.
+
+use super::geometry::PathGeometry;
+use crate::geometry::FloatPoint;
+use std::f64::consts::PI;
+
+/// The largest angle of the ellipse that one conic covers.
+const LARGEST_ANGLE_OF_ONE_CONIC: f64 = 2.0 * PI / 3.0;
+
+pub(super) fn append_elliptical_arc(
+ geometry: &mut PathGeometry,
+ end: FloatPoint,
+ radii: (f32, f32),
+ x_axis_rotation: f32,
+ large_arc: bool,
+ sweep: bool,
+) {
+ if ![end.x, end.y, radii.0, radii.1, x_axis_rotation]
+ .iter()
+ .all(|value| value.is_finite())
+ {
+ return;
+ }
+
+ let start = geometry.last_point();
+ let (mut radius_x, mut radius_y) = (f64::from(radii.0.abs()), f64::from(radii.1.abs()));
+ if start == end || radius_x == 0.0 || radius_y == 0.0 {
+ geometry.contour_line_to(end);
+ return;
+ }
+
+ let (sin_rotation, cos_rotation) = f64::from(x_axis_rotation).sin_cos();
+ let (start_x, start_y) = (f64::from(start.x), f64::from(start.y));
+ let (end_x, end_y) = (f64::from(end.x), f64::from(end.y));
+
+ // The start point in a frame centered between the end points, with the axes of the ellipse.
+ let half_difference_x = (start_x - end_x) / 2.0;
+ let half_difference_y = (start_y - end_y) / 2.0;
+ let start_in_frame_x = cos_rotation * half_difference_x + sin_rotation * half_difference_y;
+ let start_in_frame_y = -sin_rotation * half_difference_x + cos_rotation * half_difference_y;
+
+ // Radii too small for the ellipse to reach both points grow until it just does.
+ let radii_scale = (start_in_frame_x * start_in_frame_x) / (radius_x * radius_x)
+ + (start_in_frame_y * start_in_frame_y) / (radius_y * radius_y);
+ if radii_scale > 1.0 {
+ let scale = radii_scale.sqrt();
+ radius_x *= scale;
+ radius_y *= scale;
+ }
+
+ let rx_squared = radius_x * radius_x;
+ let ry_squared = radius_y * radius_y;
+ let x_squared = start_in_frame_x * start_in_frame_x;
+ let y_squared = start_in_frame_y * start_in_frame_y;
+ let numerator = rx_squared * ry_squared - rx_squared * y_squared - ry_squared * x_squared;
+ let denominator = rx_squared * y_squared + ry_squared * x_squared;
+ let mut center_factor = (numerator / denominator).max(0.0).sqrt();
+ if large_arc == sweep {
+ center_factor = -center_factor;
+ }
+ let center_in_frame_x = center_factor * radius_x * start_in_frame_y / radius_y;
+ let center_in_frame_y = -center_factor * radius_y * start_in_frame_x / radius_x;
+ let center_x = cos_rotation * center_in_frame_x - sin_rotation * center_in_frame_y + (start_x + end_x) / 2.0;
+ let center_y = sin_rotation * center_in_frame_x + cos_rotation * center_in_frame_y + (start_y + end_y) / 2.0;
+
+ // The angles of both end points on the unit circle that the ellipse is a mapping of.
+ let start_on_circle = (
+ (start_in_frame_x - center_in_frame_x) / radius_x,
+ (start_in_frame_y - center_in_frame_y) / radius_y,
+ );
+ let end_on_circle = (
+ (-start_in_frame_x - center_in_frame_x) / radius_x,
+ (-start_in_frame_y - center_in_frame_y) / radius_y,
+ );
+ let start_angle = start_on_circle.1.atan2(start_on_circle.0);
+ let mut sweep_angle = (start_on_circle.0 * end_on_circle.1 - start_on_circle.1 * end_on_circle.0)
+ .atan2(start_on_circle.0 * end_on_circle.0 + start_on_circle.1 * end_on_circle.1);
+ if !sweep && sweep_angle > 0.0 {
+ sweep_angle -= 2.0 * PI;
+ } else if sweep && sweep_angle < 0.0 {
+ sweep_angle += 2.0 * PI;
+ }
+ if !(start_angle.is_finite() && sweep_angle.is_finite() && center_x.is_finite() && center_y.is_finite()) {
+ geometry.contour_line_to(end);
+ return;
+ }
+
+ let to_ellipse = |unit_x: f64, unit_y: f64| {
+ let x = radius_x * snap_to_axis(unit_x);
+ let y = radius_y * snap_to_axis(unit_y);
+ FloatPoint {
+ x: (center_x + cos_rotation * x - sin_rotation * y) as f32,
+ y: (center_y + sin_rotation * x + cos_rotation * y) as f32,
+ }
+ };
+
+ let conic_count = ((sweep_angle.abs() / LARGEST_ANGLE_OF_ONE_CONIC) - 1e-9)
+ .ceil()
+ .max(1.0) as usize;
+ let angle_per_conic = sweep_angle / conic_count as f64;
+ let half_angle_cosine = (angle_per_conic / 2.0).cos();
+ let weight = half_angle_cosine as f32;
+ for index in 0..conic_count {
+ let from_angle = start_angle + angle_per_conic * index as f64;
+ let middle_angle = from_angle + angle_per_conic / 2.0;
+ let to_angle = from_angle + angle_per_conic;
+ let control = to_ellipse(
+ middle_angle.cos() / half_angle_cosine,
+ middle_angle.sin() / half_angle_cosine,
+ );
+ let conic_end = if index + 1 == conic_count {
+ end
+ } else {
+ to_ellipse(to_angle.cos(), to_angle.sin())
+ };
+ geometry.contour_conic_to(control, conic_end, weight);
+ }
+}
+
+/// A coordinate on the unit circle that is 0, 1 or -1 but for rounding, as at the ends of quarter
+/// circles, is made exact, so that arcs along the axes have exact points.
+fn snap_to_axis(value: f64) -> f64 {
+ const ROUNDING_TOLERANCE: f64 = 1e-12;
+ for exact in [0.0, 1.0, -1.0] {
+ if (value - exact).abs() < ROUNDING_TOLERANCE {
+ return exact;
+ }
+ }
+ value
+}
diff --git a/Libraries/LibGfx/Rust/src/path/curves.rs b/Libraries/LibGfx/Rust/src/path/curves.rs
new file mode 100644
index 00000000000..98bfb144444
--- /dev/null
+++ b/Libraries/LibGfx/Rust/src/path/curves.rs
@@ -0,0 +1,225 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Points, tangents and subdivisions of the segments of a path, computed in double precision.
+
+use super::geometry::Segment;
+use crate::geometry::FloatPoint;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Point {
+ pub x: f64,
+ pub y: f64,
+}
+
+impl Point {
+ pub fn new(x: f64, y: f64) -> Self {
+ Self { x, y }
+ }
+
+ pub fn from_float(point: FloatPoint) -> Self {
+ Self::new(f64::from(point.x), f64::from(point.y))
+ }
+
+ pub fn to_float(self) -> FloatPoint {
+ FloatPoint {
+ x: self.x as f32,
+ y: self.y as f32,
+ }
+ }
+
+ pub fn plus(self, other: Self) -> Self {
+ Self::new(self.x + other.x, self.y + other.y)
+ }
+
+ pub fn minus(self, other: Self) -> Self {
+ Self::new(self.x - other.x, self.y - other.y)
+ }
+
+ pub fn scaled(self, factor: f64) -> Self {
+ Self::new(self.x * factor, self.y * factor)
+ }
+
+ pub fn length(self) -> f64 {
+ self.x.hypot(self.y)
+ }
+
+ pub fn distance_to(self, other: Self) -> f64 {
+ self.minus(other).length()
+ }
+
+ pub fn lerp(self, other: Self, t: f64) -> Self {
+ Self::new(self.x + (other.x - self.x) * t, self.y + (other.y - self.y) * t)
+ }
+}
+
+/// A segment with its points in double precision. A line is a curve of degree one.
+#[derive(Clone, Copy, Debug)]
+pub enum Curve {
+ Line([Point; 2]),
+ Quad([Point; 3]),
+ Conic([Point; 3], f64),
+ Cubic([Point; 4]),
+}
+
+impl Curve {
+ pub fn from_segment(segment: &Segment) -> Self {
+ let convert = Point::from_float;
+ match segment {
+ Segment::Line(points) => Self::Line(points.map(convert)),
+ Segment::Quad(points) => Self::Quad(points.map(convert)),
+ Segment::Conic(points, weight) => Self::Conic(points.map(convert), f64::from(*weight)),
+ Segment::Cubic(points) => Self::Cubic(points.map(convert)),
+ }
+ }
+
+ pub fn control_points(&self) -> &[Point] {
+ match self {
+ Self::Line(points) => points,
+ Self::Quad(points) | Self::Conic(points, _) => points,
+ Self::Cubic(points) => points,
+ }
+ }
+
+ pub fn start(&self) -> Point {
+ self.control_points()[0]
+ }
+
+ pub fn end(&self) -> Point {
+ *self.control_points().last().expect("a curve has points")
+ }
+
+ pub fn point_at(&self, t: f64) -> Point {
+ let u = 1.0 - t;
+ match *self {
+ Self::Line([p0, p1]) => p0.lerp(p1, t),
+ Self::Quad([p0, p1, p2]) => {
+ let (a, b, c) = (u * u, 2.0 * u * t, t * t);
+ Point::new(a * p0.x + b * p1.x + c * p2.x, a * p0.y + b * p1.y + c * p2.y)
+ }
+ Self::Conic([p0, p1, p2], weight) => {
+ let (a, b, c) = (u * u, 2.0 * weight * u * t, t * t);
+ let denominator = a + b + c;
+ Point::new(
+ (a * p0.x + b * p1.x + c * p2.x) / denominator,
+ (a * p0.y + b * p1.y + c * p2.y) / denominator,
+ )
+ }
+ Self::Cubic([p0, p1, p2, p3]) => {
+ let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
+ Point::new(
+ a * p0.x + b * p1.x + c * p2.x + d * p3.x,
+ a * p0.y + b * p1.y + c * p2.y + d * p3.y,
+ )
+ }
+ }
+ }
+
+ /// The derivative of the curve with respect to its parameter.
+ pub fn derivative_at(&self, t: f64) -> Point {
+ let u = 1.0 - t;
+ match *self {
+ Self::Line([p0, p1]) => p1.minus(p0),
+ Self::Quad([p0, p1, p2]) => p1.minus(p0).scaled(2.0 * u).plus(p2.minus(p1).scaled(2.0 * t)),
+ Self::Conic([p0, p1, p2], weight) => {
+ // The quotient rule on numerator / denominator.
+ let (a, b, c) = (u * u, 2.0 * weight * u * t, t * t);
+ let (da, db, dc) = (-2.0 * u, 2.0 * weight * (u - t), 2.0 * t);
+ let denominator = a + b + c;
+ let denominator_derivative = da + db + dc;
+ let numerator = Point::new(a * p0.x + b * p1.x + c * p2.x, a * p0.y + b * p1.y + c * p2.y);
+ let numerator_derivative =
+ Point::new(da * p0.x + db * p1.x + dc * p2.x, da * p0.y + db * p1.y + dc * p2.y);
+ numerator_derivative
+ .scaled(denominator)
+ .minus(numerator.scaled(denominator_derivative))
+ .scaled(1.0 / (denominator * denominator))
+ }
+ Self::Cubic([p0, p1, p2, p3]) => p1
+ .minus(p0)
+ .scaled(3.0 * u * u)
+ .plus(p2.minus(p1).scaled(6.0 * u * t))
+ .plus(p3.minus(p2).scaled(3.0 * t * t)),
+ }
+ }
+
+ /// The direction in which the curve goes at the parameter. Where the derivative vanishes, as at
+ /// an end whose control point coincides with it, the direction comes from the next points.
+ pub fn direction_at(&self, t: f64) -> Option<Point> {
+ let derivative = self.derivative_at(t);
+ if derivative.length() > 0.0 {
+ return Some(derivative);
+ }
+ let points = self.control_points();
+ if t <= 0.5 {
+ let start = points[0];
+ points[1..]
+ .iter()
+ .map(|point| point.minus(start))
+ .find(|vector| vector.length() > 0.0)
+ } else {
+ let end = points[points.len() - 1];
+ points[..points.len() - 1]
+ .iter()
+ .rev()
+ .map(|point| end.minus(*point))
+ .find(|vector| vector.length() > 0.0)
+ }
+ }
+
+ /// The parameters strictly between 0 and 1 where the curve turns in the given coordinate, in increasing
+ /// order.
+ pub fn turning_parameters(&self, coordinate: impl Fn(Point) -> f64) -> Vec<f64> {
+ let mut roots = match *self {
+ Self::Line(_) => Vec::new(),
+ Self::Quad([p0, p1, p2]) => {
+ let (v0, v1, v2) = (coordinate(p0), coordinate(p1), coordinate(p2));
+ // The derivative is linear: (v1 - v0) + t (v0 - 2 v1 + v2), up to a factor of 2.
+ solve_quadratic(0.0, v0 - 2.0 * v1 + v2, v1 - v0)
+ }
+ Self::Conic([p0, p1, p2], weight) => {
+ // The derivative has the sign of N'(t) D(t) - N(t) D'(t), whose cubic terms cancel. With the
+ // coordinate measured from p0, it is (w (v1 - v0)) + t (v2 - v0 - 2 w (v1 - v0))
+ // + t^2 (w - 1) (v2 - v0) times 2.
+ let (b, c) = (coordinate(p1) - coordinate(p0), coordinate(p2) - coordinate(p0));
+ solve_quadratic((weight - 1.0) * c, c - 2.0 * weight * b, weight * b)
+ }
+ Self::Cubic([p0, p1, p2, p3]) => {
+ let (v0, v1, v2, v3) = (coordinate(p0), coordinate(p1), coordinate(p2), coordinate(p3));
+ // The derivative over 3 is a t^2 + b t + c.
+ let a = v3 - 3.0 * v2 + 3.0 * v1 - v0;
+ let b = 2.0 * (v2 - 2.0 * v1 + v0);
+ let c = v1 - v0;
+ solve_quadratic(a, b, c)
+ }
+ };
+ roots.retain(|t| *t > 0.0 && *t < 1.0);
+ roots.sort_by(f64::total_cmp);
+ roots.dedup();
+ roots
+ }
+}
+
+/// The real roots of a t^2 + b t + c.
+fn solve_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
+ if a == 0.0 {
+ if b == 0.0 {
+ return Vec::new();
+ }
+ return vec![-c / b];
+ }
+ let discriminant = b * b - 4.0 * a * c;
+ if discriminant < 0.0 {
+ return Vec::new();
+ }
+ // The form that avoids subtracting nearly equal values.
+ let root = discriminant.sqrt();
+ let q = -0.5 * (b + if b < 0.0 { -root } else { root });
+ if q == 0.0 {
+ return vec![0.0];
+ }
+ vec![q / a, c / q]
+}
diff --git a/Libraries/LibGfx/Rust/src/path/encoding.rs b/Libraries/LibGfx/Rust/src/path/encoding.rs
new file mode 100644
index 00000000000..5b954ab34fd
--- /dev/null
+++ b/Libraries/LibGfx/Rust/src/path/encoding.rs
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The byte form in which paths cross process boundaries and live in display lists.
+//!
+//! All values are little-endian: a u8 version, a u8 fill rule, two zero bytes, then the u32 counts of
+//! verbs, points and conic weights, then the verbs as u8, zeros up to a multiple of four bytes, the
+//! points as pairs of f32, and the conic weights as f32. A path without geometry is written as an
+//! empty path.
+
+use super::geometry::{PathGeometry, PathVerb};
+use crate::geometry::FloatPoint;
+use crate::paint_enums::WindingRule;
+
+const VERSION: u8 = 1;
+const HEADER_SIZE: usize = 16;
+
+fn padded_to_four(size: usize) -> usize {
+ size.div_ceil(4) * 4
+}
+
+pub fn encode(geometry: &PathGeometry) -> Vec<u8> {
+ let empty = PathGeometry::new();
+ let geometry = if geometry.has_geometry() { geometry } else { &empty };
+ let verbs = geometry.verbs();
+ let points = geometry.points();
+ let conic_weights = geometry.conic_weights();
+
+ let mut bytes =
+ Vec::with_capacity(HEADER_SIZE + padded_to_four(verbs.len()) + points.len() * 8 + conic_weights.len() * 4);
+ bytes.extend_from_slice(&[VERSION, geometry.fill_rule() as u8, 0, 0]);
+ for count in [verbs.len(), points.len(), conic_weights.len()] {
+ bytes.extend_from_slice(&(count as u32).to_le_bytes());
+ }
+ bytes.extend(verbs.iter().map(|verb| *verb as u8));
+ bytes.resize(HEADER_SIZE + padded_to_four(verbs.len()), 0);
+ for point in points {
+ bytes.extend_from_slice(&point.x.to_le_bytes());
+ bytes.extend_from_slice(&point.y.to_le_bytes());
+ }
+ for weight in conic_weights {
+ bytes.extend_from_slice(&weight.to_le_bytes());
+ }
+ bytes
+}
+
+/// The path that the bytes describe, or None if they do not describe one: if the sizes do not match
+/// the counts, if a contour does not start with a move, if the verbs need other numbers of points or
+/// weights than there are, or if a point or weight is not finite or a weight is not positive.
+pub fn decode(bytes: &[u8]) -> Option<PathGeometry> {
+ let header = bytes.get(..HEADER_SIZE)?;
+ if header[0] != VERSION || header[2] != 0 || header[3] != 0 {
+ return None;
+ }
+ let fill_rule = match header[1] {
+ 0 => WindingRule::Nonzero,
+ 1 => WindingRule::EvenOdd,
+ _ => return None,
+ };
+ let read_count =
+ |offset: usize| u32::from_le_bytes(header[offset..offset + 4].try_into().expect("four bytes")) as usize;
+ let (verb_count, point_count, conic_weight_count) = (read_count(4), read_count(8), read_count(12));
+
+ let verbs_end = HEADER_SIZE.checked_add(padded_to_four(verb_count))?;
+ let points_end = verbs_end.checked_add(point_count.checked_mul(8)?)?;
+ let weights_end = points_end.checked_add(conic_weight_count.checked_mul(4)?)?;
+ if bytes.len() != weights_end {
+ return None;
+ }
+
+ let mut verbs = Vec::with_capacity(verb_count);
+ let mut needed_points = 0usize;
+ let mut needed_conic_weights = 0usize;
+ for &byte in &bytes[HEADER_SIZE..HEADER_SIZE + verb_count] {
+ let verb = PathVerb::from_u8(byte)?;
+ let starts_contour = matches!(verbs.last(), None | Some(PathVerb::Close));
+ if starts_contour && verb != PathVerb::Move {
+ return None;
+ }
+ needed_points += verb.stored_point_count();
+ if verb == PathVerb::Conic {
+ needed_conic_weights += 1;
+ }
+ verbs.push(verb);
+ }
+ if bytes[HEADER_SIZE + verb_count..verbs_end].iter().any(|byte| *byte != 0) {
+ return None;
+ }
+ if needed_points != point_count || needed_conic_weights != conic_weight_count {
+ return None;
+ }
+
+ let read_f32 = |offset: usize| f32::from_le_bytes(bytes[offset..offset + 4].try_into().expect("four bytes"));
+ let points: Vec<FloatPoint> = (0..point_count)
+ .map(|index| {
+ let offset = verbs_end + index * 8;
+ FloatPoint {
+ x: read_f32(offset),
+ y: read_f32(offset + 4),
+ }
+ })
+ .collect();
+ let conic_weights: Vec<f32> = (0..conic_weight_count)
+ .map(|index| read_f32(points_end + index * 4))
+ .collect();
+ if !points.iter().all(|point| point.x.is_finite() && point.y.is_finite())
+ || !conic_weights.iter().all(|weight| weight.is_finite() && *weight > 0.0)
+ {
+ return None;
+ }
+ Some(PathGeometry::from_checked_contours(
+ verbs,
+ points,
+ conic_weights,
+ fill_rule,
+ ))
+}
diff --git a/Libraries/LibGfx/Rust/src/path/ffi.rs b/Libraries/LibGfx/Rust/src/path/ffi.rs
new file mode 100644
index 00000000000..c269eb15e6a
--- /dev/null
+++ b/Libraries/LibGfx/Rust/src/path/ffi.rs
@@ -0,0 +1,577 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The functions through which `Gfx::Path` in C++ owns, builds and queries a path.
+//!
+//! Only LibGfx's copy of this crate makes and frees the paths of `Gfx::Path`. Rust code in other
+//! libraries reaches them through the `ladybird_gfx_path_*` functions of LibGfx.
+
+use super::encoding;
+use super::geometry::PathGeometry;
+use super::hit_test;
+use super::measure::{self, ContourMeasure, PathVertex};
+use super::stroke::{self, StrokeStyle};
+use super::svg_text;
+use crate::geometry::FloatPoint;
+use crate::matrix::AffineTransform;
+use crate::paint_enums::{CapStyle, JoinStyle, WindingRule};
+use std::ffi::c_void;
+
+/// The contours of a path, valid until the path changes or is destroyed. A path without geometry has
+/// none.
+#[repr(C)]
+pub struct PathGeometryData {
+ pub verbs: *const u8,
+ pub verb_count: usize,
+ pub points: *const FloatPoint,
+ pub point_count: usize,
+ pub conic_weights: *const f32,
+ pub conic_weight_count: usize,
+ pub fill_rule: u8,
+}
+
+fn point(x: f32, y: f32) -> FloatPoint {
+ FloatPoint { x, y }
+}
+
+/// # Safety
+/// `transform` must point to the six values a, b, c, d, e and f of an affine transform.
+unsafe fn read_transform(transform: *const f32) -> AffineTransform {
+ AffineTransform {
+ // SAFETY: The caller passes six floats.
+ values: unsafe { std::ptr::read(transform.cast::<[f32; 6]>()) },
+ }
+}
+
+/// # Safety
+/// `out_point_and_tangent` must point to four floats.
+unsafe fn write_point_and_tangent(out_point_and_tangent: *mut f32, (position, tangent): (FloatPoint, FloatPoint)) {
+ // SAFETY: The caller passes room for four floats.
+ unsafe {
+ std::ptr::write(
+ out_point_and_tangent.cast::<[f32; 4]>(),
+ [position.x, position.y, tangent.x, tangent.y],
+ );
+ }
+}
+
+/// Calls the function with the path and the other path. A path appended to itself is copied first.
+///
+/// # Safety
+/// `path` and `other` must be live paths from this module; nothing else may use `path` for the call.
+unsafe fn with_other_path(
+ path: *mut PathGeometry,
+ other: *const PathGeometry,
+ function: impl FnOnce(&mut PathGeometry, &PathGeometry),
+) {
+ if std::ptr::eq(path, other) {
+ // SAFETY: Forwarded from the caller.
+ let copy = unsafe { &*other }.clone();
+ // SAFETY: Forwarded from the caller.
+ function(unsafe { &mut *path }, &copy);
+ } else {
+ // SAFETY: Forwarded from the caller; the paths are distinct.
+ function(unsafe { &mut *path }, unsafe { &*other });
+ }
+}
+
+fn into_raw(geometry: PathGeometry) -> *mut PathGeometry {
+ Box::into_raw(Box::new(geometry))
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn path_geometry_create() -> *mut PathGeometry {
+ into_raw(PathGeometry::new())
+}
+
+/// # Safety
+/// `path` must be a live path from this module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_clone(path: *const PathGeometry) -> *mut PathGeometry {
+ // SAFETY: Forwarded from the caller.
+ into_raw(unsafe { &*path }.clone())
+}
+
+/// # Safety
+/// `path` must be a path from this module that nothing uses afterwards, or null.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_destroy(path: *mut PathGeometry) {
+ if !path.is_null() {
+ // SAFETY: The caller hands over the path, which into_raw() made from a Box.
+ drop(unsafe { Box::from_raw(path) });
+ }
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_clear(path: *mut PathGeometry) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.clear();
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_move_to(path: *mut PathGeometry, x: f32, y: f32) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.move_to(point(x, y));
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_line_to(path: *mut PathGeometry, x: f32, y: f32) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.line_to(point(x, y));
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_quadratic_bezier_curve_to(
+ path: *mut PathGeometry,
+ control_x: f32,
+ control_y: f32,
+ x: f32,
+ y: f32,
+) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.quadratic_bezier_curve_to(point(control_x, control_y), point(x, y));
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_cubic_bezier_curve_to(
+ path: *mut PathGeometry,
+ control1_x: f32,
+ control1_y: f32,
+ control2_x: f32,
+ control2_y: f32,
+ x: f32,
+ y: f32,
+) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.cubic_bezier_curve_to(
+ point(control1_x, control1_y),
+ point(control2_x, control2_y),
+ point(x, y),
+ );
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_elliptical_arc_to(
+ path: *mut PathGeometry,
+ x: f32,
+ y: f32,
+ radius_x: f32,
+ radius_y: f32,
+ x_axis_rotation: f32,
+ large_arc: bool,
+ sweep: bool,
+) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.elliptical_arc_to(point(x, y), (radius_x, radius_y), x_axis_rotation, large_arc, sweep);
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_arc_to(
+ path: *mut PathGeometry,
+ x: f32,
+ y: f32,
+ radius: f32,
+ large_arc: bool,
+ sweep: bool,
+) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.arc_to(point(x, y), radius, large_arc, sweep);
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_close(path: *mut PathGeometry) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.close();
+}
+
+// Contour building for outlines, without the rules of Gfx::Path for a path that has no current point.
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_contour_move_to(path: *mut PathGeometry, x: f32, y: f32) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.contour_move_to(point(x, y));
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_contour_line_to(path: *mut PathGeometry, x: f32, y: f32) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.contour_line_to(point(x, y));
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_contour_quad_to(
+ path: *mut PathGeometry,
+ control_x: f32,
+ control_y: f32,
+ x: f32,
+ y: f32,
+) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.contour_quad_to(point(control_x, control_y), point(x, y));
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_contour_cubic_to(
+ path: *mut PathGeometry,
+ control1_x: f32,
+ control1_y: f32,
+ control2_x: f32,
+ control2_y: f32,
+ x: f32,
+ y: f32,
+) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.contour_cubic_to(
+ point(control1_x, control1_y),
+ point(control2_x, control2_y),
+ point(x, y),
+ );
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_contour_close(path: *mut PathGeometry) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.contour_close();
+}
+
+/// # Safety
+/// `path` and `other` must be live paths from this module; nothing else may use `path` for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_append_path(path: *mut PathGeometry, other: *const PathGeometry) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { with_other_path(path, other, |path, other| path.append_path(other)) };
+}
+
+/// Adds the contours of the other path, mapped by the affine transform, without changing what the
+/// operations of Gfx::Path remember.
+///
+/// # Safety
+/// `path` and `other` must be live paths from this module; nothing else may use `path` for the call.
+/// `transform` must point to the six values a, b, c, d, e and f of an affine transform.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_append_transformed_contours(
+ path: *mut PathGeometry,
+ other: *const PathGeometry,
+ transform: *const f32,
+) {
+ // SAFETY: Forwarded from the caller.
+ let transform = unsafe { read_transform(transform) };
+ // SAFETY: Forwarded from the caller.
+ unsafe {
+ with_other_path(path, other, |path, other| {
+ path.append_mapped(other, |point| transform.map_point(point))
+ })
+ };
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_update_state_from_contours(path: *mut PathGeometry) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.update_state_from_contours();
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_set_fill_rule(path: *mut PathGeometry, winding_rule: i32) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.set_fill_rule(WindingRule::from_raw(winding_rule));
+}
+
+/// # Safety
+/// `path` must be a live path from this module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_is_empty(path: *const PathGeometry) -> bool {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &*path }.is_empty()
+}
+
+/// # Safety
+/// `path` must be a live path from this module, and `out_x_y` must point to two floats.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_last_point(path: *const PathGeometry, out_x_y: *mut f32) {
+ // SAFETY: Forwarded from the caller.
+ let last = unsafe { &*path }.last_point();
+ // SAFETY: The caller passes room for two floats.
+ unsafe { std::ptr::write(out_x_y.cast::<[f32; 2]>(), [last.x, last.y]) };
+}
+
+/// # Safety
+/// `path` must be a live path from this module, and `out_x_y_width_height` must point to four floats.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_bounding_box(path: *const PathGeometry, out_x_y_width_height: *mut f32) {
+ // SAFETY: Forwarded from the caller.
+ let bounds = unsafe { &*path }.bounding_box();
+ // SAFETY: The caller passes room for four floats.
+ unsafe { std::ptr::write(out_x_y_width_height.cast::<[f32; 4]>(), bounds) };
+}
+
+/// # Safety
+/// `path` must be a live path from this module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_length(path: *const PathGeometry) -> f32 {
+ // SAFETY: Forwarded from the caller.
+ measure::length(unsafe { &*path })
+}
+
+/// Writes the point and the unit tangent at the distance along the path, and returns whether the path
+/// has a point.
+///
+/// # Safety
+/// `path` must be a live path from this module, and `out_point_and_tangent` must point to four floats.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_point_at_length(
+ path: *const PathGeometry,
+ distance: f32,
+ out_point_and_tangent: *mut f32,
+) -> bool {
+ // SAFETY: Forwarded from the caller.
+ let Some(point_and_tangent) = measure::point_at_length(unsafe { &*path }, distance) else {
+ return false;
+ };
+ // SAFETY: Forwarded from the caller.
+ unsafe { write_point_and_tangent(out_point_and_tangent, point_and_tangent) };
+ true
+}
+
+/// Calls the callback once with the vertices of the polylines that follow the path.
+///
+/// # Safety
+/// `path` must be a live path from this module, and the callback must accept `context`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_vertices(
+ path: *const PathGeometry,
+ callback: unsafe extern "C" fn(*mut c_void, *const PathVertex, usize),
+ context: *mut c_void,
+) {
+ // SAFETY: Forwarded from the caller.
+ let vertices = measure::vertices(unsafe { &*path });
+ // SAFETY: The vertices live for the synchronous call.
+ unsafe { callback(context, vertices.as_ptr(), vertices.len()) };
+}
+
+/// # Safety
+/// `path` must be a live path from this module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_contains(path: *const PathGeometry, x: f32, y: f32, winding_rule: i32) -> bool {
+ // SAFETY: Forwarded from the caller.
+ hit_test::contains(unsafe { &*path }, x, y, WindingRule::from_raw(winding_rule))
+}
+
+/// The outline of the area that stroking the path covers, as a path to fill with the nonzero winding rule.
+/// The cap and join styles have the values of `Gfx::Path::CapStyle` and `Gfx::Path::JoinStyle`.
+///
+/// # Safety
+/// `path` must be a live path from this module, and `dash_array` must point to `dash_count` floats, or be
+/// null with a count of zero.
+#[allow(clippy::too_many_arguments)]
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_stroke_to_fill(
+ path: *const PathGeometry,
+ thickness: f32,
+ cap_style: i32,
+ join_style: i32,
+ miter_limit: f32,
+ dash_array: *const f32,
+ dash_count: usize,
+ dash_offset: f32,
+) -> *mut PathGeometry {
+ let style = StrokeStyle {
+ thickness,
+ cap_style: match cap_style {
+ 1 => CapStyle::Round,
+ 2 => CapStyle::Square,
+ _ => CapStyle::Butt,
+ },
+ join_style: match join_style {
+ 1 => JoinStyle::Round,
+ 2 => JoinStyle::Bevel,
+ _ => JoinStyle::Miter,
+ },
+ miter_limit,
+ // SAFETY: Forwarded from the caller.
+ dash_array: unsafe { ak::slice_from_raw_parts(dash_array, dash_count) },
+ dash_offset,
+ };
+ // SAFETY: Forwarded from the caller.
+ into_raw(stroke::stroke_to_fill(unsafe { &*path }, &style))
+}
+
+/// # Safety
+/// `path` must be a live path from this module, and `transform` must point to the six values a, b, c, d,
+/// e and f of an affine transform.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_copy_transformed(
+ path: *const PathGeometry,
+ transform: *const f32,
+) -> *mut PathGeometry {
+ // SAFETY: Forwarded from the caller.
+ let transform = unsafe { read_transform(transform) };
+ // SAFETY: Forwarded from the caller.
+ into_raw(unsafe { &*path }.copy_transformed(transform))
+}
+
+/// # Safety
+/// `path` must be a live path from this module, which nothing else uses for the call, and `transform`
+/// must point to the six values a, b, c, d, e and f of an affine transform.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_transform(path: *mut PathGeometry, transform: *const f32) {
+ // SAFETY: Forwarded from the caller.
+ let transform = unsafe { read_transform(transform) };
+ // SAFETY: Forwarded from the caller.
+ unsafe { &mut *path }.transform(transform);
+}
+
+/// Calls the callback once with the byte form of the path.
+///
+/// # Safety
+/// `path` must be a live path from this module, and the callback must accept `context`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_encode(
+ path: *const PathGeometry,
+ callback: unsafe extern "C" fn(*mut c_void, *const u8, usize),
+ context: *mut c_void,
+) {
+ // SAFETY: Forwarded from the caller.
+ let bytes = encoding::encode(unsafe { &*path });
+ // SAFETY: The bytes live for the synchronous call.
+ unsafe { callback(context, bytes.as_ptr(), bytes.len()) };
+}
+
+/// The path that the bytes describe. Bytes that describe no path give an empty path.
+///
+/// # Safety
+/// `bytes` must point to `count` bytes, or be null with a count of zero.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_decode(bytes: *const u8, count: usize) -> *mut PathGeometry {
+ // SAFETY: Forwarded from the caller.
+ let bytes = unsafe { ak::slice_from_raw_parts(bytes, count) };
+ into_raw(encoding::decode(bytes).unwrap_or_default())
+}
+
+/// Calls the callback once with the SVG path data of the path, as UTF-8.
+///
+/// # Safety
+/// `path` must be a live path from this module, and the callback must accept `context`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_svg_string(
+ path: *const PathGeometry,
+ callback: unsafe extern "C" fn(*mut c_void, *const u8, usize),
+ context: *mut c_void,
+) {
+ // SAFETY: Forwarded from the caller.
+ let string = svg_text::to_svg_string(unsafe { &*path });
+ // SAFETY: The string lives for the synchronous call.
+ unsafe { callback(context, string.as_ptr(), string.len()) };
+}
+
+/// # Safety
+/// `a` and `b` must be live paths from this module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_equals(a: *const PathGeometry, b: *const PathGeometry) -> bool {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &*a }.has_same_contours(unsafe { &*b })
+}
+
+/// # Safety
+/// `path` must be a live path from this module, and `out_data` must point to room for the data.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_data(path: *const PathGeometry, out_data: *mut PathGeometryData) {
+ // SAFETY: Forwarded from the caller.
+ let geometry = unsafe { &*path };
+ let (verbs, points, conic_weights) = if geometry.has_geometry() {
+ (geometry.verbs(), geometry.points(), geometry.conic_weights())
+ } else {
+ (&[][..], &[][..], &[][..])
+ };
+ let data = PathGeometryData {
+ verbs: verbs.as_ptr().cast::<u8>(),
+ verb_count: verbs.len(),
+ points: points.as_ptr(),
+ point_count: points.len(),
+ conic_weights: conic_weights.as_ptr(),
+ conic_weight_count: conic_weights.len(),
+ fill_rule: geometry.fill_rule() as u8,
+ };
+ // SAFETY: The caller passes room for the data.
+ unsafe { std::ptr::write(out_data, data) };
+}
+
+/// The measure of the first contour of the path that has length, or null if none has.
+///
+/// # Safety
+/// `path` must be a live path from this module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn path_geometry_measure_first_contour(path: *const PathGeometry) -> *mut ContourMeasure {
+ // SAFETY: Forwarded from the caller.
+ ContourMeasure::contours_of(unsafe { &*path })
+ .next()
+ .map_or(std::ptr::null_mut(), |contour| Box::into_raw(Box::new(contour)))
+}
+
+/// # Safety
+/// `measure` must be a live measure from path_geometry_measure_first_contour().
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn contour_measure_length(measure: *const ContourMeasure) -> f32 {
+ // SAFETY: Forwarded from the caller.
+ unsafe { &*measure }.length()
+}
+
+/// Writes the point at the distance along the contour, clamped to its ends, and the unit tangent there.
+///
+/// # Safety
+/// `measure` must be a live measure from path_geometry_measure_first_contour(), and
+/// `out_point_and_tangent` must point to four floats.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn contour_measure_position_and_tangent(
+ measure: *const ContourMeasure,
+ distance: f32,
+ out_point_and_tangent: *mut f32,
+) {
+ // SAFETY: Forwarded from the caller.
+ let point_and_tangent = unsafe { &*measure }.position_and_tangent(distance);
+ // SAFETY: Forwarded from the caller.
+ unsafe { write_point_and_tangent(out_point_and_tangent, point_and_tangent) };
+}
+
+/// # Safety
+/// `measure` must be a measure from path_geometry_measure_first_contour() that nothing uses afterwards,
+/// or null.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn contour_measure_destroy(measure: *mut ContourMeasure) {
+ if !measure.is_null() {
+ // SAFETY: The caller hands over the measure, which was made from a Box.
+ drop(unsafe { Box::from_raw(measure) });
+ }
+}
diff --git a/Libraries/LibGfx/Rust/src/path/geometry.rs b/Libraries/LibGfx/Rust/src/path/geometry.rs
new file mode 100644
index 00000000000..e35e7d826ed
--- /dev/null
+++ b/Libraries/LibGfx/Rust/src/path/geometry.rs
@@ -0,0 +1,504 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The data of a `Gfx::Path`: its verbs, the points that they use and the weights of its conics,
+//! and the rules by which the operations of `Gfx::Path` add to them.
+
+use super::arcs;
+use crate::geometry::FloatPoint;
+use crate::matrix::AffineTransform;
+use crate::paint_enums::WindingRule;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum PathVerb {
+ Move = 0,
+ Line = 1,
+ Quad = 2,
+ Conic = 3,
+ Cubic = 4,
+ Close = 5,
+}
+
+impl PathVerb {
+ pub fn from_u8(value: u8) -> Option<Self> {
+ Some(match value {
+ 0 => Self::Move,
+ 1 => Self::Line,
+ 2 => Self::Quad,
+ 3 => Self::Conic,
+ 4 => Self::Cubic,
+ 5 => Self::Close,
+ _ => return None,
+ })
+ }
+
+ /// The number of points that the verb stores.
+ pub fn stored_point_count(self) -> usize {
+ match self {
+ Self::Move | Self::Line => 1,
+ Self::Quad | Self::Conic => 2,
+ Self::Cubic => 3,
+ Self::Close => 0,
+ }
+ }
+}
+
+/// A segment of a path, with the point where it starts as its first point.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Segment {
+ Line([FloatPoint; 2]),
+ Quad([FloatPoint; 3]),
+ Conic([FloatPoint; 3], f32),
+ Cubic([FloatPoint; 4]),
+}
+
+impl Segment {
+ pub fn points(&self) -> &[FloatPoint] {
+ match self {
+ Self::Line(points) => points,
+ Self::Quad(points) | Self::Conic(points, _) => points,
+ Self::Cubic(points) => points,
+ }
+ }
+
+ pub fn start(&self) -> FloatPoint {
+ self.points()[0]
+ }
+
+ pub fn end(&self) -> FloatPoint {
+ *self.points().last().expect("a segment has points")
+ }
+
+ /// Whether every point of the segment is the same, so that it goes nowhere.
+ pub fn is_degenerate(&self) -> bool {
+ let start = self.start();
+ self.points().iter().all(|point| *point == start)
+ }
+}
+
+/// What a walk over the verbs of a path meets: the start of a contour, a segment, or a close with
+/// the line back to the start of its contour.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum PathElement {
+ MoveTo(FloatPoint),
+ Segment(Segment),
+ Close([FloatPoint; 2]),
+}
+
+impl PathElement {
+ /// The segment that the element draws, if any. A close draws the line back to the start.
+ pub fn drawn_segment(&self) -> Option<Segment> {
+ match self {
+ Self::MoveTo(_) => None,
+ Self::Segment(segment) => Some(*segment),
+ Self::Close(points) => Some(Segment::Line(*points)),
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct PathGeometry {
+ verbs: Vec<PathVerb>,
+ points: Vec<FloatPoint>,
+ conic_weights: Vec<f32>,
+ fill_rule: WindingRule,
+ has_only_finite_points: bool,
+
+ // What the operations of Gfx::Path remember between calls: whether there is a point to draw from,
+ // and where the last subpath started.
+ has_current_point: bool,
+ last_move_to: FloatPoint,
+}
+
+fn is_finite_point(point: FloatPoint) -> bool {
+ point.x.is_finite() && point.y.is_finite()
+}
+
+impl Default for PathGeometry {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl PathGeometry {
+ pub fn new() -> Self {
+ Self {
+ verbs: Vec::new(),
+ points: Vec::new(),
+ conic_weights: Vec::new(),
+ fill_rule: WindingRule::Nonzero,
+ has_only_finite_points: true,
+ has_current_point: false,
+ last_move_to: FloatPoint::default(),
+ }
+ }
+
+ pub fn verbs(&self) -> &[PathVerb] {
+ &self.verbs
+ }
+
+ pub fn points(&self) -> &[FloatPoint] {
+ &self.points
+ }
+
+ pub fn conic_weights(&self) -> &[f32] {
+ &self.conic_weights
+ }
+
+ pub fn fill_rule(&self) -> WindingRule {
+ self.fill_rule
+ }
+
+ pub fn set_fill_rule(&mut self, fill_rule: WindingRule) {
+ self.fill_rule = fill_rule;
+ }
+
+ /// A path with a point that is not finite has no geometry: it draws nothing, has no length and
+ /// contains no point. It still remembers its operations, so that drawing can continue from it.
+ pub fn has_geometry(&self) -> bool {
+ self.has_only_finite_points && !self.verbs.is_empty()
+ }
+
+ /// Whether the path has no current point, which Gfx::Path::is_empty() calls empty.
+ pub fn is_empty(&self) -> bool {
+ !self.has_current_point
+ }
+
+ pub fn last_point(&self) -> FloatPoint {
+ self.points.last().copied().unwrap_or_default()
+ }
+
+ pub fn clear(&mut self) {
+ *self = Self::new();
+ }
+
+ /// The elements of the path. A move that ends the path starts nothing, and is left out.
+ pub fn elements(&self) -> PathElements<'_> {
+ PathElements {
+ geometry: self,
+ verb_index: 0,
+ point_index: 0,
+ conic_weight_index: 0,
+ current_point: FloatPoint::default(),
+ contour_start: FloatPoint::default(),
+ }
+ }
+
+ /// The bounds of the points of the path, as x, y, width and height. A move that ends the path,
+ /// and that so starts nothing, does not count, unless it is the only point.
+ pub fn bounding_box(&self) -> [f32; 4] {
+ if self.points.is_empty() || !self.has_only_finite_points {
+ return [0.0; 4];
+ }
+ let mut counted_points = self.points.as_slice();
+ if counted_points.len() > 1 && self.verbs.last() == Some(&PathVerb::Move) {
+ counted_points = &counted_points[..counted_points.len() - 1];
+ }
+ let first = counted_points[0];
+ let (mut left, mut top, mut right, mut bottom) = (first.x, first.y, first.x, first.y);
+ for point in &counted_points[1..] {
+ left = left.min(point.x);
+ top = top.min(point.y);
+ right = right.max(point.x);
+ bottom = bottom.max(point.y);
+ }
+ [left, top, right - left, bottom - top]
+ }
+
+ // Contour building, without the rules of Gfx::Path for a path that has no current point.
+
+ fn push_point(&mut self, point: FloatPoint) {
+ self.has_only_finite_points &= is_finite_point(point);
+ self.points.push(point);
+ }
+
+ fn pop_point(&mut self) {
+ if let Some(point) = self.points.pop()
+ && !is_finite_point(point)
+ {
+ self.recompute_finiteness();
+ }
+ }
+
+ /// Starts a contour. A move that follows a move replaces it.
+ pub fn contour_move_to(&mut self, point: FloatPoint) {
+ if self.verbs.last() == Some(&PathVerb::Move) {
+ self.pop_point();
+ self.push_point(point);
+ return;
+ }
+ self.verbs.push(PathVerb::Move);
+ self.push_point(point);
+ }
+
+ /// A segment needs a contour to belong to. After a close, the next contour starts where the
+ /// closed one did.
+ fn start_contour_for_segment(&mut self) {
+ match self.verbs.last() {
+ None => self.contour_move_to(FloatPoint::default()),
+ Some(PathVerb::Close) => self.contour_move_to(self.start_of_last_contour()),
+ Some(_) => {}
+ }
+ }
+
+ fn start_of_last_contour(&self) -> FloatPoint {
+ let mut point_index = 0;
+ let mut start = FloatPoint::default();
+ for verb in &self.verbs {
+ if *verb == PathVerb::Move {
+ start = self.points[point_index];
+ }
+ point_index += verb.stored_point_count();
+ }
+ start
+ }
+
+ pub fn contour_line_to(&mut self, point: FloatPoint) {
+ self.start_contour_for_segment();
+ self.verbs.push(PathVerb::Line);
+ self.push_point(point);
+ }
+
+ pub fn contour_quad_to(&mut self, control: FloatPoint, point: FloatPoint) {
+ self.start_contour_for_segment();
+ self.verbs.push(PathVerb::Quad);
+ self.push_point(control);
+ self.push_point(point);
+ }
+
+ /// A conic with a weight of 1 is a quadratic curve, and is stored as one.
+ pub fn contour_conic_to(&mut self, control: FloatPoint, point: FloatPoint, weight: f32) {
+ if weight == 1.0 {
+ self.contour_quad_to(control, point);
+ return;
+ }
+ self.start_contour_for_segment();
+ self.verbs.push(PathVerb::Conic);
+ self.push_point(control);
+ self.push_point(point);
+ self.conic_weights.push(weight);
+ }
+
+ pub fn contour_cubic_to(&mut self, control1: FloatPoint, control2: FloatPoint, point: FloatPoint) {
+ self.start_contour_for_segment();
+ self.verbs.push(PathVerb::Cubic);
+ self.push_point(control1);
+ self.push_point(control2);
+ self.push_point(point);
+ }
+
+ pub fn contour_close(&mut self) {
+ if matches!(self.verbs.last(), None | Some(PathVerb::Close)) {
+ return;
+ }
+ self.verbs.push(PathVerb::Close);
+ }
+
+ // The operations of Gfx::Path.
+
+ pub fn move_to(&mut self, point: FloatPoint) {
+ self.last_move_to = point;
+ self.has_current_point = true;
+ self.contour_move_to(point);
+ }
+
+ pub fn line_to(&mut self, point: FloatPoint) {
+ if !self.has_current_point {
+ self.move_to(point);
+ return;
+ }
+ self.contour_line_to(point);
+ }
+
+ pub fn quadratic_bezier_curve_to(&mut self, control: FloatPoint, point: FloatPoint) {
+ if !self.has_current_point {
+ self.move_to(control);
+ }
+ self.contour_quad_to(control, point);
+ }
+
+ pub fn cubic_bezier_curve_to(&mut self, control1: FloatPoint, control2: FloatPoint, point: FloatPoint) {
+ if !self.has_current_point {
+ self.move_to(control1);
+ }
+ self.contour_cubic_to(control1, control2, point);
+ }
+
+ /// An arc of an ellipse, with the parameters of the SVG path command. The rotation is in radians.
+ pub fn elliptical_arc_to(
+ &mut self,
+ point: FloatPoint,
+ radii: (f32, f32),
+ x_axis_rotation: f32,
+ large_arc: bool,
+ sweep: bool,
+ ) {
+ if !self.has_current_point {
+ self.move_to(point);
+ return;
+ }
+ arcs::append_elliptical_arc(self, point, radii, x_axis_rotation, large_arc, sweep);
+ }
+
+ pub fn arc_to(&mut self, point: FloatPoint, radius: f32, large_arc: bool, sweep: bool) {
+ self.elliptical_arc_to(point, (radius, radius), 0.0, large_arc, sweep);
+ }
+
+ /// Closes the subpath, and starts the next one where it started.
+ pub fn close(&mut self) {
+ if !self.has_current_point {
+ return;
+ }
+ self.contour_close();
+ self.contour_move_to(self.last_move_to);
+ }
+
+ /// Adds the subpaths of the other path. A move that ends this path starts nothing, so it does
+ /// not stay in front of the other path's first move. A path without geometry adds no subpaths,
+ /// but what it remembers for the operations that follow carries over.
+ pub fn append_path(&mut self, other: &PathGeometry) {
+ if other.has_only_finite_points {
+ self.append_mapped(other, |point| point);
+ }
+ if other.has_current_point {
+ self.has_current_point = true;
+ self.last_move_to = other.last_move_to;
+ }
+ }
+
+ /// Adds the contours of the other path with its points mapped, as for glyph outlines. The state of
+ /// Gfx::Path is left as it was; update_state_from_contours() sets it.
+ pub fn append_mapped(&mut self, other: &PathGeometry, map: impl Fn(FloatPoint) -> FloatPoint) {
+ if other.verbs.is_empty() {
+ return;
+ }
+ if self.verbs.last() == Some(&PathVerb::Move) {
+ self.verbs.pop();
+ self.pop_point();
+ }
+ let first_appended_point = self.points.len();
+ self.verbs.extend_from_slice(&other.verbs);
+ self.points.extend(other.points.iter().map(|point| map(*point)));
+ self.conic_weights.extend_from_slice(&other.conic_weights);
+ self.has_only_finite_points &= self.points[first_appended_point..]
+ .iter()
+ .all(|point| is_finite_point(*point));
+ }
+
+ /// Sets the state of Gfx::Path from the contours, for a path that was not built by its operations.
+ pub fn update_state_from_contours(&mut self) {
+ self.has_current_point = !self.verbs.is_empty();
+ self.last_move_to = self.start_of_last_contour();
+ }
+
+ /// A copy with every point mapped by the transform. Conics keep their weights.
+ pub fn copy_transformed(&self, transform: AffineTransform) -> PathGeometry {
+ let mut copy = self.clone();
+ copy.transform(transform);
+ copy
+ }
+
+ pub fn transform(&mut self, transform: AffineTransform) {
+ for point in &mut self.points {
+ *point = transform.map_point(*point);
+ }
+ if self.has_current_point {
+ self.last_move_to = transform.map_point(self.last_move_to);
+ }
+ self.recompute_finiteness();
+ }
+
+ fn recompute_finiteness(&mut self) {
+ self.has_only_finite_points = self.points.iter().all(|point| is_finite_point(*point));
+ }
+
+ /// Makes a path from contours that a decoder checked: each verb has its points and weights, and
+ /// every point is finite.
+ pub(super) fn from_checked_contours(
+ verbs: Vec<PathVerb>,
+ points: Vec<FloatPoint>,
+ conic_weights: Vec<f32>,
+ fill_rule: WindingRule,
+ ) -> Self {
+ let mut geometry = Self {
+ verbs,
+ points,
+ conic_weights,
+ fill_rule,
+ has_only_finite_points: true,
+ has_current_point: false,
+ last_move_to: FloatPoint::default(),
+ };
+ geometry.update_state_from_contours();
+ geometry
+ }
+
+ /// Whether both paths have the same fill rule and the same contours, point for point.
+ pub fn has_same_contours(&self, other: &PathGeometry) -> bool {
+ let same_bits = |a: f32, b: f32| a.to_bits() == b.to_bits();
+ self.fill_rule == other.fill_rule
+ && self.verbs == other.verbs
+ && self.points.len() == other.points.len()
+ && self
+ .points
+ .iter()
+ .zip(&other.points)
+ .all(|(a, b)| same_bits(a.x, b.x) && same_bits(a.y, b.y))
+ && self.conic_weights.len() == other.conic_weights.len()
+ && self
+ .conic_weights
+ .iter()
+ .zip(&other.conic_weights)
+ .all(|(a, b)| same_bits(*a, *b))
+ }
+}
+
+pub struct PathElements<'a> {
+ geometry: &'a PathGeometry,
+ verb_index: usize,
+ point_index: usize,
+ conic_weight_index: usize,
+ current_point: FloatPoint,
+ contour_start: FloatPoint,
+}
+
+impl Iterator for PathElements<'_> {
+ type Item = PathElement;
+
+ fn next(&mut self) -> Option<PathElement> {
+ let verbs = &self.geometry.verbs;
+ let verb = *verbs.get(self.verb_index)?;
+ if verb == PathVerb::Move && self.verb_index + 1 == verbs.len() {
+ return None;
+ }
+ self.verb_index += 1;
+ let points = &self.geometry.points[self.point_index..self.point_index + verb.stored_point_count()];
+ self.point_index += verb.stored_point_count();
+ let start = self.current_point;
+ let element = match verb {
+ PathVerb::Move => {
+ self.contour_start = points[0];
+ PathElement::MoveTo(points[0])
+ }
+ PathVerb::Line => PathElement::Segment(Segment::Line([start, points[0]])),
+ PathVerb::Quad => PathElement::Segment(Segment::Quad([start, points[0], points[1]])),
+ PathVerb::Conic => {
+ let weight = self.geometry.conic_weights[self.conic_weight_index];
+ self.conic_weight_index += 1;
+ PathElement::Segment(Segment::Conic([start, points[0], points[1]], weight))
+ }
+ PathVerb::Cubic => PathElement::Segment(Segment::Cubic([start, points[0], points[1], points[2]])),
+ PathVerb::Close => PathElement::Close([start, self.contour_start]),
+ };
+ self.current_point = match element {
+ PathElement::MoveTo(point) => point,
+ PathElement::Segment(segment) => segment.end(),
+ PathElement::Close(_) => self.contour_start,
+ };
+ Some(element)
+ }
+}
diff --git a/Libraries/LibGfx/Rust/src/path/hit_test.rs b/Libraries/LibGfx/Rust/src/path/hit_test.rs
new file mode 100644
index 00000000000..0db355a4aba
--- /dev/null
+++ b/Libraries/LibGfx/Rust/src/path/hit_test.rs
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Whether a point is inside a path, as the fill of the path covers it.
+//!
+//! https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-ispointinpath
+//!
+//! Every subpath counts as closed. The winding number of the path around the point decides: the edges
+//! that cross the horizontal ray from the point to the right add one when they go down and subtract one
+//! when they go up. An edge includes the point where it starts in y and excludes the one where it ends,
+//! so that a ray through a vertex counts it once where the path passes through and not at all where it
+//! turns back.
+//!
+//! A point on the path itself is inside. A point where one edge ends and the next starts is on the next
+//! edge only. Where the edges through a point cancel out, as where the path goes back over itself and
+//! so bounds nothing, the winding number decides after all.
+
+use super::curves::{Curve, Point};
+use super::geometry::{PathElement, PathGeometry, Segment};
+use crate::geometry::FloatPoint;
+use crate::paint_enums::WindingRule;
+
+/// The furthest that a point may be off a curve, relative to the size of its coordinates, and still
+/// lie on it. The position of a curve at a given y is solved for numerically.
+const ON_CURVE_TOLERANCE: f64 = 1e-6;
+
+/// The number of bisection steps that find the parameter of a monotonic curve at a given y. Each step
+/// halves the interval, so the parameter ends up as precise as a double allows.
+const BISECTION_STEPS: u32 = 64;
+
+/// How close the sum of the unit tangents of the edges through a point has to come to zero for them to
+/// cancel out.
+const CANCELLED_TANGENTS_TOLERANCE: f64 = 1e-6;
+
+pub fn contains(geometry: &PathGeometry, x: f32, y: f32, fill_rule: WindingRule) -> bool {
+ if !geometry.has_geometry() || !x.is_finite() || !y.is_finite() {
+ return false;
+ }
+ let point = Point::new(f64::from(x), f64::from(y));
+ let mut winding = 0i32;
+ let mut tangents_through_point = Vec::new();
+ for_each_filled_segment(geometry, |segment| {
+ if !segment.is_degenerate() {
+ add_crossings_of_segment(
+ &Curve::from_segment(&segment),
+ point,
+ &mut winding,
+ &mut tangents_through_point,
+ );
+ }
+ });
+
+ if !tangents_through_point.is_empty() {
+ if tangents_through_point.len() % 2 == 1 {
+ return true;
+ }
+ let tangent_sum = tangents_through_point
+ .iter()
+ .fold(Point::default(), |sum, tangent| sum.plus(*tangent));
+ if tangent_sum.length() > CANCELLED_TANGENTS_TOLERANCE {
+ return true;
+ }
+ }
+ match fill_rule {
+ WindingRule::Nonzero => winding != 0,
+ WindingRule::EvenOdd => winding % 2 != 0,
+ }
+}
+
+/// Calls the callback with the segments that bound the fill: those of the path, and a line back
+/// to the start of every subpath that does not end there.
+fn for_each_filled_segment(geometry: &PathGeometry, mut callback: impl FnMut(Segment)) {
+ // The start of the subpath that is being walked, and where the walk is in it.
+ let mut open_subpath: Option<(FloatPoint, FloatPoint)> = None;
+ let close_open_subpath = |open_subpath: Option<(FloatPoint, FloatPoint)>, callback: &mut dyn FnMut(Segment)| {
+ if let Some((start, current)) = open_subpath
+ && start != current
+ {
+ callback(Segment::Line([current, start]));
+ }
+ };
+ for element in geometry.elements() {
+ if let PathElement::MoveTo(point) = element {
+ close_open_subpath(open_subpath, &mut callback);
+ open_subpath = Some((point, point));
+ } else if let Some(segment) = element.drawn_segment() {
+ callback(segment);
+ if let Some((_, current)) = &mut open_subpath {
+ *current = segment.end();
+ }
+ }
+ }
+ close_open_subpath(open_subpath, &mut callback);
+}
+
+fn unit(vector: Point) -> Point {
+ vector.scaled(1.0 / vector.length())
+}
+
+/// Adds the crossings of the segment with the ray from the point to the winding number, and the unit
+/// tangent of the segment where it passes through the point, if it does, to the tangents.
+fn add_crossings_of_segment(curve: &Curve, point: Point, winding: &mut i32, tangents_through_point: &mut Vec<Point>) {
+ if let Curve::Line([start, end]) = *curve {
+ add_crossing_of_line(start, end, point, winding, tangents_through_point);
+ return;
+ }
+
+ // A curve stays within the bounds of its control points.
+ let control_points = curve.control_points();
+ if control_points.iter().all(|control| control.y < point.y)
+ || control_points.iter().all(|control| control.y > point.y)
+ {
+ return;
+ }
+
+ let tolerance = ON_CURVE_TOLERANCE * point.x.abs().max(point.y.abs()).max(1.0);
+ // The end of a piece belongs to the next one, and the end of the segment to the next segment.
+ let mut parameters_through_point: Vec<f64> = Vec::new();
+
+ // The curve in pieces that go only one way in y.
+ for (from, to) in monotonic_pieces(curve, 0.0, 1.0, |point| point.y) {
+ let from_point = curve_point(curve, from);
+ let to_point = curve_point(curve, to);
+ let (low_y, high_y) = (from_point.y.min(to_point.y), from_point.y.max(to_point.y));
+ if point.y < low_y || point.y > high_y {
+ continue;
+ }
+
+ if low_y == high_y {
+ // A piece that stays at one y can only have the point on it, at the parameters where it
+ // reaches the x of the point, and crosses no ray.
+ for (from, to) in monotonic_pieces(curve, from, to, |point| point.x) {
+ let (from_x, to_x) = (curve_point(curve, from).x, curve_point(curve, to).x);
+ if point.x < from_x.min(to_x) || point.x > from_x.max(to_x) {
+ continue;
+ }
+ let t = parameter_at(curve, from, to, from_x, to_x, point.x, |point| point.x);
+ if t < to {
+ parameters_through_point.push(t);
+ }
+ }
+ continue;
+ }
+
+ let t = parameter_at(curve, from, to, from_point.y, to_point.y, point.y, |point| point.y);
+ let x_at_point = curve.point_at(t).x;
+ if (x_at_point - point.x).abs() <= tolerance {
+ if t < to {
+ parameters_through_point.push(t);
+ }
+ continue;
+ }
+ if point.y == high_y || x_at_point < point.x {
+ continue;
+ }
+ *winding += if to_point.y > from_point.y { 1 } else { -1 };
+ }
+
+ for t in parameters_through_point {
+ if let Some(direction) = curve.direction_at(t) {
+ tangents_through_point.push(unit(direction));
+ }
+ }
+}
+
+/// The ranges of the parameter between from and to in which the curve goes only one way in the coordinate.
+fn monotonic_pieces(curve: &Curve, from: f64, to: f64, coordinate: impl Fn(Point) -> f64) -> Vec<(f64, f64)> {
+ let mut parameters = vec![from];
+ parameters.extend(
+ curve
+ .turning_parameters(coordinate)
+ .into_iter()
+ .filter(|t| *t > from && *t < to),
+ );
+ parameters.push(to);
+ parameters.windows(2).map(|range| (range[0], range[1])).collect()
+}
+
+fn curve_point(curve: &Curve, t: f64) -> Point {
+ if t == 0.0 {
+ curve.start()
+ } else if t == 1.0 {
+ curve.end()
+ } else {
+ curve.point_at(t)
+ }
+}
+
+fn add_crossing_of_line(
+ start: Point,
+ end: Point,
+ point: Point,
+ winding: &mut i32,
+ tangents_through_point: &mut Vec<Point>,
+) {
+ let (low_y, high_y) = (start.y.min(end.y), start.y.max(end.y));
+ if point.y < low_y || point.y > high_y {
+ return;
+ }
+ let (low_x, high_x) = (start.x.min(end.x), start.x.max(end.x));
+ // The sign of the cross product says on which side of the line the point is.
+ let cross = (end.x - start.x) * (point.y - start.y) - (end.y - start.y) * (point.x - start.x);
+ if cross == 0.0 && point.x >= low_x && point.x <= high_x {
+ // The end of a line belongs to the next segment.
+ if point != end {
+ tangents_through_point.push(unit(end.minus(start)));
+ }
+ return;
+ }
+ if start.y == end.y || point.y == high_y {
+ return;
+ }
+ // The point is left of a line that goes down when the cross product is positive, and left of one
+ // that goes up when it is negative.
+ let goes_down = end.y > start.y;
+ if (goes_down && cross > 0.0) || (!goes_down && cross < 0.0) {
+ *winding += if goes_down { 1 } else { -1 };
+ }
+}
+
+/// The parameter in the range where the curve goes one way in the coordinate at which it reaches the given
+/// value.
+fn parameter_at(
+ curve: &Curve,
+ mut from: f64,
+ mut to: f64,
+ from_value: f64,
+ to_value: f64,
+ value: f64,
+ coordinate: impl Fn(Point) -> f64,
+) -> f64 {
+ if value == from_value {
+ return from;
+ }
+ if value == to_value {
+ return to;
+ }
+ let increasing = to_value > from_value;
+ for _ in 0..BISECTION_STEPS {
+ let middle = (from + to) / 2.0;
+ if (coordinate(curve.point_at(middle)) < value) == increasing {
+ from = middle;
+ } else {
+ to = middle;
+ }
+ }
+ (from + to) / 2.0
+}
diff --git a/Libraries/LibGfx/Rust/src/path/measure.rs b/Libraries/LibGfx/Rust/src/path/measure.rs
new file mode 100644
index 00000000000..f2b7e4cfb40
--- /dev/null
+++ b/Libraries/LibGfx/Rust/src/path/measure.rs
@@ -0,0 +1,376 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Lengths of paths, and positions and directions along them.
+//!
+//! A curve is measured in pieces between points at equal steps of its parameter. The number of steps
+//! comes from Wang's formula, which keeps the line between the ends of each piece within
+//! MEASURE_TOLERANCE of the curve. The length of each piece is the integral of the speed of the curve,
+//! by Gauss-Legendre quadrature, which is exact to well within float precision for pieces this flat.
+//! A position within a piece is at the parameter that is as far between its ends as the distance is.
+
+use super::curves::{Curve, Point};
+use super::geometry::{PathElement, PathElements, PathGeometry, Segment};
+use crate::geometry::FloatPoint;
+
+/// The furthest that the lines that measure a curve are from it.
+const MEASURE_TOLERANCE: f64 = 1.0 / 32.0;
+
+/// The most lines with which to follow a single curve, which bounds the work for a huge curve.
+const MAXIMUM_LINE_COUNT_ALONG_CURVE: u32 = 4096;
+
+/// The number of lines between points at equal parameter steps that follow the curve within the
+/// tolerance, by Wang's formula: the square root of the largest second difference of its control
+/// points, scaled by its degree, over the tolerance.
+pub(super) fn line_count_to_follow(curve: &Curve) -> u32 {
+ let second_difference = |points: &[Point], index: usize| {
+ points[index]
+ .minus(points[index + 1].scaled(2.0))
+ .plus(points[index + 2])
+ .length()
+ };
+ let scaled_second_difference = match curve {
+ Curve::Line(_) => return 1,
+ Curve::Quad(points) => second_difference(points, 0) / 4.0,
+ // A conic with a weight of at most 1, like the arcs of SVG paths, bends no more than the quadratic curve
+ // with the same control points.
+ Curve::Conic(points, weight) => weight.max(1.0) * second_difference(points, 0) / 4.0,
+ Curve::Cubic(points) => 3.0 * second_difference(points, 0).max(second_difference(points, 1)) / 4.0,
+ };
+ let line_count = (scaled_second_difference / MEASURE_TOLERANCE).sqrt().ceil();
+ if line_count.is_nan() {
+ return 1;
+ }
+ line_count.clamp(1.0, f64::from(MAXIMUM_LINE_COUNT_ALONG_CURVE)) as u32
+}
+
+/// The length of the curve between two parameters: the integral of its speed, by five-point
+/// Gauss-Legendre quadrature.
+fn length_between(curve: &Curve, from: f64, to: f64) -> f64 {
+ const NODES_AND_WEIGHTS: [(f64, f64); 5] = [
+ (0.0, 0.568_888_888_888_888_9),
+ (-0.538_469_310_105_683_1, 0.478_628_670_499_366_5),
+ (0.538_469_310_105_683_1, 0.478_628_670_499_366_5),
+ (-0.906_179_845_938_664, 0.236_926_885_056_189_1),
+ (0.906_179_845_938_664, 0.236_926_885_056_189_1),
+ ];
+ let half_width = (to - from) / 2.0;
+ let middle = (from + to) / 2.0;
+ let integral: f64 = NODES_AND_WEIGHTS
+ .iter()
+ .map(|(node, weight)| weight * curve.derivative_at(middle + half_width * node).length())
+ .sum();
+ integral * half_width
+}
+
+#[derive(Clone, Copy, Debug)]
+struct MeasuredPiece {
+ segment_index: usize,
+ from_parameter: f64,
+ to_parameter: f64,
+ distance_at_end: f64,
+}
+
+/// The measure of one contour of a path that has length.
+#[derive(Clone, Debug)]
+pub struct ContourMeasure {
+ curves: Vec<Curve>,
+ pieces: Vec<MeasuredPiece>,
+}
+
+impl ContourMeasure {
+ fn new() -> Self {
+ Self {
+ curves: Vec::new(),
+ pieces: Vec::new(),
+ }
+ }
+
+ fn distance(&self) -> f64 {
+ self.pieces.last().map_or(0.0, |piece| piece.distance_at_end)
+ }
+
+ fn add_segment(&mut self, segment: &Segment) {
+ let curve = Curve::from_segment(segment);
+ let line_count = line_count_to_follow(&curve);
+ self.add_curve(curve, line_count);
+ }
+
+ fn add_curve(&mut self, curve: Curve, line_count: u32) {
+ let segment_index = self.curves.len();
+ let mut distance = self.distance();
+ let mut previous_point = curve.start();
+ let mut previous_parameter = 0.0;
+ for line in 1..=line_count {
+ let parameter = f64::from(line) / f64::from(line_count);
+ let point = if line == line_count {
+ curve.end()
+ } else {
+ curve.point_at(parameter)
+ };
+ let length = match curve {
+ Curve::Line(_) => previous_point.distance_to(point),
+ _ => length_between(&curve, previous_parameter, parameter),
+ };
+ if length > 0.0 {
+ distance += length;
+ self.pieces.push(MeasuredPiece {
+ segment_index,
+ from_parameter: previous_parameter,
+ to_parameter: parameter,
+ distance_at_end: distance,
+ });
+ }
+ previous_point = point;
+ previous_parameter = parameter;
+ }
+ self.curves.push(curve);
+ }
+
+ pub fn length(&self) -> f32 {
+ self.distance() as f32
+ }
+
+ /// The point at the distance along the contour, clamped to its ends, and the unit tangent there.
+ pub fn position_and_tangent(&self, distance: f32) -> (FloatPoint, FloatPoint) {
+ let distance = f64::from(distance).clamp(0.0, self.distance());
+ let piece_index = self
+ .pieces
+ .partition_point(|piece| piece.distance_at_end < distance)
+ .min(self.pieces.len() - 1);
+ let piece = &self.pieces[piece_index];
+ let distance_at_start = if piece_index == 0 {
+ 0.0
+ } else {
+ self.pieces[piece_index - 1].distance_at_end
+ };
+ let fraction = (distance - distance_at_start) / (piece.distance_at_end - distance_at_start);
+ let curve = &self.curves[piece.segment_index];
+ let parameter = piece.from_parameter + (piece.to_parameter - piece.from_parameter) * fraction;
+ let position = match *curve {
+ Curve::Line([start, end]) => start.lerp(end, parameter),
+ _ => curve.point_at(parameter),
+ };
+ let direction = curve.direction_at(parameter).unwrap_or_default();
+ let direction_length = direction.length();
+ let tangent = if direction_length > 0.0 {
+ direction.scaled(1.0 / direction_length)
+ } else {
+ direction
+ };
+ (position.to_float(), tangent.to_float())
+ }
+
+ /// The measures of the contours of the path that have length, in order, each measured when it is
+ /// asked for. A close adds the line back to the start of its contour; an open contour gets no such
+ /// line.
+ pub fn contours_of(geometry: &PathGeometry) -> ContourMeasures<'_> {
+ ContourMeasures {
+ elements: geometry.has_geometry().then(|| geometry.elements()),
+ }
+ }
+
+ fn of_curve(curve: Curve, line_count: u32) -> ContourMeasure {
+ let mut contour = ContourMeasure::new();
+ contour.add_curve(curve, line_count);
+ contour
+ }
+}
+
+pub struct ContourMeasures<'a> {
+ elements: Option<PathElements<'a>>,
+}
+
+impl Iterator for ContourMeasures<'_> {
+ type Item = ContourMeasure;
+
+ fn next(&mut self) -> Option<ContourMeasure> {
+ let elements = self.elements.as_mut()?;
+ let mut contour = ContourMeasure::new();
+ for element in elements.by_ref() {
+ match element.drawn_segment() {
+ Some(segment) => contour.add_segment(&segment),
+ None if !contour.pieces.is_empty() => return Some(contour),
+ None => contour.curves.clear(),
+ }
+ }
+ self.elements = None;
+ (!contour.pieces.is_empty()).then_some(contour)
+ }
+}
+
+/// The length of the path: the sum of the lengths of its contours.
+pub fn length(geometry: &PathGeometry) -> f32 {
+ // Summing floats starts from -0, which a path without length must not give.
+ ContourMeasure::contours_of(geometry).fold(0.0, |length, contour| length + contour.length())
+}
+
+/// The point at a distance along the path, clamped to its ends, and the unit tangent of the path there.
+/// The gaps between the subpaths do not add to the distance. A path without length is only its start
+/// point, where it has no tangent.
+pub fn point_at_length(geometry: &PathGeometry, distance: f32) -> Option<(FloatPoint, FloatPoint)> {
+ let mut remaining_distance = distance.max(0.0);
+ let mut end_of_path = None;
+ for contour in ContourMeasure::contours_of(geometry) {
+ let contour_length = contour.length();
+ end_of_path = Some(contour.position_and_tangent(remaining_distance.min(contour_length)));
+ if remaining_distance <= contour_length {
+ return end_of_path;
+ }
+ remaining_distance -= contour_length;
+ }
+ if end_of_path.is_some() {
+ return end_of_path;
+ }
+ if !geometry.has_geometry() {
+ return None;
+ }
+ Some((geometry.points()[0], FloatPoint::default()))
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+#[repr(C)]
+pub struct PathVertex {
+ pub point: FloatPoint,
+ pub distance: f32,
+ pub direction: FloatPoint,
+}
+
+/// The vertices of polylines through the ends of the segments of the path, with their distance along
+/// it. Along a curved segment, the polylines pass through points along the curve that keep them within
+/// MEASURE_TOLERANCE of it. The gaps between the subpaths do not add to the distance, so a subpath
+/// starts at the distance its predecessor ends at. A path without length is only its start point.
+///
+/// Each vertex has the unit tangent of the path there as its direction. Where the path changes
+/// direction at once, the vertex appears twice: with the direction in which the path arrives, and with
+/// the one in which it leaves. A subpath start that no segment with length leaves from has no
+/// direction.
+pub fn vertices(geometry: &PathGeometry) -> Vec<PathVertex> {
+ let mut vertices: Vec<PathVertex> = Vec::new();
+ if !geometry.has_geometry() {
+ return vertices;
+ }
+ let mut distance = 0.0f32;
+ for element in geometry.elements() {
+ let Some(segment) = element.drawn_segment() else {
+ if let PathElement::MoveTo(point) = element {
+ vertices.push(PathVertex {
+ point,
+ distance,
+ direction: FloatPoint::default(),
+ });
+ }
+ continue;
+ };
+
+ // A segment without length has no direction, and leaves the path where it was.
+ let curve = Curve::from_segment(&segment);
+ let line_count = line_count_to_follow(&curve);
+ let measure = ContourMeasure::of_curve(curve, line_count);
+ let segment_length = measure.length();
+ if segment_length <= 0.0 {
+ continue;
+ }
+ let direction_at = |distance_in_segment: f32| measure.position_and_tangent(distance_in_segment).1;
+
+ let start_direction = direction_at(0.0);
+ if let Some(last) = vertices.last_mut()
+ && last.direction == FloatPoint::default()
+ {
+ last.direction = start_direction;
+ } else if vertices.last().map(|vertex| vertex.direction) != Some(start_direction) {
+ vertices.push(PathVertex {
+ point: segment.start(),
+ distance,
+ direction: start_direction,
+ });
+ }
+
+ let mut curve = CurveToFollow {
+ measure: &measure,
+ distance_to_curve: distance,
+ vertices: &mut vertices,
+ remaining_line_count: MAXIMUM_LINE_COUNT_ALONG_CURVE - line_count,
+ };
+ let mut previous_distance = 0.0f32;
+ let mut previous_point = segment.start();
+ for line in 1..=line_count {
+ let distance_in_segment = segment_length * line as f32 / line_count as f32;
+ let (position, tangent) = if line == line_count {
+ (segment.end(), FloatPoint::default())
+ } else {
+ measure.position_and_tangent(distance_in_segment)
+ };
+ curve.follow_between(previous_distance, previous_point, distance_in_segment, position);
+ if line < line_count {
+ curve.vertices.push(PathVertex {
+ point: position,
+ distance: distance + distance_in_segment,
+ direction: tangent,
+ });
+ }
+ previous_distance = distance_in_segment;
+ previous_point = position;
+ }
+ distance += segment_length;
+ vertices.push(PathVertex {
+ point: segment.end(),
+ distance,
+ direction: direction_at(segment_length),
+ });
+ }
+
+ if vertices.is_empty() {
+ vertices.push(PathVertex {
+ point: geometry.points()[0],
+ distance: 0.0,
+ direction: FloatPoint::default(),
+ });
+ }
+ vertices
+}
+
+struct CurveToFollow<'a> {
+ measure: &'a ContourMeasure,
+ distance_to_curve: f32,
+ vertices: &'a mut Vec<PathVertex>,
+ remaining_line_count: u32,
+}
+
+impl CurveToFollow<'_> {
+ /// Appends the vertices between two points along the curve, splitting the line between them in half
+ /// for as long as the curve passes further than the tolerance from it halfway, or until the curve has
+ /// as many lines as it may have.
+ fn follow_between(
+ &mut self,
+ start_distance: f32,
+ start_point: FloatPoint,
+ end_distance: f32,
+ end_point: FloatPoint,
+ ) {
+ if self.remaining_line_count == 0 {
+ return;
+ }
+ let middle_distance = (start_distance + end_distance) / 2.0;
+ let (middle_point, tangent) = self.measure.position_and_tangent(middle_distance);
+ let chord_middle = FloatPoint {
+ x: (start_point.x + end_point.x) / 2.0,
+ y: (start_point.y + end_point.y) / 2.0,
+ };
+ if Point::from_float(middle_point).distance_to(Point::from_float(chord_middle)) <= MEASURE_TOLERANCE {
+ return;
+ }
+
+ self.remaining_line_count -= 1;
+ self.follow_between(start_distance, start_point, middle_distance, middle_point);
+ self.vertices.push(PathVertex {
+ point: middle_point,
+ distance: self.distance_to_curve + middle_distance,
+ direction: tangent,
+ });
+ self.follow_between(middle_distance, middle_point, end_distance, end_point);
+ }
+}
diff --git a/Libraries/LibGfx/Rust/src/path/stroke.rs b/Libraries/LibGfx/Rust/src/path/stroke.rs
new file mode 100644
index 00000000000..da2afd5c201
--- /dev/null
+++ b/Libraries/LibGfx/Rust/src/path/stroke.rs
@@ -0,0 +1,463 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The area that stroking a path covers, as a path to fill with the nonzero winding rule.
+//!
+//! Each subpath is followed as a polyline through points along its curves, each with the directions in
+//! which the path arrives at it and leaves it, and is cut into dashes when the stroke has a dash pattern.
+//! Every line of a polyline adds the band between the normals of the path at its ends, every corner of the
+//! path the piece that its join adds, and every open end its cap. All pieces wind the same way, so the
+//! nonzero fill of them all is the area that they cover together.
+
+use super::curves::{Curve, Point};
+use super::geometry::{PathElement, PathGeometry};
+use super::measure::line_count_to_follow;
+use crate::geometry::FloatPoint;
+use crate::paint_enums::{CapStyle, JoinStyle, WindingRule};
+
+/// The smallest cosine of half a turn that one conic covers as a round join. A turn that comes closer to a
+/// reversal gets a whole circle.
+const SMALLEST_HALF_TURN_COSINE_OF_A_SECTOR: f64 = 0.1;
+
+pub struct StrokeStyle<'a> {
+ pub thickness: f32,
+ pub cap_style: CapStyle,
+ pub join_style: JoinStyle,
+ pub miter_limit: f32,
+ pub dash_array: &'a [f32],
+ pub dash_offset: f32,
+}
+
+#[derive(Clone, Copy)]
+struct PolylinePoint {
+ point: Point,
+ // The unit directions in which the path arrives at the point and leaves it. They differ only at the
+ // corners of the path.
+ incoming: Point,
+ outgoing: Point,
+}
+
+struct Polyline {
+ points: Vec<PolylinePoint>,
+ closed: bool,
+}
+
+pub fn stroke_to_fill(geometry: &PathGeometry, style: &StrokeStyle) -> PathGeometry {
+ let mut output = PathGeometry::new();
+ let half_thickness = f64::from(style.thickness) / 2.0;
+ if !geometry.has_geometry() || !half_thickness.is_finite() || half_thickness <= 0.0 {
+ return output;
+ }
+ let mut stroker = Stroker {
+ output: &mut output,
+ half_thickness,
+ style,
+ };
+ let dash_pattern = dash_pattern(style);
+ for subpath in subpaths_of(geometry) {
+ match &dash_pattern {
+ Some(pattern) => {
+ for dash in dashes_of(&subpath, pattern, f64::from(style.dash_offset)) {
+ stroker.stroke(&dash);
+ }
+ }
+ None => stroker.stroke(&subpath),
+ }
+ }
+ output.set_fill_rule(WindingRule::Nonzero);
+ output.update_state_from_contours();
+ output
+}
+
+fn unit(vector: Point) -> Point {
+ vector.scaled(1.0 / vector.length())
+}
+
+fn normal(direction: Point) -> Point {
+ Point::new(-direction.y, direction.x)
+}
+
+/// The subpaths of the path as polylines. Only a subpath that a segment follows its move into is stroked,
+/// even if the segment goes nowhere, so that round and square caps can draw it as a dot.
+fn subpaths_of(geometry: &PathGeometry) -> Vec<Polyline> {
+ let mut subpaths = Vec::new();
+ // The subpath that is being followed, and whether a segment has followed its move.
+ let mut current: Option<(Polyline, bool)> = None;
+ for element in geometry.elements() {
+ if let PathElement::MoveTo(point) = element {
+ if let Some((subpath, true)) = current.take() {
+ subpaths.push(subpath);
+ }
+ // The directions at the start are those of the first segment that goes somewhere.
+ let start = PolylinePoint {
+ point: Point::from_float(point),
+ incoming: Point::default(),
+ outgoing: Point::default(),
+ };
+ current = Some((
+ Polyline {
+ points: vec![start],
+ closed: false,
+ },
+ false,
+ ));
+ continue;
+ }
+ let (subpath, has_segment) = current.as_mut().expect("a segment follows a move");
+ *has_segment = true;
+ let Some(segment) = element.drawn_segment() else {
+ continue;
+ };
+ if segment.is_degenerate() {
+ if let PathElement::Close(_) = element {
+ subpath.closed = true;
+ }
+ continue;
+ }
+ let curve = Curve::from_segment(&segment);
+ let direction_at = |t: f64| {
+ unit(
+ curve
+ .direction_at(t)
+ .expect("a segment that goes somewhere has directions"),
+ )
+ };
+ leave_in_direction(subpath, direction_at(0.0));
+ let line_count = line_count_to_follow(&curve);
+ for line in 1..=line_count {
+ let t = f64::from(line) / f64::from(line_count);
+ let point = if line == line_count {
+ curve.end()
+ } else {
+ curve.point_at(t)
+ };
+ push_point(subpath, point, direction_at(t));
+ }
+ if let PathElement::Close(_) = element {
+ subpath.closed = true;
+ }
+ }
+ if let Some((subpath, true)) = current {
+ subpaths.push(subpath);
+ }
+ subpaths
+}
+
+/// Sets the direction in which the path leaves the last point of the polyline, and the one in which it
+/// arrives at the start, if nothing has arrived there.
+fn leave_in_direction(polyline: &mut Polyline, direction: Point) {
+ let last = polyline.points.last_mut().expect("a polyline has a start");
+ last.outgoing = direction;
+ if last.incoming == Point::default() {
+ last.incoming = direction;
+ }
+}
+
+/// Adds a point where the path goes in the direction. A point where the polyline already is only takes the
+/// direction in which the path leaves it.
+fn push_point(polyline: &mut Polyline, point: Point, direction: Point) {
+ if let Some(last) = polyline.points.last_mut()
+ && last.point == point
+ {
+ last.outgoing = direction;
+ return;
+ }
+ polyline.points.push(PolylinePoint {
+ point,
+ incoming: direction,
+ outgoing: direction,
+ });
+}
+
+/// The dash pattern of the style, if it has one that dashes anything: an even number of lengths that are
+/// not negative, and that do not all add up to nothing.
+fn dash_pattern(style: &StrokeStyle) -> Option<Vec<f64>> {
+ let pattern: Vec<f64> = style.dash_array.iter().map(|length| f64::from(*length)).collect();
+ if pattern.is_empty()
+ || !pattern.len().is_multiple_of(2)
+ || !pattern.iter().all(|length| length.is_finite() && *length >= 0.0)
+ {
+ return None;
+ }
+ let total: f64 = pattern.iter().sum();
+ (total > 0.0 && f64::from(style.dash_offset).is_finite()).then_some(pattern)
+}
+
+/// The dashes of a subpath. The pattern starts over at the start of each subpath, at the offset. A dash
+/// that runs through the start of a closed subpath is one dash. A subpath that goes nowhere has no dashes.
+fn dashes_of(subpath: &Polyline, pattern: &[f64], offset: f64) -> Vec<Polyline> {
+ if subpath.points.len() < 2 {
+ return Vec::new();
+ }
+ let total: f64 = pattern.iter().sum();
+ let mut index = 0;
+ let mut remaining = pattern[0];
+ let mut phase = offset.rem_euclid(total);
+ // A dash with no length at the offset still starts there, and draws a dot with round and square caps.
+ while phase > remaining || (phase == remaining && remaining > 0.0) {
+ phase -= remaining;
+ index = (index + 1) % pattern.len();
+ remaining = pattern[index];
+ }
+ remaining -= phase;
+
+ // The lengths at even indices are dashes, and those at odd ones are gaps.
+ let starts_in_dash = index % 2 == 0;
+ let mut dashes = Vec::new();
+ let mut current = starts_in_dash.then(|| vec![subpath.points[0]]);
+ for pair in subpath.points.windows(2) {
+ let (from, to) = (pair[0], pair[1]);
+ let length = from.point.distance_to(to.point);
+ let mut travelled = 0.0;
+ while length - travelled > remaining {
+ travelled += remaining;
+ let fraction = travelled / length;
+ let direction = unit(from.outgoing.lerp(to.incoming, fraction));
+ let point = PolylinePoint {
+ point: from.point.lerp(to.point, fraction),
+ incoming: direction,
+ outgoing: direction,
+ };
+ // The pattern alternates between dashes and gaps, so a dash ends here or one starts.
+ match current.take() {
+ Some(mut dash) => {
+ dash.push(point);
+ dashes.push(dash);
+ }
+ None => current = Some(vec![point]),
+ }
+ index = (index + 1) % pattern.len();
+ remaining = pattern[index];
+ }
+ remaining -= length - travelled;
+ if let Some(dash) = current.as_mut() {
+ dash.push(to);
+ }
+ }
+ let ends_in_dash = current.is_some();
+ dashes.extend(current);
+
+ if subpath.closed && starts_in_dash && ends_in_dash && dashes.len() > 1 {
+ let first = dashes.remove(0);
+ let last = dashes.last_mut().expect("there is more than one dash");
+ last.last_mut().expect("a dash has points").outgoing = first[0].outgoing;
+ last.extend(first.into_iter().skip(1));
+ }
+ dashes
+ .into_iter()
+ .map(|points| Polyline { points, closed: false })
+ .collect()
+}
+
+struct Stroker<'a> {
+ output: &'a mut PathGeometry,
+ half_thickness: f64,
+ style: &'a StrokeStyle<'a>,
+}
+
+impl Stroker<'_> {
+ fn stroke(&mut self, polyline: &Polyline) {
+ let mut points: Vec<PolylinePoint> = Vec::with_capacity(polyline.points.len());
+ for point in &polyline.points {
+ match points.last_mut() {
+ Some(last) if last.point == point.point => last.outgoing = point.outgoing,
+ _ => points.push(*point),
+ }
+ }
+ if points.len() < 2 {
+ if let Some(point) = points.first() {
+ self.add_dot(point.point);
+ }
+ return;
+ }
+
+ for pair in points.windows(2) {
+ self.add_band(pair[0], pair[1]);
+ }
+ for point in &points[1..points.len() - 1] {
+ self.add_join(point.point, point.incoming, point.outgoing);
+ }
+ let (first, last) = (points[0], points[points.len() - 1]);
+ if polyline.closed {
+ self.add_join(first.point, last.incoming, first.outgoing);
+ } else {
+ self.add_cap(first.point, first.outgoing.scaled(-1.0));
+ self.add_cap(last.point, last.incoming);
+ }
+ }
+
+ /// The band that a line of the polyline sweeps, between the normals of the path where the line starts
+ /// and where it ends.
+ fn add_band(&mut self, from: PolylinePoint, to: PolylinePoint) {
+ let from_offset = normal(from.outgoing).scaled(self.half_thickness);
+ let to_offset = normal(to.incoming).scaled(self.half_thickness);
+ let corners = [
+ from.point.plus(from_offset),
+ to.point.plus(to_offset),
+ to.point.minus(to_offset),
+ from.point.minus(from_offset),
+ ];
+ if is_convex(&corners) {
+ self.add_convex_polygon(&corners);
+ return;
+ }
+ // Where the curve bends more tightly than the stroke is wide, the normals cross on the inner side.
+ // Triangles fanned from the line cover the band without needing it to be convex.
+ for triangle in [
+ [from.point, corners[0], corners[1]],
+ [from.point, corners[1], to.point],
+ [from.point, to.point, corners[2]],
+ [from.point, corners[2], corners[3]],
+ ] {
+ self.add_convex_polygon(&triangle);
+ }
+ }
+
+ /// The piece that the join adds at a corner, on the outer side of the turn.
+ fn add_join(&mut self, point: Point, incoming: Point, outgoing: Point) {
+ let cross = incoming.x * outgoing.y - incoming.y * outgoing.x;
+ let dot = incoming.x * outgoing.x + incoming.y * outgoing.y;
+ if cross == 0.0 && dot > 0.0 {
+ return;
+ }
+ let half_turn_cosine = ((1.0 + dot) / 2.0).max(0.0).sqrt();
+ // The outer side of a turn is the one away from the side that the path turns to.
+ let outer_side = if cross > 0.0 { -1.0 } else { 1.0 };
+ let incoming_offset = point.plus(normal(incoming).scaled(outer_side * self.half_thickness));
+ let outgoing_offset = point.plus(normal(outgoing).scaled(outer_side * self.half_thickness));
+ let miter_tip = || {
+ let bisector = unit(incoming_offset.plus(outgoing_offset).minus(point.scaled(2.0)));
+ point.plus(bisector.scaled(self.half_thickness / half_turn_cosine))
+ };
+ match self.style.join_style {
+ JoinStyle::Round if half_turn_cosine < SMALLEST_HALF_TURN_COSINE_OF_A_SECTOR => {
+ self.add_circle(point, self.half_thickness);
+ }
+ JoinStyle::Round => {
+ // An arc around the corner from one offset to the other is a conic with the miter tip as its
+ // control point, and the cosine of half the turn as its weight.
+ self.add_sector(
+ point,
+ incoming_offset,
+ miter_tip(),
+ outgoing_offset,
+ half_turn_cosine as f32,
+ );
+ }
+ // The miter is as long as the stroke is wide times one over the cosine of half the turn. One longer
+ // than the limit is a bevel.
+ JoinStyle::Miter
+ if half_turn_cosine > 0.0 && 1.0 / half_turn_cosine <= f64::from(self.style.miter_limit) =>
+ {
+ self.add_convex_polygon(&[point, incoming_offset, miter_tip(), outgoing_offset]);
+ }
+ JoinStyle::Miter | JoinStyle::Bevel => {
+ self.add_convex_polygon(&[point, incoming_offset, outgoing_offset]);
+ }
+ }
+ }
+
+ /// The cap at an open end, where the path leaves in the given direction.
+ fn add_cap(&mut self, end: Point, direction: Point) {
+ match self.style.cap_style {
+ CapStyle::Butt => {}
+ CapStyle::Round => self.add_circle(end, self.half_thickness),
+ CapStyle::Square => {
+ let along = direction.scaled(self.half_thickness);
+ let across = normal(direction).scaled(self.half_thickness);
+ self.add_convex_polygon(&[
+ end.plus(across),
+ end.plus(across).plus(along),
+ end.minus(across).plus(along),
+ end.minus(across),
+ ]);
+ }
+ }
+ }
+
+ /// A polyline that goes nowhere: round caps make it a circle, and square caps a square along the x axis.
+ fn add_dot(&mut self, point: Point) {
+ match self.style.cap_style {
+ CapStyle::Butt => {}
+ CapStyle::Round => self.add_circle(point, self.half_thickness),
+ CapStyle::Square => {
+ let half = self.half_thickness;
+ self.add_convex_polygon(&[
+ Point::new(point.x - half, point.y - half),
+ Point::new(point.x + half, point.y - half),
+ Point::new(point.x + half, point.y + half),
+ Point::new(point.x - half, point.y + half),
+ ]);
+ }
+ }
+ }
+
+ /// Adds a convex polygon that winds the same way as every other piece. One without area adds nothing.
+ fn add_convex_polygon(&mut self, points: &[Point]) {
+ let twice_area: f64 = (0..points.len())
+ .map(|index| {
+ let (a, b) = (points[index], points[(index + 1) % points.len()]);
+ a.x * b.y - b.x * a.y
+ })
+ .sum();
+ if !twice_area.is_normal() {
+ return;
+ }
+ let mut ordered: Vec<Point> = points.to_vec();
+ if twice_area < 0.0 {
+ ordered.reverse();
+ }
+ self.output.contour_move_to(ordered[0].to_float());
+ for point in &ordered[1..] {
+ self.output.contour_line_to(point.to_float());
+ }
+ self.output.contour_close();
+ }
+
+ /// Adds the sector of a circle around the center from one point on it to another, along the conic with
+ /// the control point and the weight, winding the same way as the polygons.
+ fn add_sector(&mut self, center: Point, from: Point, control: Point, to: Point, weight: f32) {
+ let twice_area = (from.x - center.x) * (to.y - center.y) - (to.x - center.x) * (from.y - center.y);
+ if !twice_area.is_normal() {
+ return;
+ }
+ let (from, to) = if twice_area > 0.0 { (from, to) } else { (to, from) };
+ self.output.contour_move_to(center.to_float());
+ self.output.contour_line_to(from.to_float());
+ self.output.contour_conic_to(control.to_float(), to.to_float(), weight);
+ self.output.contour_close();
+ }
+
+ /// Adds a circle as four quarter circles, winding the same way as the polygons.
+ fn add_circle(&mut self, center: Point, radius: f64) {
+ let at = |x: f64, y: f64| FloatPoint {
+ x: (center.x + x * radius) as f32,
+ y: (center.y + y * radius) as f32,
+ };
+ let weight = std::f32::consts::FRAC_1_SQRT_2;
+ self.output.contour_move_to(at(1.0, 0.0));
+ self.output.contour_conic_to(at(1.0, 1.0), at(0.0, 1.0), weight);
+ self.output.contour_conic_to(at(-1.0, 1.0), at(-1.0, 0.0), weight);
+ self.output.contour_conic_to(at(-1.0, -1.0), at(0.0, -1.0), weight);
+ self.output.contour_conic_to(at(1.0, -1.0), at(1.0, 0.0), weight);
+ self.output.contour_close();
+ }
+}
+
+/// Whether the polygon turns the same way at each corner.
+fn is_convex(points: &[Point]) -> bool {
+ let count = points.len();
+ let turns = (0..count).map(|index| {
+ let (a, b, c) = (points[index], points[(index + 1) % count], points[(index + 2) % count]);
+ (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x)
+ });
+ let (mut has_left_turn, mut has_right_turn) = (false, false);
+ for turn in turns {
+ has_left_turn |= turn > 0.0;
+ has_right_turn |= turn < 0.0;
+ }
+ !(has_left_turn && has_right_turn)
+}
diff --git a/Libraries/LibGfx/Rust/src/path/svg_text.rs b/Libraries/LibGfx/Rust/src/path/svg_text.rs
new file mode 100644
index 00000000000..69535834cc8
--- /dev/null
+++ b/Libraries/LibGfx/Rust/src/path/svg_text.rs
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The path as the text of SVG path data, with absolute commands and no separator before a command.
+
+use super::curves::Point;
+use super::geometry::{PathElement, PathGeometry, Segment};
+use crate::geometry::FloatPoint;
+use std::fmt::Write;
+
+/// The furthest that the quadratic curves that stand for a conic may be from it.
+const CONIC_TO_QUADS_TOLERANCE: f64 = 1.0 / 1024.0;
+
+/// A conic becomes at most 2^5 quadratic curves.
+const MAXIMUM_CONIC_SPLIT_DEPTH: u32 = 5;
+
+pub fn to_svg_string(geometry: &PathGeometry) -> String {
+ let mut output = String::new();
+ if !geometry.has_geometry() {
+ return output;
+ }
+ for element in geometry.elements() {
+ match element {
+ PathElement::MoveTo(point) => write_command(&mut output, 'M', &[point]),
+ PathElement::Segment(Segment::Line([_, end])) => write_command(&mut output, 'L', &[end]),
+ PathElement::Segment(Segment::Quad([_, control, end])) => write_command(&mut output, 'Q', &[control, end]),
+ PathElement::Segment(Segment::Cubic([_, control1, control2, end])) => {
+ write_command(&mut output, 'C', &[control1, control2, end]);
+ }
+ PathElement::Segment(Segment::Conic(points, weight)) => {
+ for (control, end) in quads_for_conic(points, weight) {
+ write_command(&mut output, 'Q', &[control, end]);
+ }
+ }
+ PathElement::Close([current, start]) => {
+ if current != start {
+ write_command(&mut output, 'L', &[start]);
+ }
+ output.push('Z');
+ }
+ }
+ }
+ output
+}
+
+fn write_command(output: &mut String, command: char, points: &[FloatPoint]) {
+ output.push(command);
+ for (index, point) in points.iter().enumerate() {
+ if index > 0 {
+ output.push(' ');
+ }
+ write_number(output, point.x);
+ output.push(' ');
+ write_number(output, point.y);
+ }
+}
+
+/// Writes the number with eight significant digits and without trailing zeros, in the notation that
+/// printf() gives for "%.8g": a fixed point when the decimal exponent is at least -4 and less than 8,
+/// and an exponent of at least two digits otherwise.
+fn write_number(output: &mut String, value: f32) {
+ const SIGNIFICANT_DIGITS: i32 = 8;
+ let value = f64::from(value);
+ let scientific = format!("{:.*e}", (SIGNIFICANT_DIGITS - 1) as usize, value);
+ let (mantissa, exponent) = scientific
+ .split_once('e')
+ .expect("the scientific notation has an exponent");
+ let exponent: i32 = exponent.parse().expect("the exponent is a number");
+ if (-4..SIGNIFICANT_DIGITS).contains(&exponent) {
+ let fixed = format!("{:.*}", (SIGNIFICANT_DIGITS - 1 - exponent) as usize, value);
+ output.push_str(without_trailing_zeros(&fixed));
+ } else {
+ output.push_str(without_trailing_zeros(mantissa));
+ let sign = if exponent < 0 { '-' } else { '+' };
+ write!(output, "e{sign}{:02}", exponent.abs()).expect("writing to a String succeeds");
+ }
+}
+
+fn without_trailing_zeros(number: &str) -> &str {
+ if !number.contains('.') {
+ return number;
+ }
+ number.trim_end_matches('0').trim_end_matches('.')
+}
+
+/// The quadratic curves that stand for a conic: the conic halved n times, with n the smallest number for
+/// which the pieces are within the tolerance of it. The quadratic curve with the control points of a conic
+/// of weight w is furthest from it halfway, by (1 - w) / (4 (1 + w)) times the length of p0 - 2 p1 + p2,
+/// and each halving cuts that distance to about a quarter.
+fn quads_for_conic(points: [FloatPoint; 3], weight: f32) -> Vec<(FloatPoint, FloatPoint)> {
+ let conic = (points.map(Point::from_float), f64::from(weight));
+ let ([p0, p1, p2], weight) = conic;
+ let mut distance = (1.0 - weight).abs() / (4.0 * (1.0 + weight)) * p0.minus(p1.scaled(2.0)).plus(p2).length();
+ let mut depth = 0;
+ while depth < MAXIMUM_CONIC_SPLIT_DEPTH && distance > CONIC_TO_QUADS_TOLERANCE {
+ distance /= 4.0;
+ depth += 1;
+ }
+
+ let mut pieces = vec![conic];
+ for _ in 0..depth {
+ pieces = pieces
+ .iter()
+ .flat_map(|piece| {
+ let (first, second) = halve_conic(*piece);
+ [first, second]
+ })
+ .collect();
+ }
+ let piece_count = pieces.len();
+ pieces
+ .iter()
+ .enumerate()
+ .map(|(index, ([_, control, end], _))| {
+ // The end of the whole conic stays exactly where it is.
+ let end = if index + 1 == piece_count {
+ points[2]
+ } else {
+ end.to_float()
+ };
+ (control.to_float(), end)
+ })
+ .collect()
+}
+
+/// The two halves of a conic, each with the weight that keeps the weights of its ends at 1. In
+/// homogeneous coordinates, a conic is a quadratic curve, which halves as one.
+fn halve_conic(([p0, p1, p2], weight): ([Point; 3], f64)) -> (([Point; 3], f64), ([Point; 3], f64)) {
+ let lift = |point: Point, w: f64| (point.x * w, point.y * w, w);
+ let middle_of = |a: (f64, f64, f64), b: (f64, f64, f64)| {
+ (
+ a.0 + (b.0 - a.0) * 0.5,
+ a.1 + (b.1 - a.1) * 0.5,
+ a.2 + (b.2 - a.2) * 0.5,
+ )
+ };
+ let project = |h: (f64, f64, f64)| Point::new(h.0 / h.2, h.1 / h.2);
+ let (h0, h1, h2) = (lift(p0, 1.0), lift(p1, weight), lift(p2, 1.0));
+ let first_control = middle_of(h0, h1);
+ let second_control = middle_of(h1, h2);
+ let middle = middle_of(first_control, second_control);
+ let middle_point = project(middle);
+ (
+ (
+ [p0, project(first_control), middle_point],
+ first_control.2 / (h0.2 * middle.2).sqrt(),
+ ),
+ (
+ [middle_point, project(second_control), p2],
+ second_control.2 / (middle.2 * h2.2).sqrt(),
+ ),
+ )
+}