Voxley / app · voxley.si / Sources / Voxley / DictationController.swift
| 1 | import AppKit |
| 2 | import ApplicationServices |
| 3 | import AVFoundation |
| 4 | import Observation |
| 5 | import OSLog |
| 6 | import Speech |
| 7 | import UniformTypeIdentifiers |
| 8 | |
| 9 | enum Phase: Equatable { |
| 10 | case idle, preparing, recording, transcribing, refining |
| 11 | |
| 12 | var isCapturing: Bool { self == .preparing || self == .recording } |
| 13 | |
| 14 | var title: String { |
| 15 | switch self { |
| 16 | case .idle: "Ready to dictate" |
| 17 | case .preparing: "Getting the microphone ready…" |
| 18 | case .recording: "Listening…" |
| 19 | case .transcribing: "Transcribing…" |
| 20 | case .refining: "Polishing with Apple Intelligence…" |
| 21 | } |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | /// Which shortcut started a dictation. Paste is the original flow. Refine opens the Refine window instead. |
| 26 | enum CaptureKind: Equatable { |
| 27 | case paste, refine |
| 28 | } |
| 29 | |
| 30 | enum ShortcutKind { |
| 31 | case dictation, refine |
| 32 | } |
| 33 | |
| 34 | @MainActor |
| 35 | @Observable |
| 36 | final class DictationController { |
| 37 | private(set) var phase = Phase.idle |
| 38 | private(set) var liveText = "" |
| 39 | private(set) var waveform = WaveformFrame.silence |
| 40 | private(set) var recordingWindow: NSRect? |
| 41 | private(set) var captureKind = CaptureKind.paste |
| 42 | private(set) var refineShortcutReady = false |
| 43 | private var latest: Transcript? |
| 44 | private(set) var locales: [Locale] = [] |
| 45 | private(set) var shortcutReady = false |
| 46 | private(set) var modelStatus = AppleModels.modelStatus |
| 47 | private(set) var microphoneReady = false |
| 48 | private(set) var accessibilityReady = false |
| 49 | private(set) var pasteNeedsAttention = false |
| 50 | private(set) var speechReady = false |
| 51 | private(set) var speechStatus = "Checking model…" |
| 52 | private(set) var shortcutPressed = false |
| 53 | private(set) var shortcutPresses = 0 |
| 54 | private(set) var lastPasteStatus: String? |
| 55 | private(set) var lastPracticePasteStatus: String? |
| 56 | private(set) var testingPracticePaste = false |
| 57 | @ObservationIgnored weak var practiceWindow: NSWindow? |
| 58 | @ObservationIgnored weak var shortcutProbeWindow: NSWindow? |
| 59 | /// Receives the transcript of a Refine dictation and the app it started in. |
| 60 | @ObservationIgnored var onRefineReady: ((String, Destination) -> Void)? |
| 61 | var message: String? |
| 62 | |
| 63 | var preferences: Preferences { |
| 64 | get { library.preferences } |
| 65 | set { |
| 66 | let changedLocale = newValue.locale != library.preferences.locale |
| 67 | library.preferences = newValue |
| 68 | if changedLocale { prepareSpeech() } |
| 69 | save() |
| 70 | } |
| 71 | } |
| 72 | var mostRecentTranscript: Transcript? { latest ?? library.history.first } |
| 73 | |
| 74 | private var library: Library |
| 75 | @ObservationIgnored private let libraryURL: URL |
| 76 | @ObservationIgnored private let shortcut = GlobalShortcut() |
| 77 | @ObservationIgnored private let refineShortcut = GlobalShortcut(signature: 0x56584C52) |
| 78 | @ObservationIgnored private var refineGesture = DictationShortcutGesture() |
| 79 | @ObservationIgnored private let deliveryLog = Logger(subsystem: "com.protomota.voxley", category: "Delivery") |
| 80 | @ObservationIgnored private var shortcutGesture = DictationShortcutGesture() |
| 81 | @ObservationIgnored private var live: LiveDictation? |
| 82 | @ObservationIgnored private var task: Task<Void, Never>? |
| 83 | @ObservationIgnored private var destination: Destination? |
| 84 | @ObservationIgnored private var capturePreferences: Preferences? |
| 85 | @ObservationIgnored private var captureID: UUID? |
| 86 | @ObservationIgnored private var speechPreparation: Task<Locale, Error>? |
| 87 | @ObservationIgnored private var speechPreparationID: UUID? |
| 88 | @ObservationIgnored private var preparationTimeout: Task<Void, Never>? |
| 89 | @ObservationIgnored private var started = false |
| 90 | @ObservationIgnored private var diskReadable = true |
| 91 | |
| 92 | init() { |
| 93 | let directory = URL.applicationSupportDirectory.appending(path: "Voxley", directoryHint: .isDirectory) |
| 94 | libraryURL = directory.appending(path: "Library.json") |
| 95 | do { |
| 96 | library = FileManager.default.fileExists(atPath: libraryURL.path) ? try Library.read(libraryURL) : Library() |
| 97 | } catch { |
| 98 | library = Library() |
| 99 | diskReadable = false |
| 100 | message = "Couldn’t open the saved library. Voxley will leave that file untouched. Restore a backup to recover." |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | func activate() { |
| 105 | refreshPermissions() |
| 106 | guard !started else { return } |
| 107 | started = true |
| 108 | shortcut.onEvent = { [weak self] pressed, time in self?.handleShortcut(pressed, at: time) } |
| 109 | shortcut.onInterrupted = { [weak self] in |
| 110 | guard let self else { return } |
| 111 | self.shortcutPressed = false |
| 112 | if self.shortcutGesture.interrupt() { self.cancel() } |
| 113 | } |
| 114 | refineShortcut.onEvent = { [weak self] pressed, time in self?.handleRefineShortcut(pressed, at: time) } |
| 115 | refineShortcut.onInterrupted = { [weak self] in |
| 116 | guard let self else { return } |
| 117 | if self.refineGesture.interrupt() { self.cancel() } |
| 118 | } |
| 119 | if preferences.shortcutKey.isStandardEditingShortcut { |
| 120 | let oldLabel = preferences.shortcutKey.label |
| 121 | preferences.shortcutKey = .controlShiftSpace |
| 122 | message = "Voxley reset \(oldLabel) to \(Shortcut.controlShiftSpace.label) so the editing command works normally." |
| 123 | } |
| 124 | retryShortcut() |
| 125 | retryRefineShortcut() |
| 126 | Task { locales = await SpeechTranscriber.supportedLocales } |
| 127 | prepareSpeech() |
| 128 | } |
| 129 | |
| 130 | var statusTitle: String { |
| 131 | guard captureKind == .refine else { return phase.title } |
| 132 | switch phase { |
| 133 | case .recording: return "Listening for Refine…" |
| 134 | case .transcribing: return "Getting your words ready to refine…" |
| 135 | default: return phase.title |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | func shortcutLabel(_ kind: ShortcutKind) -> String { |
| 140 | kind == .dictation ? preferences.shortcutKey.label : preferences.refineShortcutKey.label |
| 141 | } |
| 142 | |
| 143 | func beginShortcutRecording(_ kind: ShortcutKind = .dictation) { |
| 144 | guard kind == .dictation else { |
| 145 | refineGesture = DictationShortcutGesture() |
| 146 | message = nil |
| 147 | refineShortcut.suspend() |
| 148 | return |
| 149 | } |
| 150 | shortcutGesture = DictationShortcutGesture() |
| 151 | shortcutPressed = false |
| 152 | message = nil |
| 153 | shortcut.suspend() |
| 154 | } |
| 155 | |
| 156 | func saveRecordedShortcut(_ recorded: Shortcut, kind: ShortcutKind) -> Bool { |
| 157 | guard kind == .refine else { return saveRecordedShortcut(recorded) } |
| 158 | let dictation = preferences.shortcutKey |
| 159 | guard recorded.code != dictation.code || recorded.modifiers != dictation.modifiers, |
| 160 | refineShortcut.register(recorded) else { return false } |
| 161 | refineShortcutReady = true |
| 162 | message = "Refine shortcut saved: \(recorded.label)" |
| 163 | if preferences.refineShortcutKey != recorded { preferences.refineShortcutKey = recorded } |
| 164 | return true |
| 165 | } |
| 166 | |
| 167 | func cancelShortcutRecording(_ kind: ShortcutKind) { |
| 168 | if kind == .refine { retryRefineShortcut() } else { cancelShortcutRecording() } |
| 169 | } |
| 170 | |
| 171 | func setRefineEnabled(_ enabled: Bool) { |
| 172 | preferences.refineEnabled = enabled |
| 173 | retryRefineShortcut() |
| 174 | } |
| 175 | |
| 176 | func retryRefineShortcut() { |
| 177 | guard preferences.refineEnabled else { |
| 178 | refineShortcut.suspend() |
| 179 | refineShortcutReady = false |
| 180 | return |
| 181 | } |
| 182 | let refine = preferences.refineShortcutKey |
| 183 | let dictation = preferences.shortcutKey |
| 184 | guard refine.code != dictation.code || refine.modifiers != dictation.modifiers else { |
| 185 | refineShortcut.suspend() |
| 186 | refineShortcutReady = false |
| 187 | return |
| 188 | } |
| 189 | refineShortcutReady = refineShortcut.register(refine) |
| 190 | deliveryLog.info("Refine shortcut registered: \(self.refineShortcutReady, privacy: .public)") |
| 191 | } |
| 192 | |
| 193 | func saveRecordedShortcut(_ recorded: Shortcut) -> Bool { |
| 194 | let refine = preferences.refineShortcutKey |
| 195 | if preferences.refineEnabled, recorded.code == refine.code, recorded.modifiers == refine.modifiers { |
| 196 | return false |
| 197 | } |
| 198 | guard shortcut.register(recorded) else { return false } |
| 199 | shortcutReady = true |
| 200 | message = "Shortcut saved: \(recorded.label)" |
| 201 | if preferences.shortcutKey != recorded { preferences.shortcutKey = recorded } |
| 202 | return true |
| 203 | } |
| 204 | |
| 205 | func retryShortcut() { |
| 206 | shortcutReady = shortcut.register(preferences.shortcutKey) |
| 207 | deliveryLog.info("Global shortcut registered: \(self.shortcutReady, privacy: .public)") |
| 208 | } |
| 209 | |
| 210 | func endSetupTest() { |
| 211 | practiceWindow = nil |
| 212 | shortcutProbeWindow = nil |
| 213 | if destination?.isPractice == true { cancel() } |
| 214 | } |
| 215 | |
| 216 | func testPracticePaste() async { |
| 217 | guard phase == .idle, !testingPracticePaste else { return } |
| 218 | let target = Destination(practiceWindow: practiceWindow, explicitPractice: true) |
| 219 | guard target.practiceFieldReady else { |
| 220 | lastPracticePasteStatus = "Click inside the practice field first" |
| 221 | return |
| 222 | } |
| 223 | testingPracticePaste = true |
| 224 | defer { testingPracticePaste = false } |
| 225 | let delivery = await target.deliver("Voxley paste test.") |
| 226 | lastPracticePasteStatus = delivery.status |
| 227 | message = delivery.message |
| 228 | deliveryLog.info("Practice paste: \(delivery.status, privacy: .public)") |
| 229 | } |
| 230 | |
| 231 | func cancelShortcutRecording() { retryShortcut() } |
| 232 | |
| 233 | private func prepareSpeech() { |
| 234 | speechPreparation?.cancel() |
| 235 | let locale = preferences.locale |
| 236 | let id = UUID() |
| 237 | speechPreparationID = id |
| 238 | speechStatus = "Preparing the on-device model…" |
| 239 | speechPreparation = Task { [weak self] in |
| 240 | do { |
| 241 | let resolved = try await AppleModels.prepareSpeech(for: locale) |
| 242 | if self?.speechPreparationID == id { self?.speechStatus = "Ready on this Mac" } |
| 243 | return resolved |
| 244 | } catch { |
| 245 | if self?.speechPreparationID == id { self?.speechStatus = error.localizedDescription } |
| 246 | throw error |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | func refreshPermissions() { |
| 252 | modelStatus = AppleModels.modelStatus |
| 253 | microphoneReady = AVCaptureDevice.authorizationStatus(for: .audio) == .authorized |
| 254 | let canAccessFields = AXIsProcessTrusted() |
| 255 | let canPostPaste = CGPreflightPostEventAccess() |
| 256 | accessibilityReady = canAccessFields && canPostPaste |
| 257 | deliveryLog.info("Voxley permissions: microphone \(self.microphoneReady, privacy: .public), field access \(canAccessFields, privacy: .public), key events \(canPostPaste, privacy: .public)") |
| 258 | speechReady = SpeechTranscriber.isAvailable |
| 259 | } |
| 260 | |
| 261 | func allowMicrophone() { |
| 262 | Task { |
| 263 | if AVCaptureDevice.authorizationStatus(for: .audio) == .denied { |
| 264 | Self.openSettings("com.apple.preference.security?Privacy_Microphone") |
| 265 | } else { |
| 266 | _ = await LiveDictation.requestMicrophone() |
| 267 | refreshPermissions() |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | func allowAccessibility() { |
| 273 | Destination.requestAccessibility() |
| 274 | Self.openSettings("com.apple.preference.security?Privacy_Accessibility") |
| 275 | } |
| 276 | |
| 277 | static func openSettings(_ pane: String) { |
| 278 | if let url = URL(string: "x-apple.systempreferences:" + pane) { |
| 279 | NSWorkspace.shared.open(url) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | private func handleShortcut(_ pressed: Bool, at time: TimeInterval) { |
| 284 | shortcutPressed = pressed |
| 285 | if pressed { shortcutPresses += 1 } |
| 286 | deliveryLog.debug("Shortcut \(pressed ? "pressed" : "released", privacy: .public)") |
| 287 | if let shortcutProbeWindow, NSApp.keyWindow === shortcutProbeWindow, phase == .idle { return } |
| 288 | let action = shortcutGesture.update(pressed: pressed, time: time, |
| 289 | canStart: phase == .idle, isRecording: phase.isCapturing) |
| 290 | switch action { |
| 291 | case .start: start() |
| 292 | case .stop: |
| 293 | if phase == .preparing { cancel() } |
| 294 | else { stopRecording() } |
| 295 | case .none: break |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | private func handleRefineShortcut(_ pressed: Bool, at time: TimeInterval) { |
| 300 | deliveryLog.debug("Refine shortcut \(pressed ? "pressed" : "released", privacy: .public)") |
| 301 | let action = refineGesture.update(pressed: pressed, time: time, |
| 302 | canStart: phase == .idle, isRecording: phase.isCapturing) |
| 303 | switch action { |
| 304 | case .start: start(kind: .refine) |
| 305 | case .stop: |
| 306 | if phase == .preparing { cancel() } |
| 307 | else { stopRecording() } |
| 308 | case .none: break |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | private func start(kind: CaptureKind = .paste) { |
| 313 | guard phase == .idle, !testingPracticePaste else { return } |
| 314 | captureKind = kind |
| 315 | let capture = LiveDictation() |
| 316 | let id = UUID() |
| 317 | let snapshot = preferences |
| 318 | let target = Destination(practiceWindow: practiceWindow) |
| 319 | live = capture |
| 320 | captureID = id |
| 321 | destination = target |
| 322 | capturePreferences = snapshot |
| 323 | liveText = "" |
| 324 | recordingWindow = target.windowFrame |
| 325 | message = nil |
| 326 | if target.isPractice { lastPracticePasteStatus = nil } |
| 327 | pasteNeedsAttention = false |
| 328 | phase = .preparing |
| 329 | |
| 330 | if speechPreparation == nil { prepareSpeech() } |
| 331 | let preparation = speechPreparation |
| 332 | preparationTimeout = Task { [weak self] in |
| 333 | do { try await Task.sleep(for: .seconds(12)) } |
| 334 | catch { return } |
| 335 | guard let self, self.captureID == id, self.phase == .preparing else { return } |
| 336 | self.cancel() |
| 337 | self.message = "Apple Speech is still getting ready. Try holding the shortcut again in a moment." |
| 338 | } |
| 339 | task = Task { [self] in |
| 340 | do { |
| 341 | guard await LiveDictation.requestMicrophone() else { throw VoxleyError.microphone } |
| 342 | refreshPermissions() |
| 343 | try Task.checkCancellation() |
| 344 | guard let preparation else { throw VoxleyError.speechUnavailable } |
| 345 | let locale: Locale |
| 346 | do { |
| 347 | locale = try await preparation.value |
| 348 | } catch { |
| 349 | if captureID == id, preferences.locale == snapshot.locale { speechPreparation = nil } |
| 350 | throw error |
| 351 | } |
| 352 | let module = SpeechTranscriber(locale: locale, preset: .progressiveTranscription) |
| 353 | try Task.checkCancellation() |
| 354 | try await capture.start( |
| 355 | module: module, words: snapshot.contextWords, |
| 356 | update: { [weak self] text in await self?.showPartial(text, capture: id) }, |
| 357 | meter: { [weak self] waveform in |
| 358 | Task { @MainActor in |
| 359 | guard let self, self.captureID == id, self.phase == .recording else { return } |
| 360 | self.waveform = waveform |
| 361 | } |
| 362 | } |
| 363 | ) |
| 364 | try Task.checkCancellation() |
| 365 | preparationTimeout?.cancel() |
| 366 | phase = .recording |
| 367 | } catch { |
| 368 | await capture.cancel() |
| 369 | guard captureID == id else { return } |
| 370 | if !Task.isCancelled { message = error.localizedDescription } |
| 371 | reset() |
| 372 | } |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | private func showPartial(_ text: String, capture id: UUID) { |
| 377 | if captureID == id { liveText = text } |
| 378 | } |
| 379 | |
| 380 | func stopRecording() { |
| 381 | guard phase == .recording, let live, let target = destination, let snapshot = capturePreferences else { return } |
| 382 | phase = .transcribing |
| 383 | let kind = captureKind |
| 384 | task = Task { [self] in |
| 385 | do { |
| 386 | let original = try await live.finish() |
| 387 | try Task.checkCancellation() |
| 388 | if kind == .refine { |
| 389 | try openRefine(original, snapshot: snapshot, target: target) |
| 390 | reset() |
| 391 | return |
| 392 | } |
| 393 | let mode = target.isPractice ? .verbatim : target.identifier.flatMap { snapshot.appModes[$0] } ?? snapshot.mode |
| 394 | try await complete(original, mode: mode, snapshot: snapshot, source: target.name, target: target) |
| 395 | } catch { |
| 396 | if !Task.isCancelled { message = error.localizedDescription } |
| 397 | } |
| 398 | reset() |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | /// A Refine dictation skips cleanup and paste. The words go to the Refine window, |
| 403 | /// and history keeps them so they are never lost. |
| 404 | private func openRefine(_ original: String, snapshot: Preferences, target: Destination) throws { |
| 405 | let text = snapshot.applyingReplacements(to: original) |
| 406 | guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw VoxleyError.noSpeech } |
| 407 | let entry = Transcript(original: original, text: text, source: "Refine · \(target.name)", mode: .verbatim) |
| 408 | latest = entry |
| 409 | if preferences.retainHistory { |
| 410 | library.history.insert(entry, at: 0) |
| 411 | save() |
| 412 | } |
| 413 | onRefineReady?(text, target) |
| 414 | } |
| 415 | |
| 416 | func cancel() { |
| 417 | guard phase.isCapturing else { return } |
| 418 | let capture = live |
| 419 | task?.cancel() |
| 420 | reset() |
| 421 | Task { await capture?.cancel() } |
| 422 | } |
| 423 | |
| 424 | private func complete(_ original: String, mode: WritingMode, snapshot: Preferences, |
| 425 | source: String, target: Destination) async throws { |
| 426 | guard !original.isEmpty else { throw VoxleyError.noSpeech } |
| 427 | if mode != .verbatim { phase = .refining } |
| 428 | let result = await AppleModels.refine(original, mode: mode, locale: snapshot.locale) |
| 429 | let text = snapshot.applyingReplacements(to: result.text) |
| 430 | guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw VoxleyError.noSpeech } |
| 431 | |
| 432 | let delivery = await target.deliver(text) |
| 433 | deliveryLog.info("Delivery to \(target.identifier ?? "unknown", privacy: .public): \(delivery.status, privacy: .public)") |
| 434 | refreshPermissions() |
| 435 | if target.isPractice { |
| 436 | lastPracticePasteStatus = delivery.status |
| 437 | message = delivery.message |
| 438 | return |
| 439 | } |
| 440 | let entry = Transcript(original: original, text: text, source: source, mode: mode) |
| 441 | latest = entry |
| 442 | lastPasteStatus = "\(source): \(delivery.status)" |
| 443 | pasteNeedsAttention = delivery.needsAttention |
| 444 | message = [result.note, delivery.message].compactMap { $0 }.joined(separator: " ").nilIfEmpty |
| 445 | if preferences.retainHistory { |
| 446 | library.history.insert(entry, at: 0) |
| 447 | save() |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | func exportBackup() { |
| 452 | let panel = NSSavePanel() |
| 453 | panel.allowedContentTypes = [.json] |
| 454 | panel.nameFieldStringValue = "Voxley Backup.json" |
| 455 | guard panel.runModal() == .OK, let url = panel.url else { return } |
| 456 | do { |
| 457 | try library.write(url) |
| 458 | message = "Backup exported." |
| 459 | } catch { |
| 460 | message = error.localizedDescription |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | func importWordList() { |
| 465 | let panel = NSOpenPanel() |
| 466 | panel.title = "Import Word List" |
| 467 | panel.prompt = "Import" |
| 468 | panel.allowedContentTypes = [.plainText, .commaSeparatedText, .tabSeparatedText] |
| 469 | guard panel.runModal() == .OK, let url = panel.url else { return } |
| 470 | |
| 471 | do { |
| 472 | var encoding = String.Encoding.utf8 |
| 473 | let text = try String(contentsOf: url, usedEncoding: &encoding) |
| 474 | var updated = library |
| 475 | let added = try updated.preferences.importVocabulary(text) |
| 476 | guard added > 0 else { |
| 477 | message = "Those entries are already in your vocabulary." |
| 478 | return |
| 479 | } |
| 480 | guard diskReadable else { |
| 481 | message = "Restore your library before importing a word list." |
| 482 | return |
| 483 | } |
| 484 | try persist(updated) |
| 485 | library = updated |
| 486 | message = added == 1 ? "Added 1 vocabulary entry." : "Added \(added) vocabulary entries." |
| 487 | } catch { |
| 488 | message = error.localizedDescription |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | func importBackup() { |
| 493 | let panel = NSOpenPanel() |
| 494 | panel.allowedContentTypes = [.json] |
| 495 | guard panel.runModal() == .OK, let url = panel.url else { return } |
| 496 | do { |
| 497 | let backup = try Library.read(url) |
| 498 | let confirm = NSAlert() |
| 499 | confirm.messageText = "Restore Voxley backup?" |
| 500 | confirm.informativeText = "This replaces your settings and merges transcripts into your current history." |
| 501 | confirm.addButton(withTitle: "Restore") |
| 502 | confirm.addButton(withTitle: "Cancel") |
| 503 | guard confirm.runModal() == .alertFirstButtonReturn else { return } |
| 504 | if !diskReadable && FileManager.default.fileExists(atPath: libraryURL.path) { |
| 505 | let original = libraryURL.deletingLastPathComponent().appending(path: "Library-recovery-\(UUID()).json") |
| 506 | try FileManager.default.copyItem(at: libraryURL, to: original) |
| 507 | } |
| 508 | var merged = library |
| 509 | merged.restore(backup) |
| 510 | let previousShortcut = preferences.shortcutKey |
| 511 | let restoredShortcut = shortcut.register(merged.preferences.shortcutKey) |
| 512 | if !restoredShortcut { merged.preferences.shortcutKey = previousShortcut } |
| 513 | do { |
| 514 | try persist(merged) |
| 515 | } catch { |
| 516 | shortcutReady = shortcut.register(previousShortcut) |
| 517 | throw error |
| 518 | } |
| 519 | diskReadable = true |
| 520 | library = merged |
| 521 | shortcutReady = shortcut.register(preferences.shortcutKey) |
| 522 | retryRefineShortcut() |
| 523 | prepareSpeech() |
| 524 | message = restoredShortcut ? "Backup restored." : "Backup restored. The saved shortcut was unavailable, so Voxley kept your current shortcut." |
| 525 | } catch { |
| 526 | message = error.localizedDescription |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | private func reset() { |
| 531 | preparationTimeout?.cancel() |
| 532 | preparationTimeout = nil |
| 533 | shortcutGesture = DictationShortcutGesture() |
| 534 | refineGesture = DictationShortcutGesture() |
| 535 | captureKind = .paste |
| 536 | phase = .idle |
| 537 | task = nil |
| 538 | captureID = nil |
| 539 | live = nil |
| 540 | destination = nil |
| 541 | capturePreferences = nil |
| 542 | liveText = "" |
| 543 | waveform = WaveformFrame.silence |
| 544 | recordingWindow = nil |
| 545 | } |
| 546 | |
| 547 | private func persist(_ value: Library) throws { |
| 548 | try FileManager.default.createDirectory(at: libraryURL.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 549 | try value.write(libraryURL) |
| 550 | } |
| 551 | |
| 552 | private func save() { |
| 553 | guard diskReadable else { |
| 554 | message = "The library could not be read. Changes are in memory until you restore a backup." |
| 555 | return |
| 556 | } |
| 557 | do { try persist(library) } |
| 558 | catch { message = "Couldn’t save the library: \(error.localizedDescription)" } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | private extension String { |
| 563 | var nilIfEmpty: String? { isEmpty ? nil : self } |
| 564 | } |