Sources/OrgApp/ConfigSync.swift

b5449dec59a00fac6867954166c6c612ffd6aee4
orgstar/Sources/OrgApp/ConfigSync.swift history · blame · raw

95 lines · 4142 bytes

 1#if os(macOS)
 2import Foundation
 3import OrgCore
 4import OrgWorkspace
 5
 6/// Keeps `config.toml` and the settings in user defaults the same: the file applies at launch
 7/// and whenever it changes on disk, and a change made in the app is written into the file. A
 8/// missing file is created with every setting at its current value.
 9@MainActor
10@Observable
11public final class ConfigSync {
12    public static let shared = ConfigSync()
13
14    /// Problems in the file, from the last time it was read.
15    public private(set) var problems: [String] = []
16    /// The last file of the configuration folder that changed, with a serial number.
17    public private(set) var changedFile: (name: String, serial: Int)?
18
19    private let url: URL
20    private let defaults: UserDefaults
21    @ObservationIgnored private var text: String?
22    @ObservationIgnored private var applying = false
23    @ObservationIgnored private var watcher: FSEventsWatcher?
24    @ObservationIgnored private var observer: NSObjectProtocol?
25    @ObservationIgnored private var serial = 0
26
27    public init(url: URL = UserConfig.configFile, defaults: UserDefaults = .standard) {
28        self.url = url
29        self.defaults = defaults
30    }
31
32    public func start(watch: Bool = true) {
33        guard observer == nil else { return }
34        try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
35        if FileManager.default.fileExists(atPath: url.path) {
36            reload()
37            // A file from before settings took Emacs's names is written again with them.
38            if let text, UserConfig.usesLegacyNames(text) {
39                let template = UserConfig.template(from: defaults)
40                try? template.write(to: url, atomically: true, encoding: .utf8)
41                self.text = template
42            }
43        } else {
44            let template = UserConfig.template(from: defaults)
45            try? template.write(to: url, atomically: true, encoding: .utf8)
46            text = template
47        }
48        observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
49            MainActor.assumeIsolated { self?.writeBack() }
50        }
51        guard watch else { return }
52        let directory = url.deletingLastPathComponent()
53        watcher = FSEventsWatcher(roots: [directory.resolvingSymlinksInPath()]) { [weak self] events in
54            let names = Set(events.compactMap { event -> String? in
55                if case .changed(let url) = event { return url.lastPathComponent }
56                return nil
57            })
58            Task { @MainActor [weak self] in
59                guard let self else { return }
60                for name in names.sorted() {
61                    if name == self.url.lastPathComponent { self.reload() }
62                    self.serial += 1
63                    self.changedFile = (name, self.serial)
64                }
65            }
66        }
67        watcher?.start()
68    }
69
70    /// Reads the file and applies it when it changed since the last read or write.
71    public func reload() {
72        guard let new = try? String(contentsOf: url, encoding: .utf8), new != text else { return }
73        text = new
74        applying = true
75        problems = UserConfig.apply(new, to: defaults)
76        applying = false
77    }
78
79    /// Writes settings that differ from the file into it.
80    func writeBack() {
81        guard !applying, var current = text ?? (try? String(contentsOf: url, encoding: .utf8)) else { return }
82        let values = UserConfig.values(in: current)
83        let original = current
84        for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil {
85            let value = UserConfig.value(setting, in: defaults)
86            if values[setting.path] != value {
87                current = UserConfig.setting(current, section: setting.section, key: setting.key, to: value)
88            }
89        }
90        guard current != original else { return }
91        text = current
92        try? current.write(to: url, atomically: true, encoding: .utf8)
93    }
94}
95#endif