M0.6: command registry, guard, theme tokens, app.about and app.quit
Command trait with static spec, enabled check and run; Registry rejects duplicate ids; Engine::execute runs every command inside the guard, which turns panics into EngineError::Internal and keeps the engine usable. Effects (Quit) are applied by the host. Theme tokens for Lutra Dark and Lutra Light render as --lt-* CSS variables and a webview init script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
50bcc95006
commit
b382f9fae7
12 changed files with 758 additions and 1 deletions
26
Cargo.lock
generated
26
Cargo.lock
generated
|
|
@ -41,6 +41,11 @@ version = "0.0.0"
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lutra-engine"
|
name = "lutra-engine"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"thiserror",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lutra-index"
|
name = "lutra-index"
|
||||||
|
|
@ -109,6 +114,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_core",
|
"serde_core",
|
||||||
|
"serde_derive",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -164,6 +170,26 @@ dependencies = [
|
||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thiserror"
|
||||||
|
version = "2.0.21"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||||
|
dependencies = [
|
||||||
|
"thiserror-impl",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thiserror-impl"
|
||||||
|
version = "2.0.21"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml"
|
name = "toml"
|
||||||
version = "1.1.8+spec-1.1.0"
|
version = "1.1.8+spec-1.1.0"
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,9 @@ publish.workspace = true
|
||||||
layer = 4
|
layer = 4
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
|
serde_json = "1.0.154"
|
||||||
|
thiserror = "2.0.21"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|
|
||||||
53
crates/engine/src/cmd/app.rs
Normal file
53
crates/engine/src/cmd/app.rs
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
//! Application commands: `app.about` and `app.quit`.
|
||||||
|
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use crate::{Command, CommandSpec, Effect, EngineError, Outcome, State};
|
||||||
|
|
||||||
|
/// Product name shown in the About window and window titles.
|
||||||
|
pub const PRODUCT_NAME: &str = "Lutra";
|
||||||
|
|
||||||
|
/// Product slogan.
|
||||||
|
pub const SLOGAN: &str = "An otterly perfect IDE";
|
||||||
|
|
||||||
|
/// `app.about`: returns the product name, version and slogan.
|
||||||
|
pub struct About;
|
||||||
|
|
||||||
|
impl Command for About {
|
||||||
|
fn spec(&self) -> &CommandSpec {
|
||||||
|
&CommandSpec {
|
||||||
|
id: "app.about",
|
||||||
|
label: "About Lutra",
|
||||||
|
menu_path: Some("Help/About Lutra"),
|
||||||
|
default_shortcut: None,
|
||||||
|
params: "none; returns { name, version, slogan }",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&self, _state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||||
|
Ok(Outcome::value(json!({
|
||||||
|
"name": PRODUCT_NAME,
|
||||||
|
"version": env!("CARGO_PKG_VERSION"),
|
||||||
|
"slogan": SLOGAN,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `app.quit`: asks the host to quit the application.
|
||||||
|
pub struct Quit;
|
||||||
|
|
||||||
|
impl Command for Quit {
|
||||||
|
fn spec(&self) -> &CommandSpec {
|
||||||
|
&CommandSpec {
|
||||||
|
id: "app.quit",
|
||||||
|
label: "Quit",
|
||||||
|
menu_path: Some("File/Quit"),
|
||||||
|
default_shortcut: Some("Mod+Q"),
|
||||||
|
params: "none; returns null and the effect quit",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&self, _state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||||
|
Ok(Outcome::effect(Effect::Quit))
|
||||||
|
}
|
||||||
|
}
|
||||||
15
crates/engine/src/cmd/mod.rs
Normal file
15
crates/engine/src/cmd/mod.rs
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
//! Built-in commands, one module per area.
|
||||||
|
|
||||||
|
mod app;
|
||||||
|
|
||||||
|
use crate::{EngineError, Registry};
|
||||||
|
|
||||||
|
/// Registers every built-in command.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Returns [`EngineError::Internal`] if two commands share an id.
|
||||||
|
pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
||||||
|
registry.register(Box::new(app::About))?;
|
||||||
|
registry.register(Box::new(app::Quit))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
111
crates/engine/src/command.rs
Normal file
111
crates/engine/src/command.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
//! The command abstraction: static metadata, the run contract and the
|
||||||
|
//! effects a command asks its host to carry out.
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::{EngineError, State};
|
||||||
|
|
||||||
|
/// Static metadata of a command.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct CommandSpec {
|
||||||
|
/// Unique id, `area.action` in camelCase, e.g. `app.about`.
|
||||||
|
pub id: &'static str,
|
||||||
|
/// Label for menus and the command palette, in English.
|
||||||
|
pub label: &'static str,
|
||||||
|
/// Menu path with `/` separators, e.g. `Help/About Lutra`.
|
||||||
|
pub menu_path: Option<&'static str>,
|
||||||
|
/// Default shortcut in Lutra notation; `Mod` is Ctrl, or Cmd on macOS.
|
||||||
|
pub default_shortcut: Option<&'static str>,
|
||||||
|
/// Documentation of the params object, `none` if the command takes none.
|
||||||
|
pub params: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Something the engine asks its host to do after a command returns,
|
||||||
|
/// because it needs a layer the engine cannot reach (windows, the process).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||||
|
pub enum Effect {
|
||||||
|
/// Quit the application.
|
||||||
|
Quit,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of a successful command.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Default)]
|
||||||
|
pub struct Outcome {
|
||||||
|
/// JSON result returned to the caller.
|
||||||
|
pub value: Value,
|
||||||
|
/// Effects for the host to apply, in order.
|
||||||
|
pub effects: Vec<Effect>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Outcome {
|
||||||
|
/// An outcome with a value and no effects.
|
||||||
|
pub fn value(value: Value) -> Self {
|
||||||
|
Self {
|
||||||
|
value,
|
||||||
|
effects: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An outcome with a null value and one effect.
|
||||||
|
pub fn effect(effect: Effect) -> Self {
|
||||||
|
Self {
|
||||||
|
value: Value::Null,
|
||||||
|
effects: vec![effect],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A user-visible action.
|
||||||
|
///
|
||||||
|
/// Implementations are stateless; everything they change lives in [`State`].
|
||||||
|
pub trait Command: Send + Sync {
|
||||||
|
/// Static metadata.
|
||||||
|
fn spec(&self) -> &CommandSpec;
|
||||||
|
|
||||||
|
/// Whether the command can run in the given state. Defaults to always.
|
||||||
|
fn enabled(&self, _state: &State) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the command.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Returns [`EngineError::InvalidParams`] for params that don't match
|
||||||
|
/// [`CommandSpec::params`], and [`EngineError::Failed`] when the action
|
||||||
|
/// itself fails.
|
||||||
|
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Description of a command for menus, the palette, keymaps and agents.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct CommandInfo {
|
||||||
|
/// Command id.
|
||||||
|
pub id: String,
|
||||||
|
/// Label.
|
||||||
|
pub label: String,
|
||||||
|
/// Menu path, if the command is in a menu.
|
||||||
|
pub menu_path: Option<String>,
|
||||||
|
/// Default shortcut, if any.
|
||||||
|
pub default_shortcut: Option<String>,
|
||||||
|
/// Params documentation.
|
||||||
|
pub params: String,
|
||||||
|
/// Whether the command can run in the current state.
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CommandInfo {
|
||||||
|
/// Builds the description from a spec and the current enabled state.
|
||||||
|
pub fn new(spec: &CommandSpec, enabled: bool) -> Self {
|
||||||
|
Self {
|
||||||
|
id: spec.id.to_string(),
|
||||||
|
label: spec.label.to_string(),
|
||||||
|
menu_path: spec.menu_path.map(str::to_string),
|
||||||
|
default_shortcut: spec.default_shortcut.map(str::to_string),
|
||||||
|
params: spec.params.to_string(),
|
||||||
|
enabled,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
202
crates/engine/src/engine.rs
Normal file
202
crates/engine/src/engine.rs
Normal file
|
|
@ -0,0 +1,202 @@
|
||||||
|
//! The engine: registry plus state, and the one entry point that runs
|
||||||
|
//! commands.
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::{Command, CommandInfo, EngineError, Outcome, Registry, State, cmd, guard};
|
||||||
|
|
||||||
|
/// The command registry together with the workspace state.
|
||||||
|
///
|
||||||
|
/// Hosts keep one engine behind a lock and call [`Engine::execute`] for every
|
||||||
|
/// action, whatever its origin (menu, shortcut, palette, CLI, control
|
||||||
|
/// channel, MCP).
|
||||||
|
pub struct Engine {
|
||||||
|
/// Registered commands.
|
||||||
|
registry: Registry,
|
||||||
|
/// Workspace state.
|
||||||
|
state: State,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Engine {
|
||||||
|
/// An engine with the built-in commands.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Returns [`EngineError::Internal`] if two built-in commands share an id.
|
||||||
|
pub fn new() -> Result<Self, EngineError> {
|
||||||
|
let mut engine = Self::empty();
|
||||||
|
cmd::register_builtins(&mut engine.registry)?;
|
||||||
|
Ok(engine)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An engine without any commands, for tests and embedding.
|
||||||
|
pub fn empty() -> Self {
|
||||||
|
Self {
|
||||||
|
registry: Registry::default(),
|
||||||
|
state: State::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a command.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Returns [`EngineError::Internal`] if the id is already taken.
|
||||||
|
pub fn register(&mut self, command: Box<dyn Command>) -> Result<(), EngineError> {
|
||||||
|
self.registry.register(command)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a command inside the guard.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`EngineError::UnknownCommand`] for an unknown id,
|
||||||
|
/// [`EngineError::Disabled`] if the command is disabled, the command's own
|
||||||
|
/// error, or [`EngineError::Internal`] if it panicked.
|
||||||
|
pub fn execute(&mut self, id: &str, params: Value) -> Result<Outcome, EngineError> {
|
||||||
|
let Self { registry, state } = self;
|
||||||
|
let command = registry
|
||||||
|
.get(id)
|
||||||
|
.ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||||
|
let result = guard::run(|| {
|
||||||
|
if !command.enabled(state) {
|
||||||
|
return Err(EngineError::Disabled(id.to_string()));
|
||||||
|
}
|
||||||
|
command.run(state, params)
|
||||||
|
});
|
||||||
|
state.commands_run = state.commands_run.saturating_add(1);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Describes every command with its current enabled state. A command whose
|
||||||
|
/// `enabled` check panics is listed as disabled.
|
||||||
|
pub fn list_commands(&self) -> Vec<CommandInfo> {
|
||||||
|
self.registry
|
||||||
|
.iter()
|
||||||
|
.map(|c| {
|
||||||
|
let enabled = guard::run(|| Ok(c.enabled(&self.state))).unwrap_or(false);
|
||||||
|
CommandInfo::new(c.spec(), enabled)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read access to the state.
|
||||||
|
pub fn state(&self) -> &State {
|
||||||
|
&self.state
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::{CommandSpec, Effect};
|
||||||
|
|
||||||
|
struct Panicking;
|
||||||
|
|
||||||
|
impl Command for Panicking {
|
||||||
|
fn spec(&self) -> &CommandSpec {
|
||||||
|
&CommandSpec {
|
||||||
|
id: "test.panic",
|
||||||
|
label: "Panic",
|
||||||
|
menu_path: None,
|
||||||
|
default_shortcut: None,
|
||||||
|
params: "none",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||||
|
state.commands_run += 100;
|
||||||
|
panic!("index out of bounds");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Disabled;
|
||||||
|
|
||||||
|
impl Command for Disabled {
|
||||||
|
fn spec(&self) -> &CommandSpec {
|
||||||
|
&CommandSpec {
|
||||||
|
id: "test.disabled",
|
||||||
|
label: "Disabled",
|
||||||
|
menu_path: None,
|
||||||
|
default_shortcut: None,
|
||||||
|
params: "none",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enabled(&self, _state: &State) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&self, _state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
||||||
|
Ok(Outcome::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn about_reports_product_information() {
|
||||||
|
let mut engine = Engine::new().unwrap();
|
||||||
|
let out = engine.execute("app.about", Value::Null).unwrap();
|
||||||
|
assert_eq!(out.value["name"], "Lutra");
|
||||||
|
assert_eq!(out.value["slogan"], "An otterly perfect IDE");
|
||||||
|
assert_eq!(out.value["version"], env!("CARGO_PKG_VERSION"));
|
||||||
|
assert!(out.effects.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn quit_asks_the_host_to_quit() {
|
||||||
|
let mut engine = Engine::new().unwrap();
|
||||||
|
let out = engine.execute("app.quit", json!({})).unwrap();
|
||||||
|
assert_eq!(out.effects, vec![Effect::Quit]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_and_disabled_commands_fail() {
|
||||||
|
let mut engine = Engine::new().unwrap();
|
||||||
|
engine.register(Box::new(Disabled)).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
engine.execute("nope", Value::Null).unwrap_err().code(),
|
||||||
|
"unknown_command"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
engine
|
||||||
|
.execute("test.disabled", Value::Null)
|
||||||
|
.unwrap_err()
|
||||||
|
.code(),
|
||||||
|
"disabled"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn guard_survives_a_panicking_command() {
|
||||||
|
let mut engine = Engine::new().unwrap();
|
||||||
|
engine.register(Box::new(Panicking)).unwrap();
|
||||||
|
let err = engine.execute("test.panic", Value::Null).unwrap_err();
|
||||||
|
assert_eq!(err, EngineError::Internal("index out of bounds".into()));
|
||||||
|
assert!(engine.execute("app.about", Value::Null).is_ok());
|
||||||
|
assert_eq!(engine.state().commands_run, 102);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicate_ids_are_rejected() {
|
||||||
|
let mut engine = Engine::new().unwrap();
|
||||||
|
engine.register(Box::new(Disabled)).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
engine.register(Box::new(Disabled)).unwrap_err().code(),
|
||||||
|
"internal"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lists_commands_with_metadata() {
|
||||||
|
let mut engine = Engine::new().unwrap();
|
||||||
|
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!(quit.default_shortcut.as_deref(), Some("Mod+Q"));
|
||||||
|
assert!(quit.enabled);
|
||||||
|
assert!(!list[2].enabled);
|
||||||
|
let json = serde_json::to_value(quit).unwrap();
|
||||||
|
assert_eq!(json["menuPath"], "File/Quit");
|
||||||
|
}
|
||||||
|
}
|
||||||
82
crates/engine/src/error.rs
Normal file
82
crates/engine/src/error.rs
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
//! The error type every engine entry point returns.
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
/// Why a command could not run or failed.
|
||||||
|
///
|
||||||
|
/// Each variant has a stable [`code`](EngineError::code) that the control
|
||||||
|
/// channel, MCP and the frontend use to tell errors apart.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum EngineError {
|
||||||
|
/// No command is registered under the id.
|
||||||
|
#[error("unknown command: {0}")]
|
||||||
|
UnknownCommand(String),
|
||||||
|
/// The command exists but is disabled in the current state.
|
||||||
|
#[error("command is not available right now: {0}")]
|
||||||
|
Disabled(String),
|
||||||
|
/// The params do not match the command's documented schema.
|
||||||
|
#[error("invalid params for {command}: {message}")]
|
||||||
|
InvalidParams {
|
||||||
|
/// The command id.
|
||||||
|
command: String,
|
||||||
|
/// What is wrong with the params.
|
||||||
|
message: String,
|
||||||
|
},
|
||||||
|
/// The command ran and failed, e.g. a file could not be read.
|
||||||
|
#[error("{0}")]
|
||||||
|
Failed(String),
|
||||||
|
/// A bug: a command panicked or reached a state it should not. The guard
|
||||||
|
/// reports panics with this variant.
|
||||||
|
#[error("internal error: {0}")]
|
||||||
|
Internal(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EngineError {
|
||||||
|
/// Stable machine-readable code of the error.
|
||||||
|
pub fn code(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::UnknownCommand(_) => "unknown_command",
|
||||||
|
Self::Disabled(_) => "disabled",
|
||||||
|
Self::InvalidParams { .. } => "invalid_params",
|
||||||
|
Self::Failed(_) => "failed",
|
||||||
|
Self::Internal(_) => "internal",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The error as a `{ code, message }` payload for IPC and the control
|
||||||
|
/// channel.
|
||||||
|
pub fn payload(&self) -> ErrorPayload {
|
||||||
|
ErrorPayload {
|
||||||
|
code: self.code().to_string(),
|
||||||
|
message: self.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serialisable form of an [`EngineError`].
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
|
||||||
|
pub struct ErrorPayload {
|
||||||
|
/// Stable code, see [`EngineError::code`].
|
||||||
|
pub code: String,
|
||||||
|
/// Message for the user.
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn codes_are_stable() {
|
||||||
|
assert_eq!(
|
||||||
|
EngineError::UnknownCommand("x".into()).code(),
|
||||||
|
"unknown_command"
|
||||||
|
);
|
||||||
|
let e = EngineError::InvalidParams {
|
||||||
|
command: "a.b".into(),
|
||||||
|
message: "missing path".into(),
|
||||||
|
};
|
||||||
|
assert_eq!(e.payload().code, "invalid_params");
|
||||||
|
assert_eq!(e.payload().message, "invalid params for a.b: missing path");
|
||||||
|
}
|
||||||
|
}
|
||||||
59
crates/engine/src/guard.rs
Normal file
59
crates/engine/src/guard.rs
Normal file
|
|
@ -0,0 +1,59 @@
|
||||||
|
//! The last line of defence against bugs: turns a panic at an entry point
|
||||||
|
//! into [`EngineError::Internal`] so that the process, and the user's unsaved
|
||||||
|
//! work, survive.
|
||||||
|
//!
|
||||||
|
//! The guard is for bugs. Expected failures are `Result`s and never reach it.
|
||||||
|
//! Release builds keep `panic = "unwind"`, which this module relies on.
|
||||||
|
|
||||||
|
use std::any::Any;
|
||||||
|
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||||
|
|
||||||
|
use crate::EngineError;
|
||||||
|
|
||||||
|
/// Runs `f` and converts a panic inside it into [`EngineError::Internal`].
|
||||||
|
///
|
||||||
|
/// The closure is treated as unwind safe: after a panic the engine state may
|
||||||
|
/// hold a half-finished change from the failed command, which is preferable to
|
||||||
|
/// losing every open buffer.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Returns the closure's own error, or [`EngineError::Internal`] with the
|
||||||
|
/// panic message if it panicked.
|
||||||
|
pub fn run<T>(f: impl FnOnce() -> Result<T, EngineError>) -> Result<T, EngineError> {
|
||||||
|
catch_unwind(AssertUnwindSafe(f))
|
||||||
|
.unwrap_or_else(|payload| Err(EngineError::Internal(panic_message(payload.as_ref()))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extracts the message of a panic payload, which is a `&str` or a `String`
|
||||||
|
/// for `panic!` with a literal or a format string.
|
||||||
|
fn panic_message(payload: &(dyn Any + Send)) -> String {
|
||||||
|
if let Some(s) = payload.downcast_ref::<&str>() {
|
||||||
|
(*s).to_string()
|
||||||
|
} else if let Some(s) = payload.downcast_ref::<String>() {
|
||||||
|
s.clone()
|
||||||
|
} else {
|
||||||
|
"a command panicked".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn passes_results_through() {
|
||||||
|
assert_eq!(run(|| Ok(3)), Ok(3));
|
||||||
|
assert_eq!(
|
||||||
|
run::<()>(|| Err(EngineError::Failed("no".into()))),
|
||||||
|
Err(EngineError::Failed("no".into()))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn converts_panics() {
|
||||||
|
let r = run::<()>(|| panic!("boom {}", 42));
|
||||||
|
assert_eq!(r, Err(EngineError::Internal("boom 42".into())));
|
||||||
|
let r = run::<()>(|| std::panic::panic_any(7_u8));
|
||||||
|
assert_eq!(r, Err(EngineError::Internal("a command panicked".into())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,21 @@
|
||||||
//! Engine of Lutra (layer L4).
|
//! Engine of Lutra (layer L4).
|
||||||
//!
|
//!
|
||||||
//! Owns the command registry, the workspace state, the panic guard around every
|
//! Owns the command registry, the workspace state, the panic guard around every
|
||||||
//! entry point and the crash-recovery journal.
|
//! entry point and the crash-recovery journal. Every user-visible action is a
|
||||||
|
//! [`Command`]; menus, the palette, shortcuts, the CLI, the control channel and
|
||||||
|
//! MCP all reach it through [`Engine::execute`].
|
||||||
|
|
||||||
|
pub mod cmd;
|
||||||
|
mod command;
|
||||||
|
mod engine;
|
||||||
|
mod error;
|
||||||
|
pub mod guard;
|
||||||
|
mod registry;
|
||||||
|
mod state;
|
||||||
|
pub mod theme;
|
||||||
|
|
||||||
|
pub use command::{Command, CommandInfo, CommandSpec, Effect, Outcome};
|
||||||
|
pub use engine::Engine;
|
||||||
|
pub use error::{EngineError, ErrorPayload};
|
||||||
|
pub use registry::Registry;
|
||||||
|
pub use state::State;
|
||||||
|
|
|
||||||
50
crates/engine/src/registry.rs
Normal file
50
crates/engine/src/registry.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
//! The command registry, keyed by command id.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use crate::{Command, EngineError};
|
||||||
|
|
||||||
|
/// All registered commands, in id order.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Registry {
|
||||||
|
/// Commands by id.
|
||||||
|
commands: BTreeMap<&'static str, Box<dyn Command>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Registry {
|
||||||
|
/// Adds a command.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Returns [`EngineError::Internal`] if the id is already taken; two
|
||||||
|
/// commands with one id is a programming error.
|
||||||
|
pub fn register(&mut self, command: Box<dyn Command>) -> Result<(), EngineError> {
|
||||||
|
let id = command.spec().id;
|
||||||
|
if self.commands.contains_key(id) {
|
||||||
|
return Err(EngineError::Internal(format!(
|
||||||
|
"command registered twice: {id}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
self.commands.insert(id, command);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks a command up by id.
|
||||||
|
pub fn get(&self, id: &str) -> Option<&dyn Command> {
|
||||||
|
self.commands.get(id).map(Box::as_ref)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Iterates over the commands in id order.
|
||||||
|
pub fn iter(&self) -> impl Iterator<Item = &dyn Command> {
|
||||||
|
self.commands.values().map(Box::as_ref)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Number of registered commands.
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.commands.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether no command is registered.
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.commands.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
10
crates/engine/src/state.rs
Normal file
10
crates/engine/src/state.rs
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
//! Workspace state that commands read and change.
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
}
|
||||||
129
crates/engine/src/theme.rs
Normal file
129
crates/engine/src/theme.rs
Normal file
|
|
@ -0,0 +1,129 @@
|
||||||
|
//! Theme tokens: the single source of every colour and font in the UI.
|
||||||
|
//!
|
||||||
|
//! Themes are defined here in Rust and rendered as CSS custom properties
|
||||||
|
//! (`--lt-<token>`). Frontend components use only `var(--lt-…)`. The palettes
|
||||||
|
//! are Lutra's own: warm otter browns with a copper accent.
|
||||||
|
|
||||||
|
/// A named set of token values.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Theme {
|
||||||
|
/// Stable id used in settings, e.g. `lutra-dark`.
|
||||||
|
pub id: &'static str,
|
||||||
|
/// Display name.
|
||||||
|
pub name: &'static str,
|
||||||
|
/// Whether the theme is dark, for the window chrome and `color-scheme`.
|
||||||
|
pub dark: bool,
|
||||||
|
/// Token names (without the `--lt-` prefix) and CSS values.
|
||||||
|
pub tokens: &'static [(&'static str, &'static str)],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens shared by every theme (fonts and sizes).
|
||||||
|
const COMMON: &[(&str, &str)] = &[
|
||||||
|
(
|
||||||
|
"font-ui",
|
||||||
|
"system-ui, -apple-system, \"Segoe UI\", Roboto, Ubuntu, sans-serif",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"font-mono",
|
||||||
|
"ui-monospace, \"Cascadia Code\", Menlo, Consolas, monospace",
|
||||||
|
),
|
||||||
|
("font-size-ui", "13px"),
|
||||||
|
("font-size-small", "12px"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The default dark theme.
|
||||||
|
pub const DARK: Theme = Theme {
|
||||||
|
id: "lutra-dark",
|
||||||
|
name: "Lutra Dark",
|
||||||
|
dark: true,
|
||||||
|
tokens: &[
|
||||||
|
("bg", "#1f1d1b"),
|
||||||
|
("editor-bg", "#191817"),
|
||||||
|
("fg", "#e6e1da"),
|
||||||
|
("fg-muted", "#9a928a"),
|
||||||
|
("border", "#34302c"),
|
||||||
|
("accent", "#d39a5c"),
|
||||||
|
("error", "#ef7b6c"),
|
||||||
|
("statusbar-bg", "#24211f"),
|
||||||
|
("statusbar-fg", "#b8afa6"),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The light theme.
|
||||||
|
pub const LIGHT: Theme = Theme {
|
||||||
|
id: "lutra-light",
|
||||||
|
name: "Lutra Light",
|
||||||
|
dark: false,
|
||||||
|
tokens: &[
|
||||||
|
("bg", "#f4f1ec"),
|
||||||
|
("editor-bg", "#fbfaf8"),
|
||||||
|
("fg", "#2a2622"),
|
||||||
|
("fg-muted", "#7a7168"),
|
||||||
|
("border", "#ddd6cd"),
|
||||||
|
("accent", "#a8662a"),
|
||||||
|
("error", "#c2412f"),
|
||||||
|
("statusbar-bg", "#ece7e0"),
|
||||||
|
("statusbar-fg", "#5a5149"),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Every built-in theme.
|
||||||
|
pub const BUILTIN: &[Theme] = &[DARK, LIGHT];
|
||||||
|
|
||||||
|
/// Looks a built-in theme up by id.
|
||||||
|
pub fn by_id(id: &str) -> Option<Theme> {
|
||||||
|
BUILTIN.iter().copied().find(|t| t.id == id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders a theme as a `:root { … }` rule of CSS custom properties.
|
||||||
|
pub fn css_variables(theme: &Theme) -> String {
|
||||||
|
let mut css = String::from(":root {\n");
|
||||||
|
css.push_str(&format!(
|
||||||
|
" color-scheme: {};\n",
|
||||||
|
if theme.dark { "dark" } else { "light" }
|
||||||
|
));
|
||||||
|
for (name, value) in COMMON.iter().chain(theme.tokens) {
|
||||||
|
css.push_str(&format!(" --lt-{name}: {value};\n"));
|
||||||
|
}
|
||||||
|
css.push('}');
|
||||||
|
css
|
||||||
|
}
|
||||||
|
|
||||||
|
/// JavaScript that installs the theme's CSS as a `<style id="lt-theme">`
|
||||||
|
/// element as soon as the document has a `<head>`, for use as a webview
|
||||||
|
/// initialization script.
|
||||||
|
pub fn init_script(theme: &Theme) -> String {
|
||||||
|
let css = serde_json::Value::String(css_variables(theme)).to_string();
|
||||||
|
format!(
|
||||||
|
"(function(){{var css={css};function apply(){{var s=document.getElementById('lt-theme');if(!s){{s=document.createElement('style');s.id='lt-theme';document.head.appendChild(s);}}s.textContent=css;}}if(document.head){{apply();}}else{{document.addEventListener('DOMContentLoaded',apply);}}}})();"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn themes_define_the_same_tokens() {
|
||||||
|
let names = |t: &Theme| t.tokens.iter().map(|(n, _)| *n).collect::<Vec<_>>();
|
||||||
|
assert_eq!(names(&DARK), names(&LIGHT));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn renders_css_variables() {
|
||||||
|
let css = css_variables(&DARK);
|
||||||
|
assert!(css.starts_with(":root {"));
|
||||||
|
assert!(css.contains(" --lt-bg: #1f1d1b;\n"));
|
||||||
|
assert!(css.contains(" --lt-font-size-ui: 13px;\n"));
|
||||||
|
assert!(css.contains("color-scheme: dark;"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn init_script_embeds_escaped_css() {
|
||||||
|
let js = init_script(&LIGHT);
|
||||||
|
assert!(js.contains("\\\"Segoe UI\\\""));
|
||||||
|
assert!(js.contains("lt-theme"));
|
||||||
|
assert_eq!(by_id("lutra-light"), Some(LIGHT));
|
||||||
|
assert_eq!(by_id("nope"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue