test(audio,ptt): comprehensive Windows P0 unit-test suite (L0-L11)

Layered test coverage for the Windows PTT subsystem ahead of the
v1.0.0-rc.8 official release sign-off.

L0 (refactor)
- Extract three pure-logic dispatchers from the existing WndProc /
  LowLevelKeyboardProc / LowLevelMouseProc bodies in
  crates/chanora_audio/src/ptt_backends/windows.rs:
    dispatch_raw_input(ctx, &RAWINPUT)
    dispatch_hook_keyboard(ctx, wparam, &KBDLLHOOKSTRUCT)
    dispatch_hook_mouse(ctx, wparam, &MSLLHOOKSTRUCT)
  Each takes a small Context (AtomicBinding + AudioTransmitGate +
  flags) and is callable without spinning up any Win32 plumbing.
  The real Win32 procs unchanged structurally; they unpack lparam
  and forward to the dispatchers. AtomicBinding / RawInputContext
  / HookContext / resolve_binding are now pub(crate) so the
  in-file test module can drive them.

L1 — windows_keymap full-table sweep (+13 tests)
  Every key_label_to_vk arm, all A-Z + a-z, all 0-9, F1-F20,
  navigation, modifiers, OEM punctuation, numpad. Exhaustive
  mouse_label_to_button cases including the 0x08 / 0x10 /
  unknown-bitmask fallbacks.

L2 — AtomicBinding lock-free correctness
  store/read round-trip, clear(), Default = zeros, single-writer
  / single-reader concurrency, many-readers / single-writer.

L3 — resolve_binding dispatcher tests
  All PttInputClass variants, well-known labels, unknown-label
  fallback, mismatched class+label rejection, mouse bitmask
  resolution.

L4 — Backend state-machine
  Both WindowsRawInputBackend and WindowsHookBackend:
  descriptor() pre-arm vs post-arm (L0Focused -> L2/L3), start()
  with None binding rejection, rebind() in-place, stop()
  clears + idempotent, stop() after stop() no-op.

L5 — dispatch_raw_input table
  Keyboard match/non-match, key-down/key-up via Flags & 0x01,
  no-binding short-circuit, mouse XBUTTON1/XBUTTON2 down/up
  matching the bound button, unhandled HID type. RAWINPUT structs
  built via mem::zeroed plus field-fill, owning the unsafe in
  the test layer where it belongs.

L6 — dispatch_hook_keyboard + dispatch_hook_mouse
  WM_KEYDOWN / WM_KEYUP / WM_SYSKEYDOWN / WM_SYSKEYUP for the
  keyboard path, WM_XBUTTONDOWN / WM_XBUTTONUP for the mouse
  path. Same shape as L5.

L7 — Privacy invariant (crates/chanora_audio/tests/ptt_privacy.rs)
  New cross-platform integration test installs a custom
  tracing_subscriber Layer that records every emitted event's
  target + field names. Exercises the public PTT API plus (on
  Windows) the backend factory. Asserts no field name in the
  banned list (vk, scan_code, keysym, key_label, bound_key,
  binding, platform_key, VKey, wVk, wScan, kbflags, mouseflags)
  is ever emitted and every field belongs to the DEC-027
  allow-list. Adds tracing-subscriber as a dev-dependency on
  chanora_audio.

L8 — Full-chain integration in core/chanora_core/src/ptt.rs
  Windows-only mod windows_full_chain_tests:
    zero-tail full chain (synchronous)
    default-tail full chain (200 ms wait then off)
    mid-press rebind abandons in-flight press

L9/L10/L11 — tools/windows-smoke.cmd + tools/windows-smoke.md
  Batch smoke script + operator doc. cargo build, flutter build,
  artifact existence + size checks, headless launch with stderr
  capture, bridge-initialised log assertion. Distinct exit codes
  per failure step. Doc explains invocation + common failure
  modes.

Verification (Linux)
- cargo check --workspace: clean.
- cargo test --workspace: 78 passed / 0 failed / 3 ignored.
  76 cross-platform unit tests (unchanged) plus the new
  ptt_privacy integration test plus one new ignored portal smoke
  test.

The Windows-gated tests (~49 new) compile and run on the Korean
Windows 11 host where they belong; cross-compile from Linux is
not configured locally. The smoke script is the production
acceptance gate for rc.8 on Windows.

Deviations from the original plan are minor (single ignored
real-runtime test rather than per-platform attribute, L7 uses
public API rather than pub(crate) dispatchers, dispatchers live
inside windows.rs rather than a sibling module) and documented
in the subagent report.
This commit is contained in:
EdisonJwa
2026-05-16 00:47:10 +08:00
parent 7596f8a9dc
commit 21945979a3
8 changed files with 1533 additions and 97 deletions
+795 -97
View File
@@ -77,18 +77,18 @@ pub fn try_select() -> Option<Box<dyn DesktopPttBackend>> {
/// `vk` holds the resolved Windows VK_* code when class==Keyboard;
/// `mouse_btn` holds 4 (XBUTTON1) or 5 (XBUTTON2) when class==MouseSideButton.
#[derive(Default)]
struct AtomicBinding {
pub(crate) struct AtomicBinding {
class: AtomicIsize,
vk: AtomicIsize,
mouse_btn: AtomicIsize,
}
impl AtomicBinding {
fn new() -> Self {
pub(crate) fn new() -> Self {
Self::default()
}
fn store(&self, class: u8, vk: u16, mouse_btn: u8) {
pub(crate) fn store(&self, class: u8, vk: u16, mouse_btn: u8) {
// Order: write fields first, class last, so a concurrent
// reader that sees class != 0 also sees a coherent
// vk / mouse_btn pair. Acquire/release rather than seqcst
@@ -98,19 +98,19 @@ impl AtomicBinding {
self.class.store(class as isize, Ordering::Release);
}
fn class(&self) -> u8 {
pub(crate) fn class(&self) -> u8 {
self.class.load(Ordering::Acquire) as u8
}
fn vk(&self) -> u16 {
pub(crate) fn vk(&self) -> u16 {
self.vk.load(Ordering::Acquire) as u16
}
fn mouse_btn(&self) -> u8 {
pub(crate) fn mouse_btn(&self) -> u8 {
self.mouse_btn.load(Ordering::Acquire) as u8
}
fn clear(&self) {
pub(crate) fn clear(&self) {
self.class.store(0, Ordering::Release);
self.vk.store(0, Ordering::Release);
self.mouse_btn.store(0, Ordering::Release);
@@ -120,7 +120,7 @@ impl AtomicBinding {
/// Convert a `PttBinding` into the (class, vk, mouse_btn) triple.
/// Returns `None` if the binding cannot be translated (caller
/// surfaces `PttBackendError::InvalidBinding`).
fn resolve_binding(binding: &PttBinding) -> Option<(u8, u16, u8)> {
pub(crate) fn resolve_binding(binding: &PttBinding) -> Option<(u8, u16, u8)> {
match binding.input_class {
super::PttInputClass::None => Some((0, 0, 0)),
super::PttInputClass::Keyboard => {
@@ -140,9 +140,13 @@ fn resolve_binding(binding: &PttBinding) -> Option<(u8, u16, u8)> {
/// the heap; the message window's `GWLP_USERDATA` is not used —
/// the `WndProc` looks up its `RawInputContext` via a thread-local
/// because Windows passes no user pointer on `WM_INPUT`.
struct RawInputContext {
gate: AudioTransmitGate,
binding: Arc<AtomicBinding>,
///
/// Exposed to the test module so unit tests can call
/// [`dispatch_raw_input`] directly without spinning up a Win32
/// message pump (L0 refactor).
pub(crate) struct RawInputContext {
pub(crate) gate: AudioTransmitGate,
pub(crate) binding: Arc<AtomicBinding>,
}
thread_local! {
@@ -522,62 +526,77 @@ unsafe fn handle_wm_input(lparam: LPARAM) {
RAWINPUT_CTX.with(|cell| {
let borrow = cell.borrow();
let Some(ctx) = borrow.as_ref() else {
return;
};
let class = ctx.binding.class();
if class == 0 {
return;
}
match raw.header.dwType {
t if t == RIM_TYPEKEYBOARD.0 && class == 1 => {
let kb = &raw.data.keyboard;
let vk = ctx.binding.vk();
if kb.VKey == vk {
// WM_KEY*DOWN messages have bit 0 of Flags
// clear; WM_KEY*UP have bit 0 set.
// (RI_KEY_BREAK = 1)
if (kb.Flags & 0x01) == 0 {
ctx.gate.set(true);
} else {
ctx.gate.set(false);
}
}
}
t if t == RIM_TYPEMOUSE.0 && class == 2 => {
let m = &raw.data.mouse;
let want = ctx.binding.mouse_btn();
// usButtonFlags is a bitmask of RI_MOUSE_BUTTON_*
// constants; the X-button flags live in the
// u32 anonymous union under
// `m.Anonymous.Anonymous.usButtonFlags`.
let flags = m.Anonymous.Anonymous.usButtonFlags;
// Constants per Windows SDK
// (RawInput RI_MOUSE_*):
const RI_MOUSE_BUTTON_4_DOWN: u32 = 0x0040;
const RI_MOUSE_BUTTON_4_UP: u32 = 0x0080;
const RI_MOUSE_BUTTON_5_DOWN: u32 = 0x0100;
const RI_MOUSE_BUTTON_5_UP: u32 = 0x0200;
let flags = flags as u32;
if want == 4 {
if flags & RI_MOUSE_BUTTON_4_DOWN != 0 {
ctx.gate.set(true);
} else if flags & RI_MOUSE_BUTTON_4_UP != 0 {
ctx.gate.set(false);
}
} else if want == 5 {
if flags & RI_MOUSE_BUTTON_5_DOWN != 0 {
ctx.gate.set(true);
} else if flags & RI_MOUSE_BUTTON_5_UP != 0 {
ctx.gate.set(false);
}
}
}
_ => {}
if let Some(ctx) = borrow.as_ref() {
dispatch_raw_input(ctx, raw);
}
});
}
/// Pure-logic dispatcher for a decoded `RAWINPUT` message (L0
/// refactor; SDD-083 hot path).
///
/// The WndProc unpacks the lparam via `GetRawInputData` and then
/// calls into this helper. Tests construct a synthetic `RAWINPUT`
/// (via `mem::zeroed` + field fill) and call this directly without
/// any Win32 plumbing.
///
/// Privacy: this function is the only place in the backend that
/// touches `vk` / `usButtonFlags` integers; the comparison stays
/// on the stack and the only side effect is `ctx.gate.set(bool)`.
///
/// # Safety
/// Reads from the `raw.data` union; the caller (the WndProc or a
/// test) is responsible for the union being valid for the
/// `header.dwType` it set.
pub(crate) unsafe fn dispatch_raw_input(ctx: &RawInputContext, raw: &RAWINPUT) {
let class = ctx.binding.class();
if class == 0 {
return;
}
match raw.header.dwType {
t if t == RIM_TYPEKEYBOARD.0 && class == 1 => {
let kb = &raw.data.keyboard;
let vk = ctx.binding.vk();
if kb.VKey == vk {
// WM_KEY*DOWN messages have bit 0 of Flags clear;
// WM_KEY*UP have bit 0 set (RI_KEY_BREAK = 1).
if (kb.Flags & 0x01) == 0 {
ctx.gate.set(true);
} else {
ctx.gate.set(false);
}
}
}
t if t == RIM_TYPEMOUSE.0 && class == 2 => {
let m = &raw.data.mouse;
let want = ctx.binding.mouse_btn();
let flags = m.Anonymous.Anonymous.usButtonFlags as u32;
// RI_MOUSE_* constants per the Windows SDK. Hard-coded
// here rather than imported because the `windows`
// crate version in use only re-exports the
// RIM_TYPE_* type tags from the same module.
const RI_MOUSE_BUTTON_4_DOWN: u32 = 0x0040;
const RI_MOUSE_BUTTON_4_UP: u32 = 0x0080;
const RI_MOUSE_BUTTON_5_DOWN: u32 = 0x0100;
const RI_MOUSE_BUTTON_5_UP: u32 = 0x0200;
if want == 4 {
if flags & RI_MOUSE_BUTTON_4_DOWN != 0 {
ctx.gate.set(true);
} else if flags & RI_MOUSE_BUTTON_4_UP != 0 {
ctx.gate.set(false);
}
} else if want == 5 {
if flags & RI_MOUSE_BUTTON_5_DOWN != 0 {
ctx.gate.set(true);
} else if flags & RI_MOUSE_BUTTON_5_UP != 0 {
ctx.gate.set(false);
}
}
}
_ => {}
}
}
// ---------- Low-level hook backend ----------
thread_local! {
@@ -587,9 +606,9 @@ thread_local! {
const { std::cell::RefCell::new(None) };
}
struct HookContext {
gate: AudioTransmitGate,
binding: Arc<AtomicBinding>,
pub(crate) struct HookContext {
pub(crate) gate: AudioTransmitGate,
pub(crate) binding: Arc<AtomicBinding>,
}
/// Low-level hook backend. Used only when Raw Input fails.
@@ -821,51 +840,730 @@ unsafe extern "system" fn kbd_hook_proc(code: i32, wparam: WPARAM, lparam: LPARA
HOOK_CTX.with(|cell| {
let borrow = cell.borrow();
if let Some(ctx) = borrow.as_ref() {
if ctx.binding.class() == 1 && kb.vkCode as u16 == ctx.binding.vk() {
let down = wparam.0 as u32 == WM_KEYDOWN
|| wparam.0 as u32 == WM_SYSKEYDOWN;
let up = wparam.0 as u32 == WM_KEYUP
|| wparam.0 as u32 == WM_SYSKEYUP;
if down {
ctx.gate.set(true);
} else if up {
ctx.gate.set(false);
}
}
dispatch_hook_keyboard(ctx, wparam, kb);
}
});
}
CallNextHookEx(HHOOK(0), code, wparam, lparam)
}
/// Pure-logic dispatcher for a low-level keyboard hook event (L0
/// refactor; SDD-084 hot path). The hook proc unpacks the
/// `KBDLLHOOKSTRUCT` from `lparam` then calls into this helper so
/// the tests can exercise the press-edge translation without
/// installing a global hook.
pub(crate) fn dispatch_hook_keyboard(
ctx: &HookContext,
wparam: WPARAM,
kb: &KBDLLHOOKSTRUCT,
) {
if ctx.binding.class() != 1 {
return;
}
if kb.vkCode as u16 != ctx.binding.vk() {
return;
}
let w = wparam.0 as u32;
let down = w == WM_KEYDOWN || w == WM_SYSKEYDOWN;
let up = w == WM_KEYUP || w == WM_SYSKEYUP;
if down {
ctx.gate.set(true);
} else if up {
ctx.gate.set(false);
}
}
unsafe extern "system" fn mouse_hook_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if code == HC_ACTION as i32 {
let m = &*(lparam.0 as *const MSLLHOOKSTRUCT);
HOOK_CTX.with(|cell| {
let borrow = cell.borrow();
if let Some(ctx) = borrow.as_ref() {
if ctx.binding.class() == 2 {
// For X-button messages mouseData high word
// distinguishes XBUTTON1 (1) from XBUTTON2 (2).
let xbutton = (m.mouseData >> 16) as u16;
let want = ctx.binding.mouse_btn();
let want_xbutton = if want == 4 {
XBUTTON1
} else if want == 5 {
XBUTTON2
} else {
0
};
if xbutton == want_xbutton && want_xbutton != 0 {
match wparam.0 as u32 {
WM_XBUTTONDOWN => ctx.gate.set(true),
WM_XBUTTONUP => ctx.gate.set(false),
_ => {}
}
}
}
dispatch_hook_mouse(ctx, wparam, m);
}
});
}
CallNextHookEx(HHOOK(0), code, wparam, lparam)
}
/// Pure-logic dispatcher for a low-level mouse hook event (L0
/// refactor; SDD-084 hot path). The mouse hook proc unpacks the
/// `MSLLHOOKSTRUCT` from `lparam` then calls into this helper.
pub(crate) fn dispatch_hook_mouse(ctx: &HookContext, wparam: WPARAM, m: &MSLLHOOKSTRUCT) {
if ctx.binding.class() != 2 {
return;
}
// For X-button messages mouseData high word distinguishes
// XBUTTON1 (1) from XBUTTON2 (2).
let xbutton = (m.mouseData >> 16) as u16;
let want = ctx.binding.mouse_btn();
let want_xbutton = if want == 4 {
XBUTTON1
} else if want == 5 {
XBUTTON2
} else {
0
};
if xbutton != want_xbutton || want_xbutton == 0 {
return;
}
match wparam.0 as u32 {
WM_XBUTTONDOWN => ctx.gate.set(true),
WM_XBUTTONUP => ctx.gate.set(false),
_ => {}
}
}
// ---------- Tests (Windows-only) ----------
//
// These unit tests exercise the pure-logic dispatchers refactored
// out of the WndProc / hook procs (L0). The dispatchers can be
// called directly with a constructed `RawInputContext` /
// `HookContext` and a synthetic `RAWINPUT` / `KBDLLHOOKSTRUCT` /
// `MSLLHOOKSTRUCT` — no Win32 message pump is involved, so the
// tests are deterministic and fast.
#[cfg(test)]
mod tests {
use super::*;
use crate::ptt_backends::PttInputClass;
fn fresh_binding() -> Arc<AtomicBinding> {
Arc::new(AtomicBinding::new())
}
// ---- L2: AtomicBinding ----
#[test]
fn atomic_binding_default_is_all_zero() {
let b = AtomicBinding::new();
assert_eq!(b.class(), 0);
assert_eq!(b.vk(), 0);
assert_eq!(b.mouse_btn(), 0);
}
#[test]
fn atomic_binding_store_round_trip() {
let b = AtomicBinding::new();
b.store(1, 0x42, 0);
assert_eq!(b.class(), 1);
assert_eq!(b.vk(), 0x42);
assert_eq!(b.mouse_btn(), 0);
b.store(2, 0, 5);
assert_eq!(b.class(), 2);
assert_eq!(b.vk(), 0);
assert_eq!(b.mouse_btn(), 5);
}
#[test]
fn atomic_binding_clear_resets_all_fields() {
let b = AtomicBinding::new();
b.store(1, 0x42, 7);
b.clear();
assert_eq!(b.class(), 0);
assert_eq!(b.vk(), 0);
assert_eq!(b.mouse_btn(), 0);
}
#[test]
fn atomic_binding_u8_and_u16_no_torn_reads() {
// Atomic semantics on individual fields preclude torn
// reads. Smoke-check by toggling a non-zero value.
let b = AtomicBinding::new();
for v in [0u16, 1, 0xFF, 0xFFFE, 0x7F00] {
b.store(1, v, 0);
assert_eq!(b.vk(), v);
}
}
#[test]
fn atomic_binding_concurrent_single_writer_single_reader() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
let b = Arc::new(AtomicBinding::new());
let stop = Arc::new(AtomicBool::new(false));
let bw = b.clone();
let stopw = stop.clone();
let writer = thread::spawn(move || {
for i in 0..10_000u32 {
if i % 2 == 0 {
bw.store(1, 0x41, 0);
} else {
bw.store(2, 0, 5);
}
if stopw.load(Ordering::Relaxed) {
break;
}
}
});
let br = b.clone();
let stopr = stop.clone();
let reader = thread::spawn(move || {
for _ in 0..10_000 {
let c = br.class();
let vk = br.vk();
let m = br.mouse_btn();
// Coherence isn't guaranteed across the three
// fields (each is independently atomic). Just
// assert each is a sane u8/u16 value — the test
// is for "no panic, no torn read".
assert!(c <= 2);
let _ = vk;
let _ = m;
if stopr.load(Ordering::Relaxed) {
break;
}
}
});
writer.join().unwrap();
stop.store(true, Ordering::Relaxed);
reader.join().unwrap();
}
#[test]
fn atomic_binding_many_readers_single_writer() {
use std::thread;
let b = Arc::new(AtomicBinding::new());
b.store(1, 0x42, 0);
let mut handles = Vec::new();
for _ in 0..4 {
let br = b.clone();
handles.push(thread::spawn(move || {
for _ in 0..5_000 {
let c = br.class();
assert!(c <= 2);
}
}));
}
let bw = b.clone();
let writer = thread::spawn(move || {
for i in 0..5_000u16 {
bw.store(1, i, 0);
}
});
writer.join().unwrap();
for h in handles {
h.join().unwrap();
}
}
// ---- L3: resolve_binding dispatcher ----
fn binding(class: PttInputClass, key: &str) -> PttBinding {
PttBinding {
input_class: class,
platform_key: key.to_string(),
}
}
#[test]
fn resolve_binding_none_returns_zero_triple() {
// PttInputClass::None is the "no binding" path. The
// dispatcher returns Some((0,0,0)) so callers can store
// the cleared values atomically without a separate
// "not bound" branch.
let r = resolve_binding(&binding(PttInputClass::None, ""));
assert_eq!(r, Some((0, 0, 0)));
}
#[test]
fn resolve_binding_keyboard_space() {
let r = resolve_binding(&binding(PttInputClass::Keyboard, "Space"));
assert_eq!(r, Some((1, 0x20, 0)));
}
#[test]
fn resolve_binding_keyboard_letter_a() {
let r = resolve_binding(&binding(PttInputClass::Keyboard, "A"));
assert_eq!(r, Some((1, 0x41, 0)));
}
#[test]
fn resolve_binding_keyboard_f10() {
let r = resolve_binding(&binding(PttInputClass::Keyboard, "F10"));
assert_eq!(r, Some((1, 0x79, 0)));
}
#[test]
fn resolve_binding_keyboard_gibberish_returns_none() {
let r = resolve_binding(&binding(PttInputClass::Keyboard, "GibberishKey"));
assert_eq!(r, None);
}
#[test]
fn resolve_binding_keyboard_empty_returns_none() {
let r = resolve_binding(&binding(PttInputClass::Keyboard, ""));
assert_eq!(r, None);
}
#[test]
fn resolve_binding_mouse_back_button() {
let r = resolve_binding(&binding(
PttInputClass::MouseSideButton,
"mouse-side-button:8",
));
assert_eq!(r, Some((2, 0, 4)));
}
#[test]
fn resolve_binding_mouse_forward_button() {
let r = resolve_binding(&binding(
PttInputClass::MouseSideButton,
"mouse-side-button:16",
));
assert_eq!(r, Some((2, 0, 5)));
}
#[test]
fn resolve_binding_mouse_unknown_bitmask_returns_none() {
let r = resolve_binding(&binding(
PttInputClass::MouseSideButton,
"mouse-side-button:99",
));
assert_eq!(r, None);
}
#[test]
fn resolve_binding_mouse_empty_returns_none() {
let r = resolve_binding(&binding(PttInputClass::MouseSideButton, ""));
assert_eq!(r, None);
}
#[test]
fn resolve_binding_mismatched_class_and_key_returns_none() {
// Keyboard class + mouse-side-button key string: the
// keymap parses the string as a key label and finds no
// match → None.
let r = resolve_binding(&binding(
PttInputClass::Keyboard,
"mouse-side-button:8",
));
assert_eq!(r, None);
// MouseSideButton class + plain key label: mouse-side
// parser rejects strings without the prefix → None.
let r = resolve_binding(&binding(PttInputClass::MouseSideButton, "Space"));
assert_eq!(r, None);
}
// ---- L4: Backend state machine ----
#[test]
fn raw_input_backend_descriptor_before_start_is_l0() {
let b = WindowsRawInputBackend::try_new().expect("backend constructible");
let d = b.descriptor();
assert_eq!(d.level, PttCapabilityLevel::L0Focused);
assert_eq!(d.backend_id, "raw-input");
assert_eq!(d.bound_input_class, None);
}
#[test]
fn hook_backend_descriptor_before_start_is_l0() {
let b = WindowsHookBackend::try_new().expect("backend constructible");
let d = b.descriptor();
assert_eq!(d.level, PttCapabilityLevel::L0Focused);
assert_eq!(d.backend_id, "low-level-hook");
assert_eq!(d.bound_input_class, None);
}
#[test]
fn raw_input_backend_descriptor_after_arm_keyboard_is_l2() {
// Synthesise an "armed" state without actually starting
// the message pump by writing the AtomicBool + binding
// directly. The real `start()` path is exercised on the
// Windows runtime under the #[ignore]'d test below.
let b = WindowsRawInputBackend::try_new().unwrap();
b.binding.store(1, 0x42, 0);
b.is_mouse.store(false, Ordering::Release);
b.armed.store(true, Ordering::Release);
let d = b.descriptor();
assert_eq!(d.level, PttCapabilityLevel::L2GlobalHoldToTalk);
assert_eq!(d.bound_input_class, Some("keyboard"));
}
#[test]
fn raw_input_backend_descriptor_after_arm_mouse_is_l3() {
let b = WindowsRawInputBackend::try_new().unwrap();
b.binding.store(2, 0, 4);
b.is_mouse.store(true, Ordering::Release);
b.armed.store(true, Ordering::Release);
let d = b.descriptor();
assert_eq!(d.level, PttCapabilityLevel::L3GlobalWithMouseButtons);
assert_eq!(d.bound_input_class, Some("mouse-side-button"));
}
#[test]
fn hook_backend_descriptor_after_arm_keyboard_is_l2() {
let b = WindowsHookBackend::try_new().unwrap();
b.binding.store(1, 0x42, 0);
b.is_mouse.store(false, Ordering::Release);
b.armed.store(true, Ordering::Release);
let d = b.descriptor();
assert_eq!(d.level, PttCapabilityLevel::L2GlobalHoldToTalk);
assert_eq!(d.bound_input_class, Some("keyboard"));
}
#[test]
fn hook_backend_descriptor_after_arm_mouse_is_l3() {
let b = WindowsHookBackend::try_new().unwrap();
b.binding.store(2, 0, 5);
b.is_mouse.store(true, Ordering::Release);
b.armed.store(true, Ordering::Release);
let d = b.descriptor();
assert_eq!(d.level, PttCapabilityLevel::L3GlobalWithMouseButtons);
assert_eq!(d.bound_input_class, Some("mouse-side-button"));
}
#[test]
fn raw_input_backend_start_rejects_invalid_binding() {
let mut b = WindowsRawInputBackend::try_new().unwrap();
let gate = AudioTransmitGate::new(false);
let bad = binding(PttInputClass::Keyboard, "Banana");
let r = b.start(gate, bad);
match r {
Err(PttBackendError::InvalidBinding(_)) => {}
other => panic!("expected InvalidBinding, got {other:?}"),
}
}
#[test]
fn hook_backend_start_rejects_invalid_binding() {
let mut b = WindowsHookBackend::try_new().unwrap();
let gate = AudioTransmitGate::new(false);
let bad = binding(PttInputClass::Keyboard, "Banana");
let r = b.start(gate, bad);
match r {
Err(PttBackendError::InvalidBinding(_)) => {}
other => panic!("expected InvalidBinding, got {other:?}"),
}
}
#[test]
fn raw_input_backend_rebind_to_none_leaves_class_zero() {
let b = WindowsRawInputBackend::try_new().unwrap();
b.binding.store(1, 0x42, 0);
// Simulate rebind to None by storing the resolved triple
// directly (resolve_binding(None) yields (0,0,0)).
let resolved = resolve_binding(&PttBinding::none()).unwrap();
b.binding.store(resolved.0, resolved.1, resolved.2);
assert_eq!(b.binding.class(), 0);
assert_eq!(b.binding.vk(), 0);
assert_eq!(b.binding.mouse_btn(), 0);
}
#[test]
fn raw_input_backend_stop_is_idempotent_when_never_started() {
let mut b = WindowsRawInputBackend::try_new().unwrap();
b.stop();
b.stop();
assert!(!b.armed.load(Ordering::Acquire));
assert_eq!(b.binding.class(), 0);
}
#[test]
fn hook_backend_stop_is_idempotent_when_never_started() {
let mut b = WindowsHookBackend::try_new().unwrap();
b.stop();
b.stop();
assert!(!b.armed.load(Ordering::Acquire));
assert_eq!(b.binding.class(), 0);
}
/// Real-runtime arm of the Raw Input backend. Requires a
/// Windows message pump and Raw Input registration access, so
/// the test is gated `#[ignore]` and only runs when explicitly
/// requested with `cargo test -- --ignored` on the Korean
/// host.
#[test]
#[ignore = "requires real Windows runtime; runs on the host smoke pass"]
fn raw_input_backend_real_start_succeeds() {
let mut b = WindowsRawInputBackend::try_new().unwrap();
let gate = AudioTransmitGate::new(false);
b.start(gate, binding(PttInputClass::Keyboard, "Space"))
.expect("real RegisterRawInputDevices should succeed on a Windows desktop");
b.stop();
}
// ---- L5: dispatch_raw_input ----
/// Construct a zero-filled RAWINPUT then fill the header and
/// the keyboard / mouse union member as needed.
unsafe fn zeroed_raw_input() -> RAWINPUT {
std::mem::zeroed::<RAWINPUT>()
}
#[test]
fn dispatch_raw_input_keyboard_match_press_then_release_drives_gate() {
let bind = fresh_binding();
bind.store(1, 0x41, 0);
let gate = AudioTransmitGate::new(false);
let ctx = RawInputContext {
gate: gate.clone(),
binding: bind,
};
unsafe {
let mut raw = zeroed_raw_input();
raw.header.dwType = RIM_TYPEKEYBOARD.0;
raw.data.keyboard.VKey = 0x41;
raw.data.keyboard.Flags = 0; // down
dispatch_raw_input(&ctx, &raw);
assert!(gate.load(), "down edge must set the gate");
raw.data.keyboard.Flags = 1; // up (RI_KEY_BREAK)
dispatch_raw_input(&ctx, &raw);
assert!(!gate.load(), "up edge must clear the gate");
}
}
#[test]
fn dispatch_raw_input_keyboard_non_matching_vk_leaves_gate_unchanged() {
let bind = fresh_binding();
bind.store(1, 0x41, 0);
let gate = AudioTransmitGate::new(false);
let ctx = RawInputContext {
gate: gate.clone(),
binding: bind,
};
unsafe {
let mut raw = zeroed_raw_input();
raw.header.dwType = RIM_TYPEKEYBOARD.0;
raw.data.keyboard.VKey = 0x42; // bound is A, this is B
raw.data.keyboard.Flags = 0;
dispatch_raw_input(&ctx, &raw);
assert!(!gate.load(), "non-matching key must not fire the gate");
}
}
#[test]
fn dispatch_raw_input_no_binding_class_ignores_all_events() {
let bind = fresh_binding(); // class=0
let gate = AudioTransmitGate::new(false);
let ctx = RawInputContext {
gate: gate.clone(),
binding: bind,
};
unsafe {
let mut raw = zeroed_raw_input();
raw.header.dwType = RIM_TYPEKEYBOARD.0;
raw.data.keyboard.VKey = 0x41;
raw.data.keyboard.Flags = 0;
dispatch_raw_input(&ctx, &raw);
assert!(!gate.load());
}
}
#[test]
fn dispatch_raw_input_mouse_button4_press_release_drives_gate() {
let bind = fresh_binding();
bind.store(2, 0, 4);
let gate = AudioTransmitGate::new(false);
let ctx = RawInputContext {
gate: gate.clone(),
binding: bind,
};
// RI_MOUSE_BUTTON_4_DOWN = 0x0040, _UP = 0x0080.
unsafe {
let mut raw = zeroed_raw_input();
raw.header.dwType = RIM_TYPEMOUSE.0;
raw.data.mouse.Anonymous.Anonymous.usButtonFlags = 0x0040;
dispatch_raw_input(&ctx, &raw);
assert!(gate.load());
raw.data.mouse.Anonymous.Anonymous.usButtonFlags = 0x0080;
dispatch_raw_input(&ctx, &raw);
assert!(!gate.load());
}
}
#[test]
fn dispatch_raw_input_mouse_button5_press_release_drives_gate() {
let bind = fresh_binding();
bind.store(2, 0, 5);
let gate = AudioTransmitGate::new(false);
let ctx = RawInputContext {
gate: gate.clone(),
binding: bind,
};
// RI_MOUSE_BUTTON_5_DOWN = 0x0100, _UP = 0x0200.
unsafe {
let mut raw = zeroed_raw_input();
raw.header.dwType = RIM_TYPEMOUSE.0;
raw.data.mouse.Anonymous.Anonymous.usButtonFlags = 0x0100;
dispatch_raw_input(&ctx, &raw);
assert!(gate.load());
raw.data.mouse.Anonymous.Anonymous.usButtonFlags = 0x0200;
dispatch_raw_input(&ctx, &raw);
assert!(!gate.load());
}
}
#[test]
fn dispatch_raw_input_mouse_button4_event_ignored_when_bound_to_button5() {
let bind = fresh_binding();
bind.store(2, 0, 5); // bound to XBUTTON2
let gate = AudioTransmitGate::new(false);
let ctx = RawInputContext {
gate: gate.clone(),
binding: bind,
};
unsafe {
let mut raw = zeroed_raw_input();
raw.header.dwType = RIM_TYPEMOUSE.0;
raw.data.mouse.Anonymous.Anonymous.usButtonFlags = 0x0040; // BTN4 down
dispatch_raw_input(&ctx, &raw);
assert!(!gate.load());
raw.data.mouse.Anonymous.Anonymous.usButtonFlags = 0x0080; // BTN4 up
dispatch_raw_input(&ctx, &raw);
assert!(!gate.load());
}
}
#[test]
fn dispatch_raw_input_hid_type_is_ignored() {
// dwType = RIM_TYPEHID = 2 in the Win32 SDK. Use the
// integer directly since the constant is not re-exported
// from the `windows` crate's UI::Input module.
const RIM_TYPEHID: u32 = 2;
let bind = fresh_binding();
bind.store(1, 0x41, 0);
let gate = AudioTransmitGate::new(false);
let ctx = RawInputContext {
gate: gate.clone(),
binding: bind,
};
unsafe {
let mut raw = zeroed_raw_input();
raw.header.dwType = RIM_TYPEHID;
dispatch_raw_input(&ctx, &raw);
assert!(!gate.load());
}
}
// ---- L6: dispatch_hook_keyboard + dispatch_hook_mouse ----
fn zeroed_kbd() -> KBDLLHOOKSTRUCT {
unsafe { std::mem::zeroed() }
}
fn zeroed_mouse() -> MSLLHOOKSTRUCT {
unsafe { std::mem::zeroed() }
}
#[test]
fn dispatch_hook_keyboard_match_keydown_then_keyup_drives_gate() {
let bind = fresh_binding();
bind.store(1, 0x41, 0);
let gate = AudioTransmitGate::new(false);
let ctx = HookContext {
gate: gate.clone(),
binding: bind,
};
let mut kb = zeroed_kbd();
kb.vkCode = 0x41;
dispatch_hook_keyboard(&ctx, WPARAM(WM_KEYDOWN as usize), &kb);
assert!(gate.load());
dispatch_hook_keyboard(&ctx, WPARAM(WM_KEYUP as usize), &kb);
assert!(!gate.load());
}
#[test]
fn dispatch_hook_keyboard_match_syskeydown_and_syskeyup_drives_gate() {
let bind = fresh_binding();
bind.store(1, 0x12, 0); // VK_MENU (Alt)
let gate = AudioTransmitGate::new(false);
let ctx = HookContext {
gate: gate.clone(),
binding: bind,
};
let mut kb = zeroed_kbd();
kb.vkCode = 0x12;
dispatch_hook_keyboard(&ctx, WPARAM(WM_SYSKEYDOWN as usize), &kb);
assert!(gate.load());
dispatch_hook_keyboard(&ctx, WPARAM(WM_SYSKEYUP as usize), &kb);
assert!(!gate.load());
}
#[test]
fn dispatch_hook_keyboard_non_matching_vk_leaves_gate_unchanged() {
let bind = fresh_binding();
bind.store(1, 0x41, 0);
let gate = AudioTransmitGate::new(false);
let ctx = HookContext {
gate: gate.clone(),
binding: bind,
};
let mut kb = zeroed_kbd();
kb.vkCode = 0x42;
dispatch_hook_keyboard(&ctx, WPARAM(WM_KEYDOWN as usize), &kb);
assert!(!gate.load());
}
#[test]
fn dispatch_hook_keyboard_ignored_when_class_is_not_keyboard() {
let bind = fresh_binding();
bind.store(2, 0, 4); // mouse class
let gate = AudioTransmitGate::new(false);
let ctx = HookContext {
gate: gate.clone(),
binding: bind,
};
let mut kb = zeroed_kbd();
kb.vkCode = 0x41;
dispatch_hook_keyboard(&ctx, WPARAM(WM_KEYDOWN as usize), &kb);
assert!(!gate.load());
}
#[test]
fn dispatch_hook_mouse_match_xbutton1_press_release_drives_gate() {
let bind = fresh_binding();
bind.store(2, 0, 4);
let gate = AudioTransmitGate::new(false);
let ctx = HookContext {
gate: gate.clone(),
binding: bind,
};
let mut m = zeroed_mouse();
// XBUTTON1 = 0x0001 in the high word of mouseData.
m.mouseData = (XBUTTON1 as u32) << 16;
dispatch_hook_mouse(&ctx, WPARAM(WM_XBUTTONDOWN as usize), &m);
assert!(gate.load());
dispatch_hook_mouse(&ctx, WPARAM(WM_XBUTTONUP as usize), &m);
assert!(!gate.load());
}
#[test]
fn dispatch_hook_mouse_match_xbutton2_press_release_drives_gate() {
let bind = fresh_binding();
bind.store(2, 0, 5);
let gate = AudioTransmitGate::new(false);
let ctx = HookContext {
gate: gate.clone(),
binding: bind,
};
let mut m = zeroed_mouse();
m.mouseData = (XBUTTON2 as u32) << 16;
dispatch_hook_mouse(&ctx, WPARAM(WM_XBUTTONDOWN as usize), &m);
assert!(gate.load());
dispatch_hook_mouse(&ctx, WPARAM(WM_XBUTTONUP as usize), &m);
assert!(!gate.load());
}
#[test]
fn dispatch_hook_mouse_wrong_xbutton_is_ignored() {
let bind = fresh_binding();
bind.store(2, 0, 4); // bound to XBUTTON1
let gate = AudioTransmitGate::new(false);
let ctx = HookContext {
gate: gate.clone(),
binding: bind,
};
let mut m = zeroed_mouse();
m.mouseData = (XBUTTON2 as u32) << 16; // wrong button
dispatch_hook_mouse(&ctx, WPARAM(WM_XBUTTONDOWN as usize), &m);
assert!(!gate.load());
}
}