//! 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": "", ...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, }, /// 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-` → CSS value. tokens: BTreeMap, }, /// 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, }, /// 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, /// English text, for messages without a catalog key and as a /// fallback. #[serde(skip_serializing_if = "Option::is_none")] message: Option, /// Interpolation params for the catalog text. #[serde(skip_serializing_if = "Option::is_none")] params: Option>, }, /// 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, }, /// 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, }, /// 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: "