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