- crates/terminal: portable-pty sessions (ConPTY on Windows) with reader, writer and waiter threads, UTF-8 chunking, a 1 MiB output buffer with backpressure, a non-blocking input queue, resize, kill and exit codes; default shell pwsh -> powershell -> cmd on Windows, $SHELL or /bin/sh. - Engine: terminal.create/input/resize/close, terminalOutput (capped per terminal and per pump, round-robin) and terminalExited through the pump; terminals close with the project and on app.quit. - UI: Terminal tab in the bottom panel (tabs next to Find), xterm.js with the fit addon, sub-tabs, copy/paste, a focus rule that leaves plain Ctrl keys to the shell, terminal.open (Mod+Shift+T), --lt-terminal-* ANSI tokens in both themes (text colours AA) and a 4.5:1 minimum contrast. - Tests: real-shell crate tests (UTF-8, backpressure), engine and TCP control tests, Vitest with a mocked xterm; live check on port 7936; docs and parity rows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
445 lines
16 KiB
Rust
445 lines
16 KiB
Rust
//! The engine: registry plus state, and the one entry point that runs
|
|
//! commands.
|
|
|
|
use std::path::PathBuf;
|
|
|
|
use serde_json::Value;
|
|
|
|
use crate::settings::Settings;
|
|
use crate::{
|
|
Command, CommandInfo, EngineError, NotificationLevel, Outcome, Registry, State, cmd, guard,
|
|
};
|
|
|
|
/// Where an engine stores its files. The desktop passes Tauri's app config
|
|
/// and app data directories; tests pass temp directories.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct EngineConfig {
|
|
/// User configuration: `settings.json`.
|
|
pub config_dir: PathBuf,
|
|
/// Application data, such as the crash-recovery journal.
|
|
pub data_dir: PathBuf,
|
|
}
|
|
|
|
/// 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 that stores its files in
|
|
/// `config`'s directories, and loads the settings. A missing settings
|
|
/// file gives the defaults. A corrupt or unreadable one never fails
|
|
/// construction: the defaults are used and a warning
|
|
/// [`crate::Event::Notification`] is queued; hosts take it with
|
|
/// [`Engine::take_events`].
|
|
///
|
|
/// # Errors
|
|
/// Returns [`EngineError::Internal`] if two built-in commands share an id.
|
|
pub fn with_config(config: EngineConfig) -> Result<Self, EngineError> {
|
|
let mut engine = Self::new()?;
|
|
let (settings, problem) = Settings::load(&config.config_dir);
|
|
engine.state.settings = settings;
|
|
engine.state.config = Some(config);
|
|
if let Some(problem) = problem {
|
|
engine.state.notify(
|
|
NotificationLevel::Warning,
|
|
Some(problem.message_key()),
|
|
Some(problem.message()),
|
|
Some(problem.params()),
|
|
);
|
|
}
|
|
Ok(engine)
|
|
}
|
|
|
|
/// An engine with the built-in commands and no persistence: settings
|
|
/// live in memory only. For tests and the control-channel test backend.
|
|
///
|
|
/// # 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)?;
|
|
engine.state.engine_commands = engine.registry.ids().collect();
|
|
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> {
|
|
let id = command.spec().id;
|
|
self.registry.register(command)?;
|
|
self.state.engine_commands.insert(id);
|
|
Ok(())
|
|
}
|
|
|
|
/// 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`]. After every command the parent directories of
|
|
/// open buffers are re-pinned in the project watcher
|
|
/// ([`crate::workspace::sync_buffer_dirs`]).
|
|
///
|
|
/// # 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.
|
|
///
|
|
/// A UI command registered with `ui.registerCommands` is not run here:
|
|
/// the engine queues `uiCommand` for the frontend and returns `null`.
|
|
pub fn execute(&mut self, id: &str, params: Value) -> Result<Outcome, EngineError> {
|
|
let Self { registry, state } = self;
|
|
let Some(command) = registry.get(id) else {
|
|
let mut outcome = cmd::ui::dispatch(state, id, params)
|
|
.ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
|
state.commands_run = state.commands_run.saturating_add(1);
|
|
outcome.events = state.take_events();
|
|
return Ok(outcome);
|
|
};
|
|
let result = guard::run(|| {
|
|
if !command.enabled(state) {
|
|
return Err(EngineError::Disabled(id.to_string()));
|
|
}
|
|
let outcome = command.run(state, params);
|
|
crate::workspace::sync_buffer_dirs(state);
|
|
cmd::terminal::sync_project(state);
|
|
outcome
|
|
});
|
|
state.commands_run = state.commands_run.saturating_add(1);
|
|
result.map(|mut outcome| {
|
|
outcome.events = state.take_events();
|
|
outcome
|
|
})
|
|
}
|
|
|
|
/// Applies pending changes on disk (reloads clean buffers, reports
|
|
/// changed directories and conflicts), writes due recovery-journal
|
|
/// entries (see [`crate::journal`]), moves finished search results into
|
|
/// events (see [`cmd::search`]), merges index updates (see
|
|
/// [`cmd::goto`]), stores finished parses and starts due ones (see
|
|
/// [`cmd::syntax`]) and returns every queued event.
|
|
/// Terminal output and exits become events too (see [`cmd::terminal`]).
|
|
/// 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);
|
|
crate::journal::tick(state, std::time::Instant::now());
|
|
cmd::search::pump(state);
|
|
cmd::goto::sync(state);
|
|
cmd::syntax::pump(state, std::time::Instant::now());
|
|
cmd::toolchain::pump(state);
|
|
cmd::terminal::pump(state);
|
|
Ok(())
|
|
})?;
|
|
Ok(state.take_events())
|
|
}
|
|
|
|
/// Writes every unsaved edit to the recovery journal now instead of
|
|
/// after the debounce, and returns every queued event. For tests and
|
|
/// for hosts that are about to stop.
|
|
///
|
|
/// # Errors
|
|
/// [`EngineError::Internal`] if writing panicked; the queued events stay
|
|
/// queued.
|
|
pub fn flush_journal(&mut self) -> Result<Vec<crate::Event>, EngineError> {
|
|
let state = &mut self.state;
|
|
guard::run(|| {
|
|
crate::journal::flush(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()
|
|
}
|
|
|
|
/// Queues an [`crate::Event::Notification`] from the host, such as an
|
|
/// error after the folder picker closed, with a fresh id from the same
|
|
/// sequence as the engine's own notifications, and takes the queued
|
|
/// events.
|
|
///
|
|
/// # Parameters
|
|
/// - `level`: severity.
|
|
/// - `message_key`: message-catalog key of the text.
|
|
/// - `message`: English text, the fallback without a catalog entry.
|
|
/// - `params`: interpolation params for the catalog text.
|
|
///
|
|
/// # Returns
|
|
/// The queued events, oldest first, ending with the notification.
|
|
pub fn notify(
|
|
&mut self,
|
|
level: NotificationLevel,
|
|
message_key: Option<&str>,
|
|
message: Option<String>,
|
|
params: Option<serde_json::Map<String, Value>>,
|
|
) -> Vec<crate::Event> {
|
|
self.state.notify(level, message_key, message, params);
|
|
self.state.take_events()
|
|
}
|
|
|
|
/// Describes every command with its current enabled state, the
|
|
/// engine's and the registered UI commands (`ui: true`), in id order.
|
|
/// A command whose `enabled` check panics is listed as disabled.
|
|
pub fn list_commands(&self) -> Vec<CommandInfo> {
|
|
let mut list: Vec<CommandInfo> = self
|
|
.registry
|
|
.iter()
|
|
.map(|c| {
|
|
let enabled = guard::run(|| Ok(c.enabled(&self.state))).unwrap_or(false);
|
|
CommandInfo::new(c.spec(), enabled)
|
|
})
|
|
.chain(
|
|
self.state
|
|
.ui_commands
|
|
.values()
|
|
.map(cmd::ui::UiCommand::info),
|
|
)
|
|
.collect();
|
|
list.sort_by(|a, b| a.id.cmp(&b.id));
|
|
list
|
|
}
|
|
|
|
/// Allows the one network access Lutra makes: downloading the pinned
|
|
/// Phpactor release (owner decision D15, see [`cmd::toolchain`]). Without
|
|
/// this call the engine downloads nothing, which keeps tests offline.
|
|
///
|
|
/// # Errors
|
|
/// [`EngineError::Internal`] if the pinned hash is malformed.
|
|
pub fn allow_downloads(&mut self) -> Result<(), EngineError> {
|
|
let source = lutra_lsp::toolchain::phpactor::pinned().map_err(EngineError::Internal)?;
|
|
self.allow_downloads_from(source);
|
|
Ok(())
|
|
}
|
|
|
|
/// Allows Phpactor downloads from `source` instead of the pinned
|
|
/// release, for tests against a local server.
|
|
pub fn allow_downloads_from(&mut self, source: lutra_lsp::toolchain::download::Source) {
|
|
self.state.toolchain.allow_downloads(source);
|
|
}
|
|
|
|
/// 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 host_notifications_get_fresh_ids() {
|
|
let mut engine = Engine::new().unwrap();
|
|
let first = engine.notify(
|
|
NotificationLevel::Error,
|
|
Some("notification.project.openFailed"),
|
|
Some("cannot open".into()),
|
|
None,
|
|
);
|
|
let second = engine.notify(NotificationLevel::Info, None, Some("hi".into()), None);
|
|
let id = |events: &[crate::Event]| match events.last() {
|
|
Some(crate::Event::Notification { id, .. }) => id.clone(),
|
|
other => panic!("not a notification: {other:?}"),
|
|
};
|
|
assert_eq!(first.len(), 1);
|
|
assert_eq!(id(&first), "n1");
|
|
assert_eq!(id(&second), "n2");
|
|
assert!(engine.take_events().is_empty());
|
|
}
|
|
|
|
#[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 open_dialog_asks_the_host_to_pick_a_folder() {
|
|
let mut engine = Engine::new().unwrap();
|
|
let out = engine.execute("project.openDialog", Value::Null).unwrap();
|
|
assert_eq!(out.effects, vec![Effect::PickFolder]);
|
|
assert_eq!(out.value, Value::Null);
|
|
}
|
|
|
|
#[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",
|
|
"buffer.close",
|
|
"buffer.edit",
|
|
"buffer.get",
|
|
"buffer.list",
|
|
"file.open",
|
|
"file.save",
|
|
"file.saveAll",
|
|
"goto.class",
|
|
"goto.file",
|
|
"goto.symbol",
|
|
"index.status",
|
|
"project.children",
|
|
"project.close",
|
|
"project.open",
|
|
"project.openDialog",
|
|
"recovery.discard",
|
|
"recovery.list",
|
|
"recovery.restore",
|
|
"search.cancel",
|
|
"search.find",
|
|
"settings.get",
|
|
"settings.list",
|
|
"settings.reset",
|
|
"settings.set",
|
|
"syntax.outline",
|
|
"terminal.close",
|
|
"terminal.create",
|
|
"terminal.input",
|
|
"terminal.resize",
|
|
"test.disabled",
|
|
"theme.list",
|
|
"theme.systemPreference",
|
|
"toolchain.downloadPhpactor",
|
|
"toolchain.status",
|
|
"ui.registerCommands",
|
|
]
|
|
);
|
|
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);
|
|
for (id, shortcut) in [
|
|
("file.save", "Mod+S"),
|
|
("file.saveAll", "Mod+Alt+S"),
|
|
("buffer.close", "Mod+W"),
|
|
] {
|
|
assert_eq!(by_id(id).default_shortcut.as_deref(), Some(shortcut));
|
|
}
|
|
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");
|
|
}
|
|
}
|