use f_office_paint::stroke::StrokeCap;
use f_office_units::Length;
use f_office_warnings::Warnings;
use f_office_xml::{Document, NodeId};
use crate::color::{DrawColor, PlaceholderModifiers, SchemeColors};
use crate::dash::{LineDash, ReadDash, read_cap, read_dash};
use crate::effect::{OuterShadow, ThemeShadow};
use crate::gradient::{ShapeFillGradient, ThemeGradient};
use crate::line_end::{LineEnds, ReadEnds, read_ends};
use crate::{A, Feature, Warning, effect, emus_of};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ShapeTheme {
pub colors: SchemeColors,
fill_colors: [Option<PlaceholderModifiers>; 3],
fill_gradients: [Option<ThemeGradient>; 3],
bg_fill_colors: [Option<PlaceholderModifiers>; 3],
bg_fill_gradients: [Option<ThemeGradient>; 3],
line_widths: [Option<Length>; 3],
line_colors: [Option<PlaceholderModifiers>; 3],
line_dashes: [Option<LineDash>; 3],
line_caps: [Option<StrokeCap>; 3],
line_ends: [Option<LineEnds>; 3],
effect_shadows: [Option<ThemeShadow>; 3],
left_out: LeftOut,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum StyleReference {
Fill(usize),
Line(usize),
LineDash(usize),
LineEnds(usize),
Effect(usize),
}
const FIRST_BACKGROUND_FILL: usize = 1001;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct LeftOut {
fills: [bool; 3],
background_fills: [bool; 3],
lines: [bool; 3],
dashed_lines: [bool; 3],
ended_lines: [bool; 3],
effects: [bool; 3],
}
impl ShapeTheme {
#[must_use]
pub fn read(doc: &Document, theme: NodeId, warnings: &mut Warnings<Warning>) -> Self {
let elements = doc.child(theme, A, "themeElements");
let colors = elements
.and_then(|node| doc.child(node, A, "clrScheme"))
.map_or_default(|scheme| SchemeColors::read(doc, scheme, warnings));
let scheme = elements.and_then(|node| doc.child(node, A, "fmtScheme"));
let styles = |list: &str, style: Option<&str>| -> Vec<NodeId> {
scheme
.and_then(|node| doc.child(node, A, list))
.map_or_default(|list| {
doc.child_elements(list)
.filter(|node| style.is_none_or(|name| doc.is(*node, A, name)))
.collect()
})
};
let lines = styles("lnStyleLst", Some("ln"));
let effect_styles = styles("effectStyleLst", Some("effectStyle"));
let line_widths = [0, 1, 2].map(|index| {
lines
.get(index)
.and_then(|node| emus_of(doc, *node, "w", warnings))
});
let line_colors = [0, 1, 2].map(|index| {
let line = *lines.get(index)?;
if !matches!(doc.attribute(line, None, "cmpd"), None | Some("sng")) {
return None;
}
let fill = doc.child(line, A, "solidFill")?;
PlaceholderModifiers::read(doc, fill, warnings)
});
let first_three = |styles: &[NodeId], left_out: fn(&Document, NodeId) -> bool| {
[0, 1, 2].map(|index| styles.get(index).is_some_and(|node| left_out(doc, *node)))
};
let (fill_colors, fill_gradients, fills_left_out) =
read_fill_styles(doc, &styles("fillStyleLst", None), warnings);
let (bg_fill_colors, bg_fill_gradients, bg_fills_left_out) =
read_fill_styles(doc, &styles("bgFillStyleLst", None), warnings);
let lines_left_out = [0, 1, 2].map(|index| {
lines.get(index).is_some() && line_colors.get(index).copied().flatten().is_none()
});
let parsed_effects = [0, 1, 2].map(|index| {
effect_styles.get(index).map_or((None, false), |&node| {
effect::effect_style(doc, node, warnings)
})
});
let [(shadow0, left0), (shadow1, left1), (shadow2, left2)] = parsed_effects;
let line_dashes = [0, 1, 2].map(|index| {
let line = *lines.get(index)?;
match read_dash(doc, line) {
ReadDash::Dashed(dash) => Some(dash),
ReadDash::Omitted | ReadDash::Solid | ReadDash::Unsupported => None,
}
});
let line_caps = [0, 1, 2].map(|index| lines.get(index).and_then(|&n| read_cap(doc, n)));
let line_ends = [0, 1, 2].map(|index| {
let line = *lines.get(index)?;
match read_ends(doc, line) {
ReadEnds::Present(ends) if ends.any() => Some(ends),
ReadEnds::Omitted | ReadEnds::Present(_) | ReadEnds::Unsupported => None,
}
});
Self {
colors,
fill_colors,
fill_gradients,
bg_fill_colors,
bg_fill_gradients,
line_widths,
line_colors,
line_dashes,
line_caps,
line_ends,
effect_shadows: [shadow0, shadow1, shadow2],
left_out: LeftOut {
fills: fills_left_out,
background_fills: bg_fills_left_out,
lines: lines_left_out,
dashed_lines: first_three(&lines, |doc, line| {
read_dash(doc, line) == ReadDash::Unsupported
}),
ended_lines: first_three(&lines, |doc, line| {
read_ends(doc, line) == ReadEnds::Unsupported
}),
effects: [left0, left1, left2],
},
}
}
pub(crate) fn fill_color(&self, index: usize, color: DrawColor) -> DrawColor {
let placeholder = if let Some(background) = index.checked_sub(FIRST_BACKGROUND_FILL - 1) {
background
.checked_sub(1)
.and_then(|slot| self.bg_fill_colors.get(slot))
.copied()
.flatten()
} else {
index
.checked_sub(1)
.and_then(|slot| self.fill_colors.get(slot))
.copied()
.flatten()
};
match placeholder {
Some(modifiers) => color.in_place_of(modifiers),
None => color,
}
}
pub(crate) fn line_color(&self, index: usize, color: DrawColor) -> DrawColor {
let placeholder = index
.checked_sub(1)
.and_then(|slot| self.line_colors.get(slot))
.copied()
.flatten();
match placeholder {
Some(modifiers) => color.in_place_of(modifiers),
None => color,
}
}
fn fill_gradient_slot(&self, index: usize) -> Option<&ThemeGradient> {
if let Some(background) = index.checked_sub(FIRST_BACKGROUND_FILL - 1) {
self.bg_fill_gradients
.get(background.checked_sub(1)?)?
.as_ref()
} else {
self.fill_gradients.get(index.checked_sub(1)?)?.as_ref()
}
}
pub(crate) fn has_fill_gradient(&self, index: usize) -> bool {
self.fill_gradient_slot(index).is_some()
}
pub(crate) fn fill_gradient(
&self,
index: usize,
color: Option<&DrawColor>,
) -> Option<ShapeFillGradient> {
self.fill_gradient_slot(index)?.resolve(color)
}
pub(crate) fn line_dash(&self, index: usize) -> Option<&LineDash> {
let slot = index.checked_sub(1)?;
self.line_dashes.get(slot)?.as_ref()
}
pub(crate) fn line_cap(&self, index: usize) -> Option<StrokeCap> {
let slot = index.checked_sub(1)?;
self.line_caps.get(slot).copied().flatten()
}
pub(crate) fn line_ends(&self, index: usize) -> Option<LineEnds> {
let slot = index.checked_sub(1)?;
self.line_ends.get(slot).copied().flatten()
}
pub(crate) fn has_effect_shadow(&self, index: usize) -> bool {
index
.checked_sub(1)
.and_then(|slot| self.effect_shadows.get(slot))
.is_some_and(Option::is_some)
}
pub(crate) fn effect_shadow(
&self,
index: usize,
color: Option<&DrawColor>,
) -> Option<OuterShadow> {
let slot = index.checked_sub(1)?;
self.effect_shadows.get(slot)?.as_ref()?.resolve(color)
}
#[must_use]
pub fn line_width(&self, index: usize) -> Option<Length> {
let index = index.checked_sub(1)?;
self.line_widths.get(index).copied().flatten()
}
#[must_use]
pub fn line_style(&self, index: usize, color: DrawColor) -> Option<(DrawColor, Length)> {
let slot = index.checked_sub(1)?;
let placeholder = self.line_colors.get(slot).copied().flatten()?;
Some((color.in_place_of(placeholder), self.line_width(index)?))
}
pub(crate) fn feature(&self, reference: StyleReference) -> Option<Feature> {
let at = |list: &[bool; 3], index: usize| {
index
.checked_sub(1)
.and_then(|index| list.get(index))
.copied()
.unwrap_or(false)
};
let LeftOut {
fills,
background_fills,
lines,
dashed_lines,
ended_lines,
effects,
} = &self.left_out;
let (left_out, feature) = match reference {
StyleReference::Fill(index) => match index.checked_sub(FIRST_BACKGROUND_FILL - 1) {
Some(background) => (at(background_fills, background), Feature::ThemeStyle),
None => (at(fills, index), Feature::ThemeStyle),
},
StyleReference::Line(index) => (at(lines, index), Feature::ThemeStyle),
StyleReference::LineDash(index) => (at(dashed_lines, index), Feature::LineDash),
StyleReference::LineEnds(index) => (at(ended_lines, index), Feature::LineEnd),
StyleReference::Effect(index) => (at(effects, index), Feature::ThemeStyle),
};
left_out.then_some(feature)
}
}
fn read_fill_styles(
doc: &Document,
list: &[NodeId],
warnings: &mut Warnings<Warning>,
) -> (
[Option<PlaceholderModifiers>; 3],
[Option<ThemeGradient>; 3],
[bool; 3],
) {
let mut parse_one = |index: usize| {
let Some(&node) = list.get(index) else {
return (None, None, false);
};
if let Some(modifiers) = PlaceholderModifiers::read(doc, node, warnings) {
return (Some(modifiers), None, false);
}
match ThemeGradient::read(doc, node) {
Some(gradient) => (None, Some(gradient), false),
None => (None, None, true),
}
};
let [(c0, g0, l0), (c1, g1, l1), (c2, g2, l2)] = [0, 1, 2].map(&mut parse_one);
([c0, c1, c2], [g0, g1, g2], [l0, l1, l2])
}
#[cfg(test)]
mod tests {
use super::{ShapeTheme, StyleReference};
use crate::{A, Feature};
use f_office_units::Length;
use f_office_warnings::Warnings;
use f_office_xml::{Document, Limits};
#[test]
fn reads_the_colors_and_line_widths_and_warns_of_a_width_that_does_not_read() {
let xml = format!(
r#"<a:theme xmlns:a="{A}"><a:themeElements><a:clrScheme><a:accent1><a:srgbClr val="4472C4"/></a:accent1></a:clrScheme><a:fmtScheme><a:lnStyleLst><a:ln w="6350"/><a:ln w="1pt"/><a:ln w="19050 "/></a:lnStyleLst></a:fmtScheme></a:themeElements></a:theme>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut warnings = Warnings::new();
let theme = ShapeTheme::read(&doc, doc.root().unwrap(), &mut warnings);
assert_eq!(theme.line_width(1), Length::from_emus(6_350));
assert_eq!(theme.line_width(2), Length::from_emus(12_700));
assert_eq!(theme.line_width(3), None);
let kinds: Vec<_> = warnings.iter().map(|(w, n)| (w.kind(), n)).collect();
assert_eq!(kinds, [("drawingml-invalid-value", 1)]);
assert_eq!((theme.line_width(0), theme.line_width(4)), (None, None));
assert_ne!(theme.colors, ShapeTheme::default().colors);
}
#[test]
fn says_which_styles_of_the_format_scheme_hold_what_it_does_not_draw() {
let plain = r#"<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>"#;
let scheme = [
format!(
r#"<a:fillStyleLst>{plain}<a:gradFill/><a:solidFill><a:schemeClr val="phClr"><a:hueMod val="50000"/></a:schemeClr></a:solidFill></a:fillStyleLst>"#
),
format!(
r#"<a:lnStyleLst><a:ln w="6350" cmpd="sng">{plain}<a:prstDash val="dash"/></a:ln><a:ln cmpd="dbl">{plain}<a:tailEnd type="triangle"/></a:ln><a:ln><a:noFill/><a:prstDash val="solid"/><a:headEnd type="none"/></a:ln></a:lnStyleLst>"#
),
"<a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw/></a:effectLst></a:effectStyle></a:effectStyleLst>".to_owned(),
format!(
r#"<a:bgFillStyleLst><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill>{plain}</a:bgFillStyleLst>"#
),
]
.concat();
let xml = format!(
r#"<a:theme xmlns:a="{A}"><a:themeElements><a:fmtScheme>{scheme}</a:fmtScheme></a:themeElements></a:theme>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let theme = ShapeTheme::read(&doc, doc.root().unwrap(), &mut Warnings::new());
let style = Some(Feature::ThemeStyle);
let cases = [
(StyleReference::Fill(0), None),
(StyleReference::Fill(1), None),
(StyleReference::Fill(2), style),
(StyleReference::Fill(3), style),
(StyleReference::Fill(4), None),
(StyleReference::Fill(1000), None),
(StyleReference::Fill(1001), style),
(StyleReference::Fill(1002), None),
(StyleReference::Line(1), None),
(StyleReference::LineDash(1), None),
(StyleReference::LineEnds(1), None),
(StyleReference::Line(2), style),
(StyleReference::LineDash(2), None),
(StyleReference::LineEnds(2), None),
(StyleReference::Line(3), style),
(StyleReference::LineDash(3), None),
(StyleReference::LineEnds(3), None),
(StyleReference::Effect(1), None),
(StyleReference::Effect(2), style),
(StyleReference::Effect(3), None),
];
for (reference, feature) in cases {
assert_eq!(theme.feature(reference), feature, "{reference:?}");
assert_eq!(ShapeTheme::default().feature(reference), None);
}
assert!(theme.line_dash(1).is_some());
assert!(theme.line_dash(2).is_none());
assert!(theme.line_ends(2).is_some_and(super::LineEnds::any));
assert!(theme.line_ends(1).is_none());
}
#[test]
fn gives_a_line_style_with_the_modifiers_of_its_placeholder_after_the_color() {
use crate::color::{DrawColor, SchemeSlot};
let fill = |modifiers: &str| {
format!(
r#"<a:solidFill><a:schemeClr val="phClr">{modifiers}</a:schemeClr></a:solidFill>"#
)
};
let lines = [
format!(
r#"<a:ln w="9525">{}</a:ln>"#,
fill(r#"<a:shade val="95000"/><a:satMod val="105000"/>"#)
),
format!(r#"<a:ln w="25400">{}</a:ln>"#, fill("")),
format!(
r#"<a:ln w="38100">{}</a:ln>"#,
fill(r#"<a:hueMod val="50000"/>"#)
),
]
.concat();
let xml = format!(
r#"<a:theme xmlns:a="{A}"><a:themeElements><a:clrScheme><a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1></a:clrScheme><a:fmtScheme><a:lnStyleLst>{lines}</a:lnStyleLst></a:fmtScheme></a:themeElements></a:theme>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let theme = ShapeTheme::read(&doc, doc.root().unwrap(), &mut Warnings::new());
let text = || DrawColor::scheme(SchemeSlot::Dark1).tinted(75_000);
let drawn = |index| {
theme.line_style(index, text()).map(|(color, width)| {
let (rgb, _) = color.resolve(&theme.colors).unwrap();
(format!("{:02X}{:02X}{:02X}", rgb.r, rgb.g, rgb.b), width)
})
};
assert_eq!(
drawn(1),
Some(("868686".to_owned(), Length::from_emus(9_525).unwrap()))
);
assert_eq!(
drawn(2),
Some(("898989".to_owned(), Length::from_emus(25_400).unwrap()))
);
assert_eq!(drawn(3), None);
assert_eq!((drawn(0), drawn(4)), (None, None));
}
}