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