Lutra/apps/lutra-desktop/src/screenshot.rs
danny f49b42836a F2: ui.screenshot captures the webview without focusing the window
On Windows the webview renders itself into a PNG through WebView2
CapturePreview (scheduled on the main thread via with_webview, 10 s
timeout, PNG signature and 64 MiB cap checked). macOS and Linux keep the
xcap screen-region capture as a documented fallback, now without focusing.
app.focus is the only control method that changes focus. A --control
instance opens its window without taking the foreground. An ignored live
test samples the foreground window while the app starts and takes five
screenshots and fails if Lutra ever owns it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:13:38 +01:00

89 lines
3.3 KiB
Rust

//! Screenshots of Lutra's main window for `ui.screenshot`.
//!
//! A screenshot never focuses, raises or shows the window: `app.focus` is the
//! only control method that does. Taking one while the user types into
//! another app must not pull their keystrokes into Lutra.
//!
//! - Windows: the webview renders itself into a PNG through WebView2's
//! `CapturePreview` ([`webview2`]). The image is the page as the webview
//! draws it, whether or not other windows cover Lutra; the native title bar
//! is not part of it.
//! - Other platforms (fallback): the window's client area is located in
//! physical pixels through Tauri and that region of its monitor is captured
//! with `xcap` ([`region`]). Windows covering Lutra at that moment appear in
//! the image. WKWebView's and WebKitGTK's own snapshot APIs can replace it.
use std::path::Path;
use std::time::Duration;
use tauri::{AppHandle, Manager};
#[cfg(not(windows))]
mod region;
#[cfg(windows)]
mod webview2;
/// The eight bytes every PNG file starts with.
const PNG_SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n'];
/// Largest PNG accepted from the platform capture.
const MAX_PNG_BYTES: usize = 64 * 1024 * 1024;
/// How long to wait for the platform capture before giving up.
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(10);
/// Captures the window labelled `label` and writes it to `path` as PNG,
/// without changing which window is in front or has the keyboard focus.
/// Must not be called on the main thread: the capture is scheduled there and
/// this function waits for it.
///
/// # Errors
/// A message if the window does not exist or is minimised, the capture fails
/// or times out, the result is not a PNG, or the file 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());
}
#[cfg(windows)]
let png = webview2::capture_png(&window)?;
#[cfg(not(windows))]
let png = region::capture_png(&window)?;
check_png(&png)?;
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()))?;
}
std::fs::write(path, png).map_err(|e| format!("{}: {e}", path.display()))
}
/// Checks that `bytes` start with the PNG signature and stay within
/// [`MAX_PNG_BYTES`].
///
/// # Errors
/// A message naming what is wrong.
fn check_png(bytes: &[u8]) -> Result<(), String> {
if bytes.len() > MAX_PNG_BYTES {
return Err(format!("the capture is larger than {MAX_PNG_BYTES} bytes"));
}
if !bytes.starts_with(&PNG_SIGNATURE) {
return Err("the capture is not a PNG image".into());
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_png_and_rejects_the_rest() {
let mut png = PNG_SIGNATURE.to_vec();
png.extend_from_slice(b"rest");
assert!(check_png(&png).is_ok());
assert!(check_png(b"GIF89a").is_err());
assert!(check_png(&[]).is_err());
assert!(check_png(&vec![0; MAX_PNG_BYTES + 1]).is_err());
}
}