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>
This commit is contained in:
parent
228669036c
commit
e1dc24dc25
18 changed files with 996 additions and 37 deletions
|
|
@ -1,6 +1,6 @@
|
|||
//! Open buffers: the engine's copy of every file the user is editing.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lutra_text::{Buffer, LineEnding};
|
||||
|
|
@ -38,6 +38,16 @@ pub struct Buffers {
|
|||
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 {
|
||||
|
|
@ -61,9 +71,47 @@ impl Buffers {
|
|||
|
||||
/// 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
|
||||
|
|
@ -98,6 +146,8 @@ impl Buffers {
|
|||
|
||||
/// Removes every buffer.
|
||||
pub fn clear(&mut self) {
|
||||
self.conflicts.clear();
|
||||
self.written.clear();
|
||||
self.by_id.clear();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,12 @@
|
|||
//! File commands: `file.open`, `file.save`, `file.saveAll`.
|
||||
//!
|
||||
//! `file.saveAll {skipConflicts: true}` is the engine half of "save every
|
||||
//! dirty buffer and wait" (M3.10): autosave and anything that must see the
|
||||
//! files on disk first (deployment, run configurations, terminal commands)
|
||||
//! call it through the frontend's `flushDirty()`. It extends `file.saveAll`
|
||||
//! instead of adding a command, so there is one save-all with one result
|
||||
//! shape; the flag only adds the rule that a buffer in conflict with its file
|
||||
//! on disk is skipped, because only the user can settle that.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
|
@ -57,6 +65,9 @@ impl Command for Open {
|
|||
bom: file.bom,
|
||||
};
|
||||
let new_id = state.buffers.insert(buffer);
|
||||
state
|
||||
.buffers
|
||||
.note_written(new_id, journal::hex_hash(file.text.as_bytes()), file.bom);
|
||||
state.emit(Event::BufferOpened {
|
||||
id: new_id,
|
||||
path: path_string(&rel),
|
||||
|
|
@ -66,7 +77,9 @@ impl Command for Open {
|
|||
}
|
||||
|
||||
/// Writes buffer `id` to its file, keeping its line ending and byte order
|
||||
/// mark, and marks it clean.
|
||||
/// mark, marks it clean, clears a disk conflict (saving is the user's answer
|
||||
/// to it) and remembers what was written, so the watcher's report of this
|
||||
/// write is not taken for an outside change.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`EngineError::Failed`] for an unknown buffer or a failed write.
|
||||
|
|
@ -76,7 +89,13 @@ fn save(state: &mut State, command: &str, id: BufferId) -> Result<u64, EngineErr
|
|||
.get(id)
|
||||
.ok_or_else(|| EngineError::Failed(format!("no buffer {id}")))?;
|
||||
let abs = absolute(state, command, &open.path)?;
|
||||
lutra_vfs::write_text(&abs, &open.buffer.save_text(), open.bom).map_err(vfs_error)?;
|
||||
let text = open.buffer.save_text();
|
||||
let bom = open.bom;
|
||||
lutra_vfs::write_text(&abs, &text, bom).map_err(vfs_error)?;
|
||||
state
|
||||
.buffers
|
||||
.note_written(id, journal::hex_hash(text.as_bytes()), bom);
|
||||
state.buffers.clear_conflict(id);
|
||||
let open = state
|
||||
.buffers
|
||||
.get_mut(id)
|
||||
|
|
@ -124,8 +143,20 @@ impl Command for Save {
|
|||
}
|
||||
}
|
||||
|
||||
/// Params of `file.saveAll`.
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
struct SaveAllParams {
|
||||
/// Leave buffers in conflict with their file on disk unsaved and list
|
||||
/// them under `skipped`.
|
||||
#[serde(default)]
|
||||
skip_conflicts: bool,
|
||||
}
|
||||
|
||||
/// `file.saveAll`: writes every dirty buffer. A failure doesn't stop the
|
||||
/// others; failures are listed in the result.
|
||||
/// others; failures are listed in the result. With `skipConflicts` a dirty
|
||||
/// buffer whose file changed or disappeared on disk is not written and is
|
||||
/// listed under `skipped`.
|
||||
pub struct SaveAll;
|
||||
|
||||
impl Command for SaveAll {
|
||||
|
|
@ -135,7 +166,7 @@ impl Command for SaveAll {
|
|||
label: "Save All",
|
||||
menu_path: Some("File/Save All"),
|
||||
default_shortcut: Some("Mod+Alt+S"),
|
||||
params: "none; returns { saved: [id], failed: [{ id, message }] }",
|
||||
params: "{ skipConflicts?: boolean (leave buffers whose file changed on disk unsaved) }; returns { saved: [id], failed: [{ id, path, message }], skipped: [id] }",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -143,15 +174,30 @@ impl Command for SaveAll {
|
|||
state.has_project()
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let p: SaveAllParams = parse(self.spec().id, params)?;
|
||||
let mut saved = Vec::new();
|
||||
let mut failed = Vec::new();
|
||||
let mut skipped = Vec::new();
|
||||
for id in state.buffers.dirty_ids() {
|
||||
if p.skip_conflicts && state.buffers.has_conflict(id) {
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
match save(state, self.spec().id, id) {
|
||||
Ok(_) => saved.push(id),
|
||||
Err(e) => failed.push(json!({ "id": id, "message": e.to_string() })),
|
||||
Err(e) => {
|
||||
let path = state
|
||||
.buffers
|
||||
.get(id)
|
||||
.map(|b| path_string(&b.path))
|
||||
.unwrap_or_default();
|
||||
failed.push(json!({ "id": id, "path": path, "message": e.to_string() }));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Outcome::value(json!({ "saved": saved, "failed": failed })))
|
||||
Ok(Outcome::value(
|
||||
json!({ "saved": saved, "failed": failed, "skipped": skipped }),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -224,6 +224,30 @@ pub const DEFS: &[Def] = &[
|
|||
description_key: "settings.phpactor.autoDownload.description",
|
||||
section: "php",
|
||||
},
|
||||
Def {
|
||||
key: "editor.autosave.onBlur",
|
||||
kind: Kind::Bool,
|
||||
default: DefaultValue::Bool(true),
|
||||
label_key: "settings.editor.autosave.onBlur.label",
|
||||
description_key: "settings.editor.autosave.onBlur.description",
|
||||
section: "editor",
|
||||
},
|
||||
Def {
|
||||
key: "editor.autosave.onTabSwitch",
|
||||
kind: Kind::Bool,
|
||||
default: DefaultValue::Bool(true),
|
||||
label_key: "settings.editor.autosave.onTabSwitch.label",
|
||||
description_key: "settings.editor.autosave.onTabSwitch.description",
|
||||
section: "editor",
|
||||
},
|
||||
Def {
|
||||
key: "editor.autosave.idleSeconds",
|
||||
kind: Kind::Int { min: 0, max: 600 },
|
||||
default: DefaultValue::Int(15),
|
||||
label_key: "settings.editor.autosave.idleSeconds.label",
|
||||
description_key: "settings.editor.autosave.idleSeconds.description",
|
||||
section: "editor",
|
||||
},
|
||||
];
|
||||
|
||||
/// Looks a known setting up by key.
|
||||
|
|
@ -584,6 +608,29 @@ mod tests {
|
|||
assert_eq!(s.get("editor.fontSize"), Some(json!(14)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_defaults_and_validation() {
|
||||
let mut s = Settings::in_memory();
|
||||
assert_eq!(s.get("editor.autosave.onBlur"), Some(json!(true)));
|
||||
assert_eq!(s.get("editor.autosave.onTabSwitch"), Some(json!(true)));
|
||||
assert_eq!(s.get("editor.autosave.idleSeconds"), Some(json!(15)));
|
||||
assert_eq!(s.set("editor.autosave.onBlur", json!(false)), Ok(true));
|
||||
for bad in [json!(0), json!("false"), json!(null)] {
|
||||
assert!(matches!(
|
||||
s.set("editor.autosave.onTabSwitch", bad),
|
||||
Err(SetError::Invalid(_))
|
||||
));
|
||||
}
|
||||
assert_eq!(s.set("editor.autosave.idleSeconds", json!(0)), Ok(true));
|
||||
assert_eq!(s.set("editor.autosave.idleSeconds", json!(600)), Ok(true));
|
||||
for bad in [json!(-1), json!(601), json!(true)] {
|
||||
assert!(matches!(
|
||||
s.set("editor.autosave.idleSeconds", bad),
|
||||
Err(SetError::Invalid(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_default_is_valid() {
|
||||
for d in DEFS {
|
||||
|
|
|
|||
|
|
@ -278,6 +278,7 @@ pub fn pump(state: &mut State) {
|
|||
}
|
||||
for path in gone {
|
||||
if let Some(id) = state.buffers.find(&path) {
|
||||
state.buffers.mark_conflict(id);
|
||||
state.emit(Event::FileChangedOnDisk {
|
||||
path: path_string(&path),
|
||||
id,
|
||||
|
|
@ -297,24 +298,22 @@ pub fn pump(state: &mut State) {
|
|||
|
||||
/// Brings buffer `id` in line with its file after the file changed: a clean
|
||||
/// buffer takes the new text (unless it already matches, as after our own
|
||||
/// save), a dirty one keeps its text and the client is told. A file that
|
||||
/// cannot be read is reported like a removed one.
|
||||
/// save), a dirty one keeps its text and the client is told, and the buffer
|
||||
/// is marked as in conflict ([`crate::buffers::Buffers::mark_conflict`]).
|
||||
/// A dirty buffer whose file holds exactly what Lutra last wrote is left
|
||||
/// alone: that is our own save reported after the user typed again (an
|
||||
/// autosave followed by a keystroke). A file that cannot be read is reported
|
||||
/// like a removed one.
|
||||
fn reload(state: &mut State, id: BufferId, abs: &Path) {
|
||||
let Some(open) = state.buffers.get(id) else {
|
||||
return;
|
||||
};
|
||||
let path = path_string(&open.path);
|
||||
if open.dirty() {
|
||||
state.emit(Event::FileChangedOnDisk {
|
||||
path,
|
||||
id,
|
||||
removed: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let dirty = open.dirty();
|
||||
let file = match lutra_vfs::read_text(abs) {
|
||||
Ok(file) => file,
|
||||
Err(_) => {
|
||||
state.buffers.mark_conflict(id);
|
||||
state.emit(Event::FileChangedOnDisk {
|
||||
path,
|
||||
id,
|
||||
|
|
@ -323,17 +322,40 @@ fn reload(state: &mut State, id: BufferId, abs: &Path) {
|
|||
return;
|
||||
}
|
||||
};
|
||||
if dirty {
|
||||
if state.buffers.is_own_write(
|
||||
id,
|
||||
&crate::journal::hex_hash(file.text.as_bytes()),
|
||||
file.bom,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
state.buffers.mark_conflict(id);
|
||||
state.emit(Event::FileChangedOnDisk {
|
||||
path,
|
||||
id,
|
||||
removed: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let Some(open) = state.buffers.get(id) else {
|
||||
return;
|
||||
};
|
||||
if file.text == open.buffer.save_text() && file.bom == open.bom {
|
||||
state.buffers.clear_conflict(id);
|
||||
return;
|
||||
}
|
||||
let Some(open) = state.buffers.get_mut(id) else {
|
||||
return;
|
||||
};
|
||||
let hash = crate::journal::hex_hash(file.text.as_bytes());
|
||||
open.buffer = Buffer::new(&file.text);
|
||||
open.bom = file.bom;
|
||||
open.version = open.version.saturating_add(1);
|
||||
open.saved_version = open.version;
|
||||
let version = open.version;
|
||||
state.buffers.clear_conflict(id);
|
||||
state.buffers.note_written(id, hash, file.bom);
|
||||
state.emit(Event::BufferChanged { id, version });
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue