f-office-drawingml 0.2.2

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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
//! DrawingML colors (ECMA-376 Part 1, 20.1.2.3): RGB, theme and system colors with the
//! modifiers that lighten, darken or fade them, and the color scheme of a theme.

use f_office_paint::{Opacity, Rgb};
use f_office_units::scale::{DRAWING_WHOLE, THOUSANDTHS, THOUSANDTHS_DIGITS};
use f_office_warnings::Warnings;
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};

use crate::{A, Feature, Warning, attribute_of, case_of, element_name};

/// The names of the slots of a color scheme (`a:clrScheme`), in their order there.
const SLOTS: [&str; 12] = [
    "dk1", "lt1", "dk2", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6",
    "hlink", "folHlink",
];

/// `ST_SchemeColorVal`: each slot of the color scheme by its index in [`SLOTS`], the text and
/// background names, which stand for the dark and light slots, and the placeholder color of a
/// theme's style matrix (`phClr`), which F-Office draws as no color, because it reads no style
/// matrix.
const SCHEME: &Values<Option<usize>> = &Values::new(&[
    own("dk1", Some(0)),
    own("lt1", Some(1)),
    own("dk2", Some(2)),
    own("lt2", Some(3)),
    own("accent1", Some(4)),
    own("accent2", Some(5)),
    own("accent3", Some(6)),
    own("accent4", Some(7)),
    own("accent5", Some(8)),
    own("accent6", Some(9)),
    own("hlink", Some(10)),
    own("folHlink", Some(11)),
    own("tx1", Some(0)),
    own("bg1", Some(1)),
    own("tx2", Some(2)),
    own("bg2", Some(3)),
    another("phClr", None),
]);

/// The 190 names of `ST_PresetColorVal`, the type of `a:prstClr`, in the order of the schema
/// `dml-main.xsd` of ISO/IEC 29500-4:2016.
const PRESET_COLORS: [&str; 190] = [
    "aliceBlue",
    "antiqueWhite",
    "aqua",
    "aquamarine",
    "azure",
    "beige",
    "bisque",
    "black",
    "blanchedAlmond",
    "blue",
    "blueViolet",
    "brown",
    "burlyWood",
    "cadetBlue",
    "chartreuse",
    "chocolate",
    "coral",
    "cornflowerBlue",
    "cornsilk",
    "crimson",
    "cyan",
    "darkBlue",
    "darkCyan",
    "darkGoldenrod",
    "darkGray",
    "darkGrey",
    "darkGreen",
    "darkKhaki",
    "darkMagenta",
    "darkOliveGreen",
    "darkOrange",
    "darkOrchid",
    "darkRed",
    "darkSalmon",
    "darkSeaGreen",
    "darkSlateBlue",
    "darkSlateGray",
    "darkSlateGrey",
    "darkTurquoise",
    "darkViolet",
    "dkBlue",
    "dkCyan",
    "dkGoldenrod",
    "dkGray",
    "dkGrey",
    "dkGreen",
    "dkKhaki",
    "dkMagenta",
    "dkOliveGreen",
    "dkOrange",
    "dkOrchid",
    "dkRed",
    "dkSalmon",
    "dkSeaGreen",
    "dkSlateBlue",
    "dkSlateGray",
    "dkSlateGrey",
    "dkTurquoise",
    "dkViolet",
    "deepPink",
    "deepSkyBlue",
    "dimGray",
    "dimGrey",
    "dodgerBlue",
    "firebrick",
    "floralWhite",
    "forestGreen",
    "fuchsia",
    "gainsboro",
    "ghostWhite",
    "gold",
    "goldenrod",
    "gray",
    "grey",
    "green",
    "greenYellow",
    "honeydew",
    "hotPink",
    "indianRed",
    "indigo",
    "ivory",
    "khaki",
    "lavender",
    "lavenderBlush",
    "lawnGreen",
    "lemonChiffon",
    "lightBlue",
    "lightCoral",
    "lightCyan",
    "lightGoldenrodYellow",
    "lightGray",
    "lightGrey",
    "lightGreen",
    "lightPink",
    "lightSalmon",
    "lightSeaGreen",
    "lightSkyBlue",
    "lightSlateGray",
    "lightSlateGrey",
    "lightSteelBlue",
    "lightYellow",
    "ltBlue",
    "ltCoral",
    "ltCyan",
    "ltGoldenrodYellow",
    "ltGray",
    "ltGrey",
    "ltGreen",
    "ltPink",
    "ltSalmon",
    "ltSeaGreen",
    "ltSkyBlue",
    "ltSlateGray",
    "ltSlateGrey",
    "ltSteelBlue",
    "ltYellow",
    "lime",
    "limeGreen",
    "linen",
    "magenta",
    "maroon",
    "medAquamarine",
    "medBlue",
    "medOrchid",
    "medPurple",
    "medSeaGreen",
    "medSlateBlue",
    "medSpringGreen",
    "medTurquoise",
    "medVioletRed",
    "mediumAquamarine",
    "mediumBlue",
    "mediumOrchid",
    "mediumPurple",
    "mediumSeaGreen",
    "mediumSlateBlue",
    "mediumSpringGreen",
    "mediumTurquoise",
    "mediumVioletRed",
    "midnightBlue",
    "mintCream",
    "mistyRose",
    "moccasin",
    "navajoWhite",
    "navy",
    "oldLace",
    "olive",
    "oliveDrab",
    "orange",
    "orangeRed",
    "orchid",
    "paleGoldenrod",
    "paleGreen",
    "paleTurquoise",
    "paleVioletRed",
    "papayaWhip",
    "peachPuff",
    "peru",
    "pink",
    "plum",
    "powderBlue",
    "purple",
    "red",
    "rosyBrown",
    "royalBlue",
    "saddleBrown",
    "salmon",
    "sandyBrown",
    "seaGreen",
    "seaShell",
    "sienna",
    "silver",
    "skyBlue",
    "slateBlue",
    "slateGray",
    "slateGrey",
    "snow",
    "springGreen",
    "steelBlue",
    "tan",
    "teal",
    "thistle",
    "tomato",
    "turquoise",
    "violet",
    "wheat",
    "white",
    "whiteSmoke",
    "yellow",
    "yellowGreen",
];

/// `ST_PresetColorVal`: the red, green and blue of the colors that shapes use most; F-Office
/// draws every other name as no color.
const PRESET: &Values<Option<[u8; 3]>> = &Values::with_others(
    &[
        own("black", Some([0, 0, 0])),
        own("white", Some([255, 255, 255])),
        own("red", Some([255, 0, 0])),
        own("green", Some([0, 128, 0])),
        own("blue", Some([0, 0, 255])),
        own("yellow", Some([255, 255, 0])),
        own("gray", Some([128, 128, 128])),
        own("grey", Some([128, 128, 128])),
        own("darkGray", Some([169, 169, 169])),
        own("darkGrey", Some([169, 169, 169])),
        own("lightGray", Some([211, 211, 211])),
        own("lightGrey", Some([211, 211, 211])),
    ],
    &PRESET_COLORS,
    None,
);

/// The twelve colors of a theme's color scheme.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SchemeColors([Option<Rgb>; 12]);

impl SchemeColors {
    /// Reads an `a:clrScheme`, with the warnings of its colors' values in `warnings`.
    #[must_use]
    pub fn read(doc: &Document, scheme: NodeId, warnings: &mut Warnings<Warning>) -> Self {
        Self(SLOTS.map(|name| {
            let slot = doc.child(scheme, A, name)?;
            doc.child_elements(slot).find_map(|node| {
                match base(doc, node, ColorNames::DrawingMl, warnings) {
                    Some(Base::Rgb(rgb)) => Some(rgb),
                    _ => None,
                }
            })
        }))
    }

    /// The color of `slot`, or `None` when the scheme lacks it.
    #[must_use]
    pub fn get(&self, slot: SchemeSlot) -> Option<Rgb> {
        self.0.get(slot as usize).copied().flatten()
    }
}

/// A slot of a theme's color scheme, in the order of the scheme's elements, from `a:dk1` to
/// `a:folHlink`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SchemeSlot {
    /// `dk1`.
    Dark1,
    /// `lt1`.
    Light1,
    /// `dk2`.
    Dark2,
    /// `lt2`.
    Light2,
    /// `accent1`.
    Accent1,
    /// `accent2`.
    Accent2,
    /// `accent3`.
    Accent3,
    /// `accent4`.
    Accent4,
    /// `accent5`.
    Accent5,
    /// `accent6`.
    Accent6,
    /// `hlink`.
    Hyperlink,
    /// `folHlink`.
    FollowedHyperlink,
}

/// A step of a color's lightness toward white or black, by a share in 255ths of the way that the
/// color keeps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LightnessStep {
    /// Toward white: the new HSL lightness is `L * t + (1 - t)`, with `t` the share kept.
    Tint(u8),
    /// Toward black: the new HSL lightness is `L * t`.
    Shade(u8),
}

impl LightnessStep {
    /// The color with its HSL lightness stepped and its hue and saturation kept, each channel cut
    /// to a whole step toward zero.
    #[must_use]
    pub fn apply(self, rgb: Rgb) -> Rgb {
        let whole = i64::from(u8::MAX);
        let channels = [rgb.r, rgb.g, rgb.b].map(|c| i64::from(c) * MILLI);
        let channels = with_lightness(channels, |l| match self {
            Self::Tint(kept) => {
                let kept = i64::from(kept);
                l * kept / whole + LIGHTNESS * (whole - kept) / whole
            }
            Self::Shade(kept) => l * i64::from(kept) / whole,
        });
        let [r, g, b] =
            channels.map(|c| u8::try_from((c / MILLI).clamp(0, whole)).unwrap_or(u8::MAX));
        Rgb { r, g, b }
    }
}

/// A color as a file gives it, which a theme's colors resolve.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DrawColor {
    base: Base,
    modifiers: Vec<Modifier>,
}

/// The namespaces of a color's elements and of their values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ColorNames {
    /// DrawingML's colors, whose values carry no namespace: `a:srgbClr val="4472C4"`
    /// (ECMA-376 Part 1, 20.1.2.3).
    DrawingMl,
    /// The colors of the text effects of WordprocessingML 2010, whose elements and values both
    /// carry its namespace: `w14:srgbClr w14:val="4472C4"` ([MS-DOCX] 2.6.1).
    Word2010,
}

impl ColorNames {
    /// The namespace of the color elements and their modifiers.
    const fn elements(self) -> &'static str {
        match self {
            Self::DrawingMl => A,
            Self::Word2010 => WORD_2010,
        }
    }

    /// The namespace of their `val` attributes, if any.
    const fn values(self) -> Option<&'static str> {
        match self {
            Self::DrawingMl => None,
            Self::Word2010 => Some(WORD_2010),
        }
    }
}

/// The namespace of WordprocessingML 2010 ([MS-DOCX] 2.1).
pub(crate) const WORD_2010: &str = "http://schemas.microsoft.com/office/word/2010/wordml";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Base {
    Rgb(Rgb),
    /// The index of a slot of the color scheme.
    Scheme(usize),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Modifier {
    LumMod(i64),
    LumOff(i64),
    Shade(i64),
    Tint(i64),
    Alpha(i64),
    /// A factor of the saturation in HSL (`a:satMod`).
    SatMod(i64),
    /// Each channel's value taken as linear light and given as its sRGB value (`a:gamma`).
    Gamma,
    /// Each channel's sRGB value given as its linear light (`a:invGamma`), the reverse of
    /// [`Modifier::Gamma`].
    InvGamma,
}

/// The most modifiers of a style's placeholder color that [`PlaceholderModifiers`] holds.
const MOST_PLACEHOLDER_MODIFIERS: usize = 4;

/// The modifiers of the placeholder color (`a:schemeClr val="phClr"`) of a solid fill of a
/// theme's style, which apply after the modifiers of the color that takes its place: those
/// that F-Office applies to a color. A modifier that changes nothing, such as `a:satOff` of
/// zero, is left out.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PlaceholderModifiers([Option<Modifier>; MOST_PLACEHOLDER_MODIFIERS]);

impl PlaceholderModifiers {
    /// The modifiers of the solid fill `fill` (`a:solidFill`) whose only color is the
    /// placeholder color, or `None` for another fill, for a modifier that F-Office does not
    /// apply and that changes the color, and for more than [`MOST_PLACEHOLDER_MODIFIERS`].
    pub(crate) fn read(
        doc: &Document,
        fill: NodeId,
        warnings: &mut Warnings<Warning>,
    ) -> Option<Self> {
        doc.is(fill, A, "solidFill")
            .then(|| Self::read_child(doc, fill, warnings))
            .flatten()
    }

    /// The modifiers of `parent` whose only child element is `<a:schemeClr val="phClr">`, or
    /// `None` for any other color, for an unread modifier that changes the color, or for more
    /// than [`MOST_PLACEHOLDER_MODIFIERS`].
    pub(crate) fn read_child(
        doc: &Document,
        parent: NodeId,
        warnings: &mut Warnings<Warning>,
    ) -> Option<Self> {
        let mut colors = doc.child_elements(parent);
        let color = match (colors.next(), colors.next()) {
            (Some(color), None)
                if doc.is(color, A, "schemeClr")
                    && doc.attribute(color, None, "val") == Some("phClr") =>
            {
                color
            }
            _ => return None,
        };
        let mut found = [None; MOST_PLACEHOLDER_MODIFIERS];
        let mut count = 0;
        for child in doc.child_elements(color) {
            if changes_unread(doc, child, ColorNames::DrawingMl, warnings) {
                return None;
            }
            if let Some(modifier) = modifier(doc, child, ColorNames::DrawingMl, warnings) {
                *found.get_mut(count)? = Some(modifier);
                count += 1;
            }
        }
        Some(Self(found))
    }
}

impl DrawColor {
    /// A color without modifiers.
    #[must_use]
    pub fn rgb(rgb: Rgb) -> Self {
        Self {
            base: Base::Rgb(rgb),
            modifiers: Vec::new(),
        }
    }

    /// The color of `slot` of the theme's color scheme, without modifiers.
    #[must_use]
    pub fn scheme(slot: SchemeSlot) -> Self {
        Self {
            base: Base::Scheme(slot as usize),
            modifiers: Vec::new(),
        }
    }

    /// The color mixed with black in linear light (`a:shade`), keeping `kept` of each channel,
    /// in thousandths of a percent.
    #[must_use]
    pub fn shaded(mut self, kept: i64) -> Self {
        self.modifiers.push(Modifier::Shade(kept));
        self
    }

    /// The color mixed with white in linear light (`a:tint`), keeping `kept` of each channel,
    /// in thousandths of a percent.
    #[must_use]
    pub fn tinted(mut self, kept: i64) -> Self {
        self.modifiers.push(Modifier::Tint(kept));
        self
    }

    /// The color in place of a style's placeholder color, with the placeholder's modifiers
    /// after its own.
    #[must_use]
    pub fn in_place_of(mut self, placeholder: PlaceholderModifiers) -> Self {
        self.modifiers.extend(placeholder.0.into_iter().flatten());
        self
    }

    /// Reads the first color element inside `parent`, such as the child of `a:solidFill` or
    /// of a style reference, with the warnings of its value in `warnings`. The modifiers of
    /// hue, of the saturation other than its factor, of the red, green and blue channels and
    /// of gray are not read: a color with one that changes the color warns once of
    /// [`Feature::ColorModifier`].
    #[must_use]
    pub fn read(doc: &Document, parent: NodeId, warnings: &mut Warnings<Warning>) -> Option<Self> {
        Self::read_in(doc, parent, ColorNames::DrawingMl, warnings)
    }

    /// Reads the first color element inside `parent` as [`Self::read`] does, in the elements
    /// and values of `names`: a color of a text effect of WordprocessingML 2010, such as the
    /// child of `w14:solidFill` or of `w14:shadow`, with [`ColorNames::Word2010`].
    #[must_use]
    pub fn read_in(
        doc: &Document,
        parent: NodeId,
        names: ColorNames,
        warnings: &mut Warnings<Warning>,
    ) -> Option<Self> {
        Self::read_marked(doc, parent, names, warnings).map(|(color, _)| color)
    }

    /// Reads one color element `node`, with its warnings and whether it holds an unread modifier.
    fn read_element(
        doc: &Document,
        node: NodeId,
        names: ColorNames,
        warnings: &mut Warnings<Warning>,
    ) -> Option<(Self, bool)> {
        let base = base(doc, node, names, warnings)?;
        let modifiers = doc
            .child_elements(node)
            .filter_map(|child| modifier(doc, child, names, warnings))
            .collect();
        let unread = doc
            .child_elements(node)
            .any(|child| changes_unread(doc, child, names, warnings));
        if unread {
            warnings.push(Warning::FeatureNotSupported {
                feature: Feature::ColorModifier,
            });
        }
        Some((Self { base, modifiers }, unread))
    }

    /// Reads every DrawingML color child directly inside `parent` (such as the two colors of
    /// `a:duotone`).
    pub(crate) fn read_all(
        doc: &Document,
        parent: NodeId,
        warnings: &mut Warnings<Warning>,
    ) -> Vec<Self> {
        doc.child_elements(parent)
            .filter_map(|node| {
                Self::read_element(doc, node, ColorNames::DrawingMl, warnings)
                    .map(|(color, _)| color)
            })
            .collect()
    }

    /// Reads the color as [`Self::read`] does, with its warnings, and whether it has a modifier
    /// that F-Office does not apply and that changes the color.
    pub(crate) fn read_marked(
        doc: &Document,
        parent: NodeId,
        names: ColorNames,
        warnings: &mut Warnings<Warning>,
    ) -> Option<(Self, bool)> {
        doc.child_elements(parent)
            .find_map(|node| Self::read_element(doc, node, names, warnings))
    }

    /// Whether the color is opaque: whether none of its alpha modifiers (`a:alpha`) is below a
    /// whole.
    pub(crate) fn opaque(&self) -> bool {
        self.modifiers.iter().all(|modifier| match *modifier {
            Modifier::Alpha(value) => Opacity::clamped(value) == Opacity::FULL,
            _ => true,
        })
    }

    /// The color with its modifiers applied, and its opacity. A theme color that the scheme
    /// lacks gives `None`.
    ///
    /// `lumMod` and `lumOff` change the lightness in HSL, `satMod` the saturation in HSL,
    /// `shade` and `tint` mix the color with black or white in linear light, and `gamma` takes
    /// each channel's value as linear light and gives its sRGB value, `invGamma` the reverse.
    #[must_use]
    pub fn resolve(&self, scheme: &SchemeColors) -> Option<(Rgb, Opacity)> {
        let rgb = match self.base {
            Base::Rgb(rgb) => rgb,
            Base::Scheme(index) => scheme.0.get(index).copied().flatten()?,
        };
        // The channels stay in thousandths of a step until the end, so that rounding does not
        // add up over several modifiers.
        let mut channels = [rgb.r, rgb.g, rgb.b].map(|c| i64::from(c) * MILLI);
        let mut alpha = Opacity::FULL;
        for modifier in &self.modifiers {
            channels = match *modifier {
                Modifier::LumMod(value) => with_lightness(channels, |l| l * value / DRAWING_WHOLE),
                Modifier::LumOff(value) => {
                    with_lightness(channels, |l| l + LIGHTNESS * value / DRAWING_WHOLE)
                }
                Modifier::Shade(value) => in_linear_light(channels, |l| l * value / DRAWING_WHOLE),
                Modifier::Tint(value) => in_linear_light(channels, |l| {
                    l * value / DRAWING_WHOLE
                        + LINEAR_WHITE * (DRAWING_WHOLE - value) / DRAWING_WHOLE
                }),
                Modifier::Alpha(value) => {
                    alpha = Opacity::clamped(value);
                    channels
                }
                Modifier::SatMod(value) => with_saturation(channels, value),
                Modifier::Gamma => {
                    channels.map(|c| from_linear(scaled(c, LINEAR_WHITE, 255 * MILLI)))
                }
                Modifier::InvGamma => {
                    channels.map(|c| scaled(to_linear(c), 255 * MILLI, LINEAR_WHITE))
                }
            };
        }
        let [r, g, b] =
            channels.map(|c| u8::try_from(((c + MILLI / 2) / MILLI).clamp(0, 255)).unwrap_or(255));
        Some((Rgb { r, g, b }, alpha))
    }
}

/// Thousandths of a channel step.
const MILLI: i64 = 1_000;

/// Mixes a color with the opacity `alpha` over a white page.
#[must_use]
pub fn on_white(rgb: Rgb, alpha: Opacity) -> Rgb {
    let alpha = alpha.share();
    let mix = |c: u8| {
        let value = (i64::from(c) * alpha + 255 * (DRAWING_WHOLE - alpha) + DRAWING_WHOLE / 2)
            / DRAWING_WHOLE;
        u8::try_from(value.clamp(0, 255)).unwrap_or(255)
    };
    Rgb {
        r: mix(rgb.r),
        g: mix(rgb.g),
        b: mix(rgb.b),
    }
}

/// Reads the color of a color element, without its modifiers, with the warnings of a scheme or
/// preset color's name in `warnings`.
fn base(
    doc: &Document,
    node: NodeId,
    names: ColorNames,
    warnings: &mut Warnings<Warning>,
) -> Option<Base> {
    let elements = names.elements();
    let value = doc.attribute(node, names.values(), "val");
    if doc.is(node, elements, "srgbClr") {
        return value.and_then(Rgb::from_hex).map(Base::Rgb);
    }
    if doc.is(node, elements, "schemeClr") {
        return named(doc, node, value, (SCHEME, warnings))
            .flatten()
            .map(Base::Scheme);
    }
    // The name of a system color stays outside the one reader of enumerations: text outside
    // the type reads as a system color, the color of `lastClr` or else black, where a missing
    // name gives no color. Every name of the type is drawn, as the color of `lastClr`.
    if doc.is(node, elements, "sysClr") {
        let last = doc.attribute(node, None, "lastClr").and_then(Rgb::from_hex);
        let fallback = match value? {
            "window" => Rgb {
                r: 255,
                g: 255,
                b: 255,
            },
            _ => Rgb::BLACK,
        };
        return Some(Base::Rgb(last.unwrap_or(fallback)));
    }
    if doc.is(node, elements, "prstClr") {
        return named(doc, node, value, (PRESET, warnings))
            .flatten()
            .map(|[r, g, b]| Base::Rgb(Rgb { r, g, b }));
    }
    if OTHER_MODELS.iter().any(|name| doc.is(node, elements, name)) {
        warnings.push(Warning::FeatureNotSupported {
            feature: Feature::ColorModel,
        });
    }
    None
}

/// The case in `table` of `value`, the value (`val`) of the color element `node` in its
/// namespace, with a warning in `warnings` of a value outside the table; `None` for a missing
/// value too.
fn named<T: Clone>(
    doc: &Document,
    node: NodeId,
    value: Option<&str>,
    (table, warnings): (&'static Values<T>, &mut Warnings<Warning>),
) -> Option<T> {
    case_of(value?, (&element_name(doc, node), "val"), (table, warnings))
}

/// The color elements of the models that F-Office does not read (ECMA-376 Part 1, 20.1.2.3):
/// HSL (`a:hslClr`) and scRGB (`a:scrgbClr`), which give no color
/// ([`Feature::ColorModel`]).
const OTHER_MODELS: [&str; 2] = ["hslClr", "scrgbClr"];

/// The modifier of a color that a value makes.
type MakeModifier = fn(i64) -> Modifier;

/// The modifiers of a color without a value that F-Office applies, by their element names.
const VALUELESS_MODIFIERS: [(&str, Modifier); 2] =
    [("gamma", Modifier::Gamma), ("invGamma", Modifier::InvGamma)];

/// The modifiers of a color of a value that F-Office applies, by their element names.
const MODIFIERS: [(&str, MakeModifier); 6] = [
    ("satMod", Modifier::SatMod),
    ("lumMod", Modifier::LumMod),
    ("lumOff", Modifier::LumOff),
    ("shade", Modifier::Shade),
    ("tint", Modifier::Tint),
    ("alpha", Modifier::Alpha),
];

/// The modifier that the child `node` of a color element makes, when F-Office applies it: none
/// for a value that does not read, which counts as missing, with a warning in `warnings`.
fn modifier(
    doc: &Document,
    node: NodeId,
    names: ColorNames,
    warnings: &mut Warnings<Warning>,
) -> Option<Modifier> {
    let elements = names.elements();
    if let Some(&(_, valueless)) = VALUELESS_MODIFIERS
        .iter()
        .find(|(name, _)| doc.is(node, elements, name))
    {
        return Some(valueless);
    }
    let (_, kind) = MODIFIERS
        .into_iter()
        .find(|(name, _)| doc.is(node, elements, name))?;
    let value = modifier_value(doc, node, names, warnings)?;
    Some(kind(value))
}

/// The percentage of the modifier `node` in the values of `names`, with a warning in `warnings`
/// when it does not read.
fn modifier_value(
    doc: &Document,
    node: NodeId,
    names: ColorNames,
    warnings: &mut Warnings<Warning>,
) -> Option<i64> {
    let Some(namespace) = names.values() else {
        return attribute_of(doc, node, "val", percentage, warnings);
    };
    let value = percentage(doc.attribute(node, Some(namespace), "val")?);
    if value.is_none() {
        warnings.push(Warning::InvalidValue {
            element: element_name(doc, node),
            attribute: f_office_warnings::Name::new("val"),
        });
    }
    value
}

/// Whether the child `node` of a color element is a modifier that F-Office does not apply
/// ([`Feature::ColorModifier`]) and that changes the color. Each other child of a color
/// element is a modifier (ECMA-376 Part 1, 20.1.2.3). An offset of zero (a name that ends
/// in `Off`, such as `a:satOff`) and a factor of 100,000ths that is 100 % (one that ends in
/// `Mod`, such as `a:hueMod`) change nothing; SmartArt's drawings write them often. A value
/// that does not read counts as missing, with a warning in `warnings`.
fn changes_unread(
    doc: &Document,
    node: NodeId,
    names: ColorNames,
    warnings: &mut Warnings<Warning>,
) -> bool {
    let Some(element) = doc.element(node) else {
        return false;
    };
    let name = element.name.local;
    if !doc.is(node, names.elements(), name)
        || MODIFIERS.iter().any(|(read, _)| *read == name)
        || VALUELESS_MODIFIERS.iter().any(|(read, _)| *read == name)
    {
        return false;
    }
    let value = modifier_value(doc, node, names, warnings);
    let unchanged = if name.ends_with("Off") {
        Some(0)
    } else if name.ends_with("Mod") {
        Some(DRAWING_WHOLE)
    } else {
        None
    };
    unchanged.is_none() || value != unchanged
}

/// Reads a DrawingML percentage (`ST_Percentage`, ECMA-376 Part 1, 20.1.10.40) in 1,000ths of a
/// percent: a whole number such as `60000`, as Transitional files write it, or a decimal number
/// with a percent sign such as `-1.5%`, as Strict files write it. Spaces around the value do not
/// count. A value that the type forbids, such as a second sign or a non-digit in the fraction,
/// gives `None`, and so does one whose thousandths lie beyond the 32 bits of `xsd:int`, the
/// type of the whole number (`ST_PercentageDecimal`), in either form: the products of a
/// percentage with a length or a color then fit. Digits past the third of the fraction are
/// dropped.
#[must_use]
pub fn percentage(text: &str) -> Option<i64> {
    let text = text.trim();
    let Some(number) = text.strip_suffix('%') else {
        return text.parse::<i32>().ok().map(i64::from);
    };
    let digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
    let (negative, number) = match number.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, number),
    };
    let (whole, fraction) = match number.split_once('.') {
        Some((whole, fraction)) if digits(fraction) => (whole, fraction),
        Some(_) => return None,
        None => (number, ""),
    };
    if !digits(whole) {
        return None;
    }
    let thousandths: String = fraction
        .chars()
        .chain("000".chars())
        .take(THOUSANDTHS_DIGITS)
        .collect();
    let value = whole
        .parse::<i64>()
        .ok()?
        .checked_mul(THOUSANDTHS)?
        .checked_add(thousandths.parse().ok()?)?;
    let value = if negative { -value } else { value };
    i32::try_from(value).ok().map(i64::from)
}

/// Twice the largest HSL lightness, in thousandths of a channel step.
const LIGHTNESS: i64 = 510_000;

/// Changes the HSL lightness of a color, in thousandths of a step, and keeps its hue and
/// saturation. `change` maps twice the lightness, from 0 to [`LIGHTNESS`], to its new value.
fn with_lightness(channels: [i64; 3], change: impl Fn(i64) -> i64) -> [i64; 3] {
    let high = channels.iter().copied().max().unwrap_or(0);
    let low = channels.iter().copied().min().unwrap_or(0);
    let half = LIGHTNESS / 2;
    // The largest chroma at a lightness, which the saturation is a share of.
    let room = |l: i64| half - (l - half).abs();
    let lightness = high + low;
    let new = change(lightness).clamp(0, LIGHTNESS);
    let chroma = high - low;
    let new_chroma = if room(lightness) == 0 {
        0
    } else {
        chroma * room(new) / room(lightness)
    };
    let new_low = (new - new_chroma) / 2;
    channels.map(|c| {
        if chroma == 0 {
            new_low
        } else {
            new_low + (c - low) * new_chroma / chroma
        }
    })
}

/// Changes the saturation of a color in HSL by the factor `factor`, in thousandths of a
/// percent, keeping its hue and its lightness: its chroma times the factor. A saturation
/// above the whole is kept, and each channel that it takes beyond black or white is cut to
/// it. A gray stays as it is.
fn with_saturation(channels: [i64; 3], factor: i64) -> [i64; 3] {
    let high = channels.iter().copied().max().unwrap_or(0);
    let low = channels.iter().copied().min().unwrap_or(0);
    let lightness = high + low;
    let chroma = high - low;
    let new_chroma = (chroma * factor / DRAWING_WHOLE).max(0);
    let new_low = (lightness - new_chroma) / 2;
    channels.map(|c| {
        if chroma == 0 {
            c
        } else {
            (new_low + (c - low) * new_chroma / chroma).clamp(0, 255 * MILLI)
        }
    })
}

/// Linear light of white in [`TO_LINEAR`].
const LINEAR_WHITE: i64 = 65_535;

/// `value` times `numerator` over `denominator`, rounded to the nearest, a half up, for
/// non-negative numbers.
fn scaled(value: i64, numerator: i64, denominator: i64) -> i64 {
    (value * numerator + denominator / 2) / denominator
}

/// Changes each channel of a color, in thousandths of a step, in linear light. `change` maps a
/// linear value, from 0 to [`LINEAR_WHITE`], to its new value.
fn in_linear_light(channels: [i64; 3], change: impl Fn(i64) -> i64) -> [i64; 3] {
    channels.map(|c| from_linear(change(to_linear(c)).clamp(0, LINEAR_WHITE)))
}

/// The table value at a channel step, as an `i64`.
fn table(index: usize) -> i64 {
    TO_LINEAR
        .get(index)
        .copied()
        .map_or(LINEAR_WHITE, i64::from)
}

/// The linear light of a channel in thousandths of a step, between the table's values.
fn to_linear(channel: i64) -> i64 {
    let channel = channel.clamp(0, 255 * MILLI);
    let index = usize::try_from(channel / MILLI).unwrap_or(0);
    let low = table(index);
    low + (table(index + 1) - low) * (channel % MILLI) / MILLI
}

/// The channel in thousandths of a step whose linear light is `linear`, between the table's
/// values.
fn from_linear(linear: i64) -> i64 {
    let above = TO_LINEAR.partition_point(|&value| i64::from(value) < linear);
    if above == 0 {
        return 0;
    }
    let (low, high) = (table(above - 1), table(above));
    let step = i64::try_from(above - 1).unwrap_or(0) * MILLI;
    if high == low {
        step
    } else {
        step + (linear - low) * MILLI / (high - low)
    }
}

/// The linear light of each sRGB channel value (IEC 61966-2-1), scaled to 65,535.
const TO_LINEAR: [u16; 256] = [
    0, 20, 40, 60, 80, 99, 119, 139, 159, 179, 199, 219, 241, 264, 288, 313, 340, 367, 396, 427,
    458, 491, 526, 562, 599, 637, 677, 718, 761, 805, 851, 898, 947, 997, 1048, 1101, 1156, 1212,
    1270, 1330, 1391, 1453, 1517, 1583, 1651, 1720, 1790, 1863, 1937, 2013, 2090, 2170, 2250, 2333,
    2418, 2504, 2592, 2681, 2773, 2866, 2961, 3058, 3157, 3258, 3360, 3464, 3570, 3678, 3788, 3900,
    4014, 4129, 4247, 4366, 4488, 4611, 4736, 4864, 4993, 5124, 5257, 5392, 5530, 5669, 5810, 5953,
    6099, 6246, 6395, 6547, 6700, 6856, 7014, 7174, 7335, 7500, 7666, 7834, 8004, 8177, 8352, 8528,
    8708, 8889, 9072, 9258, 9445, 9635, 9828, 10022, 10219, 10417, 10619, 10822, 11028, 11235,
    11446, 11658, 11873, 12090, 12309, 12530, 12754, 12980, 13209, 13440, 13673, 13909, 14146,
    14387, 14629, 14874, 15122, 15371, 15623, 15878, 16135, 16394, 16656, 16920, 17187, 17456,
    17727, 18001, 18277, 18556, 18837, 19121, 19407, 19696, 19987, 20281, 20577, 20876, 21177,
    21481, 21787, 22096, 22407, 22721, 23038, 23357, 23678, 24002, 24329, 24658, 24990, 25325,
    25662, 26001, 26344, 26688, 27036, 27386, 27739, 28094, 28452, 28813, 29176, 29542, 29911,
    30282, 30656, 31033, 31412, 31794, 32179, 32567, 32957, 33350, 33745, 34143, 34544, 34948,
    35355, 35764, 36176, 36591, 37008, 37429, 37852, 38278, 38706, 39138, 39572, 40009, 40449,
    40891, 41337, 41785, 42236, 42690, 43147, 43606, 44069, 44534, 45002, 45473, 45947, 46423,
    46903, 47385, 47871, 48359, 48850, 49344, 49841, 50341, 50844, 51349, 51858, 52369, 52884,
    53401, 53921, 54445, 54971, 55500, 56032, 56567, 57105, 57646, 58190, 58737, 59287, 59840,
    60396, 60955, 61517, 62082, 62650, 63221, 63795, 64372, 64952, 65535,
];

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::{
        DrawColor, LightnessStep, PRESET, PRESET_COLORS, SCHEME, SLOTS, SchemeColors, SchemeSlot,
        on_white, percentage,
    };
    use crate::{A, Warning};
    use f_office_paint::{Opacity, Rgb};
    use f_office_warnings::{Name, Warnings};
    use f_office_xml::{Document, Limits};

    #[test]
    fn steps_the_lightness_and_cuts_each_channel_toward_zero() {
        let hex = |text: &str| Rgb::from_hex(text).unwrap();
        let cases = [
            ("4472C4", LightnessStep::Tint(0x99), "8EAADB"),
            ("4472C4", LightnessStep::Shade(0xBF), "2F5496"),
            ("A5A5A5", LightnessStep::Tint(0x33), "EDEDED"),
            ("70AD47", LightnessStep::Tint(0x66), "C5E0B3"),
            ("FFC000", LightnessStep::Shade(0x40), "403000"),
            ("4472C4", LightnessStep::Tint(0xFF), "4472C4"),
            ("4472C4", LightnessStep::Tint(0), "FFFFFF"),
            ("4472C4", LightnessStep::Shade(0), "000000"),
        ];
        for (color, step, stepped) in cases {
            assert_eq!(step.apply(hex(color)), hex(stepped), "{color} {step:?}");
        }
    }

    #[test]
    fn gives_the_color_of_a_slot() {
        let scheme = scheme();
        assert_eq!(scheme.get(SchemeSlot::Accent1), Rgb::from_hex("4472C4"));
        assert_eq!(scheme.get(SchemeSlot::Dark1), Some(Rgb::BLACK));
        assert_eq!(scheme.get(SchemeSlot::Light2), Rgb::from_hex("E7E6E6"));
        assert_eq!(scheme.get(SchemeSlot::Accent2), None);
    }

    #[test]
    fn reads_percentages_of_both_forms_and_refuses_what_the_type_forbids() {
        let cases = [
            ("25000", Some(25_000)),
            ("-25000", Some(-25_000)),
            ("12.5%", Some(12_500)),
            ("-0.25%", Some(-250)),
            ("-1.5%", Some(-1_500)),
            ("-3.5%", Some(-3_500)),
            ("7%", Some(7_000)),
            ("1.2345%", Some(1_234)),
            (" 45500 ", Some(45_500)),
            (" 45.5% ", Some(45_500)),
            ("2147483647", Some(2_147_483_647)),
            ("-2147483648", Some(-2_147_483_648)),
            ("2147483.647%", Some(2_147_483_647)),
            ("-2147483.648%", Some(-2_147_483_648)),
            ("2147483648", None),
            ("-2147483649", None),
            ("2147483.648%", None),
            ("-2147483.649%", None),
            ("99999999999999999%", None),
            ("--5%", None),
            ("+5%", None),
            ("-+5%", None),
            ("5.%", None),
            (".5%", None),
            ("1.2345x%", None),
            ("1.+5%", None),
            ("x%", None),
            ("1.x%", None),
            ("", None),
        ];
        for (text, expected) in cases {
            assert_eq!(percentage(text), expected, "{text}");
        }
    }

    fn parse(xml: &str) -> Document {
        Document::parse(
            format!(r#"<a:x xmlns:a="{A}">{xml}</a:x>"#).as_bytes(),
            &Limits::default(),
        )
        .unwrap()
    }

    const SCHEME_XML: &str = r#"<a:clrScheme><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:clrScheme>"#;

    fn scheme() -> SchemeColors {
        let doc = parse(SCHEME_XML);
        let node = doc.child_elements(doc.root().unwrap()).next().unwrap();
        SchemeColors::read(&doc, node, &mut Warnings::new())
    }

    /// Resolves the color inside `<a:solidFill>`.
    fn color(fill: &str) -> Option<(Rgb, Opacity)> {
        color_warned(fill).0
    }

    /// [`color`], with the warnings of the reading.
    fn color_warned(fill: &str) -> (Option<(Rgb, Opacity)>, Vec<Warning>) {
        let doc = parse(fill);
        let mut warnings = Warnings::new();
        let found = DrawColor::read(&doc, doc.root().unwrap(), &mut warnings)
            .and_then(|color| color.resolve(&scheme()));
        (
            found,
            warnings
                .iter()
                .map(|(warning, _)| warning.clone())
                .collect(),
        )
    }

    #[test]
    fn warns_of_a_scheme_or_preset_color_that_it_draws_as_none() {
        let not_drawn = |element: &str, value: &str| Warning::ValueNotSupported {
            element: Name::new(element),
            attribute: Name::new("val"),
            value: Name::new(value),
        };
        let invalid = |element: &str| Warning::InvalidValue {
            element: Name::new(element),
            attribute: Name::new("val"),
        };
        let cases = [
            (
                r#"<a:schemeClr val="phClr"/>"#,
                None,
                vec![not_drawn("schemeClr", "phClr")],
            ),
            (
                r#"<a:prstClr val="aliceBlue"/>"#,
                None,
                vec![not_drawn("prstClr", "aliceBlue")],
            ),
            (
                r#"<a:prstClr val="lightGrey"/>"#,
                Some(rgb(211, 211, 211)),
                vec![],
            ),
            // A name in another case, a name with space around it and an empty value.
            (
                r#"<a:schemeClr val="Accent1"/>"#,
                None,
                vec![invalid("schemeClr")],
            ),
            (
                r#"<a:schemeClr val=" accent1"/>"#,
                None,
                vec![invalid("schemeClr")],
            ),
            (r#"<a:prstClr val=""/>"#, None, vec![invalid("prstClr")]),
        ];
        for (xml, want, warnings) in cases {
            let found = color_warned(xml);
            assert_eq!(
                found,
                (want.map(|rgb| (rgb, Opacity::FULL)), warnings),
                "{xml}"
            );
        }
    }

    #[test]
    fn the_color_tables_hold_the_names_of_their_types() {
        let mut scheme: Vec<&str> = SCHEME.names().into_iter().map(|(name, _)| name).collect();
        let mut listed: Vec<&str> = "bg1 tx1 bg2 tx2 accent1 accent2 accent3 accent4 accent5 \
                                     accent6 hlink folHlink phClr dk1 lt1 dk2 lt2"
            .split_whitespace()
            .collect();
        scheme.sort_unstable();
        listed.sort_unstable();
        assert_eq!(scheme, listed);
        for (index, slot) in SLOTS.iter().enumerate() {
            assert_eq!(
                SCHEME.find(slot).map(|(case, _, _)| *case),
                Some(Some(index))
            );
        }
        // Each name of `ST_PresetColorVal` once, and each drawn color among them.
        let presets: HashSet<&str> = PRESET_COLORS.iter().copied().collect();
        assert_eq!((PRESET_COLORS.len(), presets.len()), (190, 190));
        assert_eq!(PRESET.names().len(), 190);
    }

    fn rgb(r: u8, g: u8, b: u8) -> Rgb {
        Rgb { r, g, b }
    }

    #[test]
    fn reads_plain_and_theme_colors() {
        let cases = [
            (r#"<a:srgbClr val="1F3864"/>"#, Some(rgb(31, 56, 100))),
            (r#"<a:schemeClr val="accent1"/>"#, Some(rgb(68, 114, 196))),
            (r#"<a:schemeClr val="bg1"/>"#, Some(rgb(255, 255, 255))),
            (r#"<a:schemeClr val="tx2"/>"#, Some(rgb(68, 84, 106))),
            (r#"<a:prstClr val="black"/>"#, Some(rgb(0, 0, 0))),
            (r#"<a:sysClr val="window"/>"#, Some(rgb(255, 255, 255))),
            // A slot that the scheme lacks, the placeholder color and a short value.
            (r#"<a:schemeClr val="accent6"/>"#, None),
            (r#"<a:schemeClr val="phClr"/>"#, None),
            (r#"<a:srgbClr val="12"/>"#, None),
        ];
        for (xml, want) in cases {
            assert_eq!(color(xml), want.map(|rgb| (rgb, Opacity::FULL)), "{xml}");
        }
    }

    #[test]
    fn reads_six_hexadecimal_digits_and_refuses_a_sign() {
        // `ST_HexColorRGB` is `xsd:hexBinary` of 3 bytes: six digits of either case, no sign.
        let cases = [
            (r#"<a:srgbClr val="1f3864"/>"#, Some(rgb(31, 56, 100))),
            (r#"<a:srgbClr val="+FFFFF"/>"#, None),
            (r#"<a:srgbClr val="-FFFFF"/>"#, None),
            (
                r#"<a:sysClr val="window" lastClr="+00000"/>"#,
                Some(rgb(255, 255, 255)),
            ),
        ];
        for (xml, want) in cases {
            assert_eq!(color(xml), want.map(|rgb| (rgb, Opacity::FULL)), "{xml}");
        }
    }

    #[test]
    fn changes_lightness_in_hsl() {
        // Lighter 40%: 60% of the lightness and 40% more.
        let lighter = r#"<a:schemeClr val="accent1"><a:lumMod val="60000"/><a:lumOff val="40000"/></a:schemeClr>"#;
        assert_eq!(color(lighter), Some((rgb(143, 170, 220), Opacity::FULL)));
        let darker = r#"<a:schemeClr val="accent1"><a:lumMod val="75000"/></a:schemeClr>"#;
        assert_eq!(color(darker), Some((rgb(47, 85, 151), Opacity::FULL)));
        let gray = r#"<a:schemeClr val="bg1"><a:lumMod val="85000"/></a:schemeClr>"#;
        assert_eq!(color(gray), Some((rgb(217, 217, 217), Opacity::FULL)));
        // Strict files write percentages with a percent sign.
        let strict =
            r#"<a:schemeClr val="bg1"><a:lumMod val="85%"/><a:alpha val="90.5%"/></a:schemeClr>"#;
        assert_eq!(
            color(strict),
            Some((rgb(217, 217, 217), Opacity::clamped(90_500)))
        );
    }

    /// A modifier whose value lies beyond the 32 bits of `xsd:int` reads as missing, and the
    /// largest value that reads changes the color without an overflow.
    #[test]
    fn leaves_out_a_modifier_beyond_the_range_of_its_type() {
        for name in ["lumMod", "lumOff", "shade", "tint"] {
            let far =
                format!(r#"<a:srgbClr val="4472C4"><a:{name} val="99999999999999"/></a:srgbClr>"#);
            assert_eq!(
                color(&far),
                Some((rgb(68, 114, 196), Opacity::FULL)),
                "{name}"
            );
            let largest =
                format!(r#"<a:srgbClr val="4472C4"><a:{name} val="2147483647"/></a:srgbClr>"#);
            assert!(color(&largest).is_some(), "{name}");
        }
    }

    #[test]
    fn shades_and_tints_in_linear_light() {
        let shade = r#"<a:schemeClr val="accent1"><a:shade val="50000"/></a:schemeClr>"#;
        assert_eq!(color(shade), Some((rgb(47, 82, 143), Opacity::FULL)));
        let tint = r#"<a:srgbClr val="000000"><a:tint val="50000"/></a:srgbClr>"#;
        assert_eq!(color(tint), Some((rgb(188, 188, 188), Opacity::FULL)));
        let alpha = r#"<a:srgbClr val="FF0000"><a:alpha val="25000"/></a:srgbClr>"#;
        let (red, opacity) = color(alpha).unwrap();
        assert_eq!(on_white(red, opacity), rgb(255, 191, 191));
    }

    /// Word's colors of `a:gamma` and `a:invGamma`, alone and around a tint.
    #[test]
    fn takes_gamma_as_the_srgb_curve_and_inv_gamma_as_its_reverse() {
        let cases = [
            ("808080", "<a:gamma/>", rgb(0xBC, 0xBC, 0xBC)),
            ("808080", "<a:invGamma/>", rgb(0x37, 0x37, 0x37)),
            ("808080", r#"<a:tint val="50000"/>"#, rgb(0xCD, 0xCD, 0xCD)),
            ("4472C4", "<a:gamma/>", rgb(0x8D, 0xB2, 0xE3)),
            ("4472C4", "<a:invGamma/>", rgb(0x0F, 0x2B, 0x8D)),
            (
                "808080",
                r#"<a:gamma/><a:tint val="50000"/><a:invGamma/>"#,
                rgb(0xBF, 0xBF, 0xBF),
            ),
            (
                "FFFFFF",
                r#"<a:gamma/><a:tint val="43922"/><a:invGamma/>"#,
                rgb(255, 255, 255),
            ),
        ];
        for (base, modifiers, want) in cases {
            let xml = format!(r#"<a:srgbClr val="{base}">{modifiers}</a:srgbClr>"#);
            assert_eq!(color(&xml), Some((want, Opacity::FULL)), "{xml}");
        }
    }

    #[test]
    fn warns_once_of_a_color_whose_unread_modifiers_change_it_and_of_other_models() {
        use crate::Feature;
        let feature = |feature| vec![Warning::FeatureNotSupported { feature }];
        let invalid = |element| Warning::InvalidValue {
            element: Name::new(element),
            attribute: Name::new("val"),
        };
        let red = |modifiers: &str| format!(r#"<a:srgbClr val="FF0000">{modifiers}</a:srgbClr>"#);
        let cases = [
            // Offsets of zero and factors of 100 % change nothing.
            (
                red(
                    r#"<a:hueOff val="0"/><a:satOff val="0%"/><a:satMod val="100000"/><a:alphaOff val="0"/>"#,
                ),
                vec![],
            ),
            // A value that does not read counts as missing, with a warning: a modifier that
            // F-Office applies is then left out, and is no unread modifier, and one that it
            // does not apply changes the color.
            (
                red(r#"<a:lumMod val="x"/><a:hueMod val="1.5"/>"#),
                vec![
                    invalid("lumMod"),
                    invalid("hueMod"),
                    Warning::FeatureNotSupported {
                        feature: Feature::ColorModifier,
                    },
                ],
            ),
            (
                red(r#"<a:satMod val="150000"/><a:hueOff val="60000"/>"#),
                feature(Feature::ColorModifier),
            ),
            (red(r#"<a:satMod val="150000"/>"#), vec![]),
            (red("<a:gamma/>"), vec![]),
            (red("<a:gray/>"), feature(Feature::ColorModifier)),
            (
                r#"<a:hslClr hue="0" sat="100%" lum="50%"/>"#.to_owned(),
                feature(Feature::ColorModel),
            ),
            (
                r#"<a:scrgbClr r="100%" g="0" b="0"/>"#.to_owned(),
                feature(Feature::ColorModel),
            ),
        ];
        for (xml, want) in cases {
            assert_eq!(color_warned(&xml).1, want, "{xml}");
        }
        // The color is drawn without the modifier.
        assert_eq!(color(&red(r#"<a:hueOff val="50000"/>"#)), color(&red("")));
    }

    #[test]
    fn gives_the_stops_of_two_gradient_styles_as_word_draws_them() {
        // The stops of two gradient fills of chart styles in three accents, and the colors
        // that Word for Windows paints for them.
        let preset = [
            r#"<a:shade val="51000"/><a:satMod val="130000"/>"#,
            r#"<a:shade val="93000"/><a:satMod val="130000"/>"#,
            r#"<a:shade val="94000"/><a:satMod val="135000"/>"#,
        ];
        let theme = [
            r#"<a:satMod val="103000"/><a:lumMod val="102000"/><a:tint val="94000"/>"#,
            r#"<a:satMod val="110000"/><a:lumMod val="100000"/><a:shade val="100000"/>"#,
            r#"<a:lumMod val="99000"/><a:satMod val="120000"/><a:shade val="78000"/>"#,
        ];
        let cases = [
            ("4472C4", preset, ["214F9F", "2F69D0", "2C69D4"]),
            ("ED7D31", preset, ["C5570C", "FF7414", "FF730F"]),
            ("A5A5A5", preset, ["797979", "A0A0A0", "A0A0A0"]),
            ("4472C4", theme, ["6083CB", "3E70CA", "2E61BA"]),
            ("ED7D31", theme, ["F18C55", "F67B28", "E56B17"]),
            ("A5A5A5", theme, ["AFAFAF", "A5A5A5", "929292"]),
        ];
        // The darker end of a gradient from an accent to the accent at 84 % luminance.
        let darker = r#"<a:srgbClr val="4472C4"><a:lumMod val="84000"/></a:srgbClr>"#;
        assert_eq!(color(darker), Some((rgb(0x35, 0x5F, 0xA9), Opacity::FULL)));
        let mut found = Vec::new();
        for (accent, modifiers, _) in cases {
            for modifiers in modifiers {
                let xml = format!(r#"<a:srgbClr val="{accent}">{modifiers}</a:srgbClr>"#);
                let (rgb, _) = color(&xml).unwrap();
                found.push(format!("{:02X}{:02X}{:02X}", rgb.r, rgb.g, rgb.b));
            }
        }
        let want: Vec<String> = cases
            .iter()
            .flat_map(|(_, _, want)| want.map(str::to_owned))
            .collect();
        assert_eq!(found, want);
    }
}