Skip to main content

ui/
titlebar.rs

1//! [`titlebar`] — the strip a window with no system titlebar moves itself by.
2//!
3//! The strip does not move the window. A [`grip`] in it does, and everything
4//! else in the bar is an ordinary element.
5//!
6//! That split is forced by how the platform asks. Windows answers
7//! `WM_NCHITTEST` out of a flat list of control areas and takes the first one
8//! the pointer falls in, parent before child — so a bar that is itself one
9//! drag area turns every control in it into a window handle, unless each
10//! control blocks the mouse, and blocking the mouse also takes the scroll
11//! wheel from everything behind it. Naming the drag surface instead is what
12//! AppKit does with a drag gesture on a view, and it costs no control
13//! anything.
14//!
15//! Three platforms, three mechanisms, all of them on the grip: AppKit drags by
16//! itself, Linux is told to with `start_window_move` on the first *motion*
17//! after a press rather than on the press, and Windows implements neither and
18//! reads `WindowControlArea::Drag` back out of the hit test.
19//!
20//! The macOS traffic lights need [`Theme::TRAFFIC_LIGHT_INSET`] of leading
21//! room, which is nothing until the window goes full screen and AppKit takes
22//! them away. Off macOS the buttons are the app's to paint: [`controls`] is
23//! the cluster, and the frame around it — border, corners, shadow, resize
24//! edges — is [`crate::window::frame`].
25//!
26//! The window it belongs to opens with `appears_transparent: true`, and on
27//! Linux asks for `WindowDecorations::Client`. On macOS AppKit still drags the
28//! window by its transparent titlebar, and a [`grip`] there is redundant.
29//!
30//! ```ignore
31//! titlebar::titlebar("titlebar", true, window)
32//!     .px(px(8.0))
33//!     .child(/* … */)
34//!     .child(titlebar::grip("titlebar-grip", &self.drag, window))
35//!     .child(titlebar::controls(CaptionSide::Right, window, cx))
36//! ```
37
38use std::{cell::Cell, rc::Rc};
39
40use gpui::{
41    App, Div, ElementId, MAX_BUTTONS_PER_SIDE, MouseButton, Stateful, Window, WindowButton,
42    WindowButtonLayout, WindowControlArea, div, prelude::*, px,
43};
44
45use theme::Theme;
46
47/// Whether the press on a [`grip`] is still a candidate for a window move.
48///
49/// Shaped like [`crate::scroll::FollowState`] and for the same reason: it
50/// mutates through `&self`, so the element carries the whole gesture and the
51/// view holds one field.
52#[derive(Clone, Default)]
53pub struct DragState(Rc<Cell<bool>>);
54
55/// The strip: full width, [`Theme::TITLEBAR_HEIGHT`] tall, and inert. What it
56/// holds is the caller's, including [`grip`], without which the window has no
57/// handle off macOS.
58///
59/// `traffic_lights` reserves the leading inset for the macOS buttons — pass it
60/// on the one strip they sit over, and it stands down in full screen, where
61/// they are gone and the gap would be a hole.
62pub fn titlebar(id: impl Into<ElementId>, traffic_lights: bool, window: &Window) -> Stateful<Div> {
63    div()
64        .id(id)
65        .w_full()
66        .h(px(Theme::TITLEBAR_HEIGHT))
67        .flex()
68        .flex_row()
69        .items_center()
70        .when(traffic_lights && !window.is_fullscreen(), |bar| {
71            bar.pl(px(Theme::TRAFFIC_LIGHT_INSET))
72        })
73}
74
75/// The bare stretch of a titlebar that drags its window, zooms it on a double
76/// click and opens the desktop's window menu on a right press.
77///
78/// Takes the free space in the bar, so it is the room the content leaves. A
79/// bar whose content fills it has no handle — the window can then only be
80/// moved by its own edges, where the system has any.
81///
82/// Nothing needs to opt out of it: a control beside a grip is not inside it,
83/// and the platform hit test only ever lands in one of them.
84pub fn grip(id: impl Into<ElementId>, drag: &DragState, window: &Window) -> Stateful<Div> {
85    let (armed, disarm, release) = (drag.0.clone(), drag.0.clone(), drag.0.clone());
86    let moving = drag.0.clone();
87    let zoomable = window.window_controls().maximize && window.is_resizable();
88    div()
89        .id(id)
90        .flex_1()
91        .self_stretch()
92        .on_mouse_down(MouseButton::Left, move |_, _, _| armed.set(true))
93        .on_mouse_up(MouseButton::Left, move |_, _, _| release.set(false))
94        // A press that leaves the grip is not a window move either — without
95        // this the flag survives, and the next stray motion over it drags the
96        // window with no button held.
97        .on_mouse_down_out(move |_, _, _| disarm.set(false))
98        .on_mouse_move(move |_, window, _| {
99            if moving.replace(false) {
100                window.start_window_move();
101            }
102        })
103        // What Windows moves by: the area answers `WM_NCHITTEST` with
104        // `HTCAPTION`, and the system drag, the edge snap and the double-click
105        // zoom all follow from that. `start_window_move` above is the Linux
106        // path and is not implemented there at all.
107        .window_control_area(WindowControlArea::Drag)
108        // The window menu the desktop hangs off its own titlebar, where the
109        // compositor says there is one. On the press, which is where a context
110        // menu belongs, and a no-op on macOS and on Windows, where the system
111        // menu comes from the caption hit test instead.
112        .when(window.window_controls().window_menu, |grip| {
113            grip.on_mouse_down(MouseButton::Right, |event, window, _| {
114                window.show_window_menu(event.position);
115            })
116        })
117        .on_click(move |click, window, _| {
118            if click.click_count() == 2 {
119                // macOS runs whatever the user set the gesture to — zoom,
120                // minimise or nothing — and Windows zooms from `HTCAPTION`
121                // without being asked. Linux has neither, and only where the
122                // window can be zoomed at all.
123                match cfg!(any(target_os = "linux", target_os = "freebsd")) {
124                    true if zoomable => window.zoom_window(),
125                    true => {}
126                    false => window.titlebar_double_click(),
127                }
128            }
129        })
130}
131
132/// Which end of the bar a caption cluster sits at.
133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
134pub enum CaptionSide {
135    Left,
136    Right,
137}
138
139/// The caption buttons, for a window whose system caption is gone —
140/// `appears_transparent` on Windows, `Decorations::Client` on Linux.
141///
142/// Call it at both ends of the bar and let the desktop decide which end fills:
143/// `App::button_layout` reads GNOME's `gtk-decoration-layout`, and a platform
144/// that reports no layout at all puts the three on the right.
145///
146/// Empty in full screen, and short whatever `Window::window_controls` says the
147/// compositor will refuse. Close is never refused.
148///
149/// The cluster takes its own width in the bar, so nothing is reserved for it
150/// the way [`Theme::TRAFFIC_LIGHT_INSET`] is reserved for AppKit's lights —
151/// those are painted over the client area by someone else, and these are not.
152///
153/// ```ignore
154/// titlebar::titlebar("titlebar", true, window)
155///     .child(titlebar::controls(CaptionSide::Left, window, cx))
156///     .child(titlebar::grip("titlebar-grip", &self.drag, window))
157///     .child(titlebar::controls(CaptionSide::Right, window, cx))
158/// ```
159pub fn controls(side: CaptionSide, window: &Window, cx: &App) -> Div {
160    let row = div().flex().flex_row().items_center().h_full();
161    if window.is_fullscreen() {
162        return row;
163    }
164
165    let allowed = window.window_controls();
166    let layout = cx.button_layout().unwrap_or(TRAILING);
167    let buttons = match side {
168        CaptionSide::Left => layout.left,
169        CaptionSide::Right => layout.right,
170    };
171
172    buttons
173        .into_iter()
174        .flatten()
175        .filter(|button| match button {
176            WindowButton::Close => true,
177            WindowButton::Maximize => allowed.maximize,
178            WindowButton::Minimize => allowed.minimize,
179        })
180        .fold(row, |row, button| {
181            row.child(caption_button(button, window, cx))
182        })
183}
184
185/// What a platform with no layout of its own gets: all three, trailing.
186const TRAILING: WindowButtonLayout = WindowButtonLayout {
187    left: [None; MAX_BUTTONS_PER_SIDE],
188    right: [
189        Some(WindowButton::Minimize),
190        Some(WindowButton::Maximize),
191        Some(WindowButton::Close),
192    ],
193};
194
195/// The caption glyphs are drawn to their own scale, not the type ladder's —
196/// Windows sets them at 10px whatever the shell font is doing.
197const CAPTION_GLYPH: f32 = 10.0;
198
199/// One caption button: the glyph, the hover wash, and the hitbox the platform
200/// reads.
201///
202/// The click is wired everywhere but Windows, where answering `WM_NCHITTEST`
203/// with `HTCLOSE` and friends has already handed the press to the system —
204/// acting on it here as well would minimise and restore in one gesture.
205fn caption_button(button: WindowButton, window: &Window, cx: &App) -> Stateful<Div> {
206    let theme = Theme::of(cx);
207    let (area, glyph, hover) = match button {
208        WindowButton::Close => (WindowControlArea::Close, icons::glyph::X, theme.danger),
209        WindowButton::Minimize => (
210            WindowControlArea::Min,
211            icons::glyph::Minus,
212            theme.element_hover,
213        ),
214        // The restore mark is two offset squares, which is what `copy` draws.
215        WindowButton::Maximize => (
216            WindowControlArea::Max,
217            match window.is_maximized() {
218                true => icons::glyph::Copy,
219                false => icons::glyph::Square,
220            },
221            theme.element_hover,
222        ),
223    };
224
225    div()
226        .id(button.id())
227        .flex()
228        .items_center()
229        .justify_center()
230        .w(px(Theme::CAPTION_BUTTON_WIDTH))
231        .h_full()
232        .hover(|button| button.bg(hover))
233        .child(
234            icons::icon(glyph)
235                .size(px(CAPTION_GLYPH))
236                .text_color(theme.text),
237        )
238        .window_control_area(area)
239        .when(!cfg!(target_os = "windows"), |control| {
240            control.on_click(move |_, window, _| match button {
241                WindowButton::Close => window.remove_window(),
242                WindowButton::Minimize => window.minimize_window(),
243                WindowButton::Maximize => window.zoom_window(),
244            })
245        })
246}