Sources/OrgApp/ConfigSync.swift

147 lines · 7480 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    /// Where `url` leads: a symlinked config.toml is written through, not replaced by a file.
 33    private var target: URL { url.resolvingSymlinksInPath() }
 34
 35    public init(url: URL = UserConfig.configFile, defaults: UserDefaults = .standard) {
 36        self.url = url
 37        self.defaults = defaults
 38    }
 39
 40    public func start(watch: Bool = true) {
 41        guard observer == nil else { return }
 42        try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
 43        let reference = url.deletingLastPathComponent().appendingPathComponent("default-theme.toml")
 44        if (try? String(contentsOf: reference, encoding: .utf8)) != ThemeSpec.defaultThemeFile() {
 45            try? ThemeSpec.defaultThemeFile().write(to: reference, atomically: true, encoding: .utf8)
 46        }
 47        if FileManager.default.fileExists(atPath: url.path) {
 48            reload()
 49            // A file from before settings took Emacs's names gets them in place; one from
 50            // before a section existed gets the section.
 51            if let text {
 52                let migrated = UserConfig.usesLegacyNames(text) ? UserConfig.migratingLegacyNames(text) : text
 53                let completed = UserConfig.addingMissingSections(migrated, from: defaults)
 54                if completed != text {
 55                    try? completed.write(to: target, atomically: true, encoding: .utf8)
 56                    self.text = completed
 57                }
 58            }
 59        } else {
 60            let template = UserConfig.template(from: defaults)
 61            try? template.write(to: target, 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().resolvingSymlinksInPath()
 69        // The linked file's folder too, when config.toml is a symlink.
 70        let linked = target.deletingLastPathComponent().resolvingSymlinksInPath()
 71        let watchesLinked = linked.path != directory.path
 72        // Files still read from where earlier versions kept them reload when edited there too.
 73        let legacy = UserConfig.legacyDirectory.resolvingSymlinksInPath()
 74        let watchesLegacy = legacy.path != directory.path && FileManager.default.fileExists(atPath: legacy.path)
 75        watcher = FSEventsWatcher(roots: [directory] + (watchesLinked ? [linked] : []) + (watchesLegacy ? [legacy] : [])) { [weak self] events in
 76            let changed = Set(events.compactMap { event -> URL? in
 77                if case .changed(let url) = event { return url }
 78                return nil
 79            })
 80            Task { @MainActor [weak self] in
 81                guard let self else { return }
 82                for file in changed.sorted(by: { $0.path < $1.path }) {
 83                    if !file.path.hasPrefix(directory.path + "/"),
 84                       UserConfig.file(file.lastPathComponent).resolvingSymlinksInPath().path != file.resolvingSymlinksInPath().path { continue }
 85                    let name = file.lastPathComponent
 86                    if name == self.url.lastPathComponent { self.reload() }
 87                    if self.isThemeFile(file) { self.readTheme() }
 88                    self.serial += 1
 89                    self.changedFile = (name, self.serial)
 90                }
 91            }
 92        }
 93        watcher?.start()
 94    }
 95
 96    /// Reads the file and applies it when it changed since the last read or write.
 97    public func reload() {
 98        guard let new = try? String(contentsOf: url, encoding: .utf8), new != text else { return }
 99        text = new
100        applying = true
101        configProblems = UserConfig.apply(new, to: defaults)
102        applying = false
103        readTheme()
104    }
105
106    /// `theme-file`, relative to the configuration folder.
107    private var themeFile: URL? {
108        guard let name = defaults.string(forKey: "themeFile"), !name.isEmpty else { return nil }
109        return url.deletingLastPathComponent().appendingPathComponent(name)
110    }
111
112    /// Whether `file`, as the watcher reports it, is `theme-file`, which may be in a subfolder.
113    func isThemeFile(_ file: URL) -> Bool {
114        themeFile?.resolvingSymlinksInPath().path == file.resolvingSymlinksInPath().path
115    }
116
117    /// The theme from the file read last and its theme file.
118    func readTheme() {
119        guard let text, let read = UserConfig.theme(
120            config: text, themeFile: defaults.string(forKey: "themeFile"), in: url.deletingLastPathComponent()
121        ) else { return }
122        if read.theme != theme { theme = read.theme }
123        problems = configProblems + read.problems
124    }
125
126    /// Writes settings that differ from the file into it.
127    func writeBack() {
128        // The file as it is now, so that tables written into it since, as by Emacs import, stay.
129        guard !applying, var current = (try? String(contentsOf: url, encoding: .utf8)) ?? text else { return }
130        let values = UserConfig.values(in: current)
131        let original = current
132        for setting in UserConfig.settings where defaults.object(forKey: setting.defaultsKey) != nil {
133            let value = UserConfig.value(setting, in: defaults)
134            if values[setting.path] != value {
135                current = UserConfig.setting(current, section: setting.section, key: setting.key, to: value)
136            }
137        }
138        // Templates added in the app, as by Emacs import; removing one is done in the file.
139        for template in UserConfig.structureTemplates(defaults) where values[UserConfig.path(UserConfig.structureTemplateTable, template.key)] != .string(template.type) {
140            current = UserConfig.setting(current, section: UserConfig.structureTemplateTable, key: template.key, to: .string(template.type))
141        }
142        guard current != original else { return }
143        text = current
144        try? current.write(to: target, atomically: true, encoding: .utf8)
145    }
146}
147#endif