Sources/OrgApp/WorkspaceModel.swift

6e84c5315a776376ffe643f78b5b48551895d250
orgstar/Sources/OrgApp/WorkspaceModel.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form