EngineConfig and Engine::with_config; the desktop resolves Tauri's app config and data dirs. Settings model (appearance.theme, editor.fontSize, ui.language) with typed validation, persistence in settings.json via write_atomic (1 MiB cap, unknown keys kept, corrupt file backed up with a warning notification), settings.list/get/set/reset, settingsChanged and notification events. Property test over random settings.json content, control-channel test for persistence and corrupt-file recovery. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
186 lines
6.2 KiB
Rust
186 lines
6.2 KiB
Rust
//! The Lutra desktop app (layer L6): a Tauri 2 shell around the engine.
|
|
//!
|
|
//! Builds the main window with the theme 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, Event, 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 theme = theme::DARK;
|
|
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 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(&theme));
|
|
if let Some(color) = token_color(&theme, "bg") {
|
|
window = window.background_color(color);
|
|
}
|
|
window.build()?;
|
|
if let Some(path) = &initial_path
|
|
&& let Err(e) = setup_host.open_project(path)
|
|
{
|
|
eprintln!("lutra: cannot open {}: {e}", path.display());
|
|
}
|
|
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())?;
|
|
log_startup_events(&engine.take_events());
|
|
let host = Host::new(engine);
|
|
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}"))?,
|
|
})
|
|
}
|
|
|
|
/// Logs the notifications the engine queued while starting, such as the
|
|
/// fallback to default settings, to stderr.
|
|
fn log_startup_events(events: &[Event]) {
|
|
for event in events {
|
|
if let Event::Notification {
|
|
level,
|
|
message: Some(message),
|
|
..
|
|
} = event
|
|
{
|
|
eprintln!("lutra: {level:?}: {message}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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 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);
|
|
}
|
|
}
|