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