Sources/OrgApp/WorkspaceModel.swift

fcb63f5b7ba2983a61307124d831d8093a15a186
orgstar/Sources/OrgApp/WorkspaceModel.swift

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