Skip to content

Truly independent web browser

LibGfx: Add a native Path to libgfx_rust

Aliaksandr Kalenika068a24c5846
diff --git a/Libraries/LibGfx/Rust/src/lib.rs b/Libraries/LibGfx/Rust/src/lib.rs
index 1aa1dcc17f8..b6f44c21e3c 100644
--- a/Libraries/LibGfx/Rust/src/lib.rs
+++ b/Libraries/LibGfx/Rust/src/lib.rs
@@ -58,6 +58,7 @@ const _: () = {
const fn assert_send_and_sync<T: Send + Sync>() {}
assert_send_and_sync::<font::FontHandle>();
assert_send_and_sync::<path::OwnedPath>();
+ assert_send_and_sync::<path::Path>();
assert_send_and_sync::<image_frame::ImageFrameHandle>();
assert_send_and_sync::<text_layout::GlyphBuffer>();
};
diff --git a/Libraries/LibGfx/Rust/src/path.rs b/Libraries/LibGfx/Rust/src/path.rs
index c77bc0b47b4..5d089b2097b 100644
--- a/Libraries/LibGfx/Rust/src/path.rs
+++ b/Libraries/LibGfx/Rust/src/path.rs
@@ -8,8 +8,12 @@ use std::ffi::c_void;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::ptr::NonNull;
+use std::sync::OnceLock;
use crate::geometry::{FloatPoint, FloatSize};
+use crate::matrix::AffineTransform;
+use crate::paint_enums::WindingRule;
+use geometry::PathGeometry;
mod arcs;
mod curves;
@@ -343,6 +347,188 @@ pub struct StrokeStyle {
pub dash_offset: f32,
}
+/// A path, with the rules of `Gfx::Path` for each operation.
+pub struct Path {
+ geometry: PathGeometry,
+ // A process-unique, never-reused identity, so that consumers that hold a copied snapshot can
+ // recognize an unchanged path without comparing contents. It is taken when first asked for, and a
+ // change to the path drops it.
+ identity: OnceLock<u64>,
+}
+
+impl Default for Path {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl std::fmt::Debug for Path {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter
+ .debug_struct("Path")
+ .field("identity", &self.identity.get())
+ .finish()
+ }
+}
+
+impl Path {
+ pub fn new() -> Self {
+ Self::from_geometry(PathGeometry::new())
+ }
+
+ fn from_geometry(geometry: PathGeometry) -> Self {
+ Self {
+ geometry,
+ identity: OnceLock::new(),
+ }
+ }
+
+ fn geometry_mut(&mut self) -> &mut PathGeometry {
+ self.identity.take();
+ &mut self.geometry
+ }
+
+ #[inline]
+ pub fn identity(&self) -> u64 {
+ // The counter is LibGfx's: this crate is compiled into more than one library, and a counter
+ // here would let each of them hand out the same identities. See `LibGfx/RustProcessState.cpp`.
+ // SAFETY: The counter is an atomic on the other side of the boundary.
+ *self
+ .identity
+ .get_or_init(|| unsafe { ladybird_gfx_process_next_path_identity() })
+ }
+
+ pub fn move_to(&mut self, point: FloatPoint) {
+ self.geometry_mut().move_to(point);
+ }
+
+ pub fn line_to(&mut self, point: FloatPoint) {
+ self.geometry_mut().line_to(point);
+ }
+
+ pub fn quadratic_bezier_curve_to(&mut self, through: FloatPoint, point: FloatPoint) {
+ self.geometry_mut().quadratic_bezier_curve_to(through, point);
+ }
+
+ pub fn cubic_bezier_curve_to(&mut self, c1: FloatPoint, c2: FloatPoint, point: FloatPoint) {
+ self.geometry_mut().cubic_bezier_curve_to(c1, c2, 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: FloatSize,
+ x_axis_rotation: f32,
+ large_arc: bool,
+ sweep: bool,
+ ) {
+ self.geometry_mut()
+ .elliptical_arc_to(point, (radii.width, radii.height), x_axis_rotation, large_arc, sweep);
+ }
+
+ pub fn arc_to(&mut self, point: FloatPoint, radius: f32, large_arc: bool, sweep: bool) {
+ self.geometry_mut().arc_to(point, radius, large_arc, sweep);
+ }
+
+ pub fn close(&mut self) {
+ self.geometry_mut().close();
+ }
+
+ /// Adds all the subpaths of the other path to this one.
+ pub fn append_path(&mut self, other: &Path) {
+ self.geometry_mut().append_path(&other.geometry);
+ }
+
+ pub fn set_fill_rule(&mut self, fill_rule: WindingRule) {
+ self.geometry_mut().set_fill_rule(fill_rule);
+ }
+
+ /// Whether the path has no current point, which Gfx::Path::is_empty() calls empty.
+ pub fn is_empty(&self) -> bool {
+ self.geometry.is_empty()
+ }
+
+ pub fn last_point(&self) -> FloatPoint {
+ self.geometry.last_point()
+ }
+
+ pub fn bounding_box(&self) -> [f32; 4] {
+ self.geometry.bounding_box()
+ }
+
+ pub fn length(&self) -> f32 {
+ measure::length(&self.geometry)
+ }
+
+ /// The point at the given distance along the path, followed by the path's tangent there.
+ pub fn point_at_length(&self, distance: f32) -> Option<[f32; 4]> {
+ measure::point_at_length(&self.geometry, distance)
+ .map(|(point, tangent)| [point.x, point.y, tangent.x, tangent.y])
+ }
+
+ pub fn contains(&self, x: f32, y: f32, winding_rule: WindingRule) -> bool {
+ hit_test::contains(&self.geometry, x, y, winding_rule)
+ }
+
+ /// The outline of the area that stroking this path with the given style covers, as a path to fill with the
+ /// nonzero winding rule.
+ pub fn stroke_to_fill(&self, style: &StrokeStyle) -> Path {
+ Self::from_geometry(stroke::stroke_to_fill(
+ &self.geometry,
+ &stroke::StrokeStyle {
+ thickness: style.thickness,
+ cap_style: style.cap_style,
+ join_style: style.join_style,
+ miter_limit: style.miter_limit,
+ dash_array: &style.dash_array,
+ dash_offset: style.dash_offset,
+ },
+ ))
+ }
+
+ pub fn copy_transformed(&self, affine_values: [f32; 6]) -> Path {
+ Self::from_geometry(
+ self.geometry
+ .copy_transformed(AffineTransform { values: affine_values }),
+ )
+ }
+
+ pub fn to_svg_string(&self) -> String {
+ svg_text::to_svg_string(&self.geometry)
+ }
+
+ pub fn serialize_to_bytes(&self) -> Vec<u8> {
+ encoding::encode(&self.geometry)
+ }
+
+ /// The path that the bytes describe. Bytes that describe no path give an empty path.
+ pub fn from_serialized_bytes(bytes: &[u8]) -> Path {
+ Self::from_geometry(encoding::decode(bytes).unwrap_or_default())
+ }
+
+ /// The contours of the path, as C++ reads them, valid until the path changes or is dropped.
+ pub fn geometry_data(&self) -> ffi::PathGeometryData {
+ ffi::PathGeometryData::of(&self.geometry)
+ }
+}
+
+/// A copy of the path, which has an identity of its own.
+impl Clone for Path {
+ fn clone(&self) -> Self {
+ Self::from_geometry(self.geometry.clone())
+ }
+}
+
+impl PartialEq for Path {
+ fn eq(&self, other: &Self) -> bool {
+ std::ptr::eq(self, other) || self.geometry.has_same_contours(&other.geometry)
+ }
+}
+
+// The contours are compared bit for bit, which is reflexive even for NaN.
+impl Eq for Path {}
+
/// The sole owner of a heap-allocated `Gfx::Path`, destroying it on drop.
pub struct OwnedPath {
raw: NonNull<c_void>,
diff --git a/Libraries/LibGfx/Rust/src/path/ffi.rs b/Libraries/LibGfx/Rust/src/path/ffi.rs
index c269eb15e6a..3381822c59b 100644
--- a/Libraries/LibGfx/Rust/src/path/ffi.rs
+++ b/Libraries/LibGfx/Rust/src/path/ffi.rs
@@ -504,26 +504,31 @@ pub unsafe extern "C" fn path_geometry_equals(a: *const PathGeometry, b: *const
unsafe { &*a }.has_same_contours(unsafe { &*b })
}
+impl PathGeometryData {
+ pub fn of(geometry: &PathGeometry) -> Self {
+ let (verbs, points, conic_weights) = if geometry.has_geometry() {
+ (geometry.verbs(), geometry.points(), geometry.conic_weights())
+ } else {
+ (&[][..], &[][..], &[][..])
+ };
+ Self {
+ 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
/// `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,
- };
+ let data = PathGeometryData::of(unsafe { &*path });
// SAFETY: The caller passes room for the data.
unsafe { std::ptr::write(out_data, data) };
}