use f_office_paint::{ColorEffect, Opacity, Rgb};
use f_office_units::scale::{FULL_TURN, QUARTER_TURN};
use f_office_units::{Length, fixed};
use f_office_warnings::Warnings;
use f_office_xml::{Document, NodeId};
use crate::color::{DrawColor, PlaceholderModifiers, SchemeColors, percentage};
use crate::theme::ShapeTheme;
use crate::{A, Feature, Warning, attribute_of, emus_of, integer_of};
const WHOLE_SCALE: i64 = 100_000;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OuterShadow {
pub blur: Length,
pub distance: Length,
pub direction: i64,
turns_with_shape: bool,
color: DrawColor,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShadowOffset {
pub across: Length,
pub down: Length,
}
impl ShadowOffset {
#[must_use]
pub fn of(distance: Length, direction: i64) -> Self {
let [sin, cos] = fixed::sin_cos(i128::from(direction) * fixed::ONE);
let along = |share: i128| {
let units = fixed::rounded(i128::from(distance.units()) * share, fixed::UNIT);
Length::from_units(i64::try_from(units).unwrap_or(0))
};
Self {
across: along(cos),
down: along(sin),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShadowColor {
pub rgb: Rgb,
pub opacity: Opacity,
}
impl OuterShadow {
#[must_use]
pub fn color(&self, theme: &ShapeTheme) -> Option<ShadowColor> {
let (rgb, opacity) = self.color.resolve(&theme.colors)?;
Some(ShadowColor { rgb, opacity })
}
#[must_use]
pub fn offset(&self) -> ShadowOffset {
ShadowOffset::of(self.distance, self.direction)
}
pub(crate) const fn turns_with_shape(&self) -> bool {
self.turns_with_shape
}
pub(crate) fn rotated_by(mut self, rotation: i64) -> Self {
if self.turns_with_shape && rotation != 0 {
self.direction = (self.direction + rotation).rem_euclid(FULL_TURN);
}
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Glow {
pub radius: Length,
color: DrawColor,
}
impl Glow {
#[must_use]
pub fn color(&self, theme: &ShapeTheme) -> Option<ShadowColor> {
self.color
.resolve(&theme.colors)
.map(|(rgb, opacity)| ShadowColor { rgb, opacity })
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Reflection {
pub blur: Length,
pub start_alpha: i64,
pub start_pos: i64,
pub end_alpha: i64,
pub end_pos: i64,
pub distance: Length,
turns_with_shape: bool,
}
impl Reflection {
pub(crate) const fn turns_with_shape(&self) -> bool {
self.turns_with_shape
}
}
const EFFECTS: [(&str, Feature); 8] = [
("blur", Feature::OtherEffect),
("fillOverlay", Feature::OtherEffect),
("glow", Feature::Glow),
("innerShdw", Feature::Shadow),
("outerShdw", Feature::Shadow),
("prstShdw", Feature::Shadow),
("reflection", Feature::Reflection),
("softEdge", Feature::SoftEdge),
];
pub fn effects(
doc: &Document,
props: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<OuterShadow> {
let shadow = doc
.child(props, A, "effectLst")
.and_then(|list| doc.child(list, A, "outerShdw"))
.and_then(|node| outer_shadow(doc, node, warnings).map(|shadow| (node, shadow)));
let drawn = shadow
.as_ref()
.map_or(&[][..], |(node, _)| std::slice::from_ref(node));
for feature in features(doc, props, drawn, warnings) {
warnings.push(Warning::FeatureNotSupported { feature });
}
shadow.map(|(_, shadow)| shadow)
}
enum ReadGlow {
Empty,
Drawn(Glow),
}
fn glow_of(doc: &Document, node: NodeId, warnings: &mut Warnings<Warning>) -> Option<ReadGlow> {
let radius = emus_of(doc, node, "rad", warnings).unwrap_or(Length::ZERO);
if radius < Length::ZERO {
return None;
}
if radius == Length::ZERO {
return Some(ReadGlow::Empty);
}
let color = DrawColor::read(doc, node, warnings)?;
Some(ReadGlow::Drawn(Glow { radius, color }))
}
impl ReadGlow {
fn into_option(self) -> Option<Glow> {
match self {
Self::Empty => None,
Self::Drawn(glow) => Some(glow),
}
}
}
enum ReadReflection {
Empty,
Drawn(Reflection),
}
impl ReadReflection {
fn into_option(self) -> Option<Reflection> {
match self {
Self::Empty => None,
Self::Drawn(reflection) => Some(reflection),
}
}
}
fn reflection_of(
doc: &Document,
node: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<ReadReflection> {
let pct = |name: &str, default: i64, warnings: &mut Warnings<Warning>| {
attribute_of(doc, node, name, percentage, warnings).unwrap_or(default)
};
let sx = pct("sx", WHOLE_SCALE, warnings);
let sy = pct("sy", WHOLE_SCALE, warnings);
let kx = integer_of(doc, node, "kx", warnings).unwrap_or(0);
let ky = integer_of(doc, node, "ky", warnings).unwrap_or(0);
let fade_dir = integer_of(doc, node, "fadeDir", warnings).unwrap_or(QUARTER_TURN);
let dir = integer_of(doc, node, "dir", warnings).unwrap_or(0);
let algn_ok = doc
.attribute(node, None, "algn")
.is_none_or(|a| matches!(a, "b" | "bl" | "br"));
let blur = emus_of(doc, node, "blurRad", warnings).unwrap_or(Length::ZERO);
let distance = emus_of(doc, node, "dist", warnings).unwrap_or(Length::ZERO);
let plain = sx == WHOLE_SCALE
&& sy == -WHOLE_SCALE
&& kx == 0
&& ky == 0
&& fade_dir == QUARTER_TURN
&& (distance == Length::ZERO || dir == QUARTER_TURN)
&& algn_ok;
if !plain || blur < Length::ZERO || distance < Length::ZERO {
return None;
}
let start_alpha = pct("stA", WHOLE_SCALE, warnings).clamp(0, WHOLE_SCALE);
let start_pos = pct("stPos", 0, warnings).clamp(0, WHOLE_SCALE);
let end_alpha = pct("endA", 0, warnings).clamp(0, WHOLE_SCALE);
let end_pos = pct("endPos", WHOLE_SCALE, warnings).clamp(0, WHOLE_SCALE);
if start_alpha == 0 && end_alpha == 0 {
return Some(ReadReflection::Empty);
}
let turns_with_shape = doc
.attribute(node, None, "rotWithShape")
.is_none_or(crate::boolean);
Some(ReadReflection::Drawn(Reflection {
blur,
start_alpha,
start_pos,
end_alpha,
end_pos,
distance,
turns_with_shape,
}))
}
pub(crate) fn shape_effects_of(
doc: &Document,
props: NodeId,
warnings: &mut Warnings<Warning>,
) -> (Option<OuterShadow>, Option<Glow>, Option<Reflection>) {
let list = doc.child(props, A, "effectLst");
let shadow = list
.and_then(|list| doc.child(list, A, "outerShdw"))
.and_then(|node| outer_shadow(doc, node, warnings).map(|shadow| (node, shadow)));
let glow = list
.and_then(|list| doc.child(list, A, "glow"))
.and_then(|node| glow_of(doc, node, warnings).map(|glow| (node, glow)));
let reflection = list
.and_then(|list| doc.child(list, A, "reflection"))
.and_then(|node| reflection_of(doc, node, warnings).map(|refl| (node, refl)));
let mut drawn = Vec::new();
if let Some((node, _)) = &shadow {
drawn.push(*node);
}
if let Some((node, _)) = &glow {
drawn.push(*node);
}
if let Some((node, _)) = &reflection {
drawn.push(*node);
}
for feature in features(doc, props, &drawn, warnings) {
warnings.push(Warning::FeatureNotSupported { feature });
}
(
shadow.map(|(_, shadow)| shadow),
glow.and_then(|(_, glow)| glow.into_option()),
reflection.and_then(|(_, refl)| refl.into_option()),
)
}
pub(crate) fn picture_effects_of(
doc: &Document,
props: NodeId,
warnings: &mut Warnings<Warning>,
) -> (
Option<OuterShadow>,
Option<Length>,
Option<Glow>,
Option<Reflection>,
) {
let list = doc.child(props, A, "effectLst");
let shadow = list
.and_then(|list| doc.child(list, A, "outerShdw"))
.and_then(|node| outer_shadow(doc, node, warnings).map(|shadow| (node, shadow)));
let soft_edge = list
.and_then(|list| doc.child(list, A, "softEdge"))
.and_then(|node| {
let rad = emus_of(doc, node, "rad", warnings).unwrap_or(Length::ZERO);
(rad >= Length::ZERO).then_some((node, rad))
});
let glow = list
.and_then(|list| doc.child(list, A, "glow"))
.and_then(|node| glow_of(doc, node, warnings).map(|glow| (node, glow)));
let reflection = list
.and_then(|list| doc.child(list, A, "reflection"))
.and_then(|node| reflection_of(doc, node, warnings).map(|refl| (node, refl)));
let mut drawn = Vec::new();
if let Some((node, _)) = &shadow {
drawn.push(*node);
}
if let Some((node, _)) = &soft_edge {
drawn.push(*node);
}
if let Some((node, _)) = &glow {
drawn.push(*node);
}
if let Some((node, _)) = &reflection {
drawn.push(*node);
}
for feature in features(doc, props, &drawn, warnings) {
warnings.push(Warning::FeatureNotSupported { feature });
}
let radius = soft_edge.and_then(|(_, rad)| (rad > Length::ZERO).then_some(rad));
(
shadow.map(|(_, shadow)| shadow),
radius,
glow.and_then(|(_, glow)| glow.into_option()),
reflection.and_then(|(_, refl)| refl.into_option()),
)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ThemeShadow {
blur: Length,
distance: Length,
direction: i64,
turns_with_shape: bool,
color: ThemeShadowColor,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum ThemeShadowColor {
Fixed(DrawColor),
Placeholder(PlaceholderModifiers),
}
impl ThemeShadow {
pub(crate) fn resolve(&self, reference_color: Option<&DrawColor>) -> Option<OuterShadow> {
let color = match &self.color {
ThemeShadowColor::Fixed(color) => color.clone(),
ThemeShadowColor::Placeholder(modifiers) => {
reference_color?.clone().in_place_of(*modifiers)
}
};
Some(OuterShadow {
blur: self.blur,
distance: self.distance,
direction: self.direction,
turns_with_shape: self.turns_with_shape,
color,
})
}
}
fn outer_shadow_geometry(
doc: &Document,
node: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<(Length, Length, i64, bool)> {
let mut value =
|name: &str, default: i64| integer_of(doc, node, name, warnings).unwrap_or(default);
let plain = value("sx", WHOLE_SCALE) == WHOLE_SCALE
&& value("sy", WHOLE_SCALE) == WHOLE_SCALE
&& value("kx", 0) == 0
&& value("ky", 0) == 0;
let direction = value("dir", 0);
if !plain || direction < 0 {
return None;
}
let blur = emus_of(doc, node, "blurRad", warnings).unwrap_or(Length::ZERO);
let distance = emus_of(doc, node, "dist", warnings).unwrap_or(Length::ZERO);
if blur < Length::ZERO || distance < Length::ZERO {
return None;
}
let turns_with_shape = doc
.attribute(node, None, "rotWithShape")
.is_none_or(crate::boolean);
Some((blur, distance, direction, turns_with_shape))
}
fn outer_shadow(
doc: &Document,
node: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<OuterShadow> {
let (blur, distance, direction, turns_with_shape) = outer_shadow_geometry(doc, node, warnings)?;
Some(OuterShadow {
blur,
distance,
direction,
turns_with_shape,
color: DrawColor::read(doc, node, warnings)?,
})
}
pub(crate) fn effect_style(
doc: &Document,
style: NodeId,
warnings: &mut Warnings<Warning>,
) -> (Option<ThemeShadow>, bool) {
let drawn = doc
.child(style, A, "effectLst")
.and_then(|list| doc.child(list, A, "outerShdw"))
.and_then(|node| {
let (blur, distance, direction, turns_with_shape) =
outer_shadow_geometry(doc, node, warnings)?;
let color = PlaceholderModifiers::read_child(doc, node, warnings)
.map(ThemeShadowColor::Placeholder)
.or_else(|| DrawColor::read(doc, node, warnings).map(ThemeShadowColor::Fixed))?;
Some((
node,
ThemeShadow {
blur,
distance,
direction,
turns_with_shape,
color,
},
))
});
let drawn_slice = drawn
.as_ref()
.map_or(&[][..], |(node, _)| std::slice::from_ref(node));
let left_out = !features(doc, style, drawn_slice, warnings).is_empty();
(drawn.map(|(_, shadow)| shadow), left_out)
}
fn features(
doc: &Document,
props: NodeId,
drawn: &[NodeId],
warnings: &mut Warnings<Warning>,
) -> Vec<Feature> {
let mut features = Vec::new();
let listed = doc
.child(props, A, "effectLst")
.into_iter()
.flat_map(|list| doc.child_elements(list))
.filter(|effect| !drawn.contains(effect))
.filter_map(|effect| {
EFFECTS
.iter()
.find(|(name, _)| doc.is(effect, A, name))
.map(|&(_, feature)| feature)
});
let graph = doc
.child(props, A, "effectDag")
.filter(|graph| doc.child_elements(*graph).next().is_some())
.map(|_| Feature::OtherEffect);
let look = three_d(doc, props, warnings).then_some(Feature::ThreeD);
for feature in listed.chain(graph).chain(look) {
if !features.contains(&feature) {
features.push(feature);
}
}
features
}
fn three_d(doc: &Document, props: NodeId, warnings: &mut Warnings<Warning>) -> bool {
let mut value = |node: NodeId, name: &str| {
attribute_of(
doc,
node,
name,
|text| text.trim().parse::<i64>().ok(),
warnings,
)
};
let turned = doc
.child(props, A, "scene3d")
.and_then(|scene| doc.child(scene, A, "camera"))
.is_some_and(|camera| {
doc.attribute(camera, None, "prst") != Some("orthographicFront")
|| doc.child(camera, A, "rot").is_some_and(|rot| {
["lat", "lon", "rev"]
.iter()
.any(|n| value(rot, n).is_some_and(|angle| angle != 0))
})
});
let shaped = doc.child(props, A, "sp3d").is_some_and(|shape| {
let bevel = ["bevelT", "bevelB"]
.iter()
.filter_map(|name| doc.child(shape, A, name))
.any(|bevel| {
["w", "h"].iter().any(|n| {
doc.attribute(bevel, None, n).is_none()
|| value(bevel, n).is_some_and(|size| size != 0)
})
});
bevel
|| ["extrusionH", "contourW"]
.iter()
.any(|n| value(shape, n).is_some_and(|size| size != 0))
});
turned || shaped
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PictureColorEffect {
Grayscale,
Luminance {
bright: i32,
contrast: i32,
},
BiLevel {
threshold: i32,
},
Duotone {
dark: DrawColor,
light: DrawColor,
},
ColorChange {
from: DrawColor,
to: DrawColor,
use_alpha: bool,
},
}
impl PictureColorEffect {
#[must_use]
pub fn resolve(&self, scheme: &SchemeColors) -> Option<ColorEffect> {
match self {
Self::Grayscale => Some(ColorEffect::Gray709),
Self::Luminance { bright, contrast } => Some(ColorEffect::Luminance {
bright: *bright,
contrast: *contrast,
}),
Self::BiLevel { threshold } => Some(ColorEffect::BiLevel {
threshold: *threshold,
}),
Self::Duotone { dark, light } => Some(ColorEffect::Duotone {
dark: dark.resolve(scheme)?.0,
light: light.resolve(scheme)?.0,
}),
Self::ColorChange {
from,
to,
use_alpha,
} => {
let (from, _) = from.resolve(scheme)?;
let (to, opacity) = to.resolve(scheme)?;
let alpha = (opacity.share() * 255 + 50_000) / 100_000;
let to_alpha = u8::try_from(alpha.clamp(0, 255)).unwrap_or(u8::MAX);
Some(ColorEffect::ColorChange {
from,
to,
to_alpha,
use_alpha: *use_alpha,
})
}
}
}
}
pub fn picture_effects(
doc: &Document,
blip: NodeId,
warnings: &mut Warnings<Warning>,
) -> Vec<PictureColorEffect> {
let mut effects = Vec::new();
let mut unsupported = false;
for child in doc.child_elements(blip) {
let Some(element) = doc.element(child) else {
continue;
};
let name = element.name.local;
if !doc.is(child, A, name) {
continue;
}
match read_picture_effect(doc, child, name, warnings) {
ReadPictureEffect::Ignore => {}
ReadPictureEffect::Supported(effect) => effects.push(effect),
ReadPictureEffect::Unsupported => unsupported = true,
}
}
if unsupported {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::PictureEffect,
});
}
effects
}
enum ReadPictureEffect {
Ignore,
Supported(PictureColorEffect),
Unsupported,
}
fn read_picture_effect(
doc: &Document,
node: NodeId,
name: &str,
warnings: &mut Warnings<Warning>,
) -> ReadPictureEffect {
match name {
"alphaModFix" | "extLst" => ReadPictureEffect::Ignore,
"grayscl" => ReadPictureEffect::Supported(PictureColorEffect::Grayscale),
"lum" => read_lum(doc, node),
"biLevel" => read_bilevel(doc, node),
"duotone" => read_duotone(doc, node, warnings),
"clrChange" => read_clr_change(doc, node, warnings),
_ => ReadPictureEffect::Unsupported,
}
}
fn read_lum(doc: &Document, node: NodeId) -> ReadPictureEffect {
let parse = |attr: &str| match doc.attribute(node, None, attr) {
None => Some(0_i64),
Some(value) => percentage(value),
};
let (Some(bright), Some(contrast)) = (parse("bright"), parse("contrast")) else {
return ReadPictureEffect::Unsupported;
};
if bright == 0 && contrast == 0 {
return ReadPictureEffect::Ignore;
}
let clamp = |v: i64| i32::try_from(v.clamp(-100_000, 100_000)).unwrap_or(0);
ReadPictureEffect::Supported(PictureColorEffect::Luminance {
bright: clamp(bright),
contrast: clamp(contrast),
})
}
fn read_bilevel(doc: &Document, node: NodeId) -> ReadPictureEffect {
let Some(thresh) = doc.attribute(node, None, "thresh").and_then(percentage) else {
return ReadPictureEffect::Unsupported;
};
let threshold = i32::try_from(thresh.clamp(0, 100_000)).unwrap_or(0);
ReadPictureEffect::Supported(PictureColorEffect::BiLevel { threshold })
}
fn read_duotone(
doc: &Document,
node: NodeId,
warnings: &mut Warnings<Warning>,
) -> ReadPictureEffect {
let mut colors = DrawColor::read_all(doc, node, warnings).into_iter();
let (Some(dark), Some(light), None) = (colors.next(), colors.next(), colors.next()) else {
return ReadPictureEffect::Unsupported;
};
ReadPictureEffect::Supported(PictureColorEffect::Duotone { dark, light })
}
fn read_clr_change(
doc: &Document,
node: NodeId,
warnings: &mut Warnings<Warning>,
) -> ReadPictureEffect {
let from = doc
.child(node, A, "clrFrom")
.and_then(|c| DrawColor::read(doc, c, warnings));
let to = doc
.child(node, A, "clrTo")
.and_then(|c| DrawColor::read(doc, c, warnings));
let (Some(from), Some(to)) = (from, to) else {
return ReadPictureEffect::Unsupported;
};
let use_alpha = doc.attribute(node, None, "useA").is_none_or(crate::boolean);
ReadPictureEffect::Supported(PictureColorEffect::ColorChange {
from,
to,
use_alpha,
})
}
#[cfg(test)]
mod tests;