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