Skip to main content

repose_core/
shape.rs

1//! Compose-style shapes and their resolution against a layout [`Rect`].
2//!
3//! A [`Shape`] is authored in density-independent pixels (or as a relative
4//! percentage) and is resolved once layout has produced a px-space [`Rect`].
5//! The resolved form, [`ResolvedShape`], is what the paint layer consumes.
6
7use std::sync::Arc;
8
9use crate::geometry::Rect;
10use crate::units::{Dp, Px};
11
12/// Corner radii order used by [`ResolvedShape::Rect`] and [`Shape::Rounded`]:
13/// `[top_left, top_right, bottom_right, bottom_left]` (CSS order).
14pub type CornerRadii = [Dp; 4];
15
16/// A single command of a [`ShapePath`], in Dp-local coordinates relative to the
17/// element's top-left corner. The paint layer converts these to px with the
18/// ambient density and adds the resolved offset.
19#[derive(Clone, Debug, PartialEq)]
20pub enum PathCommand {
21    /// Start a new subpath at `(x, y)`.
22    MoveTo(Dp, Dp),
23    /// Append a straight line to `(x, y)`.
24    LineTo(Dp, Dp),
25    /// Append a cubic Bezier with control points `c1`, `c2` and endpoint `end`.
26    CubicTo {
27        c1: (Dp, Dp),
28        c2: (Dp, Dp),
29        end: (Dp, Dp),
30    },
31    /// Close the current subpath back to its starting point.
32    Close,
33}
34
35/// An arbitrary shape described by path commands in Dp-local space.
36#[derive(Clone, Debug, Default, PartialEq)]
37pub struct ShapePath {
38    pub commands: Vec<PathCommand>,
39}
40
41impl ShapePath {
42    pub fn new() -> Self {
43        Self::default()
44    }
45
46    pub fn move_to(mut self, x: Dp, y: Dp) -> Self {
47        self.commands.push(PathCommand::MoveTo(x, y));
48        self
49    }
50
51    pub fn line_to(mut self, x: Dp, y: Dp) -> Self {
52        self.commands.push(PathCommand::LineTo(x, y));
53        self
54    }
55
56    pub fn cubic_to(mut self, c1: (Dp, Dp), c2: (Dp, Dp), end: (Dp, Dp)) -> Self {
57        self.commands.push(PathCommand::CubicTo { c1, c2, end });
58        self
59    }
60
61    pub fn close(mut self) -> Self {
62        self.commands.push(PathCommand::Close);
63        self
64    }
65}
66
67/// A Compose-style shape.
68#[derive(Clone, Debug, Default, PartialEq)]
69pub enum Shape {
70    /// A sharp-cornered rectangle filling the bounds.
71    #[default]
72    Rectangle,
73    /// A rectangle with independent per-corner radii, in [`Dp`].
74    Rounded { radii: CornerRadii },
75    /// A rounded shape whose radius is `percent / 100` of half the rect's
76    /// smaller side (0 = sharp rectangle, 100 = same radius as [`Shape::Circle`]).
77    /// The value is clamped to `0.0..=100.0`.
78    Percent(f32),
79    /// A circle/ellipse inscribed in the bounds (Compose's `CircleShape`).
80    Circle,
81    /// An arbitrary path in Dp-local coordinates, offset to the rect origin.
82    Path(Arc<ShapePath>),
83}
84
85impl Shape {
86    /// Uniform-radius rounded rectangle.
87    pub fn rounded(radius: Dp) -> Self {
88        Shape::Rounded { radii: [radius; 4] }
89    }
90
91    /// Arbitrary path shape.
92    pub fn path(path: ShapePath) -> Self {
93        Shape::Path(Arc::new(path))
94    }
95
96    /// Resolve this shape against a px-space layout rect.
97    pub fn resolve(&self, rect: Rect) -> ResolvedShape {
98        match self {
99            Shape::Rectangle => ResolvedShape::Rect([Px::ZERO; 4]),
100            Shape::Rounded { radii } => ResolvedShape::Rect([
101                radii[0].to_px(),
102                radii[1].to_px(),
103                radii[2].to_px(),
104                radii[3].to_px(),
105            ]),
106            Shape::Percent(percent) => {
107                let half_min = (rect.w.min(rect.h) * 0.5).max(0.0);
108                let radius = Px(half_min * (percent.clamp(0.0, 100.0) / 100.0));
109                ResolvedShape::Rect([radius; 4])
110            }
111            Shape::Circle => ResolvedShape::Ellipse,
112            Shape::Path(path) => ResolvedShape::Path {
113                path: path.clone(),
114                offset: (Px(rect.x), Px(rect.y)),
115            },
116        }
117    }
118}
119
120/// A [`Shape`] resolved to px-space against a concrete layout [`Rect`].
121#[derive(Clone, Debug, PartialEq)]
122pub enum ResolvedShape {
123    /// Corner radii in px, ordered `[top_left, top_right, bottom_right,
124    /// bottom_left]`. Zero radii mean a sharp rectangle.
125    Rect([Px; 4]),
126    /// An ellipse inscribed in the scene node's rect.
127    Ellipse,
128    /// A Dp-local path plus its px-space translation (the rect's origin).
129    Path {
130        path: Arc<ShapePath>,
131        offset: (Px, Px),
132    },
133}