use f_office_drawingml::color::on_white;
use f_office_drawingml::shape::{Geometry, outside_ring, picture_clip_path, picture_outside_ring};
use f_office_drawingml::{Feature as DrawingMlFeature, Warning as DrawingMlWarning};
use f_office_effects::{MaskFormat, MaskSource};
use f_office_emf::{Drawing, FontHeight, Frame, Horizontal, Text, Vertical};
use f_office_paint::{
Clip, FillRule, Glyph as PaintGlyph, GlyphRun, Group, GroupClip, GroupPlaces, ImageFormat,
Item, Opacity, PathCommand, PathItem, Point, Rect, Rgb, Turn,
};
use f_office_units::{Edges, Length};
use super::{Layout, decisions};
use crate::FamilyName;
use crate::picture::Picture;
use crate::props::{FontRef, RunProps};
use crate::text::FaceIndex;
use crate::params::METAFILE_BOLD_WEIGHT as BOLD_WEIGHT;
impl Layout<'_> {
pub(super) fn picture_items(&mut self, picture: &Picture, x: Length, top: Length) -> Vec<Item> {
self.picture_items_in(picture, x, top, None)
}
pub(super) fn picture_items_in(
&mut self,
picture: &Picture,
x: Length,
top: Length,
cut: Option<PictureCut>,
) -> Vec<Item> {
let line = self.picture_line(picture, x, top);
let mut items = self.picture_shadow(picture, (x, top), line.as_ref());
items.extend(self.picture_glow(picture, (x, top), line.as_ref()));
items.extend(self.picture_reflection(picture, (x, top)));
let (image, baked_line) = if let Some(soft_edge) = picture.soft_edge.as_deref() {
if let Some(feathered) = self.picture_soft_edge(picture, (x, top), soft_edge.radius) {
(vec![feathered], true)
} else {
self.output.warnings.push(crate::Warning::DrawingMl {
part: soft_edge.part.clone(),
warning: DrawingMlWarning::FeatureNotSupported {
feature: DrawingMlFeature::SoftEdge,
},
});
(self.picture_image(picture, x, top), false)
}
} else {
(self.picture_image(picture, x, top), false)
};
let image = if !baked_line
&& !image.is_empty()
&& let Some((commands, fill_rule)) = picture.clip_path(x, top)
{
vec![Item::Group(Group {
items: image,
clip: Some(GroupClip {
commands,
fill_rule,
}),
places: GroupPlaces::Own,
})]
} else {
image
};
match cut.zip(picture.drawn_bounds(x, top)) {
Some((cut, bounds)) => items.extend(clipped_to(image, bounds, cut)),
None => items.extend(image),
}
if !baked_line {
items.extend(line);
}
items
}
fn picture_soft_edge(
&self,
picture: &Picture,
(x, top): (Length, Length),
radius: Length,
) -> Option<Item> {
let image = picture.image.as_ref()?;
let format = mask_format(image.format)?;
let shown = picture.shown(x, top)?;
let border = decisions::picture_line(&self.context.quirks, || {
let (rgb, alpha, width) = picture
.line
.as_ref()?
.resolve(&self.shaper.theme().shapes)?;
Some((on_white(rgb, alpha), width))
});
let clip = picture_clip_path(&picture.geometry, shown);
let bytes = image.load_bytes()?;
super::shadow::soft_edge_picture(super::shadow::SoftEdgePlacement {
format,
data: &bytes,
shown,
crop: picture.crop,
border,
clip,
opacity: picture.opacity,
color: picture.color.clone(),
turn: picture.turn,
radius,
})
}
fn picture_shadow(
&mut self,
picture: &Picture,
(x, top): (Length, Length),
line: Option<&Item>,
) -> Vec<Item> {
let Some(shadow) = picture.shadow.as_deref() else {
return Vec::new();
};
let glow_radius = picture
.glow
.as_deref()
.map_or(Length::ZERO, |glow| glow.glow.radius);
let theme = &self.shaper.theme().shapes;
let cast = decisions::picture_shadow(&self.context.quirks, || {
let color = shadow.shadow.color(theme)?;
if opaque_picture(picture) {
let frame = opaque_picture_frame(picture, (x, top), line)?;
return super::shadow::items_with_glow(
shadow.shadow.blur,
shadow.shadow.offset(),
color,
glow_radius,
&frame,
);
}
let (covered, placement) = picture_mask_placement(picture, (x, top))?;
super::shadow::masked_picture_with_glow(
covered,
line,
placement,
shadow.shadow.offset(),
shadow.shadow.blur,
glow_radius,
color,
)
.map(|item| vec![item])
})
.flatten();
cast.unwrap_or_else(|| {
self.output.warnings.push(crate::Warning::DrawingMl {
part: shadow.part.clone(),
warning: DrawingMlWarning::FeatureNotSupported {
feature: DrawingMlFeature::Shadow,
},
});
Vec::new()
})
}
fn picture_glow(
&mut self,
picture: &Picture,
(x, top): (Length, Length),
line: Option<&Item>,
) -> Vec<Item> {
let Some(glow) = picture.glow.as_deref() else {
return Vec::new();
};
let theme = &self.shaper.theme().shapes;
let cast = decisions::picture_shadow(&self.context.quirks, || {
let color = glow.glow.color(theme)?;
if opaque_picture(picture) {
let frame = opaque_picture_frame(picture, (x, top), line)?;
return super::shadow::glow_items(glow.glow.radius, color, &frame);
}
let (covered, placement) = picture_mask_placement(picture, (x, top))?;
super::shadow::masked_picture_glow(covered, line, placement, glow.glow.radius, color)
.map(|item| vec![item])
})
.flatten();
cast.unwrap_or_else(|| {
self.output.warnings.push(crate::Warning::DrawingMl {
part: glow.part.clone(),
warning: DrawingMlWarning::FeatureNotSupported {
feature: DrawingMlFeature::Glow,
},
});
Vec::new()
})
}
fn picture_reflection(
&mut self,
picture: &Picture,
(x, top): (Length, Length),
) -> Option<Item> {
let reflection = picture.reflection.as_deref()?;
let cast = decisions::picture_shadow(&self.context.quirks, || {
let image = picture.image.as_ref()?;
let format = mask_format(image.format)?;
let shown = picture.shown(x, top)?;
let border = decisions::picture_line(&self.context.quirks, || {
let (rgb, alpha, width) = picture
.line
.as_ref()?
.resolve(&self.shaper.theme().shapes)?;
Some((on_white(rgb, alpha), width))
});
let clip = picture_clip_path(&picture.geometry, shown);
let bytes = image.load_bytes()?;
super::shadow::picture_reflection_item(super::shadow::PictureReflectionPlacement {
format,
data: &bytes,
shown,
crop: picture.crop,
border,
clip,
opacity: picture.opacity,
color: picture.color.clone(),
turn: picture.turn,
reflection: reflection.reflection,
})
})
.flatten();
if cast.is_none() {
self.output.warnings.push(crate::Warning::DrawingMl {
part: reflection.part.clone(),
warning: DrawingMlWarning::FeatureNotSupported {
feature: DrawingMlFeature::Reflection,
},
});
}
cast
}
fn picture_line(&self, picture: &Picture, x: Length, top: Length) -> Option<Item> {
decisions::picture_line(&self.context.quirks, || {
let (rgb, alpha, width) = picture
.line
.as_ref()?
.resolve(&self.shaper.theme().shapes)?;
let color = on_white(rgb, alpha);
if picture.geometry == Geometry::Rect {
let ring = outside_ring(picture.covered(x, top)?, width, color);
return picture.turned_line(x, top, ring);
}
let mut ring =
picture_outside_ring(&picture.geometry, picture.shown(x, top)?, width, color)?;
if let Item::Path(path) = &mut ring {
picture.turn_commands(x, top, &mut path.commands)?;
}
Some(ring)
})
}
fn picture_image(&mut self, picture: &Picture, x: Length, top: Length) -> Vec<Item> {
let metafile = picture
.image
.as_ref()
.filter(|image| matches!(image.format, ImageFormat::Emf | ImageFormat::Wmf));
let drawings = metafile
.zip(picture.whole(x, top))
.and_then(|(image, whole)| {
let frame = Frame {
x: whole.left,
y: whole.top,
width: whole.width(),
height: whole.height(),
};
let bytes = image.load_bytes()?;
let played = if image.format == ImageFormat::Wmf {
f_office_emf::play_wmf(&bytes, frame)
} else {
f_office_emf::play(&bytes, frame)
};
played.map(|played| played.value)
});
let Some(drawings) = drawings else {
return picture.item(x, top).into_iter().collect();
};
let clip = metafile
.filter(|image| image.format == ImageFormat::Emf)
.and_then(|_| picture.shown(x, top))
.map(|shown| GroupClip::rect(shown.left, shown.top, shown.width(), shown.height()));
vec![Item::Group(Group {
items: self.metafile_items(drawings),
clip,
places: GroupPlaces::Own,
})]
}
fn metafile_items(&mut self, drawings: Vec<Drawing>) -> Vec<Item> {
let mut items = Vec::with_capacity(drawings.len());
for drawing in drawings {
match drawing {
Drawing::Item(item) => items.push(item),
Drawing::Text(text) => items.extend(self.metafile_text(&text)),
Drawing::Clipped(clipped) => items.push(Item::Group(Group {
items: self.metafile_items(clipped.drawings),
clip: Some(clipped.clip),
places: GroupPlaces::Own,
})),
}
}
items
}
fn metafile_text(&mut self, text: &Text) -> Vec<Item> {
let bold = text.weight >= BOLD_WEIGHT;
let family = self.metafile_family(text, bold);
let props = RunProps {
font_ascii: Some(FontRef::Name(family.clone())),
font_hansi: Some(FontRef::Name(family)),
bold: Some(bold),
italic: Some(text.italic),
size: Some(1),
..RunProps::default()
};
let Some(face) = self.shaper.line_face(&props) else {
return Vec::new();
};
let Some(&found) = self.shaper.faces().get(face) else {
return Vec::new();
};
let metrics = found.metrics;
let per_em = i64::from(metrics.units_per_em.max(1));
let (ascent, descent) = (i64::from(metrics.hhea_ascender), i64::from(metrics.descent));
let em = match text.height {
FontHeight::Em(em) => em,
FontHeight::Cell(cell) => {
f_office_units::div_round(cell * per_em, (ascent + descent).max(1))
}
};
let scaled = |font_units: i64| f_office_units::div_round(font_units * em, per_em);
let baseline = match text.align.vertical {
Vertical::Baseline => text.y,
Vertical::Top => {
text.y
+ decisions::metafile_top_ascent(
&self.context.quirks,
|| scaled(ascent),
|| self.logical_pixel_ascent(text, face),
)
}
Vertical::Bottom => text.y - scaled(descent),
};
let (start, total, placed) =
self.place_metafile_glyphs(text, face, found.font, baseline, |font_units| {
f_office_units::div_round(font_units * em, per_em)
});
let Some(placed) = placed else {
return Vec::new();
};
let mut out = Vec::new();
let origin = (text.x, text.y);
if let Some(bg) = text.background
&& total > 0
{
out.push(turned_box(
text.turn,
origin,
(start, baseline - scaled(ascent)),
(start + total, baseline + scaled(descent)),
bg,
));
}
out.push(Item::Glyphs(GlyphRun {
font: found.font,
size: Length::from_units(em),
color: text.color,
text: text.text.clone(),
glyphs: placed,
outline: None,
filled: true,
effect: false,
turn: text.turn,
}));
if text.strikeout && total > 0 {
let top = baseline - scaled(i64::from(metrics.strikeout_position));
let thick = scaled(i64::from(metrics.strikeout_thickness)).max(1);
out.push(turned_box(
text.turn,
origin,
(start, top),
(start + total, top + thick),
text.color,
));
}
out
}
fn place_metafile_glyphs(
&mut self,
text: &Text,
face: FaceIndex,
font: f_office_fonts::FontId,
baseline: i64,
scaled: impl Fn(i64) -> i64,
) -> (i64, i64, Option<Vec<PaintGlyph>>) {
let chars: Vec<(usize, char)> = text.text.char_indices().collect();
let glyphs: Vec<(u32, i64)> = chars
.iter()
.enumerate()
.map(|(index, (_, ch))| {
let id = self.shaper.glyph(face, *ch).map_or(0, |g| g.id);
let own = self
.shaper
.font_advance(font, id)
.map_or(0, |advance| scaled(i64::from(advance)));
let advance = text
.advances
.as_ref()
.and_then(|list| list.get(index).copied())
.unwrap_or(own);
(id, advance)
})
.collect();
let total: i64 = glyphs.iter().map(|(_, advance)| advance).sum();
let start = match text.align.horizontal {
Horizontal::Left => text.x,
Horizontal::Center => text.x - total / 2,
Horizontal::Right => text.x - total,
};
let mut x = start;
let mut placed = Vec::with_capacity(chars.len());
for ((id, advance), (index, ch)) in glyphs.iter().zip(&chars) {
let end = index + ch.len_utf8();
let (x_turned, y_turned) = turned(text.turn, (text.x, text.y), (x, baseline));
let (Ok(text_start), Ok(text_end)) = (u32::try_from(*index), u32::try_from(end)) else {
return (start, total, None);
};
placed.push(PaintGlyph {
id: *id,
x: Length::from_units(x_turned),
y: Length::from_units(y_turned),
text_start,
text_end,
});
x += advance;
}
(start, total, Some(placed))
}
fn logical_pixel_ascent(&self, text: &Text, face: FaceIndex) -> Option<i64> {
let FontHeight::Em(em) = text.height else {
return None;
};
let pels = u16::try_from(text.logical_height).ok()?;
let (ascent, _) = self.shaper.whole_pixel_heights(face, pels)?;
Some(f_office_units::div_round(
ascent * em,
i64::from(pels.max(1)),
))
}
fn metafile_family(&self, text: &Text, bold: bool) -> String {
let fonts = self.shaper.fonts();
let own = FamilyName::new(text.face.as_str());
if fonts.face(&own, bold, text.italic).is_some() {
return text.face.clone();
}
fonts
.metafile_face(&own, text.charset, text.pitch_and_family)
.map_or_else(|| text.face.clone(), |mapped| mapped.as_str().to_owned())
}
}
fn turned_box(
turn: Option<Turn>,
origin: (i64, i64),
(left, top): (i64, i64),
(right, bottom): (i64, i64),
color: Rgb,
) -> Item {
let pt = |x: i64, y: i64| {
let (tx, ty) = turned(turn, origin, (x, y));
Point {
x: Length::from_units(tx),
y: Length::from_units(ty),
}
};
Item::Path(PathItem {
commands: vec![
PathCommand::MoveTo(pt(left, top)),
PathCommand::LineTo(pt(right, top)),
PathCommand::LineTo(pt(right, bottom)),
PathCommand::LineTo(pt(left, bottom)),
PathCommand::Close,
],
color,
fill_rule: FillRule::NonZero,
})
}
fn turned(turn: Option<Turn>, origin: (i64, i64), (x, y): (i64, i64)) -> (i64, i64) {
let Some(turn) = turn else {
return (x, y);
};
let (along, down) = (x - origin.0, y - origin.1);
let step = |across: i32, downward: i32| {
f_office_units::div_round(
along * i64::from(across) + down * i64::from(downward),
i64::from(Turn::SCALE),
)
};
(
origin.0 + step(turn.xx, turn.xy),
origin.1 + step(turn.yx, turn.yy),
)
}
#[cfg(test)]
mod tests;
fn opaque_picture(picture: &Picture) -> bool {
let Some(image) = picture.image.as_ref() else {
return false;
};
let crop = picture.crop;
opaque_image_file(image)
&& picture.opacity == Opacity::FULL
&& [crop.left, crop.top, crop.right, crop.bottom]
.iter()
.all(|share| *share >= 0)
&& picture.turn.is_none_or(|turn| turn.xx == 0 || turn.xy == 0)
}
fn opaque_image_file(image: &f_office_paint::Image) -> bool {
match image.format {
ImageFormat::Jpeg => true,
ImageFormat::Png => {
if let Some(prefix) = image.load_prefix(crate::params::IMAGE_HEADER_PREFIX_BYTES)
&& (f_office_paint::image_header::png_header_complete(&prefix)
|| prefix.len() < crate::params::IMAGE_HEADER_PREFIX_BYTES)
&& let Some(clear) = f_office_paint::image_header::png_can_be_clear(&prefix)
{
return !clear;
}
image.load_bytes().is_some_and(|bytes| {
f_office_paint::image_header::png_can_be_clear(&bytes) == Some(false)
})
}
_ => false,
}
}
fn mask_format(format: ImageFormat) -> Option<MaskFormat> {
match format {
ImageFormat::Png => Some(MaskFormat::Png),
ImageFormat::Jpeg => Some(MaskFormat::Jpeg),
ImageFormat::Gif => Some(MaskFormat::Gif),
ImageFormat::Bmp => Some(MaskFormat::Bmp),
ImageFormat::Tiff => Some(MaskFormat::Tiff),
ImageFormat::Emf | ImageFormat::Wmf | ImageFormat::EffectPicture | ImageFormat::Unknown => {
None
}
}
}
fn picture_mask_source(picture: &Picture) -> Option<MaskSource> {
let image = picture.image.as_ref()?;
if opaque_image_file(image) {
return Some(MaskSource::Opaque);
}
let format = mask_format(image.format)?;
let bytes = image.load_bytes()?;
Some(MaskSource::Image {
format,
data: bytes.to_vec(),
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PictureCut {
Line(Length, Length),
Box(Edges<Length>),
}
impl PictureCut {
const fn down(self) -> (Length, Length) {
match self {
Self::Line(top, bottom) => (top, bottom),
Self::Box(edges) => (edges.top, edges.bottom),
}
}
fn across(self, from: Length, to: Length) -> (Length, Length) {
match self {
Self::Line(..) => (from, to),
Self::Box(edges) => (from.max(edges.left), to.min(edges.right)),
}
}
pub(super) fn moved(self, (top, bottom): (Length, Length)) -> Self {
match self {
Self::Line(above, below) => Self::Line(above + top, below + bottom),
Self::Box(_) => self,
}
}
}
fn clipped_to(items: Vec<Item>, bounds: Edges<Length>, cut: PictureCut) -> Vec<Item> {
let (top, bottom) = cut.down();
let (left, right) = cut.across(bounds.left, bounds.right);
let inside = bounds.top >= top && bounds.bottom <= bottom;
if inside && (left, right) == (bounds.left, bounds.right) {
return items;
}
let rect = |left: Length, top: Length, right: Length, bottom: Length| {
GroupClip::rect(
left,
top,
(right - left).max(Length::ZERO),
(bottom - top).max(Length::ZERO),
)
};
items
.into_iter()
.map(|item| match item {
Item::Image(image) if image.turn.is_none() => {
let shown = rect(left, top.max(bounds.top), right, bottom.min(bounds.bottom));
Item::Group(Group::of_page(vec![Item::Image(image)], shown))
}
Item::Image(mut image) => {
let (clip_left, clip_right, clip_top, clip_bottom) = match image.clip {
Some(clip) => {
let (clip_left, clip_right) = cut.across(clip.x, clip.x + clip.width);
(
clip_left,
clip_right,
clip.y.max(top),
(clip.y + clip.height).min(bottom),
)
}
None => (left, right, top, bottom),
};
image.clip = Some(Clip {
x: clip_left,
y: clip_top,
width: (clip_right - clip_left).max(Length::ZERO),
height: (clip_bottom - clip_top).max(Length::ZERO),
});
Item::Image(image)
}
Item::Group(_) => Item::Group(Group {
items: vec![item],
clip: Some(rect(left, top, right, bottom)),
places: GroupPlaces::Own,
}),
other => other,
})
.collect()
}
fn opaque_picture_frame(
picture: &Picture,
(x, top): (Length, Length),
line: Option<&Item>,
) -> Option<Vec<Item>> {
let frame = if let Some((commands, fill_rule)) = picture.clip_path(x, top) {
Item::Path(PathItem {
commands,
fill_rule,
color: Rgb::default(),
})
} else {
let covered = picture.covered(x, top)?;
Item::Rect(Rect {
x: covered.left,
y: covered.top,
width: covered.width(),
height: covered.height(),
color: Rgb::default(),
})
};
Some(std::iter::once(frame).chain(line.cloned()).collect())
}
fn picture_mask_placement(
picture: &Picture,
(x, top): (Length, Length),
) -> Option<(Edges<Length>, super::shadow::MaskPlacement)> {
let source = picture_mask_source(picture)?;
let covered = picture.drawn_bounds(x, top)?;
let corners = picture.turned_whole_corners(x, top)?;
let placement = super::shadow::MaskPlacement {
source,
opacity: picture.opacity,
corners,
crop: picture.crop,
};
Some((covered, placement))
}