Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ The configuration command sends the token directly into macOS Keychain without d

### Change the shortcut

In **Settings → General**, click the shortcut, then press your new key combination. It saves immediately and survives a restart; no separate Apply or Save is required. Press **Escape**, click elsewhere, or leave the app to cancel. Include Control, Option, or Command with a letter, number, Space, or F-key. Key names refer to US keyboard positions. If macOS reports a conflict, try another combination or cancel to restore the previous shortcut. Avoid combinations already used by your editor or system; some app-local shortcuts cannot be detected. Press Option–Shift–Space in the recorder to restore the default. Finish or cancel active dictation before editing.
In **Settings → General**, click the shortcut, then press your new key combination. It saves immediately and survives a restart; no separate Apply or Save is required. Press **Escape**, click elsewhere, or leave the app to cancel. Tap **Fn/Globe alone**, or include Control, Option, or Command with a letter, number, Space, or F-key. Fn toggles on release and ignores combinations such as Fn–arrow. For Fn, enable ClearFlow’s Accessibility access and set macOS **Keyboard → Press 🌐 key to → Do Nothing**; disable competing Fn shortcuts in other dictation apps. Fn monitoring inspects modifier/key state only, never typed characters. If permission is missing, Fn is saved but stays inactive until you enable access and refresh permission status. Key names refer to US keyboard positions. If macOS reports a conflict, try another combination or cancel to restore the previous shortcut. Avoid combinations already used by your editor or system; some app-local shortcuts cannot be detected. Press Option–Shift–Space in the recorder to restore the default. Finish or cancel active dictation before editing.

### 3. Dictate

Expand Down
11 changes: 10 additions & 1 deletion Sources/ClearFlow/DictationModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,12 @@ import ClearFlowCore
var registerShortcut: ((Shortcut) -> Bool)?
func changeShortcut(_ value: Shortcut) -> String? {
guard !busy else { return "Finish or cancel dictation before changing the shortcut." }
guard value.isValid else { return "Include Control, Option, or Command with a key." }
guard value.isValid else { return "Tap Fn alone, or include Control, Option, or Command with a key." }
if value.isFn && !AXIsProcessTrusted() {
suspendShortcut?()
AppSettings.shortcut = value; shortcut = value; shortcutAvailable = false
return nil // Save the selection; visibly report the permission needed to activate it.
}
guard let registerShortcut, registerShortcut(value) else {
return "This shortcut is unavailable or used by another app."
}
Expand Down Expand Up @@ -85,6 +90,10 @@ import ClearFlowCore
func refreshPermissions() {
guard !demoMode else { return }
hasAccessibility = AXIsProcessTrusted()
if shortcut.isFn {
if !hasAccessibility { suspendShortcut?(); shortcutAvailable = false }
else if !shortcutAvailable { shortcutAvailable = registerShortcut?(shortcut) ?? false }
}
microphoneGranted = AVCaptureDevice.authorizationStatus(for: .audio) == .authorized
}
func grantAccessibility() {
Expand Down
41 changes: 41 additions & 0 deletions Sources/ClearFlow/GlobalShortcut.swift
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import Carbon
import AppKit
import ClearFlowCore

@MainActor final class GlobalShortcut {
private var reference: EventHotKeyRef?
private var handler: EventHandlerRef?
private var current: Shortcut?
private var generation: UInt32 = 0
private var fnGlobalMonitor: Any?
private var fnLocalMonitor: Any?
private var fnTap = FnTap()
var onPress: (() -> Void)?
// Register the replacement first: a conflict must never discard the working shortcut.
func register(_ value: Shortcut) -> Bool {
guard value.isValid else { return false }
if value.isFn { return registerFn() }
if current == value, reference != nil { return true }
guard installHandler() else { return false }
var modifiers: UInt32 = 0
Expand All @@ -22,9 +27,44 @@ import ClearFlowCore
let id = EventHotKeyID(signature: 0x43464c57, id: next)
guard RegisterEventHotKey(value.keyCode, modifiers, id, GetApplicationEventTarget(), 0, &candidate) == noErr else { return false }
if let reference { UnregisterEventHotKey(reference) }
removeFnMonitors()
reference = candidate; current = value; generation = next
return true
}
private func registerFn() -> Bool {
guard AXIsProcessTrusted() else { return false }
if current == .fn, fnGlobalMonitor != nil, fnLocalMonitor != nil { return true }
let mask: NSEvent.EventTypeMask = [.flagsChanged, .keyDown, .systemDefined]
guard let global = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: { [weak self] event in
self?.handleFn(event)
}) else { return false }
guard let local = NSEvent.addLocalMonitorForEvents(matching: mask, handler: { [weak self] event in
self?.handleFn(event)
return event
}) else { NSEvent.removeMonitor(global); return false }
unregister()
fnGlobalMonitor = global; fnLocalMonitor = local
current = .fn; generation &+= 1
return true
}
private func handleFn(_ event: NSEvent) {
guard current == .fn else { return }
// Only state is inspected. Typed characters are never read, stored or transmitted.
if event.type == .keyDown || event.type == .systemDefined { fnTap.cancelChord(); return }
let others = !event.modifierFlags.intersection([.control, .option, .shift, .command]).isEmpty
if fnTap.flagsChanged(keyCode: event.keyCode, fnDown: event.modifierFlags.contains(.function), otherModifiers: others) {
let expectedGeneration = generation
Task { @MainActor [weak self] in
guard let self, self.current == .fn, self.generation == expectedGeneration else { return }
self.onPress?()
}
}
}
private func removeFnMonitors() {
if let fnGlobalMonitor { NSEvent.removeMonitor(fnGlobalMonitor) }
if let fnLocalMonitor { NSEvent.removeMonitor(fnLocalMonitor) }
fnGlobalMonitor = nil; fnLocalMonitor = nil; fnTap = FnTap()
}
private func installHandler() -> Bool {
if handler != nil { return true }
var type = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
Expand All @@ -46,6 +86,7 @@ import ClearFlowCore
return status == noErr
}
func unregister() {
removeFnMonitors()
if let reference { UnregisterEventHotKey(reference) }
if let handler { RemoveEventHandler(handler) }
reference = nil; handler = nil; current = nil
Expand Down
29 changes: 24 additions & 5 deletions Sources/ClearFlow/ShortcutRecorderButton.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import ClearFlowCore
var onCapture: ((Shortcut) -> String?)?
var onMessage: ((String) -> Void)?
var savedTitle = "" { didSet { if !isRecording { title = savedTitle } } }
private var mouseMonitor: Any?
private var fnTap = FnTap()
private var captureMonitor: Any?
private(set) var isRecording = false
override var acceptsFirstResponder: Bool { true }

Expand All @@ -25,10 +26,12 @@ import ClearFlowCore
@objc private func beginRecording() {
guard isEnabled, !isRecording, window?.makeFirstResponder(self) == true else { return }
isRecording = true
fnTap = FnTap(heldAtStart: NSEvent.modifierFlags.contains(.function))
title = "Press shortcut…"
onBegin?()
mouseMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] event in
captureMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .systemDefined]) { [weak self] event in
guard let self else { return event }
if event.type == .systemDefined { self.fnTap.cancelChord(); return event }
if event.window !== self.window || !self.bounds.contains(self.convert(event.locationInWindow, from: nil)) {
self.cancelRecording()
}
Expand All @@ -45,8 +48,8 @@ import ClearFlowCore
}
private func finishRecording() {
isRecording = false
if let mouseMonitor { NSEvent.removeMonitor(mouseMonitor) }
mouseMonitor = nil
if let captureMonitor { NSEvent.removeMonitor(captureMonitor) }
captureMonitor = nil
NotificationCenter.default.removeObserver(self, name: NSWindow.didResignKeyNotification, object: nil)
title = savedTitle
onEnd?()
Expand All @@ -64,18 +67,34 @@ import ClearFlowCore
keyDown(with: event)
return true
}
override func flagsChanged(with event: NSEvent) {
guard isRecording else { super.flagsChanged(with: event); return }
let others = !event.modifierFlags.intersection([.control, .option, .shift, .command]).isEmpty
if fnTap.flagsChanged(keyCode: event.keyCode, fnDown: event.modifierFlags.contains(.function), otherModifiers: others) {
capture(.fn)
}
}
override func keyDown(with event: NSEvent) {
guard isRecording else { super.keyDown(with: event); return }
guard !event.isARepeat else { return }
fnTap.cancelChord()
if event.keyCode == 53 { cancelRecording(); return }
var modifiers: Shortcut.Modifiers = []
if event.modifierFlags.contains(.control) { modifiers.insert(.control) }
if event.modifierFlags.contains(.option) { modifiers.insert(.option) }
if event.modifierFlags.contains(.shift) { modifiers.insert(.shift) }
if event.modifierFlags.contains(.command) { modifiers.insert(.command) }
let value = Shortcut(keyCode: UInt32(event.keyCode), modifiers: modifiers)
// Fn combinations must not silently become a different shortcut without Fn.
if fnTap.isPressed {
onMessage?("Tap Fn by itself, or use a combination without Fn. Escape cancels.")
return
}
capture(value)
}
private func capture(_ value: Shortcut) {
guard value.isValid else {
onMessage?("Use Control, Option, or Command with a letter, number, Space, or F-key. Escape cancels.")
onMessage?("Tap Fn alone, or use Control, Option, or Command with a key. Escape cancels.")
return
}
guard let onCapture else { cancelRecording(); return }
Expand Down
8 changes: 7 additions & 1 deletion Sources/ClearFlow/Views.swift
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,13 @@ private struct FlowSettings: View {
}
Text(model.shortcutMessage.isEmpty ? "Click the shortcut, then press the new key combination." : model.shortcutMessage)
.font(.caption).foregroundStyle(FlowTheme.muted).padding(.top, 8)
if !model.shortcutAvailable { Text("This shortcut is unavailable. Choose another combination above, or use Start dictation.")
if model.shortcut.isFn {
Text("Tap Fn to start or finish. In macOS Keyboard settings, set ‘Press 🌐 key to’ to ‘Do Nothing’. Disable Fn in other dictation apps to avoid conflicts.")
.font(.caption).foregroundStyle(FlowTheme.muted).padding(.top, 8)
}
if !model.shortcutAvailable { Text(model.shortcut.isFn && !model.hasAccessibility
? "Fn is saved. Enable Accessibility below, then refresh permission status to activate it."
: "This shortcut is unavailable. Choose another combination above, or use Start dictation.")
.font(.caption).foregroundStyle(.orange).padding(.top, 8) }
rule()
row("Microphone", "Use your Mac’s default input.", granted: model.microphoneGranted) { model.requestMicrophone() }
Expand Down
22 changes: 22 additions & 0 deletions Sources/ClearFlowCore/FnTap.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/// A physical Fn press toggles only on release, and only if it was used alone.
public struct FnTap {
private var down = false
private var eligible = false
public var isPressed: Bool { down }
public init(heldAtStart: Bool = false) { down = heldAtStart }
public mutating func cancelChord() { eligible = false }
public mutating func flagsChanged(keyCode: UInt16, fnDown: Bool, otherModifiers: Bool) -> Bool {
if otherModifiers { eligible = false }
guard keyCode == 63 else {
if down { eligible = false }
return false
}
if fnDown {
if !down { down = true; eligible = !otherModifiers }
return false
}
let fire = down && eligible && !otherModifiers
down = false; eligible = false
return fire
}
}
6 changes: 5 additions & 1 deletion Sources/ClearFlowCore/Shortcut.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ public struct Shortcut: Codable, Equatable {
public var keyCode: UInt32
public var modifiers: Modifiers
public init(keyCode: UInt32, modifiers: Modifiers) { self.keyCode = keyCode; self.modifiers = modifiers }
public static let fn = Self(keyCode: 63, modifiers: [])
public var isFn: Bool { self == .fn }
public static let `default` = Self(keyCode: 49, modifiers: [.option, .shift])
public static let keys: [(code: UInt32, name: String)] = [
(49, "Space"), (0, "A"), (11, "B"), (8, "C"), (2, "D"), (14, "E"), (3, "F"),
Expand All @@ -25,11 +27,13 @@ public struct Shortcut: Codable, Equatable {
(98, "F7"), (100, "F8"), (101, "F9"), (109, "F10"), (103, "F11"), (111, "F12")
]
public var isValid: Bool {
modifiers.rawValue & ~UInt32(15) == 0 &&
if isFn { return true }
return modifiers.rawValue & ~UInt32(15) == 0 &&
!modifiers.intersection([.control, .option, .command]).isEmpty &&
Self.keys.contains { $0.code == keyCode }
}
public var keycaps: [String] {
if isFn { return ["Fn"] }
var labels: [String] = []
if modifiers.contains(.control) { labels.append("⌃") }
if modifiers.contains(.option) { labels.append("⌥") }
Expand Down
33 changes: 33 additions & 0 deletions Tests/ClearFlowCoreTests/SessionGateTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,38 @@ func XCTAssertNil<T>(_ a: T?, file: String = #file, line: Int = #line) { XCTAsse
func XCTAssertNotNil<T>(_ a: T?, file: String = #file, line: Int = #line) { XCTAssertTrue(a != nil, "Expected value", file: file, line: line) }

final class SessionGateTests {
func testFnTapFiresOnceOnReleaseAndIgnoresChords() {
XCTAssertTrue(Shortcut.fn.isValid)
XCTAssertEqual(Shortcut.load(Shortcut.fn.encoded), .fn)
XCTAssertEqual(Shortcut.fn.display, "Fn")
var held = FnTap(heldAtStart: true)
XCTAssertTrue(held.isPressed)
XCTAssertFalse(held.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
XCTAssertFalse(held.isPressed)
_ = held.flagsChanged(keyCode: 63, fnDown: true, otherModifiers: false)
XCTAssertTrue(held.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
var tap = FnTap()
XCTAssertFalse(tap.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
XCTAssertFalse(tap.flagsChanged(keyCode: 63, fnDown: true, otherModifiers: false))
XCTAssertFalse(tap.flagsChanged(keyCode: 63, fnDown: true, otherModifiers: false))
XCTAssertTrue(tap.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
XCTAssertFalse(tap.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
_ = tap.flagsChanged(keyCode: 63, fnDown: true, otherModifiers: false)
tap.cancelChord()
XCTAssertFalse(tap.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
_ = tap.flagsChanged(keyCode: 63, fnDown: true, otherModifiers: false)
_ = tap.flagsChanged(keyCode: 56, fnDown: true, otherModifiers: true)
_ = tap.flagsChanged(keyCode: 56, fnDown: true, otherModifiers: false)
XCTAssertFalse(tap.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
_ = tap.flagsChanged(keyCode: 63, fnDown: true, otherModifiers: false)
_ = tap.flagsChanged(keyCode: 57, fnDown: true, otherModifiers: false)
XCTAssertFalse(tap.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
// Arrow/function-key events can carry the function flag without a physical Fn tap.
XCTAssertFalse(tap.flagsChanged(keyCode: 123, fnDown: true, otherModifiers: false))
XCTAssertFalse(tap.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
_ = tap.flagsChanged(keyCode: 63, fnDown: true, otherModifiers: true)
XCTAssertFalse(tap.flagsChanged(keyCode: 63, fnDown: false, otherModifiers: false))
}
func testShortcutRejectsTypingKeysAndMalformedSavedValues() {
XCTAssertFalse(Shortcut(keyCode: 0, modifiers: []).isValid)
XCTAssertFalse(Shortcut(keyCode: 0, modifiers: [.shift]).isValid)
Expand Down Expand Up @@ -88,6 +120,7 @@ final class SessionGateTests {
@main enum CoreChecks {
static func main() {
let tests = SessionGateTests()
tests.testFnTapFiresOnceOnReleaseAndIgnoresChords()
tests.testShortcutRejectsTypingKeysAndMalformedSavedValues()
tests.testOnlyFinalResultForCurrentRecordingCanComplete()
tests.testCancelledRequestCannotOverwriteNewDictation()
Expand Down
25 changes: 25 additions & 0 deletions Tests/ShortcutRegistrationChecks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ import ClearFlowCore
}
require(shortcut.register(first), "initial registration")
require(shortcut.register(first), "reapplying the current shortcut")
if !AXIsProcessTrusted() {
require(!shortcut.register(.fn), "Fn must not report active without Accessibility")
let old = reserve(first.keyCode)
if let old { UnregisterEventHotKey(old) }
require(old == nil, "permission failure must preserve the Carbon binding")
}
guard let conflict = reserve(second.keyCode) else { fatalError("Test combination already occupied") }
require(!shortcut.register(second), "conflicting shortcut must be rejected")
let stolen = reserve(first.keyCode)
Expand Down Expand Up @@ -75,6 +81,25 @@ import ClearFlowCore
NotificationCenter.default.post(name: NSWindow.didResignKeyNotification, object: window)
require(!recorder.isRecording, "leaving window cancels recording")
shortcut.unregister()
// Exercise Fn recorder flags directly without posting any events to other apps.
recorder.onCapture = { value in chosen = value; return nil }
recorder.onEnd = nil
recorder.performClick(nil)
func fnEvent(_ flags: NSEvent.ModifierFlags) -> NSEvent {
NSEvent.keyEvent(with: .flagsChanged, location: .zero, modifierFlags: flags, timestamp: 0,
windowNumber: window.windowNumber, context: nil, characters: "", charactersIgnoringModifiers: "",
isARepeat: false, keyCode: 63)!
}
recorder.flagsChanged(with: fnEvent(.function))
require(recorder.isRecording, "Fn down must wait for release")
recorder.flagsChanged(with: fnEvent([]))
require(!recorder.isRecording && chosen == .fn, "Fn release saves Fn alone")
recorder.performClick(nil)
recorder.flagsChanged(with: fnEvent(.function))
recorder.keyDown(with: key(0, [.function, .control]))
recorder.flagsChanged(with: fnEvent([]))
require(recorder.isRecording && chosen == .fn, "Fn chord cannot be captured as another shortcut")
recorder.cancelRecording()
print("PASS: shortcut recorder key capture, invalid input, Escape and focus loss")
print("PASS: Carbon registration, reapply, conflict preservation, replacement and cleanup")
}
Expand Down
Loading
Loading