Файли
openidea/src-tauri/src/macos.rs
T
l0ng-ai 1ba2ce55bb fix(macos): keep project tab close confirmations visible (#7501)
Closing a macOS project tab group could cover the running-agent confirmation when a peer returned to Welcome and took focus. Confirmations and the Welcome transition now take turns, and background web views stay attached while their close checks are pending.
2026-12-02 21:43:58 +08:00

726 рядки
29 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, msg_send,
rc::Retained,
runtime::{AnyClass, AnyObject, Imp, ProtocolObject, Sel},
sel,
};
use objc2_app_kit::{
NSAnimationContext, NSApplication, NSView, NSWindow, NSWindowOcclusionState, NSWindowOrderingMode,
NSWindowStyleMask, NSWindowUserTabbingPreference,
};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSOperationQueue, NSRect};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
ffi::c_void,
sync::mpsc::SyncSender,
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;
}
// Selecting a peer for its close dialog can schedule another detach. Keep this
// page attached until its own close guard has answered.
if window.state::<WindowsState>().is_closing(window.label()) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
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));
}
/// Upper bound on waiting for an occluded or freshly re-attached WKWebView to commit a GPU frame
/// before swapping tabs, so a busy WebContent process never makes tab switching feel stuck.
const TAB_PREWARM_TIMEOUT: Duration = Duration::from_millis(80);
struct PendingTabSwitch<W = Retained<NSView>> {
generation: u64,
webview: W,
done: Option<SyncSender<()>>,
}
impl<W> PendingTabSwitch<W> {
fn take_matching(slot: &mut Option<Self>, generation: u64) -> Option<Self> {
if slot.as_ref().is_some_and(|p| p.generation == generation) { slot.take() } else { None }
}
fn finish(mut self, restore: impl FnOnce(&W)) {
restore(&self.webview);
if let Some(done) = self.done.take() {
let _ = done.send(());
}
}
}
enum PrewarmOutcome {
Switched,
Waiting { generation: u64, rx: std::sync::mpsc::Receiver<()> },
}
thread_local! {
static NEXT_SWITCH_GENERATION: Cell<u64> = const { Cell::new(0) };
static PENDING_TAB_SWITCH: RefCell<Option<PendingTabSwitch>> = const { RefCell::new(None) };
}
fn next_switch_generation() -> u64 {
NEXT_SWITCH_GENERATION.with(|slot| {
let next = slot.get().wrapping_add(1);
slot.set(next);
next
})
}
fn without_animation<R>(f: impl FnOnce() -> R) -> R {
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
NSAnimationContext::endGrouping();
}
}
NSAnimationContext::beginGrouping();
let _guard = Guard;
let ctx = NSAnimationContext::currentContext();
ctx.setDuration(0.0);
ctx.setAllowsImplicitAnimation(false);
f()
}
fn frames_differ(a: NSRect, b: NSRect) -> bool {
a.origin.x != b.origin.x
|| a.origin.y != b.origin.y
|| a.size.width != b.size.width
|| a.size.height != b.size.height
}
fn webview_supports_prewarm(webview: &NSView) -> bool {
unsafe {
let has_setter: bool = msg_send![webview, respondsToSelector: sel!(_setWindowOcclusionDetectionEnabled:)];
let has_getter: bool = msg_send![webview, respondsToSelector: sel!(_windowOcclusionDetectionEnabled)];
let has_update: bool = msg_send![webview, respondsToSelector: sel!(_doAfterNextPresentationUpdate:)];
if !(has_setter && has_getter && has_update) {
return false;
}
msg_send![webview, _windowOcclusionDetectionEnabled]
}
}
fn set_window_occlusion_detection_enabled(webview: &NSView, enabled: bool) {
unsafe {
let _: () = msg_send![webview, _setWindowOcclusionDetectionEnabled: enabled];
}
}
/// Restores occlusion detection on any superseded pre-warm and unblocks its caller.
fn cancel_pending_tab_switch() {
let pending = PENDING_TAB_SWITCH.with(|slot| slot.borrow_mut().take());
if let Some(pending) = pending {
pending.finish(|webview| set_window_occlusion_detection_enabled(webview, true));
}
}
fn switch_tab_group_now(members: &[WebviewWindow], anchor: &WebviewWindow, target: &WebviewWindow) {
let Some(shown) = native(target) else { return };
let Some(anchor_window) = native(anchor) else { return };
without_animation(|| {
// 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
.selectedWindow()
.is_none_or(|current| !std::ptr::eq(Retained::as_ptr(&current), std::ptr::from_ref(shown)))
{
group.setSelectedWindow(Some(shown));
}
// Hide AppKit's tab bar before ordering front so it cannot flash over our tab strip.
hide_tab_bar(shown);
if !shown.isKeyWindow() {
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);
}
}
});
}
fn complete_pending_tab_switch(
generation: u64,
members: &[WebviewWindow],
anchor: &WebviewWindow,
target: &WebviewWindow,
) {
let pending = PENDING_TAB_SWITCH.with(|slot| PendingTabSwitch::take_matching(&mut slot.borrow_mut(), generation));
let Some(pending) = pending else { return };
switch_tab_group_now(members, anchor, target);
// Restore occlusion detection only after `target` is visible on screen so WebKit does not
// bounce `ActivityState::IsVisible` through `false` -> `true`.
pending.finish(|webview| set_window_occlusion_detection_enabled(webview, true));
}
/// Adds `members` to the existing anchor's native tab group and shows `selected`.
///
/// Inactive macOS tabs are occluded (and detached after `DETACH_BACKGROUND_TAB_AFTER`), so WebKit
/// suspends compositing and frees or marks their GPU backing stores volatile. When switching to an
/// occluded tab from off the main thread, re-attach and temporarily wake its WKWebView, waiting for
/// one presentation commit (bounded by `TAB_PREWARM_TIMEOUT`) before swapping windows so the
/// incoming tab paints complete on the first visible frame.
pub fn sync_tab_group(
members: Vec<WebviewWindow>,
anchor: &WebviewWindow,
selected: &WebviewWindow,
) -> tauri::Result<()> {
let anchor = anchor.clone();
let target = selected.clone();
if MainThreadMarker::new().is_some() {
cancel_pending_tab_switch();
switch_tab_group_now(&members, &anchor, &target);
return Ok(());
}
let members_for_setup = members.clone();
let anchor_for_setup = anchor.clone();
let target_for_setup = target.clone();
let outcome = on_main(selected, move || {
cancel_pending_tab_switch();
let Some(shown) = native(&target_for_setup) else { return PrewarmOutcome::Switched };
let Some(anchor_window) = native(&anchor_for_setup) else { return PrewarmOutcome::Switched };
let all_grouped = members_for_setup.iter().all(|m| native(m).is_some_and(|w| same_group(anchor_window, w)));
let occluded = !shown.occlusionState().contains(NSWindowOcclusionState::Visible);
if anchor_for_setup.label() != target_for_setup.label() && all_grouped && occluded {
// Match the currently visible tab's frame first (outside native fullscreen) so both
// re-attached views and WebKit's pre-warm render at the exact post-swap size.
let reference = shown.tabGroup().and_then(|group| group.selectedWindow());
let reference_window: &NSWindow = reference.as_deref().unwrap_or(anchor_window);
let in_fullscreen = reference_window.styleMask().contains(NSWindowStyleMask::FullScreen)
|| shown.styleMask().contains(NSWindowStyleMask::FullScreen);
let reference_frame = reference_window.frame();
if !in_fullscreen && frames_differ(shown.frame(), reference_frame) {
shown.setFrame_display(reference_frame, false);
}
attach(&target_for_setup);
if let Some(webview) = background_tab::web_view(shown)
&& webview_supports_prewarm(&webview)
{
let generation = next_switch_generation();
let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1);
set_window_occlusion_detection_enabled(&webview, false);
PENDING_TAB_SWITCH.with(|slot| {
*slot.borrow_mut() =
Some(PendingTabSwitch { generation, webview: webview.clone(), done: Some(done_tx) });
});
let cb_members = members_for_setup.clone();
let cb_anchor = anchor_for_setup.clone();
let cb_target = target_for_setup.clone();
let block = block2::RcBlock::new(move || {
complete_pending_tab_switch(generation, &cb_members, &cb_anchor, &cb_target);
});
unsafe {
let _: () = msg_send![&*webview, _doAfterNextPresentationUpdate: &*block];
}
return PrewarmOutcome::Waiting { generation, rx: done_rx };
}
}
switch_tab_group_now(&members_for_setup, &anchor_for_setup, &target_for_setup);
PrewarmOutcome::Switched
})?;
if let PrewarmOutcome::Waiting { generation, rx } = outcome
&& rx.recv_timeout(TAB_PREWARM_TIMEOUT).is_err()
{
on_main(selected, move || {
complete_pending_tab_switch(generation, &members, &anchor, &target);
})?;
}
Ok(())
}
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 || {
cancel_pending_tab_switch();
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 || {
cancel_pending_tab_switch();
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) {
let needs_hide = window
.titlebarAccessoryViewControllers()
.iter()
.any(|accessory| !accessory.isHidden() && has_tab_bar(&accessory.view()));
if !needs_hide {
return;
}
without_animation(|| {
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, PendingTabSwitch, frames_differ};
use objc2_foundation::{NSPoint, NSRect, NSSize};
#[test]
fn frames_differ_detects_origin_and_size_changes() {
let base = NSRect::new(NSPoint::new(10.0, 20.0), NSSize::new(1200.0, 800.0));
assert!(!frames_differ(base, base));
assert!(frames_differ(base, NSRect::new(NSPoint::new(11.0, 20.0), NSSize::new(1200.0, 800.0))));
assert!(frames_differ(base, NSRect::new(NSPoint::new(10.0, 20.0), NSSize::new(1400.0, 800.0))));
assert!(frames_differ(base, NSRect::new(NSPoint::new(10.0, 20.0), NSSize::new(1200.0, 900.0))));
}
#[test]
fn pending_tab_switch_completes_once_and_ignores_stale_generations() {
let (tx1, rx1) = std::sync::mpsc::sync_channel(1);
let mut slot = Some(PendingTabSwitch { generation: 1, webview: "tab-a", done: Some(tx1) });
// Wrong generation leaves the active switch intact.
assert!(PendingTabSwitch::take_matching(&mut slot, 2).is_none());
assert!(slot.is_some());
// Matching generation takes it once, restores occlusion detection, and signals the waiter.
let mut restored = Vec::new();
let taken = PendingTabSwitch::take_matching(&mut slot, 1).expect("matching generation");
taken.finish(|w| restored.push(*w));
assert_eq!(restored, vec!["tab-a"]);
assert!(rx1.try_recv().is_ok());
// A late timeout or duplicate callback for the same generation is a no-op.
assert!(PendingTabSwitch::take_matching(&mut slot, 1).is_none());
}
#[test]
fn superseding_pending_tab_switch_restores_previous_webview_and_unblocks_waiter() {
let (tx1, rx1) = std::sync::mpsc::sync_channel(1);
let (tx2, rx2) = std::sync::mpsc::sync_channel(1);
let mut slot = Some(PendingTabSwitch { generation: 1, webview: "tab-b", done: Some(tx1) });
// Rapid second switch cancels tab-b before registering tab-c.
let mut restored = Vec::new();
if let Some(prev) = slot.take() {
prev.finish(|w| restored.push(*w));
}
slot = Some(PendingTabSwitch { generation: 2, webview: "tab-c", done: Some(tx2) });
assert_eq!(restored, vec!["tab-b"]);
assert!(rx1.try_recv().is_ok());
// Late presentation callback for tab-b must not touch tab-c.
assert!(PendingTabSwitch::take_matching(&mut slot, 1).is_none());
assert!(rx2.try_recv().is_err());
// tab-c completes normally.
PendingTabSwitch::take_matching(&mut slot, 2).unwrap().finish(|w| restored.push(*w));
assert_eq!(restored, vec!["tab-b", "tab-c"]);
assert!(rx2.try_recv().is_ok());
}
#[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);
}
}