Sources/OrgApp/WorkspaceModel.swift

411 lines · 18286 bytes

  1import Foundation
  2import Observation
  3import OrgDocument
  4import OrgPresentation
  5import OrgCore
  6import OrgIndex
  7import OrgWorkspace
  8
  9/// The folders the user added, the index over them, and the queries the window runs.
 10@MainActor
 11@Observable
 12public final class WorkspaceModel {
 13    public private(set) var roots: [WorkspaceRoot] = []
 14    public private(set) var files: [FileEntry] = []
 15    /// iCloud files asked to download and not indexed yet, by path.
 16    public private(set) var downloading: Set<String> = []
 17    public private(set) var isIndexing = false
 18    /// The last error worth showing, such as a folder that can no longer be found.
 19    public var lastError: String?
 20    /// Bumped when an indexed file changes on disk, with its path.
 21    public private(set) var changedFile: (path: String, version: Int)?
 22
 23    public let index: IndexStore
 24    /// A change (other TODO keywords) reindexes the files it affects.
 25    public var settings: IndexSettings {
 26        didSet {
 27            guard settings.version != oldValue.version else { return }
 28            Task { await refresh() }
 29        }
 30    }
 31    private let rootsFile: URL
 32    /// Resolved root folders, keyed by their resolved path, which is how the index stores them.
 33    private var resolvedRoots: [String: URL] = [:]
 34    @ObservationIgnored private var watcher: AnyObject?
 35    /// Watchers of the roots where there are no FSEvents.
 36    @ObservationIgnored private var presenters: [FolderPresenter] = []
 37    /// Set once watching starts, so adding or removing a root watches the new set.
 38    @ObservationIgnored private var watching = false
 39    private var changeVersion = 0
 40    @ObservationIgnored private var overlayCache: (text: String, record: FileRecord)?
 41
 42    /// `directory` holds the index and the list of roots; nil keeps both in memory.
 43    public init(directory: URL?, settings: IndexSettings = IndexSettings()) throws {
 44        self.settings = settings
 45        if let directory {
 46            try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
 47            index = try IndexStore(path: directory.appendingPathComponent("index.sqlite").path)
 48            rootsFile = directory.appendingPathComponent("roots.json")
 49        } else {
 50            index = try IndexStore()
 51            rootsFile = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roots-\(UUID().uuidString).json")
 52        }
 53        if let data = try? Data(contentsOf: rootsFile), let saved = try? JSONDecoder().decode([WorkspaceRoot].self, from: data) {
 54            roots = saved
 55        }
 56        resolveRoots()
 57        try reloadFiles()
 58        // `remote()` in table formulas reaches tables in other files by ID.
 59        let index = index
 60        RemoteTables.fileWithID = { (id: String) -> String? in
 61            guard let path = (try? index.headings(withID: id))?.first?.path else { return nil }
 62            return FileManager.default.contents(atPath: path).map { SourceText(bytes: [UInt8]($0)).text }
 63        }
 64    }
 65
 66    /// `~/Library/Application Support/Orgstar`, or `ORGSTAR_DATA_DIR` when set (for development).
 67    public static var defaultDirectory: URL {
 68        if let override = ProcessInfo.processInfo.environment["ORGSTAR_DATA_DIR"] {
 69            return URL(fileURLWithPath: override)
 70        }
 71        return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Orgstar")
 72    }
 73
 74    // MARK: - Roots
 75
 76    public func addRoot(_ url: URL) async throws {
 77        let root = try WorkspaceRoot(url: url)
 78        // A folder already added, perhaps since moved: its bookmark resolves to it.
 79        guard !roots.contains(where: { $0.path == root.path }), resolvedRoots[root.path] == nil else { return }
 80        roots.append(root)
 81        try saveRoots()
 82        resolveRoots()
 83        rootsChanged()
 84        await refresh()
 85    }
 86
 87    /// Removes a root by its resolved path, as `FileEntry.root` gives it.
 88    public func removeRoot(path: String) throws {
 89        let bookmarkPaths = roots.filter { (try? $0.resolve().url.path) == path || $0.path == path }.map(\.path)
 90        roots.removeAll { bookmarkPaths.contains($0.path) }
 91        try saveRoots()
 92        resolveRoots()
 93        rootsChanged()
 94        var change = IndexChange()
 95        change.removals = files.filter { $0.root == path }.map(\.path)
 96        try index.apply(change)
 97        try reloadFiles()
 98    }
 99
100    private func rootsChanged() {
101        if watching { startWatching() }
102    }
103
104    private func saveRoots() throws {
105        try JSONEncoder().encode(roots).write(to: rootsFile, options: .atomic)
106    }
107
108    /// Resolves bookmarks; refreshes stale ones; reports folders that can't be found.
109    private func resolveRoots() {
110        resolvedRoots = [:]
111        var refreshed = roots
112        for (i, root) in roots.enumerated() {
113            guard let (url, isStale) = try? root.resolve() else {
114                lastError = "Can't find the folder \(root.path)."
115                continue
116            }
117            if isStale, let fresh = try? WorkspaceRoot(url: url) { refreshed[i] = fresh }
118            resolvedRoots[url.path] = url
119        }
120        if refreshed != roots {
121            roots = refreshed
122            try? saveRoots()
123        }
124    }
125
126    public func url(forRoot path: String) -> URL? { resolvedRoots[path] }
127
128    /// Resolved root paths, sorted.
129    public var rootPaths: [String] { resolvedRoots.keys.sorted() }
130
131    // MARK: - Indexing
132
133    /// Which files the folders show; a change rescans them.
134    public var scanRules = ScanRules() {
135        didSet {
136            guard scanRules != oldValue else { return }
137            Task { await refresh() }
138        }
139    }
140
141    /// Reconciles every root off the main thread, then reloads the file list. A call while a
142    /// refresh runs waits for it and one more pass, which covers every such call.
143    public func refresh() async {
144        if let refreshing {
145            refreshAgain = true
146            return await refreshing.value
147        }
148        let task = Task {
149            repeat {
150                refreshAgain = false
151                await refreshOnce()
152            } while refreshAgain
153        }
154        refreshing = task
155        await task.value
156        refreshing = nil
157    }
158
159    @ObservationIgnored private var refreshing: Task<Void, Never>?
160    @ObservationIgnored private var refreshAgain = false
161
162    private func refreshOnce() async {
163        let interval = Perf.begin("workspace.refresh")
164        defer { interval.end() }
165        isIndexing = true
166        defer { isIndexing = false }
167        let reconciler = Reconciler(index: index, settings: settings, rules: scanRules)
168        var pending: Set<String> = []
169        for url in resolvedRoots.values {
170            do {
171                let report = try await Task.detached { try reconciler.reconcile(root: url) }.value
172                pending.formUnion(report.placeholders.map(\.path))
173            } catch {
174                lastError = "Indexing \(url.path) failed: \(error.localizedDescription)"
175            }
176        }
177        // Rows of folders that moved or went away (indexed under their old paths).
178        let current = Array(resolvedRoots.keys)
179        if let indexed = try? index.files() {
180            var change = IndexChange()
181            change.removals = indexed.map(\.path).filter { path in !current.contains { path.hasPrefix($0 + "/") } }
182            if !change.removals.isEmpty { try? index.apply(change) }
183        }
184        try? reloadFiles()
185        setDownloading(pending)
186    }
187
188    /// Pending downloads, less the ones that have arrived and been indexed.
189    private func setDownloading(_ pending: Set<String>) {
190        let still = pending.subtracting(files.map(\.path))
191        if still != downloading { downloading = still }
192    }
193
194    private func reloadFiles() throws {
195        let roots = Set(resolvedRoots.keys)
196        files = try index.files().compactMap { file in
197            guard let root = roots.first(where: { file.path.hasPrefix($0 + "/") }) else { return nil }
198            return FileEntry(path: file.path, root: root, kind: file.kind)
199        }
200    }
201
202    /// Reconciles the paths a batch of file events named, or whole roots when events were lost.
203    public func filesChanged(_ paths: [URL], rescan roots: [URL]) async {
204        let reconciler = Reconciler(index: index, settings: settings, rules: scanRules)
205        var pending = downloading
206        for rootURL in roots {
207            let report = try? await Task.detached { try reconciler.reconcile(root: rootURL) }.value
208            pending = pending.filter { !$0.hasPrefix(rootURL.path + "/") }.union(report?.placeholders.map(\.path) ?? [])
209        }
210        for (rootPath, rootURL) in resolvedRoots where !roots.contains(rootURL) {
211            let inRoot = paths.filter { $0.path.hasPrefix(rootPath + "/") }
212            guard !inRoot.isEmpty else { continue }
213            let report = try? await Task.detached { try reconciler.reconcile(root: rootURL, paths: inRoot) }.value
214            pending.formUnion(report?.placeholders.map(\.path) ?? [])
215        }
216        try? reloadFiles()
217        setDownloading(pending)
218        for path in paths {
219            changeVersion += 1
220            changedFile = (path.standardizedFileURL.path, changeVersion)
221        }
222    }
223
224    #if os(macOS)
225    /// Watches every root, including roots added later; changes reconcile the index and are
226    /// reported through `changedFile`.
227    public func startWatching() {
228        watching = true
229        (watcher as? FSEventsWatcher)?.stop()
230        watcher = nil
231        let roots = Array(resolvedRoots.values)
232        guard !roots.isEmpty else { return }
233        let fsWatcher = FSEventsWatcher(roots: roots.map { $0.resolvingSymlinksInPath() }) { [weak self] events in
234            var changed: [URL] = []
235            var rescans: [URL] = []
236            for event in events {
237                switch event {
238                case .changed(let url): changed.append(url)
239                case .rescan(let url): rescans.append(url)
240                }
241            }
242            Task { @MainActor [weak self] in
243                guard let self else { return }
244                await self.filesChanged(changed.map(self.indexForm), rescan: rescans.compactMap(self.root(containing:)))
245            }
246        }
247        fsWatcher.start()
248        watcher = fsWatcher
249    }
250    #else
251    /// Watches every root through file presenters; changes reconcile the index and are
252    /// reported through `changedFile`.
253    public func startWatching() {
254        watching = true
255        presenters.forEach { $0.stop() }
256        presenters = resolvedRoots.values.map { root in
257            FolderPresenter(root: root) { [weak self] events in
258                Task { @MainActor [weak self] in
259                    guard let self else { return }
260                    var changed: [URL] = []
261                    var rescans: [URL] = []
262                    for event in events {
263                        switch event {
264                        case .changed(let url): changed.append(url)
265                        case .rescan(let url): rescans.append(url)
266                        }
267                    }
268                    await self.filesChanged(changed, rescan: rescans.compactMap(self.root(containing:)))
269                }
270            }
271        }
272        presenters.forEach { $0.start() }
273    }
274    #endif
275
276    /// The root an event path belongs to.
277    private func root(containing url: URL) -> URL? {
278        resolvedRoots.values.first { url.path.hasPrefix($0.resolvingSymlinksInPath().path) || url.path.hasPrefix($0.path) }
279    }
280
281    /// FSEvents reports real paths (`/private/var/...`); the index uses the root's own form.
282    func indexForm(_ url: URL) -> URL {
283        for root in resolvedRoots.values {
284            let real = root.resolvingSymlinksInPath().path
285            if real != root.path, url.path.hasPrefix(real + "/") {
286                return URL(fileURLWithPath: root.path + url.path.dropFirst(real.count))
287            }
288        }
289        return url
290    }
291
292    // MARK: - Files
293
294    public struct FileError: LocalizedError {
295        public let message: String
296        public var errorDescription: String? { message }
297        public init(message: String) { self.message = message }
298    }
299
300    /// Creates an empty file at `name` (a name or a relative path; `.org` is added when it has
301    /// no extension) inside `folder`, which must be in a root. Returns its path.
302    public func createFile(named name: String, in folder: String) async throws -> String {
303        let trimmed = name.trimmingCharacters(in: .whitespaces)
304        guard !trimmed.isEmpty, !trimmed.hasPrefix("/"), !trimmed.split(separator: "/").contains(where: { $0 == ".." }) else {
305            throw FileError(message: "Not a file name: \(name)")
306        }
307        var url = URL(fileURLWithPath: folder).appendingPathComponent(trimmed)
308        if url.pathExtension.isEmpty { url.appendPathExtension("org") }
309        guard rootURL(containing: url.path) != nil else { throw FileError(message: "\(folder) isn't in a folder you added.") }
310        guard !FileManager.default.fileExists(atPath: url.path) else { throw FileError(message: "\(url.lastPathComponent) already exists.") }
311        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
312        try Data().write(to: url, options: .withoutOverwriting)
313        await rescan(containing: url.path)
314        return url.standardizedFileURL.path
315    }
316
317    /// Renames a file or folder in place. Returns the new path.
318    public func rename(_ path: String, to name: String) async throws -> String {
319        let trimmed = name.trimmingCharacters(in: .whitespaces)
320        guard !trimmed.isEmpty, !trimmed.contains("/"), trimmed != ".", trimmed != ".." else {
321            throw FileError(message: "Not a file name: \(name)")
322        }
323        let target = URL(fileURLWithPath: path).deletingLastPathComponent().appendingPathComponent(trimmed)
324        guard target.path != path else { return path }
325        guard !FileManager.default.fileExists(atPath: target.path) else { throw FileError(message: "\(trimmed) already exists.") }
326        try FileManager.default.moveItem(atPath: path, toPath: target.path)
327        await rescan(containing: path)
328        return target.standardizedFileURL.path
329    }
330
331    /// How `trash` disposes of a file; tests replace it so nothing reaches the real Trash.
332    @ObservationIgnored public var trasher: @Sendable (URL) throws -> Void = { url in
333        try FileManager.default.trashItem(at: url, resultingItemURL: nil)
334    }
335
336    /// Moves a file or folder to the Trash.
337    public func trash(_ path: String) async throws {
338        try trasher(URL(fileURLWithPath: path))
339        await rescan(containing: path)
340    }
341
342    private func rootURL(containing path: String) -> URL? {
343        resolvedRoots.first { path == $0.key || path.hasPrefix($0.key + "/") }?.value
344    }
345
346    /// Brings the index up to date for the root holding `path` now, rather than when the
347    /// file events arrive.
348    private func rescan(containing path: String) async {
349        let interval = Perf.begin("workspace.rescan")
350        defer { interval.end() }
351        guard let root = rootURL(containing: path) else { return }
352        await filesChanged([], rescan: [root])
353    }
354
355    // MARK: - Queries
356
357    public func tree(forRoot path: String) -> FileTreeNode {
358        FileTreeNode.build(root: path, files: files, downloading: downloading.sorted())
359    }
360
361    /// Headings with links to `target`, the target heading's own links left out, each with
362    /// the line its link is on as its snippet.
363    public func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
364        var seen = Set<HeadingLocation>()
365        return ((try? index.links(overlay: overlay)) ?? []).compactMap { link in
366            guard !(link.source.path == target.path && link.source.start == start),
367                  Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil }
368            var source = link.source
369            if let text = try? index.text(of: source, overlay: overlay), let context = Backlinks.context(in: text, link: link.target) {
370                source.snippet = Snippet(text: context.text, matches: [context.link])
371            }
372            return source
373        }
374    }
375
376    /// Headings and files with IDs (org-roam's nodes).
377    public func nodes(overlay: [String: FileRecord] = [:]) -> [IndexStore.Node] {
378        (try? index.nodes(overlay: overlay)) ?? []
379    }
380
381    public func search(_ query: String, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
382        (try? index.search(query, overlay: overlay)) ?? []
383    }
384
385    /// Index rows for an open file's unsaved text, keyed by path, for queries to use in place
386    /// of its rows on disk. Empty when the file has no unsaved edits. Cached until the text
387    /// changes.
388    /// Index records for open buffers with unsaved edits, so search sees what they hold.
389    public func overlay(_ documents: [(path: String, document: DocumentState)]) -> [String: FileRecord] {
390        var result: [String: FileRecord] = [:]
391        for (path, document) in documents where document.isDirty {
392            result.merge(overlay(path: path, document: document)) { a, _ in a }
393        }
394        return result
395    }
396
397    public func overlay(path: String?, document: DocumentState?) -> [String: FileRecord] {
398        guard let path, let document, document.isDirty, let bytes = try? document.encodedText(),
399              let entry = files.first(where: { $0.path == path }) else { return [:] }
400        if let cached = overlayCache, cached.record.path == path, cached.text == document.text {
401            return [path: cached.record]
402        }
403        let record = FileRecord(path: path, root: entry.root, kind: entry.kind, bytes: bytes, mtime: Date().timeIntervalSince1970, settings: settings)
404        overlayCache = (document.text, record)
405        return [path: record]
406    }
407
408    public func quickOpen(_ query: String) -> [FileEntry] {
409        FuzzyMatch.rank(query, files.filter { $0.kind != .conflict })
410    }
411}