Branchwell

Voxley / app · voxley.si / Sources / Voxley / VoxleyUpdates.swift

1#if VOXLEY_SPARKLE
2import Foundation
3import Observation
4import Sparkle
5
6@MainActor
7@Observable
8final class VoxleyUpdates: NSObject, SPUUpdaterDelegate {
9 static let shared = VoxleyUpdates()
10
11 private(set) var canCheck = false
12 private(set) var automaticUpdates = false
13 @ObservationIgnored private weak var dictation: DictationController?
14 @ObservationIgnored private var controller: SPUStandardUpdaterController?
15 @ObservationIgnored private var observations: [NSKeyValueObservation] = []
16 @ObservationIgnored private var pendingInstall: (() -> Void)?
17
18 func start(dictation: DictationController) {
19 guard controller == nil else { return }
20 self.dictation = dictation
21 let controller = SPUStandardUpdaterController(
22 startingUpdater: false, updaterDelegate: self, userDriverDelegate: nil
23 )
24 self.controller = controller
25 observations = [
26 controller.updater.observe(\.canCheckForUpdates, options: [.initial, .new]) { [weak self] _, _ in
27 Task { @MainActor in self?.refresh() }
28 },
29 controller.updater.observe(\.automaticallyDownloadsUpdates, options: [.initial, .new]) { [weak self] _, _ in
30 Task { @MainActor in self?.refresh() }
31 }
32 ]
33 controller.startUpdater()
34 refresh()
35 }
36
37 func check() {
38 guard dictation?.phase == .idle, let updater = controller?.updater, updater.canCheckForUpdates else { return }
39 updater.checkForUpdates()
40 }
41
42 func setAutomaticUpdates(_ enabled: Bool) {
43 controller?.updater.automaticallyDownloadsUpdates = enabled
44 refresh()
45 }
46
47 func updater(_ updater: SPUUpdater, mayPerform updateCheck: SPUUpdateCheck) throws {
48 guard dictation?.phase == .idle else {
49 throw CocoaError(.userCancelled, userInfo: [
50 NSLocalizedDescriptionKey: "Finish dictating before checking for updates."
51 ])
52 }
53 }
54
55 func updater(
56 _ updater: SPUUpdater, shouldPostponeRelaunchForUpdate item: SUAppcastItem,
57 untilInvokingBlock installHandler: @escaping () -> Void
58 ) -> Bool {
59 guard let dictation, dictation.phase != .idle else { return false }
60 // Observe the whole dictation session, including final transcription and paste.
61 pendingInstall = installHandler
62 installWhenIdle()
63 return true
64 }
65
66 private func installWhenIdle() {
67 guard let dictation, dictation.phase != .idle else {
68 let install = pendingInstall
69 pendingInstall = nil
70 install?()
71 return
72 }
73 withObservationTracking {
74 _ = dictation.phase
75 } onChange: { [weak self] in
76 Task { @MainActor in self?.installWhenIdle() }
77 }
78 }
79
80 private func refresh() {
81 canCheck = controller?.updater.canCheckForUpdates ?? false
82 automaticUpdates = controller?.updater.automaticallyDownloadsUpdates ?? false
83 }
84}
85#endif