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