use std::path::{Path, PathBuf};
use crate::e2e::{CaptureImage, Locator};
use native_gui_core::error::{GuiError, GuiResult};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Rect {
pub x: u32,
pub y: u32,
pub width: u32,
pub height: u32,
}
impl Rect {
pub const fn new(x: u32, y: u32, width: u32, height: u32) -> Self {
Self {
x,
y,
width,
height,
}
}
pub fn contains(&self, px: u32, py: u32) -> bool {
px >= self.x
&& px < self.x.saturating_add(self.width)
&& py >= self.y
&& py < self.y.saturating_add(self.height)
}
pub fn union(&self, other: &Rect) -> Rect {
if self.width == 0 || self.height == 0 {
return *other;
}
if other.width == 0 || other.height == 0 {
return *self;
}
let min_x = self.x.min(other.x);
let min_y = self.y.min(other.y);
let max_x = (self.x + self.width).max(other.x + other.width);
let max_y = (self.y + self.height).max(other.y + other.height);
Rect {
x: min_x,
y: min_y,
width: max_x - min_x,
height: max_y - min_y,
}
}
pub fn area(&self) -> usize {
(self.width as usize) * (self.height as usize)
}
}
#[derive(Debug, Clone)]
pub enum MaskRegion {
Rect(Rect),
Element(Locator),
}
impl From<Rect> for MaskRegion {
fn from(rect: Rect) -> Self {
MaskRegion::Rect(rect)
}
}
impl From<(u32, u32, u32, u32)> for MaskRegion {
fn from((x, y, width, height): (u32, u32, u32, u32)) -> Self {
MaskRegion::Rect(Rect::new(x, y, width, height))
}
}
impl From<Locator> for MaskRegion {
fn from(locator: Locator) -> Self {
MaskRegion::Element(locator)
}
}
#[derive(Debug, Clone)]
pub struct ImageDiffOptions {
pub tolerance: u8,
pub max_mismatch_percent: f64,
pub masks: Vec<MaskRegion>,
pub diff_output_dir: Option<PathBuf>,
}
impl Default for ImageDiffOptions {
fn default() -> Self {
Self {
tolerance: 0,
max_mismatch_percent: 0.0,
masks: Vec::new(),
diff_output_dir: None,
}
}
}
impl ImageDiffOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_tolerance(mut self, tolerance: u8) -> Self {
self.tolerance = tolerance;
self
}
pub fn with_max_mismatch_percent(mut self, percent: f64) -> Self {
self.max_mismatch_percent = percent.clamp(0.0, 100.0);
self
}
pub fn with_mask(mut self, mask: impl Into<MaskRegion>) -> Self {
self.masks.push(mask.into());
self
}
pub fn with_mask_rect(self, x: u32, y: u32, width: u32, height: u32) -> Self {
self.with_mask(Rect::new(x, y, width, height))
}
pub fn with_mask_element(self, locator: Locator) -> Self {
self.with_mask(MaskRegion::Element(locator))
}
pub fn with_diff_output_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.diff_output_dir = Some(dir.into());
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ImageDiffResult {
pub passed: bool,
pub mismatch_percentage: f64,
pub mismatched_pixels: usize,
pub total_pixels: usize,
pub diff_bounds: Option<Rect>,
pub diff_image: Option<CaptureImage>,
}
impl ImageDiffResult {
pub fn is_match(&self) -> bool {
self.passed
}
pub fn passed(&self) -> bool {
self.passed
}
pub fn mismatched_pixels(&self) -> usize {
self.mismatched_pixels
}
pub fn mismatch_percentage(&self) -> f64 {
self.mismatch_percentage
}
pub fn diff_bounds(&self) -> Option<Rect> {
self.diff_bounds
}
pub fn diff_image(&self) -> Option<&CaptureImage> {
self.diff_image.as_ref()
}
pub fn save_diff_image(&self, path: impl AsRef<Path>) -> GuiResult<()> {
let diff_img = self.diff_image.as_ref().ok_or_else(|| {
GuiError::Backend("e2e.visual: no diff image available to save".to_owned())
})?;
diff_img.save_png(path)
}
}
pub fn compare_images(
actual: &CaptureImage,
expected: &CaptureImage,
options: &ImageDiffOptions,
resolved_masks: &[Rect],
) -> GuiResult<ImageDiffResult> {
if actual.width != expected.width || actual.height != expected.height {
let max_w = actual.width.max(expected.width);
let max_h = actual.height.max(expected.height);
let total = (max_w as usize) * (max_h as usize);
return Ok(ImageDiffResult {
passed: false,
mismatch_percentage: 100.0,
mismatched_pixels: total,
total_pixels: total,
diff_bounds: Some(Rect::new(0, 0, max_w, max_h)),
diff_image: None,
});
}
let width = actual.width;
let height = actual.height;
let total_pixels_in_image = (width as usize) * (height as usize);
let mut mismatched_pixels = 0usize;
let mut total_evaluated = 0usize;
let mut min_diff_x = u32::MAX;
let mut min_diff_y = u32::MAX;
let mut max_diff_x = 0u32;
let mut max_diff_y = 0u32;
let mut diff_buffer = vec![0u8; total_pixels_in_image * 4];
for y in 0..height {
for x in 0..width {
let pixel_idx = ((y * width + x) * 4) as usize;
let is_masked = resolved_masks.iter().any(|mask| mask.contains(x, y));
if is_masked {
diff_buffer[pixel_idx] = 60;
diff_buffer[pixel_idx + 1] = 64;
diff_buffer[pixel_idx + 2] = 75;
diff_buffer[pixel_idx + 3] = 255;
continue;
}
total_evaluated += 1;
let act_r = actual.data[pixel_idx];
let act_g = actual.data[pixel_idx + 1];
let act_b = actual.data[pixel_idx + 2];
let act_a = actual.data[pixel_idx + 3];
let exp_r = expected.data[pixel_idx];
let exp_g = expected.data[pixel_idx + 1];
let exp_b = expected.data[pixel_idx + 2];
let exp_a = expected.data[pixel_idx + 3];
let dr = act_r.abs_diff(exp_r);
let dg = act_g.abs_diff(exp_g);
let db = act_b.abs_diff(exp_b);
let da = act_a.abs_diff(exp_a);
let is_mismatch = dr > options.tolerance
|| dg > options.tolerance
|| db > options.tolerance
|| da > options.tolerance;
if is_mismatch {
mismatched_pixels += 1;
min_diff_x = min_diff_x.min(x);
min_diff_y = min_diff_y.min(y);
max_diff_x = max_diff_x.max(x);
max_diff_y = max_diff_y.max(y);
diff_buffer[pixel_idx] = 255;
diff_buffer[pixel_idx + 1] = 0;
diff_buffer[pixel_idx + 2] = 128;
diff_buffer[pixel_idx + 3] = 255;
} else {
let fade_r = (exp_r / 3).saturating_add(120);
let fade_g = (exp_g / 3).saturating_add(120);
let fade_b = (exp_b / 3).saturating_add(120);
diff_buffer[pixel_idx] = fade_r;
diff_buffer[pixel_idx + 1] = fade_g;
diff_buffer[pixel_idx + 2] = fade_b;
diff_buffer[pixel_idx + 3] = 255;
}
}
}
let mismatch_percentage = if total_evaluated > 0 {
(mismatched_pixels as f64 / total_evaluated as f64) * 100.0
} else {
0.0
};
let passed = mismatch_percentage <= options.max_mismatch_percent;
let diff_bounds = if mismatched_pixels > 0 && min_diff_x <= max_diff_x {
Some(Rect::new(
min_diff_x,
min_diff_y,
max_diff_x - min_diff_x + 1,
max_diff_y - min_diff_y + 1,
))
} else {
None
};
let diff_image = Some(CaptureImage::new(width, height, diff_buffer));
Ok(ImageDiffResult {
passed,
mismatch_percentage,
mismatched_pixels,
total_pixels: total_evaluated,
diff_bounds,
diff_image,
})
}
const PNG_SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
pub fn decode_png_rgba(bytes: &[u8]) -> GuiResult<CaptureImage> {
if bytes.len() < 8 || bytes[0..8] != PNG_SIGNATURE {
return Err(GuiError::Backend("e2e.png: invalid PNG signature".into()));
}
let mut pos = 8;
let mut width = 0u32;
let mut height = 0u32;
let mut color_type = 0u8;
let mut idat_data = Vec::new();
while pos + 8 <= bytes.len() {
let chunk_len =
u32::from_be_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
as usize;
let chunk_type = &bytes[pos + 4..pos + 8];
pos += 8;
if pos + chunk_len > bytes.len() {
return Err(GuiError::Backend(
"e2e.png: unexpected end of chunk data".into(),
));
}
let chunk_payload = &bytes[pos..pos + chunk_len];
pos += chunk_len;
pos += 4;
match chunk_type {
b"IHDR" => {
if chunk_len < 13 {
return Err(GuiError::Backend("e2e.png: malformed IHDR chunk".into()));
}
width = u32::from_be_bytes([
chunk_payload[0],
chunk_payload[1],
chunk_payload[2],
chunk_payload[3],
]);
height = u32::from_be_bytes([
chunk_payload[4],
chunk_payload[5],
chunk_payload[6],
chunk_payload[7],
]);
let bit_depth = chunk_payload[8];
color_type = chunk_payload[9];
let compression = chunk_payload[10];
let filter = chunk_payload[11];
let interlace = chunk_payload[12];
if bit_depth != 8 {
return Err(GuiError::Backend(format!(
"e2e.png: unsupported bit depth {bit_depth}"
)));
}
if color_type != 6 && color_type != 2 {
return Err(GuiError::Backend(format!("e2e.png: unsupported color type {color_type} (only RGB and RGBA supported)")));
}
if compression != 0 || filter != 0 {
return Err(GuiError::Backend(
"e2e.png: unknown compression or filter method".into(),
));
}
if interlace != 0 {
return Err(GuiError::Backend(
"e2e.png: interlacing is not supported".into(),
));
}
}
b"IDAT" => {
idat_data.extend_from_slice(chunk_payload);
}
b"IEND" => break,
_ => {
}
}
}
if width == 0 || height == 0 {
return Err(GuiError::Backend(
"e2e.png: missing or zero dimensions in IHDR".into(),
));
}
if idat_data.is_empty() {
return Err(GuiError::Backend("e2e.png: missing IDAT image data".into()));
}
let decompressed = inflate_zlib(&idat_data)?;
let bpp = if color_type == 6 { 4usize } else { 3usize };
let stride = (width as usize) * bpp;
let expected_len = (height as usize) * (1 + stride);
if decompressed.len() < expected_len {
return Err(GuiError::Backend(format!(
"e2e.png: decompressed length {} is smaller than required scanline buffer {}",
decompressed.len(),
expected_len
)));
}
let mut rgba_out = Vec::with_capacity((width as usize) * (height as usize) * 4);
let mut prior_row = vec![0u8; stride];
let mut current_row = vec![0u8; stride];
let mut dec_pos = 0;
for _y in 0..height {
let filter_type = decompressed[dec_pos];
dec_pos += 1;
let raw_line = &decompressed[dec_pos..dec_pos + stride];
dec_pos += stride;
for x in 0..stride {
let filt = raw_line[x];
let a = if x >= bpp { current_row[x - bpp] } else { 0 };
let b = prior_row[x];
let c = if x >= bpp { prior_row[x - bpp] } else { 0 };
let recon = match filter_type {
0 => filt,
1 => filt.wrapping_add(a),
2 => filt.wrapping_add(b),
3 => filt.wrapping_add(((a as u16 + b as u16) / 2) as u8),
4 => filt.wrapping_add(paeth_predictor(a, b, c)),
other => {
return Err(GuiError::Backend(format!(
"e2e.png: invalid scanline filter type {other}"
)));
}
};
current_row[x] = recon;
}
if color_type == 6 {
rgba_out.extend_from_slice(¤t_row);
} else {
for px in (0..stride).step_by(3) {
rgba_out.push(current_row[px]);
rgba_out.push(current_row[px + 1]);
rgba_out.push(current_row[px + 2]);
rgba_out.push(255);
}
}
prior_row.copy_from_slice(¤t_row);
}
Ok(CaptureImage::new(width, height, rgba_out))
}
fn paeth_predictor(a: u8, b: u8, c: u8) -> u8 {
let p = a as i32 + b as i32 - c as i32;
let pa = (p - a as i32).abs();
let pb = (p - b as i32).abs();
let pc = (p - c as i32).abs();
if pa <= pb && pa <= pc {
a
} else if pb <= pc {
b
} else {
c
}
}
fn inflate_zlib(data: &[u8]) -> GuiResult<Vec<u8>> {
if data.len() < 6 {
return Err(GuiError::Backend(
"e2e.deflate: zlib stream too short".into(),
));
}
let cmf = data[0];
let flg = data[1];
let check = ((cmf as u16) << 8) | (flg as u16);
if !check.is_multiple_of(31) {
return Err(GuiError::Backend(
"e2e.deflate: zlib header checksum failed".into(),
));
}
let cm = cmf & 0x0F;
if cm != 8 {
return Err(GuiError::Backend(format!(
"e2e.deflate: unsupported compression method {cm}"
)));
}
let fdict = (flg & 0x20) != 0;
let offset = if fdict { 6 } else { 2 };
if data.len() < offset + 4 {
return Err(GuiError::Backend(
"e2e.deflate: truncated zlib payload".into(),
));
}
let payload = &data[offset..data.len() - 4];
inflate_raw(payload)
}
struct BitReader<'a> {
bytes: &'a [u8],
pos: usize,
bits: u32,
num_bits: u8,
}
impl<'a> BitReader<'a> {
fn new(bytes: &'a [u8]) -> Self {
Self {
bytes,
pos: 0,
bits: 0,
num_bits: 0,
}
}
fn ensure_bits(&mut self, n: u8) {
while self.num_bits < n && self.pos < self.bytes.len() {
self.bits |= (self.bytes[self.pos] as u32) << self.num_bits;
self.num_bits += 8;
self.pos += 1;
}
}
fn read_bits(&mut self, n: u8) -> u32 {
if n == 0 {
return 0;
}
self.ensure_bits(n);
let mask = (1u32 << n) - 1;
let val = self.bits & mask;
self.bits >>= n;
self.num_bits = self.num_bits.saturating_sub(n);
val
}
fn align_byte(&mut self) {
let discard = self.num_bits % 8;
self.bits >>= discard;
self.num_bits -= discard;
self.bits = 0;
self.num_bits = 0;
}
fn read_u16_le(&mut self) -> GuiResult<u16> {
self.align_byte();
if self.pos + 2 > self.bytes.len() {
return Err(GuiError::Backend(
"e2e.deflate: unexpected end of stream reading u16".into(),
));
}
let val = u16::from_le_bytes([self.bytes[self.pos], self.bytes[self.pos + 1]]);
self.pos += 2;
Ok(val)
}
fn read_bytes(&mut self, len: usize) -> GuiResult<&'a [u8]> {
self.align_byte();
if self.pos + len > self.bytes.len() {
return Err(GuiError::Backend(
"e2e.deflate: unexpected end of stream reading bytes".into(),
));
}
let slice = &self.bytes[self.pos..self.pos + len];
self.pos += len;
Ok(slice)
}
}
fn inflate_raw(data: &[u8]) -> GuiResult<Vec<u8>> {
let mut reader = BitReader::new(data);
let mut out = Vec::new();
loop {
let bfinal = reader.read_bits(1);
let btype = reader.read_bits(2);
match btype {
0 => {
let len = reader.read_u16_le()? as usize;
let nlen = reader.read_u16_le()? as usize;
if (len ^ 0xFFFF) != nlen {
return Err(GuiError::Backend(
"e2e.deflate: invalid stored block length check".into(),
));
}
let bytes = reader.read_bytes(len)?;
out.extend_from_slice(bytes);
}
1 => {
inflate_fixed_huffman(&mut reader, &mut out)?;
}
2 => {
inflate_dynamic_huffman(&mut reader, &mut out)?;
}
_ => {
return Err(GuiError::Backend(
"e2e.deflate: reserved block type 3".into(),
));
}
}
if bfinal != 0 {
break;
}
}
Ok(out)
}
fn inflate_fixed_huffman(reader: &mut BitReader, out: &mut Vec<u8>) -> GuiResult<()> {
loop {
let code = decode_fixed_lit_len(reader);
match code {
0..=255 => out.push(code as u8),
256 => break, 257..=285 => {
let length = decode_length(code, reader)?;
let dist_code = reader.read_bits(5) as u16;
let distance = decode_distance(dist_code, reader)?;
copy_match(out, length, distance)?;
}
_ => {
return Err(GuiError::Backend(
"e2e.deflate: invalid literal/length code in fixed Huffman".into(),
))
}
}
}
Ok(())
}
fn decode_fixed_lit_len(reader: &mut BitReader) -> u16 {
reader.ensure_bits(9);
let bits7 = reverse_bits(reader.bits & 0x7F, 7);
if bits7 <= 0x17 {
reader.read_bits(7);
return 256 + bits7;
}
let bits8 = reverse_bits(reader.bits & 0xFF, 8);
if bits8 <= 0xBF {
reader.read_bits(8);
return bits8 - 0x30;
}
if (0xC0..=0xC7).contains(&bits8) {
reader.read_bits(8);
return 280 + (bits8 - 0xC0);
}
let bits9 = reverse_bits(reader.bits & 0x1FF, 9);
reader.read_bits(9);
144 + (bits9 - 0x190)
}
fn reverse_bits(mut val: u32, n: u8) -> u16 {
let mut res = 0;
for _ in 0..n {
res = (res << 1) | (val & 1);
val >>= 1;
}
res as u16
}
fn decode_length(code: u16, reader: &mut BitReader) -> GuiResult<usize> {
const LENGTH_BASE: [u16; 29] = [
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115,
131, 163, 195, 227, 258,
];
const EXTRA_BITS: [u8; 29] = [
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
];
let idx = (code - 257) as usize;
if idx >= 29 {
return Err(GuiError::Backend("e2e.deflate: invalid length code".into()));
}
let extra = reader.read_bits(EXTRA_BITS[idx]) as usize;
Ok(LENGTH_BASE[idx] as usize + extra)
}
fn decode_distance(code: u16, reader: &mut BitReader) -> GuiResult<usize> {
const DIST_BASE: [u16; 30] = [
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
];
const EXTRA_BITS: [u8; 30] = [
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12,
13, 13,
];
let idx = code as usize;
if idx >= 30 {
return Err(GuiError::Backend(
"e2e.deflate: invalid distance code".into(),
));
}
let extra = reader.read_bits(EXTRA_BITS[idx]) as usize;
Ok(DIST_BASE[idx] as usize + extra)
}
fn copy_match(out: &mut Vec<u8>, length: usize, distance: usize) -> GuiResult<()> {
if distance == 0 || distance > out.len() {
return Err(GuiError::Backend(format!(
"e2e.deflate: match distance {distance} exceeds current output length {}",
out.len()
)));
}
let start = out.len() - distance;
for i in 0..length {
let b = out[start + i];
out.push(b);
}
Ok(())
}
fn inflate_dynamic_huffman(reader: &mut BitReader, out: &mut Vec<u8>) -> GuiResult<()> {
let hlit = (reader.read_bits(5) + 257) as usize;
let hdist = (reader.read_bits(5) + 1) as usize;
let hclen = (reader.read_bits(4) + 4) as usize;
const CL_ORDER: [usize; 19] = [
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
];
let mut cl_lengths = [0u8; 19];
for i in 0..hclen {
cl_lengths[CL_ORDER[i]] = reader.read_bits(3) as u8;
}
let cl_tree = HuffmanTable::build(&cl_lengths)?;
let mut lengths = Vec::with_capacity(hlit + hdist);
while lengths.len() < hlit + hdist {
let sym = cl_tree.decode(reader)?;
match sym {
0..=15 => lengths.push(sym as u8),
16 => {
let repeat = (reader.read_bits(2) + 3) as usize;
let last = *lengths.last().ok_or_else(|| {
GuiError::Backend("e2e.deflate: repeat with no prior code".into())
})?;
for _ in 0..repeat {
lengths.push(last);
}
}
17 => {
let repeat = (reader.read_bits(3) + 3) as usize;
lengths.extend(std::iter::repeat_n(0, repeat));
}
18 => {
let repeat = (reader.read_bits(7) + 11) as usize;
lengths.extend(std::iter::repeat_n(0, repeat));
}
_ => {
return Err(GuiError::Backend(
"e2e.deflate: invalid code length symbol".into(),
))
}
}
}
let lit_tree = HuffmanTable::build(&lengths[..hlit])?;
let dist_tree = HuffmanTable::build(&lengths[hlit..])?;
loop {
let sym = lit_tree.decode(reader)?;
match sym {
0..=255 => out.push(sym as u8),
256 => break,
257..=285 => {
let length = decode_length(sym, reader)?;
let dist_code = dist_tree.decode(reader)?;
let distance = decode_distance(dist_code, reader)?;
copy_match(out, length, distance)?;
}
_ => {
return Err(GuiError::Backend(
"e2e.deflate: invalid symbol in dynamic block".into(),
))
}
}
}
Ok(())
}
struct HuffmanTable {
symbols: Vec<u16>,
codes: Vec<u16>,
lengths: Vec<u8>,
}
impl HuffmanTable {
fn build(lengths: &[u8]) -> GuiResult<Self> {
let mut max_len = 0;
for &l in lengths {
if l > max_len {
max_len = l;
}
}
if max_len == 0 {
return Ok(Self {
symbols: Vec::new(),
codes: Vec::new(),
lengths: Vec::new(),
});
}
let mut bl_count = vec![0u16; (max_len + 1) as usize];
for &l in lengths {
if l > 0 {
bl_count[l as usize] += 1;
}
}
let mut next_code = vec![0u16; (max_len + 1) as usize];
let mut code = 0u16;
for bits in 1..=max_len {
code = (code + bl_count[(bits - 1) as usize]) << 1;
next_code[bits as usize] = code;
}
let mut symbols = Vec::new();
let mut codes = Vec::new();
let mut lens = Vec::new();
for (sym, &len) in lengths.iter().enumerate() {
if len > 0 {
let c = next_code[len as usize];
next_code[len as usize] += 1;
symbols.push(sym as u16);
codes.push(c);
lens.push(len);
}
}
Ok(Self {
symbols,
codes,
lengths: lens,
})
}
fn decode(&self, reader: &mut BitReader) -> GuiResult<u16> {
let mut curr_code = 0u16;
for bits in 1..=15 {
let bit = reader.read_bits(1) as u16;
curr_code = (curr_code << 1) | bit;
for (i, &l) in self.lengths.iter().enumerate() {
if l == bits && self.codes[i] == curr_code {
return Ok(self.symbols[i]);
}
}
}
Err(GuiError::Backend(
"e2e.deflate: huffman symbol not found".into(),
))
}
}