betteroffice-drawingml 0.5.1

Shared DrawingML colors, themes, shape models, and preset geometry.
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! `a:fmtScheme` style lists and the `a:fillRef`/`a:lnRef` references into them.

use serde::{Deserialize, Serialize};

use crate::{
    ColorValue, ShapeEffects, ShapeFill, ShapeOutline, Theme, resolve_color_value_to_hex_with_theme,
};

/// Line width applied to a style reference the theme does not define.
const DEFAULT_STYLE_LINE_WIDTH_EMU: f64 = 9_525.0;

/// First `a:fillRef` index naming `a:bgFillStyleLst` instead of `a:fillStyleLst`.
const BACKGROUND_FILL_INDEX_BASE: u32 = 1_001;

/// Theme style lists with stable, one-based slots.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThemeFormatScheme {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fills: Vec<Option<ShapeFill>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub lines: Vec<Option<ShapeOutline>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effects: Vec<Option<ShapeEffects>>,
    /// `a:bgFillStyleLst`, which `a:fillRef` indices from 1001 name.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub background_fills: Vec<Option<ShapeFill>>,
}

impl ThemeFormatScheme {
    pub fn is_empty(&self) -> bool {
        self.fills.is_empty()
            && self.lines.is_empty()
            && self.effects.is_empty()
            && self.background_fills.is_empty()
    }

    fn fill(&self, index: u32) -> Option<&ShapeFill> {
        let (list, first) = if index >= BACKGROUND_FILL_INDEX_BASE {
            (&self.background_fills, BACKGROUND_FILL_INDEX_BASE)
        } else {
            (&self.fills, 1)
        };
        list.get(index.checked_sub(first)? as usize)?.as_ref()
    }

    fn line(&self, index: u32) -> Option<&ShapeOutline> {
        self.lines.get(index.checked_sub(1)? as usize)?.as_ref()
    }
}

/// A style index and its placeholder colour.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StyleReference {
    pub index: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<ColorValue>,
}

/// Theme references and unsupported explicit fills.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ShapeStyle {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font_color: Option<ColorValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fill: Option<StyleReference>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<StyleReference>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effect: Option<StyleReference>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub fill_disabled: bool,
    #[serde(default, skip_serializing_if = "is_false")]
    pub line_disabled: bool,
}

fn is_false(value: &bool) -> bool {
    !value
}

impl ShapeStyle {
    pub fn is_empty(&self) -> bool {
        self.font_color.is_none()
            && self.fill.is_none()
            && self.line.is_none()
            && self.effect.is_none()
            && !self.fill_disabled
            && !self.line_disabled
    }
}

/// Resolves a fill reference; 0 and 1000 mean no fill.
pub fn style_fill(
    scheme: &ThemeFormatScheme,
    reference: &StyleReference,
    theme: &Theme,
) -> ShapeFill {
    if matches!(reference.index, 0 | 1000) {
        return ShapeFill::named("none");
    }
    let placeholder = placeholder_color(reference, theme);
    let Some(fill) = scheme.fill(reference.index) else {
        return ShapeFill {
            fill_type: "solid".to_owned(),
            color: placeholder,
            gradient: None,
        };
    };
    let mut resolved = fill.clone();
    resolved.color = substitute_color(fill.color.as_ref(), placeholder.as_ref());
    if let Some(gradient) = &mut resolved.gradient {
        for stop in &mut gradient.stops {
            if let Some(color) = substitute_color(Some(&stop.color), placeholder.as_ref()) {
                stop.color = color;
            }
        }
    }
    resolved
}

/// Resolves `a:lnRef` against the theme. Index 0 means no outline.
pub fn style_outline(
    scheme: &ThemeFormatScheme,
    reference: &StyleReference,
    theme: &Theme,
) -> Option<ShapeOutline> {
    if reference.index == 0 {
        return None;
    }
    let placeholder = placeholder_color(reference, theme);
    let Some(outline) = scheme.line(reference.index) else {
        return Some(ShapeOutline {
            width: Some(DEFAULT_STYLE_LINE_WIDTH_EMU),
            color: placeholder,
            ..ShapeOutline::default()
        });
    };
    let mut resolved = ShapeOutline {
        width: outline.width.or(Some(DEFAULT_STYLE_LINE_WIDTH_EMU)),
        color: substitute_color(outline.color.as_ref(), placeholder.as_ref()),
        ..outline.clone()
    };
    if let Some(gradient) = &mut resolved.gradient {
        for stop in &mut gradient.stops {
            if let Some(color) = substitute_color(Some(&stop.color), placeholder.as_ref()) {
                stop.color = color;
            }
        }
    }
    Some(resolved)
}

/// Resolves `a:effectRef`; index 0 means no effects.
pub fn style_effects(
    scheme: &ThemeFormatScheme,
    reference: &StyleReference,
    theme: &Theme,
) -> Option<ShapeEffects> {
    let index = reference.index.checked_sub(1)? as usize;
    let mut effects = scheme.effects.get(index)?.as_ref()?.clone();
    if let Some(shadow) = &mut effects.outer_shadow {
        shadow.color = substitute_color(
            shadow.color.as_ref(),
            placeholder_color(reference, theme).as_ref(),
        );
    }
    Some(effects)
}

/// Resolves a `phClr` colour against the reference's colour, as a style fill does.
pub fn style_reference_color(
    value: &ColorValue,
    reference: &StyleReference,
    theme: &Theme,
) -> Option<ColorValue> {
    substitute_color(Some(value), placeholder_color(reference, theme).as_ref())
}

/// Applies reference modifiers before style modifiers.
fn placeholder_color(reference: &StyleReference, theme: &Theme) -> Option<ColorValue> {
    let color = reference.color.as_ref()?;
    if !color.transforms.is_empty() {
        let base = ColorValue {
            rgb: color.rgb.clone(),
            theme_color: color.theme_color.clone(),
            ..ColorValue::default()
        };
        let rgb = resolve_color_value_to_hex_with_theme(Some(&base), Some(theme))?;
        return Some(ColorValue {
            rgb: Some(rgb.trim_start_matches('#').to_owned()),
            theme_color: None,
            ..color.clone()
        });
    }
    let rgb = resolve_color_value_to_hex_with_theme(Some(color), Some(theme))?;
    Some(ColorValue {
        rgb: Some(rgb.trim_start_matches('#').to_owned()),
        alpha: color.alpha,
        ..ColorValue::default()
    })
}

/// Replaces the base colour while retaining style modifiers.
fn substitute_color(
    value: Option<&ColorValue>,
    placeholder: Option<&ColorValue>,
) -> Option<ColorValue> {
    let value = value?;
    if value.theme_color.as_deref() != Some("phClr") {
        return Some(value.clone());
    }
    let Some(placeholder) = placeholder else {
        return Some(value.clone());
    };
    let legacy = value.theme_tint.is_some()
        || value.theme_shade.is_some()
        || value.luminance_modulation.is_some()
        || value.luminance_offset.is_some()
        || value.saturation_modulation.is_some()
        || value.alpha.is_some();
    let placeholder = if !placeholder.transforms.is_empty() && value.transforms.is_empty() && legacy
    {
        ColorValue {
            rgb: resolve_color_value_to_hex_with_theme(Some(placeholder), None)
                .map(|hex| hex.trim_start_matches('#').to_owned()),
            alpha: Some(crate::resolve_color_value_alpha(placeholder)),
            ..ColorValue::default()
        }
    } else {
        placeholder.clone()
    };
    let mut transforms: Vec<_> = placeholder.drawingml_transforms().collect();
    if transforms.is_empty()
        && !value.transforms.is_empty()
        && let Some(alpha) = placeholder.alpha
    {
        transforms.push(crate::ColorTransform::Alpha(alpha));
    }
    transforms.extend(value.drawingml_transforms());
    Some(ColorValue {
        rgb: placeholder.rgb.clone(),
        theme_color: None,
        auto: None,
        alpha: value.alpha.or(placeholder.alpha),
        transforms,
        ..value.clone()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{GradientFill, GradientStop};

    fn rgb(value: &str) -> ColorValue {
        ColorValue {
            rgb: Some(value.to_owned()),
            ..Default::default()
        }
    }

    #[test]
    fn gradient_outline_substitutes_placeholder_colour_and_preserves_modifiers() {
        let scheme = ThemeFormatScheme {
            lines: vec![Some(ShapeOutline {
                gradient: Some(GradientFill {
                    gradient_type: "linear".into(),
                    angle: Some(45.0),
                    stops: vec![GradientStop {
                        position: 0.0,
                        color: ColorValue {
                            theme_color: Some("phClr".into()),
                            luminance_modulation: Some(0.5),
                            ..Default::default()
                        },
                    }],
                }),
                ..Default::default()
            })],
            ..Default::default()
        };
        let reference = StyleReference {
            index: 1,
            color: Some(ColorValue {
                alpha: Some(0.25),
                ..rgb("FF0000")
            }),
        };
        let resolved = style_outline(&scheme, &reference, &Theme::default()).unwrap();
        let gradient = resolved.gradient.unwrap();
        assert_eq!(gradient.angle, Some(45.0));
        assert_eq!(gradient.stops[0].color.rgb.as_deref(), Some("FF0000"));
        assert_eq!(gradient.stops[0].color.theme_color, None);
        assert_eq!(gradient.stops[0].color.luminance_modulation, Some(0.5));
        assert_eq!(gradient.stops[0].color.alpha, Some(0.25));
    }

    fn solid(color: ColorValue) -> ShapeFill {
        ShapeFill {
            fill_type: "solid".to_owned(),
            color: Some(color),
            gradient: None,
        }
    }

    fn reference(index: u32) -> StyleReference {
        StyleReference {
            index,
            color: Some(rgb("808080")),
        }
    }

    #[test]
    fn fill_indices_keep_holes_and_select_background_styles() {
        let scheme = ThemeFormatScheme {
            fills: vec![Some(solid(rgb("112233"))), None, Some(solid(rgb("445566")))],
            background_fills: vec![Some(solid(rgb("778899"))), Some(solid(rgb("AABBCC")))],
            ..Default::default()
        };
        let theme = Theme::default();
        for (index, expected) in [
            (1, "112233"),
            (2, "808080"),
            (3, "445566"),
            (999, "808080"),
            (1001, "778899"),
            (1002, "AABBCC"),
            (1003, "808080"),
        ] {
            assert_eq!(
                style_fill(&scheme, &reference(index), &theme)
                    .color
                    .unwrap()
                    .rgb
                    .as_deref(),
                Some(expected),
                "index {index}"
            );
        }
        for index in [0, 1000] {
            assert_eq!(
                style_fill(&scheme, &reference(index), &theme),
                ShapeFill::named("none")
            );
        }
    }

    #[test]
    fn ordered_placeholder_transforms_compose_without_intermediate_rounding() {
        use crate::{ColorTransform, resolve_color_value_to_rgba_hex};

        let color = ColorValue {
            theme_color: Some("phClr".to_owned()),
            transforms: vec![ColorTransform::LumMod(0.6), ColorTransform::AlphaMod(0.5)],
            ..Default::default()
        };
        let scheme = ThemeFormatScheme {
            fills: vec![
                Some(solid(color.clone())),
                Some(ShapeFill {
                    fill_type: "gradient".to_owned(),
                    color: None,
                    gradient: Some(GradientFill {
                        gradient_type: "linear".to_owned(),
                        angle: None,
                        stops: vec![GradientStop {
                            position: 0.0,
                            color: color.clone(),
                        }],
                    }),
                }),
            ],
            lines: vec![Some(ShapeOutline {
                color: Some(color),
                ..Default::default()
            })],
            ..Default::default()
        };
        let mut reference = StyleReference {
            index: 1,
            color: Some(ColorValue {
                theme_color: Some("accent1".to_owned()),
                transforms: vec![ColorTransform::Tint(0.5), ColorTransform::Alpha(0.5)],
                ..Default::default()
            }),
        };
        let theme = Theme::default();
        let solid = style_fill(&scheme, &reference, &theme).color.unwrap();
        let line = style_outline(&scheme, &reference, &theme)
            .unwrap()
            .color
            .unwrap();
        reference.index = 2;
        let gradient = style_fill(&scheme, &reference, &theme).gradient.unwrap();
        for color in [&solid, &line, &gradient.stops[0].color] {
            assert_eq!(
                color.transforms,
                vec![
                    ColorTransform::Tint(0.5),
                    ColorTransform::Alpha(0.5),
                    ColorTransform::LumMod(0.6),
                    ColorTransform::AlphaMod(0.5),
                ]
            );
            assert_eq!(
                resolve_color_value_to_rgba_hex(Some(color), Some(&theme)).as_deref(),
                Some("#4C64B040")
            );
        }
        reference.index = 1;
        let color = reference.color.as_mut().unwrap();
        color.transforms = vec![ColorTransform::Tint(0.5)];
        color.alpha = Some(0.5);
        let mixed = style_fill(&scheme, &reference, &theme).color.unwrap();
        assert_eq!(mixed.transforms, solid.transforms);
        assert_eq!(
            resolve_color_value_to_rgba_hex(Some(&mixed), Some(&theme)).as_deref(),
            Some("#4C64B040")
        );
    }

    #[test]
    fn placeholder_modifiers_compose_in_solids_lines_and_every_gradient_stop() {
        let first = ColorValue {
            theme_color: Some("phClr".to_owned()),
            luminance_modulation: Some(0.5),
            luminance_offset: Some(0.1),
            ..Default::default()
        };
        let last = ColorValue {
            luminance_modulation: Some(0.25),
            luminance_offset: Some(0.2),
            ..first.clone()
        };
        let scheme = ThemeFormatScheme {
            fills: vec![
                Some(solid(first.clone())),
                Some(ShapeFill {
                    fill_type: "gradient".to_owned(),
                    color: None,
                    gradient: Some(GradientFill {
                        gradient_type: "linear".to_owned(),
                        angle: Some(90.0),
                        stops: vec![
                            GradientStop {
                                position: 0.0,
                                color: first.clone(),
                            },
                            GradientStop {
                                position: 50000.0,
                                color: rgb("123456"),
                            },
                            GradientStop {
                                position: 100000.0,
                                color: last,
                            },
                        ],
                    }),
                }),
            ],
            lines: vec![Some(ShapeOutline {
                color: Some(first),
                ..Default::default()
            })],
            ..Default::default()
        };
        let mut theme = Theme::default();
        theme.color_scheme.accent1 = "808080".to_owned();
        let reference = |index| StyleReference {
            index,
            color: Some(ColorValue {
                theme_color: Some("accent1".to_owned()),
                luminance_modulation: Some(0.5),
                luminance_offset: Some(0.1),
                ..Default::default()
            }),
        };
        let hex = |color: &ColorValue| {
            resolve_color_value_to_hex_with_theme(Some(color), Some(&theme)).unwrap()
        };
        assert_eq!(
            hex(style_fill(&scheme, &reference(1), &theme)
                .color
                .as_ref()
                .unwrap()),
            "#474747"
        );
        assert_eq!(
            hex(style_outline(&scheme, &reference(1), &theme)
                .unwrap()
                .color
                .as_ref()
                .unwrap()),
            "#474747"
        );
        let gradient = style_fill(&scheme, &reference(2), &theme).gradient.unwrap();
        assert_eq!(gradient.angle, Some(90.0));
        assert_eq!(
            gradient
                .stops
                .iter()
                .map(|s| (s.position, hex(&s.color)))
                .collect::<Vec<_>>(),
            vec![
                (0.0, "#474747".to_owned()),
                (50000.0, "#123456".to_owned()),
                (100000.0, "#4A4A4A".to_owned())
            ]
        );
    }

    #[test]
    fn line_indices_preserve_no_fill_slots_and_explicit_style_properties() {
        let line = ShapeOutline {
            width: Some(28575.0),
            color: Some(rgb("123456")),
            style: Some("dash".to_owned()),
            cap: Some("rnd".to_owned()),
            ..Default::default()
        };
        let scheme = ThemeFormatScheme {
            lines: vec![Some(ShapeOutline::default()), None, Some(line.clone())],
            ..Default::default()
        };
        let theme = Theme::default();
        assert_eq!(style_outline(&scheme, &reference(0), &theme), None);
        assert!(
            style_outline(&scheme, &reference(1), &theme)
                .unwrap()
                .color
                .is_none()
        );
        assert_eq!(style_outline(&scheme, &reference(3), &theme), Some(line));
        for index in [2, 9] {
            let outline = style_outline(&scheme, &reference(index), &theme).unwrap();
            assert_eq!(outline.width, Some(9525.0));
            assert_eq!(outline.color.unwrap().rgb.as_deref(), Some("808080"));
        }
    }
}