Skip to main content

gpui_material_extras/window_chrome/
caption.rs

1use gpui::{
2    AccessibleAction, App, Bounds, ClickEvent, ElementId, Hsla, InteractiveElement, IntoElement,
3    ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement,
4    Styled, Window, WindowControlArea, canvas, div, point, prelude::FluentBuilder, px,
5    transparent_black,
6};
7use gpui_base::TestSupportExt as _;
8use gpui_material_foundation::{color, current_material_theme};
9use gpui_material_theme::{ColorRole, Direction};
10
11use super::platform::{
12    ChromePlatform, CloseHandler, activate_close, activate_maximize_or_restore, activate_minimize,
13    sanitize_positive, should_show_caption_buttons,
14};
15
16/// Optional color overrides for [`CaptionButtons`]. Omitted fields resolve from
17/// the current window Material theme.
18#[derive(Clone, Copy, Debug, Default, PartialEq)]
19pub struct CaptionButtonColors {
20    /// Glyph color for caption buttons when the window is active.
21    pub active_foreground: Option<Hsla>,
22    /// Glyph color for caption buttons when the window is inactive.
23    pub inactive_foreground: Option<Hsla>,
24    /// Background fill color when hovering Minimize or Maximize/Restore.
25    pub hover_background: Option<Hsla>,
26    /// Glyph color when hovering Minimize or Maximize/Restore.
27    pub hover_foreground: Option<Hsla>,
28    /// Background fill color while pressing Minimize or Maximize/Restore.
29    pub pressed_background: Option<Hsla>,
30    /// Glyph color while pressing Minimize or Maximize/Restore.
31    pub pressed_foreground: Option<Hsla>,
32    /// Background fill color when hovering the Close button. Defaults to `ColorRole::Error`.
33    pub close_hover_background: Option<Hsla>,
34    /// Glyph color when hovering the Close button. Defaults to `ColorRole::OnError`.
35    pub close_hover_foreground: Option<Hsla>,
36    /// Background fill color while pressing the Close button. Defaults to `ColorRole::ErrorContainer`.
37    pub close_pressed_background: Option<Hsla>,
38    /// Glyph color while pressing the Close button. Defaults to `ColorRole::OnErrorContainer`.
39    pub close_pressed_foreground: Option<Hsla>,
40}
41
42/// Localized accessible names for [`CaptionButtons`] and [`super::TitleBar`].
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct CaptionButtonLabels {
45    /// Accessible label for the minimize button. Defaults to `"Minimize"`.
46    pub minimize: SharedString,
47    /// Accessible label for the maximize button. Defaults to `"Maximize"`.
48    pub maximize: SharedString,
49    /// Accessible label for the restore button when maximized. Defaults to `"Restore"`.
50    pub restore: SharedString,
51    /// Accessible label for the close button. Defaults to `"Close"`.
52    pub close: SharedString,
53}
54
55impl Default for CaptionButtonLabels {
56    fn default() -> Self {
57        Self {
58            minimize: SharedString::new_static("Minimize"),
59            maximize: SharedString::new_static("Maximize"),
60            restore: SharedString::new_static("Restore"),
61            close: SharedString::new_static("Close"),
62        }
63    }
64}
65
66impl CaptionButtonLabels {
67    fn for_control(&self, control: CaptionButton) -> SharedString {
68        match control {
69            CaptionButton::Minimize => self.minimize.clone(),
70            CaptionButton::Maximize => self.maximize.clone(),
71            CaptionButton::Restore => self.restore.clone(),
72            CaptionButton::Close => self.close.clone(),
73        }
74    }
75}
76
77/// Minimize, maximize or restore, and close buttons for a client-drawn title bar.
78///
79/// Use this directly in a custom title bar layout for a window opened with
80/// [`super::title_bar_window_options`]. Buttons render crisp vector glyphs that
81/// do not depend on platform-specific icon fonts.
82#[derive(IntoElement)]
83pub struct CaptionButtons {
84    id: ElementId,
85    colors: CaptionButtonColors,
86    labels: CaptionButtonLabels,
87    button_width: Option<Pixels>,
88    platform: ChromePlatform,
89    show: Option<bool>,
90    on_close: Option<CloseHandler>,
91}
92
93impl CaptionButtons {
94    /// Creates caption buttons with a stable identity in their parent layout.
95    pub fn new(id: impl Into<ElementId>) -> Self {
96        Self {
97            id: id.into(),
98            colors: CaptionButtonColors::default(),
99            labels: CaptionButtonLabels::default(),
100            button_width: None,
101            platform: ChromePlatform::current(),
102            show: None,
103            on_close: None,
104        }
105    }
106
107    /// Overrides the button palette. Omitted fields keep the Material theme defaults.
108    pub fn colors(mut self, colors: CaptionButtonColors) -> Self {
109        self.colors = colors;
110        self
111    }
112
113    /// Overrides the localized accessible button names (Minimize, Maximize, Restore, Close).
114    pub fn labels(mut self, labels: CaptionButtonLabels) -> Self {
115        self.labels = labels;
116        self
117    }
118
119    /// Sets the logical width of each caption button. Defaults to 46 px on
120    /// Windows and 40 px on Linux.
121    pub fn button_width(mut self, width: Pixels) -> Self {
122        self.button_width = Some(width);
123        self
124    }
125
126    /// Overrides the target chrome platform rules for rendering and activation.
127    pub fn platform(mut self, platform: ChromePlatform) -> Self {
128        self.platform = platform;
129        self
130    }
131
132    /// Explicitly forces caption buttons to be shown or hidden (still hidden in
133    /// fullscreen). When omitted, buttons follow platform defaults: shown on
134    /// Windows, hidden on macOS, and shown on Linux under client-side decorations.
135    pub fn show(mut self, show: bool) -> Self {
136        self.show = Some(show);
137        self
138    }
139
140    /// Installs a custom close callback invoked when the Close button activates.
141    pub fn on_close(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
142        self.on_close = Some(std::rc::Rc::new(handler));
143        self
144    }
145
146    pub(super) fn with_close_handler(mut self, handler: Option<CloseHandler>) -> Self {
147        self.on_close = handler;
148        self
149    }
150
151    pub(super) fn with_show_override(mut self, show: Option<bool>) -> Self {
152        self.show = show;
153        self
154    }
155
156    pub(super) fn with_button_width_override(mut self, width: Option<Pixels>) -> Self {
157        self.button_width = width;
158        self
159    }
160}
161
162impl RenderOnce for CaptionButtons {
163    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
164        let parent_id = self.id.clone();
165        let buttons = div().id(self.id);
166        if !should_show_caption_buttons(window, self.platform, self.show) {
167            return buttons;
168        }
169
170        let controls = window.window_controls();
171        let show_minimize = window.is_minimizable() && controls.minimize;
172        let show_maximize = window.is_resizable() && controls.maximize;
173        let button_width = self.button_width.map_or_else(
174            || self.platform.default_caption_button_width(),
175            |width| sanitize_positive(width, self.platform.default_caption_button_width()),
176        );
177        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
178
179        let minimize = show_minimize.then(|| {
180            title_bar_control(
181                &parent_id,
182                CaptionButton::Minimize,
183                self.platform,
184                button_width,
185                self.colors,
186                self.labels.for_control(CaptionButton::Minimize),
187                None,
188                window,
189                cx,
190            )
191        });
192        let maximize = show_maximize.then(|| {
193            let control = if window.is_maximized() {
194                CaptionButton::Restore
195            } else {
196                CaptionButton::Maximize
197            };
198            title_bar_control(
199                &parent_id,
200                control,
201                self.platform,
202                button_width,
203                self.colors,
204                self.labels.for_control(control),
205                None,
206                window,
207                cx,
208            )
209        });
210        let close = title_bar_control(
211            &parent_id,
212            CaptionButton::Close,
213            self.platform,
214            button_width,
215            self.colors,
216            self.labels.for_control(CaptionButton::Close),
217            self.on_close,
218            window,
219            cx,
220        );
221
222        buttons
223            .flex()
224            .items_stretch()
225            .flex_shrink_0()
226            .when(rtl, |buttons| buttons.flex_row_reverse())
227            .when_some(minimize, |buttons, button| buttons.child(button))
228            .when_some(maximize, |buttons, button| buttons.child(button))
229            .child(close)
230    }
231}
232
233#[derive(Clone, Copy)]
234enum CaptionButton {
235    Minimize,
236    Maximize,
237    Restore,
238    Close,
239}
240
241impl CaptionButton {
242    fn id(self) -> &'static str {
243        match self {
244            Self::Minimize => "minimize",
245            Self::Maximize | Self::Restore => "maximize-restore",
246            Self::Close => "close",
247        }
248    }
249
250    fn area(self) -> WindowControlArea {
251        match self {
252            Self::Minimize => WindowControlArea::Min,
253            Self::Maximize | Self::Restore => WindowControlArea::Max,
254            Self::Close => WindowControlArea::Close,
255        }
256    }
257
258    fn activate(self, window: &mut Window, cx: &mut App, on_close: Option<&CloseHandler>) {
259        match self {
260            Self::Minimize => activate_minimize(window),
261            Self::Maximize | Self::Restore => activate_maximize_or_restore(window),
262            Self::Close => activate_close(window, cx, on_close),
263        }
264    }
265}
266
267#[allow(clippy::too_many_arguments)]
268fn title_bar_control(
269    parent_id: &ElementId,
270    control: CaptionButton,
271    platform: ChromePlatform,
272    button_width: Pixels,
273    colors: CaptionButtonColors,
274    label: SharedString,
275    on_close: Option<CloseHandler>,
276    window: &mut Window,
277    cx: &mut App,
278) -> impl IntoElement + use<> {
279    let key = ElementId::from((ElementId::from((parent_id.clone(), control.id())), "focus"));
280    let focus_handle = window
281        .use_keyed_state(key, cx, |_, cx| cx.focus_handle().tab_stop(true))
282        .read(cx)
283        .clone();
284    let theme = current_material_theme(window, cx);
285    let tone = |role| color(theme.colors.color(role));
286    let foreground = if window.is_window_active() {
287        colors
288            .active_foreground
289            .unwrap_or_else(|| tone(ColorRole::OnSurface))
290    } else {
291        colors
292            .inactive_foreground
293            .unwrap_or_else(|| tone(ColorRole::OnSurfaceVariant))
294    };
295    let (hover_fill, hover_text, pressed_fill, pressed_text) = match control {
296        CaptionButton::Close => (
297            colors
298                .close_hover_background
299                .unwrap_or_else(|| tone(ColorRole::Error)),
300            colors
301                .close_hover_foreground
302                .unwrap_or_else(|| tone(ColorRole::OnError)),
303            colors
304                .close_pressed_background
305                .unwrap_or_else(|| tone(ColorRole::ErrorContainer)),
306            colors
307                .close_pressed_foreground
308                .unwrap_or_else(|| tone(ColorRole::OnErrorContainer)),
309        ),
310        _ => (
311            colors
312                .hover_background
313                .unwrap_or_else(|| tone(ColorRole::SurfaceContainerHigh)),
314            colors
315                .hover_foreground
316                .unwrap_or_else(|| tone(ColorRole::OnSurface)),
317            colors
318                .pressed_background
319                .unwrap_or_else(|| tone(ColorRole::SurfaceContainerHighest)),
320            colors
321                .pressed_foreground
322                .unwrap_or_else(|| tone(ColorRole::OnSurface)),
323        ),
324    };
325    let ring = tone(ColorRole::Secondary);
326
327    // Windows routes native pointer clicks (and Snap Layouts on Maximize) through
328    // non-client hit areas unless a custom `on_close` callback overrides Close.
329    let use_native_win32_area = platform == ChromePlatform::Windows
330        && !(matches!(control, CaptionButton::Close) && on_close.is_some());
331
332    let click_close = on_close.clone();
333    let a11y_close = on_close;
334
335    div()
336        .id(control.id())
337        .flex()
338        .items_center()
339        .justify_center()
340        .w(button_width)
341        .min_h(px(32.))
342        .flex_shrink_0()
343        .border_1()
344        .border_color(transparent_black())
345        .text_color(foreground)
346        .when(use_native_win32_area, |button| {
347            button.window_control_area(control.area())
348        })
349        .role(Role::Button)
350        .aria_label(label)
351        .track_focus(&focus_handle)
352        .tab_index(0)
353        .focus_visible(move |style| style.border_color(ring))
354        .hover(move |style| style.bg(hover_fill).text_color(hover_text))
355        .active(move |style| style.bg(pressed_fill).text_color(pressed_text))
356        .on_click(move |event, window, cx| {
357            if !use_native_win32_area || matches!(event, ClickEvent::Keyboard(_)) {
358                control.activate(window, cx, click_close.as_ref());
359            }
360        })
361        .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
362            control.activate(window, cx, a11y_close.as_ref());
363        })
364        .child(caption_glyph(control))
365        .test_support()
366}
367
368fn caption_glyph(control: CaptionButton) -> impl IntoElement {
369    canvas(
370        |_, _, _| {},
371        move |bounds: Bounds<Pixels>, _, window: &mut Window, _| {
372            let stroke = window.text_style().color;
373            let x = bounds.origin.x;
374            let y = bounds.origin.y;
375            let w = bounds.size.width;
376            let h = bounds.size.height;
377            let mut builder = PathBuilder::stroke(px(1.));
378            match control {
379                CaptionButton::Minimize => {
380                    let mid_y = y + h * 0.5;
381                    builder.move_to(point(x, mid_y));
382                    builder.line_to(point(x + w, mid_y));
383                }
384                CaptionButton::Maximize => {
385                    let inset = px(0.5);
386                    let x0 = x + inset;
387                    let y0 = y + inset;
388                    let x1 = x + w - inset;
389                    let y1 = y + h - inset;
390                    builder.add_polygon(
391                        &[point(x0, y0), point(x1, y0), point(x1, y1), point(x0, y1)],
392                        true,
393                    );
394                }
395                CaptionButton::Restore => {
396                    let inset = px(0.5);
397                    let offset = px(2.);
398                    // Front lower-left square.
399                    let fx0 = x + inset;
400                    let fy0 = y + offset + inset;
401                    let fx1 = x + w - offset - inset;
402                    let fy1 = y + h - inset;
403                    builder.add_polygon(
404                        &[
405                            point(fx0, fy0),
406                            point(fx1, fy0),
407                            point(fx1, fy1),
408                            point(fx0, fy1),
409                        ],
410                        true,
411                    );
412                    // Back upper-right L-frame.
413                    let bx0 = x + offset + inset;
414                    let by0 = y + inset;
415                    let bx1 = x + w - inset;
416                    let by1 = y + h - offset - inset;
417                    builder.move_to(point(bx0, fy0));
418                    builder.line_to(point(bx0, by0));
419                    builder.line_to(point(bx1, by0));
420                    builder.line_to(point(bx1, by1));
421                    builder.line_to(point(fx1, by1));
422                }
423                CaptionButton::Close => {
424                    let inset = px(0.5);
425                    let x0 = x + inset;
426                    let y0 = y + inset;
427                    let x1 = x + w - inset;
428                    let y1 = y + h - inset;
429                    builder.move_to(point(x0, y0));
430                    builder.line_to(point(x1, y1));
431                    builder.move_to(point(x1, y0));
432                    builder.line_to(point(x0, y1));
433                }
434            }
435            if let Ok(path) = builder.build() {
436                window.paint_path(path, stroke);
437            }
438        },
439    )
440    .size(px(10.))
441    .flex_shrink_0()
442}