Sources/OrgApp/ConfigSync.swift
143 lines · 6575 bytes
1#if os(macOS)
2import Foundation
3import OrgCore
4import OrgPresentation
5import OrgWorkspace
6
7/// Keeps `config.toml` and the settings in user defaults the same: the file applies at launch
8/// and whenever it changes on disk, and a change made in the app is written into the file. A
9/// missing file is created with every setting at its current value.
10@MainActor
11@Observable
12public final class ConfigSync {
13 public static let shared = ConfigSync()
14
15 /// Problems in the file, from the last time it was read.
16 public private(set) var problems: [String] = []
17 /// The colors of `[theme]`, `[theme.light]`, `[theme.dark]` and `[theme.todo]` over the
18 /// default theme, with `theme-file`'s under them.
19 public private(set) var theme = ThemeSpec.default
20 /// The last file of the configuration folder that changed, with a serial number.
21 public private(set) var changedFile: (name: String, serial: Int)?
22
23 private let url: URL
24 private let defaults: UserDefaults
25 @ObservationIgnored private var text: String?
26 @ObservationIgnored private var configProblems: [String] = []
27 @ObservationIgnored private var applying = false
28 @ObservationIgnored private var watcher: FSEventsWatcher?
29 @ObservationIgnored private var observer: NSObjectProtocol?
30 @ObservationIgnored private var serial = 0
31
32 public init(url: URL = UserConfig.configFile, defaults: UserDefaults = .standard) {
33 self.url = url
34 self.defaults = defaults
35 }
36
37 public func start(watch: Bool = true) {
38 guard observer == nil else { return }
39 try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
40 let reference = url.deletingLastPathComponent().appendingPathComponent("default-theme.toml")
41 if (try? String(contentsOf: reference, encoding: .utf8)) != ThemeSpec.defaultThemeFile() {
42 try? ThemeSpec.defaultThemeFile().write(to: reference, atomically: true, encoding: .utf8)
43 }
44 if FileManager.default.fileExists(atPath: url.path) {
45 reload()
46 // A file from before settings took Emacs's names gets them in place; one from
47 // before a section existed gets the section.
48 if let text {
49 let migrated = UserConfig.usesLegacyNames(text) ? UserConfig.migratingLegacyNames(text) : text
50 let completed = UserConfig.addingMissingSections(migrated, from: defaults)
51 if completed != text {
52 try? completed.write(to: url, atomically: true, encoding: .utf8)
53 self.text = completed
54 }
55 }
56 } else {
57 let template = UserConfig.template(from: defaults)
58 try? template.write(to: url, atomically: true, encoding: .utf8)
59 text = template
60 }
61 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
62 MainActor.assumeIsolated { self?.writeBack() }
63 }
64 guard watch else { return }
65 let directory = url.deletingLastPathComponent()
66 watcher = FSEventsWatcher(roots: [directory.resolvingSymlinksInPath()]) { [weak self] events in
67 let changed = Set(events.compactMap { event -> URL? in
68 if case .changed(let url) = event { return url }
69 return nil
70 })
71 Task { @MainActor [weak self] in
72 guard let self else { return }
73 for file in changed.sorted(by: { $0.path < $1.path }) {
74 let name = file.lastPathComponent
75 if name == self.url.lastPathComponent { self.reload() }
76 if self.isThemeFile(file) { self.readTheme() }
77 self.serial += 1
78 self.changedFile = (name, self.serial)
79 }
80 }
81 }
82 watcher?.start()
83 }
84
85 /// Reads the file and applies it when it changed since the last read or write.
86 public func reload() {
87 guard let new = try? String(contentsOf: url, encoding: .utf8), new != text else { return }
88 text = new
89 applying = true
90 configProblems = UserConfig.apply(new, to: defaults)
91 applying = false
92 readTheme()
93 }
94
95 /// `theme-file`, relative to the configuration folder.
96 private var themeFile: URL? {
97 guard let name = defaults.string(forKey: "themeFile"), !name.isEmpty else { return nil }
98 return url.deletingLastPathComponent().appendingPathComponent(name)
99 }
100
101 /// Whether `file`, as the watcher reports it, is `theme-file`, which may be in a subfolder.
102 func isThemeFile(_ file: URL) -> Bool {
103 themeFile?.resolvingSymlinksInPath().path == file.resolvingSymlinksInPath().path
104 }
105
106 /// The theme from the file read last and its theme file.
107 func readTheme() {
108 guard let text, let tables = try? TOML.parse(text) else { return }
109 var spec = ThemeSpec.default
110 var themeProblems: [String] = []
111 if let name = defaults.string(forKey: "themeFile"), let file = themeFile {
112 if let themeText = try? String(contentsOf: file, encoding: .utf8) {
113 do {
114 (spec, themeProblems) = ThemeSpec.reading(try TOML.parse(themeText), file: name)
115 } catch {
116 themeProblems.append("\(name): \(error)")
117 }
118 } else {
119 themeProblems.append("config.toml: theme-file \(name) can't be read")
120 }
121 }
122 let (merged, more) = ThemeSpec.reading(tables, over: spec)
123 if merged != theme { theme = merged }
124 problems = configProblems + themeProblems + more
125 }
126
127 /// Writes settings that differ from the file into it.
128 func writeBack() {
129 guard !applying, var current = text ?? (try? String(contentsOf: url, encoding: .utf8)) else { return }
130 let values = UserConfig.values(in: current)
131 let original = current
132 for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil {
133 let value = UserConfig.value(setting, in: defaults)
134 if values[setting.path] != value {
135 current = UserConfig.setting(current, section: setting.section, key: setting.key, to: value)
136 }
137 }
138 guard current != original else { return }
139 text = current
140 try? current.write(to: url, atomically: true, encoding: .utf8)
141 }
142}
143#endif