Sources/OrgApp/DocumentSession.swift

8847b010a7b834c174ec4eaa9c7ab0c5ffa1ca46
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

309 lines · 13630 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    /// Org options for commands the session runs (refile, archive).
 67    public var options: EditingOptions = .org
 68    /// TODO keywords and priorities for files without their own settings.
 69    public var defaults: OrgSettings = .default
 70
 71    private let fileSystem: FileSystem
 72    private let recovery: RecoveryStore
 73    @ObservationIgnored private var buffer: DocumentBuffer?
 74    @ObservationIgnored var autosave: Task<Void, Never>?
 75    @ObservationIgnored private var outlineUpdate: Task<Void, Never>?
 76    private var requestID = 0
 77
 78    public init(
 79        fileSystem: FileSystem = CoordinatedFileSystem(),
 80        recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
 81    ) {
 82        self.fileSystem = fileSystem
 83        self.recovery = recovery
 84    }
 85
 86    private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
 87    private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
 88
 89    public func open(_ path: String) {
 90        do {
 91            guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
 92                lastError = "\((path as NSString).lastPathComponent) no longer exists."
 93                return
 94            }
 95            autosave?.cancel()
 96            self.path = path
 97            buffer = StateBuffer(DocumentState(bytes: bytes, defaults: defaults))
 98            conflict = nil
 99            revealRequest = nil
100            refresh()
101        } catch {
102            lastError = "Can't open \(path): \(error.localizedDescription)"
103        }
104    }
105
106    /// Makes `buffer`, built from `document`, the live state of the open file.
107    public func attach(_ buffer: DocumentBuffer) {
108        self.buffer = buffer
109        refresh()
110    }
111
112    /// The buffer changed through typing. The outline follows once typing pauses.
113    public func bufferChanged() {
114        refresh(outline: false)
115        outlineUpdate?.cancel()
116        outlineUpdate = Task { [weak self] in
117            try? await Task.sleep(for: .milliseconds(300))
118            guard !Task.isCancelled, let self, let document = self.document else { return }
119            self.outline = Presentation.outline(document.tree)
120        }
121        scheduleAutosave()
122    }
123
124    private func refresh(outline updateOutline: Bool = true) {
125        guard let buffer else { return }
126        let state = buffer.document
127        document = state
128        if isDirty != state.isDirty { isDirty = state.isDirty }
129        if isReadOnly == state.isEditable { isReadOnly = !state.isEditable }
130        if updateOutline { outline = Presentation.outline(state.tree) }
131    }
132
133    // MARK: - Saving
134
135    private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
136
137    private func scheduleAutosave() {
138        autosave?.cancel()
139        guard saveMode == .automatic, isDirty, conflict == nil else { return }
140        autosave = Task { [weak self, autosaveDelay] in
141            try? await Task.sleep(for: autosaveDelay)
142            guard !Task.isCancelled else { return }
143            self?.save()
144        }
145    }
146
147    /// Saves now. True when nothing is left unsaved.
148    @discardableResult
149    public func save() -> Bool {
150        autosave?.cancel()
151        guard let buffer, let url, isDirty else { return !isDirty }
152        guard conflict == nil else { return false }
153        do {
154            let outcome = try buffer.update { try saver.save(&$0, to: url) }
155            switch outcome {
156            case .saved, .mergedAndSaved:
157                break
158            case .conflict:
159                conflict = "\(name) changed on disk, and the changes conflict with yours."
160            case .overwroteExternalChange(let change), .changedAfterWrite(let change):
161                if case .conflict = change {
162                    conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
163                }
164            }
165        } catch {
166            lastError = "Can't save \(name): \(error.localizedDescription)"
167        }
168        refresh()
169        return !isDirty
170    }
171
172    /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
173    public func keepMine() {
174        guard let buffer, let url else { return }
175        do {
176            try buffer.update { try saver.overwrite(&$0, to: url) }
177            conflict = nil
178        } catch {
179            lastError = "Can't save \(name): \(error.localizedDescription)"
180        }
181        refresh()
182    }
183
184    /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
185    public func useDiskVersion() {
186        guard let buffer, let url else { return }
187        do {
188            guard let bytes = try fileSystem.read(url) else { return }
189            if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
190            buffer.update { $0 = DocumentState(bytes: bytes, defaults: $0.defaults) }
191            conflict = nil
192        } catch {
193            lastError = "Can't read \(name): \(error.localizedDescription)"
194        }
195        refresh()
196    }
197
198    // MARK: - Moving subtrees
199
200    /// The current context of the buffer, as commands see it.
201    private func editContext(now: Date) -> EditContext? {
202        guard let buffer else { return nil }
203        let document = buffer.document
204        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
205    }
206
207    /// Moves the subtree at the caret under `target`. For another file, that file is written
208    /// first, through the save path; the subtree leaves this buffer only once it has. Returns a
209    /// message for the echo area.
210    @discardableResult
211    public func refile(to target: RefileTarget, now: Date = Date()) -> String? {
212        guard let buffer, let path, let context = editContext(now: now) else { return nil }
213        if target.path == path {
214            let step = buffer.perform(RefileWithinFile(), now: now, answers: ["refile": target.start.map(String.init) ?? ""])
215            if case .failed(let message) = step { return message }
216            bufferChanged()
217            return "Refiled to \(target.label)"
218        }
219        let url = URL(fileURLWithPath: target.path)
220        do {
221            guard let bytes = try fileSystem.read(url) else { return "\((target.path as NSString).lastPathComponent) no longer exists." }
222            var state = DocumentState(bytes: bytes, defaults: defaults)
223            guard state.isEditable else { return "\((target.path as NSString).lastPathComponent) isn't UTF-8, so it can't be changed." }
224            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
225            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
226            try state.apply([result.target], baseRevision: state.revision)
227            if case .conflict = try saver.save(&state, to: url) { return "\((target.path as NSString).lastPathComponent) changed on disk; nothing was refiled." }
228            if case .failed(let message) = buffer.perform(PrecomputedEdit(result.source), now: now, answers: [:]) { return message }
229            bufferChanged()
230            return "Refiled to \(target.label)"
231        } catch {
232            return "Can't refile: \(error.localizedDescription)"
233        }
234    }
235
236    /// Archives the subtree at the caret where `org-archive-subtree` would. Returns a message.
237    @discardableResult
238    public func archive(now: Date = Date()) -> String? {
239        guard let buffer, let path, let context = editContext(now: now) else { return nil }
240        let destination: Archive.Destination
241        switch Archive.destination(context, sourcePath: path) {
242        case .success(let value): destination = value
243        case .failure(.message(let message)): return message
244        }
245        do {
246            let url = URL(fileURLWithPath: destination.path)
247            let existing = destination.isSameFile ? nil : try fileSystem.read(url)
248            var state = DocumentState(bytes: existing ?? [], defaults: defaults)
249            if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
250            let edits: Archive.Edits
251            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
252            case .success(let value): edits = value
253            case .failure(.message(let message)): return message
254            }
255            if let archiveEdit = edits.archive {
256                try state.apply([archiveEdit], baseRevision: state.revision)
257                if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
258            }
259            if case .failed(let message) = buffer.perform(PrecomputedEdit(edits.source), now: now, answers: [:]) { return message }
260            bufferChanged()
261            return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
262        } catch {
263            return "Can't archive: \(error.localizedDescription)"
264        }
265    }
266
267    // MARK: - Locations
268
269    /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
270    /// are used only if the buffer matches what was indexed; otherwise the heading is found
271    /// again by position and title.
272    public func show(_ location: HeadingLocation) {
273        if path != location.path { open(location.path) }
274        guard let document else { return }
275        let hash = FileRecord.hash(document.mergeBase)
276        let offset: Int
277        if !isDirty, hash == location.contentHash {
278            offset = location.start
279        } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
280            offset = outline[location.ordinal].start
281        } else if let entry = outline.first(where: { $0.title == location.title }) {
282            offset = entry.start
283        } else {
284            return
285        }
286        reveal(offset)
287    }
288
289    public func reveal(_ offset: Int) {
290        requestID += 1
291        revealRequest = (offset, requestID)
292    }
293
294    /// Called when the workspace sees the open file change on disk.
295    public func fileChanged(_ path: String) {
296        guard path == self.path, let buffer, let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
297        guard bytes != buffer.document.mergeBase else { return }
298        switch buffer.update({ $0.diskChanged(to: bytes) }) {
299        case .conflict:
300            autosave?.cancel()
301            conflict = "\(name) changed on disk, and the changes conflict with yours."
302        case .merged, .reloaded:
303            conflict = nil
304        case .unchanged:
305            break
306        }
307        refresh()
308    }
309}