From 1a470e2a23f4fa237fb6e1c9f5a8ec02be89f387 Mon Sep 17 00:00:00 2001 From: Gabriel Gondim <52431033+GGVidal@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:28:43 -0300 Subject: [PATCH] fix(window): host system buttons in the macOS fullscreen title bar (#4923) In native full screen on macOS, the window buttons lived in the title bar strip AppKit slides down with the menu bar, which showed up as a dark band over the IDE's own title bar. Full screen now hosts system window buttons made by standardWindowButton:forStyleMask: in the slot the page keeps for them, and hides that strip. The strip is re-hidden from its own window notifications (no polling), matched by its exact class, and only for the window in full screen. Fixes #4746 Co-authored-by: GGVidal <52431033+GGVidal@users.noreply.github.com> --- src-tauri/src/titlebar.rs | 391 +++++++++++++++++- .../settings/__tests__/contrast.test.ts | 4 +- src/workbench/TitleBar.module.css | 9 +- src/workbench/TitleBar.tsx | 3 - src/workbench/useFullscreen.ts | 28 -- 5 files changed, 375 insertions(+), 60 deletions(-) delete mode 100644 src/workbench/useFullscreen.ts diff --git a/src-tauri/src/titlebar.rs b/src-tauri/src/titlebar.rs index 9f4cc002c..8859a8a93 100644 --- a/src-tauri/src/titlebar.rs +++ b/src-tauri/src/titlebar.rs @@ -6,19 +6,34 @@ //! //! In native full screen the same toolbar is drawn as an opaque strip over the web title bar, so //! it is hidden from the moment the window starts entering full screen until it has left (#1899). +//! +//! Full screen also parks the window buttons in the title bar AppKit reveals with the menu bar. +//! Moving that title-bar view out of the window asserts in `_relinquishTitlebar`, so full screen +//! hosts a second set made by `standardWindowButton:forStyleMask:` (the buttons IntelliJ's runtime +//! uses) in the slot the page keeps, and hides the menu-bar strip (#4746). use objc2::{ - MainThreadMarker, + MainThreadMarker, msg_send, rc::{Retained, Weak}, - runtime::ProtocolObject, + runtime::{AnyClass, ProtocolObject}, + sel, }; use objc2_app_kit::{ - NSToolbar, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowDidEnterFullScreenNotification, - NSWindowDidExitFullScreenNotification, NSWindowStyleMask, NSWindowToolbarStyle, - NSWindowWillEnterFullScreenNotification, + NSApplication, NSAutoresizingMaskOptions, NSToolbar, NSView, NSWindow, NSWindowButton, + NSWindowDidBecomeKeyNotification, NSWindowDidChangeOcclusionStateNotification, + NSWindowDidEnterFullScreenNotification, NSWindowDidExitFullScreenNotification, NSWindowDidUpdateNotification, + NSWindowOrderingMode, NSWindowStyleMask, NSWindowTitleVisibility, NSWindowToolbarStyle, + NSWindowWillEnterFullScreenNotification, NSWindowWillExitFullScreenNotification, +}; +use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSPoint, NSRect, NSSize}; +use std::{ + cell::Cell, + cell::RefCell, + collections::HashMap, + ffi::CStr, + rc::Rc, + sync::atomic::{AtomicBool, Ordering}, }; -use objc2_foundation::{NSNotificationCenter, NSObjectProtocol}; -use std::{cell::Cell, cell::RefCell, collections::HashMap, rc::Rc}; use tauri::Manager; /// The native chrome around the window buttons: the plain title bar (28pt), or an empty unified @@ -47,21 +62,42 @@ fn chrome_for(height: f64) -> Chrome { /// Whether a window is in, or on its way into, native full screen. `styleMask` cannot answer /// this: its full screen flag only turns on at `didEnterFullScreen`, after the resize. +/// `leaving` is set at `willExit` so the buttons return before the animation, while the toolbar +/// stays hidden until `didExit`. #[derive(Default)] -struct Fullscreen(Cell); +struct Fullscreen { + entered: Cell, + leaving: Cell, +} impl Fullscreen { fn will_enter(&self) { - self.0.set(true); + self.entered.set(true); + self.leaving.set(false); + } + + fn will_exit(&self) { + self.leaving.set(true); } fn did_exit(&self) { - self.0.set(false); + self.entered.set(false); + self.leaving.set(false); } fn toolbar_visible(&self) -> bool { - !self.0.get() + !self.entered.get() } + + /// Buttons stay on the theme frame only while full screen is settled, not while leaving it. + fn hosts_buttons(&self) -> bool { + self.entered.get() && !self.leaving.get() + } +} + +/// The system buttons hosted in the page's title-bar slot for the duration of full screen. +struct ButtonHost { + slot: Retained, } struct Observer(Retained>); @@ -73,22 +109,266 @@ impl Drop for Observer { } } +/// `DidUpdate` on the one strip window belonging to a fullscreen window. +struct StripBinding { + strip: Weak, + _update: Observer, +} + struct Tracked { state: Rc, - _observers: [Observer; 4], + height: Rc>, + buttons: Rc>>, + strip: Rc>>, + _observers: [Observer; 6], } thread_local! { static WINDOWS: RefCell> = RefCell::default(); } -fn apply(window: &NSWindow, state: &Fullscreen) { +fn sync_chrome( + window: &NSWindow, + state: &Rc, + height: f64, + buttons: &RefCell>, + strip: &RefCell>, +) { if let Some(toolbar) = window.toolbar() { let visible = state.toolbar_visible(); if toolbar.isVisible() != visible { toolbar.setVisible(visible); } } + if state.hosts_buttons() { + transparent_titlebar(window); + host_buttons(window, height, buttons); + bind_strip(window, state, strip); + } else { + restore_buttons(buttons); + release_strip(strip); + } +} + +/// Full-screen content draws under a transparent title bar, so the reparented buttons sit in the +/// page's slot instead of a separate strip. +fn transparent_titlebar(window: &NSWindow) { + if !window.styleMask().contains(NSWindowStyleMask::FullSizeContentView) { + let mut mask = window.styleMask(); + mask.insert(NSWindowStyleMask::FullSizeContentView); + window.setStyleMask(mask); + } + window.setTitlebarAppearsTransparent(true); + window.setTitleVisibility(NSWindowTitleVisibility::Hidden); +} + +/// Left inset AppKit uses for the button container on the desktop. +const BUTTON_X: f64 = 7.0; + +/// Origin of the button container in a top-left title-bar slot. AppKit's y grows upward. +fn button_origin(parent_height: f64, titlebar_height: f64, button_height: f64) -> (f64, f64) { + let y = parent_height - titlebar_height + (titlebar_height - button_height).max(0.0) / 2.0; + (BUTTON_X, y) +} + +fn host_buttons(window: &NSWindow, height: f64, buttons: &RefCell>) { + let Some(content) = window.contentView() else { return }; + let Some(mtm) = MainThreadMarker::new() else { return }; + if buttons.borrow().is_none() { + let Some(slot) = fullscreen_buttons(window, mtm) else { return }; + buttons.borrow_mut().replace(ButtonHost { slot }); + } + let host = buttons.borrow(); + let Some(host) = host.as_ref() else { return }; + let slot = &host.slot; + let (x, y) = button_origin(content.bounds().size.height, height, slot.frame().size.height); + slot.setFrameOrigin(NSPoint::new(x, y)); + slot.setAutoresizingMask(NSAutoresizingMaskOptions::ViewMinYMargin); + // Above the layer-backed web view. A non-layer sibling paints behind it. + slot.setWantsLayer(true); + content.addSubview_positioned_relativeTo(slot, NSWindowOrderingMode::Above, None); +} + +/// System buttons at the same size and spacing as the window's own, wired to that window. +/// Full screen disables miniaturize; the yellow button stays, greyed out. +fn fullscreen_buttons(window: &NSWindow, mtm: MainThreadMarker) -> Option> { + let kinds = [NSWindowButton::CloseButton, NSWindowButton::MiniaturizeButton, NSWindowButton::ZoomButton]; + let actions = [sel!(performClose:), sel!(performMiniaturize:), sel!(toggleFullScreen:)]; + let live = kinds.iter().map(|kind| window.standardWindowButton(*kind)).collect::>>()?; + let close = live[0].frame(); + let mini = live[1].frame(); + let zoom = live[2].frame(); + let slot = NSView::initWithFrame( + mtm.alloc(), + NSRect::new( + NSPoint::new(0.0, 0.0), + NSSize::new(zoom.origin.x - close.origin.x + zoom.size.width, close.size.height), + ), + ); + let mut mask = window.styleMask(); + mask.insert(NSWindowStyleMask::FullScreen); + for (index, kind) in kinds.into_iter().enumerate() { + let button = NSWindow::standardWindowButton_forStyleMask(kind, mask, mtm)?; + let x = [0.0, mini.origin.x - close.origin.x, zoom.origin.x - close.origin.x][index]; + let size = [close.size, mini.size, zoom.size][index]; + button.setFrame(NSRect::new(NSPoint::new(x, 0.0), size)); + unsafe { + let _: () = msg_send![&*button, setTarget: window]; + let _: () = msg_send![&*button, setAction: Some(actions[index])]; + } + if kind == NSWindowButton::MiniaturizeButton { + button.setEnabled(false); + } + slot.addSubview(&button); + } + Some(slot) +} + +/// AppKit's private fullscreen title-bar window. Matched exactly; the KVO subclass AppKit +/// interposes still counts, a name that merely contains this text does not. +const STRIP_CLASS: &CStr = c"NSToolbarFullScreenWindow"; + +fn warn_once(slot: &AtomicBool, message: &str) { + if slot.swap(true, Ordering::Relaxed) { + return; + } + tracing::warn!("{message}"); +} + +fn strip_class() -> Option<&'static AnyClass> { + static MISSING: AtomicBool = AtomicBool::new(false); + match AnyClass::get(STRIP_CLASS) { + Some(class) => Some(class), + None => { + warn_once( + &MISSING, + "NSToolbarFullScreenWindow is not registered; the fullscreen title-bar strip is left alone", + ); + None + } + } +} + +fn is_strip(window: &NSWindow) -> bool { + let Some(class) = strip_class() else { return false }; + let kind: bool = unsafe { msg_send![window, isKindOfClass: class] }; + kind +} + +/// The strip sits on the top edge of the fullscreen window it belongs to. A strip on another +/// display does not overlap that window. +fn overlaps(a: NSRect, b: NSRect) -> bool { + a.origin.x < b.origin.x + b.size.width + && b.origin.x < a.origin.x + a.size.width + && a.origin.y < b.origin.y + b.size.height + && b.origin.y < a.origin.y + a.size.height +} + +fn same_window(a: &NSWindow, b: &NSWindow) -> bool { + std::ptr::from_ref(a) == std::ptr::from_ref(b) +} + +/// This window's reveal strip, or nothing. Never another window's. +fn strip_for(window: &NSWindow) -> Option> { + let mtm = MainThreadMarker::new()?; + let frame = window.frame(); + let found = NSApplication::sharedApplication(mtm) + .windows() + .iter() + .find(|candidate| is_strip(candidate) && overlaps(candidate.frame(), frame)); + if found.is_none() && window.styleMask().contains(NSWindowStyleMask::FullScreen) { + static MISSING: AtomicBool = AtomicBool::new(false); + warn_once( + &MISSING, + "no NSToolbarFullScreenWindow overlaps this fullscreen window; the title-bar strip is left alone", + ); + } + found +} + +fn conceal(strip: &NSWindow) { + thread_local! { + static BUSY: Cell = const { Cell::new(false) }; + } + if strip.alphaValue() == 0.0 && strip.contentView().is_some_and(|view| view.isHidden()) { + return; + } + // Setting alpha posts `DidUpdate` on this same window. + if BUSY.with(|busy| busy.replace(true)) { + return; + } + strip.setOpaque(false); + strip.setAlphaValue(0.0); + if let Some(content) = strip.contentView() { + content.setHidden(true); + } + strip.setIgnoresMouseEvents(true); + BUSY.with(|busy| busy.set(false)); +} + +fn reveal(strip: &NSWindow) { + strip.setOpaque(true); + strip.setAlphaValue(1.0); + if let Some(content) = strip.contentView() { + content.setHidden(false); + } + strip.setIgnoresMouseEvents(false); +} + +fn bind_strip(window: &NSWindow, state: &Rc, strip: &RefCell>) { + let Some(found) = strip_for(window) else { return }; + let bound = strip + .borrow() + .as_ref() + .and_then(|binding| binding.strip.load()) + .is_some_and(|bound| same_window(&bound, &found)); + if !bound { + *strip.borrow_mut() = + Some(StripBinding { strip: Weak::new(&found), _update: watch_strip_updates(&found, state) }); + } + conceal(&found); +} + +fn release_strip(strip: &RefCell>) { + if let Some(binding) = strip.borrow_mut().take() + && let Some(strip) = binding.strip.load() + { + reveal(&strip); + } +} + +/// Re-hide when AppKit brings this strip back (pointer at the top of the screen). +fn watch_strip_updates(strip: &NSWindow, state: &Rc) -> Observer { + let weak = Weak::new(strip); + let state = state.clone(); + let block = block2::RcBlock::new(move |_| { + if !state.hosts_buttons() { + return; + } + if let Some(strip) = weak.load() { + conceal(&strip); + } + }); + let observer = unsafe { + NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock( + Some(NSWindowDidUpdateNotification), + Some(strip), + None, + &block, + ) + }; + Observer(observer) +} + +fn noted_window(note: std::ptr::NonNull) -> Option> { + let note = unsafe { note.as_ref() }; + note.object()?.downcast().ok() +} + +fn restore_buttons(buttons: &RefCell>) { + if let Some(host) = buttons.borrow_mut().take() { + host.slot.removeFromSuperview(); + } } fn track(window: &NSWindow, app: &tauri::AppHandle) -> Tracked { @@ -96,17 +376,22 @@ fn track(window: &NSWindow, app: &tauri::AppHandle) -> Tracked { if window.styleMask().contains(NSWindowStyleMask::FullScreen) { state.will_enter(); } + let height = Rc::new(Cell::new(0.0)); + let buttons = Rc::new(RefCell::new(None)); + let strip = Rc::new(RefCell::new(None)); let observe = |name, change: fn(&Fullscreen)| { let weak = Weak::new(window); let state = state.clone(); + let height = height.clone(); + let buttons = buttons.clone(); + let strip = strip.clone(); let app = app.clone(); let block = block2::RcBlock::new(move |_| { change(&state); if let Some(window) = weak.load() { - apply(&window, &state); + sync_chrome(&window, &state, height.get(), &buttons, &strip); crate::macos::hide_tab_bar(&window); } - // The web title bar releases the room kept for the window buttons in full screen. // Closing a window posts this while the runtime still holds its window table, and an // emit from here evaluates script in that table; send it from outside the notification. let app = app.clone(); @@ -124,16 +409,50 @@ fn track(window: &NSWindow, app: &tauri::AppHandle) -> Tracked { }; Observer(observer) }; + let owner = Weak::new(window); + let occlusion_state = state.clone(); + let occlusion_strip = strip.clone(); + let occlusion = block2::RcBlock::new(move |note| { + if !occlusion_state.hosts_buttons() { + return; + } + let Some(owner) = owner.load() else { return }; + let Some(candidate) = noted_window(note) else { return }; + if !is_strip(&candidate) || !overlaps(candidate.frame(), owner.frame()) { + return; + } + let bound = occlusion_strip + .borrow() + .as_ref() + .and_then(|binding| binding.strip.load()) + .is_some_and(|bound| same_window(&bound, &candidate)); + if !bound { + *occlusion_strip.borrow_mut() = Some(StripBinding { + strip: Weak::new(&candidate), + _update: watch_strip_updates(&candidate, &occlusion_state), + }); + } + conceal(&candidate); + }); let observers = unsafe { [ observe(NSWindowWillEnterFullScreenNotification, Fullscreen::will_enter), observe(NSWindowDidEnterFullScreenNotification, Fullscreen::will_enter), + observe(NSWindowWillExitFullScreenNotification, Fullscreen::will_exit), observe(NSWindowDidExitFullScreenNotification, Fullscreen::did_exit), // A tab shown in its group: AppKit's tab bar moves to it, and it may be in full screen. observe(NSWindowDidBecomeKeyNotification, |_| {}), + // The strip is another window. When one appears, the block keeps only the strip + // that overlaps this window. + Observer(NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock( + Some(NSWindowDidChangeOcclusionStateNotification), + None, + None, + &occlusion, + )), ] }; - Tracked { state, _observers: observers } + Tracked { state, height, buttons, strip, _observers: observers } } pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<()> { @@ -143,8 +462,11 @@ pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<( window.with_webview(move |webview| unsafe { let Some(mtm) = MainThreadMarker::new() else { return }; let native = &*webview.ns_window().cast::(); - let state = WINDOWS - .with_borrow_mut(|windows| windows.entry(label).or_insert_with(|| track(native, &app)).state.clone()); + let (state, buttons, strip) = WINDOWS.with_borrow_mut(|windows| { + let tracked = windows.entry(label).or_insert_with(|| track(native, &app)); + tracked.height.set(height); + (tracked.state.clone(), tracked.buttons.clone(), tracked.strip.clone()) + }); match chrome_for(height) { Chrome::Plain => { if native.toolbar().is_some() { @@ -163,7 +485,7 @@ pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<( } } } - apply(native, &state); + sync_chrome(native, &state, height, &buttons, &strip); }) } @@ -241,4 +563,35 @@ mod tests { assert_eq!(chrome_for(height), expected, "{height}"); } } + + #[test] + fn leaving_full_screen_returns_the_buttons_before_the_toolbar() { + let state = Fullscreen::default(); + state.will_enter(); + assert!(state.hosts_buttons()); + assert!(!state.toolbar_visible()); + state.will_exit(); + assert!(!state.hosts_buttons()); + assert!(!state.toolbar_visible()); + state.did_exit(); + assert!(!state.hosts_buttons()); + assert!(state.toolbar_visible()); + } + + #[test] + fn button_container_sits_in_the_title_bar_slot() { + let (x, y) = button_origin(900.0, 40.0, 16.0); + assert_eq!((x, y), (7.0, 872.0)); + let (_, short) = button_origin(900.0, 30.0, 40.0); + assert_eq!(short, 870.0); + } + + #[test] + fn a_strip_on_another_display_is_not_this_windows() { + let window = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(1920.0, 1080.0)); + let own = NSRect::new(NSPoint::new(0.0, 1048.0), NSSize::new(1920.0, 32.0)); + let other = NSRect::new(NSPoint::new(-1080.0, 1888.0), NSSize::new(1080.0, 32.0)); + assert!(overlaps(own, window)); + assert!(!overlaps(other, window)); + } } diff --git a/src/features/settings/__tests__/contrast.test.ts b/src/features/settings/__tests__/contrast.test.ts index c05084bb1..13a61d994 100644 --- a/src/features/settings/__tests__/contrast.test.ts +++ b/src/features/settings/__tests__/contrast.test.ts @@ -121,8 +121,8 @@ describe("theme tokens", () => { /** * Tokens the palette themes (Solarized, One) take from their light / dark base * on purpose: colours the user assigns (project and data source colours), the - * platform's caption close and macOS window buttons, the tint strength, and - * the selection and caret identifier foregrounds, whose base default preserves syntax colours. + * platform's caption close, the tint strength, and the selection and caret + * identifier foregrounds, whose base default preserves syntax colours. */ const INHERITED_FROM_BASE = /^--(project-color-|db-color-|file-color-|caption-close-|fg-caption-close-|tint-strength$|file-tint-strength$|fg-editor-selection$|fg-identifier-under-caret(-write)?$)/; diff --git a/src/workbench/TitleBar.module.css b/src/workbench/TitleBar.module.css index 5ace4b85b..09ff2383d 100644 --- a/src/workbench/TitleBar.module.css +++ b/src/workbench/TitleBar.module.css @@ -11,16 +11,12 @@ color: var(--fg-strong); font-size: var(--fs-chrome); } -/* Room for the native macOS traffic lights (Overlay title bar). */ +/* Room for the native macOS traffic lights, including in full screen (#4746). */ .overlay { padding-left: max(82px, calc(82px / var(--titlebar-zoom, 1))); /* Keep the gear on the icon-only right stripe's centre line, including compact mode. */ padding-right: calc(var(--stripe-outer-padding) + (var(--stripe-icon-button) - var(--titlebar-tool-button)) / 2); } -/* Native full screen moves the window buttons out of the bar. */ -.overlayFullscreen { - padding-left: 10px; -} /* Welcome window: plain title on the frame colour with a hairline, like IntelliJ's welcome frame. */ .minimal { background: var(--bg-elev); @@ -38,9 +34,6 @@ .overlay.compactHeader { padding-right: max(82px, calc(82px / var(--titlebar-zoom, 1))); } -.overlayFullscreen.compactHeader { - padding-right: 10px; -} .compactTitle { flex: 1; min-width: 0; diff --git a/src/workbench/TitleBar.tsx b/src/workbench/TitleBar.tsx index 91a7bff2f..28ddfe0e7 100644 --- a/src/workbench/TitleBar.tsx +++ b/src/workbench/TitleBar.tsx @@ -24,7 +24,6 @@ import { } from "./mainToolbar"; import { WindowControls } from "./WindowControls"; import { captionButtons } from "./windowButtons"; -import { useFullscreen } from "./useFullscreen"; import { usePlatform } from "@/platform/platformInfo"; import { projectInitials } from "./projectColor"; import { keymapItems, themeItems, themePreview, type ThemePreview, VIEW_MODE_ITEMS } from "./quickSwitch"; @@ -313,7 +312,6 @@ export function TitleBar({ title?: string; }) { const overlay = usePlatform((s) => s.overlayTitleBar); - const fullscreen = useFullscreen(); const frameless = usePlatform((s) => s.framelessTitleBar); const windowButtons = usePlatform((s) => s.windowButtons); const { map, shown, menu } = useToolbar(); @@ -324,7 +322,6 @@ export function TitleBar({ const className = clsx( styles.bar, overlay && styles.overlay, - overlay && fullscreen && styles.overlayFullscreen, frameless && styles.frameless, frameless && captionButtons(windowButtons, "left", dialog).length > 0 && styles.captionsAtLeft, frameless && captionButtons(windowButtons, "right", dialog).length === 0 && styles.noCaptionsAtRight, diff --git a/src/workbench/useFullscreen.ts b/src/workbench/useFullscreen.ts deleted file mode 100644 index d7c02f4cc..000000000 --- a/src/workbench/useFullscreen.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Whether this window fills the screen: native full screen, or a project tab shown in its - * group's full-screen Space. Native full screen moves the window buttons out of the title bar, - * so the room kept for them is released. - */ -import { useEffect, useState } from "react"; -import { commands, isTauri, onIdeEvent } from "@/platform/ipc"; - -export function useFullscreen(): boolean { - const [fullscreen, setFullscreen] = useState(false); - useEffect(() => { - // The plain-browser shell and tests have no Tauri window to ask. - if (!isTauri()) return; - let disposed = false; - const sync = () => - void commands - .windowIsFullscreen() - .then((on) => !disposed && setFullscreen(on)) - .catch(() => {}); - sync(); - const off = onIdeEvent("windowFullscreenChanged", sync); - return () => { - disposed = true; - off(); - }; - }, []); - return fullscreen; -}