Sources/OrgApp/WorkspaceModel.swift

213799f3f0792831bdbd707d1f85cb19b614f39f
orgstar/Sources/OrgApp/WorkspaceModel.swift

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