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    if platform == ChromePlatform::Linux
146        && matches!(window.window_decorations(), Decorations::Server)
147        && show_caption_buttons != Some(true)
148    {
149        return false;
150    }
151    true
152}
153
154pub(super) fn should_show_caption_buttons(
155    window: &Window,
156    platform: ChromePlatform,
157    explicit: Option<bool>,
158) -> bool {
159    if window.is_fullscreen() {
160        return false;
161    }
162    if let Some(show) = explicit {
163        return show;
164    }
165    match platform {
166        ChromePlatform::Windows => true,
167        ChromePlatform::MacOs => false,
168        ChromePlatform::Linux => matches!(window.window_decorations(), Decorations::Client { .. }),
169    }
170}
171
172pub(super) fn read_window_title(window: &Window) -> SharedString {
173    #[cfg(windows)]
174    {
175        if let Some(title) = win32::window_title(window) {
176            return title;
177        }
178    }
179    SharedString::from(window.window_title())
180}
181
182pub(super) fn activate_minimize(window: &mut Window) {
183    window.minimize_window();
184}
185
186pub(super) fn activate_maximize_or_restore(window: &mut Window) {
187    #[cfg(windows)]
188    {
189        if window.is_maximized() && win32::restore_window(window) {
190            return;
191        }
192    }
193    window.zoom_window();
194}
195
196pub(super) fn activate_close(window: &mut Window, cx: &mut App, on_close: Option<&CloseHandler>) {
197    if let Some(handler) = on_close {
198        handler(window, cx);
199        return;
200    }
201    #[cfg(windows)]
202    {
203        if win32::close_window(window) {
204            return;
205        }
206    }
207    window.remove_window();
208}
209
210#[cfg(windows)]
211mod win32 {
212    use std::{
213        cell::RefCell,
214        collections::HashMap,
215        time::{Duration, Instant},
216    };
217
218    use gpui::{SharedString, Window};
219    use raw_window_handle::{HasWindowHandle, RawWindowHandle};
220    use windows::Win32::{
221        Foundation::{HWND, LPARAM, WPARAM},
222        UI::WindowsAndMessaging::{
223            GetWindowTextLengthW, GetWindowTextW, PostMessageW, SC_RESTORE, WM_CLOSE, WM_SYSCOMMAND,
224        },
225    };
226
227    const TITLE_CACHE_TTL: Duration = Duration::from_millis(250);
228
229    thread_local! {
230        static TITLE_CACHE: RefCell<HashMap<isize, (Instant, SharedString)>> =
231            RefCell::new(HashMap::new());
232    }
233
234    pub(super) fn window_title(window: &Window) -> Option<SharedString> {
235        let hwnd = window_hwnd(window)?;
236        let key = hwnd.0 as isize;
237        let now = Instant::now();
238        if let Some(cached) = TITLE_CACHE.with(|cache| {
239            let cache = cache.borrow();
240            cache.get(&key).and_then(|(at, title)| {
241                (now.saturating_duration_since(*at) < TITLE_CACHE_TTL).then(|| title.clone())
242            })
243        }) {
244            return Some(cached);
245        }
246
247        // GPUI's window_title getter currently only reads the platform title on macOS.
248        // Windows reads the title from the live HWND into a caller-owned buffer.
249        let length = unsafe { GetWindowTextLengthW(hwnd) };
250        if length < 0 {
251            return None;
252        }
253        let title = if length == 0 {
254            SharedString::new_static("")
255        } else {
256            let mut buffer = vec![0u16; length as usize + 1];
257            let copied = unsafe { GetWindowTextW(hwnd, &mut buffer) };
258            if copied < 0 {
259                return None;
260            }
261            let copied = (copied as usize).min(buffer.len());
262            SharedString::from(String::from_utf16_lossy(&buffer[..copied]))
263        };
264
265        TITLE_CACHE.with(|cache| {
266            let mut cache = cache.borrow_mut();
267            if cache.len() >= 32 {
268                cache.retain(|_, (at, _)| now.saturating_duration_since(*at) < TITLE_CACHE_TTL);
269            }
270            cache.insert(key, (now, title.clone()));
271        });
272        Some(title)
273    }
274
275    pub(super) fn restore_window(window: &Window) -> bool {
276        post_window_message(window, WM_SYSCOMMAND, WPARAM(SC_RESTORE as usize))
277    }
278
279    pub(super) fn close_window(window: &Window) -> bool {
280        post_window_message(window, WM_CLOSE, WPARAM(0))
281    }
282
283    fn post_window_message(window: &Window, message: u32, wparam: WPARAM) -> bool {
284        let Some(hwnd) = window_hwnd(window) else {
285            return false;
286        };
287        // Queue the command so GPUI handles it after the current input dispatch.
288        // The HWND comes from the live window, and neither message carries pointers.
289        unsafe { PostMessageW(Some(hwnd), message, wparam, LPARAM(0)) }.is_ok()
290    }
291
292    fn window_hwnd(window: &Window) -> Option<HWND> {
293        let handle = HasWindowHandle::window_handle(window).ok()?;
294        let RawWindowHandle::Win32(handle) = handle.as_raw() else {
295            return None;
296        };
297        Some(HWND(handle.hwnd.get() as *mut _))
298    }
299}