Lutra/crates/engine/src/buffers.rs
danny e1dc24dc25 M3.10: autosave and flushDirty
Autosave saves dirty buffers when the window loses focus (DOM blur and
visibilitychange), when the active tab changes and after
editor.autosave.idleSeconds (default 15) without an edit; three settings,
all on by default. flushDirty() in ui/src/stores/autosave.ts is the one
save-all-dirty-and-wait entry point for later deployment, run and
terminal features: it waits for pending buffer sync, then runs
file.saveAll {skipConflicts: true}; one toast per failed file.

Engine: file.saveAll takes skipConflicts and returns skipped; Buffers
tracks buffers in conflict with their file and the hash of the last
read/written content, so our own save reported late is not a conflict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 21:01:12 +02:00

185 lines
5.4 KiB
Rust

//! Open buffers: the engine's copy of every file the user is editing.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use lutra_text::{Buffer, LineEnding};
use serde::{Deserialize, Serialize};
/// Identifier of an open buffer, unique for the engine's lifetime.
pub type BufferId = u64;
/// One open file.
#[derive(Debug, Clone)]
pub struct OpenBuffer {
/// The text.
pub buffer: Buffer,
/// Project-relative path of the file.
pub path: PathBuf,
/// Incremented by every change of the text.
pub version: u64,
/// The version that matches the file on disk.
pub saved_version: u64,
/// The file started with a UTF-8 byte order mark; kept on save.
pub bom: bool,
}
impl OpenBuffer {
/// Whether the buffer has unsaved changes.
pub fn dirty(&self) -> bool {
self.version != self.saved_version
}
}
/// The open buffers by id.
#[derive(Debug, Default)]
pub struct Buffers {
/// Buffers by id.
by_id: BTreeMap<BufferId, OpenBuffer>,
/// The id the next buffer gets.
next_id: BufferId,
/// Buffers whose file changed or disappeared on disk while they had
/// unsaved changes ([`crate::Event::FileChangedOnDisk`]). The user has to
/// decide, so `file.saveAll {skipConflicts}` leaves them alone until an
/// explicit save or a reload settles it.
conflicts: BTreeSet<BufferId>,
/// What each buffer's file held when Lutra last read or wrote it: the
/// hash ([`crate::journal::hex_hash`]) of the text and the byte order
/// mark. A change on disk that matches it (our own save reported late, a
/// touch) is not a conflict.
written: BTreeMap<BufferId, (String, bool)>,
}
impl Buffers {
/// Adds a buffer and returns its id.
pub fn insert(&mut self, buffer: OpenBuffer) -> BufferId {
self.next_id = self.next_id.saturating_add(1);
let id = self.next_id;
self.by_id.insert(id, buffer);
id
}
/// The buffer with `id`.
pub fn get(&self, id: BufferId) -> Option<&OpenBuffer> {
self.by_id.get(&id)
}
/// The buffer with `id`, mutable.
pub fn get_mut(&mut self, id: BufferId) -> Option<&mut OpenBuffer> {
self.by_id.get_mut(&id)
}
/// Removes the buffer with `id`.
pub fn remove(&mut self, id: BufferId) -> Option<OpenBuffer> {
self.conflicts.remove(&id);
self.written.remove(&id);
self.by_id.remove(&id)
}
/// Marks buffer `id` as in conflict with its file on disk.
pub fn mark_conflict(&mut self, id: BufferId) {
if self.by_id.contains_key(&id) {
self.conflicts.insert(id);
}
}
/// Clears the disk conflict of buffer `id` (saved or reloaded).
pub fn clear_conflict(&mut self, id: BufferId) {
self.conflicts.remove(&id);
}
/// Whether buffer `id` is in conflict with its file on disk.
pub fn has_conflict(&self, id: BufferId) -> bool {
self.conflicts.contains(&id)
}
/// Remembers what buffer `id`'s file holds after Lutra read or wrote it.
///
/// # Parameters
/// - `hash`: [`crate::journal::hex_hash`] of the text.
/// - `bom`: whether the file has a byte order mark.
pub fn note_written(&mut self, id: BufferId, hash: String, bom: bool) {
if self.by_id.contains_key(&id) {
self.written.insert(id, (hash, bom));
}
}
/// Whether the file content `hash`/`bom` is what Lutra last read or
/// wrote for buffer `id`.
pub fn is_own_write(&self, id: BufferId, hash: &str, bom: bool) -> bool {
self.written
.get(&id)
.is_some_and(|(h, b)| h == hash && *b == bom)
}
/// The id of the buffer for the project-relative `path`, if open.
pub fn find(&self, path: &Path) -> Option<BufferId> {
self.by_id
.iter()
.find(|(_, b)| b.path == path)
.map(|(id, _)| *id)
}
/// Ids of all buffers, ascending.
pub fn ids(&self) -> Vec<BufferId> {
self.by_id.keys().copied().collect()
}
/// Ids of the buffers with unsaved changes, ascending.
pub fn dirty_ids(&self) -> Vec<BufferId> {
self.by_id
.iter()
.filter(|(_, b)| b.dirty())
.map(|(id, _)| *id)
.collect()
}
/// Number of open buffers.
pub fn len(&self) -> usize {
self.by_id.len()
}
/// Whether no buffer is open.
pub fn is_empty(&self) -> bool {
self.by_id.is_empty()
}
/// Removes every buffer.
pub fn clear(&mut self) {
self.conflicts.clear();
self.written.clear();
self.by_id.clear();
}
}
/// A line ending as sent to clients: `"lf"`, `"crlf"` or `"cr"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LineEndingName {
/// `\n`.
Lf,
/// `\r\n`.
Crlf,
/// `\r`.
Cr,
}
impl From<LineEnding> for LineEndingName {
fn from(ending: LineEnding) -> Self {
match ending {
LineEnding::Lf => Self::Lf,
LineEnding::CrLf => Self::Crlf,
LineEnding::Cr => Self::Cr,
}
}
}
impl From<LineEndingName> for LineEnding {
fn from(name: LineEndingName) -> Self {
match name {
LineEndingName::Lf => Self::Lf,
LineEndingName::Crlf => Self::CrLf,
LineEndingName::Cr => Self::Cr,
}
}
}