f-office 0.2.3

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! The image file of an image edit ([`NamedEdit::InsertImage`](super::NamedEdit)): its format
//! by its first bytes, never by its name, and its size at its own resolution by its header.

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};

/// The resolution of an image whose file gives none, in pixels per inch: the resolution of a
/// screen at a scale of 100 % in Windows, at which CSS also takes a pixel to be 1/96 inch.
const PIXELS_PER_INCH: u32 = 96;

/// One meter in tenths of a millimeter.
const TENTHS_OF_MM_PER_METER: i64 = 10_000;

/// Why a file is not an image that an edit inserts. Each message names the fix.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ImageError {
    /// The file is larger than [`EditLimits::max_image_bytes`].
    TooLarge {
        /// The limit.
        limit: usize,
    },
    /// The file is of a format other than PNG and JPEG, by its first bytes.
    Format(ImageFormat),
    /// The file's header does not read.
    Header,
    /// The image has no pixels, or a size at its resolution that is too large for a file.
    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 {}

/// The image file `data` of an image edit: a PNG or a JPEG file by its first bytes, with its
/// size at the resolution that its header gives, or at 96 pixels per inch when it gives none.
///
/// # Errors
///
/// Returns [`ImageError`] for a file beyond `limits`, of another format, whose header does not
/// read, or without a size.
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)
}

/// The width and the height of the image of `header` at its resolution.
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};

    /// A PNG file of `width` by `height` pixels with the chunk `phys` after its header, if
    /// given, each chunk with a CRC of zeros, which the reader does not check.
    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() {
        // 11,811 pixels per meter are 300 pixels per inch, to the nearest whole one.
        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 })
        );
    }
}