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