M0.5: Tauri desktop shell with themed main window
The window is built in setup with the theme tokens injected by an initialization script and the background colour taken from the theme, so the first frame is already themed. Frontend IPC (engine_execute, engine_list_commands) and the control channel both run commands through the Host, which applies effects such as Quit. ui.screenshot captures the window's client area from the screen because xcap skips windows of its own process. build.rs generates the placeholder icon into the gitignored icons/ directory. Verified on Windows: window opens, ping, listCommands, screenshot, app.quit, and exit status 1 when the control port is taken. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a3f83102f1
commit
55acb0dffb
14 changed files with 6025 additions and 36 deletions
93
apps/lutra-desktop/src/args.rs
Normal file
93
apps/lutra-desktop/src/args.rs
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
//! Command-line arguments of the desktop app.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Parsed arguments.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub struct Args {
|
||||
/// Port for the JSON control channel (`--control PORT`).
|
||||
pub control: Option<u16>,
|
||||
/// Folder or file to open.
|
||||
pub path: Option<PathBuf>,
|
||||
/// `--help` was given.
|
||||
pub help: bool,
|
||||
/// `--version` was given.
|
||||
pub version: bool,
|
||||
}
|
||||
|
||||
/// Usage text for `--help`.
|
||||
pub const USAGE: &str = "usage: lutra-desktop [--control PORT] [PATH]
|
||||
|
||||
--control PORT serve the JSON control channel on 127.0.0.1:PORT
|
||||
--version print the version
|
||||
--help print this help";
|
||||
|
||||
/// Parses the arguments after the program name.
|
||||
///
|
||||
/// # Errors
|
||||
/// A message for an unknown flag, a missing or invalid port, or more than one
|
||||
/// path.
|
||||
pub fn parse(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
let mut parsed = Args::default();
|
||||
let mut args = args.into_iter();
|
||||
while let Some(arg) = args.next() {
|
||||
if let Some(value) = arg.strip_prefix("--control=") {
|
||||
parsed.control = Some(port(value)?);
|
||||
continue;
|
||||
}
|
||||
match arg.as_str() {
|
||||
"--control" => {
|
||||
let value = args.next().ok_or("--control needs a port")?;
|
||||
parsed.control = Some(port(&value)?);
|
||||
}
|
||||
"--help" | "-h" => parsed.help = true,
|
||||
"--version" | "-V" => parsed.version = true,
|
||||
flag if flag.starts_with('-') => return Err(format!("unknown option {flag}")),
|
||||
path => {
|
||||
if parsed.path.is_some() {
|
||||
return Err("only one PATH can be given".into());
|
||||
}
|
||||
parsed.path = Some(PathBuf::from(path));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
/// Parses a TCP port number.
|
||||
///
|
||||
/// # Errors
|
||||
/// A message if the value is not a number from 1 to 65535.
|
||||
fn port(value: &str) -> Result<u16, String> {
|
||||
match value.parse::<u16>() {
|
||||
Ok(0) | Err(_) => Err(format!("invalid port {value:?}; expected 1-65535")),
|
||||
Ok(port) => Ok(port),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn p(args: &[&str]) -> Result<Args, String> {
|
||||
parse(args.iter().map(|s| s.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_control_and_path() {
|
||||
let a = p(&["--control", "7979", "/tmp/demo"]).unwrap();
|
||||
assert_eq!(a.control, Some(7979));
|
||||
assert_eq!(a.path, Some(PathBuf::from("/tmp/demo")));
|
||||
assert_eq!(p(&["--control=80"]).unwrap().control, Some(80));
|
||||
assert_eq!(p(&[]).unwrap(), Args::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_input() {
|
||||
assert!(p(&["--control"]).is_err());
|
||||
assert!(p(&["--control", "0"]).is_err());
|
||||
assert!(p(&["--control", "70000"]).is_err());
|
||||
assert!(p(&["--frobnicate"]).is_err());
|
||||
assert!(p(&["a", "b"]).is_err());
|
||||
}
|
||||
}
|
||||
92
apps/lutra-desktop/src/host.rs
Normal file
92
apps/lutra-desktop/src/host.rs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
//! The host: owns the engine, applies effects to the Tauri app and serves
|
||||
//! the control channel's [`Backend`].
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
|
||||
|
||||
use lutra_control::Backend;
|
||||
use lutra_engine::{CommandInfo, Effect, Engine, EngineError};
|
||||
use serde_json::Value;
|
||||
use tauri::AppHandle;
|
||||
|
||||
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";
|
||||
|
||||
/// Engine plus the handle needed to apply effects.
|
||||
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<Engine>,
|
||||
/// The Tauri app, set once the app is set up.
|
||||
app: OnceLock<AppHandle>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// A host with a fresh engine.
|
||||
///
|
||||
/// # Errors
|
||||
/// The engine's error if the built-in commands cannot be registered.
|
||||
pub fn new() -> Result<Self, EngineError> {
|
||||
Ok(Self {
|
||||
engine: Mutex::new(Engine::new()?),
|
||||
app: OnceLock::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)
|
||||
}
|
||||
|
||||
/// Runs a command and applies its effects.
|
||||
///
|
||||
/// # Errors
|
||||
/// The engine's error for the command.
|
||||
pub fn run(&self, command: &str, params: Value) -> Result<Value, EngineError> {
|
||||
let outcome = self.engine().execute(command, params)?;
|
||||
for effect in outcome.effects {
|
||||
self.apply(effect);
|
||||
}
|
||||
Ok(outcome.value)
|
||||
}
|
||||
|
||||
/// Lists every command with its current enabled state.
|
||||
pub fn commands(&self) -> Vec<CommandInfo> {
|
||||
self.engine().list_commands()
|
||||
}
|
||||
|
||||
/// 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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for Host {
|
||||
fn execute(&self, command: &str, params: Value) -> Result<Value, EngineError> {
|
||||
self.run(command, params)
|
||||
}
|
||||
|
||||
fn list_commands(&self) -> Vec<CommandInfo> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
130
apps/lutra-desktop/src/main.rs
Normal file
130
apps/lutra-desktop/src/main.rs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
//! 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 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;
|
||||
|
||||
use lutra_engine::{CommandInfo, ErrorPayload, theme};
|
||||
use serde_json::Value;
|
||||
use tauri::window::Color;
|
||||
use tauri::{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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the host, the control channel and the Tauri event loop.
|
||||
///
|
||||
/// # Errors
|
||||
/// A message if the engine cannot start, the control port cannot be bound,
|
||||
/// or Tauri fails.
|
||||
fn run(args: &args::Args) -> Result<(), String> {
|
||||
let host = Arc::new(Host::new().map_err(|e| e.to_string())?);
|
||||
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());
|
||||
}
|
||||
if let Some(path) = &args.path {
|
||||
eprintln!(
|
||||
"lutra: opening {} arrives with milestone M1; starting without a project",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
let theme = theme::DARK;
|
||||
let setup_host = host.clone();
|
||||
tauri::Builder::default()
|
||||
.manage(host)
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
engine_execute,
|
||||
engine_list_commands
|
||||
])
|
||||
.setup(move |app| {
|
||||
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()?;
|
||||
Ok(())
|
||||
})
|
||||
.run(tauri::generate_context!())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
107
apps/lutra-desktop/src/screenshot.rs
Normal file
107
apps/lutra-desktop/src/screenshot.rs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
//! Screenshots of Lutra's main window for `ui.screenshot`.
|
||||
//!
|
||||
//! `xcap` refuses to enumerate windows of the calling process (querying their
|
||||
//! titles can deadlock), so the screenshot is taken from the screen instead:
|
||||
//! the main window is brought to the front, its client area is located in
|
||||
//! physical pixels through Tauri, and that region of the monitor is captured.
|
||||
//! Anything covering the window at that moment shows up in the image.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use tauri::{AppHandle, Manager};
|
||||
use xcap::Monitor;
|
||||
use xcap::image::ImageFormat;
|
||||
|
||||
/// Time for the compositor to show the window after it was focused.
|
||||
const SETTLE: Duration = Duration::from_millis(150);
|
||||
|
||||
/// Captures the client area of the window labelled `label` and writes it to
|
||||
/// `path` as PNG. Must not be called on the main thread, which has to stay
|
||||
/// free to answer the window queries. Focusing the window is best effort: a
|
||||
/// failure is ignored because the capture still works when the window is
|
||||
/// already in front.
|
||||
///
|
||||
/// # Errors
|
||||
/// A message if the window does not exist or is minimised, the monitor
|
||||
/// cannot be captured, or the PNG cannot be written.
|
||||
pub fn capture_window(app: &AppHandle, label: &str, path: &Path) -> Result<(), String> {
|
||||
let window = app
|
||||
.get_webview_window(label)
|
||||
.ok_or_else(|| format!("no window labelled {label}"))?;
|
||||
if window.is_minimized().unwrap_or(false) {
|
||||
return Err("the main window is minimised".into());
|
||||
}
|
||||
let _ = window.set_focus();
|
||||
std::thread::sleep(SETTLE);
|
||||
let pos = window.inner_position().map_err(|e| e.to_string())?;
|
||||
let size = window.inner_size().map_err(|e| e.to_string())?;
|
||||
let centre_x = pos
|
||||
.x
|
||||
.saturating_add(i32::try_from(size.width / 2).unwrap_or(0));
|
||||
let centre_y = pos
|
||||
.y
|
||||
.saturating_add(i32::try_from(size.height / 2).unwrap_or(0));
|
||||
let monitor = Monitor::from_point(centre_x, centre_y)
|
||||
.map_err(|e| format!("cannot find the window's monitor: {e}"))?;
|
||||
let (mx, my) = (
|
||||
monitor.x().map_err(|e| e.to_string())?,
|
||||
monitor.y().map_err(|e| e.to_string())?,
|
||||
);
|
||||
let (mw, mh) = (
|
||||
monitor.width().map_err(|e| e.to_string())?,
|
||||
monitor.height().map_err(|e| e.to_string())?,
|
||||
);
|
||||
let region = clip(
|
||||
pos.x.saturating_sub(mx),
|
||||
pos.y.saturating_sub(my),
|
||||
size.width,
|
||||
size.height,
|
||||
mw,
|
||||
mh,
|
||||
)
|
||||
.ok_or("the main window is outside its monitor")?;
|
||||
let image = monitor
|
||||
.capture_region(region.0, region.1, region.2, region.3)
|
||||
.map_err(|e| format!("cannot capture the screen: {e}"))?;
|
||||
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
||||
}
|
||||
image
|
||||
.save_with_format(path, ImageFormat::Png)
|
||||
.map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Clips a rectangle given relative to a monitor's origin to the monitor's
|
||||
/// bounds, returning `(x, y, width, height)` or `None` if nothing is left.
|
||||
fn clip(x: i32, y: i32, w: u32, h: u32, mw: u32, mh: u32) -> Option<(u32, u32, u32, u32)> {
|
||||
let left = i64::from(x).max(0);
|
||||
let top = i64::from(y).max(0);
|
||||
let right = (i64::from(x) + i64::from(w)).min(i64::from(mw));
|
||||
let bottom = (i64::from(y) + i64::from(h)).min(i64::from(mh));
|
||||
if right <= left || bottom <= top {
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
u32::try_from(left).ok()?,
|
||||
u32::try_from(top).ok()?,
|
||||
u32::try_from(right - left).ok()?,
|
||||
u32::try_from(bottom - top).ok()?,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::clip;
|
||||
|
||||
#[test]
|
||||
fn clips_to_the_monitor() {
|
||||
assert_eq!(clip(10, 20, 100, 50, 1920, 1080), Some((10, 20, 100, 50)));
|
||||
assert_eq!(clip(-10, -5, 100, 50, 1920, 1080), Some((0, 0, 90, 45)));
|
||||
assert_eq!(
|
||||
clip(1900, 1000, 100, 100, 1920, 1080),
|
||||
Some((1900, 1000, 20, 80))
|
||||
);
|
||||
assert_eq!(clip(2000, 0, 100, 100, 1920, 1080), None);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue