Sources/OrgApp/ConfigSync.swift
89 lines · 3817 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 } else {
38 let template = UserConfig.template(from: defaults)
39 try? template.write(to: url, atomically: true, encoding: .utf8)
40 text = template
41 }
42 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
43 MainActor.assumeIsolated { self?.writeBack() }
44 }
45 guard watch else { return }
46 let directory = url.deletingLastPathComponent()
47 watcher = FSEventsWatcher(roots: [directory.resolvingSymlinksInPath()]) { [weak self] events in
48 let names = Set(events.compactMap { event -> String? in
49 if case .changed(let url) = event { return url.lastPathComponent }
50 return nil
51 })
52 Task { @MainActor [weak self] in
53 guard let self else { return }
54 for name in names.sorted() {
55 if name == self.url.lastPathComponent { self.reload() }
56 self.serial += 1
57 self.changedFile = (name, self.serial)
58 }
59 }
60 }
61 watcher?.start()
62 }
63
64 /// Reads the file and applies it when it changed since the last read or write.
65 public func reload() {
66 guard let new = try? String(contentsOf: url, encoding: .utf8), new != text else { return }
67 text = new
68 applying = true
69 problems = UserConfig.apply(new, to: defaults)
70 applying = false
71 }
72
73 /// Writes settings that differ from the file into it.
74 func writeBack() {
75 guard !applying, var current = text ?? (try? String(contentsOf: url, encoding: .utf8)) else { return }
76 let values = UserConfig.values(in: current)
77 let original = current
78 for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil {
79 let value = UserConfig.value(setting, in: defaults)
80 if values[setting.section + "." + setting.key] != value {
81 current = UserConfig.setting(current, section: setting.section, key: setting.key, to: value)
82 }
83 }
84 guard current != original else { return }
85 text = current
86 try? current.write(to: url, atomically: true, encoding: .utf8)
87 }
88}
89#endif