Skip to main content

f_office_docx/named_edits/
image.rs

1//! The image of a named edit: the file, the size of its drawing, and the drawing of one inline
2//! picture (ECMA-376 Part 1, 20.4.2.8 `inline`, and 20.2.2.5 `pic`).
3
4use f_office_paint::ImageFormat;
5use f_office_units::{Length, div_round_i128};
6
7use super::NamedFault;
8use super::build::escaped;
9
10/// A PNG or a JPEG file that an image edit inserts, with its size at its own resolution.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct ImageFile {
13    format: PictureFormat,
14    data: Vec<u8>,
15    size: (Length, Length),
16}
17
18/// The formats of the files that an image edit inserts.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20enum PictureFormat {
21    Png,
22    Jpeg,
23}
24
25impl ImageFile {
26    /// The file `data` of the format `format`, whose width and height at its own resolution
27    /// are `size`: none for a format other than PNG and JPEG, and for a width or a height that
28    /// is not more than zero or that lies beyond the largest length of a file.
29    #[must_use]
30    pub fn new(format: ImageFormat, data: Vec<u8>, size: (Length, Length)) -> Option<Self> {
31        let format = match format {
32            ImageFormat::Png => PictureFormat::Png,
33            ImageFormat::Jpeg => PictureFormat::Jpeg,
34            _ => return None,
35        };
36        (in_file(size.0) && in_file(size.1)).then_some(Self { format, data, size })
37    }
38
39    /// The file's format.
40    #[must_use]
41    pub const fn format(&self) -> ImageFormat {
42        match self.format {
43            PictureFormat::Png => ImageFormat::Png,
44            PictureFormat::Jpeg => ImageFormat::Jpeg,
45        }
46    }
47
48    /// The file's bytes.
49    #[must_use]
50    pub fn data(&self) -> &[u8] {
51        &self.data
52    }
53
54    /// The width and the height of the image at its own resolution.
55    #[must_use]
56    pub const fn size(&self) -> (Length, Length) {
57        self.size
58    }
59
60    /// The extension of the file's part and its content type.
61    pub(super) const fn extension_and_type(&self) -> (&'static str, &'static str) {
62        match self.format {
63            PictureFormat::Png => ("png", "image/png"),
64            PictureFormat::Jpeg => ("jpeg", "image/jpeg"),
65        }
66    }
67}
68
69/// Whether `length` is more than zero and at most the largest length of a file.
70fn in_file(length: Length) -> bool {
71    length > Length::ZERO && length.units() <= Length::FILE_LIMIT
72}
73
74/// The size of the drawing of `image`: `width` and `height` when the edit gives both, one of
75/// them with the other in the image's aspect, or else the image's own size, made smaller in its
76/// aspect to the width `column` when it is wider.
77pub(super) fn drawn_size(
78    image: &ImageFile,
79    (width, height): (Option<Length>, Option<Length>),
80    column: Option<Length>,
81) -> Result<(Length, Length), NamedFault> {
82    let (own_width, own_height) = image.size;
83    let size = match (width, height) {
84        (Some(width), Some(height)) => (width, height),
85        (Some(width), None) => (width, scaled(own_height, width, own_width)),
86        (None, Some(height)) => (scaled(own_width, height, own_height), height),
87        (None, None) => match column {
88            Some(column) if own_width > column => (column, scaled(own_height, column, own_width)),
89            _ => image.size,
90        },
91    };
92    if in_file(size.0) && in_file(size.1) {
93        Ok(size)
94    } else {
95        Err(NamedFault::ImageSize)
96    }
97}
98
99/// `length` times `numerator` over `denominator`, which is more than zero, rounded to the
100/// nearest unit.
101fn scaled(length: Length, numerator: Length, denominator: Length) -> Length {
102    let quotient = div_round_i128(
103        i128::from(length.units()) * i128::from(numerator.units()),
104        i128::from(denominator.units()),
105    );
106    Length::from_units(i64::try_from(quotient).unwrap_or(i64::MAX))
107}
108
109/// A length in EMUs, the unit of DrawingML, rounded to the nearest one.
110const fn emus(length: Length) -> i64 {
111    length.div_round(Length::UNITS_PER_EMU).units()
112}
113
114/// The namespace URIs that a drawing writes: of the WordprocessingML drawings, of DrawingML,
115/// of its pictures and of the relationships.
116pub(super) struct DrawingNamespaces {
117    pub(super) wp: &'static str,
118    pub(super) a: &'static str,
119    pub(super) pic: &'static str,
120    pub(super) r: &'static str,
121}
122
123/// What a drawing shows: its ID, the ID of the relationship of its file, the file's name, the
124/// text that describes it, and its size.
125pub(super) struct Drawing<'d> {
126    pub(super) id: u64,
127    pub(super) relationship: &'d str,
128    pub(super) file: &'d str,
129    pub(super) alt: &'d str,
130    pub(super) size: (Length, Length),
131}
132
133/// The `w:drawing` element, with the prefix `w`, of one inline picture, which declares the
134/// namespaces that it uses itself, so that it parses in any part.
135pub(super) fn drawing(w: &str, namespaces: &DrawingNamespaces, drawing: &Drawing<'_>) -> String {
136    let (cx, cy) = (emus(drawing.size.0), emus(drawing.size.1));
137    let DrawingNamespaces { wp, a, pic, r } = namespaces;
138    let id = drawing.id;
139    let alt = escaped(drawing.alt);
140    let file = escaped(drawing.file);
141    let relationship = escaped(drawing.relationship);
142    format!(
143        concat!(
144            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}">"#,
145            r#"<wp:extent cx="{cx}" cy="{cy}"/><wp:docPr id="{id}" name="Picture {id}" descr="{alt}"/>"#,
146            r#"<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>"#,
147            r#"<a:graphic><a:graphicData uri="{pic}"><pic:pic><pic:nvPicPr><pic:cNvPr id="0" name="{file}" descr="{alt}"/><pic:cNvPicPr/></pic:nvPicPr>"#,
148            r#"<pic:blipFill><a:blip r:embed="{relationship}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>"#,
149            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>"#,
150            r#"</pic:pic></a:graphicData></a:graphic></wp:inline></{w}:drawing>"#
151        ),
152        w = w,
153        wp = wp,
154        a = a,
155        pic = pic,
156        r = r,
157        cx = cx,
158        cy = cy,
159        id = id,
160        alt = alt,
161        file = file,
162        relationship = relationship,
163    )
164}