Sources/OrgApp/WorkspaceModel.swift

3959d9c38d34f2d30757a8c9c88309a5328522e5
orgstar/Sources/OrgApp/WorkspaceModel.swift history · blame · raw

322 lines · 14607 bytes

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