Skip to main content

gpui_material_extras/window_chrome/
mod.rs

1//! Cross-platform client-drawn window title bars and controls backed by GPUI.
2
3mod caption;
4mod platform;
5#[cfg(test)]
6mod tests;
7
8use gpui::{
9    AnyElement, App, ElementId, Font, Hsla, InteractiveElement, IntoElement, MouseButton,
10    MouseDownEvent, ParentElement, Pixels, RenderOnce, SharedString, Styled, Window,
11    WindowControlArea, div, prelude::FluentBuilder, px,
12};
13use gpui_base::TestSupportExt as _;
14use gpui_material_foundation::{color, current_material_theme, font_for_style};
15use gpui_material_theme::{ColorRole, Direction, TypeRole, TypographyEmphasis};
16
17pub use caption::{CaptionButtonColors, CaptionButtonLabels, CaptionButtons};
18pub use platform::{
19    ChromePlatform, DEFAULT_LINUX_CAPTION_BUTTON_WIDTH, DEFAULT_MACOS_TRAFFIC_LIGHT_PADDING,
20    DEFAULT_TITLE_BAR_HEIGHT, DEFAULT_WINDOWS_CAPTION_BUTTON_WIDTH, title_bar_window_options,
21    title_bar_window_options_with_height,
22};
23
24use platform::{CloseHandler, read_window_title, sanitize_nonnegative, sanitize_positive};
25
26/// Optional color overrides for [`TitleBar`]. Omitted fields resolve from the
27/// current window Material theme.
28#[derive(Clone, Copy, Debug, Default, PartialEq)]
29pub struct TitleBarColors {
30    /// Background fill color of the title bar strip. Defaults to `ColorRole::Surface`.
31    pub background: Option<Hsla>,
32    /// Title text and foreground color when the window is active. Defaults to `ColorRole::OnSurface`.
33    pub active_foreground: Option<Hsla>,
34    /// Title text and foreground color when the window is inactive. Defaults to `ColorRole::OnSurfaceVariant`.
35    pub inactive_foreground: Option<Hsla>,
36    /// Optional 1px bottom border color separating the title bar from window content.
37    pub border: Option<Hsla>,
38}
39
40/// Cross-platform client-drawn title bar with a drag region, customizable title
41/// typography, optional leading/content/trailing slots, macOS traffic-light
42/// spacing, and platform-appropriate window controls.
43#[derive(IntoElement)]
44pub struct TitleBar {
45    id: ElementId,
46    title: Option<SharedString>,
47    height: Pixels,
48    title_role: TypeRole,
49    title_font: Option<Font>,
50    title_font_family: Option<SharedString>,
51    title_font_size: Option<Pixels>,
52    leading: Option<AnyElement>,
53    content: Option<AnyElement>,
54    trailing: Option<AnyElement>,
55    traffic_light_padding: Pixels,
56    colors: TitleBarColors,
57    caption_colors: CaptionButtonColors,
58    caption_labels: CaptionButtonLabels,
59    caption_button_width: Option<Pixels>,
60    show_caption_buttons: Option<bool>,
61    on_close: Option<CloseHandler>,
62    platform: ChromePlatform,
63}
64
65impl TitleBar {
66    /// Creates a title bar with a stable identity in the window view.
67    pub fn new(id: impl Into<ElementId>) -> Self {
68        Self {
69            id: id.into(),
70            title: None,
71            height: DEFAULT_TITLE_BAR_HEIGHT,
72            title_role: TypeRole::TitleSmall,
73            title_font: None,
74            title_font_family: None,
75            title_font_size: None,
76            leading: None,
77            content: None,
78            trailing: None,
79            traffic_light_padding: DEFAULT_MACOS_TRAFFIC_LIGHT_PADDING,
80            colors: TitleBarColors::default(),
81            caption_colors: CaptionButtonColors::default(),
82            caption_labels: CaptionButtonLabels::default(),
83            caption_button_width: None,
84            show_caption_buttons: None,
85            on_close: None,
86            platform: ChromePlatform::current(),
87        }
88    }
89
90    /// Sets an explicit title string. When omitted, reads the live window title.
91    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
92        self.title = Some(title.into());
93        self
94    }
95
96    /// Sets the logical height of the title bar. Defaults to [`DEFAULT_TITLE_BAR_HEIGHT`] (48 px).
97    pub fn height(mut self, height: Pixels) -> Self {
98        self.height = sanitize_positive(height, DEFAULT_TITLE_BAR_HEIGHT);
99        self
100    }
101
102    /// Selects the Material typography role for the title text. Defaults to `TypeRole::TitleSmall`.
103    pub fn title_role(mut self, role: TypeRole) -> Self {
104        self.title_role = role;
105        self
106    }
107
108    /// Overrides the full GPUI [`Font`] used for the title text.
109    pub fn title_font(mut self, font: Font) -> Self {
110        self.title_font = Some(font);
111        self
112    }
113
114    /// Overrides only the title font family while preserving weight and theme metrics.
115    pub fn title_font_family(mut self, family: impl Into<SharedString>) -> Self {
116        self.title_font_family = Some(family.into());
117        self
118    }
119
120    /// Overrides the title font size in logical pixels.
121    pub fn title_font_size(mut self, size: Pixels) -> Self {
122        self.title_font_size = Some(size);
123        self
124    }
125
126    /// Places leading client-area content after any macOS traffic-light inset and
127    /// before the title/drag region.
128    pub fn leading(mut self, content: impl IntoElement) -> Self {
129        self.leading = Some(content.into_any_element());
130        self
131    }
132
133    /// Places client-area content between the drag region and trailing/caption controls.
134    pub fn content(mut self, content: impl IntoElement) -> Self {
135        self.content = Some(content.into_any_element());
136        self
137    }
138
139    /// Places trailing client-area content before the caption buttons.
140    pub fn trailing(mut self, content: impl IntoElement) -> Self {
141        self.trailing = Some(content.into_any_element());
142        self
143    }
144
145    /// Sets the logical leading inset reserved for macOS traffic light buttons
146    /// when not fullscreen. Defaults to [`DEFAULT_MACOS_TRAFFIC_LIGHT_PADDING`] (78 px).
147    pub fn traffic_light_padding(mut self, padding: Pixels) -> Self {
148        self.traffic_light_padding =
149            sanitize_nonnegative(padding, DEFAULT_MACOS_TRAFFIC_LIGHT_PADDING);
150        self
151    }
152
153    /// Overrides the title bar surface, foreground, and optional bottom divider colors.
154    pub fn colors(mut self, colors: TitleBarColors) -> Self {
155        self.colors = colors;
156        self
157    }
158
159    /// Overrides the caption button palette.
160    pub fn caption_colors(mut self, colors: CaptionButtonColors) -> Self {
161        self.caption_colors = colors;
162        self
163    }
164
165    /// Overrides the localized accessible names for the caption buttons.
166    pub fn caption_labels(mut self, labels: CaptionButtonLabels) -> Self {
167        self.caption_labels = labels;
168        self
169    }
170
171    /// Overrides the logical width of each caption button.
172    pub fn caption_button_width(mut self, width: Pixels) -> Self {
173        self.caption_button_width = Some(width);
174        self
175    }
176
177    /// Explicitly shows or hides caption buttons (still hidden in fullscreen).
178    pub fn show_caption_buttons(mut self, show: bool) -> Self {
179        self.show_caption_buttons = Some(show);
180        self
181    }
182
183    /// Installs a custom close callback invoked when the Close button activates.
184    pub fn on_close(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
185        self.on_close = Some(std::rc::Rc::new(handler));
186        self
187    }
188
189    /// Overrides the target chrome platform rules. Defaults to [`ChromePlatform::current`].
190    pub fn platform(mut self, platform: ChromePlatform) -> Self {
191        self.platform = platform;
192        self
193    }
194}
195
196impl RenderOnce for TitleBar {
197    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
198        let theme = current_material_theme(window, cx);
199        let rtl = theme.layout.direction == Direction::Rtl;
200        let tone = |role| color(theme.colors.color(role));
201
202        let background = self
203            .colors
204            .background
205            .unwrap_or_else(|| tone(ColorRole::Surface));
206        let foreground = if window.is_window_active() {
207            self.colors
208                .active_foreground
209                .unwrap_or_else(|| tone(ColorRole::OnSurface))
210        } else {
211            self.colors
212                .inactive_foreground
213                .unwrap_or_else(|| tone(ColorRole::OnSurfaceVariant))
214        };
215
216        let type_style = theme
217            .typography
218            .style(self.title_role, TypographyEmphasis::Baseline);
219        let mut resolved_font = self
220            .title_font
221            .unwrap_or_else(|| font_for_style(&theme.typography, type_style, cx));
222        if let Some(family) = self.title_font_family {
223            resolved_font.family = family;
224        }
225        let font_size = self.title_font_size.map_or(px(type_style.size), |size| {
226            sanitize_positive(size, px(type_style.size))
227        });
228
229        let title_text = self
230            .title
231            .unwrap_or_else(|| SharedString::from(read_window_title(window)));
232        let fullscreen = window.is_fullscreen();
233        let platform = self.platform;
234        let show_traffic_light_inset = platform.uses_traffic_lights() && !fullscreen;
235        let has_leading = self.leading.is_some();
236        let title_start_pad = if show_traffic_light_inset || has_leading {
237            px(8.)
238        } else {
239            px(16.)
240        };
241
242        let drag_region = div()
243            .flex()
244            .flex_1()
245            .min_w(px(32.))
246            .items_center()
247            .when(rtl, |title| title.flex_row_reverse().pr(title_start_pad))
248            .when(!rtl, |title| title.pl(title_start_pad))
249            .when(!fullscreen, |title| {
250                let title = title.window_control_area(WindowControlArea::Drag);
251                match platform {
252                    ChromePlatform::MacOs => title.on_mouse_down(
253                        MouseButton::Left,
254                        |event: &MouseDownEvent, window, _| {
255                            if event.click_count == 2 {
256                                window.titlebar_double_click();
257                            }
258                        },
259                    ),
260                    ChromePlatform::Linux => title
261                        .on_mouse_down(MouseButton::Left, |event: &MouseDownEvent, window, _| {
262                            if event.click_count == 2 {
263                                if window.is_resizable() && window.window_controls().maximize {
264                                    window.zoom_window();
265                                }
266                            } else {
267                                window.start_window_move();
268                            }
269                        })
270                        .on_mouse_down(MouseButton::Right, |event: &MouseDownEvent, window, _| {
271                            if window.window_controls().window_menu {
272                                window.show_window_menu(event.position);
273                            }
274                        }),
275                    ChromePlatform::Windows => title,
276                }
277            })
278            .child(
279                div()
280                    .min_w_0()
281                    .truncate()
282                    .font(resolved_font)
283                    .text_size(font_size)
284                    .child(title_text),
285            );
286
287        let caption_buttons = CaptionButtons::new("caption-buttons")
288            .colors(self.caption_colors)
289            .labels(self.caption_labels)
290            .with_button_width_override(self.caption_button_width)
291            .platform(platform)
292            .with_show_override(self.show_caption_buttons)
293            .with_close_handler(self.on_close);
294
295        div()
296            .id(self.id.clone())
297            .flex()
298            .w_full()
299            .h(self.height)
300            .min_h(self.height)
301            .flex_shrink_0()
302            .items_stretch()
303            .when(rtl, |bar| bar.flex_row_reverse())
304            .bg(background)
305            .text_color(foreground)
306            .when_some(self.colors.border, |bar, border| {
307                bar.border_b_1().border_color(border)
308            })
309            .when(show_traffic_light_inset, |bar| {
310                bar.child(
311                    div()
312                        .id((self.id.clone(), "traffic-light-inset"))
313                        .w(self.traffic_light_padding)
314                        .h_full()
315                        .flex_shrink_0(),
316                )
317            })
318            .when_some(self.leading, |bar, leading| {
319                bar.child(
320                    div()
321                        .flex()
322                        .flex_shrink_0()
323                        .items_center()
324                        .when(!show_traffic_light_inset && !rtl, |slot| slot.pl(px(8.)))
325                        .when(!show_traffic_light_inset && rtl, |slot| slot.pr(px(8.)))
326                        .child(leading),
327                )
328            })
329            .child(drag_region)
330            .when_some(self.content, |bar, content| {
331                bar.child(div().flex().min_w_0().items_center().child(content))
332            })
333            .when_some(self.trailing, |bar, trailing| {
334                bar.child(div().flex().min_w_0().items_center().child(trailing))
335            })
336            .child(caption_buttons)
337            .test_support()
338    }
339}