f-office-paint 0.2.4

Display list: the contract between layout and output.
Documentation
//! The helpers of the tests that draw a display list, behind the feature `testing`, which only
//! dev-dependencies turn on: Carlito from the test fonts of `F_OFFICE_UNIT_TEST_FONTS`, lengths, pages,
//! rectangles and images in whole points, the image file of given pixels, written once for
//! the output crates, a PNG file of zero pixels of any size, which takes a few bytes for a
//! mebibyte of pixels, a PNG or JPEG file that embeds a given ICC profile, and, from the module
//! `files`, a JPEG file of four components with a CMYK profile.

use std::io::Cursor;

use f_office_fonts::{FontDb, FontId};
use f_office_units::Length;
use image::{DynamicImage, ImageResult};

use crate::{Clip, Image, ImageItem, Item, Orientation, Page, Rect, Rgb};

pub use crate::files::{cmyk_jpeg, cmyk_profile};

/// The bytes of Carlito Regular, the test font.
pub const CARLITO: &[u8] = include_bytes!(concat!(
    env!(
        "F_OFFICE_UNIT_TEST_FONTS",
        "set F_OFFICE_UNIT_TEST_FONTS to the folder of the test fonts, which holds Carlito-Regular.ttf"
    ),
    "/Carlito-Regular.ttf"
));

/// A font database that holds Carlito only, with its font, or `None` when the database does
/// not read it.
#[must_use]
pub fn carlito() -> Option<(FontDb, FontId)> {
    let mut fonts = FontDb::new();
    let font = *fonts.add_font(CARLITO).ok()?.first()?;
    Some((fonts, font))
}

/// The length of `points` whole points, which always fits: a 32-bit count of points is far
/// below the limit of a length.
#[must_use]
pub fn pt(points: i32) -> Length {
    Length::from_units(i64::from(points) * Length::UNITS_PER_POINT)
}

/// A page of `width` by `height` points with `items`, in a portrait section.
#[must_use]
pub fn page(width: i32, height: i32, items: Vec<Item>) -> Page {
    Page {
        width: pt(width),
        height: pt(height),
        orientation: Orientation::Portrait,
        items,
    }
}

/// A rectangle in `color` whose corner is at `x` and `y` points and whose sides are `width`
/// and `height` points, which may be negative.
#[must_use]
pub fn rect(x: i32, y: i32, width: i32, height: i32, color: Rgb) -> Item {
    Item::Rect(Rect {
        x: pt(x),
        y: pt(y),
        width: pt(width),
        height: pt(height),
        color,
    })
}

/// `image` drawn upright into the rectangle of `x`, `y`, `width` and `height` points, inside
/// `clip`, if any.
#[must_use]
pub fn image_item(
    image: &Image,
    (x, y, width, height): (i32, i32, i32, i32),
    clip: Option<Clip>,
) -> Item {
    Item::Image(ImageItem {
        x: pt(x),
        y: pt(y),
        width: pt(width),
        height: pt(height),
        clip,
        turn: None,
        image: image.clone(),
    })
}

/// `pixels` encoded as an image file of `format`. JPEG keeps no alpha, so pixels with alpha
/// lose it there; other pixels keep their color type, such as gray.
///
/// # Errors
///
/// When the encoder of `format` does not write the pixels.
pub fn encoded(pixels: impl Into<DynamicImage>, format: image::ImageFormat) -> ImageResult<Image> {
    let mut pixels = pixels.into();
    if format == image::ImageFormat::Jpeg && pixels.color().has_alpha() {
        pixels = DynamicImage::ImageRgb8(pixels.into_rgb8());
    }
    let mut bytes = Cursor::new(Vec::new());
    pixels.write_to(&mut bytes, format)?;
    Ok(Image::new(bytes.into_inner()))
}

/// The RGB `pixels` encoded as a PNG file, or a JPEG file of quality 100, that embeds the ICC
/// profile `profile`.
///
/// # Errors
///
/// When the encoder fails, or for another format.
pub fn encoded_with_profile(
    pixels: &image::RgbImage,
    format: image::ImageFormat,
    profile: Vec<u8>,
) -> ImageResult<Image> {
    use image::ImageEncoder;
    use image::codecs::{jpeg::JpegEncoder, png::PngEncoder};

    let (width, height) = pixels.dimensions();
    let color = image::ExtendedColorType::Rgb8;
    let mut bytes = Vec::new();
    match format {
        image::ImageFormat::Png => {
            let mut encoder = PngEncoder::new(&mut bytes);
            encoder
                .set_icc_profile(profile)
                .map_err(image::ImageError::Unsupported)?;
            encoder.write_image(pixels, width, height, color)?;
        }
        image::ImageFormat::Jpeg => {
            let mut encoder = JpegEncoder::new_with_quality(&mut bytes, 100);
            encoder
                .set_icc_profile(profile)
                .map_err(image::ImageError::Unsupported)?;
            encoder.write_image(pixels, width, height, color)?;
        }
        _ => {
            return Err(image::ImageError::Unsupported(
                image::error::UnsupportedError::from_format_and_kind(
                    format.into(),
                    image::error::UnsupportedErrorKind::Format(format.into()),
                ),
            ));
        }
    }
    Ok(Image::new(bytes))
}

/// The field types SHORT and LONG of TIFF 6.0, section 2, for [`palette_tiff`].
const TIFF_SHORT: u16 = 3;
const TIFF_LONG: u16 = 4;

/// A TIFF file of palette pixels with no compression, in little-endian byte order (TIFF 6.0,
/// sections 2 and 5): `width` by `height` pixels whose indices of `bits` bits fill `pixels` row
/// by row, and the `ColorMap` `color_map` after the IFD, if any. `None` when a length does not
/// fit in its field.
#[must_use]
pub fn palette_tiff(
    (width, height): (u16, u16),
    bits: u16,
    pixels: &[u8],
    color_map: Option<&[u16]>,
) -> Option<Vec<u8>> {
    let entries = if color_map.is_some() { 10 } else { 9 };
    // The header of 8 bytes, then the IFD: its count, its entries of 12 bytes and the place of
    // the next IFD.
    let ifd_end = 8 + 2 + 12 * entries + 4;
    let map = color_map.unwrap_or_default();
    let pixels_at = ifd_end + 2 * u32::try_from(map.len()).ok()?;
    let mut fields = vec![
        (256, TIFF_SHORT, 1, u32::from(width)),
        (257, TIFF_SHORT, 1, u32::from(height)),
        (258, TIFF_SHORT, 1, u32::from(bits)),
        (259, TIFF_SHORT, 1, 1),
        (262, TIFF_SHORT, 1, 3),
        (273, TIFF_LONG, 1, pixels_at),
        (277, TIFF_SHORT, 1, 1),
        (278, TIFF_SHORT, 1, u32::from(height)),
        (279, TIFF_LONG, 1, u32::try_from(pixels.len()).ok()?),
    ];
    if color_map.is_some() {
        fields.push((320, TIFF_SHORT, u32::try_from(map.len()).ok()?, ifd_end));
    }
    let mut file = b"II*\0".to_vec();
    file.extend(8_u32.to_le_bytes());
    file.extend(u16::try_from(fields.len()).ok()?.to_le_bytes());
    for field in fields {
        file.extend(tiff_entry(field)?);
    }
    file.extend(0_u32.to_le_bytes());
    file.extend(map.iter().flat_map(|value| value.to_le_bytes()));
    file.extend(pixels);
    Some(file)
}

/// The 12 bytes of an IFD entry of `tag`, `kind`, `count` and `value`, little-endian; a single
/// SHORT value fills the first 2 bytes of the value field.
fn tiff_entry((tag, kind, count, value): (u16, u16, u32, u32)) -> Option<Vec<u8>> {
    let mut entry = Vec::with_capacity(12);
    entry.extend(tag.to_le_bytes());
    entry.extend(kind.to_le_bytes());
    entry.extend(count.to_le_bytes());
    if kind == TIFF_SHORT && count == 1 {
        entry.extend(u16::try_from(value).ok()?.to_le_bytes());
        entry.extend([0, 0]);
    } else {
        entry.extend(value.to_le_bytes());
    }
    Some(entry)
}

/// A PNG file of `width` by `height` RGBA pixels that are all 0, with `sample_bits` bits a channel,
/// 8 or 16, written by hand. Its filtered rows are one run of zero bytes, which one fixed-code
/// deflate block holds as a literal 0 and copies of 258 bytes at a distance of 1 (RFC 1951,
/// 3.2.6), so a file whose pixels need hundreds of mebibytes takes a few mebibytes. `None` for
/// other `sample_bits`, or when a length does not fit in its field.
#[must_use]
pub fn zero_png(width: u32, height: u32, sample_bits: u8) -> Option<Vec<u8>> {
    let bytes_per_pixel = match sample_bits {
        8 => 4,
        16 => 8,
        _ => return None,
    };
    let raw = u64::from(height) * (1 + bytes_per_pixel * u64::from(width));
    let mut bits = Bits::default();
    bits.put(1, 1); // the last block
    bits.put(1, 2); // fixed codes
    bits.code(0x30, 8); // the literal 0
    for _ in 0..raw.saturating_sub(1) / 258 {
        bits.code(0xC5, 8); // length 258, code 285
        bits.code(0, 5); // distance 1, code 0
    }
    for _ in 0..raw.saturating_sub(1) % 258 {
        bits.code(0x30, 8);
    }
    bits.code(0, 7); // the end of the block, code 256
    // The zlib header (RFC 1950) and the Adler-32 sum of `raw` zero bytes: A stays 1, and B
    // adds A once for each byte.
    let mut zlib = vec![0x78, 0x01];
    zlib.extend(bits.bytes);
    let sum = (u32::try_from(raw % 65_521).ok()? << 16) | 1;
    zlib.extend(sum.to_be_bytes());
    let mut header = Vec::new();
    header.extend(width.to_be_bytes());
    header.extend(height.to_be_bytes());
    header.extend([sample_bits, 6, 0, 0, 0]); // the bits, RGBA, deflate, filters, no interlace
    let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
    for (kind, data) in [(b"IHDR", header), (b"IDAT", zlib), (b"IEND", Vec::new())] {
        png.extend(u32::try_from(data.len()).ok()?.to_be_bytes());
        let start = png.len();
        png.extend(kind);
        png.extend(&data);
        let crc = crc32(png.get(start..)?);
        png.extend(crc.to_be_bytes());
    }
    Some(png)
}

/// The bits of a deflate stream, the first bit in the lowest bit of each byte, for
/// [`zero_png`].
#[derive(Default)]
struct Bits {
    bytes: Vec<u8>,
    /// The place of the next bit in the last byte, 0 when the next bit starts a new byte.
    place: u32,
}

impl Bits {
    /// Puts the `count` lowest bits of `value`, the lowest first.
    fn put(&mut self, value: u32, count: u32) {
        for bit in 0..count {
            if self.place == 0 {
                self.bytes.push(0);
            }
            if let (1, Some(last)) = ((value >> bit) & 1, self.bytes.last_mut()) {
                *last |= 1 << self.place;
            }
            self.place = (self.place + 1) % 8;
        }
    }

    /// Puts a Huffman code of `count` bits, its highest bit first (RFC 1951, 3.1.1).
    fn code(&mut self, code: u32, count: u32) {
        for bit in (0..count).rev() {
            self.put((code >> bit) & 1, 1);
        }
    }
}

/// The CRC-32 of a PNG chunk (ISO 3309, as the PNG specification gives it).
fn crc32(data: &[u8]) -> u32 {
    let mut crc = u32::MAX;
    for &byte in data {
        crc ^= u32::from(byte);
        for _ in 0..8 {
            crc = if crc & 1 == 1 {
                (crc >> 1) ^ 0xEDB8_8320
            } else {
                crc >> 1
            };
        }
    }
    !crc
}