Sources/OrgApp/ConfigSync.swift
135 lines · 6250 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 is written again with them; one
47 // from before a section existed gets the section.
48 if let text, UserConfig.usesLegacyNames(text) {
49 let template = UserConfig.template(from: defaults)
50 try? template.write(to: url, atomically: true, encoding: .utf8)
51 self.text = template
52 } else if let text {
53 let completed = UserConfig.addingMissingSections(text, from: defaults)
54 if completed != text {
55 try? completed.write(to: url, atomically: true, encoding: .utf8)
56 self.text = completed
57 }
58 }
59 } else {
60 let template = UserConfig.template(from: defaults)
61 try? template.write(to: url, atomically: true, encoding: .utf8)
62 text = template
63 }
64 observer = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: defaults, queue: .main) { [weak self] _ in
65 MainActor.assumeIsolated { self?.writeBack() }
66 }
67 guard watch else { return }
68 let directory = url.deletingLastPathComponent()
69 watcher = FSEventsWatcher(roots: [directory.resolvingSymlinksInPath()]) { [weak self] events in
70 let names = Set(events.compactMap { event -> String? in
71 if case .changed(let url) = event { return url.lastPathComponent }
72 return nil
73 })
74 Task { @MainActor [weak self] in
75 guard let self else { return }
76 for name in names.sorted() {
77 if name == self.url.lastPathComponent { self.reload() }
78 if name == self.defaults.string(forKey: "themeFile") { self.readTheme() }
79 self.serial += 1
80 self.changedFile = (name, self.serial)
81 }
82 }
83 }
84 watcher?.start()
85 }
86
87 /// Reads the file and applies it when it changed since the last read or write.
88 public func reload() {
89 guard let new = try? String(contentsOf: url, encoding: .utf8), new != text else { return }
90 text = new
91 applying = true
92 configProblems = UserConfig.apply(new, to: defaults)
93 applying = false
94 readTheme()
95 }
96
97 /// The theme from the file read last and its theme file.
98 func readTheme() {
99 guard let text, let tables = try? TOML.parse(text) else { return }
100 var spec = ThemeSpec.default
101 var themeProblems: [String] = []
102 if let name = defaults.string(forKey: "themeFile"), !name.isEmpty {
103 let file = url.deletingLastPathComponent().appendingPathComponent(name)
104 if let themeText = try? String(contentsOf: file, encoding: .utf8) {
105 do {
106 (spec, themeProblems) = ThemeSpec.reading(try TOML.parse(themeText), file: name)
107 } catch {
108 themeProblems.append("\(name): \(error)")
109 }
110 } else {
111 themeProblems.append("config.toml: theme-file \(name) can't be read")
112 }
113 }
114 let (merged, more) = ThemeSpec.reading(tables, over: spec)
115 if merged != theme { theme = merged }
116 problems = configProblems + themeProblems + more
117 }
118
119 /// Writes settings that differ from the file into it.
120 func writeBack() {
121 guard !applying, var current = text ?? (try? String(contentsOf: url, encoding: .utf8)) else { return }
122 let values = UserConfig.values(in: current)
123 let original = current
124 for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil {
125 let value = UserConfig.value(setting, in: defaults)
126 if values[setting.path] != value {
127 current = UserConfig.setting(current, section: setting.section, key: setting.key, to: value)
128 }
129 }
130 guard current != original else { return }
131 text = current
132 try? current.write(to: url, atomically: true, encoding: .utf8)
133 }
134}
135#endif