M1.3: engine workspace, file and buffer commands, event stream

State holds the open project (VFS project, watcher, watched directories)
and versioned buffers. New commands: project.open/close/children,
file.open/save/saveAll, buffer.get/edit/close. buffer.edit takes UTF-16
change sets based on a version and fails with the new stale_version code;
closing dirty buffers or projects without force fails with
unsaved_changes. Commands queue events (projectOpened, treeChanged,
bufferChanged, dirtyChanged, fileChangedOnDisk, ...) that the engine
returns in Outcome.events; Engine::pump_vfs maps changes on disk to
events and reloads clean buffers. project.children watches listed
directories, capped at 256 native / 32 polling, least recently listed
dropped first.

Control channel: events.subscribe streams {"event": ...} lines, with
bounded per-subscriber queues (lutra_control::Subscribers) and method docs
in methods.rs. testkit's EngineBackend and the desktop Host implement the
new Backend::subscribe. Verified with 14 engine integration tests, a TCP
events test and the running app over the control channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-14 20:24:44 +02:00
parent a63ab4ac45
commit f1976c7d67
30 changed files with 2235 additions and 46 deletions

View file

@ -12,9 +12,14 @@ publish.workspace = true
layer = 4
[dependencies]
lutra-text.workspace = true
lutra-vfs.workspace = true
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
thiserror = "2.0.21"
[lints]
workspace = true
[dev-dependencies]
tempfile.workspace = true

View file

@ -0,0 +1,125 @@
//! Open buffers: the engine's copy of every file the user is editing.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use lutra_text::{Buffer, LineEnding};
use serde::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,
}
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.by_id.remove(&id)
}
/// 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.by_id.clear();
}
}
/// A line ending as sent to clients: `"lf"`, `"crlf"` or `"cr"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[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,
}
}
}

View file

@ -0,0 +1,219 @@
//! Buffer commands: `buffer.get`, `buffer.edit`, `buffer.close`.
//!
//! Edits use UTF-16 code unit offsets, as CodeMirror and LSP do, and follow
//! CodeMirror's change-set semantics: every `{from, to}` of a batch refers
//! to the text at `baseVersion`, ranges must not overlap, and the batch is
//! applied atomically. An edit based on an older version is rejected with
//! `stale_version`; the client fetches the text with `buffer.get` and
//! reapplies its pending changes.
use serde::Deserialize;
use serde_json::{Value, json};
use super::params::parse;
use crate::buffers::{BufferId, LineEndingName};
use crate::workspace::path_string;
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
/// Most edits accepted in one `buffer.edit`.
pub const MAX_EDITS: usize = 100_000;
/// Most inserted bytes accepted in one `buffer.edit`.
pub const MAX_INSERT_BYTES: usize = 64 * 1024 * 1024;
/// The full description of buffer `id`, as returned by `file.open` and
/// `buffer.get`.
///
/// # Errors
/// [`EngineError::Failed`] for an unknown buffer.
pub fn describe(state: &State, command: &str, id: BufferId) -> Result<Value, EngineError> {
let open = state
.buffers
.get(id)
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {id}")))?;
Ok(json!({
"id": id,
"path": path_string(&open.path),
"text": open.buffer.text(),
"version": open.version,
"dirty": open.dirty(),
"lineEnding": LineEndingName::from(open.buffer.line_ending()),
}))
}
/// Params naming one buffer.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct IdParams {
/// Buffer id.
id: BufferId,
}
/// `buffer.get`: the text and state of a buffer.
pub struct Get;
impl Command for Get {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "buffer.get",
label: "Get Buffer",
menu_path: None,
default_shortcut: None,
params: "{ id: number }; returns { id, path, text, version, dirty, lineEnding }",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let p: IdParams = parse(self.spec().id, params)?;
describe(state, self.spec().id, p.id).map(Outcome::value)
}
}
/// One change of a `buffer.edit` batch.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Change {
/// Start, in UTF-16 code units of the text at the base version.
from: usize,
/// End (exclusive), same units; equal to `from` for an insertion.
to: usize,
/// Text to insert; empty for a deletion.
#[serde(default)]
insert: String,
}
/// Params of `buffer.edit`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct EditParams {
/// Buffer id.
id: BufferId,
/// The version the changes are based on.
base_version: u64,
/// The changes.
edits: Vec<Change>,
}
/// `buffer.edit`: applies a batch of changes.
pub struct Edit;
impl Command for Edit {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "buffer.edit",
label: "Edit Buffer",
menu_path: None,
default_shortcut: None,
params: "{ id: number, baseVersion: number, edits: [{ from, to, insert }] } with UTF-16 offsets into the text at baseVersion; returns { id, version, dirty }; fails with stale_version if baseVersion is not the current version",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: EditParams = parse(command, params)?;
if p.edits.len() > MAX_EDITS {
return Err(EngineError::invalid_params(
command,
format!("at most {MAX_EDITS} edits per call"),
));
}
let inserted: usize = p.edits.iter().map(|c| c.insert.len()).sum();
if inserted > MAX_INSERT_BYTES {
return Err(EngineError::invalid_params(
command,
format!("at most {MAX_INSERT_BYTES} inserted bytes per call"),
));
}
let open = state
.buffers
.get_mut(p.id)
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {}", p.id)))?;
if p.base_version != open.version {
return Err(EngineError::StaleVersion {
id: p.id,
base: p.base_version,
current: open.version,
});
}
if p.edits.is_empty() {
let (version, dirty) = (open.version, open.dirty());
return Ok(Outcome::value(
json!({ "id": p.id, "version": version, "dirty": dirty }),
));
}
let mut edits = Vec::with_capacity(p.edits.len());
for change in p.edits {
let invalid =
|e: lutra_text::TextError| EngineError::invalid_params(command, e.to_string());
let from = open.buffer.utf16_to_offset(change.from).map_err(invalid)?;
let to = open.buffer.utf16_to_offset(change.to).map_err(invalid)?;
edits.push(lutra_text::Edit::replace(from..to, change.insert));
}
let was_dirty = open.dirty();
open.buffer
.apply(&edits)
.map_err(|e| EngineError::invalid_params(command, e.to_string()))?;
open.version = open.version.saturating_add(1);
let (version, dirty) = (open.version, open.dirty());
state.emit(Event::BufferChanged { id: p.id, version });
if dirty != was_dirty {
state.emit(Event::DirtyChanged { id: p.id, dirty });
}
Ok(Outcome::value(
json!({ "id": p.id, "version": version, "dirty": dirty }),
))
}
}
/// Params of `buffer.close`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CloseParams {
/// Buffer id.
id: BufferId,
/// Discard unsaved changes.
#[serde(default)]
force: bool,
}
/// `buffer.close`: closes a buffer.
pub struct Close;
impl Command for Close {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "buffer.close",
label: "Close Buffer",
menu_path: None,
default_shortcut: None,
params: "{ id: number, force?: bool (discard unsaved changes) }; returns null; fails with unsaved_changes if the buffer is dirty and force is not set",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: CloseParams = parse(command, params)?;
let open = state
.buffers
.get(p.id)
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {}", p.id)))?;
if open.dirty() && !p.force {
return Err(EngineError::UnsavedChanges(path_string(&open.path)));
}
state.buffers.remove(p.id);
state.emit(Event::BufferClosed { id: p.id });
Ok(Outcome::value(Value::Null))
}
}

View file

@ -0,0 +1,152 @@
//! File commands: `file.open`, `file.save`, `file.saveAll`.
use serde::Deserialize;
use serde_json::{Value, json};
use super::buffer::describe;
use super::params::{absolute, parse, project_path};
use crate::buffers::{BufferId, OpenBuffer};
use crate::workspace::{path_string, vfs_error};
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
/// Params of `file.open`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct OpenParams {
/// Project-relative or absolute path of the file.
path: String,
}
/// `file.open`: opens a file into a buffer, or returns the buffer that
/// already holds it.
pub struct Open;
impl Command for Open {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "file.open",
label: "Open File",
menu_path: None,
default_shortcut: None,
params: "{ path: string (project-relative or absolute inside the project) }; returns { id, path, text, version, dirty, lineEnding: lf|crlf|cr }",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let id = self.spec().id;
let p: OpenParams = parse(id, params)?;
let rel = project_path(state, id, &p.path)?;
if let Some(existing) = state.buffers.find(&rel) {
return describe(state, id, existing).map(Outcome::value);
}
let abs = absolute(state, id, &rel)?;
let file = lutra_vfs::read_text(&abs).map_err(vfs_error)?;
let buffer = OpenBuffer {
buffer: lutra_text::Buffer::new(&file.text),
path: rel.clone(),
version: 1,
saved_version: 1,
bom: file.bom,
};
let new_id = state.buffers.insert(buffer);
state.emit(Event::BufferOpened {
id: new_id,
path: path_string(&rel),
});
describe(state, id, new_id).map(Outcome::value)
}
}
/// Writes buffer `id` to its file, keeping its line ending and byte order
/// mark, and marks it clean.
///
/// # Errors
/// [`EngineError::Failed`] for an unknown buffer or a failed write.
fn save(state: &mut State, command: &str, id: BufferId) -> Result<u64, EngineError> {
let open = state
.buffers
.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 open = state
.buffers
.get_mut(id)
.ok_or_else(|| EngineError::Failed(format!("no buffer {id}")))?;
let was_dirty = open.dirty();
open.saved_version = open.version;
let version = open.version;
if was_dirty {
state.emit(Event::DirtyChanged { id, dirty: false });
}
Ok(version)
}
/// Params of `file.save`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SaveParams {
/// Buffer id.
id: BufferId,
}
/// `file.save`: writes one buffer to disk.
pub struct Save;
impl Command for Save {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "file.save",
label: "Save",
menu_path: Some("File/Save"),
default_shortcut: Some("Mod+S"),
params: "{ id: number }; returns { id, version }",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let p: SaveParams = parse(self.spec().id, params)?;
let version = save(state, self.spec().id, p.id)?;
Ok(Outcome::value(json!({ "id": p.id, "version": version })))
}
}
/// `file.saveAll`: writes every dirty buffer. A failure doesn't stop the
/// others; failures are listed in the result.
pub struct SaveAll;
impl Command for SaveAll {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "file.saveAll",
label: "Save All",
menu_path: Some("File/Save All"),
default_shortcut: Some("Mod+Alt+S"),
params: "none; returns { saved: [id], failed: [{ id, message }] }",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
let mut saved = Vec::new();
let mut failed = Vec::new();
for id in state.buffers.dirty_ids() {
match save(state, self.spec().id, id) {
Ok(_) => saved.push(id),
Err(e) => failed.push(json!({ "id": id, "message": e.to_string() })),
}
}
Ok(Outcome::value(json!({ "saved": saved, "failed": failed })))
}
}

View file

@ -1,6 +1,10 @@
//! Built-in commands, one module per area.
mod app;
mod buffer;
mod file;
mod params;
mod project;
use crate::{EngineError, Registry};
@ -11,5 +15,14 @@ use crate::{EngineError, Registry};
pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(app::About))?;
registry.register(Box::new(app::Quit))?;
registry.register(Box::new(project::Open))?;
registry.register(Box::new(project::Close))?;
registry.register(Box::new(project::Children))?;
registry.register(Box::new(file::Open))?;
registry.register(Box::new(file::Save))?;
registry.register(Box::new(file::SaveAll))?;
registry.register(Box::new(buffer::Get))?;
registry.register(Box::new(buffer::Edit))?;
registry.register(Box::new(buffer::Close))?;
Ok(())
}

View file

@ -0,0 +1,59 @@
//! Shared helpers for command params: typed parsing and project paths.
use std::path::{Path, PathBuf};
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::workspace::vfs_error;
use crate::{EngineError, State};
/// Parses `params` into `T`. `null` counts as an empty object, so commands
/// whose params are all optional accept both.
///
/// # Errors
/// [`EngineError::InvalidParams`] naming `command` if the params don't match.
pub fn parse<T: DeserializeOwned>(command: &str, params: Value) -> Result<T, EngineError> {
let params = if params.is_null() {
Value::Object(serde_json::Map::new())
} else {
params
};
serde_json::from_value(params).map_err(|e| EngineError::invalid_params(command, e.to_string()))
}
/// Resolves a path from a client to a project-relative path: relative paths
/// (with `/` or the platform separator) are taken as they are, absolute ones
/// must lie inside the project. The VFS rejects `..` and other escapes when
/// the path is used.
///
/// # Errors
/// [`EngineError::Disabled`] without a project, [`EngineError::Failed`] for
/// an absolute path outside the project.
pub fn project_path(state: &State, command: &str, path: &str) -> Result<PathBuf, EngineError> {
let workspace = state
.project
.as_ref()
.ok_or_else(|| EngineError::Disabled(command.to_string()))?;
let given = Path::new(path);
if given.is_absolute() {
return workspace
.project
.relative(given)
.ok_or_else(|| EngineError::Failed(format!("{path} is outside the project")));
}
Ok(given.components().collect())
}
/// Resolves a project-relative path to an absolute one.
///
/// # Errors
/// [`EngineError::Disabled`] without a project, [`EngineError::Failed`] if
/// the path escapes the project.
pub fn absolute(state: &State, command: &str, rel: &Path) -> Result<PathBuf, EngineError> {
let workspace = state
.project
.as_ref()
.ok_or_else(|| EngineError::Disabled(command.to_string()))?;
workspace.project.resolve(rel).map_err(vfs_error)
}

View file

@ -0,0 +1,197 @@
//! Project commands: `project.open`, `project.close`, `project.children`.
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::params::{parse, project_path};
use crate::workspace::{Workspace, path_string, vfs_error};
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
/// Closes the open project and all its buffers.
///
/// # Errors
/// [`EngineError::UnsavedChanges`] if a buffer is dirty and `force` is false.
pub fn close_project(state: &mut State, force: bool) -> Result<(), EngineError> {
if state.project.is_none() {
return Ok(());
}
let dirty = state.buffers.dirty_ids();
if !force && let Some(first) = dirty.first() {
let name = state
.buffers
.get(*first)
.map(|b| path_string(&b.path))
.unwrap_or_default();
let what = if dirty.len() == 1 {
name
} else {
format!("{name} and {} more files", dirty.len() - 1)
};
return Err(EngineError::UnsavedChanges(what));
}
for id in state.buffers.ids() {
state.buffers.remove(id);
state.emit(Event::BufferClosed { id });
}
state.project = None;
state.emit(Event::ProjectClosed);
Ok(())
}
/// Params of `project.open`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct OpenParams {
/// Folder to open.
path: String,
/// Discard unsaved changes of a project that is open.
#[serde(default)]
force: bool,
}
/// `project.open`: opens a folder as the project, closing the current one.
pub struct Open;
impl Command for Open {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "project.open",
label: "Open Folder",
menu_path: None,
default_shortcut: None,
params: "{ path: string (absolute folder), force?: bool (discard unsaved changes of the open project) }; returns { root, name }",
}
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let p: OpenParams = parse(self.spec().id, params)?;
let (workspace, events) = Workspace::open(std::path::Path::new(&p.path))?;
close_project(state, p.force)?;
let root = workspace.project.root().to_path_buf();
state.project = Some(workspace);
let mut name = String::new();
for event in events {
if let Event::ProjectOpened { name: n, .. } = &event {
name = n.clone();
}
state.emit(event);
}
Ok(Outcome::value(json!({
"root": root.to_string_lossy(),
"name": name,
})))
}
}
/// Params of `project.close`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CloseParams {
/// Discard unsaved changes.
#[serde(default)]
force: bool,
}
/// `project.close`: closes the project and its buffers.
pub struct Close;
impl Command for Close {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "project.close",
label: "Close Project",
menu_path: Some("File/Close Project"),
default_shortcut: None,
params: "{ force?: bool (discard unsaved changes) }; returns null; fails with unsaved_changes if a buffer is dirty and force is not set",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let p: CloseParams = parse(self.spec().id, params)?;
close_project(state, p.force)?;
Ok(Outcome::value(Value::Null))
}
}
/// Params of `project.children`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ChildrenParams {
/// Directory, project-relative; `""` or missing for the root.
#[serde(default)]
dir: String,
}
/// One entry of a `project.children` result.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct EntryOut {
/// Display name.
name: String,
/// Project-relative path.
path: String,
/// `file`, `directory` or `other`.
kind: &'static str,
/// Matched by an ignore rule.
ignored: bool,
/// `normal`, `library` or `excluded`.
role: &'static str,
}
/// `project.children`: lists one directory and watches it for changes.
pub struct Children;
impl Command for Children {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "project.children",
label: "List Directory",
menu_path: None,
default_shortcut: None,
params: "{ dir?: string (project-relative, \"\" = root) }; returns { dir, entries: [{ name, path, kind: file|directory|other, ignored, role: normal|library|excluded }], truncated }",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let p: ChildrenParams = parse(self.spec().id, params)?;
let dir = project_path(state, self.spec().id, &p.dir)?;
let workspace = state
.project
.as_mut()
.ok_or_else(|| EngineError::Disabled(self.spec().id.to_string()))?;
let listing = workspace.project.children(&dir).map_err(vfs_error)?;
workspace.touch_dir(&dir);
let entries: Vec<EntryOut> = listing
.entries
.into_iter()
.map(|e| EntryOut {
name: e.name,
path: path_string(&e.path),
kind: match e.kind {
lutra_vfs::EntryKind::File => "file",
lutra_vfs::EntryKind::Directory => "directory",
lutra_vfs::EntryKind::Other => "other",
},
ignored: e.ignored,
role: match e.role {
lutra_vfs::EntryRole::Normal => "normal",
lutra_vfs::EntryRole::Library => "library",
lutra_vfs::EntryRole::Excluded => "excluded",
},
})
.collect();
Ok(Outcome::value(json!({
"dir": path_string(&dir),
"entries": entries,
"truncated": listing.truncated,
})))
}
}

View file

@ -4,7 +4,7 @@
use serde::Serialize;
use serde_json::Value;
use crate::{EngineError, State};
use crate::{EngineError, Event, State};
/// Static metadata of a command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -37,6 +37,9 @@ pub struct Outcome {
pub value: Value,
/// Effects for the host to apply, in order.
pub effects: Vec<Effect>,
/// State changes for the host to publish, oldest first. Filled by the
/// engine from the events the command queued; commands leave it empty.
pub events: Vec<Event>,
}
impl Outcome {
@ -45,6 +48,7 @@ impl Outcome {
Self {
value,
effects: Vec::new(),
events: Vec::new(),
}
}
@ -53,6 +57,7 @@ impl Outcome {
Self {
value: Value::Null,
effects: vec![effect],
events: Vec::new(),
}
}
}

View file

@ -44,7 +44,11 @@ impl Engine {
self.registry.register(command)
}
/// Runs a command inside the guard.
/// Runs a command inside the guard. On success the outcome carries every
/// event queued so far. When the command fails, events it queued before
/// failing (real changes, such as files saved before another failed) stay
/// queued and arrive with the next successful outcome or
/// [`Engine::take_events`].
///
/// # Errors
/// [`EngineError::UnknownCommand`] for an unknown id,
@ -62,7 +66,31 @@ impl Engine {
command.run(state, params)
});
state.commands_run = state.commands_run.saturating_add(1);
result
result.map(|mut outcome| {
outcome.events = state.take_events();
outcome
})
}
/// Applies pending changes on disk (reloads clean buffers, reports
/// changed directories and conflicts) and returns every queued event.
/// Hosts call it regularly, e.g. every 100 ms from a background thread.
///
/// # Errors
/// [`EngineError::Internal`] if handling the changes panicked; the queued
/// events stay queued.
pub fn pump_vfs(&mut self) -> Result<Vec<crate::Event>, EngineError> {
let state = &mut self.state;
guard::run(|| {
crate::workspace::pump(state);
Ok(())
})?;
Ok(state.take_events())
}
/// Takes the queued events, oldest first.
pub fn take_events(&mut self) -> Vec<crate::Event> {
self.state.take_events()
}
/// Describes every command with its current enabled state. A command whose
@ -191,11 +219,30 @@ mod tests {
engine.register(Box::new(Disabled)).unwrap();
let list = engine.list_commands();
let ids: Vec<_> = list.iter().map(|c| c.id.as_str()).collect();
assert_eq!(ids, vec!["app.about", "app.quit", "test.disabled"]);
let quit = &list[1];
assert_eq!(
ids,
vec![
"app.about",
"app.quit",
"buffer.close",
"buffer.edit",
"buffer.get",
"file.open",
"file.save",
"file.saveAll",
"project.children",
"project.close",
"project.open",
"test.disabled",
]
);
let by_id = |id: &str| list.iter().find(|c| c.id == id).unwrap();
let quit = by_id("app.quit");
assert_eq!(quit.default_shortcut.as_deref(), Some("Mod+Q"));
assert!(quit.enabled);
assert!(!list[2].enabled);
assert!(!by_id("test.disabled").enabled);
assert!(by_id("project.open").enabled);
assert!(!by_id("file.open").enabled, "needs a project");
let json = serde_json::to_value(quit).unwrap();
assert_eq!(json["menuPath"], "File/Quit");
}

View file

@ -22,6 +22,21 @@ pub enum EngineError {
/// What is wrong with the params.
message: String,
},
/// An edit was based on an older version of the buffer than the engine
/// holds. The caller resynchronises (`buffer.get`) and retries.
#[error("buffer {id} is at version {current}, the edit was based on version {base}")]
StaleVersion {
/// The buffer id.
id: u64,
/// The version the caller based its edit on.
base: u64,
/// The engine's current version.
current: u64,
},
/// The action would discard unsaved changes; repeat it with `force` to
/// discard them.
#[error("{0} has unsaved changes")]
UnsavedChanges(String),
/// The command ran and failed, e.g. a file could not be read.
#[error("{0}")]
Failed(String),
@ -38,11 +53,21 @@ impl EngineError {
Self::UnknownCommand(_) => "unknown_command",
Self::Disabled(_) => "disabled",
Self::InvalidParams { .. } => "invalid_params",
Self::StaleVersion { .. } => "stale_version",
Self::UnsavedChanges(_) => "unsaved_changes",
Self::Failed(_) => "failed",
Self::Internal(_) => "internal",
}
}
/// Shorthand for [`EngineError::InvalidParams`].
pub fn invalid_params(command: &str, message: impl Into<String>) -> Self {
Self::InvalidParams {
command: command.to_string(),
message: message.into(),
}
}
/// The error as a `{ code, message }` payload for IPC and the control
/// channel.
pub fn payload(&self) -> ErrorPayload {

103
crates/engine/src/event.rs Normal file
View file

@ -0,0 +1,103 @@
//! Events: state changes the engine pushes to its hosts.
//!
//! Commands and [`crate::Engine::pump_vfs`] queue events in the state; the
//! engine hands them to the host with each [`crate::Outcome`] and from each
//! pump. Hosts fan them out to the frontend (Tauri events) and to control
//! channel subscribers (`events.subscribe`). Events describe what changed;
//! consumers fetch data they need with commands (`project.children`,
//! `buffer.get`).
//!
//! Serialised as `{"kind": "<camelCase variant>", ...fields in camelCase}`.
//! Paths are project-relative with `/` separators, the root is `""`.
use serde::Serialize;
/// A state change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(
tag = "kind",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
pub enum Event {
/// A project was opened.
ProjectOpened {
/// Absolute root path.
root: String,
/// Folder name, for titles.
name: String,
},
/// The project was closed; all buffers are gone.
ProjectClosed,
/// The children of a directory changed on disk; refetch them with
/// `project.children`.
TreeChanged {
/// The directory.
dir: String,
},
/// A buffer was opened.
BufferOpened {
/// Buffer id.
id: u64,
/// File path.
path: String,
},
/// A buffer's text changed; `version` is the new version.
BufferChanged {
/// Buffer id.
id: u64,
/// New version.
version: u64,
},
/// A buffer became dirty or clean.
DirtyChanged {
/// Buffer id.
id: u64,
/// Whether it has unsaved changes.
dirty: bool,
},
/// A buffer was closed.
BufferClosed {
/// Buffer id.
id: u64,
},
/// The file of an open buffer changed or disappeared on disk and the
/// buffer kept its text: it is dirty, or the file is gone.
FileChangedOnDisk {
/// File path.
path: String,
/// The open buffer.
id: u64,
/// The file was removed or renamed away.
removed: bool,
},
/// File watching stopped; the project keeps working without it.
WatchFailed {
/// Why.
message: String,
},
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::Event;
#[test]
fn serialises_with_kind_and_camel_case_fields() {
let e = Event::FileChangedOnDisk {
path: "src/a.php".into(),
id: 3,
removed: false,
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "fileChangedOnDisk", "path": "src/a.php", "id": 3, "removed": false})
);
assert_eq!(
serde_json::to_value(Event::ProjectClosed).unwrap(),
json!({"kind": "projectClosed"})
);
}
}

View file

@ -5,17 +5,22 @@
//! [`Command`]; menus, the palette, shortcuts, the CLI, the control channel and
//! MCP all reach it through [`Engine::execute`].
mod buffers;
pub mod cmd;
mod command;
mod engine;
mod error;
mod event;
pub mod guard;
mod registry;
mod state;
pub mod theme;
pub mod workspace;
pub use buffers::{BufferId, LineEndingName, OpenBuffer};
pub use command::{Command, CommandInfo, CommandSpec, Effect, Outcome};
pub use engine::Engine;
pub use error::{EngineError, ErrorPayload};
pub use event::Event;
pub use registry::Registry;
pub use state::State;

View file

@ -1,10 +1,35 @@
//! Workspace state that commands read and change.
use crate::Event;
use crate::buffers::Buffers;
use crate::workspace::Workspace;
/// Everything the engine knows about the running session.
///
/// Empty in milestone M0; M1 adds the open project, buffers and settings.
#[derive(Debug, Default)]
pub struct State {
/// Number of commands that ran to completion, successful or not.
pub commands_run: u64,
/// The open project, if any.
pub project: Option<Workspace>,
/// Open buffers. Empty whenever no project is open.
pub buffers: Buffers,
/// Events queued for the host, oldest first.
events: Vec<Event>,
}
impl State {
/// Queues an event for the host.
pub fn emit(&mut self, event: Event) {
self.events.push(event);
}
/// Takes the queued events, oldest first.
pub fn take_events(&mut self) -> Vec<Event> {
std::mem::take(&mut self.events)
}
/// Whether a project is open.
pub fn has_project(&self) -> bool {
self.project.is_some()
}
}

View file

@ -0,0 +1,283 @@
//! The open project: the VFS project, its watcher, and the translation of
//! changes on disk into engine events and buffer reloads.
//!
//! # Watched directories
//! The VFS watcher is non-recursive: the root is watched from the start and
//! [`Workspace::touch_dir`] adds each directory whose children a client
//! lists. To keep the cost bounded on huge trees (a deep `vendor/`), at most
//! [`MAX_WATCHED_DIRS_NATIVE`] directories besides the root are watched with
//! native notifications, and [`MAX_WATCHED_DIRS_POLLING`] when the watcher
//! fell back to polling, where every watched directory is rescanned each
//! interval. When the limit is reached the directory listed least recently
//! is unwatched; listing it again watches it again. Changes inside an
//! unwatched directory are not reported until then.
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, TryRecvError};
use lutra_text::Buffer;
use lutra_vfs::{Project, VfsError, VfsEvent, Watcher};
use crate::buffers::BufferId;
use crate::{EngineError, Event, State};
/// Directories watched besides the root with native notifications.
pub const MAX_WATCHED_DIRS_NATIVE: usize = 256;
/// Directories watched besides the root when polling.
pub const MAX_WATCHED_DIRS_POLLING: usize = 32;
/// Most VFS events handled by one pump; the rest wait for the next one.
pub const MAX_EVENTS_PER_PUMP: usize = 10_000;
/// An open project.
#[derive(Debug)]
pub struct Workspace {
/// The VFS project.
pub project: Project,
/// The watcher, `None` if watching is unavailable or failed.
watcher: Option<Watcher>,
/// Changes on disk from the watcher.
events: Option<Receiver<VfsEvent>>,
/// Directories watched besides the root, least recently listed first.
watched: VecDeque<PathBuf>,
}
impl Workspace {
/// Opens the folder at `path` and starts watching it. A watcher that
/// cannot start is not an error: the workspace works without it and the
/// returned events contain [`Event::WatchFailed`].
///
/// # Errors
/// [`EngineError::Failed`] if the folder cannot be opened.
pub fn open(path: &Path) -> Result<(Self, Vec<Event>), EngineError> {
let project = Project::open(path).map_err(vfs_error)?;
let root = project.root().to_path_buf();
let mut events = vec![Event::ProjectOpened {
root: root.to_string_lossy().into_owned(),
name: root
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| root.to_string_lossy().into_owned()),
}];
let (watcher, receiver) = match project.watch() {
Ok((watcher, receiver)) => (Some(watcher), Some(receiver)),
Err(e) => {
events.push(Event::WatchFailed {
message: e.to_string(),
});
(None, None)
}
};
Ok((
Self {
project,
watcher,
events: receiver,
watched: VecDeque::new(),
},
events,
))
}
/// Records that a client listed `dir` and watches it, unwatching the
/// least recently listed directory if the limit is reached. Watching is
/// best effort: a directory the watcher refuses or cannot read is simply
/// not watched, because listing it worked and that is what the caller
/// asked for.
pub fn touch_dir(&mut self, dir: &Path) {
let Some(watcher) = &self.watcher else {
return;
};
if dir.as_os_str().is_empty() {
return;
}
if let Some(at) = self.watched.iter().position(|d| d == dir) {
if let Some(d) = self.watched.remove(at) {
self.watched.push_back(d);
}
return;
}
if !matches!(watcher.watch_dir(dir), Ok(true)) {
return;
}
self.watched.push_back(dir.to_path_buf());
let limit = self.watch_limit();
let Some(watcher) = &self.watcher else {
return;
};
while self.watched.len() > limit {
if let Some(old) = self.watched.pop_front() {
watcher.unwatch_dir(&old);
}
}
}
/// How many directories besides the root may be watched with the
/// current backend; 0 without a watcher.
pub fn watch_limit(&self) -> usize {
match &self.watcher {
Some(w) if w.is_native() => MAX_WATCHED_DIRS_NATIVE,
Some(_) => MAX_WATCHED_DIRS_POLLING,
None => 0,
}
}
/// Directories watched besides the root, least recently listed first.
pub fn watched_dirs(&self) -> Vec<PathBuf> {
self.watched.iter().cloned().collect()
}
/// Whether the project is watched.
pub fn is_watching(&self) -> bool {
self.watcher.is_some()
}
/// Takes up to [`MAX_EVENTS_PER_PUMP`] pending changes from the watcher.
/// A failed or disconnected watcher is dropped and reported once.
fn drain(&mut self) -> (Vec<VfsEvent>, Option<String>) {
let mut out = Vec::new();
let mut failure = None;
let Some(receiver) = &self.events else {
return (out, None);
};
while out.len() < MAX_EVENTS_PER_PUMP {
match receiver.try_recv() {
Ok(VfsEvent::Failed(e)) => {
failure = Some(e.to_string());
break;
}
Ok(event) => out.push(event),
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => {
failure = Some("the file watcher stopped".to_string());
break;
}
}
}
if failure.is_some() {
self.watcher = None;
self.events = None;
self.watched.clear();
}
(out, failure)
}
}
/// Applies pending changes on disk to the state: queues
/// [`Event::TreeChanged`] for affected directories, reloads clean buffers
/// whose file changed, and queues [`Event::FileChangedOnDisk`] for dirty
/// buffers and for buffers whose file disappeared.
pub fn pump(state: &mut State) {
let Some(workspace) = state.project.as_mut() else {
return;
};
let (changes, failure) = workspace.drain();
let root = workspace.project.root().to_path_buf();
let mut dirs: Vec<PathBuf> = Vec::new();
let mut add_dir = |path: &Path| {
let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();
if !dirs.contains(&dir) {
dirs.push(dir);
}
};
let mut modified = Vec::new();
let mut gone = Vec::new();
for change in changes {
match change {
VfsEvent::Created { path, .. } => add_dir(&path),
VfsEvent::Removed { path } => {
add_dir(&path);
gone.push(path);
}
VfsEvent::Renamed { from, to } => {
add_dir(&from);
add_dir(&to);
gone.push(from);
}
VfsEvent::Modified { path } => modified.push(path),
VfsEvent::Failed(_) => {}
}
}
for dir in dirs {
state.emit(Event::TreeChanged {
dir: path_string(&dir),
});
}
for path in gone {
if let Some(id) = state.buffers.find(&path) {
state.emit(Event::FileChangedOnDisk {
path: path_string(&path),
id,
removed: true,
});
}
}
for path in modified {
if let Some(id) = state.buffers.find(&path) {
reload(state, id, &root.join(&path));
}
}
if let Some(message) = failure {
state.emit(Event::WatchFailed { message });
}
}
/// 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.
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 file = match lutra_vfs::read_text(abs) {
Ok(file) => file,
Err(_) => {
state.emit(Event::FileChangedOnDisk {
path,
id,
removed: true,
});
return;
}
};
if file.text == open.buffer.save_text() && file.bom == open.bom {
return;
}
let Some(open) = state.buffers.get_mut(id) else {
return;
};
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.emit(Event::BufferChanged { id, version });
}
/// A project-relative path as sent to clients: `/` separators, `""` for the
/// root.
pub fn path_string(path: &Path) -> String {
let text = path.to_string_lossy();
if std::path::MAIN_SEPARATOR == '/' {
text.into_owned()
} else {
text.replace(std::path::MAIN_SEPARATOR, "/")
}
}
/// Converts a VFS error into an engine error.
pub fn vfs_error(error: VfsError) -> EngineError {
EngineError::Failed(error.to_string())
}

View file

@ -0,0 +1,445 @@
//! Workspace commands and events against real folders in temp directories.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::fs;
use std::path::Path;
use std::time::{Duration, Instant};
use lutra_engine::{Command, CommandSpec, Engine, EngineError, Event, Outcome, State};
use serde_json::{Value, json};
use tempfile::TempDir;
/// A temp folder with a few files, opened in a fresh engine.
fn open_project(files: &[(&str, &[u8])]) -> (TempDir, Engine, Vec<Event>) {
let dir = tempfile::tempdir().unwrap();
for (path, bytes) in files {
let abs = dir.path().join(path);
fs::create_dir_all(abs.parent().unwrap()).unwrap();
fs::write(abs, bytes).unwrap();
}
let mut engine = Engine::new().unwrap();
let out = engine
.execute("project.open", json!({"path": dir.path()}))
.unwrap();
(dir, engine, out.events)
}
fn run(engine: &mut Engine, command: &str, params: Value) -> Outcome {
engine
.execute(command, params)
.unwrap_or_else(|e| panic!("{command} failed: {e}"))
}
fn open_file(engine: &mut Engine, path: &str) -> (u64, Value) {
let out = run(engine, "file.open", json!({"path": path}));
(out.value["id"].as_u64().unwrap(), out.value)
}
/// Pumps VFS events until `pred` matches one, or fails after five seconds.
fn wait_for(engine: &mut Engine, pred: impl Fn(&Event) -> bool) -> Vec<Event> {
let deadline = Instant::now() + Duration::from_secs(5);
let mut seen = Vec::new();
while Instant::now() < deadline {
let events = engine.pump_vfs().unwrap();
let hit = events.iter().any(&pred);
seen.extend(events);
if hit {
return seen;
}
std::thread::sleep(Duration::from_millis(25));
}
panic!("event not seen within 5 s; got {seen:?}");
}
#[test]
fn file_commands_are_disabled_without_a_project() {
let mut engine = Engine::new().unwrap();
for (command, params) in [
("project.children", json!({})),
("project.close", json!({})),
("file.open", json!({"path": "a.php"})),
("file.save", json!({"id": 1})),
("file.saveAll", Value::Null),
("buffer.get", json!({"id": 1})),
(
"buffer.edit",
json!({"id": 1, "baseVersion": 1, "edits": []}),
),
("buffer.close", json!({"id": 1})),
] {
let err = engine.execute(command, params).unwrap_err();
assert_eq!(err.code(), "disabled", "{command}");
}
}
#[test]
fn opening_a_missing_folder_fails_and_keeps_state() {
let mut engine = Engine::new().unwrap();
let err = engine
.execute("project.open", json!({"path": "/definitely/not/here"}))
.unwrap_err();
assert_eq!(err.code(), "failed");
assert!(!engine.state().has_project());
}
#[test]
fn open_lists_children_and_reports_the_project() {
let (dir, mut engine, events) = open_project(&[
("src/Kernel.php", b"<?php\n"),
("b.txt", b"b"),
("A.txt", b"a"),
(".gitignore", b"b.txt\n"),
("vendor/x/y.php", b"<?php\n"),
]);
let root = fs::canonicalize(dir.path()).unwrap();
assert!(matches!(&events[0], Event::ProjectOpened { name, .. }
if *name == root.file_name().unwrap().to_string_lossy()));
let out = run(&mut engine, "project.children", json!({}));
let names: Vec<&str> = out.value["entries"]
.as_array()
.unwrap()
.iter()
.map(|e| e["name"].as_str().unwrap())
.collect();
assert_eq!(names, ["src", "vendor", ".gitignore", "A.txt", "b.txt"]);
let entries = out.value["entries"].as_array().unwrap();
let by_name = |n: &str| entries.iter().find(|e| e["name"] == n).unwrap();
assert_eq!(by_name("b.txt")["ignored"], true);
assert_eq!(by_name("vendor")["role"], "library");
assert_eq!(by_name("src")["kind"], "directory");
let out = run(&mut engine, "project.children", json!({"dir": "src"}));
assert_eq!(out.value["entries"][0]["path"], "src/Kernel.php");
let err = engine
.execute("project.children", json!({"dir": "../.."}))
.unwrap_err();
assert_eq!(err.code(), "failed");
}
#[test]
fn edit_save_and_dirty_state() {
let (dir, mut engine, _) = open_project(&[("a.php", "<?php\n// 😀 x\n".as_bytes())]);
let (id, opened) = open_file(&mut engine, "a.php");
assert_eq!(opened["version"], 1);
assert_eq!(opened["dirty"], false);
assert_eq!(opened["lineEnding"], "lf");
let (again, _) = open_file(&mut engine, "a.php");
assert_eq!(again, id, "opening twice returns the same buffer");
let after_emoji = "<?php\n// 😀".encode_utf16().count();
let out = run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [
{"from": 0, "to": 5, "insert": "<?PHP"},
{"from": after_emoji, "to": after_emoji + 2, "insert": "!"}
]}),
);
assert_eq!(out.value, json!({"id": id, "version": 2, "dirty": true}));
assert_eq!(
out.events,
vec![
Event::BufferChanged { id, version: 2 },
Event::DirtyChanged { id, dirty: true }
]
);
let text = run(&mut engine, "buffer.get", json!({"id": id})).value["text"].clone();
assert_eq!(text, "<?PHP\n// 😀!\n");
let out = run(&mut engine, "file.save", json!({"id": id}));
assert_eq!(out.value["version"], 2);
assert_eq!(out.events, vec![Event::DirtyChanged { id, dirty: false }]);
assert_eq!(
fs::read_to_string(dir.path().join("a.php")).unwrap(),
"<?PHP\n// 😀!\n"
);
}
#[test]
fn stale_and_invalid_edits_are_rejected_without_change() {
let (_dir, mut engine, _) = open_project(&[("a.php", "a😀b".as_bytes())]);
let (id, _) = open_file(&mut engine, "a.php");
run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "x"}]}),
);
let err = engine
.execute(
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "y"}]}),
)
.unwrap_err();
assert_eq!(err.code(), "stale_version");
assert_eq!(
err,
EngineError::StaleVersion {
id,
base: 1,
current: 2
}
);
for edits in [
json!([{"from": 3, "to": 3, "insert": "z"}]),
json!([{"from": 0, "to": 99, "insert": ""}]),
json!([{"from": 0, "to": 2}, {"from": 1, "to": 3}]),
] {
let err = engine
.execute(
"buffer.edit",
json!({"id": id, "baseVersion": 2, "edits": edits}),
)
.unwrap_err();
assert_eq!(err.code(), "invalid_params", "{edits}");
}
let got = run(&mut engine, "buffer.get", json!({"id": id})).value;
assert_eq!(got["text"], "xa😀b");
assert_eq!(got["version"], 2);
}
#[test]
fn line_endings_and_bom_survive_a_save() {
let mut bytes = vec![0xef, 0xbb, 0xbf];
bytes.extend_from_slice(b"a\r\nb\r\n");
let (dir, mut engine, _) = open_project(&[("w.php", &bytes)]);
let (id, opened) = open_file(&mut engine, "w.php");
assert_eq!(opened["lineEnding"], "crlf");
assert_eq!(opened["text"], "a\r\nb\r\n");
run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 6, "to": 6, "insert": "c\n"}]}),
);
run(&mut engine, "file.save", json!({"id": id}));
let mut expected = vec![0xef, 0xbb, 0xbf];
expected.extend_from_slice(b"a\r\nb\r\nc\r\n");
assert_eq!(fs::read(dir.path().join("w.php")).unwrap(), expected);
}
#[test]
fn closing_dirty_buffers_needs_force() {
let (_dir, mut engine, _) = open_project(&[("a.php", b"a"), ("b.php", b"b")]);
let (a, _) = open_file(&mut engine, "a.php");
let (b, _) = open_file(&mut engine, "b.php");
run(
&mut engine,
"buffer.edit",
json!({"id": a, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": "!"}]}),
);
let err = engine
.execute("buffer.close", json!({"id": a}))
.unwrap_err();
assert_eq!(err.code(), "unsaved_changes");
let out = run(&mut engine, "buffer.close", json!({"id": b}));
assert_eq!(out.events, vec![Event::BufferClosed { id: b }]);
let err = engine.execute("project.close", json!({})).unwrap_err();
assert_eq!(err.code(), "unsaved_changes");
assert!(engine.state().has_project());
let out = run(&mut engine, "project.close", json!({"force": true}));
assert_eq!(
out.events,
vec![Event::BufferClosed { id: a }, Event::ProjectClosed]
);
assert!(!engine.state().has_project());
}
#[test]
fn save_all_saves_every_dirty_buffer() {
let (dir, mut engine, _) = open_project(&[("a.php", b"a"), ("b.php", b"b")]);
let (a, _) = open_file(&mut engine, "a.php");
let (b, _) = open_file(&mut engine, "b.php");
for id in [a, b] {
run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": ">"}]}),
);
}
let out = run(&mut engine, "file.saveAll", Value::Null);
assert_eq!(out.value, json!({"saved": [a, b], "failed": []}));
assert_eq!(fs::read_to_string(dir.path().join("b.php")).unwrap(), ">b");
}
#[test]
fn absolute_paths_must_be_inside_the_project() {
let (dir, mut engine, _) = open_project(&[("a.php", b"a")]);
let inside = fs::canonicalize(dir.path()).unwrap().join("a.php");
let (id, value) = open_file(&mut engine, inside.to_str().unwrap());
assert_eq!(value["path"], "a.php");
assert!(id > 0);
let other = tempfile::tempdir().unwrap();
fs::write(other.path().join("x.php"), "x").unwrap();
let outside = fs::canonicalize(other.path()).unwrap().join("x.php");
let err = engine
.execute("file.open", json!({"path": outside}))
.unwrap_err();
assert_eq!(err.code(), "failed");
let err = engine
.execute("file.open", json!({"path": "../x.php"}))
.unwrap_err();
assert_eq!(err.code(), "failed");
}
#[test]
fn clean_buffers_reload_and_dirty_ones_report_conflicts() {
let (dir, mut engine, _) = open_project(&[("clean.php", b"one"), ("dirty.php", b"one")]);
let (clean, _) = open_file(&mut engine, "clean.php");
let (dirty, _) = open_file(&mut engine, "dirty.php");
run(
&mut engine,
"buffer.edit",
json!({"id": dirty, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "mine "}]}),
);
fs::write(dir.path().join("clean.php"), "two, longer").unwrap();
fs::write(dir.path().join("dirty.php"), "theirs, longer").unwrap();
let mut events = wait_for(
&mut engine,
|e| matches!(e, Event::BufferChanged { id, .. } if *id == clean),
);
if !events
.iter()
.any(|e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty))
{
events = wait_for(
&mut engine,
|e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty),
);
}
assert!(
events
.iter()
.all(|e| !matches!(e, Event::FileChangedOnDisk { id, .. } if *id == clean))
);
let clean_now = run(&mut engine, "buffer.get", json!({"id": clean})).value;
assert_eq!(clean_now["text"], "two, longer");
assert_eq!(clean_now["dirty"], false);
let dirty_now = run(&mut engine, "buffer.get", json!({"id": dirty})).value;
assert_eq!(dirty_now["text"], "mine one");
assert_eq!(dirty_now["dirty"], true);
fs::remove_file(dir.path().join("clean.php")).unwrap();
wait_for(
&mut engine,
|e| matches!(e, Event::FileChangedOnDisk { id, removed: true, .. } if *id == clean),
);
}
#[test]
fn own_saves_do_not_reload() {
let (_dir, mut engine, _) = open_project(&[("a.php", b"a")]);
let (id, _) = open_file(&mut engine, "a.php");
run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": "b"}]}),
);
run(&mut engine, "file.save", json!({"id": id}));
let deadline = Instant::now() + Duration::from_millis(600);
while Instant::now() < deadline {
let events = engine.pump_vfs().unwrap();
assert!(
!events.iter().any(|e| matches!(
e,
Event::BufferChanged { .. } | Event::FileChangedOnDisk { .. }
)),
"{events:?}"
);
std::thread::sleep(Duration::from_millis(25));
}
assert_eq!(
run(&mut engine, "buffer.get", json!({"id": id})).value["version"],
2
);
}
#[test]
fn tree_changes_are_reported_for_listed_directories() {
let (dir, mut engine, _) = open_project(&[("src/a.php", b"a")]);
run(&mut engine, "project.children", json!({"dir": "src"}));
fs::write(dir.path().join("new.php"), "n").unwrap();
wait_for(
&mut engine,
|e| matches!(e, Event::TreeChanged { dir } if dir.is_empty()),
);
fs::write(dir.path().join("src").join("b.php"), "b").unwrap();
wait_for(
&mut engine,
|e| matches!(e, Event::TreeChanged { dir } if dir == "src"),
);
}
#[test]
fn watched_directories_are_capped_least_recently_listed_first() {
let (dir, mut engine, _) = open_project(&[]);
let limit = engine.state().project.as_ref().unwrap().watch_limit();
assert!(limit > 0, "the watcher should start on a temp dir");
let count = limit + 5;
for n in 0..count {
fs::create_dir(dir.path().join(format!("d{n:04}"))).unwrap();
}
for n in 0..count {
run(
&mut engine,
"project.children",
json!({"dir": format!("d{n:04}")}),
);
}
run(&mut engine, "project.children", json!({"dir": "d0000"}));
let watched = engine.state().project.as_ref().unwrap().watched_dirs();
assert_eq!(watched.len(), limit);
assert_eq!(watched.last().unwrap(), Path::new("d0000"));
assert!(!watched.iter().any(|d| d == Path::new("d0001")));
assert!(!watched.iter().any(|d| d == Path::new("d0005")));
assert!(watched.iter().any(|d| d == Path::new("d0006")));
}
/// A command that reads the state and then panics on an index.
struct PanicsMidway;
impl Command for PanicsMidway {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "test.panicsMidway",
label: "Panics",
menu_path: None,
default_shortcut: None,
params: "none",
}
}
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
let _ = state.buffers.len();
let empty: Vec<u8> = Vec::new();
Ok(Outcome::value(json!(empty[3])))
}
}
#[test]
fn a_panicking_command_leaves_open_buffers_intact() {
let (_dir, mut engine, _) = open_project(&[("a.php", b"a")]);
engine.register(Box::new(PanicsMidway)).unwrap();
let (id, _) = open_file(&mut engine, "a.php");
run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": " unsaved"}]}),
);
let err = engine
.execute("test.panicsMidway", Value::Null)
.unwrap_err();
assert_eq!(err.code(), "internal");
let got = run(&mut engine, "buffer.get", json!({"id": id})).value;
assert_eq!(got["text"], "a unsaved");
assert_eq!(got["dirty"], true);
run(&mut engine, "file.save", json!({"id": id}));
}