hex/src/suppression/tests.rs
Dax 7a2c78ace2
feat(labs): model switch shortcut (#2679)
One key swaps the dictation model and language with a saved other one, and back, installed only, through the same save and reload path the speech-model picker uses. Requested in #2654.
2026-11-24 12:57:57 -05:00

5303 lines
185 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use super::*;
use crate::app_settings::{
COMMAND_KEY_MASK, CONTROL_KEY_MASK, FUNCTION_KEY_MASK, LEFT_COMMAND_MASK, LEFT_CONTROL_MASK,
LEFT_OPTION_MASK, MICROPHONE_KEY_CODE, MicrophoneKey, MicrophoneKeyTap, OPTION_KEY_MASK,
RIGHT_OPTION_MASK, SHIFT_KEY_MASK,
};
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
fn CGEventCreate(source: *mut c_void) -> EventRef;
fn CGEventSetTimestamp(event: EventRef, timestamp: u64);
fn CGEventSetType(event: EventRef, event_type: u32);
fn CGEventSetFlags(event: EventRef, flags: u64);
fn CGEventSetIntegerValueField(event: EventRef, field: u32, value: i64);
}
fn test_tap_context(takes_escape: bool) -> (EventTapContext, mpsc::Receiver<ObservedInputEvent>) {
let (sender, receiver) = mpsc::channel();
let context = EventTapContext {
sink: Arc::new(InputSink::new(sender, PendingInputEvents::default())),
activity: InputActivity::default(),
policy: Arc::new(Mutex::new(TapPolicy::for_listener(
false,
takes_escape,
false,
None,
))),
key_tap: AtomicPtr::new(ptr::null_mut()),
observation_tap: AtomicPtr::new(ptr::null_mut()),
physical_tap: AtomicPtr::new(ptr::null_mut()),
dictation_key_tap: AtomicPtr::new(ptr::null_mut()),
microphone_key: Mutex::new(crate::app_settings::MicrophoneKey::default()),
shortcut_suppression: Mutex::new(ShortcutSuppression::default()),
};
(context, receiver)
}
// Drive the real callback without installing a tap or posting global input.
fn callback_input(timestamps_and_events: &[(u64, InputEvent)]) -> Vec<ObservedInputEvent> {
callback_input_with(false, timestamps_and_events)
}
fn callback_input_with(
takes_escape: bool,
timestamps_and_events: &[(u64, InputEvent)],
) -> Vec<ObservedInputEvent> {
let (mut context, receiver) = test_tap_context(takes_escape);
for &(timestamp, input) in timestamps_and_events {
// SAFETY: This locally owned event and context live through the callback.
unsafe {
let event = CGEventCreate(ptr::null_mut());
assert!(!event.is_null());
CGEventSetTimestamp(event, timestamp);
let event_type = match input {
InputEvent::Flags(flags) => {
CGEventSetType(event, EVENT_FLAGS_CHANGED);
CGEventSetFlags(event, flags);
EVENT_FLAGS_CHANGED
}
InputEvent::Key { code, down, flags } => {
CGEventSetType(event, if down { EVENT_KEY_DOWN } else { EVENT_KEY_UP });
CGEventSetFlags(event, flags);
CGEventSetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE, i64::from(code));
assert_eq!(
CGEventGetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE),
i64::from(code)
);
if down { EVENT_KEY_DOWN } else { EVENT_KEY_UP }
}
_ => panic!("expected a keyboard event"),
};
let returned = event_callback(
ptr::null_mut(),
event_type,
event,
(&mut context as *mut EventTapContext).cast(),
);
CFRelease(event.cast_const());
if matches!(input, InputEvent::Flags(_)) {
assert_eq!(returned, event, "modifier observation must remain passive");
}
}
}
receiver.try_iter().collect()
}
#[cfg(hex_capture)]
#[test]
fn a_capture_logs_only_keys_that_reach_the_app() {
const ESCAPE: u16 = 53;
const K: u16 = 40;
let now = capture_time().as_nanos();
let tapped = crate::capture_host::tapped_while(|| {
callback_input_with(
true,
&[
// Hex takes Escape (the capsule's picker): it consumes it.
(
now,
InputEvent::Key {
code: ESCAPE,
down: true,
flags: 0,
},
),
// ⌘K goes to the app, so the capture logs it.
(
now + 1,
InputEvent::Key {
code: K,
down: true,
flags: COMMAND_KEY_MASK,
},
),
],
);
});
assert!(
matches!(
tapped.as_slice(),
[crate::capture_host::Tapped::Key { code: K, .. }]
),
"{tapped:?}"
);
}
#[test]
fn a_key_latched_only_in_session_state_reads_as_released() {
const TAB: u16 = 48;
let state = |session: bool, hid: bool| {
move |source: u32, _: u16| {
if source == COMBINED_SESSION_STATE {
session
} else {
hid
}
}
};
// Command-Tab swallowed Tab's release: the session still says down,
// the physical keyboard says up (#612).
assert!(!reads_held(TAB, state(true, false)));
assert!(reads_held(TAB, state(true, true)));
assert!(!reads_held(TAB, state(false, true)));
}
#[test]
fn callback_timestamps_preserve_nanoseconds_and_short_tap_discard() {
let start = 60_000_000_000;
let edges = callback_input(&[
(start, InputEvent::Flags(OPTION_KEY_MASK)),
(start + 80_000_000, InputEvent::Flags(0)),
]);
assert_eq!(edges.len(), 2);
let mut capture = crate::dictation::DictationCapture::new(16_000);
capture.start_at(edges[0].capture_at);
assert!(matches!(
capture.finish(edges[1].capture_at),
crate::dictation::Finish::Discard
));
assert_eq!(edges[0].capture_at.as_nanos(), start);
assert_eq!(edges[1].capture_at.as_nanos(), start + 80_000_000);
}
#[test]
fn callback_press_reaches_intentional_hold_on_the_audio_clock() {
let now = capture_time();
let press = callback_input(&[(now.as_nanos(), InputEvent::Flags(OPTION_KEY_MASK))])[0];
// This capture has no recording environment, so threshold checks cannot mute audio.
let mut capture = crate::dictation::DictationCapture::new(16_000);
capture.start_at(press.capture_at);
assert!(!capture.become_intentional(now + Duration::from_millis(299)));
assert!(capture.become_intentional(now + Duration::from_millis(300)));
assert!(!capture.become_intentional(now + Duration::from_millis(301)));
}
#[test]
fn suspended_key_tracking_preserves_held_keys_and_observes_releases() {
let now = capture_time();
let ordinary = |down| InputEvent::Key {
code: 0,
down,
flags: 0,
};
for pressed_before in [false, true] {
for released_during in [false, true] {
let mut hotkey = test_hotkey(false, now);
if pressed_before {
assert_eq!(hotkey.process(ordinary(true), now), None);
} else {
assert_eq!(hotkey.track_key_state(ordinary(true), now), Some(true));
}
hotkey.track_key_state(InputEvent::Flags(OPTION_KEY_MASK), now);
hotkey.track_key_state(InputEvent::Flags(0), now);
if released_during {
hotkey.track_key_state(ordinary(false), now);
}
assert!(!hotkey.is_recording());
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
now + Duration::from_secs(1)
),
released_during.then_some(HotkeyAction::Start)
);
if !released_during {
hotkey.process(InputEvent::Flags(0), now + Duration::from_secs(1));
hotkey.process(ordinary(false), now + Duration::from_secs(1));
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
now + Duration::from_secs(2)
),
Some(HotkeyAction::Start)
);
}
}
}
}
#[test]
fn suspended_escape_and_double_taps_never_activate_a_gesture() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
for event in [
InputEvent::Flags(OPTION_KEY_MASK),
InputEvent::Flags(0),
InputEvent::Flags(OPTION_KEY_MASK),
InputEvent::Flags(0),
InputEvent::Key {
code: ESCAPE_KEY_CODE,
down: true,
flags: 0,
},
] {
hotkey.track_key_state(event, now);
assert!(!hotkey.is_recording());
}
assert_eq!(
hotkey.process(
InputEvent::Key {
code: ESCAPE_KEY_CODE,
down: false,
flags: 0
},
now
),
None
);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(InputEvent::Flags(0), now + Duration::from_millis(80)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn callback_release_trims_delayed_audio_at_the_physical_boundary() {
let start = 60_000_000_000;
let edges = callback_input(&[
(start, InputEvent::Flags(OPTION_KEY_MASK)),
(start + 1_000_000_000, InputEvent::Flags(0)),
]);
// Handle both edges late: the timeline already includes post-release audio.
let mut capture = ingest_timeline(CaptureInstant::from_nanos(start));
capture.start_at(edges[0].capture_at);
let crate::dictation::Finish::Transcribe(clip) = capture.finish(edges[1].capture_at) else {
panic!("one second hold must transcribe");
};
assert_eq!(clip.duration_ms(), 1_450);
let samples = clip.into_transcription_samples();
assert_eq!(&samples[..7_200], &[0.25; 7_200]);
assert_eq!(&samples[7_200..], &[0.5; 16_000]);
}
#[test]
fn callback_double_tap_locks_for_modifier_and_key_bindings() {
let command = COMMAND_KEY_MASK | crate::app_settings::RIGHT_COMMAND_MASK;
let right_command = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers {
command: Some(crate::app_settings::ModifierSide::Right),
..Default::default()
},
key_code: None,
};
let key_chord = RuntimeHotkey {
key_code: Some(49),
..right_command
};
for (binding, flags) in [
(option_binding(), OPTION_KEY_MASK),
(right_command, command),
(function_binding(), FUNCTION_KEY_MASK),
(key_chord, command),
] {
let start = 60_000_000_000;
let mut hotkey = DictationHotkey::with_binding(false, capture_time(), true, binding);
let press = binding
.key_code
.map_or(InputEvent::Flags(flags), |code| InputEvent::Key {
code,
down: true,
flags,
});
let release = binding
.key_code
.map_or(InputEvent::Flags(0), |code| InputEvent::Key {
code,
down: false,
flags,
});
let edges = callback_input(&[
(start, press),
(start + 80_000_000, release),
(start + 180_000_000, press),
(start + 260_000_000, release),
(start + 1_000_000_000, press),
(start + 1_080_000_000, release),
]);
let mut capture = ingest_timeline(CaptureInstant::from_nanos(start));
let mut discarded = 0;
let mut clips = Vec::new();
let actions: Vec<_> = edges
.into_iter()
.map(|edge| {
let action = hotkey.process(edge.event, edge.capture_at);
match action {
Some(HotkeyAction::Start) => capture.start_at(edge.capture_at),
Some(HotkeyAction::Finish) => match capture.finish(edge.capture_at) {
crate::dictation::Finish::Discard => discarded += 1,
crate::dictation::Finish::Transcribe(clip) => clips.push(clip),
},
None => {}
_ => panic!("unexpected hotkey action"),
}
assert_eq!(hotkey.is_recording(), capture.is_recording());
action
})
.collect();
assert_eq!(
actions,
vec![
Some(HotkeyAction::Start),
Some(HotkeyAction::Finish),
Some(HotkeyAction::Start),
None,
Some(HotkeyAction::Finish),
None,
]
);
assert!(!hotkey.is_recording());
assert_eq!(discarded, 1);
assert_eq!(clips.len(), 1);
let clip = clips.pop().unwrap();
assert_eq!(clip.duration_ms(), 1_270);
let samples = clip.into_transcription_samples();
assert_eq!(&samples[..4_320], &[0.25; 4_320]);
assert_eq!(&samples[4_320..], &[0.5; 16_000]);
}
}
#[test]
fn function_keys_match_despite_the_fn_flag_macos_adds() {
const F14: u16 = 107;
let bare = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::default(),
key_code: Some(F14),
};
let command = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers {
command: Some(crate::app_settings::ModifierSide::Either),
..Default::default()
},
key_code: Some(F14),
};
for (binding, held) in [(bare, 0), (command, COMMAND_KEY_MASK)] {
let flags = held | FUNCTION_KEY_MASK;
assert!(binding.matches_key_press(F14, flags));
assert!(!binding.matches_key_press(F14, held | SHIFT_KEY_MASK | FUNCTION_KEY_MASK));
let now = capture_time();
let mut hotkey = DictationHotkey::with_binding(false, now, false, binding);
if held != 0 {
assert_eq!(hotkey.process(InputEvent::Flags(held), now), None);
}
let key = |down| InputEvent::Key {
code: F14,
down,
flags,
};
assert_eq!(
hotkey.process(key(true), now + Duration::from_millis(10)),
Some(HotkeyAction::Start)
);
// Autorepeat carries the same flags and is not a chord.
assert_eq!(
hotkey.process(key(true), now + Duration::from_millis(100)),
None
);
assert_eq!(
hotkey.process(key(false), now + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
// Fn stays significant for keys macOS does not mark with it.
let space = RuntimeHotkey {
key_code: Some(49),
..command
};
assert!(!space.matches_key_press(49, COMMAND_KEY_MASK | FUNCTION_KEY_MASK));
}
/// Issue 181: a laptop keyboard's microphone (dictation) key reports virtual
/// key code 176 with SecondaryFn always set (observed flags 0x800100), so a
/// lone 176 binding ignores that flag like a function key does. Fn stays
/// significant everywhere else.
#[test]
fn the_microphone_key_matches_with_the_fn_flag_macos_adds() {
// 0x800100: SecondaryFn plus NonCoalesced, as the key was observed.
const OBSERVED: u64 = 0x800100;
let microphone = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::default(),
key_code: Some(MICROPHONE_KEY_CODE),
};
assert!(microphone.matches_key_press(MICROPHONE_KEY_CODE, OBSERVED));
assert!(!microphone.matches_key_press(MICROPHONE_KEY_CODE, OBSERVED | SHIFT_KEY_MASK));
assert!(
!microphone.matches_key_press(49, OBSERVED),
"space is another key"
);
let now = capture_time();
let mut hotkey = DictationHotkey::with_binding(false, now, false, microphone);
let key = |down| InputEvent::Key {
code: MICROPHONE_KEY_CODE,
down,
flags: OBSERVED,
};
assert_eq!(
hotkey.process(key(true), now + Duration::from_millis(10)),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(key(false), now + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
// Fn is still significant for a key macOS does not mark with it.
let space = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::default(),
key_code: Some(49),
};
assert!(!space.matches_key_press(49, FUNCTION_KEY_MASK));
}
/// Issue 181: the session tap takes a bound microphone key's press and its
/// release, and those feed the same dictation state machine every other key
/// does.
#[test]
fn the_microphone_key_taken_at_the_session_tap_starts_and_finishes_a_dictation() {
const OBSERVED: u64 = 0x800100;
let mut microphone_key = MicrophoneKey::default();
let mut hotkey = DictationHotkey::with_binding(
false,
capture_time(),
false,
RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::default(),
key_code: Some(MICROPHONE_KEY_CODE),
},
);
// Lab on, bound, not recording.
let press = microphone_key.take(MICROPHONE_KEY_CODE, true, true, false, false, true);
assert_eq!(press, MicrophoneKeyTap::Listener { down: true });
let now = capture_time();
assert_eq!(
hotkey.process(
InputEvent::Key {
code: MICROPHONE_KEY_CODE,
down: true,
flags: OBSERVED,
},
now + Duration::from_millis(10),
),
Some(HotkeyAction::Start)
);
// The release is the tap's even though nothing is bound by the time it
// arrives.
let release = microphone_key.take(MICROPHONE_KEY_CODE, false, true, false, false, false);
assert_eq!(release, MicrophoneKeyTap::Listener { down: false });
assert_eq!(
hotkey.process(
InputEvent::Key {
code: MICROPHONE_KEY_CODE,
down: false,
flags: OBSERVED,
},
now + Duration::from_secs(1),
),
Some(HotkeyAction::Finish)
);
}
#[test]
fn callback_hold_and_double_tap_boundaries_are_milliseconds() {
for duration_ms in [299, 300, 301] {
let start = 60_000_000_000;
let press = InputEvent::Flags(OPTION_KEY_MASK);
let release = InputEvent::Flags(0);
let edges = callback_input(&[(start, press), (start + duration_ms * 1_000_000, release)]);
let mut capture = crate::dictation::DictationCapture::new(16_000);
capture.start_at(edges[0].capture_at);
assert_eq!(
matches!(
capture.finish(edges[1].capture_at),
crate::dictation::Finish::Discard
),
duration_ms < 300
);
let edges = callback_input(&[
(start, press),
(start + 80_000_000, release),
(start + 180_000_000, press),
(start + (80 + duration_ms) * 1_000_000, release),
]);
let mut hotkey = test_hotkey(false, capture_time());
for edge in edges {
hotkey.process(edge.event, edge.capture_at);
}
assert_eq!(hotkey.is_recording(), duration_ms < 300);
}
}
fn mouse_hotkeys() -> RuntimeHotkeys {
RuntimeHotkeys {
dictation: HotkeyBinding {
modifiers: Default::default(),
key: crate::app_settings::HotkeyKey::mouse(3),
}
.runtime(),
paste_last: None,
..RuntimeHotkeys::default()
}
}
#[test]
fn mouse_events_reach_the_filtering_tap_only_while_a_mouse_shortcut_is_bound() {
// Idle clicks and drags on a filtering tap broke dragging windows
// between displays and Spaces (#1215).
assert!(!filters_mouse(RuntimeHotkeys::default()));
let (key, observation) = tap_masks(false);
assert_eq!(key & MOUSE_MASK, 0);
assert_eq!(observation & MOUSE_MASK, MOUSE_MASK);
assert!(filters_mouse(mouse_hotkeys()));
let (key, observation) = tap_masks(true);
assert_eq!(key & MOUSE_MASK, MOUSE_MASK);
assert_eq!(observation & MOUSE_MASK, 0);
for filter in [false, true] {
let (key, observation) = tap_masks(filter);
assert_eq!(key & KEY_MASK, KEY_MASK);
assert_eq!(observation & OBSERVATION_MASK, OBSERVATION_MASK);
}
// Labs › More dictation shortcuts' mouse buttons filter clicks too.
let mut extra_mouse = RuntimeHotkeys::default();
extra_mouse.extra_dictation[0] = Some(
HotkeyBinding {
modifiers: Default::default(),
key: crate::app_settings::HotkeyKey::mouse(3),
}
.runtime(),
);
assert!(filters_mouse(extra_mouse));
let mouse_code = crate::app_settings::HotkeyKey::mouse_code(3).expect("mouse code");
assert!(matches!(
mouse_input(3, true, 0, extra_mouse),
Some(InputEvent::Key {
code,
down: true,
flags: 0,
}) if code == mouse_code
));
}
#[test]
fn mouse_hold_and_release_use_the_dictation_state_machine() {
let now = capture_time();
let bindings = mouse_hotkeys();
let mut hotkey = DictationHotkey::new(now, false, bindings.dictation);
assert_eq!(
hotkey.process(mouse_input(3, true, 0, bindings).unwrap(), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(
mouse_input(3, false, 0, bindings).unwrap(),
now + Duration::from_secs(1)
),
Some(HotkeyAction::Finish)
);
assert!(matches!(
mouse_input(0, true, 0, bindings),
Some(InputEvent::MouseDown)
));
assert!(mouse_input(0, false, 0, bindings).is_none());
}
#[test]
fn mouse_toggle_uses_the_same_capture_controls() {
let now = capture_time();
let bindings = mouse_hotkeys();
let mut hotkey = DictationHotkey::new(now, false, bindings.dictation);
hotkey.set_toggle(true);
assert_eq!(
hotkey.process(mouse_input(3, true, 0, bindings).unwrap(), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(
mouse_input(3, false, 0, bindings).unwrap(),
now + Duration::from_millis(100)
),
None
);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(
InputEvent::Key {
code: ESCAPE_KEY_CODE,
down: true,
flags: 0
},
now + Duration::from_secs(1)
),
None
);
assert!(hotkey.is_recording());
}
#[test]
fn mouse_held_during_stale_keyboard_recovery_is_not_forgotten() {
let now = capture_time();
let bindings = mouse_hotkeys();
let mut hotkey = DictationHotkey::new(now, false, bindings.dictation);
let code = bindings.dictation.key_code.unwrap();
hotkey.state = State::Dirty;
hotkey.held.press(0, now);
hotkey.held.press(code, now);
for millis in [0, 200] {
hotkey.recover_stale_keys_with(
|| now + Duration::from_millis(millis),
|| 0,
|key| key == code,
);
}
assert!(hotkey.held.contains_key(code));
assert!(matches!(hotkey.state, State::Dirty));
recover_after_neutral_window(&mut hotkey, now + Duration::from_secs(1), 0);
assert!(hotkey.held.keys_empty());
}
#[test]
fn mouse_double_tap_locks_and_a_fresh_press_finishes() {
let now = capture_time();
let bindings = mouse_hotkeys();
let mut hotkey = DictationHotkey::new(now, true, bindings.dictation);
for (millis, down, expected) in [
(0, true, Some(HotkeyAction::Start)),
(50, false, Some(HotkeyAction::Finish)),
(100, true, Some(HotkeyAction::Start)),
(150, false, None),
(1000, true, Some(HotkeyAction::Finish)),
] {
assert_eq!(
hotkey.process(
mouse_input(3, down, 0, bindings).unwrap(),
now + Duration::from_millis(millis)
),
expected
);
}
}
#[test]
fn mouse_release_stays_balanced_after_its_binding_is_removed() {
let bindings = mouse_hotkeys();
let mut suppression = ShortcutSuppression::default();
assert!(suppression.process_all(
mouse_input(3, true, 0, bindings).unwrap(),
bindings,
true,
false
));
let removed = RuntimeHotkeys::default();
assert!(mouse_input(3, false, 0, removed).is_none());
let release = suppression.tracked_mouse_release(3, 0).unwrap();
assert!(suppression.process_all(release, removed, true, false));
assert!(suppression.tracked_mouse_release(3, 0).is_none());
assert!(!suppression.suppresses_mouse_drag(3));
}
#[test]
fn mouse_suppression_balances_release_and_drag_even_after_modifiers_change() {
let mut bindings = mouse_hotkeys();
bindings.dictation.modifiers = crate::app_settings::HotkeyModifiers::option();
let mut suppression = ShortcutSuppression::default();
let activity = InputActivity::default();
let down = mouse_input(3, true, OPTION_KEY_MASK, bindings).unwrap();
let suppressed = suppression.process_all(down, bindings, true, false);
assert!(suppressed);
activity.observe(down, suppressed);
assert_eq!(activity.revision(), 0);
assert!(suppression.suppresses_mouse_drag(3));
assert!(!suppression.suppresses_mouse_drag(0));
assert!(suppression.process_all(
mouse_input(3, false, 0, bindings).unwrap(),
bindings,
true,
false
));
assert!(!suppression.suppresses_mouse_drag(3));
// Wrong modifiers and failed delivery must leave the ordinary click alone.
for (flags, delivered) in [(0, true), (OPTION_KEY_MASK, false)] {
assert!(!suppression.process_all(
mouse_input(3, true, flags, bindings).unwrap(),
bindings,
delivered,
false
));
assert!(!suppression.suppresses_mouse_drag(3));
assert!(!suppression.process_all(
mouse_input(3, false, flags, bindings).unwrap(),
bindings,
true,
false
));
}
}
const NO_FLAGS: u64 = 0;
fn capture_time() -> CaptureInstant {
CaptureInstant::from_nanos(60_000_000_000)
}
// One second of 0.25 from `start`, one second of 0.5, then half a second of
// 0.75 past the release at `start + 1s`, so clips expose their boundaries.
fn ingest_timeline(start: CaptureInstant) -> crate::dictation::DictationCapture {
let mut capture = crate::dictation::DictationCapture::new(16_000);
capture.ingest(&vec![0.25; 16_000], start);
capture.ingest(&vec![0.5; 16_000], start + Duration::from_secs(1));
capture.ingest(&vec![0.75; 8_000], start + Duration::from_millis(1_500));
capture
}
fn option_binding() -> RuntimeHotkey {
RuntimeHotkey {
modifiers: crate::app_settings::modifiers_from_flags(OPTION_KEY_MASK),
key_code: None,
}
}
fn function_binding() -> RuntimeHotkey {
RuntimeHotkey {
modifiers: crate::app_settings::modifiers_from_flags(FUNCTION_KEY_MASK),
key_code: None,
}
}
#[test]
fn consumed_dictation_keys_preserve_continuation_but_typing_and_clicks_do_not() {
for flags in [NO_FLAGS, SHIFT_KEY_MASK] {
let activity = InputActivity::default();
let mut suppression = ShortcutSuppression::default();
let binding = RuntimeHotkey {
modifiers: crate::app_settings::modifiers_from_flags(flags),
key_code: Some(96),
};
let revision = activity.revision();
for down in [true, true, false] {
let input = InputEvent::Key {
code: 96,
down,
flags,
};
let suppressed = suppression.process(input, 47, binding, true);
assert!(suppressed);
activity.observe(input, suppressed);
}
assert_eq!(activity.revision(), revision);
let typed = InputEvent::Key {
code: 0,
down: true,
flags: NO_FLAGS,
};
activity.observe(typed, suppression.process(typed, 47, binding, true));
assert_eq!(activity.revision(), revision + 1);
activity.observe(InputEvent::MouseDown, false);
assert_eq!(activity.revision(), revision + 2);
let undelivered = InputEvent::Key {
code: 96,
down: true,
flags,
};
activity.observe(
undelivered,
suppression.process(undelivered, 47, binding, false),
);
assert_eq!(activity.revision(), revision + 3);
}
}
#[test]
fn standalone_function_modifier_starts_and_finishes_dictation() {
let now = capture_time();
let mut hotkey = DictationHotkey::with_binding(false, now, true, function_binding());
assert_eq!(
hotkey.process(InputEvent::Flags(FUNCTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), now + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn globe_key_events_are_not_a_chord_with_the_function_shortcut() {
let now = capture_time();
let globe = |down| InputEvent::Key {
code: GLOBE_KEY_CODE,
down,
flags: FUNCTION_KEY_MASK,
};
let hid_globe = |at| InputEvent::PhysicalKeyDown {
code: GLOBE_KEY_CODE,
timing: HidTiming {
raw: 0,
clock: HidClock::Arrival,
received_at: at,
},
};
let mut hotkey = DictationHotkey::with_binding(false, now, false, function_binding());
hotkey.set_toggle(true);
let ms = |millis| now + Duration::from_millis(millis);
for (at, event, expected) in [
(ms(0), globe(true), None),
(
ms(0),
InputEvent::Flags(FUNCTION_KEY_MASK),
Some(HotkeyAction::Start),
),
(ms(60), hid_globe(ms(60)), None),
(ms(80), globe(false), None),
(ms(90), InputEvent::Flags(NO_FLAGS), None),
(ms(1_000), globe(true), None),
(
ms(1_000),
InputEvent::Flags(FUNCTION_KEY_MASK),
Some(HotkeyAction::Finish),
),
] {
assert_eq!(hotkey.process(event, at), expected);
}
let hotkeys = RuntimeHotkeys {
dictation: function_binding(),
..RuntimeHotkeys::default()
};
assert!(!is_chord_evidence(
GLOBE_KEY_CODE,
FUNCTION_KEY_MASK,
hotkeys
));
// Another key held with Fn is still a chord, and Globe is evidence for
// a shortcut without Fn.
assert!(is_chord_evidence(0, FUNCTION_KEY_MASK, hotkeys));
let option = RuntimeHotkeys {
dictation: option_binding(),
..RuntimeHotkeys::default()
};
assert!(is_chord_evidence(GLOBE_KEY_CODE, FUNCTION_KEY_MASK, option));
// A raw or extra shortcut holding Fn owns Globe too.
let raw = RuntimeHotkeys {
raw_dictation: Some(function_binding()),
..RuntimeHotkeys::default()
};
assert!(!is_chord_evidence(GLOBE_KEY_CODE, FUNCTION_KEY_MASK, raw));
assert!(is_chord_evidence(0, FUNCTION_KEY_MASK, raw));
let extra = RuntimeHotkeys {
extra_dictation: [Some(function_binding()), None, None, None],
..RuntimeHotkeys::default()
};
assert!(!is_chord_evidence(GLOBE_KEY_CODE, FUNCTION_KEY_MASK, extra));
assert!(is_chord_evidence(0, FUNCTION_KEY_MASK, extra));
// Only the dictation shortcuts own Globe: any other shortcut holding Fn
// leaves it as chord evidence.
let paste_last = RuntimeHotkeys {
paste_last: Some(function_binding()),
..RuntimeHotkeys::default()
};
assert!(is_chord_evidence(
GLOBE_KEY_CODE,
FUNCTION_KEY_MASK,
paste_last
));
}
#[test]
fn modifier_only_shortcuts_pass_through_after_delivery() {
for (flags, binding) in [
(OPTION_KEY_MASK, option_binding()),
(FUNCTION_KEY_MASK, function_binding()),
] {
let mut suppression = ShortcutSuppression::default();
assert!(!suppression.process(InputEvent::Flags(flags), 47, binding, true));
assert!(!suppression.process(InputEvent::Flags(NO_FLAGS), 47, binding, true));
}
}
fn test_hotkey(trigger_down: bool, now: CaptureInstant) -> DictationHotkey {
DictationHotkey::with_binding(trigger_down, now, true, option_binding())
}
fn toggle_hotkey(now: CaptureInstant, tap_or_hold: bool) -> DictationHotkey {
let mut hotkey = test_hotkey(false, now);
hotkey.set_toggle(true);
hotkey.tap_or_hold = if tap_or_hold { || true } else { || false };
hotkey
}
#[test]
fn tap_or_hold_locks_a_short_tap_and_finishes_a_long_hold_on_release() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let press = InputEvent::Flags(OPTION_KEY_MASK);
let release = InputEvent::Flags(NO_FLAGS);
// A short tap locks, and the next press finishes, as plain Toggle.
let mut hotkey = toggle_hotkey(now, true);
assert_eq!(hotkey.process(press, ms(0)), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(release, ms(299)), None);
assert!(hotkey.is_locked());
assert_eq!(hotkey.process(press, ms(2_000)), Some(HotkeyAction::Finish));
assert_eq!(hotkey.process(release, ms(2_080)), None);
assert!(!hotkey.is_recording());
// A hold past the threshold finishes on release.
let mut hotkey = toggle_hotkey(now, true);
assert_eq!(hotkey.process(press, ms(0)), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(release, ms(300)), Some(HotkeyAction::Finish));
assert!(!hotkey.is_recording());
// The next press starts afresh.
assert_eq!(hotkey.process(press, ms(2_000)), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(release, ms(4_000)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn tap_or_hold_still_discards_a_chord_and_off_keeps_plain_toggle() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let press = InputEvent::Flags(OPTION_KEY_MASK);
let mut hotkey = toggle_hotkey(now, true);
assert_eq!(hotkey.process(press, ms(0)), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(
InputEvent::Key {
code: 0,
down: true,
flags: OPTION_KEY_MASK,
},
ms(100)
),
Some(HotkeyAction::Discard(DiscardCause::Key))
);
assert!(!hotkey.is_recording());
// Off, a long hold still locks.
let mut hotkey = toggle_hotkey(now, false);
assert_eq!(hotkey.process(press, ms(0)), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(2_000)), None);
assert!(hotkey.is_locked());
// Hold mode ignores it: a long hold finishes either way.
let mut hotkey = test_hotkey(false, now);
hotkey.tap_or_hold = || true;
assert_eq!(hotkey.process(press, ms(0)), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), ms(2_000)),
Some(HotkeyAction::Finish)
);
}
fn key_binding(code: u16) -> RuntimeHotkey {
RuntimeHotkey {
modifiers: Default::default(),
key_code: Some(code),
}
}
fn shift_space_binding() -> RuntimeHotkey {
RuntimeHotkey {
modifiers: crate::app_settings::modifiers_from_flags(SHIFT_KEY_MASK),
key_code: Some(49),
}
}
fn shift_space_event(down: bool) -> InputEvent {
InputEvent::Key {
code: 49,
down,
flags: SHIFT_KEY_MASK,
}
}
fn recover_after_neutral_window(
hotkey: &mut DictationHotkey,
start: CaptureInstant,
flags: u64,
) -> CaptureInstant {
let repaired = start + STALE_KEY_NEUTRAL_DURATION;
hotkey.recover_stale_keys_with(|| start, || flags, |_| false);
hotkey.recover_stale_keys_with(|| repaired, || flags, |_| false);
repaired
}
#[test]
fn stale_key_recovery_restores_a_fresh_hold_without_changing_its_boundaries() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
let down = InputEvent::Key {
code: 0,
down: true,
flags: 0,
};
assert_eq!(hotkey.process(down, now), None);
// The ordinary key's release never reached the reducer.
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
None
);
let first = now + Duration::from_secs(1);
hotkey.recover_stale_keys_with(|| first, || 0, |_| false);
hotkey.recover_stale_keys_with(|| first + Duration::from_millis(99), || 0, |_| false);
assert!(hotkey.held.contains_key(0));
let repaired = first + STALE_KEY_NEUTRAL_DURATION;
hotkey.recover_stale_keys_with(|| repaired, || 0, |_| false);
assert!(hotkey.held.keys_empty());
let press = repaired + Duration::from_millis(1);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), press),
Some(HotkeyAction::Start)
);
let mut capture = crate::dictation::DictationCapture::new(16_000);
capture.start_at(press);
capture.ingest(&vec![0.5; 16_000], press + Duration::from_secs(1));
let release = press + Duration::from_millis(500);
assert_eq!(
hotkey.process(InputEvent::Flags(0), release),
Some(HotkeyAction::Finish)
);
let crate::dictation::Finish::Transcribe(clip) = capture.finish(release) else {
panic!("the fresh hold must transcribe");
};
assert_eq!(clip.duration_ms(), 500);
}
#[test]
fn delayed_neutral_callback_after_recovery_preserves_the_next_hold() {
for double_tap_enabled in [false, true] {
for (neutral_event, offset_ms) in [
(InputEvent::Flags(0), 0),
(InputEvent::Flags(0), 100),
(
InputEvent::Key {
code: 48,
down: false,
flags: 0,
},
0,
),
(
InputEvent::Key {
code: 48,
down: false,
flags: 0,
},
100,
),
] {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.set_double_tap_enabled(double_tap_enabled);
let down = callback_input(&[(
now.as_nanos(),
InputEvent::Key {
code: 48,
down: true,
flags: COMMAND_KEY_MASK,
},
)])[0];
hotkey.process(down.event, down.capture_at);
// Two native neutral samples repair the missing key-up, but an old
// neutral release has not reached its tap callback yet.
let first_sample = now + Duration::from_secs(1);
let repaired = recover_after_neutral_window(&mut hotkey, first_sample, 0);
let neutral_at = first_sample + Duration::from_millis(offset_ms);
let neutral = callback_input(&[(neutral_at.as_nanos(), neutral_event)])[0];
assert_eq!(hotkey.process(neutral.event, neutral.capture_at), None);
for attempt in 0..3 {
let press = repaired + Duration::from_secs(1 + attempt * 2);
let release = press + Duration::from_secs(1);
let edges = callback_input(&[
(press.as_nanos(), InputEvent::Flags(OPTION_KEY_MASK)),
(release.as_nanos(), InputEvent::Flags(0)),
]);
let mut capture = ingest_timeline(press);
assert_eq!(
hotkey.process(edges[0].event, edges[0].capture_at),
Some(HotkeyAction::Start),
"attempt {attempt}, double_tap_enabled={double_tap_enabled}"
);
capture.start_at(edges[0].capture_at);
assert_eq!(
hotkey.process(edges[1].event, edges[1].capture_at),
Some(HotkeyAction::Finish)
);
let crate::dictation::Finish::Transcribe(clip) =
capture.finish(edges[1].capture_at)
else {
panic!("the hold must produce a clip");
};
assert_eq!(clip.duration_ms(), 1_450);
let samples = clip.into_transcription_samples();
assert_eq!(&samples[..7_200], &[0.25; 7_200]);
assert_eq!(&samples[7_200..], &[0.5; 16_000]);
assert!(!hotkey.is_recording());
}
}
}
}
/// Command-Tab: the app switcher swallows Tab's key-up, leaving Tab tracked.
fn command_tab(hotkey: &mut DictationHotkey, at: CaptureInstant) -> CaptureInstant {
let tab = InputEvent::Key {
code: 48,
down: true,
flags: COMMAND_KEY_MASK,
};
for (offset, event) in [
(0, InputEvent::Flags(COMMAND_KEY_MASK)),
(40, tab),
(120, InputEvent::Flags(NO_FLAGS)),
] {
assert_eq!(
hotkey.process(event, at + Duration::from_millis(offset)),
None
);
}
assert!(hotkey.held.contains_key(48));
at + Duration::from_millis(120)
}
#[test]
fn option_soon_after_command_tab_records() {
for double_tap_enabled in [false, true] {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.set_double_tap_enabled(double_tap_enabled);
let released = command_tab(&mut hotkey, now);
assert!(matches!(hotkey.state, State::Idle { .. }));
// Well inside the 100 ms that `recover_stale_keys` needs.
let press = released + Duration::from_millis(30);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), press),
Some(HotkeyAction::Start)
);
assert!(hotkey.held.keys_empty());
let mut capture = ingest_timeline(press);
capture.start_at(press);
// An older queued edge cannot finish the fresh press.
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), released), None);
assert!(hotkey.is_recording());
let release = press + Duration::from_secs(1);
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), release),
Some(HotkeyAction::Finish)
);
let crate::dictation::Finish::Transcribe(clip) = capture.finish(release) else {
panic!("the hold must transcribe");
};
assert_eq!(clip.duration_ms(), 1_450);
}
}
#[test]
fn shortcut_press_after_command_tab_from_dirty_records() {
let now = capture_time();
for binding in [option_binding(), key_binding(96)] {
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
let (press, release) = match binding.key_code {
None => (
InputEvent::Flags(OPTION_KEY_MASK),
InputEvent::Flags(NO_FLAGS),
),
Some(code) => (
InputEvent::Key {
code,
down: true,
flags: NO_FLAGS,
},
InputEvent::Key {
code,
down: false,
flags: NO_FLAGS,
},
),
};
let (extra, lift) = match binding.key_code {
None => (
OPTION_KEY_MASK | COMMAND_KEY_MASK,
InputEvent::Flags(COMMAND_KEY_MASK),
),
Some(code) => (
COMMAND_KEY_MASK,
InputEvent::Key {
code,
down: false,
flags: COMMAND_KEY_MASK,
},
),
};
// Command-Tab while holding the shortcut discards it, then the
// switcher swallows Tab's release.
assert_eq!(hotkey.process(press, now), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(InputEvent::Flags(extra), now + Duration::from_millis(50)),
Some(HotkeyAction::Discard(DiscardCause::ExtraModifier))
);
for (offset, event) in [
(
100,
InputEvent::Key {
code: 48,
down: true,
flags: extra,
},
),
(200, lift),
(250, InputEvent::Flags(NO_FLAGS)),
] {
assert_eq!(
hotkey.process(event, now + Duration::from_millis(offset)),
None
);
}
assert!(matches!(hotkey.state, State::Dirty));
let again = now + Duration::from_millis(280);
assert_eq!(hotkey.process(press, again), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(release, again + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
}
#[test]
fn stale_press_waits_for_recovery_while_anything_else_is_held() {
let now = capture_time();
let option = InputEvent::Flags(OPTION_KEY_MASK);
for keyboard in [
// Tab really is still down.
PhysicalKeyboard {
flags: || NO_FLAGS,
key_down: |code| code == 48,
},
// Another modifier went down after the press was queued.
PhysicalKeyboard {
flags: || OPTION_KEY_MASK | SHIFT_KEY_MASK,
key_down: |_| false,
},
] {
let mut hotkey = test_hotkey(false, now);
hotkey.physical = keyboard;
let released = command_tab(&mut hotkey, now);
let press = released + Duration::from_millis(30);
assert_eq!(hotkey.process(option, press), None);
assert!(hotkey.held.contains_key(48));
// The held press stays ignored; recovery rearms after release.
let release = press + Duration::from_secs(1);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), release), None);
recover_after_neutral_window(&mut hotkey, release, 0);
let next = release + Duration::from_secs(1);
assert_eq!(hotkey.process(option, next), Some(HotkeyAction::Start));
}
}
#[test]
fn a_latched_key_without_key_repeats_stops_blocking_the_shortcut() {
let now = capture_time();
let fn_down = InputEvent::Flags(FUNCTION_KEY_MASK);
let neutral = InputEvent::Flags(NO_FLAGS);
// Both system key states keep reading Tab down after its release was
// missed, and no key repeat ever arrives (#1008).
let latched_tab = PhysicalKeyboard {
flags: || NO_FLAGS,
key_down: |code| code == 48,
};
let mut hotkey = DictationHotkey::with_binding(false, now, true, function_binding());
hotkey.physical = latched_tab;
let released = command_tab(&mut hotkey, now);
let soon = released + Duration::from_secs(1);
assert_eq!(hotkey.process(fn_down, soon), None);
assert_eq!(
hotkey.process(neutral, soon + Duration::from_millis(100)),
None
);
let later = released + TRACKED_KEY_REPEAT_TIMEOUT;
assert_eq!(hotkey.process(fn_down, later), Some(HotkeyAction::Start));
assert!(hotkey.held.keys_empty());
assert_eq!(
hotkey.process(neutral, later + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
// A Tab really held keeps repeating, so it still blocks the press.
let mut hotkey = DictationHotkey::with_binding(false, now, true, function_binding());
hotkey.physical = latched_tab;
let released = command_tab(&mut hotkey, now);
let repeat = InputEvent::Key {
code: 48,
down: true,
flags: NO_FLAGS,
};
let repeated = released + Duration::from_secs(4);
assert_eq!(hotkey.process(repeat, repeated), None);
assert_eq!(
hotkey.process(neutral, repeated + Duration::from_millis(100)),
None
);
assert_eq!(
hotkey.process(fn_down, released + TRACKED_KEY_REPEAT_TIMEOUT),
None
);
assert!(hotkey.held.contains_key(48));
}
#[test]
fn stale_press_requires_a_neutral_keyboard_after_the_tracked_keys() {
let now = capture_time();
// A key pressed alone and then Option is a chord even if the key
// reads up by the time the press is processed.
let mut hotkey = test_hotkey(false, now);
let tab = InputEvent::Key {
code: 48,
down: true,
flags: NO_FLAGS,
};
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), now), None);
assert_eq!(hotkey.process(tab, now + Duration::from_millis(10)), None);
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
now + Duration::from_millis(40)
),
None
);
// Shift went down and up again while Option-Command was assembled.
let binding = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::option_command(),
key_code: None,
};
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
let released = command_tab(&mut hotkey, now);
for (offset, flags) in [
(10, SHIFT_KEY_MASK),
(20, SHIFT_KEY_MASK | OPTION_KEY_MASK),
(30, OPTION_KEY_MASK),
(40, OPTION_KEY_MASK | COMMAND_KEY_MASK),
] {
assert_eq!(
hotkey.process(
InputEvent::Flags(flags),
released + Duration::from_millis(offset)
),
None
);
}
// Without Shift, the same chord starts.
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
let released = command_tab(&mut hotkey, now);
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
released + Duration::from_millis(10)
),
None
);
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK | COMMAND_KEY_MASK),
released + Duration::from_millis(20)
),
Some(HotkeyAction::Start)
);
}
#[test]
fn stale_press_finishes_a_lock_and_leaves_escape_unchanged() {
let now = capture_time();
let option = InputEvent::Flags(OPTION_KEY_MASK);
let neutral = InputEvent::Flags(NO_FLAGS);
let escape = |down| InputEvent::Key {
code: ESCAPE_KEY_CODE,
down,
flags: NO_FLAGS,
};
// Command-Tab while locked: the next press finishes the lock at once.
let mut hotkey = test_hotkey(false, now);
assert!(hotkey.lock());
let released = command_tab(&mut hotkey, now);
assert!(hotkey.is_locked());
let press = released + Duration::from_millis(30);
assert_eq!(hotkey.process(option, press), Some(HotkeyAction::Finish));
assert!(!hotkey.is_recording());
assert!(hotkey.held.keys_empty());
// An older queued edge cannot restart it.
assert_eq!(hotkey.process(option, released), None);
assert_eq!(
hotkey.process(neutral, press + Duration::from_millis(80)),
None
);
assert_eq!(
hotkey.process(option, press + Duration::from_secs(1)),
Some(HotkeyAction::Start)
);
// Escape leaves a lock that tracks a stale key recording.
let mut hotkey = test_hotkey(false, now);
assert!(hotkey.lock());
let released = command_tab(&mut hotkey, now);
assert_eq!(
hotkey.process(escape(true), released + Duration::from_millis(50)),
None
);
assert!(hotkey.is_locked());
// After a resynchronized press, double-tap lock behaves as it does for
// any fresh press, and Escape ends nothing.
let mut hotkey = test_hotkey(false, now);
let released = command_tab(&mut hotkey, now);
let first = released + Duration::from_millis(30);
let ms = |offset| first + Duration::from_millis(offset);
assert_eq!(hotkey.process(option, first), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(neutral, ms(80)), Some(HotkeyAction::Finish));
assert_eq!(hotkey.process(option, ms(180)), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(neutral, ms(260)), None);
assert!(hotkey.is_locked());
assert_eq!(hotkey.process(escape(true), ms(1_000)), None);
assert_eq!(hotkey.process(escape(false), ms(1_050)), None);
assert!(hotkey.is_locked());
assert_eq!(
hotkey.process(option, ms(2_000)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn typing_after_command_tab_does_not_block_the_next_press() {
let now = capture_time();
let key = |code, down, flags| InputEvent::Key { code, down, flags };
for binding in [option_binding(), key_binding(96)] {
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
let released = command_tab(&mut hotkey, now);
if binding.key_code.is_some() {
// Tracked keys block a key binding only from Dirty, as a
// Command-Tab during the press leaves it.
hotkey.suppress_until_release();
}
// "hI" and Return in the new app.
for (offset, event) in [
(20, key(4, true, NO_FLAGS)),
(40, key(4, false, NO_FLAGS)),
(60, InputEvent::Flags(SHIFT_KEY_MASK)),
(70, key(34, true, SHIFT_KEY_MASK)),
(90, key(34, false, SHIFT_KEY_MASK)),
(100, InputEvent::Flags(NO_FLAGS)),
(150, key(36, true, NO_FLAGS)),
(170, key(36, false, NO_FLAGS)),
] {
assert_eq!(
hotkey.process(event, released + Duration::from_millis(offset)),
None
);
}
assert!(hotkey.held.contains_key(48));
let (press, release) = match binding.key_code {
None => (
InputEvent::Flags(OPTION_KEY_MASK),
InputEvent::Flags(NO_FLAGS),
),
Some(code) => (key(code, true, NO_FLAGS), key(code, false, NO_FLAGS)),
};
let pressed = released + Duration::from_millis(200);
assert_eq!(hotkey.process(press, pressed), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(release, pressed + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
}
#[test]
fn a_delayed_release_cannot_untrack_a_resynchronized_key_press() {
let now = capture_time();
let f5 = |down| InputEvent::Key {
code: 96,
down,
flags: NO_FLAGS,
};
let mut hotkey = DictationHotkey::with_binding(false, now, true, key_binding(96));
let released = command_tab(&mut hotkey, now);
hotkey.suppress_until_release();
let press = released + Duration::from_millis(30);
assert_eq!(hotkey.process(f5(true), press), Some(HotkeyAction::Start));
// An older release delivered late.
assert_eq!(
hotkey.process(
f5(false),
press.checked_sub(Duration::from_millis(10)).unwrap()
),
None
);
assert!(hotkey.held.contains_key(96));
assert_eq!(
hotkey.process(
InputEvent::Flags(NO_FLAGS),
press + Duration::from_millis(50)
),
None
);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(f5(false), press + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn a_chord_at_the_resynchronized_press_still_discards_it() {
let now = capture_time();
for (chord, cause) in [
(InputEvent::MouseDown, DiscardCause::Mouse),
(hid_key(18), DiscardCause::HidKey),
(
InputEvent::Flags(OPTION_KEY_MASK | COMMAND_KEY_MASK),
DiscardCause::ExtraModifier,
),
] {
let mut hotkey = test_hotkey(false, now);
let released = command_tab(&mut hotkey, now);
let press = released + Duration::from_millis(30);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), press),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(chord, press),
Some(HotkeyAction::Discard(cause))
);
}
}
#[test]
fn fenced_and_pre_reset_modifier_edges_are_not_neutral_evidence() {
let option = InputEvent::Flags(OPTION_KEY_MASK);
let neutral = InputEvent::Flags(NO_FLAGS);
// A key and a neutral edge from before a recovery arrive after it.
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
command_tab(&mut hotkey, now);
let repaired = recover_after_neutral_window(&mut hotkey, now + Duration::from_secs(1), 0);
let before = |ms| repaired.checked_sub(Duration::from_millis(ms)).unwrap();
let a = InputEvent::Key {
code: 0,
down: true,
flags: NO_FLAGS,
};
assert_eq!(hotkey.process(a, before(50)), None);
assert_eq!(hotkey.process(neutral, before(20)), None);
let press = repaired + Duration::from_millis(30);
assert_eq!(hotkey.process(option, press), None);
let release = press + Duration::from_secs(1);
assert_eq!(hotkey.process(neutral, release), None);
recover_after_neutral_window(&mut hotkey, release, 0);
assert_eq!(
hotkey.process(option, release + Duration::from_secs(1)),
Some(HotkeyAction::Start)
);
// A neutral edge queued before the tap was disabled.
let now = CaptureInstant::now();
let mut hotkey = test_hotkey(false, now);
command_tab(
&mut hotkey,
now.checked_sub(Duration::from_secs(1)).unwrap(),
);
assert_eq!(hotkey.process(InputEvent::TapDisabled, now), None);
assert_eq!(
hotkey.process(
neutral,
now.checked_sub(Duration::from_millis(500)).unwrap()
),
None
);
let press = CaptureInstant::now() + Duration::from_secs(1);
assert_eq!(hotkey.process(option, press), None);
assert!(hotkey.held.contains_key(48));
// Suspending forgets a modifier it may never see released.
let mut hotkey = test_hotkey(false, now);
hotkey.track_key_state(option, now);
hotkey.suspend();
assert_eq!(hotkey.modifier_history.flags, NO_FLAGS);
assert_eq!(hotkey.modifier_history.neutral_at, None);
}
#[test]
fn neutral_keyboard_rearms_after_a_missing_modifier_release() {
for double_tap_enabled in [false, true] {
for finish_locked in [false, true] {
if finish_locked && !double_tap_enabled {
continue;
}
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.set_double_tap_enabled(double_tap_enabled);
let mut trace = vec![(0, OPTION_KEY_MASK, Some(HotkeyAction::Start))];
if finish_locked {
trace.extend([
(80, 0, Some(HotkeyAction::Finish)),
(180, OPTION_KEY_MASK, Some(HotkeyAction::Start)),
(260, 0, None),
(1_000, OPTION_KEY_MASK, Some(HotkeyAction::Finish)),
]);
} else {
trace.extend([
(
50,
OPTION_KEY_MASK | SHIFT_KEY_MASK,
Some(HotkeyAction::Discard(DiscardCause::ExtraModifier)),
),
(100, SHIFT_KEY_MASK, None),
]);
}
let edges = callback_input(
&trace
.iter()
.map(|(ms, flags, _)| {
(
(now + Duration::from_millis(*ms)).as_nanos(),
InputEvent::Flags(*flags),
)
})
.collect::<Vec<_>>(),
);
for (edge, (_, _, expected)) in edges.into_iter().zip(trace) {
assert_eq!(hotkey.process(edge.event, edge.capture_at), expected);
}
assert!(matches!(hotkey.state, State::Dirty));
assert!(hotkey.held.keys_empty());
// The final modifier release never reached either callback. Native
// neutrality must repair suppression without synthesizing a capture.
let first = now + Duration::from_secs(2);
recover_after_neutral_window(&mut hotkey, first, 0);
assert!(!hotkey.is_recording());
let press = now + Duration::from_secs(5);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), press),
Some(HotkeyAction::Start),
"double_tap_enabled={double_tap_enabled}, finish_locked={finish_locked}"
);
assert_eq!(
hotkey.process(InputEvent::Flags(0), press + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
assert!(!hotkey.is_recording());
}
}
}
#[test]
fn arrow_function_metadata_does_not_block_the_next_option_hold() {
// Observed after an arrow key-up with no physical keys held: numeric-pad,
// secondary-Fn, and noncoalesced flags remain in native session state.
let arrow_flags = 0x00a0_0100;
for double_tap_enabled in [false, true] {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.set_double_tap_enabled(double_tap_enabled);
let trace = [
(0, InputEvent::Flags(OPTION_KEY_MASK)),
(15, InputEvent::Flags(OPTION_KEY_MASK | SHIFT_KEY_MASK)),
(
30,
InputEvent::Key {
code: 123,
down: true,
flags: arrow_flags | OPTION_KEY_MASK | SHIFT_KEY_MASK,
},
),
(150, InputEvent::Flags(OPTION_KEY_MASK)),
(155, InputEvent::Flags(0x100)),
(
180,
InputEvent::Key {
code: 123,
down: false,
flags: arrow_flags,
},
),
];
let edges = callback_input(
&trace.map(|(ms, event)| ((now + Duration::from_millis(ms)).as_nanos(), event)),
);
let actions = edges
.into_iter()
.filter_map(|edge| hotkey.process(edge.event, edge.capture_at))
.collect::<Vec<_>>();
assert_eq!(
actions,
[
HotkeyAction::Start,
HotkeyAction::Discard(DiscardCause::ExtraModifier)
]
);
assert!(matches!(hotkey.state, State::Dirty));
assert!(hotkey.held.keys_empty());
let first = now + Duration::from_secs(1);
recover_after_neutral_window(&mut hotkey, first, arrow_flags);
assert!(!hotkey.is_recording());
let press = now + Duration::from_secs(5);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), press),
Some(HotkeyAction::Start),
"double_tap_enabled={double_tap_enabled}"
);
assert_eq!(
hotkey.process(InputEvent::Flags(0x100), press + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
}
#[test]
fn lifting_shift_off_shift_option_is_not_an_option_press() {
// A key or macro sends Shift-Option-Left and lifts Shift just before
// Option (#1076). Two bursts inside the double-tap window must not lock.
let shift_option = OPTION_KEY_MASK | SHIFT_KEY_MASK;
let left = |down| InputEvent::Key {
code: 123,
down,
flags: shift_option,
};
for option_first in [false, true] {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
let at = |ms: u64| now + Duration::from_millis(ms);
for burst in [0, 70] {
let first = if option_first {
OPTION_KEY_MASK
} else {
SHIFT_KEY_MASK
};
let mut actions = Vec::new();
for (offset, event) in [
(0, InputEvent::Flags(first)),
(2, InputEvent::Flags(shift_option)),
(4, left(true)),
(6, left(false)),
(8, InputEvent::Flags(OPTION_KEY_MASK)),
(10, InputEvent::Flags(NO_FLAGS)),
] {
actions.extend(hotkey.process(event, at(burst + offset)));
}
let expected: &[HotkeyAction] = if option_first {
&[
HotkeyAction::Start,
HotkeyAction::Discard(DiscardCause::ExtraModifier),
]
} else {
&[]
};
assert_eq!(actions, expected, "option_first={option_first}");
assert!(!hotkey.is_recording(), "option_first={option_first}");
}
// A real Option press still starts and finishes.
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), at(1_000)),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), at(2_000)),
Some(HotkeyAction::Finish)
);
}
}
#[test]
fn caps_lock_while_option_is_held_is_not_an_option_press() {
const CAPS_LOCK_MASK: u64 = 1 << 16;
let now = capture_time();
let at = |ms: u64| now + Duration::from_millis(ms);
let mut hotkey = test_hotkey(false, now);
for (ms, flags) in [
(0, SHIFT_KEY_MASK),
(10, SHIFT_KEY_MASK | OPTION_KEY_MASK),
(20, OPTION_KEY_MASK),
(30, OPTION_KEY_MASK | CAPS_LOCK_MASK),
(40, OPTION_KEY_MASK),
(50, OPTION_KEY_MASK | CAPS_LOCK_MASK),
(60, CAPS_LOCK_MASK),
] {
assert_eq!(hotkey.process(InputEvent::Flags(flags), at(ms)), None);
assert!(!hotkey.is_recording());
}
// Option pressed with Caps Lock on is a press.
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK | CAPS_LOCK_MASK),
at(1_000)
),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), at(1_200)),
None
);
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), at(2_000)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn the_other_option_key_is_not_a_fresh_press_of_an_either_binding() {
use crate::app_settings::{LEFT_OPTION_MASK, LEFT_SHIFT_MASK, RIGHT_OPTION_MASK};
let left_option = OPTION_KEY_MASK | LEFT_OPTION_MASK;
let right_option = OPTION_KEY_MASK | RIGHT_OPTION_MASK;
let both_options = left_option | right_option;
let shift = SHIFT_KEY_MASK | LEFT_SHIFT_MASK;
let now = capture_time();
let at = |ms: u64| now + Duration::from_millis(ms);
let mut hotkey = test_hotkey(false, now);
for (ms, flags) in [
(0, shift),
(10, shift | left_option),
(20, left_option),
(30, both_options),
(40, right_option),
(50, NO_FLAGS),
] {
assert_eq!(hotkey.process(InputEvent::Flags(flags), at(ms)), None);
assert!(!hotkey.is_recording());
}
// Either Option alone presses, and the other joining it changes nothing.
assert_eq!(
hotkey.process(InputEvent::Flags(right_option), at(1_000)),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(InputEvent::Flags(both_options), at(1_400)),
None
);
assert_eq!(
hotkey.process(InputEvent::Flags(left_option), at(1_500)),
None
);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), at(2_000)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn option_double_tap_still_locks() {
let now = capture_time();
let at = |ms: u64| now + Duration::from_millis(ms);
let press = InputEvent::Flags(OPTION_KEY_MASK);
let release = InputEvent::Flags(NO_FLAGS);
let mut hotkey = test_hotkey(false, now);
assert_eq!(hotkey.process(press, at(0)), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(release, at(80)), Some(HotkeyAction::Finish));
assert_eq!(hotkey.process(press, at(150)), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(release, at(230)), None);
assert!(hotkey.is_locked());
assert_eq!(hotkey.process(press, at(1_000)), Some(HotkeyAction::Finish));
assert_eq!(hotkey.process(release, at(1_080)), None);
assert!(!hotkey.is_recording());
}
#[test]
fn neutral_keyboard_rebuilds_modifier_history_after_a_missed_release() {
let now = capture_time();
let option = InputEvent::Flags(OPTION_KEY_MASK);
let mut hotkey = test_hotkey(false, now);
// Option went down while matching was suspended; its release never came.
hotkey.track_key_state(option, now);
assert_eq!(hotkey.process(option, now + Duration::from_secs(1)), None);
let repaired = recover_after_neutral_window(&mut hotkey, now + Duration::from_secs(2), 0);
assert_eq!(hotkey.modifier_history.flags, NO_FLAGS);
assert_eq!(
hotkey.process(option, repaired + Duration::from_secs(1)),
Some(HotkeyAction::Start)
);
}
#[test]
fn function_recovery_preserves_unknown_and_flags_only_fn_holds() {
let now = capture_time();
for observed in [false, true] {
let mut hotkey = test_hotkey(false, now);
if observed {
hotkey.track_key_state(InputEvent::Flags(FUNCTION_KEY_MASK), now);
// An older neutral modifier event cannot erase the Fn press.
hotkey.track_key_state(InputEvent::Flags(0), CaptureInstant::ZERO);
}
hotkey.suppress_until_release();
for offset in [0, 100, 1_000] {
hotkey.recover_stale_keys_with(
|| now + Duration::from_millis(offset),
|| FUNCTION_KEY_MASK,
|_| false,
);
assert!(matches!(hotkey.state, State::Dirty));
}
// A missed Fn release must not turn the observation itself into a latch.
let neutral = now + Duration::from_secs(2);
recover_after_neutral_window(&mut hotkey, neutral, 0);
assert!(matches!(hotkey.state, State::Idle { .. }));
hotkey.suppress_until_release();
// A later explicit modifier release allows the navigation metadata
// to be ignored without changing ordinary key-event Fn matching.
let released = now + Duration::from_secs(3);
hotkey.track_key_state(InputEvent::Flags(0), released);
recover_after_neutral_window(&mut hotkey, released, FUNCTION_KEY_MASK);
assert!(matches!(hotkey.state, State::Idle { .. }));
}
}
#[test]
fn blind_input_periods_invalidate_function_modifier_evidence() {
for reset in 0..3 {
let mut hotkey = test_hotkey(false, CaptureInstant::ZERO);
hotkey.track_key_state(InputEvent::Flags(0), CaptureInstant::ZERO);
match reset {
0 => {
hotkey.suspend();
}
1 => {
hotkey.process(InputEvent::TapDisabled, CaptureInstant::ZERO);
}
_ => {
hotkey.track_key_state(InputEvent::TapDisabled, CaptureInstant::ZERO);
}
}
let invalidated = hotkey.function_modifier.0;
hotkey.track_key_state(
InputEvent::Flags(0),
invalidated.checked_sub(Duration::from_nanos(1)).unwrap(),
);
hotkey.suppress_until_release();
recover_after_neutral_window(&mut hotkey, invalidated, FUNCTION_KEY_MASK);
assert!(matches!(hotkey.state, State::Dirty));
}
}
#[test]
fn function_key_chord_still_uses_function_flags_on_key_events() {
let now = capture_time();
let binding = RuntimeHotkey {
key_code: Some(49),
..function_binding()
};
let mut hotkey = DictationHotkey::with_binding(false, now, false, binding);
assert_eq!(
hotkey.process(InputEvent::Flags(FUNCTION_KEY_MASK), now),
None
);
assert_eq!(
hotkey.process(
InputEvent::Key {
code: 49,
down: true,
flags: FUNCTION_KEY_MASK
},
now
),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(
InputEvent::Key {
code: 49,
down: false,
flags: FUNCTION_KEY_MASK
},
now + Duration::from_secs(1)
),
Some(HotkeyAction::Finish)
);
}
#[test]
fn blocked_modifier_recovery_requires_a_fully_neutral_keyboard() {
let now = capture_time();
for (flags, held_key) in [
(OPTION_KEY_MASK, None),
(0, Some(48)),
(FUNCTION_KEY_MASK, Some(63)),
(FUNCTION_KEY_MASK | (1 << 21), Some(63)),
] {
let mut hotkey = test_hotkey(false, now);
hotkey.track_key_state(InputEvent::Flags(0), now);
hotkey.suppress_until_release();
for offset in [0, 100, 1_000] {
hotkey.recover_stale_keys_with(
|| now + Duration::from_millis(offset),
|| flags,
|code| held_key == Some(code),
);
assert!(matches!(hotkey.state, State::Dirty));
}
let neutral = now + Duration::from_secs(2);
hotkey.recover_stale_keys_with(|| neutral, || 0, |_| false);
hotkey.recover_stale_keys_with(|| neutral + Duration::from_millis(99), || 0, |_| false);
assert!(matches!(hotkey.state, State::Dirty));
hotkey.recover_stale_keys_with(|| neutral + STALE_KEY_NEUTRAL_DURATION, || 0, |_| false);
assert!(matches!(hotkey.state, State::Idle { .. }));
}
}
#[test]
fn stale_key_recovery_does_not_reinterpret_delayed_chords() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
let key = |down| InputEvent::Key {
code: 0,
down,
flags: OPTION_KEY_MASK,
};
hotkey.process(key(true), now);
let first = now + Duration::from_secs(1);
let repaired = recover_after_neutral_window(&mut hotkey, first, 0);
for (offset, event) in [
(10, key(true)),
(20, InputEvent::Flags(OPTION_KEY_MASK)),
(30, key(false)),
(40, InputEvent::Flags(0)),
] {
assert_eq!(
hotkey.process(event, now + Duration::from_millis(offset)),
None
);
}
assert!(!hotkey.is_recording());
assert!(hotkey.held.keys_empty());
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
repaired + Duration::from_millis(1)
),
None
);
assert_eq!(
hotkey.process(InputEvent::Flags(0), repaired + Duration::from_millis(2)),
None
);
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
repaired + Duration::from_millis(3)
),
Some(HotkeyAction::Start)
);
}
#[test]
fn stale_key_recovery_retains_edges_inside_the_sample_window() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.process(
InputEvent::Key {
code: 0,
down: true,
flags: 0,
},
now,
);
let repaired = recover_after_neutral_window(&mut hotkey, now, 0);
// This new key went down after its native query but before sampling ended.
let key = |down| InputEvent::Key {
code: 1,
down,
flags: 0,
};
assert_eq!(hotkey.process(key(true), repaired), None);
assert!(hotkey.held.contains_key(1));
let later = repaired + Duration::from_millis(1);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), later),
None
);
assert_eq!(hotkey.process(InputEvent::Flags(0), later), None);
assert!(matches!(hotkey.state, State::Dirty));
assert_eq!(hotkey.process(key(false), later), None);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), later),
Some(HotkeyAction::Start)
);
}
#[test]
fn stale_key_recovery_old_release_cannot_erase_a_fresh_press() {
for binding in [option_binding(), key_binding(97)] {
let now = capture_time();
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
let key = |down| InputEvent::Key {
code: 97,
down,
flags: 0,
};
hotkey.process(
InputEvent::Key {
code: 0,
down: true,
flags: 0,
},
now,
);
let fence = recover_after_neutral_window(&mut hotkey, now, 0);
let fresh = fence + Duration::from_millis(1);
hotkey.process(key(true), fresh);
assert_eq!(hotkey.process(key(false), now), None);
assert!(hotkey.held.contains_key(97));
assert_eq!(hotkey.process(InputEvent::Flags(0), fresh), None);
if binding.key_code.is_none() {
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), fresh),
None
);
} else {
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(key(false), fresh + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
}
}
#[test]
fn stale_key_recovery_protects_programmatic_key_transitions() {
for down in [false, true] {
let now = capture_time();
let key = |down| InputEvent::Key {
code: 0,
down,
flags: 0,
};
let mut hotkey = test_hotkey(false, now);
hotkey.process(key(true), now);
let fence = recover_after_neutral_window(&mut hotkey, now, 0);
hotkey.track_key_state(key(down), fence + Duration::from_millis(1));
assert_eq!(hotkey.track_key_state(key(!down), now), None);
assert_eq!(hotkey.held.contains_key(0), down);
}
}
#[test]
fn programmatic_ownership_disarms_pending_double_taps_without_losing_held_keys() {
let now = capture_time();
let binding = key_binding(97);
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.set_double_tap_only(true);
let key = |code, down| InputEvent::Key {
code,
down,
flags: 0,
};
assert_eq!(hotkey.process(key(97, true), now), None);
assert!(matches!(hotkey.state, State::FirstTapPressed { .. }));
hotkey.disarm_pending_gesture();
assert!(hotkey.held.contains_key(97));
hotkey.track_key_state(key(97, false), now + Duration::from_millis(80));
let later = now + Duration::from_secs(5);
for (offset, event) in [
(0, key(0, true)),
(10, key(0, false)),
(20, key(97, true)),
(80, key(97, false)),
] {
assert_eq!(
hotkey.process(event, later + Duration::from_millis(offset)),
None
);
}
assert!(!hotkey.is_recording());
assert_eq!(
hotkey.process(key(97, true), later + Duration::from_millis(180)),
None
);
assert_eq!(
hotkey.process(key(97, false), later + Duration::from_millis(260)),
Some(HotkeyAction::Start)
);
hotkey.disarm_pending_gesture();
assert!(
hotkey.is_recording(),
"disarming pending gestures must not end a capture"
);
}
#[test]
fn programmatic_ownership_preserves_dirty_chord_suppression() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK | SHIFT_KEY_MASK),
now + Duration::from_millis(50)
),
Some(HotkeyAction::Discard(DiscardCause::ExtraModifier))
);
hotkey.disarm_pending_gesture();
let later = now + Duration::from_secs(1);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), later),
None
);
assert_eq!(hotkey.process(InputEvent::Flags(0), later), None);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), later),
Some(HotkeyAction::Start)
);
}
#[test]
fn stale_key_recovery_requires_complete_neutrality_and_no_intervening_input() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.process(
InputEvent::Key {
code: 0,
down: true,
flags: 0,
},
now,
);
hotkey.recover_stale_keys_with(|| now, || 0, |_| false);
let later = now + Duration::from_secs(1);
// An untracked held key must prevent repair as well.
hotkey.recover_stale_keys_with(|| later, || 0, |code| code == 1);
assert!(hotkey.stale_keys_neutral_since.is_none());
assert!(hotkey.held.contains_key(0));
hotkey.recover_stale_keys_with(|| later, || 0, |_| false);
hotkey.process(InputEvent::MouseDown, later);
hotkey.recover_stale_keys_with(|| later + STALE_KEY_NEUTRAL_DURATION, || 0, |_| false);
assert!(hotkey.held.contains_key(0));
let mut flags = [0, OPTION_KEY_MASK].into_iter();
hotkey.recover_stale_keys_with(
|| later + Duration::from_secs(1),
|| flags.next().unwrap(),
|_| false,
);
assert!(hotkey.stale_keys_neutral_since.is_none());
assert!(hotkey.held.contains_key(0));
}
#[test]
fn stale_key_recovery_never_polls_holds_or_pending_gestures() {
let now = capture_time();
for state in [
State::Recording {
started_at: now,
previous_release: None,
},
State::FirstTapPressed { started_at: now },
State::AwaitingSecondTap { released_at: now },
State::SecondTapPressed {
first_released_at: now,
},
] {
let mut hotkey = test_hotkey(false, now);
hotkey.state = state;
hotkey.held.press(0, now);
let was_recording = hotkey.is_recording();
hotkey.recover_stale_keys_with(
|| panic!("clock must not be polled"),
|| panic!("flags must not be polled"),
|_| panic!("keys must not be polled"),
);
assert_eq!(hotkey.is_recording(), was_recording);
assert!(hotkey.held.contains_key(0));
}
// A lock with accurate tracking has nothing to repair.
let mut hotkey = test_hotkey(false, now);
hotkey.state = State::Locked;
hotkey.recover_stale_keys_with(
|| panic!("clock must not be polled"),
|| panic!("flags must not be polled"),
|_| panic!("keys must not be polled"),
);
assert!(hotkey.is_recording());
}
#[test]
fn programmatic_lock_finishes_on_the_next_press() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
assert!(hotkey.lock());
assert!(hotkey.is_recording());
let option = InputEvent::Flags(OPTION_KEY_MASK);
let press = now + Duration::from_millis(500);
assert_eq!(hotkey.process(option, press), Some(HotkeyAction::Finish));
assert!(!hotkey.is_recording());
// A held shortcut is not interrupted by a programmatic lock.
let mut held = test_hotkey(false, now);
assert_eq!(held.process(option, now), Some(HotkeyAction::Start));
assert!(!held.lock());
}
#[test]
fn a_stop_phrase_finishes_a_locked_capture_and_leaves_the_next_press_free() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let press = InputEvent::Flags(OPTION_KEY_MASK);
let release = InputEvent::Flags(NO_FLAGS);
// An idle machine has nothing to finish.
let mut hotkey = toggle_hotkey(now, false);
assert_eq!(hotkey.finish_hands_free(), None);
// A held press records on: the words are speech.
let mut held = toggle_hotkey(now, false);
assert_eq!(held.process(press, ms(0)), Some(HotkeyAction::Start));
assert_eq!(held.finish_hands_free(), None);
assert!(held.is_recording());
// Toggle's release locks the capture; the words finish it with no key
// down, so the next press starts afresh instead of recovering stale keys.
let mut hotkey = toggle_hotkey(now, false);
assert_eq!(hotkey.process(press, ms(0)), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(release, ms(80)), None);
assert!(hotkey.is_locked());
assert_eq!(hotkey.finish_hands_free(), Some(HotkeyAction::Finish));
assert!(!hotkey.is_recording());
assert!(!hotkey.suppresses_recognition());
assert_eq!(hotkey.process(press, ms(2_000)), Some(HotkeyAction::Start));
// A completed double tap locks the same way.
let mut hotkey = test_hotkey(false, now);
assert_eq!(hotkey.process(press, ms(0)), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(release, ms(80)), Some(HotkeyAction::Finish));
assert_eq!(hotkey.process(press, ms(180)), Some(HotkeyAction::Start));
assert_eq!(hotkey.process(release, ms(260)), None);
assert!(hotkey.is_locked());
assert_eq!(hotkey.finish_hands_free(), Some(HotkeyAction::Finish));
assert_eq!(hotkey.process(press, ms(1_000)), Some(HotkeyAction::Start));
}
#[test]
fn locked_dictation_finishes_after_a_missing_key_release() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
let option = InputEvent::Flags(OPTION_KEY_MASK);
let neutral = InputEvent::Flags(NO_FLAGS);
assert_eq!(hotkey.process(option, now), Some(HotkeyAction::Start));
let released = now + Duration::from_millis(80);
assert_eq!(
hotkey.process(neutral, released),
Some(HotkeyAction::Finish)
);
let second = now + Duration::from_millis(180);
assert_eq!(hotkey.process(option, second), Some(HotkeyAction::Start));
let locked = now + Duration::from_millis(260);
assert_eq!(hotkey.process(neutral, locked), None);
assert!(hotkey.is_recording());
// A key pressed while locked whose release never reaches the reducer.
let down = InputEvent::Key {
code: 0,
down: true,
flags: 0,
};
assert_eq!(hotkey.process(down, now + Duration::from_secs(1)), None);
let blocked = now + Duration::from_secs(2);
assert_eq!(hotkey.process(option, blocked), None);
assert_eq!(
hotkey.process(neutral, blocked + Duration::from_millis(80)),
None
);
assert!(hotkey.is_recording());
// Repair leaves the capture locked and emits no action of its own.
let first_sample = now + Duration::from_secs(3);
hotkey.recover_stale_keys_with(|| first_sample, || 0, |_| false);
let held = first_sample + Duration::from_millis(50);
hotkey.recover_stale_keys_with(|| held, || 0, |code| code == 0);
assert!(hotkey.held.contains_key(0));
let repaired = recover_after_neutral_window(&mut hotkey, held, 0);
assert!(hotkey.held.keys_empty());
assert!(hotkey.is_recording());
let finish = repaired + Duration::from_millis(1);
assert_eq!(hotkey.process(option, finish), Some(HotkeyAction::Finish));
assert!(!hotkey.is_recording());
}
#[test]
fn stale_key_recovery_does_not_scan_a_held_key_or_disturb_a_normal_double_tap() {
let now = capture_time();
let binding = key_binding(96);
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.process(
InputEvent::Key {
code: 0,
down: true,
flags: 0,
},
now,
);
let mut queried = Vec::new();
hotkey.recover_stale_keys_with(
|| now,
|| 0,
|code| {
queried.push(code);
true
},
);
assert_eq!(queried, vec![0]);
hotkey.process(
InputEvent::Key {
code: 0,
down: false,
flags: 0,
},
now,
);
let key = |down| InputEvent::Key {
code: 96,
down,
flags: 0,
};
assert_eq!(hotkey.process(key(true), now), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(key(false), now + Duration::from_millis(50)),
Some(HotkeyAction::Finish)
);
hotkey.recover_stale_keys_with(
|| panic!("no stale key"),
|| panic!("no stale key"),
|_| panic!("no stale key"),
);
assert_eq!(
hotkey.process(key(true), now + Duration::from_millis(100)),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(key(false), now + Duration::from_millis(150)),
None
);
assert!(hotkey.is_recording());
}
#[test]
fn option_press_and_release_finishes() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), now + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn key_chord_starts_on_key_down_and_finishes_on_key_up() {
let now = capture_time();
let binding = shift_space_binding();
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
let key_down = shift_space_event(true);
assert_eq!(hotkey.process(key_down, now), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(shift_space_event(false), now + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
let mut suppression = ShortcutSuppression::default();
assert!(suppression.process(key_down, 42, binding, true));
assert!(suppression.process(shift_space_event(false), 42, binding, true));
}
#[test]
fn key_chord_double_tap_locks_until_the_chord_is_pressed_again() {
let now = capture_time();
let binding = shift_space_binding();
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
let event = shift_space_event;
assert_eq!(hotkey.process(event(true), now), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(event(false), now + Duration::from_millis(70)),
Some(HotkeyAction::Finish)
);
assert_eq!(
hotkey.process(event(true), now + Duration::from_millis(150)),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(event(false), now + Duration::from_millis(230)),
None
);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(event(true), now + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn toggle_mode_starts_on_a_press_and_finishes_on_the_next() {
let command = COMMAND_KEY_MASK | crate::app_settings::RIGHT_COMMAND_MASK;
let key_chord = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers {
command: Some(crate::app_settings::ModifierSide::Right),
..Default::default()
},
key_code: Some(49),
};
for (binding, flags, double_tap_only) in [
(option_binding(), OPTION_KEY_MASK, false),
(function_binding(), FUNCTION_KEY_MASK, false),
(key_chord, command, false),
(key_chord, command, true),
] {
let now = capture_time();
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.set_double_tap_only(double_tap_only);
hotkey.set_toggle(true);
let event = |down: bool| {
binding
.key_code
.map_or(InputEvent::Flags(if down { flags } else { 0 }), |code| {
InputEvent::Key { code, down, flags }
})
};
assert_eq!(hotkey.process(event(true), now), Some(HotkeyAction::Start));
// Releasing keeps recording, however short the press was.
assert_eq!(
hotkey.process(event(false), now + Duration::from_millis(80)),
None
);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(event(true), now + Duration::from_secs(3)),
Some(HotkeyAction::Finish)
);
assert_eq!(
hotkey.process(event(false), now + Duration::from_millis(3_080)),
None
);
assert!(!hotkey.is_recording());
}
}
#[test]
fn toggle_mode_finishes_after_command_tab_while_recording() {
let now = capture_time();
let option = InputEvent::Flags(OPTION_KEY_MASK);
let neutral = InputEvent::Flags(NO_FLAGS);
for physical_still_down in [false, true] {
let mut hotkey = test_hotkey(false, now);
hotkey.set_toggle(true);
assert_eq!(hotkey.process(option, now), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(neutral, now + Duration::from_millis(80)),
None
);
assert!(hotkey.is_locked());
if physical_still_down {
// Tab really is still down: the press waits, as before.
hotkey.physical = PhysicalKeyboard {
flags: || NO_FLAGS,
key_down: |code| code == 48,
};
}
let released = command_tab(&mut hotkey, now + Duration::from_secs(1));
assert!(hotkey.is_locked());
let press = released + Duration::from_secs(1);
let expected = (!physical_still_down).then_some(HotkeyAction::Finish);
assert_eq!(hotkey.process(option, press), expected);
assert_eq!(hotkey.is_recording(), physical_still_down);
assert_eq!(
hotkey.process(neutral, press + Duration::from_millis(80)),
None
);
assert_eq!(hotkey.is_recording(), physical_still_down);
}
}
#[test]
fn toggle_mode_escape_leaves_a_locked_capture_recording() {
let now = capture_time();
let binding = shift_space_binding();
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.set_toggle(true);
let event = shift_space_event;
assert_eq!(hotkey.process(event(true), now), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(event(false), now + Duration::from_millis(60)),
None
);
assert_eq!(
hotkey.process(
InputEvent::Key {
code: ESCAPE_KEY_CODE,
down: true,
flags: 0,
},
now + Duration::from_secs(1)
),
None
);
assert!(hotkey.is_recording());
}
/// Toggle's cancel shortcut discards a toggled recording, held or
/// locked; Hold mode has none (only Escape on a held capture), and idle it
/// does nothing.
#[test]
fn the_cancel_shortcut_discards_only_a_toggled_recording() {
let now = capture_time();
let escape = |down| InputEvent::Key {
code: ESCAPE_KEY_CODE,
down,
flags: 0,
};
let cancel = Some(HotkeyBinding::cancel_default().runtime());
let ms = |ms| now + Duration::from_millis(ms);
let toggled = || {
let mut hotkey = DictationHotkey::with_binding(false, now, true, shift_space_binding());
hotkey.set_toggle(true);
hotkey.set_cancel(cancel);
hotkey
};
// Idle: the key is the app's.
let mut hotkey = toggled();
assert_eq!(hotkey.process(escape(true), now), None);
assert_eq!(hotkey.process(escape(false), ms(20)), None);
// Locked after the toggle press: cancelled, and the next press starts.
assert_eq!(
hotkey.process(shift_space_event(true), ms(100)),
Some(HotkeyAction::Start)
);
assert_eq!(hotkey.process(shift_space_event(false), ms(160)), None);
assert!(hotkey.is_locked());
assert_eq!(
hotkey.process(escape(true), ms(1_000)),
Some(HotkeyAction::CancelShortcut)
);
assert!(!hotkey.is_recording());
assert_eq!(hotkey.process(escape(false), ms(1_050)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(1_060)), None);
assert_eq!(
hotkey.process(shift_space_event(true), ms(2_000)),
Some(HotkeyAction::Start)
);
// Held, before the release locks it.
let mut hotkey = toggled();
hotkey.process(shift_space_event(true), now);
assert_eq!(
hotkey.process(escape(true), ms(500)),
Some(HotkeyAction::CancelShortcut)
);
// Hold mode: no cancel shortcut, even with a binding; Escape cancels
// only a held capture past the hold threshold.
let mut hotkey = test_hotkey(true, now);
hotkey.set_cancel(cancel);
let held_escape = InputEvent::Key {
code: ESCAPE_KEY_CODE,
down: true,
flags: OPTION_KEY_MASK,
};
assert_eq!(hotkey.process(held_escape, ms(200)), None);
assert!(hotkey.is_recording());
assert_eq!(hotkey.recording_cancel(), None);
}
/// The tap keeps the cancel key from the app only while the listener
/// arms it (a toggled recording runs).
#[test]
fn the_cancel_key_is_suppressed_only_while_armed() {
let mut suppression = ShortcutSuppression::default();
let escape = |down| InputEvent::Key {
code: ESCAPE_KEY_CODE,
down,
flags: NO_FLAGS,
};
let idle = RuntimeHotkeys::default();
assert!(!suppression.process_all(escape(true), idle, true, false));
assert!(!suppression.process_all(escape(false), idle, true, false));
let armed = RuntimeHotkeys {
cancel: Some(HotkeyBinding::cancel_default().runtime()),
..RuntimeHotkeys::default()
};
assert!(suppression.process_all(escape(true), armed, true, false));
assert!(suppression.process_all(escape(false), armed, true, false));
}
/// Each extra-mode trigger sets the three switches the dictation shortcut's
/// own mode sets; double-tap only still needs a keyed binding.
#[test]
fn an_extra_mode_sets_its_trigger_switches() {
use crate::app_settings::ExtraDictationMode;
let now = capture_time();
let keyed = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::option(),
key_code: Some(49),
};
for mode in ExtraDictationMode::ALL {
let mut hotkey = DictationHotkey::with_binding(false, now, false, keyed);
hotkey.set_trigger(mode);
let (toggle, double_tap_enabled, double_tap_only) = mode.switches();
assert_eq!(hotkey.toggle, toggle, "{mode:?}");
assert_eq!(hotkey.double_tap_enabled, double_tap_enabled, "{mode:?}");
assert_eq!(hotkey.double_tap_only, double_tap_only, "{mode:?}");
}
let mut modifier_only = DictationHotkey::with_binding(false, now, true, option_binding());
modifier_only.set_trigger(ExtraDictationMode::DoubleTap);
assert!(
!modifier_only.double_tap_only,
"double-tap only folds away without a key, as the dictation mode does"
);
modifier_only.set_trigger(ExtraDictationMode::Tap);
assert!(modifier_only.toggle);
assert!(modifier_only.double_tap_enabled);
assert!(!modifier_only.double_tap_only);
}
/// A machine set to cancel in any mode takes its cancel binding while a
/// locked Hold-or-double-tap capture records; an ordinary machine keeps
/// ignoring it.
#[test]
fn a_cancel_in_any_mode_machine_takes_its_cancel_in_hold_mode() {
let now = capture_time();
let escape = |flags| InputEvent::Key {
code: ESCAPE_KEY_CODE,
down: true,
flags,
};
let cancel = HotkeyBinding::cancel_default().runtime();
let option = |hotkey: &mut DictationHotkey, at: CaptureInstant| {
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), at)
};
let lock = |hotkey: &mut DictationHotkey| {
assert_eq!(option(hotkey, now), Some(HotkeyAction::Start));
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), now + Duration::from_millis(80)),
Some(HotkeyAction::Finish)
);
assert_eq!(
option(hotkey, now + Duration::from_millis(180)),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(
InputEvent::Flags(NO_FLAGS),
now + Duration::from_millis(260)
),
None
);
assert!(hotkey.is_locked());
};
// A Hold machine never takes its cancel while the shortcut is held.
let mut plain = test_hotkey(false, now);
plain.set_cancel(Some(cancel));
assert_eq!(option(&mut plain, now), Some(HotkeyAction::Start));
assert_eq!(
plain.process(escape(OPTION_KEY_MASK), now + Duration::from_millis(50)),
None
);
assert!(plain.is_recording());
// A lock is hands-free, but only the flag lets a non-toggle machine
// take the cancel.
let mut locked = test_hotkey(false, now);
locked.set_cancel(Some(cancel));
lock(&mut locked);
assert_eq!(
locked.process(escape(NO_FLAGS), now + Duration::from_millis(200)),
None
);
assert!(locked.is_recording());
let mut extra = test_hotkey(false, now);
extra.set_cancel(Some(cancel));
extra.set_cancel_in_any_mode(true);
lock(&mut extra);
assert_eq!(
extra.process(escape(NO_FLAGS), now + Duration::from_millis(200)),
Some(HotkeyAction::CancelShortcut)
);
assert!(!extra.is_recording());
}
#[test]
fn double_tap_only_waits_for_two_complete_key_chord_taps() {
let now = capture_time();
let binding = shift_space_binding();
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.set_double_tap_only(true);
let event = shift_space_event;
assert_eq!(hotkey.process(event(true), now), None);
assert!(!hotkey.is_recording());
assert_eq!(
hotkey.process(event(false), now + Duration::from_millis(50)),
None
);
assert_eq!(
hotkey.process(event(true), now + Duration::from_millis(150)),
None
);
assert_eq!(
hotkey.process(event(false), now + Duration::from_millis(200)),
Some(HotkeyAction::Start)
);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(event(true), now + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn double_tap_only_restarts_with_the_first_press_after_timeout() {
let now = capture_time();
let binding = shift_space_binding();
for delay in [DOUBLE_TAP_WINDOW, Duration::from_secs(1)] {
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.set_double_tap_only(true);
let event = shift_space_event;
assert_eq!(hotkey.process(event(true), now), None);
let released_at = now + Duration::from_millis(50);
assert_eq!(hotkey.process(event(false), released_at), None);
let first_press = released_at + delay;
assert_eq!(hotkey.process(event(true), first_press), None);
assert_eq!(
hotkey.process(event(false), first_press + Duration::from_millis(50)),
None
);
assert!(!hotkey.is_recording());
assert_eq!(
hotkey.process(event(true), first_press + Duration::from_millis(150)),
None
);
assert_eq!(
hotkey.process(event(false), first_press + Duration::from_millis(200)),
Some(HotkeyAction::Start)
);
assert!(hotkey.is_recording());
}
}
#[test]
fn double_tap_only_timeout_and_unrelated_chord_never_start_capture() {
let now = capture_time();
let binding = shift_space_binding();
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.set_double_tap_only(true);
let trigger = shift_space_event;
hotkey.process(trigger(true), now);
hotkey.process(trigger(false), now + Duration::from_millis(50));
assert_eq!(
hotkey.process(trigger(true), now + Duration::from_millis(400)),
None
);
assert!(!hotkey.is_recording());
hotkey.process(trigger(true), now + Duration::from_millis(500));
hotkey.process(trigger(false), now + Duration::from_millis(550));
assert_eq!(
hotkey.process(
InputEvent::Key {
code: 11,
down: true,
flags: 0,
},
now + Duration::from_millis(600),
),
None
);
assert!(!hotkey.is_recording());
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.set_double_tap_only(true);
hotkey.process(trigger(true), now);
hotkey.process(trigger(false), now + Duration::from_millis(50));
hotkey.process(trigger(true), now + Duration::from_millis(150));
assert_eq!(
hotkey.process(trigger(false), now + Duration::from_millis(400)),
None
);
assert!(!hotkey.is_recording());
}
#[test]
fn double_tap_only_with_the_lab_starts_from_a_lone_modifier() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let option = OPTION_KEY_MASK | LEFT_OPTION_MASK;
for (binding, flags) in [
(option_binding(), option),
(function_binding(), FUNCTION_KEY_MASK),
] {
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.double_tap_modifiers = || true;
hotkey.set_double_tap_only(true);
// One complete tap arms the window and records nothing.
assert_eq!(hotkey.process(InputEvent::Flags(flags), ms(0)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(80)), None);
assert!(!hotkey.is_recording());
// A hold records nothing either, and keeps the modifier's own use.
assert_eq!(hotkey.process(InputEvent::Flags(flags), ms(400)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(1_000)), None);
assert!(!hotkey.is_recording());
// Two complete taps inside the window lock a hands-free capture.
assert_eq!(hotkey.process(InputEvent::Flags(flags), ms(1_400)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(1_480)), None);
assert_eq!(hotkey.process(InputEvent::Flags(flags), ms(1_580)), None);
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), ms(1_660)),
Some(HotkeyAction::Start)
);
assert!(hotkey.is_locked());
// A fresh press finishes it.
assert_eq!(
hotkey.process(InputEvent::Flags(flags), ms(2_200)),
Some(HotkeyAction::Finish)
);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(2_280)), None);
assert!(!hotkey.is_recording());
}
}
#[test]
fn double_tap_only_with_the_lab_still_discards_a_lone_modifier_chord() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let option = OPTION_KEY_MASK | LEFT_OPTION_MASK;
let mut hotkey = DictationHotkey::with_binding(false, now, true, option_binding());
hotkey.double_tap_modifiers = || true;
hotkey.set_double_tap_only(true);
// One complete tap.
assert_eq!(hotkey.process(InputEvent::Flags(option), ms(0)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(80)), None);
// The second press, then a key joining it while Option is held: a chord
// meant for another app, so the gesture goes dirty and records nothing.
assert_eq!(hotkey.process(InputEvent::Flags(option), ms(120)), None);
for (at, down) in [(ms(140), true), (ms(160), false)] {
assert_eq!(
hotkey.process(
InputEvent::Key {
code: 0,
down,
flags: option,
},
at,
),
None
);
}
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(180)), None);
// The next complete tap is a fresh first tap, not the second of a pair.
assert_eq!(hotkey.process(InputEvent::Flags(option), ms(220)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(300)), None);
assert!(!hotkey.is_recording());
}
#[test]
fn double_tap_only_with_the_lab_does_not_take_a_held_first_press_as_a_tap() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let option = OPTION_KEY_MASK | LEFT_OPTION_MASK;
let mut hotkey = DictationHotkey::with_binding(false, now, true, option_binding());
hotkey.double_tap_modifiers = || true;
hotkey.set_double_tap_only(true);
// A lone modifier held past the hold threshold is a hold, not a tap.
assert_eq!(hotkey.process(InputEvent::Flags(option), ms(0)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(400)), None);
// The tap right after it must not complete the held press as a pair.
assert_eq!(hotkey.process(InputEvent::Flags(option), ms(450)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(520)), None);
assert!(!hotkey.is_recording());
}
#[test]
fn double_tap_only_with_the_lab_discards_a_different_modifier_between_taps() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let option = OPTION_KEY_MASK | LEFT_OPTION_MASK;
let command = COMMAND_KEY_MASK | LEFT_COMMAND_MASK;
let mut hotkey = DictationHotkey::with_binding(false, now, true, option_binding());
hotkey.double_tap_modifiers = || true;
hotkey.set_double_tap_only(true);
assert_eq!(hotkey.process(InputEvent::Flags(option), ms(0)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(80)), None);
// Command between the Option taps is a chord, not part of the pair.
assert_eq!(hotkey.process(InputEvent::Flags(command), ms(120)), None);
assert!(matches!(hotkey.state, State::Dirty));
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(160)), None);
// The next Option tap is a fresh first tap, so the pair before Command
// never locks.
assert_eq!(hotkey.process(InputEvent::Flags(option), ms(200)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(280)), None);
assert!(!hotkey.is_recording());
}
#[test]
fn double_tap_only_with_the_lab_locks_a_keyless_control_option_chord() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let control = CONTROL_KEY_MASK | LEFT_CONTROL_MASK;
let option = OPTION_KEY_MASK | LEFT_OPTION_MASK;
let binding = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::control_option(),
key_code: None,
};
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.double_tap_modifiers = || true;
hotkey.set_double_tap_only(true);
// First chord: one flags event per key, released one key at a time.
assert_eq!(hotkey.process(InputEvent::Flags(control), ms(0)), None);
assert_eq!(
hotkey.process(InputEvent::Flags(control | option), ms(40)),
None
);
assert_eq!(hotkey.process(InputEvent::Flags(control), ms(90)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(140)), None);
assert!(!hotkey.is_recording());
// The second chord starts with Control alone: it is the binding's own
// key, not a different modifier, so the pending tap stays live.
assert_eq!(hotkey.process(InputEvent::Flags(control), ms(200)), None);
assert_eq!(
hotkey.process(InputEvent::Flags(control | option), ms(240)),
None
);
assert_eq!(
hotkey.process(InputEvent::Flags(control), ms(280)),
Some(HotkeyAction::Start)
);
assert!(hotkey.is_locked());
}
#[test]
fn double_tap_only_with_the_lab_locks_a_both_options_chord() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let left = OPTION_KEY_MASK | LEFT_OPTION_MASK;
let right = OPTION_KEY_MASK | RIGHT_OPTION_MASK;
let binding = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers {
option: Some(crate::app_settings::ModifierSide::Both),
..Default::default()
},
key_code: None,
};
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.double_tap_modifiers = || true;
hotkey.set_double_tap_only(true);
// First chord: both sides go down together, then come up one at a time.
assert_eq!(hotkey.process(InputEvent::Flags(left), ms(0)), None);
assert_eq!(
hotkey.process(InputEvent::Flags(left | right), ms(40)),
None
);
assert_eq!(hotkey.process(InputEvent::Flags(right), ms(90)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(140)), None);
assert!(!hotkey.is_recording());
// The second chord starts on one side: its own key, not a different
// modifier.
assert_eq!(hotkey.process(InputEvent::Flags(left), ms(200)), None);
assert_eq!(
hotkey.process(InputEvent::Flags(left | right), ms(240)),
None
);
assert_eq!(
hotkey.process(InputEvent::Flags(left), ms(280)),
Some(HotkeyAction::Start)
);
assert!(hotkey.is_locked());
}
#[test]
fn double_tap_only_with_the_lab_discards_the_other_option_side_between_taps() {
let now = capture_time();
let ms = |millis| now + Duration::from_millis(millis);
let left = OPTION_KEY_MASK | LEFT_OPTION_MASK;
let right = OPTION_KEY_MASK | RIGHT_OPTION_MASK;
let binding = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers {
option: Some(crate::app_settings::ModifierSide::Right),
..Default::default()
},
key_code: None,
};
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.double_tap_modifiers = || true;
hotkey.set_double_tap_only(true);
// A Right Option tap arms the window.
assert_eq!(hotkey.process(InputEvent::Flags(right), ms(0)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(80)), None);
// Left Option is a side the binding doesn't name: a chord.
assert_eq!(hotkey.process(InputEvent::Flags(left), ms(120)), None);
assert!(matches!(hotkey.state, State::Dirty));
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(160)), None);
// The next Right Option tap is a fresh first tap, not a second one.
assert_eq!(hotkey.process(InputEvent::Flags(right), ms(200)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(280)), None);
assert!(!hotkey.is_recording());
}
#[test]
fn without_the_lab_double_tap_only_stays_off_for_a_lone_modifier() {
let now = capture_time();
let option = OPTION_KEY_MASK | LEFT_OPTION_MASK;
for (binding, flags) in [
(option_binding(), option),
(function_binding(), FUNCTION_KEY_MASK),
] {
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
hotkey.double_tap_modifiers = || false;
hotkey.set_double_tap_only(true);
// The press is an ordinary hold, exactly as before the lab.
assert_eq!(
hotkey.process(InputEvent::Flags(flags), now),
Some(HotkeyAction::Start)
);
assert!(!hotkey.is_locked());
}
}
#[test]
fn modifier_chord_requires_the_exact_binding_to_start() {
let now = capture_time();
let binding = RuntimeHotkey {
modifiers: crate::app_settings::modifiers_from_flags(CONTROL_KEY_MASK | SHIFT_KEY_MASK),
key_code: None,
};
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
assert_eq!(
hotkey.process(InputEvent::Flags(CONTROL_KEY_MASK), now),
None
);
assert_eq!(
hotkey.process(
InputEvent::Flags(CONTROL_KEY_MASK | SHIFT_KEY_MASK),
now + Duration::from_millis(50),
),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(
InputEvent::Flags(SHIFT_KEY_MASK),
now + Duration::from_secs(1),
),
Some(HotkeyAction::Finish)
);
}
#[test]
fn remapped_control_does_not_start_or_hold_right_control_dictation() {
use crate::app_settings::{HotkeyModifiers, ModifierSide, RIGHT_CONTROL_MASK};
let now = capture_time();
let binding = RuntimeHotkey {
modifiers: HotkeyModifiers {
control: Some(ModifierSide::Right),
..Default::default()
},
key_code: None,
};
let mut hotkey = DictationHotkey::with_binding(false, now, false, binding);
// Remapped Caps Lock may carry the general Control flag without a side.
assert_eq!(
hotkey.process(InputEvent::Flags(CONTROL_KEY_MASK), now),
None
);
assert!(!hotkey.is_recording());
assert_eq!(hotkey.process(InputEvent::Flags(0), now), None);
assert_eq!(
hotkey.process(
InputEvent::Flags(CONTROL_KEY_MASK | RIGHT_CONTROL_MASK),
now
),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(
InputEvent::Flags(CONTROL_KEY_MASK),
now + Duration::from_secs(1)
),
Some(HotkeyAction::Finish)
);
let mut either = DictationHotkey::with_binding(
false,
now,
false,
RuntimeHotkey {
modifiers: HotkeyModifiers {
control: Some(ModifierSide::Either),
..Default::default()
},
key_code: None,
},
);
assert_eq!(
either.process(InputEvent::Flags(CONTROL_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(
either.process(InputEvent::Flags(0), now + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
/// macOS's HID keyboard filter rewrites a Caps Lock remapped to Control as
/// Right Control. The raw HID snapshot clears that invented side, so a Right
/// Control binding ignores the remapped key while Either still starts; a
/// keyboard actually holding Right Control keeps its side.
#[test]
fn normalized_remapped_caps_lock_starts_only_a_side_less_control_binding() {
use crate::app_settings::{
CAPS_LOCK_USAGE, HotkeyModifiers, ModifierSide, PhysicalModifierKeys, RIGHT_CONTROL_MASK,
RIGHT_CONTROL_USAGE, normalized_modifier_flags,
};
let now = capture_time();
let right = RuntimeHotkey {
modifiers: HotkeyModifiers {
control: Some(ModifierSide::Right),
..Default::default()
},
key_code: None,
};
let either = RuntimeHotkey {
modifiers: HotkeyModifiers {
control: Some(ModifierSide::Either),
..Default::default()
},
key_code: None,
};
let caps_lock = Some(PhysicalModifierKeys::from_usages([CAPS_LOCK_USAGE]));
let remapped = normalized_modifier_flags(CONTROL_KEY_MASK | RIGHT_CONTROL_MASK, caps_lock);
assert_eq!(remapped, CONTROL_KEY_MASK);
let mut sided = DictationHotkey::with_binding(false, now, false, right);
assert_eq!(sided.process(InputEvent::Flags(remapped), now), None);
assert!(!sided.is_recording());
assert_eq!(
sided.process(InputEvent::Flags(0), now + Duration::from_millis(100)),
None
);
let mut any_side = DictationHotkey::with_binding(false, now, false, either);
assert_eq!(
any_side.process(InputEvent::Flags(remapped), now),
Some(HotkeyAction::Start)
);
assert_eq!(
any_side.process(InputEvent::Flags(0), now + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
let real_right = normalized_modifier_flags(
CONTROL_KEY_MASK | RIGHT_CONTROL_MASK,
Some(PhysicalModifierKeys::from_usages([
CAPS_LOCK_USAGE,
RIGHT_CONTROL_USAGE,
])),
);
assert_eq!(real_right, CONTROL_KEY_MASK | RIGHT_CONTROL_MASK);
assert_eq!(
sided.process(InputEvent::Flags(real_right), now + Duration::from_secs(2)),
Some(HotkeyAction::Start)
);
assert_eq!(
sided.process(InputEvent::Flags(0), now + Duration::from_secs(3)),
Some(HotkeyAction::Finish)
);
}
/// A real Right Control starts a capture. Pressing a remapped Caps Lock makes
/// CoreGraphics keep reporting Right Control, but releasing the physical
/// Right Control must still finish: the remapped Caps Lock cannot hold the
/// capture open.
#[test]
fn a_remapped_caps_lock_does_not_hold_a_real_right_control_capture() {
use crate::app_settings::{
CAPS_LOCK_USAGE, HotkeyModifiers, ModifierSide, PhysicalModifierKeys, RIGHT_CONTROL_MASK,
RIGHT_CONTROL_USAGE, normalized_modifier_flags,
};
let now = capture_time();
let mut hotkey = DictationHotkey::with_binding(
false,
now,
false,
RuntimeHotkey {
modifiers: HotkeyModifiers {
control: Some(ModifierSide::Right),
..Default::default()
},
key_code: None,
},
);
let both = [CAPS_LOCK_USAGE, RIGHT_CONTROL_USAGE];
let right_down = normalized_modifier_flags(
CONTROL_KEY_MASK | RIGHT_CONTROL_MASK,
Some(PhysicalModifierKeys::from_usages([RIGHT_CONTROL_USAGE])),
);
assert_eq!(right_down, CONTROL_KEY_MASK | RIGHT_CONTROL_MASK);
assert_eq!(
hotkey.process(InputEvent::Flags(right_down), now),
Some(HotkeyAction::Start)
);
// Caps Lock (remapped to Control) goes down while Right Control is held.
let with_caps = normalized_modifier_flags(
CONTROL_KEY_MASK | RIGHT_CONTROL_MASK,
Some(PhysicalModifierKeys::from_usages(both)),
);
assert_eq!(with_caps, CONTROL_KEY_MASK | RIGHT_CONTROL_MASK);
assert_eq!(
hotkey.process(
InputEvent::Flags(with_caps),
now + Duration::from_millis(200)
),
None
);
assert!(hotkey.is_recording());
// The physical Right Control lets go; Caps Lock still reports Control.
let released = normalized_modifier_flags(
CONTROL_KEY_MASK | RIGHT_CONTROL_MASK,
Some(PhysicalModifierKeys::from_usages([CAPS_LOCK_USAGE])),
);
assert_eq!(released, CONTROL_KEY_MASK);
assert_eq!(
hotkey.process(
InputEvent::Flags(released),
now + Duration::from_millis(400)
),
Some(HotkeyAction::Finish)
);
assert!(!hotkey.is_recording());
assert_eq!(
hotkey.process(InputEvent::Flags(0), now + Duration::from_millis(600)),
None
);
assert!(!hotkey.is_recording());
}
#[test]
fn tap_failure_cancels_recording_after_live_opt_in() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.wait_for_release_with_state(now, 0, false);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(InputEvent::TapDisabled, CaptureInstant::ZERO),
Some(HotkeyAction::Cancel)
);
assert!(!hotkey.is_recording());
}
#[test]
fn enabling_a_held_key_binding_waits_for_a_fresh_press() {
let now = capture_time();
let binding = RuntimeHotkey {
modifiers: Default::default(),
key_code: Some(40),
};
let mut hotkey = DictationHotkey::with_binding(false, now, false, binding);
let event = |down| InputEvent::Key {
code: 40,
down,
flags: 0,
};
hotkey.wait_for_release_with_state(now, 0, true);
assert_eq!(hotkey.process(event(true), now), None);
assert_eq!(hotkey.process(InputEvent::Flags(0), now), None);
assert_eq!(hotkey.process(event(false), now), None);
assert_eq!(hotkey.process(event(true), now), Some(HotkeyAction::Start));
}
#[test]
fn suppressing_until_release_does_not_activate_a_remaining_option_modifier() {
let now = capture_time();
let chord = OPTION_KEY_MASK | COMMAND_KEY_MASK;
let mut hotkey = test_hotkey(false, now);
hotkey.suppress_until_release();
assert_eq!(hotkey.process(InputEvent::Flags(chord), now), None);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
None
);
assert_eq!(hotkey.process(InputEvent::Flags(0), now), None);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
}
#[test]
fn waiting_for_release_does_not_block_explicit_paste() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.suppress_until_release();
let binding = HotkeyBinding::paste_last_default();
assert_eq!(
hotkey.process(
InputEvent::Key {
code: binding.key.unwrap().code,
down: true,
flags: OPTION_KEY_MASK | SHIFT_KEY_MASK,
},
now
),
Some(HotkeyAction::PasteLast)
);
}
#[test]
fn enabling_with_no_keys_held_accepts_the_next_gesture() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.wait_for_release_with_state(now, 0, false);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
}
#[test]
fn opt_in_transitions_ignore_queued_old_shortcut_edges() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
let changed_at = now + Duration::from_secs(1);
hotkey.wait_for_release_with_state(changed_at, 0, false);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
None
);
assert_eq!(
hotkey.process(InputEvent::Flags(0), now + Duration::from_millis(500)),
None
);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), changed_at),
Some(HotkeyAction::Start)
);
}
#[test]
fn a_held_modifier_only_shortcut_breaks_the_chord_once_after_the_hold_threshold() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
for press in [now, now + Duration::from_secs(5)] {
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), press),
Some(HotkeyAction::Start)
);
assert!(!hotkey.take_chord_break(press + Duration::from_millis(299)));
assert!(hotkey.take_chord_break(press + MINIMUM_HOLD_DURATION));
assert!(!hotkey.take_chord_break(press + Duration::from_secs(2)));
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), press + Duration::from_secs(3)),
Some(HotkeyAction::Finish)
);
assert!(!hotkey.take_chord_break(press + Duration::from_secs(4)));
}
}
#[test]
fn short_taps_chords_and_other_bindings_never_break_the_chord() {
let now = capture_time();
let later = now + Duration::from_secs(1);
let mut tap = test_hotkey(false, now);
tap.process(InputEvent::Flags(OPTION_KEY_MASK), now);
tap.process(
InputEvent::Flags(NO_FLAGS),
now + Duration::from_millis(200),
);
assert!(!tap.take_chord_break(later));
for (chord, cause) in [
(option_key(0, true, OPTION_KEY_MASK), DiscardCause::Key),
(hid_key(18), DiscardCause::HidKey),
(InputEvent::MouseDown, DiscardCause::Mouse),
(
InputEvent::Flags(OPTION_KEY_MASK | SHIFT_KEY_MASK),
DiscardCause::ExtraModifier,
),
] {
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert_eq!(
hotkey.process(chord, now + Duration::from_millis(100)),
Some(HotkeyAction::Discard(cause))
);
assert!(!hotkey.take_chord_break(later), "{cause:?}");
}
// A key held past the threshold is already a chord to other apps.
let mut held_key = test_hotkey(false, now);
held_key.process(InputEvent::Flags(OPTION_KEY_MASK), now);
held_key.process(
option_key(0, true, OPTION_KEY_MASK),
now + Duration::from_millis(400),
);
assert!(!held_key.take_chord_break(later));
// Keyed shortcuts are consumed, and Globe's own tap action is the system's.
let mut keyed = DictationHotkey::with_binding(false, now, true, shift_space_binding());
assert_eq!(
keyed.process(shift_space_event(true), now),
Some(HotkeyAction::Start)
);
let mut globe = DictationHotkey::with_binding(false, now, true, function_binding());
assert_eq!(
globe.process(InputEvent::Flags(FUNCTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert!(!keyed.take_chord_break(later));
assert!(!globe.take_chord_break(later));
// A suspended press (such as a refused start) owes nothing.
let mut suspended = test_hotkey(false, now);
suspended.process(InputEvent::Flags(OPTION_KEY_MASK), now);
suspended.suspend();
assert!(!suspended.take_chord_break(later));
}
#[test]
fn locked_and_toggle_captures_break_the_chord_only_for_presses_hex_owns() {
let now = capture_time();
let at = |ms| now + Duration::from_millis(ms);
// Double-tap lock: both presses are taps, which stay taps.
let mut locked = test_hotkey(false, now);
locked.process(InputEvent::Flags(OPTION_KEY_MASK), now);
locked.process(InputEvent::Flags(NO_FLAGS), at(100));
locked.process(InputEvent::Flags(OPTION_KEY_MASK), at(200));
locked.process(InputEvent::Flags(NO_FLAGS), at(300));
assert!(locked.is_locked());
assert!(!locked.take_chord_break(at(2_000)));
// The press that finishes the lock is Hex's.
assert_eq!(
locked.process(InputEvent::Flags(OPTION_KEY_MASK), at(3_000)),
Some(HotkeyAction::Finish)
);
assert!(locked.take_chord_break(at(3_000)));
assert!(!locked.take_chord_break(at(3_050)));
// Released before the loop got to it: nothing to break.
let mut programmatic = test_hotkey(false, now);
assert!(programmatic.lock());
programmatic.process(InputEvent::Flags(OPTION_KEY_MASK), at(1_000));
programmatic.process(InputEvent::Flags(NO_FLAGS), at(1_060));
assert!(!programmatic.take_chord_break(at(1_060)));
// Toggle: the starting press is Hex's once past the chord grace.
let grace = crate::feedback::CHORD_GRACE;
let mut toggle = test_hotkey(false, now);
toggle.set_toggle(true);
toggle.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert!(!toggle.take_chord_break(now));
assert!(!toggle.take_chord_break(now + (grace - Duration::from_millis(1))));
assert!(toggle.take_chord_break(now + grace));
toggle.process(InputEvent::Flags(NO_FLAGS), at(80));
assert!(toggle.is_locked());
assert!(!toggle.take_chord_break(at(1_000)));
toggle.process(InputEvent::Flags(OPTION_KEY_MASK), at(2_000));
assert!(toggle.take_chord_break(at(2_000)));
// Shift pressed with it, as for Option-Shift-S, discards the press first.
let mut chord = test_hotkey(false, now);
chord.set_toggle(true);
chord.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert_eq!(
chord.process(InputEvent::Flags(OPTION_KEY_MASK | SHIFT_KEY_MASK), at(20)),
Some(HotkeyAction::Discard(DiscardCause::ExtraModifier))
);
assert!(!chord.take_chord_break(at(1_000)));
}
/// The chord breaker is posted through both taps; its mark keeps it from
/// becoming the user's chord or HID chord evidence, and the key tap drops
/// it so the focused app never beeps at it. Hex's other synthetic keys,
/// such as the paste shortcut, still reach the app.
#[test]
fn marked_chord_breaker_never_reaches_the_shortcut_machines_or_the_app() {
let breaker = crate::keyboard::CHORD_BREAKER_KEY_CODE;
for (code, marked) in [(breaker, true), (breaker, false), (9, true)] {
let (mut context, receiver) = test_tap_context(false);
// SAFETY: This locally owned event and context live through both callbacks.
unsafe {
let user_info = (&mut context as *mut EventTapContext).cast();
for event_type in [EVENT_KEY_DOWN, EVENT_KEY_UP] {
let event = CGEventCreate(ptr::null_mut());
assert!(!event.is_null());
CGEventSetType(event, event_type);
CGEventSetFlags(event, OPTION_KEY_MASK);
CGEventSetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE, i64::from(code));
if marked {
CGEventSetIntegerValueField(
event,
EVENT_SOURCE_USER_DATA,
crate::keyboard::SYNTHETIC_EVENT_MARKER,
);
}
let returned = event_callback(ptr::null_mut(), event_type, event, user_info);
if marked && code == breaker {
assert!(returned.is_null());
} else {
assert_eq!(returned, event);
}
if event_type == EVENT_KEY_DOWN {
let returned =
physical_event_callback(ptr::null_mut(), event_type, event, user_info);
assert_eq!(returned, event);
}
CFRelease(event.cast_const());
}
}
let observed = receiver.try_iter().count();
if marked {
assert_eq!(observed, 0);
} else {
assert_eq!(observed, 3, "an unmarked key is the user's chord");
}
}
}
/// Labs › Microphone key alone: these drive the session tap's callback with
/// real CGEvents, like the annotated tap's own callback tests above. The labs
/// gate, the process-wide hotkeys, and the recorder feed are global, so the
/// tests share one lock and put them back.
static MICROPHONE_KEY_TESTS: Mutex<()> = Mutex::new(());
/// The microphone key's flags as observed: SecondaryFn and NonCoalesced.
const MICROPHONE_KEY_FLAGS: u64 = 0x800100;
struct MicrophoneKeyTest {
_lock: std::sync::MutexGuard<'static, ()>,
}
impl MicrophoneKeyTest {
/// Turns Labs › Microphone key alone on (or off) and clears everything the
/// callback reads.
fn new(lab: bool) -> Self {
let lock = MICROPHONE_KEY_TESTS
.lock()
.unwrap_or_else(|error| error.into_inner());
crate::labs::apply(&crate::app_settings::LabsSettings {
microphone_key: lab,
..Default::default()
});
crate::app_settings::install_test_hotkeys(RuntimeHotkeys::default());
crate::app_settings::set_hotkey_capture_active(false);
crate::shortcut_pause::reconcile(false);
crate::suppression::dictation_key::clear_captured();
Self { _lock: lock }
}
/// Binds the microphone key to Dictation alone, like the recorder saves.
fn bind_dictation(&self) {
crate::app_settings::install_test_hotkeys(RuntimeHotkeys {
dictation: RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::default(),
key_code: Some(MICROPHONE_KEY_CODE),
},
..RuntimeHotkeys::default()
});
}
}
impl Drop for MicrophoneKeyTest {
fn drop(&mut self) {
crate::labs::apply(&crate::app_settings::LabsSettings::default());
crate::app_settings::install_test_hotkeys(RuntimeHotkeys::default());
crate::app_settings::set_hotkey_capture_active(false);
crate::shortcut_pause::reconcile(false);
crate::suppression::dictation_key::clear_captured();
}
}
/// One microphone-key event as macOS sends it, released by the caller.
fn microphone_key_event(event_type: u32) -> EventRef {
// SAFETY: a locally created event, released by the caller.
unsafe {
let event = CGEventCreate(ptr::null_mut());
assert!(!event.is_null());
CGEventSetType(event, event_type);
CGEventSetFlags(event, MICROPHONE_KEY_FLAGS);
CGEventSetTimestamp(event, 0);
CGEventSetIntegerValueField(
event,
KEYBOARD_EVENT_KEYCODE,
i64::from(MICROPHONE_KEY_CODE),
);
event
}
}
fn run_dictation_callback(
context: &mut EventTapContext,
event_type: u32,
event: EventRef,
) -> EventRef {
// SAFETY: the context and event live through the call.
unsafe {
dictation_key::dictation_key_callback(
ptr::null_mut(),
event_type,
event,
(context as *mut EventTapContext).cast(),
)
}
}
/// Whether the tap consumed a fresh microphone-key event of this type.
fn dictation_press(context: &mut EventTapContext, event_type: u32) -> bool {
let event = microphone_key_event(event_type);
let consumed = run_dictation_callback(context, event_type, event).is_null();
// SAFETY: the event was created here and is released once.
unsafe { CFRelease(event.cast_const()) };
consumed
}
fn dictation_events(receiver: &mpsc::Receiver<ObservedInputEvent>) -> Vec<InputEvent> {
receiver.try_iter().map(|observed| observed.event).collect()
}
/// A bound press is consumed and drives the listener; its release follows it
/// even after the state changes, so the app never sees half a key.
#[test]
fn the_dictation_tap_takes_a_bound_microphone_key_and_its_release() {
let test = MicrophoneKeyTest::new(true);
test.bind_dictation();
let (mut context, receiver) = test_tap_context(false);
assert!(dictation_press(&mut context, EVENT_KEY_DOWN));
// The binding is gone by the release, and the press this tap took still
// owns it.
crate::app_settings::install_test_hotkeys(RuntimeHotkeys::default());
assert!(dictation_press(&mut context, EVENT_KEY_UP));
let events = dictation_events(&receiver);
assert_eq!(events.len(), 2);
assert!(matches!(
events[0],
InputEvent::Key {
code: MICROPHONE_KEY_CODE,
down: true,
flags: MICROPHONE_KEY_FLAGS,
}
));
assert!(matches!(
events[1],
InputEvent::Key {
code: MICROPHONE_KEY_CODE,
down: false,
..
}
));
}
/// With the lab on but nothing bound, macOS keeps the key: both events pass.
#[test]
fn the_dictation_tap_passes_an_unbound_microphone_key_through() {
let _test = MicrophoneKeyTest::new(true);
let (mut context, receiver) = test_tap_context(false);
assert!(!dictation_press(&mut context, EVENT_KEY_DOWN));
assert!(!dictation_press(&mut context, EVENT_KEY_UP));
assert!(dictation_events(&receiver).is_empty());
}
/// Labs › Pause from menu bar suspends every shortcut, microphone key too.
#[test]
fn the_dictation_tap_passes_a_paused_microphone_key_through() {
let test = MicrophoneKeyTest::new(true);
test.bind_dictation();
crate::shortcut_pause::toggle();
assert!(crate::shortcut_pause::suspended());
let (mut context, receiver) = test_tap_context(false);
assert!(!dictation_press(&mut context, EVENT_KEY_DOWN));
assert!(!dictation_press(&mut context, EVENT_KEY_UP));
assert!(dictation_events(&receiver).is_empty());
}
/// While the window records a shortcut, the press goes to the recorder and
/// the listener never sees it; the release is consumed and queued nothing.
#[test]
fn the_dictation_tap_queues_a_recording_press_for_the_recorder() {
let test = MicrophoneKeyTest::new(true);
// Recording takes the key before the binding it is replacing.
test.bind_dictation();
crate::app_settings::set_hotkey_capture_active(true);
let (mut context, receiver) = test_tap_context(false);
assert!(dictation_press(&mut context, EVENT_KEY_DOWN));
assert!(dictation_press(&mut context, EVENT_KEY_UP));
assert!(dictation_events(&receiver).is_empty());
let captured = crate::suppression::dictation_key::take_captured();
assert_eq!(captured.len(), 1, "one press, no release");
assert_eq!(captured[0].code, MICROPHONE_KEY_CODE);
assert_eq!(captured[0].flags, MICROPHONE_KEY_FLAGS);
assert!(!captured[0].repeat);
}
/// Hex's own synthetic events are not the user's key, even when it is bound.
#[test]
fn the_dictation_tap_passes_hexs_own_synthetic_microphone_key_through() {
let test = MicrophoneKeyTest::new(true);
test.bind_dictation();
let (mut context, receiver) = test_tap_context(false);
let event = microphone_key_event(EVENT_KEY_DOWN);
// SAFETY: the event was created here and is released once.
unsafe {
CGEventSetIntegerValueField(
event,
EVENT_SOURCE_USER_DATA,
crate::keyboard::SYNTHETIC_EVENT_MARKER,
);
}
let consumed = run_dictation_callback(&mut context, EVENT_KEY_DOWN, event);
// SAFETY: as above.
unsafe { CFRelease(event.cast_const()) };
assert!(!consumed.is_null());
assert!(dictation_events(&receiver).is_empty());
}
/// macOS can disable the tap at any moment; the pseudo event has no event to
/// read, and a press whose release may have been missed is forgotten.
#[test]
fn the_dictation_tap_recovers_from_a_disable_and_forgets_its_press() {
let test = MicrophoneKeyTest::new(true);
test.bind_dictation();
let (mut context, receiver) = test_tap_context(false);
assert!(dictation_press(&mut context, EVENT_KEY_DOWN));
let returned =
run_dictation_callback(&mut context, EVENT_TAP_DISABLED_BY_TIMEOUT, ptr::null_mut());
assert!(returned.is_null());
// The press is forgotten, so its release passes to the app.
assert!(!dictation_press(&mut context, EVENT_KEY_UP));
assert!(matches!(
dictation_events(&receiver).last(),
Some(InputEvent::TapDisabled)
));
}
#[test]
fn option_double_tap_locks_until_option_is_pressed_again() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), now + Duration::from_millis(80)),
Some(HotkeyAction::Finish)
);
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
now + Duration::from_millis(180)
),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(
InputEvent::Flags(NO_FLAGS),
now + Duration::from_millis(260)
),
None
);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(InputEvent::MouseDown, now + Duration::from_secs(1)),
None
);
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
now + Duration::from_secs(2)
),
Some(HotkeyAction::Finish)
);
assert!(!hotkey.is_recording());
}
#[test]
fn second_tap_finishes_as_press_and_hold_when_double_tap_cannot_lock() {
let now = capture_time();
// Double-tap lock disabled, or enabled with the second release outside its window.
for (double_tap_enabled, second_release_ms) in [(false, 260), (true, 450)] {
let mut hotkey =
DictationHotkey::with_binding(false, now, double_tap_enabled, option_binding());
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
hotkey.process(InputEvent::Flags(NO_FLAGS), now + Duration::from_millis(80));
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
now + Duration::from_millis(180),
);
assert_eq!(
hotkey.process(
InputEvent::Flags(NO_FLAGS),
now + Duration::from_millis(second_release_ms)
),
Some(HotkeyAction::Finish),
"double_tap_enabled={double_tap_enabled}"
);
assert!(!hotkey.is_recording());
}
}
#[test]
fn live_double_tap_only_change_preserves_capture_until_release() {
use crate::dictation::{DictationCapture, Finish};
let now = capture_time();
let binding = shift_space_binding();
let mut hotkey = DictationHotkey::with_binding(false, now, true, binding);
let mut capture = DictationCapture::new(16_000);
let key = |code, down| InputEvent::Key {
code,
down,
flags: SHIFT_KEY_MASK,
};
assert_eq!(
hotkey.process(key(49, true), now),
Some(HotkeyAction::Start)
);
capture.start_at(now);
capture.ingest(&[0.5; 8_000], now + Duration::from_millis(500));
hotkey.set_double_tap_only(true);
hotkey.set_double_tap_only(true);
assert!(hotkey.is_recording());
assert!(capture.is_recording());
let ended_at = now + Duration::from_millis(600);
capture.ingest(&[0.5; 1_600], ended_at);
assert_eq!(
hotkey.process(key(49, false), ended_at),
Some(HotkeyAction::Finish)
);
let Finish::Transcribe(clip) = capture.finish(ended_at) else {
panic!("the active hold must finish after changing double-tap-only");
};
assert_eq!(clip.duration_ms(), 600);
assert!(!hotkey.is_recording());
assert!(!capture.is_recording());
hotkey.process(InputEvent::Flags(0), ended_at);
assert_eq!(
hotkey.process(key(49, true), now + Duration::from_secs(1)),
None,
"the next gesture must use double-tap-only"
);
assert!(!hotkey.is_recording());
}
#[test]
fn live_double_tap_disable_prevents_the_second_release_from_locking() {
use crate::dictation::{DictationCapture, Finish};
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
let mut capture = DictationCapture::new(16_000);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
capture.start_at(now);
let first_release = now + Duration::from_millis(80);
capture.ingest(&[0.5; 1_280], first_release);
assert_eq!(
hotkey.process(InputEvent::Flags(0), first_release),
Some(HotkeyAction::Finish)
);
assert!(matches!(capture.finish(first_release), Finish::Discard));
let second_press = now + Duration::from_millis(180);
capture.ingest(&[0.5; 1_600], second_press);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), second_press),
Some(HotkeyAction::Start)
);
capture.start_at(second_press);
hotkey.set_double_tap_enabled(false);
hotkey.set_double_tap_only(false);
assert!(hotkey.is_recording());
assert!(capture.is_recording());
let second_release = now + Duration::from_millis(260);
capture.ingest(&[0.5; 1_280], second_release);
assert_eq!(
hotkey.process(InputEvent::Flags(0), second_release),
Some(HotkeyAction::Finish)
);
assert!(matches!(capture.finish(second_release), Finish::Discard));
assert!(!hotkey.is_recording());
assert!(!capture.is_recording());
}
#[test]
fn early_chord_discards_until_everything_is_released() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert_eq!(
hotkey.process(
InputEvent::Key {
code: 0,
down: true,
flags: OPTION_KEY_MASK,
},
now + Duration::from_millis(100),
),
Some(HotkeyAction::Discard(DiscardCause::Key))
);
assert_eq!(
hotkey.process(
InputEvent::Flags(NO_FLAGS),
now + Duration::from_millis(150)
),
None
);
assert_eq!(
hotkey.process(
InputEvent::Key {
code: 0,
down: false,
flags: NO_FLAGS,
},
now + Duration::from_millis(200),
),
None
);
assert!(!hotkey.is_recording());
}
fn option_key(code: u16, down: bool, flags: u64) -> InputEvent {
InputEvent::Key { code, down, flags }
}
fn hid_key(code: u16) -> InputEvent {
InputEvent::PhysicalKeyDown {
code,
timing: HidTiming {
raw: 0,
clock: HidClock::Nanos,
received_at: CaptureInstant::from_nanos(0),
},
}
}
// Another app's global Option-1 hides the digit from the session tap, so
// the HID press is the only sign of the chord.
#[test]
fn hid_evidence_discards_a_chord_hidden_by_a_global_shortcut() {
let now = capture_time();
for (key, chord_ms) in [(18, 20), (19, 100), (20, 200), (49, 150)] {
let mut hotkey = test_hotkey(false, now);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(hid_key(key), now + Duration::from_millis(chord_ms)),
Some(HotkeyAction::Discard(DiscardCause::HidKey)),
"key {key} at {chord_ms} ms"
);
for release_ms in [chord_ms + 50, 1_500] {
assert_eq!(
hotkey.process(
InputEvent::Flags(NO_FLAGS),
now + Duration::from_millis(release_ms)
),
None
);
}
assert!(!hotkey.is_recording());
// The discarded chord is not the first tap of a double tap.
let again = now + Duration::from_millis(1_600);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), again),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), again + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
}
#[test]
fn hid_evidence_and_visible_chord_keys_discard_once_in_either_release_order() {
let now = capture_time();
for key_released_first in [true, false] {
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
let chord = now + Duration::from_millis(60);
assert_eq!(
hotkey.process(hid_key(18), chord),
Some(HotkeyAction::Discard(DiscardCause::HidKey))
);
assert_eq!(
hotkey.process(option_key(18, true, OPTION_KEY_MASK), chord),
None
);
let mut releases = vec![
option_key(18, false, OPTION_KEY_MASK),
InputEvent::Flags(NO_FLAGS),
];
if !key_released_first {
releases = vec![InputEvent::Flags(NO_FLAGS), option_key(18, false, NO_FLAGS)];
}
for (offset, event) in releases.into_iter().enumerate() {
let at = chord + Duration::from_millis(40 * (offset as u64 + 1));
assert_eq!(hotkey.process(event, at), None);
}
assert!(!hotkey.is_recording());
assert!(hotkey.held.keys_empty());
let again = now + Duration::from_secs(1);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), again),
Some(HotkeyAction::Start),
"key_released_first={key_released_first}"
);
}
}
// On 2026-10-22 two quick Option-1/Option-2 switches locked dictation:
// with the digits hidden, the two Option taps looked like a double tap.
#[test]
fn hidden_chords_in_quick_succession_never_double_tap_lock() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
let mut actions = Vec::new();
for (at_ms, event) in [
(0, InputEvent::Flags(OPTION_KEY_MASK)),
(40, hid_key(18)),
(160, InputEvent::Flags(NO_FLAGS)),
(280, InputEvent::Flags(OPTION_KEY_MASK)),
(310, hid_key(19)),
(400, InputEvent::Flags(NO_FLAGS)),
] {
actions.extend(hotkey.process(event, now + Duration::from_millis(at_ms)));
}
assert_eq!(
actions,
[
HotkeyAction::Start,
HotkeyAction::Discard(DiscardCause::HidKey),
HotkeyAction::Start,
HotkeyAction::Discard(DiscardCause::HidKey)
]
);
assert!(!hotkey.is_recording());
}
#[test]
fn hid_evidence_that_overtakes_its_press_prevents_the_capture() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
let chord = now + Duration::from_millis(15);
assert_eq!(hotkey.process(hid_key(18), chord), None);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
None
);
assert_eq!(
hotkey.process(
InputEvent::Flags(NO_FLAGS),
now + Duration::from_millis(500)
),
None
);
assert!(!hotkey.is_recording());
// A later overtaking press must not hide the early one.
let mut hotkey = test_hotkey(false, now);
for chord_ms in [20, 400] {
hotkey.process(hid_key(18), now + Duration::from_millis(chord_ms));
}
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
None
);
// Delayed evidence of a key pressed before the shortcut is no chord.
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert_eq!(
hotkey.process(
hid_key(0),
now.checked_sub(Duration::from_millis(5)).unwrap()
),
None
);
assert!(hotkey.is_recording());
// A key pressed before the shortcut does not block it.
let mut hotkey = test_hotkey(false, now);
let later = now + Duration::from_secs(2);
hotkey.process(hid_key(0), later);
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
later + Duration::from_millis(5)
),
Some(HotkeyAction::Start)
);
}
// Kit's Studio, 2026-10-25: holds discarded ~20 ms after the press. Suspect:
// the HID press of a key typed just before Option, delivered late in Mach
// ticks, reads as a chord. The conversion and the guard keep it a hold.
#[test]
fn late_hid_evidence_in_mach_ticks_of_a_key_before_the_press_keeps_the_hold() {
let now = CaptureInstant::now();
let press = now.checked_sub(Duration::from_millis(100)).unwrap();
for typed_before_ms in [1, 5, 30] {
let typed = press
.checked_sub(Duration::from_millis(typed_before_ms))
.unwrap();
for delivered_after_press_ms in [1, 20, 60] {
let received = press + Duration::from_millis(delivered_after_press_ms);
let raw = mach_ticks_for(typed);
let (at, clock) = physical_event_instant(raw, received);
assert_eq!(clock, HidClock::MachTicks);
assert!(signed_ms(at, typed).abs() < 0.001);
let mut hotkey = test_hotkey(false, press);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), press),
Some(HotkeyAction::Start)
);
let event = InputEvent::PhysicalKeyDown {
code: 0,
timing: HidTiming {
raw,
clock,
received_at: received,
},
};
assert_eq!(hotkey.process(event, at), None);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), press + Duration::from_secs(1)),
Some(HotkeyAction::Finish)
);
}
}
}
#[test]
fn early_mouse_down_discards_with_its_cause() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert_eq!(
hotkey.process(InputEvent::MouseDown, now + Duration::from_millis(20)),
Some(HotkeyAction::Discard(DiscardCause::Mouse))
);
}
#[test]
fn held_modifier_only_shortcut_plus_any_key_discards_after_the_hold_threshold() {
let now = capture_time();
for chord_ms in [300, 450, 2_000] {
for (key, hidden) in [(18, true), (19, true), (20, true), (49, true), (18, false)] {
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
let chord = now + Duration::from_millis(chord_ms);
let event = if hidden {
hid_key(key)
} else {
option_key(key, true, OPTION_KEY_MASK)
};
assert_eq!(
hotkey.process(event, chord),
Some(HotkeyAction::Discard(if hidden {
DiscardCause::HidKey
} else {
DiscardCause::Key
})),
"key {key} hidden={hidden} at {chord_ms} ms"
);
if !hidden {
hotkey.process(option_key(key, false, OPTION_KEY_MASK), chord);
}
assert_eq!(
hotkey.process(
InputEvent::Flags(NO_FLAGS),
chord + Duration::from_millis(50)
),
None
);
assert!(!hotkey.is_recording());
}
}
// Toggle captures keep recording, and keyed shortcuts keep the threshold.
let mut hotkey = test_hotkey(false, now);
hotkey.set_toggle(true);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert_eq!(
hotkey.process(hid_key(18), now + Duration::from_millis(500)),
None
);
assert!(hotkey.is_recording());
let mut hotkey = DictationHotkey::with_binding(false, now, true, shift_space_binding());
hotkey.process(shift_space_event(true), now);
assert_eq!(
hotkey.process(
InputEvent::Key {
code: 0,
down: true,
flags: SHIFT_KEY_MASK
},
now + Duration::from_millis(500)
),
None
);
assert!(hotkey.is_recording());
}
/// Labs › Hold through other keys: with the lab on, a key joining a held
/// modifier-only press a second or more in reaches the app and the capture
/// keeps recording, and the release still finishes it. Inside the first
/// second the chord still discards, and off, every chord does.
#[test]
fn hold_through_keys_keeps_a_long_hold_through_a_joining_key() {
let now = capture_time();
let press = InputEvent::Flags(OPTION_KEY_MASK);
let release = InputEvent::Flags(NO_FLAGS);
for (chord_ms, hidden) in [(0, true), (500, true), (500, false), (999, false)] {
let mut hotkey = test_hotkey(false, now);
hotkey.hold_through_keys = || true;
hotkey.process(press, now);
let chord = now + Duration::from_millis(chord_ms);
let event = if hidden {
hid_key(18)
} else {
option_key(18, true, OPTION_KEY_MASK)
};
assert_eq!(
hotkey.process(event, chord),
Some(HotkeyAction::Discard(if hidden {
DiscardCause::HidKey
} else {
DiscardCause::Key
})),
"hidden={hidden} at {chord_ms} ms, before the first second"
);
assert!(!hotkey.is_recording());
}
// At and after one second the key is the app's, hidden or visible, as
// long as the shortcut is held.
for (chord_ms, hidden) in [(1_000, true), (1_000, false), (5_000, true), (5_000, false)] {
let mut hotkey = test_hotkey(false, now);
hotkey.hold_through_keys = || true;
hotkey.process(press, now);
let chord = now + Duration::from_millis(chord_ms);
let event = if hidden {
hid_key(18)
} else {
option_key(18, true, OPTION_KEY_MASK)
};
assert_eq!(
hotkey.process(event, chord),
None,
"hidden={hidden} at {chord_ms} ms keeps recording"
);
assert!(hotkey.is_recording());
// The extra key is still down as the shortcut lets go: Finish.
let released = chord + Duration::from_millis(200);
assert_eq!(
hotkey.process(release, released),
Some(HotkeyAction::Finish)
);
assert!(!hotkey.is_recording());
}
// Once both are up, the next press pairs with that release as any press
// after a release does: it starts, and its release inside the double-tap
// window locks the capture for hands-free dictation.
let mut hotkey = test_hotkey(false, now);
hotkey.hold_through_keys = || true;
hotkey.process(press, now);
hotkey.process(
option_key(18, true, OPTION_KEY_MASK),
now + Duration::from_millis(1_500),
);
let released = now + Duration::from_millis(2_000);
assert_eq!(
hotkey.process(release, released),
Some(HotkeyAction::Finish)
);
hotkey.process(option_key(18, false, OPTION_KEY_MASK), released);
assert_eq!(
hotkey.process(press, released + Duration::from_millis(100)),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(release, released + Duration::from_millis(200)),
None
);
assert!(hotkey.is_locked());
// Off, a long hold still discards the key.
let mut hotkey = test_hotkey(false, now);
hotkey.process(press, now);
assert_eq!(
hotkey.process(hid_key(18), now + Duration::from_millis(5_000)),
Some(HotkeyAction::Discard(DiscardCause::HidKey))
);
assert!(!hotkey.is_recording());
}
/// Return pressed while dictating (the session event and its HID echo) keeps
/// the capture once the hold made the press Hex's; inside the threshold it is
/// still Option-Return, a chord.
#[test]
fn return_after_the_hold_threshold_keeps_a_held_capture() {
let now = capture_time();
for code in [36, 76] {
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
for (offset, event) in [
(809, hid_key(code)),
(809, option_key(code, true, OPTION_KEY_MASK)),
(880, option_key(code, false, OPTION_KEY_MASK)),
(21_721, hid_key(code)),
(21_721, option_key(code, true, OPTION_KEY_MASK)),
(21_800, option_key(code, false, OPTION_KEY_MASK)),
] {
assert_eq!(
hotkey.process(event, now + Duration::from_millis(offset)),
None,
"key {code} at {offset} ms"
);
assert!(hotkey.is_recording());
}
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), now + Duration::from_secs(22)),
Some(HotkeyAction::Finish)
);
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert_eq!(
hotkey.process(hid_key(code), now + Duration::from_millis(100)),
Some(HotkeyAction::Discard(DiscardCause::HidKey))
);
}
}
/// Escape while the Hold shortcut is held past the threshold cancels it, with
/// the shortcut's modifier still in its flags; earlier it may be
/// Option-Escape, and a hands-free capture never takes it (#786).
#[test]
fn escape_cancels_a_held_capture_after_the_hold_threshold() {
let now = capture_time();
let ms = |offset| now + Duration::from_millis(offset);
let escape = |down| option_key(ESCAPE_KEY_CODE, down, OPTION_KEY_MASK);
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert!(!hotkey.takes_escape(ms(200)));
assert_eq!(hotkey.process(escape(true), ms(200)), None);
assert_eq!(hotkey.process(escape(false), ms(250)), None);
assert!(hotkey.is_recording());
assert!(hotkey.takes_escape(ms(300)));
assert_eq!(
hotkey.process(escape(true), ms(1_200)),
Some(HotkeyAction::CancelShortcut)
);
assert!(!hotkey.is_recording());
assert!(!hotkey.takes_escape(ms(1_200)));
assert_eq!(hotkey.process(escape(false), ms(1_250)), None);
assert_eq!(hotkey.process(InputEvent::Flags(NO_FLAGS), ms(1_400)), None);
// A double-tap lock is hands-free: Escape stays with the app.
let mut hotkey = test_hotkey(false, now);
hotkey.set_double_tap_enabled(true);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
hotkey.process(InputEvent::Flags(NO_FLAGS), ms(80));
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), ms(180));
hotkey.process(InputEvent::Flags(NO_FLAGS), ms(260));
assert!(hotkey.is_recording());
assert!(!hotkey.takes_escape(ms(2_000)));
let plain_escape = |down| option_key(ESCAPE_KEY_CODE, down, NO_FLAGS);
assert_eq!(hotkey.process(plain_escape(true), ms(2_000)), None);
assert!(hotkey.is_recording());
// Toggle keeps its own cancel shortcut.
let mut hotkey = toggle_hotkey(now, false);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
assert!(!hotkey.takes_escape(ms(1_000)));
assert_eq!(hotkey.process(escape(true), ms(1_000)), None);
assert!(hotkey.is_recording());
}
#[test]
fn hid_evidence_while_locked_is_ignored() {
let now = capture_time();
let mut hotkey = test_hotkey(false, now);
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now);
hotkey.process(InputEvent::Flags(NO_FLAGS), now + Duration::from_millis(80));
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK),
now + Duration::from_millis(180),
);
hotkey.process(
InputEvent::Flags(NO_FLAGS),
now + Duration::from_millis(260),
);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(hid_key(18), now + Duration::from_millis(400)),
None
);
assert!(hotkey.is_recording());
}
#[test]
fn chord_evidence_skips_escape_and_hex_shortcuts() {
let hotkeys = RuntimeHotkeys::default();
assert!(is_chord_evidence(18, OPTION_KEY_MASK, hotkeys));
assert!(is_chord_evidence(49, OPTION_KEY_MASK, hotkeys));
assert!(!is_chord_evidence(
ESCAPE_KEY_CODE,
OPTION_KEY_MASK,
hotkeys
));
let paste_last = hotkeys
.paste_last
.expect("paste last has a default binding");
let code = paste_last.key_code.expect("paste last binds a key");
assert!(!is_chord_evidence(
code,
OPTION_KEY_MASK | SHIFT_KEY_MASK,
hotkeys
));
assert!(is_chord_evidence(code, OPTION_KEY_MASK, hotkeys));
}
#[test]
fn physical_event_instants_accept_mach_ticks_or_nanoseconds() {
let now = CaptureInstant::now();
let earlier = now.checked_sub(Duration::from_millis(8)).unwrap();
let (converted, clock) = physical_event_instant(earlier.as_nanos(), now);
assert_eq!(converted, earlier);
// With a 1:1 timebase (Intel) both readings agree and Mach wins.
let unit_timebase = CaptureInstant::from_mach_ticks(1_000) == CaptureInstant::from_nanos(1_000);
assert_eq!(
clock,
if unit_timebase {
HidClock::MachTicks
} else {
HidClock::Nanos
}
);
let (converted, clock) = physical_event_instant(mach_ticks_for(earlier), now);
assert_eq!(clock, HidClock::MachTicks);
assert!(now.duration_since(converted) < Duration::from_millis(9));
assert!(converted <= now);
assert_eq!(physical_event_instant(1, now), (now, HidClock::Arrival));
}
fn mach_ticks_for(instant: CaptureInstant) -> u64 {
// Binary search the tick count whose conversion reaches `instant`.
let (mut low, mut high) = (0_u64, instant.as_nanos().max(1));
while low < high {
let mid = low + (high - low) / 2;
if CaptureInstant::from_mach_ticks(mid) < instant {
low = mid + 1;
} else {
high = mid;
}
}
low
}
/// Escape pressed with the shortcut is Option-Escape until the hold
/// threshold, then cancels the held capture.
#[test]
fn escape_ends_a_held_capture_only_after_the_hold_threshold() {
let now = capture_time();
let mut hotkey = test_hotkey(true, now);
let escape = |down| InputEvent::Key {
code: ESCAPE_KEY_CODE,
down,
flags: OPTION_KEY_MASK,
};
assert_eq!(hotkey.process(escape(true), now), None);
assert_eq!(hotkey.process(escape(false), now), None);
assert!(hotkey.is_recording());
assert_eq!(
hotkey.process(escape(true), now + Duration::from_secs(300)),
Some(HotkeyAction::CancelShortcut)
);
assert!(!hotkey.is_recording());
assert_eq!(
hotkey.process(InputEvent::Flags(NO_FLAGS), now + Duration::from_secs(301)),
None
);
}
/// A capsule list left open when captures are turned off takes no keys.
#[cfg(hex_capture)]
#[test]
fn the_list_takes_keys_only_while_captures_are_on() {
assert!(list_takes_keys(true, true, false));
assert!(!list_takes_keys(false, true, false));
assert!(!list_takes_keys(true, false, false));
assert!(!list_takes_keys(true, true, true));
}
/// Escape during a dictation hold while a screen capture records ends
/// neither: the capture shortcut lets it pass, and the dictation keeps
/// recording.
#[cfg(hex_capture)]
#[test]
fn escape_during_a_capture_ends_nothing() {
use crate::capture_host::{CaptureShortcut, ShortcutAction, ShortcutActivity};
let now = capture_time();
let mut hotkey = test_hotkey(true, now);
let escape = InputEvent::Key {
code: ESCAPE_KEY_CODE,
down: true,
flags: OPTION_KEY_MASK,
};
let mut capture = CaptureShortcut::default();
let recording = ShortcutActivity::Recording {
elapsed: std::time::Duration::from_secs(5),
};
assert_eq!(
capture.input(escape, RuntimeHotkeys::default(), recording),
ShortcutAction::None
);
assert!(!capture.takes_escape());
assert_eq!(hotkey.process(escape, now), None);
assert!(hotkey.is_recording());
}
#[test]
fn escape_is_suppressed_only_while_hex_takes_it() {
let mut suppression = ShortcutSuppression::default();
let hotkeys = RuntimeHotkeys::default();
let down = InputEvent::Key {
code: ESCAPE_KEY_CODE,
down: true,
flags: NO_FLAGS,
};
let up = InputEvent::Key {
code: ESCAPE_KEY_CODE,
down: false,
flags: NO_FLAGS,
};
assert!(!suppression.process_all(down, hotkeys, true, false));
assert!(!suppression.process_all(up, hotkeys, true, false));
assert!(!suppression.process_all(down, hotkeys, false, true));
assert!(!suppression.process_all(up, hotkeys, false, true));
// Hex can stop taking Escape before the key lifts;
// the repeat and release keep the press's suppression decision.
assert!(suppression.process_all(down, hotkeys, true, true));
assert!(suppression.process_all(down, hotkeys, true, false));
assert!(suppression.process_all(up, hotkeys, true, false));
assert!(!suppression.process_all(down, hotkeys, true, false));
}
#[test]
fn extra_modifier_after_threshold_is_ignored() {
let now = capture_time();
let mut hotkey = test_hotkey(true, now);
assert_eq!(
hotkey.process(
InputEvent::Flags(OPTION_KEY_MASK | SHIFT_KEY_MASK),
now + Duration::from_millis(500),
),
None
);
assert!(hotkey.is_recording());
}
#[test]
fn option_shift_v_pastes_last_transcript() {
let now = capture_time();
let mut hotkey = test_hotkey(true, now);
let paste_key_code = HotkeyBinding::paste_last_default()
.key
.expect("default paste key")
.code;
let key_down = InputEvent::Key {
code: paste_key_code,
down: true,
flags: OPTION_KEY_MASK | SHIFT_KEY_MASK,
};
assert_eq!(
hotkey.process(key_down, now + Duration::from_millis(50)),
Some(HotkeyAction::PasteLast)
);
assert_eq!(
hotkey.process(key_down, now + Duration::from_millis(60)),
None
);
assert!(!hotkey.is_recording());
let mut suppression = ShortcutSuppression::default();
assert!(suppression.process(key_down, paste_key_code, option_binding(), true));
assert!(suppression.process(key_down, paste_key_code, option_binding(), true));
assert!(suppression.process(
InputEvent::Key {
code: paste_key_code,
down: false,
flags: OPTION_KEY_MASK | SHIFT_KEY_MASK,
},
paste_key_code,
option_binding(),
true,
));
}
#[test]
fn the_capture_shortcut_is_suppressed_and_never_chord_evidence() {
let hotkeys = RuntimeHotkeys {
capture: Some(RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers {
option: Some(crate::app_settings::ModifierSide::Either),
shift: Some(crate::app_settings::ModifierSide::Either),
..Default::default()
},
key_code: Some(1),
}),
..RuntimeHotkeys::default()
};
let flags = OPTION_KEY_MASK | SHIFT_KEY_MASK;
assert!(!is_chord_evidence(1, flags, hotkeys));
assert!(is_chord_evidence(1, flags, RuntimeHotkeys::default()));
let mut suppression = ShortcutSuppression::default();
let key = |down| InputEvent::Key {
code: 1,
down,
flags,
};
assert!(suppression.process_all(key(true), hotkeys, true, false));
assert!(suppression.process_all(key(false), hotkeys, true, false));
assert!(!suppression.process_all(key(true), RuntimeHotkeys::default(), true, false));
}
#[test]
fn paste_last_can_be_disabled_or_bound_to_a_side_specific_shortcut() {
let key_code = 0;
let input = InputEvent::Key {
code: key_code,
down: true,
flags: OPTION_KEY_MASK | crate::app_settings::RIGHT_OPTION_MASK,
};
let disabled = RuntimeHotkeys {
paste_last: None,
..RuntimeHotkeys::default()
};
assert_eq!(paste_action(input, disabled), None);
let configured = RuntimeHotkeys {
paste_last: Some(RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers {
option: Some(crate::app_settings::ModifierSide::Right),
..Default::default()
},
key_code: Some(key_code),
}),
..RuntimeHotkeys::default()
};
assert_eq!(
paste_action(input, configured),
Some(HotkeyAction::PasteLast)
);
assert_eq!(
paste_action(
InputEvent::Key {
code: key_code,
down: true,
flags: OPTION_KEY_MASK | crate::app_settings::LEFT_OPTION_MASK,
},
configured,
),
None
);
}
#[test]
fn option_control_v_is_an_ordinary_chord() {
let now = capture_time();
let mut hotkey = test_hotkey(true, now);
let paste_key_code = HotkeyBinding::paste_last_default()
.key
.expect("default paste key")
.code;
assert_eq!(
hotkey.process(
InputEvent::Key {
code: paste_key_code,
down: true,
flags: OPTION_KEY_MASK | CONTROL_KEY_MASK,
},
now + Duration::from_millis(50),
),
Some(HotkeyAction::Discard(DiscardCause::Key))
);
assert!(!hotkey.is_recording());
let paste = |flags| {
paste_action_on(
InputEvent::Key {
code: paste_key_code,
down: true,
flags,
},
paste_key_code,
)
};
assert_eq!(
paste(OPTION_KEY_MASK | SHIFT_KEY_MASK),
Some(HotkeyAction::PasteLast)
);
assert_eq!(paste(OPTION_KEY_MASK), None);
assert_eq!(paste(OPTION_KEY_MASK | CONTROL_KEY_MASK), None);
}
fn both_options() -> RuntimeHotkey {
use crate::app_settings::{HotkeyModifiers, ModifierSide};
RuntimeHotkey {
modifiers: HotkeyModifiers {
option: Some(ModifierSide::Both),
..Default::default()
},
key_code: None,
}
}
const LEFT_OPTION: u64 = OPTION_KEY_MASK | crate::app_settings::LEFT_OPTION_MASK;
const RIGHT_OPTION: u64 = OPTION_KEY_MASK | crate::app_settings::RIGHT_OPTION_MASK;
const BOTH_OPTIONS: u64 = LEFT_OPTION | RIGHT_OPTION;
#[test]
fn both_options_press_on_the_second_key_and_release_on_either() {
let now = capture_time();
let ms = Duration::from_millis;
for (first, release_to) in [(LEFT_OPTION, RIGHT_OPTION), (RIGHT_OPTION, LEFT_OPTION)] {
let mut hotkey = DictationHotkey::with_binding(false, now, false, both_options());
assert_eq!(hotkey.process(InputEvent::Flags(first), now), None);
assert!(!hotkey.is_recording(), "one Option is not the chord");
// The press is the second key's own edge: the hold threshold and
// pre-roll count from it, never from an earlier key.
let down = now + ms(30);
assert_eq!(
hotkey.process(InputEvent::Flags(BOTH_OPTIONS), down),
Some(HotkeyAction::Start)
);
assert!(
hotkey
.process(InputEvent::Flags(BOTH_OPTIONS), down + ms(500))
.is_none()
);
assert_eq!(
hotkey.process(InputEvent::Flags(release_to), down + ms(800)),
Some(HotkeyAction::Finish),
"lifting either key ends the chord"
);
assert_eq!(hotkey.process(InputEvent::Flags(0), down + ms(900)), None);
}
}
#[test]
fn both_options_must_go_down_together() {
let now = capture_time();
let mut hotkey = DictationHotkey::with_binding(false, now, false, both_options());
assert_eq!(hotkey.process(InputEvent::Flags(LEFT_OPTION), now), None);
let late = now + BOTH_SIDES_WINDOW + Duration::from_millis(1);
assert_eq!(
hotkey.process(InputEvent::Flags(BOTH_OPTIONS), late),
None,
"an Option held while the other is added later presses nothing"
);
assert_eq!(hotkey.process(InputEvent::Flags(LEFT_OPTION), late), None);
assert_eq!(hotkey.process(InputEvent::Flags(0), late), None);
let again = late + Duration::from_secs(1);
assert_eq!(hotkey.process(InputEvent::Flags(RIGHT_OPTION), again), None);
assert_eq!(
hotkey.process(InputEvent::Flags(BOTH_OPTIONS), again + BOTH_SIDES_WINDOW),
Some(HotkeyAction::Start),
"the window's edge still counts"
);
}
#[test]
fn both_options_discard_an_extra_key_within_the_hold() {
let now = capture_time();
let mut hotkey = DictationHotkey::with_binding(false, now, false, both_options());
hotkey.process(InputEvent::Flags(LEFT_OPTION), now);
assert_eq!(
hotkey.process(InputEvent::Flags(BOTH_OPTIONS), now),
Some(HotkeyAction::Start)
);
assert_eq!(
hotkey.process(
InputEvent::Flags(BOTH_OPTIONS | COMMAND_KEY_MASK),
now + Duration::from_millis(100)
),
Some(HotkeyAction::Discard(DiscardCause::ExtraModifier))
);
let mut typed = DictationHotkey::with_binding(false, now, false, both_options());
typed.process(InputEvent::Flags(BOTH_OPTIONS), now);
assert_eq!(
typed.process(
InputEvent::Key {
code: 0,
down: true,
flags: BOTH_OPTIONS,
},
now + Duration::from_secs(2)
),
Some(HotkeyAction::Discard(DiscardCause::Key)),
"a held modifier-only chord plus a key is a chord at any time"
);
}
#[test]
fn both_options_lock_on_a_double_tap_and_in_toggle_mode() {
let ms = Duration::from_millis;
let now = capture_time();
let mut hotkey = DictationHotkey::with_binding(false, now, true, both_options());
let tap = |hotkey: &mut DictationHotkey, at: CaptureInstant| {
let pressed = hotkey.process(InputEvent::Flags(BOTH_OPTIONS), at);
let released = hotkey.process(InputEvent::Flags(0), at + ms(60));
(pressed, released)
};
assert_eq!(
tap(&mut hotkey, now),
(Some(HotkeyAction::Start), Some(HotkeyAction::Finish))
);
assert_eq!(
tap(&mut hotkey, now + ms(150)),
(Some(HotkeyAction::Start), None)
);
assert!(hotkey.is_locked());
assert_eq!(
hotkey.process(InputEvent::Flags(RIGHT_OPTION), now + ms(2_000)),
None,
"one Option does not finish the lock"
);
hotkey.process(InputEvent::Flags(0), now + ms(2_050));
assert_eq!(
hotkey.process(InputEvent::Flags(BOTH_OPTIONS), now + ms(3_000)),
Some(HotkeyAction::Finish)
);
let mut toggle = DictationHotkey::with_binding(false, now, false, both_options());
toggle.set_toggle(true);
assert_eq!(tap(&mut toggle, now), (Some(HotkeyAction::Start), None));
assert!(toggle.is_locked());
assert_eq!(
toggle.process(InputEvent::Flags(BOTH_OPTIONS), now + ms(5_000)),
Some(HotkeyAction::Finish)
);
}
#[test]
fn one_sided_options_never_start_with_both_held_but_either_side_does() {
use crate::app_settings::{HotkeyModifiers, ModifierSide};
let now = capture_time();
let sided = |side| RuntimeHotkey {
modifiers: HotkeyModifiers {
option: Some(side),
..Default::default()
},
key_code: None,
};
let mut right = DictationHotkey::with_binding(false, now, false, sided(ModifierSide::Right));
assert_eq!(right.process(InputEvent::Flags(BOTH_OPTIONS), now), None);
let mut either = DictationHotkey::with_binding(false, now, false, sided(ModifierSide::Either));
assert_eq!(
either.process(InputEvent::Flags(BOTH_OPTIONS), now),
Some(HotkeyAction::Start),
"Option keeps matching both held, as before chords"
);
// Right Option held, then the left one added: the extra key
// discards a press still inside its hold.
let mut promoted = DictationHotkey::with_binding(false, now, false, sided(ModifierSide::Right));
assert_eq!(
promoted.process(InputEvent::Flags(RIGHT_OPTION), now),
Some(HotkeyAction::Start)
);
assert_eq!(
promoted.process(
InputEvent::Flags(BOTH_OPTIONS),
now + Duration::from_millis(40)
),
Some(HotkeyAction::Discard(DiscardCause::ExtraModifier))
);
}
#[test]
fn caps_lock_press_starts_and_finishes_its_own_hands_free_capture() {
let now = capture_time();
let mut hotkey =
DictationHotkey::new(now, false, crate::app_settings::RuntimeHotkey::default());
assert_eq!(hotkey.caps_lock_toggle(), Some(HotkeyAction::Start));
assert!(hotkey.is_locked());
assert_eq!(hotkey.caps_lock_toggle(), Some(HotkeyAction::Finish));
assert!(!hotkey.is_recording());
}
// Labs › Pause from menu bar's resume waits on `neutral_with`, which runs on
// the real keyboard only in macOS builds; these pin its rules.
#[test]
fn a_toggled_caps_lock_still_reads_neutral() {
// CoreGraphics reports Caps Lock as a held key, and sets alpha shift,
// for as long as it is toggled on.
assert!(neutral_with(
|| crate::caps_lock_dictation::ALPHA_SHIFT_MASK,
|code| code == CAPS_LOCK_KEY_CODE
));
assert_eq!(held_key_with(|code| code == CAPS_LOCK_KEY_CODE), None);
}
#[test]
fn a_held_key_reads_not_neutral() {
const K: u16 = 40;
assert!(!neutral_with(|| 0, |code| code == K));
assert_eq!(held_key_with(|code| code == K), Some(K));
}
#[test]
fn a_held_modifier_reads_not_neutral() {
const LEFT_SHIFT: u16 = 56;
assert!(!neutral_with(|| SHIFT_KEY_MASK, |code| code == LEFT_SHIFT));
}
#[test]
fn a_stuck_function_flag_still_reads_neutral() {
// Arrow-key metadata can leave SecondaryFn set after the key is up.
assert!(neutral_with(|| FUNCTION_KEY_MASK, |_| false));
}
#[test]
fn caps_lock_leaves_a_hold_capture_alone() {
let now = capture_time();
let mut hotkey = DictationHotkey::new(
now,
false,
RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::option(),
key_code: None,
},
);
assert_eq!(
hotkey.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(hotkey.caps_lock_toggle(), None);
assert!(hotkey.is_recording());
}
#[test]
fn lock_and_caps_lock_finish_clear_modifier_side_down_times() {
use crate::app_settings::{HotkeyModifiers, ModifierSide};
let now = capture_time();
let both_options = RuntimeHotkey {
modifiers: HotkeyModifiers {
option: Some(ModifierSide::Both),
..HotkeyModifiers::default()
},
key_code: None,
};
let mut hotkey = DictationHotkey::new(now, false, both_options);
// Track Left Option going down, then lock programmatically.
let _ = hotkey.process(InputEvent::Flags(OPTION_KEY_MASK | LEFT_OPTION_MASK), now);
assert!(hotkey.held.side_down_at(LEFT_OPTION_MASK).is_some());
assert!(hotkey.lock());
assert!(
hotkey.held.side_down_at(LEFT_OPTION_MASK).is_none(),
"lock() must clear tracked modifier sides alongside pressed keys"
);
// While locked, track Left Option again, then finish via Caps Lock:
// side_down_at must be cleared so a later Right Option cannot pair with it.
let later = now + Duration::from_millis(20);
let _ = hotkey.track_key_state(InputEvent::Flags(OPTION_KEY_MASK | LEFT_OPTION_MASK), later);
assert!(hotkey.held.side_down_at(LEFT_OPTION_MASK).is_some());
assert_eq!(hotkey.caps_lock_toggle(), Some(HotkeyAction::Finish));
assert!(
hotkey.held.side_down_at(LEFT_OPTION_MASK).is_none(),
"Caps Lock finish must clear tracked modifier sides"
);
}
#[test]
fn tap_policy_claims_nothing_during_programmatic_and_combines_escape_with_cancel() {
let cancel = RuntimeHotkey {
modifiers: crate::app_settings::HotkeyModifiers::default(),
key_code: Some(1),
};
assert_eq!(
TapPolicy::for_listener(false, false, false, None),
TapPolicy::None
);
// Programmatic capture claims neither Escape nor a cancel shortcut.
assert_eq!(
TapPolicy::for_listener(true, true, true, Some(cancel)),
TapPolicy::None
);
let both = TapPolicy::for_listener(false, true, false, Some(cancel));
assert!(both.takes_escape());
assert_eq!(both.cancel(), Some(cancel));
let held_escape = TapPolicy::for_listener(false, false, true, None);
assert!(held_escape.takes_escape());
assert_eq!(held_escape.cancel(), None);
let toggle_cancel = TapPolicy::for_listener(false, false, false, Some(cancel));
assert!(!toggle_cancel.takes_escape());
assert_eq!(toggle_cancel.cancel(), Some(cancel));
}
/// Labs › Model switch shortcut's key is swallowed while a capture records,
/// so the press cannot strand it: a held capture still finishes on release,
/// and a locked one still finishes on the next press.
#[test]
fn a_switch_press_never_strands_a_capture() {
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
struct Guard {
_lock: std::sync::MutexGuard<'static, ()>,
}
impl Drop for Guard {
fn drop(&mut self) {
crate::app_settings::install_test_hotkeys(RuntimeHotkeys::default());
}
}
let _guard = Guard {
_lock: LOCK.lock().unwrap_or_else(|error| error.into_inner()),
};
let code = 46;
crate::app_settings::install_test_hotkeys(RuntimeHotkeys {
model_switch: Some(RuntimeHotkey {
modifiers: crate::app_settings::modifiers_from_flags(
OPTION_KEY_MASK | CONTROL_KEY_MASK,
),
key_code: Some(code),
}),
..RuntimeHotkeys::default()
});
let now = capture_time();
let switch_down = InputEvent::Key {
code,
down: true,
flags: OPTION_KEY_MASK | CONTROL_KEY_MASK,
};
let switch_up = InputEvent::Key {
code,
down: false,
flags: OPTION_KEY_MASK | CONTROL_KEY_MASK,
};
// Hold: the switch press is swallowed and the release still finishes.
let mut held = test_hotkey(false, now);
assert_eq!(
held.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
let held_at = now + Duration::from_millis(600);
assert_eq!(held.process(switch_down, held_at), None);
assert!(held.is_recording());
assert_eq!(
held.process(switch_up, held_at + Duration::from_millis(20)),
None
);
assert_eq!(
held.process(
InputEvent::Flags(NO_FLAGS),
held_at + Duration::from_millis(100)
),
Some(HotkeyAction::Finish)
);
// A locked capture holds no modifier, so its switch chord needn't name
// the dictation one.
crate::app_settings::install_test_hotkeys(RuntimeHotkeys {
model_switch: Some(RuntimeHotkey {
modifiers: crate::app_settings::modifiers_from_flags(CONTROL_KEY_MASK),
key_code: Some(code),
}),
..RuntimeHotkeys::default()
});
let switch_down = InputEvent::Key {
code,
down: true,
flags: CONTROL_KEY_MASK,
};
let switch_up = InputEvent::Key {
code,
down: false,
flags: CONTROL_KEY_MASK,
};
// Locked: the switch press leaves it locked, and the next press finishes.
let mut locked = toggle_hotkey(now, false);
assert_eq!(
locked.process(InputEvent::Flags(OPTION_KEY_MASK), now),
Some(HotkeyAction::Start)
);
assert_eq!(
locked.process(InputEvent::Flags(NO_FLAGS), now + Duration::from_millis(80)),
None
);
assert!(locked.is_locked());
assert_eq!(
locked.process(switch_down, now + Duration::from_millis(200)),
None
);
assert_eq!(
locked.process(switch_up, now + Duration::from_millis(220)),
None
);
assert!(locked.is_locked());
assert_eq!(
locked.process(
InputEvent::Flags(OPTION_KEY_MASK),
now + Duration::from_millis(400)
),
Some(HotkeyAction::Finish)
);
}