use crate::Harness;
use image::ImageError;
use std::fmt::Display;
use std::io::ErrorKind;
use std::path::PathBuf;
pub type SnapshotResult = Result<(), SnapshotError>;
#[non_exhaustive]
pub struct SnapshotOptions {
pub threshold: f32,
pub failed_pixel_count_threshold: usize,
pub output_path: PathBuf,
}
#[derive(Debug, Clone, Copy)]
pub struct OsThreshold<T> {
pub windows: T,
pub macos: T,
pub linux: T,
pub fallback: T,
}
impl From<usize> for OsThreshold<usize> {
fn from(value: usize) -> Self {
Self::new(value)
}
}
impl<T> OsThreshold<T>
where
T: Copy,
{
pub fn new(same: T) -> Self {
Self {
windows: same,
macos: same,
linux: same,
fallback: same,
}
}
#[inline]
pub fn windows(mut self, threshold: T) -> Self {
self.windows = threshold;
self
}
#[inline]
pub fn macos(mut self, threshold: T) -> Self {
self.macos = threshold;
self
}
#[inline]
pub fn linux(mut self, threshold: T) -> Self {
self.linux = threshold;
self
}
pub fn threshold(&self) -> T {
if cfg!(target_os = "windows") {
self.windows
} else if cfg!(target_os = "macos") {
self.macos
} else if cfg!(target_os = "linux") {
self.linux
} else {
self.fallback
}
}
}
impl From<OsThreshold<Self>> for usize {
fn from(threshold: OsThreshold<Self>) -> Self {
threshold.threshold()
}
}
impl From<OsThreshold<Self>> for f32 {
fn from(threshold: OsThreshold<Self>) -> Self {
threshold.threshold()
}
}
impl Default for SnapshotOptions {
fn default() -> Self {
Self {
threshold: 0.6,
output_path: PathBuf::from("tests/snapshots"),
failed_pixel_count_threshold: 0, }
}
}
impl SnapshotOptions {
pub fn new() -> Self {
Default::default()
}
#[inline]
pub fn threshold(mut self, threshold: impl Into<f32>) -> Self {
self.threshold = threshold.into();
self
}
#[inline]
pub fn output_path(mut self, output_path: impl Into<PathBuf>) -> Self {
self.output_path = output_path.into();
self
}
#[inline]
pub fn failed_pixel_count_threshold(
mut self,
failed_pixel_count_threshold: impl Into<OsThreshold<usize>>,
) -> Self {
let failed_pixel_count_threshold = failed_pixel_count_threshold.into().threshold();
self.failed_pixel_count_threshold = failed_pixel_count_threshold;
self
}
}
#[derive(Debug)]
pub enum SnapshotError {
Diff {
name: String,
diff: i32,
diff_path: PathBuf,
},
OpenSnapshot {
path: PathBuf,
err: ImageError,
},
SizeMismatch {
name: String,
expected: (u32, u32),
actual: (u32, u32),
},
WriteSnapshot {
path: PathBuf,
err: ImageError,
},
RenderError {
err: String,
},
}
const HOW_TO_UPDATE_SCREENSHOTS: &str =
"Run `UPDATE_SNAPSHOTS=1 cargo test --all-features` to update the snapshots.";
impl Display for SnapshotError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Diff {
name,
diff,
diff_path,
} => {
let diff_path = std::path::absolute(diff_path).unwrap_or(diff_path.clone());
write!(
f,
"'{name}' Image did not match snapshot. Diff: {diff}, {diff_path:?}. {HOW_TO_UPDATE_SCREENSHOTS}"
)
}
Self::OpenSnapshot { path, err } => {
let path = std::path::absolute(path).unwrap_or(path.clone());
match err {
ImageError::IoError(io) => match io.kind() {
ErrorKind::NotFound => {
write!(f, "Missing snapshot: {path:?}. {HOW_TO_UPDATE_SCREENSHOTS}")
}
err => {
write!(
f,
"Error reading snapshot: {err:?}\nAt: {path:?}. {HOW_TO_UPDATE_SCREENSHOTS}"
)
}
},
err => {
write!(
f,
"Error decoding snapshot: {err:?}\nAt: {path:?}. Make sure git-lfs is setup correctly. Read the instructions here: https://github.com/emilk/egui/blob/main/CONTRIBUTING.md#making-a-pr"
)
}
}
}
Self::SizeMismatch {
name,
expected,
actual,
} => {
write!(
f,
"'{name}' Image size did not match snapshot. Expected: {expected:?}, Actual: {actual:?}. {HOW_TO_UPDATE_SCREENSHOTS}"
)
}
Self::WriteSnapshot { path, err } => {
let path = std::path::absolute(path).unwrap_or(path.clone());
write!(f, "Error writing snapshot: {err:?}\nAt: {path:?}")
}
Self::RenderError { err } => {
write!(f, "Error rendering image: {err:?}")
}
}
}
}
fn should_update_snapshots() -> bool {
match std::env::var("UPDATE_SNAPSHOTS") {
Ok(value) => !matches!(value.as_str(), "false" | "0" | "no" | "off"),
Err(_) => false,
}
}
pub fn try_image_snapshot_options(
new: &image::RgbaImage,
name: impl Into<String>,
options: &SnapshotOptions,
) -> SnapshotResult {
try_image_snapshot_options_impl(new, name.into(), options)
}
fn try_image_snapshot_options_impl(
new: &image::RgbaImage,
name: String,
options: &SnapshotOptions,
) -> SnapshotResult {
let SnapshotOptions {
threshold,
output_path,
failed_pixel_count_threshold,
} = options;
let parent_path = if let Some(parent) = PathBuf::from(&name).parent() {
output_path.join(parent)
} else {
output_path.clone()
};
std::fs::create_dir_all(parent_path).ok();
let snapshot_path = output_path.join(format!("{name}.png"));
let diff_path = output_path.join(format!("{name}.diff.png"));
let old_backup_path = output_path.join(format!("{name}.old.png"));
let new_path = output_path.join(format!("{name}.new.png"));
std::fs::remove_file(&diff_path).ok();
std::fs::remove_file(&old_backup_path).ok();
std::fs::remove_file(&new_path).ok();
let update_snapshot = || {
std::fs::rename(&snapshot_path, &old_backup_path).ok();
new.save(&snapshot_path)
.map_err(|err| SnapshotError::WriteSnapshot {
err,
path: snapshot_path.clone(),
})?;
std::fs::remove_file(&new_path).ok();
println!("Updated snapshot: {snapshot_path:?}");
Ok(())
};
new.save(&new_path)
.map_err(|err| SnapshotError::WriteSnapshot {
err,
path: new_path.clone(),
})?;
let previous = match image::open(&snapshot_path) {
Ok(image) => image.to_rgba8(),
Err(err) => {
if should_update_snapshots() {
return update_snapshot();
} else {
return Err(SnapshotError::OpenSnapshot {
path: snapshot_path.clone(),
err,
});
}
}
};
if previous.dimensions() != new.dimensions() {
if should_update_snapshots() {
return update_snapshot();
} else {
return Err(SnapshotError::SizeMismatch {
name,
expected: previous.dimensions(),
actual: new.dimensions(),
});
}
}
let result =
dify::diff::get_results(previous, new.clone(), *threshold, true, None, &None, &None);
if let Some((num_wrong_pixels, result_image)) = result {
result_image
.save(diff_path.clone())
.map_err(|err| SnapshotError::WriteSnapshot {
path: diff_path.clone(),
err,
})?;
if num_wrong_pixels as i64 <= *failed_pixel_count_threshold as i64 {
return Ok(());
}
if should_update_snapshots() {
update_snapshot()
} else {
Err(SnapshotError::Diff {
name,
diff: num_wrong_pixels,
diff_path,
})
}
} else {
Ok(())
}
}
pub fn try_image_snapshot(current: &image::RgbaImage, name: impl Into<String>) -> SnapshotResult {
try_image_snapshot_options(current, name, &SnapshotOptions::default())
}
#[track_caller]
pub fn image_snapshot_options(
current: &image::RgbaImage,
name: impl Into<String>,
options: &SnapshotOptions,
) {
match try_image_snapshot_options(current, name, options) {
Ok(_) => {}
Err(err) => {
panic!("{}", err);
}
}
}
#[track_caller]
pub fn image_snapshot(current: &image::RgbaImage, name: impl Into<String>) {
match try_image_snapshot(current, name) {
Ok(_) => {}
Err(err) => {
panic!("{}", err);
}
}
}
#[cfg(feature = "wgpu")]
impl<State> Harness<'_, State> {
pub fn try_snapshot_options(
&mut self,
name: impl Into<String>,
options: &SnapshotOptions,
) -> SnapshotResult {
let image = self
.render()
.map_err(|err| SnapshotError::RenderError { err })?;
try_image_snapshot_options(&image, name.into(), options)
}
pub fn try_snapshot(&mut self, name: impl Into<String>) -> SnapshotResult {
let image = self
.render()
.map_err(|err| SnapshotError::RenderError { err })?;
try_image_snapshot(&image, name)
}
#[track_caller]
pub fn snapshot_options(&mut self, name: impl Into<String>, options: &SnapshotOptions) {
match self.try_snapshot_options(name, options) {
Ok(_) => {}
Err(err) => {
panic!("{}", err);
}
}
}
#[track_caller]
pub fn snapshot(&mut self, name: impl Into<String>) {
match self.try_snapshot(name) {
Ok(_) => {}
Err(err) => {
panic!("{}", err);
}
}
}
}
#[expect(clippy::missing_errors_doc)]
#[cfg(feature = "wgpu")]
impl<State> Harness<'_, State> {
#[deprecated(
since = "0.31.0",
note = "Use `try_snapshot_options` instead. This function will be removed in 0.32"
)]
pub fn try_wgpu_snapshot_options(
&mut self,
name: impl Into<String>,
options: &SnapshotOptions,
) -> SnapshotResult {
self.try_snapshot_options(name, options)
}
#[deprecated(
since = "0.31.0",
note = "Use `try_snapshot` instead. This function will be removed in 0.32"
)]
pub fn try_wgpu_snapshot(&mut self, name: impl Into<String>) -> SnapshotResult {
self.try_snapshot(name)
}
#[deprecated(
since = "0.31.0",
note = "Use `snapshot_options` instead. This function will be removed in 0.32"
)]
pub fn wgpu_snapshot_options(&mut self, name: impl Into<String>, options: &SnapshotOptions) {
self.snapshot_options(name, options);
}
#[deprecated(
since = "0.31.0",
note = "Use `snapshot` instead. This function will be removed in 0.32"
)]
pub fn wgpu_snapshot(&mut self, name: &str) {
self.snapshot(name);
}
}
#[derive(Debug, Default)]
pub struct SnapshotResults {
errors: Vec<SnapshotError>,
}
impl Display for SnapshotResults {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.errors.is_empty() {
write!(f, "All snapshots passed")
} else {
writeln!(f, "Snapshot errors:")?;
for error in &self.errors {
writeln!(f, " {error}")?;
}
Ok(())
}
}
}
impl SnapshotResults {
pub fn new() -> Self {
Default::default()
}
pub fn add(&mut self, result: SnapshotResult) {
if let Err(err) = result {
self.errors.push(err);
}
}
pub fn has_errors(&self) -> bool {
!self.errors.is_empty()
}
#[expect(clippy::missing_errors_doc)]
pub fn into_result(self) -> Result<(), Self> {
if self.has_errors() { Err(self) } else { Ok(()) }
}
pub fn into_inner(mut self) -> Vec<SnapshotError> {
std::mem::take(&mut self.errors)
}
#[expect(clippy::unused_self)]
#[track_caller]
pub fn unwrap(self) {
}
}
impl From<SnapshotResults> for Vec<SnapshotError> {
fn from(results: SnapshotResults) -> Self {
results.into_inner()
}
}
impl Drop for SnapshotResults {
#[track_caller]
fn drop(&mut self) {
if std::thread::panicking() {
return;
}
#[expect(clippy::manual_assert)]
if self.has_errors() {
panic!("{}", self);
}
}
}