Lutra/apps/lutra-desktop/src/main.rs
danny f41df518b5 M1.12: notifications as toasts
The host publishes picker, command-line and pump errors as notification
events (Engine::notify, same id sequence) instead of stderr, keeps
notifications and watchFailed published before engine_ready and replays
them after the state replay, so startup warnings (corrupt settings,
journal entries) reach the UI. ipc.ts announces engine_ready once all
subscriptions started together are registered.

Frontend: notifications store and NotificationStack (bottom right, info
auto-dismissed after 5 s, warnings/errors stay, close button and Escape,
at most 5 visible with "+n more", role status/alert); watchFailed maps to
a warning toast; failed commands without their own UI raise an error
toast. Catalog keys notification.settings.*, project.*, vfs.*, watch.*,
command.* plus the runtime allow-list. Docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:20:45 +02:00

206 lines
7.1 KiB
Rust

//! 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`).
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod args;
mod host;
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(std::env::args().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
}
}
}
/// Builds the Tauri app, starts the engine with the app's config and data
/// directories, the host, the control channel, and runs the event loop.
/// The window is created in the setup hook, which runs once the event loop
/// has started.
///
/// # Errors
/// A message if 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 slot: Arc<OnceLock<Arc<Host>>> = 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())?;
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());
}
host.start_pump()
.map_err(|e| format!("cannot start watching for changes: {e}"))?;
app.run(|_, _| {});
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<EngineConfig, String> {
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<Color> {
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<Host>>,
command: String,
params: Value,
) -> Result<Value, ErrorPayload> {
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<Host>>) -> Vec<CommandInfo> {
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>>) {
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);
}
}