f-office-drawingml 0.3.0

DrawingML shapes, pictures, fills, lines, themes and colors.
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! The effects of DrawingML (ECMA-376 Part 1, 20.1.8 and 20.1.5): the effects of a shape or a
//! picture (`a:effectLst`, `a:effectDag`), its 3-D look (`a:scene3d`, `a:sp3d`), and the color
//! effects of a picture (the children of `a:blip`). The readers give an outer shadow that a
//! layout can draw ([`OuterShadow`]), and warn of each other effect with a [`Feature`] and draw
//! the shape or the picture without it.

use f_office_paint::{ColorEffect, Opacity, Rgb};
use f_office_units::scale::{FULL_TURN, QUARTER_TURN};
use f_office_units::{Length, fixed};
use f_office_warnings::Warnings;
use f_office_xml::{Document, NodeId};

use crate::color::{DrawColor, PlaceholderModifiers, SchemeColors, percentage};
use crate::theme::ShapeTheme;
use crate::{A, Feature, Warning, attribute_of, emus_of, integer_of};

/// The units of a whole in a shadow's scale (`sx`, `sy`, `ST_Percentage`): 100,000.
const WHOLE_SCALE: i64 = 100_000;

/// An outer shadow of a shape (`a:outerShdw`, ECMA-376 Part 1, 20.1.8.49) that a layout can
/// draw: of the shape's own size and not skewed (`sx` and `sy` of 100%, `kx` and `ky` of 0), so
/// that its alignment (`algn`) moves nothing. It casts the shape moved by its distance in its
/// direction, blurred by its radius, in its color.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OuterShadow {
    /// The radius of its blur (`blurRad`), 0 for a sharp shadow.
    pub blur: Length,
    /// How far it lies from the shape (`dist`).
    pub distance: Length,
    /// The direction in which it lies, in 60,000ths of a degree clockwise from the right
    /// (`dir`).
    pub direction: i64,
    /// Whether it turns and flips with its shape (`rotWithShape`, true by default).
    turns_with_shape: bool,
    /// Its color, with its alpha.
    color: DrawColor,
}

/// How far an outer shadow lies right of and below its shape.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShadowOffset {
    /// How far right of the shape it lies, below 0 when it lies left of it.
    pub across: Length,
    /// How far below the shape it lies, below 0 when it lies above it.
    pub down: Length,
}

impl ShadowOffset {
    /// The offset of a shadow that lies `distance` away in the direction `direction`, in
    /// 60,000ths of a degree clockwise from the right (`ST_PositiveFixedAngle`): the distance
    /// times the direction's cosine across and its sine down, each rounded to the nearest unit,
    /// a half away from 0.
    #[must_use]
    pub fn of(distance: Length, direction: i64) -> Self {
        let [sin, cos] = fixed::sin_cos(i128::from(direction) * fixed::ONE);
        let along = |share: i128| {
            let units = fixed::rounded(i128::from(distance.units()) * share, fixed::UNIT);
            Length::from_units(i64::try_from(units).unwrap_or(0))
        };
        Self {
            across: along(cos),
            down: along(sin),
        }
    }
}

/// The color of an outer shadow and how opaque it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShadowColor {
    /// Its color.
    pub rgb: Rgb,
    /// How opaque it is, from its alpha.
    pub opacity: Opacity,
}

impl OuterShadow {
    /// The shadow's color and opacity in `theme`'s colors, or `None` when they do not give
    /// it.
    #[must_use]
    pub fn color(&self, theme: &ShapeTheme) -> Option<ShadowColor> {
        let (rgb, opacity) = self.color.resolve(&theme.colors)?;
        Some(ShadowColor { rgb, opacity })
    }

    /// How far the shadow lies right of and below its shape: its distance in its direction
    /// ([`ShadowOffset::of`]).
    #[must_use]
    pub fn offset(&self) -> ShadowOffset {
        ShadowOffset::of(self.distance, self.direction)
    }

    /// Whether the shadow turns and flips with its shape (`rotWithShape`).
    pub(crate) const fn turns_with_shape(&self) -> bool {
        self.turns_with_shape
    }

    /// Returns this shadow with its offset direction rotated clockwise by `rotation` (in
    /// 60,000ths of a degree) when `rotWithShape` is enabled.
    pub(crate) fn rotated_by(mut self, rotation: i64) -> Self {
        if self.turns_with_shape && rotation != 0 {
            self.direction = (self.direction + rotation).rem_euclid(FULL_TURN);
        }
        self
    }
}

/// A glow around a shape or picture (`a:glow`, ECMA-376 Part 1, 20.1.8.32) that a layout can
/// draw: its positive radius and its color with alpha.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Glow {
    /// The radius of the glow (`rad`).
    pub radius: Length,
    /// Its color, with its alpha.
    color: DrawColor,
}

impl Glow {
    /// The glow's color and opacity in `theme`'s colors, or `None` when they do not give it.
    #[must_use]
    pub fn color(&self, theme: &ShapeTheme) -> Option<ShadowColor> {
        self.color
            .resolve(&theme.colors)
            .map(|(rgb, opacity)| ShadowColor { rgb, opacity })
    }
}

/// A downward vertical reflection of a shape or picture (`a:reflection`, ECMA-376 Part 1,
/// 20.1.8.50) that a layout can draw: unscaled horizontally, mirrored vertically (`sy = -100%`),
/// unskewed, bottom-aligned, fading downward, and placed `distance` below the outer bottom edge.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Reflection {
    /// The radius of its blur (`blurRad`), 0 for a sharp reflection.
    pub blur: Length,
    /// Opacity at and above `start_pos`, in thousandths of a percent (`stA`, `0..=100_000`).
    pub start_alpha: i64,
    /// Start position of the vertical fade along the reflected height (`stPos`, `0..=100_000`).
    pub start_pos: i64,
    /// Opacity at and below `end_pos`, in thousandths of a percent (`endA`, `0..=100_000`).
    pub end_alpha: i64,
    /// End position of the vertical fade along the reflected height (`endPos`, `0..=100_000`).
    pub end_pos: i64,
    /// Gap below the shape or picture's outer bottom edge (`dist`).
    pub distance: Length,
    /// Whether it turns with its shape (`rotWithShape`, true by default).
    turns_with_shape: bool,
}

impl Reflection {
    /// Whether the reflection turns with its shape (`rotWithShape`).
    pub(crate) const fn turns_with_shape(&self) -> bool {
        self.turns_with_shape
    }
}

/// The effects of an effect list (`a:effectLst`, ECMA-376 Part 1, 20.1.8.26), by their element
/// names, with the feature of each.
const EFFECTS: [(&str, Feature); 8] = [
    ("blur", Feature::OtherEffect),
    ("fillOverlay", Feature::OtherEffect),
    ("glow", Feature::Glow),
    ("innerShdw", Feature::Shadow),
    ("outerShdw", Feature::Shadow),
    ("prstShdw", Feature::Shadow),
    ("reflection", Feature::Reflection),
    ("softEdge", Feature::SoftEdge),
];

/// The outer shadow of the effect list of the properties `props` of a shape or a picture
/// (`spPr`) that a layout can draw ([`OuterShadow`]), the first in the list, of which it does
/// not warn; and warns in `warnings` of each other feature of the effects and the 3-D look,
/// once for each feature: another effect of its effect list, a graph of effects with an effect
/// in it, and a 3-D look (`three_d`). An empty effect list gives no warning. A caller that does
/// not draw the outer shadow warns of [`Feature::Shadow`] itself.
pub fn effects(
    doc: &Document,
    props: NodeId,
    warnings: &mut Warnings<Warning>,
) -> Option<OuterShadow> {
    let shadow = doc
        .child(props, A, "effectLst")
        .and_then(|list| doc.child(list, A, "outerShdw"))
        .and_then(|node| outer_shadow(doc, node, warnings).map(|shadow| (node, shadow)));
    let drawn = shadow
        .as_ref()
        .map_or(&[][..], |(node, _)| std::slice::from_ref(node));
    for feature in features(doc, props, drawn, warnings) {
        warnings.push(Warning::FeatureNotSupported { feature });
    }
    shadow.map(|(_, shadow)| shadow)
}

/// Outcome of reading `a:glow` when it is handled without an unsupported-feature warning.
enum ReadGlow {
    /// Zero radius: draws nothing.
    Empty,
    /// Positive radius with a resolved color.
    Drawn(Glow),
}

/// Reads `a:glow` (`node`): `Some(ReadGlow::Drawn(glow))` for a positive radius with a readable
/// color, `Some(ReadGlow::Empty)` for a zero radius (draws nothing and clears the warning), or
/// `None` when it cannot be drawn.
fn glow_of(doc: &Document, node: NodeId, warnings: &mut Warnings<Warning>) -> Option<ReadGlow> {
    let radius = emus_of(doc, node, "rad", warnings).unwrap_or(Length::ZERO);
    if radius < Length::ZERO {
        return None;
    }
    if radius == Length::ZERO {
        return Some(ReadGlow::Empty);
    }
    let color = DrawColor::read(doc, node, warnings)?;
    Some(ReadGlow::Drawn(Glow { radius, color }))
}

impl ReadGlow {
    fn into_option(self) -> Option<Glow> {
        match self {
            Self::Empty => None,
            Self::Drawn(glow) => Some(glow),
        }
    }
}

/// Outcome of reading `a:reflection` when it is handled without an unsupported-feature warning.
enum ReadReflection {
    /// Zero opacity throughout: draws nothing.
    Empty,
    /// Drawable downward reflection.
    Drawn(Reflection),
}

impl ReadReflection {
    fn into_option(self) -> Option<Reflection> {
        match self {
            Self::Empty => None,
            Self::Drawn(reflection) => Some(reflection),
        }
    }
}

/// Reads `a:reflection` (`node`): `Some(ReadReflection::Drawn(..))` for a downward vertical
/// reflection, `Some(ReadReflection::Empty)` when fully transparent, or `None` when unsupported.
fn reflection_of(
    doc: &Document,
    node: NodeId,
    warnings: &mut Warnings<Warning>,
) -> Option<ReadReflection> {
    let pct = |name: &str, default: i64, warnings: &mut Warnings<Warning>| {
        attribute_of(doc, node, name, percentage, warnings).unwrap_or(default)
    };
    let sx = pct("sx", WHOLE_SCALE, warnings);
    let sy = pct("sy", WHOLE_SCALE, warnings);
    let kx = integer_of(doc, node, "kx", warnings).unwrap_or(0);
    let ky = integer_of(doc, node, "ky", warnings).unwrap_or(0);
    let fade_dir = integer_of(doc, node, "fadeDir", warnings).unwrap_or(QUARTER_TURN);
    let dir = integer_of(doc, node, "dir", warnings).unwrap_or(0);
    let algn_ok = doc
        .attribute(node, None, "algn")
        .is_none_or(|a| matches!(a, "b" | "bl" | "br"));
    let blur = emus_of(doc, node, "blurRad", warnings).unwrap_or(Length::ZERO);
    let distance = emus_of(doc, node, "dist", warnings).unwrap_or(Length::ZERO);
    let plain = sx == WHOLE_SCALE
        && sy == -WHOLE_SCALE
        && kx == 0
        && ky == 0
        && fade_dir == QUARTER_TURN
        && (distance == Length::ZERO || dir == QUARTER_TURN)
        && algn_ok;
    if !plain || blur < Length::ZERO || distance < Length::ZERO {
        return None;
    }
    let start_alpha = pct("stA", WHOLE_SCALE, warnings).clamp(0, WHOLE_SCALE);
    let start_pos = pct("stPos", 0, warnings).clamp(0, WHOLE_SCALE);
    let end_alpha = pct("endA", 0, warnings).clamp(0, WHOLE_SCALE);
    let end_pos = pct("endPos", WHOLE_SCALE, warnings).clamp(0, WHOLE_SCALE);
    if start_alpha == 0 && end_alpha == 0 {
        return Some(ReadReflection::Empty);
    }
    let turns_with_shape = doc
        .attribute(node, None, "rotWithShape")
        .is_none_or(crate::boolean);
    Some(ReadReflection::Drawn(Reflection {
        blur,
        start_alpha,
        start_pos,
        end_alpha,
        end_pos,
        distance,
        turns_with_shape,
    }))
}

/// The drawable outer shadow, glow (`a:glow`), and reflection (`a:reflection`) of a shape's
/// properties `props`, warning in `warnings` of every other unsupported effect or 3-D look.
pub(crate) fn shape_effects_of(
    doc: &Document,
    props: NodeId,
    warnings: &mut Warnings<Warning>,
) -> (Option<OuterShadow>, Option<Glow>, Option<Reflection>) {
    let list = doc.child(props, A, "effectLst");
    let shadow = list
        .and_then(|list| doc.child(list, A, "outerShdw"))
        .and_then(|node| outer_shadow(doc, node, warnings).map(|shadow| (node, shadow)));
    let glow = list
        .and_then(|list| doc.child(list, A, "glow"))
        .and_then(|node| glow_of(doc, node, warnings).map(|glow| (node, glow)));
    let reflection = list
        .and_then(|list| doc.child(list, A, "reflection"))
        .and_then(|node| reflection_of(doc, node, warnings).map(|refl| (node, refl)));
    let mut drawn = Vec::new();
    if let Some((node, _)) = &shadow {
        drawn.push(*node);
    }
    if let Some((node, _)) = &glow {
        drawn.push(*node);
    }
    if let Some((node, _)) = &reflection {
        drawn.push(*node);
    }
    for feature in features(doc, props, &drawn, warnings) {
        warnings.push(Warning::FeatureNotSupported { feature });
    }
    (
        shadow.map(|(_, shadow)| shadow),
        glow.and_then(|(_, glow)| glow.into_option()),
        reflection.and_then(|(_, refl)| refl.into_option()),
    )
}

/// The drawable outer shadow, soft-edge radius (`a:softEdge`), glow (`a:glow`), and reflection
/// (`a:reflection`) of a picture's properties `props` (`pic:spPr`), warning in `warnings` of every
/// other unsupported effect or 3-D look. A soft edge or glow with `rad="0"`, or a reflection with
/// zero opacity, clears the warning and returns `None`.
pub(crate) fn picture_effects_of(
    doc: &Document,
    props: NodeId,
    warnings: &mut Warnings<Warning>,
) -> (
    Option<OuterShadow>,
    Option<Length>,
    Option<Glow>,
    Option<Reflection>,
) {
    let list = doc.child(props, A, "effectLst");
    let shadow = list
        .and_then(|list| doc.child(list, A, "outerShdw"))
        .and_then(|node| outer_shadow(doc, node, warnings).map(|shadow| (node, shadow)));
    let soft_edge = list
        .and_then(|list| doc.child(list, A, "softEdge"))
        .and_then(|node| {
            let rad = emus_of(doc, node, "rad", warnings).unwrap_or(Length::ZERO);
            (rad >= Length::ZERO).then_some((node, rad))
        });
    let glow = list
        .and_then(|list| doc.child(list, A, "glow"))
        .and_then(|node| glow_of(doc, node, warnings).map(|glow| (node, glow)));
    let reflection = list
        .and_then(|list| doc.child(list, A, "reflection"))
        .and_then(|node| reflection_of(doc, node, warnings).map(|refl| (node, refl)));
    let mut drawn = Vec::new();
    if let Some((node, _)) = &shadow {
        drawn.push(*node);
    }
    if let Some((node, _)) = &soft_edge {
        drawn.push(*node);
    }
    if let Some((node, _)) = &glow {
        drawn.push(*node);
    }
    if let Some((node, _)) = &reflection {
        drawn.push(*node);
    }
    for feature in features(doc, props, &drawn, warnings) {
        warnings.push(Warning::FeatureNotSupported { feature });
    }
    let radius = soft_edge.and_then(|(_, rad)| (rad > Length::ZERO).then_some(rad));
    (
        shadow.map(|(_, shadow)| shadow),
        radius,
        glow.and_then(|(_, glow)| glow.into_option()),
        reflection.and_then(|(_, refl)| refl.into_option()),
    )
}

/// An outer shadow defined in a theme's effect style (`a:effectStyle/a:effectLst/a:outerShdw`),
/// whose color is either a concrete [`DrawColor`] or the placeholder color (`phClr`) with its
/// [`PlaceholderModifiers`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ThemeShadow {
    blur: Length,
    distance: Length,
    direction: i64,
    turns_with_shape: bool,
    color: ThemeShadowColor,
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum ThemeShadowColor {
    Fixed(DrawColor),
    Placeholder(PlaceholderModifiers),
}

impl ThemeShadow {
    /// Resolves this theme shadow for a shape whose `a:effectRef` holds `reference_color`.
    pub(crate) fn resolve(&self, reference_color: Option<&DrawColor>) -> Option<OuterShadow> {
        let color = match &self.color {
            ThemeShadowColor::Fixed(color) => color.clone(),
            ThemeShadowColor::Placeholder(modifiers) => {
                reference_color?.clone().in_place_of(*modifiers)
            }
        };
        Some(OuterShadow {
            blur: self.blur,
            distance: self.distance,
            direction: self.direction,
            turns_with_shape: self.turns_with_shape,
            color,
        })
    }
}

/// The geometry of an outer shadow (`blur`, `distance`, `direction`, `turns_with_shape`) when
/// a layout can draw it (unscaled, unskewed, non-negative direction/blur/distance).
fn outer_shadow_geometry(
    doc: &Document,
    node: NodeId,
    warnings: &mut Warnings<Warning>,
) -> Option<(Length, Length, i64, bool)> {
    let mut value =
        |name: &str, default: i64| integer_of(doc, node, name, warnings).unwrap_or(default);
    let plain = value("sx", WHOLE_SCALE) == WHOLE_SCALE
        && value("sy", WHOLE_SCALE) == WHOLE_SCALE
        && value("kx", 0) == 0
        && value("ky", 0) == 0;
    let direction = value("dir", 0);
    if !plain || direction < 0 {
        return None;
    }
    let blur = emus_of(doc, node, "blurRad", warnings).unwrap_or(Length::ZERO);
    let distance = emus_of(doc, node, "dist", warnings).unwrap_or(Length::ZERO);
    if blur < Length::ZERO || distance < Length::ZERO {
        return None;
    }
    let turns_with_shape = doc
        .attribute(node, None, "rotWithShape")
        .is_none_or(crate::boolean);
    Some((blur, distance, direction, turns_with_shape))
}

/// The outer shadow of `node` (`a:outerShdw`), or `None` when a layout cannot draw it: when it
/// is scaled or skewed, or gives no color. A length or an angle that does not read counts as
/// missing, with a warning in `warnings`, and a missing one as the schema's default: no blur,
/// no distance, the direction 0 and no scale or skew.
fn outer_shadow(
    doc: &Document,
    node: NodeId,
    warnings: &mut Warnings<Warning>,
) -> Option<OuterShadow> {
    let (blur, distance, direction, turns_with_shape) = outer_shadow_geometry(doc, node, warnings)?;
    Some(OuterShadow {
        blur,
        distance,
        direction,
        turns_with_shape,
        color: DrawColor::read(doc, node, warnings)?,
    })
}

/// Reads an effect style (`a:effectStyle`) of a theme: its drawable outer shadow (supporting
/// both concrete colors and `phClr` with placeholder modifiers), and whether the style holds
/// any other effect or 3-D look that F-Office does not draw.
pub(crate) fn effect_style(
    doc: &Document,
    style: NodeId,
    warnings: &mut Warnings<Warning>,
) -> (Option<ThemeShadow>, bool) {
    let drawn = doc
        .child(style, A, "effectLst")
        .and_then(|list| doc.child(list, A, "outerShdw"))
        .and_then(|node| {
            let (blur, distance, direction, turns_with_shape) =
                outer_shadow_geometry(doc, node, warnings)?;
            let color = PlaceholderModifiers::read_child(doc, node, warnings)
                .map(ThemeShadowColor::Placeholder)
                .or_else(|| DrawColor::read(doc, node, warnings).map(ThemeShadowColor::Fixed))?;
            Some((
                node,
                ThemeShadow {
                    blur,
                    distance,
                    direction,
                    turns_with_shape,
                    color,
                },
            ))
        });
    let drawn_slice = drawn
        .as_ref()
        .map_or(&[][..], |(node, _)| std::slice::from_ref(node));
    let left_out = !features(doc, style, drawn_slice, warnings).is_empty();
    (drawn.map(|(_, shadow)| shadow), left_out)
}

/// The features of the effects and the 3-D look of the properties `props`, each once, as
/// [`effects`] warns of them, without the effects `drawn` that a layout draws, with the
/// warnings of the values of the 3-D look in `warnings`.
fn features(
    doc: &Document,
    props: NodeId,
    drawn: &[NodeId],
    warnings: &mut Warnings<Warning>,
) -> Vec<Feature> {
    let mut features = Vec::new();
    let listed = doc
        .child(props, A, "effectLst")
        .into_iter()
        .flat_map(|list| doc.child_elements(list))
        .filter(|effect| !drawn.contains(effect))
        .filter_map(|effect| {
            EFFECTS
                .iter()
                .find(|(name, _)| doc.is(effect, A, name))
                .map(|&(_, feature)| feature)
        });
    let graph = doc
        .child(props, A, "effectDag")
        .filter(|graph| doc.child_elements(*graph).next().is_some())
        .map(|_| Feature::OtherEffect);
    let look = three_d(doc, props, warnings).then_some(Feature::ThreeD);
    for feature in listed.chain(graph).chain(look) {
        if !features.contains(&feature) {
            features.push(feature);
        }
    }
    features
}

/// Whether the properties `props` give a 3-D look (ECMA-376 Part 1, 20.1.5): a camera
/// (`a:scene3d/a:camera`) other than the flat view from the front (`orthographicFront`) or
/// turned by its `a:rot`, or a shape with a bevel (`a:bevelT`, `a:bevelB`) of some size, an
/// extrusion (`extrusionH`) or a contour (`contourW`) other than zero (`a:sp3d`). A light rig alone
/// changes nothing on a flat shape, and a missing size of a bevel is the schema's default,
/// 76,200 EMU. A size or an angle that is given and does not read counts as zero, with a
/// warning in `warnings`. The 3-D look gives only the warning of [`Feature::ThreeD`], as
/// F-Office draws none.
fn three_d(doc: &Document, props: NodeId, warnings: &mut Warnings<Warning>) -> bool {
    let mut value = |node: NodeId, name: &str| {
        attribute_of(
            doc,
            node,
            name,
            |text| text.trim().parse::<i64>().ok(),
            warnings,
        )
    };
    let turned = doc
        .child(props, A, "scene3d")
        .and_then(|scene| doc.child(scene, A, "camera"))
        .is_some_and(|camera| {
            doc.attribute(camera, None, "prst") != Some("orthographicFront")
                || doc.child(camera, A, "rot").is_some_and(|rot| {
                    ["lat", "lon", "rev"]
                        .iter()
                        .any(|n| value(rot, n).is_some_and(|angle| angle != 0))
                })
        });
    let shaped = doc.child(props, A, "sp3d").is_some_and(|shape| {
        let bevel = ["bevelT", "bevelB"]
            .iter()
            .filter_map(|name| doc.child(shape, A, name))
            .any(|bevel| {
                ["w", "h"].iter().any(|n| {
                    doc.attribute(bevel, None, n).is_none()
                        || value(bevel, n).is_some_and(|size| size != 0)
                })
            });
        bevel
            || ["extrusionH", "contourW"]
                .iter()
                .any(|n| value(shape, n).is_some_and(|size| size != 0))
    });
    turned || shaped
}

/// A color effect of a picture (`a:blip` child, ECMA-376 Part 1, 20.1.8) that F-Office applies
/// to decoded pixels.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PictureColorEffect {
    /// Grayscale (`a:grayscl`).
    Grayscale,
    /// Brightness and contrast (`a:lum`), in thousandths of a percent (`-100_000..=100_000`).
    Luminance {
        /// Brightness shift in thousandths of a percent.
        bright: i32,
        /// Contrast adjustment in thousandths of a percent.
        contrast: i32,
    },
    /// Bi-level black-and-white threshold (`a:biLevel`), in thousandths of a percent
    /// (`0..=100_000`).
    BiLevel {
        /// Threshold in thousandths of a percent.
        threshold: i32,
    },
    /// Duotone linear ramp from `dark` to `light` by luminance (`a:duotone`).
    Duotone {
        /// Color mapped to black.
        dark: DrawColor,
        /// Color mapped to white.
        light: DrawColor,
    },
    /// Color replacement (`a:clrChange`).
    ColorChange {
        /// Source color to match.
        from: DrawColor,
        /// Replacement color (with optional alpha).
        to: DrawColor,
        /// Whether replacement updates alpha and uses the alpha-enabled matching tolerance.
        use_alpha: bool,
    },
}

impl PictureColorEffect {
    /// Resolves this picture color effect against `scheme`, returning `None` when a referenced
    /// theme color is absent from `scheme`.
    #[must_use]
    pub fn resolve(&self, scheme: &SchemeColors) -> Option<ColorEffect> {
        match self {
            Self::Grayscale => Some(ColorEffect::Gray709),
            Self::Luminance { bright, contrast } => Some(ColorEffect::Luminance {
                bright: *bright,
                contrast: *contrast,
            }),
            Self::BiLevel { threshold } => Some(ColorEffect::BiLevel {
                threshold: *threshold,
            }),
            Self::Duotone { dark, light } => Some(ColorEffect::Duotone {
                dark: dark.resolve(scheme)?.0,
                light: light.resolve(scheme)?.0,
            }),
            Self::ColorChange {
                from,
                to,
                use_alpha,
            } => {
                let (from, _) = from.resolve(scheme)?;
                let (to, opacity) = to.resolve(scheme)?;
                let alpha = (opacity.share() * 255 + 50_000) / 100_000;
                let to_alpha = u8::try_from(alpha.clamp(0, 255)).unwrap_or(u8::MAX);
                Some(ColorEffect::ColorChange {
                    from,
                    to,
                    to_alpha,
                    use_alpha: *use_alpha,
                })
            }
        }
    }
}

/// Reads the supported color effects of a picture's image (`a:blip`) in written element order
/// (`a:grayscl`, `a:lum`, `a:biLevel`, `a:duotone`, `a:clrChange`), and warns once in `warnings`
/// of [`Feature::PictureEffect`] when `blip` holds any other DrawingML color effect (or a
/// malformed supported one). Transparency (`a:alphaModFix`), extensions (`a:extLst`), and a zero
/// `a:lum` neither push a color effect nor warn.
pub fn picture_effects(
    doc: &Document,
    blip: NodeId,
    warnings: &mut Warnings<Warning>,
) -> Vec<PictureColorEffect> {
    let mut effects = Vec::new();
    let mut unsupported = false;
    for child in doc.child_elements(blip) {
        let Some(element) = doc.element(child) else {
            continue;
        };
        let name = element.name.local;
        if !doc.is(child, A, name) {
            continue;
        }
        match read_picture_effect(doc, child, name, warnings) {
            ReadPictureEffect::Ignore => {}
            ReadPictureEffect::Supported(effect) => effects.push(effect),
            ReadPictureEffect::Unsupported => unsupported = true,
        }
    }
    if unsupported {
        warnings.push(Warning::FeatureNotSupported {
            feature: Feature::PictureEffect,
        });
    }
    effects
}

enum ReadPictureEffect {
    Ignore,
    Supported(PictureColorEffect),
    Unsupported,
}

/// Reads one DrawingML child element of `a:blip`.
fn read_picture_effect(
    doc: &Document,
    node: NodeId,
    name: &str,
    warnings: &mut Warnings<Warning>,
) -> ReadPictureEffect {
    match name {
        "alphaModFix" | "extLst" => ReadPictureEffect::Ignore,
        "grayscl" => ReadPictureEffect::Supported(PictureColorEffect::Grayscale),
        "lum" => read_lum(doc, node),
        "biLevel" => read_bilevel(doc, node),
        "duotone" => read_duotone(doc, node, warnings),
        "clrChange" => read_clr_change(doc, node, warnings),
        _ => ReadPictureEffect::Unsupported,
    }
}

/// Reads `a:lum` (`bright`, `contrast`).
fn read_lum(doc: &Document, node: NodeId) -> ReadPictureEffect {
    let parse = |attr: &str| match doc.attribute(node, None, attr) {
        None => Some(0_i64),
        Some(value) => percentage(value),
    };
    let (Some(bright), Some(contrast)) = (parse("bright"), parse("contrast")) else {
        return ReadPictureEffect::Unsupported;
    };
    if bright == 0 && contrast == 0 {
        return ReadPictureEffect::Ignore;
    }
    let clamp = |v: i64| i32::try_from(v.clamp(-100_000, 100_000)).unwrap_or(0);
    ReadPictureEffect::Supported(PictureColorEffect::Luminance {
        bright: clamp(bright),
        contrast: clamp(contrast),
    })
}

/// Reads `a:biLevel` (`thresh`).
fn read_bilevel(doc: &Document, node: NodeId) -> ReadPictureEffect {
    let Some(thresh) = doc.attribute(node, None, "thresh").and_then(percentage) else {
        return ReadPictureEffect::Unsupported;
    };
    let threshold = i32::try_from(thresh.clamp(0, 100_000)).unwrap_or(0);
    ReadPictureEffect::Supported(PictureColorEffect::BiLevel { threshold })
}

/// Reads `a:duotone` (two direct color children).
fn read_duotone(
    doc: &Document,
    node: NodeId,
    warnings: &mut Warnings<Warning>,
) -> ReadPictureEffect {
    let mut colors = DrawColor::read_all(doc, node, warnings).into_iter();
    let (Some(dark), Some(light), None) = (colors.next(), colors.next(), colors.next()) else {
        return ReadPictureEffect::Unsupported;
    };
    ReadPictureEffect::Supported(PictureColorEffect::Duotone { dark, light })
}

/// Reads `a:clrChange` (`a:clrFrom`, `a:clrTo`, optional `useA` defaulting to `true`).
fn read_clr_change(
    doc: &Document,
    node: NodeId,
    warnings: &mut Warnings<Warning>,
) -> ReadPictureEffect {
    let from = doc
        .child(node, A, "clrFrom")
        .and_then(|c| DrawColor::read(doc, c, warnings));
    let to = doc
        .child(node, A, "clrTo")
        .and_then(|c| DrawColor::read(doc, c, warnings));
    let (Some(from), Some(to)) = (from, to) else {
        return ReadPictureEffect::Unsupported;
    };
    let use_alpha = doc.attribute(node, None, "useA").is_none_or(crate::boolean);
    ReadPictureEffect::Supported(PictureColorEffect::ColorChange {
        from,
        to,
        use_alpha,
    })
}

#[cfg(test)]
mod tests;