Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 13 additions & 1 deletion Sources/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down Expand Up @@ -1823,6 +1826,7 @@ final class AppState: ObservableObject, @unchecked Sendable {
hotkeyMonitoringErrorMessage = nil
hotkeyManager.onShortcutEvent = nil
hotkeyManager.onEscapeKeyPressed = nil
hotkeyManager.shouldClaimFnHoldPress = nil
hotkeyManager.stop()
}

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
6 changes: 5 additions & 1 deletion Sources/HotkeyManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion Sources/ModifierKeyEventState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions Sources/ShortcutCore/DictationShortcutSessionController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
57 changes: 52 additions & 5 deletions Sources/ShortcutCore/ShortcutMatcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand All @@ -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 {
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
18 changes: 17 additions & 1 deletion Sources/ShortcutCore/ShortcutModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
23 changes: 23 additions & 0 deletions Sources/ShortcutCore/ShortcutStartDelayPolicy.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading