Skip to main content

gpui_material_foundation/
shape.rs

1mod clip;
2mod morph;
3mod polygon;
4#[cfg(test)]
5mod tests;
6
7use std::{
8    cell::{OnceCell, RefCell},
9    rc::Rc,
10};
11
12use gpui::{
13    Bounds, FillOptions, FillRule, Hsla, Path, PathBuilder, PathStyle, Pixels, Point, Window,
14    point, px, size,
15};
16use gpui_material_theme::{CornerShape, Direction, MaterialShape};
17use polymorpher::{Cubic, geometry::Point as PolygonPoint};
18
19use crate::feedback::{FOCUS_RING_OUTER_OFFSET, FocusRingPlacement};
20use clip::{
21    FillMesh, bounds_overlap, clip_convex_polygon_fill, clip_mesh_fill, clip_polygon_to_rect,
22    clip_rect_fill, clipped_ripple, contains_fill, cross, flatten_cubic, polygon_area,
23    rect_is_valid, segment_distance_sq, triangle_disjoint_from_rect,
24};
25use polygon::rounded_rect_cubics;
26
27pub use morph::{PolygonMorph, ShapeMorph, ShapeMorphSequence};
28pub use polygon::ShapePolygon;
29
30const MAX_STROKE_CACHE_ENTRIES: usize = 8;
31
32/// How a normalized polygon contour maps into layout bounds.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
34pub enum ShapeFit {
35    /// Fits the centered unit square inside the shorter side while preserving aspect ratio.
36    #[default]
37    Contain,
38    /// Scales independently to fill the width and height of the bounds.
39    Stretch,
40}
41
42type StrokeCacheEntry = ((u32, u32), Path);
43type ShadowCacheEntry = (u32, u32, [Option<Path>; 3]);
44type ExteriorMaskCacheEntry = ([u32; 4], Path);
45
46#[derive(Default)]
47struct ShapeCaches {
48    mesh: OnceCell<FillMesh>,
49    strokes: RefCell<Vec<StrokeCacheEntry>>,
50    shadows: RefCell<Option<ShadowCacheEntry>>,
51    exterior_mask: RefCell<Option<ExteriorMaskCacheEntry>>,
52}
53
54/// A prepared shape with a curve path for painting and lazily built caches for clipping,
55/// stroking, shadows, exterior masking, and hit testing.
56#[derive(Clone)]
57pub struct Shape {
58    outline: Outline,
59    fill: Path,
60    caches: Rc<ShapeCaches>,
61}
62
63#[derive(Clone)]
64struct Outline {
65    cubics: Vec<Cubic>,
66    bounds: Bounds<Pixels>,
67    fit: ShapeFit,
68    rotation: f32,
69    pivot: PolygonPoint,
70    scale: f32,
71    rounded_rect: Option<(CornerShape, Direction)>,
72}
73
74impl Outline {
75    fn projection_params(&self) -> Option<(Point<Pixels>, Pixels, Pixels, f32, f32)> {
76        let size = self.bounds.size;
77        let side = size.width.min(size.height);
78        if !(side > px(0.) && side < px(f32::INFINITY))
79            || !self.rotation.is_finite()
80            || !self.scale.is_finite()
81            || self.scale <= 0.
82            || self.cubics.is_empty()
83        {
84            return None;
85        }
86        let center = self.bounds.center();
87        let (width, height) = match self.fit {
88            ShapeFit::Contain => (side, side),
89            ShapeFit::Stretch => (size.width, size.height),
90        };
91        let (sin, cos) = self.rotation.sin_cos();
92        Some((center, width, height, sin, cos))
93    }
94
95    fn project_point(
96        &self,
97        p: PolygonPoint,
98        center: Point<Pixels>,
99        width: Pixels,
100        height: Pixels,
101        sin: f32,
102        cos: f32,
103    ) -> Point<Pixels> {
104        let dx = p.x - self.pivot.x;
105        let dy = p.y - self.pivot.y;
106        let (rx, ry) = if self.rotation == 0. {
107            (dx, dy)
108        } else {
109            (cos * dx - sin * dy, sin * dx + cos * dy)
110        };
111        center + point(width * (self.scale * rx), height * (self.scale * ry))
112    }
113
114    fn add_to_builder(&self, builder: &mut PathBuilder) -> bool {
115        let Some((center, width, height, sin, cos)) = self.projection_params() else {
116            return false;
117        };
118        let project = |p| self.project_point(p, center, width, height, sin, cos);
119        builder.move_to(project(self.cubics[0].anchor0()));
120        for cubic in &self.cubics {
121            builder.cubic_bezier_to(
122                project(cubic.anchor1()),
123                project(cubic.control0()),
124                project(cubic.control1()),
125            );
126        }
127        builder.close();
128        true
129    }
130
131    fn flatten_mesh(&self) -> FillMesh {
132        let Some((center, width, height, sin, cos)) = self.projection_params() else {
133            return FillMesh::empty(self.bounds.origin);
134        };
135        let project = |p| self.project_point(p, center, width, height, sin, cos);
136        let mut contour = Vec::with_capacity(self.cubics.len() * 4);
137        let start = project(self.cubics[0].anchor0());
138        contour.push(start);
139        for cubic in &self.cubics {
140            flatten_cubic(
141                project(cubic.anchor0()),
142                project(cubic.control0()),
143                project(cubic.control1()),
144                project(cubic.anchor1()),
145                &mut contour,
146            );
147        }
148        if self.rounded_rect.is_some() {
149            FillMesh::from_convex_contour(&contour)
150        } else {
151            FillMesh::from_contour(&contour)
152        }
153    }
154
155    fn outset(&self, delta: f32) -> Option<Self> {
156        if delta == 0. {
157            return Some(self.clone());
158        }
159        let expanded = Bounds::new(
160            self.bounds.origin + point(px(-delta), px(-delta)),
161            size(
162                self.bounds.size.width + px(delta * 2.),
163                self.bounds.size.height + px(delta * 2.),
164            ),
165        );
166        let width = f32::from(expanded.size.width);
167        let height = f32::from(expanded.size.height);
168        if !width.is_finite() || !height.is_finite() || width <= 0. || height <= 0. {
169            return None;
170        }
171        if let Some((corners, direction)) = self.rounded_rect {
172            let adjusted = match corners {
173                CornerShape::Full => CornerShape::Full,
174                CornerShape::Radii(radii) => {
175                    CornerShape::Radii(radii.map(|r| if r > 0. { (r + delta).max(0.) } else { 0. }))
176                }
177            };
178            let cubics = rounded_rect_cubics(width, height, adjusted, direction)?;
179            return Some(Self {
180                cubics,
181                bounds: expanded,
182                fit: ShapeFit::Stretch,
183                rotation: 0.,
184                pivot: PolygonPoint::splat(0.5),
185                scale: 1.,
186                rounded_rect: Some((adjusted, direction)),
187            });
188        }
189        Some(Self {
190            bounds: expanded,
191            ..self.clone()
192        })
193    }
194
195    fn path(&self, mut builder: PathBuilder) -> Option<Path> {
196        if !self.add_to_builder(&mut builder) {
197            return None;
198        }
199        builder.build().ok()
200    }
201}
202
203impl Shape {
204    /// Resolves Material corner radii against the actual bounds and direction.
205    pub fn rounded(
206        bounds: Bounds<Pixels>,
207        corners: CornerShape,
208        direction: Direction,
209    ) -> Option<Self> {
210        let width = f32::from(bounds.size.width);
211        let height = f32::from(bounds.size.height);
212        let cubics = rounded_rect_cubics(width, height, corners, direction)?;
213        Self::new(Outline {
214            cubics,
215            bounds,
216            fit: ShapeFit::Stretch,
217            rotation: 0.,
218            pivot: PolygonPoint::splat(0.5),
219            scale: 1.,
220            rounded_rect: Some((corners, direction)),
221        })
222    }
223
224    /// Prepares one of the 35 Material 3 Expressive shapes fitted inside `bounds`.
225    pub fn material(bounds: Bounds<Pixels>, shape: MaterialShape) -> Option<Self> {
226        ShapePolygon::material(shape).to_shape(bounds)
227    }
228
229    /// Prepares any reusable [`ShapePolygon`] inside `bounds`.
230    pub fn polygon(bounds: Bounds<Pixels>, polygon: &ShapePolygon, fit: ShapeFit) -> Option<Self> {
231        polygon.to_shape_with(bounds, fit, 0.)
232    }
233
234    fn from_cubics(
235        cubics: Vec<Cubic>,
236        bounds: Bounds<Pixels>,
237        fit: ShapeFit,
238        rotation_radians: f32,
239    ) -> Option<Self> {
240        if !rotation_radians.is_finite() {
241            return None;
242        }
243        Self::new(Outline {
244            cubics,
245            bounds,
246            fit,
247            rotation: rotation_radians,
248            pivot: PolygonPoint::splat(0.5),
249            scale: 1.,
250            rounded_rect: None,
251        })
252    }
253
254    fn new(outline: Outline) -> Option<Self> {
255        let fill = outline.path(PathBuilder::fill())?;
256        Some(Self {
257            outline,
258            fill,
259            caches: Rc::new(ShapeCaches::default()),
260        })
261    }
262
263    fn mesh(&self) -> &FillMesh {
264        self.caches.mesh.get_or_init(|| self.outline.flatten_mesh())
265    }
266
267    /// Returns the laid-out bounds that this shape was fitted into.
268    pub fn bounds(&self) -> Bounds<Pixels> {
269        self.outline.bounds
270    }
271
272    /// Returns the tight bounding box of this shape's flattened fill contour.
273    pub fn fill_bounds(&self) -> Bounds<Pixels> {
274        self.mesh().bounds
275    }
276
277    /// Returns the prepared GPUI fill [`Path`] for this shape.
278    pub fn fill_path(&self) -> &Path {
279        &self.fill
280    }
281
282    /// Builds a stroked outline path for this shape at the requested logical pixel width.
283    pub fn stroke_path(&self, width: Pixels) -> Option<Path> {
284        self.stroke_path_outset(width, px(0.))
285    }
286
287    /// Builds a stroked outline path expanded outward by `outset` (or inset when negative).
288    ///
289    /// Cached per `(width, outset)` pair so borders and focus rings hit simultaneously.
290    pub fn stroke_path_outset(&self, width: Pixels, outset: Pixels) -> Option<Path> {
291        let raw_width = f32::from(width);
292        let raw_outset = f32::from(outset);
293        if !raw_width.is_finite() || raw_width <= 0. || !raw_outset.is_finite() {
294            return None;
295        }
296        let key = (raw_width.to_bits(), raw_outset.to_bits());
297        if let Some((_, cached)) = self
298            .caches
299            .strokes
300            .borrow()
301            .iter()
302            .find(|(cached_key, _)| *cached_key == key)
303        {
304            return Some(cached.clone());
305        }
306        let outline = self.outline.outset(raw_outset)?;
307        let path = outline.path(PathBuilder::stroke(width))?;
308        let mut strokes = self.caches.strokes.borrow_mut();
309        if strokes.len() >= MAX_STROKE_CACHE_ENTRIES {
310            strokes.remove(0);
311        }
312        strokes.push((key, path.clone()));
313        Some(path)
314    }
315
316    /// Returns whether `position` lies inside this shape's fill mesh.
317    pub fn contains(&self, position: Point<Pixels>) -> bool {
318        contains_fill(self.mesh(), position)
319    }
320
321    /// Shape-aware hit test against the fill mesh with an optional outward `slop`
322    /// tolerance in logical pixels. Non-finite coordinates return `false`.
323    pub fn hit_test(&self, position: Point<Pixels>, slop: Pixels) -> bool {
324        if !f32::from(position.x).is_finite() || !f32::from(position.y).is_finite() {
325            return false;
326        }
327        if self.contains(position) {
328            return true;
329        }
330        let slop = f32::from(slop);
331        if !slop.is_finite() || slop <= 0. {
332            return false;
333        }
334        let mesh = self.mesh();
335        let min_x = f32::from(mesh.bounds.left()) - slop;
336        let max_x = f32::from(mesh.bounds.right()) + slop;
337        let min_y = f32::from(mesh.bounds.top()) - slop;
338        let max_y = f32::from(mesh.bounds.bottom()) + slop;
339        let px_x = f32::from(position.x);
340        let px_y = f32::from(position.y);
341        if px_x < min_x || px_x > max_x || px_y < min_y || px_y > max_y {
342            return false;
343        }
344        let limit_sq = slop * slop;
345        mesh.triangles.iter().any(|&[a, b, c]| {
346            if cross(b - a, c - a).abs() <= f32::EPSILON {
347                return false;
348            }
349            segment_distance_sq(position, a, b) <= limit_sq
350                || segment_distance_sq(position, b, c) <= limit_sq
351                || segment_distance_sq(position, c, a) <= limit_sq
352        })
353    }
354
355    /// Returns whether this shape's fill mesh intersects the axis-aligned rectangle `rect`.
356    pub fn intersects_bounds(&self, rect: Bounds<Pixels>) -> bool {
357        let mesh = self.mesh();
358        if !rect_is_valid(rect) || !bounds_overlap(mesh.bounds, rect) {
359            return false;
360        }
361        let mut polygon = Vec::with_capacity(8);
362        let mut scratch = Vec::with_capacity(8);
363        for &[a, b, c] in &mesh.triangles {
364            if triangle_disjoint_from_rect([a, b, c], rect)
365                || cross(b - a, c - a).abs() <= f32::EPSILON
366            {
367                continue;
368            }
369            polygon.clear();
370            polygon.extend([a, b, c]);
371            clip_polygon_to_rect(&mut polygon, &mut scratch, rect);
372            if polygon.len() >= 3 && polygon_area(&polygon).abs() > f32::EPSILON {
373                return true;
374            }
375        }
376        false
377    }
378
379    /// Clips an axis-aligned rectangle against this shape's fill mesh.
380    pub fn clip_rect(&self, rect: Bounds<Pixels>) -> Option<Path> {
381        clip_rect_fill(self.mesh(), rect).to_path()
382    }
383
384    /// Clips a disc centered at `origin` with logical `radius` against this shape's fill mesh.
385    pub fn clip_disc(&self, origin: Point<Pixels>, radius: Pixels) -> Option<Path> {
386        clipped_ripple(self.mesh(), origin, radius).to_path()
387    }
388
389    /// Clips a convex polygon (in either winding order) against this shape's fill mesh.
390    pub fn clip_convex_polygon(&self, vertices: &[Point<Pixels>]) -> Option<Path> {
391        clip_convex_polygon_fill(self.mesh(), vertices).to_path()
392    }
393
394    /// Clips another [`Shape`] (convex or concave) against this shape's fill mesh,
395    /// returning the exact geometric intersection.
396    pub fn clip_shape(&self, source: &Shape) -> Option<Path> {
397        clip_mesh_fill(self.mesh(), source.mesh()).to_path()
398    }
399
400    /// Builds an EvenOdd exterior mask representing `outer \ self` within `outer`.
401    ///
402    /// Because GPUI's native `ContentMask` is rectangular, painting this exterior mask
403    /// in a uniform parent backdrop color visually clips arbitrary child elements to the
404    /// exact non-rectangular shape contour.
405    pub fn exterior_mask(&self, outer: Bounds<Pixels>) -> Option<Path> {
406        if !rect_is_valid(outer) {
407            return None;
408        }
409        let key = [
410            f32::from(outer.origin.x).to_bits(),
411            f32::from(outer.origin.y).to_bits(),
412            f32::from(outer.size.width).to_bits(),
413            f32::from(outer.size.height).to_bits(),
414        ];
415        if let Some((cached_key, cached)) = self.caches.exterior_mask.borrow().as_ref()
416            && *cached_key == key
417        {
418            return Some(cached.clone());
419        }
420        let mesh = self.mesh();
421        let contained = mesh.bounds.left() >= outer.left()
422            && mesh.bounds.right() <= outer.right()
423            && mesh.bounds.top() >= outer.top()
424            && mesh.bounds.bottom() <= outer.bottom();
425        let mut builder = PathBuilder::fill().with_style(PathStyle::Fill(FillOptions {
426            fill_rule: FillRule::EvenOdd,
427        }));
428        builder.move_to(outer.origin);
429        builder.line_to(outer.top_right());
430        builder.line_to(outer.bottom_right());
431        builder.line_to(outer.bottom_left());
432        builder.close();
433        if contained {
434            if !self.outline.add_to_builder(&mut builder) {
435                return None;
436            }
437        } else {
438            let interior = clip_rect_fill(mesh, outer);
439            for &[a, b, c] in &interior.triangles {
440                if cross(b - a, c - a).abs() <= f32::EPSILON {
441                    continue;
442                }
443                builder.move_to(a);
444                builder.line_to(b);
445                builder.line_to(c);
446                builder.close();
447            }
448        }
449        let path = builder.build().ok()?;
450        *self.caches.exterior_mask.borrow_mut() = Some((key, path.clone()));
451        Some(path)
452    }
453
454    /// Paints the fill path with `color`.
455    pub fn paint(&self, color: Hsla, window: &mut Window) {
456        window.paint_path(self.fill.clone(), color);
457    }
458
459    /// Paints a stroked outline around this shape.
460    pub fn paint_stroke(&self, width: Pixels, color: Hsla, window: &mut Window) {
461        if let Some(path) = self.stroke_path(width) {
462            window.paint_path(path, color);
463        }
464    }
465
466    /// Paints `source` clipped to this shape's fill mesh.
467    pub fn paint_clipped_shape(&self, source: &Shape, color: Hsla, window: &mut Window) {
468        if let Some(clipped) = self.clip_shape(source) {
469            window.paint_path(clipped, color);
470        }
471    }
472
473    /// Paints `rect` clipped to this shape's fill mesh.
474    pub fn paint_clipped_rect(&self, rect: Bounds<Pixels>, color: Hsla, window: &mut Window) {
475        if let Some(clipped) = self.clip_rect(rect) {
476            window.paint_path(clipped, color);
477        }
478    }
479
480    /// Paints a disc clipped to this shape's fill mesh.
481    pub fn paint_clipped_disc(
482        &self,
483        origin: Point<Pixels>,
484        radius: Pixels,
485        color: Hsla,
486        window: &mut Window,
487    ) {
488        self.paint_ripple(origin, radius, color, window);
489    }
490
491    /// Paints the EvenOdd exterior mask `outer \ self` in `backdrop` to visually clip
492    /// overflowing children to this shape on a uniform background.
493    pub fn paint_backdrop_mask(&self, outer: Bounds<Pixels>, backdrop: Hsla, window: &mut Window) {
494        if let Some(mask) = self.exterior_mask(outer) {
495            window.paint_path(mask, backdrop);
496        }
497    }
498
499    /// Approximates a shape-matched elevation shadow with three translucent fills.
500    pub fn paint_shadow(&self, elevation: f32, scale: f32, shadow: Hsla, window: &mut Window) {
501        let dp = elevation * scale;
502        if !dp.is_finite() || dp <= 0. || !scale.is_finite() || scale <= 0. {
503            return;
504        }
505        let key = (elevation.to_bits(), scale.to_bits());
506        let alphas = [0.08, 0.10, 0.12];
507        let mut cache = self.caches.shadows.borrow_mut();
508        let paths = match cache.as_ref() {
509            Some((elev_bits, scale_bits, paths)) if *elev_bits == key.0 && *scale_bits == key.1 => {
510                paths
511            }
512            _ => {
513                let specs = [
514                    (dp * 0.45, dp * 0.35),
515                    (dp * 0.25, dp * 0.18),
516                    (scale.min(dp * 0.5), dp * 0.06),
517                ];
518                let built = specs.map(|(offset_y, spread)| {
519                    let expanded = Bounds::new(
520                        self.outline.bounds.origin + point(px(-spread), px(offset_y - spread)),
521                        size(
522                            self.outline.bounds.size.width + px(spread * 2.),
523                            self.outline.bounds.size.height + px(spread * 2.),
524                        ),
525                    );
526                    let layer = Outline {
527                        bounds: expanded,
528                        ..self.outline.clone()
529                    };
530                    layer.path(PathBuilder::fill())
531                });
532                *cache = Some((key.0, key.1, built));
533                &cache.as_ref().expect("shadow cache populated").2
534            }
535        };
536        for (path, alpha) in paths.iter().zip(alphas) {
537            if let Some(path) = path {
538                window.paint_path(path.clone(), shadow.opacity(alpha));
539            }
540        }
541    }
542
543    /// Computes the Material 3 focus ring stroke path for the given `width` and `placement`.
544    pub fn focus_ring_path(&self, width: Pixels, placement: FocusRingPlacement) -> Option<Path> {
545        let outset = match placement {
546            FocusRingPlacement::Outer => FOCUS_RING_OUTER_OFFSET + width * 0.5,
547            FocusRingPlacement::Inset => -width * 0.5,
548        };
549        self.stroke_path_outset(width, outset)
550            .or_else(|| self.stroke_path(width))
551    }
552
553    pub(crate) fn paint_ring(
554        &self,
555        width: Pixels,
556        placement: FocusRingPlacement,
557        color: Hsla,
558        window: &mut Window,
559    ) {
560        if let Some(path) = self.focus_ring_path(width, placement) {
561            window.paint_path(path, color);
562        }
563    }
564
565    pub(crate) fn paint_ripple(
566        &self,
567        origin: Point<Pixels>,
568        radius: Pixels,
569        color: Hsla,
570        window: &mut Window,
571    ) {
572        if let Some(path) = self.clip_disc(origin, radius) {
573            window.paint_path(path, color);
574        }
575    }
576}