use std::num::NonZeroU16;
use f_office_drawingml::Feature;
use f_office_drawingml::color::percentage;
use f_office_drawingml::effect::{Glow, OuterShadow, Reflection, picture_effects};
use f_office_drawingml::shape::{
Geometry, PictureLine, picture_clip_path, picture_properties, turned_clockwise,
};
use f_office_paint::{
Clip, FillRule, Image, ImageColor, ImageFormat, ImageItem, Item, Opacity, PathCommand, Point,
Turn,
};
use f_office_units::scale::DRAWING_WHOLE;
use f_office_units::{Edges, Length, div_round_i128, saturated};
use f_office_warnings::Name;
use f_office_xml::NodeId;
use crate::body::{Block, DrawingMut, visit_drawings};
use crate::ns::{A, O, PIC, R};
use crate::reader::PartReader;
use crate::warnings::{Drawing, Reason};
mod natural;
pub(crate) use natural::{bullet_natural_size, scale_to_original};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Picture {
pub embed: String,
pub image: Option<Image>,
pub opacity: Opacity,
pub color: ImageColor,
pub left: Length,
pub top: Length,
pub width: Length,
pub height: Length,
pub crop: Edges<i64>,
pub turn: Option<Turn>,
pub drops: bool,
pub line: Option<Box<PictureLine>>,
pub shadow: Option<Box<PictureShadow>>,
pub soft_edge: Option<Box<PictureSoftEdge>>,
pub glow: Option<Box<PictureGlow>>,
pub reflection: Option<Box<PictureReflection>>,
pub geometry: Geometry,
pub scale_steps: Option<NonZeroU16>,
pub on_device_dots: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureShadow {
pub shadow: OuterShadow,
pub part: Name,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureSoftEdge {
pub radius: Length,
pub part: Name,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureGlow {
pub glow: Glow,
pub part: Name,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PictureReflection {
pub reflection: Reflection,
pub part: Name,
}
#[must_use]
pub fn fit_to_twips(width: Length, height: Length) -> (Length, Length) {
let twip = Length::UNITS_PER_TWIP;
let (w, h) = (width.units(), height.units());
if w <= 0 || h <= 0 {
return (width, height);
}
let (rest_w, rest_h) = (w % twip, h % twip);
if rest_h * w <= rest_w * h {
(
Length::from_units(w - rest_w),
Length::from_units(h + f_office_units::div_round(-(h * rest_w), w)),
)
} else {
(
Length::from_units(w + f_office_units::div_round(-(w * rest_h), h)),
Length::from_units(h - rest_h),
)
}
}
#[must_use]
pub(crate) fn fit_aspect_to_twips(
(width, height): (Length, Length),
(aspect_w, aspect_h): (Length, Length),
) -> (Length, Length) {
let twip = Length::UNITS_PER_TWIP;
let (wc, hc) = (
width.units() - width.units().rem_euclid(twip),
height.units() - height.units().rem_euclid(twip),
);
let (aw, ah) = (aspect_w.units(), aspect_h.units());
if wc <= 0 || hc <= 0 || aw <= 0 || ah <= 0 {
return fit_to_twips(width, height);
}
let (wc, hc, aw, ah) = (
i128::from(wc),
i128::from(hc),
i128::from(aw),
i128::from(ah),
);
if wc * ah <= hc * aw {
(
Length::from_units(saturated(wc)),
Length::from_units(saturated(div_round_i128(wc * ah, aw))),
)
} else {
(
Length::from_units(saturated(div_round_i128(hc * aw, ah))),
Length::from_units(saturated(hc)),
)
}
}
fn drawn_extent(doc: &f_office_xml::Document, pic: NodeId) -> Option<(Length, Length)> {
let ext = doc
.child(pic, PIC, "spPr")
.and_then(|shape| doc.child(shape, A, "xfrm"))
.and_then(|xfrm| doc.child(xfrm, A, "ext"))?;
let cx = doc
.attribute(ext, None, "cx")
.and_then(f_office_drawingml::emu_length)?;
let cy = doc
.attribute(ext, None, "cy")
.and_then(f_office_drawingml::emu_length)?;
(cx > Length::ZERO && cy > Length::ZERO).then_some((cx, cy))
}
impl Picture {
pub(crate) fn read(
reader: &mut PartReader,
inline: NodeId,
frame: Edges<Length>,
) -> Option<Self> {
let doc = reader.doc;
let pic = doc
.child(inline, A, "graphic")
.and_then(|graphic| doc.child(graphic, A, "graphicData"))
.and_then(|data| doc.child(data, PIC, "pic"))?;
let (width, height) = reader
.turned_pictures()
.fit_size((frame.width(), frame.height()), drawn_extent(doc, pic));
let fitted = Edges::placed(frame.left, frame.top, width, height)?;
Self::from_pic(reader, pic, fitted)
}
pub(crate) fn from_pic(
reader: &mut PartReader,
pic: NodeId,
frame: Edges<Length>,
) -> Option<Self> {
let doc = reader.doc;
let fill = doc.child(pic, PIC, "blipFill")?;
let blip = doc.child(fill, A, "blip")?;
let embed = embedded_image(reader, blip, BLIP_IMAGE)?;
let turn = match turn_of(reader, pic) {
Shape::Upright => None,
Shape::Turned(turn) => Some(turn),
Shape::OtherAngle => return None,
};
let look = doc
.child(pic, PIC, "spPr")
.map_or_default(|props| picture_properties(doc, props, reader.drawing_warnings()));
let shadow = look.shadow.map(|shadow| {
Box::new(PictureShadow {
shadow,
part: Name::new(reader.part()),
})
});
let soft_edge = look.soft_edge.map(|radius| {
Box::new(PictureSoftEdge {
radius,
part: Name::new(reader.part()),
})
});
let glow = look.glow.map(|glow| {
Box::new(PictureGlow {
glow,
part: Name::new(reader.part()),
})
});
let reflection = look.reflection.map(|reflection| {
Box::new(PictureReflection {
reflection,
part: Name::new(reader.part()),
})
});
let color = read_picture_color(reader, blip);
let crop = shares(reader, doc.child(fill, A, "srcRect"));
if crop != Edges::default() && turn.is_some_and(|turn| !by_quarters(turn)) {
reader.drawingml_feature_not_supported(Feature::Turn);
return None;
}
Some(Self {
turn,
line: look.line.map(Box::new),
shadow,
soft_edge,
glow,
reflection,
geometry: look.geometry,
opacity: opacity(reader, blip),
color,
..Self::new(embed, frame, crop)
})
}
pub(crate) fn compose_outer_turn(&mut self, matrix: [[i32; 2]; 2]) {
if matrix == [[1, 0], [0, 1]] {
return;
}
let identity = Turn {
xx: Turn::SCALE,
yx: 0,
xy: 0,
yy: Turn::SCALE,
};
let cur = self.turn.unwrap_or(identity);
let next = Turn {
xx: matrix[0][0] * cur.xx + matrix[0][1] * cur.yx,
yx: matrix[1][0] * cur.xx + matrix[1][1] * cur.yx,
xy: matrix[0][0] * cur.xy + matrix[0][1] * cur.yy,
yy: matrix[1][0] * cur.xy + matrix[1][1] * cur.yy,
};
self.turn = (next != identity).then_some(next);
}
pub(crate) fn compose_outer_rotation(&mut self, rotation: i64) -> bool {
let Some(outer) = any_turn(rotation, [false, false]) else {
return false;
};
let identity = Turn {
xx: Turn::SCALE,
yx: 0,
xy: 0,
yy: Turn::SCALE,
};
let cur = self.turn.unwrap_or(identity);
let entry = |a: i32, b: i32, c: i32, d: i32| {
i32::try_from(f_office_units::div_round(
i64::from(a) * i64::from(b) + i64::from(c) * i64::from(d),
i64::from(Turn::SCALE),
))
.ok()
};
let (Some(xx), Some(yx), Some(xy), Some(yy)) = (
entry(outer.xx, cur.xx, outer.xy, cur.yx),
entry(outer.yx, cur.xx, outer.yy, cur.yx),
entry(outer.xx, cur.xy, outer.xy, cur.yy),
entry(outer.yx, cur.xy, outer.yy, cur.yy),
) else {
return false;
};
let next = Turn { xx, yx, xy, yy };
if self.crop != Edges::default() && !by_quarters(next) {
return false;
}
self.turn = (next != identity).then_some(next);
true
}
pub(crate) fn new(embed: &str, frame: Edges<Length>, crop: Edges<i64>) -> Self {
Self {
embed: embed.to_owned(),
image: None,
opacity: Opacity::FULL,
color: ImageColor::Original,
left: frame.left,
top: frame.top,
width: frame.width(),
height: frame.height(),
crop,
turn: None,
drops: false,
line: None,
shadow: None,
soft_edge: None,
glow: None,
reflection: None,
geometry: Geometry::Rect,
scale_steps: None,
on_device_dots: false,
}
}
fn with_blip(self, reader: &mut PartReader, blip: NodeId) -> Self {
Self {
opacity: opacity(reader, blip),
color: read_picture_color(reader, blip),
..self
}
}
pub fn from_fill(
reader: &mut PartReader,
fill: NodeId,
(width, height): (Length, Length),
) -> Option<Self> {
let doc = reader.doc;
let blip = doc.child(fill, A, "blip")?;
let embed = doc.attribute(blip, Some(R), "embed")?;
let crop = shares(reader, doc.child(fill, A, "srcRect"));
let insets = shares(
reader,
doc.child(fill, A, "stretch")
.and_then(|stretch| doc.child(stretch, A, "fillRect")),
);
let (left, width, crop_left, crop_right) =
stretched(width, (insets.left, insets.right), (crop.left, crop.right))?;
let (top, height, crop_top, crop_bottom) =
stretched(height, (insets.top, insets.bottom), (crop.top, crop.bottom))?;
let crop = Edges {
left: crop_left,
top: crop_top,
right: crop_right,
bottom: crop_bottom,
};
let frame = Edges::placed(left, top, width, height)?;
Some(Self::new(embed, frame, crop).with_blip(reader, blip))
}
#[must_use]
pub fn item(&self, x: Length, top: Length) -> Option<Item> {
let mut image = self.image.clone()?;
image.opacity = self.opacity;
if self.color != ImageColor::Original {
image.color = self.color.clone();
}
let whole = self.whole(x, top)?;
let (mut image_x, mut image_y) = (whole.left, whole.top);
let (image_width, image_height) = (whole.width(), whole.height());
let mut frame = self.shown(x, top)?;
if let Some(turn) = self.turn {
let centre = |edges: Edges<Length>| {
Some((
edges.left.checked_mul(2)?.checked_add(edges.width())?,
edges.top.checked_mul(2)?.checked_add(edges.height())?,
))
};
let (frame_x, frame_y) = centre(frame)?;
let (whole_x, whole_y) = centre(whole)?;
let offset = (whole_x - frame_x, whole_y - frame_y);
let (moved_x, moved_y) = turned_about((frame_x, frame_y), offset, turn)?;
image_x = (moved_x - image_width).div_round(2);
image_y = (moved_y - image_height).div_round(2);
if turn.xx == 0 {
let (width, height) = (frame.width(), frame.height());
frame = Edges::placed(
(frame_x - height).div_round(2),
(frame_y - width).div_round(2),
height,
width,
)?;
}
}
let clip = (self.crop != Edges::default()).then_some(Clip {
x: frame.left,
y: frame.top,
width: frame.width(),
height: frame.height(),
});
Some(Item::Image(ImageItem {
x: image_x,
y: image_y,
width: image_width,
height: image_height,
clip,
turn: self.turn,
image,
}))
}
#[must_use]
pub fn shown(&self, x: Length, top: Length) -> Option<Edges<Length>> {
Edges::placed(
x.checked_add(self.left)?,
top.checked_add(self.top)?,
self.width,
self.height,
)
}
#[must_use]
pub fn covered(&self, x: Length, top: Length) -> Option<Edges<Length>> {
let shown = self.shown(x, top)?;
if self.turn.is_none_or(|turn| turn.xx != 0) {
return Some(shown);
}
let (width, height) = (shown.width(), shown.height());
let centre_x = shown.left.checked_mul(2)?.checked_add(width)?;
let centre_y = shown.top.checked_mul(2)?.checked_add(height)?;
Edges::placed(
(centre_x - height).div_round(2),
(centre_y - width).div_round(2),
height,
width,
)
}
#[must_use]
pub fn drawn_bounds(&self, x: Length, top: Length) -> Option<Edges<Length>> {
let Some(turn) = self.turn.filter(|turn| !by_quarters(*turn)) else {
return self.covered(x, top);
};
let shown = self.shown(x, top)?;
let (width, height) = (shown.width(), shown.height());
let half = |[across, down]: [i32; 2]| {
let sum = i128::from(width.units()) * i128::from(across.unsigned_abs())
+ i128::from(height.units()) * i128::from(down.unsigned_abs());
let half = f_office_units::div_round_i128(sum, 2 * i128::from(Turn::SCALE));
i64::try_from(half).ok().map(Length::from_units)
};
let (half_width, half_height) = (half([turn.xx, turn.xy])?, half([turn.yx, turn.yy])?);
let centre_x = shown.left.checked_mul(2)?.checked_add(width)?;
let centre_y = shown.top.checked_mul(2)?.checked_add(height)?;
Edges::placed(
(centre_x - half_width.checked_mul(2)?).div_round(2),
(centre_y - half_height.checked_mul(2)?).div_round(2),
half_width.checked_mul(2)?,
half_height.checked_mul(2)?,
)
}
#[must_use]
pub fn turned_line(&self, x: Length, top: Length, mut line: Item) -> Option<Item> {
let Some(turn) = self.turn.filter(|turn| !by_quarters(*turn)) else {
return Some(line);
};
let shown = self.shown(x, top)?;
let centre_x = shown.left.checked_mul(2)?.checked_add(shown.width())?;
let centre_y = shown.top.checked_mul(2)?.checked_add(shown.height())?;
if let Item::Path(path) = &mut line {
for point in path.commands.iter_mut().flat_map(PathCommand::points_mut) {
*point = turned_point(*point, (centre_x, centre_y), turn)?;
}
}
Some(line)
}
pub(crate) fn turn_commands(
&self,
x: Length,
top: Length,
commands: &mut [PathCommand],
) -> Option<()> {
let Some(turn) = self.turn else {
return Some(());
};
let shown = self.shown(x, top)?;
let centre_x = shown.left.checked_mul(2)?.checked_add(shown.width())?;
let centre_y = shown.top.checked_mul(2)?.checked_add(shown.height())?;
for point in commands.iter_mut().flat_map(PathCommand::points_mut) {
*point = turned_point(*point, (centre_x, centre_y), turn)?;
}
Some(())
}
pub(crate) fn clip_path(&self, x: Length, top: Length) -> Option<(Vec<PathCommand>, FillRule)> {
let (mut commands, rule) = picture_clip_path(&self.geometry, self.shown(x, top)?)?;
self.turn_commands(x, top, &mut commands)?;
Some((commands, rule))
}
#[must_use]
pub fn lies_on_device_dots(&self) -> bool {
self.on_device_dots
&& self
.image
.as_ref()
.is_some_and(|image| matches!(image.format, ImageFormat::Png | ImageFormat::Jpeg))
}
#[must_use]
pub fn whole(&self, x: Length, top: Length) -> Option<Edges<Length>> {
let left = x.checked_add(self.left)?;
let top = top.checked_add(self.top)?;
let crop = self.crop;
let (image_x, width) = uncrop(left, self.width, (crop.left, crop.right))?;
let (image_y, height) = uncrop(top, self.height, (crop.top, crop.bottom))?;
Edges::placed(image_x, image_y, width, height)
}
pub(crate) fn turned_whole_corners(&self, x: Length, top: Length) -> Option<[Point; 3]> {
let shown = self.shown(x, top)?;
let whole = self.whole(x, top)?;
let corners = [
Point {
x: whole.left,
y: whole.top,
},
Point {
x: whole.right,
y: whole.top,
},
Point {
x: whole.left,
y: whole.bottom,
},
];
let Some(turn) = self.turn else {
return Some(corners);
};
let centre = (
shown.left.checked_mul(2)?.checked_add(shown.width())?,
shown.top.checked_mul(2)?.checked_add(shown.height())?,
);
Some([
turned_point(corners[0], centre, turn)?,
turned_point(corners[1], centre, turn)?,
turned_point(corners[2], centre, turn)?,
])
}
}
fn opacity(reader: &mut PartReader, blip: NodeId) -> Opacity {
let doc = reader.doc;
doc.children(blip)
.iter()
.copied()
.filter(|&node| doc.is(node, A, "alphaModFix"))
.filter_map(|node| reader.or_missing_in(node, (None, "amt"), percentage))
.fold(Opacity::FULL, |alpha, amount| {
alpha.times(Opacity::clamped(amount))
})
}
fn read_picture_color(reader: &mut PartReader, blip: NodeId) -> ImageColor {
let parsed = picture_effects(reader.doc, blip, reader.drawing_warnings());
let mut resolved = Vec::with_capacity(parsed.len());
let mut unresolved = false;
for effect in &parsed {
match effect.resolve(reader.scheme()) {
Some(color_effect) => resolved.push(color_effect),
None => unresolved = true,
}
}
if unresolved {
reader.drawingml_feature_not_supported(Feature::PictureEffect);
}
ImageColor::from_effects(resolved)
}
fn uncrop(start: Length, length: Length, (before, after): (i64, i64)) -> Option<(Length, Length)> {
let shown = DRAWING_WHOLE.checked_sub(before)?.checked_sub(after)?;
if shown <= 0 {
return None;
}
let whole = length.checked_mul(DRAWING_WHOLE)?.div_round(shown);
let cut = whole.checked_mul(before)?.div_round(DRAWING_WHOLE);
Some((start.checked_sub(cut)?, whole))
}
pub(crate) type ImageAttributes = (&'static str, (&'static str, &'static str));
pub(crate) const BLIP_IMAGE: ImageAttributes = ("embed", (R, "link"));
pub(crate) const VML_IMAGE: ImageAttributes = ("id", (O, "href"));
pub(crate) fn embedded_image<'d>(
reader: &mut PartReader<'d>,
node: NodeId,
(embed, (link_namespace, link)): ImageAttributes,
) -> Option<&'d str> {
let doc = reader.doc;
let id = doc.attribute(node, Some(R), embed);
if id.is_none() && doc.attribute(node, Some(link_namespace), link).is_some() {
reader.drawing_skipped(Drawing::Picture, Reason::Unlinked);
}
id
}
pub(crate) enum Shape {
Upright,
Turned(Turn),
OtherAngle,
}
fn turn_of(reader: &mut PartReader, pic: NodeId) -> Shape {
let doc = reader.doc;
let Some(xfrm) = doc
.child(pic, PIC, "spPr")
.and_then(|shape| doc.child(shape, A, "xfrm"))
else {
return Shape::Upright;
};
let on = |name| {
doc.attribute(xfrm, None, name)
.is_some_and(f_office_drawingml::boolean)
};
let rotation = reader
.or_missing_in(xfrm, (None, "rot"), f_office_drawingml::integer)
.unwrap_or(0);
let shape = reader
.turned_pictures()
.turn(rotation, [on("flipH"), on("flipV")]);
if matches!(shape, Shape::OtherAngle) {
reader.drawingml_feature_not_supported(Feature::Turn);
}
shape
}
pub(crate) fn rotation(doc: &f_office_xml::Document, drawing: NodeId) -> i64 {
doc.child(drawing, A, "graphic")
.and_then(|graphic| doc.child(graphic, A, "graphicData"))
.and_then(|data| doc.child(data, PIC, "pic"))
.and_then(|pic| doc.child(pic, PIC, "spPr"))
.and_then(|shape| doc.child(shape, A, "xfrm"))
.and_then(|xfrm| doc.attribute(xfrm, None, "rot"))
.and_then(f_office_drawingml::integer)
.unwrap_or(0)
}
pub(crate) fn any_turn(rotation: i64, [flip_x, flip_y]: [bool; 2]) -> Option<Turn> {
let scale = i64::from(Turn::SCALE);
let [cos, sin] = unit_millionths(turned_clockwise([scale, 0], [0, 0], rotation)?)
.map(|entry| i32::try_from(entry).ok());
let (cos, sin) = (cos?, sin?);
let mirrored = |flipped: bool| if flipped { -1 } else { 1 };
let (across, down) = (mirrored(flip_x), mirrored(flip_y));
Some(Turn {
xx: cos * across,
yx: sin * across,
xy: -sin * down,
yy: cos * down,
})
}
fn unit_millionths([cos, sin]: [i64; 2]) -> [i64; 2] {
let square = i64::from(Turn::SCALE) * i64::from(Turn::SCALE);
let off = |[a, b]: [i64; 2]| (a * a + b * b - square).abs();
let mut best = [cos, sin];
for (across, down) in [
(0, -1),
(0, 1),
(-1, 0),
(1, 0),
(-1, -1),
(-1, 1),
(1, -1),
(1, 1),
] {
let pair = [cos + across, sin + down];
if off(pair) < off(best) {
best = pair;
}
}
best
}
const fn by_quarters(turn: Turn) -> bool {
turn.xx % Turn::SCALE == 0 && turn.yx % Turn::SCALE == 0
}
pub(crate) fn turn(quarters: i64, [flip_x, flip_y]: [bool; 2]) -> Option<Turn> {
let [xx, yx, xy, yy] = match quarters {
0 if !flip_x && !flip_y => return None,
0 => [1, 0, 0, 1],
1 => [0, 1, -1, 0],
2 => [-1, 0, 0, -1],
_ => [0, -1, 1, 0],
};
let sign = |flipped: bool| if flipped { -Turn::SCALE } else { Turn::SCALE };
let (across, down) = (sign(flip_x), sign(flip_y));
Some(Turn {
xx: xx * across,
yx: yx * across,
xy: xy * down,
yy: yy * down,
})
}
fn shares(reader: &mut PartReader, rect: Option<NodeId>) -> Edges<i64> {
rect.map_or_else(Edges::default, |rect| {
Edges::from(["l", "t", "r", "b"].map(|side| {
reader
.or_missing_in(rect, (None, side), percentage)
.unwrap_or(0)
}))
})
}
fn stretched(
length: Length,
(near, far): (i64, i64),
(crop_near, crop_far): (i64, i64),
) -> Option<(Length, Length, i64, i64)> {
let span = DRAWING_WHOLE - near - far;
if span <= 0 {
return None;
}
let start = near.max(0);
let end = (DRAWING_WHOLE - far).min(DRAWING_WHOLE);
if end <= start {
return None;
}
let kept = i128::from(DRAWING_WHOLE - crop_near - crop_far);
let crop = |crop: i64, outside: i64| {
let cut =
f_office_units::div_round_i128(kept * i128::from(outside.max(0)), i128::from(span));
i64::try_from(i128::from(crop) + cut).ok()
};
let share = |value: i64| (length * value).div_round(DRAWING_WHOLE);
Some((
share(start),
share(end - start),
crop(crop_near, -near)?,
crop(crop_far, -far)?,
))
}
pub fn attach_images(blocks: &mut [Block], mut find: impl FnMut(&str) -> Option<Image>) {
visit_drawings(blocks, &mut |drawing| match drawing {
DrawingMut::Object { picture, room } => {
picture.image = find(&picture.embed);
natural::scale_to_image(picture, room);
}
DrawingMut::Floating(floating) => {
if let Some(picture) = floating.picture.as_mut() {
picture.image = find(&picture.embed);
}
}
});
}
fn turned_step(dx: Length, dy: Length, [across, down]: [i32; 2]) -> Option<Length> {
let sum =
i128::from(dx.units()) * i128::from(across) + i128::from(dy.units()) * i128::from(down);
let step = f_office_units::div_round_i128(sum, i128::from(Turn::SCALE));
i64::try_from(step).ok().map(Length::from_units)
}
fn turned_about(
(centre_x, centre_y): (Length, Length),
(dx, dy): (Length, Length),
turn: Turn,
) -> Option<(Length, Length)> {
Some((
centre_x.checked_add(turned_step(dx, dy, [turn.xx, turn.xy])?)?,
centre_y.checked_add(turned_step(dx, dy, [turn.yx, turn.yy])?)?,
))
}
fn turned_point(point: Point, centre: (Length, Length), turn: Turn) -> Option<Point> {
let dx = point.x.checked_mul(2)?.checked_sub(centre.0)?;
let dy = point.y.checked_mul(2)?.checked_sub(centre.1)?;
let (x, y) = turned_about(centre, (dx, dy), turn)?;
Some(Point {
x: x.div_round(2),
y: y.div_round(2),
})
}
#[cfg(test)]
mod tests {
use f_office_paint::{Clip, Image, ImageItem, Item, Opacity, Turn};
use f_office_units::Length;
use f_office_xml::{Document, Limits};
use super::{Picture, fit_to_twips, stretched, uncrop};
use crate::ns::{A, PIC, R, WP};
use crate::reader::PartReader;
use f_office_units::Edges;
fn inline(pic: &str) -> Option<Picture> {
let xml = format!(
r#"<wp:inline xmlns:wp="{WP}" xmlns:a="{A}" xmlns:pic="{PIC}" xmlns:r="{R}"><a:graphic><a:graphicData>{pic}</a:graphicData></a:graphic></wp:inline>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let [x, y, width, height] = [1, 2, 300 * 1270, 400 * 1270].map(Length::from_units);
let frame = Edges::placed(x, y, width, height).unwrap();
Picture::read(&mut PartReader::new(&doc), doc.root().unwrap(), frame)
}
#[test]
fn reads_the_image_and_its_crop() {
let picture = inline(
r#"<pic:pic><pic:blipFill><a:blip r:embed="rId7"/><a:srcRect l="25000" t="-5%" r="12.5%"/></pic:blipFill><pic:spPr><a:xfrm rot="21600000"/></pic:spPr></pic:pic>"#,
)
.unwrap();
assert_eq!(picture.embed, "rId7");
assert_eq!(picture.crop, Edges::from([25_000, -5_000, 12_500, 0]));
assert_eq!(picture.image, None);
let units = [picture.left, picture.top, picture.width, picture.height].map(Length::units);
assert_eq!(units, [1, 2, 300 * 1270, 400 * 1270]);
}
#[test]
fn carries_direct_grayscale_to_each_picture_and_fill_use() {
use f_office_paint::ImageColor;
for (effects, expected) in [
("", ImageColor::Original),
("<a:grayscl/>", ImageColor::Gray709),
("<a:grayscl/><a:grayscl/>", ImageColor::Gray709),
("<a:extLst><a:grayscl/></a:extLst>", ImageColor::Original),
("<grayscl/>", ImageColor::Original),
] {
let xml = format!(
r#"<pic:pic><pic:blipFill><a:blip r:embed="rId1">{effects}</a:blip></pic:blipFill></pic:pic>"#
);
let mut picture = inline(&xml).unwrap();
let source = Image::new(vec![0xFF, 0xD8, 0xFF]);
picture.image = Some(source.clone());
let Item::Image(item) = picture.item(Length::ZERO, Length::ZERO).unwrap() else {
panic!()
};
assert_eq!(item.image.color, expected, "{effects}");
assert_eq!(source.color, ImageColor::Original);
assert!(std::sync::Arc::ptr_eq(
source.data.inline_bytes().unwrap(),
item.image.data.inline_bytes().unwrap()
));
let xml = format!(
r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId1">{effects}</a:blip></a:blipFill>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let fill = Picture::from_fill(
&mut PartReader::new(&doc),
doc.root().unwrap(),
(Length::from_units(100), Length::from_units(100)),
)
.unwrap();
assert_eq!(fill.color, expected);
}
}
#[test]
fn carries_fixed_alpha_modifiers_to_pictures_and_shape_fills() {
let cases = [
("", 100_000),
(r#"<a:alphaModFix amt="10000"/>"#, 10_000),
(r#"<a:alphaModFix amt="12.5%"/>"#, 12_500),
(r#"<a:alphaModFix amt="0"/>"#, 0),
(r#"<a:alphaModFix amt="150000"/>"#, 100_000),
(r#"<a:alphaModFix amt="-1"/>"#, 0),
(r#"<a:alphaModFix/><a:alphaModFix amt="bad"/>"#, 100_000),
(
r#"<a:alphaModFix amt="50000"/><a:alphaModFix amt="25000"/>"#,
12_500,
),
];
for (effects, expected) in cases {
let xml = format!(
r#"<pic:pic><pic:blipFill><a:blip r:embed="rId1">{effects}</a:blip></pic:blipFill></pic:pic>"#
);
let mut picture = inline(&xml).unwrap();
let source = Image::new(vec![0xFF, 0xD8, 0xFF]);
picture.image = Some(source.clone());
let Item::Image(item) = picture.item(Length::ZERO, Length::ZERO).unwrap() else {
panic!()
};
assert_eq!(item.image.opacity.share(), expected, "{effects}");
assert_eq!(source.opacity, Opacity::FULL);
assert!(std::sync::Arc::ptr_eq(
item.image.data.inline_bytes().unwrap(),
source.data.inline_bytes().unwrap()
));
let xml = format!(
r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId1">{effects}</a:blip></a:blipFill>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let fill = Picture::from_fill(
&mut PartReader::new(&doc),
doc.root().unwrap(),
(Length::from_units(100), Length::from_units(100)),
)
.unwrap();
assert_eq!(fill.opacity.share(), expected, "{effects}");
}
}
#[test]
fn reads_a_crop_or_an_alpha_that_does_not_read_as_missing_with_a_warning() {
let fill = |blip: &str, crop: &str| {
let xml = format!(
r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId1">{blip}</a:blip><a:srcRect {crop}/></a:blipFill>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut reader = PartReader::new(&doc);
let size = (Length::from_units(100), Length::from_units(100));
let picture = Picture::from_fill(&mut reader, doc.root().unwrap(), size).unwrap();
let invalid: Vec<String> = reader
.invalid_values()
.into_iter()
.map(|(element, _, _, _)| element)
.collect();
(picture.crop, picture.opacity.share(), invalid)
};
let top = Edges::from([0, 20_000, 0, 0]);
assert_eq!(
fill(r#"<a:alphaModFix amt="50000"/>"#, r#"l="0" t="20000""#),
(top, 50_000, vec![])
);
assert_eq!(
fill(r#"<a:alphaModFix amt="x"/>"#, r#"l="x" t="20000""#),
(top, 100_000, vec!["srcRect".into(), "alphaModFix".into()])
);
}
#[test]
fn stretches_a_picture_fill_over_its_fill_rectangle() {
let xml = format!(
r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId3"/><a:srcRect t="20000"/><a:stretch><a:fillRect l="-25000" r="10000" b="-50000"/></a:stretch></a:blipFill>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let size = (Length::from_units(100_000), Length::from_units(200_000));
let picture =
Picture::from_fill(&mut PartReader::new(&doc), doc.root().unwrap(), size).unwrap();
assert_eq!(picture.embed, "rId3");
let frame = [picture.left, picture.top, picture.width, picture.height].map(Length::units);
assert_eq!(frame, [0, 0, 90_000, 200_000]);
assert_eq!(picture.crop, Edges::from([21_739, 20_000, 0, 26_667]));
let flat = format!(
r#"<a:blipFill xmlns:a="{A}" xmlns:r="{R}"><a:blip r:embed="rId3"/><a:stretch><a:fillRect l="60000" r="40000"/></a:stretch></a:blipFill>"#
);
let doc = Document::parse(flat.as_bytes(), &Limits::default()).unwrap();
assert_eq!(
Picture::from_fill(&mut PartReader::new(&doc), doc.root().unwrap(), size),
None
);
}
#[test]
fn fits_the_size_inside_the_size_cut_to_whole_twips() {
let emus = |cx: i64, cy: i64| {
let (width, height) = fit_to_twips(
Length::from_emus(cx).unwrap(),
Length::from_emus(cy).unwrap(),
);
(width.units(), height.units())
};
let twips = |n: i64| n * Length::UNITS_PER_TWIP;
assert_eq!(emus(1_785_938, 1_886_084), (twips(2812), 3_771_496));
assert_eq!(emus(3_246_536, 2_760_292), (6_491_703, twips(4346)));
assert_eq!(emus(3_324_225, 866_906), (6_647_445, twips(1365)));
assert_eq!(emus(1_270_000, 635_000), (twips(2000), twips(1000)));
}
#[test]
fn fits_drawn_extent_aspect_inside_whole_twip_frame() {
let pt = |n: i64| Length::from_points(n).unwrap();
let frame = (
Length::from_emus(1_785_938).unwrap(),
Length::from_emus(1_886_084).unwrap(),
);
assert_eq!(
super::fit_aspect_to_twips(frame, frame),
fit_to_twips(frame.0, frame.1)
);
let (w, h) = super::fit_aspect_to_twips((pt(144), pt(72)), (pt(140), pt(68)));
assert_eq!(w, pt(144));
assert_eq!(h.units(), 1_776_549);
let (w, h) = super::fit_aspect_to_twips((pt(144), pt(72)), (pt(148), pt(76)));
assert_eq!(w.units(), 3_561_347);
assert_eq!(h, pt(72));
assert_eq!(
super::fit_aspect_to_twips((pt(144), pt(100)), (pt(180), pt(60))),
(pt(144), pt(48))
);
assert_eq!(
super::fit_aspect_to_twips((pt(144), pt(100)), (pt(60), pt(120))),
(pt(50), pt(100))
);
}
#[test]
fn fits_a_size_near_the_limit_of_a_length_to_whole_twips() {
let most = Length::FILE_LIMIT;
let (width, height) = fit_to_twips(Length::from_units(most), Length::from_units(most - 1));
let rest = most % Length::UNITS_PER_TWIP;
assert_eq!(
(width.units(), height.units()),
(most - rest, 70_368_744_177_139)
);
}
#[test]
fn crops_a_fill_stretched_with_the_extreme_shares() {
let box_size = Length::from_units(100_000);
let (low, high) = (i64::from(i32::MIN), i64::from(i32::MAX));
for near in [low, 0, 99_999] {
for far in [low, 0] {
for crop in [(low, low), (low, high), (high, low), (high, high)] {
assert!(
stretched(box_size, (near, far), crop).is_some(),
"{near} {far} {crop:?}"
);
}
}
}
let (_, _, crop_near, crop_far) = stretched(box_size, (low, 0), (low, low)).unwrap();
assert_eq!((crop_near, crop_far), (2_147_383_653, low));
}
#[test]
fn leaves_out_drawings_without_a_picture_or_turned_by_another_angle() {
let blip = r#"<pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill>"#;
let cases = [
String::new(),
"<pic:pic/>".to_owned(),
r#"<pic:pic><pic:blipFill><a:blip r:link="rId1"/></pic:blipFill></pic:pic>"#.to_owned(),
format!(r#"<pic:pic>{blip}<pic:spPr><a:xfrm rot="1800000"/></pic:spPr></pic:pic>"#),
];
for pic in cases {
assert_eq!(inline(&pic), None, "{pic}");
}
let plain = format!(r#"<pic:pic>{blip}<pic:spPr><a:xfrm flipH="0"/></pic:spPr></pic:pic>"#);
assert_eq!(inline(&plain).unwrap().turn, None);
}
#[test]
fn reads_flips_and_quarter_turns() {
let blip = r#"<pic:blipFill><a:blip r:embed="rId1"/></pic:blipFill>"#;
let one = Turn::SCALE;
let turn = |xfrm: &str| {
inline(&format!(
"<pic:pic>{blip}<pic:spPr><a:xfrm {xfrm}/></pic:spPr></pic:pic>"
))
.unwrap()
.turn
.map(|t| [t.xx, t.yx, t.xy, t.yy])
};
assert_eq!(turn(r#"flipH="1""#), Some([-one, 0, 0, one]));
assert_eq!(turn(r#"flipV="true""#), Some([one, 0, 0, -one]));
assert_eq!(turn(r#"rot="5400000""#), Some([0, one, -one, 0]));
assert_eq!(turn(r#"rot="-5400000""#), Some([0, -one, one, 0]));
assert_eq!(
turn(r#"rot="10800000" flipH="1" flipV="1""#),
Some([one, 0, 0, one])
);
assert_eq!(turn(r#"rot="21600000""#), None);
}
#[test]
fn turns_a_cropped_picture_about_the_centre_of_its_frame() {
let mut picture = picture([0, 0, 33_333, 0]);
let [left, top, width, height] = [0, 0, 300, 100].map(Length::from_units);
(picture.left, picture.top, picture.width, picture.height) = (left, top, width, height);
let one = Turn::SCALE;
picture.turn = Some(Turn {
xx: 0,
yx: one,
xy: -one,
yy: 0,
});
let Some(Item::Image(item)) = picture.item(Length::ZERO, Length::ZERO) else {
panic!("no image");
};
let units = [item.x, item.y, item.width, item.height].map(Length::units);
assert_eq!(units, [-75, 75, 450, 100]);
let clip = item.clip.unwrap();
let clip = [clip.x, clip.y, clip.width, clip.height].map(Length::units);
assert_eq!(clip, [100, -100, 100, 300]);
assert_eq!(item.turn, picture.turn);
}
fn picture(crop: [i64; 4]) -> Picture {
let [x, y, width, height] = [10, 20, 600, 300].map(Length::from_units);
Picture {
image: Some(Image::new(vec![0xFF, 0xD8, 0xFF])),
..Picture::new(
"rId1",
Edges::placed(x, y, width, height).unwrap(),
Edges::from(crop),
)
}
}
fn rect(item: &Item) -> ([i64; 4], Option<Clip>) {
let Item::Image(ImageItem {
x,
y,
width,
height,
clip,
..
}) = item
else {
panic!("not an image: {item:?}");
};
([x, y, width, height].map(|l| l.units()), *clip)
}
const CORNER: (Length, Length) = (Length::from_units(1_000), Length::from_units(2_000));
#[test]
fn places_the_picture_in_the_drawings_box() {
let item = picture([0; 4]).item(CORNER.0, CORNER.1).unwrap();
assert_eq!(rect(&item), ([1_010, 2_020, 600, 300], None));
let mut empty = picture([0; 4]);
empty.image = None;
assert_eq!(empty.item(Length::ZERO, Length::ZERO), None);
}
#[test]
fn scales_a_cropped_image_so_that_its_shown_part_fills_the_picture() {
let item = picture([25_000, 25_000, 0, 0])
.item(CORNER.0, CORNER.1)
.unwrap();
let clip = Clip {
x: Length::from_units(1_010),
y: Length::from_units(2_020),
width: Length::from_units(600),
height: Length::from_units(300),
};
assert_eq!(rect(&item), ([810, 1_920, 800, 400], Some(clip)));
let zero = Length::ZERO;
assert_eq!(picture([60_000, 0, 40_000, 0]).item(zero, zero), None);
let u = Length::from_units;
assert_eq!(
uncrop(zero, u(100), (-50_000, -50_000)),
Some((u(25), u(50)))
);
assert_eq!(uncrop(zero, u(i64::MAX), (1, 0)), None);
}
#[test]
fn attaches_images_inside_text_boxes() {
use crate::body::{Block, Content, Paragraph, Run};
let mut empty = picture([0; 4]);
empty.image = None;
let paragraph = |content| {
Block::Paragraph(Paragraph {
runs: vec![Run {
content: vec![content],
..Run::default()
}],
..Paragraph::empty()
})
};
let object = Content::Object {
width: Length::ZERO,
height: Length::ZERO,
picture: Some(Box::new(empty)),
extent: Some(Length::ZERO),
};
let mut floating_picture = picture([0; 4]);
floating_picture.image = None;
let text_box = crate::floating::Floating {
blocks: vec![paragraph(object)],
..crate::floating::Floating::default()
};
let drawn = crate::floating::Floating {
picture: Some(floating_picture),
..crate::floating::Floating::default()
};
let mut blocks = vec![
paragraph(Content::Floating(Box::new(text_box))),
paragraph(Content::Floating(Box::new(drawn))),
];
super::attach_images(&mut blocks, |id| {
(id == "rId1").then(|| Image::new(vec![0xFF, 0xD8, 0xFF]))
});
let floating = |index: usize| {
let Block::Paragraph(outer) = &blocks[index] else {
panic!("no paragraph");
};
let Content::Floating(floating) = &outer.runs[0].content[0] else {
panic!("no floating drawing");
};
floating.clone()
};
let picture_of_drawing = floating(1).picture.unwrap();
assert!(picture_of_drawing.image.is_some());
let text_box = floating(0);
let Block::Paragraph(inner) = &text_box.blocks[0] else {
panic!("no paragraph in the text box");
};
let Content::Object {
picture: Some(picture),
..
} = &inner.runs[0].content[0]
else {
panic!("no picture");
};
assert!(picture.image.is_some());
}
}