From 4faf1f6c4ab394152417138652d1d91dbc2a9d9e Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 00:54:05 -0500 Subject: [PATCH 1/7] Browser: a click in the page is the person's from the press itself (XI2 raw press inside the page's container, taken once within 400 ms), also when CEF reports only on_got_focus Co-Authored-By: Claude Opus 5.5 --- native/gpui/Cargo.toml | 2 +- native/gpui/src/viewers/cef.rs | 17 ++++++-- native/gpui/src/viewers/cef_native.rs | 58 ++++++++++++++++++++++++++- native/gpui/src/viewers/cef_page.rs | 4 +- 4 files changed, 74 insertions(+), 7 deletions(-) diff --git a/native/gpui/Cargo.toml b/native/gpui/Cargo.toml index 40fce0485c..9fa9eae5de 100644 --- a/native/gpui/Cargo.toml +++ b/native/gpui/Cargo.toml @@ -47,7 +47,7 @@ resvg = { version = "0.45.0", default-features = false, features = ["text", "sys flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] } [target.'cfg(target_os = "linux")'.dependencies] -x11rb = { version = "0.13", default-features = false, features = ["shape", "xfixes"] } +x11rb = { version = "0.13", default-features = false, features = ["shape", "xfixes", "xinput"] } gpui = { version = "=0.2.2", default-features = false, features = ["x11"] } # The 3D page's own GPU context (viewers/solid_gpu.rs): the versions gpui already builds on Linux. blade-graphics = "0.7.0" diff --git a/native/gpui/src/viewers/cef.rs b/native/gpui/src/viewers/cef.rs index c97b645ceb..fd3f1c0127 100644 --- a/native/gpui/src/viewers/cef.rs +++ b/native/gpui/src/viewers/cef.rs @@ -181,12 +181,23 @@ wrap_focus_handler! { struct FocusH { tab: Arc } impl FocusHandler { /// windowed: the person clicked into the page (Chromium has the keyboard now); the page gives it gpui's focus too - fn on_got_focus(&self, _b: Option<&mut Browser>) { if self.tab.host.is_some() { self.tab.st.lock().unwrap().got_focus = true; let _ = self.tab.wake.try_send(()); } } + /// (and when it got it on the person's press in the page: their click, though CEF did not ask on_set_focus first; it does not when it + /// counts the browser focused already, as after a yank that moved only the X focus away: with a KiCad pane, a click in the page then + /// came here alone and the keyboard was taken back) + fn on_got_focus(&self, _b: Option<&mut Browser>) { if self.tab.host.is_some() { + let clicked = native::pressed_in(self.tab.outer()) == Some(true); + if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_got_focus": {"clicked": clicked}})); } + let mut st = self.tab.st.lock().unwrap(); st.got_focus = true; if clicked { st.person = true; } drop(st); let _ = self.tab.wake.try_send(()); } } /// Tab past the page's last element: the keyboard goes back to the client /// a click into the page (the system moving the keyboard there) is the person's, unlike our own SetFocus calls fn on_set_focus(&self, _b: Option<&mut Browser>, source: FocusSource) -> ::std::os::raw::c_int { - // (with a mouse button down: a window manager that focuses what is under the pointer moves it there too, and that is nobody's click) - if self.tab.host.is_some() && source == FocusSource::SYSTEM && native::button_down() { self.tab.st.lock().unwrap().person = true; let _ = self.tab.wake.try_send(()); } + // (the person's press inside this page's container, recorded when it happened (cef_native `pressed_in`, X11 with XInput 2): a window + // manager that focuses what is under the pointer moves it there too, and that is nobody's click; nor is a script's focus. Asking + // whether a button is down when this callback runs missed the click whenever the press reached Chromium late (a KiCad pane's button + // grab replaying it): the page was given the keyboard and taken it back. Elsewhere, and without XInput 2: a button down now) + let clicked = self.tab.host.is_some() && source == FocusSource::SYSTEM && native::pressed_in(self.tab.outer()).unwrap_or_else(native::button_down); + if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_set_focus": {"system": source == FocusSource::SYSTEM, "clicked": clicked}})); } + if clicked { self.tab.st.lock().unwrap().person = true; let _ = self.tab.wake.try_send(()); } false as _ } fn on_take_focus(&self, _b: Option<&mut Browser>, _next: ::std::os::raw::c_int) { if self.tab.host.is_some() { self.tab.st.lock().unwrap().took_focus = true; let _ = self.tab.wake.try_send(()); } } diff --git a/native/gpui/src/viewers/cef_native.rs b/native/gpui/src/viewers/cef_native.rs index 7a7238cb70..44fe8fac24 100644 --- a/native/gpui/src/viewers/cef_native.rs +++ b/native/gpui/src/viewers/cef_native.rs @@ -52,9 +52,59 @@ mod imp { let id = c.generate_id().ok()?; c.create_window(scr.root_depth, id, parent, 0, 0, 1, 1, 0, WindowClass::INPUT_OUTPUT, scr.root_visual, &CreateWindowAux::new().background_pixel(scr.white_pixel).border_pixel(scr.black_pixel).colormap(scr.default_colormap)).ok()?.check().ok()?; - let _ = c.flush(); Some(Host::X11(id)) + let _ = c.flush(); containers().lock().unwrap().insert(id); watch_presses(); Some(Host::X11(id)) } pub fn close(_w: u64) {} + /// Every container of ours (a tab's `container`), until it is destroyed: what a recorded press is matched against. + fn containers() -> &'static Mutex> { static C: OnceLock>> = OnceLock::new(); C.get_or_init(Default::default) } + /// The person's last press on the display that was inside a container of ours: when, and which container. Nothing else of a press is kept + /// (no position, no other window). Taken by the one focus it explains (`pressed_in`). + static PRESS: Mutex> = Mutex::new(None); + /// Whether the press watcher runs (XInput 2 on the display): without it `pressed_in` is never true, and on_set_focus falls back to `button_down`. + static PRESSES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + /// How long after the person's press a focus of the page is still that press's. The press reaches us (a raw event, sent before the + /// press is delivered or grabbed) before Chromium has it; Chromium focuses its window on it and CEF says so 15-25 ms later on Xvfb, more + /// under load, and later still when a KiCad pane's button grab holds the press until the pane's tick replays it (40 ms ticks). Neither + /// the press nor CEF's callback carries an X time to order them by, so the order is the press's arrival here, and a press explains one + /// focus only: a script's focus after the person's own click has nothing left to claim. + const PRESS_SPAN: std::time::Duration = std::time::Duration::from_millis(400); + /// The press watcher: a connection and a thread of its own, XInput 2 raw button presses selected on the root (every press on the display, + /// whatever grabs it; no other client's delivery is changed). On each, the window under the pointer is followed down from the root and the + /// press is recorded only when a container of ours is on that path. Started with the first container. XWayland sends raw events only + /// while one of its own clients has the focus: a click from a Wayland window into the page is then not seen, and button_down decides. + fn watch_presses() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + use x11rb::protocol::xinput::{self, ConnectionExt as _}; + let Ok((c, n)) = RustConnection::connect(None) else { return }; + let Some(root) = c.setup().roots.get(n).map(|s| s.root) else { return }; + if !c.xinput_xi_query_version(2, 2).ok().and_then(|r| r.reply().ok()).is_some_and(|v| v.major_version >= 2) { return } + let mask = [xinput::EventMask { deviceid: 1 /* XIAllMasterDevices */, mask: vec![xinput::XIEventMask::RAW_BUTTON_PRESS] }]; + if c.xinput_xi_select_events(root, &mask).ok().and_then(|k| k.check().ok()).is_none() { return } + PRESSES.store(true, std::sync::atomic::Ordering::Relaxed); + if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_presses": "watched"})); } + std::thread::Builder::new().name("cef-presses".into()).spawn(move || while let Ok(e) = c.wait_for_event() { + let x11rb::protocol::Event::XinputRawButtonPress(_) = e else { continue }; + // said at once (container 0: not yet known), so a focus that CEF reports while the pointer is followed waits for it (pressed_in) + let at = std::time::Instant::now(); *PRESS.lock().unwrap() = Some((at, 0)); + let ours = containers().lock().unwrap().clone(); + let (mut w, mut hit) = (root, None); + for _ in 0..16 { let Some(r) = c.query_pointer(w).ok().and_then(|r| r.reply().ok()) else { break }; if r.child == x11rb::NONE { break } w = r.child; if ours.contains(&w) { hit = Some(w); break } } + *PRESS.lock().unwrap() = hit.map(|h| (at, h)); + if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_press_in_page": hit.is_some()})); } + }).ok(); + }); + } + /// Whether the person pressed a mouse button inside container `frame` within PRESS_SPAN (taken: it answers yes once); None without the watcher. + pub fn pressed_in(frame: u64) -> Option { + if !PRESSES.load(std::sync::atomic::Ordering::Relaxed) { return None } + // a press still being followed down (a few round trips): waited for, 50 ms at most + let t0 = std::time::Instant::now(); + let mut p = loop { let p = PRESS.lock().unwrap(); if !p.is_some_and(|(at, w)| w == 0 && at.elapsed() <= PRESS_SPAN) || t0.elapsed().as_millis() >= 50 { break p } drop(p); std::thread::sleep(std::time::Duration::from_millis(1)); }; + let yes = p.is_some_and(|(at, w)| w as u64 == frame && at.elapsed() <= PRESS_SPAN); + if yes { *p = None; } + Some(yes) + } /// Whether a mouse button is down now (a focus change while one is, is the person's click; without, a window manager's focus-follows-mouse). pub fn button_down() -> bool { let Some(g) = conn() else { return false }; let c = g.as_ref().unwrap(); @@ -62,7 +112,7 @@ mod imp { c.query_pointer(root).ok().and_then(|r| r.reply().ok()).map_or(false, |p| u16::from(p.mask) & (u16::from(KeyButMask::BUTTON1) | u16::from(KeyButMask::BUTTON2) | u16::from(KeyButMask::BUTTON3)) != 0) } /// The container gone (its browser closed). - pub fn destroy(frame: u64) { let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); let _ = c.destroy_window(frame as u32); let _ = c.flush(); } + pub fn destroy(frame: u64) { containers().lock().unwrap().remove(&(frame as u32)); let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); let _ = c.destroy_window(frame as u32); let _ = c.flush(); } /// The container (and Chromium's window filling it) over the pane at `r`, mapped; or unmapped. pub fn place_in(frame: u64, w: u64, r: Option) { { let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); @@ -138,6 +188,8 @@ mod imp { pub fn container(_h: Host) -> Option { None } pub fn place_in(_frame: u64, _w: u64, _r: Option) {} pub fn destroy(_frame: u64) {} + /// X11 only (its press watcher): here on_set_focus asks `button_down`. + pub fn pressed_in(_frame: u64) -> Option { None } #[cfg(windows)] pub fn close(w: u64) { unsafe { windows_sys::Win32::UI::WindowsAndMessaging::DestroyWindow(w as isize as _); } } #[cfg(target_os = "macos")] pub fn close(w: u64) { unsafe { send0(v(w), c"removeFromSuperview"); } } /// Every window under `h` (class, rect in the screen, visible, style), for the report. @@ -196,6 +248,8 @@ mod imp { pub fn container(_h: Host) -> Option { None } pub fn place_in(_frame: u64, _w: u64, _r: Option) {} pub fn destroy(_frame: u64) {} + /// X11 only (its press watcher): here on_set_focus asks `button_down`. + pub fn pressed_in(_frame: u64) -> Option { None } #[cfg(windows)] pub fn close(w: u64) { unsafe { windows_sys::Win32::UI::WindowsAndMessaging::DestroyWindow(w as isize as _); } } #[cfg(target_os = "macos")] pub fn close(w: u64) { unsafe { send0(v(w), c"removeFromSuperview"); } } /// Every window under `h` (class, rect in the screen, visible, style), for the report. diff --git a/native/gpui/src/viewers/cef_page.rs b/native/gpui/src/viewers/cef_page.rs index fcb56ac025..5abe5a6131 100644 --- a/native/gpui/src/viewers/cef_page.rs +++ b/native/gpui/src/viewers/cef_page.rs @@ -232,7 +232,9 @@ impl Render for CefPage { if self.host.is_none() { self.decide(window, cx); } if self.tabs.is_empty() { self.new_tab(&self.start.clone(), cx); } if std::mem::take(&mut self.want_focus) && !self.focus.is_focused(window) { window.focus(&self.focus); self.bar_edit = false; } - if std::mem::take(&mut self.want_yank) && !self.focus.is_focused(window) && window.is_window_active() { if let Some(t) = self.tab() { t.give_keyboard(false); } } + if std::mem::take(&mut self.want_yank) && !self.focus.is_focused(window) && window.is_window_active() { if let Some(t) = self.tab() { + if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_yank": true})); } + t.give_keyboard(false); } } if !self.from_page.is_empty() { let keys = std::mem::take(&mut self.from_page); let flag = self.dispatching.clone(); let tab = self.tab().cloned(); window.defer(cx, move |window, cx| for (ks, e) in keys { From 02ecb23a440fcd72f7c1c127145e9e8bdd1d168a Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 01:09:19 -0500 Subject: [PATCH 2/7] Browser (Linux): the window's focus proxy while the page is on screen too (one focus watcher thread for every native child; the Browser gives the keyboard back to the proxy); sequence e2e S1-S3 and focus_trace gap A window with only the Browser left Backplane's keyboard on the top-level itself, and core X gave every key typed with the pointer over the page to Chromium (B2/B4). The page now registers as a native child (native_child adopt_child / note_pane_on_screen with its container), its focus_host goes to the proxy (focus_home), and the FocusIn redirect runs on a thread and connection of its own (x11-focus-proxy) for every top-level with a proxy, not on the pane's wake thread. Co-Authored-By: Claude Opus 5.5 --- native/gpui/src/viewers/cef_native.rs | 23 ++- native/gpui/src/viewers/native_child.rs | 83 +++++++--- .../embed_pointer_keys_browser_seq_e2e.sh | 150 ++++++++++++++++++ test/kicad_embed/lib/focus_trace.py | 30 +++- 4 files changed, 256 insertions(+), 30 deletions(-) create mode 100755 test/kicad_embed/embed_pointer_keys_browser_seq_e2e.sh diff --git a/native/gpui/src/viewers/cef_native.rs b/native/gpui/src/viewers/cef_native.rs index 44fe8fac24..4db00e33a9 100644 --- a/native/gpui/src/viewers/cef_native.rs +++ b/native/gpui/src/viewers/cef_native.rs @@ -52,11 +52,19 @@ mod imp { let id = c.generate_id().ok()?; c.create_window(scr.root_depth, id, parent, 0, 0, 1, 1, 0, WindowClass::INPUT_OUTPUT, scr.root_visual, &CreateWindowAux::new().background_pixel(scr.white_pixel).border_pixel(scr.black_pixel).colormap(scr.default_colormap)).ok()?.check().ok()?; - let _ = c.flush(); containers().lock().unwrap().insert(id); watch_presses(); Some(Host::X11(id)) + let _ = c.flush(); drop(g); + containers().lock().unwrap().insert(id, parent); watch_presses(); + // a native child in the client's window like a KiCad pane's: while it is on screen (place_in) Backplane's keyboard is on the window's + // focus proxy, not the window itself, or core X gives every key typed with the pointer over the page to Chromium (#1505's fault) + nc::adopt_child(parent as u64, id as u64); + Some(Host::X11(id)) } pub fn close(_w: u64) {} /// Every container of ours (a tab's `container`), until it is destroyed: what a recorded press is matched against. - fn containers() -> &'static Mutex> { static C: OnceLock>> = OnceLock::new(); C.get_or_init(Default::default) } + /// (each with the client's top-level it is in) + fn containers() -> &'static Mutex> { static C: OnceLock>> = OnceLock::new(); C.get_or_init(Default::default) } + fn top_of(frame: u64) -> Option { containers().lock().unwrap().get(&(frame as u32)).map(|t| *t as u64) } + use crate::viewers::native_child as nc; /// The person's last press on the display that was inside a container of ours: when, and which container. Nothing else of a press is kept /// (no position, no other window). Taken by the one focus it explains (`pressed_in`). static PRESS: Mutex> = Mutex::new(None); @@ -89,7 +97,7 @@ mod imp { let at = std::time::Instant::now(); *PRESS.lock().unwrap() = Some((at, 0)); let ours = containers().lock().unwrap().clone(); let (mut w, mut hit) = (root, None); - for _ in 0..16 { let Some(r) = c.query_pointer(w).ok().and_then(|r| r.reply().ok()) else { break }; if r.child == x11rb::NONE { break } w = r.child; if ours.contains(&w) { hit = Some(w); break } } + for _ in 0..16 { let Some(r) = c.query_pointer(w).ok().and_then(|r| r.reply().ok()) else { break }; if r.child == x11rb::NONE { break } w = r.child; if ours.contains_key(&w) { hit = Some(w); break } } *PRESS.lock().unwrap() = hit.map(|h| (at, h)); if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_press_in_page": hit.is_some()})); } }).ok(); @@ -112,9 +120,10 @@ mod imp { c.query_pointer(root).ok().and_then(|r| r.reply().ok()).map_or(false, |p| u16::from(p.mask) & (u16::from(KeyButMask::BUTTON1) | u16::from(KeyButMask::BUTTON2) | u16::from(KeyButMask::BUTTON3)) != 0) } /// The container gone (its browser closed). - pub fn destroy(frame: u64) { containers().lock().unwrap().remove(&(frame as u32)); let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); let _ = c.destroy_window(frame as u32); let _ = c.flush(); } + pub fn destroy(frame: u64) { if let Some(t) = containers().lock().unwrap().remove(&(frame as u32)) { nc::release_child(t as u64, frame); } let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); let _ = c.destroy_window(frame as u32); let _ = c.flush(); } /// The container (and Chromium's window filling it) over the pane at `r`, mapped; or unmapped. pub fn place_in(frame: u64, w: u64, r: Option) { + if let Some(t) = top_of(frame) { nc::note_pane_on_screen(t, frame, r.is_some()); } { let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); if let Some(r) = r { let _ = c.configure_window(frame as u32, &ConfigureWindowAux::new().x(r.x).y(r.y).width(r.w.max(1) as u32).height(r.h.max(1) as u32)); if w != 0 { let _ = c.configure_window(w as u32, &ConfigureWindowAux::new().x(0).y(0).width(r.w.max(1) as u32).height(r.h.max(1) as u32)); } } @@ -148,10 +157,8 @@ mod imp { if viewable { let _ = c.set_input_focus(InputFocus::PARENT, t, x11rb::CURRENT_TIME); let _ = c.flush(); } } /// The keyboard back to the client's window. - pub fn focus_host(h: Host) { - let Host::X11(w) = h else { return }; let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); - let _ = c.set_input_focus(InputFocus::PARENT, w, x11rb::CURRENT_TIME); let _ = c.flush(); - } + /// (to its focus proxy while a native child is on screen there: native_child `focus_home`) + pub fn focus_host(h: Host) { if let Host::X11(w) = h { nc::focus_home(w as u64) } } /// Where the child is (its geometry in the parent) and whether it is mapped: what the e2e checks. pub fn geometry(w: u64) -> Option<(R, bool)> { let g = conn()?; let c = g.as_ref().unwrap(); diff --git a/native/gpui/src/viewers/native_child.rs b/native/gpui/src/viewers/native_child.rs index 7d819b55c0..d55ac3a48a 100644 --- a/native/gpui/src/viewers/native_child.rs +++ b/native/gpui/src/viewers/native_child.rs @@ -208,11 +208,10 @@ mod imp { if let Some(p) = proxies().lock().unwrap().get(&top).copied() { return Some(p) } // GPUI's own (vendor gpui PATCH.md, x11 `key_proxy`): it reads the keys, since a key never propagates above the focus window let id = prop32(c, top, atom(c, "_BACKPLANE_KEY_PROXY"), AtomEnum::WINDOW).first().copied().filter(|&p| p != 0)?; - // the top-level's focus changes come to our connection too (each client selects its own): a focus put on it (the window manager, - // GPUI's activate) moves on to the proxy at once (pump) - let mask = c.get_window_attributes(top).ok().and_then(|r| r.reply().ok()).map(|a| u32::from(a.your_event_mask)).unwrap_or(0); - let _ = c.change_window_attributes(top, &ChangeWindowAttributesAux::new().event_mask(EventMask::from(mask | u32::from(EventMask::FOCUS_CHANGE)))); + // the top-level's focus changes come to the focus watcher's connection too (each client selects its own): a focus put on it (the + // window manager, GPUI's activate) moves on to the proxy at once (watch_focus) proxies().lock().unwrap().insert(top, id); + watch_focus(top); // the focus already on the top-level (it had the keyboard before the pane came: an automatic attach) has no FocusIn to come: moved now if !PANE_KEYS.load(std::sync::atomic::Ordering::SeqCst) && pane_on_screen(top) && c.get_input_focus().ok().and_then(|r| r.reply().ok()).is_some_and(|r| r.focus == top) { let _ = c.set_input_focus(InputFocus::PARENT, id, x11rb::CURRENT_TIME); @@ -221,7 +220,63 @@ mod imp { if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"kicad_focus_proxy": id, "top": top})); } Some(id) } - /// The wake thread's redirect, at most REDIRECTS_PER within REDIRECT_SPAN: a window manager that puts the focus back on the top-level + /// The focus watcher: a connection and a thread of their own, FocusChange selected on every top-level with a proxy, for every native + /// child (a KiCad pane's container, the Browser's page): the focus put on a top-level itself (the window manager on a click or + /// activation, GPUI's activate) goes on to its proxy at once, while a child is on screen there (pane_on_screen). Not when it went into a + /// child (the proxy, KiCad, the Browser's Chromium). Also while the pane still says KiCad has the keys: a click outside the pane that the + /// window manager answers by focusing the top-level (openbox, xfwm4) comes before GPUI has handled the click, and in that gap (4-40 ms + /// measured) a key over the pane went to KiCad (the race, 1 of 20 on a real desktop). The pane reads its keys from the X focus + /// (has_focus of its container), and a focus on the top-level or on its proxy reads the same there; a hand-in that follows focuses + /// KiCad's frame from either. Its own thread, not the pane's wake thread: a window with only the Browser has no pane to wake, and the + /// thread waits on nothing but these events (the wake thread also reads the pane's own). + fn watcher() -> Option<&'static RustConnection> { + static W: OnceLock>> = OnceLock::new(); + W.get_or_init(|| { + let c = std::sync::Arc::new(RustConnection::connect(None).ok()?.0); + let t = c.clone(); + std::thread::Builder::new().name("x11-focus-proxy".into()).spawn(move || while let Ok(e) = t.wait_for_event() { + let x11rb::protocol::Event::FocusIn(f) = e else { continue }; + let proxy = proxies().lock().unwrap().get(&f.event).copied().filter(|_| pane_on_screen(f.event)); + if let Some(p) = proxy { + if t.get_input_focus().ok().and_then(|r| r.reply().ok()).is_some_and(|r| r.focus == f.event) && redirect_allowed() { + let _ = t.set_input_focus(InputFocus::PARENT, p, x11rb::CURRENT_TIME); let _ = t.flush(); + } + } + }).ok()?; + Some(c) + }).as_deref() + } + fn watch_focus(top: u32) { + let Some(w) = watcher() else { return }; + let _ = w.change_window_attributes(top, &ChangeWindowAttributesAux::new().event_mask(EventMask::FOCUS_CHANGE)); let _ = w.flush(); + } + /// Native children that are not a KiCad pane's container (the Browser's page: cef_native), per top-level: the proxy is kept while any is. + fn others() -> &'static Mutex>> { static O: OnceLock>>> = OnceLock::new(); O.get_or_init(Default::default) } + /// A native child `child` of ours (not KiCad's) made in top-level `top`: the top-level's proxy found and watched, as for a pane. + /// It counts as on screen once `note_pane_on_screen(top, child, true)` says so. + pub fn adopt_child(top: u64, child: u64) { + others().lock().unwrap().entry(top as u32).or_default().insert(child); + let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); focus_proxy(c, top as u32); + } + /// That child gone: off screen, and the proxy dropped when nothing else of ours is in the top-level. + pub fn release_child(top: u64, child: u64) { + note_pane_on_screen(top, child, false); + let top = top as u32; + let empty = { let mut o = others().lock().unwrap(); if let Some(s) = o.get_mut(&top) { s.remove(&child); if s.is_empty() { o.remove(&top); } } !o.contains_key(&top) }; + if !empty { return } + let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); + let parent_of = |w: u32| c.query_tree(w).ok().and_then(|q| q.reply().ok()).map(|t| t.parent); + let ours = containers().lock().unwrap().iter().copied().collect::>(); + if !ours.into_iter().any(|o| parent_of(o) == Some(top)) { proxies().lock().unwrap().remove(&top); } + } + /// The keyboard back to top-level `top` (the Browser giving it back): to its proxy while a native child is on screen there, else the + /// top-level itself. + pub fn focus_home(top: u64) { + let w = home_of(top as u32); + let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); + let _ = c.set_input_focus(InputFocus::PARENT, w, x11rb::CURRENT_TIME); let _ = c.flush(); + } + /// The redirect, at most REDIRECTS_PER within REDIRECT_SPAN: a window manager that puts the focus back on the top-level /// each time it moves (none seen; the review's guard) gets the proxy a few times, then the top-level is left focused for REDIRECT_REST, /// said once, instead of the two of them trading the focus as fast as the X server allows const REDIRECTS_PER: u32 = 4; @@ -290,7 +345,8 @@ mod imp { let parent_of = |w: u32| c.query_tree(w).ok().and_then(|q| q.reply().ok()).map(|t| t.parent); if let Some(top) = parent_of(container) { let others = containers().lock().unwrap().iter().copied().collect::>(); - if !others.into_iter().any(|o| parent_of(o) == Some(top)) { proxies().lock().unwrap().remove(&top); } + let browser = self::others().lock().unwrap().contains_key(&top); + if !browser && !others.into_iter().any(|o| parent_of(o) == Some(top)) { proxies().lock().unwrap().remove(&top); } } let _ = c.allow_events(Allow::REPLAY_POINTER, x11rb::CURRENT_TIME); let _ = c.ungrab_button(ButtonIndex::ANY, container, ModMask::ANY); @@ -887,20 +943,7 @@ mod imp { let _ = c.allow_events(Allow::REPLAY_POINTER, b.time); out.push(super::Ev::Click); } - // the focus put on a top-level of ours itself (the window manager on a click or activation, GPUI's activate): on to its proxy at - // once, here on the wake thread. Not when it went into a child (the proxy, KiCad, the Browser's Chromium). Also while the pane - // still says KiCad has the keys: a click outside the pane that the window manager answers by focusing the top-level (openbox, - // xfwm4) comes before GPUI has handled the click, and in that gap (4-40 ms measured) a key over the pane went to KiCad (the race, - // 1 of 20 on a real desktop). The pane reads its keys from the X focus (has_focus of its container), and a focus on the - // top-level or on its proxy reads the same there; a hand-in that follows focuses KiCad's frame from either. - x11rb::protocol::Event::FocusIn(f) => { - let proxy = proxies().lock().unwrap().get(&f.event).copied().filter(|_| pane_on_screen(f.event)); - if let Some(p) = proxy { - if c.get_input_focus().ok().and_then(|r| r.reply().ok()).is_some_and(|r| r.focus == f.event) && redirect_allowed() { - let _ = c.set_input_focus(InputFocus::PARENT, p, x11rb::CURRENT_TIME); - } - } - } + // (a focus put on a top-level itself: the focus watcher's, on its own connection: watcher) x11rb::protocol::Event::ClientMessage(m) if m.format == 32 => { let d = m.data.as_data32(); if m.type_ == key { if let Some(k) = super::chord(d[1], d[2]) { out.push(if k == "ctrl-`" { super::Ev::Escape } else { super::Ev::Key(k) }); } } diff --git a/test/kicad_embed/embed_pointer_keys_browser_seq_e2e.sh b/test/kicad_embed/embed_pointer_keys_browser_seq_e2e.sh new file mode 100755 index 0000000000..74390c5dcc --- /dev/null +++ b/test/kicad_embed/embed_pointer_keys_browser_seq_e2e.sh @@ -0,0 +1,150 @@ +#!/bin/bash +# The Browser tab's page and a KiCad pane in one client, through the sequences a person can reach today (one viewer page shows at a time: +# a KiCad tile beside the Browser in the same window is not reachable, so not tested here). Backplane holds the keyboard unless the person +# clicked a child; keys typed with the pointer over a child that was not clicked must land in the composer. Needs a client built with the +# embedded Chromium (feature cef) and the fork KiCad (EMBED_MODE=fork). A page logs every keydown into its title (`k:`). +# S1 the Browser shown, the pane alive but hidden: a click in the page gives the page the keys, and the pane says keys=false +# S2 Browser -> board pane -> Browser: over the pane (no click) the keys land in the composer; a click in KiCad gives KiCad the keys; +# Ctrl+` gives them back (keys=false); back on the Browser, over the page (no click) the composer, a click in the page the page +# S3 the pane popped out into its own window, the Browser in the main one: over the page (no click) the composer, a click in the page the +# page (keys=false); the mirror: a click in the popped-out KiCad (keys=true), then a click in the main window's page gives the page the +# keys and the pane says keys=false +set -uo pipefail +HERE=$(cd "$(dirname "$0")" && pwd) +# shellcheck source=lib/env_xvfb.sh +. "$HERE/lib/env_xvfb.sh" +[ "$EMBED_MODE" = "fork" ] || { echo "embed_pointer_keys_browser_seq_e2e: fork only (EMBED_MODE=fork)"; exit 0; } +discover_bins +[ -x "$REAL_HOME/.bun/bin/bun" ] && PATH="$REAL_HOME/.bun/bin:$PATH" +discover_kicad +init_isolated_dirs +python3 "$SEED_PY" "$OUT" "$REPO_ROOT" +start_xvfb_and_wm +export BACKPLANE_KICAD_DEBUG=1 +start_hub +SHOTS="$OUT/barriers"; mkdir -p "$SHOTS" +PAGE='data:text/html,

keys

' +PAGE_JSON=$(python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$PAGE") +# each phase: the client reports, marks, and waits at a barrier (a "shot" whose .done the driver below writes) while the driver types +REP='{"read":"composer"},{"cef":{"report":true}},{"kicad":{"report":true}}' +bar() { printf '{"mark":"%s"},{"shot":"%s","timeout_ms":180000}' "$1" "$1"; } +cat >"$OUT/script.json" <"$OUT/client.log" 2>&1 & +CP=$!; track_pid "$CP" +TOP= +top_xy() { python3 "$DRIVER_PY" list-windows | python3 -c 'import json,sys +w=[w for w in json.load(sys.stdin) if w["xid"]==sys.argv[1]]; print(w[0]["root_x"], w[0]["root_y"]) if w else print(0, 0)' "$TOP"; } +# what the client said last before mark $1: composer text, the page's title, the pane's keys, the page's middle and the pane's middle (root) +state() { python3 - "$OUT/client.log" "$1" "$TX" "$TY" <<'PY' +import json, sys +log, mark, tx, ty = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]) +t = title = keys = r = k = c = None +for l in open(log, errors="ignore"): + if "GPUI_METRIC " not in l: continue + try: o = json.loads(l.split("GPUI_METRIC ", 1)[1]) + except Exception: continue + if o.get("event") == "mark" and o.get("name") == mark: break + if isinstance(o.get("rects"), dict) and "composer" in o["rects"]: c = o["rects"]["composer"] + if isinstance(o.get("rects"), list): + for x in o["rects"]: + if x.get("id") == "composer": c = x + if o.get("event") == "read" and o.get("what") == "composer": t = o.get("text") + if o.get("event") == "cef" and "title" in o: title = o.get("title") + if o.get("event") == "cef" and o.get("view_x") is not None: r = o + if o.get("event") == "kicad" and "keys" in o: keys = o.get("keys"); k = o.get("container") +gx = tx + int(r["view_x"] + r["frame"][0] / 2) if r else 0; gy = ty + int(r["view_y"] + r["frame"][1] / 2) if r else 0 +cx = tx + int(c["x"] + c["w"] / 2) if c else 0; cy = ty + int(c["y"] + c["h"] / 3) if c else 0 +kx = int(k["root_x"] + k["w"] / 2) if k and k.get("root_x") is not None else 0; ky = int(k["root_y"] + k["h"] / 2) if k and k.get("root_y") is not None else 0 +print("\t".join([json.dumps(t or ""), json.dumps(title or ""), json.dumps(keys)] + [str(v) for v in (gx, gy, cx, cy, kx, ky)])) +PY +} +release() { wait_for_log "$OUT/client.log" "\"name\":\"$1\",\"event\":\"mark\"" 900 || { echo "FAIL the client never reached $1"; finish_suite "embed_pointer_keys_browser_seq_e2e"; exit 1; }; sleep 0.5; } +go_on() { touch "$SHOTS/$1.done"; } +type_word() { local w=$1 i; for ((i = 0; i < ${#w}; i++)); do python3 "$XINPUT_PY" key "${w:i:1}" >/dev/null; sleep 0.15; done; } +click() { python3 "$XINPUT_PY" click "$1" "$2" >/dev/null; sleep 1.0; } +move() { python3 "$XINPUT_PY" move "$1" "$2" >/dev/null; sleep 0.8; } +say() { echo "INFO $1: focus [$(xfocus_chain)]"; } +has() { python3 -c 'import json,sys; print(1 if sys.argv[2] in (json.loads(sys.argv[1]) or "") else 0)' "$1" "$2"; } +logged() { python3 -c 'import json,sys; t=json.loads(sys.argv[1]) or ""; print(1 if t.startswith("k:") and sys.argv[2] in t[2:] else 0)' "$1" "$2"; } +not_logged() { python3 -c 'import json,sys; t=json.loads(sys.argv[1]) or ""; print(0 if t.startswith("k:") and sys.argv[2] in t[2:] else 1)' "$1" "$2"; } +is() { [ "$1" = "$2" ] && echo 1 || echo 0; } + +release s1 +TOP=$(python3 "$DRIVER_PY" list-windows | python3 -c 'import json,sys +w=[w for w in json.load(sys.stdin) if "Backplane GPUI" in (w.get("title") or "")]; print(w[0]["xid"] if w else "")') +read -r TX TY < <(top_xy) +IFS=$'\t' read -r _ _ _ GX GY CX CY _ _ < <(state s1) +echo "INFO top $TOP; page root ($GX, $GY); composer root ($CX, $CY)" +if [ "${GX:-0}" -le 0 ] || [ "${CX:-0}" -le 0 ]; then check "S0 the page's and the composer's places are known" 0 "page ($GX, $GY) composer ($CX, $CY)"; finish_suite "embed_pointer_keys_browser_seq_e2e"; exit 1; fi +# S1: the Browser, the pane alive but hidden +click "$CX" "$CY" +# the window manager's part (a click-to-focus putting the X focus on the top-level itself), played GAPS times: how long until it is on the proxy +python3 "$HERE/lib/focus_trace.py" gap "$TOP" "${GAPS:-20}" >"$OUT/gap-s1.log" 2>&1; G1=$(tail -1 "$OUT/gap-s1.log"); echo "INFO S1 gap (the Browser on screen, the pane hidden): $G1" +move "$GX" "$GY"; type_word ha; say "S1 over the page, no click" +click "$GX" "$GY"; type_word hp; say "S1 a click in the page" +go_on s1; release r1 +IFS=$'\t' read -r T1 P1 K1 _ < <(state r1) +check "S1a the pane hidden, over the page (no click): the composer" "$(has "$T1" ha)" "composer $T1, page $P1" +check "S1b a click in the page: the page has the keys" "$(logged "$P1" hp)" "page $P1" +check "S1c and the pane says keys=false" "$(is "$K1" false)" "keys $K1" +all_moved() { [[ $1 =~ moved\ ([0-9]+)/([0-9]+) ]] && [ "${BASH_REMATCH[1]}" = "${BASH_REMATCH[2]}" ] && [ "${BASH_REMATCH[2]}" -gt 0 ] && echo 1 || echo 0; } +check "S1d the Browser on screen: a focus put on the top-level moves to its proxy, every time" "$(all_moved "$G1")" "$G1" +# S2: the board pane shown +release s2a +IFS=$'\t' read -r _ _ _ _ _ _ _ KX KY < <(state s2a) +echo "INFO S2 pane root ($KX, $KY)" +click "$CX" "$CY" +python3 "$HERE/lib/focus_trace.py" gap "$TOP" "${GAPS:-20}" >"$OUT/gap-s2.log" 2>&1; G2=$(tail -1 "$OUT/gap-s2.log"); echo "INFO S2 gap (the pane on screen): $G2" +move "$KX" "$KY"; type_word pb; say "S2 over the pane, no click" +click "$KX" "$KY"; say "S2 a click in KiCad" +go_on s2a; release s2b +IFS=$'\t' read -r T2 _ K2 _ < <(state s2b) +check "S2a over the pane (no click): the composer" "$(has "$T2" pb)" "composer $T2" +check "S2g the pane on screen: a focus put on the top-level moves to its proxy, every time" "$(all_moved "$G2")" "$G2" +check "S2b a click in KiCad hands it the keys" "$(is "$K2" true)" "keys $K2" +python3 "$XINPUT_PY" chord ctrl grave >/dev/null; sleep 0.5; say "S2 Ctrl+\` in KiCad" +go_on s2b; release k2c +IFS=$'\t' read -r _ _ K2C _ < <(state k2c) +check "S2c Ctrl+\` gives the keys back (keys=false)" "$(is "$K2C" false)" "keys $K2C" +release s2d +click "$CX" "$CY"; move "$GX" "$GY"; type_word rb; say "S2 back on the Browser, over the page" +click "$GX" "$GY"; type_word rp; say "S2 a click in the page" +go_on s2d; release r2 +IFS=$'\t' read -r T2D P2D K2D _ < <(state r2) +check "S2d back on the Browser, over the page (no click): the composer" "$(has "$T2D" rb)" "composer $T2D, page $P2D" +check "S2e a click in the page: the page" "$(logged "$P2D" rp)" "page $P2D" +check "S2f and the pane says keys=false" "$(is "$K2D" false)" "keys $K2D" +# S3: the pane popped out, the Browser in the main window +release s3 +# (the window manager may have moved and resized the main window to make room for the popped-out one: everything measured again) +read -r TX TY < <(top_xy) +IFS=$'\t' read -r _ _ _ GX GY CX CY PX PY < <(state s3) +echo "INFO S3 main window at ($TX, $TY): page root ($GX, $GY), composer root ($CX, $CY); popped-out pane root ($PX, $PY)" +click "$CX" "$CY"; move "$GX" "$GY"; type_word ob; say "S3 over the page, pane popped out" +click "$GX" "$GY"; type_word op; say "S3 a click in the page" +go_on s3; release r3 +IFS=$'\t' read -r T3 P3 K3 _ < <(state r3) +check "S3a pane popped out, over the page (no click): the composer" "$(has "$T3" ob)" "composer $T3, page $P3" +check "S3b a click in the page: the page" "$(logged "$P3" op)" "page $P3" +check "S3c and the pane says keys=false" "$(is "$K3" false)" "keys $K3" +release s3m +if [ "${PX:-0}" -gt 0 ]; then click "$PX" "$PY"; say "S3 a click in the popped-out KiCad"; fi +go_on s3m; release k3m +IFS=$'\t' read -r _ _ K3M _ < <(state k3m) +check "S3d the mirror: a click in the popped-out KiCad gives it the keys" "$(is "$K3M" true)" "keys $K3M, pane ($PX, $PY)" +release s3n +click "$GX" "$GY"; type_word mp; say "S3 a click in the main window's page" +go_on s3n; release done +IFS=$'\t' read -r T3N P3N K3N _ < <(state done) +check "S3e then a click in the main window's page: the page" "$(logged "$P3N" mp)" "page $P3N" +check "S3f and the pane says keys=false" "$(is "$K3N" false)" "keys $K3N" +check "S3g nothing typed in KiCad reached the composer or the page by itself" "$(not_logged "$P3N" pb)" "page $P3N" +finish_suite "embed_pointer_keys_browser_seq_e2e" diff --git a/test/kicad_embed/lib/focus_trace.py b/test/kicad_embed/lib/focus_trace.py index a966b1f3bc..4714ee82db 100644 --- a/test/kicad_embed/lib/focus_trace.py +++ b/test/kicad_embed/lib/focus_trace.py @@ -1,7 +1,9 @@ """The X focus over time, for embed_pointer_keys_e2e's race. focus_trace.py watch SECONDS a line ` ` at each change of the X input focus (polled every 2 ms), on $DISPLAY focus_trace.py judge FOCUS KEYS TOP per key line ` `: the focus the key met, and how long after - the click began the focus left the window it had then (the click's hand-back)""" + the click began the focus left the window it had then (the click's hand-back) + focus_trace.py gap TOP N the window manager's part played N times: the X focus put on top-level TOP itself, and how long until + the client moved it on (its focus proxy redirect), polled every 0.2 ms; a line per try and a summary""" import ctypes, ctypes.util, os, sys, time @@ -18,6 +20,28 @@ def watch(seconds): time.sleep(0.002) +def gap(top, n): + x = ctypes.CDLL(ctypes.util.find_library("X11")) + x.XOpenDisplay.restype = ctypes.c_void_p + d = ctypes.c_void_p(x.XOpenDisplay(os.environ["DISPLAY"].encode())) + top, w, r, out = int(top, 0), ctypes.c_ulong(), ctypes.c_int(), [] + for i in range(int(n)): + x.XSetInputFocus(d, ctypes.c_ulong(top), 2, 0) # RevertToParent, CurrentTime: as a window manager's click-to-focus does + x.XSync(d, 0) + t0, moved = time.perf_counter(), None + while time.perf_counter() - t0 < 0.5: + x.XGetInputFocus(d, ctypes.byref(w), ctypes.byref(r)) + if w.value != top: + moved = (time.perf_counter() - t0) * 1000, w.value + break + time.sleep(0.0002) + out.append(moved[0] if moved else None) + print(f"try {i + 1}: " + (f"moved to {hex(moved[1])} after {moved[0]:.1f} ms" if moved else "left on the top-level (500 ms)"), flush=True) + time.sleep(0.3) # (over the redirect cap's 100 ms span: each try is a burst of its own) + got = sorted(v for v in out if v is not None) + print(f"summary: moved {len(got)}/{len(out)}" + (f", median {got[len(got) // 2]:.1f} ms, max {got[-1]:.1f} ms" if got else ""), flush=True) + + def judge(focus_path, keys_path, top): f = [(int(a), int(b, 16)) for a, b in (l.split() for l in open(focus_path) if len(l.split()) == 2)] top = int(top, 0) @@ -40,7 +64,9 @@ def at(t): if __name__ == "__main__": - if sys.argv[1] == "watch": + if sys.argv[1] == "gap": + gap(sys.argv[2], sys.argv[3]) + elif sys.argv[1] == "watch": watch(float(sys.argv[2])) else: judge(*sys.argv[2:5]) From 1fe26bd6058347ca2ac6cb07d4d2f98629ba6387 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 01:28:11 -0500 Subject: [PATCH 3/7] Keep Linux native keyboard focus recovery active --- native/gpui/src/viewers/cef.rs | 4 +- native/gpui/src/viewers/cef_native.rs | 90 +++++++--- native/gpui/src/viewers/native_child.rs | 220 +++++++++++++++++++----- 3 files changed, 241 insertions(+), 73 deletions(-) diff --git a/native/gpui/src/viewers/cef.rs b/native/gpui/src/viewers/cef.rs index fd3f1c0127..b5befba536 100644 --- a/native/gpui/src/viewers/cef.rs +++ b/native/gpui/src/viewers/cef.rs @@ -195,7 +195,7 @@ wrap_focus_handler! { // manager that focuses what is under the pointer moves it there too, and that is nobody's click; nor is a script's focus. Asking // whether a button is down when this callback runs missed the click whenever the press reached Chromium late (a KiCad pane's button // grab replaying it): the page was given the keyboard and taken it back. Elsewhere, and without XInput 2: a button down now) - let clicked = self.tab.host.is_some() && source == FocusSource::SYSTEM && native::pressed_in(self.tab.outer()).unwrap_or_else(native::button_down); + let clicked = self.tab.host.is_some() && source == FocusSource::SYSTEM && native::pressed_in(self.tab.outer()).unwrap_or_else(|| native::button_down(self.tab.outer())); if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_set_focus": {"system": source == FocusSource::SYSTEM, "clicked": clicked}})); } if clicked { self.tab.st.lock().unwrap().person = true; let _ = self.tab.wake.try_send(()); } false as _ @@ -544,7 +544,7 @@ impl Tab { /// windowed: the keyboard to the page (`on`) or back to the client's window pub fn give_keyboard(&self, on: bool) { self.focus(on); - if on { native::focus_child(self.native()) } else if let Some(h) = self.host { native::focus_host(h) } + if on { native::focus_child(self.native()) } else if let Some(h) = self.host { native::focus_host(h, self.frame) } } /// windowed: a key the client did not want goes to the page after all (on_pre_key_event lets it through this time) pub fn reinject(&self, e: &KeyEvent) { diff --git a/native/gpui/src/viewers/cef_native.rs b/native/gpui/src/viewers/cef_native.rs index 4db00e33a9..978236a13d 100644 --- a/native/gpui/src/viewers/cef_native.rs +++ b/native/gpui/src/viewers/cef_native.rs @@ -67,7 +67,9 @@ mod imp { use crate::viewers::native_child as nc; /// The person's last press on the display that was inside a container of ours: when, and which container. Nothing else of a press is kept /// (no position, no other window). Taken by the one focus it explains (`pressed_in`). - static PRESS: Mutex> = Mutex::new(None); + #[derive(Clone, Copy)] + enum PressTarget { Pending, Page(u32), Unavailable } + static PRESS: Mutex> = Mutex::new(None); /// Whether the press watcher runs (XInput 2 on the display): without it `pressed_in` is never true, and on_set_focus falls back to `button_down`. static PRESSES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// How long after the person's press a focus of the page is still that press's. The press reaches us (a raw event, sent before the @@ -90,34 +92,66 @@ mod imp { let mask = [xinput::EventMask { deviceid: 1 /* XIAllMasterDevices */, mask: vec![xinput::XIEventMask::RAW_BUTTON_PRESS] }]; if c.xinput_xi_select_events(root, &mask).ok().and_then(|k| k.check().ok()).is_none() { return } PRESSES.store(true, std::sync::atomic::Ordering::Relaxed); - if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_presses": "watched"})); } - std::thread::Builder::new().name("cef-presses".into()).spawn(move || while let Ok(e) = c.wait_for_event() { - let x11rb::protocol::Event::XinputRawButtonPress(_) = e else { continue }; - // said at once (container 0: not yet known), so a focus that CEF reports while the pointer is followed waits for it (pressed_in) - let at = std::time::Instant::now(); *PRESS.lock().unwrap() = Some((at, 0)); - let ours = containers().lock().unwrap().clone(); - let (mut w, mut hit) = (root, None); - for _ in 0..16 { let Some(r) = c.query_pointer(w).ok().and_then(|r| r.reply().ok()) else { break }; if r.child == x11rb::NONE { break } w = r.child; if ours.contains_key(&w) { hit = Some(w); break } } - *PRESS.lock().unwrap() = hit.map(|h| (at, h)); - if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_press_in_page": hit.is_some()})); } - }).ok(); + let started = std::thread::Builder::new().name("cef-presses".into()).spawn(move || { + while let Ok(e) = c.wait_for_event() { + let x11rb::protocol::Event::XinputRawButtonPress(press) = e else { continue }; + if !matches!(press.detail, 1..=3 | 8..=9) + || press.flags.contains(xinput::PointerEventFlags::POINTER_EMULATED) + { continue } + let at = std::time::Instant::now(); + *PRESS.lock().unwrap() = Some((at, PressTarget::Pending)); + let ours = containers().lock().unwrap().clone(); + let hit = pointer_target(&c, root, |w| ours.contains_key(&w)); + *PRESS.lock().unwrap() = Some((at, hit.map_or(PressTarget::Unavailable, PressTarget::Page))); + if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { + eprintln!("GPUI_LOG {}", serde_json::json!({"cef_press_in_page": hit.is_some()})); + } + } + PRESSES.store(false, std::sync::atomic::Ordering::Relaxed); + }); + if started.is_err() { PRESSES.store(false, std::sync::atomic::Ordering::Relaxed); } }); } - /// Whether the person pressed a mouse button inside container `frame` within PRESS_SPAN (taken: it answers yes once); None without the watcher. + + fn pointer_target(c: &RustConnection, mut w: u32, matches: impl Fn(u32) -> bool) -> Option { + for _ in 0..16 { + w = c.query_pointer(w).ok()?.reply().ok()?.child; + if w == x11rb::NONE { break } + if matches(w) { return Some(w) } + } + None + } + + /// A recent press is consumed once. Preserve the record after consumption so the + /// second CEF callback cannot treat the same press as missing. pub fn pressed_in(frame: u64) -> Option { if !PRESSES.load(std::sync::atomic::Ordering::Relaxed) { return None } - // a press still being followed down (a few round trips): waited for, 50 ms at most let t0 = std::time::Instant::now(); - let mut p = loop { let p = PRESS.lock().unwrap(); if !p.is_some_and(|(at, w)| w == 0 && at.elapsed() <= PRESS_SPAN) || t0.elapsed().as_millis() >= 50 { break p } drop(p); std::thread::sleep(std::time::Duration::from_millis(1)); }; - let yes = p.is_some_and(|(at, w)| w as u64 == frame && at.elapsed() <= PRESS_SPAN); - if yes { *p = None; } - Some(yes) + let mut record = loop { + let record = PRESS.lock().unwrap(); + if !record.is_some_and(|(at, target)| matches!(target, PressTarget::Pending) && at.elapsed() <= PRESS_SPAN) + || t0.elapsed().as_millis() >= 50 + { break record } + drop(record); + std::thread::sleep(std::time::Duration::from_millis(1)); + }; + if let Some((at, target)) = record.filter(|(at, _)| at.elapsed() <= PRESS_SPAN) { + let clicked = matches!(target, PressTarget::Page(w) if w as u64 == frame); + if clicked { *record = Some((at, PressTarget::Unavailable)); } + return Some(clicked); + } + // XWayland can omit the press when the previously focused app is native Wayland. + if std::env::var_os("WAYLAND_DISPLAY").is_some() { None } else { Some(false) } } - /// Whether a mouse button is down now (a focus change while one is, is the person's click; without, a window manager's focus-follows-mouse). - pub fn button_down() -> bool { + + /// Fallback for SYSTEM focus when XI2 did not supply a press. Require the held + /// button and the pointer inside the page that reported focus. + pub fn button_down(frame: u64) -> bool { let Some(g) = conn() else { return false }; let c = g.as_ref().unwrap(); let Some(root) = c.setup().roots.get(SCREEN.load(std::sync::atomic::Ordering::Relaxed)).map(|s| s.root) else { return false }; - c.query_pointer(root).ok().and_then(|r| r.reply().ok()).map_or(false, |p| u16::from(p.mask) & (u16::from(KeyButMask::BUTTON1) | u16::from(KeyButMask::BUTTON2) | u16::from(KeyButMask::BUTTON3)) != 0) + let held = c.query_pointer(root).ok().and_then(|r| r.reply().ok()).is_some_and(|p| + u16::from(p.mask) & u16::from(KeyButMask::BUTTON1 | KeyButMask::BUTTON2 | KeyButMask::BUTTON3) != 0); + held && pointer_target(c, root, |w| w as u64 == frame).is_some() } /// The container gone (its browser closed). pub fn destroy(frame: u64) { if let Some(t) = containers().lock().unwrap().remove(&(frame as u32)) { nc::release_child(t as u64, frame); } let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); let _ = c.destroy_window(frame as u32); let _ = c.flush(); } @@ -158,7 +192,7 @@ mod imp { } /// The keyboard back to the client's window. /// (to its focus proxy while a native child is on screen there: native_child `focus_home`) - pub fn focus_host(h: Host) { if let Host::X11(w) = h { nc::focus_home(w as u64) } } + pub fn focus_host(h: Host, frame: u64) { if let Host::X11(w) = h { nc::focus_home(w as u64, frame) } } /// Where the child is (its geometry in the parent) and whether it is mapped: what the e2e checks. pub fn geometry(w: u64) -> Option<(R, bool)> { let g = conn()?; let c = g.as_ref().unwrap(); @@ -213,8 +247,8 @@ mod imp { EnumChildWindows(p as HWND, Some(cb), &mut out as *mut _ as LPARAM); } out } - #[cfg(windows)] pub fn button_down() -> bool { use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; unsafe { [0x01, 0x02, 0x04].iter().any(|k| GetAsyncKeyState(*k) as u16 & 0x8000 != 0) } } - #[cfg(target_os = "macos")] pub fn button_down() -> bool { + #[cfg(windows)] pub fn button_down(_frame: u64) -> bool { use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; unsafe { [0x01, 0x02, 0x04].iter().any(|k| GetAsyncKeyState(*k) as u16 & 0x8000 != 0) } } + #[cfg(target_os = "macos")] pub fn button_down(_frame: u64) -> bool { #[link(name = "objc")] unsafe extern "C" { fn objc_getClass(n: *const std::ffi::c_char) -> *mut c_void; } unsafe { let cls = objc_getClass(c"NSEvent".as_ptr()); !cls.is_null() && !send0(cls, c"pressedMouseButtons").is_null() } // i18n-ok: an Objective-C class name } @@ -226,7 +260,7 @@ mod imp { /// CEF's SetFocus does it on Windows (its UI thread owns the child); nothing more here. pub fn focus_child(_w: u64) {} /// The client's window is gpui's, on this (its) thread. - pub fn focus_host(h: Host) { if let Host::Win(p) = h { unsafe { SetFocus(p as HWND); } } } + pub fn focus_host(h: Host, _frame: u64) { if let Host::Win(p) = h { unsafe { SetFocus(p as HWND); } } } pub fn geometry(w: u64) -> Option<(R, bool)> { unsafe { let mut rc = std::mem::zeroed::(); @@ -273,8 +307,8 @@ mod imp { EnumChildWindows(p as HWND, Some(cb), &mut out as *mut _ as LPARAM); } out } - #[cfg(windows)] pub fn button_down() -> bool { use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; unsafe { [0x01, 0x02, 0x04].iter().any(|k| GetAsyncKeyState(*k) as u16 & 0x8000 != 0) } } - #[cfg(target_os = "macos")] pub fn button_down() -> bool { + #[cfg(windows)] pub fn button_down(_frame: u64) -> bool { use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; unsafe { [0x01, 0x02, 0x04].iter().any(|k| GetAsyncKeyState(*k) as u16 & 0x8000 != 0) } } + #[cfg(target_os = "macos")] pub fn button_down(_frame: u64) -> bool { #[link(name = "objc")] unsafe extern "C" { fn objc_getClass(n: *const std::ffi::c_char) -> *mut c_void; } unsafe { let cls = objc_getClass(c"NSEvent".as_ptr()); !cls.is_null() && !send0(cls, c"pressedMouseButtons").is_null() } // i18n-ok: an Objective-C class name } @@ -303,7 +337,7 @@ mod imp { } pub fn show(w: u64, on: bool) { unsafe { send_flag(v(w), c"setHidden:", !on); } } pub fn focus_child(w: u64) { unsafe { let win = send0(v(w), c"window"); if !win.is_null() { send_obj(win, c"makeFirstResponder:", v(w)); } } } - pub fn focus_host(h: Host) { if let Host::Mac(p) = h { unsafe { let win = send0(p as *mut c_void, c"window"); if !win.is_null() { send_obj(win, c"makeFirstResponder:", p as *mut c_void); } } } } + pub fn focus_host(h: Host, _frame: u64) { if let Host::Mac(p) = h { unsafe { let win = send0(p as *mut c_void, c"window"); if !win.is_null() { send_obj(win, c"makeFirstResponder:", p as *mut c_void); } } } } pub fn geometry(w: u64) -> Option<(R, bool)> { unsafe { let parent = send0(v(w), c"superview"); if parent.is_null() { return None } diff --git a/native/gpui/src/viewers/native_child.rs b/native/gpui/src/viewers/native_child.rs index d55ac3a48a..b3e9d51356 100644 --- a/native/gpui/src/viewers/native_child.rs +++ b/native/gpui/src/viewers/native_child.rs @@ -148,7 +148,14 @@ impl RedirectCap { if self.n > self.per { self.rest_until = Some(now + self.rest); self.recheck_due = true; return (false, true) } (true, false) } - /// The pane's tick at `now`: true once when a rest has run out (the re-check: the focus looked at again), then false until a cap trips again + /// Milliseconds to the next recovery check, or an indefinite wait with no recovery pending. + #[cfg(target_os = "linux")] + fn recheck_timeout(&self, now: std::time::Instant) -> i32 { + if !self.recheck_due { return -1 } + let remaining = self.rest_until.map_or(std::time::Duration::ZERO, |until| until.saturating_duration_since(now)); + remaining.as_nanos().div_ceil(1_000_000).min(i32::MAX as u128) as i32 + } + /// True once when a rest has run out, then false until the cap trips again. pub(crate) fn recheck(&mut self, now: std::time::Instant) -> bool { if !self.recheck_due || self.rest_until.is_some_and(|r| now < r) { return false } self.recheck_due = false; @@ -159,7 +166,7 @@ impl RedirectCap { #[cfg(target_os = "linux")] mod imp { use super::{Frame, R}; - use std::sync::{Mutex, MutexGuard, OnceLock}; + use std::{os::{fd::AsRawFd, unix::net::UnixDatagram}, sync::{Arc, Mutex, MutexGuard, OnceLock, atomic::{AtomicBool, Ordering}}, time::Instant}; use x11rb::{connection::Connection, protocol::{shape::{self, ConnectionExt as _}, xproto::*}, rust_connection::RustConnection, wrapper::ConnectionExt as _}; static SCREEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); @@ -193,6 +200,9 @@ mod imp { &CreateWindowAux::new().background_pixmap(x11rb::NONE).border_pixel(scr.black_pixel).colormap(scr.default_colormap) .event_mask(EventMask::SUBSTRUCTURE_NOTIFY)).ok()?.check().ok()?; let _ = c.flush(); containers().lock().unwrap().insert(id); + // Keep a second subscription for the pane's pump if the watcher is unavailable. + let mask = c.get_window_attributes(parent).ok().and_then(|r| r.reply().ok()).map_or(EventMask::NO_EVENT, |a| a.your_event_mask); + let _ = c.change_window_attributes(parent, &ChangeWindowAttributesAux::new().event_mask(mask | EventMask::FOCUS_CHANGE)); focus_proxy(c, parent); Some(id as u64) } @@ -212,10 +222,8 @@ mod imp { // window manager, GPUI's activate) moves on to the proxy at once (watch_focus) proxies().lock().unwrap().insert(top, id); watch_focus(top); - // the focus already on the top-level (it had the keyboard before the pane came: an automatic attach) has no FocusIn to come: moved now - if !PANE_KEYS.load(std::sync::atomic::Ordering::SeqCst) && pane_on_screen(top) && c.get_input_focus().ok().and_then(|r| r.reply().ok()).is_some_and(|r| r.focus == top) { - let _ = c.set_input_focus(InputFocus::PARENT, id, x11rb::CURRENT_TIME); - } + // The top-level can already have focus when a child attaches, with no FocusIn to come. + redirect_focus(c, Some(top)); let _ = c.flush(); if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"kicad_focus_proxy": id, "top": top})); } Some(id) @@ -229,27 +237,104 @@ mod imp { /// (has_focus of its container), and a focus on the top-level or on its proxy reads the same there; a hand-in that follows focuses /// KiCad's frame from either. Its own thread, not the pane's wake thread: a window with only the Browser has no pane to wake, and the /// thread waits on nothing but these events (the wake thread also reads the pane's own). - fn watcher() -> Option<&'static RustConnection> { - static W: OnceLock>> = OnceLock::new(); - W.get_or_init(|| { - let c = std::sync::Arc::new(RustConnection::connect(None).ok()?.0); - let t = c.clone(); - std::thread::Builder::new().name("x11-focus-proxy".into()).spawn(move || while let Ok(e) = t.wait_for_event() { - let x11rb::protocol::Event::FocusIn(f) = e else { continue }; - let proxy = proxies().lock().unwrap().get(&f.event).copied().filter(|_| pane_on_screen(f.event)); - if let Some(p) = proxy { - if t.get_input_focus().ok().and_then(|r| r.reply().ok()).is_some_and(|r| r.focus == f.event) && redirect_allowed() { - let _ = t.set_input_focus(InputFocus::PARENT, p, x11rb::CURRENT_TIME); let _ = t.flush(); + struct FocusWatcher { + connection: Arc, + wake: UnixDatagram, + } + static WATCHER: OnceLock> = OnceLock::new(); + static WATCHER_RUNNING: AtomicBool = AtomicBool::new(false); + + fn watcher_error(stage: &str, error: impl std::fmt::Display) { + eprintln!("GPUI_LOG {}", serde_json::json!({"native_focus_watcher": stage, "error": error.to_string()})); + } + + impl FocusWatcher { + fn start() -> Result> { + let connection = Arc::new(RustConnection::connect(None)?.0); + let (wake, notices) = UnixDatagram::pair()?; + wake.set_nonblocking(true)?; + let receiver = connection.clone(); + WATCHER_RUNNING.store(true, Ordering::Release); + let thread = std::thread::Builder::new().name("x11-focus-proxy".into()).spawn(move || { + let result = watch_focus_events(&receiver, ¬ices); + WATCHER_RUNNING.store(false, Ordering::Release); + watcher_error("stopped", result); + // FocusIn may already have been consumed by the pump before the failure. + if let Some(g) = conn() { + redirect_focus(g.as_ref().unwrap(), None); + } + }); + if let Err(error) = thread { + WATCHER_RUNNING.store(false, Ordering::Release); + return Err(error.into()); + } + Ok(Self { connection, wake }) + } + } + + fn watch_focus_events(c: &RustConnection, notices: &UnixDatagram) -> Box { + let mut fds = [ + libc::pollfd { fd: c.stream().as_raw_fd(), events: libc::POLLIN, revents: 0 }, + libc::pollfd { fd: notices.as_raw_fd(), events: libc::POLLIN, revents: 0 }, + ]; + loop { + let timeout = { + let mut cap = CAP.lock().unwrap_or_else(|e| e.into_inner()); + let now = Instant::now(); + let timeout = cap.recheck_timeout(now); + let due = cap.recheck(now); + drop(cap); + if due { redirect_focus(c, None); } + timeout + }; + match c.poll_for_event() { + Ok(Some(x11rb::protocol::Event::FocusIn(f))) => { redirect_focus(c, Some(f.event)); } + Ok(Some(_)) => {} + Err(error) => return error.into(), + Ok(None) => { + if unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as _, timeout) } < 0 { + let error = std::io::Error::last_os_error(); + if error.kind() == std::io::ErrorKind::Interrupted { continue } + return error.into(); + } + if fds[1].revents & libc::POLLIN != 0 { + if let Err(error) = notices.recv(&mut [0]) { return error.into() } } } - }).ok()?; - Some(c) - }).as_deref() + } + } } + fn watch_focus(top: u32) { - let Some(w) = watcher() else { return }; - let _ = w.change_window_attributes(top, &ChangeWindowAttributesAux::new().event_mask(EventMask::FOCUS_CHANGE)); let _ = w.flush(); + let Some(watcher) = WATCHER.get_or_init(|| match FocusWatcher::start() { + Ok(watcher) => Some(watcher), + Err(error) => { watcher_error("failed to start", error); None } + }) else { return }; + let result = watcher.connection.change_window_attributes(top, + &ChangeWindowAttributesAux::new().event_mask(EventMask::FOCUS_CHANGE)); + let error = match result { + Ok(request) => request.check().err().map(|e| e.to_string()), + Err(error) => Some(error.to_string()), + }; + if let Some(error) = error { watcher_error("could not subscribe", error); } + // The checked request can queue events in x11rb while draining the socket. + let _ = watcher.wake.send(&[0]); } + + // The event may have been queued before focus moved elsewhere. With no event (cap recovery), + // look up the top-level that actually holds focus, across all registered native children. + fn redirect_focus(c: &RustConnection, event_top: Option) { + let proxy_for = |top| proxies().lock().unwrap().get(&top).copied().filter(|_| pane_on_screen(top)); + let event_proxy = event_top.and_then(proxy_for); + if event_top.is_some() && event_proxy.is_none() { return } + let Some(focus) = c.get_input_focus().ok().and_then(|request| request.reply().ok()).map(|r| r.focus) else { return }; + if event_top.is_some_and(|top| top != focus) { return } + if let Some(proxy) = event_proxy.or_else(|| proxy_for(focus)).filter(|_| redirect_allowed()) { + let _ = c.set_input_focus(InputFocus::PARENT, proxy, x11rb::CURRENT_TIME); + let _ = c.flush(); + } + } + /// Native children that are not a KiCad pane's container (the Browser's page: cef_native), per top-level: the proxy is kept while any is. fn others() -> &'static Mutex>> { static O: OnceLock>>> = OnceLock::new(); O.get_or_init(Default::default) } /// A native child `child` of ours (not KiCad's) made in top-level `top`: the top-level's proxy found and watched, as for a pane. @@ -267,14 +352,21 @@ mod imp { let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); let parent_of = |w: u32| c.query_tree(w).ok().and_then(|q| q.reply().ok()).map(|t| t.parent); let ours = containers().lock().unwrap().iter().copied().collect::>(); + // The watcher can keep its FocusChange selection until X destroys the top-level. Without a proxy it ignores those events. if !ours.into_iter().any(|o| parent_of(o) == Some(top)) { proxies().lock().unwrap().remove(&top); } } - /// The keyboard back to top-level `top` (the Browser giving it back): to its proxy while a native child is on screen there, else the - /// top-level itself. - pub fn focus_home(top: u64) { - let w = home_of(top as u32); + /// Return the keyboard only from this Browser container. Serialize the ownership check + /// and the focus change on the X server so a click in another window cannot intervene. + #[cfg(feature = "cef")] + pub fn focus_home(top: u64, container: u64) { let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); - let _ = c.set_input_focus(InputFocus::PARENT, w, x11rb::CURRENT_TIME); let _ = c.flush(); + let w = home_of(top as u32); + if c.grab_server().ok().and_then(|request| request.check().ok()).is_none() { return } + if focus_in(c, container as u32) { + let _ = c.set_input_focus(InputFocus::PARENT, w, x11rb::CURRENT_TIME); + } + let _ = c.ungrab_server(); + let _ = c.flush(); } /// The redirect, at most REDIRECTS_PER within REDIRECT_SPAN: a window manager that puts the focus back on the top-level /// each time it moves (none seen; the review's guard) gets the proxy a few times, then the top-level is left focused for REDIRECT_REST, @@ -285,7 +377,11 @@ mod imp { static CAP: Mutex = Mutex::new(super::RedirectCap::new(REDIRECTS_PER, REDIRECT_SPAN, REDIRECT_REST)); fn redirect_allowed() -> bool { let (ok, tripped) = CAP.lock().unwrap_or_else(|e| e.into_inner()).allow(std::time::Instant::now()); - if tripped { eprintln!("GPUI_LOG {}", serde_json::json!({"kicad_focus_proxy_rest": {"redirects": REDIRECTS_PER, "within_ms": REDIRECT_SPAN.as_millis() as u64, "rest_ms": REDIRECT_REST.as_millis() as u64}})); } + if tripped { + // The cap can also trip on the UI thread as a native child comes on screen. + // Interrupt the watcher's indefinite wait so it schedules the recovery. + if let Some(Some(watcher)) = WATCHER.get() { let _ = watcher.wake.send(&[0]); } + eprintln!("GPUI_LOG {}", serde_json::json!({"kicad_focus_proxy_rest": {"redirects": REDIRECTS_PER, "within_ms": REDIRECT_SPAN.as_millis() as u64, "rest_ms": REDIRECT_REST.as_millis() as u64}})); } ok } static SCREENS: std::sync::LazyLock> = std::sync::LazyLock::new(Default::default); @@ -295,11 +391,10 @@ mod imp { pub fn note_pane_on_screen(top: u64, child: u64, on: bool) { if top == 0 { return } let came = SCREENS.lock().unwrap_or_else(|e| e.into_inner()).set(top, child, on); - if !came || PANE_KEYS.load(std::sync::atomic::Ordering::SeqCst) { return } - let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); - let Some(p) = proxies().lock().unwrap().get(&(top as u32)).copied() else { return }; - // (counted against the redirect cap like every other move: a pane flapping on and off screen cannot trade the focus without bound) - if c.get_input_focus().ok().and_then(|r| r.reply().ok()).is_some_and(|r| r.focus == top as u32) && redirect_allowed() { let _ = c.set_input_focus(InputFocus::PARENT, p, x11rb::CURRENT_TIME); let _ = c.flush(); } + if !came { return } + // Check actual X focus. A pane's last tick may report keys after it closes, + // and a pane in another window says nothing about this top-level. + if let Some(g) = conn() { redirect_focus(g.as_ref().unwrap(), Some(top as u32)); } } /// The window the keyboard goes to when it is Backplane's in top-level `w`: its focus proxy while a pane's frame is on screen there, /// else `w` itself @@ -763,19 +858,17 @@ mod imp { pub fn activated_after_close(_main: u64, _popped: u64) -> bool { true } pub fn keep_focus(_top: u64) -> bool { false } /// Whether KiCad has the keyboard now (the pane's tick). Its change to Backplane moves a focus left on a top-level to its proxy; the - /// wake thread's redirect (pump) does not wait for it + /// focus watcher's redirect does not wait for it static PANE_KEYS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub fn note_pane_keys(kicad: bool) { // (called every tick: only a change to Backplane's keyboard looks at the focus) let was = PANE_KEYS.swap(kicad, std::sync::atomic::Ordering::SeqCst); // a rest of the redirect cap run out with Backplane holding the keyboard: a focus still on a top-level goes to its proxy (else the // cap would leave #1505's fault in place until the next focus change) - if !kicad && CAP.lock().unwrap_or_else(|e| e.into_inner()).recheck(std::time::Instant::now()) { - let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); - let f = c.get_input_focus().ok().and_then(|r| r.reply().ok()).map(|r| r.focus); - let p = f.filter(|&f| pane_on_screen(f)).and_then(|f| proxies().lock().unwrap().get(&f).copied()); - if let Some(p) = p.filter(|_| redirect_allowed()) { let _ = c.set_input_focus(InputFocus::PARENT, p, x11rb::CURRENT_TIME); let _ = c.flush(); } - if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"kicad_focus_proxy_recheck": {"focus": f, "moved_to": p}})); } + if !kicad && !WATCHER_RUNNING.load(Ordering::Acquire) + && CAP.lock().unwrap_or_else(|e| e.into_inner()).recheck(Instant::now()) + { + if let Some(g) = conn() { redirect_focus(g.as_ref().unwrap(), None); } return; } // the keyboard Backplane's again with the focus left on a top-level itself (a FocusIn seen while KiCad still had the keys): its proxy @@ -846,8 +939,12 @@ mod imp { } /// Whether the X keyboard focus is in `container` (on one of its frames or their windows): the editor has the keys. pub fn has_focus(container: u64) -> bool { - let container = container as u32; - let Some(g) = conn() else { return false }; let c = g.as_ref().unwrap(); + let Some(g) = conn() else { return false }; + focus_in(g.as_ref().unwrap(), container as u32) + } + + fn focus_in(c: &RustConnection, container: u32) -> bool { + if container <= 1 { return false } let Some(mut w) = c.get_input_focus().ok().and_then(|r| r.reply().ok()).map(|f| f.focus) else { return false }; let root = root(c).unwrap_or(0); for _ in 0..32 { if w == container { return true } if w == root || w == 0 || w == 1 { return false } @@ -921,6 +1018,39 @@ mod imp { let per = m.keysyms_per_keycode as usize; m.keysyms.chunks(per.max(1)).position(|k| k.contains(&keysym)).map(|i| lo + i as u8) } + fn pane_fallback_top(watcher_running: bool, top: u32) -> Option { + (!watcher_running).then_some(top) + } + + #[cfg(test)] + mod focus_watcher_tests { + use super::*; + use std::time::Duration; + + #[test] + fn watcher_waits_for_and_recovers_from_each_cap_rest() { + let ms = Duration::from_millis; + let now = Instant::now(); + let mut cap = super::super::RedirectCap::new(1, ms(100), ms(1000)); + assert_eq!(cap.recheck_timeout(now), -1); + for start in [now, now + ms(1010)] { + assert_eq!(cap.allow(start), (true, false)); + assert_eq!(cap.allow(start + ms(5)), (false, true)); + assert_eq!(cap.recheck_timeout(start + ms(6)), 999); + assert_eq!(cap.recheck_timeout(start + ms(1005)), 0); + assert!(cap.recheck(start + ms(1005))); + assert_eq!(cap.recheck_timeout(start + ms(1005)), -1); + assert!(!cap.recheck(start + ms(1006))); + } + } + + #[test] + fn pane_pump_redirects_only_without_a_watcher() { + assert_eq!(pane_fallback_top(false, 42), Some(42)); + assert_eq!(pane_fallback_top(true, 42), None); + } + } + /// What came to our own connection since the last call (drained): the grabbed escape chord, and the fork's ClientMessages to the container /// (`_BACKPLANE_KEY`: a reserved chord pressed in KiCad, as a gpui keystroke; `_BACKPLANE_FOCUS`: a click gave KiCad the keyboard). /// What our connection read for the pane and it has not taken yet (`pump` fills it, `events` empties it). @@ -943,7 +1073,11 @@ mod imp { let _ = c.allow_events(Allow::REPLAY_POINTER, b.time); out.push(super::Ev::Click); } - // (a focus put on a top-level itself: the focus watcher's, on its own connection: watcher) + x11rb::protocol::Event::FocusIn(f) => { + if let Some(top) = pane_fallback_top(WATCHER_RUNNING.load(Ordering::Acquire), f.event) { + redirect_focus(c, Some(top)); + } + } x11rb::protocol::Event::ClientMessage(m) if m.format == 32 => { let d = m.data.as_data32(); if m.type_ == key { if let Some(k) = super::chord(d[1], d[2]) { out.push(if k == "ctrl-`" { super::Ev::Escape } else { super::Ev::Key(k) }); } } From 59d5dff035ebee856c7e129af285f784249d8488 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 01:52:33 -0500 Subject: [PATCH 4/7] Expose both windows in the stacked WM keyboard test --- .../embed_pointer_keys_browser_seq_e2e.sh | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/test/kicad_embed/embed_pointer_keys_browser_seq_e2e.sh b/test/kicad_embed/embed_pointer_keys_browser_seq_e2e.sh index 74390c5dcc..4664141e28 100755 --- a/test/kicad_embed/embed_pointer_keys_browser_seq_e2e.sh +++ b/test/kicad_embed/embed_pointer_keys_browser_seq_e2e.sh @@ -33,7 +33,7 @@ cat >"$OUT/script.json" < Date: Sat, 21 Nov 2026 01:57:17 -0500 Subject: [PATCH 5/7] Record the delivered Browser click and serialize X focus redirects --- native/gpui/Cargo.toml | 2 +- native/gpui/src/viewers/cef.rs | 6 +- native/gpui/src/viewers/cef_native.rs | 129 ++++++++++++------------ native/gpui/src/viewers/native_child.rs | 38 ++++--- 4 files changed, 90 insertions(+), 85 deletions(-) diff --git a/native/gpui/Cargo.toml b/native/gpui/Cargo.toml index 9fa9eae5de..40fce0485c 100644 --- a/native/gpui/Cargo.toml +++ b/native/gpui/Cargo.toml @@ -47,7 +47,7 @@ resvg = { version = "0.45.0", default-features = false, features = ["text", "sys flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] } [target.'cfg(target_os = "linux")'.dependencies] -x11rb = { version = "0.13", default-features = false, features = ["shape", "xfixes", "xinput"] } +x11rb = { version = "0.13", default-features = false, features = ["shape", "xfixes"] } gpui = { version = "=0.2.2", default-features = false, features = ["x11"] } # The 3D page's own GPU context (viewers/solid_gpu.rs): the versions gpui already builds on Linux. blade-graphics = "0.7.0" diff --git a/native/gpui/src/viewers/cef.rs b/native/gpui/src/viewers/cef.rs index b5befba536..fba7c757ff 100644 --- a/native/gpui/src/viewers/cef.rs +++ b/native/gpui/src/viewers/cef.rs @@ -191,10 +191,8 @@ wrap_focus_handler! { /// Tab past the page's last element: the keyboard goes back to the client /// a click into the page (the system moving the keyboard there) is the person's, unlike our own SetFocus calls fn on_set_focus(&self, _b: Option<&mut Browser>, source: FocusSource) -> ::std::os::raw::c_int { - // (the person's press inside this page's container, recorded when it happened (cef_native `pressed_in`, X11 with XInput 2): a window - // manager that focuses what is under the pointer moves it there too, and that is nobody's click; nor is a script's focus. Asking - // whether a button is down when this callback runs missed the click whenever the press reached Chromium late (a KiCad pane's button - // grab replaying it): the page was given the keyboard and taken it back. Elsewhere, and without XInput 2: a button down now) + // The native page records and replays the delivered X press before CEF sees it. + // A SYSTEM focus with no such record cannot claim a page with an active button grab. let clicked = self.tab.host.is_some() && source == FocusSource::SYSTEM && native::pressed_in(self.tab.outer()).unwrap_or_else(|| native::button_down(self.tab.outer())); if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { eprintln!("GPUI_LOG {}", serde_json::json!({"cef_set_focus": {"system": source == FocusSource::SYSTEM, "clicked": clicked}})); } if clicked { self.tab.st.lock().unwrap().person = true; let _ = self.tab.wake.try_send(()); } diff --git a/native/gpui/src/viewers/cef_native.rs b/native/gpui/src/viewers/cef_native.rs index 978236a13d..6cee11275b 100644 --- a/native/gpui/src/viewers/cef_native.rs +++ b/native/gpui/src/viewers/cef_native.rs @@ -53,7 +53,7 @@ mod imp { c.create_window(scr.root_depth, id, parent, 0, 0, 1, 1, 0, WindowClass::INPUT_OUTPUT, scr.root_visual, &CreateWindowAux::new().background_pixel(scr.white_pixel).border_pixel(scr.black_pixel).colormap(scr.default_colormap)).ok()?.check().ok()?; let _ = c.flush(); drop(g); - containers().lock().unwrap().insert(id, parent); watch_presses(); + containers().lock().unwrap().insert(id, parent); watch_presses(id); // a native child in the client's window like a KiCad pane's: while it is on screen (place_in) Backplane's keyboard is on the window's // focus proxy, not the window itself, or core X gives every key typed with the pointer over the page to Chromium (#1505's fault) nc::adopt_child(parent as u64, id as u64); @@ -65,52 +65,65 @@ mod imp { fn containers() -> &'static Mutex> { static C: OnceLock>> = OnceLock::new(); C.get_or_init(Default::default) } fn top_of(frame: u64) -> Option { containers().lock().unwrap().get(&(frame as u32)).map(|t| *t as u64) } use crate::viewers::native_child as nc; - /// The person's last press on the display that was inside a container of ours: when, and which container. Nothing else of a press is kept - /// (no position, no other window). Taken by the one focus it explains (`pressed_in`). - #[derive(Clone, Copy)] - enum PressTarget { Pending, Page(u32), Unavailable } - static PRESS: Mutex> = Mutex::new(None); - /// Whether the press watcher runs (XInput 2 on the display): without it `pressed_in` is never true, and on_set_focus falls back to `button_down`. - static PRESSES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - /// How long after the person's press a focus of the page is still that press's. The press reaches us (a raw event, sent before the - /// press is delivered or grabbed) before Chromium has it; Chromium focuses its window on it and CEF says so 15-25 ms later on Xvfb, more - /// under load, and later still when a KiCad pane's button grab holds the press until the pane's tick replays it (40 ms ticks). Neither - /// the press nor CEF's callback carries an X time to order them by, so the order is the press's arrival here, and a press explains one - /// focus only: a script's focus after the person's own click has nothing left to claim. + /// The latest press delivered to one of our containers. Record it before replaying + /// the original X event, so even a released click can explain one CEF focus callback. + static PRESS: Mutex> = Mutex::new(None); + static PRESS_WINDOWS: std::sync::LazyLock>> = + std::sync::LazyLock::new(Default::default); const PRESS_SPAN: std::time::Duration = std::time::Duration::from_millis(400); - /// The press watcher: a connection and a thread of its own, XInput 2 raw button presses selected on the root (every press on the display, - /// whatever grabs it; no other client's delivery is changed). On each, the window under the pointer is followed down from the root and the - /// press is recorded only when a container of ours is on that path. Started with the first container. XWayland sends raw events only - /// while one of its own clients has the focus: a click from a Wayland window into the page is then not seen, and button_down decides. - fn watch_presses() { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - use x11rb::protocol::xinput::{self, ConnectionExt as _}; - let Ok((c, n)) = RustConnection::connect(None) else { return }; - let Some(root) = c.setup().roots.get(n).map(|s| s.root) else { return }; - if !c.xinput_xi_query_version(2, 2).ok().and_then(|r| r.reply().ok()).is_some_and(|v| v.major_version >= 2) { return } - let mask = [xinput::EventMask { deviceid: 1 /* XIAllMasterDevices */, mask: vec![xinput::XIEventMask::RAW_BUTTON_PRESS] }]; - if c.xinput_xi_select_events(root, &mask).ok().and_then(|k| k.check().ok()).is_none() { return } - PRESSES.store(true, std::sync::atomic::Ordering::Relaxed); - let started = std::thread::Builder::new().name("cef-presses".into()).spawn(move || { - while let Ok(e) = c.wait_for_event() { - let x11rb::protocol::Event::XinputRawButtonPress(press) = e else { continue }; - if !matches!(press.detail, 1..=3 | 8..=9) - || press.flags.contains(xinput::PointerEventFlags::POINTER_EMULATED) - { continue } - let at = std::time::Instant::now(); - *PRESS.lock().unwrap() = Some((at, PressTarget::Pending)); - let ours = containers().lock().unwrap().clone(); - let hit = pointer_target(&c, root, |w| ours.contains_key(&w)); - *PRESS.lock().unwrap() = Some((at, hit.map_or(PressTarget::Unavailable, PressTarget::Page))); - if std::env::var_os("BACKPLANE_KICAD_DEBUG").is_some() { - eprintln!("GPUI_LOG {}", serde_json::json!({"cef_press_in_page": hit.is_some()})); - } + + fn watch_presses(frame: u32) { + use std::sync::{Arc, Weak}; + static WATCHER: OnceLock>> = OnceLock::new(); + let watcher = WATCHER.get_or_init(|| { + let start = || -> Result, Box> { + let connection = Arc::new(RustConnection::connect(None)?.0); + let thread = connection.clone(); + std::thread::Builder::new().name("cef-presses".into()).spawn(move || { + let error = loop { + match thread.wait_for_event() { + Ok(x11rb::protocol::Event::ButtonPress(press)) => { + *PRESS.lock().unwrap() = Some((std::time::Instant::now(), press.event)); + // Replay releases the synchronous grab and delivers the same press to Chromium. + if let Err(error) = thread.allow_events(Allow::REPLAY_POINTER, press.time).and_then(|_| thread.flush()) { + break error; + } + } + Ok(_) => {} + Err(error) => break error, + } + }; + PRESS_WINDOWS.lock().unwrap().clear(); + eprintln!("GPUI_LOG {}", serde_json::json!({"cef_press_watcher": error.to_string()})); + })?; + Ok(Arc::downgrade(&connection)) + }; + match start() { + Ok(connection) => Some(connection), + Err(error) => { + eprintln!("GPUI_LOG {}", serde_json::json!({"cef_press_watcher": error.to_string()})); + None } - PRESSES.store(false, std::sync::atomic::Ordering::Relaxed); - }); - if started.is_err() { PRESSES.store(false, std::sync::atomic::Ordering::Relaxed); } + } }); + let Some(connection) = watcher.as_ref().and_then(Weak::upgrade) else { return }; + // Only buttons that count as a click are grabbed. The server delivers wheel buttons + // normally, and delivers touch taps that emulate a button through the same grab. + // A container grab observes the actual delivered click, including entry from native Wayland. + let mut installed = true; + for button in [1u8, 2, 3, 8, 9] { + let request = connection.grab_button(false, frame, EventMask::BUTTON_PRESS, + GrabMode::SYNC, GrabMode::ASYNC, x11rb::NONE, x11rb::NONE, + ButtonIndex::from(button), ModMask::ANY); + installed &= request.ok().and_then(|request| request.check().ok()).is_some(); + } + if installed { + PRESS_WINDOWS.lock().unwrap().insert(frame); + } else { + let _ = connection.ungrab_button(ButtonIndex::ANY, frame, ModMask::ANY); + let _ = connection.flush(); + eprintln!("GPUI_LOG {}", serde_json::json!({"cef_press_watcher": "could not grab page buttons", "frame": frame})); + } } fn pointer_target(c: &RustConnection, mut w: u32, matches: impl Fn(u32) -> bool) -> Option { @@ -122,29 +135,17 @@ mod imp { None } - /// A recent press is consumed once. Preserve the record after consumption so the - /// second CEF callback cannot treat the same press as missing. + /// A recent press is consumed once for the page that received it. pub fn pressed_in(frame: u64) -> Option { - if !PRESSES.load(std::sync::atomic::Ordering::Relaxed) { return None } - let t0 = std::time::Instant::now(); - let mut record = loop { - let record = PRESS.lock().unwrap(); - if !record.is_some_and(|(at, target)| matches!(target, PressTarget::Pending) && at.elapsed() <= PRESS_SPAN) - || t0.elapsed().as_millis() >= 50 - { break record } - drop(record); - std::thread::sleep(std::time::Duration::from_millis(1)); - }; - if let Some((at, target)) = record.filter(|(at, _)| at.elapsed() <= PRESS_SPAN) { - let clicked = matches!(target, PressTarget::Page(w) if w as u64 == frame); - if clicked { *record = Some((at, PressTarget::Unavailable)); } - return Some(clicked); + let mut record = PRESS.lock().unwrap(); + if record.is_some_and(|(at, window)| window as u64 == frame && at.elapsed() <= PRESS_SPAN) { + *record = None; + return Some(true); } - // XWayland can omit the press when the previously focused app is native Wayland. - if std::env::var_os("WAYLAND_DISPLAY").is_some() { None } else { Some(false) } + PRESS_WINDOWS.lock().unwrap().contains(&(frame as u32)).then_some(false) } - /// Fallback for SYSTEM focus when XI2 did not supply a press. Require the held + /// Fallback for SYSTEM focus if the page button grab could not be installed. Require the held /// button and the pointer inside the page that reported focus. pub fn button_down(frame: u64) -> bool { let Some(g) = conn() else { return false }; let c = g.as_ref().unwrap(); @@ -154,7 +155,7 @@ mod imp { held && pointer_target(c, root, |w| w as u64 == frame).is_some() } /// The container gone (its browser closed). - pub fn destroy(frame: u64) { if let Some(t) = containers().lock().unwrap().remove(&(frame as u32)) { nc::release_child(t as u64, frame); } let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); let _ = c.destroy_window(frame as u32); let _ = c.flush(); } + pub fn destroy(frame: u64) { PRESS_WINDOWS.lock().unwrap().remove(&(frame as u32)); if let Some(t) = containers().lock().unwrap().remove(&(frame as u32)) { nc::release_child(t as u64, frame); } let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); let _ = c.destroy_window(frame as u32); let _ = c.flush(); } /// The container (and Chromium's window filling it) over the pane at `r`, mapped; or unmapped. pub fn place_in(frame: u64, w: u64, r: Option) { if let Some(t) = top_of(frame) { nc::note_pane_on_screen(t, frame, r.is_some()); } diff --git a/native/gpui/src/viewers/native_child.rs b/native/gpui/src/viewers/native_child.rs index b3e9d51356..24c8338379 100644 --- a/native/gpui/src/viewers/native_child.rs +++ b/native/gpui/src/viewers/native_child.rs @@ -327,12 +327,21 @@ mod imp { let proxy_for = |top| proxies().lock().unwrap().get(&top).copied().filter(|_| pane_on_screen(top)); let event_proxy = event_top.and_then(proxy_for); if event_top.is_some() && event_proxy.is_none() { return } - let Some(focus) = c.get_input_focus().ok().and_then(|request| request.reply().ok()).map(|r| r.focus) else { return }; - if event_top.is_some_and(|top| top != focus) { return } - if let Some(proxy) = event_proxy.or_else(|| proxy_for(focus)).filter(|_| redirect_allowed()) { - let _ = c.set_input_focus(InputFocus::PARENT, proxy, x11rb::CURRENT_TIME); - let _ = c.flush(); - } + with_server_grab(c, || { + let Some(focus) = c.get_input_focus().ok().and_then(|request| request.reply().ok()).map(|r| r.focus) else { return }; + if event_top.is_some_and(|top| top != focus) { return } + if let Some(proxy) = event_proxy.or_else(|| proxy_for(focus)).filter(|_| redirect_allowed()) { + let _ = c.set_input_focus(InputFocus::PARENT, proxy, x11rb::CURRENT_TIME); + } + }); + } + + // A focus check and its SetInputFocus are one operation with respect to other X clients. + fn with_server_grab(c: &RustConnection, operation: impl FnOnce()) { + if c.grab_server().is_err() { return } + operation(); + let _ = c.ungrab_server(); + let _ = c.flush(); } /// Native children that are not a KiCad pane's container (the Browser's page: cef_native), per top-level: the proxy is kept while any is. @@ -361,12 +370,11 @@ mod imp { pub fn focus_home(top: u64, container: u64) { let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); let w = home_of(top as u32); - if c.grab_server().ok().and_then(|request| request.check().ok()).is_none() { return } - if focus_in(c, container as u32) { - let _ = c.set_input_focus(InputFocus::PARENT, w, x11rb::CURRENT_TIME); - } - let _ = c.ungrab_server(); - let _ = c.flush(); + with_server_grab(c, || { + if focus_in(c, container as u32) { + let _ = c.set_input_focus(InputFocus::PARENT, w, x11rb::CURRENT_TIME); + } + }); } /// The redirect, at most REDIRECTS_PER within REDIRECT_SPAN: a window manager that puts the focus back on the top-level /// each time it moves (none seen; the review's guard) gets the proxy a few times, then the top-level is left focused for REDIRECT_REST, @@ -871,11 +879,9 @@ mod imp { if let Some(g) = conn() { redirect_focus(g.as_ref().unwrap(), None); } return; } - // the keyboard Backplane's again with the focus left on a top-level itself (a FocusIn seen while KiCad still had the keys): its proxy + // A pane can release the keyboard with focus already on the top-level. if kicad || !was { return } - let Some(g) = conn() else { return }; let c = g.as_ref().unwrap(); - let Some(f) = c.get_input_focus().ok().and_then(|r| r.reply().ok()).map(|r| r.focus) else { return }; - if let Some(p) = proxies().lock().unwrap().get(&f).copied().filter(|_| pane_on_screen(f)) { let _ = c.set_input_focus(InputFocus::PARENT, p, x11rb::CURRENT_TIME); let _ = c.flush(); } + if let Some(g) = conn() { redirect_focus(g.as_ref().unwrap(), None); } } /// Windows only (the F3 input shield): Linux has its button grab (grab_click). pub fn shield(_container: u64, _on: bool) {} From d66f0f02e3e4f68518b0576bab620f8b255ba4f2 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 02:09:27 -0500 Subject: [PATCH 6/7] Keep composer focus when KiCad dialog tracking clears on X11 --- native/gpui/src/viewers/kicad_pane.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/native/gpui/src/viewers/kicad_pane.rs b/native/gpui/src/viewers/kicad_pane.rs index a7c9bdb772..e18f2319d9 100644 --- a/native/gpui/src/viewers/kicad_pane.rs +++ b/native/gpui/src/viewers/kicad_pane.rs @@ -1671,10 +1671,14 @@ impl KicadPane { // a KiCad dialog closed with the keyboard in it: to the dialog still open under it (a dialog of a dialog closed: back to its parent), // else to the editor's frame if std::mem::replace(&mut self.was_dialog, in_dialog) && !has { - // (never when the person went to Backplane itself: the focus is then in our window, outside KiCad's container) - let to_dialog = if nc::has_focus(self.toplevel) { None } else { nc::open_dialogs(self.info["pid"].as_u64().unwrap_or(0) as u32).last().copied() }; + let backplane_focused = nc::has_focus(self.toplevel); + let to_dialog = if backplane_focused { None } else { nc::open_dialogs(self.info["pid"].as_u64().unwrap_or(0) as u32).last().copied() }; if let Some(d) = to_dialog { nc::activate(d); self.was_dialog = true; has = true; } - else if let Some(w) = editor_focus_target(self.in_page, self.want()) { nc::focus(w); has = true; } + // On X11 the user may have clicked the composer while KiCad owned focus + // outside its container. That transition also clears in_dialog. + else if !cfg!(target_os = "linux") || !backplane_focused { + if let Some(w) = editor_focus_target(self.in_page, self.want()) { nc::focus(w); has = true; } + } } // KiCad took the keyboard on a click (`_BACKPLANE_FOCUS`) and a window manager that focuses on click (i3) gave it straight back to // Backplane's window: the click was KiCad's, so is the keyboard (once, within moments of it) From 2ecd44bf8962ddd89ad834854c8f7b332365cea1 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sat, 21 Nov 2026 02:26:56 -0500 Subject: [PATCH 7/7] Mark X focus watcher diagnostics as log strings --- native/gpui/src/viewers/native_child.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/native/gpui/src/viewers/native_child.rs b/native/gpui/src/viewers/native_child.rs index 24c8338379..6b4bfa6359 100644 --- a/native/gpui/src/viewers/native_child.rs +++ b/native/gpui/src/viewers/native_child.rs @@ -308,7 +308,7 @@ mod imp { fn watch_focus(top: u32) { let Some(watcher) = WATCHER.get_or_init(|| match FocusWatcher::start() { Ok(watcher) => Some(watcher), - Err(error) => { watcher_error("failed to start", error); None } + Err(error) => { watcher_error("failed to start", error); None } // i18n-ok: structured diagnostic log }) else { return }; let result = watcher.connection.change_window_attributes(top, &ChangeWindowAttributesAux::new().event_mask(EventMask::FOCUS_CHANGE)); @@ -316,7 +316,7 @@ mod imp { Ok(request) => request.check().err().map(|e| e.to_string()), Err(error) => Some(error.to_string()), }; - if let Some(error) = error { watcher_error("could not subscribe", error); } + if let Some(error) = error { watcher_error("could not subscribe", error); } // i18n-ok: structured diagnostic log // The checked request can queue events in x11rb while draining the socket. let _ = watcher.wake.send(&[0]); }