diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 450d64d..065fa8e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,7 @@ jobs: steps: - uses: actions/checkout@v4 - run: scripts/test-native.sh + - run: scripts/test-shortcut-registration.sh - run: scripts/build-app.sh - run: python3 scripts/check-distribution.py worker: diff --git a/AGENTS.md b/AGENTS.md index 43bcf31..d514e9d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,7 @@ Never commit credentials, actual service endpoints, account IDs, local machine p ```sh scripts/test-native.sh +scripts/test-shortcut-registration.sh scripts/build-app.sh python3 -m unittest discover -s local-stt -v python3 scripts/check-distribution.py diff --git a/README.md b/README.md index 0d75b11..99de3c6 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,10 @@ python3.12 local-stt/run.py --configure-app /Applications/ClearFlow.app The configuration command sends the token directly into macOS Keychain without displaying it or putting it in command-line arguments. Run it from your logged-in macOS desktop terminal so Keychain is available. Restart ClearFlow after configuring it. No Cloudflare account or Tailscale installation is needed for same-Mac use. +### Change the shortcut + +In **Settings → General**, click the shortcut beside the pencil. Choose modifiers and a key, then click **Apply shortcut**. Changes take effect immediately and survive a restart; no service configuration or separate Save is required. Include Control, Option, or Command. Key names refer to US keyboard positions. If macOS reports a conflict, ClearFlow keeps the previous shortcut. Avoid combinations already used by your editor or system; some app-local shortcuts cannot be detected. **Use default**, then Apply, restores Option–Shift–Space. Finish or cancel active dictation before editing. + ### 3. Dictate 1. Open ClearFlow. In Settings → General, allow Microphone and Accessibility through the normal macOS prompts. @@ -77,6 +81,7 @@ Deploy the supplied Worker in **your own account**, generate your own secret, an ```sh scripts/test-native.sh +scripts/test-shortcut-registration.sh scripts/build-app.sh python3 -m unittest discover -s local-stt -v python3 scripts/check-distribution.py diff --git a/Sources/ClearFlow/ClearFlowApp.swift b/Sources/ClearFlow/ClearFlowApp.swift index 00748ff..05ba97b 100644 --- a/Sources/ClearFlow/ClearFlowApp.swift +++ b/Sources/ClearFlow/ClearFlowApp.swift @@ -61,7 +61,7 @@ import ClearFlowCore let menu = NSMenu() statusMenuItem = NSMenuItem(title: model.status, action: nil, keyEquivalent: "") menu.addItem(statusMenuItem); menu.addItem(.separator()) - startItem = NSMenuItem(title: "Start dictation ⌥⇧Space", action: #selector(toggle), keyEquivalent: "") + startItem = NSMenuItem(title: "Start dictation", action: #selector(toggle), keyEquivalent: "") startItem.target = self; menu.addItem(startItem) let open = NSMenuItem(title: "Open ClearFlow…", action: #selector(showWindow), keyEquivalent: "") open.target = self; menu.addItem(open) @@ -77,16 +77,22 @@ import ClearFlowCore overlay.contentView = NSHostingView(rootView: OverlayView(model: model)) model.showWindow = { [weak self] in self?.showWindow() } shortcut.onPress = { [weak self] in self?.model.toggle() } - model.shortcutAvailable = shortcut.register() - subscription = model.$mode.combineLatest(model.$status).sink { [weak self] _, _ in + model.shortcutAvailable = shortcut.register(model.shortcut) + model.registerShortcut = { [weak self] value in + guard let self else { return false } + return self.shortcut.register(value) + } + subscription = model.$mode.combineLatest(model.$status, model.$shortcut).sink { [weak self] _, _, _ in DispatchQueue.main.async { self?.refresh() } } + refresh() // Open the controls at launch; recording still requires an explicit action. showWindow() } private func refresh() { statusMenuItem.title = String(model.status.prefix(85)) - startItem.title = model.mode == .recording ? "Finish dictation ⌥⇧Space" : model.busy ? "Cancel ⌥⇧Space" : "Start dictation ⌥⇧Space" + let action = model.mode == .recording ? "Finish dictation" : model.busy ? "Cancel" : "Start dictation" + startItem.title = action + " " + model.shortcut.display statusItem.button?.image = NSImage(systemSymbolName: model.mode == .recording ? "mic.fill" : model.mode == .transcribing ? "hourglass" : "waveform", accessibilityDescription: "ClearFlow") if model.busy { diff --git a/Sources/ClearFlow/DictationModel.swift b/Sources/ClearFlow/DictationModel.swift index e6f63b4..e8f780c 100644 --- a/Sources/ClearFlow/DictationModel.swift +++ b/Sources/ClearFlow/DictationModel.swift @@ -22,6 +22,18 @@ import ClearFlowCore @Published var hasAccessibility = AXIsProcessTrusted() @Published var microphoneGranted = AVCaptureDevice.authorizationStatus(for: .audio) == .authorized @Published var shortcutAvailable = true + @Published private(set) var shortcut = AppSettings.shortcut + 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 let registerShortcut, registerShortcut(value) else { + return "Could not register this shortcut. It may be used by another app or macOS. Choose another combination; your previous shortcut is unchanged." + } + AppSettings.shortcut = value + shortcut = value; shortcutAvailable = true + return nil + } var showWindow: (() -> Void)? var lastExternalApp: NSRunningApplication? private var demoMode = false @@ -39,6 +51,7 @@ import ClearFlowCore init(demo: Bool = false) { if demo { demoMode = true + shortcut = .default endpoint = "http://127.0.0.1:8768"; vocabulary = ""; token = "" saveHistory = false; hasAccessibility = true; microphoneGranted = true history = [Transcript(id: UUID(), date: Date(timeIntervalSince1970: 1780322400), diff --git a/Sources/ClearFlow/GlobalShortcut.swift b/Sources/ClearFlow/GlobalShortcut.swift index 30eee6c..24792a9 100644 --- a/Sources/ClearFlow/GlobalShortcut.swift +++ b/Sources/ClearFlow/GlobalShortcut.swift @@ -1,10 +1,32 @@ import Carbon +import ClearFlowCore @MainActor final class GlobalShortcut { private var reference: EventHotKeyRef? private var handler: EventHandlerRef? + private var current: Shortcut? + private var generation: UInt32 = 0 var onPress: (() -> Void)? - func register() -> Bool { + // Register the replacement first: a conflict must never discard the working shortcut. + func register(_ value: Shortcut) -> Bool { + guard value.isValid else { return false } + if current == value, reference != nil { return true } + guard installHandler() else { return false } + var modifiers: UInt32 = 0 + if value.modifiers.contains(.control) { modifiers |= UInt32(controlKey) } + if value.modifiers.contains(.option) { modifiers |= UInt32(optionKey) } + if value.modifiers.contains(.shift) { modifiers |= UInt32(shiftKey) } + if value.modifiers.contains(.command) { modifiers |= UInt32(cmdKey) } + let next = generation &+ 1 + var candidate: EventHotKeyRef? + 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) } + reference = candidate; current = value; generation = next + return true + } + private func installHandler() -> Bool { + if handler != nil { return true } var type = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed)) let pointer = Unmanaged.passUnretained(self).toOpaque() let status = InstallEventHandler(GetApplicationEventTarget(), { _, event, userData in @@ -14,16 +36,18 @@ import Carbon nil, MemoryLayout.size, nil, &id) guard id.signature == 0x43464c57 else { return OSStatus(eventNotHandledErr) } let shortcut = Unmanaged.fromOpaque(userData).takeUnretainedValue() - Task { @MainActor in shortcut.onPress?() } + let receivedID = id.id + Task { @MainActor in + guard shortcut.reference != nil, shortcut.generation == receivedID else { return } + shortcut.onPress?() + } return noErr }, 1, &type, pointer, &handler) - guard status == noErr else { return false } - let id = EventHotKeyID(signature: 0x43464c57, id: 1) - return RegisterEventHotKey(UInt32(kVK_Space), UInt32(optionKey | shiftKey), id, GetApplicationEventTarget(), 0, &reference) == noErr + return status == noErr } func unregister() { if let reference { UnregisterEventHotKey(reference) } if let handler { RemoveEventHandler(handler) } - reference = nil; handler = nil + reference = nil; handler = nil; current = nil } } diff --git a/Sources/ClearFlow/SettingsStore.swift b/Sources/ClearFlow/SettingsStore.swift index 0a072f4..bae3331 100644 --- a/Sources/ClearFlow/SettingsStore.swift +++ b/Sources/ClearFlow/SettingsStore.swift @@ -4,6 +4,10 @@ import ClearFlowCore struct AppSettings { static let defaults = UserDefaults.standard + static var shortcut: Shortcut { + get { Shortcut.load(defaults.data(forKey: "dictationShortcut")) } + set { defaults.set(newValue.encoded, forKey: "dictationShortcut") } + } static var endpoint: String { get { defaults.string(forKey: "endpoint") ?? (Bundle.main.object(forInfoDictionaryKey: "ClearFlowEndpoint") as? String ?? "http://127.0.0.1:8768") } set { defaults.set(newValue, forKey: "endpoint") } diff --git a/Sources/ClearFlow/Views.swift b/Sources/ClearFlow/Views.swift index bc61554..3110cae 100644 --- a/Sources/ClearFlow/Views.swift +++ b/Sources/ClearFlow/Views.swift @@ -1,4 +1,5 @@ import SwiftUI +import ClearFlowCore private enum FlowTheme { static let shell = Color(red: 0.965, green: 0.960, blue: 0.945) @@ -66,9 +67,9 @@ struct MainView: View { Spacer() VStack(alignment: .leading, spacing: 12) { Text("Make yourself heard").font(.system(size: 12, weight: .semibold)) - Text("Press Option–Shift–Space\nto start and finish.") + Text("Press \(model.shortcut.display)\nto start and finish.") .font(.system(size: 12)).foregroundStyle(FlowTheme.muted).lineSpacing(4) - HStack(spacing: 5) { keycap("⌥"); keycap("⇧"); keycap("space") } + HStack(spacing: 3) { ForEach(model.shortcut.keycaps, id: \.self) { keycap($0) } } }.padding(15).frame(maxWidth: .infinity, alignment: .leading) .background(.white, in: RoundedRectangle(cornerRadius: 13)) .overlay(RoundedRectangle(cornerRadius: 13).stroke(FlowTheme.line)) @@ -98,7 +99,7 @@ struct MainView: View { } private func keycap(_ text: String) -> some View { Text(text).font(.system(size: 12, weight: .medium)) - .padding(.horizontal, 9).padding(.vertical, 5) + .padding(.horizontal, 5).padding(.vertical, 5) .background(FlowTheme.shell, in: RoundedRectangle(cornerRadius: 5)) .overlay(RoundedRectangle(cornerRadius: 5).stroke(FlowTheme.line)) } @@ -150,7 +151,7 @@ struct MainView: View { Text(model.mode == .recording ? "Go on. We’re listening." : model.mode == .transcribing ? "Finding your words." : "Less typing.\nMore you.") .font(.system(size: 29, weight: .regular, design: .serif)) .foregroundStyle(Color(red: 0.98, green: 0.97, blue: 0.91)).lineSpacing(0) - Text(model.mode == .recording ? "Press Option–Shift–Space when you’re done." : model.mode == .transcribing ? "Your transcript will be ready in a moment." : "Speak naturally, wherever you write.") + Text(model.mode == .recording ? "Press \(model.shortcut.display) when you’re done." : model.mode == .transcribing ? "Your transcript will be ready in a moment." : "Speak naturally, wherever you write.") .font(.system(size: 12)).foregroundStyle(.white.opacity(0.80)) HStack(spacing: 9) { Button { model.toggle() } label: { @@ -208,7 +209,7 @@ struct MainView: View { Image(systemName: query.isEmpty ? "text.bubble" : "magnifyingglass").font(.system(size: 25)).foregroundStyle(FlowTheme.muted) Text(query.isEmpty ? "Your next thought starts here" : "No matching dictations") .font(.system(size: 16, weight: .medium)) - Text(query.isEmpty ? "Press ⌥ ⇧ Space, say what’s on your mind,\nthen press it again. Your words will appear here." : "Try another word or phrase.") + Text(query.isEmpty ? "Press \(model.shortcut.display), say what’s on your mind,\nthen press it again. Your words will appear here." : "Try another word or phrase.") .font(.system(size: 12)).foregroundStyle(FlowTheme.muted).multilineTextAlignment(.center).lineSpacing(4) }.frame(maxWidth: .infinity).padding(.vertical, 38) } else { @@ -263,6 +264,7 @@ private struct FlowSettings: View { @ObservedObject var model: DictationModel @Environment(\.dismiss) private var dismiss @State private var section = "General" + @State private var editingShortcut = false var body: some View { HStack(spacing: 0) { VStack(alignment: .leading, spacing: 6) { @@ -272,7 +274,7 @@ private struct FlowSettings: View { sectionButton("Transcription", "waveform") sectionButton("Data & privacy", "hand.raised") Spacer() - Text("ClearFlow 0.3").font(.system(size: 11)).foregroundStyle(FlowTheme.muted).padding(14) + Text("ClearFlow " + (Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "")).font(.system(size: 11)).foregroundStyle(FlowTheme.muted).padding(14) }.padding(10).frame(width: 174).background(FlowTheme.shell) VStack(alignment: .leading, spacing: 24) { HStack { @@ -324,10 +326,15 @@ private struct FlowSettings: View { Text("Press once to speak. Press again to finish.").font(.system(size: 12)).foregroundStyle(FlowTheme.muted) } Spacer() - Text("⌥ ⇧ Space").font(.system(size: 14, weight: .medium)).padding(11) - .background(FlowTheme.selected, in: RoundedRectangle(cornerRadius: 8)) + Button { editingShortcut = true } label: { + HStack { Text(model.shortcut.display); Image(systemName: "pencil") } + }.buttonStyle(FlowButton()).disabled(model.busy) + .accessibilityLabel("Change shortcut") + .popover(isPresented: $editingShortcut) { + ShortcutEditor(model: model, draft: model.shortcut) + } } - if !model.shortcutAvailable { Text("This shortcut is in use by another app. Close that app and restart ClearFlow, or use Start dictation.") + if !model.shortcutAvailable { Text("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() } @@ -375,6 +382,47 @@ private struct FlowSettings: View { } } } +private struct ShortcutEditor: View { + @ObservedObject var model: DictationModel + @State var draft: Shortcut + @State private var error = "" + @Environment(\.dismiss) private var dismiss + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Text("Change shortcut").font(.headline) + Text("Choose modifiers and a key. Applies immediately.") + .font(.caption).foregroundStyle(.secondary) + HStack { + modifier("⌃ Control", .control) + modifier("⌥ Option", .option) + modifier("⇧ Shift", .shift) + modifier("⌘ Command", .command) + } + Picker("Key (US keyboard positions)", selection: $draft.keyCode) { + ForEach(Shortcut.keys, id: \.code) { key in Text(key.name).tag(key.code) } + } + .onChange(of: draft.keyCode) { _, _ in error = "" } + Text(draft.display).font(.title3.monospaced()) + if !draft.isValid { Text("Include Control, Option, or Command.").font(.caption).foregroundStyle(.orange) } + if !error.isEmpty { Text(error).font(.caption).foregroundStyle(.red).fixedSize(horizontal: false, vertical: true) } + HStack { + Button("Use default") { draft = .default; error = "" } + Spacer() + Button("Cancel") { dismiss() } + Button("Apply shortcut") { + if let issue = model.changeShortcut(draft) { error = issue } + else { dismiss() } + }.disabled(!draft.isValid || model.busy) + } + }.padding(22).frame(width: 470) + } + private func modifier(_ title: String, _ flag: Shortcut.Modifiers) -> some View { + Toggle(title, isOn: Binding(get: { draft.modifiers.contains(flag) }, set: { enabled in + if enabled { draft.modifiers.insert(flag) } else { draft.modifiers.remove(flag) } + error = "" + })).toggleStyle(.checkbox).font(.caption) + } +} struct Waveform: View { let samples: [Double] var body: some View { diff --git a/Sources/ClearFlowCore/SessionGate.swift b/Sources/ClearFlowCore/SessionGate.swift index 36bf0ec..c944e8e 100644 --- a/Sources/ClearFlowCore/SessionGate.swift +++ b/Sources/ClearFlowCore/SessionGate.swift @@ -62,8 +62,8 @@ public enum DestinationPolicy { } public static func failure(accessibility: Bool, hasApp: Bool, hasField: Bool, secure: Bool, editable: Bool) -> String? { guard accessibility else { return "Enable Accessibility for ClearFlow in System Settings to insert text automatically." } - guard hasApp else { return "Select a text field in another app, then start with Option–Shift–Space." } - guard hasField else { return "The selected app did not expose a focused text field. Click its editor, then start with Option–Shift–Space." } + guard hasApp else { return "Select a text field in another app, then press your dictation shortcut." } + guard hasField else { return "The selected app did not expose a focused text field. Click its editor, then press your dictation shortcut." } guard !secure else { return "Automatic insertion is disabled in password fields." } guard editable else { return "The focused control is not an editable text field. Click inside the editor first." } return nil diff --git a/Sources/ClearFlowCore/Shortcut.swift b/Sources/ClearFlowCore/Shortcut.swift new file mode 100644 index 0000000..3fc358a --- /dev/null +++ b/Sources/ClearFlowCore/Shortcut.swift @@ -0,0 +1,47 @@ +import Foundation + +/// Physical key codes, independent of typed characters and transient modifier flags. +public struct Shortcut: Codable, Equatable { + public struct Modifiers: OptionSet, Codable, Equatable { + public let rawValue: UInt32 + public init(rawValue: UInt32) { self.rawValue = rawValue } + public static let control = Self(rawValue: 1) + public static let option = Self(rawValue: 2) + public static let shift = Self(rawValue: 4) + public static let command = Self(rawValue: 8) + } + public var keyCode: UInt32 + public var modifiers: Modifiers + public init(keyCode: UInt32, modifiers: Modifiers) { self.keyCode = keyCode; self.modifiers = modifiers } + 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"), + (5, "G"), (4, "H"), (34, "I"), (38, "J"), (40, "K"), (37, "L"), (46, "M"), + (45, "N"), (31, "O"), (35, "P"), (12, "Q"), (15, "R"), (1, "S"), (17, "T"), + (32, "U"), (9, "V"), (13, "W"), (7, "X"), (16, "Y"), (6, "Z"), + (29, "0"), (18, "1"), (19, "2"), (20, "3"), (21, "4"), (23, "5"), + (22, "6"), (26, "7"), (28, "8"), (25, "9"), + (122, "F1"), (120, "F2"), (99, "F3"), (118, "F4"), (96, "F5"), (97, "F6"), + (98, "F7"), (100, "F8"), (101, "F9"), (109, "F10"), (103, "F11"), (111, "F12") + ] + public var isValid: Bool { + modifiers.rawValue & ~UInt32(15) == 0 && + !modifiers.intersection([.control, .option, .command]).isEmpty && + Self.keys.contains { $0.code == keyCode } + } + public var keycaps: [String] { + var labels: [String] = [] + if modifiers.contains(.control) { labels.append("⌃") } + if modifiers.contains(.option) { labels.append("⌥") } + if modifiers.contains(.shift) { labels.append("⇧") } + if modifiers.contains(.command) { labels.append("⌘") } + labels.append(Self.keys.first { $0.code == keyCode }?.name ?? "Unknown") + return labels + } + public var display: String { keycaps.joined(separator: " ") } + public var encoded: Data? { try? JSONEncoder().encode(self) } + public static func load(_ data: Data?) -> Self { + guard let data, let value = try? JSONDecoder().decode(Self.self, from: data), value.isValid else { return .default } + return value + } +} diff --git a/Tests/ClearFlowCoreTests/SessionGateTests.swift b/Tests/ClearFlowCoreTests/SessionGateTests.swift index ddd0b16..2534672 100644 --- a/Tests/ClearFlowCoreTests/SessionGateTests.swift +++ b/Tests/ClearFlowCoreTests/SessionGateTests.swift @@ -9,6 +9,18 @@ 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 testShortcutRejectsTypingKeysAndMalformedSavedValues() { + XCTAssertFalse(Shortcut(keyCode: 0, modifiers: []).isValid) + XCTAssertFalse(Shortcut(keyCode: 0, modifiers: [.shift]).isValid) + XCTAssertFalse(Shortcut(keyCode: 999, modifiers: [.option]).isValid) + XCTAssertFalse(Shortcut(keyCode: 49, modifiers: .init(rawValue: 128)).isValid) + XCTAssertTrue(Shortcut(keyCode: 49, modifiers: [.control, .option]).isValid) + XCTAssertEqual(Shortcut.load(Data("{}".utf8)), .default) + XCTAssertEqual(Shortcut.load(Data("{\"keyCode\":0,\"modifiers\":0}".utf8)), .default) + let chosen = Shortcut(keyCode: 40, modifiers: [.control, .shift]) + XCTAssertEqual(Shortcut.load(chosen.encoded), chosen) + XCTAssertEqual(chosen.display, "⌃ ⇧ K") + } func testOnlyFinalResultForCurrentRecordingCanComplete() { var gate = SessionGate() let id = UUID() @@ -76,6 +88,7 @@ final class SessionGateTests { @main enum CoreChecks { static func main() { let tests = SessionGateTests() + tests.testShortcutRejectsTypingKeysAndMalformedSavedValues() tests.testOnlyFinalResultForCurrentRecordingCanComplete() tests.testCancelledRequestCannotOverwriteNewDictation() tests.testEndpointRejectsCredentialAndQueryLeakage() diff --git a/Tests/ShortcutRegistrationChecks.swift b/Tests/ShortcutRegistrationChecks.swift new file mode 100644 index 0000000..604743b --- /dev/null +++ b/Tests/ShortcutRegistrationChecks.swift @@ -0,0 +1,40 @@ +import AppKit +import Carbon +import ClearFlowCore + +// Device integration check: exercises Carbon ownership without synthesizing keypresses. +@main enum ShortcutRegistrationChecks { + @MainActor static func main() { + _ = NSApplication.shared + let shortcut = GlobalShortcut() + defer { shortcut.unregister() } + let first = Shortcut(keyCode: 98, modifiers: [.control, .option, .shift, .command]) + let second = Shortcut(keyCode: 100, modifiers: [.control, .option, .shift, .command]) + func require(_ condition: Bool, _ message: String) { + if !condition { fputs("FAIL: \(message)\n", stderr); exit(1) } + } + func reserve(_ key: UInt32) -> EventHotKeyRef? { + var ref: EventHotKeyRef? + let result = RegisterEventHotKey(key, UInt32(controlKey | optionKey | shiftKey | cmdKey), + EventHotKeyID(signature: 0x54455354, id: key), GetApplicationEventTarget(), 0, &ref) + return result == noErr ? ref : nil + } + require(shortcut.register(first), "initial registration") + require(shortcut.register(first), "reapplying the current shortcut") + 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) + if let stolen { UnregisterEventHotKey(stolen) } + require(stolen == nil, "failed change must preserve the first shortcut") + UnregisterEventHotKey(conflict) + require(shortcut.register(second), "retry after conflict is released") + let released = reserve(first.keyCode) + require(released != nil, "successful replacement must release the old shortcut") + if let released { UnregisterEventHotKey(released) } + shortcut.unregister() + let final = reserve(second.keyCode) + require(final != nil, "unregister must release the current shortcut") + if let final { UnregisterEventHotKey(final) } + print("PASS: Carbon registration, reapply, conflict preservation, replacement and cleanup") + } +} diff --git a/scripts/build-app.sh b/scripts/build-app.sh index b0c29ef..0ebf97f 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.0","CFBundleVersion":"8","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.1","CFBundleVersion":"9","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. diff --git a/scripts/test-shortcut-registration.sh b/scripts/test-shortcut-registration.sh new file mode 100755 index 0000000..7716905 --- /dev/null +++ b/scripts/test-shortcut-registration.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +swift build --product ClearFlow +BUILD_DIR="$(swift build --show-bin-path)" +swiftc -parse-as-library -I "$BUILD_DIR/Modules" "$BUILD_DIR"/ClearFlowCore.build/*.o \ + Sources/ClearFlow/GlobalShortcut.swift Tests/ShortcutRegistrationChecks.swift \ + -o "$BUILD_DIR/ShortcutRegistrationChecks" +"$BUILD_DIR/ShortcutRegistrationChecks"