rdocx-oxml 0.7.0

WordprocessingML XML element types for OOXML
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Theme parsing: extracts color scheme and font scheme from theme1.xml.

use quick_xml::Reader;
use quick_xml::events::Event;

use crate::error::Result;
use crate::namespace::matches_local_name;

/// Parsed theme information from `word/theme/theme1.xml`.
#[derive(Debug, Clone, Default)]
pub struct Theme {
    /// Theme color scheme (dk1, dk2, lt1, lt2, accent1-6, hlink, folHlink).
    pub colors: ThemeColors,
    /// Major font family (typically used for headings).
    pub major_font: Option<String>,
    /// Minor font family (typically used for body text).
    pub minor_font: Option<String>,
}

/// The 12 standard theme colors, stored as 6-character hex RGB strings.
#[derive(Debug, Clone, Default)]
pub struct ThemeColors {
    pub dk1: Option<String>,
    pub dk2: Option<String>,
    pub lt1: Option<String>,
    pub lt2: Option<String>,
    pub accent1: Option<String>,
    pub accent2: Option<String>,
    pub accent3: Option<String>,
    pub accent4: Option<String>,
    pub accent5: Option<String>,
    pub accent6: Option<String>,
    pub hlink: Option<String>,
    pub fol_hlink: Option<String>,
}

impl ThemeColors {
    /// Look up a theme color by its OOXML name (e.g., "accent1", "dark1").
    pub fn get(&self, name: &str) -> Option<&str> {
        match name {
            "dark1" | "dk1" => self.dk1.as_deref(),
            "dark2" | "dk2" => self.dk2.as_deref(),
            "light1" | "lt1" => self.lt1.as_deref(),
            "light2" | "lt2" => self.lt2.as_deref(),
            "accent1" => self.accent1.as_deref(),
            "accent2" => self.accent2.as_deref(),
            "accent3" => self.accent3.as_deref(),
            "accent4" => self.accent4.as_deref(),
            "accent5" => self.accent5.as_deref(),
            "accent6" => self.accent6.as_deref(),
            "hlink" | "hyperlink" => self.hlink.as_deref(),
            "folHlink" | "followedHyperlink" => self.fol_hlink.as_deref(),
            // Word also uses "text1" = dk1, "text2" = dk2, "background1" = lt1, "background2" = lt2
            "text1" => self.dk1.as_deref(),
            "text2" => self.dk2.as_deref(),
            "background1" | "bg1" => self.lt1.as_deref(),
            "background2" | "bg2" => self.lt2.as_deref(),
            _ => None,
        }
    }
}

impl Theme {
    /// Parse theme from XML bytes (the content of `word/theme/theme1.xml`).
    pub fn from_xml(xml: &[u8]) -> Result<Self> {
        let mut reader = Reader::from_reader(xml);
        reader.config_mut().trim_text(true);

        let mut theme = Theme::default();
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(ref e)) => {
                    let name = e.name();
                    if matches_local_name(name.as_ref(), b"clrScheme") {
                        parse_color_scheme(&mut reader, &mut theme.colors)?;
                    } else if matches_local_name(name.as_ref(), b"majorFont") {
                        theme.major_font = parse_font_scheme(&mut reader, b"majorFont")?;
                    } else if matches_local_name(name.as_ref(), b"minorFont") {
                        theme.minor_font = parse_font_scheme(&mut reader, b"minorFont")?;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(e.into()),
                _ => {}
            }
            buf.clear();
        }

        Ok(theme)
    }
}

/// Parse the `<a:clrScheme>` element to extract theme colors.
fn parse_color_scheme(reader: &mut Reader<&[u8]>, colors: &mut ThemeColors) -> Result<()> {
    let mut buf = Vec::new();
    let mut current_slot: Option<String> = None;

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                let name = e.name();
                let local = local_name(name.as_ref());
                // Color slot elements: dk1, dk2, lt1, lt2, accent1-6, hlink, folHlink
                match local {
                    b"dk1" | b"dk2" | b"lt1" | b"lt2" | b"accent1" | b"accent2" | b"accent3"
                    | b"accent4" | b"accent5" | b"accent6" | b"hlink" | b"folHlink" => {
                        current_slot = Some(std::str::from_utf8(local).unwrap_or("").to_string());
                    }
                    _ => {}
                }
            }
            Ok(Event::Empty(ref e)) => {
                let name = e.name();
                let local = local_name(name.as_ref());
                // Inside a color slot, look for <a:srgbClr val="RRGGBB"/> or <a:sysClr lastClr="RRGGBB"/>
                if let Some(ref slot) = current_slot {
                    let color = if matches_local_name(name.as_ref(), b"srgbClr") {
                        get_attr(e, b"val")
                    } else if matches_local_name(name.as_ref(), b"sysClr") {
                        // System color: use lastClr (the resolved value) if available
                        get_attr(e, b"lastClr").or_else(|| get_attr(e, b"val"))
                    } else {
                        None
                    };

                    if let Some(hex) = color {
                        match slot.as_str() {
                            "dk1" => colors.dk1 = Some(hex),
                            "dk2" => colors.dk2 = Some(hex),
                            "lt1" => colors.lt1 = Some(hex),
                            "lt2" => colors.lt2 = Some(hex),
                            "accent1" => colors.accent1 = Some(hex),
                            "accent2" => colors.accent2 = Some(hex),
                            "accent3" => colors.accent3 = Some(hex),
                            "accent4" => colors.accent4 = Some(hex),
                            "accent5" => colors.accent5 = Some(hex),
                            "accent6" => colors.accent6 = Some(hex),
                            "hlink" => colors.hlink = Some(hex),
                            "folHlink" => colors.fol_hlink = Some(hex),
                            _ => {}
                        }
                    }
                } else {
                    // Top-level color slot with inline color (dk1, etc.)
                    match local {
                        b"dk1" | b"dk2" | b"lt1" | b"lt2" | b"accent1" | b"accent2"
                        | b"accent3" | b"accent4" | b"accent5" | b"accent6" | b"hlink"
                        | b"folHlink" => {
                            // Shouldn't happen (they're Start not Empty), but handle anyway
                        }
                        _ => {}
                    }
                }
            }
            Ok(Event::End(ref e)) => {
                let name = e.name();
                let local = local_name(name.as_ref());
                match local {
                    b"dk1" | b"dk2" | b"lt1" | b"lt2" | b"accent1" | b"accent2" | b"accent3"
                    | b"accent4" | b"accent5" | b"accent6" | b"hlink" | b"folHlink" => {
                        current_slot = None;
                    }
                    b"clrScheme" => break,
                    _ => {}
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(e.into()),
            _ => {}
        }
        buf.clear();
    }

    Ok(())
}

/// Parse a `<a:majorFont>` or `<a:minorFont>` element to extract the latin typeface.
fn parse_font_scheme(reader: &mut Reader<&[u8]>, end_tag: &[u8]) -> Result<Option<String>> {
    let mut buf = Vec::new();
    let mut latin_font = None;

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Empty(ref e)) => {
                if matches_local_name(e.name().as_ref(), b"latin") {
                    latin_font = get_attr(e, b"typeface");
                }
            }
            Ok(Event::End(ref e)) if matches_local_name(e.name().as_ref(), end_tag) => break,
            Ok(Event::Eof) => break,
            Err(e) => return Err(e.into()),
            _ => {}
        }
        buf.clear();
    }

    Ok(latin_font)
}

/// Get the local name (after namespace prefix) from a qualified name.
fn local_name(qname: &[u8]) -> &[u8] {
    match qname.iter().position(|&b| b == b':') {
        Some(pos) => &qname[pos + 1..],
        None => qname,
    }
}

/// Extract a named attribute value from an element.
fn get_attr(e: &quick_xml::events::BytesStart, attr_name: &[u8]) -> Option<String> {
    for attr in e.attributes().flatten() {
        let key = attr.key.as_ref();
        let local = local_name(key);
        if local == attr_name {
            return std::str::from_utf8(&attr.value).ok().map(|s| s.to_string());
        }
    }
    None
}

/// Apply theme tint/shade modifiers to a base color.
///
/// `tint_val` is 0-255 where 255 means full tint (lightest).
/// `shade_val` is 0-255 where 255 means full shade (darkest).
pub fn apply_tint_shade(hex: &str, tint_val: Option<u8>, shade_val: Option<u8>) -> String {
    let hex = hex.trim_start_matches('#');
    if hex.len() < 6 {
        return hex.to_string();
    }

    let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0) as f64 / 255.0;
    let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0) as f64 / 255.0;
    let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0) as f64 / 255.0;

    let (r, g, b) = if let Some(tint) = tint_val {
        // Tint: mix with white. tint=0 means no change, tint=255 means pure white
        let t = tint as f64 / 255.0;
        (r + (1.0 - r) * t, g + (1.0 - g) * t, b + (1.0 - b) * t)
    } else if let Some(shade) = shade_val {
        // Shade: mix with black. shade=0 means pure black, shade=255 means no change
        let s = shade as f64 / 255.0;
        (r * s, g * s, b * s)
    } else {
        (r, g, b)
    };

    format!(
        "{:02X}{:02X}{:02X}",
        (r.clamp(0.0, 1.0) * 255.0) as u8,
        (g.clamp(0.0, 1.0) * 255.0) as u8,
        (b.clamp(0.0, 1.0) * 255.0) as u8,
    )
}

/// Project a shared DrawingML theme onto this crate's Word theme.
///
/// The adapter lives here rather than in `oxml-drawing` so the dependency runs
/// one way, from the format crate to the shared crate. Hosting it the other way
/// round made the two publication trains mutually dependent, since
/// `rdocx-layout` already depends on `oxml-layout`. The orphan rule allows this
/// placement because `Theme` is local here.
impl From<&oxml_drawing::theme::CT_OfficeStyleSheet> for Theme {
    fn from(theme: &oxml_drawing::theme::CT_OfficeStyleSheet) -> Self {
        let colours = &theme.theme_elements.color_scheme;
        let fonts = &theme.theme_elements.font_scheme;
        Self {
            colors: ThemeColors {
                dk1: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Dark1)),
                dk2: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Dark2)),
                lt1: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Light1)),
                lt2: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Light2)),
                accent1: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Accent1)),
                accent2: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Accent2)),
                accent3: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Accent3)),
                accent4: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Accent4)),
                accent5: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Accent5)),
                accent6: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Accent6)),
                hlink: legacy_colour(colours.color(oxml_drawing::color::ThemeColorSlot::Hyperlink)),
                fol_hlink: legacy_colour(
                    colours.color(oxml_drawing::color::ThemeColorSlot::FollowedHyperlink),
                ),
            },
            major_font: Some(fonts.major_font.latin.typeface.clone()),
            minor_font: Some(fonts.minor_font.latin.typeface.clone()),
        }
    }
}

fn legacy_colour(colour: &oxml_drawing::color::ColorChoice) -> Option<String> {
    match colour {
        oxml_drawing::color::ColorChoice::Srgb { value, .. } => Some(value.to_string()),
        oxml_drawing::color::ColorChoice::System {
            value, last_color, ..
        } => Some(
            last_color
                .map(|resolved| resolved.to_string())
                .unwrap_or_else(|| value.clone()),
        ),
        oxml_drawing::color::ColorChoice::Scheme { .. }
        | oxml_drawing::color::ColorChoice::Preset { .. } => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // F-X024, the theme adapter's regressions, moved here with the impl.

    #[test]
    fn shared_theme_adapter_matches_the_legacy_theme_projection() {
        let shared = oxml_drawing::theme::CT_OfficeStyleSheet::from_xml(
            oxml_drawing::theme::OFFICE_DEFAULT_XML.as_bytes(),
        )
        .unwrap();
        let legacy = Theme::from_xml(oxml_drawing::theme::OFFICE_DEFAULT_XML.as_bytes()).unwrap();
        let projected = Theme::from(&shared);

        for slot in [
            "dk1", "dk2", "lt1", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5",
            "accent6", "hlink", "folHlink",
        ] {
            assert_eq!(projected.colors.get(slot), legacy.colors.get(slot));
        }
        assert_eq!(projected.major_font, legacy.major_font);
        assert_eq!(projected.minor_font, legacy.minor_font);
    }

    #[test]
    fn shared_theme_adapter_does_not_project_unresolved_colour_forms() {
        let mut shared = oxml_drawing::theme::CT_OfficeStyleSheet::office_default();
        shared.theme_elements.color_scheme.accent1 = oxml_drawing::color::ColorChoice::Scheme {
            value: "accent2".to_owned(),
            transforms: Vec::new(),
            raw_children: oxml_drawing::order::OrderedRawChildren::default(),
        };
        shared.theme_elements.color_scheme.accent2 = oxml_drawing::color::ColorChoice::Preset {
            value: "red".to_owned(),
            transforms: Vec::new(),
            raw_children: oxml_drawing::order::OrderedRawChildren::default(),
        };
        shared.theme_elements.color_scheme.accent3 = oxml_drawing::color::ColorChoice::System {
            value: "windowText".to_owned(),
            last_color: None,
            transforms: Vec::new(),
            raw_children: oxml_drawing::order::OrderedRawChildren::default(),
        };
        shared.theme_elements.color_scheme.accent4 = oxml_drawing::color::ColorChoice::System {
            value: "window".to_owned(),
            last_color: Some(oxml_drawing::color::RgbColor::new(0xab, 0xcd, 0xef)),
            transforms: Vec::new(),
            raw_children: oxml_drawing::order::OrderedRawChildren::default(),
        };

        let projected = Theme::from(&shared);

        assert_eq!(projected.colors.accent1, None);
        assert_eq!(projected.colors.accent2, None);
        assert_eq!(projected.colors.accent3.as_deref(), Some("windowText"));
        assert_eq!(projected.colors.accent4.as_deref(), Some("ABCDEF"));
    }

    #[test]
    fn parse_office_theme() {
        let xml = br#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">
  <a:themeElements>
    <a:clrScheme name="Office">
      <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:accent2><a:srgbClr val="ED7D31"/></a:accent2>
      <a:accent3><a:srgbClr val="A5A5A5"/></a:accent3>
      <a:accent4><a:srgbClr val="FFC000"/></a:accent4>
      <a:accent5><a:srgbClr val="5B9BD5"/></a:accent5>
      <a:accent6><a:srgbClr val="70AD47"/></a:accent6>
      <a:hlink><a:srgbClr val="0563C1"/></a:hlink>
      <a:folHlink><a:srgbClr val="954F72"/></a:folHlink>
    </a:clrScheme>
    <a:fontScheme name="Office">
      <a:majorFont>
        <a:latin typeface="Calibri Light"/>
        <a:ea typeface=""/>
        <a:cs typeface=""/>
      </a:majorFont>
      <a:minorFont>
        <a:latin typeface="Calibri"/>
        <a:ea typeface=""/>
        <a:cs typeface=""/>
      </a:minorFont>
    </a:fontScheme>
  </a:themeElements>
</a:theme>"#;

        let theme = Theme::from_xml(xml).unwrap();

        assert_eq!(theme.colors.dk1.as_deref(), Some("000000"));
        assert_eq!(theme.colors.lt1.as_deref(), Some("FFFFFF"));
        assert_eq!(theme.colors.dk2.as_deref(), Some("44546A"));
        assert_eq!(theme.colors.lt2.as_deref(), Some("E7E6E6"));
        assert_eq!(theme.colors.accent1.as_deref(), Some("4472C4"));
        assert_eq!(theme.colors.accent2.as_deref(), Some("ED7D31"));
        assert_eq!(theme.colors.hlink.as_deref(), Some("0563C1"));
        assert_eq!(theme.colors.fol_hlink.as_deref(), Some("954F72"));

        assert_eq!(theme.major_font.as_deref(), Some("Calibri Light"));
        assert_eq!(theme.minor_font.as_deref(), Some("Calibri"));
    }

    #[test]
    fn theme_color_lookup() {
        let colors = ThemeColors {
            dk1: Some("000000".to_string()),
            lt1: Some("FFFFFF".to_string()),
            accent1: Some("4472C4".to_string()),
            ..Default::default()
        };
        assert_eq!(colors.get("dark1"), Some("000000"));
        assert_eq!(colors.get("text1"), Some("000000"));
        assert_eq!(colors.get("light1"), Some("FFFFFF"));
        assert_eq!(colors.get("background1"), Some("FFFFFF"));
        assert_eq!(colors.get("accent1"), Some("4472C4"));
        assert_eq!(colors.get("nonexistent"), None);
    }

    #[test]
    fn tint_shade_modifiers() {
        // Pure red with 50% tint → pinkish
        let result = apply_tint_shade("FF0000", Some(128), None);
        assert_eq!(result, "FF8080");

        // Pure red with no modification
        let result = apply_tint_shade("FF0000", None, None);
        assert_eq!(result, "FF0000");
    }
}