Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions native/gpui/src/viewers/cef.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,21 @@ wrap_focus_handler! {
struct FocusH { tab: Arc<Tab> }
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 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(()); }
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(()); } }
Expand Down Expand Up @@ -533,7 +542,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) {
Expand Down
126 changes: 111 additions & 15 deletions native/gpui/src/viewers/cef_native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,113 @@ 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(); drop(g);
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);
Some(Host::X11(id))
}
pub fn close(_w: u64) {}
/// 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 {
/// Every container of ours (a tab's `container`), until it is destroyed: what a recorded press is matched against.
/// (each with the client's top-level it is in)
fn containers() -> &'static Mutex<std::collections::HashMap<u32, u32>> { static C: OnceLock<Mutex<std::collections::HashMap<u32, u32>>> = OnceLock::new(); C.get_or_init(Default::default) }
fn top_of(frame: u64) -> Option<u64> { containers().lock().unwrap().get(&(frame as u32)).map(|t| *t as u64) }
use crate::viewers::native_child as nc;
/// 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<Option<(std::time::Instant, u32)>> = Mutex::new(None);
static PRESS_WINDOWS: std::sync::LazyLock<Mutex<std::collections::HashSet<u32>>> =
std::sync::LazyLock::new(Default::default);
const PRESS_SPAN: std::time::Duration = std::time::Duration::from_millis(400);

fn watch_presses(frame: u32) {
use std::sync::{Arc, Weak};
static WATCHER: OnceLock<Option<Weak<RustConnection>>> = OnceLock::new();
let watcher = WATCHER.get_or_init(|| {
let start = || -> Result<Weak<RustConnection>, Box<dyn std::error::Error>> {
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
}
}
});
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<u32> {
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 for the page that received it.
pub fn pressed_in(frame: u64) -> Option<bool> {
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);
}
PRESS_WINDOWS.lock().unwrap().contains(&(frame as u32)).then_some(false)
}

/// 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();
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) { 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<R>) {
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)); } }
Expand Down Expand Up @@ -98,10 +192,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, 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();
Expand Down Expand Up @@ -138,6 +230,8 @@ mod imp {
pub fn container(_h: Host) -> Option<Host> { None }
pub fn place_in(_frame: u64, _w: u64, _r: Option<R>) {}
pub fn destroy(_frame: u64) {}
/// X11 only (its press watcher): here on_set_focus asks `button_down`.
pub fn pressed_in(_frame: u64) -> Option<bool> { 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.
Expand All @@ -154,8 +248,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
}
Expand All @@ -167,7 +261,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::<windows_sys::Win32::Foundation::RECT>();
Expand Down Expand Up @@ -196,6 +290,8 @@ mod imp {
pub fn container(_h: Host) -> Option<Host> { None }
pub fn place_in(_frame: u64, _w: u64, _r: Option<R>) {}
pub fn destroy(_frame: u64) {}
/// X11 only (its press watcher): here on_set_focus asks `button_down`.
pub fn pressed_in(_frame: u64) -> Option<bool> { 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.
Expand All @@ -212,8 +308,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
}
Expand Down Expand Up @@ -242,7 +338,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 }
Expand Down
4 changes: 3 additions & 1 deletion native/gpui/src/viewers/cef_page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
10 changes: 7 additions & 3 deletions native/gpui/src/viewers/kicad_pane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading