Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

Support multiple primary dictation shortcuts

George Pickett52592778bc33
diff --git a/Sources/Fluid/AppBundleMetadata.swift b/Sources/Fluid/AppBundleMetadata.swift
new file mode 100644
index 00000000..7e15c4cf
--- /dev/null
+++ b/Sources/Fluid/AppBundleMetadata.swift
@@ -0,0 +1,11 @@
+import Foundation
+
+extension Bundle {
+ var fluidAppDisplayName: String {
+ let displayName = self.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
+ let bundleName = self.object(forInfoDictionaryKey: "CFBundleName") as? String
+ return [displayName, bundleName]
+ .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .first { !$0.isEmpty } ?? "FluidVoice"
+ }
+}
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 63941339..0af8db26 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -61,8 +61,18 @@ enum SidebarItem: Hashable {
case rewriteMode
}
+enum PrimaryDictationShortcutEdit: Hashable {
+ case add
+ case replace(Int)
+
+ var replacementIndex: Int? {
+ if case let .replace(index) = self { return index }
+ return nil
+ }
+}
+
enum ShortcutRecordingTarget: Hashable {
- case primaryDictation
+ case primaryDictation(PrimaryDictationShortcutEdit)
case secondaryDictation
case command
case edit
@@ -104,7 +114,19 @@ enum ShortcutRecordingTarget: Hashable {
}
var allowsMouseShortcut: Bool {
- self == .primaryDictation
+ self.isPrimaryDictation
+ }
+
+ var isPrimaryDictation: Bool {
+ if case .primaryDictation = self { return true }
+ return false
+ }
+
+ var primaryDictationReplacementIndex: Int? {
+ if case let .primaryDictation(edit) = self {
+ return edit.replacementIndex
+ }
+ return nil
}
}
@@ -155,7 +177,7 @@ struct ContentView: View {
@State private var appear = false
@State private var accessibilityEnabled = false
- @State private var hotkeyShortcut: HotkeyShortcut = SettingsStore.shared.hotkeyShortcut
+ @State private var primaryDictationShortcuts: [HotkeyShortcut] = SettingsStore.shared.primaryDictationShortcuts
@State private var promptModeHotkeyShortcut: HotkeyShortcut = SettingsStore.shared.promptModeHotkeyShortcut
@State private var commandModeHotkeyShortcut: HotkeyShortcut = SettingsStore.shared.commandModeHotkeyShortcut
@State private var rewriteModeHotkeyShortcut: HotkeyShortcut = SettingsStore.shared.rewriteModeHotkeyShortcut
@@ -176,6 +198,7 @@ struct ContentView: View {
@State private var pendingModifierKeyCode: UInt16?
@State private var pendingModifierOnly = false
@State private var shortcutRecordingMessage: String? = nil
+ @State private var shortcutCaptureMonitor: Any?
@FocusState private var isTranscriptionFocused: Bool
@State private var selectedSidebarItem: SidebarItem?
@@ -275,10 +298,7 @@ struct ContentView: View {
return observed
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
- let trusted = AXIsProcessTrusted()
- if trusted != self.accessibilityEnabled {
- self.accessibilityEnabled = trusted
- }
+ self.refreshAccessibilityPermissionState()
}
.onReceive(NotificationCenter.default.publisher(for: .openCustomDictionaryFromVoiceEngine)) { _ in
self.selectedSidebarItem = .customDictionary
@@ -367,10 +387,19 @@ struct ContentView: View {
// Stop accessibility polling
self.finishAccessibilityPermissionFlow()
+ self.removeShortcutCaptureMonitor()
}
- .onChange(of: self.hotkeyShortcut) { _, newValue in
- DebugLogger.shared.debug("Hotkey shortcut changed to \(newValue.displayString)", source: "ContentView")
- self.hotkeyManager?.updateShortcut(newValue)
+ .onChange(of: self.primaryDictationShortcuts) { _, newValue in
+ SettingsStore.shared.primaryDictationShortcuts = newValue
+ let storedShortcuts = SettingsStore.shared.primaryDictationShortcuts
+ if storedShortcuts != newValue {
+ self.primaryDictationShortcuts = storedShortcuts
+ return
+ }
+
+ let display = storedShortcuts.map(\.displayString).joined(separator: ", ")
+ DebugLogger.shared.debug("Primary dictation shortcuts changed to \(display)", source: "ContentView")
+ self.hotkeyManager?.updatePrimaryShortcuts(storedShortcuts)
// Update initialization status after shortcut change
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
@@ -488,7 +517,7 @@ struct ContentView: View {
private func handleContentAppear() {
self.appear = true
- self.accessibilityEnabled = self.checkAccessibilityPermissions()
+ self.refreshAccessibilityPermissionState()
self.handleMenuBarNavigation(self.menuBarManager.requestedNavigationDestination)
if UserDefaults.standard.bool(forKey: self.accessibilityRestartFlagKey) {
@@ -641,11 +670,20 @@ struct ContentView: View {
}
private func installShortcutCaptureMonitor() {
- NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .flagsChanged, .leftMouseDown, .rightMouseDown, .otherMouseDown]) { event in
+ self.removeShortcutCaptureMonitor()
+ self.shortcutCaptureMonitor = NSEvent.addLocalMonitorForEvents(
+ matching: [.keyDown, .flagsChanged, .leftMouseDown, .rightMouseDown, .otherMouseDown]
+ ) { event in
self.handleShortcutCaptureEvent(event)
}
}
+ private func removeShortcutCaptureMonitor() {
+ guard let monitor = self.shortcutCaptureMonitor else { return }
+ NSEvent.removeMonitor(monitor)
+ self.shortcutCaptureMonitor = nil
+ }
+
private func handleShortcutCaptureEvent(_ event: NSEvent) -> NSEvent? {
let eventModifiers = event.modifierFlags.intersection([.function, .command, .option, .control, .shift])
let isRecordingAnyShortcut = self.isRecordingAnyShortcutCapture
@@ -938,8 +976,17 @@ struct ContentView: View {
}
}
+ let replacingPrimaryIndex = target.primaryDictationReplacementIndex
+ for (index, configuredShortcut) in self.primaryDictationShortcuts.enumerated() where replacingPrimaryIndex != index {
+ if configuredShortcut == shortcut {
+ return "Duplicate with Primary Dictation Shortcut"
+ }
+ if shortcut.conflictsWith(configuredShortcut) {
+ return "Overlaps Primary Dictation Shortcut — use a different modifier key"
+ }
+ }
+
let configuredShortcuts: [(ShortcutRecordingTarget, HotkeyShortcut)] = [
- (.primaryDictation, self.hotkeyShortcut),
(.secondaryDictation, self.promptModeHotkeyShortcut),
(.command, self.commandModeHotkeyShortcut),
(.edit, self.rewriteModeHotkeyShortcut),
@@ -983,10 +1030,8 @@ struct ContentView: View {
private func applyRecordedShortcut(_ shortcut: HotkeyShortcut, to target: ShortcutRecordingTarget) {
switch target {
- case .primaryDictation:
- self.hotkeyShortcut = shortcut
- SettingsStore.shared.hotkeyShortcut = shortcut
- self.hotkeyManager?.updateShortcut(shortcut)
+ case let .primaryDictation(edit):
+ self.applyPrimaryDictationShortcut(shortcut, edit: edit)
case .secondaryDictation:
self.promptModeHotkeyShortcut = shortcut
SettingsStore.shared.promptModeHotkeyShortcut = shortcut
@@ -1017,6 +1062,21 @@ struct ContentView: View {
}
}
+ private func applyPrimaryDictationShortcut(_ shortcut: HotkeyShortcut, edit: PrimaryDictationShortcutEdit) {
+ var shortcuts = self.primaryDictationShortcuts
+ switch edit {
+ case .add:
+ shortcuts.append(shortcut)
+ case let .replace(index):
+ if shortcuts.indices.contains(index) {
+ shortcuts[index] = shortcut
+ } else {
+ shortcuts.append(shortcut)
+ }
+ }
+ self.primaryDictationShortcuts = shortcuts
+ }
+
private func setShortcutTargetEnabled(_ enabled: Bool, for target: ShortcutRecordingTarget) {
switch target {
case .secondaryDictation:
@@ -1352,7 +1412,7 @@ struct ContentView: View {
inputDevices: self.$inputDevices,
outputDevices: self.$outputDevices,
accessibilityEnabled: self.$accessibilityEnabled,
- hotkeyShortcut: self.$hotkeyShortcut,
+ primaryDictationShortcuts: self.$primaryDictationShortcuts,
activeShortcutRecordingTarget: self.$activeShortcutRecordingTarget,
shortcutRecordingMessage: self.$shortcutRecordingMessage,
commandModeShortcut: self.$commandModeHotkeyShortcut,
@@ -2950,7 +3010,7 @@ struct ContentView: View {
self.hotkeyManager = GlobalHotkeyManager(
asrService: self.asr,
- shortcut: self.hotkeyShortcut,
+ primaryShortcuts: self.primaryDictationShortcuts,
promptModeShortcut: self.promptModeHotkeyShortcut,
commandModeShortcut: self.commandModeHotkeyShortcut,
rewriteModeShortcut: self.rewriteModeHotkeyShortcut,
@@ -3543,6 +3603,15 @@ extension ContentView {
return AXIsProcessTrusted()
}
+ @discardableResult
+ private func refreshAccessibilityPermissionState() -> Bool {
+ let trusted = self.checkAccessibilityPermissions()
+ if trusted != self.accessibilityEnabled {
+ self.accessibilityEnabled = trusted
+ }
+ return trusted
+ }
+
func openAccessibilitySettings() {
let requestID = UUID()
self.accessibilityGuideRequestID = requestID
@@ -3647,7 +3716,7 @@ extension ContentView {
private func showAccessibilityGuidePanel(requestID: UUID) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.65) {
guard self.accessibilityGuideRequestID == requestID else { return }
- guard !AXIsProcessTrusted() else {
+ guard !self.refreshAccessibilityPermissionState() else {
self.finishAccessibilityPermissionFlow()
return
}
@@ -3692,6 +3761,7 @@ extension ContentView {
panel.contentView = NSHostingView(
rootView: AccessibilitySettingsFloatingGuideView(
appURL: self.draggableAccessibilityAppURL,
+ appName: self.accessibilityAppDisplayName,
onReturnToApp: {
self.cancelAccessibilityPermissionFlow()
},
@@ -3764,6 +3834,7 @@ extension ContentView {
if isTrusted {
await MainActor.run {
+ self.refreshAccessibilityPermissionState()
self.finishAccessibilityPermissionFlow()
}
return
@@ -3786,6 +3857,13 @@ extension ContentView {
}
private var draggableAccessibilityAppURL: URL {
+ let runningAppURL = Bundle.main.bundleURL
+ if runningAppURL.pathExtension == "app",
+ FileManager.default.fileExists(atPath: runningAppURL.path)
+ {
+ return runningAppURL
+ }
+
let installedURL = URL(fileURLWithPath: "/Applications/FluidVoice.app")
if FileManager.default.fileExists(atPath: installedURL.path) {
return installedURL
@@ -3793,6 +3871,10 @@ extension ContentView {
return Bundle.main.bundleURL
}
+ private var accessibilityAppDisplayName: String {
+ Bundle.main.fluidAppDisplayName
+ }
+
func restartApp() {
let appPath = Bundle.main.bundlePath
let process = Process()
@@ -3808,9 +3890,9 @@ extension ContentView {
}
func startAccessibilityPolling() {
- // Don't poll if already enabled or if we've already auto-restarted once
+ // Keep polling until macOS reports the current process is trusted. The restart guard
+ // only prevents restart loops; it must not prevent the UI from noticing permission changes.
guard !self.accessibilityEnabled else { return }
- guard !UserDefaults.standard.bool(forKey: self.hasAutoRestartedForAccessibilityKey) else { return }
// Cancel any existing polling task
self.accessibilityPollingTask?.cancel()
@@ -3824,13 +3906,18 @@ extension ContentView {
let nowTrusted = AXIsProcessTrusted()
if nowTrusted && !self.accessibilityEnabled {
await MainActor.run {
- DebugLogger.shared.info("Accessibility permission granted! Auto-restarting app...", source: "ContentView")
+ DebugLogger.shared.info("Accessibility permission granted", source: "ContentView")
+ self.refreshAccessibilityPermissionState()
self.finishAccessibilityPermissionFlow()
- // Mark that we've auto-restarted to prevent loops
- UserDefaults.standard.set(true, forKey: self.hasAutoRestartedForAccessibilityKey)
+ guard !UserDefaults.standard.bool(forKey: self.hasAutoRestartedForAccessibilityKey) else {
+ self.hotkeyManager?.reinitialize()
+ return
+ }
- // Give user brief moment to see any UI feedback
+ // Mark that we've auto-restarted to prevent loops.
+ UserDefaults.standard.set(true, forKey: self.hasAutoRestartedForAccessibilityKey)
+ DebugLogger.shared.info("Auto-restarting app after accessibility grant", source: "ContentView")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.restartApp()
}
@@ -3851,6 +3938,7 @@ extension ContentView {
private struct AccessibilitySettingsFloatingGuideView: View {
let appURL: URL
+ let appName: String
let onReturnToApp: () -> Void
let onClose: () -> Void
@@ -3874,7 +3962,7 @@ private struct AccessibilitySettingsFloatingGuideView: View {
value: self.isArrowRaised
)
- Text("Drag FluidVoice into the Accessibility apps list as shown")
+ Text("Drag \(self.appName) into the Accessibility apps list as shown")
.font(.system(size: 15, weight: .semibold))
.foregroundStyle(.white.opacity(0.78))
.lineLimit(1)
@@ -3909,14 +3997,14 @@ private struct AccessibilitySettingsFloatingGuideView: View {
}
.buttonStyle(.plain)
.focusable(false)
- .help("Return to FluidVoice")
+ .help("Return to \(self.appName)")
Image(nsImage: self.appIcon)
.resizable()
.frame(width: 34, height: 34)
.clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
- Text("FluidVoice")
+ Text(self.appName)
.font(.system(size: 16, weight: .semibold))
.foregroundStyle(.white.opacity(0.92))
@@ -3950,7 +4038,7 @@ private struct AccessibilitySettingsFloatingGuideView: View {
.onDrag {
NSItemProvider(object: self.appURL as NSURL)
}
- .accessibilityLabel("Drag FluidVoice to the Accessibility list")
+ .accessibilityLabel("Drag \(self.appName) to the Accessibility list")
}
.padding(.horizontal, 20)
.padding(.vertical, 16)
@@ -3972,7 +4060,7 @@ private struct AccessibilitySettingsFloatingGuideView: View {
private extension ContentView {
func reloadSettingsStateAfterBackupRestore() {
- self.hotkeyShortcut = SettingsStore.shared.hotkeyShortcut
+ self.primaryDictationShortcuts = SettingsStore.shared.primaryDictationShortcuts
self.promptModeHotkeyShortcut = SettingsStore.shared.promptModeHotkeyShortcut
self.commandModeHotkeyShortcut = SettingsStore.shared.commandModeHotkeyShortcut
self.rewriteModeHotkeyShortcut = SettingsStore.shared.rewriteModeHotkeyShortcut
@@ -3995,7 +4083,7 @@ private extension ContentView {
self.savedProviders = SettingsStore.shared.savedProviders
self.selectedProviderID = SettingsStore.shared.selectedProviderID
- self.hotkeyManager?.updateShortcut(self.hotkeyShortcut)
+ self.hotkeyManager?.updatePrimaryShortcuts(self.primaryDictationShortcuts)
self.hotkeyManager?.updatePromptModeShortcut(self.promptModeHotkeyShortcut)
self.hotkeyManager?.updatePromptModeShortcutEnabled(self.isPromptModeShortcutEnabled)
self.hotkeyManager?.updatePromptShortcutAssignments(SettingsStore.shared.dictationPromptShortcutAssignments())
diff --git a/Sources/Fluid/Persistence/BackupService.swift b/Sources/Fluid/Persistence/BackupService.swift
index d53523e6..4d590e7c 100644
--- a/Sources/Fluid/Persistence/BackupService.swift
+++ b/Sources/Fluid/Persistence/BackupService.swift
@@ -18,6 +18,9 @@ struct SettingsBackupPayload: Codable, Equatable {
let selectedNemotronLanguage: SettingsStore.NemotronLanguage?
let selectedAppleSpeechLocaleIdentifier: String?
let hotkeyShortcut: HotkeyShortcut
+ // Older backup files only contain hotkeyShortcut; nil restores that legacy single shortcut.
+ // swiftlint:disable:next discouraged_optional_collection
+ let primaryDictationShortcuts: [HotkeyShortcut]?
let promptModeHotkeyShortcut: HotkeyShortcut
let promptModeShortcutEnabled: Bool
let promptModeSelectedPromptID: String?
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index e90be710..56bd56c5 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -96,7 +96,9 @@ final class SettingsStore: ObservableObject {
case primary
case secondary
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var displayName: String {
switch self {
@@ -1467,22 +1469,84 @@ final class SettingsStore: ObservableObject {
var hotkeyShortcut: HotkeyShortcut {
get {
- if let data = defaults.data(forKey: Keys.hotkeyShortcutKey),
- let shortcut = try? JSONDecoder().decode(HotkeyShortcut.self, from: data)
+ self.primaryDictationShortcuts.first ?? Self.defaultPrimaryDictationShortcut
+ }
+ set {
+ objectWillChange.send()
+ let shortcuts = Self.normalizedPrimaryDictationShortcuts([newValue], fallback: Self.defaultPrimaryDictationShortcut)
+ self.storePrimaryDictationShortcuts(shortcuts)
+ self.storeLegacyHotkeyShortcut(shortcuts[0])
+ }
+ }
+
+ var primaryDictationShortcutDisplayString: String {
+ let displays = self.primaryDictationShortcuts
+ .map(\.displayString)
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ return displays.isEmpty ? Self.defaultPrimaryDictationShortcut.displayString : displays.joined(separator: " / ")
+ }
+
+ var primaryDictationShortcuts: [HotkeyShortcut] {
+ get {
+ let fallback = self.legacyHotkeyShortcut
+ if let data = defaults.data(forKey: Keys.primaryDictationShortcutsKey),
+ let shortcuts = try? JSONDecoder().decode([HotkeyShortcut].self, from: data)
{
- return shortcut
+ return Self.normalizedPrimaryDictationShortcuts(shortcuts, fallback: fallback)
}
- return HotkeyShortcut(keyCode: 61, modifierFlags: [])
+ return [fallback]
}
set {
objectWillChange.send()
- if let data = try? JSONEncoder().encode(newValue) {
- self.defaults.set(data, forKey: Keys.hotkeyShortcutKey)
- }
+ let shortcuts = Self.normalizedPrimaryDictationShortcuts(newValue, fallback: self.legacyHotkeyShortcut)
+ self.storePrimaryDictationShortcuts(shortcuts)
+ self.storeLegacyHotkeyShortcut(shortcuts[0])
+ }
+ }
+
+ private static var defaultPrimaryDictationShortcut: HotkeyShortcut {
+ HotkeyShortcut(keyCode: 61, modifierFlags: [])
+ }
+
+ private var legacyHotkeyShortcut: HotkeyShortcut {
+ if let data = defaults.data(forKey: Keys.hotkeyShortcutKey),
+ let shortcut = try? JSONDecoder().decode(HotkeyShortcut.self, from: data)
+ {
+ return shortcut
+ }
+ return Self.defaultPrimaryDictationShortcut
+ }
+
+ private static func normalizedPrimaryDictationShortcuts(
+ _ shortcuts: [HotkeyShortcut],
+ fallback: HotkeyShortcut
+ ) -> [HotkeyShortcut] {
+ var unique: [HotkeyShortcut] = []
+ for shortcut in shortcuts where !unique.contains(shortcut) {
+ unique.append(shortcut)
+ }
+ if unique.isEmpty {
+ unique.append(fallback)
}
+ return unique
}
- var pressAndHoldMode: Bool { get { self.defaults.object(forKey: Keys.hotkeyMode) != nil ? self.hotkeyMode == .hold : self.defaults.bool(forKey: Keys.pressAndHoldMode) } set { self.hotkeyMode = newValue ? .hold : .toggle } }
+ private func storePrimaryDictationShortcuts(_ shortcuts: [HotkeyShortcut]) {
+ if let data = try? JSONEncoder().encode(shortcuts) {
+ self.defaults.set(data, forKey: Keys.primaryDictationShortcutsKey)
+ }
+ }
+
+ private func storeLegacyHotkeyShortcut(_ shortcut: HotkeyShortcut) {
+ if let data = try? JSONEncoder().encode(shortcut) {
+ self.defaults.set(data, forKey: Keys.hotkeyShortcutKey)
+ }
+ }
+
+ var pressAndHoldMode: Bool {
+ get { self.defaults.object(forKey: Keys.hotkeyMode) != nil ? self.hotkeyMode == .hold : self.defaults.bool(forKey: Keys.pressAndHoldMode) } set { self.hotkeyMode = newValue ? .hold : .toggle }
+ }
var hotkeyMode: HotkeyActivationMode {
get { self.defaults.string(forKey: Keys.hotkeyMode).flatMap(HotkeyActivationMode.init(rawValue:)) ?? (self.defaults.bool(forKey: Keys.pressAndHoldMode) ? .hold : .toggle) }
@@ -2193,6 +2257,7 @@ final class SettingsStore: ObservableObject {
private func hasLegacyUsageSignals() -> Bool {
if self.defaults.object(forKey: Keys.playgroundUsed) != nil { return true }
if self.defaults.object(forKey: Keys.hotkeyShortcutKey) != nil { return true }
+ if self.defaults.object(forKey: Keys.primaryDictationShortcutsKey) != nil { return true }
if let rawSpeechModel = self.defaults.string(forKey: Keys.selectedSpeechModel),
rawSpeechModel != SpeechModel.defaultModel.rawValue
{
@@ -2639,6 +2704,7 @@ final class SettingsStore: ObservableObject {
selectedNemotronLanguage: self.selectedNemotronLanguage,
selectedAppleSpeechLocaleIdentifier: self.selectedAppleSpeechLocaleIdentifier,
hotkeyShortcut: self.hotkeyShortcut,
+ primaryDictationShortcuts: self.primaryDictationShortcuts,
promptModeHotkeyShortcut: self.promptModeHotkeyShortcut,
promptModeShortcutEnabled: self.promptModeShortcutEnabled,
promptModeSelectedPromptID: self.promptModeSelectedPromptID,
@@ -2731,7 +2797,7 @@ final class SettingsStore: ObservableObject {
if let selectedAppleSpeechLocaleIdentifier = payload.selectedAppleSpeechLocaleIdentifier {
self.selectedAppleSpeechLocaleIdentifier = selectedAppleSpeechLocaleIdentifier
}
- self.hotkeyShortcut = payload.hotkeyShortcut
+ self.primaryDictationShortcuts = payload.primaryDictationShortcuts ?? [payload.hotkeyShortcut]
self.promptModeHotkeyShortcut = payload.promptModeHotkeyShortcut
self.promptModeShortcutEnabled = payload.promptModeShortcutEnabled
self.commandModeHotkeyShortcut = payload.commandModeHotkeyShortcut
@@ -3065,9 +3131,11 @@ final class SettingsStore: ObservableObject {
let originalCount = configurations.count
configurations = configurations.filter { key, configuration in
validKeys.contains(key) &&
- (configuration.shortcut != nil ||
- !configuration.providerID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
- !configuration.modelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ (
+ configuration.shortcut != nil ||
+ !configuration.providerID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
+ !configuration.modelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ )
}
if configurations.count != originalCount {
self.dictationPromptConfigurations = configurations
@@ -3923,10 +3991,11 @@ final class SettingsStore: ObservableObject {
}
/// Whether this model supports real-time streaming/chunk processing.
- /// Large Whisper models are too slow for streaming, so they only do final transcription on stop.
+ /// Whisper preview re-transcribes the growing prefix and shares the final
+ /// transcription executor, so even tiny models can make stop feel stuck.
var supportsStreaming: Bool {
switch self {
- case .qwen3Asr, .whisperMedium, .whisperLargeTurbo, .whisperLarge:
+ case .qwen3Asr, .whisperTiny, .whisperBase, .whisperSmall, .whisperMedium, .whisperLargeTurbo, .whisperLarge:
return false // Too slow for real-time chunk processing
default:
return true // All other models support streaming
@@ -4194,6 +4263,7 @@ private extension SettingsStore {
static let shareAnonymousAnalytics = "ShareAnonymousAnalytics"
static let privateAIInterestCaptured = "PrivateAIProviderInterestCaptured"
static let hotkeyShortcutKey = "HotkeyShortcutKey"
+ static let primaryDictationShortcutsKey = "PrimaryDictationShortcuts"
static let preferredInputDeviceUID = "PreferredInputDeviceUID"
static let preferredOutputDeviceUID = "PreferredOutputDeviceUID"
static let syncAudioDevicesWithSystem = "SyncAudioDevicesWithSystem"
@@ -4471,7 +4541,9 @@ extension SettingsStore {
case vietnamese = "vi"
case mandarinChinese = "zh"
- var id: String { self.rawValue }
+ var id: String {
+ self.rawValue
+ }
var displayName: String {
switch self {
@@ -4492,7 +4564,9 @@ extension SettingsStore {
}
}
- var tokenString: String { "<|\(self.rawValue)|>" }
+ var tokenString: String {
+ "<|\(self.rawValue)|>"
+ }
}
// MARK: - Unified Speech Model Selection
diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swift
index 0dd97d45..0af78248 100644
--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift
+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift
@@ -9,6 +9,11 @@ private nonisolated enum HotkeyHoldModeType: Hashable {
case promptAssignment
}
+private nonisolated enum ActivePrimaryShortcutPress: Equatable {
+ case keyboard(UInt16)
+ case mouse(Int)
+}
+
private final nonisolated class HotkeyState: @unchecked Sendable {
private let lock = NSLock()
var isKeyPressed = false
@@ -28,7 +33,7 @@ private final nonisolated class HotkeyState: @unchecked Sendable {
var automaticPressStartTimes: [HotkeyHoldModeType: Date] = [:]
var automaticPressWasTargetActive: [HotkeyHoldModeType: Bool] = [:]
var automaticPressStartedTypes: Set<HotkeyHoldModeType> = []
- var activePrimaryMouseButton: Int?
+ var activePrimaryShortcutPress: ActivePrimaryShortcutPress?
func withLock<T>(_ block: () -> T) -> T {
self.lock.lock()
@@ -43,7 +48,7 @@ final class GlobalHotkeyManager: NSObject {
private nonisolated(unsafe) var eventTap: CFMachPort?
private nonisolated(unsafe) var runLoopSource: CFRunLoopSource?
private let asrService: ASRService
- private var shortcut: HotkeyShortcut
+ private var primaryShortcuts: [HotkeyShortcut]
private var promptModeShortcut: HotkeyShortcut
private var commandModeShortcut: HotkeyShortcut
private var rewriteModeShortcut: HotkeyShortcut
@@ -113,9 +118,9 @@ final class GlobalHotkeyManager: NSObject {
set { self.state.withLock { self.state.isPromptAssignmentKeyPressed = newValue } }
}
- private nonisolated var activePrimaryMouseButton: Int? {
- get { self.state.withLock { self.state.activePrimaryMouseButton } }
- set { self.state.withLock { self.state.activePrimaryMouseButton = newValue } }
+ private nonisolated var activePrimaryShortcutPress: ActivePrimaryShortcutPress? {
+ get { self.state.withLock { self.state.activePrimaryShortcutPress } }
+ set { self.state.withLock { self.state.activePrimaryShortcutPress = newValue } }
}
private nonisolated var pressedModifierKeyCodes: Set<UInt16> {
@@ -272,7 +277,7 @@ final class GlobalHotkeyManager: NSObject {
init(
asrService: ASRService,
- shortcut: HotkeyShortcut,
+ primaryShortcuts: [HotkeyShortcut],
promptModeShortcut: HotkeyShortcut,
commandModeShortcut: HotkeyShortcut,
rewriteModeShortcut: HotkeyShortcut,
@@ -294,7 +299,7 @@ final class GlobalHotkeyManager: NSObject {
isShortcutCaptureActiveProvider: (() -> Bool)? = nil
) {
self.asrService = asrService
- self.shortcut = shortcut
+ self.primaryShortcuts = primaryShortcuts
self.promptModeShortcut = promptModeShortcut
self.commandModeShortcut = commandModeShortcut
self.rewriteModeShortcut = rewriteModeShortcut
@@ -339,9 +344,9 @@ final class GlobalHotkeyManager: NSObject {
self.commandModeCallback = callback
}
- func updateShortcut(_ newShortcut: HotkeyShortcut) {
- self.shortcut = newShortcut
- DebugLogger.shared.info("Updated transcription hotkey", source: "GlobalHotkeyManager")
+ func updatePrimaryShortcuts(_ newShortcuts: [HotkeyShortcut]) {
+ self.primaryShortcuts = newShortcuts
+ DebugLogger.shared.info("Updated transcription hotkeys", source: "GlobalHotkeyManager")
}
func updateCommandModeShortcut(_ newShortcut: HotkeyShortcut) {
@@ -503,6 +508,22 @@ final class GlobalHotkeyManager: NSObject {
self.eventTap = nil
self.runLoopSource = nil
+ self.clearPrimaryShortcutPressState()
+ }
+
+ private nonisolated func clearPrimaryShortcutPressState() {
+ let task = self.state.withLock { () -> Task<Void, Never>? in
+ guard self.state.activePrimaryShortcutPress != nil || self.state.isKeyPressed else { return nil }
+ self.state.activePrimaryShortcutPress = nil
+ self.state.isKeyPressed = false
+ self.state.holdModeStartTriggeredTypes.remove(.transcription)
+ self.state.automaticPressStartTimes.removeValue(forKey: .transcription)
+ self.state.automaticPressWasTargetActive.removeValue(forKey: .transcription)
+ self.state.automaticPressStartedTypes.remove(.transcription)
+ _ = self.state.pendingReleaseStopTokens.removeValue(forKey: .transcription)
+ return self.state.pendingReleaseStopTasks.removeValue(forKey: .transcription)
+ }
+ task?.cancel()
}
private func markOtherInputDuringModifierOnly() {
@@ -520,6 +541,62 @@ final class GlobalHotkeyManager: NSObject {
Int(event.getIntegerValueField(.mouseEventButtonNumber))
}
+ private func beginPrimaryShortcutPress(_ press: ActivePrimaryShortcutPress) -> Bool {
+ self.state.withLock {
+ guard self.state.activePrimaryShortcutPress == nil, !self.state.isKeyPressed else {
+ return false
+ }
+ self.state.activePrimaryShortcutPress = press
+ return true
+ }
+ }
+
+ private func finishPrimaryShortcutPress(_ press: ActivePrimaryShortcutPress) -> Bool {
+ self.state.withLock {
+ guard self.state.activePrimaryShortcutPress == press else {
+ return false
+ }
+ self.state.activePrimaryShortcutPress = nil
+ return true
+ }
+ }
+
+ private func primaryModifierOnlyBehavior(for shortcut: HotkeyShortcut) -> ModifierOnlyShortcutBehavior {
+ .init(
+ shortcut: shortcut,
+ isEnabled: true,
+ holdModeType: .transcription,
+ holdStartCancelledMessage: "Transcription hold start cancelled - key combo detected",
+ holdStartMessage: "Transcription modifier held (hold mode) - starting after delay",
+ holdReleaseMessage: "Transcription modifier released (hold mode) - stopping",
+ toggleIgnoredMessage: "Transcription modifier released but another key was pressed - ignoring",
+ isModeKeyPressed: { self.isKeyPressed },
+ setModeKeyPressed: { self.isKeyPressed = $0 },
+ onHoldStart: { self.startRecordingIfNeeded() },
+ onToggleRelease: {
+ if self.asrService.isRunning {
+ let isSameMode = self.isDictateRecordingProvider?() ?? false
+ DebugLogger.shared.info(
+ "Hotkey route | pressed=dictate(mod) | active=\(isSameMode ? "dictate" : "other") | asrRunning=true | action=\(isSameMode ? "stop" : "switch")",
+ source: "GlobalHotkeyManager"
+ )
+ if isSameMode {
+ self.stopRecordingIfNeeded()
+ } else {
+ self.triggerDictationMode()
+ }
+ } else {
+ DebugLogger.shared.info(
+ "Hotkey route | pressed=dictate(mod) | active=none | asrRunning=false | action=start",
+ source: "GlobalHotkeyManager"
+ )
+ self.triggerDictationMode()
+ }
+ },
+ isTargetModeActive: { self.isDictateRecordingProvider?() ?? false }
+ )
+ }
+
private func handleKeyEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {
if let tapRecoveryResult = self.handleTapDisableEvent(type: type, event: event) {
return tapRecoveryResult
@@ -724,8 +801,9 @@ final class GlobalHotkeyManager: NSObject {
}
}
- // Then check transcription hotkey
- if self.shortcut.matches(keyCode: keyCode, modifiers: eventModifiers) {
+ // Then check transcription hotkeys
+ if let shortcut = self.primaryShortcuts.first(where: { $0.matches(keyCode: keyCode, modifiers: eventModifiers) }) {
+ guard self.beginPrimaryShortcutPress(.keyboard(shortcut.keyCode)) else { return nil }
self.handlePrimaryDictationTriggerDown()
return nil
}
@@ -793,7 +871,7 @@ final class GlobalHotkeyManager: NSObject {
// Transcription key up
// Note: Only check keyCode, not modifiers - user may release modifier before/with main key
- if self.isKeyPressed, !self.shortcut.isMouseShortcut, keyCode == self.shortcut.keyCode {
+ if self.finishPrimaryShortcutPress(.keyboard(keyCode)) {
self.handlePrimaryDictationTriggerUp()
return nil
}
@@ -801,16 +879,15 @@ final class GlobalHotkeyManager: NSObject {
case .leftMouseDown, .rightMouseDown, .otherMouseDown:
self.markOtherInputDuringModifierOnly()
let mouseButton = self.mouseButton(from: event)
- if self.shortcut.matchesMouse(button: mouseButton, modifiers: eventModifiers) {
- self.activePrimaryMouseButton = mouseButton
+ if self.primaryShortcuts.contains(where: { $0.matchesMouse(button: mouseButton, modifiers: eventModifiers) }) {
+ guard self.beginPrimaryShortcutPress(.mouse(mouseButton)) else { return nil }
self.handlePrimaryDictationTriggerDown()
return nil
}
case .leftMouseUp, .rightMouseUp, .otherMouseUp:
let mouseButton = self.mouseButton(from: event)
- guard self.activePrimaryMouseButton == mouseButton else { break }
- self.activePrimaryMouseButton = nil
+ guard self.finishPrimaryShortcutPress(.mouse(mouseButton)) else { break }
self.handlePrimaryDictationTriggerUp()
return nil
@@ -890,43 +967,13 @@ final class GlobalHotkeyManager: NSObject {
modifiers: eventModifiers
) { return nil }
- if self.handleModifierOnlyShortcutFlagsChanged(
- behavior: .init(
- shortcut: self.shortcut,
- isEnabled: true,
- holdModeType: .transcription,
- holdStartCancelledMessage: "Transcription hold start cancelled - key combo detected",
- holdStartMessage: "Transcription modifier held (hold mode) - starting after delay",
- holdReleaseMessage: "Transcription modifier released (hold mode) - stopping",
- toggleIgnoredMessage: "Transcription modifier released but another key was pressed - ignoring",
- isModeKeyPressed: { self.isKeyPressed },
- setModeKeyPressed: { self.isKeyPressed = $0 },
- onHoldStart: { self.startRecordingIfNeeded() },
- onToggleRelease: {
- if self.asrService.isRunning {
- let isSameMode = self.isDictateRecordingProvider?() ?? false
- DebugLogger.shared.info(
- "Hotkey route | pressed=dictate(mod) | active=\(isSameMode ? "dictate" : "other") | asrRunning=true | action=\(isSameMode ? "stop" : "switch")",
- source: "GlobalHotkeyManager"
- )
- if isSameMode {
- self.stopRecordingIfNeeded()
- } else {
- self.triggerDictationMode()
- }
- } else {
- DebugLogger.shared.info(
- "Hotkey route | pressed=dictate(mod) | active=none | asrRunning=false | action=start",
- source: "GlobalHotkeyManager"
- )
- self.triggerDictationMode()
- }
- },
- isTargetModeActive: { self.isDictateRecordingProvider?() ?? false }
- ),
- keyCode: keyCode,
- modifiers: eventModifiers
- ) { return nil }
+ for shortcut in self.primaryShortcuts where shortcut.isModifierOnlyShortcut {
+ if self.handleModifierOnlyShortcutFlagsChanged(
+ behavior: self.primaryModifierOnlyBehavior(for: shortcut),
+ keyCode: keyCode,
+ modifiers: eventModifiers
+ ) { return nil }
+ }
default:
break
@@ -1308,7 +1355,7 @@ final class GlobalHotkeyManager: NSObject {
self.isCommandModeKeyPressed = false
self.isRewriteKeyPressed = false
self.isPromptAssignmentKeyPressed = false
- self.activePrimaryMouseButton = nil
+ self.activePrimaryShortcutPress = nil
if shouldStopActiveHold {
switch reason {
@@ -1555,6 +1602,7 @@ final class GlobalHotkeyManager: NSObject {
private func triggerPromptMode() {
Task { @MainActor [weak self] in
guard let self = self else { return }
+ guard self.canTriggerRecordingAction("Prompt mode hotkey") else { return }
DebugLogger.shared.info("Prompt mode hotkey triggered", source: "GlobalHotkeyManager")
await self.promptModeCallback?()
}
@@ -1563,6 +1611,7 @@ final class GlobalHotkeyManager: NSObject {
private func triggerPromptSelection(_ selection: SettingsStore.DictationPromptSelection) {
Task { @MainActor [weak self] in
guard let self = self else { return }
+ guard self.canTriggerRecordingAction("Prompt selection hotkey") else { return }
DebugLogger.shared.info("Prompt selection hotkey triggered", source: "GlobalHotkeyManager")
await self.promptSelectionCallback?(selection)
}
@@ -1571,6 +1620,7 @@ final class GlobalHotkeyManager: NSObject {
private func triggerCommandMode() {
Task { @MainActor [weak self] in
guard let self = self else { return }
+ guard self.canTriggerRecordingAction("Command mode hotkey") else { return }
DebugLogger.shared.info("Command mode hotkey triggered", source: "GlobalHotkeyManager")
DebugLogger.shared.debug(
"GlobalHotkeyManager: command callback path, isRunning=\(self.asrService.isRunning), isReady=\(self.asrService.isAsrReady)",
@@ -1583,6 +1633,7 @@ final class GlobalHotkeyManager: NSObject {
private func triggerRewriteMode() {
Task { @MainActor [weak self] in
guard let self = self else { return }
+ guard self.canTriggerRecordingAction("Rewrite mode hotkey") else { return }
DebugLogger.shared.info("Rewrite mode hotkey triggered", source: "GlobalHotkeyManager")
DebugLogger.shared.debug(
"GlobalHotkeyManager: rewrite callback path, isRunning=\(self.asrService.isRunning), isReady=\(self.asrService.isAsrReady)",
@@ -1595,6 +1646,7 @@ final class GlobalHotkeyManager: NSObject {
private func triggerDictationMode() {
Task { @MainActor [weak self] in
guard let self = self else { return }
+ guard self.canTriggerRecordingAction("Dictate mode hotkey") else { return }
let model = SettingsStore.shared.selectedSpeechModel
DebugLogger.shared.info("Dictate mode hotkey triggered", source: "GlobalHotkeyManager")
DebugLogger.shared.debug(
@@ -1635,7 +1687,7 @@ final class GlobalHotkeyManager: NSObject {
self.isCommandModeKeyPressed = false
self.isRewriteKeyPressed = false
self.isPromptAssignmentKeyPressed = false
- self.activePrimaryMouseButton = nil
+ self.activePrimaryShortcutPress = nil
if shouldStopActivePress {
self.stopRecordingIfNeeded()
@@ -1647,21 +1699,22 @@ final class GlobalHotkeyManager: NSObject {
self.setHotkeyMode(enable ? .hold : .toggle)
}
- private func toggleRecording() {
- // Capture state at event time to prevent race conditions
- let shouldStop = self.asrService.isRunning
- let alreadyProcessing = self.isProcessingStop
+ private func canTriggerRecordingAction(_ label: String) -> Bool {
+ guard !self.isProcessingStop else {
+ DebugLogger.shared.debug("Ignoring \(label) - stop already processing", source: "GlobalHotkeyManager")
+ return false
+ }
+ return true
+ }
+ private func toggleRecording() {
Task { @MainActor [weak self] in
guard let self = self else { return }
// Prevent new operations while stop is processing
- if alreadyProcessing {
- DebugLogger.shared.debug("Ignoring toggle - stop already in progress", source: "GlobalHotkeyManager")
- return
- }
+ guard self.canTriggerRecordingAction("toggle") else { return }
- if shouldStop {
+ if self.asrService.isRunning {
await self.stopRecordingInternal()
} else {
// Use callback if available, otherwise fallback to direct start
@@ -1675,20 +1728,13 @@ final class GlobalHotkeyManager: NSObject {
}
private func startRecordingIfNeeded() {
- // Capture state at event time
- let alreadyRunning = self.asrService.isRunning
- let alreadyProcessing = self.isProcessingStop
-
Task { @MainActor [weak self] in
guard let self = self else { return }
// Prevent starting while stop is processing
- if alreadyProcessing {
- DebugLogger.shared.debug("Ignoring start - stop in progress", source: "GlobalHotkeyManager")
- return
- }
+ guard self.canTriggerRecordingAction("start") else { return }
- if !alreadyRunning {
+ if !self.asrService.isRunning {
// Use callback if available, otherwise fallback to direct start
if let callback = self.startRecordingCallback {
await callback()
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index 795a6d8c..5b768c95 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -24,12 +24,12 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
private weak var asrService: ASRService?
private var cancellables = Set<AnyCancellable>()
- // Overlay management (persistent, independent of window lifecycle)
+ /// Overlay management (persistent, independent of window lifecycle)
private var overlayVisible: Bool = false
- // Track when AI processing is active.
- // When recording stops, ASRService flips `isRunning` to false, which would normally hide the
- // overlay. During post-processing we want the overlay to stay visible until processing ends.
+ /// Track when AI processing is active.
+ /// When recording stops, ASRService flips `isRunning` to false, which would normally hide the
+ /// overlay. During post-processing we want the overlay to stay visible until processing ends.
private var isProcessingActive: Bool = false
@Published var isRecording: Bool = false
@@ -38,21 +38,21 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
/// `ContentView` consumes this and clears it.
@Published var requestedNavigationDestination: MenuBarNavigationDestination? = nil
- // Track current overlay mode for notch
+ /// Track current overlay mode for notch
private var currentOverlayMode: OverlayMode = .dictation
// Track pending overlay operations to prevent spam
private var pendingShowOperation: DispatchWorkItem?
private var pendingHideOperation: DispatchWorkItem?
private var pendingProcessingShowOperation: DispatchWorkItem?
- // Show immediately so users see the processing state right away.
+ /// Show immediately so users see the processing state right away.
private let processingVisualDelay: DispatchTimeInterval = .milliseconds(0)
- // Debounce the hide so a fast transcription doesn't flash the processing
- // overlay for a single frame. 80ms is under the perception threshold but
- // long enough to coalesce a quick show->hide cycle.
+ /// Debounce the hide so a fast transcription doesn't flash the processing
+ /// overlay for a single frame. 80ms is under the perception threshold but
+ /// long enough to coalesce a quick show->hide cycle.
private let processingHideDelay: DispatchTimeInterval = .milliseconds(80)
- // Subscription for forwarding audio levels to expanded command notch
+ /// Subscription for forwarding audio levels to expanded command notch
private var expandedModeAudioSubscription: AnyCancellable?
override init() {
@@ -484,8 +484,8 @@ final class MenuBarManager: NSObject, ObservableObject, NSMenuDelegate {
private func updateMenuItemsText() {
// Update status text with hotkey info
- let hotkeyShortcut = SettingsStore.shared.hotkeyShortcut
- let hotkeyInfo = hotkeyShortcut.displayString.isEmpty ? "" : " (\(hotkeyShortcut.displayString))"
+ let hotkeyDisplay = SettingsStore.shared.primaryDictationShortcutDisplayString
+ let hotkeyInfo = hotkeyDisplay.isEmpty ? "" : " (\(hotkeyDisplay))"
let statusTitle = self.isRecording ? "Recording...\(hotkeyInfo)" : "Ready to Record\(hotkeyInfo)"
self.statusMenuItem?.title = statusTitle
self.microphoneMenuItem?.isEnabled = true
diff --git a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
index 9d7aa3cb..15f4580a 100644
--- a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
+++ b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
@@ -962,9 +962,10 @@ extension AIEnhancementSettingsView {
} else {
self.promptRoutingScopeRow(mode: mode)
- Text(isSelectedAppsOnly
- ? "Custom prompts only run in apps listed in App Overrides."
- : "Custom prompts run based on your shortcut or the app you're in."
+ Text(
+ isSelectedAppsOnly
+ ? "Custom prompts only run in apps listed in App Overrides."
+ : "Custom prompts run based on your shortcut or the app you're in."
)
.font(.caption2)
.foregroundStyle(self.theme.palette.secondaryText)
@@ -1141,9 +1142,10 @@ extension AIEnhancementSettingsView {
.foregroundStyle(self.theme.palette.accent)
.frame(width: 18, height: 18)
- Text(mode.normalized == .dictate
- ? "No default enhancement. Add app overrides to use prompts in selected apps."
- : "Default edit stays built-in. App overrides can use custom prompts."
+ Text(
+ mode.normalized == .dictate
+ ? "No default enhancement. Add app overrides to use prompts in selected apps."
+ : "Default edit stays built-in. App overrides can use custom prompts."
)
.font(.caption2)
.foregroundStyle(self.theme.palette.secondaryText)
@@ -1730,7 +1732,7 @@ extension AIEnhancementSettingsView {
Spacer()
}
- let hotkeyDisplay = self.settings.hotkeyShortcut.displayString
+ let hotkeyDisplay = self.settings.primaryDictationShortcutDisplayString
let canTest = self.viewModel.isAIPostProcessingConfiguredForDictation()
Toggle(isOn: Binding(
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index 23a7f47c..f9ff0c68 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -33,7 +33,7 @@ struct SettingsView: View {
@Binding var inputDevices: [AudioDevice.Device]
@Binding var outputDevices: [AudioDevice.Device]
@Binding var accessibilityEnabled: Bool
- @Binding var hotkeyShortcut: HotkeyShortcut
+ @Binding var primaryDictationShortcuts: [HotkeyShortcut]
@Binding var activeShortcutRecordingTarget: ShortcutRecordingTarget?
@Binding var shortcutRecordingMessage: String?
@Binding var commandModeShortcut: HotkeyShortcut
@@ -122,6 +122,10 @@ struct SettingsView: View {
Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "Unknown"
}
+ private var appDisplayName: String {
+ Bundle.main.fluidAppDisplayName
+ }
+
private var launchAtStartupBinding: Binding<Bool> {
Binding(
get: { self.settings.launchAtStartupEnabled },
@@ -589,7 +593,11 @@ struct SettingsView: View {
title: "How to enable microphone access:",
steps: self.asr.micStatus == .notDetermined
? ["Click **Grant Access** above", "Choose **Allow** in the system dialog"]
- : ["Click **Open Settings** above", "Find **FluidVoice** in the microphone list", "Toggle **FluidVoice ON** to allow access"]
+ : [
+ "Click **Open Settings** above",
+ "Find **\(self.appDisplayName)** in the microphone list",
+ "Toggle **\(self.appDisplayName) ON** to allow access",
+ ]
)
}
}
@@ -661,23 +669,7 @@ struct SettingsView: View {
.font(.caption)
.foregroundStyle(.tertiary)
- self.shortcutRow(
- content: .init(
- icon: "mic.fill",
- iconColor: .secondary,
- title: "Primary Dictation Shortcut",
- description: "Use a keyboard shortcut, auxiliary mouse button, or modified click."
- ),
- shortcut: self.hotkeyShortcut,
- isRecording: self.isRecording(.primaryDictation),
- isAnyRecordingActive: self.isRecordingAnyShortcut,
- recordingMessage: self.isRecording(.primaryDictation) ? self.shortcutRecordingMessage : nil,
- onChangePressed: {
- DebugLogger.shared.debug("Starting to record new transcribe shortcut", source: "SettingsView")
- self.shortcutRecordingMessage = nil
- self.activeShortcutRecordingTarget = .primaryDictation
- }
- )
+ self.primaryDictationShortcutsList()
self.dictationPromptPicker(for: .primary)
Divider().opacity(0.2).padding(.vertical, 4)
@@ -970,8 +962,8 @@ struct SettingsView: View {
steps: [
"Click **Open Accessibility Settings** above",
"In the Accessibility window, click the **+ button**",
- "Navigate to Applications and select **FluidVoice**",
- "Click **Open**, then toggle **FluidVoice ON** in the list",
+ "Select **\(self.appDisplayName)**; use **Reveal in Finder** below if needed",
+ "Click **Open**, then toggle **\(self.appDisplayName) ON** in the list",
],
warningStyle: true
)
@@ -2027,6 +2019,150 @@ struct SettingsView: View {
)
}
+ @ViewBuilder
+ private func primaryDictationShortcutsList() -> some View {
+ let addTarget = ShortcutRecordingTarget.primaryDictation(.add)
+ let isAdding = self.isRecording(addTarget)
+
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 10) {
+ Image(systemName: "mic.fill")
+ .foregroundStyle(.secondary)
+ .frame(width: 20)
+
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Primary Dictation Shortcuts")
+ .font(.body)
+ Text("Use any keyboard shortcut, auxiliary mouse button, or modified click.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+
+ Spacer()
+
+ Button {
+ if isAdding {
+ self.shortcutRecordingMessage = nil
+ self.activeShortcutRecordingTarget = nil
+ } else {
+ DebugLogger.shared.debug("Starting to record new primary dictation shortcut", source: "SettingsView")
+ self.shortcutRecordingMessage = nil
+ self.activeShortcutRecordingTarget = addTarget
+ }
+ } label: {
+ Label(isAdding ? "Cancel" : "Add shortcut", systemImage: isAdding ? "xmark" : "plus")
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ .disabled(!isAdding && self.isRecordingAnyShortcut)
+ }
+
+ ForEach(Array(self.primaryDictationShortcuts.enumerated()), id: \.offset) { index, shortcut in
+ self.primaryDictationShortcutRow(shortcut: shortcut, index: index)
+ }
+
+ if isAdding {
+ self.primaryDictationShortcutCaptureStatus(for: addTarget)
+ }
+ }
+ }
+
+ @ViewBuilder
+ private func primaryDictationShortcutRow(shortcut: HotkeyShortcut, index: Int) -> some View {
+ let target = ShortcutRecordingTarget.primaryDictation(.replace(index))
+ let isRecording = self.isRecording(target)
+
+ HStack(spacing: 10) {
+ Color.clear
+ .frame(width: 20)
+
+ if isRecording {
+ self.shortcutCapturePill()
+ } else {
+ self.shortcutDisplayPill(shortcut.displayString)
+ }
+
+ Button(isRecording ? "Cancel" : "Change") {
+ if isRecording {
+ self.shortcutRecordingMessage = nil
+ self.activeShortcutRecordingTarget = nil
+ } else {
+ DebugLogger.shared.debug("Starting to record replacement primary dictation shortcut", source: "SettingsView")
+ self.shortcutRecordingMessage = nil
+ self.activeShortcutRecordingTarget = target
+ }
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ .disabled(!isRecording && self.isRecordingAnyShortcut)
+
+ Button("Remove") {
+ guard self.primaryDictationShortcuts.count > 1,
+ self.primaryDictationShortcuts.indices.contains(index)
+ else { return }
+ self.primaryDictationShortcuts.remove(at: index)
+ }
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+ .disabled(self.primaryDictationShortcuts.count <= 1 || self.isRecordingAnyShortcut)
+
+ if isRecording,
+ let recordingMessage = self.shortcutRecordingMessage,
+ !recordingMessage.isEmpty
+ {
+ Text(recordingMessage)
+ .font(.caption)
+ .foregroundStyle(self.theme.palette.warning)
+ }
+ }
+ }
+
+ private func primaryDictationShortcutCaptureStatus(for target: ShortcutRecordingTarget) -> some View {
+ HStack(spacing: 10) {
+ Color.clear
+ .frame(width: 20)
+
+ self.shortcutCapturePill()
+
+ if self.isRecording(target),
+ let recordingMessage = self.shortcutRecordingMessage,
+ !recordingMessage.isEmpty
+ {
+ Text(recordingMessage)
+ .font(.caption)
+ .foregroundStyle(self.theme.palette.warning)
+ }
+ }
+ }
+
+ private func shortcutCapturePill() -> some View {
+ Text("Press shortcut...")
+ .font(.caption.weight(.medium))
+ .foregroundStyle(.orange)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 4)
+ .background(
+ RoundedRectangle(cornerRadius: 5, style: .continuous)
+ .fill(.orange.opacity(0.2))
+ )
+ }
+
+ private func shortcutDisplayPill(_ text: String) -> some View {
+ Text(text)
+ .font(.caption.monospaced().weight(.medium))
+ .padding(.horizontal, 8)
+ .padding(.vertical, 4)
+ .background(
+ RoundedRectangle(cornerRadius: 5, style: .continuous)
+ .fill(.quaternary.opacity(0.5))
+ .overlay(
+ RoundedRectangle(cornerRadius: 5, style: .continuous)
+ .stroke(.primary.opacity(0.15), lineWidth: 1)
+ )
+ )
+ }
+
@ViewBuilder
private func shortcutRow(
content: ShortcutRowContent,
@@ -2070,28 +2206,9 @@ struct SettingsView: View {
.frame(width: 20)
if isRecording && enabledValue {
- Text("Press shortcut...")
- .font(.caption.weight(.medium))
- .foregroundStyle(.orange)
- .padding(.horizontal, 8)
- .padding(.vertical, 4)
- .background(
- RoundedRectangle(cornerRadius: 5, style: .continuous)
- .fill(.orange.opacity(0.2))
- )
+ self.shortcutCapturePill()
} else {
- Text(shortcut.displayString)
- .font(.caption.monospaced().weight(.medium))
- .padding(.horizontal, 8)
- .padding(.vertical, 4)
- .background(
- RoundedRectangle(cornerRadius: 5, style: .continuous)
- .fill(.quaternary.opacity(0.5))
- .overlay(
- RoundedRectangle(cornerRadius: 5, style: .continuous)
- .stroke(.primary.opacity(0.15), lineWidth: 1)
- )
- )
+ self.shortcutDisplayPill(shortcut.displayString)
}
Button(isRecording ? "Cancel" : "Change") {
diff --git a/Sources/Fluid/UI/WelcomeView.swift b/Sources/Fluid/UI/WelcomeView.swift
index 9edb2cb9..96c02372 100644
--- a/Sources/Fluid/UI/WelcomeView.swift
+++ b/Sources/Fluid/UI/WelcomeView.swift
@@ -11,7 +11,10 @@ import SwiftUI
struct WelcomeView: View {
@EnvironmentObject var appServices: AppServices
- private var asr: ASRService { self.appServices.asr }
+ private var asr: ASRService {
+ self.appServices.asr
+ }
+
@ObservedObject private var settings = SettingsStore.shared
@Binding var selectedSidebarItem: SidebarItem?
@Binding var playgroundUsed: Bool
@@ -35,13 +38,22 @@ struct WelcomeView: View {
private let playgroundSectionID = "welcome-playground-section"
- private var commandModeColor: Color { self.theme.palette.warning }
- private var editModeColor: Color { self.theme.palette.accent }
+ private var commandModeColor: Color {
+ self.theme.palette.warning
+ }
+
+ private var editModeColor: Color {
+ self.theme.palette.accent
+ }
private var isAIEnhancementReady: Bool {
DictationAIPostProcessingGate.isProviderConfigured()
}
+ private var appDisplayName: String {
+ Bundle.main.fluidAppDisplayName
+ }
+
var body: some View {
ScrollViewReader { proxy in
ScrollView {
@@ -87,9 +99,11 @@ struct WelcomeView: View {
title: (self.asr.isAsrReady || self.asr.modelsExistOnDisk) ? "Voice Model Ready" : "Download Voice Model",
description: self.asr.isAsrReady
? "Speech recognition model is loaded and ready"
- : (self.asr.modelsExistOnDisk
- ? "Model downloaded, will load when needed"
- : "Download the AI model for offline voice transcription (~500MB)"),
+ : (
+ self.asr.modelsExistOnDisk
+ ? "Model downloaded, will load when needed"
+ : "Download the AI model for offline voice transcription (~500MB)"
+ ),
status: (self.asr.isAsrReady || self.asr.modelsExistOnDisk) ? .completed : .pending,
action: {
self.selectedSidebarItem = .voiceEngine
@@ -121,7 +135,7 @@ struct WelcomeView: View {
title: self.accessibilityEnabled ? "Accessibility Access Enabled" : "Enable Accessibility Access",
description: self.accessibilityEnabled
? "Accessibility permission granted for typing into apps"
- : "Drag FluidVoice into the Accessibility apps list as shown",
+ : "Drag \(self.appDisplayName) into the Accessibility apps list as shown",
status: self.accessibilityEnabled ? .completed : .pending,
action: {
self.openAccessibilitySettings()
@@ -560,7 +574,10 @@ struct WelcomeView: View {
struct OnboardingFlowView: View {
@EnvironmentObject var appServices: AppServices
@Environment(\.accessibilityReduceMotion) private var reduceMotion
- private var asr: ASRService { self.appServices.asr }
+ private var asr: ASRService {
+ self.appServices.asr
+ }
+
@ObservedObject private var settings = SettingsStore.shared
@Binding var currentStep: Int
@@ -798,7 +815,7 @@ struct OnboardingFlowView: View {
}
private var onboardingShortcutDisplay: String {
- let display = self.settings.hotkeyShortcut.displayString.trimmingCharacters(in: .whitespacesAndNewlines)
+ let display = self.settings.primaryDictationShortcutDisplayString.trimmingCharacters(in: .whitespacesAndNewlines)
return display.isEmpty ? "your shortcut" : display
}
@@ -806,6 +823,10 @@ struct OnboardingFlowView: View {
self.activeShortcutRecordingTarget != nil
}
+ private var isRecordingPrimaryShortcut: Bool {
+ self.activeShortcutRecordingTarget?.isPrimaryDictation == true
+ }
+
private var canContinue: Bool {
guard !self.isModelPreparationInProgress else {
return false
@@ -1666,8 +1687,8 @@ struct OnboardingFlowView: View {
shortcutDisplay: self.onboardingShortcutDisplay,
isTestReady: self.isPlaygroundReady,
isRunning: self.asr.isRunning,
- isRecordingShortcut: self.activeShortcutRecordingTarget == .primaryDictation,
- shortcutRecordingMessage: self.activeShortcutRecordingTarget == .primaryDictation ? self.shortcutRecordingMessage : nil,
+ isRecordingShortcut: self.isRecordingPrimaryShortcut,
+ shortcutRecordingMessage: self.isRecordingPrimaryShortcut ? self.shortcutRecordingMessage : nil,
onGlowMove: self.updateLandingGlow(location:in:),
onGlowExit: self.resetLandingGlow,
onBack: self.goBack,
@@ -1717,8 +1738,8 @@ struct OnboardingFlowView: View {
shortcutDisplay: self.onboardingShortcutDisplay,
isReady: self.isPlaygroundReady,
isRunning: self.asr.isRunning,
- isRecordingShortcut: self.activeShortcutRecordingTarget == .primaryDictation,
- shortcutRecordingMessage: self.activeShortcutRecordingTarget == .primaryDictation ? self.shortcutRecordingMessage : nil,
+ isRecordingShortcut: self.isRecordingPrimaryShortcut,
+ shortcutRecordingMessage: self.isRecordingPrimaryShortcut ? self.shortcutRecordingMessage : nil,
onToggleShortcut: self.togglePrimaryShortcutRecording
)
}
@@ -1777,12 +1798,16 @@ struct OnboardingFlowView: View {
private var accessibilityPermissionSubtitle: String {
if self.isAccessibilityReady {
- return "FluidVoice can place text into the app you're using."
+ return "\(self.appDisplayName) can place text into the app you're using."
}
if self.accessibilitySetupInProgress {
- return "Use the floating guide to drag FluidVoice into the Accessibility apps list."
+ return "Use the floating guide to drag \(self.appDisplayName) into the Accessibility apps list."
}
- return "Open Settings, then use the floating guide to add FluidVoice."
+ return "Open Settings, then use the floating guide to add \(self.appDisplayName)."
+ }
+
+ private var appDisplayName: String {
+ Bundle.main.fluidAppDisplayName
}
private var accessibilityPermissionStatusTitle: String {
@@ -2514,12 +2539,12 @@ struct OnboardingFlowView: View {
private func togglePrimaryShortcutRecording() {
guard !self.asr.isRunning else { return }
- if self.activeShortcutRecordingTarget == .primaryDictation {
+ if self.isRecordingPrimaryShortcut {
self.activeShortcutRecordingTarget = nil
self.shortcutRecordingMessage = nil
} else {
self.shortcutRecordingMessage = nil
- self.activeShortcutRecordingTarget = .primaryDictation
+ self.activeShortcutRecordingTarget = .primaryDictation(.replace(0))
}
}
diff --git a/Sources/Fluid/Views/BottomOverlayView.swift b/Sources/Fluid/Views/BottomOverlayView.swift
index 85594c90..c8aa2e3f 100644
--- a/Sources/Fluid/Views/BottomOverlayView.swift
+++ b/Sources/Fluid/Views/BottomOverlayView.swift
@@ -13,7 +13,7 @@ private enum OverlayShortcutResolver {
static func shortcutDisplay(for mode: OverlayMode, settings: SettingsStore = .shared) -> String {
switch mode {
case .dictation:
- return settings.hotkeyShortcut.displayString
+ return settings.primaryDictationShortcutDisplayString
case .edit, .write, .rewrite:
return settings.rewriteModeHotkeyShortcut.displayString
case .command:
@@ -1356,9 +1356,11 @@ private struct BottomOverlayPromptMenuView: View {
@ViewBuilder
private func defaultRow(selectedID: String?) -> some View {
let activeSlot = self.contentState.activeDictationShortcutSlot ?? .primary
- let isSelected = !self.privateAILocked && (self.promptMode.normalized == .dictate
- ? (self.settings.dictationPromptSelection(for: activeSlot) == .default)
- : (selectedID == nil))
+ let isSelected = !self.privateAILocked && (
+ self.promptMode.normalized == .dictate
+ ? (self.settings.dictationPromptSelection(for: activeSlot) == .default)
+ : (selectedID == nil)
+ )
Button(action: {
guard !self.privateAILocked else { return }
if self.promptMode.normalized == .dictate {
@@ -1424,9 +1426,11 @@ private struct BottomOverlayPromptMenuView: View {
@ViewBuilder
private func profileRow(_ profile: SettingsStore.DictationPromptProfile, selectedID: String?) -> some View {
let activeSlot = self.contentState.activeDictationShortcutSlot ?? .primary
- let isSelected = !self.privateAILocked && (self.promptMode.normalized == .dictate
- ? (self.settings.dictationPromptSelection(for: activeSlot) == .profile(profile.id))
- : (selectedID == profile.id))
+ let isSelected = !self.privateAILocked && (
+ self.promptMode.normalized == .dictate
+ ? (self.settings.dictationPromptSelection(for: activeSlot) == .profile(profile.id))
+ : (selectedID == profile.id)
+ )
Button(action: {
guard !self.privateAILocked else { return }
if self.promptMode.normalized == .dictate {
@@ -1751,8 +1755,8 @@ private enum PillShadowMetrics {
// Keep in sync with the pill shadow in BottomOverlayView.body.
static let radius: CGFloat = 10
static let yOffset: CGFloat = 4
- // Hit-test inset must cover the visible shadow extent (radius + |offset|)
- // plus a small margin so the shadow region doesn't intercept clicks.
+ /// Hit-test inset must cover the visible shadow extent (radius + |offset|)
+ /// plus a small margin so the shadow region doesn't intercept clicks.
static let hitTestInset: CGFloat = radius + abs(yOffset) + 12
}
diff --git a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
index 9d441a7f..fd7a9c81 100644
--- a/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
+++ b/Tests/FluidDictationIntegrationTests/DictationE2ETests.swift
@@ -1,8 +1,7 @@
+@testable import FluidVoice_Debug
import Foundation
import XCTest
-@testable import FluidVoice_Debug
-
@MainActor
final class DictationE2ETests: XCTestCase {
private let enableTranscriptionSoundsKey = "EnableTranscriptionSounds"
@@ -22,9 +21,18 @@ final class DictationE2ETests: XCTestCase {
private let commandModeLinkedToGlobalKey = "CommandModeLinkedToGlobal"
private let commandModeSelectedProviderIDKey = "CommandModeSelectedProviderID"
private let commandModeSelectedModelKey = "CommandModeSelectedModel"
- private var privateAISelectedModelIDKey: String { PrivateAIProviderFeature.shared.selectedModelDefaultsKey }
- private var privateAILocalModelPathKey: String { PrivateAIProviderFeature.shared.localModelPathDefaultsKey }
- private var privateAIPrefixKVCacheEnabledKey: String { PrivateAIProviderFeature.shared.prefixCacheDefaultsKey }
+ private var privateAISelectedModelIDKey: String {
+ PrivateAIProviderFeature.shared.selectedModelDefaultsKey
+ }
+
+ private var privateAILocalModelPathKey: String {
+ PrivateAIProviderFeature.shared.localModelPathDefaultsKey
+ }
+
+ private var privateAIPrefixKVCacheEnabledKey: String {
+ PrivateAIProviderFeature.shared.prefixCacheDefaultsKey
+ }
+
private let verifiedProviderFingerprintsKey = "VerifiedProviderFingerprints"
func testTranscriptionStartSound_noneOptionHasNoFile() {
@@ -60,6 +68,19 @@ final class DictationE2ETests: XCTestCase {
}
}
+ func testWhisperModelsUseFinalOnlyDictation() {
+ let whisperModels: [SettingsStore.SpeechModel] = [
+ .whisperTiny,
+ .whisperBase,
+ .whisperSmall,
+ .whisperMedium,
+ .whisperLargeTurbo,
+ .whisperLarge,
+ ]
+
+ XCTAssertTrue(whisperModels.allSatisfy { !$0.supportsStreaming })
+ }
+
func testDictationEndToEnd_whisperTiny_transcribesFixture() async throws {
// Arrange
SettingsStore.shared.shareAnonymousAnalytics = false
@@ -535,12 +556,10 @@ final class DictationE2ETests: XCTestCase {
if CharacterSet.punctuationCharacters.contains(scalar) { return " " }
return Character(scalar)
}
- let collapsed = String(noPunct)
+ return String(noPunct)
.components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
.joined(separator: " ")
-
- return collapsed
}
private func withRestoredDefaults(keys: [String], run: () -> Void) {
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index 2cac7053..25886def 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -4,6 +4,9 @@ import Foundation
import XCTest
final class HotkeyShortcutTests: XCTestCase {
+ private let legacyHotkeyShortcutKey = "HotkeyShortcutKey"
+ private let primaryDictationShortcutsKey = "PrimaryDictationShortcuts"
+
func testLegacyKeyboardShortcutPayloadDefaultsToKeyboardKind() throws {
let json = #"{"keyCode":61,"modifierFlagsRawValue":0}"#
let data = try XCTUnwrap(json.data(using: .utf8))
@@ -68,4 +71,54 @@ final class HotkeyShortcutTests: XCTestCase {
XCTAssertEqual(mouseShortcut.displayString, "Mouse 4")
XCTAssertNotEqual(mouseShortcut, keyboardShortcut)
}
+
+ func testPrimaryDictationShortcutsFallbackToLegacyShortcut() throws {
+ try self.withRestoredDefaults(keys: [self.legacyHotkeyShortcutKey, self.primaryDictationShortcutsKey]) {
+ let legacyShortcut = HotkeyShortcut(keyCode: 12, modifierFlags: [.option])
+ let data = try JSONEncoder().encode(legacyShortcut)
+ UserDefaults.standard.set(data, forKey: self.legacyHotkeyShortcutKey)
+ UserDefaults.standard.removeObject(forKey: self.primaryDictationShortcutsKey)
+
+ XCTAssertEqual(SettingsStore.shared.primaryDictationShortcuts, [legacyShortcut])
+ XCTAssertEqual(SettingsStore.shared.hotkeyShortcut, legacyShortcut)
+ }
+ }
+
+ func testPrimaryDictationShortcutsPersistMultipleAndUpdateLegacyFirst() throws {
+ try self.withRestoredDefaults(keys: [self.legacyHotkeyShortcutKey, self.primaryDictationShortcutsKey]) {
+ let mouseShortcut = HotkeyShortcut(mouseButton: 3, modifierFlags: NSEvent.ModifierFlags())
+ let keyboardShortcut = HotkeyShortcut(keyCode: 12, modifierFlags: [.option])
+
+ SettingsStore.shared.primaryDictationShortcuts = [mouseShortcut, keyboardShortcut, mouseShortcut]
+
+ XCTAssertEqual(SettingsStore.shared.primaryDictationShortcuts, [mouseShortcut, keyboardShortcut])
+ XCTAssertEqual(SettingsStore.shared.hotkeyShortcut, mouseShortcut)
+ XCTAssertEqual(
+ SettingsStore.shared.primaryDictationShortcutDisplayString,
+ "\(mouseShortcut.displayString) / \(keyboardShortcut.displayString)"
+ )
+ }
+ }
+
+ private func withRestoredDefaults(keys: [String], run: () throws -> Void) rethrows {
+ let defaults = UserDefaults.standard
+ var snapshot: [String: Any] = [:]
+ for key in keys {
+ if let value = defaults.object(forKey: key) {
+ snapshot[key] = value
+ }
+ }
+
+ defer {
+ for key in keys {
+ if let previous = snapshot[key] {
+ defaults.set(previous, forKey: key)
+ } else {
+ defaults.removeObject(forKey: key)
+ }
+ }
+ }
+
+ try run()
+ }
}