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