Sources/OrgApp/WorkspaceModel.swift
198 lines · 7955 bytes
1import Foundation
2import Observation
3import OrgIndex
4import OrgWorkspace
5
6/// The folders the user added, the index over them, and the queries the window runs.
7@MainActor
8@Observable
9public final class WorkspaceModel {
10 public private(set) var roots: [WorkspaceRoot] = []
11 public private(set) var files: [FileEntry] = []
12 public private(set) var isIndexing = false
13 /// The last error worth showing, such as a folder that can no longer be found.
14 public var lastError: String?
15 /// Bumped when an indexed file changes on disk, with its path.
16 public private(set) var changedFile: (path: String, version: Int)?
17
18 public let index: IndexStore
19 public let settings: IndexSettings
20 private let rootsFile: URL
21 /// Resolved root folders, keyed by their resolved path, which is how the index stores them.
22 private var resolvedRoots: [String: URL] = [:]
23 @ObservationIgnored private var watcher: AnyObject?
24 private var changeVersion = 0
25
26 /// `directory` holds the index and the list of roots; nil keeps both in memory.
27 public init(directory: URL?, settings: IndexSettings = IndexSettings()) throws {
28 self.settings = settings
29 if let directory {
30 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
31 index = try IndexStore(path: directory.appendingPathComponent("index.sqlite").path)
32 rootsFile = directory.appendingPathComponent("roots.json")
33 } else {
34 index = try IndexStore()
35 rootsFile = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-roots-\(UUID().uuidString).json")
36 }
37 if let data = try? Data(contentsOf: rootsFile), let saved = try? JSONDecoder().decode([WorkspaceRoot].self, from: data) {
38 roots = saved
39 }
40 resolveRoots()
41 try reloadFiles()
42 }
43
44 /// `~/Library/Application Support/Orgstar`, or `ORGSTAR_DATA_DIR` when set (for development).
45 public static var defaultDirectory: URL {
46 if let override = ProcessInfo.processInfo.environment["ORGSTAR_DATA_DIR"] {
47 return URL(fileURLWithPath: override)
48 }
49 return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Orgstar")
50 }
51
52 // MARK: - Roots
53
54 public func addRoot(_ url: URL) async throws {
55 let root = try WorkspaceRoot(url: url)
56 guard !roots.contains(where: { $0.path == root.path }) else { return }
57 roots.append(root)
58 try saveRoots()
59 resolveRoots()
60 await refresh()
61 }
62
63 /// Removes a root by its resolved path, as `FileEntry.root` gives it.
64 public func removeRoot(path: String) throws {
65 let bookmarkPaths = roots.filter { (try? $0.resolve().url.path) == path || $0.path == path }.map(\.path)
66 roots.removeAll { bookmarkPaths.contains($0.path) }
67 try saveRoots()
68 resolveRoots()
69 var change = IndexChange()
70 change.removals = files.filter { $0.root == path }.map(\.path)
71 try index.apply(change)
72 try reloadFiles()
73 }
74
75 private func saveRoots() throws {
76 try JSONEncoder().encode(roots).write(to: rootsFile, options: .atomic)
77 }
78
79 /// Resolves bookmarks; refreshes stale ones; reports folders that can't be found.
80 private func resolveRoots() {
81 resolvedRoots = [:]
82 var refreshed = roots
83 for (i, root) in roots.enumerated() {
84 guard let (url, isStale) = try? root.resolve() else {
85 lastError = "Can't find the folder \(root.path)."
86 continue
87 }
88 if isStale, let fresh = try? WorkspaceRoot(url: url) { refreshed[i] = fresh }
89 resolvedRoots[url.path] = url
90 }
91 if refreshed != roots {
92 roots = refreshed
93 try? saveRoots()
94 }
95 }
96
97 public func url(forRoot path: String) -> URL? { resolvedRoots[path] }
98
99 /// Resolved root paths, sorted.
100 public var rootPaths: [String] { resolvedRoots.keys.sorted() }
101
102 // MARK: - Indexing
103
104 /// Reconciles every root off the main thread, then reloads the file list.
105 public func refresh() async {
106 isIndexing = true
107 defer { isIndexing = false }
108 let reconciler = Reconciler(index: index, settings: settings)
109 for url in resolvedRoots.values {
110 do {
111 _ = try await Task.detached { try reconciler.reconcile(root: url) }.value
112 } catch {
113 lastError = "Indexing \(url.path) failed: \(error.localizedDescription)"
114 }
115 }
116 try? reloadFiles()
117 }
118
119 private func reloadFiles() throws {
120 let roots = Set(resolvedRoots.keys)
121 files = try index.files().compactMap { file in
122 guard let root = roots.first(where: { file.path.hasPrefix($0 + "/") }) else { return nil }
123 return FileEntry(path: file.path, root: root, kind: file.kind)
124 }
125 }
126
127 /// Reconciles the paths a batch of file events named, or whole roots when events were lost.
128 public func filesChanged(_ paths: [URL], rescan roots: [URL]) async {
129 let reconciler = Reconciler(index: index, settings: settings)
130 for rootURL in roots {
131 _ = try? await Task.detached { try reconciler.reconcile(root: rootURL) }.value
132 }
133 for (rootPath, rootURL) in resolvedRoots where !roots.contains(rootURL) {
134 let inRoot = paths.filter { $0.path.hasPrefix(rootPath + "/") }
135 guard !inRoot.isEmpty else { continue }
136 _ = try? await Task.detached { try reconciler.reconcile(root: rootURL, paths: inRoot) }.value
137 }
138 try? reloadFiles()
139 for path in paths {
140 changeVersion += 1
141 changedFile = (path.standardizedFileURL.path, changeVersion)
142 }
143 }
144
145 #if os(macOS)
146 /// Watches every root; changes reconcile the index and are reported through `changedFile`.
147 public func startWatching() {
148 let roots = Array(resolvedRoots.values)
149 guard !roots.isEmpty else { return }
150 let fsWatcher = FSEventsWatcher(roots: roots.map { $0.resolvingSymlinksInPath() }) { [weak self] events in
151 var changed: [URL] = []
152 var rescans: [URL] = []
153 for event in events {
154 switch event {
155 case .changed(let url): changed.append(url)
156 case .rescan(let url): rescans.append(url)
157 }
158 }
159 Task { @MainActor [weak self] in
160 guard let self else { return }
161 await self.filesChanged(changed.map(self.indexForm), rescan: rescans.compactMap(self.root(containing:)))
162 }
163 }
164 fsWatcher.start()
165 watcher = fsWatcher
166 }
167 #endif
168
169 /// The root an event path belongs to.
170 private func root(containing url: URL) -> URL? {
171 resolvedRoots.values.first { url.path.hasPrefix($0.resolvingSymlinksInPath().path) || url.path.hasPrefix($0.path) }
172 }
173
174 /// FSEvents reports real paths (`/private/var/...`); the index uses the root's own form.
175 func indexForm(_ url: URL) -> URL {
176 for root in resolvedRoots.values {
177 let real = root.resolvingSymlinksInPath().path
178 if real != root.path, url.path.hasPrefix(real + "/") {
179 return URL(fileURLWithPath: root.path + url.path.dropFirst(real.count))
180 }
181 }
182 return url
183 }
184
185 // MARK: - Queries
186
187 public func tree(forRoot path: String) -> FileTreeNode {
188 FileTreeNode.build(root: path, files: files)
189 }
190
191 public func search(_ query: String, overlay: [String: FileRecord] = [:]) -> [HeadingLocation] {
192 (try? index.search(query, overlay: overlay)) ?? []
193 }
194
195 public func quickOpen(_ query: String) -> [FileEntry] {
196 FuzzyMatch.rank(query, files.filter { $0.kind != .conflict })
197 }
198}