Sources/OrgApp/ConfigSync.swift
216 lines · 10418 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 @ObservationIgnored private var url: URL
24 private let defaults: UserDefaults
25 @ObservationIgnored private var text: String?
26 @ObservationIgnored private var configProblems: [String] = []
27 @ObservationIgnored private var themeProblems: [String] = []
28 @ObservationIgnored private var macroProblems: [String] = []
29 /// Why the file couldn't be read or written, the last time a setting was to go into it.
30 @ObservationIgnored private var fileProblem: String?
31 @ObservationIgnored private var applying = false
32 @ObservationIgnored private var watcher: FSEventsWatcher?
33 @ObservationIgnored private var observer: NSObjectProtocol?
34 @ObservationIgnored private var serial = 0
35 @ObservationIgnored private var watches = true
36
37 /// Where `url` leads: a symlinked config.toml is written through, not replaced by a file.
38 private var target: URL { url.resolvingSymlinksInPath() }
39
40 public init(url: URL = UserConfig.configFile, defaults: UserDefaults = .standard) {
41 self.url = url
42 self.defaults = defaults
43 }
44
45 public func start(watch: Bool = true) {
46 guard observer == nil else { return }
47 watches = watch
48 try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
49 let reference = url.deletingLastPathComponent().appendingPathComponent("default-theme.toml")
50 if (try? String(contentsOf: reference, encoding: .utf8)) != ThemeSpec.defaultThemeFile() {
51 try? ThemeSpec.defaultThemeFile().write(to: reference, atomically: true, encoding: .utf8)
52 }
53 if FileManager.default.fileExists(atPath: url.path) {
54 reload()
55 // A file from before settings took Emacs's names gets them in place; one from
56 // before a section existed gets the section.
57 if let text {
58 let migrated = UserConfig.usesLegacyNames(text) ? UserConfig.migratingLegacyNames(text) : text
59 let completed = UserConfig.addingMissingSections(migrated, from: defaults)
60 if completed != text, write(completed) { self.text = completed }
61 }
62 } else {
63 let template = UserConfig.template(from: defaults)
64 if write(template) { text = template }
65 }
66 loadMacros()
67 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
68 MainActor.assumeIsolated { self?.writeBack() }
69 }
70 guard watch else { return }
71 let directory = url.deletingLastPathComponent().resolvingSymlinksInPath()
72 // The linked file's folder too, when config.toml is a symlink.
73 let linked = target.deletingLastPathComponent().resolvingSymlinksInPath()
74 let watchesLinked = linked.path != directory.path
75 // Files still read from where earlier versions kept them reload when edited there too.
76 let legacy = UserConfig.legacyDirectory.resolvingSymlinksInPath()
77 let watchesLegacy = UserConfig.directoryOverride == nil && legacy.path != directory.path && FileManager.default.fileExists(atPath: legacy.path)
78 watcher = FSEventsWatcher(roots: [directory] + (watchesLinked ? [linked] : []) + (watchesLegacy ? [legacy] : [])) { [weak self] events in
79 let changed = Set(events.compactMap { event -> URL? in
80 if case .changed(let url) = event { return url }
81 return nil
82 })
83 Task { @MainActor [weak self] in
84 guard let self else { return }
85 for file in changed.sorted(by: { $0.path < $1.path }) {
86 if !file.path.hasPrefix(directory.path + "/"),
87 UserConfig.file(file.lastPathComponent).resolvingSymlinksInPath().path != file.resolvingSymlinksInPath().path { continue }
88 let name = file.lastPathComponent
89 if name == self.url.lastPathComponent { self.reload() }
90 if self.isThemeFile(file) { self.readTheme() }
91 if name == NamedMacros.fileName { self.loadMacros() }
92 self.serial += 1
93 self.changedFile = (name, self.serial)
94 }
95 }
96 }
97 watcher?.start()
98 }
99
100 /// Uses `url`, as in another configuration folder, from now on: its settings apply, and a
101 /// missing file is created with the current ones. Does nothing before `start`.
102 public func move(to url: URL) {
103 guard observer != nil, url != self.url else { return }
104 watcher?.stop()
105 watcher = nil
106 if let observer { NotificationCenter.default.removeObserver(observer) }
107 observer = nil
108 text = nil
109 configProblems = []
110 themeProblems = []
111 macroProblems = []
112 fileProblem = nil
113 self.url = url
114 start(watch: watches)
115 readTheme()
116 // Windows read keymap.toml once, so they reload it from the new folder.
117 serial += 1
118 changedFile = ("keymap.toml", serial)
119 }
120
121 /// Reads the file and applies it when it changed since the last read or write.
122 public func reload() {
123 guard let new = try? String(contentsOf: url, encoding: .utf8), new != text else { return }
124 text = new
125 applying = true
126 configProblems = UserConfig.apply(new, to: defaults)
127 applying = false
128 readTheme()
129 }
130
131 /// `macros.toml`, beside the file, into the named macros.
132 private func loadMacros() {
133 let problems = MacroFile.load(from: url.deletingLastPathComponent().appendingPathComponent(NamedMacros.fileName))
134 macroProblems = problems.map { "\(NamedMacros.fileName): \($0)" }
135 updateProblems()
136 }
137
138 /// `theme-file`, relative to the configuration folder.
139 private var themeFile: URL? {
140 guard let name = defaults.string(forKey: "themeFile"), !name.isEmpty else { return nil }
141 return url.deletingLastPathComponent().appendingPathComponent(name)
142 }
143
144 /// Whether `file`, as the watcher reports it, is `theme-file`, which may be in a subfolder.
145 func isThemeFile(_ file: URL) -> Bool {
146 themeFile?.resolvingSymlinksInPath().path == file.resolvingSymlinksInPath().path
147 }
148
149 /// The theme from the file read last and its theme file.
150 func readTheme() {
151 guard let text, let read = UserConfig.theme(
152 config: text, themeFile: defaults.string(forKey: "themeFile"),
153 lightTheme: defaults.string(forKey: "themeLight"), darkTheme: defaults.string(forKey: "themeDark"),
154 in: url.deletingLastPathComponent()
155 ) else { return }
156 if read.theme != theme { theme = read.theme }
157 themeProblems = read.problems
158 updateProblems()
159 }
160
161 private func updateProblems() {
162 let all = (fileProblem.map { [$0] } ?? []) + configProblems + themeProblems + macroProblems
163 if all != problems { problems = all }
164 }
165
166 /// Writes the file; false, with the reason among `problems`, when that fails.
167 private func write(_ new: String) -> Bool {
168 do {
169 try new.write(to: target, atomically: true, encoding: .utf8)
170 fileProblem = nil
171 } catch {
172 fileProblem = "\(url.lastPathComponent) wasn't written: \(error.localizedDescription)"
173 }
174 updateProblems()
175 return fileProblem == nil
176 }
177
178 /// Writes settings that differ from the file into it.
179 func writeBack() {
180 // The file as it is now, so that tables written into it since, as by Emacs import, stay.
181 guard !applying else { return }
182 let onDisk: String?
183 do {
184 onDisk = try UserFile.text(at: url)
185 } catch {
186 fileProblem = "\(url.lastPathComponent) wasn't changed: \(error.localizedDescription)"
187 updateProblems()
188 return
189 }
190 guard var current = onDisk ?? text else { return }
191 let values = UserConfig.values(in: current)
192 let original = current
193 for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil {
194 let value = UserConfig.value(setting, in: defaults)
195 if values[setting.path] != value {
196 current = UserConfig.setting(current, section: setting.section, key: setting.key, to: value)
197 }
198 }
199 // Templates added in the app, as by Emacs import; removing one is done in the file.
200 for template in UserConfig.structureTemplates(defaults) where values[UserConfig.path(UserConfig.structureTemplateTable, template.key)] != .string(template.type) {
201 current = UserConfig.setting(current, section: UserConfig.structureTemplateTable, key: template.key, to: .string(template.type))
202 }
203 for template in UserConfig.denoteTemplates(defaults) where values[UserConfig.path(UserConfig.denoteTemplateTable, template.key)] != .string(template.text) {
204 current = UserConfig.setting(current, section: UserConfig.denoteTemplateTable, key: template.key, to: .string(template.text))
205 }
206 guard current != original else {
207 fileProblem = nil
208 return updateProblems()
209 }
210 guard write(current) else { return }
211 text = current
212 // A theme picked in Settings; the watcher's reload sees the text unchanged and skips it.
213 readTheme()
214 }
215}
216#endif