f-office-paint 0.3.0

Display list: the contract between layout and output.
Documentation
//! The picture decode: the one decode of an image's file into pixels, which both outputs call,
//! its first step, the format and the limit, which the writer of pictures again calls too with
//! its own limit, and the check of the limit from a file's header alone and the file without the
//! ICC profile that the decode does not apply, which the PDF output calls for a file that its
//! PDF library decodes itself. Only the output stage turns on its feature `decode`.

use std::io::Cursor;

use f_office_effects::{DrawError, MaskFormat, Rgba};
use image::{DynamicImage, ImageDecoder, ImageError, ImageReader, Limits, RgbaImage};

use crate::{Image, ImageFault, ImageFormat, InkConversion, MAX_DECODED_BYTES};

mod cmyk;
mod ink_table;
mod palette;
mod profile;

pub use profile::without_profile;

/// The bytes of one pixel of RGBA with 8 bits a channel, the pixels that the picture decode
/// keeps.
const RGBA_BYTES_PER_PIXEL: u64 = 4;

/// Decodes a PNG, JPEG, GIF, BMP or TIFF image, or draws an effect picture, into straight RGBA
/// pixels, the first frame of an animated GIF, within [`MAX_DECODED_BYTES`], with the image's conversion of inks and its
/// color conversion applied. The picture opacity is left to each output.
///
/// # Errors
///
/// As [`decode_file`].
pub fn decode(image: &Image) -> Result<RgbaImage, ImageFault> {
    let (bytes, format) = image.load_bytes_with_format().ok_or(ImageFault::Data)?;
    let mut pixels = decode_inks(&bytes, format, MAX_DECODED_BYTES, image.inks)?.into_rgba8();
    image.color.apply(pixels.as_mut());
    Ok(pixels)
}

/// Whether the picture decode converts the inks of `image` into RGB pixels: a JPEG file of four
/// components, whose inks convert through the ink table or through the file's own profile as
/// [`InkConversion`] says. A reader of a PDF that holds the file as it is converts its inks
/// with its own arithmetic and draws other colors.
#[must_use]
pub fn converts_inks(image: &Image) -> bool {
    if image.format != ImageFormat::Jpeg {
        return false;
    }
    if let Some(prefix) = image.load_prefix(64 * 1024)
        && let Some(components) = profile::jpeg_components(&prefix)
    {
        return components == 4;
    }
    image
        .load_bytes()
        .is_some_and(|bytes| profile::jpeg_components(&bytes) == Some(4))
}

/// Decodes the file `data` of a PNG, JPEG, GIF, BMP or TIFF image into its own pixels, with
/// their own channels and depth, the first frame of an animated GIF, RGB pixels with 8 bits a
/// channel for a TIFF file of 8-bit palette pixels (TIFF 6.0, section 5), and RGB pixels
/// converted through the profile for a JPEG file of four components that embeds a CMYK profile
/// (`cmyk`), and the RGBA pixels of an effect picture, when its RGBA pixels
/// with 8 bits a channel need at most `max_bytes`, and allocating at most `max_bytes`:
/// [`MAX_DECODED_BYTES`] for the outputs, and
/// [`MAX_DECODED_BYTES_TO_WRITE_AGAIN`](crate::MAX_DECODED_BYTES_TO_WRITE_AGAIN) for a picture
/// that the writer writes again. The RGBA pixels are what [`decode`] keeps, and the most that
/// the writer keeps; their size comes from the file's header, before any pixel decodes.
///
/// # Errors
///
/// [`ImageFault::Format`] for a metafile or an image of an unknown format,
/// [`ImageFault::Limit`] for an image whose RGBA pixels, or whose decoder, need more than
/// `max_bytes`, and [`ImageFault::Data`] for data that does not decode in its format and for
/// an effect picture that does not draw within `max_bytes`.
pub fn decode_file(
    data: &[u8],
    format: ImageFormat,
    max_bytes: u64,
) -> Result<DynamicImage, ImageFault> {
    decode_inks(data, format, max_bytes, InkConversion::EmbeddedProfile)
}

/// [`decode_file`], with the inks of a JPEG file of four components converted as `inks` says.
fn decode_inks(
    data: &[u8],
    format: ImageFormat,
    max_bytes: u64,
    inks: InkConversion,
) -> Result<DynamicImage, ImageFault> {
    if format == ImageFormat::EffectPicture {
        return effect_picture(data, max_bytes);
    }
    let (format, palette) = source(data, format)?;
    let file = palette.as_ref().map_or(data, palette::Palette::gray_file);
    let decoder = within_limit(file, format, max_bytes)?;
    if format == image::ImageFormat::Jpeg
        && let Some(pixels) = cmyk::decode(file, inks)?
    {
        return Ok(DynamicImage::ImageRgb8(pixels));
    }
    let pixels = DynamicImage::from_decoder(decoder).map_err(|error| fault(&error))?;
    match palette {
        Some(palette) => palette.expand(pixels),
        None => Ok(pixels),
    }
}

/// The RGBA pixels of the effect picture `data`, when they need at most `max_bytes`.
fn effect_picture(data: &[u8], max_bytes: u64) -> Result<DynamicImage, ImageFault> {
    let picture = f_office_effects::draw_with_rgba(data, max_bytes, |format, bytes, limit| {
        let img_format = match format {
            MaskFormat::Png => ImageFormat::Png,
            MaskFormat::Jpeg => ImageFormat::Jpeg,
            MaskFormat::Gif => ImageFormat::Gif,
            MaskFormat::Bmp => ImageFormat::Bmp,
            MaskFormat::Tiff => ImageFormat::Tiff,
        };
        let rgba = decode_file(bytes, img_format, limit)
            .map_err(|fault| match fault {
                ImageFault::Limit => DrawError::Limit,
                ImageFault::Format | ImageFault::Data => DrawError::Unfit,
            })?
            .into_rgba8();
        let (width, height) = rgba.dimensions();
        Ok(Rgba {
            width,
            height,
            pixels: rgba.into_raw(),
        })
    })
    .map_err(|error| match error {
        DrawError::Limit => ImageFault::Limit,
        DrawError::Unreadable | DrawError::Unfit => ImageFault::Data,
    })?;
    RgbaImage::from_raw(picture.width, picture.height, picture.pixels)
        .map(DynamicImage::ImageRgba8)
        .ok_or(ImageFault::Data)
}

/// The format of the `image` crate that reads a file of `format`, and the palette of a TIFF
/// file `data` of 8-bit palette pixels, whose gray copy that crate reads in its place.
fn source(
    data: &[u8],
    format: ImageFormat,
) -> Result<(image::ImageFormat, Option<palette::Palette>), ImageFault> {
    let format = match format {
        ImageFormat::Png => image::ImageFormat::Png,
        ImageFormat::Jpeg => image::ImageFormat::Jpeg,
        ImageFormat::Gif => image::ImageFormat::Gif,
        ImageFormat::Bmp => image::ImageFormat::Bmp,
        ImageFormat::Tiff => image::ImageFormat::Tiff,
        ImageFormat::Emf | ImageFormat::Wmf | ImageFormat::EffectPicture | ImageFormat::Unknown => {
            return Err(ImageFault::Format);
        }
    };
    let palette = match format {
        image::ImageFormat::Tiff => palette::Palette::read(data)?,
        _ => None,
    };
    Ok((format, palette))
}

/// The decoder of `data` in `format` after the file's header, when the image's RGBA pixels
/// need at most `max_bytes` and its decoder's own pixels fit in them, with the rest of
/// `max_bytes` as the limit of its other allocations, as [`decode_file`] says.
fn within_limit(
    data: &[u8],
    format: image::ImageFormat,
    max_bytes: u64,
) -> Result<impl ImageDecoder + '_, ImageFault> {
    let mut limits = Limits::default();
    limits.max_alloc = Some(max_bytes);
    let mut reader = ImageReader::with_format(Cursor::new(data), format);
    reader.limits(limits.clone());
    let mut decoder = reader.into_decoder().map_err(|error| fault(&error))?;
    let (width, height) = decoder.dimensions();
    let rgba_bytes = (u64::from(width) * u64::from(height)).saturating_mul(RGBA_BYTES_PER_PIXEL);
    if rgba_bytes > max_bytes {
        return Err(ImageFault::Limit);
    }
    // As the `image` crate's own `ImageReader::decode`: the decoder's buffer of its own pixels
    // first, then its other allocations, within the rest of the limit.
    limits
        .reserve(decoder.total_bytes())
        .map_err(|error| fault(&error))?;
    decoder.set_limits(limits).map_err(|error| fault(&error))?;
    Ok(decoder)
}

/// The fault of a decoder's error: a limit for an error of the limits, else data that does not
/// decode.
fn fault(error: &ImageError) -> ImageFault {
    match error {
        ImageError::Limits(_) => ImageFault::Limit,
        _ => ImageFault::Data,
    }
}

#[cfg(test)]
mod tests {
    use f_office_effects::{Angle, Picture, Pie, Scene, Share, Slice};

    use super::{ImageFault, ImageFormat, decode_file};

    #[test]
    fn draws_an_effect_picture() {
        let picture = Picture {
            width: 40,
            height: 30,
            scene: Scene::Pie(Pie {
                tilt: Angle::from_sixty_thousandths(1_800_000),
                angle_of_view: Angle::from_sixty_thousandths(900_000),
                thickness: Share::ratio(1, 4).unwrap(),
                margin: Share::ratio(1, 50).unwrap(),
                slices: vec![Slice {
                    start: Angle::from_sixty_thousandths(0),
                    swing: Angle::from_sixty_thousandths(21_600_000),
                    color: [200, 40, 40],
                    explosion: 0,
                }],
            }),
        }
        .encode();
        let decode = |limit| decode_file(&picture, ImageFormat::EffectPicture, limit);
        let pixels = decode(40 * 30 * 4).unwrap().into_rgba8();
        assert_eq!(pixels.dimensions(), (40, 30));
        assert_eq!(pixels.get_pixel(0, 0).0[3], 0);
        assert_eq!(pixels.get_pixel(20, 12).0[3], 255);
        assert_eq!(decode(40 * 30 * 4 - 1).map(drop), Err(ImageFault::Limit));
        assert_eq!(
            decode_file(b"not a picture", ImageFormat::EffectPicture, u64::MAX).map(drop),
            Err(ImageFault::Data)
        );
    }
}