From a9e55f5b45cb26a5903139592879f5e97e66e8e6 Mon Sep 17 00:00:00 2001 From: Kunttycat Date: Mon, 23 Nov 2026 02:52:27 +0700 Subject: [PATCH 1/2] fix(windows): transfer keyboard focus when closing or switching tabs Release focus cleanly to chrome before tearing down a focused tab container so Win32 never leaves keyboard focus null, and hand focus programmatically to the newly revealed active page unless chrome or an empty stage already owns it. Closes #574 --- .../src/platform/windows/stage.rs | 186 +++++++++-- .../src/platform/windows/stage_focus_tests.rs | 311 +++++++++++++++++- 2 files changed, 470 insertions(+), 27 deletions(-) diff --git a/crates/zephium-engine/src/platform/windows/stage.rs b/crates/zephium-engine/src/platform/windows/stage.rs index 2316e5537..eb45f6c59 100644 --- a/crates/zephium-engine/src/platform/windows/stage.rs +++ b/crates/zephium-engine/src/platform/windows/stage.rs @@ -12,7 +12,9 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::sync::OnceLock; -use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Controller; +use webview2_com::Microsoft::Web::WebView2::Win32::{ + ICoreWebView2Controller, COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC, +}; use windows::core::{BOOL, PCWSTR}; use windows::Win32::Foundation::{COLORREF, HWND, LPARAM, LRESULT, POINT, RECT, SIZE, WPARAM}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_USE_IMMERSIVE_DARK_MODE}; @@ -190,6 +192,9 @@ struct State { /// The card on its way in or out, and the timer that steps the cut. card_motion: Option, card_tick: Option, + /// True after a deselected or closed foreground page yields focus so the + /// next revealed active page receives keyboard focus. + pending_page_focus: bool, } /// A hidden sidebar's card sliding in or out, as the share of its slide that @@ -430,6 +435,7 @@ impl Stage { card_clip: None, card_motion: None, card_tick: None, + pending_page_focus: false, })); CAPTION_STAGES.with(|stages| { stages @@ -530,6 +536,9 @@ impl Stage { } s.tree = tree; s.visible = next_visible; + if s.hidden || s.visible.is_empty() { + s.pending_page_focus = false; + } s.revision = s.revision.wrapping_add(1); hide_now }; @@ -652,18 +661,34 @@ impl Stage { pub fn remove_view(&self, id: ItemId) { // wry owns the container window; dropping the webview destroys it. - let mut state = self.state.borrow_mut(); - if state.preview.is_some_and(|moving| moving.id == id) { - state.preview = None; - } - let container = state.views.remove(&id).map(|view| view.container); - state.ready.remove(&id); - state.dirty.remove(&id); - state.visibility_uncertain.remove(&id); - state.visible.remove(&id); - let cover = state.covers.remove(&id); - drop(state); + let (container, has_visible_page, cover) = { + let mut state = self.state.borrow_mut(); + if state.preview.is_some_and(|moving| moving.id == id) { + state.preview = None; + } + let container = state.views.remove(&id).map(|view| view.container); + state.ready.remove(&id); + state.dirty.remove(&id); + state.visibility_uncertain.remove(&id); + state.visible.remove(&id); + let has_visible_page = !state.hidden && !state.visible.is_empty(); + let cover = state.covers.remove(&id); + (container, has_visible_page, cover) + }; if let Some(container) = container { + // Destroying the focused child HWND drops Win32 focus to NULL + // unless we hand focus to parent first and arm transfer to the + // surviving or next-revealed active page. + let (focus, foreground) = hidden_focus_snapshot(); + if let Some(parent) = focus_owner_parent(container, focus, foreground, false) { + set_hidden_focus(parent); + if let Ok(mut state) = self.state.try_borrow_mut() { + state.pending_page_focus = true; + } + if has_visible_page { + schedule_sync(&self.state); + } + } super::sidebar_card::forget(container); } if let Some((cover, _)) = cover { @@ -1328,23 +1353,25 @@ fn hide_views(state: &Rc>, ids: &[ItemId]) { current.dirty.insert(hide.id); } let selected = current.visible.contains(&hide.id); + let has_visible_page = !current.hidden && !current.visible.is_empty(); drop(current); // Hiding WebView2 does not release its native keyboard focus. Give it // back to chrome only if focus still belongs to a deselected page. // A selected page hidden while navigating must keep its focus. - return_hidden_focus(hide.container, selected); + if return_hidden_focus(hide.container, selected) && has_visible_page { + if let Ok(mut current) = state.try_borrow_mut() { + current.pending_page_focus = true; + } + } } } -fn hidden_focus_parent( +fn focus_owner_parent( container: HWND, focus: HWND, foreground: HWND, - selected: bool, + require_hidden: bool, ) -> Option { - if selected { - return None; - } // SAFETY: Win32 validates these borrowed handles. The queries neither // activate windows nor keep a native object alive across a callback. unsafe { @@ -1352,16 +1379,118 @@ fn hidden_focus_parent( (!parent.0.is_null() && parent == foreground && !IsIconic(parent).as_bool() - && !IsWindowVisible(container).as_bool() + && (!require_hidden || !IsWindowVisible(container).as_bool()) && (focus == container || IsChild(container, focus).as_bool())) .then_some(parent) } } -fn return_hidden_focus(container: HWND, selected: bool) { +fn hidden_focus_parent( + container: HWND, + focus: HWND, + foreground: HWND, + selected: bool, +) -> Option { + if selected { + return None; + } + focus_owner_parent(container, focus, foreground, true) +} + +fn return_hidden_focus(container: HWND, selected: bool) -> bool { let (focus, foreground) = hidden_focus_snapshot(); if let Some(parent) = hidden_focus_parent(container, focus, foreground, selected) { set_hidden_focus(parent); + return true; + } + false +} + +fn can_focus_revealed_page( + parent: HWND, + target_container: HWND, + other_visible_containers: &[HWND], + focus: HWND, + foreground: HWND, +) -> bool { + // SAFETY: Win32 validates these borrowed handles. The queries neither + // activate windows nor keep a native object alive across a callback. + unsafe { + !parent.0.is_null() + && foreground == parent + && !IsIconic(parent).as_bool() + && IsWindowVisible(target_container).as_bool() + && focus != target_container + && !IsChild(target_container, focus).as_bool() + && !other_visible_containers + .iter() + .any(|&other| focus == other || IsChild(other, focus).as_bool()) + && (focus.0.is_null() || focus == parent || IsChild(parent, focus).as_bool()) + } +} + +fn select_focus_target(state: &State) -> Option { + let ready_and_shown = |id: &ItemId| -> bool { + state.visible.contains(id) + && state.ready.contains(id) + && state.views.get(id).is_some_and(|view| { + let applied = view.applied.get(); + view.presentation_permit.load(Ordering::Acquire) + && applied.window_visible == Some(true) + && applied.controller_visible == Some(true) + }) + }; + state + .tree + .as_ref() + .and_then(|tree| tree.tabs().into_iter().find(|id| ready_and_shown(id))) + .or_else(|| { + state + .visible + .iter() + .copied() + .filter(|id| ready_and_shown(id)) + .min() + }) +} + +fn restore_page_focus(state: &Rc>, revision: u64) { + let target = { + let Ok(mut current) = state.try_borrow_mut() else { + return; + }; + if !current.pending_page_focus || current.revision != revision { + return; + } + if current.hidden || current.visible.is_empty() { + current.pending_page_focus = false; + return; + } + let Some(id) = select_focus_target(¤t) else { + // The replacement page is not revealed yet; keep armed until its + // reveal settles on a later layout or readiness pass. + return; + }; + let (container, controller) = { + let Some(view) = current.views.get(&id) else { + return; + }; + (view.container, view.controller.clone()) + }; + let others: Vec = current + .visible + .iter() + .filter(|&&other| other != id) + .filter_map(|other| current.views.get(other).map(|v| v.container)) + .collect(); + current.pending_page_focus = false; + (current.parent, container, controller, others) + }; + let (parent, container, controller, others) = target; + let (focus, foreground) = hidden_focus_snapshot(); + if can_focus_revealed_page(parent, container, &others, focus, foreground) { + // SAFETY: called on the stage's UI thread with no State borrow held. + let _ = unsafe { controller.MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC) }; } } @@ -1518,7 +1647,7 @@ fn sync(state: &Rc>) { ) }); let dirty = std::mem::take(&mut state.dirty); - if dirty.is_empty() { + if dirty.is_empty() && !state.pending_page_focus { return; } let (origin, size, offset) = travelling @@ -1661,6 +1790,7 @@ fn sync(state: &Rc>) { if let Some(transition) = transition { transition.raise(); } + restore_page_focus(state, revision); // The next step of the journey is the next pass: every visible pane is // due to move again, on the stage's own frame-paced timer. let travelling = state.try_borrow().is_ok_and(|state| { @@ -1919,8 +2049,18 @@ fn apply_native_placement(state: &Rc>, placement: &NativePlacemen // Finishing can schedule another pass or retire the view. Recheck its // identity and revision, then release State before transferring focus. if placement_is_current(state, placement) { - let selected = state.borrow().visible.contains(&placement.id); - return_hidden_focus(placement.container, selected); + let (selected, has_visible_page) = { + let current = state.borrow(); + ( + current.visible.contains(&placement.id), + !current.hidden && !current.visible.is_empty(), + ) + }; + if return_hidden_focus(placement.container, selected) && has_visible_page { + if let Ok(mut current) = state.try_borrow_mut() { + current.pending_page_focus = true; + } + } } return; } diff --git a/crates/zephium-engine/src/platform/windows/stage_focus_tests.rs b/crates/zephium-engine/src/platform/windows/stage_focus_tests.rs index efe87991a..97ab3f140 100644 --- a/crates/zephium-engine/src/platform/windows/stage_focus_tests.rs +++ b/crates/zephium-engine/src/platform/windows/stage_focus_tests.rs @@ -11,6 +11,7 @@ struct FocusRecord { focus: HWND, foreground: HWND, targets: Vec, + moved: Vec<(&'static str, COREWEBVIEW2_MOVE_FOCUS_REASON)>, } thread_local! { @@ -32,11 +33,20 @@ pub(super) fn record_focus_target(target: HWND) -> bool { let Some(record) = record.as_mut() else { return false; }; + record.focus = target; record.targets.push(target); true }) } +fn record_move_focus(label: &'static str, reason: COREWEBVIEW2_MOVE_FOCUS_REASON) { + FOCUS.with(|record| { + if let Some(record) = record.borrow_mut().as_mut() { + record.moved.push((label, reason)); + } + }); +} + struct Windows(Vec); impl Windows { @@ -76,6 +86,7 @@ impl Drop for Windows { #[windows_core::implement(ICoreWebView2Controller)] struct Controller { + label: &'static str, on_hide: Box, } @@ -93,7 +104,7 @@ impl ICoreWebView2Controller_Impl for Controller_Impl { Err(E_NOTIMPL.into()) } fn SetBounds(&self, _: &RECT) -> windows_core::Result<()> { - Err(E_NOTIMPL.into()) + Ok(()) } fn ZoomFactor(&self, _: *mut f64) -> windows_core::Result<()> { Err(E_NOTIMPL.into()) @@ -114,8 +125,9 @@ impl ICoreWebView2Controller_Impl for Controller_Impl { fn SetBoundsAndZoomFactor(&self, _: &RECT, _: f64) -> windows_core::Result<()> { Err(E_NOTIMPL.into()) } - fn MoveFocus(&self, _: COREWEBVIEW2_MOVE_FOCUS_REASON) -> windows_core::Result<()> { - Err(E_NOTIMPL.into()) + fn MoveFocus(&self, reason: COREWEBVIEW2_MOVE_FOCUS_REASON) -> windows_core::Result<()> { + record_move_focus(self.label, reason); + Ok(()) } fn add_MoveFocusRequested( &self, @@ -164,7 +176,7 @@ impl ICoreWebView2Controller_Impl for Controller_Impl { Err(E_NOTIMPL.into()) } fn NotifyParentWindowPositionChanged(&self) -> windows_core::Result<()> { - Err(E_NOTIMPL.into()) + Ok(()) } fn Close(&self) -> windows_core::Result<()> { Err(E_NOTIMPL.into()) @@ -197,6 +209,7 @@ fn hides_return_focus_after_settlement_including_a_revision_redrive() { let weak = Rc::downgrade(&stage.state); let supersede = Cell::new(redrive); let controller: ICoreWebView2Controller = Controller { + label: "page", on_hide: Box::new(move || { if deny == "visible" { // SAFETY: reshow this fixture's page without activation @@ -236,6 +249,7 @@ fn hides_return_focus_after_settlement_including_a_revision_redrive() { }, foreground: if deny == "background" { other } else { owner }, targets: Vec::new(), + moved: Vec::new(), }); }); if deny == "destroyed" { @@ -276,6 +290,7 @@ fn a_page_never_revealed_returns_focus_once_deselected() { let stage = Stage::new(owner, 8.0, |_, _| {}); let id = ItemId::generate(); let controller: ICoreWebView2Controller = Controller { + label: "page", on_hide: Box::new(|| panic!("an already hidden page is not hidden again")), } .into(); @@ -304,6 +319,7 @@ fn a_page_never_revealed_returns_focus_once_deselected() { focus: renderer, foreground: owner, targets: Vec::new(), + moved: Vec::new(), }); }); hide_views(&stage.state, &[id]); @@ -317,3 +333,290 @@ fn a_page_never_revealed_returns_focus_once_deselected() { }); } } + +#[test] +fn closing_a_focused_tab_returns_focus_before_teardown_and_focuses_the_successor_page() { + let mut windows = Windows(Vec::new()); + let owner = windows.create(None); + let page_a = windows.create(Some(owner)); + let renderer_a = windows.create(Some(page_a)); + let page_b = windows.create(Some(owner)); + let _ = unsafe { ShowWindow(page_b, windows::Win32::UI::WindowsAndMessaging::SW_HIDE) }; + let stage = Stage::new(owner, 8.0, |_, _| {}); + let tab_a = ItemId::generate(); + let tab_b = ItemId::generate(); + let ctrl_a: ICoreWebView2Controller = Controller { + label: "a", + on_hide: Box::new(|| {}), + } + .into(); + let ctrl_b: ICoreWebView2Controller = Controller { + label: "b", + on_hide: Box::new(|| {}), + } + .into(); + { + let mut s = stage.state.borrow_mut(); + s.views.insert( + tab_a, + HostView { + container: page_a, + controller: ctrl_a, + serial: 1, + applied: Cell::new(AppliedPlacement { + window_visible: Some(true), + controller_visible: Some(true), + ..AppliedPlacement::default() + }), + consecutive_failures: Cell::new(0), + terminal_failure_reported: Cell::new(false), + generation: Arc::new(AtomicBool::new(true)), + presentation_permit: Arc::new(AtomicBool::new(true)), + }, + ); + s.views.insert( + tab_b, + HostView { + container: page_b, + controller: ctrl_b, + serial: 2, + applied: Cell::new(AppliedPlacement { + window_visible: Some(false), + controller_visible: Some(false), + ..AppliedPlacement::default() + }), + consecutive_failures: Cell::new(0), + terminal_failure_reported: Cell::new(false), + generation: Arc::new(AtomicBool::new(true)), + presentation_permit: Arc::new(AtomicBool::new(true)), + }, + ); + s.ready.insert(tab_a); + s.ready.insert(tab_b); + s.visible.insert(tab_a); + s.hidden = false; + } + FOCUS.with(|record| { + *record.borrow_mut() = Some(FocusRecord { + focus: renderer_a, + foreground: owner, + targets: Vec::new(), + moved: Vec::new(), + }); + }); + + // Shell::commit closes the outgoing view first and lays out its successor next. + stage.remove_view(tab_a); + FOCUS.with(|record| { + assert_eq!(record.borrow().as_ref().unwrap().targets, vec![owner]); + }); + assert!(stage.state.borrow().pending_page_focus); + + assert!(stage.apply( + Some(Rect::new(0.0, 0.0, 800.0, 600.0)), + Some(Pane::Leaf(tab_b)), + &[tab_b], + )); + sync(&stage.state); + + FOCUS.with(|record| { + let record = record.borrow(); + let record = record.as_ref().unwrap(); + assert_eq!( + record.moved, + vec![("b", COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC)] + ); + }); + assert!(!stage.state.borrow().pending_page_focus); + + // Subsequent layout syncs must not re-steal focus once handed off. + stage.state.borrow_mut().dirty.insert(tab_b); + sync(&stage.state); + FOCUS.with(|record| { + assert_eq!(record.borrow().as_ref().unwrap().moved.len(), 1); + }); +} + +#[test] +fn switching_tabs_transfers_focus_to_the_revealed_page_unless_chrome_held_focus() { + for chrome_focused in [false, true] { + let mut windows = Windows(Vec::new()); + let owner = windows.create(None); + let chrome = windows.create(Some(owner)); + let page_a = windows.create(Some(owner)); + let renderer_a = windows.create(Some(page_a)); + let page_b = windows.create(Some(owner)); + let _ = unsafe { ShowWindow(page_b, windows::Win32::UI::WindowsAndMessaging::SW_HIDE) }; + let stage = Stage::new(owner, 8.0, |_, _| {}); + let tab_a = ItemId::generate(); + let tab_b = ItemId::generate(); + let ctrl_a: ICoreWebView2Controller = Controller { + label: "a", + on_hide: Box::new(|| {}), + } + .into(); + let ctrl_b: ICoreWebView2Controller = Controller { + label: "b", + on_hide: Box::new(|| {}), + } + .into(); + { + let mut s = stage.state.borrow_mut(); + s.views.insert( + tab_a, + HostView { + container: page_a, + controller: ctrl_a, + serial: 1, + applied: Cell::new(AppliedPlacement { + window_visible: Some(true), + controller_visible: Some(true), + ..AppliedPlacement::default() + }), + consecutive_failures: Cell::new(0), + terminal_failure_reported: Cell::new(false), + generation: Arc::new(AtomicBool::new(true)), + presentation_permit: Arc::new(AtomicBool::new(true)), + }, + ); + s.views.insert( + tab_b, + HostView { + container: page_b, + controller: ctrl_b, + serial: 2, + applied: Cell::new(AppliedPlacement { + window_visible: Some(false), + controller_visible: Some(false), + ..AppliedPlacement::default() + }), + consecutive_failures: Cell::new(0), + terminal_failure_reported: Cell::new(false), + generation: Arc::new(AtomicBool::new(true)), + presentation_permit: Arc::new(AtomicBool::new(true)), + }, + ); + s.ready.insert(tab_a); + s.ready.insert(tab_b); + s.visible.insert(tab_a); + s.hidden = false; + } + FOCUS.with(|record| { + *record.borrow_mut() = Some(FocusRecord { + focus: if chrome_focused { chrome } else { renderer_a }, + foreground: owner, + targets: Vec::new(), + moved: Vec::new(), + }); + }); + + assert!(stage.apply( + Some(Rect::new(0.0, 0.0, 800.0, 600.0)), + Some(Pane::Leaf(tab_b)), + &[tab_b], + )); + sync(&stage.state); + + FOCUS.with(|record| { + let record = record.borrow(); + let record = record.as_ref().unwrap(); + if chrome_focused { + assert!(record.moved.is_empty()); + } else { + assert_eq!( + record.moved, + vec![("b", COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC)] + ); + } + }); + } +} + +#[test] +fn empty_stage_clears_pending_focus_handoff_so_chrome_keeps_focus() { + let mut windows = Windows(Vec::new()); + let owner = windows.create(None); + let page_a = windows.create(Some(owner)); + let renderer_a = windows.create(Some(page_a)); + let page_b = windows.create(Some(owner)); + let _ = unsafe { ShowWindow(page_b, windows::Win32::UI::WindowsAndMessaging::SW_HIDE) }; + let stage = Stage::new(owner, 8.0, |_, _| {}); + let tab_a = ItemId::generate(); + let tab_b = ItemId::generate(); + { + let mut s = stage.state.borrow_mut(); + s.views.insert( + tab_a, + HostView { + container: page_a, + controller: Controller { + label: "a", + on_hide: Box::new(|| {}), + } + .into(), + serial: 1, + applied: Cell::new(AppliedPlacement { + window_visible: Some(true), + controller_visible: Some(true), + ..AppliedPlacement::default() + }), + consecutive_failures: Cell::new(0), + terminal_failure_reported: Cell::new(false), + generation: Arc::new(AtomicBool::new(true)), + presentation_permit: Arc::new(AtomicBool::new(true)), + }, + ); + s.views.insert( + tab_b, + HostView { + container: page_b, + controller: Controller { + label: "b", + on_hide: Box::new(|| {}), + } + .into(), + serial: 2, + applied: Cell::new(AppliedPlacement { + window_visible: Some(false), + controller_visible: Some(false), + ..AppliedPlacement::default() + }), + consecutive_failures: Cell::new(0), + terminal_failure_reported: Cell::new(false), + generation: Arc::new(AtomicBool::new(true)), + presentation_permit: Arc::new(AtomicBool::new(true)), + }, + ); + s.ready.insert(tab_a); + s.ready.insert(tab_b); + s.visible.insert(tab_a); + s.hidden = false; + } + FOCUS.with(|record| { + *record.borrow_mut() = Some(FocusRecord { + focus: renderer_a, + foreground: owner, + targets: Vec::new(), + moved: Vec::new(), + }); + }); + + stage.remove_view(tab_a); + assert!(stage.state.borrow().pending_page_focus); + + // Switching onto an empty stage (e.g. built-in New Tab) clears the handoff. + assert!(stage.apply(None, None, &[])); + assert!(!stage.state.borrow().pending_page_focus); + sync(&stage.state); + + // Revealing a page later must not fire the cleared handoff. + assert!(stage.apply( + Some(Rect::new(0.0, 0.0, 800.0, 600.0)), + Some(Pane::Leaf(tab_b)), + &[tab_b], + )); + sync(&stage.state); + FOCUS.with(|record| { + assert!(record.borrow().as_ref().unwrap().moved.is_empty()); + }); +} From a4161469b836fe499757a450c7a04b5b19725353 Mon Sep 17 00:00:00 2001 From: Kunttycat Date: Mon, 23 Nov 2026 03:17:54 +0700 Subject: [PATCH 2/2] fix(windows): schedule clean focus handoff and clear deferred handoff off-foreground --- .../src/platform/windows/stage.rs | 32 +++- .../src/platform/windows/stage_focus_tests.rs | 164 ++++++++++++++++++ 2 files changed, 189 insertions(+), 7 deletions(-) diff --git a/crates/zephium-engine/src/platform/windows/stage.rs b/crates/zephium-engine/src/platform/windows/stage.rs index eb45f6c59..6b1d37771 100644 --- a/crates/zephium-engine/src/platform/windows/stage.rs +++ b/crates/zephium-engine/src/platform/windows/stage.rs @@ -1244,7 +1244,7 @@ unsafe extern "system" fn layout_timer_proc(_: HWND, _: u32, timer: usize, _: u3 fn schedule_sync(state: &Rc>) { { let state = state.borrow(); - if state.layout_timer.is_some() || state.dirty.is_empty() { + if state.layout_timer.is_some() || (state.dirty.is_empty() && !state.pending_page_focus) { return; } } @@ -1406,6 +1406,17 @@ fn return_hidden_focus(container: HWND, selected: bool) -> bool { false } +fn parent_holds_foreground(parent: HWND, focus: HWND, foreground: HWND) -> bool { + // SAFETY: Win32 validates these borrowed handles. No native object is + // activated or retained across a callback. + unsafe { + !parent.0.is_null() + && foreground == parent + && !IsIconic(parent).as_bool() + && (focus.0.is_null() || focus == parent || IsChild(parent, focus).as_bool()) + } +} + fn can_focus_revealed_page( parent: HWND, target_container: HWND, @@ -1416,16 +1427,13 @@ fn can_focus_revealed_page( // SAFETY: Win32 validates these borrowed handles. The queries neither // activate windows nor keep a native object alive across a callback. unsafe { - !parent.0.is_null() - && foreground == parent - && !IsIconic(parent).as_bool() + parent_holds_foreground(parent, focus, foreground) && IsWindowVisible(target_container).as_bool() && focus != target_container && !IsChild(target_container, focus).as_bool() && !other_visible_containers .iter() .any(|&other| focus == other || IsChild(other, focus).as_bool()) - && (focus.0.is_null() || focus == parent || IsChild(parent, focus).as_bool()) } } @@ -1467,8 +1475,18 @@ fn restore_page_focus(state: &Rc>, revision: u64) { return; } let Some(id) = select_focus_target(¤t) else { - // The replacement page is not revealed yet; keep armed until its - // reveal settles on a later layout or readiness pass. + let parent = current.parent; + drop(current); + // Drop the deferred handoff if the window already left the + // foreground before the replacement page became ready. + let (focus, foreground) = hidden_focus_snapshot(); + if !parent_holds_foreground(parent, focus, foreground) { + if let Ok(mut current) = state.try_borrow_mut() { + if current.revision == revision { + current.pending_page_focus = false; + } + } + } return; }; let (container, controller) = { diff --git a/crates/zephium-engine/src/platform/windows/stage_focus_tests.rs b/crates/zephium-engine/src/platform/windows/stage_focus_tests.rs index 97ab3f140..7639bc126 100644 --- a/crates/zephium-engine/src/platform/windows/stage_focus_tests.rs +++ b/crates/zephium-engine/src/platform/windows/stage_focus_tests.rs @@ -620,3 +620,167 @@ fn empty_stage_clears_pending_focus_handoff_so_chrome_keeps_focus() { assert!(record.borrow().as_ref().unwrap().moved.is_empty()); }); } + +#[test] +fn removing_focused_split_pane_schedules_sync_when_surviving_pane_is_clean() { + let mut windows = Windows(Vec::new()); + let owner = windows.create(None); + let page_a = windows.create(Some(owner)); + let renderer_a = windows.create(Some(page_a)); + let page_b = windows.create(Some(owner)); + let stage = Stage::new(owner, 8.0, |_, _| {}); + let tab_a = ItemId::generate(); + let tab_b = ItemId::generate(); + { + let mut s = stage.state.borrow_mut(); + s.views.insert( + tab_a, + HostView { + container: page_a, + controller: Controller { + label: "a", + on_hide: Box::new(|| {}), + } + .into(), + serial: 1, + applied: Cell::new(AppliedPlacement { + window_visible: Some(true), + controller_visible: Some(true), + ..AppliedPlacement::default() + }), + consecutive_failures: Cell::new(0), + terminal_failure_reported: Cell::new(false), + generation: Arc::new(AtomicBool::new(true)), + presentation_permit: Arc::new(AtomicBool::new(true)), + }, + ); + s.views.insert( + tab_b, + HostView { + container: page_b, + controller: Controller { + label: "b", + on_hide: Box::new(|| {}), + } + .into(), + serial: 2, + applied: Cell::new(AppliedPlacement { + window_visible: Some(true), + controller_visible: Some(true), + ..AppliedPlacement::default() + }), + consecutive_failures: Cell::new(0), + terminal_failure_reported: Cell::new(false), + generation: Arc::new(AtomicBool::new(true)), + presentation_permit: Arc::new(AtomicBool::new(true)), + }, + ); + s.ready.insert(tab_a); + s.ready.insert(tab_b); + s.visible.insert(tab_a); + s.visible.insert(tab_b); + s.hidden = false; + } + FOCUS.with(|record| { + *record.borrow_mut() = Some(FocusRecord { + focus: renderer_a, + foreground: owner, + targets: Vec::new(), + moved: Vec::new(), + }); + }); + + stage.remove_view(tab_a); + assert!(stage.state.borrow().dirty.is_empty()); + assert!(stage.state.borrow().pending_page_focus); + // Timer must be armed (or already drained synchronously if SetTimer failed). + let scheduled = stage.state.borrow().layout_timer.is_some(); + if scheduled { + sync(&stage.state); + } + FOCUS.with(|record| { + assert_eq!( + record.borrow().as_ref().unwrap().moved, + vec![("b", COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC)] + ); + }); + assert!(!stage.state.borrow().pending_page_focus); +} + +#[test] +fn focus_transfer_refuses_background_minimized_or_already_focused_windows() { + use windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_MINIMIZE, SW_RESTORE}; + let mut windows = Windows(Vec::new()); + let owner = windows.create(None); + let other = windows.create(None); + let chrome = windows.create(Some(owner)); + let target = windows.create(Some(owner)); + let sibling = windows.create(Some(owner)); + let sibling_renderer = windows.create(Some(sibling)); + + assert!(can_focus_revealed_page( + owner, + target, + &[sibling], + chrome, + owner + )); + assert!(can_focus_revealed_page( + owner, + target, + &[sibling], + HWND::default(), + owner + )); + assert!(!can_focus_revealed_page( + owner, + target, + &[sibling], + chrome, + other + )); + assert!(!can_focus_revealed_page( + owner, + target, + &[sibling], + target, + owner + )); + assert!(!can_focus_revealed_page( + owner, + target, + &[sibling], + sibling_renderer, + owner + )); + + // SAFETY: test-owned offscreen window, restored before drop. + unsafe { + let _ = ShowWindow(owner, SW_MINIMIZE); + assert!(!can_focus_revealed_page( + owner, + target, + &[sibling], + chrome, + owner + )); + let _ = ShowWindow(owner, SW_RESTORE); + } + + // Losing foreground while waiting on replacement readiness clears pending handoff. + let stage = Stage::new(owner, 8.0, |_, _| {}); + let tab_b = ItemId::generate(); + stage.state.borrow_mut().hidden = false; + stage.state.borrow_mut().visible.insert(tab_b); + stage.state.borrow_mut().pending_page_focus = true; + FOCUS.with(|record| { + *record.borrow_mut() = Some(FocusRecord { + focus: chrome, + foreground: other, + targets: Vec::new(), + moved: Vec::new(), + }); + }); + restore_page_focus(&stage.state, 0); + assert!(!stage.state.borrow().pending_page_focus); +}