use std::num::NonZeroU16;
use f_office_paint::image_header::{
DensityUnit, ImageHeader, bmp_pixels, gif_pixels, jpeg_header, png_header,
};
use f_office_paint::{Image, ImageFormat};
use f_office_units::scale::{
TENTHS_OF_MM_PER_CM, TENTHS_OF_MM_PER_INCH, TENTHS_OF_MM_PER_M, TWIPS_PER_INCH,
};
use f_office_units::{Edges, Length, div_round_i128};
use super::Picture;
use crate::params::VML_PICTURE_PIXELS_PER_INCH;
pub(super) fn scale_to_image(picture: &mut Picture, room: (&mut Length, &mut Length)) {
let Some(steps) = picture.scale_steps else {
return;
};
let Some(natural) = picture.image.as_ref().and_then(natural_size) else {
return;
};
scale_to(picture, room, natural, steps);
}
pub(crate) fn scale_to_original(
picture: &mut Picture,
room: (&mut Length, &mut Length),
original: (Length, Length),
steps: NonZeroU16,
) {
scale_to(picture, room, original, steps);
}
fn scale_to(
picture: &mut Picture,
(width, height): (&mut Length, &mut Length),
(across, down): (Length, Length),
steps: NonZeroU16,
) {
if picture.turn.is_some() || picture.crop != Edges::default() {
return;
}
let (Some(scaled_width), Some(scaled_height)) = (
scaled(*width, across, steps.get()),
scaled(*height, down, steps.get()),
) else {
return;
};
(*width, *height) = (scaled_width, scaled_height);
(picture.width, picture.height) = (scaled_width, scaled_height);
picture.on_device_dots = true;
}
fn parse_header<T>(image: &Image, parse: impl Fn(&[u8]) -> Option<T>) -> Option<T> {
if let Some(prefix) = image.load_prefix(crate::params::IMAGE_HEADER_PREFIX_BYTES)
&& let Some(parsed) = parse(&prefix)
{
return Some(parsed);
}
if image.data.is_lazy() {
let full = image.load_bytes()?;
return parse(&full);
}
None
}
pub(crate) fn bullet_natural_size(image: &Image) -> Option<(Length, Length)> {
if let Some(size) = natural_size(image) {
return Some(size);
}
let (w, h) = match image.format {
ImageFormat::Gif => parse_header(image, gif_pixels)?,
ImageFormat::Bmp => parse_header(image, bmp_pixels)?,
ImageFormat::Tiff => {
let decoded = f_office_paint::decode(image).ok()?;
(
usize::try_from(decoded.width()).ok()?,
usize::try_from(decoded.height()).ok()?,
)
}
ImageFormat::Png
| ImageFormat::Jpeg
| ImageFormat::Emf
| ImageFormat::Wmf
| ImageFormat::EffectPicture
| ImageFormat::Unknown => return None,
};
Some((pixel_side(w, None)?, pixel_side(h, None)?))
}
fn natural_size(image: &Image) -> Option<(Length, Length)> {
let header = match image.format {
ImageFormat::Png => parse_header(image, |bytes| {
let full = !image.data.is_lazy()
|| f_office_paint::image_header::png_header_complete(bytes)
|| bytes.len() < crate::params::IMAGE_HEADER_PREFIX_BYTES;
full.then(|| png_header(bytes)).flatten()
})?,
ImageFormat::Jpeg => parse_header(image, jpeg_header)?,
ImageFormat::Emf => {
let bytes = image.load_bytes()?;
let (across, down) = f_office_emf::frame_size(&bytes)?;
return Some((
across.nearest_whole(Length::UNITS_PER_TWIP),
down.nearest_whole(Length::UNITS_PER_TWIP),
));
}
_ => return None,
};
let ImageHeader {
pixels: (across, down),
density,
} = header;
Some((
pixel_side(across, density.map(|(x, _, unit)| (x, unit)))?,
pixel_side(down, density.map(|(_, y, unit)| (y, unit)))?,
))
}
fn pixel_side(pixels: usize, density: Option<(u32, DensityUnit)>) -> Option<Length> {
let (count, unit) = match density {
None => (VML_PICTURE_PIXELS_PER_INCH, TENTHS_OF_MM_PER_INCH),
Some((count, DensityUnit::Inch)) => (i64::from(count), TENTHS_OF_MM_PER_INCH),
Some((count, DensityUnit::Centimeter)) => (i64::from(count), TENTHS_OF_MM_PER_CM),
Some((count, DensityUnit::Meter)) => (i64::from(count), TENTHS_OF_MM_PER_M),
};
let twips = div_round_i128(
i128::try_from(pixels).ok()? * i128::from(unit) * i128::from(TWIPS_PER_INCH),
i128::from(count) * i128::from(TENTHS_OF_MM_PER_INCH),
);
let units = i64::try_from(twips)
.ok()?
.checked_mul(Length::UNITS_PER_TWIP)?;
(units > 0).then(|| Length::from_units(units))
}
fn scaled(size: Length, natural: Length, steps: u16) -> Option<Length> {
let natural = i128::from(natural.units());
if natural <= 0 || steps == 0 {
return None;
}
let steps = i128::from(steps);
let share = div_round_i128(
i128::from(size.nearest_whole(Length::UNITS_PER_TWIP).units()) * steps,
natural,
);
i64::try_from(div_round_i128(natural * share, steps))
.ok()
.map(Length::from_units)
}
#[cfg(test)]
mod tests {
use f_office_paint::Image;
use f_office_paint::image_header::DensityUnit;
use f_office_units::{Edges, Length};
use std::num::NonZeroU16;
use super::{pixel_side, scale_to_image, scaled};
use crate::picture::Picture;
const THOUSANDTHS: Option<NonZeroU16> = NonZeroU16::new(1_000);
fn points(thousandths: i64) -> Length {
Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000)
}
fn png(width: u32, height: u32, per_meter: Option<u32>) -> Vec<u8> {
let mut file = b"\x89PNG\r\n\x1a\n".to_vec();
let mut chunk = |kind: &[u8], body: &[u8]| {
file.extend_from_slice(&u32::try_from(body.len()).unwrap().to_be_bytes());
file.extend_from_slice(kind);
file.extend_from_slice(body);
file.extend_from_slice(&[0; 4]);
};
let mut header = width.to_be_bytes().to_vec();
header.extend_from_slice(&height.to_be_bytes());
header.extend_from_slice(&[8, 2, 0, 0, 0]);
chunk(b"IHDR", &header);
if let Some(per_meter) = per_meter {
let mut body = per_meter.to_be_bytes().to_vec();
body.extend_from_slice(&per_meter.to_be_bytes());
body.push(1);
chunk(b"pHYs", &body);
}
chunk(b"IEND", &[]);
file
}
fn attached(
steps: Option<NonZeroU16>,
image: Vec<u8>,
size: (i64, i64),
) -> (Picture, Length, Length) {
let (mut width, mut height) = (points(size.0), points(size.1));
let mut picture = Picture {
image: Some(Image::new(image)),
scale_steps: steps,
..Picture::new("rId1", Edges::sized(width, height), Edges::default())
};
scale_to_image(&mut picture, (&mut width, &mut height));
(picture, width, height)
}
#[test]
fn takes_the_pixels_at_their_own_density_in_the_nearest_twip() {
let meter = |count| Some((count, DensityUnit::Meter));
assert_eq!(pixel_side(1_000, meter(11_811)), Some(points(240_000)));
assert_eq!(pixel_side(300, meter(2_835)), Some(points(299_950)));
assert_eq!(
pixel_side(1_000, Some((300, DensityUnit::Inch))),
Some(points(240_000))
);
assert_eq!(pixel_side(15, None), Some(points(11_250)));
}
#[test]
fn scales_the_natural_size_in_whole_thousandths() {
assert_eq!(
scaled(points(20_600), points(750_000), 1_000),
Some(points(20_250))
);
assert_eq!(
scaled(points(20_700), points(750_000), 1_000),
Some(points(21_000))
);
assert_eq!(
scaled(points(20_400), points(11_250), 1_000),
Some(Length::from_units(518_065))
);
assert_eq!(scaled(points(20_000), Length::ZERO, 1_000), None);
assert_eq!(scaled(points(20_000), points(11_250), 0), None);
}
#[test]
fn gives_the_scaled_size_as_the_room_and_the_drawn_size() {
let image = png(20, 1_000, Some(11_811));
let (picture, width, height) = attached(THOUSANDTHS, image, (80_000, 20_550));
assert_eq!(height, points(20_640));
assert_eq!(width, Length::from_units(2_032_041));
assert_eq!((picture.width, picture.height), (width, height));
assert!(picture.on_device_dots && picture.lies_on_device_dots());
let (kept, _, _) = attached(None, png(20, 1_000, Some(11_811)), (80_000, 20_550));
assert!(!kept.on_device_dots && !kept.lies_on_device_dots());
let metafile = Picture {
image: Some(Image::new(vec![0xD7, 0xCD, 0xC6, 0x9A, 0, 0])),
..picture
};
assert!(metafile.on_device_dots && !metafile.lies_on_device_dots());
}
#[test]
fn keeps_the_size_as_written_or_of_an_image_without_a_natural_size() {
let image = png(20, 1_000, Some(11_811));
let (_, width, height) = attached(None, image, (80_000, 20_550));
assert_eq!((width, height), (points(80_000), points(20_550)));
let wmf = vec![0xD7, 0xCD, 0xC6, 0x9A, 0, 0, 0, 0];
let (_, width, height) = attached(THOUSANDTHS, wmf, (80_000, 20_550));
assert_eq!((width, height), (points(80_000), points(20_550)));
}
}