Sources/OrgApp/ConfigSync.swift

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