use std::path::Path;
use std::time::Duration;
pub(crate) fn should_capture(painted: u64, settle_frames: u32) -> bool {
painted == settle_frames.max(1) as u64
}
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(15);
pub(crate) fn capture_exhausted(since_last_paint: Duration) -> bool {
since_last_paint >= CAPTURE_TIMEOUT
}
pub(crate) fn write_png(path: &Path, rgba: &[u8], width: u32, height: u32) -> Result<(), String> {
if rgba.is_empty() || width == 0 || height == 0 {
return Err("frame read-back returned no pixels".to_string());
}
let png = agg_gui::screenshot::encode_png_rgba(rgba, width, height)
.map_err(|e| format!("PNG encode failed: {e}"))?;
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("could not create {}: {e}", parent.display()))?;
}
}
std::fs::write(path, &png).map_err(|e| format!("could not write {}: {e}", path.display()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captures_exactly_on_the_settle_frame() {
assert!(!should_capture(1, 3));
assert!(!should_capture(2, 3));
assert!(should_capture(3, 3));
assert!(!should_capture(4, 3));
}
#[test]
fn settle_frames_zero_captures_the_first_frame() {
assert!(should_capture(1, 0));
assert!(!should_capture(2, 0));
}
#[test]
fn a_pending_capture_gives_up_after_the_wall_clock_timeout() {
assert!(!capture_exhausted(Duration::ZERO));
assert!(!capture_exhausted(
CAPTURE_TIMEOUT - Duration::from_millis(1)
));
assert!(capture_exhausted(CAPTURE_TIMEOUT));
assert!(capture_exhausted(CAPTURE_TIMEOUT + Duration::from_secs(60)));
}
#[test]
fn a_burst_of_attempts_in_a_few_milliseconds_is_not_exhaustion() {
for ms in [0_u64, 1, 5, 50, 500] {
assert!(
!capture_exhausted(Duration::from_millis(ms)),
"{ms} ms of polling must not end a pending capture"
);
}
}
#[test]
fn empty_readback_is_an_error() {
let dir = std::env::temp_dir().join("agg-gui-shell-screenshot-test");
let path = dir.join("empty.png");
let err = write_png(&path, &[], 0, 0).unwrap_err();
assert!(err.contains("no pixels"), "unexpected message: {err}");
assert!(!path.exists());
}
#[test]
fn writes_a_png_and_creates_the_parent_directory() {
let dir = std::env::temp_dir()
.join("agg-gui-shell-screenshot-test")
.join("nested");
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("shot.png");
write_png(&path, &[255, 0, 0, 255, 0, 255, 0, 255], 2, 1).expect("write png");
let bytes = std::fs::read(&path).expect("read back png");
assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
let _ = std::fs::remove_dir_all(&dir);
}
}