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