Sources/OrgApp/WorkspaceModel.swift

493 lines · 22631 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    /// Roots whose bookmark doesn't resolve: a folder gone, on a volume not mounted, or out of
 35    /// the sandbox's reach.
 36    public private(set) var unresolvedRoots: [WorkspaceRoot] = []
 37    @ObservationIgnored private var watcher: AnyObject?
 38    /// Watchers of the roots where there are no FSEvents.
 39    @ObservationIgnored private var presenters: [FolderPresenter] = []
 40    /// Set once watching starts, so adding or removing a root watches the new set.
 41    @ObservationIgnored private var watching = false
 42    private var changeVersion = 0
 43    @ObservationIgnored private var overlayCache: (text: String, record: FileRecord)?
 44
 45    /// `directory` holds the index and the list of roots; nil keeps both in memory.
 46    public init(directory: URL?, settings: IndexSettings = IndexSettings()) throws {
 47        self.settings = settings
 48        if let directory {
 49            try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
 50            index = try IndexStore(path: directory.appendingPathComponent("index.sqlite").path)
 51            rootsFile = directory.appendingPathComponent("roots.json")
 52        } else {
 53            index = try IndexStore()
 54            rootsFile = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roots-\(UUID().uuidString).json")
 55        }
 56        if let data = try? Data(contentsOf: rootsFile), let saved = try? JSONDecoder().decode([WorkspaceRoot].self, from: data) {
 57            roots = saved
 58        }
 59        resolveRoots()
 60        try reloadFiles()
 61        // `remote()` in table formulas reaches tables in other files by ID.
 62        let index = index
 63        RemoteTables.fileWithID = { (id: String) -> String? in
 64            guard let path = (try? index.headings(withID: id))?.first?.path else { return nil }
 65            return FileManager.default.contents(atPath: path).map { SourceText(bytes: [UInt8]($0)).text }
 66        }
 67        #if canImport(JavaScriptCore)
 68        // `org-sbe` in table formulas runs js blocks in JavaScriptCore.
 69        TableBlocks.javaScript = { try JavaScriptBlocks.runHere($0) }
 70        #endif
 71    }
 72
 73    /// `~/Library/Application Support/Orgstar`, or `ORGSTAR_DATA_DIR` when set (for development).
 74    public nonisolated static var defaultDirectory: URL {
 75        if let override = ProcessInfo.processInfo.environment["ORGSTAR_DATA_DIR"] {
 76            return URL(fileURLWithPath: override)
 77        }
 78        return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Orgstar")
 79    }
 80
 81    /// The resolved paths of the roots saved in `directory`, without opening the index: for
 82    /// App Intents, which may run before the app's models.
 83    public nonisolated static func savedRootPaths(in directory: URL = defaultDirectory) -> [String] {
 84        guard let data = try? Data(contentsOf: directory.appendingPathComponent("roots.json")),
 85              let roots = try? JSONDecoder().decode([WorkspaceRoot].self, from: data) else { return [] }
 86        return roots.compactMap { try? $0.resolve().url.path }.sorted()
 87    }
 88
 89    // MARK: - Roots
 90
 91    public func addRoot(_ url: URL) async throws {
 92        let root = try WorkspaceRoot(url: url)
 93        // A folder already added, perhaps since moved: its bookmark resolves to it.
 94        guard !roots.contains(where: { $0.path == root.path }), resolvedRoots[root.path] == nil else { return }
 95        roots.append(root)
 96        try saveRoots()
 97        resolveRoots()
 98        rootsChanged()
 99        await refresh()
100    }
101
102    /// Replaces `root`, one that doesn't resolve, with `url`, chosen again in an open panel.
103    public func regrant(_ root: WorkspaceRoot, with url: URL) async throws {
104        let fresh = try WorkspaceRoot(url: url)
105        roots.removeAll { $0 == root }
106        if !roots.contains(where: { $0.path == fresh.path }), resolvedRoots[fresh.path] == nil { roots.append(fresh) }
107        try saveRoots()
108        resolveRoots()
109        rootsChanged()
110        await refresh()
111    }
112
113    /// Removes a root by its resolved path, as `FileEntry.root` gives it.
114    public func removeRoot(path: String) throws {
115        let bookmarkPaths = roots.filter { (try? $0.resolve().url.path) == path || $0.path == path }.map(\.path)
116        roots.removeAll { bookmarkPaths.contains($0.path) }
117        try saveRoots()
118        resolveRoots()
119        rootsChanged()
120        var change = IndexChange()
121        change.removals = files.filter { $0.root == path }.map(\.path)
122        try index.apply(change)
123        try reloadFiles()
124    }
125
126    private func rootsChanged() {
127        if watching { startWatching() }
128    }
129
130    private func saveRoots() throws {
131        try JSONEncoder().encode(roots).write(to: rootsFile, options: .atomic)
132    }
133
134    /// Resolves bookmarks; refreshes stale ones; reports folders that can't be found.
135    private func resolveRoots() {
136        resolvedRoots = [:]
137        unresolvedRoots = []
138        var refreshed = roots
139        for (i, root) in roots.enumerated() {
140            guard let (url, isStale) = try? root.resolve() else {
141                lastError = "Can't find the folder \(root.path)."
142                unresolvedRoots.append(root)
143                continue
144            }
145            if isStale, let fresh = try? WorkspaceRoot(url: url) { refreshed[i] = fresh }
146            resolvedRoots[url.path] = url
147        }
148        if refreshed != roots {
149            roots = refreshed
150            try? saveRoots()
151        }
152    }
153
154    public func url(forRoot path: String) -> URL? { resolvedRoots[path] }
155
156    /// Resolved root paths, sorted.
157    public var rootPaths: [String] { resolvedRoots.keys.sorted() }
158
159    /// Whether `url` is a root or a granted folder, or inside one.
160    public func contains(_ url: URL) -> Bool {
161        Self.isInside(url, roots: Array(resolvedRoots.values) + FolderGrants.shared.folders)
162    }
163
164    /// The folders to ask for so that `paths` can be read and written: in the Mac sandbox, for
165    /// each path outside the roots, the grants and the app's container, its nearest existing
166    /// folder. `directories` takes the paths as folders rather than files. Empty unsandboxed.
167    public func foldersToGrant(for paths: [String], directories: Bool = false) -> [URL] {
168        guard Sandbox.isActive else { return [] }
169        let reachable = Array(resolvedRoots.values) + FolderGrants.shared.folders + [URL(fileURLWithPath: NSHomeDirectory())]
170            + (UserConfig.directoryOverride.map { [$0] } ?? [])
171        return Self.foldersToGrant(for: paths, directories: directories, reachable: reachable)
172    }
173
174    /// Whether the file at `path` is there to be read, for all the read failed: missing files
175    /// aren't worth asking for access to.
176    public nonisolated static func isThere(_ path: String) -> Bool {
177        do {
178            _ = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
179            return true
180        } catch let error as NSError {
181            return !(error.domain == NSCocoaErrorDomain && error.code == NSFileReadNoSuchFileError)
182        }
183    }
184
185    nonisolated static func foldersToGrant(
186        for paths: [String], directories: Bool, reachable: [URL],
187        exists: (String) -> Bool = { FileManager.default.fileExists(atPath: $0) }
188    ) -> [URL] {
189        var folders: [URL] = []
190        for path in paths where !path.isEmpty {
191            let url = URL(fileURLWithPath: path).standardizedFileURL
192            guard !isInside(url, roots: reachable) else { continue }
193            var folder = directories ? url : url.deletingLastPathComponent()
194            while folder.pathComponents.count > 1, !exists(folder.path) { folder.deleteLastPathComponent() }
195            if !folders.contains(folder) { folders.append(folder) }
196        }
197        return folders
198    }
199
200    /// Whether `url` is one of `roots` or inside one, by whole path components, as written or
201    /// with symbolic links resolved.
202    nonisolated static func isInside(_ url: URL, roots: [URL]) -> Bool {
203        func forms(_ url: URL) -> [[String]] {
204            let standard = url.standardizedFileURL
205            return [standard.pathComponents, standard.resolvingSymlinksInPath().pathComponents]
206        }
207        let paths = forms(url)
208        return roots.flatMap(forms).contains { root in
209            paths.contains { $0.count >= root.count && Array($0.prefix(root.count)) == root }
210        }
211    }
212
213    // MARK: - Indexing
214
215    /// Which files the folders show; a change rescans them.
216    public var scanRules = ScanRules() {
217        didSet {
218            guard scanRules != oldValue else { return }
219            Task { await refresh() }
220        }
221    }
222
223    /// Reconciles every root off the main thread, then reloads the file list. A call while a
224    /// refresh runs waits for it and one more pass, which covers every such call.
225    public func refresh() async {
226        if let refreshing {
227            refreshAgain = true
228            return await refreshing.value
229        }
230        let task = Task {
231            repeat {
232                refreshAgain = false
233                await refreshOnce()
234            } while refreshAgain
235        }
236        refreshing = task
237        await task.value
238        refreshing = nil
239    }
240
241    @ObservationIgnored private var refreshing: Task<Void, Never>?
242    @ObservationIgnored private var refreshAgain = false
243
244    private func refreshOnce() async {
245        let interval = Perf.begin("workspace.refresh")
246        defer { interval.end() }
247        isIndexing = true
248        defer { isIndexing = false }
249        let reconciler = Reconciler(index: index, settings: settings, rules: scanRules)
250        var pending: Set<String> = []
251        for url in resolvedRoots.values {
252            do {
253                let report = try await Task.detached { try reconciler.reconcile(root: url) }.value
254                pending.formUnion(report.placeholders.map(\.path))
255            } catch {
256                lastError = "Indexing \(url.path) failed: \(error.localizedDescription)"
257            }
258        }
259        // Rows of folders that moved or went away (indexed under their old paths).
260        let current = Array(resolvedRoots.keys)
261        if let indexed = try? index.files() {
262            var change = IndexChange()
263            change.removals = indexed.map(\.path).filter { path in !current.contains { path.hasPrefix($0 + "/") } }
264            if !change.removals.isEmpty { try? index.apply(change) }
265        }
266        try? reloadFiles()
267        setDownloading(pending)
268    }
269
270    /// Pending downloads, less the ones that have arrived and been indexed.
271    private func setDownloading(_ pending: Set<String>) {
272        let still = pending.subtracting(files.map(\.path))
273        if still != downloading { downloading = still }
274    }
275
276    private func reloadFiles() throws {
277        let roots = Set(resolvedRoots.keys)
278        files = try index.files().compactMap { file in
279            guard let root = roots.first(where: { file.path.hasPrefix($0 + "/") }) else { return nil }
280            return FileEntry(path: file.path, root: root, kind: file.kind)
281        }
282    }
283
284    /// Reconciles the paths a batch of file events named, or whole roots when events were lost.
285    public func filesChanged(_ paths: [URL], rescan roots: [URL]) async {
286        let reconciler = Reconciler(index: index, settings: settings, rules: scanRules)
287        var pending = downloading
288        for rootURL in roots {
289            let report = try? await Task.detached { try reconciler.reconcile(root: rootURL) }.value
290            pending = pending.filter { !$0.hasPrefix(rootURL.path + "/") }.union(report?.placeholders.map(\.path) ?? [])
291        }
292        for (rootPath, rootURL) in resolvedRoots where !roots.contains(rootURL) {
293            let inRoot = paths.filter { $0.path.hasPrefix(rootPath + "/") }
294            guard !inRoot.isEmpty else { continue }
295            let report = try? await Task.detached { try reconciler.reconcile(root: rootURL, paths: inRoot) }.value
296            pending.formUnion(report?.placeholders.map(\.path) ?? [])
297        }
298        try? reloadFiles()
299        setDownloading(pending)
300        for path in paths {
301            changeVersion += 1
302            changedFile = (path.standardizedFileURL.path, changeVersion)
303        }
304    }
305
306    #if os(macOS)
307    /// Watches every root, including roots added later; changes reconcile the index and are
308    /// reported through `changedFile`.
309    public func startWatching() {
310        watching = true
311        (watcher as? FSEventsWatcher)?.stop()
312        watcher = nil
313        let roots = Array(resolvedRoots.values)
314        guard !roots.isEmpty else { return }
315        let fsWatcher = FSEventsWatcher(roots: roots.map { $0.resolvingSymlinksInPath() }) { [weak self] events in
316            var changed: [URL] = []
317            var rescans: [URL] = []
318            for event in events {
319                switch event {
320                case .changed(let url): changed.append(url)
321                case .rescan(let url): rescans.append(url)
322                }
323            }
324            Task { @MainActor [weak self] in
325                guard let self else { return }
326                await self.filesChanged(changed.map(self.indexForm), rescan: rescans.compactMap(self.root(containing:)))
327            }
328        }
329        fsWatcher.start()
330        watcher = fsWatcher
331    }
332    #else
333    /// Watches every root through file presenters; changes reconcile the index and are
334    /// reported through `changedFile`.
335    public func startWatching() {
336        watching = true
337        presenters.forEach { $0.stop() }
338        presenters = resolvedRoots.values.map { root in
339            FolderPresenter(root: root) { [weak self] events in
340                Task { @MainActor [weak self] in
341                    guard let self else { return }
342                    var changed: [URL] = []
343                    var rescans: [URL] = []
344                    for event in events {
345                        switch event {
346                        case .changed(let url): changed.append(url)
347                        case .rescan(let url): rescans.append(url)
348                        }
349                    }
350                    await self.filesChanged(changed, rescan: rescans.compactMap(self.root(containing:)))
351                }
352            }
353        }
354        presenters.forEach { $0.start() }
355    }
356    #endif
357
358    /// The root an event path belongs to.
359    private func root(containing url: URL) -> URL? {
360        resolvedRoots.values.first { url.path.hasPrefix($0.resolvingSymlinksInPath().path) || url.path.hasPrefix($0.path) }
361    }
362
363    /// FSEvents reports real paths (`/private/var/...`); the index uses the root's own form.
364    func indexForm(_ url: URL) -> URL {
365        for root in resolvedRoots.values {
366            let real = root.resolvingSymlinksInPath().path
367            if real != root.path, url.path.hasPrefix(real + "/") {
368                return URL(fileURLWithPath: root.path + url.path.dropFirst(real.count))
369            }
370        }
371        return url
372    }
373
374    // MARK: - Files
375
376    public struct FileError: LocalizedError {
377        public let message: String
378        public var errorDescription: String? { message }
379        public init(message: String) { self.message = message }
380    }
381
382    /// Creates an empty file at `name` (a name or a relative path; `.org` is added when it has
383    /// no extension) inside `folder`, which must be in a root. Returns its path.
384    public func createFile(named name: String, in folder: String) async throws -> String {
385        let trimmed = name.trimmingCharacters(in: .whitespaces)
386        guard !trimmed.isEmpty, !trimmed.hasPrefix("/"), !trimmed.split(separator: "/").contains(where: { $0 == ".." }) else {
387            throw FileError(message: "Not a file name: \(name)")
388        }
389        var url = URL(fileURLWithPath: folder).appendingPathComponent(trimmed)
390        if url.pathExtension.isEmpty { url.appendPathExtension("org") }
391        guard rootURL(containing: url.path) != nil else { throw FileError(message: "\(folder) isn't in a folder you added.") }
392        guard !FileManager.default.fileExists(atPath: url.path) else { throw FileError(message: "\(url.lastPathComponent) already exists.") }
393        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
394        try Data().write(to: url, options: .withoutOverwriting)
395        await rescan(containing: url.path)
396        return url.standardizedFileURL.path
397    }
398
399    /// Renames a file or folder in place. Returns the new path.
400    public func rename(_ path: String, to name: String) async throws -> String {
401        let trimmed = name.trimmingCharacters(in: .whitespaces)
402        guard !trimmed.isEmpty, !trimmed.contains("/"), trimmed != ".", trimmed != ".." else {
403            throw FileError(message: "Not a file name: \(name)")
404        }
405        let target = URL(fileURLWithPath: path).deletingLastPathComponent().appendingPathComponent(trimmed)
406        guard target.path != path else { return path }
407        guard !FileManager.default.fileExists(atPath: target.path) else { throw FileError(message: "\(trimmed) already exists.") }
408        try FileManager.default.moveItem(atPath: path, toPath: target.path)
409        await rescan(containing: path)
410        return target.standardizedFileURL.path
411    }
412
413    /// How `trash` disposes of a file; tests replace it so nothing reaches the real Trash.
414    @ObservationIgnored public var trasher: @Sendable (URL) throws -> Void = { url in
415        try FileManager.default.trashItem(at: url, resultingItemURL: nil)
416    }
417
418    /// Moves a file or folder to the Trash.
419    public func trash(_ path: String) async throws {
420        try trasher(URL(fileURLWithPath: path))
421        await rescan(containing: path)
422    }
423
424    private func rootURL(containing path: String) -> URL? {
425        resolvedRoots.first { path == $0.key || path.hasPrefix($0.key + "/") }?.value
426    }
427
428    /// Brings the index up to date for the root holding `path` now, rather than when the
429    /// file events arrive.
430    private func rescan(containing path: String) async {
431        let interval = Perf.begin("workspace.rescan")
432        defer { interval.end() }
433        guard let root = rootURL(containing: path) else { return }
434        await filesChanged([], rescan: [root])
435    }
436
437    // MARK: - Queries
438
439    public func tree(forRoot path: String) -> FileTreeNode {
440        FileTreeNode.build(root: path, files: files, downloading: downloading.sorted())
441    }
442
443    /// Headings with links to `target`, the target heading's own links left out, each with
444    /// the line its link is on as its snippet.
445    public func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
446        var seen = Set<HeadingLocation>()
447        return ((try? index.links(overlay: overlay)) ?? []).compactMap { link in
448            guard !(link.source.path == target.path && link.source.start == start),
449                  Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil }
450            var source = link.source
451            if let text = try? index.text(of: source, overlay: overlay), let context = Backlinks.context(in: text, link: link.target) {
452                source.snippet = Snippet(text: context.text, matches: [context.link])
453            }
454            return source
455        }
456    }
457
458    /// Headings and files with IDs (org-roam's nodes), or Denote's notes.
459    public func nodes(overlay: [String: FileRecord] = [:], denote: Bool = OrgPreferences.usesDenote()) -> [IndexStore.Node] {
460        (try? denote ? index.denoteNodes(overlay: overlay) : index.nodes(overlay: overlay)) ?? []
461    }
462
463    public func search(_ query: String, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
464        (try? index.search(query, overlay: overlay)) ?? []
465    }
466
467    /// Index rows for an open file's unsaved text, keyed by path, for queries to use in place
468    /// of its rows on disk. Empty when the file has no unsaved edits. Cached until the text
469    /// changes.
470    /// Index records for open buffers with unsaved edits, so search sees what they hold.
471    public func overlay(_ documents: [(path: String, document: DocumentState)]) -> [String: FileRecord] {
472        var result: [String: FileRecord] = [:]
473        for (path, document) in documents where document.isDirty {
474            result.merge(overlay(path: path, document: document)) { a, _ in a }
475        }
476        return result
477    }
478
479    public func overlay(path: String?, document: DocumentState?) -> [String: FileRecord] {
480        guard let path, let document, document.isDirty, let bytes = try? document.encodedText(),
481              let entry = files.first(where: { $0.path == path }) else { return [:] }
482        if let cached = overlayCache, cached.record.path == path, cached.text == document.text {
483            return [path: cached.record]
484        }
485        let record = FileRecord(path: path, root: entry.root, kind: entry.kind, bytes: bytes, mtime: Date().timeIntervalSince1970, settings: settings)
486        overlayCache = (document.text, record)
487        return [path: record]
488    }
489
490    public func quickOpen(_ query: String) -> [FileEntry] {
491        FuzzyMatch.rank(query, files.filter { $0.kind != .conflict })
492    }
493}