Skip to main content

gpui_component/
title_bar.rs

1use std::rc::Rc;
2
3use crate::{
4    ActiveTheme, Icon, IconName, InteractiveElementExt as _, Sizable as _, StyledExt, h_flex,
5};
6use gpui::{
7    AnyElement, App, Background, ClickEvent, Context, Decorations, Hsla, InteractiveElement,
8    IntoElement, MouseButton, ParentElement, Pixels, Render, RenderOnce, Rgba,
9    StatefulInteractiveElement as _, StyleRefinement, Styled, TitlebarOptions, Window,
10    WindowControlArea, WindowOptions, div, linear_color_stop, linear_gradient,
11    prelude::FluentBuilder as _, px,
12};
13use palette::IntoColor as _;
14use smallvec::SmallVec;
15
16pub const TITLE_BAR_HEIGHT: Pixels = px(34.);
17#[cfg(target_os = "macos")]
18const TITLE_BAR_LEFT_PADDING: Pixels = px(80.);
19#[cfg(not(target_os = "macos"))]
20const TITLE_BAR_LEFT_PADDING: Pixels = px(12.);
21
22fn default_title_bar_background(title_bar: Hsla, background: Hsla) -> Background {
23    let title_bar_rgb: Rgba = title_bar.into_color();
24    let background_rgb: Rgba = background.into_color();
25    let mixed: Hsla = Rgba::new(
26        title_bar_rgb.color.red * 0.55 + background_rgb.color.red * 0.45,
27        title_bar_rgb.color.green * 0.55 + background_rgb.color.green * 0.45,
28        title_bar_rgb.color.blue * 0.55 + background_rgb.color.blue * 0.45,
29        title_bar_rgb.alpha * 0.55 + background_rgb.alpha * 0.45,
30    )
31    .into_color();
32
33    linear_gradient(
34        180.,
35        linear_color_stop(mixed, 0.),
36        linear_color_stop(title_bar, 1.),
37    )
38}
39
40/// TitleBar used to customize the appearance of the title bar.
41///
42/// We can put some elements inside the title bar.
43#[derive(IntoElement)]
44pub struct TitleBar {
45    style: StyleRefinement,
46    children: SmallVec<[AnyElement; 1]>,
47    on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
48}
49
50impl TitleBar {
51    /// Create a new TitleBar.
52    pub fn new() -> Self {
53        Self {
54            style: StyleRefinement::default(),
55            children: SmallVec::new(),
56            on_close_window: None,
57        }
58    }
59
60    /// Returns the default title bar options for compatible with the [`crate::TitleBar`].
61    pub fn title_bar_options() -> TitlebarOptions {
62        TitlebarOptions {
63            title: None,
64            appears_transparent: true,
65            traffic_light_position: Some(gpui::point(px(9.0), px(9.0))),
66        }
67    }
68
69    /// Returns the default window options for compatible with the [`crate::TitleBar`].
70    ///
71    /// Use this as the base of the [`WindowOptions`] of any window that renders a
72    /// [`crate::TitleBar`], so the title bar owns dragging and double clicking itself:
73    ///
74    /// ```no_run
75    /// # use gpui::WindowOptions;
76    /// # use gpui_component::TitleBar;
77    /// let options = WindowOptions {
78    ///     window_min_size: None,
79    ///     ..TitleBar::window_options()
80    /// };
81    /// ```
82    pub fn window_options() -> WindowOptions {
83        WindowOptions {
84            titlebar: Some(Self::title_bar_options()),
85            // The title bar draws itself and moves the window via `start_window_move`,
86            // so AppKit must not treat it as a system window-move region. Otherwise macOS
87            // handles title bar double clicks on its own (in addition to `on_double_click`
88            // below) and delays title bar clicks while disambiguating double clicks.
89            app_owns_titlebar_drag: true,
90            ..Default::default()
91        }
92    }
93
94    /// Add custom for close window event, default is None, then click X button will call `window.remove_window()`.
95    /// Linux only, this will do nothing on other platforms.
96    pub fn on_close_window(
97        mut self,
98        f: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
99    ) -> Self {
100        if cfg!(target_os = "linux") {
101            self.on_close_window = Some(Rc::new(Box::new(f)));
102        }
103        self
104    }
105}
106
107// The Windows control buttons have a fixed width of 35px.
108//
109// We don't need implementation the click event for the control buttons.
110// If user clicked in the bounds, the window event will be triggered.
111#[derive(IntoElement, Clone)]
112enum ControlIcon {
113    Minimize,
114    Restore,
115    Maximize,
116    Close {
117        on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
118    },
119}
120
121impl ControlIcon {
122    fn minimize() -> Self {
123        Self::Minimize
124    }
125
126    fn restore() -> Self {
127        Self::Restore
128    }
129
130    fn maximize() -> Self {
131        Self::Maximize
132    }
133
134    fn close(on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>) -> Self {
135        Self::Close { on_close_window }
136    }
137
138    fn id(&self) -> &'static str {
139        match self {
140            Self::Minimize => "minimize",
141            Self::Restore => "restore",
142            Self::Maximize => "maximize",
143            Self::Close { .. } => "close",
144        }
145    }
146
147    fn icon(&self) -> IconName {
148        match self {
149            Self::Minimize => IconName::WindowMinimize,
150            Self::Restore => IconName::WindowRestore,
151            Self::Maximize => IconName::WindowMaximize,
152            Self::Close { .. } => IconName::WindowClose,
153        }
154    }
155
156    fn window_control_area(&self) -> WindowControlArea {
157        match self {
158            Self::Minimize => WindowControlArea::Min,
159            Self::Restore | Self::Maximize => WindowControlArea::Max,
160            Self::Close { .. } => WindowControlArea::Close,
161        }
162    }
163
164    fn is_close(&self) -> bool {
165        matches!(self, Self::Close { .. })
166    }
167
168    #[inline]
169    fn hover_fg(&self, cx: &App) -> Hsla {
170        if self.is_close() {
171            cx.theme().danger_foreground
172        } else {
173            cx.theme().secondary_foreground
174        }
175    }
176
177    #[inline]
178    fn hover_bg(&self, cx: &App) -> Hsla {
179        if self.is_close() {
180            cx.theme().danger
181        } else {
182            cx.theme().secondary_hover
183        }
184    }
185
186    #[inline]
187    fn active_bg(&self, cx: &mut App) -> Hsla {
188        if self.is_close() {
189            cx.theme().danger_active
190        } else {
191            cx.theme().secondary_active
192        }
193    }
194}
195
196impl RenderOnce for ControlIcon {
197    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
198        let is_linux = cfg!(target_os = "linux");
199        let is_windows = cfg!(target_os = "windows");
200        let hover_fg = self.hover_fg(cx);
201        let hover_bg = self.hover_bg(cx);
202        let active_bg = self.active_bg(cx);
203        let icon = self.clone();
204        let on_close_window = match &self {
205            ControlIcon::Close { on_close_window } => on_close_window.clone(),
206            _ => None,
207        };
208
209        div()
210            .id(self.id())
211            .flex()
212            .w(TITLE_BAR_HEIGHT)
213            .h_full()
214            .flex_shrink_0()
215            .justify_center()
216            .content_center()
217            .items_center()
218            .text_color(cx.theme().foreground)
219            .hover(|style| style.bg(hover_bg).text_color(hover_fg))
220            .active(|style| style.bg(active_bg).text_color(hover_fg))
221            .when(is_windows, |this| {
222                this.window_control_area(self.window_control_area())
223            })
224            .when(is_linux, |this| {
225                this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
226                    window.prevent_default();
227                    cx.stop_propagation();
228                })
229                .on_click(move |_, window, cx| {
230                    cx.stop_propagation();
231                    match icon {
232                        Self::Minimize => window.minimize_window(),
233                        Self::Restore | Self::Maximize => window.zoom_window(),
234                        Self::Close { .. } => {
235                            if let Some(f) = on_close_window.clone() {
236                                f(&ClickEvent::default(), window, cx);
237                            } else {
238                                window.remove_window();
239                            }
240                        }
241                    }
242                })
243            })
244            .child(Icon::new(self.icon()).small())
245    }
246}
247
248#[derive(IntoElement)]
249struct WindowControls {
250    on_close_window: Option<Rc<Box<dyn Fn(&ClickEvent, &mut Window, &mut App)>>>,
251}
252
253impl RenderOnce for WindowControls {
254    fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
255        if cfg!(target_os = "macos") || cfg!(target_family = "wasm") {
256            return div().id("window-controls");
257        }
258
259        // Under server-side decorations the window manager already renders
260        // its own title bar, complete with min/max/close; drawing ours as
261        // well stacks a duplicate set of controls on top of it (most
262        // visibly two close buttons). gpui falls back to server-side
263        // decorations on X11 sessions without a compositor, and a Wayland
264        // compositor may grant server mode even when client mode was
265        // requested. Skip ours unless this window is actually client-side
266        // decorated, mirroring the `is_client_decorated` gating of the
267        // title bar's window-menu overlay.
268        #[cfg(target_os = "linux")]
269        if !matches!(window.window_decorations(), Decorations::Client { .. }) {
270            return div().id("window-controls");
271        }
272
273        // The window manager declares which controls it can honor; a tiling
274        // compositor may support neither minimize nor maximize. Close is
275        // always ours to offer.
276        let supported = window.window_controls();
277
278        h_flex()
279            .id("window-controls")
280            .items_center()
281            .flex_shrink_0()
282            .h_full()
283            .when(supported.minimize, |this| {
284                this.child(ControlIcon::minimize())
285            })
286            .when(supported.maximize, |this| {
287                this.child(if window.is_maximized() {
288                    ControlIcon::restore()
289                } else {
290                    ControlIcon::maximize()
291                })
292            })
293            .child(ControlIcon::close(self.on_close_window))
294    }
295}
296
297impl Styled for TitleBar {
298    fn style(&mut self) -> &mut gpui::StyleRefinement {
299        &mut self.style
300    }
301}
302
303impl ParentElement for TitleBar {
304    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
305        self.children.extend(elements);
306    }
307}
308
309struct TitleBarState {
310    should_move: bool,
311}
312
313// TODO: Remove this when GPUI has released v0.2.3
314impl Render for TitleBarState {
315    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
316        div()
317    }
318}
319
320impl RenderOnce for TitleBar {
321    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
322        let is_client_decorated = matches!(window.window_decorations(), Decorations::Client { .. });
323        let is_web = cfg!(target_family = "wasm");
324        let is_linux = cfg!(target_os = "linux");
325        let is_macos = cfg!(target_os = "macos");
326
327        let state = window.use_state(cx, |_, _| TitleBarState { should_move: false });
328
329        div().flex_shrink_0().child(
330            div()
331                .id("title-bar")
332                .flex()
333                .flex_row()
334                .items_center()
335                .justify_between()
336                .h(TITLE_BAR_HEIGHT)
337                .pl(TITLE_BAR_LEFT_PADDING)
338                .border_b_1()
339                .border_color(cx.theme().title_bar_border)
340                .bg(default_title_bar_background(
341                    cx.theme().title_bar,
342                    cx.theme().background,
343                ))
344                .refine_style(&self.style)
345                .when(is_linux, |this| {
346                    this.on_double_click(|_, window, _| window.zoom_window())
347                })
348                .when(is_macos, |this| {
349                    this.on_double_click(|_, window, _| window.titlebar_double_click())
350                })
351                .on_mouse_down_out(window.listener_for(&state, |state, _, _, _| {
352                    state.should_move = false;
353                }))
354                .on_mouse_down(
355                    MouseButton::Left,
356                    window.listener_for(&state, |state, _, _, _| {
357                        state.should_move = true;
358                    }),
359                )
360                .on_mouse_up(
361                    MouseButton::Left,
362                    window.listener_for(&state, |state, _, _, _| {
363                        state.should_move = false;
364                    }),
365                )
366                .on_mouse_move(window.listener_for(&state, |state, _, window, _| {
367                    if state.should_move {
368                        state.should_move = false;
369                        window.start_window_move();
370                    }
371                }))
372                .child(
373                    h_flex()
374                        .id("bar")
375                        .h_full()
376                        .justify_between()
377                        .flex_shrink_0()
378                        .flex_1()
379                        .when(!is_web, |this| {
380                            this.window_control_area(WindowControlArea::Drag)
381                                .when(window.is_fullscreen(), |this| this.pl_3())
382                                .when(is_linux && is_client_decorated, |this| {
383                                    this.child(
384                                        div()
385                                            .top_0()
386                                            .left_0()
387                                            .absolute()
388                                            .size_full()
389                                            .h_full()
390                                            .on_mouse_down(
391                                                MouseButton::Right,
392                                                move |ev, window, _| {
393                                                    window.show_window_menu(ev.position)
394                                                },
395                                            ),
396                                    )
397                                })
398                        })
399                        .children(self.children),
400                )
401                .child(WindowControls {
402                    on_close_window: self.on_close_window,
403                }),
404        )
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411    use gpui::{Rgba, linear_color_stop, linear_gradient};
412
413    #[test]
414    fn test_default_title_bar_background() {
415        let title_bar = gpui::black();
416        let background = gpui::white();
417
418        assert_eq!(
419            default_title_bar_background(title_bar, background),
420            linear_gradient(
421                180.,
422                linear_color_stop(gpui::rgb_to_hsla(Rgba::new(0.45, 0.45, 0.45, 1.)), 0.,),
423                linear_color_stop(title_bar, 1.),
424            )
425        );
426    }
427}