diff --git a/Makefile b/Makefile index fc42d01b..073e0a1e 100644 --- a/Makefile +++ b/Makefile @@ -36,7 +36,8 @@ TEST_PRODUCTION_SOURCES = \ Sources/UpdateManager.swift \ Sources/ShortcutCore/DictationShortcutSessionController.swift \ Sources/ShortcutCore/ShortcutMatcher.swift \ - Sources/ShortcutCore/ShortcutModels.swift + Sources/ShortcutCore/ShortcutModels.swift \ + Sources/ShortcutCore/ShortcutStartDelayPolicy.swift TEST_SOURCES = $(shell find Tests -name '*.swift' -type f | LC_ALL=C sort) SHELL_SCRIPTS = $(shell find .github/scripts .agents/skills -name '*.sh' -type f | LC_ALL=C sort) YAML_FILES = $(shell find .github -type f \( -name '*.yml' -o -name '*.yaml' \) | LC_ALL=C sort) diff --git a/Sources/AppState.swift b/Sources/AppState.swift index 4c10270a..e6e5d988 100644 --- a/Sources/AppState.swift +++ b/Sources/AppState.swift @@ -1794,6 +1794,9 @@ final class AppState: ObservableObject, @unchecked Sendable { hotkeyManager.onEscapeKeyPressed = { [weak self] in self?.handleEscapeKeyPress() ?? false } + hotkeyManager.shouldClaimFnHoldPress = { [weak self] in + self?.shortcutSessionController.claimsHoldShortcutPresses ?? false + } restartHotkeyMonitoring() } @@ -1823,6 +1826,7 @@ final class AppState: ObservableObject, @unchecked Sendable { hotkeyMonitoringErrorMessage = nil hotkeyManager.onShortcutEvent = nil hotkeyManager.onEscapeKeyPressed = nil + hotkeyManager.shouldClaimFnHoldPress = nil hotkeyManager.stop() } @@ -2036,6 +2040,14 @@ final class AppState: ObservableObject, @unchecked Sendable { } } + private func effectiveShortcutStartDelay(for mode: RecordingTriggerMode) -> TimeInterval { + ShortcutStartDelayPolicy.effectiveDelay( + for: mode, + holdBinding: activeShortcutConfiguration.hold, + configuredDelay: shortcutStartDelay + ) + } + /// Invalidates prior insertion actions before taking the new start-time snapshot, including during delays. private func scheduleShortcutStart(mode: RecordingTriggerMode) { textInsertionTargetID = nil @@ -2045,7 +2057,7 @@ final class AppState: ObservableObject, @unchecked Sendable { commandModeManualModifier.shortcutModifier ) pendingShortcutStartMode = mode - let delay = shortcutStartDelay + let delay = effectiveShortcutStartDelay(for: mode) guard delay > 0 else { pendingShortcutStartMode = nil diff --git a/Sources/HotkeyManager.swift b/Sources/HotkeyManager.swift index d3c97f17..9e135816 100644 --- a/Sources/HotkeyManager.swift +++ b/Sources/HotkeyManager.swift @@ -10,6 +10,9 @@ final class HotkeyManager { var onShortcutEvent: ((ShortcutEvent) -> Void)? var onEscapeKeyPressed: (() -> Bool)? + /// Asked on each new Fn press whether the hold binding should consume it + /// instead of passing it through to macOS (see `ShortcutMatcher.reduce`). + var shouldClaimFnHoldPress: (() -> Bool)? var currentPressedModifiers: ShortcutModifiers { inputState.currentModifiers @@ -53,7 +56,8 @@ final class HotkeyManager { let result = ShortcutMatcher.reduce( state: inputState, event: event, - configuration: configuration + configuration: configuration, + claimFnHoldPress: shouldClaimFnHoldPress?() ?? false ) inputState = result.state for event in result.emittedEvents { diff --git a/Sources/ModifierKeyEventState.swift b/Sources/ModifierKeyEventState.swift index e5f917d2..a0830226 100644 --- a/Sources/ModifierKeyEventState.swift +++ b/Sources/ModifierKeyEventState.swift @@ -29,7 +29,9 @@ enum ModifierKeyEventState { } } - static let fnKeyCode: UInt16 = 63 + // Single source of truth lives on ShortcutBinding so event production + // and shortcut matching cannot diverge. + static let fnKeyCode = ShortcutBinding.fnKeyCode /// Reads the current system-wide Fn state. Useful for seeding a backend's /// tracked Fn state at start or after a tap reset, since flagsChanged events diff --git a/Sources/ShortcutCore/DictationShortcutSessionController.swift b/Sources/ShortcutCore/DictationShortcutSessionController.swift index d4fc5aa1..b71e817b 100644 --- a/Sources/ShortcutCore/DictationShortcutSessionController.swift +++ b/Sources/ShortcutCore/DictationShortcutSessionController.swift @@ -20,6 +20,14 @@ final class DictationShortcutSessionController { private var latchedByDoubleTap = false private var holdStopArmed = false + /// True while the next hold-shortcut press belongs to a double-tap session: + /// the second press that latches recording, or the press that stops a + /// latched recording. Those presses should not also reach macOS (for + /// example as an Fn/Globe action), unlike an ordinary first press. + var claimsHoldShortcutPresses: Bool { + awaitingDoubleTap || latchedByDoubleTap + } + func handle( event: ShortcutEvent, isTranscribing: Bool, diff --git a/Sources/ShortcutCore/ShortcutMatcher.swift b/Sources/ShortcutCore/ShortcutMatcher.swift index 0132586e..200a8d12 100644 --- a/Sources/ShortcutCore/ShortcutMatcher.swift +++ b/Sources/ShortcutCore/ShortcutMatcher.swift @@ -18,6 +18,10 @@ struct ShortcutInputState: Equatable { var holdIsActive = false var toggleIsActive = false var copyAgainIsActive = false + /// Whether the Fn press currently down was claimed for the hold binding. + /// Decided on Fn down and kept until Fn up, so both edges of one press + /// get the same consume decision. + var fnPressIsClaimedByHold = false var currentModifiers: ShortcutModifiers { ShortcutBinding.modifiers(for: pressedModifierKeyCodes) @@ -70,10 +74,16 @@ struct ShortcutMatchResult: Equatable { } enum ShortcutMatcher { + /// - Parameter claimFnHoldPress: Read only when a new Fn press starts. + /// When true, the hold binding consumes that press like any other + /// modifier instead of letting it reach macOS. Callers set it while a + /// press is expected to belong to FreeFlow, such as the second press of + /// a double tap. static func reduce( state: ShortcutInputState, event: ShortcutInputEvent, - configuration: ShortcutConfiguration + configuration: ShortcutConfiguration, + claimFnHoldPress: Bool = false ) -> ShortcutMatchResult { switch event { case .backendReset: @@ -84,20 +94,53 @@ enum ShortcutMatcher { nextState.pressedModifierKeyCodes = pressedModifierKeyCodes let emittedEvents = updateActiveBindings(in: &nextState, configuration: configuration) + + // GlobalShortcutBackend attaches this decision to the ordinary + // key event that carried the snapshot. If the snapshot merely + // repairs a missed Fn state (e.g. after the event tap was + // re-enabled), flipping Fn hold state must not swallow that key; + // macOS still needs unobstructed Fn handling for Globe actions. + // Toggle and non-Fn hold transitions keep consuming as before. + let onlyFnHoldTransitions = + configuration.hold.usesFnKey + && emittedEvents.allSatisfy { $0 == .holdActivated || $0 == .holdDeactivated } + let consumeDecision: ShortcutConsumeDecision = + emittedEvents.isEmpty || onlyFnHoldTransitions ? .passthrough : .consume + return ShortcutMatchResult( state: nextState, emittedEvents: emittedEvents, - consumeDecision: emittedEvents.isEmpty ? .passthrough : .consume + consumeDecision: consumeDecision ) case .modifierChanged(let keyCode, let isDown): + // Fn/Globe is the only modifier with a system-level tap action + // (e.g. "Press globe to: Change Input Source"). If a hold-to-talk + // binding consumes Fn events, macOS never sees the key at all and + // the Globe action can never fire, even for quick taps. macOS + // itself ignores long Fn holds, so hold bindings can safely + // observe Fn passively: quick taps reach the system Globe action, + // sustained holds still drive hold-to-talk. Toggle bindings keep + // consuming because a Fn tap is meaningful on both sides and the + // user chose Fn for it. A press the caller claims (for example + // the second press of a double tap) is consumed for its whole + // down/up pair. + let isFnEvent = keyCode == ShortcutBinding.fnKeyCode + var nextState = state + if isFnEvent, isDown, !state.pressedModifierKeyCodes.contains(keyCode) { + nextState.fnPressIsClaimedByHold = claimFnHoldPress + } + let consumeConfiguration = + isFnEvent && !nextState.fnPressIsClaimedByHold + ? configuration.withHoldBindingDisabled + : configuration + let shouldConsumeBefore = shouldConsumeModifierEvent( for: keyCode, state: state, - configuration: configuration + configuration: consumeConfiguration ) - var nextState = state if isDown { nextState.pressedModifierKeyCodes.insert(keyCode) } else { @@ -107,8 +150,11 @@ enum ShortcutMatcher { let shouldConsumeAfter = shouldConsumeModifierEvent( for: keyCode, state: nextState, - configuration: configuration + configuration: consumeConfiguration ) + if isFnEvent, !isDown { + nextState.fnPressIsClaimedByHold = false + } let emittedEvents = updateActiveBindings(in: &nextState, configuration: configuration) return ShortcutMatchResult( state: nextState, @@ -159,6 +205,7 @@ enum ShortcutMatcher { var nextState = state nextState.pressedKeyCodes.removeAll() nextState.pressedModifierKeyCodes.removeAll() + nextState.fnPressIsClaimedByHold = false let emittedEvents = updateActiveBindings(in: &nextState, configuration: configuration) return ShortcutMatchResult( state: nextState, diff --git a/Sources/ShortcutCore/ShortcutModels.swift b/Sources/ShortcutCore/ShortcutModels.swift index d98b64e5..e19616ea 100644 --- a/Sources/ShortcutCore/ShortcutModels.swift +++ b/Sources/ShortcutCore/ShortcutModels.swift @@ -93,6 +93,20 @@ struct ShortcutConfiguration: Equatable { } static let disabled = ShortcutConfiguration(hold: .disabled, toggle: .disabled, copyAgain: .disabled) + + /// A copy of this configuration with the hold binding disabled. Used when + /// deciding whether Fn/Globe events may be consumed: hold-to-talk must not + /// consume Fn, otherwise macOS never sees the key and the system Globe + /// action (e.g. "Press globe to: Change Input Source") can never fire. + /// See `ShortcutMatcher.reduce` for the call site. + var withHoldBindingDisabled: ShortcutConfiguration { + ShortcutConfiguration( + hold: .disabled, + toggle: toggle, + copyAgain: copyAgain, + permittedAdditionalExactMatchModifiers: permittedAdditionalExactMatchModifiers + ) + } } enum ShortcutPreset: String, CaseIterable, Identifiable, Codable { @@ -193,9 +207,11 @@ struct ShortcutBinding: Codable, Hashable, Identifiable, Equatable { modifierDisplayNames.count } + static let fnKeyCode: UInt16 = 63 + var usesFnKey: Bool { guard !isDisabled else { return false } - return keyCode == 63 || modifiers.contains(.function) + return keyCode == Self.fnKeyCode || modifiers.contains(.function) } var requiresExactModifierMatch: Bool { diff --git a/Sources/ShortcutCore/ShortcutStartDelayPolicy.swift b/Sources/ShortcutCore/ShortcutStartDelayPolicy.swift new file mode 100644 index 00000000..540ffebe --- /dev/null +++ b/Sources/ShortcutCore/ShortcutStartDelayPolicy.swift @@ -0,0 +1,23 @@ +import Foundation + +/// Decides how long a shortcut press must last before recording starts. +enum ShortcutStartDelayPolicy { + /// Minimum hold time before an Fn/Globe hold-to-talk press starts + /// dictation. Fn events pass through to macOS (see `ShortcutMatcher`), so a + /// quick tap can perform the system Globe action (for example Change Input + /// Source). The floor keeps that tap from also starting a recording; + /// releasing before it cancels the pending start. + static let minimumFnHoldStartDelay: TimeInterval = 0.2 + + static func effectiveDelay( + for mode: RecordingTriggerMode, + holdBinding: ShortcutBinding, + configuredDelay: TimeInterval + ) -> TimeInterval { + let configuredDelay = max(0, configuredDelay) + guard mode == .hold, holdBinding.usesFnKey else { + return configuredDelay + } + return max(configuredDelay, minimumFnHoldStartDelay) + } +} diff --git a/Tests/ShortcutCoreTests.swift b/Tests/ShortcutCoreTests.swift index cd03f234..f2469287 100644 --- a/Tests/ShortcutCoreTests.swift +++ b/Tests/ShortcutCoreTests.swift @@ -3,6 +3,9 @@ import Foundation enum ShortcutCoreTests { static func run() { testBareFnHoldLifecycle() + testBareFnToggleStillConsumes() + testFnHoldPassthroughUnlessToggleComboActive() + testSnapshotRepairFnHoldDoesNotConsume() testDefaultShortcutSpecificityOrdering() testRightOptionPresetIsSideSpecific() testExactModifierMatching() @@ -22,6 +25,12 @@ enum ShortcutCoreTests { testLongHoldStopsImmediatelyWithDoubleTapEnabled() testToggleStartedSessionIgnoresHoldShortcut() testDoubleTapModifierChordThroughMatcher() + testFnHoldStartDelayPolicy() + testQuickFnTapCancelsPendingStart() + testClaimedFnPressDecisionIsStickyPerPress() + testBackendResetClearsFnClaim() + testFnDoubleTapLockClaimsOnlyFollowUpPresses() + testFnQuickTapPassesThroughWithDoubleTapEnabled() } private static func testBareFnHoldLifecycle() { @@ -38,9 +47,90 @@ enum ShortcutCoreTests { ) TestSupport.expectEqual(down.emittedEvents, [.holdActivated]) - TestSupport.expectEqual(down.consumeDecision, .consume) + // Fn hold-to-talk must not consume the key: macOS needs to see Fn + // events for the system Globe action (e.g. Change Input Source). + TestSupport.expectEqual(down.consumeDecision, .passthrough) TestSupport.expectEqual(up.emittedEvents, [.holdDeactivated]) - TestSupport.expectEqual(up.consumeDecision, .consume) + TestSupport.expectEqual(up.consumeDecision, .passthrough) + } + + private static func testBareFnToggleStillConsumes() { + let configuration = ShortcutConfiguration( + hold: .disabled, + toggle: ShortcutPreset.fnKey.binding + ) + let down = ShortcutMatcher.reduce( + state: ShortcutInputState(), + event: .modifierChanged(keyCode: 63, isDown: true), + configuration: configuration + ) + + // A Fn tap is meaningful to both FreeFlow (toggle dictation) and + // macOS (Globe action); the user chose Fn for the toggle binding, so + // FreeFlow keeps consuming it. + TestSupport.expectEqual(down.emittedEvents, [.toggleActivated]) + TestSupport.expectEqual(down.consumeDecision, .consume) + } + + private static func testFnHoldPassthroughUnlessToggleComboActive() { + let configuration = ShortcutConfiguration( + hold: .defaultHold, + toggle: .defaultToggle + ) + // Bare Fn: hold binding is excluded from consume decisions, and the + // Cmd+Fn toggle is not active without Cmd, so the tap passes through. + let fnDown = ShortcutMatcher.reduce( + state: ShortcutInputState(), + event: .modifierChanged(keyCode: 63, isDown: true), + configuration: configuration + ) + TestSupport.expectEqual(fnDown.emittedEvents, [.holdActivated]) + TestSupport.expectEqual(fnDown.consumeDecision, .passthrough) + + // With Cmd held, the Fn-down event activates the Cmd+Fn toggle and + // Fn is consumed. Cmd down alone activates nothing and passes through. + let cmdDown = ShortcutMatcher.reduce( + state: ShortcutInputState(), + event: .modifierChanged(keyCode: 55, isDown: true), + configuration: configuration + ) + TestSupport.expectEqual(cmdDown.emittedEvents, []) + TestSupport.expectEqual(cmdDown.consumeDecision, .passthrough) + + let fnDownWithCmd = ShortcutMatcher.reduce( + state: cmdDown.state, + event: .modifierChanged(keyCode: 63, isDown: true), + configuration: configuration + ) + TestSupport.expectEqual(fnDownWithCmd.emittedEvents, [.toggleActivated, .holdActivated]) + TestSupport.expectEqual(fnDownWithCmd.consumeDecision, .consume) + } + + private static func testSnapshotRepairFnHoldDoesNotConsume() { + // A snapshot that suddenly reports Fn as pressed (e.g. the event tap + // missed the Fn flagsChanged while disabled) repairs hold state; the + // ordinary key event carrying the snapshot must not be swallowed. + let configuration = ShortcutConfiguration(hold: .defaultHold, toggle: .disabled) + let repaired = ShortcutMatcher.reduce( + state: ShortcutInputState(), + event: .modifierSnapshot([63]), + configuration: configuration + ) + TestSupport.expectEqual(repaired.emittedEvents, [.holdActivated]) + TestSupport.expectEqual(repaired.consumeDecision, .passthrough) + + // Non-Fn hold bindings keep their existing edge-consumption behavior. + let optionConfiguration = ShortcutConfiguration( + hold: ShortcutPreset.rightOption.binding, + toggle: .disabled + ) + let optionRepaired = ShortcutMatcher.reduce( + state: ShortcutInputState(), + event: .modifierSnapshot([61]), + configuration: optionConfiguration + ) + TestSupport.expectEqual(optionRepaired.emittedEvents, [.holdActivated]) + TestSupport.expectEqual(optionRepaired.consumeDecision, .consume) } private static func testDefaultShortcutSpecificityOrdering() { @@ -457,4 +547,231 @@ enum ShortcutCoreTests { ]) TestSupport.expectEqual(controller.activeMode, .toggle) } + + private static func testFnHoldStartDelayPolicy() { + let floor = ShortcutStartDelayPolicy.minimumFnHoldStartDelay + TestSupport.expectApproximatelyEqual(floor, 0.2) + + // Fn hold gets the 200 ms floor when the configured delay is shorter. + TestSupport.expectApproximatelyEqual( + ShortcutStartDelayPolicy.effectiveDelay(for: .hold, holdBinding: .defaultHold, configuredDelay: 0), + floor + ) + TestSupport.expectApproximatelyEqual( + ShortcutStartDelayPolicy.effectiveDelay(for: .hold, holdBinding: .defaultHold, configuredDelay: 0.1), + floor + ) + // A longer user delay is kept. + TestSupport.expectApproximatelyEqual( + ShortcutStartDelayPolicy.effectiveDelay(for: .hold, holdBinding: .defaultHold, configuredDelay: 0.5), + 0.5 + ) + // A hold binding that only uses Fn as a modifier also gets the floor. + let fnSpace = ShortcutBinding(keyCode: 49, keyDisplay: "Space", modifiers: [.function], kind: .key, preset: nil) + TestSupport.expectApproximatelyEqual( + ShortcutStartDelayPolicy.effectiveDelay(for: .hold, holdBinding: fnSpace, configuredDelay: 0), + floor + ) + // Non-Fn hold bindings keep their configured delay. + let rightOption = ShortcutPreset.rightOption.binding + TestSupport.expectApproximatelyEqual( + ShortcutStartDelayPolicy.effectiveDelay(for: .hold, holdBinding: rightOption, configuredDelay: 0), + 0 + ) + TestSupport.expectApproximatelyEqual( + ShortcutStartDelayPolicy.effectiveDelay(for: .hold, holdBinding: rightOption, configuredDelay: 0.15), + 0.15 + ) + // Toggle starts are not affected by the Fn hold floor. + TestSupport.expectApproximatelyEqual( + ShortcutStartDelayPolicy.effectiveDelay(for: .toggle, holdBinding: .defaultHold, configuredDelay: 0), + 0 + ) + TestSupport.expectApproximatelyEqual( + ShortcutStartDelayPolicy.effectiveDelay(for: .toggle, holdBinding: .defaultHold, configuredDelay: 0.3), + 0.3 + ) + // A disabled hold binding does not count as Fn. + TestSupport.expectApproximatelyEqual( + ShortcutStartDelayPolicy.effectiveDelay(for: .hold, holdBinding: .disabled, configuredDelay: 0), + 0 + ) + } + + /// A Fn tap released before the start-delay floor ends the session + /// before recording can start, so AppState cancels the pending start. + private static func testQuickFnTapCancelsPendingStart() { + let delay = ShortcutStartDelayPolicy.effectiveDelay( + for: .hold, + holdBinding: .defaultHold, + configuredDelay: 0 + ) + let releaseAt: TimeInterval = 0.1 + TestSupport.expect(releaseAt < delay, "Quick tap must release before the Fn start floor") + + let controller = DictationShortcutSessionController() + TestSupport.expectEqual(controller.handle(event: .holdActivated, isTranscribing: false, now: 0), .start(.hold)) + TestSupport.expectEqual( + controller.handle(event: .holdDeactivated, isTranscribing: false, now: releaseAt), + .stop + ) + TestSupport.expectEqual(controller.activeMode, nil) + TestSupport.expectEqual(controller.claimsHoldShortcutPresses, false) + } + + private static func testClaimedFnPressDecisionIsStickyPerPress() { + let configuration = ShortcutConfiguration(hold: .defaultHold, toggle: .disabled) + + // Unclaimed on down: the matching up passes through even if the + // caller starts claiming mid-press. + let down = ShortcutMatcher.reduce( + state: ShortcutInputState(), + event: .modifierChanged(keyCode: 63, isDown: true), + configuration: configuration, + claimFnHoldPress: false + ) + let up = ShortcutMatcher.reduce( + state: down.state, + event: .modifierChanged(keyCode: 63, isDown: false), + configuration: configuration, + claimFnHoldPress: true + ) + TestSupport.expectEqual(down.consumeDecision, .passthrough) + TestSupport.expectEqual(up.emittedEvents, [.holdDeactivated]) + TestSupport.expectEqual(up.consumeDecision, .passthrough) + + // Claimed on down: the matching up is consumed even if the claim + // ends mid-press, so macOS never sees half a Fn press. + let claimedDown = ShortcutMatcher.reduce( + state: ShortcutInputState(), + event: .modifierChanged(keyCode: 63, isDown: true), + configuration: configuration, + claimFnHoldPress: true + ) + TestSupport.expectEqual(claimedDown.emittedEvents, [.holdActivated]) + TestSupport.expectEqual(claimedDown.consumeDecision, .consume) + let claimedUp = ShortcutMatcher.reduce( + state: claimedDown.state, + event: .modifierChanged(keyCode: 63, isDown: false), + configuration: configuration, + claimFnHoldPress: false + ) + TestSupport.expectEqual(claimedUp.emittedEvents, [.holdDeactivated]) + TestSupport.expectEqual(claimedUp.consumeDecision, .consume) + TestSupport.expectEqual(claimedUp.state.fnPressIsClaimedByHold, false) + + // The claim only affects Fn; other hold keys are unchanged. + let optionConfiguration = ShortcutConfiguration(hold: ShortcutPreset.rightOption.binding, toggle: .disabled) + let optionDown = ShortcutMatcher.reduce( + state: ShortcutInputState(), + event: .modifierChanged(keyCode: 61, isDown: true), + configuration: optionConfiguration, + claimFnHoldPress: false + ) + TestSupport.expectEqual(optionDown.consumeDecision, .consume) + } + + private static func testBackendResetClearsFnClaim() { + let configuration = ShortcutConfiguration(hold: .defaultHold, toggle: .disabled) + let claimedDown = ShortcutMatcher.reduce( + state: ShortcutInputState(), + event: .modifierChanged(keyCode: 63, isDown: true), + configuration: configuration, + claimFnHoldPress: true + ) + let reset = ShortcutMatcher.reduce( + state: claimedDown.state, + event: .backendReset, + configuration: configuration + ) + TestSupport.expectEqual(reset.state.fnPressIsClaimedByHold, false) + TestSupport.expectEqual(reset.emittedEvents, [.holdDeactivated]) + } + + private struct FnPressStep: Equatable { + let isDown: Bool + let consumeDecision: ShortcutConsumeDecision + let actions: [DictationShortcutAction] + } + + /// Runs bare Fn presses through the matcher and the session controller the + /// way AppState wires them: the claim is read from the controller at each + /// Fn event, and emitted events feed the controller. + private static func runFnPresses( + _ presses: [(down: TimeInterval, up: TimeInterval)], + controller: DictationShortcutSessionController + ) -> [FnPressStep] { + let configuration = ShortcutConfiguration(hold: .defaultHold, toggle: .defaultToggle) + var state = ShortcutInputState() + var steps: [FnPressStep] = [] + for press in presses { + for (isDown, now) in [(true, press.down), (false, press.up)] { + let result = ShortcutMatcher.reduce( + state: state, + event: .modifierChanged(keyCode: 63, isDown: isDown), + configuration: configuration, + claimFnHoldPress: controller.claimsHoldShortcutPresses + ) + state = result.state + let actions = result.emittedEvents.compactMap { doubleTapHandle(controller, $0, at: now) } + steps.append(FnPressStep(isDown: isDown, consumeDecision: result.consumeDecision, actions: actions)) + } + } + return steps + } + + /// Double tap on Fn locks recording. The first tap is indistinguishable + /// from a Globe tap and reaches macOS; the latching press and the press + /// that stops the locked recording belong to FreeFlow and are consumed. + private static func testFnDoubleTapLockClaimsOnlyFollowUpPresses() { + let controller = DictationShortcutSessionController() + let steps = runFnPresses( + [(down: 0, up: 0.1), (down: 0.25, up: 0.35), (down: 5, up: 5.1), (down: 8, up: 8.1)], + controller: controller + ) + + TestSupport.expectEqual(steps, [ + // First tap: passes through to macOS. + FnPressStep(isDown: true, consumeDecision: .passthrough, actions: [.start(.hold)]), + FnPressStep( + isDown: false, + consumeDecision: .passthrough, + actions: [.awaitDoubleTap(DictationShortcutSessionController.doubleTapWindow)] + ), + // Second press latches and is claimed for its whole down/up pair. + FnPressStep(isDown: true, consumeDecision: .consume, actions: [.switchedToToggle]), + FnPressStep(isDown: false, consumeDecision: .consume, actions: []), + // Stop press is claimed, including the release after the session ends. + FnPressStep(isDown: true, consumeDecision: .consume, actions: [.stop]), + FnPressStep(isDown: false, consumeDecision: .consume, actions: []), + // Next ordinary tap passes through again. + FnPressStep(isDown: true, consumeDecision: .passthrough, actions: [.start(.hold)]), + FnPressStep( + isDown: false, + consumeDecision: .passthrough, + actions: [.awaitDoubleTap(DictationShortcutSessionController.doubleTapWindow)] + ), + ]) + TestSupport.expectEqual(controller.claimsHoldShortcutPresses, true) + TestSupport.expectEqual(controller.handleDoubleTapTimeout(), .stop) + TestSupport.expectEqual(controller.claimsHoldShortcutPresses, false) + } + + /// With double tap enabled, a single quick Fn tap still reaches macOS and + /// ends without recording once the double-tap window expires. A long hold + /// also passes through and stops on release. + private static func testFnQuickTapPassesThroughWithDoubleTapEnabled() { + let controller = DictationShortcutSessionController() + let tap = runFnPresses([(down: 0, up: 0.1)], controller: controller) + TestSupport.expectEqual(tap.map(\.consumeDecision), [.passthrough, .passthrough]) + TestSupport.expectEqual(controller.handleDoubleTapTimeout(), .stop) + TestSupport.expectEqual(controller.claimsHoldShortcutPresses, false) + + let hold = runFnPresses([(down: 1, up: 3)], controller: controller) + TestSupport.expectEqual(hold, [ + FnPressStep(isDown: true, consumeDecision: .passthrough, actions: [.start(.hold)]), + FnPressStep(isDown: false, consumeDecision: .passthrough, actions: [.stop]), + ]) + TestSupport.expectEqual(controller.claimsHoldShortcutPresses, false) + } }