f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! The image of a named edit: the file, the size of its drawing, and the drawing of one inline
//! picture (ECMA-376 Part 1, 20.4.2.8 `inline`, and 20.2.2.5 `pic`).

use f_office_paint::ImageFormat;
use f_office_units::{Length, div_round_i128};

use super::NamedFault;
use super::build::escaped;

/// A PNG or a JPEG file that an image edit inserts, with its size at its own resolution.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageFile {
    format: PictureFormat,
    data: Vec<u8>,
    size: (Length, Length),
}

/// The formats of the files that an image edit inserts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PictureFormat {
    Png,
    Jpeg,
}

impl ImageFile {
    /// The file `data` of the format `format`, whose width and height at its own resolution
    /// are `size`: none for a format other than PNG and JPEG, and for a width or a height that
    /// is not more than zero or that lies beyond the largest length of a file.
    #[must_use]
    pub fn new(format: ImageFormat, data: Vec<u8>, size: (Length, Length)) -> Option<Self> {
        let format = match format {
            ImageFormat::Png => PictureFormat::Png,
            ImageFormat::Jpeg => PictureFormat::Jpeg,
            _ => return None,
        };
        (in_file(size.0) && in_file(size.1)).then_some(Self { format, data, size })
    }

    /// The file's format.
    #[must_use]
    pub const fn format(&self) -> ImageFormat {
        match self.format {
            PictureFormat::Png => ImageFormat::Png,
            PictureFormat::Jpeg => ImageFormat::Jpeg,
        }
    }

    /// The file's bytes.
    #[must_use]
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// The width and the height of the image at its own resolution.
    #[must_use]
    pub const fn size(&self) -> (Length, Length) {
        self.size
    }

    /// The extension of the file's part and its content type.
    pub(super) const fn extension_and_type(&self) -> (&'static str, &'static str) {
        match self.format {
            PictureFormat::Png => ("png", "image/png"),
            PictureFormat::Jpeg => ("jpeg", "image/jpeg"),
        }
    }
}

/// Whether `length` is more than zero and at most the largest length of a file.
fn in_file(length: Length) -> bool {
    length > Length::ZERO && length.units() <= Length::FILE_LIMIT
}

/// The size of the drawing of `image`: `width` and `height` when the edit gives both, one of
/// them with the other in the image's aspect, or else the image's own size, made smaller in its
/// aspect to the width `column` when it is wider.
pub(super) fn drawn_size(
    image: &ImageFile,
    (width, height): (Option<Length>, Option<Length>),
    column: Option<Length>,
) -> Result<(Length, Length), NamedFault> {
    let (own_width, own_height) = image.size;
    let size = match (width, height) {
        (Some(width), Some(height)) => (width, height),
        (Some(width), None) => (width, scaled(own_height, width, own_width)),
        (None, Some(height)) => (scaled(own_width, height, own_height), height),
        (None, None) => match column {
            Some(column) if own_width > column => (column, scaled(own_height, column, own_width)),
            _ => image.size,
        },
    };
    if in_file(size.0) && in_file(size.1) {
        Ok(size)
    } else {
        Err(NamedFault::ImageSize)
    }
}

/// `length` times `numerator` over `denominator`, which is more than zero, rounded to the
/// nearest unit.
fn scaled(length: Length, numerator: Length, denominator: Length) -> Length {
    let quotient = div_round_i128(
        i128::from(length.units()) * i128::from(numerator.units()),
        i128::from(denominator.units()),
    );
    Length::from_units(i64::try_from(quotient).unwrap_or(i64::MAX))
}

/// A length in EMUs, the unit of DrawingML, rounded to the nearest one.
const fn emus(length: Length) -> i64 {
    length.div_round(Length::UNITS_PER_EMU).units()
}

/// The namespace URIs that a drawing writes: of the WordprocessingML drawings, of DrawingML,
/// of its pictures and of the relationships.
pub(super) struct DrawingNamespaces {
    pub(super) wp: &'static str,
    pub(super) a: &'static str,
    pub(super) pic: &'static str,
    pub(super) r: &'static str,
}

/// What a drawing shows: its ID, the ID of the relationship of its file, the file's name, the
/// text that describes it, and its size.
pub(super) struct Drawing<'d> {
    pub(super) id: u64,
    pub(super) relationship: &'d str,
    pub(super) file: &'d str,
    pub(super) alt: &'d str,
    pub(super) size: (Length, Length),
}

/// The `w:drawing` element, with the prefix `w`, of one inline picture, which declares the
/// namespaces that it uses itself, so that it parses in any part.
pub(super) fn drawing(w: &str, namespaces: &DrawingNamespaces, drawing: &Drawing<'_>) -> String {
    let (cx, cy) = (emus(drawing.size.0), emus(drawing.size.1));
    let DrawingNamespaces { wp, a, pic, r } = namespaces;
    let id = drawing.id;
    let alt = escaped(drawing.alt);
    let file = escaped(drawing.file);
    let relationship = escaped(drawing.relationship);
    format!(
        concat!(
            r#"<{w}:drawing><wp:inline distT="0" distB="0" distL="0" distR="0" xmlns:wp="{wp}" xmlns:a="{a}" xmlns:pic="{pic}" xmlns:r="{r}">"#,
            r#"<wp:extent cx="{cx}" cy="{cy}"/><wp:docPr id="{id}" name="Picture {id}" descr="{alt}"/>"#,
            r#"<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>"#,
            r#"<a:graphic><a:graphicData uri="{pic}"><pic:pic><pic:nvPicPr><pic:cNvPr id="0" name="{file}" descr="{alt}"/><pic:cNvPicPr/></pic:nvPicPr>"#,
            r#"<pic:blipFill><a:blip r:embed="{relationship}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>"#,
            r#"<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="{cx}" cy="{cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>"#,
            r#"</pic:pic></a:graphicData></a:graphic></wp:inline></{w}:drawing>"#
        ),
        w = w,
        wp = wp,
        a = a,
        pic = pic,
        r = r,
        cx = cx,
        cy = cy,
        id = id,
        alt = alt,
        file = file,
        relationship = relationship,
    )
}