Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

winkey: notice a dropped hook from ordinary keystrokes, not only a held key (925) Windows removes a low-level hook without a word when its callback is too slow. The heartbeat noticed this only from a key held across two beats (about half a second), so several quick taps of the Windows key fell through to Windows' own Start before the hook was reinstalled. A second, minimal hook - the canary - now counts the events it is called for. Windows calls every low-level hook for every keyboard event (newest first), so keys the canary heard while the layer's own hook was called for none of them mean the hook is out of the chain: two beats of ordinary keystrokes restore it, no held key needed. The canary callback is one atomic increment; it reads, keeps and swallows nothing. Co-authored-by: openhands <[email protected]>

Dylan-ISE80d9bc921d17
diff --git a/crates/rf-app/src/shell/keylayer.rs b/crates/rf-app/src/shell/keylayer.rs
index 4c906be9..b80eb753 100644
--- a/crates/rf-app/src/shell/keylayer.rs
+++ b/crates/rf-app/src/shell/keylayer.rs
@@ -526,6 +526,7 @@ mod tests {
// (explicit names: `super::*` would bring in the toolkit's own `test` attribute, which replaces the standard one)
use super::{Actions, Settings, combos_wanted, handle, is_windows_start, log_only_from, ready_line, wanted};
use rf_win::switcher::chord::{Effect, Scope};
+ use rf_win::winkey::fakes::FakeCanary;
use rf_win::winkey::{Deliver, KeyService, Posted, Shared};
use std::sync::Arc;
use std::time::Duration;
@@ -729,7 +730,7 @@ mod tests {
let clock = Arc::new(Clock::manual());
clock.set(50);
let mask = Arc::new(FakeMask::default());
- let mut svc = KeyService::new(FakeFeed::default(), mask.clone(), Box::new(SharedProbe(Arc::new(FakeProbe::default()))), deliver, clock, false);
+ let mut svc = KeyService::new(FakeFeed::default(), mask.clone(), Box::new(SharedProbe(Arc::new(FakeProbe::default()))), Box::new(FakeCanary::default()), deliver, clock, false);
svc.set_wanted(false, true).unwrap();
let shared = svc.shared().unwrap();
let f = svc.feed_mut();
@@ -760,7 +761,7 @@ mod tests {
let deliver: Deliver = Arc::new(move |p| g.lock().push(p));
let clock = Arc::new(Clock::manual());
clock.set(50);
- let mut svc = KeyService::new(FakeFeed::default(), Arc::new(FakeMask::default()), Box::new(SharedProbe(Arc::new(FakeProbe::default()))), deliver, clock, false);
+ let mut svc = KeyService::new(FakeFeed::default(), Arc::new(FakeMask::default()), Box::new(SharedProbe(Arc::new(FakeProbe::default()))), Box::new(FakeCanary::default()), deliver, clock, false);
svc.set_wanted(true, true).unwrap();
let shared = svc.shared().unwrap();
svc.feed_mut().push_raw(VK_LMENU, 0x38, LLKHF_ALTDOWN, true);
diff --git a/crates/rf-win/src/switcher/hook.rs b/crates/rf-win/src/switcher/hook.rs
index 317124ea..1fb879d5 100644
--- a/crates/rf-win/src/switcher/hook.rs
+++ b/crates/rf-win/src/switcher/hook.rs
@@ -24,6 +24,10 @@
//! processed is not known (UNV); the host's first live test settles it. Nothing here sends a key.
//! * the thread, and with it the hook, is stopped by posting `WM_QUIT`, and a hook that was removed by Windows is noticed by a
//! heartbeat (an event the hook itself generates) and installed again: that part belongs to the host, not here.
+//!
+//! BESIDE IT, [`CanaryHook`] (issue 925): a second, minimal low-level hook whose callback only counts the events it is called for
+//! (one atomic increment, nothing read, nothing kept) so the heartbeat can notice a dropped own hook from ordinary keystrokes
+//! instead of a key held across two beats. See its own documentation below.
use std::sync::Arc;
@@ -376,6 +380,149 @@ impl Drop for LowLevelHook {
}
}
+// ---------------------------------------------------------------- the canary (the second hook, started only by `rf_win::winkey`)
+
+/// The canary: a second, minimal `WH_KEYBOARD_LL` hook that only COUNTS the events it is called for and passes every one of them on.
+/// Windows hands every keyboard event to every installed low-level hook, the most recently installed first, so while the canary is up
+/// it is called before this product's own hook for every event, whatever another hook does with it afterwards. The heartbeat of
+/// [`crate::winkey::KeyService`] compares the two counts: keys that the canary heard and that the layer's own hook was not called for
+/// mean the own hook is no longer in the chain (Windows removes a low-level hook without a word when its callback is too slow) - found
+/// from a few ordinary keystrokes instead of a key held across two beats, so a quick tap of the Windows key does not fall through to
+/// Windows' own Start while the hook is being restored (issue 925). The callback is one atomic increment: it cannot be too slow, and
+/// a canary that Windows itself removed only means this fourth check goes quiet, never that a key is touched.
+pub struct CanaryHook {
+ thread: Option<std::thread::JoinHandle<()>>,
+ thread_id: u32,
+ events: Arc<std::sync::atomic::AtomicU64>,
+}
+
+thread_local! {
+ /// The counter of the canary thread (the hook callback runs on it). Set before the hook is installed.
+ static CANARY_EVENTS: std::cell::RefCell<Option<Arc<std::sync::atomic::AtomicU64>>> = const { std::cell::RefCell::new(None) };
+}
+
+unsafe extern "system" fn canary_proc(code: i32, wp: windows::Win32::Foundation::WPARAM, lp: windows::Win32::Foundation::LPARAM) -> windows::Win32::Foundation::LRESULT {
+ use windows::Win32::UI::WindowsAndMessaging::CallNextHookEx;
+ if code >= 0 {
+ CANARY_EVENTS.with(|e| {
+ if let Some(e) = e.borrow().as_ref() {
+ e.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ }
+ });
+ }
+ unsafe { CallNextHookEx(None, code, wp, lp) }
+}
+
+impl CanaryHook {
+ pub fn new() -> CanaryHook {
+ CanaryHook { thread: None, thread_id: 0, events: Arc::new(std::sync::atomic::AtomicU64::new(0)) }
+ }
+}
+
+impl Default for CanaryHook {
+ fn default() -> Self {
+ CanaryHook::new()
+ }
+}
+
+impl CanaryHook {
+ /// Starts the canary thread and installs its hook. Safe to call while it is already running.
+ pub fn start(&mut self) -> anyhow::Result<()> {
+ use windows::Win32::UI::WindowsAndMessaging::{DispatchMessageW, GetMessageW, MSG, PM_NOREMOVE, PeekMessageW, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx, WH_KEYBOARD_LL};
+ if self.thread.is_some() {
+ return Ok(());
+ }
+ let (tx, rx) = std::sync::mpsc::channel::<anyhow::Result<u32>>();
+ let handshake = Arc::new(Handshake::default());
+ let for_thread = handshake.clone();
+ let events = self.events.clone();
+ let thread = std::thread::Builder::new().name("rf-keys-canary".into()).spawn(move || {
+ CANARY_EVENTS.with(|c| *c.borrow_mut() = Some(events));
+ let hook = unsafe { SetWindowsHookExW(WH_KEYBOARD_LL, Some(canary_proc), None, 0) };
+ let hook = match hook {
+ Ok(h) => h,
+ Err(e) => {
+ let _ = tx.send(Err(e.into()));
+ return;
+ }
+ };
+ // the thread's queue exists before the id is handed out: a WM_QUIT posted at once is not lost
+ let mut probe = MSG::default();
+ unsafe {
+ let _ = PeekMessageW(&mut probe, None, 0, 0, PM_NOREMOVE);
+ }
+ let id = unsafe { windows::Win32::System::Threading::GetCurrentThreadId() };
+ let _ = tx.send(Ok(id));
+ if !for_thread.publish(id) {
+ // the starter gave up waiting and returned an error: nobody will stop this thread, so it removes its own hook
+ unsafe {
+ let _ = UnhookWindowsHookEx(hook);
+ }
+ CANARY_EVENTS.with(|c| *c.borrow_mut() = None);
+ return;
+ }
+ let mut msg = MSG::default();
+ while unsafe { GetMessageW(&mut msg, None, 0, 0) }.0 > 0 {
+ unsafe {
+ let _ = TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+ }
+ unsafe {
+ let _ = UnhookWindowsHookEx(hook);
+ }
+ CANARY_EVENTS.with(|c| *c.borrow_mut() = None);
+ })?;
+ match rx.recv_timeout(std::time::Duration::from_secs(5)) {
+ Ok(Ok(id)) => {
+ self.thread_id = id;
+ self.thread = Some(thread);
+ Ok(())
+ }
+ Ok(Err(e)) => Err(e),
+ Err(e) => {
+ // (a thread that comes up later ends itself; one that is already up is told to quit here)
+ if let Some(id) = handshake.abandon() {
+ post_quit(id);
+ }
+ Err(e.into())
+ }
+ }
+ }
+
+ /// Removes the canary hook and ends its thread. Safe to call twice.
+ pub fn stop(&mut self) {
+ if let Some(t) = self.thread.take() {
+ post_quit(self.thread_id);
+ let _ = t.join();
+ self.thread_id = 0;
+ }
+ }
+
+ /// How many keyboard events the canary has been called for, across its lifetime. The events are not read, decoded or kept.
+ pub fn events(&self) -> u64 {
+ self.events.load(std::sync::atomic::Ordering::Relaxed)
+ }
+}
+
+impl crate::winkey::service::Canary for CanaryHook {
+ fn start(&mut self) -> anyhow::Result<()> {
+ CanaryHook::start(self)
+ }
+ fn stop(&mut self) {
+ CanaryHook::stop(self)
+ }
+ fn events(&self) -> u64 {
+ CanaryHook::events(self)
+ }
+}
+
+impl Drop for CanaryHook {
+ fn drop(&mut self) {
+ self.stop();
+ }
+}
+
// ---------------------------------------------------------------- a feed for tests
/// A feed that delivers what the test pushes, on the calling thread.
diff --git a/crates/rf-win/src/winkey/fakes.rs b/crates/rf-win/src/winkey/fakes.rs
index 0352fe1d..92ebb9a5 100644
--- a/crates/rf-win/src/winkey/fakes.rs
+++ b/crates/rf-win/src/winkey/fakes.rs
@@ -2,12 +2,12 @@
//! keyboard probe whose keys the test presses, and a feed that cannot be installed. They send nothing and read nothing.
use std::collections::HashSet;
-use std::sync::atomic::{AtomicU32, Ordering};
+use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use parking_lot::Mutex;
use super::mask::MaskSender;
-use super::service::KeyProbe;
+use super::service::{Canary, KeyProbe};
use crate::switcher::hook::{KeyFeed, OnRaw};
/// Counts the masks it was asked to send.
@@ -70,3 +70,39 @@ impl KeyFeed for RefusingFeed {
false
}
}
+
+/// A canary hook whose events the test strikes, and which counts its own starts and stops.
+#[derive(Default)]
+pub struct FakeCanary {
+ events: AtomicU64,
+ starts: AtomicU32,
+ stops: AtomicU32,
+}
+
+impl FakeCanary {
+ /// Keys were struck that the test wants the canary to have heard.
+ pub fn advance(&self) {
+ self.events.fetch_add(1, Ordering::Relaxed);
+ }
+
+ pub fn started(&self) -> u32 {
+ self.starts.load(Ordering::Relaxed)
+ }
+
+ pub fn stopped(&self) -> u32 {
+ self.stops.load(Ordering::Relaxed)
+ }
+}
+
+impl Canary for FakeCanary {
+ fn start(&mut self) -> anyhow::Result<()> {
+ self.starts.fetch_add(1, Ordering::Relaxed);
+ Ok(())
+ }
+ fn stop(&mut self) {
+ self.stops.fetch_add(1, Ordering::Relaxed);
+ }
+ fn events(&self) -> u64 {
+ self.events.load(Ordering::Relaxed)
+ }
+}
diff --git a/crates/rf-win/src/winkey/mod.rs b/crates/rf-win/src/winkey/mod.rs
index 573bb7bf..b1ec967c 100644
--- a/crates/rf-win/src/winkey/mod.rs
+++ b/crates/rf-win/src/winkey/mod.rs
@@ -1,8 +1,11 @@
//! The shell host's opt-in keyboard layer (shell plan increment B7; design in `docs/design/shell-keys.md`).
//!
//! Two settings, both OFF by default: `shell_win_key` (a tap of the Windows key alone opens OUR Start panel instead of Windows')
-//! and `shell_own_switcher` (Alt+Tab opens OUR switcher). Beside Explorer both need a low-level keyboard hook, and there is ONE:
-//! `switcher::hook::LowLevelHook`, started by [`KeyService`] only inside the shell host and only while at least one setting is on.
+//! and `shell_own_switcher` (Alt+Tab opens OUR switcher). Beside Explorer both need a low-level keyboard hook, and there is ONE that
+//! answers for them: `switcher::hook::LowLevelHook`, started by [`KeyService`] only inside the shell host and only while at least one
+//! setting is on. Beside it a second, MINIMAL hook of the same kind - the canary, `switcher::hook::CanaryHook` - counts the events it
+//! is called for and touches nothing, so a dropped hook is found from ordinary keystrokes instead of a held one (issue 925, see
+//! `service.rs`).
//!
//! | file | what | rules it obeys |
//! |---|---|---|
diff --git a/crates/rf-win/src/winkey/service.rs b/crates/rf-win/src/winkey/service.rs
index bdb26ddb..22f5ae82 100644
--- a/crates/rf-win/src/winkey/service.rs
+++ b/crates/rf-win/src/winkey/service.rs
@@ -7,7 +7,7 @@
//! (called at quit) and `Drop` remove it too. A process that is killed loses its hooks with it: Windows' own behaviour is back at once.
//!
//! HOW A DROPPED HOOK IS NOTICED. Windows removes a low-level hook without a word when its callback is too slow; ours never waits, so
-//! the usual causes are a stall of the whole process (it was suspended, the machine slept, the process was starved) - or a bug. Three
+//! the usual causes are a stall of the whole process (it was suspended, the machine slept, the process was starved) - or a bug. Four
//! checks, all made by [`KeyService::heartbeat`] on the interface thread, none of which sends a key:
//! 1. THE THREAD ENDED: the feed says it is not running (the hook thread died, or the hook could not be installed in the first place).
//! 2. A STALL: the heartbeat itself came more than [`STALL_MS`] after the previous one, so the process was away for a long moment and
@@ -19,6 +19,12 @@
//! (whether the keyboard's state shows a key the hook swallowed is not known). A release the hook cannot see (Win+L: the key comes
//! up on the secure desktop) also looks like a disagreement and installs the hook again; that is wanted, a fresh layer starts from
//! the keyboard's state and forgets a Windows key it believes is still down.
+//! 4. KEYS THAT WENT UNANSWERED (issue 925): a second, minimal hook - the canary - counts the events it is called for, and the layer's
+//! own hook counts them in the shared state. Windows calls every low-level hook for every keyboard event, so keys that the canary
+//! heard while the own hook was called for none of them mean the hook is out of the chain, held keys or not: two beats of ordinary
+//! keystrokes are enough. (The check is quiet while no keys are struck, and when the system refused the canary hook; a canary that
+//! Windows itself removed only silences the check, it never touches a key.) A quick tap of the Windows key no longer falls through
+//! to Windows' own Start while the hook is being restored: at most the very keystrokes between the drop and the recovery can.
//!
//! A SECOND, SEPARATE CHECK at the same beats: a chord that is open as a HELD one (the layer thinks Alt is down) while the keyboard
//! says Alt is up for two beats in a row. This happens when Alt came up where the hook cannot see (a window of a higher integrity level
@@ -40,7 +46,7 @@ use super::machine::{VK_LWIN, VK_RWIN};
use super::mask::{MaskSender, SendInputMask};
use super::queue::Posted;
use super::shared::{Clock, Shared, Tracked};
-use crate::switcher::hook::{KeyFeed, LowLevelHook, VK_LMENU, VK_RMENU};
+use crate::switcher::hook::{CanaryHook, KeyFeed, LowLevelHook, VK_LMENU, VK_RMENU};
/// The heartbeat is considered late, and the process to have been away, after this long since the previous one.
pub const STALL_MS: u64 = 3_000;
@@ -104,10 +110,26 @@ pub enum Why {
ThreadEnded,
Stall,
Disagreement,
+ /// The canary heard keys that the layer's own hook was not called for: it is no longer in the chain (issue 925).
+ Unanswered,
/// The pause after giving up is over.
Pause,
}
+/// The canary: a second, minimal low-level keyboard hook that only counts the events it is called for (see
+/// [`crate::switcher::hook::CanaryHook`]). Windows calls every installed low-level hook for every keyboard event, so keys that the
+/// canary heard while the layer's own hook was not called for any of them mean the hook is no longer in the chain: found from a few
+/// ordinary keystrokes, without waiting for one to be held across two beats (issue 925).
+pub trait Canary: Send {
+ /// Starts the canary hook (after the layer's own hook, so that the canary is called for every event first). Safe to call while
+ /// it is already running. An error means the system refused the second hook: the fourth check simply stays quiet.
+ fn start(&mut self) -> anyhow::Result<()>;
+ /// Removes the canary hook. Safe to call twice, and while it was never started.
+ fn stop(&mut self);
+ /// How many events the canary has been called for, across its lifetime (a count that only grows).
+ fn events(&self) -> u64;
+}
+
/// What a heartbeat found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Beat {
@@ -132,6 +154,7 @@ pub struct KeyService<F: KeyFeed> {
feed: F,
mask: Arc<dyn MaskSender>,
probe: Arc<dyn KeyProbe>,
+ canary: Box<dyn Canary>,
deliver: Deliver,
clock: Arc<Clock>,
log_only: bool,
@@ -151,22 +174,29 @@ pub struct KeyService<F: KeyFeed> {
mask_failures_logged: u32,
/// Consecutive beats at which the chord was held and the keyboard said Alt was up.
chord_strikes: u8,
+ /// Consecutive beats at which the canary heard keys and the layer's own hook was not called for any of them.
+ unanswered_strikes: u8,
+ /// The canary's count at the last beat.
+ last_canary_events: u64,
+ /// The hook's own count (in the shared state) at the last beat.
+ last_hook_events: u64,
}
impl KeyService<LowLevelHook> {
/// The real service: the system's hook, the system's `SendInput`, the keyboard's own state. Nothing is installed until
/// [`KeyService::set_wanted`] asks for it.
pub fn system(deliver: Deliver, log_only: bool) -> KeyService<LowLevelHook> {
- KeyService::new(LowLevelHook::new(), Arc::new(SendInputMask), Box::new(SystemProbe), deliver, Arc::new(Clock::real()), log_only)
+ KeyService::new(LowLevelHook::new(), Arc::new(SendInputMask), Box::new(SystemProbe), Box::new(CanaryHook::new()), deliver, Arc::new(Clock::real()), log_only)
}
}
impl<F: KeyFeed> KeyService<F> {
- pub fn new(feed: F, mask: Arc<dyn MaskSender>, probe: Box<dyn KeyProbe>, deliver: Deliver, clock: Arc<Clock>, log_only: bool) -> KeyService<F> {
+ pub fn new(feed: F, mask: Arc<dyn MaskSender>, probe: Box<dyn KeyProbe>, canary: Box<dyn Canary>, deliver: Deliver, clock: Arc<Clock>, log_only: bool) -> KeyService<F> {
KeyService {
feed,
mask,
probe: probe.into(),
+ canary,
deliver,
clock,
log_only,
@@ -181,6 +211,9 @@ impl<F: KeyFeed> KeyService<F> {
digits: false,
mask_failures_logged: 0,
chord_strikes: 0,
+ unanswered_strikes: 0,
+ last_canary_events: 0,
+ last_hook_events: 0,
}
}
@@ -221,6 +254,9 @@ impl<F: KeyFeed> KeyService<F> {
self.installs.clear();
self.watchdog.clear();
self.chord_strikes = 0;
+ self.unanswered_strikes = 0;
+ self.last_canary_events = 0;
+ self.last_hook_events = 0;
self.last_beat = None;
let shared = Arc::new(Shared::new(self.clock.clone(), self.log_only));
shared.set_wanted(win_key, own_switcher);
@@ -292,6 +328,7 @@ impl<F: KeyFeed> KeyService<F> {
self.installs.clear();
self.watchdog.clear();
self.chord_strikes = 0;
+ self.unanswered_strikes = 0;
if let Err(e) = self.install() {
log::error!("keys: the hook could not be installed after the pause: {e:#}");
}
@@ -299,12 +336,25 @@ impl<F: KeyFeed> KeyService<F> {
}
let actual = read_tracked(self.probe.as_ref());
self.watch_chord(&shared, actual);
+ // the fourth check: keys the canary heard that the layer's own hook was not called for (read the canary first: an event
+ // landing between the two reads then counts for the hook but not for the canary, which is the direction that cannot lie)
+ let canary_events = self.canary.events();
+ let hook_events = shared.hook_events();
+ if canary_events > self.last_canary_events && hook_events <= self.last_hook_events {
+ self.unanswered_strikes = self.unanswered_strikes.saturating_add(1);
+ } else {
+ self.unanswered_strikes = 0;
+ }
+ self.last_canary_events = canary_events;
+ self.last_hook_events = hook_events;
let why = if !self.feed.running() {
Some(Why::ThreadEnded)
} else if stalled {
Some(Why::Stall)
} else if self.watchdog.step(shared.believed(), actual) {
Some(Why::Disagreement)
+ } else if self.unanswered_strikes >= 2 {
+ Some(Why::Unanswered)
} else {
None
};
@@ -332,7 +382,9 @@ impl<F: KeyFeed> KeyService<F> {
if self.installs.len() >= MAX_REINSTALLS {
self.gave_up = true;
self.gave_up_at = Some(now);
+ self.canary.stop();
self.feed.stop();
+ self.unanswered_strikes = 0;
log::error!("keys: the hook keeps getting lost; the keyboard layer is off for {} minutes (or until the settings are switched off and on again)", GIVE_UP_COOLDOWN_MS / 60_000);
return Beat::GaveUp;
}
@@ -343,11 +395,13 @@ impl<F: KeyFeed> KeyService<F> {
Why::ThreadEnded => "the hook's thread had ended",
Why::Stall => "the process was away for a long moment",
Why::Disagreement => "the hook stopped seeing the keys",
+ Why::Unanswered => "keys were struck that the hook was not called for",
Why::Pause => "the pause after giving up is over",
});
self.feed.stop();
self.watchdog.clear();
self.chord_strikes = 0;
+ self.unanswered_strikes = 0;
// whatever chord was open is over; the interface closes a switcher that is still up
shared.post(Posted::Lost);
if let Err(e) = self.install() {
@@ -356,16 +410,30 @@ impl<F: KeyFeed> KeyService<F> {
Beat::Reinstalled(why)
}
- /// Installs the hook with a fresh layer, seeded from the keyboard's state.
+ /// Installs the hook with a fresh layer, seeded from the keyboard's state. The canary goes in after the hook, so that Windows
+ /// calls it for every event first.
fn install(&mut self) -> anyhow::Result<()> {
let Some(shared) = self.running.as_ref().map(|r| r.shared.clone()) else { return Ok(()) };
let now = self.clock.now_ms();
self.installs.push(now);
+ self.canary.stop();
let (l, r) = (self.probe.down(VK_LWIN), self.probe.down(VK_RWIN));
let mut layer = KeyLayer::new(shared.clone(), self.mask.clone(), l, r).with_probe(self.probe.clone());
shared.set_believed(read_tracked(self.probe.as_ref()));
- match self.feed.start_raw(Box::new(move |k| layer.on_event(k))) {
+ // every event the hook is called for is counted in the shared state, against the canary's count at the beats
+ let counted = shared.clone();
+ let started = self.feed.start_raw(Box::new(move |k| {
+ counted.note_hook_called();
+ layer.on_event(k)
+ }));
+ match started {
Ok(()) => {
+ if let Err(e) = self.canary.start() {
+ // (without the canary only the fourth check is missing: the hook itself is in place)
+ log::warn!("keys: the canary hook could not be installed: {e:#}");
+ }
+ self.last_canary_events = self.canary.events();
+ self.last_hook_events = shared.hook_events();
log::info!("keys: hook installed");
Ok(())
}
@@ -385,6 +453,7 @@ impl<F: KeyFeed> KeyService<F> {
/// phrase of the host's, never a key.
pub fn stop_because(&mut self, why: &str) {
let Some(mut r) = self.running.take() else { return };
+ self.canary.stop();
self.feed.stop();
r.stop.store(true, std::sync::atomic::Ordering::Release);
if let Some(d) = r.dispatcher.take() {
@@ -437,7 +506,7 @@ fn spawn_dispatcher(shared: Arc<Shared>, stop: Arc<std::sync::atomic::AtomicBool
mod tests {
use super::*;
use crate::switcher::hook::{FakeFeed, LLKHF_ALTDOWN, VK_TAB};
- use crate::winkey::fakes::{FakeMask, FakeProbe, RefusingFeed};
+ use crate::winkey::fakes::{FakeCanary, FakeMask, FakeProbe, RefusingFeed};
use crate::winkey::shared::STALE_AFTER_MS;
use parking_lot::Mutex;
@@ -446,6 +515,7 @@ mod tests {
clock: Arc<Clock>,
mask: Arc<FakeMask>,
probe: Arc<FakeProbe>,
+ canary: Arc<Mutex<FakeCanary>>,
got: Arc<Mutex<Vec<Posted>>>,
}
@@ -456,16 +526,30 @@ mod tests {
}
}
+ struct SharedCanary(Arc<Mutex<FakeCanary>>);
+ impl Canary for SharedCanary {
+ fn start(&mut self) -> anyhow::Result<()> {
+ self.0.lock().start()
+ }
+ fn stop(&mut self) {
+ self.0.lock().stop()
+ }
+ fn events(&self) -> u64 {
+ self.0.lock().events()
+ }
+ }
+
fn rig_with(log_only: bool) -> Rig {
let clock = Arc::new(Clock::manual());
clock.set(1_000);
let mask = Arc::new(FakeMask::default());
let probe = Arc::new(FakeProbe::default());
+ let canary = Arc::new(Mutex::new(FakeCanary::default()));
let got: Arc<Mutex<Vec<Posted>>> = Default::default();
let g = got.clone();
let deliver: Deliver = Arc::new(move |p| g.lock().push(p));
- let svc = KeyService::new(FakeFeed::default(), mask.clone(), Box::new(SharedProbe(probe.clone())), deliver, clock.clone(), log_only);
- Rig { svc, clock, mask, probe, got }
+ let svc = KeyService::new(FakeFeed::default(), mask.clone(), Box::new(SharedProbe(probe.clone())), Box::new(SharedCanary(canary.clone())), deliver, clock.clone(), log_only);
+ Rig { svc, clock, mask, probe, canary, got }
}
fn rig() -> Rig {
@@ -747,7 +831,7 @@ mod tests {
let got: Arc<Mutex<Vec<Posted>>> = Default::default();
let g = got.clone();
let deliver: Deliver = Arc::new(move |p| g.lock().push(p));
- let mut svc = KeyService::new(RefusingFeed::default(), Arc::new(FakeMask::default()), Box::new(SharedProbe(Arc::new(FakeProbe::default()))), deliver, clock.clone(), false);
+ let mut svc = KeyService::new(RefusingFeed::default(), Arc::new(FakeMask::default()), Box::new(SharedProbe(Arc::new(FakeProbe::default()))), Box::new(FakeCanary::default()), deliver, clock.clone(), false);
assert!(svc.set_wanted(true, true).is_err());
assert!(svc.wanted() && !svc.installed());
clock.set(500 + MIN_GAP_MS + 1);
@@ -821,6 +905,52 @@ mod tests {
assert!(r.svc.shared().unwrap().combos_on());
}
+ #[test]
+ fn keys_the_hook_was_not_called_for_install_the_hook_again_without_a_held_key() {
+ // The hook is dropped; ordinary keys are struck afterwards (issue 925). The canary hears them, the layer's own hook is not
+ // called for any of them, and two beats of that are enough - no key has to be held across both.
+ let mut r = rig();
+ r.svc.set_wanted(true, true).unwrap();
+ assert!(r.svc.installed());
+ assert_eq!(r.canary.lock().started(), 1, "the canary went in with the hook");
+ r.svc.heartbeat(false);
+ r.canary.lock().advance();
+ r.clock.set(3_500);
+ assert_eq!(r.svc.heartbeat(false), Beat::Fine, "one beat of unanswered keys is not yet a verdict");
+ r.canary.lock().advance();
+ r.clock.set(3_750);
+ assert_eq!(r.svc.heartbeat(false), Beat::Reinstalled(Why::Unanswered));
+ assert!(r.svc.installed());
+ // a fresh canary went in with the fresh hook, and the old one came out: every start has its stop, none is left behind
+ assert_eq!(r.canary.lock().started(), 2);
+ assert_eq!(r.canary.lock().stopped(), 2);
+ }
+
+ #[test]
+ fn keys_the_hook_was_also_called_for_are_no_signal() {
+ // The hook is alive and sees the same keystrokes the canary does.
+ let mut r = rig();
+ r.svc.set_wanted(true, true).unwrap();
+ r.svc.heartbeat(false);
+ for t in [3_500u64, 3_750] {
+ r.canary.lock().advance();
+ r.svc.shared().unwrap().note_hook_called();
+ r.clock.set(t);
+ assert_eq!(r.svc.heartbeat(false), Beat::Fine, "at {t}");
+ }
+ }
+
+ #[test]
+ fn beats_without_keystrokes_install_nothing() {
+ let mut r = rig();
+ r.svc.set_wanted(true, true).unwrap();
+ for t in [3_500u64, 3_750, 4_000, 4_250] {
+ r.clock.set(t);
+ assert_eq!(r.svc.heartbeat(false), Beat::Fine, "at {t}");
+ }
+ assert_eq!(r.canary.lock().started(), 1, "the canary was not churned while the keyboard was quiet");
+ }
+
#[test]
fn the_service_never_asks_for_the_real_hook_in_tests() {
// The real service is constructed (nothing is installed by that) and dropped without a setting having been on.
diff --git a/crates/rf-win/src/winkey/shared.rs b/crates/rf-win/src/winkey/shared.rs
index 91c93ecb..2216c9e6 100644
--- a/crates/rf-win/src/winkey/shared.rs
+++ b/crates/rf-win/src/winkey/shared.rs
@@ -108,6 +108,9 @@ pub struct Shared {
chord_held: AtomicBool,
/// Masks the system refused (the key could not be sent).
mask_failed: AtomicU32,
+ /// How many events the layer's own hook has been called for, across the layer's lifetime: counted by the callback, read against
+ /// the canary's count at the beats (a count that only grows; see `service.rs`'s fourth check).
+ hook_events: AtomicU64,
queue: Queue,
/// The thread that reads the queue; woken by every post.
waker: OnceLock<Thread>,
@@ -130,6 +133,7 @@ impl Shared {
believed: AtomicU8::new(0),
chord_held: AtomicBool::new(false),
mask_failed: AtomicU32::new(0),
+ hook_events: AtomicU64::new(0),
queue: Queue::new(),
waker: OnceLock::new(),
}
@@ -285,6 +289,16 @@ impl Shared {
pub fn note_mask_failed(&self) {
self.mask_failed.fetch_add(1, Ordering::Relaxed);
}
+
+ /// The hook callback was called: one more event it saw. Called on the hook thread, once per event.
+ pub fn note_hook_called(&self) {
+ self.hook_events.fetch_add(1, Ordering::Relaxed);
+ }
+
+ /// How many events the layer's own hook has been called for, across the layer's lifetime.
+ pub fn hook_events(&self) -> u64 {
+ self.hook_events.load(Ordering::Relaxed)
+ }
}
#[cfg(test)]