Skip to main content

extend_docx/parse/
colors.rs

1use super::context::ThemeColorMap;
2
3/// Mirrors TypeScript `DEFAULT_DRAWING_SCHEME_COLORS`.
4pub fn default_drawing_scheme_colors() -> ThemeColorMap {
5    ThemeColorMap::from([
6        ("bg1".to_string(), "#ffffff".to_string()),
7        ("bg2".to_string(), "#f3f4f6".to_string()),
8        ("tx1".to_string(), "#000000".to_string()),
9        ("tx2".to_string(), "#1f2937".to_string()),
10        ("dk1".to_string(), "#000000".to_string()),
11        ("dk2".to_string(), "#1f2937".to_string()),
12        ("lt1".to_string(), "#ffffff".to_string()),
13        ("lt2".to_string(), "#f3f4f6".to_string()),
14        ("accent1".to_string(), "#4472c4".to_string()),
15        ("accent2".to_string(), "#ed7d31".to_string()),
16        ("accent3".to_string(), "#70ad47".to_string()),
17        ("accent4".to_string(), "#5b9bd5".to_string()),
18        ("accent5".to_string(), "#7030a0".to_string()),
19        ("accent6".to_string(), "#ffc000".to_string()),
20        ("hlink".to_string(), "#0563c1".to_string()),
21        ("folhlink".to_string(), "#954f72".to_string()),
22        ("followedhyperlink".to_string(), "#954f72".to_string()),
23    ])
24}
25
26/// Mirrors TypeScript `normalizeHexColor`.
27pub fn normalize_hex_color(value: Option<&str>) -> Option<String> {
28    let normalized = value?.trim();
29    if normalized.is_empty() || normalized.eq_ignore_ascii_case("auto") {
30        return None;
31    }
32
33    if normalized.len() == 6 && normalized.chars().all(|ch| ch.is_ascii_hexdigit()) {
34        return Some(format!("#{normalized}"));
35    }
36
37    if normalized.len() == 3 && normalized.chars().all(|ch| ch.is_ascii_hexdigit()) {
38        let expanded: String = normalized.chars().flat_map(|ch| [ch, ch]).collect();
39        return Some(format!("#{expanded}"));
40    }
41
42    if normalized.starts_with('#')
43        && normalized.len() == 7
44        && normalized[1..].chars().all(|ch| ch.is_ascii_hexdigit())
45    {
46        return Some(normalized.to_string());
47    }
48
49    None
50}
51
52/// Mirrors TypeScript `resolveDrawingColorFromXml`.
53#[derive(Clone, Debug, PartialEq)]
54pub struct ResolvedDrawingColor {
55    pub color: String,
56    pub opacity: Option<f64>,
57}
58
59pub fn resolve_drawing_color_from_xml(
60    color_xml: Option<&str>,
61    theme_colors: &ThemeColorMap,
62) -> Option<ResolvedDrawingColor> {
63    let color_xml = color_xml?;
64    let defaults = default_drawing_scheme_colors();
65
66    let srgb = find_drawing_attribute_value(color_xml, "a:srgbClr", "val")
67        .as_deref()
68        .and_then(|value| normalize_hex_color(Some(value)));
69    let sys = find_drawing_attribute_value(color_xml, "a:sysClr", "lastClr")
70        .as_deref()
71        .and_then(|value| normalize_hex_color(Some(value)));
72    let scheme_token = find_drawing_attribute_value(color_xml, "a:schemeClr", "val")
73        .map(|token| token.trim().to_ascii_lowercase());
74    let scheme = scheme_token.as_ref().and_then(|token| {
75        theme_colors
76            .get(token)
77            .cloned()
78            .or_else(|| defaults.get(token).cloned())
79    });
80    let preset = find_drawing_attribute_value(color_xml, "a:prstClr", "val").and_then(|value| {
81        match value.as_str() {
82            "black" => Some("#000000".to_string()),
83            "white" => Some("#ffffff".to_string()),
84            _ => None,
85        }
86    });
87    let color = apply_drawing_color_transforms(&srgb.or(sys).or(scheme).or(preset)?, color_xml)?;
88
89    let alpha_raw = find_drawing_attribute_value(color_xml, "a:alpha", "val");
90    let alpha = alpha_raw.and_then(|raw| raw.parse::<f64>().ok());
91    let opacity = alpha
92        .filter(|value| value.is_finite() && *value >= 0.0)
93        .map(|value| (value / 100_000.0).clamp(0.0, 1.0));
94
95    Some(ResolvedDrawingColor { color, opacity })
96}
97
98fn apply_drawing_color_transforms(color: &str, xml: &str) -> Option<String> {
99    let mut rgb = [0.0; 3];
100    for (index, channel) in rgb.iter_mut().enumerate() {
101        *channel =
102            u8::from_str_radix(color.get(1 + index * 2..3 + index * 2)?, 16).ok()? as f64 / 255.0;
103    }
104    let tags = [
105        "a:tint", "a:shade", "a:sat", "a:satMod", "a:satOff", "a:lum", "a:lumMod", "a:lumOff",
106    ];
107    let transforms = crate::xml::extract_balanced_tag_blocks_in_order(xml, &tags);
108    if transforms.is_empty() {
109        return Some(color.to_string());
110    }
111    for tag in transforms {
112        let Some(value) = crate::xml::get_attribute(&xml[tag.start..tag.end], "val")
113            .and_then(|v| v.parse::<f64>().ok())
114            .filter(|v| v.is_finite())
115        else {
116            continue;
117        };
118        let amount = value / 100_000.0;
119        match tag.tag_name.as_str() {
120            "a:tint" => rgb = rgb.map(|channel| channel * amount + 1.0 - amount),
121            "a:shade" => rgb = rgb.map(|channel| channel * amount),
122            name => {
123                let max = rgb.into_iter().fold(0.0_f64, f64::max);
124                let min = rgb.into_iter().fold(1.0_f64, f64::min);
125                let delta = max - min;
126                let mut lightness = (max + min) / 2.0;
127                let mut saturation = if delta == 0.0 {
128                    0.0
129                } else {
130                    delta / (1.0 - (2.0 * lightness - 1.0).abs())
131                };
132                let hue = if delta == 0.0 {
133                    0.0
134                } else if max == rgb[0] {
135                    ((rgb[1] - rgb[2]) / delta).rem_euclid(6.0)
136                } else if max == rgb[1] {
137                    (rgb[2] - rgb[0]) / delta + 2.0
138                } else {
139                    (rgb[0] - rgb[1]) / delta + 4.0
140                };
141                let channel = if name.starts_with("a:sat") {
142                    &mut saturation
143                } else {
144                    &mut lightness
145                };
146                *channel = if name.ends_with("Mod") {
147                    *channel * amount
148                } else if name.ends_with("Off") {
149                    *channel + amount
150                } else {
151                    amount
152                };
153                *channel = channel.clamp(0.0, 1.0);
154                let chroma = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
155                let x = chroma * (1.0 - (hue % 2.0 - 1.0).abs());
156                let offset = lightness - chroma / 2.0;
157                rgb = match hue as u32 {
158                    0 => [chroma, x, 0.0],
159                    1 => [x, chroma, 0.0],
160                    2 => [0.0, chroma, x],
161                    3 => [0.0, x, chroma],
162                    4 => [x, 0.0, chroma],
163                    _ => [chroma, 0.0, x],
164                }
165                .map(|channel| channel + offset);
166            }
167        }
168        rgb = rgb.map(|channel| channel.clamp(0.0, 1.0));
169    }
170    Some(format!(
171        "#{:02x}{:02x}{:02x}",
172        (rgb[0] * 255.0).round() as u8,
173        (rgb[1] * 255.0).round() as u8,
174        (rgb[2] * 255.0).round() as u8
175    ))
176}
177
178fn find_drawing_attribute_value(xml: &str, tag_name: &str, attribute: &str) -> Option<String> {
179    let tag_token = super::scan::find_tag_token(xml, tag_name)?;
180    crate::xml::get_attribute(&tag_token, attribute)
181}