//! The Lutra desktop app (layer L6): a Tauri 2 shell around the engine. //! //! Builds the main window with the stored theme's tokens injected before //! first paint, //! bridges frontend IPC to engine commands and engine events to the window //! (see [`host`]), opens the project given on the command line, and //! optionally serves the JSON control channel (`--control PORT`). A normal //! start is a single instance (see [`instance`]): a second start forwards //! its path to the running app and exits. #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] mod args; mod host; mod instance; mod screenshot; use std::process::ExitCode; use std::sync::{Arc, OnceLock}; use lutra_engine::{CommandInfo, Engine, EngineConfig, ErrorPayload, theme}; use serde_json::Value; use tauri::window::Color; use tauri::{Manager, WebviewUrl, WebviewWindowBuilder}; use crate::host::{Host, MAIN_WINDOW, WINDOW_TITLE}; /// Parses the arguments, starts the control channel if asked, and runs the /// app until it quits. fn main() -> ExitCode { let args = match args::parse_os(std::env::args_os().skip(1)) { Ok(args) => args, Err(message) => { eprintln!("lutra: {message}\n\n{}", args::USAGE); return ExitCode::from(2); } }; if args.help { println!("{}", args::USAGE); return ExitCode::SUCCESS; } if args.version { println!("lutra-desktop {}", env!("CARGO_PKG_VERSION")); return ExitCode::SUCCESS; } match run(&args) { Ok(()) => ExitCode::SUCCESS, Err(message) => { eprintln!("lutra: {message}"); ExitCode::FAILURE } } } /// Forwards to a running instance if there is one; otherwise builds the /// Tauri app, starts the engine with the app's config and data directories, /// the host, the control channel and the single-instance listener, and runs /// the event loop. The window is created in the setup hook, which runs once /// the event loop has started. A single-instance listener or rendezvous /// file that cannot be set up is reported and the app runs without it. /// /// # Errors /// A message if a running instance refused the forwarded path, Tauri cannot /// build the app or resolve its directories, the engine cannot start, or /// the control port cannot be bound. fn run(args: &args::Args) -> Result<(), String> { let instance_dir = instance::rendezvous_dir(args); if let Some(dir) = &instance_dir && instance::forward(dir, args.path.as_deref())? { return Ok(()); } let slot: Arc>> = Arc::new(OnceLock::new()); let setup_slot = slot.clone(); let initial_path = args.path.clone(); let app = tauri::Builder::default() .plugin(tauri_plugin_dialog::init()) .invoke_handler(tauri::generate_handler![ engine_execute, engine_list_commands, engine_ready ]) .setup(move |app| { let setup_host = setup_slot.get().ok_or("the host is not ready")?; setup_host.attach(app.handle().clone()); let setting = stored_theme(setup_host); let mut window = WebviewWindowBuilder::new(app, MAIN_WINDOW, WebviewUrl::default()) .title(WINDOW_TITLE) .inner_size(1200.0, 800.0) .min_inner_size(640.0, 400.0) .initialization_script(theme::init_script(&setting)); if let Some(color) = token_color(&theme::resolve(&setting, None), "bg") { window = window.background_color(color); } let window = window.build()?; if setting == theme::SYSTEM { follow_system_background(&window); } if let Some(path) = &initial_path && let Err(e) = setup_host.open_project(path) { setup_host.report_open_failure(path, &e); } Ok(()) }) .build(tauri::generate_context!()) .map_err(|e| e.to_string())?; let mut engine = Engine::with_config(engine_config(&app)?).map_err(|e| e.to_string())?; engine.allow_downloads().map_err(|e| e.to_string())?; let startup = engine.take_events(); let host = Host::new(engine); host.publish_startup(&startup); app.manage(host.clone()); if slot.set(host.clone()).is_err() { return Err("the host was set twice".into()); } if let Some(port) = args.control { let server = lutra_control::start(port, host.clone()) .map_err(|e| format!("cannot serve the control channel on port {port}: {e}"))?; eprintln!("lutra: control channel on {}", server.local_addr()); } let claim = instance_dir .as_deref() .and_then(|dir| match instance::Claim::take(dir, &host) { Ok(claim) => Some(claim), Err(message) => { eprintln!("lutra: running without single instance: {message}"); None } }); host.start_pump() .map_err(|e| format!("cannot start watching for changes: {e}"))?; app.run(move |_, event| { if let tauri::RunEvent::Exit = event && let Some(claim) = &claim { claim.release(); } }); Ok(()) } /// The engine directories from Tauri's path resolver: the app config dir /// for settings, the app data dir for the recovery journal. /// /// # Errors /// A message if the platform has no such directories. fn engine_config(app: &tauri::App) -> Result { let paths = app.path(); Ok(EngineConfig { config_dir: paths .app_config_dir() .map_err(|e| format!("no config directory: {e}"))?, data_dir: paths .app_data_dir() .map_err(|e| format!("no data directory: {e}"))?, }) } /// The stored `appearance.theme` value, `system` if it cannot be read. fn stored_theme(host: &Host) -> String { host.run( "settings.get", serde_json::json!({ "keys": ["appearance.theme"] }), ) .ok() .and_then(|v| { v.get("values")? .get("appearance.theme")? .as_str() .map(str::to_string) }) .unwrap_or_else(|| theme::SYSTEM.to_string()) } /// In "system" mode, sets the window background to the theme the OS /// prefers; the page itself follows the OS through the init script's /// `prefers-color-scheme` query. Failures are ignored: the background only /// shows before the first paint, and the dark default stays. fn follow_system_background(window: &tauri::WebviewWindow) { let Ok(os) = window.theme() else { return; }; let resolved = theme::resolve(theme::SYSTEM, Some(os == tauri::Theme::Dark)); if let Some(color) = token_color(&resolved, "bg") { let _ = window.set_background_color(Some(color)); } } /// Reads a `#rrggbb` theme token as an opaque colour for the window /// background, so that no white frame shows before the page paints. fn token_color(theme: &theme::Theme, name: &str) -> Option { let (_, value) = theme.tokens.iter().find(|(n, _)| *n == name)?; let hex = value.strip_prefix('#')?; let byte = |at: usize| u8::from_str_radix(hex.get(at..at + 2)?, 16).ok(); Some(Color(byte(0)?, byte(2)?, byte(4)?, 255)) } /// IPC: runs an engine command for the frontend. #[tauri::command] fn engine_execute( host: tauri::State<'_, Arc>, command: String, params: Value, ) -> Result { host.run(&command, params).map_err(|e| e.payload()) } /// IPC: lists the engine's commands for the frontend. #[tauri::command] fn engine_list_commands(host: tauri::State<'_, Arc>) -> Vec { host.commands() } /// IPC: the frontend listens for engine events now; replays the current /// project state and the notifications it may have missed while loading. #[tauri::command] fn engine_ready(host: tauri::State<'_, Arc>) { host.replay_to_window(); } #[cfg(test)] mod tests { use super::*; #[test] fn reads_theme_colours() { assert_eq!( token_color(&theme::DARK, "bg"), Some(Color(0x1f, 0x1d, 0x1b, 255)) ); assert_eq!(token_color(&theme::DARK, "missing"), None); } }