use std::collections::BTreeMap;
use std::io::Cursor;
use icedwright_types::units::{Physical, ScaleFactor};
use icedwright_types::{Frame, Size};
use super::SnapshotError;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[must_use]
pub struct PngMetadata {
entries: BTreeMap<String, String>,
}
impl PngMetadata {
pub const VERSION: &'static str = "icedwright-version";
pub const RENDERER: &'static str = "renderer";
pub const THEME: &'static str = "theme";
pub const LOGICAL_SIZE: &'static str = "logical-size";
pub const SCALE: &'static str = "scale-factor";
pub const FONTS: &'static str = "fonts";
pub const FONT_SOURCE: &'static str = "font-source";
pub const VARIANT: &'static str = "variant";
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.entries.insert(key.into(), value.into());
self
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&str> {
self.entries.get(key).map(String::as_str)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.entries.iter().map(|(k, v)| (k.as_str(), v.as_str()))
}
}
fn encode_error(error: impl std::fmt::Display) -> SnapshotError {
SnapshotError::Png {
action: "encoded",
message: error.to_string(),
}
}
fn decode_error(error: impl std::fmt::Display) -> SnapshotError {
SnapshotError::Png {
action: "decoded",
message: error.to_string(),
}
}
pub fn encode_png(frame: &Frame, metadata: &PngMetadata) -> Result<Vec<u8>, SnapshotError> {
let size = frame.size().get();
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, size.width, size.height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let metadata = metadata
.clone()
.with(PngMetadata::SCALE, frame.scale().get().to_string());
for (key, value) in metadata.iter() {
encoder
.add_text_chunk(key.to_owned(), value.to_owned())
.map_err(encode_error)?;
}
let mut writer = encoder.write_header().map_err(encode_error)?;
writer
.write_image_data(frame.rgba())
.map_err(encode_error)?;
writer.finish().map_err(encode_error)?;
Ok(out)
}
pub fn decode_png(bytes: &[u8]) -> Result<(Frame, PngMetadata), SnapshotError> {
let mut decoder = png::Decoder::new(Cursor::new(bytes));
decoder.set_transformations(png::Transformations::normalize_to_color8());
let mut reader = decoder.read_info().map_err(decode_error)?;
let metadata = reader
.info()
.uncompressed_latin1_text
.iter()
.fold(PngMetadata::new(), |metadata, chunk| {
metadata.with(chunk.keyword.clone(), chunk.text.clone())
});
let length = reader
.output_buffer_size()
.ok_or_else(|| decode_error("the image is too large"))?;
let mut buffer = vec![0; length];
let info = reader.next_frame(&mut buffer).map_err(decode_error)?;
buffer.truncate(info.buffer_size());
let rgba = match info.color_type {
png::ColorType::Rgba => buffer,
png::ColorType::Rgb => buffer
.as_chunks::<3>()
.0
.iter()
.flat_map(|[r, g, b]| [*r, *g, *b, 255])
.collect(),
png::ColorType::GrayscaleAlpha => buffer
.as_chunks::<2>()
.0
.iter()
.flat_map(|[g, a]| [*g, *g, *g, *a])
.collect(),
png::ColorType::Grayscale => buffer.iter().flat_map(|g| [*g, *g, *g, 255]).collect(),
png::ColorType::Indexed => {
return Err(decode_error("an indexed image was not expanded"));
}
};
let scale = metadata
.get(PngMetadata::SCALE)
.and_then(|value| value.parse::<f32>().ok())
.map_or(Ok(ScaleFactor::ONE), ScaleFactor::new)
.map_err(decode_error)?;
let frame = Frame::new(
rgba,
Physical::new(Size::new(info.width, info.height)),
scale,
)
.map_err(decode_error)?;
Ok((frame, metadata))
}