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
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -7,3 +7,5 @@ dist/
|
|||
*.log
|
||||
.idea/
|
||||
.vscode/
|
||||
/apps/lutra-desktop/icons/
|
||||
/apps/lutra-desktop/gen/
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ Vue components read engine state (pushed as events) and act through `run(command
|
|||
|
||||
## Running and looking at the app
|
||||
- `cargo xtask dev` starts the desktop app in development mode (Vite + Tauri).
|
||||
- `cargo run -p lutra-desktop -- --control 7979 [path]` starts it with the JSON control channel. If the port is taken, the app exits with an error; pick another port.
|
||||
- `cargo xtask dev -- --control 7979 [path]` starts it with the JSON control channel. A plain `cargo run -p lutra-desktop -- --control 7979` works too while `pnpm --dir ui dev` runs; for a self-contained build run `pnpm --dir ui build` and add `--features bundled-ui`. If the port is taken, the app exits with an error; pick another port.
|
||||
- Drive it with JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"project.open","params":{"path":"/tmp/demo"}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/control/src/methods.rs`.
|
||||
- **For UI work, look at the result**: take `ui.screenshot`, read the PNG, and compare it with the public documentation notes in `plan/phpstorm/`. If no frame can be presented (headless machine), cover the component with a Vitest + Vue Test Utils test.
|
||||
- **Performance:** `lutra perf` checks the budgets (cold start, open a 1 MB file, keystroke to highlight, find in files, index a reference project) on generated and reference projects; `lutra bench PATH` times one project. Run them before and after editor, index or search changes, on an idle machine.
|
||||
|
|
|
|||
5437
Cargo.lock
generated
5437
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -39,7 +39,7 @@ git clone <repo-url> lutra
|
|||
cd lutra
|
||||
|
||||
cargo xtask dev # desktop app in development mode
|
||||
cargo run -p lutra-desktop -- --control 7979 . # + JSON control channel
|
||||
cargo xtask dev -- --control 7979 . # + JSON control channel
|
||||
cargo xtask ci # fmt, clippy, tests, layers, assets, clean-room, frontend checks
|
||||
```
|
||||
|
||||
|
|
|
|||
29
apps/lutra-desktop/Cargo.toml
Normal file
29
apps/lutra-desktop/Cargo.toml
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
[package]
|
||||
name = "lutra-desktop"
|
||||
description = "The Lutra desktop app: Tauri shell around the engine"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[package.metadata.lutra]
|
||||
layer = 6
|
||||
|
||||
[features]
|
||||
bundled-ui = ["tauri/custom-protocol"]
|
||||
|
||||
[dependencies]
|
||||
lutra-control.workspace = true
|
||||
lutra-engine.workspace = true
|
||||
serde_json = "1.0.154"
|
||||
tauri = { version = "2.11.6", features = [] }
|
||||
xcap = "0.9.8"
|
||||
|
||||
[build-dependencies]
|
||||
png = "0.18.1"
|
||||
tauri-build = { version = "2.6.3", features = [] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
130
apps/lutra-desktop/build.rs
Normal file
130
apps/lutra-desktop/build.rs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
//! Build script of the desktop app.
|
||||
//!
|
||||
//! Generates the placeholder app icon (an otter-brown rounded square holding a
|
||||
//! pale stone) into the gitignored `icons/` directory, then runs the Tauri
|
||||
//! build step, which needs those files. The real icon is the owner's to
|
||||
//! commission; this one is generated in code and has no asset file.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
/// Edge length of the generated icon in pixels.
|
||||
const SIZE: u32 = 256;
|
||||
|
||||
/// Writes the icons and runs `tauri_build`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails if the icons cannot be encoded or written.
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let dir = Path::new(&std::env::var("CARGO_MANIFEST_DIR")?).join("icons");
|
||||
fs::create_dir_all(&dir)?;
|
||||
let png = encode_png(&draw_icon(), SIZE)?;
|
||||
write_if_changed(&dir.join("icon.png"), &png)?;
|
||||
write_if_changed(&dir.join("icon.ico"), &ico_from_png(&png))?;
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
tauri_build::build();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes a file only if its content differs, so that the Tauri build step
|
||||
/// does not see a changed icon on every build.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails if the file cannot be written.
|
||||
fn write_if_changed(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
if fs::read(path).ok().as_deref() == Some(bytes) {
|
||||
return Ok(());
|
||||
}
|
||||
fs::write(path, bytes)
|
||||
}
|
||||
|
||||
/// Draws the icon as RGBA pixels, row by row, with 4×4 supersampling for
|
||||
/// smooth edges.
|
||||
fn draw_icon() -> Vec<u8> {
|
||||
let body = [0x6b, 0x4a, 0x32];
|
||||
let stone = [0xd9, 0xd2, 0xc5];
|
||||
let size = f64::from(SIZE);
|
||||
let mut pixels = Vec::with_capacity((SIZE * SIZE * 4) as usize);
|
||||
for y in 0..SIZE {
|
||||
for x in 0..SIZE {
|
||||
let (mut body_cover, mut stone_cover) = (0.0, 0.0);
|
||||
for sy in 0..4 {
|
||||
for sx in 0..4 {
|
||||
let px = (f64::from(x) + (f64::from(sx) + 0.5) / 4.0) / size;
|
||||
let py = (f64::from(y) + (f64::from(sy) + 0.5) / 4.0) / size;
|
||||
if in_rounded_square(px, py) {
|
||||
body_cover += 1.0 / 16.0;
|
||||
if in_stone(px, py) {
|
||||
stone_cover += 1.0 / 16.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mix = |b: u8, s: u8| {
|
||||
let b = f64::from(b);
|
||||
let s = f64::from(s);
|
||||
let t = if body_cover > 0.0 {
|
||||
stone_cover / body_cover
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
(b + (s - b) * t).round().clamp(0.0, 255.0) as u8
|
||||
};
|
||||
pixels.extend_from_slice(&[
|
||||
mix(body[0], stone[0]),
|
||||
mix(body[1], stone[1]),
|
||||
mix(body[2], stone[2]),
|
||||
(body_cover * 255.0).round().clamp(0.0, 255.0) as u8,
|
||||
]);
|
||||
}
|
||||
}
|
||||
pixels
|
||||
}
|
||||
|
||||
/// Whether a point in unit coordinates lies in the rounded square with a
|
||||
/// small margin.
|
||||
fn in_rounded_square(x: f64, y: f64) -> bool {
|
||||
let (lo, hi, r) = (0.06, 0.94, 0.2);
|
||||
if !(lo..=hi).contains(&x) || !(lo..=hi).contains(&y) {
|
||||
return false;
|
||||
}
|
||||
let cx = x.clamp(lo + r, hi - r);
|
||||
let cy = y.clamp(lo + r, hi - r);
|
||||
(x - cx).powi(2) + (y - cy).powi(2) <= r * r
|
||||
}
|
||||
|
||||
/// Whether a point in unit coordinates lies in the stone, an ellipse in the
|
||||
/// lower middle.
|
||||
fn in_stone(x: f64, y: f64) -> bool {
|
||||
((x - 0.5) / 0.26).powi(2) + ((y - 0.6) / 0.18).powi(2) <= 1.0
|
||||
}
|
||||
|
||||
/// Encodes RGBA pixels as PNG.
|
||||
///
|
||||
/// # Errors
|
||||
/// Fails if the encoder rejects the data.
|
||||
fn encode_png(pixels: &[u8], size: u32) -> Result<Vec<u8>, png::EncodingError> {
|
||||
let mut out = Vec::new();
|
||||
{
|
||||
let mut encoder = png::Encoder::new(&mut out, size, size);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
let mut writer = encoder.write_header()?;
|
||||
writer.write_image_data(pixels)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Wraps a 256×256 PNG in an ICO container with a single entry, which every
|
||||
/// Windows version since Vista reads.
|
||||
fn ico_from_png(png: &[u8]) -> Vec<u8> {
|
||||
let len = u32::try_from(png.len()).unwrap_or(u32::MAX);
|
||||
let mut ico = Vec::with_capacity(22 + png.len());
|
||||
ico.extend_from_slice(&[0, 0, 1, 0, 1, 0]);
|
||||
ico.extend_from_slice(&[0, 0, 0, 0, 1, 0, 32, 0]);
|
||||
ico.extend_from_slice(&len.to_le_bytes());
|
||||
ico.extend_from_slice(&22u32.to_le_bytes());
|
||||
ico.extend_from_slice(png);
|
||||
ico
|
||||
}
|
||||
7
apps/lutra-desktop/capabilities/default.json
Normal file
7
apps/lutra-desktop/capabilities/default.json
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Permissions of the main window",
|
||||
"windows": ["main"],
|
||||
"permissions": ["core:default"]
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
23
apps/lutra-desktop/tauri.conf.json
Normal file
23
apps/lutra-desktop/tauri.conf.json
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Lutra",
|
||||
"version": "0.0.0",
|
||||
"identifier": "dev.lutra.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
"frontendDist": "../../ui/dist",
|
||||
"beforeDevCommand": { "script": "pnpm dev", "cwd": "../../ui", "wait": false },
|
||||
"beforeBuildCommand": { "script": "pnpm build", "cwd": "../../ui" }
|
||||
},
|
||||
"app": {
|
||||
"windows": [],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost",
|
||||
"devCsp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost ws://localhost:5173 http://localhost:5173"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": false,
|
||||
"icon": ["icons/icon.png", "icons/icon.ico"]
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# Architecture
|
||||
|
||||
> **Status:** M0 decisions recorded · **Last updated:** 2026-10-13
|
||||
> **Status:** M0 decisions recorded · **Last updated:** 2026-10-14
|
||||
|
||||
## Overview
|
||||
|
||||
|
|
@ -60,7 +60,7 @@ As built in M0:
|
|||
- Request: `{"id": <number|string>, "method": "<name>", "params": {...}}`. Response: `{"id": ..., "result": ...}` or `{"id": ..., "error": {"code": "...", "message": "..."}}`. A line that is not valid JSON gets an error response with `"id": null`.
|
||||
- Methods (M0): `app.ping`, `engine.execute {command, params}`, `engine.listCommands`, `ui.screenshot {path}`.
|
||||
- `lutra_control` defines a `Backend` trait; the desktop app implements it (engine access, effects, screenshots), tests implement it with a bare engine. One thread accepts connections and each connection gets its own thread; no async runtime is needed in the crate.
|
||||
- Screenshots: the desktop captures its own main window with `xcap` and writes a PNG.
|
||||
- Screenshots: `xcap` does not enumerate windows of its own process (querying their titles can deadlock), so the desktop focuses its main window, reads the client area's physical position and size from Tauri and captures that region of the monitor with `xcap::Monitor::capture_region`. Windows covering Lutra at that moment appear in the image. A webview-native capture (WebView2 `CapturePreview`, WKWebView snapshots) can replace it later.
|
||||
|
||||
## Frontend ↔ engine
|
||||
|
||||
|
|
@ -78,11 +78,13 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus
|
|||
| Text buffer | `ropey` (MIT) in `crates/text`. | Mature rope with line and UTF-16 helpers. |
|
||||
| Clippy panic lints | `unwrap_used`, `expect_used`, `panic`, `unreachable`, `todo`, `unimplemented`, `indexing_slicing`, `string_slice` are denied workspace-wide; `clippy.toml` allows them in `#[test]`/`#[cfg(test)]`; integration tests in `tests/` and `testkit` allow them at crate level. `missing_docs` is denied too, to back the doc-comment code style. `unsafe_code` is denied; a crate that needs it allows it locally with a doc comment saying why. | AGENTS.md › Never crash. |
|
||||
| Desktop dev mode | Plain `cargo build`/`cargo run -p lutra-desktop` is a Tauri dev build that loads the Vite dev server. `cargo xtask dev [-- ARGS]` starts both. A self-contained build embeds `ui/dist` through the `bundled-ui` feature. | Keeps `cargo build --workspace` independent of the frontend build. |
|
||||
| App identifier | `dev.lutra.desktop` is a placeholder. The final reverse-DNS identifier depends on the project's domain and hosting, which are the owner's decision (execution plan §4); bundling stays off until then. | Tauri requires an identifier to build. |
|
||||
| App icon | A placeholder (rounded otter-brown square with a pale stone) is generated by `apps/lutra-desktop/build.rs` into the gitignored `apps/lutra-desktop/icons/`. | The real icon is the owner's to commission; ASSETS.md allows generated-in-code art. |
|
||||
|
||||
## Revision history
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-14 | minor | Screenshot method, placeholder app identifier |
|
||||
| 2026-10-13 | major | M0: layers metadata, command and guard design, control protocol, open questions decided |
|
||||
| 2026-10-13 | major | Initial draft |
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
|
||||
```sh
|
||||
cargo xtask dev # run the app in development mode
|
||||
cargo xtask dev -- --control 7979 . # with the JSON control channel
|
||||
cargo xtask ci # the full quality gate, run before every commit
|
||||
cargo xtask fixtures # create Symfony and Laravel reference projects in target/fixtures/
|
||||
```
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue