f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The natural size of an inline VML picture's image, and the size and the room that the
//! picture takes from it when the reader's VML sizes give it scale steps; and the size and the
//! room that the preview of an embedded object takes from the object's original size.

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;

/// Gives a picture with scale steps (`Picture::scale_steps`) whose image has a natural size
/// ([`natural_size`]) a size from it, as [`scale_to`] does. Any other picture keeps its size.
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);
}

/// Gives the preview of an embedded object a size from its object's original size `original`,
/// across and down, in whole `steps` of a whole, as [`scale_to`] does.
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);
}

/// Gives an upright, uncropped picture `base` times a scale in whole `steps` of a whole, a half
/// up, of its size in the nearest twip, across and down ([`scaled`]): as the room of its object
/// on its line, `room`, and as its drawn size, whose image then lies on the device's dots
/// (`Picture::on_device_dots`). A turned or cropped picture, and a base of no length, keep the
/// size.
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;
}

/// Runs a header parser on a lazy prefix first, falling back to full image bytes only when the
/// prefix was truncated before the header marker (for example a JPEG with large EXIF metadata).
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
}

/// The natural size `(width, height)` of a picture bullet's `image` (in twips, at its header
/// density or `VML_PICTURE_PIXELS_PER_INCH` = 96 dpi, or its EMF frame size), or `None` when
/// the format is unsupported or the header does not read.
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)?))
}

/// The natural size of `image`, across and down, each in the nearest twip, a half up: a PNG or
/// JPEG image's pixels at the density of its header, or at `VML_PICTURE_PIXELS_PER_INCH` when it
/// gives none, and an EMF image's frame. Another format, a WMF image among them, has 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)))?,
    ))
}

/// `pixels` at `density`, pixels in a unit, or at `VML_PICTURE_PIXELS_PER_INCH` when there is
/// none, in the nearest twip, a half up. A side of no twip, or beyond the units, has none.
fn pixel_side(pixels: usize, density: Option<(u32, DensityUnit)>) -> Option<Length> {
    // The pixels in a unit, and the unit in tenths of a millimeter.
    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))
}

/// `natural` times `size` in the nearest twip as a share of `natural` in whole `steps` of a
/// whole, a half up. A natural size of no length, or no steps, gives none.
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;

    /// The scale steps of the rule: whole thousandths.
    const THOUSANDTHS: Option<NonZeroU16> = NonZeroU16::new(1_000);

    /// `thousandths` of a point.
    fn points(thousandths: i64) -> Length {
        Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000)
    }

    /// A PNG file's signature and header chunk of `width` by `height` pixels, with a `pHYs`
    /// chunk of `per_meter` pixels a meter when it has one; the reader checks no CRC.
    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
    }

    /// A picture with `steps` of `image`, `width` by `height` thousandths of a point, with its
    /// object's room after the image is attached.
    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() {
        // 1,000 pixels at 11,811 a meter are 4,800.01 twips; 300 at 2,835 a meter, 5,999.26.
        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))
        );
        // 15 pixels at 96 an inch.
        assert_eq!(pixel_side(15, None), Some(points(11_250)));
    }

    #[test]
    fn scales_the_natural_size_in_whole_thousandths() {
        // 20.6 / 750 is 0.02747, which takes 0.027: 20.25 pt; 20.7 / 750 takes 0.028: 21.0 pt.
        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))
        );
        // 20.4 / 11.25 is 1.81333, which takes 1.813: 20.39625 pt, 518,064.75 units.
        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() {
        // 20 by 1,000 pixels at 11,811 a meter: 4.8 by 240 pt; 20.55 / 240 takes 0.086.
        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));
        // 80 / 4.8 is 16.667: 80.0016 pt, 2,032,040.64 units.
        assert_eq!(width, Length::from_units(2_032_041));
        assert_eq!((picture.width, picture.height), (width, height));
        // The scaled picture's PNG image lies on the device's dots; one that keeps its size does
        // not, nor does a scaled picture of a metafile.
        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)));
        // A WMF file's placeable key: no natural size here.
        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)));
    }
}