Lutra/crates/engine/src/event.rs
danny c68932c39c M2.7: Structure tool window and syntax.outline
Engine: every open PHP buffer keeps a tree-sitter tree, reparsed
incrementally on a worker thread off the engine lock (200 ms debounce,
edit batches recorded by buffer.edit, full parse when the chain breaks).
syntax.outline {id} returns {items, truncated, version}; outlineChanged
{id} at most every 200 ms per buffer. Replaced trees and outlines are
freed on the worker.

UI: left stripe with Project | Structure in MainLayout, the Structure
tool window (WAI-ARIA tree, Lucide kind icons, signatures, jumps via
editor.reveal), view.toggleStructure on Mod+2.

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

379 lines
12 KiB
Rust

//! 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 std::collections::BTreeMap;
use serde::Serialize;
use serde_json::{Map, Value};
use crate::journal::EntryInfo;
/// 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,
},
/// `file.open` asked for a file whose buffer was already open; clients
/// show (activate) that buffer. A new buffer gets
/// [`Event::BufferOpened`] instead.
BufferFocused {
/// Buffer id.
id: u64,
},
/// 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,
},
/// The effective value of settings changed; refetch them with
/// `settings.get`.
SettingsChanged {
/// The changed keys.
keys: Vec<String>,
},
/// The resolved theme changed, through `appearance.theme` or, in
/// "system" mode, the OS preference. The frontend writes the tokens onto
/// `:root` and sets `color-scheme`.
ThemeChanged {
/// Theme id, e.g. `lutra-light`.
id: String,
/// Whether the theme is dark.
dark: bool,
/// Every token as `--lt-<name>` → CSS value.
tokens: BTreeMap<String, String>,
},
/// The recovery journal of the project just opened holds unsaved texts
/// from an earlier session; offer `recovery.restore` /
/// `recovery.discard`.
RecoveryAvailable {
/// The entries, sorted by path.
entries: Vec<EntryInfo>,
},
/// A message for the user, shown as a toast.
Notification {
/// Unique id of this notification, for dismissing it.
id: String,
/// Severity.
level: NotificationLevel,
/// Message-catalog key of the text.
#[serde(skip_serializing_if = "Option::is_none")]
message_key: Option<String>,
/// English text, for messages without a catalog key and as a
/// fallback.
#[serde(skip_serializing_if = "Option::is_none")]
message: Option<String>,
/// Interpolation params for the catalog text.
#[serde(skip_serializing_if = "Option::is_none")]
params: Option<Map<String, Value>>,
},
/// A UI command registered with `ui.registerCommands` was run through
/// the engine (control channel, later MCP); the frontend executes it.
UiCommand {
/// Command id, e.g. `palette.open`.
id: String,
/// The params the command was run with, as given.
params: Value,
},
/// `recovery.restore` or `recovery.discard` settled journal entries:
/// they were restored into buffers or discarded, so a restore dialog
/// that still lists them drops them (M1.15).
RecoveryResolved {
/// Project-relative paths with `/`, sorted.
paths: Vec<String>,
},
/// Matches of a running search (`search.find`) in one file. A file is
/// reported once per search; files arrive in no particular order.
SearchResults {
/// The search, as `search.find` returned it.
search_id: u64,
/// Project-relative path of the file.
path: String,
/// The matches in line order; never empty.
matches: Vec<SearchMatch>,
},
/// A search ended; no `searchResults` for it follow.
SearchDone {
/// The search.
search_id: u64,
/// Files with reported matches.
files: usize,
/// Matches reported.
matches: usize,
/// The match cap stopped the search; more matches exist.
truncated: bool,
/// `search.cancel` (or closing the project) stopped the search.
cancelled: bool,
/// Wall time of the search in milliseconds.
elapsed_ms: u64,
},
/// The symbol index is being built after `project.open`; sent at most
/// every 250 ms while it runs.
IndexProgress {
/// Files indexed so far.
done: usize,
/// Files found in the project.
total: usize,
},
/// The initial build of the symbol index ended (or was cut short); go-to
/// queries now see the whole project.
IndexReady {
/// Files in the index.
files: usize,
/// Symbols in the index.
symbols: usize,
/// Wall time of the build in milliseconds.
elapsed_ms: u64,
},
/// The outline of a buffer changed; refetch it with `syntax.outline`.
/// Sent at most every 200 ms per buffer, and once after a buffer's
/// first parse.
OutlineChanged {
/// Buffer id.
id: u64,
},
}
/// One match of [`Event::SearchResults`]. Positions are 0-based; columns
/// and lengths count UTF-16 code units.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchMatch {
/// Line of the match.
pub line: usize,
/// Start of the match in the line.
pub column: usize,
/// Length of the match; never 0.
pub length: usize,
/// The line without its line break, or a window of at most 300
/// characters around the match for longer lines.
pub preview: String,
/// Start of the match inside `preview`.
pub preview_column: usize,
}
/// Severity of an [`Event::Notification`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum NotificationLevel {
/// Information; dismissed automatically.
Info,
/// Something went wrong but Lutra kept working.
Warning,
/// An action failed.
Error,
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::{Event, NotificationLevel};
#[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"})
);
}
#[test]
fn notification_and_settings_shapes() {
let mut params = serde_json::Map::new();
params.insert("backup".into(), json!("settings.json.bad-x"));
let n = Event::Notification {
id: "n1".into(),
level: NotificationLevel::Warning,
message_key: Some("notification.settings.corrupt".into()),
message: None,
params: Some(params),
};
assert_eq!(
serde_json::to_value(n).unwrap(),
json!({
"kind": "notification",
"id": "n1",
"level": "warning",
"messageKey": "notification.settings.corrupt",
"params": {"backup": "settings.json.bad-x"},
})
);
assert_eq!(
serde_json::to_value(Event::SettingsChanged {
keys: vec!["editor.fontSize".into()]
})
.unwrap(),
json!({"kind": "settingsChanged", "keys": ["editor.fontSize"]})
);
}
#[test]
fn theme_changed_shape() {
let e = Event::ThemeChanged {
id: "lutra-light".into(),
dark: false,
tokens: [("--lt-bg".to_string(), "#f4f1ec".to_string())].into(),
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "themeChanged", "id": "lutra-light", "dark": false, "tokens": {"--lt-bg": "#f4f1ec"}})
);
}
#[test]
fn search_shapes() {
let e = Event::SearchResults {
search_id: 2,
path: "src/a.php".into(),
matches: vec![super::SearchMatch {
line: 0,
column: 6,
length: 4,
preview: "<?php echo".into(),
preview_column: 6,
}],
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "searchResults", "searchId": 2, "path": "src/a.php", "matches": [
{"line": 0, "column": 6, "length": 4, "preview": "<?php echo", "previewColumn": 6}
]})
);
let e = Event::SearchDone {
search_id: 2,
files: 1,
matches: 1,
truncated: false,
cancelled: false,
elapsed_ms: 12,
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "searchDone", "searchId": 2, "files": 1, "matches": 1, "truncated": false, "cancelled": false, "elapsedMs": 12})
);
}
#[test]
fn ui_command_shape() {
let e = Event::UiCommand {
id: "palette.open".into(),
params: json!({}),
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "uiCommand", "id": "palette.open", "params": {}})
);
}
#[test]
fn index_shapes() {
let e = Event::IndexProgress {
done: 10,
total: 20,
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "indexProgress", "done": 10, "total": 20})
);
let e = Event::IndexReady {
files: 20,
symbols: 300,
elapsed_ms: 1500,
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "indexReady", "files": 20, "symbols": 300, "elapsedMs": 1500})
);
}
#[test]
fn recovery_resolved_shape() {
let e = Event::RecoveryResolved {
paths: vec!["src/a.php".into()],
};
assert_eq!(
serde_json::to_value(e).unwrap(),
json!({"kind": "recoveryResolved", "paths": ["src/a.php"]})
);
}
#[test]
fn outline_changed_shape() {
assert_eq!(
serde_json::to_value(Event::OutlineChanged { id: 4 }).unwrap(),
json!({"kind": "outlineChanged", "id": 4})
);
}
}