use std::fmt;
use f_office_docx::named_edits::ImageFile;
use f_office_paint::ImageFormat;
use f_office_units::scale::{EMUS_PER_INCH, TENTHS_OF_MM_PER_CM, TENTHS_OF_MM_PER_INCH};
use f_office_units::{Length, div_round_i128};
use super::EditLimits;
use f_office_paint::image_header::{DensityUnit, ImageHeader, jpeg_header, png_header};
const PIXELS_PER_INCH: u32 = 96;
const TENTHS_OF_MM_PER_METER: i64 = 10_000;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ImageError {
TooLarge {
limit: usize,
},
Format(ImageFormat),
Header,
Size,
}
impl fmt::Display for ImageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TooLarge { limit } => write!(
f,
"the image file is larger than {limit} bytes: save it smaller"
),
Self::Format(ImageFormat::Unknown) => f.write_str(
"the image file is of no known format by its first bytes, and an image edit takes only PNG and JPEG files: convert it to PNG",
),
Self::Format(format) => write!(
f,
"the image file is a {format} file by its first bytes, and an image edit takes only PNG and JPEG files: convert it to PNG"
),
Self::Header => {
f.write_str("the image file's header does not read: save the image again")
}
Self::Size => f.write_str(
"the image has no pixels, or a size at its resolution that is too large for a file: save it with another size or resolution",
),
}
}
}
impl std::error::Error for ImageError {}
pub fn image_file(data: Vec<u8>, limits: &EditLimits) -> Result<ImageFile, ImageError> {
if data.len() > limits.max_image_bytes {
return Err(ImageError::TooLarge {
limit: limits.max_image_bytes,
});
}
let format = ImageFormat::detect(&data);
let header = match format {
ImageFormat::Png => png_header(&data),
ImageFormat::Jpeg => jpeg_header(&data),
other => return Err(ImageError::Format(other)),
}
.ok_or(ImageError::Header)?;
let size = own_size(&header).ok_or(ImageError::Size)?;
ImageFile::new(format, data, size).ok_or(ImageError::Size)
}
fn own_size(header: &ImageHeader) -> Option<(Length, Length)> {
let (per_x, per_y, unit) =
header
.density
.unwrap_or((PIXELS_PER_INCH, PIXELS_PER_INCH, DensityUnit::Inch));
let unit = i128::from(match unit {
DensityUnit::Inch => TENTHS_OF_MM_PER_INCH,
DensityUnit::Centimeter => TENTHS_OF_MM_PER_CM,
DensityUnit::Meter => TENTHS_OF_MM_PER_METER,
});
let length = |pixels: usize, per_unit: u32| {
let emus = div_round_i128(
i128::try_from(pixels).ok()? * i128::from(EMUS_PER_INCH) * unit,
i128::from(TENTHS_OF_MM_PER_INCH) * i128::from(per_unit),
);
Length::from_emus(i64::try_from(emus).ok()?)
};
Some((
length(header.pixels.0, per_x)?,
length(header.pixels.1, per_y)?,
))
}
#[cfg(test)]
mod tests {
use f_office_paint::ImageFormat;
use f_office_units::Length;
use super::{EditLimits, ImageError, image_file};
fn png(width: u32, height: u32, phys: Option<(u32, u32)>) -> Vec<u8> {
let mut file = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
file.extend_from_slice(&width.to_be_bytes());
file.extend_from_slice(&height.to_be_bytes());
file.extend_from_slice(&[8, 2, 0, 0, 0, 0, 0, 0, 0]);
if let Some((x, y)) = phys {
file.extend_from_slice(b"\0\0\0\x09pHYs");
file.extend_from_slice(&x.to_be_bytes());
file.extend_from_slice(&y.to_be_bytes());
file.extend_from_slice(&[1, 0, 0, 0, 0]);
}
file.extend_from_slice(b"\0\0\0\0IEND\0\0\0\0");
file
}
fn inches(thousandths: i64) -> Length {
Length::from_emus(914_400 * thousandths / 1_000).unwrap()
}
#[test]
fn a_file_without_a_resolution_takes_96_pixels_per_inch() {
let image = image_file(png(192, 96, None), &EditLimits::default()).unwrap();
assert_eq!(image.format(), ImageFormat::Png);
assert_eq!(image.size(), (inches(2_000), inches(1_000)));
}
#[test]
fn a_file_takes_its_own_resolution() {
let image = image_file(
png(300, 600, Some((11_811, 11_811))),
&EditLimits::default(),
)
.unwrap();
let (width, height) = image.size();
assert!((width.units() - inches(1_000).units()).abs() <= 100);
assert!((height.units() - inches(2_000).units()).abs() <= 100);
}
#[test]
fn the_format_comes_from_the_first_bytes() {
let limits = EditLimits::default();
assert_eq!(
image_file(b"GIF89a....".to_vec(), &limits),
Err(ImageError::Format(ImageFormat::Gif))
);
assert_eq!(
image_file(b"not an image".to_vec(), &limits),
Err(ImageError::Format(ImageFormat::Unknown))
);
assert_eq!(
image_file(b"\x89PNG\r\n\x1a\n cut".to_vec(), &limits),
Err(ImageError::Header)
);
assert_eq!(image_file(png(0, 10, None), &limits), Err(ImageError::Size));
}
#[test]
fn a_file_beyond_the_limit_is_refused() {
let limits = EditLimits {
max_image_bytes: 10,
..EditLimits::default()
};
assert_eq!(
image_file(png(1, 1, None), &limits),
Err(ImageError::TooLarge { limit: 10 })
);
}
}