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