Skip to main content

gpui_material_extras/window_chrome/
platform.rs

1use std::rc::Rc;
2
3use gpui::{
4    App, Decorations, Pixels, SharedString, Window, WindowDecorations, WindowOptions, point, px,
5};
6
7/// Default logical height for a client-drawn [`super::TitleBar`].
8pub const DEFAULT_TITLE_BAR_HEIGHT: Pixels = px(48.);
9
10/// Default leading inset reserved for native macOS traffic light buttons.
11pub const DEFAULT_MACOS_TRAFFIC_LIGHT_PADDING: Pixels = px(78.);
12
13/// Default logical width for each caption button on Windows.
14pub const DEFAULT_WINDOWS_CAPTION_BUTTON_WIDTH: Pixels = px(46.);
15
16/// Default logical width for each caption button on Linux CSD title bars.
17pub const DEFAULT_LINUX_CAPTION_BUTTON_WIDTH: Pixels = px(40.);
18
19pub(super) type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
20
21/// Target desktop chrome presentation model.
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
23pub enum ChromePlatform {
24    /// Windows client-drawn title bar with native `WindowControlArea` hit testing
25    /// and Snap Layouts.
26    Windows,
27    /// macOS transparent title bar reserving space for native traffic light buttons.
28    MacOs,
29    /// Linux Wayland/X11 title bar adapting to `Decorations::Client` and
30    /// `Decorations::Server`.
31    Linux,
32}
33
34impl ChromePlatform {
35    /// Returns the compile-time target chrome platform.
36    pub const fn current() -> Self {
37        #[cfg(target_os = "macos")]
38        {
39            Self::MacOs
40        }
41        #[cfg(windows)]
42        {
43            Self::Windows
44        }
45        #[cfg(not(any(windows, target_os = "macos")))]
46        {
47            Self::Linux
48        }
49    }
50
51    /// Returns whether this platform uses native macOS traffic light buttons.
52    pub const fn uses_traffic_lights(self) -> bool {
53        matches!(self, Self::MacOs)
54    }
55
56    /// Returns whether this platform renders client-drawn caption buttons by default.
57    pub const fn uses_caption_buttons(self) -> bool {
58        matches!(self, Self::Windows | Self::Linux)
59    }
60
61    pub(super) const fn default_caption_button_width(self) -> Pixels {
62        match self {
63            Self::Windows => DEFAULT_WINDOWS_CAPTION_BUTTON_WIDTH,
64            Self::MacOs | Self::Linux => DEFAULT_LINUX_CAPTION_BUTTON_WIDTH,
65        }
66    }
67}
68
69/// Configures a window to draw its own cross-platform title bar with the default
70/// [`DEFAULT_TITLE_BAR_HEIGHT`].
71///
72/// Mount a [`super::TitleBar`] or compose a custom drag region and
73/// [`super::CaptionButtons`] in the window view. Caller-supplied title, bounds,
74/// minimum size, traffic light position, decoration preference, and capability
75/// flags are preserved.
76pub fn title_bar_window_options(options: WindowOptions) -> WindowOptions {
77    title_bar_window_options_with_height(options, DEFAULT_TITLE_BAR_HEIGHT)
78}
79
80/// Configures a window to draw its own cross-platform title bar targeting a
81/// specific logical title bar height.
82///
83/// On Windows and macOS this enables `TitlebarOptions::appears_transparent`. On
84/// macOS it also computes a vertically centered default `traffic_light_position`
85/// from `height` when the caller did not supply one. On Linux it requests
86/// `WindowDecorations::Client` when `window_decorations` is unset.
87pub fn title_bar_window_options_with_height(
88    options: WindowOptions,
89    height: Pixels,
90) -> WindowOptions {
91    configure_window_options(options, height, ChromePlatform::current())
92}
93
94pub(super) fn configure_window_options(
95    mut options: WindowOptions,
96    height: Pixels,
97    platform: ChromePlatform,
98) -> WindowOptions {
99    let height = sanitize_positive(height, DEFAULT_TITLE_BAR_HEIGHT);
100    let titlebar = options.titlebar.get_or_insert_default();
101    titlebar.appears_transparent = true;
102
103    match platform {
104        ChromePlatform::MacOs => {
105            if titlebar.traffic_light_position.is_none() {
106                // Native macOS traffic light glyphs are roughly 14 px tall.
107                let y = ((height - px(14.)) * 0.5).max(px(6.));
108                titlebar.traffic_light_position = Some(point(px(12.), y));
109            }
110        }
111        ChromePlatform::Linux => {
112            if options.window_decorations.is_none() {
113                options.window_decorations = Some(WindowDecorations::Client);
114            }
115        }
116        ChromePlatform::Windows => {}
117    }
118
119    options
120}
121
122pub(super) fn sanitize_positive(value: Pixels, fallback: Pixels) -> Pixels {
123    let raw = f32::from(value);
124    if raw.is_finite() && raw > 0. {
125        value
126    } else {
127        fallback
128    }
129}
130
131pub(super) fn sanitize_nonnegative(value: Pixels, fallback: Pixels) -> Pixels {
132    let raw = f32::from(value);
133    if raw.is_finite() && raw >= 0. {
134        value
135    } else {
136        fallback
137    }
138}
139
140pub(super) fn should_show_title_bar(
141    window: &Window,
142    platform: ChromePlatform,
143    show_caption_buttons: Option<bool>,
144) -> bool {
145    !(platform == ChromePlatform::Linux
146        && matches!(window.window_decorations(), Decorations::Server)
147        && show_caption_buttons != Some(true))
148}
149
150pub(super) fn should_show_caption_buttons(
151    window: &Window,
152    platform: ChromePlatform,
153    explicit: Option<bool>,
154) -> bool {
155    if window.is_fullscreen() {
156        return false;
157    }
158    if let Some(show) = explicit {
159        return show;
160    }
161    match platform {
162        ChromePlatform::Windows => true,
163        ChromePlatform::MacOs => false,
164        ChromePlatform::Linux => matches!(window.window_decorations(), Decorations::Client { .. }),
165    }
166}
167
168pub(super) fn read_window_title(window: &Window) -> SharedString {
169    #[cfg(windows)]
170    {
171        if let Some(title) = win32::window_title(window) {
172            return title;
173        }
174    }
175    SharedString::from(window.window_title())
176}
177
178pub(super) fn activate_minimize(window: &mut Window) {
179    window.minimize_window();
180}
181
182pub(super) fn activate_maximize_or_restore(window: &mut Window) {
183    #[cfg(windows)]
184    {
185        if window.is_maximized() && win32::restore_window(window) {
186            return;
187        }
188    }
189    window.zoom_window();
190}
191
192pub(super) fn activate_close(window: &mut Window, cx: &mut App, on_close: Option<&CloseHandler>) {
193    if let Some(handler) = on_close {
194        handler(window, cx);
195        return;
196    }
197    #[cfg(windows)]
198    {
199        if win32::close_window(window) {
200            return;
201        }
202    }
203    window.remove_window();
204}
205
206#[cfg(windows)]
207mod win32 {
208    use std::{
209        cell::RefCell,
210        collections::HashMap,
211        time::{Duration, Instant},
212    };
213
214    use gpui::{SharedString, Window};
215    use raw_window_handle::{HasWindowHandle, RawWindowHandle};
216    use windows::Win32::{
217        Foundation::{HWND, LPARAM, WPARAM},
218        UI::WindowsAndMessaging::{
219            GetWindowTextLengthW, GetWindowTextW, PostMessageW, SC_RESTORE, WM_CLOSE, WM_SYSCOMMAND,
220        },
221    };
222
223    const TITLE_CACHE_TTL: Duration = Duration::from_millis(250);
224
225    thread_local! {
226        static TITLE_CACHE: RefCell<HashMap<isize, (Instant, SharedString)>> =
227            RefCell::new(HashMap::new());
228    }
229
230    pub(super) fn window_title(window: &Window) -> Option<SharedString> {
231        let hwnd = window_hwnd(window)?;
232        let key = hwnd.0 as isize;
233        let now = Instant::now();
234        if let Some(cached) = TITLE_CACHE.with(|cache| {
235            let cache = cache.borrow();
236            cache.get(&key).and_then(|(at, title)| {
237                (now.saturating_duration_since(*at) < TITLE_CACHE_TTL).then(|| title.clone())
238            })
239        }) {
240            return Some(cached);
241        }
242
243        // GPUI's window_title getter currently only reads the platform title on macOS.
244        // Windows reads the title from the live HWND into a caller-owned buffer.
245        let length = unsafe { GetWindowTextLengthW(hwnd) };
246        if length < 0 {
247            return None;
248        }
249        let title = if length == 0 {
250            SharedString::new_static("")
251        } else {
252            let mut buffer = vec![0u16; length as usize + 1];
253            let copied = unsafe { GetWindowTextW(hwnd, &mut buffer) };
254            if copied < 0 {
255                return None;
256            }
257            let copied = (copied as usize).min(buffer.len());
258            SharedString::from(String::from_utf16_lossy(&buffer[..copied]))
259        };
260
261        TITLE_CACHE.with(|cache| {
262            let mut cache = cache.borrow_mut();
263            if cache.len() >= 32 {
264                cache.retain(|_, (at, _)| now.saturating_duration_since(*at) < TITLE_CACHE_TTL);
265            }
266            cache.insert(key, (now, title.clone()));
267        });
268        Some(title)
269    }
270
271    pub(super) fn restore_window(window: &Window) -> bool {
272        post_window_message(window, WM_SYSCOMMAND, WPARAM(SC_RESTORE as usize))
273    }
274
275    pub(super) fn close_window(window: &Window) -> bool {
276        post_window_message(window, WM_CLOSE, WPARAM(0))
277    }
278
279    fn post_window_message(window: &Window, message: u32, wparam: WPARAM) -> bool {
280        let Some(hwnd) = window_hwnd(window) else {
281            return false;
282        };
283        // Queue the command so GPUI handles it after the current input dispatch.
284        // The HWND comes from the live window, and neither message carries pointers.
285        unsafe { PostMessageW(Some(hwnd), message, wparam, LPARAM(0)) }.is_ok()
286    }
287
288    fn window_hwnd(window: &Window) -> Option<HWND> {
289        let handle = HasWindowHandle::window_handle(window).ok()?;
290        let RawWindowHandle::Win32(handle) = handle.as_raw() else {
291            return None;
292        };
293        Some(HWND(handle.hwnd.get() as *mut _))
294    }
295}