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