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};
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"
));
#[must_use]
pub fn carlito() -> Option<(FontDb, FontId)> {
let mut fonts = FontDb::new();
let font = *fonts.add_font(CARLITO).ok()?.first()?;
Some((fonts, font))
}
#[must_use]
pub fn pt(points: i32) -> Length {
Length::from_units(i64::from(points) * Length::UNITS_PER_POINT)
}
#[must_use]
pub fn page(width: i32, height: i32, items: Vec<Item>) -> Page {
Page {
width: pt(width),
height: pt(height),
orientation: Orientation::Portrait,
items,
}
}
#[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,
})
}
#[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(),
})
}
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()))
}
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))
}
const TIFF_SHORT: u16 = 3;
const TIFF_LONG: u16 = 4;
#[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 };
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)
}
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)
}
#[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); bits.put(1, 2); bits.code(0x30, 8); for _ in 0..raw.saturating_sub(1) / 258 {
bits.code(0xC5, 8); bits.code(0, 5); }
for _ in 0..raw.saturating_sub(1) % 258 {
bits.code(0x30, 8);
}
bits.code(0, 7); 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]); 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)
}
#[derive(Default)]
struct Bits {
bytes: Vec<u8>,
place: u32,
}
impl Bits {
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;
}
}
fn code(&mut self, code: u32, count: u32) {
for bit in (0..count).rev() {
self.put((code >> bit) & 1, 1);
}
}
}
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
}