//! The host: owns the engine, applies effects to the Tauri app, publishes //! engine events to the window and to control channel subscribers, pumps //! changes on disk into the engine, and serves the control channel's //! [`Backend`]. //! //! Events reach the frontend as the Tauri event [`ENGINE_EVENT`] with the //! engine's `Event` as payload. Events are published while the engine lock is //! held, so commands and the pump thread never reorder them. //! //! Errors that have no caller to return to (the folder picker, the pump, the //! project given on the command line) are published as `notification` //! events. Notifications and `watchFailed` events published before the //! frontend called `engine_ready`, such as the warning about a corrupt //! settings file found at startup, are kept and replayed to the window then. use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak}; use std::thread; use std::time::Duration; use lutra_control::{Backend, EventSink, Subscribers}; use lutra_engine::{CommandInfo, Effect, Engine, EngineError, Event, NotificationLevel}; use serde_json::{Map, Value, json}; use tauri::{AppHandle, Emitter, Manager}; use tauri_plugin_dialog::DialogExt; 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"; /// Name of the Tauri event that carries engine events to the frontend. pub const ENGINE_EVENT: &str = "engine://event"; /// Time between two pumps of changes on disk. const PUMP_INTERVAL: Duration = Duration::from_millis(100); /// Most events kept for the window before it is ready; later ones are not /// replayed (they still reach control channel subscribers). const EARLY_LIMIT: usize = 50; /// Catalog key: a folder could not be opened because buffers have unsaved /// changes. Params: `path`, `what`. pub const KEY_UNSAVED_CHANGES: &str = "notification.project.unsavedChanges"; /// Catalog key: a folder could not be opened. Params: `path`, `reason`. pub const KEY_OPEN_FAILED: &str = "notification.project.openFailed"; /// Catalog key: the folder picker returned something that is not a local /// path. Params: `reason`. pub const KEY_NOT_LOCAL: &str = "notification.project.notLocal"; /// Catalog key: applying changes on disk failed. Params: `reason`. pub const KEY_PUMP_FAILED: &str = "notification.vfs.pumpFailed"; /// Engine plus the handles needed to apply effects and publish events. 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, /// Control channel connections subscribed to engine events. subscribers: Subscribers, /// This host, for callbacks that outlive a call (the folder picker). me: Weak, /// A folder picker is open; another request is ignored until it closes. picking: AtomicBool, /// The frontend called `engine_ready`. Changed and read with the engine /// lock held, so it is ordered with [`Host::publish`]. window_ready: AtomicBool, /// Notifications and `watchFailed` events published before the window /// was ready, oldest first, at most [`EARLY_LIMIT`]. early: Mutex>, } impl Host { /// A host around `engine`. pub fn new(engine: Engine) -> Arc { Arc::new_cyclic(|me| Self { engine: Mutex::new(engine), app: OnceLock::new(), subscribers: Subscribers::default(), me: me.clone(), picking: AtomicBool::new(false), window_ready: AtomicBool::new(false), early: Mutex::new(Vec::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) } /// Locks the events kept for the window, recovering a poisoned lock. fn early(&self) -> MutexGuard<'_, Vec> { self.early.lock().unwrap_or_else(PoisonError::into_inner) } /// Sends events to the control channel subscribers and the window, and /// keeps the ones the window must not miss until it is ready. Callers /// hold the engine lock. Emitting to the window fails only when the /// window is gone, in which case nobody is listening, so that error is /// ignored. fn publish(&self, events: &[Event]) { self.subscribers.publish(events); if !self.window_ready.load(Ordering::Acquire) { let mut early = self.early(); for event in events.iter().filter(|e| kept_for_window(e)) { if early.len() < EARLY_LIMIT { early.push(event.clone()); } } } if let Some(app) = self.app.get() { for event in events { let _ = app.emit(ENGINE_EVENT, event); } } } /// Runs a command, publishes its events and applies its effects. A /// command that waits for the language server is waited for without the /// engine lock ([`lutra_engine::run_waiting`]), so the pump and other /// commands keep running meanwhile. /// /// # Errors /// The engine's error for the command. pub fn run(&self, command: &str, params: Value) -> Result { let outcome = lutra_engine::run_waiting( || self.engine(), command, params, |events| self.publish(events), )?; for effect in outcome.effects { self.apply(effect); } Ok(outcome.value) } /// Publishes the events the engine queued while starting, such as the /// warning about a corrupt settings file. The window receives the /// notifications among them when it calls `engine_ready`. pub fn publish_startup(&self, events: &[Event]) { let _engine = self.engine(); self.publish(events); } /// Publishes a notification for an error that has no caller to return /// to. /// /// # Parameters /// - `level`: severity. /// - `key`: message-catalog key of the text. /// - `message`: the English text, shown without a catalog entry. /// - `params`: interpolation params for the catalog text. pub fn notify( &self, level: NotificationLevel, key: &str, message: String, params: Map, ) { let mut engine = self.engine(); let events = engine.notify(level, Some(key), Some(message), Some(params)); self.publish(&events); } /// Reports that the folder at `path` could not be opened as the /// project: a warning when buffers have unsaved changes (the user saves /// or closes them and tries again), an error otherwise. pub fn report_open_failure(&self, path: &Path, error: &EngineError) { let shown = path.display().to_string(); let (level, key, params) = open_failure(&shown, error); self.notify(level, key, format!("Cannot open {shown}: {error}"), params); } /// Lists every command with its current enabled state. pub fn commands(&self) -> Vec { self.engine().list_commands() } /// Opens the folder at `path` as the project; a relative path is taken /// relative to the current directory. /// /// # Errors /// The engine's error, e.g. when the folder does not exist. pub fn open_project(&self, path: &Path) -> Result { let path = if path.is_absolute() { path.to_path_buf() } else { std::env::current_dir() .map(|dir| dir.join(path)) .unwrap_or_else(|_| path.to_path_buf()) }; self.run("project.open", json!({ "path": path })) } /// Sends the window the events that describe the current state (the open /// project and its buffers), then the notifications and `watchFailed` /// events published before it was ready, for a frontend that just /// started listening and missed them. From then on nothing is kept for /// the window. Control channel subscribers are not affected. pub fn replay_to_window(&self) { let Some(app) = self.app.get() else { return }; let engine = self.engine(); self.window_ready.store(true, Ordering::Release); for event in state_events(&engine) { let _ = app.emit(ENGINE_EVENT, &event); } let early = std::mem::take(&mut *self.early()); for event in &early { let _ = app.emit(ENGINE_EVENT, event); } } /// Starts the thread that applies changes on disk every /// [`PUMP_INTERVAL`] and publishes the resulting events. The thread ends /// with the host. A pump that panicked or failed is reported as one /// warning notification until a pump succeeds again, and retried on the /// next tick. /// /// # Errors /// If the thread cannot be spawned. pub fn start_pump(&self) -> std::io::Result<()> { let me = self.me.clone(); thread::Builder::new() .name("lutra-vfs-pump".into()) .spawn(move || { let mut failing = false; loop { thread::sleep(PUMP_INTERVAL); let Some(host) = me.upgrade() else { return }; let mut engine = host.engine(); match engine.pump_vfs() { Ok(events) => { failing = false; host.publish(&events); } Err(e) if !failing => { failing = true; let mut params = Map::new(); params.insert("reason".into(), Value::String(e.to_string())); let events = engine.notify( NotificationLevel::Warning, Some(KEY_PUMP_FAILED), Some(format!("Applying changes on disk failed: {e}")), Some(params), ); host.publish(&events); } Err(_) => {} } } }) .map(|_| ()) } /// 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), Effect::PickFolder => self.pick_folder(app), } } /// Shows the native folder picker without blocking and opens the chosen /// folder. Only one picker is open at a time; a request while one is /// open is ignored. Cancelling does nothing. A folder that cannot be /// opened, for example because buffers have unsaved changes, is /// reported as a notification. fn pick_folder(&self, app: &AppHandle) { if self.picking.swap(true, Ordering::AcqRel) { return; } let me = self.me.clone(); app.dialog() .file() .set_title("Open Folder") .pick_folder(move |folder| { let Some(host) = me.upgrade() else { return }; host.picking.store(false, Ordering::Release); let Some(folder) = folder else { return }; let path: PathBuf = match folder.into_path() { Ok(path) => path, Err(e) => { let mut params = Map::new(); params.insert("reason".into(), Value::String(e.to_string())); host.notify( NotificationLevel::Error, KEY_NOT_LOCAL, format!("The picked folder is not a local path: {e}"), params, ); return; } }; if let Err(e) = host.open_project(&path) { host.report_open_failure(&path, &e); } }); } } /// Whether the window must see `event` even if it was published before the /// frontend listened: notifications and `watchFailed`. The project and its /// buffers are replayed from the engine state instead. fn kept_for_window(event: &Event) -> bool { matches!( event, Event::Notification { .. } | Event::WatchFailed { .. } ) } /// The events that describe the engine's current state: the open project /// and its buffers; none without a project. fn state_events(engine: &Engine) -> Vec { let state = engine.state(); let Some(workspace) = &state.project else { return Vec::new(); }; let root = workspace.project.root(); let mut events = vec![Event::ProjectOpened { root: root.to_string_lossy().into_owned(), name: root .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_else(|| root.to_string_lossy().into_owned()), }]; for id in state.buffers.ids() { if let Some(open) = state.buffers.get(id) { events.push(Event::BufferOpened { id, path: lutra_engine::workspace::path_string(&open.path), }); } } events } /// Level, catalog key and params of the notification for a folder at /// `path` that could not be opened with `error`. fn open_failure( path: &str, error: &EngineError, ) -> (NotificationLevel, &'static str, Map) { let mut params = Map::new(); params.insert("path".into(), Value::String(path.to_string())); match error { EngineError::UnsavedChanges(what) => { params.insert("what".into(), Value::String(what.clone())); (NotificationLevel::Warning, KEY_UNSAVED_CHANGES, params) } _ => { params.insert("reason".into(), Value::String(error.to_string())); (NotificationLevel::Error, KEY_OPEN_FAILED, params) } } } 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) } fn subscribe(&self, sink: EventSink) { self.subscribers.add(sink); } /// Restores, shows and focuses the main window. Failures to restore or /// show are ignored because focusing still works on a visible window; /// the focus error is returned. fn focus(&self) -> Result<(), String> { let app = self.app.get().ok_or("the window is not open yet")?; let window = app .get_webview_window(MAIN_WINDOW) .ok_or("the window is not open yet")?; let _ = window.unminimize(); let _ = window.show(); window.set_focus().map_err(|e| e.to_string()) } } #[cfg(test)] mod tests { use super::*; #[test] fn unsaved_changes_are_a_warning() { let (level, key, params) = open_failure("/p", &EngineError::UnsavedChanges("a.php".into())); assert_eq!(level, NotificationLevel::Warning); assert_eq!(key, KEY_UNSAVED_CHANGES); assert_eq!(params["path"], "/p"); assert_eq!(params["what"], "a.php"); } #[test] fn other_open_failures_are_errors() { let (level, key, params) = open_failure("/p", &EngineError::Failed("gone".into())); assert_eq!(level, NotificationLevel::Error); assert_eq!(key, KEY_OPEN_FAILED); assert_eq!(params["reason"], "gone"); } #[test] fn notifications_wait_for_the_window() { let host = Host::new(Engine::new().unwrap()); host.notify(NotificationLevel::Info, "k", "m".into(), Map::new()); host.publish_startup(&[ Event::WatchFailed { message: "x".into(), }, Event::ProjectClosed, ]); let early = host.early(); assert_eq!(early.len(), 2); assert!(matches!(early[0], Event::Notification { .. })); assert!(matches!(early[1], Event::WatchFailed { .. })); } #[test] fn early_events_are_capped() { let host = Host::new(Engine::new().unwrap()); for _ in 0..EARLY_LIMIT + 5 { host.notify(NotificationLevel::Info, "k", "m".into(), Map::new()); } assert_eq!(host.early().len(), EARLY_LIMIT); } }