228 lines
8.6 KiB
Swift
228 lines
8.6 KiB
Swift
import Foundation
|
|
import HelderCore
|
|
import HelderServices
|
|
|
|
extension EditorStore {
|
|
// MARK: Reading from disk
|
|
|
|
/// ⌘R: re-reads a file; disk wins over an unsaved buffer, because the agent may have rewritten it.
|
|
public func reloadFromDisk(_ path: String) async {
|
|
await load(path, discardEdits: true)
|
|
}
|
|
|
|
public func reloadActiveFromDisk() async {
|
|
guard let path = activePath else { return }
|
|
await reloadFromDisk(path)
|
|
}
|
|
|
|
/// The watcher saw files change (nil: anything may have). The open file and every unsaved buffer pick up
|
|
/// the new disk text; a dirty buffer is kept, so a background write never eats the user's typing.
|
|
public func filesChanged(_ paths: [String]?) async {
|
|
let watched = (activePath.map { [$0] } ?? []) + dirtyPaths.filter { $0 != activePath }
|
|
let targets = watched.filter { path in
|
|
guard let state = states[path], state.disk != nil || state.image != nil || state.isBinary else { return false }
|
|
return paths.map { $0.contains(path) } ?? true
|
|
}
|
|
for path in targets { await load(path, discardEdits: false) }
|
|
}
|
|
|
|
/// Bytes of an image a Markdown document shows; project-relative, read through the file service.
|
|
public func readImage(_ path: String) async -> Data? {
|
|
await files.readImage(path)
|
|
}
|
|
|
|
func load(_ path: String, discardEdits: Bool) async {
|
|
let generation = nextGeneration(path)
|
|
switch EditorFileKind.of(path) {
|
|
case .image:
|
|
let data = await files.readImage(path)
|
|
guard loadGeneration[path] == generation else { return }
|
|
states[path, default: FileState()].image = data
|
|
states[path]?.imageUnreadable = data == nil
|
|
case .binary:
|
|
return
|
|
case .text:
|
|
let contents: FileContents
|
|
do {
|
|
contents = try await files.readText(path)
|
|
} catch {
|
|
guard loadGeneration[path] == generation else { return }
|
|
Log.warn("editor", "read failed for \(path): \(error.localizedDescription)")
|
|
if Self.isMissing(error) {
|
|
markDeleted(path, discardEdits: discardEdits)
|
|
} else if states[path]?.disk == nil {
|
|
states[path, default: FileState()].disk = ""
|
|
}
|
|
return
|
|
}
|
|
guard loadGeneration[path] == generation else { return }
|
|
switch contents {
|
|
case let .text(text):
|
|
states[path, default: FileState()].isBinary = false
|
|
applyDisk(text, for: path, discardEdits: discardEdits)
|
|
case .binary:
|
|
states[path, default: FileState()].isBinary = true
|
|
}
|
|
}
|
|
}
|
|
|
|
private func nextGeneration(_ path: String) -> Int {
|
|
let next = (loadGeneration[path] ?? 0) + 1
|
|
loadGeneration[path] = next
|
|
return next
|
|
}
|
|
|
|
private func applyDisk(_ text: String, for path: String, discardEdits: Bool) {
|
|
var state = states[path] ?? FileState()
|
|
let previous = state.disk
|
|
let wasDeleted = state.isDeleted
|
|
state.disk = text
|
|
state.isDeleted = false
|
|
states[path] = state
|
|
if let buffer = state.buffer {
|
|
if discardEdits {
|
|
states[path]?.buffer = nil
|
|
bumpRevision(path)
|
|
} else if buffer == text {
|
|
states[path]?.buffer = nil
|
|
}
|
|
} else if previous != text || wasDeleted {
|
|
bumpRevision(path)
|
|
}
|
|
}
|
|
|
|
/// The file is gone: its last text stays on screen as unsaved edits, so nothing is lost and
|
|
/// only an explicit save writes it back. A forced reload lets the empty disk win.
|
|
private func markDeleted(_ path: String, discardEdits: Bool) {
|
|
var state = states[path] ?? FileState()
|
|
cancelAutoSave(path)
|
|
if discardEdits {
|
|
state.buffer = nil
|
|
state.disk = ""
|
|
state.isDeleted = false
|
|
states[path] = state
|
|
bumpRevision(path)
|
|
return
|
|
}
|
|
guard !state.isDeleted else { return }
|
|
state.isDeleted = true
|
|
if state.buffer == nil { state.buffer = state.disk ?? "" }
|
|
if state.disk == nil { state.disk = "" }
|
|
states[path] = state
|
|
}
|
|
|
|
static func isMissing(_ error: Error) -> Bool {
|
|
if let cocoa = error as? CocoaError {
|
|
return cocoa.code == .fileReadNoSuchFile || cocoa.code == .fileNoSuchFile
|
|
}
|
|
let ns = error as NSError
|
|
return ns.domain == NSPOSIXErrorDomain && ns.code == Int(ENOENT)
|
|
}
|
|
|
|
// MARK: Saving
|
|
|
|
/// ⌘S: writes the active buffer when it differs from disk, then re-reads the disk copy.
|
|
public func save() async throws {
|
|
guard let path = activePath else { return }
|
|
try await save(path: path)
|
|
}
|
|
|
|
/// `announce` is off for auto-save, which would otherwise toast on every pause in typing.
|
|
public func save(path: String, announce: Bool = true) async throws {
|
|
guard let text = states[path]?.buffer, isDirty(path) else { return }
|
|
cancelAutoSave(path)
|
|
let generation = nextGeneration(path)
|
|
do {
|
|
try await files.write(path, contents: text)
|
|
} catch {
|
|
Log.error("save", "write failed for \(path): \(error.localizedDescription)")
|
|
showToast?("Save failed", path)
|
|
throw error
|
|
}
|
|
let disk = (try? await files.read(path)) ?? text
|
|
if loadGeneration[path] == generation, states[path] != nil {
|
|
states[path]?.disk = disk
|
|
states[path]?.isDeleted = false
|
|
if states[path]?.buffer == disk { states[path]?.buffer = nil }
|
|
}
|
|
if announce { showToast?("Saved", path) }
|
|
fileSaved?(path)
|
|
}
|
|
|
|
func scheduleAutoSave(_ path: String) {
|
|
cancelAutoSave(path)
|
|
let id = UUID()
|
|
let task = Task { [weak self] in
|
|
try? await Task.sleep(for: .milliseconds(600))
|
|
guard let self, !Task.isCancelled, self.autoSaves[path]?.id == id else { return }
|
|
self.autoSaves[path] = nil
|
|
try? await self.save(path: path, announce: false)
|
|
}
|
|
autoSaves[path] = (id, task)
|
|
}
|
|
|
|
func cancelAutoSave(_ path: String) {
|
|
autoSaves.removeValue(forKey: path)?.task.cancel()
|
|
}
|
|
|
|
/// Writes every auto-save still waiting on its pause, so nothing typed is left behind.
|
|
public func flushAutoSaves() async {
|
|
for path in Array(autoSaves.keys) {
|
|
cancelAutoSave(path)
|
|
try? await save(path: path, announce: false)
|
|
}
|
|
}
|
|
|
|
/// Before a window closes or switches project: each dirty file asks save, discard or cancel.
|
|
/// Returns false on cancel, and then no discard is applied.
|
|
public func resolveUnsaved() async -> Bool {
|
|
await flushAutoSaves()
|
|
var discarded: [String] = []
|
|
for path in dirtyPaths {
|
|
switch confirmUnsavedClose?(path) ?? .cancel {
|
|
case .cancel:
|
|
return false
|
|
case .save:
|
|
do { try await save(path: path) } catch { return false }
|
|
case .discard:
|
|
discarded.append(path)
|
|
}
|
|
}
|
|
for path in discarded where states[path]?.buffer != nil {
|
|
states[path]?.buffer = nil
|
|
bumpRevision(path)
|
|
}
|
|
return true
|
|
}
|
|
|
|
// MARK: Session
|
|
|
|
/// Restores the last session and the recent-files list for this project.
|
|
public func restore(restoreSession: Bool) async {
|
|
history = await recentFiles.load()
|
|
sessionEnabled = restoreSession
|
|
defer { hasRestored = true }
|
|
guard restoreSession, let saved = session.loadSession(root: root) else { return }
|
|
let usable = { (p: String) in !FileType.tooBigNames.contains(PathUtils.basename(p)) }
|
|
for (path, mode) in saved.modes { states[path, default: FileState()].mode = mode == .diff ? .actual : mode }
|
|
for (path, side) in saved.sides { states[path, default: FileState()].side = side }
|
|
activePath = saved.active.flatMap { usable($0) ? $0 : nil }
|
|
if let active = activePath { await load(active, discardEdits: true) }
|
|
}
|
|
|
|
/// Writes the session and the recent-files list.
|
|
public func persist() async {
|
|
if sessionEnabled {
|
|
let state = SessionState(active: activePath, modes: modes.filter { $0.key == activePath },
|
|
sides: sides.filter { $0.key == activePath })
|
|
session.saveSession(state, root: root)
|
|
}
|
|
await recentFiles.save(history)
|
|
}
|
|
|
|
func persistSoon() {
|
|
guard hasRestored else { return }
|
|
track { await $0.persist() }
|
|
}
|
|
}
|