Lutra/apps/lutra-desktop/src/main.rs
danny e969f6497c
Some checks are pending
ci / ci (macos-15) (push) Waiting to run
ci / ci (ubuntu-24.04) (push) Waiting to run
ci / ci (windows-2025) (push) Waiting to run
PM: merge H4 string and path settings controls, live assist settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 13:20:26 +01:00

288 lines
10 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`). A normal
//! start is a single instance (see [`instance`]): a second start forwards
//! its path to the running app and exits. A start with `--data-dir`,
//! `LUTRA_DATA_DIR` or `--control` keeps its files away from the user's
//! (see [`datadir`]).
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod args;
mod datadir;
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
/// (or the isolated data directory, sharing the user's managed tools),
/// 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, the
/// isolated data directory cannot be created, 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 isolated = datadir::isolated(args);
if let Some(dir) = &isolated {
std::fs::create_dir_all(dir)
.map_err(|e| format!("cannot create the data directory {}: {e}", dir.display()))?;
eprintln!("lutra: data directory {}", dir.display());
}
let webview_dir = isolated.as_deref().map(datadir::webview_dir);
let instance_dir = instance::rendezvous_dir(args, isolated.as_deref());
if let Some(dir) = &instance_dir
&& instance::forward(dir, args.path.as_deref())?
{
return Ok(());
}
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_execute_waiting,
engine_list_commands,
engine_ready,
pick_file
])
.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(dir) = &webview_dir {
window = window.data_directory(dir.clone());
}
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 user = engine_config(&app)?;
let config = match &isolated {
Some(dir) => datadir::engine_config(dir),
None => user.clone(),
};
let mut engine = Engine::with_config(config).map_err(|e| e.to_string())?;
if isolated.is_some() {
engine.share_tools_from(user.data_dir);
}
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 user's engine directories from Tauri's path resolver: the app config
/// dir for settings, the app data dir for the recovery journal and the
/// managed tools. Resolving creates nothing.
///
/// # 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: runs an engine command that may wait for the language server
/// (`lsp.*`). `async` makes Tauri run it off the main thread, so the window
/// stays responsive while it waits (the wait itself never holds the engine
/// lock, see [`Host::run`]). Unlike [`engine_execute`], calls are not
/// ordered with other commands; the frontend uses it only for requests that
/// follow the edits they depend on.
#[tauri::command(async)]
fn engine_execute_waiting(
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();
}
/// IPC: shows the native file picker for a path setting's "Browse…"
/// button and returns the chosen file, or `None` when the user cancels or
/// picks something that is not a local path. `async` keeps the blocking
/// picker off the main thread. The frontend stores the path through
/// `settings.set`, so the setting itself stays an engine command.
#[tauri::command(async)]
fn pick_file(app: tauri::AppHandle, title: String) -> Option<String> {
use tauri_plugin_dialog::DialogExt;
let picked = app.dialog().file().set_title(title).blocking_pick_file()?;
let path = picked.into_path().ok()?;
Some(path.to_string_lossy().into_owned())
}
#[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);
}
}