Sources/OrgApp/WorkspaceModel.swift
513 lines · 23768 bytes
38 symbols in this file
WorkspaceModelsavedRootPathsaddRootregrantremoveRootrootsChangedsaveRootsresolveRootsurlcontainsfoldersToGrantisTherefoldersToGrantisInsideformsrefreshrefreshOncesetDownloadingreloadFilesfilesChangedstartWatchingstartWatchingrootindexFormFileErrorcreateFilerenametrashrootURLrescantreebacklinksnodessearchindexFailedoverlayoverlayquickOpen
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 var placeholders: [String] = []
293 do {
294 placeholders = try await Task.detached { try reconciler.reconcile(root: rootURL) }.value.placeholders.map(\.path)
295 } catch {
296 lastError = "Indexing \(rootURL.path) failed: \(error.localizedDescription)"
297 }
298 pending = pending.filter { !$0.hasPrefix(rootURL.path + "/") }.union(placeholders)
299 }
300 for (rootPath, rootURL) in resolvedRoots where !roots.contains(rootURL) {
301 let inRoot = paths.filter { $0.path.hasPrefix(rootPath + "/") }
302 guard !inRoot.isEmpty else { continue }
303 do {
304 let report = try await Task.detached { try reconciler.reconcile(root: rootURL, paths: inRoot) }.value
305 pending.formUnion(report.placeholders.map(\.path))
306 } catch {
307 lastError = "Indexing \(rootURL.path) failed: \(error.localizedDescription)"
308 }
309 }
310 try? reloadFiles()
311 setDownloading(pending)
312 for path in paths {
313 changeVersion += 1
314 changedFile = (path.standardizedFileURL.path, changeVersion)
315 }
316 }
317
318 #if os(macOS)
319 /// Watches every root, including roots added later; changes reconcile the index and are
320 /// reported through `changedFile`.
321 public func startWatching() {
322 watching = true
323 (watcher as? FSEventsWatcher)?.stop()
324 watcher = nil
325 let roots = Array(resolvedRoots.values)
326 guard !roots.isEmpty else { return }
327 let fsWatcher = FSEventsWatcher(roots: roots.map { $0.resolvingSymlinksInPath() }) { [weak self] events in
328 var changed: [URL] = []
329 var rescans: [URL] = []
330 for event in events {
331 switch event {
332 case .changed(let url): changed.append(url)
333 case .rescan(let url): rescans.append(url)
334 }
335 }
336 Task { @MainActor [weak self] in
337 guard let self else { return }
338 await self.filesChanged(changed.map(self.indexForm), rescan: rescans.compactMap(self.root(containing:)))
339 }
340 }
341 fsWatcher.start()
342 watcher = fsWatcher
343 }
344 #else
345 /// Watches every root through file presenters; changes reconcile the index and are
346 /// reported through `changedFile`.
347 public func startWatching() {
348 watching = true
349 presenters.forEach { $0.stop() }
350 presenters = resolvedRoots.values.map { root in
351 FolderPresenter(root: root) { [weak self] events in
352 Task { @MainActor [weak self] in
353 guard let self else { return }
354 var changed: [URL] = []
355 var rescans: [URL] = []
356 for event in events {
357 switch event {
358 case .changed(let url): changed.append(url)
359 case .rescan(let url): rescans.append(url)
360 }
361 }
362 await self.filesChanged(changed, rescan: rescans.compactMap(self.root(containing:)))
363 }
364 }
365 }
366 presenters.forEach { $0.start() }
367 }
368 #endif
369
370 /// The root an event path belongs to.
371 private func root(containing url: URL) -> URL? {
372 resolvedRoots.values.first { url.path.hasPrefix($0.resolvingSymlinksInPath().path) || url.path.hasPrefix($0.path) }
373 }
374
375 /// FSEvents reports real paths (`/private/var/...`); the index uses the root's own form.
376 func indexForm(_ url: URL) -> URL {
377 for root in resolvedRoots.values {
378 let real = root.resolvingSymlinksInPath().path
379 if real != root.path, url.path.hasPrefix(real + "/") {
380 return URL(fileURLWithPath: root.path + url.path.dropFirst(real.count))
381 }
382 }
383 return url
384 }
385
386 // MARK: - Files
387
388 public struct FileError: LocalizedError {
389 public let message: String
390 public var errorDescription: String? { message }
391 public init(message: String) { self.message = message }
392 }
393
394 /// Creates an empty file at `name` (a name or a relative path; `.org` is added when it has
395 /// no extension) inside `folder`, which must be in a root. Returns its path.
396 public func createFile(named name: String, in folder: String) async throws -> String {
397 let trimmed = name.trimmingCharacters(in: .whitespaces)
398 guard !trimmed.isEmpty, !trimmed.hasPrefix("/"), !trimmed.split(separator: "/").contains(where: { $0 == ".." }) else {
399 throw FileError(message: "Not a file name: \(name)")
400 }
401 var url = URL(fileURLWithPath: folder).appendingPathComponent(trimmed)
402 if url.pathExtension.isEmpty { url.appendPathExtension("org") }
403 guard rootURL(containing: url.path) != nil else { throw FileError(message: "\(folder) isn't in a folder you added.") }
404 guard !FileManager.default.fileExists(atPath: url.path) else { throw FileError(message: "\(url.lastPathComponent) already exists.") }
405 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
406 try Data().write(to: url, options: .withoutOverwriting)
407 await rescan(containing: url.path)
408 return url.standardizedFileURL.path
409 }
410
411 /// Renames a file or folder in place. Returns the new path.
412 public func rename(_ path: String, to name: String) async throws -> String {
413 let trimmed = name.trimmingCharacters(in: .whitespaces)
414 guard !trimmed.isEmpty, !trimmed.contains("/"), trimmed != ".", trimmed != ".." else {
415 throw FileError(message: "Not a file name: \(name)")
416 }
417 let target = URL(fileURLWithPath: path).deletingLastPathComponent().appendingPathComponent(trimmed)
418 guard target.path != path else { return path }
419 guard !FileManager.default.fileExists(atPath: target.path) else { throw FileError(message: "\(trimmed) already exists.") }
420 try FileManager.default.moveItem(atPath: path, toPath: target.path)
421 await rescan(containing: path)
422 return target.standardizedFileURL.path
423 }
424
425 /// How `trash` disposes of a file; tests replace it so nothing reaches the real Trash.
426 @ObservationIgnored public var trasher: @Sendable (URL) throws -> Void = { url in
427 try FileManager.default.trashItem(at: url, resultingItemURL: nil)
428 }
429
430 /// Moves a file or folder to the Trash.
431 public func trash(_ path: String) async throws {
432 try trasher(URL(fileURLWithPath: path))
433 await rescan(containing: path)
434 }
435
436 private func rootURL(containing path: String) -> URL? {
437 resolvedRoots.first { path == $0.key || path.hasPrefix($0.key + "/") }?.value
438 }
439
440 /// Brings the index up to date for the root holding `path` now, rather than when the
441 /// file events arrive.
442 private func rescan(containing path: String) async {
443 let interval = Perf.begin("workspace.rescan")
444 defer { interval.end() }
445 guard let root = rootURL(containing: path) else { return }
446 await filesChanged([], rescan: [root])
447 }
448
449 // MARK: - Queries
450
451 public func tree(forRoot path: String) -> FileTreeNode {
452 FileTreeNode.build(root: path, files: files, downloading: downloading.sorted())
453 }
454
455 /// Headings with links to `target`, the target heading's own links left out, each with
456 /// the line its link is on as its snippet. Reads every link in the index, so call it off
457 /// the main actor; a cancelled task gets what was found so far.
458 public nonisolated func backlinks(to target: Backlinks.Target, excluding start: Int? = nil, overlay: [String: FileRecord] = [:]) throws -> [HeadingLocation] {
459 var seen = Set<HeadingLocation>()
460 let links: [(source: HeadingLocation, target: String)]
461 do { links = try index.links(overlay: overlay) } catch { throw Self.indexFailed(error) }
462 return links.compactMap { link in
463 guard !Task.isCancelled, !(link.source.path == target.path && link.source.start == start),
464 Backlinks.links(link.target, from: link.source.path, to: target), seen.insert(link.source).inserted else { return nil }
465 var source = link.source
466 if let text = try? index.text(of: source, overlay: overlay), let context = Backlinks.context(in: text, link: link.target) {
467 source.snippet = Snippet(text: context.text, matches: [context.link])
468 }
469 return source
470 }
471 }
472
473 /// Headings and files with IDs (org-roam's nodes), or Denote's notes.
474 public func nodes(overlay: [String: FileRecord] = [:], denote: Bool = OrgPreferences.usesDenote()) throws -> [IndexStore.Node] {
475 do { return try denote ? index.denoteNodes(overlay: overlay) : index.nodes(overlay: overlay) } catch { throw Self.indexFailed(error) }
476 }
477
478 public func search(_ query: String, overlay: [String: FileRecord] = [:]) throws -> [HeadingLocation] {
479 do { return try index.search(query, overlay: overlay) } catch { throw Self.indexFailed(error) }
480 }
481
482 /// A query's database error, as the screen showing the query's results says it.
483 private nonisolated static func indexFailed(_ error: any Error) -> FileError {
484 FileError(message: "Can't read the index: \(error.localizedDescription)")
485 }
486
487 /// Index rows for an open file's unsaved text, keyed by path, for queries to use in place
488 /// of its rows on disk. Empty when the file has no unsaved edits. Cached until the text
489 /// changes.
490 /// Index records for open buffers with unsaved edits, so search sees what they hold.
491 public func overlay(_ documents: [(path: String, document: DocumentState)]) -> [String: FileRecord] {
492 var result: [String: FileRecord] = [:]
493 for (path, document) in documents where document.isDirty {
494 result.merge(overlay(path: path, document: document)) { a, _ in a }
495 }
496 return result
497 }
498
499 public func overlay(path: String?, document: DocumentState?) -> [String: FileRecord] {
500 guard let path, let document, document.isDirty, let bytes = try? document.encodedText(),
501 let entry = files.first(where: { $0.path == path }) else { return [:] }
502 if let cached = overlayCache, cached.record.path == path, cached.text == document.text {
503 return [path: cached.record]
504 }
505 let record = FileRecord(path: path, root: entry.root, kind: entry.kind, bytes: bytes, mtime: Date().timeIntervalSince1970, settings: settings)
506 overlayCache = (document.text, record)
507 return [path: record]
508 }
509
510 public func quickOpen(_ query: String) -> [FileEntry] {
511 FuzzyMatch.rank(query, files.filter { $0.kind != .conflict })
512 }
513}