Skip to main content

gpui_material_foundation/
surface.rs

1mod control;
2mod elevation;
3mod passive;
4
5use std::rc::Rc;
6
7use gpui::{
8    AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, ParentElement,
9    Pixels, RenderOnce, SharedString, StyleRefinement, Styled, Window, px,
10};
11use gpui_material_theme::{ColorRole, CornerShape, Direction, Elevation, MaterialTheme};
12
13use crate::{InteractionSource, Shape, ShapeFit, ShapePolygon, current_material_theme};
14
15pub use elevation::{
16    color, elevation_shadow_pair, elevation_shadows, resolve_color_spec, resolve_edges, scrim_color,
17};
18
19/// An outline in logical pixels, drawn around the surface's shape.
20#[derive(Clone, Copy, Debug, PartialEq)]
21pub struct SurfaceBorder {
22    /// Stroke width in logical pixels.
23    pub width: Pixels,
24    /// Stroke color in HSLA.
25    pub color: Hsla,
26}
27
28/// Customizes the Material feedback painted by one interactive surface.
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub struct SurfaceFeedback {
31    /// Whether to paint hover, focus, and pressed state-layer tints (defaults to `true`).
32    pub state_layer: bool,
33    /// Whether to paint pointer-originated ink ripples on press (defaults to `true`).
34    pub ripple: bool,
35    /// Whether to paint a Material keyboard focus ring (defaults to `true`).
36    pub focus_ring: bool,
37    /// Optional explicit ink color for state layers and ripples; defaults to the resolved content color.
38    pub ink: Option<Hsla>,
39    /// Optional explicit focus ring color; defaults to the theme's secondary/focus token.
40    pub focus_color: Option<Hsla>,
41}
42
43impl Default for SurfaceFeedback {
44    fn default() -> Self {
45        Self {
46            state_layer: true,
47            ripple: true,
48            focus_ring: true,
49            ink: None,
50            focus_color: None,
51        }
52    }
53}
54
55#[derive(Clone, Copy)]
56enum SurfaceAction {
57    Activate,
58    Select(bool),
59    Check(bool),
60}
61
62type Activate = Rc<dyn Fn(&mut Window, &mut App)>;
63
64struct Control {
65    id: ElementId,
66    label: SharedString,
67    action: SurfaceAction,
68    activate: Option<Activate>,
69}
70
71/// A passive Material background or an interactive surface with arbitrary children.
72#[derive(IntoElement)]
73pub struct Surface {
74    style: StyleRefinement,
75    children: Vec<AnyElement>,
76    role: ColorRole,
77    container_color: Option<Hsla>,
78    content_color: Option<Hsla>,
79    inherit_content_color: bool,
80    shape: Option<CornerShape>,
81    polygon: Option<ShapePolygon>,
82    shape_fit: ShapeFit,
83    clip_backdrop: Option<Hsla>,
84    shape_hit_test: Option<bool>,
85    border: Option<SurfaceBorder>,
86    tonal_elevation: Elevation,
87    shadow_elevation: Elevation,
88    shadow_scale: f32,
89    theme: Option<Rc<MaterialTheme>>,
90    control: Option<Control>,
91    disabled: bool,
92    focus: Option<FocusHandle>,
93    feedback: SurfaceFeedback,
94    interaction_source: Option<Entity<InteractionSource>>,
95}
96
97impl Surface {
98    /// Creates a passive (non-interactive) Material surface filled with `role`.
99    pub fn new(role: ColorRole) -> Self {
100        Self {
101            style: StyleRefinement::default(),
102            children: Vec::new(),
103            role,
104            container_color: None,
105            content_color: None,
106            inherit_content_color: false,
107            shape: None,
108            polygon: None,
109            shape_fit: ShapeFit::Contain,
110            clip_backdrop: None,
111            shape_hit_test: None,
112            border: None,
113            tonal_elevation: Elevation::Level0,
114            shadow_elevation: Elevation::Level0,
115            shadow_scale: 1.,
116            theme: None,
117            control: None,
118            disabled: false,
119            focus: None,
120            feedback: SurfaceFeedback::default(),
121            interaction_source: None,
122        }
123    }
124
125    /// Creates an interactive clickable surface with button semantics and `on_activate` support.
126    pub fn clickable(
127        id: impl Into<ElementId>,
128        label: impl Into<SharedString>,
129        role: ColorRole,
130    ) -> Self {
131        Self::interactive(id, label, role, SurfaceAction::Activate)
132    }
133
134    /// Renders the caller's selection and requests activation through `on_activate`.
135    pub fn selectable(
136        id: impl Into<ElementId>,
137        label: impl Into<SharedString>,
138        role: ColorRole,
139        selected: bool,
140    ) -> Self {
141        Self::interactive(id, label, role, SurfaceAction::Select(selected))
142    }
143
144    /// Renders the caller's check state and requests the next value through `on_checked_change`.
145    pub fn toggleable(
146        id: impl Into<ElementId>,
147        label: impl Into<SharedString>,
148        role: ColorRole,
149        checked: bool,
150    ) -> Self {
151        Self::interactive(id, label, role, SurfaceAction::Check(checked))
152    }
153
154    fn interactive(
155        id: impl Into<ElementId>,
156        label: impl Into<SharedString>,
157        role: ColorRole,
158        action: SurfaceAction,
159    ) -> Self {
160        Self {
161            control: Some(Control {
162                id: id.into(),
163                label: label.into(),
164                action,
165                activate: None,
166            }),
167            ..Self::new(role)
168        }
169    }
170
171    /// Registers the activation callback for clickable and selectable surfaces.
172    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
173        if let Some(control) = &mut self.control {
174            control.activate = Some(Rc::new(handler));
175        }
176        self
177    }
178
179    /// Registers the toggled callback for surfaces constructed with [`Self::toggleable`],
180    /// passing the requested next checked state (`!checked`).
181    pub fn on_checked_change(
182        mut self,
183        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
184    ) -> Self {
185        if let Some(control) = &mut self.control
186            && let SurfaceAction::Check(checked) = control.action
187        {
188            control.activate = Some(Rc::new(move |window, cx| handler(!checked, window, cx)));
189        }
190        self
191    }
192
193    /// Disables pointer and keyboard interaction when `true`.
194    pub fn disabled(mut self, disabled: bool) -> Self {
195        self.disabled = disabled;
196        self
197    }
198
199    /// Associates a caller-owned GPUI [`FocusHandle`] with this interactive surface.
200    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
201        self.focus = Some(focus.clone());
202        self
203    }
204
205    /// Configures state-layer, ripple, and focus-ring feedback for this surface.
206    pub fn feedback(mut self, feedback: SurfaceFeedback) -> Self {
207        self.feedback = feedback;
208        self
209    }
210
211    /// Connects a shared [`InteractionSource`] entity so external views can observe
212    /// hover, focus, press, and drag states.
213    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
214        self.interaction_source = Some(source.clone());
215        self
216    }
217
218    /// Uses an explicit fill and inherits the foreground unless one is supplied.
219    pub fn container_color(mut self, color: Hsla) -> Self {
220        self.container_color = Some(color);
221        self
222    }
223
224    /// Sets the inherited foreground for this surface's children.
225    pub fn content_color(mut self, color: Hsla) -> Self {
226        self.content_color = Some(color);
227        self
228    }
229
230    /// Uses the ancestor text color unless this surface supplies an explicit foreground.
231    pub fn inherit_content_color(mut self, inherit: bool) -> Self {
232        self.inherit_content_color = inherit;
233        self
234    }
235
236    /// Applies a rounded-rectangle [`CornerShape`] to the surface, clearing any polygon shape.
237    pub fn shape(mut self, shape: CornerShape) -> Self {
238        self.shape = Some(shape);
239        self.polygon = None;
240        self
241    }
242
243    /// Uses any [`ShapePolygon`] (including [`MaterialShape`](gpui_material_theme::MaterialShape),
244    /// [`PolygonRole`](gpui_material_theme::PolygonRole), or sampled [`ShapeMorph`](crate::ShapeMorph)
245    /// outlines) for background painting, border stroke, shadow, clipping, and feedback.
246    ///
247    /// Interactive polygon surfaces default to shape-aware pointer hit testing unless
248    /// overridden with [`Self::shape_hit_test`].
249    pub fn polygon_shape(mut self, polygon: impl Into<ShapePolygon>) -> Self {
250        self.polygon = Some(polygon.into());
251        self.shape = None;
252        self
253    }
254
255    /// Chooses how a [`Self::polygon_shape`] maps into the laid-out surface bounds.
256    pub fn shape_fit(mut self, fit: ShapeFit) -> Self {
257        self.shape_fit = fit;
258        self
259    }
260
261    /// Visually clips overflowing children to the resolved shape contour by applying a
262    /// rectangular content mask and painting an EvenOdd exterior mask in `backdrop`.
263    /// Match `backdrop` to the uniform background behind this surface.
264    pub fn shape_clip_backdrop(mut self, backdrop: Hsla) -> Self {
265        self.clip_backdrop = Some(backdrop);
266        self
267    }
268
269    /// Controls whether pointer hover, press, and click activation require the cursor to
270    /// lie inside the resolved shape contour. Defaults to `true` for [`Self::polygon_shape`]
271    /// and `false` for rectangular or [`CornerShape`] surfaces. Keyboard and accessibility
272    /// activation remain available regardless of this setting.
273    pub fn shape_hit_test(mut self, enabled: bool) -> Self {
274        self.shape_hit_test = Some(enabled);
275        self
276    }
277
278    /// Draws an outline border around the resolved surface shape.
279    pub fn border(mut self, border: SurfaceBorder) -> Self {
280        self.border = Some(border);
281        self
282    }
283
284    /// Applies tonal surface-tint elevation (defaults to [`Elevation::Level0`]).
285    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
286        self.tonal_elevation = elevation;
287        self
288    }
289
290    /// Applies drop-shadow elevation (defaults to [`Elevation::Level0`]).
291    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
292        self.shadow_elevation = elevation;
293        self
294    }
295
296    /// Scales the offset and blur radius with an animated surface.
297    pub fn shadow_scale(mut self, scale: f32) -> Self {
298        self.shadow_scale = scale;
299        self
300    }
301
302    /// Uses an explicit window or subtree theme for this surface.
303    pub fn theme(mut self, theme: MaterialTheme) -> Self {
304        self.theme = Some(Rc::new(theme));
305        self
306    }
307}
308
309impl ParentElement for Surface {
310    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
311        self.children.extend(elements);
312    }
313}
314
315impl Styled for Surface {
316    fn style(&mut self) -> &mut StyleRefinement {
317        &mut self.style
318    }
319}
320
321#[derive(Clone)]
322pub(super) enum ResolvedShape {
323    Corners(CornerShape, Direction),
324    Polygon(ShapePolygon, ShapeFit),
325}
326
327impl ResolvedShape {
328    pub(super) fn build(&self, bounds: Bounds<Pixels>) -> Option<Shape> {
329        match self {
330            Self::Corners(shape, direction) => Shape::rounded(bounds, *shape, *direction),
331            Self::Polygon(polygon, fit) => Shape::polygon(bounds, polygon, *fit),
332        }
333    }
334}
335
336pub(super) struct PolygonPaint {
337    pub(super) background: Hsla,
338    pub(super) shadow_elevation: f32,
339    pub(super) shadow_scale: f32,
340    pub(super) shadow_color: Hsla,
341    pub(super) border: Option<(Pixels, Hsla)>,
342}
343
344impl RenderOnce for Surface {
345    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
346        let current;
347        let theme = match &self.theme {
348            Some(theme) => theme.as_ref(),
349            None => {
350                current = current_material_theme(window, cx);
351                &*current
352            }
353        };
354        let scheme = &theme.colors;
355        let default_focus = color(scheme.color(ColorRole::Secondary));
356        let shadow_color = color(scheme.color(ColorRole::Shadow));
357        let background = if self.role == ColorRole::Surface {
358            scheme.surface_at_elevation(self.tonal_elevation)
359        } else {
360            scheme.color(self.role)
361        };
362        let direction = theme.layout.direction;
363        let background = self.container_color.unwrap_or_else(|| color(background));
364        let foreground = self.content_color.or_else(|| {
365            if self.inherit_content_color || self.container_color.is_some() {
366                return None;
367            }
368            scheme.pair(self.role).map(|pair| color(pair.foreground))
369        });
370        if let Some(foreground) = foreground {
371            self.style.text.color = Some(foreground);
372        }
373        let border = self.border.map(|border| {
374            let border_width = if f32::from(border.width).is_finite() {
375                border.width.max(px(0.))
376            } else {
377                px(0.)
378            };
379            (border_width, border.color)
380        });
381        let polygon_paint = if self.polygon.is_some() {
382            Some(PolygonPaint {
383                background,
384                shadow_elevation: self.shadow_elevation.dp(),
385                shadow_scale: self.shadow_scale,
386                shadow_color,
387                border: border.filter(|(width, _)| *width > px(0.)),
388            })
389        } else {
390            self.style.background = Some(background.into());
391            let shadows =
392                elevation_shadows(self.shadow_elevation.dp(), self.shadow_scale, shadow_color);
393            if !shadows.is_empty() {
394                self.style.box_shadow = Some(shadows);
395            }
396            if let Some(shape) = self.shape {
397                if shape == CornerShape::Full {
398                    self = self.rounded_full();
399                } else {
400                    let [tl, tr, br, bl] = shape.radii(f32::MAX, f32::MAX, direction);
401                    self = self
402                        .rounded_tl(px(tl))
403                        .rounded_tr(px(tr))
404                        .rounded_br(px(br))
405                        .rounded_bl(px(bl));
406                }
407            }
408            if let Some((border_width, border_color)) = border {
409                let width = Some(border_width.into());
410                self.style.border_widths.top = width;
411                self.style.border_widths.right = width;
412                self.style.border_widths.bottom = width;
413                self.style.border_widths.left = width;
414                self.style.border_color = Some(if border_width > px(0.) {
415                    border_color
416                } else {
417                    gpui::transparent_black()
418                });
419            }
420            None
421        };
422        let resolved_shape = self.resolve_shape(direction, window);
423        let Some(control) = self.control.take() else {
424            return self.render_passive(resolved_shape, polygon_paint);
425        };
426        self.render_control(
427            control,
428            resolved_shape,
429            polygon_paint,
430            default_focus,
431            window,
432            cx,
433        )
434    }
435}
436
437impl Surface {
438    fn resolve_shape(&self, direction: Direction, window: &Window) -> ResolvedShape {
439        if let Some(polygon) = &self.polygon {
440            ResolvedShape::Polygon(polygon.clone(), self.shape_fit)
441        } else if let Some(shape) = self.shape {
442            ResolvedShape::Corners(shape, direction)
443        } else {
444            let radii = &self.style.corner_radii;
445            let radius = |value: Option<gpui::AbsoluteLength>| {
446                value.map_or(0., |value| value.to_pixels(window.rem_size()).into())
447            };
448            ResolvedShape::Corners(
449                CornerShape::Radii([
450                    radius(radii.top_left),
451                    radius(radii.top_right),
452                    radius(radii.bottom_right),
453                    radius(radii.bottom_left),
454                ]),
455                Direction::Ltr,
456            )
457        }
458    }
459}