Skip to main content

gpui_material_foundation/
surface.rs

1use std::{cell::RefCell, rc::Rc};
2
3use gpui::{
4    AccessibleAction, AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement,
5    ParentElement, Pixels, RenderOnce, Rgba, Role, SharedString, StatefulInteractiveElement,
6    StyleRefinement, Styled, Toggled, Window, canvas, div, prelude::FluentBuilder, px,
7};
8use gpui_base::{Button, StyledExt};
9use gpui_material_theme::{Argb, ColorRole, CornerShape, Direction, Elevation, MaterialTheme};
10
11use crate::{
12    InteractionFeedback, InteractionSource, Shape, ShapeFit, ShapePolygon,
13    control_feedback::{activate_feedback, feedback_target, ripple_state},
14    current_material_theme,
15};
16
17/// Converts Material's packed sRGB color and preserves its alpha channel.
18pub fn color(argb: Argb) -> Hsla {
19    let [a, r, g, b] = argb.channels().map(|channel| f32::from(channel) / 255.);
20    Rgba { r, g, b, a }.into()
21}
22
23/// Resolves the Material scrim color for an overlay that owns dismissal and focus.
24pub fn scrim_color(theme: &MaterialTheme, opacity: f32) -> Hsla {
25    color(theme.colors.color(ColorRole::Scrim)).opacity(opacity.clamp(0., 1.))
26}
27
28/// Desktop shadow projection shared by surfaces and custom-painted controls.
29/// `elevation` is in Material logical units; `scale` follows the component geometry.
30/// Compose delegates shadows to its platform renderer; GPUI uses these two layers.
31pub fn elevation_shadows(elevation: f32, scale: f32, shadow: Hsla) -> Vec<gpui::BoxShadow> {
32    let dp = elevation * scale;
33    if !dp.is_finite() || dp <= 0. || !scale.is_finite() || scale <= 0. {
34        return Vec::new();
35    }
36    vec![
37        gpui_base::box_shadow(0., dp * 0.4, dp, 0., shadow.opacity(0.18)),
38        gpui_base::box_shadow(0., scale, dp * 0.5, 0., shadow.opacity(0.13)),
39    ]
40}
41
42/// An outline in logical pixels, drawn around the surface's shape.
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub struct SurfaceBorder {
45    pub width: Pixels,
46    pub color: Hsla,
47}
48
49/// Customizes the Material feedback painted by one interactive surface.
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub struct SurfaceFeedback {
52    pub state_layer: bool,
53    pub ripple: bool,
54    pub focus_ring: bool,
55    pub ink: Option<Hsla>,
56    pub focus_color: Option<Hsla>,
57}
58
59impl Default for SurfaceFeedback {
60    fn default() -> Self {
61        Self {
62            state_layer: true,
63            ripple: true,
64            focus_ring: true,
65            ink: None,
66            focus_color: None,
67        }
68    }
69}
70
71#[derive(Clone, Copy)]
72enum SurfaceAction {
73    Activate,
74    Select(bool),
75    Check(bool),
76}
77
78type Activate = Rc<dyn Fn(&mut Window, &mut App)>;
79
80struct Control {
81    id: ElementId,
82    label: SharedString,
83    action: SurfaceAction,
84    activate: Option<Activate>,
85}
86
87/// A passive Material background or an interactive surface with arbitrary children.
88#[derive(IntoElement)]
89pub struct Surface {
90    style: StyleRefinement,
91    children: Vec<AnyElement>,
92    role: ColorRole,
93    container_color: Option<Hsla>,
94    content_color: Option<Hsla>,
95    inherit_content_color: bool,
96    shape: Option<CornerShape>,
97    polygon: Option<ShapePolygon>,
98    shape_fit: ShapeFit,
99    clip_backdrop: Option<Hsla>,
100    shape_hit_test: Option<bool>,
101    border: Option<SurfaceBorder>,
102    tonal_elevation: Elevation,
103    shadow_elevation: Elevation,
104    shadow_scale: f32,
105    theme: Option<MaterialTheme>,
106    control: Option<Control>,
107    disabled: bool,
108    focus: Option<FocusHandle>,
109    feedback: SurfaceFeedback,
110    interaction_source: Option<Entity<InteractionSource>>,
111}
112
113impl Surface {
114    pub fn new(role: ColorRole) -> Self {
115        Self {
116            style: StyleRefinement::default(),
117            children: Vec::new(),
118            role,
119            container_color: None,
120            content_color: None,
121            inherit_content_color: false,
122            shape: None,
123            polygon: None,
124            shape_fit: ShapeFit::Contain,
125            clip_backdrop: None,
126            shape_hit_test: None,
127            border: None,
128            tonal_elevation: Elevation::Level0,
129            shadow_elevation: Elevation::Level0,
130            shadow_scale: 1.,
131            theme: None,
132            control: None,
133            disabled: false,
134            focus: None,
135            feedback: SurfaceFeedback::default(),
136            interaction_source: None,
137        }
138    }
139
140    pub fn clickable(
141        id: impl Into<ElementId>,
142        label: impl Into<SharedString>,
143        role: ColorRole,
144    ) -> Self {
145        Self::interactive(id, label, role, SurfaceAction::Activate)
146    }
147
148    /// Renders the caller's selection and requests activation through on_activate.
149    pub fn selectable(
150        id: impl Into<ElementId>,
151        label: impl Into<SharedString>,
152        role: ColorRole,
153        selected: bool,
154    ) -> Self {
155        Self::interactive(id, label, role, SurfaceAction::Select(selected))
156    }
157
158    /// Renders the caller's check state and requests the next value through on_checked_change.
159    pub fn toggleable(
160        id: impl Into<ElementId>,
161        label: impl Into<SharedString>,
162        role: ColorRole,
163        checked: bool,
164    ) -> Self {
165        Self::interactive(id, label, role, SurfaceAction::Check(checked))
166    }
167
168    fn interactive(
169        id: impl Into<ElementId>,
170        label: impl Into<SharedString>,
171        role: ColorRole,
172        action: SurfaceAction,
173    ) -> Self {
174        Self {
175            control: Some(Control {
176                id: id.into(),
177                label: label.into(),
178                action,
179                activate: None,
180            }),
181            ..Self::new(role)
182        }
183    }
184
185    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
186        if let Some(control) = &mut self.control {
187            control.activate = Some(Rc::new(handler));
188        }
189        self
190    }
191
192    pub fn on_checked_change(
193        mut self,
194        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
195    ) -> Self {
196        if let Some(control) = &mut self.control
197            && let SurfaceAction::Check(checked) = control.action
198        {
199            control.activate = Some(Rc::new(move |window, cx| handler(!checked, window, cx)));
200        }
201        self
202    }
203
204    pub fn disabled(mut self, disabled: bool) -> Self {
205        self.disabled = disabled;
206        self
207    }
208
209    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
210        self.focus = Some(focus.clone());
211        self
212    }
213
214    pub fn feedback(mut self, feedback: SurfaceFeedback) -> Self {
215        self.feedback = feedback;
216        self
217    }
218
219    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
220        self.interaction_source = Some(source.clone());
221        self
222    }
223
224    /// Uses an explicit fill and inherits the foreground unless one is supplied.
225    pub fn container_color(mut self, color: Hsla) -> Self {
226        self.container_color = Some(color);
227        self
228    }
229
230    /// Sets the inherited foreground for this surface's children.
231    pub fn content_color(mut self, color: Hsla) -> Self {
232        self.content_color = Some(color);
233        self
234    }
235
236    /// Uses the ancestor text color unless this surface supplies an explicit foreground.
237    pub fn inherit_content_color(mut self, inherit: bool) -> Self {
238        self.inherit_content_color = inherit;
239        self
240    }
241
242    pub fn shape(mut self, shape: CornerShape) -> Self {
243        self.shape = Some(shape);
244        self.polygon = None;
245        self
246    }
247
248    /// Uses any [`ShapePolygon`] (including [`MaterialShape`](gpui_material_theme::MaterialShape),
249    /// [`PolygonRole`](gpui_material_theme::PolygonRole), or sampled [`ShapeMorph`](crate::ShapeMorph)
250    /// outlines) for background painting, border stroke, shadow, clipping, and feedback.
251    ///
252    /// Interactive polygon surfaces default to shape-aware pointer hit testing unless
253    /// overridden with [`Self::shape_hit_test`].
254    pub fn polygon_shape(mut self, polygon: impl Into<ShapePolygon>) -> Self {
255        self.polygon = Some(polygon.into());
256        self.shape = None;
257        self
258    }
259
260    /// Chooses how a [`Self::polygon_shape`] maps into the laid-out surface bounds.
261    pub fn shape_fit(mut self, fit: ShapeFit) -> Self {
262        self.shape_fit = fit;
263        self
264    }
265
266    /// Visually clips overflowing children to the resolved shape contour by applying a
267    /// rectangular content mask and painting an EvenOdd exterior mask in `backdrop`.
268    /// Match `backdrop` to the uniform background behind this surface.
269    pub fn shape_clip_backdrop(mut self, backdrop: Hsla) -> Self {
270        self.clip_backdrop = Some(backdrop);
271        self
272    }
273
274    /// Controls whether pointer hover, press, and click activation require the cursor to
275    /// lie inside the resolved shape contour. Defaults to `true` for [`Self::polygon_shape`]
276    /// and `false` for rectangular or [`CornerShape`] surfaces. Keyboard and accessibility
277    /// activation remain available regardless of this setting.
278    pub fn shape_hit_test(mut self, enabled: bool) -> Self {
279        self.shape_hit_test = Some(enabled);
280        self
281    }
282
283    pub fn border(mut self, border: SurfaceBorder) -> Self {
284        self.border = Some(border);
285        self
286    }
287
288    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
289        self.tonal_elevation = elevation;
290        self
291    }
292
293    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
294        self.shadow_elevation = elevation;
295        self
296    }
297
298    /// Scales the offset and blur radius with an animated surface.
299    pub fn shadow_scale(mut self, scale: f32) -> Self {
300        self.shadow_scale = scale;
301        self
302    }
303
304    /// Uses an explicit window or subtree theme for this surface.
305    pub fn with_theme(mut self, theme: MaterialTheme) -> Self {
306        self.theme = Some(theme);
307        self
308    }
309}
310
311impl ParentElement for Surface {
312    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
313        self.children.extend(elements);
314    }
315}
316
317impl Styled for Surface {
318    fn style(&mut self) -> &mut StyleRefinement {
319        &mut self.style
320    }
321}
322
323#[derive(Clone)]
324enum ResolvedShape {
325    Corners(CornerShape, Direction),
326    Polygon(ShapePolygon, ShapeFit),
327}
328
329impl ResolvedShape {
330    fn build(&self, bounds: Bounds<Pixels>) -> Option<Shape> {
331        match self {
332            Self::Corners(shape, direction) => Shape::rounded(bounds, *shape, *direction),
333            Self::Polygon(polygon, fit) => Shape::polygon(bounds, polygon, *fit),
334        }
335    }
336}
337
338struct PolygonPaint {
339    background: Hsla,
340    shadow_elevation: f32,
341    shadow_scale: f32,
342    shadow_color: Hsla,
343    border: Option<(Pixels, Hsla)>,
344}
345
346impl RenderOnce for Surface {
347    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
348        let current = current_material_theme(window, cx);
349        let theme = self.theme.as_ref().unwrap_or(&current);
350        let scheme = &theme.colors;
351        let default_focus = color(scheme.color(ColorRole::Secondary));
352        let shadow_color = color(scheme.color(ColorRole::Shadow));
353        let background = if self.role == ColorRole::Surface {
354            scheme.surface_at_elevation(self.tonal_elevation)
355        } else {
356            scheme.color(self.role)
357        };
358        let direction = theme.layout.direction;
359        let background = self.container_color.unwrap_or_else(|| color(background));
360        let foreground = self.content_color.or_else(|| {
361            if self.inherit_content_color || self.container_color.is_some() {
362                return None;
363            }
364            scheme.pair(self.role).map(|pair| color(pair.foreground))
365        });
366        if let Some(foreground) = foreground {
367            self.style.text.color = Some(foreground);
368        }
369        let border = self.border.map(|border| {
370            let border_width = if f32::from(border.width).is_finite() {
371                border.width.max(px(0.))
372            } else {
373                px(0.)
374            };
375            (border_width, border.color)
376        });
377        let polygon_paint = if self.polygon.is_some() {
378            Some(PolygonPaint {
379                background,
380                shadow_elevation: self.shadow_elevation.dp(),
381                shadow_scale: self.shadow_scale,
382                shadow_color,
383                border: border.filter(|(width, _)| *width > px(0.)),
384            })
385        } else {
386            self.style.background = Some(background.into());
387            let shadows =
388                elevation_shadows(self.shadow_elevation.dp(), self.shadow_scale, shadow_color);
389            if !shadows.is_empty() {
390                self.style.box_shadow = Some(shadows);
391            }
392            if let Some(shape) = self.shape {
393                if shape == CornerShape::Full {
394                    self = self.rounded_full();
395                } else {
396                    let [tl, tr, br, bl] = shape.radii(f32::MAX, f32::MAX, direction);
397                    self = self
398                        .rounded_tl(px(tl))
399                        .rounded_tr(px(tr))
400                        .rounded_br(px(br))
401                        .rounded_bl(px(bl));
402                }
403            }
404            if let Some((border_width, border_color)) = border {
405                let width = Some(border_width.into());
406                self.style.border_widths.top = width;
407                self.style.border_widths.right = width;
408                self.style.border_widths.bottom = width;
409                self.style.border_widths.left = width;
410                self.style.border_color = Some(if border_width > px(0.) {
411                    border_color
412                } else {
413                    gpui::transparent_black()
414                });
415            }
416            None
417        };
418        let resolved_shape = self.resolve_shape(direction, window);
419        let Some(control) = self.control.take() else {
420            return self.render_passive(resolved_shape, polygon_paint);
421        };
422        self.render_control(
423            control,
424            resolved_shape,
425            polygon_paint,
426            default_focus,
427            window,
428            cx,
429        )
430    }
431}
432
433impl Surface {
434    fn resolve_shape(&self, direction: Direction, window: &Window) -> ResolvedShape {
435        if let Some(polygon) = &self.polygon {
436            ResolvedShape::Polygon(polygon.clone(), self.shape_fit)
437        } else if let Some(shape) = self.shape {
438            ResolvedShape::Corners(shape, direction)
439        } else {
440            let radii = &self.style.corner_radii;
441            let radius = |value: Option<gpui::AbsoluteLength>| {
442                value.map_or(0., |value| value.to_pixels(window.rem_size()).into())
443            };
444            ResolvedShape::Corners(
445                CornerShape::Radii([
446                    radius(radii.top_left),
447                    radius(radii.top_right),
448                    radius(radii.bottom_right),
449                    radius(radii.bottom_left),
450                ]),
451                Direction::Ltr,
452            )
453        }
454    }
455
456    fn render_passive(
457        self,
458        resolved_shape: ResolvedShape,
459        polygon_paint: Option<PolygonPaint>,
460    ) -> AnyElement {
461        let clip_backdrop = self.clip_backdrop;
462        if polygon_paint.is_none() && clip_backdrop.is_none() {
463            return div()
464                .refine_style(&self.style)
465                .children(self.children)
466                .into_any_element();
467        }
468        let prepared: Rc<RefCell<Option<Shape>>> = Rc::new(RefCell::new(None));
469        let border = polygon_paint.as_ref().and_then(|paint| paint.border);
470        let prepaint_shape = prepared.clone();
471        let bg_shape = prepared.clone();
472        let background_layer = polygon_paint.map(|paint| {
473            let spec = resolved_shape.clone();
474            canvas(
475                move |bounds, _, _| {
476                    *prepaint_shape.borrow_mut() = spec.build(bounds);
477                },
478                move |_, _, window, _| {
479                    if let Some(shape) = bg_shape.borrow().as_ref() {
480                        shape.paint_shadow(
481                            paint.shadow_elevation,
482                            paint.shadow_scale,
483                            paint.shadow_color,
484                            window,
485                        );
486                        shape.paint(paint.background, window);
487                    }
488                },
489            )
490            .absolute()
491            .inset_0()
492        });
493        let needs_fg = clip_backdrop.is_some() || border.is_some();
494        let fg_prepaint = prepared.clone();
495        let fg_paint = prepared;
496        let has_bg = background_layer.is_some();
497        let foreground_layer = needs_fg.then(|| {
498            canvas(
499                move |bounds, _, _| {
500                    if !has_bg {
501                        *fg_prepaint.borrow_mut() = resolved_shape.build(bounds);
502                    }
503                },
504                move |bounds, _, window, _| {
505                    if let Some(shape) = fg_paint.borrow().as_ref() {
506                        if let Some(backdrop) = clip_backdrop {
507                            shape.paint_backdrop_mask(bounds, backdrop, window);
508                        }
509                        if let Some((width, color)) = border {
510                            shape.paint_stroke(width, color, window);
511                        }
512                    }
513                },
514            )
515            .absolute()
516            .inset_0()
517        });
518        div()
519            .relative()
520            .when(clip_backdrop.is_some(), Styled::overflow_hidden)
521            .refine_style(&self.style)
522            .children(background_layer)
523            .children(self.children)
524            .children(foreground_layer)
525            .into_any_element()
526    }
527
528    fn render_control(
529        self,
530        control: Control,
531        resolved_shape: ResolvedShape,
532        polygon_paint: Option<PolygonPaint>,
533        default_focus: Hsla,
534        window: &mut Window,
535        cx: &mut App,
536    ) -> AnyElement {
537        let focus = self.focus.unwrap_or_else(|| {
538            window
539                .use_keyed_state((control.id.clone(), "focus"), cx, |_, cx| cx.focus_handle())
540                .read(cx)
541                .clone()
542        });
543        let state = ripple_state(&control.id, !self.disabled, window, cx);
544        let shape_hit_test = self.shape_hit_test.unwrap_or(polygon_paint.is_some());
545        state.borrow_mut().set_shape_hit_test(shape_hit_test);
546        let tracker = self
547            .interaction_source
548            .as_ref()
549            .map(|source| InteractionSource::track(source, &control.id, window, cx));
550        let interaction = state
551            .borrow_mut()
552            .track(!self.disabled, &focus, tracker, window, cx);
553        let appearance = self.feedback;
554        let ink = appearance
555            .ink
556            .or(self.style.text.color)
557            .unwrap_or_else(|| window.text_style().color);
558        let ring = if appearance.focus_ring {
559            appearance.focus_color.unwrap_or(default_focus)
560        } else {
561            gpui::transparent_black()
562        };
563        let clip_backdrop = self.clip_backdrop;
564        let border = polygon_paint.as_ref().and_then(|paint| paint.border);
565        let bg_geometry = state.clone();
566        let bg_paint = state.clone();
567        let background_layer = polygon_paint.map(|paint| {
568            let spec = resolved_shape.clone();
569            canvas(
570                move |bounds, window, _| {
571                    bg_geometry
572                        .borrow_mut()
573                        .set_shape(spec.build(bounds), window);
574                },
575                move |_, _, window, _| {
576                    if let Some(shape) = &bg_paint.borrow().shape {
577                        shape.paint_shadow(
578                            paint.shadow_elevation,
579                            paint.shadow_scale,
580                            paint.shadow_color,
581                            window,
582                        );
583                        shape.paint(paint.background, window);
584                    }
585                },
586            )
587            .absolute()
588            .inset_0()
589        });
590        let has_bg = background_layer.is_some();
591        let geometry = state.clone();
592        let paint = state.clone();
593        let visual = canvas(
594            move |bounds, window, _| {
595                if !has_bg {
596                    geometry
597                        .borrow_mut()
598                        .set_shape(resolved_shape.build(bounds), window);
599                }
600            },
601            move |bounds, _, window, cx| {
602                let state = paint.borrow();
603                if let Some(shape) = &state.shape {
604                    if let Some(backdrop) = clip_backdrop {
605                        shape.paint_backdrop_mask(bounds, backdrop, window);
606                    }
607                    if let Some((width, color)) = border {
608                        shape.paint_stroke(width, color, window);
609                    }
610                    let reduced = cx.reduce_motion();
611                    let ripple = state.ripple.as_ref().filter(|_| appearance.ripple);
612                    let layer = interaction
613                        .layer_with_ripple(reduced || !appearance.ripple)
614                        .filter(|_| appearance.state_layer)
615                        .map_or(0., |layer| layer.opacity());
616                    InteractionFeedback::new(interaction, ink, ring).paint_with_opacity(
617                        shape,
618                        ripple,
619                        layer,
620                        cx.background_executor().now(),
621                        reduced,
622                        window,
623                    );
624                }
625            },
626        )
627        .absolute()
628        .inset_0();
629        let button = Button::new(control.id)
630            .block()
631            .items_stretch()
632            .justify_start()
633            .when(clip_backdrop.is_some(), Styled::overflow_hidden)
634            .line_height(window.text_style().line_height)
635            .refine_style(&self.style)
636            .accessibility_label(control.label)
637            .track_focus(&focus)
638            .disabled(self.disabled);
639        let button = match control.action {
640            SurfaceAction::Activate => button,
641            SurfaceAction::Select(value) => button.role(Role::ListBoxOption).aria_selected(value),
642            SurfaceAction::Check(value) => button.role(Role::CheckBox).aria_toggled(if value {
643                Toggled::True
644            } else {
645                Toggled::False
646            }),
647        };
648        let button = if let Some(activate) = control.activate.filter(|_| !self.disabled) {
649            let accessible = activate.clone();
650            let feedback = state.clone();
651            button
652                .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
653                    accessible(window, cx);
654                })
655                .on_click(move |event, window, cx| {
656                    cx.stop_propagation();
657                    if !feedback.borrow().blocks_activation(event) {
658                        activate_feedback(event, &feedback, window, cx);
659                        activate(window, cx);
660                    }
661                })
662        } else {
663            button
664        };
665        button
666            .when(!self.disabled, |button| {
667                feedback_target(button, state, true, Some(focus))
668            })
669            .children(background_layer)
670            .children(self.children)
671            .child(visual)
672            .into_any_element()
673    }
674}