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 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.
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.

### 3. Dictate

Expand Down
1 change: 1 addition & 0 deletions Sources/ClearFlow/ClearFlowApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ import ClearFlowCore
model.showWindow = { [weak self] in self?.showWindow() }
shortcut.onPress = { [weak self] in self?.model.toggle() }
model.shortcutAvailable = shortcut.register(model.shortcut)
model.suspendShortcut = { [weak self] in self?.shortcut.unregister() }
model.registerShortcut = { [weak self] value in
guard let self else { return false }
return self.shortcut.register(value)
Expand Down
18 changes: 16 additions & 2 deletions Sources/ClearFlow/DictationModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,25 @@ import ClearFlowCore
@Published var microphoneGranted = AVCaptureDevice.authorizationStatus(for: .audio) == .authorized
@Published var shortcutAvailable = true
@Published private(set) var shortcut = AppSettings.shortcut
@Published var shortcutMessage = ""
private var recordingShortcut = false
var suspendShortcut: (() -> Void)?
func beginShortcutRecording() {
guard !busy else { return }
recordingShortcut = true
suspendShortcut?()
}
func endShortcutRecording() {
guard recordingShortcut else { return }
recordingShortcut = false
shortcutAvailable = registerShortcut?(shortcut) ?? false
}
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."
return "This shortcut is unavailable or used by another app."
}
AppSettings.shortcut = value
shortcut = value; shortcutAvailable = true
Expand Down Expand Up @@ -85,14 +98,15 @@ import ClearFlowCore
}
}
func toggle() {
guard !recordingShortcut else { return }
switch mode {
case .recording: stop()
case .transcribing, .requestingPermission, .testingInsertion: cancel()
default: start()
}
}
func start() {
guard !busy else { return }
guard !busy, !recordingShortcut else { return }
guard Endpoint.validated(AppSettings.endpoint) != nil, !TokenStore.read().isEmpty else {
status = "Connect your transcription service in Settings."; mode = .error; showWindow?(); return
}
Expand Down
90 changes: 90 additions & 0 deletions Sources/ClearFlow/ShortcutRecorderButton.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import AppKit
import ClearFlowCore

/// Captures keys only while explicitly focused; never installs a global keyboard monitor.
@MainActor final class ShortcutRecorderButton: NSButton {
var onBegin: (() -> Void)?
var onEnd: (() -> Void)?
var onCapture: ((Shortcut) -> String?)?
var onMessage: ((String) -> Void)?
var savedTitle = "" { didSet { if !isRecording { title = savedTitle } } }
private var mouseMonitor: Any?
private(set) var isRecording = false
override var acceptsFirstResponder: Bool { true }

override init(frame: NSRect) {
super.init(frame: frame)
bezelStyle = .rounded; controlSize = .large
font = .systemFont(ofSize: 14, weight: .medium)
target = self; action = #selector(beginRecording)
setAccessibilityLabel("Change shortcut")
toolTip = "Click, then press your new shortcut. Escape cancels."
}
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }

@objc private func beginRecording() {
guard isEnabled, !isRecording, window?.makeFirstResponder(self) == true else { return }
isRecording = true
title = "Press shortcut…"
onBegin?()
mouseMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] event in
guard let self else { return event }
if event.window !== self.window || !self.bounds.contains(self.convert(event.locationInWindow, from: nil)) {
self.cancelRecording()
}
return event
}
onMessage?("Press your shortcut. Escape cancels.")
NotificationCenter.default.addObserver(self, selector: #selector(cancelRecording),
name: NSWindow.didResignKeyNotification, object: window)
}
@objc func cancelRecording() {
guard isRecording else { return }
finishRecording()
onMessage?("")
}
private func finishRecording() {
isRecording = false
if let mouseMonitor { NSEvent.removeMonitor(mouseMonitor) }
mouseMonitor = nil
NotificationCenter.default.removeObserver(self, name: NSWindow.didResignKeyNotification, object: nil)
title = savedTitle
onEnd?()
}
override func resignFirstResponder() -> Bool {
cancelRecording()
return super.resignFirstResponder()
}
override func viewWillMove(toWindow newWindow: NSWindow?) {
if newWindow !== window { cancelRecording() }
super.viewWillMove(toWindow: newWindow)
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
guard isRecording, window?.isKeyWindow == true else { return super.performKeyEquivalent(with: event) }
keyDown(with: event)
return true
}
override func keyDown(with event: NSEvent) {
guard isRecording else { super.keyDown(with: event); return }
guard !event.isARepeat else { return }
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)
guard value.isValid else {
onMessage?("Use Control, Option, or Command with a letter, number, Space, or F-key. Escape cancels.")
return
}
guard let onCapture else { cancelRecording(); return }
if let error = onCapture(value) {
onMessage?(error + " Try another combination, or press Escape.")
} else {
savedTitle = value.display
finishRecording()
onMessage?("Shortcut saved.")
}
}
}
63 changes: 18 additions & 45 deletions Sources/ClearFlow/Views.swift
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,6 @@ 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) {
Expand Down Expand Up @@ -326,14 +325,10 @@ private struct FlowSettings: View {
Text("Press once to speak. Press again to finish.").font(.system(size: 12)).foregroundStyle(FlowTheme.muted)
}
Spacer()
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)
}
ShortcutRecorder(model: model).frame(width: 165, height: 34)
}
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.")
.font(.caption).foregroundStyle(.orange).padding(.top, 8) }
rule()
Expand Down Expand Up @@ -382,45 +377,23 @@ private struct FlowSettings: View {
}
}
}
private struct ShortcutEditor: View {
private struct ShortcutRecorder: NSViewRepresentable {
@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)
func makeNSView(context: Context) -> ShortcutRecorderButton {
let button = ShortcutRecorderButton(frame: .zero)
button.onBegin = { model.beginShortcutRecording() }
button.onEnd = { model.endShortcutRecording() }
button.onCapture = { model.changeShortcut($0) }
button.onMessage = { model.shortcutMessage = $0 }
return button
}
func updateNSView(_ button: ShortcutRecorderButton, context: Context) {
button.savedTitle = model.shortcut.display
button.isEnabled = !model.busy
if model.busy { button.cancelRecording() }
}
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)
static func dismantleNSView(_ button: ShortcutRecorderButton, coordinator: ()) {
button.cancelRecording()
}
}
struct Waveform: View {
Expand Down
41 changes: 41 additions & 0 deletions Tests/ShortcutRegistrationChecks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,47 @@ import ClearFlowCore
let final = reserve(second.keyCode)
require(final != nil, "unregister must release the current shortcut")
if let final { UnregisterEventHotKey(final) }
let recorder = ShortcutRecorderButton(frame: NSRect(x: 0, y: 0, width: 160, height: 32))
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 200, height: 100), styleMask: [.titled], backing: .buffered, defer: false)
window.contentView?.addSubview(recorder)
var chosen = first
recorder.onBegin = { shortcut.unregister() }
recorder.onEnd = { require(shortcut.register(chosen), "restore shortcut after recording") }
recorder.onCapture = { value in
guard shortcut.register(value) else { return "Conflict" }
chosen = value; return nil
}
func key(_ code: UInt16, _ flags: NSEvent.ModifierFlags = []) -> NSEvent {
NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: 0,
windowNumber: window.windowNumber, context: nil, characters: "", charactersIgnoringModifiers: "",
isARepeat: false, keyCode: code)!
}
recorder.performClick(nil)
require(recorder.isRecording, "click starts recording")
recorder.keyDown(with: key(0))
require(recorder.isRecording && chosen == first, "plain typing key must not overwrite shortcut")
recorder.keyDown(with: key(100, [.control, .option, .shift, .command, .capsLock]))
require(!recorder.isRecording && chosen == second, "keypress saves combination and ignores Caps Lock")
recorder.performClick(nil)
recorder.keyDown(with: key(53))
require(!recorder.isRecording && chosen == second, "Escape cancels without changes")
recorder.performClick(nil)
_ = recorder.resignFirstResponder()
require(!recorder.isRecording && chosen == second, "losing focus cancels capture")
recorder.performClick(nil)
guard let occupied = reserve(first.keyCode) else { fatalError("Test key unexpectedly occupied") }
recorder.keyDown(with: key(98, [.control, .option, .shift, .command]))
require(recorder.isRecording && chosen == second, "conflict keeps recorder active without saving")
recorder.keyDown(with: key(53))
let previous = reserve(second.keyCode)
if let previous { UnregisterEventHotKey(previous) }
require(previous == nil, "cancel after conflict restores previous shortcut")
UnregisterEventHotKey(occupied)
recorder.performClick(nil)
NotificationCenter.default.post(name: NSWindow.didResignKeyNotification, object: window)
require(!recorder.isRecording, "leaving window cancels recording")
shortcut.unregister()
print("PASS: shortcut recorder key capture, invalid input, Escape and focus loss")
print("PASS: Carbon registration, reapply, conflict preservation, replacement and cleanup")
}
}
2 changes: 1 addition & 1 deletion scripts/build-app.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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.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]}
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]}
(app/"Contents/Info.plist").write_bytes(plistlib.dumps(info))
PY
# Remove linker debug records containing the build machine absolute source paths.
Expand Down
2 changes: 1 addition & 1 deletion scripts/test-shortcut-registration.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ 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 \
Sources/ClearFlow/GlobalShortcut.swift Sources/ClearFlow/ShortcutRecorderButton.swift Tests/ShortcutRegistrationChecks.swift \
-o "$BUILD_DIR/ShortcutRegistrationChecks"
"$BUILD_DIR/ShortcutRegistrationChecks"
Loading