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