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