Sources/OrgApp/ConfigSync.swift

design-themes-widgets
orgstar/Sources/OrgApp/ConfigSync.swift history · blame · raw

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