//! The host: owns the engine, applies effects to the Tauri app and serves //! the control channel's [`Backend`]. use std::path::Path; use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; use lutra_control::Backend; use lutra_engine::{CommandInfo, Effect, Engine, EngineError}; use serde_json::Value; use tauri::AppHandle; use crate::screenshot; /// Title of the main window. pub const WINDOW_TITLE: &str = "Lutra"; /// Label of the main window. pub const MAIN_WINDOW: &str = "main"; /// Engine plus the handle needed to apply effects. pub struct Host { /// The engine. Commands run inside its guard, so the lock is never /// poisoned by a command; a poisoned lock is still recovered. engine: Mutex, /// The Tauri app, set once the app is set up. app: OnceLock, } impl Host { /// A host with a fresh engine. /// /// # Errors /// The engine's error if the built-in commands cannot be registered. pub fn new() -> Result { Ok(Self { engine: Mutex::new(Engine::new()?), app: OnceLock::new(), }) } /// Records the app handle once Tauri has started. Later calls are /// ignored because there is only one app per process. pub fn attach(&self, app: AppHandle) { let _ = self.app.set(app); } /// Locks the engine, recovering it if a previous holder panicked. fn engine(&self) -> MutexGuard<'_, Engine> { self.engine.lock().unwrap_or_else(PoisonError::into_inner) } /// Runs a command and applies its effects. /// /// # Errors /// The engine's error for the command. pub fn run(&self, command: &str, params: Value) -> Result { let outcome = self.engine().execute(command, params)?; for effect in outcome.effects { self.apply(effect); } Ok(outcome.value) } /// Lists every command with its current enabled state. pub fn commands(&self) -> Vec { self.engine().list_commands() } /// Applies one effect. Before the app is attached there is nothing to /// act on, so effects are dropped. fn apply(&self, effect: Effect) { let Some(app) = self.app.get() else { return }; match effect { Effect::Quit => app.exit(0), } } } impl Backend for Host { fn execute(&self, command: &str, params: Value) -> Result { self.run(command, params) } fn list_commands(&self) -> Vec { self.commands() } fn screenshot(&self, path: &Path) -> Result<(), String> { let app = self.app.get().ok_or("the window is not open yet")?; screenshot::capture_window(app, MAIN_WINDOW, path) } }