#[cfg(doc)]
use f_office_drawingml::effect::OuterShadow;
use f_office_drawingml::effect::{ShadowColor, ShadowOffset};
use f_office_effects::{
FillRule as ShadowRule, MaskFormat, MaskSource, Outline, Picture, PictureMask, PixelLength,
Place, Scene, Segment, Shadow, Share, SoftEdge, SoftEdgeBorder,
};
use f_office_paint::{
FillRule, Image, ImageColor, ImageFormat, ImageItem, InkConversion, Item, Opacity, PathCommand,
PathItem, Point, Rect, Rgb, Turn,
};
use f_office_units::scale::DRAWING_WHOLE;
use f_office_units::{Edges, Length, div_round, div_round_i128};
use crate::params::{
SHADOW_BLUR_PIXELS, SHADOW_BLUR_SPREAD, SHADOW_BOX_ROOM, SHADOW_BOX_STEP,
SHADOW_PIXELS_PER_INCH,
};
type Filled = (Vec<PathCommand>, FillRule);
pub(super) fn items(
blur: Length,
offset: ShadowOffset,
ShadowColor { rgb, opacity }: ShadowColor,
items: &[Item],
) -> Option<Vec<Item>> {
let outlines: Vec<Filled> = items.iter().filter_map(filled).collect();
if outlines.is_empty() {
return None;
}
if blur <= Length::ZERO && opacity == Opacity::FULL {
return Some(
outlines
.into_iter()
.map(|(commands, fill_rule)| {
Item::Path(PathItem {
commands: commands.iter().map(|c| moved(*c, offset)).collect(),
color: rgb,
fill_rule,
})
})
.collect(),
);
}
let frame = picture_box(bounds(&outlines)?, offset, blur)?;
let refs: Vec<(&[PathCommand], FillRule, Length)> = outlines
.iter()
.map(|(commands, rule)| (commands.as_slice(), *rule, Length::ZERO))
.collect();
Some(vec![picture_item(
&refs,
None,
frame,
offset,
blur,
ShadowColor { rgb, opacity },
)?])
}
pub(super) struct MaskPlacement {
pub(super) source: MaskSource,
pub(super) opacity: Opacity,
pub(super) corners: [Point; 3],
pub(super) crop: Edges<i64>,
}
pub(super) fn masked_picture(
covered: Edges<Length>,
line: Option<&Item>,
mask: MaskPlacement,
offset: ShadowOffset,
blur: Length,
color: ShadowColor,
) -> Option<Item> {
let line_outline = line.and_then(filled);
let mut union = covered;
if let Some(ref outline) = line_outline
&& let Some(line_bounds) = bounds(std::slice::from_ref(outline))
{
union = Edges {
left: union.left.min(line_bounds.left),
top: union.top.min(line_bounds.top),
right: union.right.max(line_bounds.right),
bottom: union.bottom.max(line_bounds.bottom),
};
}
let frame = picture_box(union, offset, blur)?;
let refs: Vec<(&[PathCommand], FillRule, Length)> = line_outline
.iter()
.map(|(commands, rule)| (commands.as_slice(), *rule, Length::ZERO))
.collect();
picture_item(&refs, Some(mask), frame, offset, blur, color)
}
pub(super) fn stroked_picture(
commands: &[PathCommand],
fill_rule: FillRule,
stroke_width: Length,
offset: ShadowOffset,
blur: Length,
color: ShadowColor,
) -> Option<Item> {
let ink = exact_bounds(commands)?;
let half = stroke_width.max(Length::ZERO).div_toward_zero(2);
let grown = Edges {
left: ink.left - half,
top: ink.top - half,
right: ink.right + half,
bottom: ink.bottom + half,
};
let frame = picture_box(grown, offset, blur)?;
picture_item(
&[(commands, fill_rule, stroke_width.max(Length::ZERO))],
None,
frame,
offset,
blur,
color,
)
}
pub(super) struct SoftEdgePlacement<'a> {
pub(super) format: MaskFormat,
pub(super) data: &'a [u8],
pub(super) shown: Edges<Length>,
pub(super) crop: Edges<i64>,
pub(super) border: Option<(Rgb, Length)>,
pub(super) clip: Option<(Vec<PathCommand>, FillRule)>,
pub(super) opacity: Opacity,
pub(super) color: ImageColor,
pub(super) turn: Option<Turn>,
pub(super) radius: Length,
}
fn soft_edge_pixels(w_len: Length, h_len: Length) -> Option<(u32, u32)> {
if w_len <= Length::ZERO || h_len <= Length::ZERO {
return None;
}
let ppi = i128::from(SHADOW_PIXELS_PER_INCH);
let inch = i128::from(Length::UNITS_PER_INCH);
let ceil_px = |side: Length| {
let count = ((i128::from(side.units()) * ppi + inch - 1) / inch).max(1);
u32::try_from(count).ok()
};
let (w_px, h_px) = (ceil_px(w_len)?, ceil_px(h_len)?);
let bytes_per_pixel = u64::from(u32::BITS / u8::BITS);
let bytes = u64::from(w_px)
.checked_mul(u64::from(h_px))?
.checked_mul(bytes_per_pixel)?;
(bytes <= f_office_paint::MAX_DECODED_BYTES).then_some((w_px, h_px))
}
fn soft_edge_frame(shown: Edges<Length>, bw: Length) -> Option<((u32, u32), Edges<Length>)> {
let expanded = Edges {
left: shown.left.checked_sub(bw)?,
top: shown.top.checked_sub(bw)?,
right: shown.right.checked_add(bw)?,
bottom: shown.bottom.checked_add(bw)?,
};
let (w_len, h_len) = (expanded.width(), expanded.height());
let (w_px, h_px) = soft_edge_pixels(w_len, h_len)?;
let ppi = i128::from(SHADOW_PIXELS_PER_INCH);
let inch = i128::from(Length::UNITS_PER_INCH);
let px_to_len = |px: u32| {
let units = div_round_i128(i128::from(px) * inch, ppi);
i64::try_from(units).ok().map(Length::from_units)
};
let (draw_w, draw_h) = (px_to_len(w_px)?, px_to_len(h_px)?);
let draw_left = expanded.left.checked_sub((draw_w - w_len).div_round(2))?;
let draw_top = expanded.top.checked_sub((draw_h - h_len).div_round(2))?;
let placed = Edges::placed(draw_left, draw_top, draw_w, draw_h)?;
Some(((w_px, h_px), placed))
}
fn soft_edge_crop(crop: Edges<i64>) -> Option<[i32; 4]> {
if DRAWING_WHOLE - crop.left - crop.right <= 0 || DRAWING_WHOLE - crop.top - crop.bottom <= 0 {
return None;
}
Some([
i32::try_from(crop.left).ok()?,
i32::try_from(crop.top).ok()?,
i32::try_from(crop.right).ok()?,
i32::try_from(crop.bottom).ok()?,
])
}
fn soft_edge_radii(radius: Length) -> Option<(PixelLength, PixelLength)> {
let ppi = i128::from(SHADOW_PIXELS_PER_INCH);
let inch = i128::from(Length::UNITS_PER_INCH);
let parts = blur_parts(radius);
let erode_whole = (i128::from(radius.units()) * ppi / (inch * parts)) * parts;
let erode = PixelLength::ratio(i64::try_from(erode_whole).ok()?, 1)?;
let (spread, over) = SHADOW_BLUR_SPREAD;
let blur = PixelLength::ratio(
radius
.units()
.checked_mul(SHADOW_PIXELS_PER_INCH)?
.checked_mul(spread)?,
Length::UNITS_PER_INCH.checked_mul(over)?,
)?;
Some((erode, blur))
}
pub(super) fn soft_edge_picture(spec: SoftEdgePlacement<'_>) -> Option<Item> {
if spec.radius <= Length::ZERO {
return None;
}
let crop = soft_edge_crop(spec.crop)?;
let bw = spec
.border
.map_or(Length::ZERO, |(_, w)| w.max(Length::ZERO));
let ((w_px, h_px), placed) = soft_edge_frame(spec.shown, bw)?;
let (erode, blur) = soft_edge_radii(spec.radius)?;
let border = match spec.border {
Some((rgb, _)) => Some(SoftEdgeBorder {
width: PixelLength::ratio(
bw.units().checked_mul(SHADOW_PIXELS_PER_INCH)?,
Length::UNITS_PER_INCH,
)?,
color: [rgb.r, rgb.g, rgb.b],
}),
None => None,
};
let clip = match spec.clip {
Some((commands, rule)) => Some(soft_edge_clip(&commands, rule, placed, (w_px, h_px))?),
None => None,
};
let picture = Picture {
width: w_px,
height: h_px,
scene: Scene::SoftEdge(SoftEdge {
format: spec.format,
data: spec.data.to_vec(),
crop,
border,
clip,
erode,
blur,
}),
};
Some(Item::Image(ImageItem {
x: placed.left,
y: placed.top,
width: placed.width(),
height: placed.height(),
clip: None,
turn: spec.turn,
image: Image {
format: ImageFormat::EffectPicture,
data: picture.encode().into(),
opacity: spec.opacity,
color: spec.color,
inks: InkConversion::EmbeddedProfile,
},
}))
}
fn soft_edge_clip(
commands: &[PathCommand],
rule: FillRule,
placed: Edges<Length>,
(w_px, h_px): (u32, u32),
) -> Option<Outline> {
let place = |point: Point| {
let at = |value: Length, first: Length, side: Length, count: u32| {
PixelLength::ratio(
(value.units() - first.units()).checked_mul(i64::from(count))?,
side.units(),
)
};
Some(Place {
x: at(point.x, placed.left, placed.width(), w_px)?,
y: at(point.y, placed.top, placed.height(), h_px)?,
})
};
Some(Outline {
segments: segments(commands, &place)?,
rule: match rule {
FillRule::NonZero => ShadowRule::NonZero,
FillRule::EvenOdd => ShadowRule::EvenOdd,
},
stroke: PixelLength::ZERO,
})
}
fn picture_item(
outlines: &[(&[PathCommand], FillRule, Length)],
mask: Option<MaskPlacement>,
frame: Edges<Length>,
offset: ShadowOffset,
blur: Length,
ShadowColor { rgb, opacity }: ShadowColor,
) -> Option<Item> {
let parts = blur_parts(blur);
let per_inch = i128::from(SHADOW_PIXELS_PER_INCH);
let inch = i128::from(Length::UNITS_PER_INCH) * parts;
let pixels = |side: Length| {
let count = div_round_i128(i128::from(side.units()) * per_inch, inch).max(1);
u32::try_from(count).ok()
};
let size = (pixels(frame.width())?, pixels(frame.height())?);
let place = |point: Point| {
let at = |value: Length, moved: Length, first: Length, side: Length, count: u32| {
let from_first = value.units() + moved.units() - first.units();
PixelLength::ratio(from_first.checked_mul(i64::from(count))?, side.units())
};
Some(Place {
x: at(point.x, offset.across, frame.left, frame.width(), size.0)?,
y: at(point.y, offset.down, frame.top, frame.height(), size.1)?,
})
};
let inch_units = Length::UNITS_PER_INCH.checked_mul(i64::try_from(parts).ok()?)?;
let outlines = outlines
.iter()
.map(|&(commands, rule, stroke_width)| {
let stroke = if stroke_width > Length::ZERO {
PixelLength::ratio(
stroke_width.units().checked_mul(SHADOW_PIXELS_PER_INCH)?,
inch_units,
)?
} else {
PixelLength::ZERO
};
Some(Outline {
segments: segments(commands, &place)?,
rule: match rule {
FillRule::NonZero => ShadowRule::NonZero,
FillRule::EvenOdd => ShadowRule::EvenOdd,
},
stroke,
})
})
.collect::<Option<Vec<_>>>()?;
let (spread, over) = SHADOW_BLUR_SPREAD;
let sigma = PixelLength::ratio(
blur.units()
.checked_mul(SHADOW_PIXELS_PER_INCH)?
.checked_mul(spread)?,
inch_units.checked_mul(over)?,
)?;
let mask = match mask {
Some(mask) => Some(place_mask(mask, &place)?),
None => None,
};
let picture = Picture {
width: size.0,
height: size.1,
scene: Scene::Shadow(Shadow {
outlines,
mask,
blur: sigma,
color: [rgb.r, rgb.g, rgb.b],
opacity: Share::ratio(opacity.share(), DRAWING_WHOLE)?,
}),
};
Some(Item::Image(ImageItem {
x: frame.left,
y: frame.top,
width: frame.width(),
height: frame.height(),
clip: None,
turn: None,
image: Image {
format: ImageFormat::EffectPicture,
data: picture.encode().into(),
opacity: Opacity::FULL,
color: ImageColor::Original,
inks: InkConversion::EmbeddedProfile,
},
}))
}
fn place_mask(mask: MaskPlacement, place: &impl Fn(Point) -> Option<Place>) -> Option<PictureMask> {
let [origin, across, down] = mask.corners;
let crop_min = |share: i64| Share::ratio(share.clamp(0, DRAWING_WHOLE), DRAWING_WHOLE);
let crop_max = |share: i64| {
Share::ratio(
(DRAWING_WHOLE - share).clamp(0, DRAWING_WHOLE),
DRAWING_WHOLE,
)
};
Some(PictureMask {
source: mask.source,
opacity: Share::ratio(mask.opacity.share(), DRAWING_WHOLE)?,
origin: place(origin)?,
across: place(across)?,
down: place(down)?,
clip: [
crop_min(mask.crop.left)?,
crop_min(mask.crop.top)?,
crop_max(mask.crop.right)?,
crop_max(mask.crop.bottom)?,
],
})
}
fn filled(item: &Item) -> Option<Filled> {
match item {
Item::Path(path) => Some((path.commands.clone(), path.fill_rule)),
Item::Gradient(gradient) => Some((gradient.commands.clone(), gradient.fill_rule)),
Item::Rect(Rect {
x,
y,
width,
height,
..
}) => {
let corner = |dx: Length, dy: Length| Point {
x: *x + dx,
y: *y + dy,
};
let zero = Length::ZERO;
Some((
vec![
PathCommand::MoveTo(corner(zero, zero)),
PathCommand::LineTo(corner(*width, zero)),
PathCommand::LineTo(corner(*width, *height)),
PathCommand::LineTo(corner(zero, *height)),
PathCommand::Close,
],
FillRule::NonZero,
))
}
Item::Glyphs(_) | Item::Image(_) | Item::Group(_) => None,
}
}
fn moved(command: PathCommand, offset: ShadowOffset) -> PathCommand {
let to = |point: Point| Point {
x: point.x + offset.across,
y: point.y + offset.down,
};
match command {
PathCommand::MoveTo(point) => PathCommand::MoveTo(to(point)),
PathCommand::LineTo(point) => PathCommand::LineTo(to(point)),
PathCommand::QuadTo(control, point) => PathCommand::QuadTo(to(control), to(point)),
PathCommand::CubicTo(first, second, point) => {
PathCommand::CubicTo(to(first), to(second), to(point))
}
PathCommand::Close => PathCommand::Close,
}
}
fn points(command: &PathCommand) -> Vec<Point> {
match *command {
PathCommand::MoveTo(point) | PathCommand::LineTo(point) => vec![point],
PathCommand::QuadTo(control, point) => vec![control, point],
PathCommand::CubicTo(first, second, point) => vec![first, second, point],
PathCommand::Close => Vec::new(),
}
}
fn bounds(outlines: &[Filled]) -> Option<Edges<Length>> {
let mut all = outlines
.iter()
.flat_map(|(commands, _)| commands.iter().flat_map(points));
let first = all.next()?;
Some(all.fold(
Edges {
left: first.x,
top: first.y,
right: first.x,
bottom: first.y,
},
|edges, point| Edges {
left: edges.left.min(point.x),
top: edges.top.min(point.y),
right: edges.right.max(point.x),
bottom: edges.bottom.max(point.y),
},
))
}
fn exact_bounds(commands: &[PathCommand]) -> Option<Edges<Length>> {
let mut box_ = None::<Edges<Length>>;
let mut take = |x: Length, y: Length| {
box_ = Some(match box_ {
None => Edges {
left: x,
top: y,
right: x,
bottom: y,
},
Some(edges) => Edges {
left: edges.left.min(x),
top: edges.top.min(y),
right: edges.right.max(x),
bottom: edges.bottom.max(y),
},
});
};
let mut at = None;
for command in commands {
match *command {
PathCommand::MoveTo(p) | PathCommand::LineTo(p) => {
take(p.x, p.y);
at = Some(p);
}
PathCommand::QuadTo(control, end) => {
if let Some(start) = at {
if let Some(x) = super::text_path::curve_extreme([
start.x.units(),
control.x.units(),
end.x.units(),
]) {
take(Length::from_units(x), end.y);
}
if let Some(y) = super::text_path::curve_extreme([
start.y.units(),
control.y.units(),
end.y.units(),
]) {
take(end.x, Length::from_units(y));
}
}
take(end.x, end.y);
at = Some(end);
}
PathCommand::CubicTo(first, second, end) => {
for p in [first, second, end] {
take(p.x, p.y);
}
at = Some(end);
}
PathCommand::Close => {}
}
}
box_
}
fn picture_box(bounds: Edges<Length>, offset: ShadowOffset, blur: Length) -> Option<Edges<Length>> {
let step = SHADOW_BOX_STEP.units();
let grow = (blur.units().max(0) + step - 1) / step + SHADOW_BOX_ROOM;
let edge = |value: Length, moved: Length, out: i64| {
Length::from_units((div_round(value.units() + moved.units(), step) + out) * step)
};
let frame = Edges {
left: edge(bounds.left, offset.across, -grow),
top: edge(bounds.top, offset.down, -grow),
right: edge(bounds.right, offset.across, grow),
bottom: edge(bounds.bottom, offset.down, grow),
};
(frame.width() > Length::ZERO && frame.height() > Length::ZERO).then_some(frame)
}
fn blur_parts(blur: Length) -> i128 {
let span = i128::from(SHADOW_BLUR_PIXELS) * i128::from(Length::UNITS_PER_INCH);
let reach = i128::from(blur.units().max(0)) * i128::from(SHADOW_PIXELS_PER_INCH);
((reach + span - 1) / span).max(1)
}
fn segments(
commands: &[PathCommand],
place: &impl Fn(Point) -> Option<Place>,
) -> Option<Vec<Segment>> {
commands
.iter()
.map(|command| {
Some(match *command {
PathCommand::MoveTo(point) => Segment::MoveTo(place(point)?),
PathCommand::LineTo(point) => Segment::LineTo(place(point)?),
PathCommand::QuadTo(control, point) => {
Segment::QuadTo(place(control)?, place(point)?)
}
PathCommand::CubicTo(first, second, point) => {
Segment::CubicTo(place(first)?, place(second)?, place(point)?)
}
PathCommand::Close => Segment::Close,
})
})
.collect()
}
#[cfg(test)]
mod tests;