дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
A background project tab of a native tab group detaches its WKWebView from the window 30 s after it leaves the front, so WebKit frees the hidden page's graphics and caches. The view comes back when the tab is selected through our tab bar, when its window becomes key (Window menu, Close Project) or when AppKit makes it visible by itself; an inactive app's full-screen group waits for activation (#6937). Every macOS with_webview caller goes through macos::with_web_view, which hands the retained view to a detached tab instead of panicking in wry; titlebar::set_height uses the NSWindow directly. clippy.toml disallows the raw with_webview calls. Covered by BackgroundTabs unit tests and an AppKit test of the synchronous re-attach on the key notification (it no longer asks a never-loaded web view for its process ids, which WebKit asserts on). Fixes #6938 Co-authored-by: Pecnikas <[email protected]> Co-authored-by: Pecnikas <[email protected]>
468 рядки
18 KiB
Rust
468 рядки
18 KiB
Rust
//! macOS project tabs: native window tab groups behind the page's own tab bar.
|
|
use crate::background_tab::{self, Return};
|
|
use crate::windows::{Launch, WindowsState};
|
|
use ide_core::{IdeError, IdeResult};
|
|
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
|
|
use objc2::{
|
|
MainThreadMarker,
|
|
rc::Retained,
|
|
runtime::{AnyClass, AnyObject, Imp, ProtocolObject, Sel},
|
|
};
|
|
use objc2_app_kit::{
|
|
NSApplication, NSView, NSWindow, NSWindowOcclusionState, NSWindowOrderingMode, NSWindowStyleMask,
|
|
NSWindowUserTabbingPreference,
|
|
};
|
|
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSOperationQueue};
|
|
use std::{
|
|
cell::{Cell, RefCell},
|
|
collections::HashMap,
|
|
ffi::c_void,
|
|
time::Duration,
|
|
};
|
|
use tauri::{AppHandle, Manager, WebviewWindow};
|
|
|
|
/// WebKit frees a page's graphics 10 s and its caches 2 min after the page leaves its window.
|
|
const DETACH_BACKGROUND_TAB_AFTER: Duration = Duration::from_secs(30);
|
|
|
|
enum Background<V> {
|
|
Pending(u64),
|
|
Detached(V),
|
|
}
|
|
|
|
struct BackgroundTabs<V> {
|
|
next: u64,
|
|
tabs: HashMap<String, Background<V>>,
|
|
}
|
|
|
|
impl<V> Default for BackgroundTabs<V> {
|
|
fn default() -> Self {
|
|
Self { next: 0, tabs: HashMap::new() }
|
|
}
|
|
}
|
|
|
|
impl<V> BackgroundTabs<V> {
|
|
/// None when the label already has an entry: a repeated select must not restart the clock.
|
|
fn schedule(&mut self, label: &str) -> Option<u64> {
|
|
if self.tabs.contains_key(label) {
|
|
return None;
|
|
}
|
|
self.next += 1;
|
|
self.tabs.insert(label.to_string(), Background::Pending(self.next));
|
|
Some(self.next)
|
|
}
|
|
|
|
fn due(&self, label: &str, generation: u64) -> bool {
|
|
matches!(self.tabs.get(label), Some(Background::Pending(g)) if *g == generation)
|
|
}
|
|
|
|
fn detached(&mut self, label: &str, view: V) {
|
|
self.tabs.insert(label.to_string(), Background::Detached(view));
|
|
}
|
|
|
|
fn cancel(&mut self, label: &str) {
|
|
self.tabs.remove(label);
|
|
}
|
|
|
|
fn view(&self, label: &str) -> Option<&V> {
|
|
match self.tabs.get(label) {
|
|
Some(Background::Detached(view)) => Some(view),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Also cancels a pending detach.
|
|
fn attach(&mut self, label: &str) -> Option<V> {
|
|
match self.tabs.remove(label) {
|
|
Some(Background::Detached(view)) => Some(view),
|
|
_ => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
struct DetachedView {
|
|
view: Retained<NSView>,
|
|
observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
|
|
}
|
|
|
|
impl Drop for DetachedView {
|
|
fn drop(&mut self) {
|
|
for observer in &self.observers {
|
|
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
|
|
}
|
|
}
|
|
}
|
|
|
|
thread_local! {
|
|
static BACKGROUND: RefCell<BackgroundTabs<DetachedView>> = RefCell::new(BackgroundTabs::default());
|
|
}
|
|
|
|
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
|
|
fn read(mtm: MainThreadMarker) -> TabbingPreference {
|
|
match NSWindow::userTabbingPreference(mtm) {
|
|
NSWindowUserTabbingPreference::Always => TabbingPreference::Always,
|
|
NSWindowUserTabbingPreference::InFullScreen => TabbingPreference::InFullScreen,
|
|
_ => TabbingPreference::Manually,
|
|
}
|
|
}
|
|
if let Some(mtm) = MainThreadMarker::new() {
|
|
return Ok(read(mtm));
|
|
}
|
|
let (tx, rx) = std::sync::mpsc::sync_channel(1);
|
|
app.run_on_main_thread(move || {
|
|
let _ = tx.send(read(MainThreadMarker::new().expect("AppKit main thread")));
|
|
})
|
|
.map_err(|e| IdeError::internal(e.to_string()))?;
|
|
rx.recv().map_err(|e| IdeError::internal(e.to_string()))
|
|
}
|
|
|
|
/// Capture before building the new window, which takes focus itself.
|
|
pub fn new_project_tab_target(app: &AppHandle, launch: &Launch) -> IdeResult<Option<WebviewWindow>> {
|
|
let windows = app.webview_windows();
|
|
let active = windows
|
|
.values()
|
|
.find(|w| w.is_focused().unwrap_or(false))
|
|
.cloned()
|
|
.or_else(|| app.state::<WindowsState>().last_focused().and_then(|label| windows.get(&label).cloned()));
|
|
let active = active.and_then(|w| {
|
|
let label = crate::windows::auxiliary_parent(w.label()).unwrap_or(w.label());
|
|
windows.get(label).cloned()
|
|
});
|
|
let active = active.filter(|w| {
|
|
let host = app.state::<crate::state::AppState>();
|
|
host.project(w.label()).is_ok_and(|p| !p.light) || host.remote_dev.get(w.label()).is_some()
|
|
});
|
|
let fullscreen = active.as_ref().is_some_and(|w| w.is_fullscreen().unwrap_or(false));
|
|
let light_edit = launch.project.is_none() && launch.remote.is_none();
|
|
Ok(should_group_new_project(tabbing_preference(app)?, fullscreen, active.is_some(), light_edit)
|
|
.then_some(active)
|
|
.flatten())
|
|
}
|
|
|
|
/// Runs `f` on the main thread before returning, so it takes effect before what the caller does next.
|
|
fn on_main<R: Send + 'static>(window: &WebviewWindow, f: impl FnOnce() -> R + Send + 'static) -> tauri::Result<R> {
|
|
if MainThreadMarker::new().is_some() {
|
|
return Ok(f());
|
|
}
|
|
let (tx, rx) = std::sync::mpsc::sync_channel(1);
|
|
window.run_on_main_thread(move || {
|
|
let _ = tx.send(f());
|
|
})?;
|
|
rx.recv().map_err(|_| tauri::Error::FailedToReceiveMessage)
|
|
}
|
|
|
|
/// Project tabs are native window tabs, so a group shares one frame and enters full screen as one
|
|
/// window, with the system's window buttons on whichever tab is shown. The tab bar is the page's
|
|
/// own; AppKit's is hidden, and windows never join a tab group on their own.
|
|
pub fn prepare_window_tabbing(mtm: MainThreadMarker) {
|
|
NSWindow::setAllowsAutomaticWindowTabbing(false, mtm);
|
|
}
|
|
|
|
fn native(window: &WebviewWindow) -> Option<&'static NSWindow> {
|
|
let pointer = window.ns_window().ok()?;
|
|
Some(unsafe { &*pointer.cast::<NSWindow>() })
|
|
}
|
|
|
|
fn same_group(a: &NSWindow, b: &NSWindow) -> bool {
|
|
match (a.tabGroup(), b.tabGroup()) {
|
|
(Some(a), Some(b)) => Retained::as_ptr(&a) == Retained::as_ptr(&b),
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
fn schedule_detach(window: &WebviewWindow) {
|
|
// The debug-only MCP bridge calls `with_webview` directly, which panics on a detached view.
|
|
if cfg!(debug_assertions) {
|
|
return;
|
|
}
|
|
let Some(generation) = BACKGROUND.with_borrow_mut(|tabs| tabs.schedule(window.label())) else { return };
|
|
let target = window.clone();
|
|
tauri::async_runtime::spawn(async move {
|
|
tokio::time::sleep(DETACH_BACKGROUND_TAB_AFTER).await;
|
|
let window = target.clone();
|
|
let _ = window.run_on_main_thread(move || detach_if_background(&target, generation));
|
|
});
|
|
}
|
|
|
|
fn detach_if_background(window: &WebviewWindow, generation: u64) {
|
|
if !BACKGROUND.with_borrow(|tabs| tabs.due(window.label(), generation)) {
|
|
return;
|
|
}
|
|
let Some(native) = native(window) else { return };
|
|
// A visible window is never a background tab.
|
|
if native.occlusionState().contains(NSWindowOcclusionState::Visible) {
|
|
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
|
|
return;
|
|
}
|
|
// An inactive app's full-screen group can be mid-transition, where AppKit has crashed (#6937): wait for activation.
|
|
let inactive = MainThreadMarker::new().is_some_and(|mtm| !NSApplication::sharedApplication(mtm).isActive());
|
|
if inactive && native.styleMask().contains(NSWindowStyleMask::FullScreen) {
|
|
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
|
|
schedule_detach(window);
|
|
return;
|
|
}
|
|
let view = (|| {
|
|
let group = native.tabGroup()?;
|
|
let selected = group.selectedWindow()?;
|
|
let background = group.windows().count() > 1
|
|
&& !std::ptr::eq(Retained::as_ptr(&selected), native)
|
|
&& native.attachedSheet().is_none();
|
|
background.then(|| background_tab::web_view(native)).flatten()
|
|
})();
|
|
let Some(view) = view else {
|
|
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
|
|
return;
|
|
};
|
|
view.removeFromSuperview();
|
|
let target = window.clone();
|
|
let observers = background_tab::on_return(native, move |why| {
|
|
attach_for(&target, if why == Return::Key { "key" } else { "visible" }, true)
|
|
});
|
|
BACKGROUND.with_borrow_mut(|tabs| tabs.detached(window.label(), DetachedView { view, observers }));
|
|
}
|
|
|
|
/// Puts a detached web view back and cancels a pending detach.
|
|
pub fn attach(window: &WebviewWindow) {
|
|
attach_for(window, "select", false);
|
|
}
|
|
|
|
fn attach_for(window: &WebviewWindow, reason: &str, from_observer: bool) {
|
|
let Some(detached) = BACKGROUND.with_borrow_mut(|tabs| tabs.attach(window.label())) else {
|
|
return;
|
|
};
|
|
if let Some(native) = native(window) {
|
|
background_tab::put_back(native, &detached.view);
|
|
tracing::debug!(label = window.label(), reason, "re-attached background tab web view");
|
|
}
|
|
if from_observer {
|
|
// Dropping removes the observer whose block is running; wait until the post returns.
|
|
let detached = Cell::new(Some(detached));
|
|
let block = block2::RcBlock::new(move || drop(detached.take()));
|
|
unsafe { NSOperationQueue::mainQueue().addOperationWithBlock(&block) };
|
|
}
|
|
}
|
|
|
|
/// Calls `f` on the main thread with the window's `WKWebView`, attached or not.
|
|
/// tauri's webview size/position APIs (`core:webview:default` grants `webview_size`/`webview_position`) unwrap
|
|
/// `superview()` in wry and are not safe while a tab is detached.
|
|
pub fn with_web_view(window: &WebviewWindow, f: impl FnOnce(*mut c_void) + Send + 'static) -> tauri::Result<()> {
|
|
let target = window.clone();
|
|
window.run_on_main_thread(move || {
|
|
// On the main thread tauri handles with_webview synchronously, so the tab cannot be detached between
|
|
// the check and the call; wry's with_webview panics on a windowless view.
|
|
let detached = BACKGROUND.with_borrow(|tabs| tabs.view(target.label()).map(|d| Retained::as_ptr(&d.view)));
|
|
match detached {
|
|
Some(view) => f(view as *mut c_void),
|
|
None => {
|
|
#[allow(clippy::disallowed_methods)]
|
|
let _ = target.with_webview(move |w| f(w.inner()));
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
pub fn forget_background(label: &str) {
|
|
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(label));
|
|
}
|
|
|
|
/// Adds `members` to the existing anchor's native tab group and shows `selected`.
|
|
pub fn sync_tab_group(
|
|
members: Vec<WebviewWindow>,
|
|
anchor: &WebviewWindow,
|
|
selected: &WebviewWindow,
|
|
) -> tauri::Result<()> {
|
|
let anchor = anchor.clone();
|
|
let target = selected.clone();
|
|
on_main(selected, move || {
|
|
let Some(shown) = native(&target) else { return };
|
|
let Some(anchor_window) = native(&anchor) else { return };
|
|
// Joining into a new tab's desktop window would take the existing group out of full screen.
|
|
for member in members.iter().filter(|m| m.label() != anchor.label()) {
|
|
if let Some(window) = native(member)
|
|
&& !same_group(anchor_window, window)
|
|
{
|
|
anchor_window.addTabbedWindow_ordered(window, NSWindowOrderingMode::Above);
|
|
}
|
|
}
|
|
attach(&target);
|
|
if let Some(group) = shown.tabGroup() {
|
|
group.setSelectedWindow(Some(shown));
|
|
}
|
|
shown.makeKeyAndOrderFront(None);
|
|
for member in &members {
|
|
if member.label() != target.label() {
|
|
schedule_detach(member);
|
|
}
|
|
if let Some(window) = native(member) {
|
|
hide_tab_bar(window);
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
pub fn fullscreen_in_background(window: &WebviewWindow) -> bool {
|
|
let target = window.clone();
|
|
on_main(window, move || {
|
|
let active =
|
|
MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isActive());
|
|
!active && native(&target).is_some_and(|w| w.styleMask().contains(objc2_app_kit::NSWindowStyleMask::FullScreen))
|
|
})
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// Takes `window` out of its tab group into a window of its own; in full screen, a Space of its own.
|
|
pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
|
|
let target = window.clone();
|
|
on_main(window, move || {
|
|
let Some(native) = native(&target) else { return };
|
|
attach(&target);
|
|
if native.tabbedWindows().is_some_and(|tabs| tabs.count() > 1) {
|
|
native.moveTabToNewWindow(None);
|
|
}
|
|
hide_tab_bar(native);
|
|
})
|
|
}
|
|
|
|
/// Hides `windows` together in a single main-thread turn so a closing window or tab group
|
|
/// disappears at once instead of flipping through remaining tabs while webviews tear down.
|
|
/// Native fullscreen windows are left for AppKit's own Space close transition.
|
|
pub fn hide_windows(windows: Vec<WebviewWindow>) {
|
|
if windows.is_empty() {
|
|
return;
|
|
}
|
|
let first = windows[0].clone();
|
|
let _ = on_main(&first, move || {
|
|
for window in &windows {
|
|
if window.is_fullscreen().unwrap_or(false) {
|
|
continue;
|
|
}
|
|
if let Some(native) = native(window) {
|
|
native.orderOut(None);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
fn has_tab_bar(view: &objc2_app_kit::NSView) -> bool {
|
|
let class = view.class().name().to_string_lossy();
|
|
class.contains("TabBar") || view.subviews().iter().any(|v| has_tab_bar(&v))
|
|
}
|
|
|
|
/// Hides AppKit's tab bar, which a window shows while its group has more than one tab. It moves to
|
|
/// whichever tab is shown and comes back when the group changes, so this runs after each change.
|
|
pub fn hide_tab_bar(window: &NSWindow) {
|
|
for accessory in window.titlebarAccessoryViewControllers().iter() {
|
|
if !accessory.isHidden() && has_tab_bar(&accessory.view()) {
|
|
accessory.setHidden(true);
|
|
}
|
|
}
|
|
}
|
|
|
|
type ShouldTerminate = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject) -> usize;
|
|
|
|
/// `NSApplicationTerminateReply`.
|
|
const TERMINATE_CANCEL: usize = 0;
|
|
const TERMINATE_NOW: usize = 1;
|
|
|
|
/// The Dock's Quit, the system's app menu and a logout ask the application delegate whether it
|
|
/// may terminate; tao's delegate doesn't answer, so AppKit terminated at once, past the exit,
|
|
/// running-process and unsaved-changes prompts. Answer it: cancel, and quit like Cmd+Q does.
|
|
pub fn intercept_system_quit(app: &AppHandle) {
|
|
let _ = APP.set(app.clone());
|
|
let Some(mtm) = MainThreadMarker::new() else { return };
|
|
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
|
|
unsafe {
|
|
let delegate: *mut AnyObject = objc2::msg_send![&*application, delegate];
|
|
if delegate.is_null() {
|
|
return;
|
|
}
|
|
let class = objc2::ffi::object_getClass(delegate.cast()) as *mut AnyClass;
|
|
let imp: Imp = std::mem::transmute(should_terminate as ShouldTerminate);
|
|
let added = objc2::ffi::class_addMethod(class, objc2::sel!(applicationShouldTerminate:), imp, c"Q@:@".as_ptr());
|
|
if !added.as_bool() {
|
|
tracing::warn!("could not handle applicationShouldTerminate:");
|
|
}
|
|
}
|
|
}
|
|
|
|
unsafe extern "C-unwind" fn should_terminate(_this: *mut AnyObject, _selector: Sel, _sender: *mut AnyObject) -> usize {
|
|
let Some(app) = APP.get() else { return TERMINATE_NOW };
|
|
// Our own quit exits through the event loop; a system quit during it goes ahead.
|
|
if app.try_state::<WindowsState>().is_none_or(|w| w.quitting()) {
|
|
return TERMINATE_NOW;
|
|
}
|
|
crate::dispatch_menu_action(app, "app.quit");
|
|
TERMINATE_CANCEL
|
|
}
|
|
|
|
static APP: std::sync::OnceLock<AppHandle> = std::sync::OnceLock::new();
|
|
|
|
/// Whether AppKit is handling a key press right now. A menu item performed at this point
|
|
/// was chosen by its key equivalent: a click, arrow keys plus Return and accessibility
|
|
/// presses all run with a non-key current event.
|
|
pub fn handling_key_press() -> bool {
|
|
let Some(mtm) = MainThreadMarker::new() else { return false };
|
|
objc2_app_kit::NSApplication::sharedApplication(mtm)
|
|
.currentEvent()
|
|
.is_some_and(|event| event.r#type() == objc2_app_kit::NSEventType::KeyDown)
|
|
}
|
|
|
|
/// Native dialogs block the workbench even when their menu event no longer carries a key press.
|
|
pub fn native_modal_open() -> bool {
|
|
let Some(mtm) = MainThreadMarker::new() else { return false };
|
|
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
|
|
application.modalWindow().is_some() || application.windows().iter().any(|window| window.attachedSheet().is_some())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::BackgroundTabs;
|
|
|
|
#[test]
|
|
fn repeated_schedule_keeps_the_first_generation() {
|
|
let mut tabs = BackgroundTabs::<u32>::default();
|
|
let first = tabs.schedule("a").unwrap();
|
|
assert_eq!(tabs.schedule("a"), None);
|
|
assert!(tabs.due("a", first));
|
|
}
|
|
|
|
#[test]
|
|
fn attach_cancels_a_pending_detach() {
|
|
let mut tabs = BackgroundTabs::<u32>::default();
|
|
let generation = tabs.schedule("a").unwrap();
|
|
assert_eq!(tabs.attach("a"), None);
|
|
assert!(!tabs.due("a", generation));
|
|
}
|
|
|
|
#[test]
|
|
fn stale_generation_is_not_due_after_reschedule() {
|
|
let mut tabs = BackgroundTabs::<u32>::default();
|
|
let stale = tabs.schedule("a").unwrap();
|
|
tabs.attach("a");
|
|
let fresh = tabs.schedule("a").unwrap();
|
|
assert_ne!(stale, fresh);
|
|
assert!(!tabs.due("a", stale));
|
|
assert!(tabs.due("a", fresh));
|
|
}
|
|
|
|
#[test]
|
|
fn view_is_only_there_while_detached() {
|
|
let mut tabs = BackgroundTabs::<&'static str>::default();
|
|
tabs.schedule("a").unwrap();
|
|
assert_eq!(tabs.view("a"), None);
|
|
tabs.detached("a", "view");
|
|
assert_eq!(tabs.view("a"), Some(&"view"));
|
|
tabs.attach("a");
|
|
assert_eq!(tabs.view("a"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn attach_returns_the_detached_view_once() {
|
|
let mut tabs = BackgroundTabs::<&'static str>::default();
|
|
let generation = tabs.schedule("a").unwrap();
|
|
tabs.detached("a", "view");
|
|
assert!(!tabs.due("a", generation));
|
|
assert_eq!(tabs.attach("a"), Some("view"));
|
|
assert_eq!(tabs.attach("a"), None);
|
|
}
|
|
}
|