Sources/OrgApp/DocumentSession.swift

923f63b7fcb447d5753267b1cf81e58da6449ee6
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

203 lines · 7723 bytes

  1import Foundation
  2import Observation
  3import OrgCore
  4import OrgDocument
  5import OrgIndex
  6import OrgPresentation
  7
  8public enum SaveMode: String, Sendable, CaseIterable {
  9    /// Save shortly after typing stops.
 10    case automatic
 11    /// Save only on ⌘S.
 12    case explicit
 13}
 14
 15/// The file open in a window: its buffer, outline, saving, and requests for the editor to
 16/// show a location. The view layer attaches the editor as the buffer and follows
 17/// `revealRequest`.
 18@MainActor
 19@Observable
 20public final class DocumentSession {
 21    public private(set) var path: String?
 22    /// A copy of the buffer's state as of its last change. Not observed: it changes on every
 23    /// keystroke; views follow `path`, `isDirty` and `outline`.
 24    @ObservationIgnored public private(set) var document: DocumentState?
 25    public private(set) var outline: [OutlineEntry] = []
 26    public private(set) var isDirty = false
 27    /// Set while the buffer and the file on disk conflict; says how to resolve it.
 28    public private(set) var conflict: String?
 29    /// Bumped to ask the editor to reveal an offset.
 30    public private(set) var revealRequest: (offset: Int, id: Int)?
 31    public var lastError: String?
 32    public var saveMode: SaveMode = .automatic
 33    public var autosaveDelay: Duration = .seconds(1)
 34
 35    private let fileSystem: FileSystem
 36    private let recovery: RecoveryStore
 37    @ObservationIgnored private var buffer: DocumentBuffer?
 38    @ObservationIgnored var autosave: Task<Void, Never>?
 39    @ObservationIgnored private var outlineUpdate: Task<Void, Never>?
 40    private var requestID = 0
 41
 42    public init(
 43        fileSystem: FileSystem = CoordinatedFileSystem(),
 44        recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
 45    ) {
 46        self.fileSystem = fileSystem
 47        self.recovery = recovery
 48    }
 49
 50    private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
 51    private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
 52
 53    public func open(_ path: String) {
 54        do {
 55            guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
 56                lastError = "\((path as NSString).lastPathComponent) no longer exists."
 57                return
 58            }
 59            autosave?.cancel()
 60            self.path = path
 61            buffer = StateBuffer(DocumentState(bytes: bytes))
 62            conflict = nil
 63            revealRequest = nil
 64            refresh()
 65        } catch {
 66            lastError = "Can't open \(path): \(error.localizedDescription)"
 67        }
 68    }
 69
 70    /// Makes `buffer`, built from `document`, the live state of the open file.
 71    public func attach(_ buffer: DocumentBuffer) {
 72        self.buffer = buffer
 73        refresh()
 74    }
 75
 76    /// The buffer changed through typing. The outline follows once typing pauses.
 77    public func bufferChanged() {
 78        refresh(outline: false)
 79        outlineUpdate?.cancel()
 80        outlineUpdate = Task { [weak self] in
 81            try? await Task.sleep(for: .milliseconds(300))
 82            guard !Task.isCancelled, let self, let document = self.document else { return }
 83            self.outline = Presentation.outline(document.tree)
 84        }
 85        scheduleAutosave()
 86    }
 87
 88    private func refresh(outline updateOutline: Bool = true) {
 89        guard let buffer else { return }
 90        let state = buffer.document
 91        document = state
 92        if isDirty != state.isDirty { isDirty = state.isDirty }
 93        if updateOutline { outline = Presentation.outline(state.tree) }
 94    }
 95
 96    // MARK: - Saving
 97
 98    private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
 99
100    private func scheduleAutosave() {
101        autosave?.cancel()
102        guard saveMode == .automatic, isDirty, conflict == nil else { return }
103        autosave = Task { [weak self, autosaveDelay] in
104            try? await Task.sleep(for: autosaveDelay)
105            guard !Task.isCancelled else { return }
106            self?.save()
107        }
108    }
109
110    /// Saves now. True when nothing is left unsaved.
111    @discardableResult
112    public func save() -> Bool {
113        autosave?.cancel()
114        guard let buffer, let url, isDirty else { return !isDirty }
115        guard conflict == nil else { return false }
116        do {
117            let outcome = try buffer.update { try saver.save(&$0, to: url) }
118            switch outcome {
119            case .saved, .mergedAndSaved:
120                break
121            case .conflict:
122                conflict = "\(name) changed on disk, and the changes conflict with yours."
123            case .overwroteExternalChange(let change), .changedAfterWrite(let change):
124                if case .conflict = change {
125                    conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
126                }
127            }
128        } catch {
129            lastError = "Can't save \(name): \(error.localizedDescription)"
130        }
131        refresh()
132        return !isDirty
133    }
134
135    /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
136    public func keepMine() {
137        guard let buffer, let url else { return }
138        do {
139            try buffer.update { try saver.overwrite(&$0, to: url) }
140            conflict = nil
141        } catch {
142            lastError = "Can't save \(name): \(error.localizedDescription)"
143        }
144        refresh()
145    }
146
147    /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
148    public func useDiskVersion() {
149        guard let buffer, let url else { return }
150        do {
151            guard let bytes = try fileSystem.read(url) else { return }
152            if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
153            buffer.update { $0 = DocumentState(bytes: bytes, defaults: $0.defaults) }
154            conflict = nil
155        } catch {
156            lastError = "Can't read \(name): \(error.localizedDescription)"
157        }
158        refresh()
159    }
160
161    // MARK: - Locations
162
163    /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
164    /// are used only if the buffer matches what was indexed; otherwise the heading is found
165    /// again by position and title.
166    public func show(_ location: HeadingLocation) {
167        if path != location.path { open(location.path) }
168        guard let document else { return }
169        let hash = FileRecord.hash(document.mergeBase)
170        let offset: Int
171        if !isDirty, hash == location.contentHash {
172            offset = location.start
173        } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
174            offset = outline[location.ordinal].start
175        } else if let entry = outline.first(where: { $0.title == location.title }) {
176            offset = entry.start
177        } else {
178            return
179        }
180        reveal(offset)
181    }
182
183    public func reveal(_ offset: Int) {
184        requestID += 1
185        revealRequest = (offset, requestID)
186    }
187
188    /// Called when the workspace sees the open file change on disk.
189    public func fileChanged(_ path: String) {
190        guard path == self.path, let buffer, let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
191        guard bytes != buffer.document.mergeBase else { return }
192        switch buffer.update({ $0.diskChanged(to: bytes) }) {
193        case .conflict:
194            autosave?.cancel()
195            conflict = "\(name) changed on disk, and the changes conflict with yours."
196        case .merged, .reloaded:
197            conflict = nil
198        case .unchanged:
199            break
200        }
201        refresh()
202    }
203}