diff --git a/README.md b/README.md index 553f110..3b0a0c9 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/Sources/ClearFlow/DictationModel.swift b/Sources/ClearFlow/DictationModel.swift index aa04ec5..a399b0c 100644 --- a/Sources/ClearFlow/DictationModel.swift +++ b/Sources/ClearFlow/DictationModel.swift @@ -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." } @@ -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() { diff --git a/Sources/ClearFlow/GlobalShortcut.swift b/Sources/ClearFlow/GlobalShortcut.swift index 24792a9..1ed4c2b 100644 --- a/Sources/ClearFlow/GlobalShortcut.swift +++ b/Sources/ClearFlow/GlobalShortcut.swift @@ -1,4 +1,5 @@ import Carbon +import AppKit import ClearFlowCore @MainActor final class GlobalShortcut { @@ -6,10 +7,14 @@ import ClearFlowCore 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 @@ -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)) @@ -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 diff --git a/Sources/ClearFlow/ShortcutRecorderButton.swift b/Sources/ClearFlow/ShortcutRecorderButton.swift index 517c167..1d43e84 100644 --- a/Sources/ClearFlow/ShortcutRecorderButton.swift +++ b/Sources/ClearFlow/ShortcutRecorderButton.swift @@ -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 } @@ -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() } @@ -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?() @@ -64,9 +67,17 @@ 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) } @@ -74,8 +85,16 @@ import ClearFlowCore 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 } diff --git a/Sources/ClearFlow/Views.swift b/Sources/ClearFlow/Views.swift index 0cf59a9..f71187c 100644 --- a/Sources/ClearFlow/Views.swift +++ b/Sources/ClearFlow/Views.swift @@ -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() } diff --git a/Sources/ClearFlowCore/FnTap.swift b/Sources/ClearFlowCore/FnTap.swift new file mode 100644 index 0000000..0be50ce --- /dev/null +++ b/Sources/ClearFlowCore/FnTap.swift @@ -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 + } +} diff --git a/Sources/ClearFlowCore/Shortcut.swift b/Sources/ClearFlowCore/Shortcut.swift index 3fc358a..d71421c 100644 --- a/Sources/ClearFlowCore/Shortcut.swift +++ b/Sources/ClearFlowCore/Shortcut.swift @@ -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"), @@ -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("⌥") } diff --git a/Tests/ClearFlowCoreTests/SessionGateTests.swift b/Tests/ClearFlowCoreTests/SessionGateTests.swift index 2534672..e5ee9c7 100644 --- a/Tests/ClearFlowCoreTests/SessionGateTests.swift +++ b/Tests/ClearFlowCoreTests/SessionGateTests.swift @@ -9,6 +9,38 @@ func XCTAssertNil(_ a: T?, file: String = #file, line: Int = #line) { XCTAsse func XCTAssertNotNil(_ 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) @@ -88,6 +120,7 @@ final class SessionGateTests { @main enum CoreChecks { static func main() { let tests = SessionGateTests() + tests.testFnTapFiresOnceOnReleaseAndIgnoresChords() tests.testShortcutRejectsTypingKeysAndMalformedSavedValues() tests.testOnlyFinalResultForCurrentRecordingCanComplete() tests.testCancelledRequestCannotOverwriteNewDictation() diff --git a/Tests/ShortcutRegistrationChecks.swift b/Tests/ShortcutRegistrationChecks.swift index d810bf5..494f1c6 100644 --- a/Tests/ShortcutRegistrationChecks.swift +++ b/Tests/ShortcutRegistrationChecks.swift @@ -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) @@ -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") } diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 58462e2..172fcaa 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -10,7 +10,7 @@ cp "$(swift build -c release --arch arm64 --show-bin-path)/ClearFlow" "$APP/Cont python3 - "$APP" "http://127.0.0.1:8768" <<'PY' import pathlib,plistlib,sys app=pathlib.Path(sys.argv[1]) -info={"CFBundleName":"ClearFlow","CFBundleDisplayName":"ClearFlow","CFBundleIdentifier":"org.clearflow.app","CFBundleExecutable":"ClearFlow","CFBundlePackageType":"APPL","CFBundleShortVersionString":"0.4.2","CFBundleVersion":"10","LSMinimumSystemVersion":"14.0","LSUIElement":True,"NSHighResolutionCapable":True,"NSMicrophoneUsageDescription":"ClearFlow records your voice only when you start dictation, then sends it to the transcription service you configure.","ClearFlowEndpoint":sys.argv[2]} +info={"CFBundleName":"ClearFlow","CFBundleDisplayName":"ClearFlow","CFBundleIdentifier":"org.clearflow.app","CFBundleExecutable":"ClearFlow","CFBundlePackageType":"APPL","CFBundleShortVersionString":"0.4.3","CFBundleVersion":"11","LSMinimumSystemVersion":"14.0","LSUIElement":True,"NSHighResolutionCapable":True,"NSMicrophoneUsageDescription":"ClearFlow records your voice only when you start dictation, then sends it to the transcription service you configure.","ClearFlowEndpoint":sys.argv[2]} (app/"Contents/Info.plist").write_bytes(plistlib.dumps(info)) PY # Remove linker debug records containing the build machine absolute source paths.