refactor(input): register stop shortcuts as one required group
Reuse Win32 RegisterHotKey for the selected Ctrl+Alt function key and its Shift and Win combinations. A partial registration is unavailable and releases its registrations, leaving the previous binding intact. Remove the global keyboard hook and its mirrored activation state; keep the behavioral isolated-desktop check. Native integration and focused conflict checks passed; actual OS delivery of this replacement still requires the existing isolated Windows gate.
This commit is contained in:
1 parent
a2882f9604
commit
a80a7181a1
5 files changed
+45
-257
No files matched your search
@@ -132,4 +132,4 @@ vigem-rust = { version = "=0.2.0", default-features = false, features = ["x360"]
|
||||
wasapi = { version = "=0.27.0", optional = true }
|
||||
windows-capture = { version = "=2.0.1", optional = true }
|
||||
windows-core = "=0.62.2"
|
||||
windows = { version = "=0.62.2", features = ["Win32_Foundation", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_HiDpi", "Win32_Graphics_Gdi", "Win32_Graphics_Dwm", "Win32_Security"] }
|
||||
windows = { version = "=0.62.2", features = ["Win32_Foundation", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_HiDpi", "Win32_Graphics_Gdi", "Win32_Graphics_Dwm", "Win32_Security"] }
|
||||
@@ -142,8 +142,6 @@ impl Desktop {
|
||||
owner: None,
|
||||
releases: BTreeMap::new(),
|
||||
tick_wake: Arc::new(Notify::new()),
|
||||
#[cfg(target_os = "windows")]
|
||||
stop_pending: Default::default(),
|
||||
gamepad,
|
||||
}));
|
||||
Self(
|
||||
@@ -176,10 +174,7 @@ impl Desktop {
|
||||
return Ok(());
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
let next = {
|
||||
let e = self.0.lock().unwrap();
|
||||
windows::Shortcut::new(key, e.stop_pending.clone(), e.tick_wake.clone())?
|
||||
};
|
||||
let next = windows::Shortcut::new(key, Arc::downgrade(&self.0))?;
|
||||
#[cfg(target_os = "macos")]
|
||||
let next = macos::Shortcut::new(key)?;
|
||||
*current = Some(next);
|
||||
@@ -295,14 +290,6 @@ impl Desktop {
|
||||
let wake = self.0.lock().unwrap().tick_wake.clone();
|
||||
let period = Duration::from_millis(100);
|
||||
loop {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let mut e = self.0.lock().unwrap();
|
||||
if e.stop_pending.take() {
|
||||
e.revoke();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if self.needs_tick() {
|
||||
let tick = timer.get_or_insert_with(|| {
|
||||
tokio::time::interval_at(tokio::time::Instant::now() + period, period)
|
||||
@@ -837,8 +824,6 @@ struct Executor {
|
||||
/// Only failed releases survive their grant; never replay presses or motion.
|
||||
releases: BTreeMap<Held, Endpoint>,
|
||||
tick_wake: Arc<Notify>,
|
||||
#[cfg(target_os = "windows")]
|
||||
stop_pending: Arc<windows::StopPending>,
|
||||
gamepad: Option<gamepad::Backend>,
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -925,12 +910,6 @@ struct RemoteState {
|
||||
}
|
||||
|
||||
impl Executor {
|
||||
fn set_owner(&mut self, owner: Option<Uuid>) {
|
||||
self.owner = owner;
|
||||
#[cfg(target_os = "windows")]
|
||||
self.stop_pending.arm(owner.is_some());
|
||||
}
|
||||
|
||||
fn set_policy(
|
||||
&mut self,
|
||||
source: &mut SourceState,
|
||||
@@ -985,7 +964,7 @@ impl Executor {
|
||||
let result = action(self, &mut source);
|
||||
self.emit(&mut source, response);
|
||||
if self.owner == Some(video) && !source.controllers.values().any(|c| c.grant.is_some()) {
|
||||
self.set_owner(None);
|
||||
self.owner = None;
|
||||
}
|
||||
self.sources.insert(video, source);
|
||||
result
|
||||
@@ -1010,7 +989,7 @@ impl Executor {
|
||||
self.revoke_all(source);
|
||||
source.endpoint = Endpoint::default();
|
||||
if self.owner == Some(video) {
|
||||
self.set_owner(None);
|
||||
self.owner = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1112,7 +1091,7 @@ impl Executor {
|
||||
getrandom::fill(&mut token).map_err(|_| anyhow!("input_random_unavailable"))?;
|
||||
c.grant = Some(token.iter().map(|byte| format!("{byte:02x}")).collect());
|
||||
c.reason = None;
|
||||
self.set_owner(Some(video));
|
||||
self.owner = Some(video);
|
||||
match source.endpoint.observe(self.sink.as_mut(), &source.target) {
|
||||
TargetState::Ready(_) => c.suspended = false,
|
||||
TargetState::Suspended => c.suspended = true,
|
||||
|
||||
@@ -1272,61 +1272,6 @@ fn carrier_release_preserves_replay_counter_and_allows_fresh_consent() {
|
||||
assert_ne!(state["grant"], grant);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tokio::test]
|
||||
async fn windows_stop_pending_respects_consent_and_releases_held_input() {
|
||||
use crate::windows_hotkeys::Activation;
|
||||
let (d, recording) = desktop();
|
||||
let (s, mut replies, view) = source(&d);
|
||||
s.set_mode(Mode::Room).unwrap();
|
||||
let pending = d.0.lock().unwrap().stop_pending.clone();
|
||||
pending.signal(Activation::StopChord);
|
||||
assert!(!pending.take());
|
||||
let mut c = Client::new(&s);
|
||||
c.send(&s, json!({"type":"request","intent":Uuid::new_v4()}));
|
||||
let grant = c.state(&mut replies)["grant"].clone();
|
||||
c.send(&s, json!({"type":"key","grant":grant,"code":"ShiftLeft","down":true}));
|
||||
pending.signal(Activation::StopChord);
|
||||
d.tick_when_needed(&mut None).await;
|
||||
assert_eq!(view.borrow().mode, Mode::Ask);
|
||||
assert_eq!(recording.lock().unwrap().events.len(), 2);
|
||||
pending.signal(Activation::Registered(0));
|
||||
pending.signal(Activation::StopChord);
|
||||
assert!(pending.take());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tokio::test]
|
||||
async fn windows_stop_ordering_active_chord_survives_release() {
|
||||
use crate::windows_hotkeys::Activation;
|
||||
let (desktop, _) = desktop();
|
||||
let (source, mut replies, view) = source(&desktop);
|
||||
source.set_mode(Mode::Room).unwrap();
|
||||
let mut client = Client::new(&source);
|
||||
client.send(&source, json!({"type":"request","intent":Uuid::new_v4()}));
|
||||
assert_eq!(client.state(&mut replies)["state"], "active");
|
||||
desktop.0.lock().unwrap().stop_pending.signal(Activation::StopChord);
|
||||
source.release(client.id, client.flow).unwrap();
|
||||
desktop.tick_when_needed(&mut None).await;
|
||||
assert_eq!(view.borrow().mode, Mode::Ask);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tokio::test]
|
||||
async fn windows_stop_ordering_idle_chord_preserves_later_grant() {
|
||||
use crate::windows_hotkeys::Activation;
|
||||
let (desktop, _) = desktop();
|
||||
let (source, mut replies, view) = source(&desktop);
|
||||
source.set_mode(Mode::Room).unwrap();
|
||||
desktop.0.lock().unwrap().stop_pending.signal(Activation::StopChord);
|
||||
let mut client = Client::new(&source);
|
||||
client.send(&source, json!({"type":"request","intent":Uuid::new_v4()}));
|
||||
assert_eq!(client.state(&mut replies)["state"], "active");
|
||||
desktop.tick_when_needed(&mut None).await;
|
||||
assert_eq!(view.borrow().mode, Mode::Room);
|
||||
assert!(desktop.0.lock().unwrap().owner.is_some());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tokio::test]
|
||||
#[ignore = "scoped Windows hotkey registration; posts only to its own queue, never types desktop input"]
|
||||
@@ -1344,12 +1289,6 @@ async fn windows_hotkey_revokes_and_unregisters_on_process_close() {
|
||||
assert_eq!(view.borrow().stop_shortcut, Some(key));
|
||||
d.set_shortcut(key).unwrap();
|
||||
d.1.lock().unwrap().as_ref().unwrap().notify_test().unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
let mut timer = None;
|
||||
while d.0.lock().unwrap().owner.is_some() {
|
||||
d.tick_when_needed(&mut timer).await;
|
||||
}
|
||||
}).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
loop {
|
||||
if view.borrow().mode == Mode::Ask && view.borrow().requests.is_empty() {
|
||||
@@ -1414,7 +1353,7 @@ async fn windows_stop_shortcut_on_isolated_desktop() -> Result<()> {
|
||||
.ok_or_else(|| anyhow!("no available Windows fixture shortcut"))?,
|
||||
};
|
||||
selected = Some(key);
|
||||
let (source, mut replies, view) = source(&desktop);
|
||||
let (source, mut replies, mut view) = source(&desktop);
|
||||
source.set_mode(Mode::Room)?;
|
||||
let mut client = Client::new(&source);
|
||||
client.send(&source, json!({"type":"request","intent":Uuid::new_v4()}));
|
||||
@@ -1428,10 +1367,7 @@ async fn windows_stop_shortcut_on_isolated_desktop() -> Result<()> {
|
||||
chord.press("AltLeft")?;
|
||||
chord.press(&format!("F{key}"))?;
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
let mut timer = None;
|
||||
while desktop.0.lock().unwrap().owner.is_some() {
|
||||
desktop.tick_when_needed(&mut timer).await;
|
||||
}
|
||||
drop(view.wait_for(|state| state.mode == Mode::Ask).await.unwrap());
|
||||
}).await.map_err(|_| anyhow!("stop timed out with Shift={shift}, Win={win}"))?;
|
||||
chord.release()?;
|
||||
assert_eq!(view.borrow().mode, Mode::Ask);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{Action, Bounds, Held, Sink, TargetState};
|
||||
use crate::capture::{Target, TargetKind};
|
||||
use crate::windows_hotkeys::{Activation, Binding, Hotkeys};
|
||||
use crate::windows_hotkeys::Hotkeys;
|
||||
use ::windows::Win32::{
|
||||
Foundation::{CloseHandle, FILETIME, HWND, RECT},
|
||||
Graphics::{
|
||||
@@ -287,44 +287,6 @@ fn key(scan: u16, flags: KEYBD_EVENT_FLAGS) -> INPUT {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct StopPending(std::sync::atomic::AtomicU8);
|
||||
|
||||
impl StopPending {
|
||||
const ARMED: u8 = 1;
|
||||
const PENDING: u8 = 2;
|
||||
|
||||
pub(super) fn arm(&self, active: bool) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
if active {
|
||||
self.0.fetch_or(Self::ARMED, Relaxed);
|
||||
} else {
|
||||
self.0.fetch_and(!Self::ARMED, Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn signal(&self, event: Activation) -> bool {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
match event {
|
||||
Activation::Registered(_) => {
|
||||
self.0.fetch_or(Self::PENDING, Relaxed) & Self::PENDING == 0
|
||||
}
|
||||
// Admit at the key event. A subsequent release cannot cancel the pending stop.
|
||||
Activation::StopChord => self
|
||||
.0
|
||||
.compare_exchange(Self::ARMED, Self::ARMED | Self::PENDING, Relaxed, Relaxed)
|
||||
.is_ok(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn take(&self) -> bool {
|
||||
self.0
|
||||
.fetch_and(!Self::PENDING, std::sync::atomic::Ordering::Relaxed)
|
||||
& Self::PENDING
|
||||
!= 0
|
||||
}
|
||||
}
|
||||
|
||||
/// One process hotkey, independent of the number of sites and captures. The
|
||||
/// thread owns its Windows message queue/registration; the executor owns consent.
|
||||
pub(super) struct Shortcut {
|
||||
@@ -332,24 +294,14 @@ pub(super) struct Shortcut {
|
||||
_hotkeys: Hotkeys,
|
||||
}
|
||||
impl Shortcut {
|
||||
pub fn new(
|
||||
key: u8,
|
||||
pending: std::sync::Arc<StopPending>,
|
||||
wake: std::sync::Arc<tokio::sync::Notify>,
|
||||
) -> Result<Self> {
|
||||
let (hotkeys, [result]) = Hotkeys::register_stop(
|
||||
Binding {
|
||||
modifiers: MOD_CONTROL | MOD_ALT,
|
||||
key: 0x6f + u32::from(key),
|
||||
},
|
||||
move |event| {
|
||||
if pending.signal(event) {
|
||||
wake.notify_one();
|
||||
}
|
||||
},
|
||||
)?;
|
||||
pub fn new(key: u8, owner: std::sync::Weak<std::sync::Mutex<super::Executor>>) -> Result<Self> {
|
||||
let (hotkeys, results) = Hotkeys::register_stop(0x6f + u32::from(key), move |_| {
|
||||
if let Some(owner) = owner.upgrade() {
|
||||
owner.lock().unwrap().revoke();
|
||||
}
|
||||
})?;
|
||||
let Some(hotkeys) = hotkeys else {
|
||||
anyhow::bail!("input_shortcut_unavailable: {result:?}")
|
||||
anyhow::bail!("input_shortcut_unavailable: {results:?}")
|
||||
};
|
||||
Ok(Self {
|
||||
key,
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
use std::{cell::OnceCell, sync::mpsc::sync_channel, thread};
|
||||
use std::{sync::mpsc::sync_channel, thread};
|
||||
use windows::{
|
||||
core::Error,
|
||||
Win32::{
|
||||
Foundation::{LPARAM, LRESULT, WPARAM},
|
||||
System::{LibraryLoader::GetModuleHandleW, Threading::GetCurrentThreadId},
|
||||
Foundation::WPARAM,
|
||||
System::Threading::GetCurrentThreadId,
|
||||
UI::{
|
||||
Input::KeyboardAndMouse::{
|
||||
GetAsyncKeyState, RegisterHotKey, UnregisterHotKey, MOD_NOREPEAT, VIRTUAL_KEY,
|
||||
VK_CONTROL, VK_MENU,
|
||||
},
|
||||
Input::KeyboardAndMouse::{RegisterHotKey, UnregisterHotKey, MOD_NOREPEAT},
|
||||
WindowsAndMessaging::{
|
||||
CallNextHookEx, GetMessageW, PeekMessageW, PostThreadMessageW, SetWindowsHookExW,
|
||||
UnhookWindowsHookEx, HC_ACTION, KBDLLHOOKSTRUCT, MSG, PM_NOREMOVE, WH_KEYBOARD_LL,
|
||||
WM_HOTKEY, WM_KEYDOWN, WM_QUIT, WM_SYSKEYDOWN,
|
||||
GetMessageW, PeekMessageW, PostThreadMessageW, MSG, PM_NOREMOVE, WM_HOTKEY, WM_QUIT,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -22,39 +17,6 @@ pub use windows::Win32::UI::Input::KeyboardAndMouse::{
|
||||
HOT_KEY_MODIFIERS, MOD_ALT, MOD_CONTROL, MOD_SHIFT, MOD_WIN,
|
||||
};
|
||||
|
||||
struct StopObserver {
|
||||
key: u32,
|
||||
matched: Box<dyn Fn() + Send>,
|
||||
}
|
||||
thread_local! { static STOP_OBSERVER: OnceCell<StopObserver> = const { OnceCell::new() }; }
|
||||
|
||||
pub(crate) enum Activation {
|
||||
Registered(usize),
|
||||
StopChord,
|
||||
}
|
||||
|
||||
fn stop_chord(key: u32, configured: u32, down: impl Fn(VIRTUAL_KEY) -> bool) -> bool {
|
||||
key == configured && down(VK_CONTROL) && down(VK_MENU)
|
||||
}
|
||||
|
||||
unsafe extern "system" fn observe_stop(code: i32, message: WPARAM, data: LPARAM) -> LRESULT {
|
||||
unsafe {
|
||||
if code == HC_ACTION as i32 && matches!(message.0 as u32, WM_KEYDOWN | WM_SYSKEYDOWN) {
|
||||
let key = (*(data.0 as *const KBDLLHOOKSTRUCT)).vkCode;
|
||||
STOP_OBSERVER.with(|slot| {
|
||||
if let Some(observer) = slot.get() {
|
||||
if stop_chord(key, observer.key, |modifier| {
|
||||
GetAsyncKeyState(modifier.0.into()) < 0
|
||||
}) {
|
||||
(observer.matched)();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
CallNextHookEx(None, code, message, data)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Binding {
|
||||
pub modifiers: HOT_KEY_MODIFIERS,
|
||||
pub key: u32,
|
||||
@@ -70,37 +32,31 @@ impl Hotkeys {
|
||||
pub fn register<const N: usize>(
|
||||
name: &str,
|
||||
bindings: [Option<Binding>; N],
|
||||
mut activated: impl FnMut(usize) + Send + 'static,
|
||||
activated: impl FnMut(usize) + Send + 'static,
|
||||
) -> std::io::Result<(Option<Self>, [Option<Result<(), Error>>; N])> {
|
||||
Self::listen(name, bindings, None, move |event| {
|
||||
if let Activation::Registered(id) = event {
|
||||
activated(id);
|
||||
}
|
||||
})
|
||||
Self::listen(name, bindings, false, activated)
|
||||
}
|
||||
|
||||
pub(crate) fn register_stop(
|
||||
binding: Binding,
|
||||
activated: impl Fn(Activation) + Clone + Send + 'static,
|
||||
) -> std::io::Result<(Option<Self>, [Option<Result<(), Error>>; 1])> {
|
||||
let on_match = activated.clone();
|
||||
let observer = StopObserver {
|
||||
key: binding.key,
|
||||
matched: Box::new(move || on_match(Activation::StopChord)),
|
||||
};
|
||||
Self::listen(
|
||||
"piik-input-stop",
|
||||
[Some(binding)],
|
||||
Some(observer),
|
||||
activated,
|
||||
)
|
||||
key: u32,
|
||||
activated: impl FnMut(usize) + Send + 'static,
|
||||
) -> std::io::Result<(Option<Self>, [Option<Result<(), Error>>; 4])> {
|
||||
let base = MOD_CONTROL | MOD_ALT;
|
||||
let bindings = [
|
||||
base,
|
||||
base | MOD_SHIFT,
|
||||
base | MOD_WIN,
|
||||
base | MOD_SHIFT | MOD_WIN,
|
||||
]
|
||||
.map(|modifiers| Some(Binding { modifiers, key }));
|
||||
Self::listen("piik-input-stop", bindings, true, activated)
|
||||
}
|
||||
|
||||
fn listen<const N: usize>(
|
||||
name: &str,
|
||||
bindings: [Option<Binding>; N],
|
||||
observer: Option<StopObserver>,
|
||||
mut activated: impl FnMut(Activation) + Send + 'static,
|
||||
require_all: bool,
|
||||
mut activated: impl FnMut(usize) + Send + 'static,
|
||||
) -> std::io::Result<(Option<Self>, [Option<Result<(), Error>>; N])> {
|
||||
let (ready, started) = sync_channel(1);
|
||||
let task = thread::Builder::new()
|
||||
@@ -119,42 +75,26 @@ impl Hotkeys {
|
||||
binding.key,
|
||||
)
|
||||
});
|
||||
if require_all && !matches!(results[id], Some(Ok(()))) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let registered = results
|
||||
.each_ref()
|
||||
.map(|result| matches!(result, Some(Ok(()))));
|
||||
let mut active = registered.contains(&true);
|
||||
let mut hook = None;
|
||||
if let Some(observer) = observer.filter(|_| active) {
|
||||
STOP_OBSERVER.with(|slot| {
|
||||
let _ = slot.set(observer);
|
||||
});
|
||||
match GetModuleHandleW(None).and_then(|module| {
|
||||
SetWindowsHookExW(
|
||||
WH_KEYBOARD_LL,
|
||||
Some(observe_stop),
|
||||
Some(module.into()),
|
||||
0,
|
||||
)
|
||||
}) {
|
||||
Ok(handle) => hook = Some(handle),
|
||||
Err(error) => {
|
||||
results[0] = Some(Err(error));
|
||||
active = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
let active = if require_all {
|
||||
registered.iter().all(|&ok| ok)
|
||||
} else {
|
||||
registered.contains(&true)
|
||||
};
|
||||
if ready.send((GetCurrentThreadId(), active, results)).is_ok() && active {
|
||||
while GetMessageW(&mut message, None, 0, 0).0 > 0 {
|
||||
let id = message.wParam.0;
|
||||
if message.message == WM_HOTKEY && registered.get(id) == Some(&true) {
|
||||
activated(Activation::Registered(id));
|
||||
activated(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(handle) = hook {
|
||||
let _ = UnhookWindowsHookEx(handle);
|
||||
}
|
||||
for (id, registered) in registered.into_iter().enumerate() {
|
||||
if registered {
|
||||
let _ = UnregisterHotKey(None, id as i32);
|
||||
@@ -202,25 +142,6 @@ mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn windows_stop_matches_configured_function_with_extra_modifiers() {
|
||||
use windows::Win32::UI::Input::KeyboardAndMouse::{VK_LWIN, VK_RWIN, VK_SHIFT};
|
||||
for extra in [
|
||||
vec![],
|
||||
vec![VK_SHIFT],
|
||||
vec![VK_LWIN],
|
||||
vec![VK_SHIFT, VK_RWIN],
|
||||
] {
|
||||
let held = |key| key == VK_CONTROL || key == VK_MENU || extra.contains(&key);
|
||||
assert!(stop_chord(0x79, 0x79, held));
|
||||
assert!(!stop_chord(0x78, 0x79, |_| panic!(
|
||||
"unrelated key queried modifiers"
|
||||
)));
|
||||
assert!(!stop_chord(0x79, 0x79, |key| key == VK_CONTROL));
|
||||
assert!(!stop_chord(0x79, 0x79, |key| key == VK_MENU));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "scoped Win32 registration; only posts to its own queue"]
|
||||
fn windows_hotkeys_dispatch_registered_ids_and_release_on_drop() -> anyhow::Result<()> {
|
||||
|
||||
Reference in new issue
Block a user