//! 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); } }