Sources/OrgApp/WorkspaceModel.swift

2b4bbb38252d0a3d7b97adde900413f734f0506b
orgstar/Sources/OrgApp/WorkspaceModel.swift

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