Sources/OrgApp/DocumentSession.swift

6ecbf692e07af991cfe740d095dce71f29a670ae
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

305 lines · 13314 bytes

  1import Foundation
  2import Observation
  3import OrgCore
  4import OrgDocument
  5import OrgIndex
  6import OrgPresentation
  7
  8/// A heading, or a whole file, a subtree can be refiled to.
  9public struct RefileTarget: Sendable, Hashable {
 10    /// `file.org/Parent/Heading`, as the prompt lists it.
 11    public let label: String
 12    public let path: String
 13    /// Start of the heading when the file had `contentHash`; nil refiles to the end of the file.
 14    public let start: Int?
 15    public let title: String
 16    public let level: Int
 17    public let contentHash: String
 18
 19    public init(label: String, path: String, start: Int?, title: String, level: Int, contentHash: String) {
 20        self.label = label
 21        self.path = path
 22        self.start = start
 23        self.title = title
 24        self.level = level
 25        self.contentHash = contentHash
 26    }
 27
 28    /// The heading's start in `state`: its indexed offset if the file hasn't changed, else the
 29    /// first heading with the same title and level. Nil for the end of the file.
 30    func locate(in state: DocumentState) -> Int?? {
 31        guard let start else { return .some(nil) }
 32        if FileRecord.hash(state.mergeBase) == contentHash { return .some(start) }
 33        let entry = Presentation.outline(state.tree).first { $0.title == title && $0.level == level }
 34        return entry.map { .some($0.start) }
 35    }
 36}
 37
 38public enum SaveMode: String, Sendable, CaseIterable {
 39    /// Save shortly after typing stops.
 40    case automatic
 41    /// Save only on ⌘S.
 42    case explicit
 43}
 44
 45/// The file open in a window: its buffer, outline, saving, and requests for the editor to
 46/// show a location. The view layer attaches the editor as the buffer and follows
 47/// `revealRequest`.
 48@MainActor
 49@Observable
 50public final class DocumentSession {
 51    public private(set) var path: String?
 52    /// A copy of the buffer's state as of its last change. Not observed: it changes on every
 53    /// keystroke; views follow `path`, `isDirty` and `outline`.
 54    @ObservationIgnored public private(set) var document: DocumentState?
 55    public private(set) var outline: [OutlineEntry] = []
 56    public private(set) var isDirty = false
 57    /// The file isn't UTF-8, so it can't be edited or saved.
 58    public private(set) var isReadOnly = false
 59    /// Set while the buffer and the file on disk conflict; says how to resolve it.
 60    public private(set) var conflict: String?
 61    /// Bumped to ask the editor to reveal an offset.
 62    public private(set) var revealRequest: (offset: Int, id: Int)?
 63    public var lastError: String?
 64    public var saveMode: SaveMode = .automatic
 65    public var autosaveDelay: Duration = .seconds(1)
 66
 67    private let fileSystem: FileSystem
 68    private let recovery: RecoveryStore
 69    @ObservationIgnored private var buffer: DocumentBuffer?
 70    @ObservationIgnored var autosave: Task<Void, Never>?
 71    @ObservationIgnored private var outlineUpdate: Task<Void, Never>?
 72    private var requestID = 0
 73
 74    public init(
 75        fileSystem: FileSystem = CoordinatedFileSystem(),
 76        recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
 77    ) {
 78        self.fileSystem = fileSystem
 79        self.recovery = recovery
 80    }
 81
 82    private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
 83    private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
 84
 85    public func open(_ path: String) {
 86        do {
 87            guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
 88                lastError = "\((path as NSString).lastPathComponent) no longer exists."
 89                return
 90            }
 91            autosave?.cancel()
 92            self.path = path
 93            buffer = StateBuffer(DocumentState(bytes: bytes))
 94            conflict = nil
 95            revealRequest = nil
 96            refresh()
 97        } catch {
 98            lastError = "Can't open \(path): \(error.localizedDescription)"
 99        }
100    }
101
102    /// Makes `buffer`, built from `document`, the live state of the open file.
103    public func attach(_ buffer: DocumentBuffer) {
104        self.buffer = buffer
105        refresh()
106    }
107
108    /// The buffer changed through typing. The outline follows once typing pauses.
109    public func bufferChanged() {
110        refresh(outline: false)
111        outlineUpdate?.cancel()
112        outlineUpdate = Task { [weak self] in
113            try? await Task.sleep(for: .milliseconds(300))
114            guard !Task.isCancelled, let self, let document = self.document else { return }
115            self.outline = Presentation.outline(document.tree)
116        }
117        scheduleAutosave()
118    }
119
120    private func refresh(outline updateOutline: Bool = true) {
121        guard let buffer else { return }
122        let state = buffer.document
123        document = state
124        if isDirty != state.isDirty { isDirty = state.isDirty }
125        if isReadOnly == state.isEditable { isReadOnly = !state.isEditable }
126        if updateOutline { outline = Presentation.outline(state.tree) }
127    }
128
129    // MARK: - Saving
130
131    private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
132
133    private func scheduleAutosave() {
134        autosave?.cancel()
135        guard saveMode == .automatic, isDirty, conflict == nil else { return }
136        autosave = Task { [weak self, autosaveDelay] in
137            try? await Task.sleep(for: autosaveDelay)
138            guard !Task.isCancelled else { return }
139            self?.save()
140        }
141    }
142
143    /// Saves now. True when nothing is left unsaved.
144    @discardableResult
145    public func save() -> Bool {
146        autosave?.cancel()
147        guard let buffer, let url, isDirty else { return !isDirty }
148        guard conflict == nil else { return false }
149        do {
150            let outcome = try buffer.update { try saver.save(&$0, to: url) }
151            switch outcome {
152            case .saved, .mergedAndSaved:
153                break
154            case .conflict:
155                conflict = "\(name) changed on disk, and the changes conflict with yours."
156            case .overwroteExternalChange(let change), .changedAfterWrite(let change):
157                if case .conflict = change {
158                    conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
159                }
160            }
161        } catch {
162            lastError = "Can't save \(name): \(error.localizedDescription)"
163        }
164        refresh()
165        return !isDirty
166    }
167
168    /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
169    public func keepMine() {
170        guard let buffer, let url else { return }
171        do {
172            try buffer.update { try saver.overwrite(&$0, to: url) }
173            conflict = nil
174        } catch {
175            lastError = "Can't save \(name): \(error.localizedDescription)"
176        }
177        refresh()
178    }
179
180    /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
181    public func useDiskVersion() {
182        guard let buffer, let url else { return }
183        do {
184            guard let bytes = try fileSystem.read(url) else { return }
185            if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
186            buffer.update { $0 = DocumentState(bytes: bytes, defaults: $0.defaults) }
187            conflict = nil
188        } catch {
189            lastError = "Can't read \(name): \(error.localizedDescription)"
190        }
191        refresh()
192    }
193
194    // MARK: - Moving subtrees
195
196    /// The current context of the buffer, as commands see it.
197    private func editContext(now: Date) -> EditContext? {
198        guard let buffer else { return nil }
199        let document = buffer.document
200        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now)
201    }
202
203    /// Moves the subtree at the caret under `target`. For another file, that file is written
204    /// first, through the save path; the subtree leaves this buffer only once it has. Returns a
205    /// message for the echo area.
206    @discardableResult
207    public func refile(to target: RefileTarget, now: Date = Date()) -> String? {
208        guard let buffer, let path, let context = editContext(now: now) else { return nil }
209        if target.path == path {
210            let step = buffer.perform(RefileWithinFile(), now: now, answers: ["refile": target.start.map(String.init) ?? ""])
211            if case .failed(let message) = step { return message }
212            bufferChanged()
213            return "Refiled to \(target.label)"
214        }
215        let url = URL(fileURLWithPath: target.path)
216        do {
217            guard let bytes = try fileSystem.read(url) else { return "\((target.path as NSString).lastPathComponent) no longer exists." }
218            var state = DocumentState(bytes: bytes)
219            guard state.isEditable else { return "\((target.path as NSString).lastPathComponent) isn't UTF-8, so it can't be changed." }
220            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
221            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
222            try state.apply([result.target], baseRevision: state.revision)
223            if case .conflict = try saver.save(&state, to: url) { return "\((target.path as NSString).lastPathComponent) changed on disk; nothing was refiled." }
224            if case .failed(let message) = buffer.perform(PrecomputedEdit(result.source), now: now, answers: [:]) { return message }
225            bufferChanged()
226            return "Refiled to \(target.label)"
227        } catch {
228            return "Can't refile: \(error.localizedDescription)"
229        }
230    }
231
232    /// Archives the subtree at the caret where `org-archive-subtree` would. Returns a message.
233    @discardableResult
234    public func archive(now: Date = Date()) -> String? {
235        guard let buffer, let path, let context = editContext(now: now) else { return nil }
236        let destination: Archive.Destination
237        switch Archive.destination(context, sourcePath: path) {
238        case .success(let value): destination = value
239        case .failure(.message(let message)): return message
240        }
241        do {
242            let url = URL(fileURLWithPath: destination.path)
243            let existing = destination.isSameFile ? nil : try fileSystem.read(url)
244            var state = DocumentState(bytes: existing ?? [])
245            if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
246            let edits: Archive.Edits
247            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
248            case .success(let value): edits = value
249            case .failure(.message(let message)): return message
250            }
251            if let archiveEdit = edits.archive {
252                try state.apply([archiveEdit], baseRevision: state.revision)
253                if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
254            }
255            if case .failed(let message) = buffer.perform(PrecomputedEdit(edits.source), now: now, answers: [:]) { return message }
256            bufferChanged()
257            return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
258        } catch {
259            return "Can't archive: \(error.localizedDescription)"
260        }
261    }
262
263    // MARK: - Locations
264
265    /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
266    /// are used only if the buffer matches what was indexed; otherwise the heading is found
267    /// again by position and title.
268    public func show(_ location: HeadingLocation) {
269        if path != location.path { open(location.path) }
270        guard let document else { return }
271        let hash = FileRecord.hash(document.mergeBase)
272        let offset: Int
273        if !isDirty, hash == location.contentHash {
274            offset = location.start
275        } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
276            offset = outline[location.ordinal].start
277        } else if let entry = outline.first(where: { $0.title == location.title }) {
278            offset = entry.start
279        } else {
280            return
281        }
282        reveal(offset)
283    }
284
285    public func reveal(_ offset: Int) {
286        requestID += 1
287        revealRequest = (offset, requestID)
288    }
289
290    /// Called when the workspace sees the open file change on disk.
291    public func fileChanged(_ path: String) {
292        guard path == self.path, let buffer, let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
293        guard bytes != buffer.document.mergeBase else { return }
294        switch buffer.update({ $0.diskChanged(to: bytes) }) {
295        case .conflict:
296            autosave?.cancel()
297            conflict = "\(name) changed on disk, and the changes conflict with yours."
298        case .merged, .reloaded:
299            conflict = nil
300        case .unchanged:
301            break
302        }
303        refresh()
304    }
305}