Skip to main content

sheetkit_core/
theme.rs

1//! Theme color resolution.
2
3use sheetkit_xml::theme::ThemeColors;
4
5/// Maps spreadsheet `theme` values to the DrawingML color scheme order.
6///
7/// SpreadsheetML indexes `lt1`, `dk1`, `lt2`, and `dk2` first, whereas
8/// DrawingML stores those color scheme entries as `dk1`, `lt1`, `dk2`, `lt2`.
9const SPREADSHEET_THEME_TO_SCHEME: [usize; 12] = [1, 0, 3, 2, 4, 5, 6, 7, 8, 9, 10, 11];
10
11/// Resolve a theme color index to an ARGB hex string.
12/// Applies tint modification if specified.
13pub fn resolve_theme_color(theme: &ThemeColors, index: u32, tint: Option<f64>) -> Option<String> {
14    let scheme_index = *SPREADSHEET_THEME_TO_SCHEME.get(index as usize)?;
15    let base = theme.get(scheme_index)?;
16    if base.is_empty() {
17        return None;
18    }
19    match tint {
20        Some(t) if t != 0.0 => Some(apply_tint(base, t)),
21        _ => Some(base.to_string()),
22    }
23}
24
25/// Apply a tint value to an ARGB hex color.
26/// Tint > 0 lightens toward white, tint < 0 darkens toward black.
27///
28/// SpreadsheetML tint changes HLS luminance, with HLS values from 0 to 255.
29fn apply_tint(argb: &str, tint: f64) -> String {
30    if argb.len() != 8 {
31        return argb.to_string();
32    }
33    let Ok(alpha) = u8::from_str_radix(&argb[0..2], 16) else {
34        return argb.to_string();
35    };
36    let Ok(red) = u8::from_str_radix(&argb[2..4], 16) else {
37        return argb.to_string();
38    };
39    let Ok(green) = u8::from_str_radix(&argb[4..6], 16) else {
40        return argb.to_string();
41    };
42    let Ok(blue) = u8::from_str_radix(&argb[6..8], 16) else {
43        return argb.to_string();
44    };
45
46    let tint = if tint.is_finite() {
47        tint.clamp(-1.0, 1.0)
48    } else {
49        0.0
50    };
51    let (hue, saturation, luminance) = rgb_to_hsl(red, green, blue);
52    let luminance = if tint < 0.0 {
53        luminance * (1.0 + tint)
54    } else {
55        luminance * (1.0 - tint) + (1.0 - (1.0 - tint))
56    };
57    let (red, green, blue) = hsl_to_rgb(hue, saturation, luminance.clamp(0.0, 1.0));
58
59    format!("{alpha:02X}{red:02X}{green:02X}{blue:02X}")
60}
61
62fn rgb_to_hsl(red: u8, green: u8, blue: u8) -> (f64, f64, f64) {
63    let red = f64::from(red) / 255.0;
64    let green = f64::from(green) / 255.0;
65    let blue = f64::from(blue) / 255.0;
66    let max = red.max(green).max(blue);
67    let min = red.min(green).min(blue);
68    let luminance = (max + min) / 2.0;
69    let delta = max - min;
70    if delta == 0.0 {
71        return (0.0, 0.0, luminance);
72    }
73
74    let saturation = delta / (1.0 - (2.0 * luminance - 1.0).abs());
75    let hue = if max == red {
76        ((green - blue) / delta).rem_euclid(6.0)
77    } else if max == green {
78        (blue - red) / delta + 2.0
79    } else {
80        (red - green) / delta + 4.0
81    } / 6.0;
82    (hue, saturation, luminance)
83}
84
85fn hsl_to_rgb(hue: f64, saturation: f64, luminance: f64) -> (u8, u8, u8) {
86    if saturation == 0.0 {
87        let gray = channel(luminance);
88        return (gray, gray, gray);
89    }
90    let upper = if luminance <= 0.5 {
91        luminance * (1.0 + saturation)
92    } else {
93        luminance + saturation - luminance * saturation
94    };
95    let lower = 2.0 * luminance - upper;
96    (
97        channel(hue_to_rgb(lower, upper, hue + 1.0 / 3.0)),
98        channel(hue_to_rgb(lower, upper, hue)),
99        channel(hue_to_rgb(lower, upper, hue - 1.0 / 3.0)),
100    )
101}
102
103fn hue_to_rgb(lower: f64, upper: f64, hue: f64) -> f64 {
104    let hue = hue.rem_euclid(1.0);
105    if hue < 1.0 / 6.0 {
106        lower + (upper - lower) * 6.0 * hue
107    } else if hue < 0.5 {
108        upper
109    } else if hue < 2.0 / 3.0 {
110        lower + (upper - lower) * (2.0 / 3.0 - hue) * 6.0
111    } else {
112        lower
113    }
114}
115
116fn channel(value: f64) -> u8 {
117    (value * 255.0).round().clamp(0.0, 255.0) as u8
118}
119
120/// Get the default Office theme colors.
121pub fn default_theme_colors() -> ThemeColors {
122    ThemeColors {
123        colors: [
124            "FF000000".to_string(),
125            "FFFFFFFF".to_string(),
126            "FF44546A".to_string(),
127            "FFE7E6E6".to_string(),
128            "FF4472C4".to_string(),
129            "FFED7D31".to_string(),
130            "FFA5A5A5".to_string(),
131            "FFFFC000".to_string(),
132            "FF5B9BD5".to_string(),
133            "FF70AD47".to_string(),
134            "FF0563C1".to_string(),
135            "FF954F72".to_string(),
136        ],
137    }
138}
139
140/// Generate default theme1.xml content as raw bytes.
141pub fn default_theme_xml() -> Vec<u8> {
142    let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
143<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">
144  <a:themeElements>
145    <a:clrScheme name="Office">
146      <a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1>
147      <a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1>
148      <a:dk2><a:srgbClr val="44546A"/></a:dk2>
149      <a:lt2><a:srgbClr val="E7E6E6"/></a:lt2>
150      <a:accent1><a:srgbClr val="4472C4"/></a:accent1>
151      <a:accent2><a:srgbClr val="ED7D31"/></a:accent2>
152      <a:accent3><a:srgbClr val="A5A5A5"/></a:accent3>
153      <a:accent4><a:srgbClr val="FFC000"/></a:accent4>
154      <a:accent5><a:srgbClr val="5B9BD5"/></a:accent5>
155      <a:accent6><a:srgbClr val="70AD47"/></a:accent6>
156      <a:hlink><a:srgbClr val="0563C1"/></a:hlink>
157      <a:folHlink><a:srgbClr val="954F72"/></a:folHlink>
158    </a:clrScheme>
159    <a:fontScheme name="Office">
160      <a:majorFont><a:latin typeface="Calibri Light"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont>
161      <a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont>
162    </a:fontScheme>
163    <a:fmtScheme name="Office">
164      <a:fillStyleLst>
165        <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
166        <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
167        <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
168      </a:fillStyleLst>
169      <a:lnStyleLst>
170        <a:ln w="6350"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>
171        <a:ln w="12700"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>
172        <a:ln w="19050"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>
173      </a:lnStyleLst>
174      <a:effectStyleLst>
175        <a:effectStyle><a:effectLst/></a:effectStyle>
176        <a:effectStyle><a:effectLst/></a:effectStyle>
177        <a:effectStyle><a:effectLst/></a:effectStyle>
178      </a:effectStyleLst>
179      <a:bgFillStyleLst>
180        <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
181        <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
182        <a:solidFill><a:schemeClr val="phClr"/></a:solidFill>
183      </a:bgFillStyleLst>
184    </a:fmtScheme>
185  </a:themeElements>
186</a:theme>"#;
187    xml.as_bytes().to_vec()
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn test_resolve_theme_color_no_tint() {
196        let theme = default_theme_colors();
197        let color = resolve_theme_color(&theme, 1, None);
198        assert_eq!(color, Some("FF000000".to_string()));
199    }
200
201    #[test]
202    fn test_resolve_theme_color_with_positive_tint() {
203        let theme = default_theme_colors();
204        let color = resolve_theme_color(&theme, 1, Some(0.5));
205        assert_eq!(color, Some("FF808080".to_string()));
206    }
207
208    #[test]
209    fn test_resolve_invalid_index() {
210        let theme = default_theme_colors();
211        assert!(resolve_theme_color(&theme, 99, None).is_none());
212    }
213
214    #[test]
215    fn test_apply_tint_lighten() {
216        let result = apply_tint("FF000000", 0.5);
217        assert_eq!(result, "FF808080");
218    }
219
220    #[test]
221    fn test_apply_tint_darken() {
222        let result = apply_tint("FFFFFFFF", -0.5);
223        assert_eq!(result, "FF808080");
224    }
225
226    #[test]
227    fn test_apply_tint_zero() {
228        let theme = default_theme_colors();
229        let color = resolve_theme_color(&theme, 4, Some(0.0));
230        assert_eq!(color, Some("FF4472C4".to_string()));
231    }
232
233    #[test]
234    fn test_spreadsheet_theme_indices_match_cell_style_order() {
235        let theme = default_theme_colors();
236        let expected = [
237            "FFFFFFFF", "FF000000", "FFE7E6E6", "FF44546A", "FF4472C4", "FFED7D31", "FFA5A5A5",
238            "FFFFC000", "FF5B9BD5", "FF70AD47", "FF0563C1", "FF954F72",
239        ];
240        for (index, color) in expected.into_iter().enumerate() {
241            assert_eq!(
242                resolve_theme_color(&theme, index as u32, None),
243                Some(color.to_string())
244            );
245        }
246    }
247
248    #[test]
249    fn test_apply_tint_uses_hls_luminance_for_chromatic_colors() {
250        assert_eq!(apply_tint("804472C4", 0.5), "80A1B8E2");
251        assert_eq!(apply_tint("804472C4", -0.5), "80203864");
252    }
253
254    #[test]
255    fn test_default_theme_has_all_colors() {
256        let theme = default_theme_colors();
257        for i in 0..12 {
258            assert!(!theme.colors[i].is_empty());
259        }
260    }
261
262    #[test]
263    fn test_default_theme_xml_parseable() {
264        let xml_bytes = default_theme_xml();
265        let colors = sheetkit_xml::theme::parse_theme_colors(&xml_bytes);
266        assert_eq!(colors.colors[0], "FF000000");
267        assert_eq!(colors.colors[1], "FFFFFFFF");
268        assert_eq!(colors.colors[4], "FF4472C4");
269    }
270}