use f_office_paint::{Opacity, Rgb};
use f_office_units::scale::{DRAWING_WHOLE, THOUSANDTHS, THOUSANDTHS_DIGITS};
use f_office_warnings::Warnings;
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
use crate::{A, Feature, Warning, attribute_of, case_of, element_name};
const SLOTS: [&str; 12] = [
"dk1", "lt1", "dk2", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6",
"hlink", "folHlink",
];
const SCHEME: &Values<Option<usize>> = &Values::new(&[
own("dk1", Some(0)),
own("lt1", Some(1)),
own("dk2", Some(2)),
own("lt2", Some(3)),
own("accent1", Some(4)),
own("accent2", Some(5)),
own("accent3", Some(6)),
own("accent4", Some(7)),
own("accent5", Some(8)),
own("accent6", Some(9)),
own("hlink", Some(10)),
own("folHlink", Some(11)),
own("tx1", Some(0)),
own("bg1", Some(1)),
own("tx2", Some(2)),
own("bg2", Some(3)),
another("phClr", None),
]);
const PRESET_COLORS: [&str; 190] = [
"aliceBlue",
"antiqueWhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"black",
"blanchedAlmond",
"blue",
"blueViolet",
"brown",
"burlyWood",
"cadetBlue",
"chartreuse",
"chocolate",
"coral",
"cornflowerBlue",
"cornsilk",
"crimson",
"cyan",
"darkBlue",
"darkCyan",
"darkGoldenrod",
"darkGray",
"darkGrey",
"darkGreen",
"darkKhaki",
"darkMagenta",
"darkOliveGreen",
"darkOrange",
"darkOrchid",
"darkRed",
"darkSalmon",
"darkSeaGreen",
"darkSlateBlue",
"darkSlateGray",
"darkSlateGrey",
"darkTurquoise",
"darkViolet",
"dkBlue",
"dkCyan",
"dkGoldenrod",
"dkGray",
"dkGrey",
"dkGreen",
"dkKhaki",
"dkMagenta",
"dkOliveGreen",
"dkOrange",
"dkOrchid",
"dkRed",
"dkSalmon",
"dkSeaGreen",
"dkSlateBlue",
"dkSlateGray",
"dkSlateGrey",
"dkTurquoise",
"dkViolet",
"deepPink",
"deepSkyBlue",
"dimGray",
"dimGrey",
"dodgerBlue",
"firebrick",
"floralWhite",
"forestGreen",
"fuchsia",
"gainsboro",
"ghostWhite",
"gold",
"goldenrod",
"gray",
"grey",
"green",
"greenYellow",
"honeydew",
"hotPink",
"indianRed",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderBlush",
"lawnGreen",
"lemonChiffon",
"lightBlue",
"lightCoral",
"lightCyan",
"lightGoldenrodYellow",
"lightGray",
"lightGrey",
"lightGreen",
"lightPink",
"lightSalmon",
"lightSeaGreen",
"lightSkyBlue",
"lightSlateGray",
"lightSlateGrey",
"lightSteelBlue",
"lightYellow",
"ltBlue",
"ltCoral",
"ltCyan",
"ltGoldenrodYellow",
"ltGray",
"ltGrey",
"ltGreen",
"ltPink",
"ltSalmon",
"ltSeaGreen",
"ltSkyBlue",
"ltSlateGray",
"ltSlateGrey",
"ltSteelBlue",
"ltYellow",
"lime",
"limeGreen",
"linen",
"magenta",
"maroon",
"medAquamarine",
"medBlue",
"medOrchid",
"medPurple",
"medSeaGreen",
"medSlateBlue",
"medSpringGreen",
"medTurquoise",
"medVioletRed",
"mediumAquamarine",
"mediumBlue",
"mediumOrchid",
"mediumPurple",
"mediumSeaGreen",
"mediumSlateBlue",
"mediumSpringGreen",
"mediumTurquoise",
"mediumVioletRed",
"midnightBlue",
"mintCream",
"mistyRose",
"moccasin",
"navajoWhite",
"navy",
"oldLace",
"olive",
"oliveDrab",
"orange",
"orangeRed",
"orchid",
"paleGoldenrod",
"paleGreen",
"paleTurquoise",
"paleVioletRed",
"papayaWhip",
"peachPuff",
"peru",
"pink",
"plum",
"powderBlue",
"purple",
"red",
"rosyBrown",
"royalBlue",
"saddleBrown",
"salmon",
"sandyBrown",
"seaGreen",
"seaShell",
"sienna",
"silver",
"skyBlue",
"slateBlue",
"slateGray",
"slateGrey",
"snow",
"springGreen",
"steelBlue",
"tan",
"teal",
"thistle",
"tomato",
"turquoise",
"violet",
"wheat",
"white",
"whiteSmoke",
"yellow",
"yellowGreen",
];
const PRESET: &Values<Option<[u8; 3]>> = &Values::with_others(
&[
own("black", Some([0, 0, 0])),
own("white", Some([255, 255, 255])),
own("red", Some([255, 0, 0])),
own("green", Some([0, 128, 0])),
own("blue", Some([0, 0, 255])),
own("yellow", Some([255, 255, 0])),
own("gray", Some([128, 128, 128])),
own("grey", Some([128, 128, 128])),
own("darkGray", Some([169, 169, 169])),
own("darkGrey", Some([169, 169, 169])),
own("lightGray", Some([211, 211, 211])),
own("lightGrey", Some([211, 211, 211])),
],
&PRESET_COLORS,
None,
);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SchemeColors([Option<Rgb>; 12]);
impl SchemeColors {
#[must_use]
pub fn read(doc: &Document, scheme: NodeId, warnings: &mut Warnings<Warning>) -> Self {
Self(SLOTS.map(|name| {
let slot = doc.child(scheme, A, name)?;
doc.child_elements(slot).find_map(|node| {
match base(doc, node, ColorNames::DrawingMl, warnings) {
Some(Base::Rgb(rgb)) => Some(rgb),
_ => None,
}
})
}))
}
#[must_use]
pub fn get(&self, slot: SchemeSlot) -> Option<Rgb> {
self.0.get(slot as usize).copied().flatten()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SchemeSlot {
Dark1,
Light1,
Dark2,
Light2,
Accent1,
Accent2,
Accent3,
Accent4,
Accent5,
Accent6,
Hyperlink,
FollowedHyperlink,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LightnessStep {
Tint(u8),
Shade(u8),
}
impl LightnessStep {
#[must_use]
pub fn apply(self, rgb: Rgb) -> Rgb {
let whole = i64::from(u8::MAX);
let channels = [rgb.r, rgb.g, rgb.b].map(|c| i64::from(c) * MILLI);
let channels = with_lightness(channels, |l| match self {
Self::Tint(kept) => {
let kept = i64::from(kept);
l * kept / whole + LIGHTNESS * (whole - kept) / whole
}
Self::Shade(kept) => l * i64::from(kept) / whole,
});
let [r, g, b] =
channels.map(|c| u8::try_from((c / MILLI).clamp(0, whole)).unwrap_or(u8::MAX));
Rgb { r, g, b }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DrawColor {
base: Base,
modifiers: Vec<Modifier>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ColorNames {
DrawingMl,
Word2010,
}
impl ColorNames {
const fn elements(self) -> &'static str {
match self {
Self::DrawingMl => A,
Self::Word2010 => WORD_2010,
}
}
const fn values(self) -> Option<&'static str> {
match self {
Self::DrawingMl => None,
Self::Word2010 => Some(WORD_2010),
}
}
}
pub(crate) const WORD_2010: &str = "http://schemas.microsoft.com/office/word/2010/wordml";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Base {
Rgb(Rgb),
Scheme(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Modifier {
LumMod(i64),
LumOff(i64),
Shade(i64),
Tint(i64),
Alpha(i64),
SatMod(i64),
Gamma,
InvGamma,
}
const MOST_PLACEHOLDER_MODIFIERS: usize = 4;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlaceholderModifiers([Option<Modifier>; MOST_PLACEHOLDER_MODIFIERS]);
impl PlaceholderModifiers {
pub(crate) fn read(
doc: &Document,
fill: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<Self> {
doc.is(fill, A, "solidFill")
.then(|| Self::read_child(doc, fill, warnings))
.flatten()
}
pub(crate) fn read_child(
doc: &Document,
parent: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<Self> {
let mut colors = doc.child_elements(parent);
let color = match (colors.next(), colors.next()) {
(Some(color), None)
if doc.is(color, A, "schemeClr")
&& doc.attribute(color, None, "val") == Some("phClr") =>
{
color
}
_ => return None,
};
let mut found = [None; MOST_PLACEHOLDER_MODIFIERS];
let mut count = 0;
for child in doc.child_elements(color) {
if changes_unread(doc, child, ColorNames::DrawingMl, warnings) {
return None;
}
if let Some(modifier) = modifier(doc, child, ColorNames::DrawingMl, warnings) {
*found.get_mut(count)? = Some(modifier);
count += 1;
}
}
Some(Self(found))
}
}
impl DrawColor {
#[must_use]
pub fn rgb(rgb: Rgb) -> Self {
Self {
base: Base::Rgb(rgb),
modifiers: Vec::new(),
}
}
#[must_use]
pub fn scheme(slot: SchemeSlot) -> Self {
Self {
base: Base::Scheme(slot as usize),
modifiers: Vec::new(),
}
}
#[must_use]
pub fn shaded(mut self, kept: i64) -> Self {
self.modifiers.push(Modifier::Shade(kept));
self
}
#[must_use]
pub fn tinted(mut self, kept: i64) -> Self {
self.modifiers.push(Modifier::Tint(kept));
self
}
#[must_use]
pub fn in_place_of(mut self, placeholder: PlaceholderModifiers) -> Self {
self.modifiers.extend(placeholder.0.into_iter().flatten());
self
}
#[must_use]
pub fn read(doc: &Document, parent: NodeId, warnings: &mut Warnings<Warning>) -> Option<Self> {
Self::read_in(doc, parent, ColorNames::DrawingMl, warnings)
}
#[must_use]
pub fn read_in(
doc: &Document,
parent: NodeId,
names: ColorNames,
warnings: &mut Warnings<Warning>,
) -> Option<Self> {
Self::read_marked(doc, parent, names, warnings).map(|(color, _)| color)
}
fn read_element(
doc: &Document,
node: NodeId,
names: ColorNames,
warnings: &mut Warnings<Warning>,
) -> Option<(Self, bool)> {
let base = base(doc, node, names, warnings)?;
let modifiers = doc
.child_elements(node)
.filter_map(|child| modifier(doc, child, names, warnings))
.collect();
let unread = doc
.child_elements(node)
.any(|child| changes_unread(doc, child, names, warnings));
if unread {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::ColorModifier,
});
}
Some((Self { base, modifiers }, unread))
}
pub(crate) fn read_all(
doc: &Document,
parent: NodeId,
warnings: &mut Warnings<Warning>,
) -> Vec<Self> {
doc.child_elements(parent)
.filter_map(|node| {
Self::read_element(doc, node, ColorNames::DrawingMl, warnings)
.map(|(color, _)| color)
})
.collect()
}
pub(crate) fn read_marked(
doc: &Document,
parent: NodeId,
names: ColorNames,
warnings: &mut Warnings<Warning>,
) -> Option<(Self, bool)> {
doc.child_elements(parent)
.find_map(|node| Self::read_element(doc, node, names, warnings))
}
pub(crate) fn opaque(&self) -> bool {
self.modifiers.iter().all(|modifier| match *modifier {
Modifier::Alpha(value) => Opacity::clamped(value) == Opacity::FULL,
_ => true,
})
}
#[must_use]
pub fn resolve(&self, scheme: &SchemeColors) -> Option<(Rgb, Opacity)> {
let rgb = match self.base {
Base::Rgb(rgb) => rgb,
Base::Scheme(index) => scheme.0.get(index).copied().flatten()?,
};
let mut channels = [rgb.r, rgb.g, rgb.b].map(|c| i64::from(c) * MILLI);
let mut alpha = Opacity::FULL;
for modifier in &self.modifiers {
channels = match *modifier {
Modifier::LumMod(value) => with_lightness(channels, |l| l * value / DRAWING_WHOLE),
Modifier::LumOff(value) => {
with_lightness(channels, |l| l + LIGHTNESS * value / DRAWING_WHOLE)
}
Modifier::Shade(value) => in_linear_light(channels, |l| l * value / DRAWING_WHOLE),
Modifier::Tint(value) => in_linear_light(channels, |l| {
l * value / DRAWING_WHOLE
+ LINEAR_WHITE * (DRAWING_WHOLE - value) / DRAWING_WHOLE
}),
Modifier::Alpha(value) => {
alpha = Opacity::clamped(value);
channels
}
Modifier::SatMod(value) => with_saturation(channels, value),
Modifier::Gamma => {
channels.map(|c| from_linear(scaled(c, LINEAR_WHITE, 255 * MILLI)))
}
Modifier::InvGamma => {
channels.map(|c| scaled(to_linear(c), 255 * MILLI, LINEAR_WHITE))
}
};
}
let [r, g, b] =
channels.map(|c| u8::try_from(((c + MILLI / 2) / MILLI).clamp(0, 255)).unwrap_or(255));
Some((Rgb { r, g, b }, alpha))
}
}
const MILLI: i64 = 1_000;
#[must_use]
pub fn on_white(rgb: Rgb, alpha: Opacity) -> Rgb {
let alpha = alpha.share();
let mix = |c: u8| {
let value = (i64::from(c) * alpha + 255 * (DRAWING_WHOLE - alpha) + DRAWING_WHOLE / 2)
/ DRAWING_WHOLE;
u8::try_from(value.clamp(0, 255)).unwrap_or(255)
};
Rgb {
r: mix(rgb.r),
g: mix(rgb.g),
b: mix(rgb.b),
}
}
fn base(
doc: &Document,
node: NodeId,
names: ColorNames,
warnings: &mut Warnings<Warning>,
) -> Option<Base> {
let elements = names.elements();
let value = doc.attribute(node, names.values(), "val");
if doc.is(node, elements, "srgbClr") {
return value.and_then(Rgb::from_hex).map(Base::Rgb);
}
if doc.is(node, elements, "schemeClr") {
return named(doc, node, value, (SCHEME, warnings))
.flatten()
.map(Base::Scheme);
}
if doc.is(node, elements, "sysClr") {
let last = doc.attribute(node, None, "lastClr").and_then(Rgb::from_hex);
let fallback = match value? {
"window" => Rgb {
r: 255,
g: 255,
b: 255,
},
_ => Rgb::BLACK,
};
return Some(Base::Rgb(last.unwrap_or(fallback)));
}
if doc.is(node, elements, "prstClr") {
return named(doc, node, value, (PRESET, warnings))
.flatten()
.map(|[r, g, b]| Base::Rgb(Rgb { r, g, b }));
}
if OTHER_MODELS.iter().any(|name| doc.is(node, elements, name)) {
warnings.push(Warning::FeatureNotSupported {
feature: Feature::ColorModel,
});
}
None
}
fn named<T: Clone>(
doc: &Document,
node: NodeId,
value: Option<&str>,
(table, warnings): (&'static Values<T>, &mut Warnings<Warning>),
) -> Option<T> {
case_of(value?, (&element_name(doc, node), "val"), (table, warnings))
}
const OTHER_MODELS: [&str; 2] = ["hslClr", "scrgbClr"];
type MakeModifier = fn(i64) -> Modifier;
const VALUELESS_MODIFIERS: [(&str, Modifier); 2] =
[("gamma", Modifier::Gamma), ("invGamma", Modifier::InvGamma)];
const MODIFIERS: [(&str, MakeModifier); 6] = [
("satMod", Modifier::SatMod),
("lumMod", Modifier::LumMod),
("lumOff", Modifier::LumOff),
("shade", Modifier::Shade),
("tint", Modifier::Tint),
("alpha", Modifier::Alpha),
];
fn modifier(
doc: &Document,
node: NodeId,
names: ColorNames,
warnings: &mut Warnings<Warning>,
) -> Option<Modifier> {
let elements = names.elements();
if let Some(&(_, valueless)) = VALUELESS_MODIFIERS
.iter()
.find(|(name, _)| doc.is(node, elements, name))
{
return Some(valueless);
}
let (_, kind) = MODIFIERS
.into_iter()
.find(|(name, _)| doc.is(node, elements, name))?;
let value = modifier_value(doc, node, names, warnings)?;
Some(kind(value))
}
fn modifier_value(
doc: &Document,
node: NodeId,
names: ColorNames,
warnings: &mut Warnings<Warning>,
) -> Option<i64> {
let Some(namespace) = names.values() else {
return attribute_of(doc, node, "val", percentage, warnings);
};
let value = percentage(doc.attribute(node, Some(namespace), "val")?);
if value.is_none() {
warnings.push(Warning::InvalidValue {
element: element_name(doc, node),
attribute: f_office_warnings::Name::new("val"),
});
}
value
}
fn changes_unread(
doc: &Document,
node: NodeId,
names: ColorNames,
warnings: &mut Warnings<Warning>,
) -> bool {
let Some(element) = doc.element(node) else {
return false;
};
let name = element.name.local;
if !doc.is(node, names.elements(), name)
|| MODIFIERS.iter().any(|(read, _)| *read == name)
|| VALUELESS_MODIFIERS.iter().any(|(read, _)| *read == name)
{
return false;
}
let value = modifier_value(doc, node, names, warnings);
let unchanged = if name.ends_with("Off") {
Some(0)
} else if name.ends_with("Mod") {
Some(DRAWING_WHOLE)
} else {
None
};
unchanged.is_none() || value != unchanged
}
#[must_use]
pub fn percentage(text: &str) -> Option<i64> {
let text = text.trim();
let Some(number) = text.strip_suffix('%') else {
return text.parse::<i32>().ok().map(i64::from);
};
let digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
let (negative, number) = match number.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, number),
};
let (whole, fraction) = match number.split_once('.') {
Some((whole, fraction)) if digits(fraction) => (whole, fraction),
Some(_) => return None,
None => (number, ""),
};
if !digits(whole) {
return None;
}
let thousandths: String = fraction
.chars()
.chain("000".chars())
.take(THOUSANDTHS_DIGITS)
.collect();
let value = whole
.parse::<i64>()
.ok()?
.checked_mul(THOUSANDTHS)?
.checked_add(thousandths.parse().ok()?)?;
let value = if negative { -value } else { value };
i32::try_from(value).ok().map(i64::from)
}
const LIGHTNESS: i64 = 510_000;
fn with_lightness(channels: [i64; 3], change: impl Fn(i64) -> i64) -> [i64; 3] {
let high = channels.iter().copied().max().unwrap_or(0);
let low = channels.iter().copied().min().unwrap_or(0);
let half = LIGHTNESS / 2;
let room = |l: i64| half - (l - half).abs();
let lightness = high + low;
let new = change(lightness).clamp(0, LIGHTNESS);
let chroma = high - low;
let new_chroma = if room(lightness) == 0 {
0
} else {
chroma * room(new) / room(lightness)
};
let new_low = (new - new_chroma) / 2;
channels.map(|c| {
if chroma == 0 {
new_low
} else {
new_low + (c - low) * new_chroma / chroma
}
})
}
fn with_saturation(channels: [i64; 3], factor: i64) -> [i64; 3] {
let high = channels.iter().copied().max().unwrap_or(0);
let low = channels.iter().copied().min().unwrap_or(0);
let lightness = high + low;
let chroma = high - low;
let new_chroma = (chroma * factor / DRAWING_WHOLE).max(0);
let new_low = (lightness - new_chroma) / 2;
channels.map(|c| {
if chroma == 0 {
c
} else {
(new_low + (c - low) * new_chroma / chroma).clamp(0, 255 * MILLI)
}
})
}
const LINEAR_WHITE: i64 = 65_535;
fn scaled(value: i64, numerator: i64, denominator: i64) -> i64 {
(value * numerator + denominator / 2) / denominator
}
fn in_linear_light(channels: [i64; 3], change: impl Fn(i64) -> i64) -> [i64; 3] {
channels.map(|c| from_linear(change(to_linear(c)).clamp(0, LINEAR_WHITE)))
}
fn table(index: usize) -> i64 {
TO_LINEAR
.get(index)
.copied()
.map_or(LINEAR_WHITE, i64::from)
}
fn to_linear(channel: i64) -> i64 {
let channel = channel.clamp(0, 255 * MILLI);
let index = usize::try_from(channel / MILLI).unwrap_or(0);
let low = table(index);
low + (table(index + 1) - low) * (channel % MILLI) / MILLI
}
fn from_linear(linear: i64) -> i64 {
let above = TO_LINEAR.partition_point(|&value| i64::from(value) < linear);
if above == 0 {
return 0;
}
let (low, high) = (table(above - 1), table(above));
let step = i64::try_from(above - 1).unwrap_or(0) * MILLI;
if high == low {
step
} else {
step + (linear - low) * MILLI / (high - low)
}
}
const TO_LINEAR: [u16; 256] = [
0, 20, 40, 60, 80, 99, 119, 139, 159, 179, 199, 219, 241, 264, 288, 313, 340, 367, 396, 427,
458, 491, 526, 562, 599, 637, 677, 718, 761, 805, 851, 898, 947, 997, 1048, 1101, 1156, 1212,
1270, 1330, 1391, 1453, 1517, 1583, 1651, 1720, 1790, 1863, 1937, 2013, 2090, 2170, 2250, 2333,
2418, 2504, 2592, 2681, 2773, 2866, 2961, 3058, 3157, 3258, 3360, 3464, 3570, 3678, 3788, 3900,
4014, 4129, 4247, 4366, 4488, 4611, 4736, 4864, 4993, 5124, 5257, 5392, 5530, 5669, 5810, 5953,
6099, 6246, 6395, 6547, 6700, 6856, 7014, 7174, 7335, 7500, 7666, 7834, 8004, 8177, 8352, 8528,
8708, 8889, 9072, 9258, 9445, 9635, 9828, 10022, 10219, 10417, 10619, 10822, 11028, 11235,
11446, 11658, 11873, 12090, 12309, 12530, 12754, 12980, 13209, 13440, 13673, 13909, 14146,
14387, 14629, 14874, 15122, 15371, 15623, 15878, 16135, 16394, 16656, 16920, 17187, 17456,
17727, 18001, 18277, 18556, 18837, 19121, 19407, 19696, 19987, 20281, 20577, 20876, 21177,
21481, 21787, 22096, 22407, 22721, 23038, 23357, 23678, 24002, 24329, 24658, 24990, 25325,
25662, 26001, 26344, 26688, 27036, 27386, 27739, 28094, 28452, 28813, 29176, 29542, 29911,
30282, 30656, 31033, 31412, 31794, 32179, 32567, 32957, 33350, 33745, 34143, 34544, 34948,
35355, 35764, 36176, 36591, 37008, 37429, 37852, 38278, 38706, 39138, 39572, 40009, 40449,
40891, 41337, 41785, 42236, 42690, 43147, 43606, 44069, 44534, 45002, 45473, 45947, 46423,
46903, 47385, 47871, 48359, 48850, 49344, 49841, 50341, 50844, 51349, 51858, 52369, 52884,
53401, 53921, 54445, 54971, 55500, 56032, 56567, 57105, 57646, 58190, 58737, 59287, 59840,
60396, 60955, 61517, 62082, 62650, 63221, 63795, 64372, 64952, 65535,
];
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::{
DrawColor, LightnessStep, PRESET, PRESET_COLORS, SCHEME, SLOTS, SchemeColors, SchemeSlot,
on_white, percentage,
};
use crate::{A, Warning};
use f_office_paint::{Opacity, Rgb};
use f_office_warnings::{Name, Warnings};
use f_office_xml::{Document, Limits};
#[test]
fn steps_the_lightness_and_cuts_each_channel_toward_zero() {
let hex = |text: &str| Rgb::from_hex(text).unwrap();
let cases = [
("4472C4", LightnessStep::Tint(0x99), "8EAADB"),
("4472C4", LightnessStep::Shade(0xBF), "2F5496"),
("A5A5A5", LightnessStep::Tint(0x33), "EDEDED"),
("70AD47", LightnessStep::Tint(0x66), "C5E0B3"),
("FFC000", LightnessStep::Shade(0x40), "403000"),
("4472C4", LightnessStep::Tint(0xFF), "4472C4"),
("4472C4", LightnessStep::Tint(0), "FFFFFF"),
("4472C4", LightnessStep::Shade(0), "000000"),
];
for (color, step, stepped) in cases {
assert_eq!(step.apply(hex(color)), hex(stepped), "{color} {step:?}");
}
}
#[test]
fn gives_the_color_of_a_slot() {
let scheme = scheme();
assert_eq!(scheme.get(SchemeSlot::Accent1), Rgb::from_hex("4472C4"));
assert_eq!(scheme.get(SchemeSlot::Dark1), Some(Rgb::BLACK));
assert_eq!(scheme.get(SchemeSlot::Light2), Rgb::from_hex("E7E6E6"));
assert_eq!(scheme.get(SchemeSlot::Accent2), None);
}
#[test]
fn reads_percentages_of_both_forms_and_refuses_what_the_type_forbids() {
let cases = [
("25000", Some(25_000)),
("-25000", Some(-25_000)),
("12.5%", Some(12_500)),
("-0.25%", Some(-250)),
("-1.5%", Some(-1_500)),
("-3.5%", Some(-3_500)),
("7%", Some(7_000)),
("1.2345%", Some(1_234)),
(" 45500 ", Some(45_500)),
(" 45.5% ", Some(45_500)),
("2147483647", Some(2_147_483_647)),
("-2147483648", Some(-2_147_483_648)),
("2147483.647%", Some(2_147_483_647)),
("-2147483.648%", Some(-2_147_483_648)),
("2147483648", None),
("-2147483649", None),
("2147483.648%", None),
("-2147483.649%", None),
("99999999999999999%", None),
("--5%", None),
("+5%", None),
("-+5%", None),
("5.%", None),
(".5%", None),
("1.2345x%", None),
("1.+5%", None),
("x%", None),
("1.x%", None),
("", None),
];
for (text, expected) in cases {
assert_eq!(percentage(text), expected, "{text}");
}
}
fn parse(xml: &str) -> Document {
Document::parse(
format!(r#"<a:x xmlns:a="{A}">{xml}</a:x>"#).as_bytes(),
&Limits::default(),
)
.unwrap()
}
const SCHEME_XML: &str = r#"<a:clrScheme><a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1><a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="44546A"/></a:dk2><a:lt2><a:srgbClr val="E7E6E6"/></a:lt2><a:accent1><a:srgbClr val="4472C4"/></a:accent1></a:clrScheme>"#;
fn scheme() -> SchemeColors {
let doc = parse(SCHEME_XML);
let node = doc.child_elements(doc.root().unwrap()).next().unwrap();
SchemeColors::read(&doc, node, &mut Warnings::new())
}
fn color(fill: &str) -> Option<(Rgb, Opacity)> {
color_warned(fill).0
}
fn color_warned(fill: &str) -> (Option<(Rgb, Opacity)>, Vec<Warning>) {
let doc = parse(fill);
let mut warnings = Warnings::new();
let found = DrawColor::read(&doc, doc.root().unwrap(), &mut warnings)
.and_then(|color| color.resolve(&scheme()));
(
found,
warnings
.iter()
.map(|(warning, _)| warning.clone())
.collect(),
)
}
#[test]
fn warns_of_a_scheme_or_preset_color_that_it_draws_as_none() {
let not_drawn = |element: &str, value: &str| Warning::ValueNotSupported {
element: Name::new(element),
attribute: Name::new("val"),
value: Name::new(value),
};
let invalid = |element: &str| Warning::InvalidValue {
element: Name::new(element),
attribute: Name::new("val"),
};
let cases = [
(
r#"<a:schemeClr val="phClr"/>"#,
None,
vec![not_drawn("schemeClr", "phClr")],
),
(
r#"<a:prstClr val="aliceBlue"/>"#,
None,
vec![not_drawn("prstClr", "aliceBlue")],
),
(
r#"<a:prstClr val="lightGrey"/>"#,
Some(rgb(211, 211, 211)),
vec![],
),
(
r#"<a:schemeClr val="Accent1"/>"#,
None,
vec![invalid("schemeClr")],
),
(
r#"<a:schemeClr val=" accent1"/>"#,
None,
vec![invalid("schemeClr")],
),
(r#"<a:prstClr val=""/>"#, None, vec![invalid("prstClr")]),
];
for (xml, want, warnings) in cases {
let found = color_warned(xml);
assert_eq!(
found,
(want.map(|rgb| (rgb, Opacity::FULL)), warnings),
"{xml}"
);
}
}
#[test]
fn the_color_tables_hold_the_names_of_their_types() {
let mut scheme: Vec<&str> = SCHEME.names().into_iter().map(|(name, _)| name).collect();
let mut listed: Vec<&str> = "bg1 tx1 bg2 tx2 accent1 accent2 accent3 accent4 accent5 \
accent6 hlink folHlink phClr dk1 lt1 dk2 lt2"
.split_whitespace()
.collect();
scheme.sort_unstable();
listed.sort_unstable();
assert_eq!(scheme, listed);
for (index, slot) in SLOTS.iter().enumerate() {
assert_eq!(
SCHEME.find(slot).map(|(case, _, _)| *case),
Some(Some(index))
);
}
let presets: HashSet<&str> = PRESET_COLORS.iter().copied().collect();
assert_eq!((PRESET_COLORS.len(), presets.len()), (190, 190));
assert_eq!(PRESET.names().len(), 190);
}
fn rgb(r: u8, g: u8, b: u8) -> Rgb {
Rgb { r, g, b }
}
#[test]
fn reads_plain_and_theme_colors() {
let cases = [
(r#"<a:srgbClr val="1F3864"/>"#, Some(rgb(31, 56, 100))),
(r#"<a:schemeClr val="accent1"/>"#, Some(rgb(68, 114, 196))),
(r#"<a:schemeClr val="bg1"/>"#, Some(rgb(255, 255, 255))),
(r#"<a:schemeClr val="tx2"/>"#, Some(rgb(68, 84, 106))),
(r#"<a:prstClr val="black"/>"#, Some(rgb(0, 0, 0))),
(r#"<a:sysClr val="window"/>"#, Some(rgb(255, 255, 255))),
(r#"<a:schemeClr val="accent6"/>"#, None),
(r#"<a:schemeClr val="phClr"/>"#, None),
(r#"<a:srgbClr val="12"/>"#, None),
];
for (xml, want) in cases {
assert_eq!(color(xml), want.map(|rgb| (rgb, Opacity::FULL)), "{xml}");
}
}
#[test]
fn reads_six_hexadecimal_digits_and_refuses_a_sign() {
let cases = [
(r#"<a:srgbClr val="1f3864"/>"#, Some(rgb(31, 56, 100))),
(r#"<a:srgbClr val="+FFFFF"/>"#, None),
(r#"<a:srgbClr val="-FFFFF"/>"#, None),
(
r#"<a:sysClr val="window" lastClr="+00000"/>"#,
Some(rgb(255, 255, 255)),
),
];
for (xml, want) in cases {
assert_eq!(color(xml), want.map(|rgb| (rgb, Opacity::FULL)), "{xml}");
}
}
#[test]
fn changes_lightness_in_hsl() {
let lighter = r#"<a:schemeClr val="accent1"><a:lumMod val="60000"/><a:lumOff val="40000"/></a:schemeClr>"#;
assert_eq!(color(lighter), Some((rgb(143, 170, 220), Opacity::FULL)));
let darker = r#"<a:schemeClr val="accent1"><a:lumMod val="75000"/></a:schemeClr>"#;
assert_eq!(color(darker), Some((rgb(47, 85, 151), Opacity::FULL)));
let gray = r#"<a:schemeClr val="bg1"><a:lumMod val="85000"/></a:schemeClr>"#;
assert_eq!(color(gray), Some((rgb(217, 217, 217), Opacity::FULL)));
let strict =
r#"<a:schemeClr val="bg1"><a:lumMod val="85%"/><a:alpha val="90.5%"/></a:schemeClr>"#;
assert_eq!(
color(strict),
Some((rgb(217, 217, 217), Opacity::clamped(90_500)))
);
}
#[test]
fn leaves_out_a_modifier_beyond_the_range_of_its_type() {
for name in ["lumMod", "lumOff", "shade", "tint"] {
let far =
format!(r#"<a:srgbClr val="4472C4"><a:{name} val="99999999999999"/></a:srgbClr>"#);
assert_eq!(
color(&far),
Some((rgb(68, 114, 196), Opacity::FULL)),
"{name}"
);
let largest =
format!(r#"<a:srgbClr val="4472C4"><a:{name} val="2147483647"/></a:srgbClr>"#);
assert!(color(&largest).is_some(), "{name}");
}
}
#[test]
fn shades_and_tints_in_linear_light() {
let shade = r#"<a:schemeClr val="accent1"><a:shade val="50000"/></a:schemeClr>"#;
assert_eq!(color(shade), Some((rgb(47, 82, 143), Opacity::FULL)));
let tint = r#"<a:srgbClr val="000000"><a:tint val="50000"/></a:srgbClr>"#;
assert_eq!(color(tint), Some((rgb(188, 188, 188), Opacity::FULL)));
let alpha = r#"<a:srgbClr val="FF0000"><a:alpha val="25000"/></a:srgbClr>"#;
let (red, opacity) = color(alpha).unwrap();
assert_eq!(on_white(red, opacity), rgb(255, 191, 191));
}
#[test]
fn takes_gamma_as_the_srgb_curve_and_inv_gamma_as_its_reverse() {
let cases = [
("808080", "<a:gamma/>", rgb(0xBC, 0xBC, 0xBC)),
("808080", "<a:invGamma/>", rgb(0x37, 0x37, 0x37)),
("808080", r#"<a:tint val="50000"/>"#, rgb(0xCD, 0xCD, 0xCD)),
("4472C4", "<a:gamma/>", rgb(0x8D, 0xB2, 0xE3)),
("4472C4", "<a:invGamma/>", rgb(0x0F, 0x2B, 0x8D)),
(
"808080",
r#"<a:gamma/><a:tint val="50000"/><a:invGamma/>"#,
rgb(0xBF, 0xBF, 0xBF),
),
(
"FFFFFF",
r#"<a:gamma/><a:tint val="43922"/><a:invGamma/>"#,
rgb(255, 255, 255),
),
];
for (base, modifiers, want) in cases {
let xml = format!(r#"<a:srgbClr val="{base}">{modifiers}</a:srgbClr>"#);
assert_eq!(color(&xml), Some((want, Opacity::FULL)), "{xml}");
}
}
#[test]
fn warns_once_of_a_color_whose_unread_modifiers_change_it_and_of_other_models() {
use crate::Feature;
let feature = |feature| vec![Warning::FeatureNotSupported { feature }];
let invalid = |element| Warning::InvalidValue {
element: Name::new(element),
attribute: Name::new("val"),
};
let red = |modifiers: &str| format!(r#"<a:srgbClr val="FF0000">{modifiers}</a:srgbClr>"#);
let cases = [
(
red(
r#"<a:hueOff val="0"/><a:satOff val="0%"/><a:satMod val="100000"/><a:alphaOff val="0"/>"#,
),
vec![],
),
(
red(r#"<a:lumMod val="x"/><a:hueMod val="1.5"/>"#),
vec![
invalid("lumMod"),
invalid("hueMod"),
Warning::FeatureNotSupported {
feature: Feature::ColorModifier,
},
],
),
(
red(r#"<a:satMod val="150000"/><a:hueOff val="60000"/>"#),
feature(Feature::ColorModifier),
),
(red(r#"<a:satMod val="150000"/>"#), vec![]),
(red("<a:gamma/>"), vec![]),
(red("<a:gray/>"), feature(Feature::ColorModifier)),
(
r#"<a:hslClr hue="0" sat="100%" lum="50%"/>"#.to_owned(),
feature(Feature::ColorModel),
),
(
r#"<a:scrgbClr r="100%" g="0" b="0"/>"#.to_owned(),
feature(Feature::ColorModel),
),
];
for (xml, want) in cases {
assert_eq!(color_warned(&xml).1, want, "{xml}");
}
assert_eq!(color(&red(r#"<a:hueOff val="50000"/>"#)), color(&red("")));
}
#[test]
fn gives_the_stops_of_two_gradient_styles_as_word_draws_them() {
let preset = [
r#"<a:shade val="51000"/><a:satMod val="130000"/>"#,
r#"<a:shade val="93000"/><a:satMod val="130000"/>"#,
r#"<a:shade val="94000"/><a:satMod val="135000"/>"#,
];
let theme = [
r#"<a:satMod val="103000"/><a:lumMod val="102000"/><a:tint val="94000"/>"#,
r#"<a:satMod val="110000"/><a:lumMod val="100000"/><a:shade val="100000"/>"#,
r#"<a:lumMod val="99000"/><a:satMod val="120000"/><a:shade val="78000"/>"#,
];
let cases = [
("4472C4", preset, ["214F9F", "2F69D0", "2C69D4"]),
("ED7D31", preset, ["C5570C", "FF7414", "FF730F"]),
("A5A5A5", preset, ["797979", "A0A0A0", "A0A0A0"]),
("4472C4", theme, ["6083CB", "3E70CA", "2E61BA"]),
("ED7D31", theme, ["F18C55", "F67B28", "E56B17"]),
("A5A5A5", theme, ["AFAFAF", "A5A5A5", "929292"]),
];
let darker = r#"<a:srgbClr val="4472C4"><a:lumMod val="84000"/></a:srgbClr>"#;
assert_eq!(color(darker), Some((rgb(0x35, 0x5F, 0xA9), Opacity::FULL)));
let mut found = Vec::new();
for (accent, modifiers, _) in cases {
for modifiers in modifiers {
let xml = format!(r#"<a:srgbClr val="{accent}">{modifiers}</a:srgbClr>"#);
let (rgb, _) = color(&xml).unwrap();
found.push(format!("{:02X}{:02X}{:02X}", rgb.r, rgb.g, rgb.b));
}
}
let want: Vec<String> = cases
.iter()
.flat_map(|(_, _, want)| want.map(str::to_owned))
.collect();
assert_eq!(found, want);
}
}