f-office-docx 0.3.0

DOCX model and Word's layout rules.
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
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
//! The warnings of a DOCX layout: what it left out of the file, or drew in another way than
//! the file asks, while it went on with the rest. A warning holds no content of the document,
//! only the names that the file uses to point at a part or a font, as `f_office_warnings::Name`
//! keeps them.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use f_office_emf::Frame;
use f_office_fonts::{FamilyName, FontId, NotReadCause, OutlineError, ShapeFailure};
use f_office_paint::{DisplayList, Image, ImageFormat, Item};
use f_office_units::Length;
use f_office_warnings::Name;

use crate::Fonts;
use crate::text::{FontNotes, FontResolution};

/// What the player of an EMF or WMF picture left out of it, or drew in another way than it
/// asks, which [`Warning::Metafile`] holds.
pub use f_office_emf::Warning as MetafileWarning;

/// The type of a record of an EMF or WMF picture in the numbering of its format, which a
/// [`MetafileWarning`] of a record names.
pub use f_office_emf::RecordType as MetafileRecordType;

/// What a reader of DrawingML read in another way than the file asks, which
/// [`Warning::DrawingMl`] holds.
pub use f_office_drawingml::Warning as DrawingMlWarning;

/// A feature of DrawingML that F-Office does not draw, which a [`DrawingMlWarning`] names. The
/// features of VML, WordprocessingML and OMML are [`Feature`]: one set of features for each
/// crate, as each crate has its own warnings.
pub use f_office_drawingml::Feature as DrawingMlFeature;

/// What a DOCX layout left out or drew in another way, and went on.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Warning {
    /// A part that the layout does without: its name in the package, and why.
    PartSkipped {
        /// The part.
        part: Name,
        /// Why.
        reason: Reason,
    },
    /// A part whose relationships do not read, so that the layout draws it without what they
    /// name, such as its pictures: the part's name, or `/` for the package's own relationships.
    RelationshipsSkipped {
        /// The part.
        part: Name,
    },
    /// A drawing that the layout leaves out: its kind, the part that holds it (or, when its
    /// relationship ID names no part, the part that names it, and for a drawing that the reader
    /// of a part leaves out, that part), and why.
    DrawingSkipped {
        /// The kind of drawing.
        drawing: Drawing,
        /// The part.
        part: Name,
        /// Why.
        reason: Reason,
    },
    /// The polygon of a floating drawing's tight or through wrap (`wp:wrapPolygon`) that the
    /// layout leaves out, so that the text keeps out of the drawing's box, as for a wrap
    /// without a polygon: the part that holds the drawing, and why.
    WrapPolygonSkipped {
        /// The part.
        part: Name,
        /// Why.
        reason: Reason,
    },
    /// A page border's side of an art style, such as `apples`, that the layout leaves out
    /// because the caller gave no picture of the style at the side's size
    /// ([`crate::ArtPictures`]): the style and the size.
    ArtBorderNotDrawn {
        /// The art style, as the schema spells it.
        style: &'static str,
        /// The side's size, in points (`w:sz`).
        size: u32,
    },
    /// A font family that the document asks for and that a face of another family draws: the
    /// family asked for, and the family and version of the face that draws it, when the caller
    /// knows them, with how its layout stands to the family's.
    FontSubstituted {
        /// The family that the document asks for.
        asked: Name,
        /// The family of the face that draws it, `None` when the caller does not know it
        /// ([`crate::Fonts::family_name`]).
        used: Option<Name>,
        /// The version of the face that draws it, such as "7.06.1", `None` when the caller does
        /// not know it ([`crate::Fonts::face_version`]).
        version: Option<Name>,
        /// How the layout of the face that draws it stands to the family's.
        layout: SubstituteLayout,
    },
    /// Text that the layout leaves out because the caller has no face for it: none of the
    /// family that it asks for, nor of the names that stand for that family, nor of a family
    /// that Word draws in its place.
    TextNotDrawn {
        /// The family that the text asks for, `None` for text that names no font.
        asked: Option<Name>,
        /// The families that were tried, in order, each with the faces that stand in for it.
        tried: Vec<Name>,
    },
    /// A font that the layout looks for, other than for text that it leaves out, when the
    /// caller has no face of it, nor of the names that stand for it, nor of a family that Word
    /// draws in its place: for a paragraph mark, a tab or a line break, which then takes no
    /// face, so that its height is not part of its line's, or for a character that its run's
    /// font lacks, which then does not take the family. A font whose text the layout leaves
    /// out gives [`Warning::TextNotDrawn`] only.
    FontNotFound {
        /// The family looked for, `None` for a piece that names no font.
        asked: Option<Name>,
        /// The families that were tried, in order, each with the faces that stand in for it.
        tried: Vec<Name>,
    },
    /// A font whose text of a shaped script, such as Arabic, the caller could not shape, so
    /// that each of its characters has the glyph of the font's character map.
    ScriptNotShaped {
        /// The family of the font, `None` when the caller does not know it
        /// ([`crate::Fonts::family_name`]).
        font: Option<Name>,
        /// Why the caller could not shape it.
        cause: ShapeFailure,
    },
    /// A font file whose bytes did not load when the caller chose one of its faces, so that
    /// the face counted as missing: the file's path in its font folder, and why.
    FontFileNotRead {
        /// The file's path in its font folder.
        file: Name,
        /// Why the file did not load.
        cause: NotReadCause,
    },
    /// A font with a glyph whose ink the layout asked for, as for an equation, and that the
    /// caller could not measure, so that the layout places the glyph as one without ink.
    InkNotMeasured {
        /// The family of the font, `None` when the caller does not know it
        /// ([`crate::Fonts::family_name`]).
        font: Option<Name>,
        /// Why the caller could not measure it.
        cause: OutlineError,
    },
    /// Characters that rendered as `.notdef` because neither the chosen font nor character
    /// fallback had a glyph for them: the font family (when known), the coarse Unicode block, and
    /// how many characters rendered as `.notdef`. Never holds raw document text.
    GlyphMissing {
        /// The family of the font that drew `.notdef`, `None` when the caller does not know it
        /// ([`crate::Fonts::family_name`]).
        font: Option<Name>,
        /// The coarse Unicode script or block of the missing characters.
        block: UnicodeBlock,
        /// Number of characters in this font and block that rendered as `.notdef`.
        count: u32,
    },
    /// A value that does not read as its type, such as a length written as text: the part, the
    /// element and the place in the element that hold it, and the reading that the layout took
    /// in its place.
    InvalidValue {
        /// The part.
        part: Name,
        /// The element that holds the value.
        element: Name,
        /// Where the value lies in the element.
        place: ValuePlace,
        /// The reading that the layout took.
        read_as: ReadAs,
    },
    /// A value that is a value of its type and that the layout draws as another value of the
    /// type, such as a striped shading that it draws as its fill alone: the part, the element
    /// and the place in the element that hold it, and the value, a name of the type.
    ValueNotSupported {
        /// The part.
        part: Name,
        /// The element that holds the value.
        element: Name,
        /// Where the value lies in the element.
        place: ValuePlace,
        /// The value, a name of its type.
        value: Name,
    },
    /// A normal footnote or endnote whose ID has the number of an earlier normal note of its
    /// part: the part, and the number. The layout keeps one of the two, as the target's quirk
    /// `RepeatedNoteId` says, and a reference of the number finds it. The
    /// warning comes once for each note that repeats a number.
    NoteIdRepeated {
        /// The part.
        part: Name,
        /// The number of the ID.
        id: i64,
    },
    /// A reference to a footnote or an endnote (`w:footnoteReference`, `w:endnoteReference`)
    /// whose ID no normal note of the footnotes or the endnotes part has: the part of the
    /// reference, the kind of note, and the number of the ID. The reference's number is drawn,
    /// and no note. The warning comes once for each such reference.
    NoteMissing {
        /// The part of the reference.
        part: Name,
        /// Whether it refers to a footnote or an endnote.
        note: NoteKind,
        /// The number of the ID.
        id: i64,
    },
    /// A namespace prefix that a part, or a relationships part, uses on an element or an
    /// attribute without a declaration, which XML's namespaces forbid: the part, and the
    /// prefix. The reader goes on, once for each prefix of a part: an element of the prefix,
    /// with what it holds, is none that a reader takes, and an attribute of it reads as an
    /// attribute without a prefix ([`f_office_xml::Document::undeclared_prefixes`]).
    UndeclaredPrefix {
        /// The part.
        part: Name,
        /// The prefix.
        prefix: Name,
    },
    /// A value of the file beyond a limit of F-Office's work, which the reader takes as the
    /// limit before it goes on, such as a table of more grid columns than the layout takes: the
    /// part, and the limit.
    LimitReached {
        /// The part.
        part: Name,
        /// The limit.
        limit: Limit,
    },
    /// A record of an EMF or WMF picture that the layout leaves out or draws in another way:
    /// the picture's part, and what its player warns of.
    Metafile {
        /// The part of the picture.
        part: Name,
        /// What the player warns of.
        warning: MetafileWarning,
    },
    /// A value of DrawingML that a reader of DrawingML read in another way than the file asks,
    /// such as a line width that does not read: the part, and what the reader warns of.
    DrawingMl {
        /// The part.
        part: Name,
        /// What the reader of DrawingML warns of.
        warning: DrawingMlWarning,
    },
    /// A feature of VML, WordprocessingML or OMML that F-Office does not draw, which it draws
    /// in another way or leaves out, such as the rotation of a VML shape: the part, and the
    /// feature.
    FeatureNotSupported {
        /// The part.
        part: Name,
        /// The feature.
        feature: Feature,
    },
}

/// A feature of VML, WordprocessingML or OMML that F-Office does not draw, which
/// [`Warning::FeatureNotSupported`] names. Each says what F-Office draws in its place. The
/// features of DrawingML are [`DrawingMlFeature`].
///
/// The warning names the part that sets the feature: the part of the layer of the cascade that
/// sets the property that shows it, such as the styles part for a style or the numbering part
/// for a list level; the main document's for a setting that acts by default where no layer
/// sets it, such as hanging punctuation; and the part that holds a table for the own properties
/// of its rows and cells. The readers of the parts give the features that act where they are
/// read, such as a rotation of a VML shape or a section's text direction. The layout gives the
/// features of text, paragraphs, frames and tables where it lays them out: a feature of runs
/// once for each paragraph whose text draws it and each part that sets it, with the list label
/// as a run of its paragraph, so that a style, a list level or a paragraph mark that draws no
/// text gives none; and a feature of a table once for each table and part.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Feature {
    /// A VML shape whose outline is other than a rectangle, a rounded rectangle, an ellipse or
    /// a line: a `v:shape` of a type (`type`) other than the text box, the rectangle and the
    /// straight connector, whose outline, fill and line are not drawn, or a `v:shape` with its
    /// own path (`path`), which is drawn as a rectangle. Its text box is laid out.
    VmlGeometry,
    /// A rotation of a VML shape or picture other than a whole number of quarter turns
    /// (`rotation` in its CSS `style`): the shape or the picture is drawn upright.
    VmlRotation,
    /// A color change of a VML picture in its text line (`gain`, `blacklevel`, `grayscale` or
    /// `bilevel` of `v:imagedata`): the picture keeps its own colors.
    VmlPictureColors,
    /// A text box of a VML picture in its text line (a `v:textbox` with `w:txbxContent` of a
    /// `v:shape` whose `v:imagedata` names an image): the picture is drawn without its text
    /// box. One warning for each such shape.
    VmlPictureTextBox,
    /// A fill of a run's text other than a solid opaque one (`w14:textFill`): an empty fill, a
    /// gradient, or a solid fill of a color that is not opaque. The text is drawn in its color
    /// (`w:color`). One warning for each paragraph whose text shows it, for each part that sets it.
    TextFill,
    /// A glow, shadow, reflection or 3-D look of a run's text that draws something
    /// (`w14:glow`, `w14:shadow`, `w14:reflection`, `w14:scene3d`, `w14:props3d`), or an
    /// outline, shadow, emboss or imprint of a run's text that is on (`w:outline`, `w:shadow`,
    /// `w:emboss`, `w:imprint`): the text is drawn without it. One warning for each paragraph whose text shows it, for each part that sets it.
    TextEffect,
    /// A fill of the line along the outline of a run's glyphs (`w14:textOutline`) other than a
    /// solid opaque one: a gradient (`w14:gradFill`), which is not drawn, or a solid fill of a
    /// color that is not opaque, which is drawn opaque. One warning for each paragraph whose text shows it, for each part that sets it.
    TextOutlineFill,
    /// A structure of an equation that F-Office does not lay out as a structure: a box that acts
    /// as an operator or holds a break (`m:box` with `m:opEmu` or `m:brk`). Its content is laid
    /// out in a row, without the structure's marks and places.
    MathStructure,
    /// A double strike through a run's text that is on (`w:dstrike`): a target whose quirk
    /// `UnderlineForms` is `AllSingle` draws it as a single strike. One warning for each
    /// paragraph whose text shows it, for each part that sets it.
    DoubleStrike,
    /// A border around a run's text of a line style other than none (`w:bdr`): the text is
    /// drawn without it. One warning for each paragraph whose text shows it, for each part that sets it.
    TextBorder,
    /// A width that a run's text or a cell's text is fitted into (`w:fitText` above 0,
    /// `w:tcFitText` on): the text keeps its own spacing. One warning for each paragraph whose
    /// text shows it, and one for each table with such cells, for each part that sets it.
    FitText,
    /// An emphasis mark of a run's text (`w:em` other than `none`), or two lines in one or text
    /// turned in its line (`w:eastAsianLayout` with `w:combine` or `w:vert` on): the text is
    /// laid out in its line without them. One warning for each paragraph whose text shows it, for each part that sets it.
    EastAsianLayout,
    /// Automatic hyphenation of the document (`w:autoHyphenation` on in the settings) on a
    /// target whose configuration hyphenates no language: no word is hyphenated at the end of a
    /// line.
    AutoHyphenation,
    /// A shading of a whole table that gives a fill or a pattern (`w:shd` of `w:tblPr`, also in a
    /// table style, or of a row's `w:tblPrEx`, which takes the table's place in the row): only
    /// the shading of the cells is drawn. One warning for each table, for each part that sets
    /// the shading of one of its rows; a table style that no table uses gives none.
    TableShading,
    /// A section's text direction other than upright from left to right (`w:textDirection` of
    /// `w:sectPr` other than `lrTb` and `tb`): the section's text is laid out upright.
    SectionTextDirection,
    /// A place of a section's footnotes other than the bottom of the page (`w:pos` of
    /// `w:footnotePr` of the section or the settings other than `pageBottom`), in a document
    /// that holds footnotes: they stand at the bottom of the page.
    FootnotePosition,
    /// A place of a section's endnotes at the end of the section (`w:pos` of `w:endnotePr` of
    /// the section or the settings `sectEnd`), in a document that holds endnotes: they follow
    /// the text at the end of the document.
    EndnotePosition,
    /// A paragraph's text alignment at the top, the middle or the bottom of its lines
    /// (`w:textAlignment` of `top`, `center` or `bottom`), on a line whose pieces have two
    /// heights, such as runs of two font sizes or a picture beside text: every piece of the
    /// line stands on one baseline. One warning for each paragraph that holds such a line; a
    /// line of one height gives none.
    TextAlignment,
    /// Hanging punctuation (`w:overflowPunct`, on by default): a punctuation mark of East
    /// Asian text, of its language's list in [MS-OI29500] 2.1.52, that does not fit at the end
    /// of a line goes to the next line with the text before it, where Word lets it stand past
    /// the end of the line. One warning for each paragraph that holds such a line, with the part
    /// that sets `w:overflowPunct`, or the main document's where no layer sets it.
    HangingPunctuation,
    /// A paragraph's text direction that turns its text (`w:textDirection` of `w:pPr` other
    /// than `lrTb` and `tb`), in a frame, where Word turns the paragraph ([MS-OI29500] 2.1.63):
    /// the paragraph is laid out upright. One warning for each such paragraph, a paragraph of a
    /// header or a footer once whatever the number of its pages. Outside frames Word lays the
    /// paragraph out upright too, and it gives none.
    ParagraphTextDirection,
    /// A text box whose text is turned (`vert` of `wps:bodyPr` other than `horz`, `layout-flow`
    /// of the style of `v:textbox` other than `horizontal`, or a VML or DrawingML shape turned
    /// by whole quarter turns other than none, unless `upright` of `wps:bodyPr` keeps the text
    /// upright): its text is laid out upright. One warning for each such box.
    TurnedTextBox,
    /// Mirrored indents (`w:mirrorIndents` on) of a paragraph whose left and right indents
    /// differ, which make them the inside and outside indents of mirrored pages: the left
    /// indent stays on the left of every page. One warning for each such paragraph.
    MirrorIndents,
    /// A right indent that moves to the section's grid of characters (`w:adjustRightInd`, on by
    /// default, in a paragraph on the grid of a section whose `w:docGrid` is of the type
    /// `linesAndChars`): the right indent stays as set. One warning for each such paragraph,
    /// with the part that sets `w:adjustRightInd`, or the main document's where no layer sets
    /// it.
    GridRightIndent,
    /// A frame of the body that overlaps an earlier frame of its page in the layout, where one
    /// of the two must not overlap other frames (`w:suppressOverlap` on): Word moves it, and it
    /// stays at its own place. One warning for each such frame, with the part that sets
    /// `w:suppressOverlap` for it, or else for the earlier frame.
    FrameOverlap,
    /// A paragraph of a text box whose lines take part in the box's tight wrap
    /// (`w:textboxTightWrap` other than `none`): the text around the box wraps around its
    /// rectangle. One warning for each such paragraph.
    TextBoxTightWrap,
    /// A row's own alignment (`w:jc` of `w:trPr` or of `w:tblPrEx`) other than its table's,
    /// in a table narrower than its column: the row stands where the table's alignment puts
    /// the table. One warning for each such row, with the part that holds the table.
    RowAlignment,
    /// A row's own cell spacing (`w:tblCellSpacing` of `w:trPr` or of `w:tblPrEx`) other than
    /// its table's: the row's cells keep the table's spacing. One warning for each such row, with
    /// the part that holds the table.
    RowCellSpacing,
    /// A paragraph of an HTML div (`w:divId`) that has, or lies in a div that has, a margin
    /// other than 0 or a border line (`w:div` of the web settings part): the paragraph is laid
    /// out without them. One warning for each such paragraph.
    HtmlDiv,
    /// A drawing group's own turn or flip (its **group transform**: `rot`, `flipH` and `flipV` of
    /// the `a:xfrm` of `wpg:grpSpPr`), which says what is not drawn: the group's parts and their
    /// text are drawn upright and unflipped, at their places before the turn. One warning for
    /// each such group, an inner group too.
    GroupTransform(GroupTransform),
    /// A character of Word's symbol extension (`w16se:symEx`), a character in a font of its
    /// own, such as an emoji, in a choice of alternate content that F-Office takes: nothing is
    /// drawn in its place. One warning for each such character.
    SymbolExtension,
    /// A choice of alternate content (`mc:Choice`) that F-Office passes over because it does not
    /// read a namespace that the choice requires, and that holds no drawing: a later choice or
    /// the fallback is drawn in its place, or nothing. One warning for each such choice.
    AlternateChoice,
    /// Text in a bidirectional embedding or override of a paragraph (`w:dir`, `w:bdo`): its
    /// runs are left out. One warning for each such element.
    BidirectionalEmbedding,
    /// A phonetic guide over a run's text (`w:ruby`): its guide text and its base text are left
    /// out. One warning for each such guide.
    Ruby,
    /// A page number written as an element of a run (`w:pgNum`), not as a field: no number is
    /// drawn in its place. One warning for each such element.
    PageNumberElement,
    /// A part of the current date written as an element of a run (`w:dayShort`, `w:dayLong`,
    /// `w:monthShort`, `w:monthLong`, `w:yearShort`, `w:yearLong`): nothing is drawn in its
    /// place. One warning for each such element.
    DateBlock,
    /// A border between the paragraphs of a group of the same borders (`w:between` of
    /// `w:pBdr`) with a line: it is not drawn. One warning for each paragraph or style whose
    /// own borders hold it.
    BetweenBorder,
    /// A bar border beside a paragraph (`w:bar` of `w:pBdr`) with a line: it is not drawn. One
    /// warning for each paragraph or style whose own borders hold it.
    BarBorder,
    /// An element in an equation outside Office Math that F-Office does not read: not a
    /// tracked change, a hyperlink, a smart tag, custom XML, a content control or a mark that
    /// draws nothing. What it holds is left out. One warning for each such element.
    MathElement,
    /// The title, the legend or labels of the axes of a chart that F-Office draws (`c:title`,
    /// `c:legend`, the labels of `c:catAx` and `c:valAx`), which F-Office does not draw: the
    /// chart is drawn without them. One warning for each chart drawn without a part of its text.
    ChartLabels,
    /// The picture bullet of a list label (`w:lvlPicBulletId`), which F-Office does not draw:
    /// the label takes no room and nothing is drawn in its place. One warning for each
    /// paragraph with such a label.
    PictureBullet,
    /// The mark of a footnote or an endnote (`w:footnoteRef`, `w:endnoteRef`) in a text box of
    /// its note, or the mark of an endnote in a frame of its note, which F-Office does not number
    /// from the note: the mark shows 1. One warning for each such text box or frame.
    NoteMarkInBox,
    /// The data labels of a chart that F-Office draws (`c:dLbls`, `c:dLbl`), which F-Office
    /// does not draw: the chart is drawn without them. One warning for each chart whose series
    /// show data labels.
    DataLabels,
}

/// What F-Office does not draw of a drawing group's own **group transform**.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GroupTransform {
    /// A turn other than none, at any angle (`rot`).
    Turn,
    /// A flip across, down or both (`flipH`, `flipV`).
    Flip,
    /// A turn and a flip.
    TurnAndFlip,
}

impl GroupTransform {
    /// Every value, in the order of their declaration.
    pub const ALL: [Self; 3] = [Self::Turn, Self::Flip, Self::TurnAndFlip];
}

impl Feature {
    /// Every feature, in the order of their declaration, each kind once: a feature that says
    /// what is not drawn takes its first value, such as [`GroupTransform::Turn`].
    pub const ALL: [Self; 42] = [
        Self::VmlGeometry,
        Self::VmlRotation,
        Self::VmlPictureColors,
        Self::VmlPictureTextBox,
        Self::TextFill,
        Self::TextEffect,
        Self::TextOutlineFill,
        Self::MathStructure,
        Self::DoubleStrike,
        Self::TextBorder,
        Self::FitText,
        Self::EastAsianLayout,
        Self::AutoHyphenation,
        Self::TableShading,
        Self::SectionTextDirection,
        Self::FootnotePosition,
        Self::EndnotePosition,
        Self::TextAlignment,
        Self::HangingPunctuation,
        Self::ParagraphTextDirection,
        Self::TurnedTextBox,
        Self::MirrorIndents,
        Self::GridRightIndent,
        Self::FrameOverlap,
        Self::TextBoxTightWrap,
        Self::RowAlignment,
        Self::RowCellSpacing,
        Self::HtmlDiv,
        Self::GroupTransform(GroupTransform::Turn),
        Self::SymbolExtension,
        Self::AlternateChoice,
        Self::BidirectionalEmbedding,
        Self::Ruby,
        Self::PageNumberElement,
        Self::DateBlock,
        Self::BetweenBorder,
        Self::BarBorder,
        Self::MathElement,
        Self::ChartLabels,
        Self::PictureBullet,
        Self::NoteMarkInBox,
        Self::DataLabels,
    ];

    /// The kind of the warning of the feature, as [`Warning::kind`] gives it.
    #[must_use]
    pub fn kind(self) -> &'static str {
        match self {
            Self::VmlGeometry => "vml-geometry-not-supported",
            Self::VmlRotation => "vml-rotation-not-supported",
            Self::VmlPictureColors => "vml-picture-colors-not-supported",
            Self::VmlPictureTextBox => "vml-picture-text-box-not-supported",
            Self::TextFill => "text-fill-not-supported",
            Self::TextEffect => "text-effect-not-supported",
            Self::TextOutlineFill => "text-outline-fill-not-supported",
            Self::MathStructure => "math-structure-not-supported",
            Self::DoubleStrike => "double-strike-not-supported",
            Self::TextBorder => "text-border-not-supported",
            Self::FitText => "fit-text-not-supported",
            Self::EastAsianLayout => "east-asian-layout-not-supported",
            Self::AutoHyphenation => "auto-hyphenation-not-supported",
            Self::TableShading => "table-shading-not-supported",
            Self::SectionTextDirection => "section-text-direction-not-supported",
            Self::FootnotePosition => "footnote-position-not-supported",
            Self::EndnotePosition => "endnote-position-not-supported",
            Self::TextAlignment => "text-alignment-not-supported",
            Self::HangingPunctuation => "hanging-punctuation-not-supported",
            Self::ParagraphTextDirection => "paragraph-text-direction-not-supported",
            Self::TurnedTextBox => "turned-text-box-not-supported",
            Self::MirrorIndents => "mirror-indents-not-supported",
            Self::GridRightIndent => "grid-right-indent-not-supported",
            Self::FrameOverlap => "frame-overlap-not-supported",
            Self::TextBoxTightWrap => "text-box-tight-wrap-not-supported",
            Self::RowAlignment => "row-alignment-not-supported",
            Self::RowCellSpacing => "row-cell-spacing-not-supported",
            Self::HtmlDiv => "html-div-not-supported",
            Self::GroupTransform(_) => "group-transform-not-supported",
            Self::SymbolExtension => "symbol-extension-not-supported",
            Self::AlternateChoice => "alternate-choice-not-supported",
            Self::BidirectionalEmbedding => "bidirectional-embedding-not-supported",
            Self::Ruby => "ruby-not-supported",
            Self::PageNumberElement => "page-number-element-not-supported",
            Self::DateBlock => "date-block-not-supported",
            Self::BetweenBorder => "between-border-not-supported",
            Self::BarBorder => "bar-border-not-supported",
            Self::MathElement => "math-element-not-supported",
            Self::ChartLabels => "chart-labels-not-supported",
            Self::PictureBullet => "picture-bullet-not-supported",
            Self::NoteMarkInBox => "note-mark-in-box-not-supported",
            Self::DataLabels => "data-labels-not-supported",
        }
    }
}

impl fmt::Display for Feature {
    #[expect(
        clippy::too_many_lines,
        reason = "one arm for each feature of the closed set, which says what is drawn in its place"
    )]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::VmlGeometry => {
                "a VML shape of an outline other than a rectangle, a rounded rectangle, an \
                 ellipse or a line is not supported, and the shape is drawn as a rectangle or \
                 not at all"
            }
            Self::VmlRotation => {
                "a rotation of a VML shape or picture other than a whole number of quarter turns \
                 is not supported, and it is drawn upright"
            }
            Self::VmlPictureColors => {
                "a color change of a VML picture in its text line is not supported, and the \
                 picture keeps its own colors"
            }
            Self::VmlPictureTextBox => {
                "a text box of a VML picture in its text line is not supported, and the picture \
                 is drawn without it"
            }
            Self::TextFill => {
                "a fill of text other than a solid opaque one is not supported, and the text is \
                 drawn in its color"
            }
            Self::TextEffect => {
                "a glow, shadow, reflection, 3-D look, outline, emboss or imprint of text is not \
                 supported, and the text is drawn without it"
            }
            Self::TextOutlineFill => {
                "an outline of text whose fill is other than a solid opaque one is not supported, \
                 and a gradient outline is not drawn and a transparent one is drawn opaque"
            }
            Self::MathStructure => {
                "a structure of an equation such as a radical, an accent or a matrix is not \
                 supported, and its content is laid out in a row"
            }
            Self::DoubleStrike => {
                "a double strike through text is not supported on a target that does not draw \
                 its own form, and it is drawn as a single strike"
            }
            Self::TextBorder => {
                "a border around text is not supported, and the text is drawn without it"
            }
            Self::FitText => {
                "text fitted into a width is not supported, and the text keeps its own spacing"
            }
            Self::EastAsianLayout => {
                "an emphasis mark, two lines in one or text turned in its line is not supported, \
                 and the text is laid out in its line without them"
            }
            Self::AutoHyphenation => {
                "automatic hyphenation is not supported, and no word is hyphenated at the end of a \
                 line"
            }
            Self::TableShading => {
                "the shading of a whole table is not supported, and only the shading of its cells \
                 is drawn"
            }
            Self::SectionTextDirection => {
                "a section's vertical text direction is not supported, and its text is laid out \
                 upright"
            }
            Self::FootnotePosition => {
                "a place of a section's footnotes other than the bottom of the page is not \
                 supported, and they stand at the bottom of the page"
            }
            Self::EndnotePosition => {
                "a place of a section's endnotes at the end of the section is not supported, and \
                 they follow the text at the end of the document"
            }
            Self::TextAlignment => {
                "a paragraph's text alignment at the top, the middle or the bottom of its lines is \
                 not supported, and the pieces of a line of two heights stand on one baseline"
            }
            Self::HangingPunctuation => {
                "hanging punctuation is not supported, and a mark that does not fit at the end of \
                 a line goes to the next line with the text before it"
            }
            Self::ParagraphTextDirection => {
                "a vertical text direction of a paragraph in a frame is not supported, and the \
                 paragraph is laid out upright"
            }
            Self::TurnedTextBox => {
                "turned text in a text box is not supported, and the text is laid out upright"
            }
            Self::MirrorIndents => {
                "mirroring indents is not supported, and the left indent stays on the left"
            }
            Self::GridRightIndent => {
                "moving a right indent to the grid is not supported, and it stays as set"
            }
            Self::FrameOverlap => {
                "keeping frames apart is not supported, and a frame stays over the other"
            }
            Self::TextBoxTightWrap => {
                "a tight wrap of a text box is not supported, and text wraps around its box"
            }
            Self::RowAlignment => {
                "a row's own alignment is not supported, and it takes its table's"
            }
            Self::RowCellSpacing => {
                "a row's own cell spacing is not supported, and it takes its table's"
            }
            Self::HtmlDiv => {
                "an HTML div with margins or borders is not supported, and they are left out"
            }
            Self::GroupTransform(GroupTransform::Turn) => {
                "a turn of a drawing group is not supported, and its parts are drawn upright"
            }
            Self::GroupTransform(GroupTransform::Flip) => {
                "a flip of a drawing group is not supported, and its parts are drawn unflipped"
            }
            Self::GroupTransform(GroupTransform::TurnAndFlip) => {
                "a turn and flip of a drawing group is not supported, and its parts are drawn \
                 upright and unflipped"
            }
            Self::SymbolExtension => {
                "a character of the symbol extension is not supported, and nothing is drawn in \
                 its place"
            }
            Self::AlternateChoice => {
                "a choice of alternate content in a namespace that F-Office does not read is \
                 not supported, and a later choice, the fallback or nothing is drawn in its place"
            }
            Self::BidirectionalEmbedding => {
                "a bidirectional embedding or override is not supported, and its text is left \
                 out"
            }
            Self::Ruby => {
                "a phonetic guide is not supported, and its guide text and its base text are \
                 left out"
            }
            Self::PageNumberElement => {
                "a page number element is not supported, and no number is drawn in its place"
            }
            Self::DateBlock => "a date element is not supported, and nothing is drawn in its place",
            Self::BetweenBorder => {
                "a border between paragraphs is not supported, and it is not drawn"
            }
            Self::BarBorder => "a bar border of a paragraph is not supported, and it is not drawn",
            Self::MathElement => {
                "an element of an equation outside Office Math is not supported, and what it \
                 holds is left out"
            }
            Self::ChartLabels => {
                "the text of a chart's title, legend or axis labels is not supported, and the \
                 chart is drawn without it"
            }
            Self::PictureBullet => {
                "a picture bullet of a list label is not supported, and nothing is drawn in its \
                 place"
            }
            Self::NoteMarkInBox => {
                "a note mark in a text box or a frame of its note is not supported, and it \
                 shows 1"
            }
            Self::DataLabels => {
                "a data label of a chart is not supported, and the chart is drawn without its \
                 data labels"
            }
        })
    }
}

/// The kinds of drawing that a layout can leave out.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Drawing {
    /// A picture, whose image file is a part of the package.
    Picture,
    /// A chart.
    Chart,
    /// A SmartArt graphic.
    SmartArt,
    /// A shape, such as one of custom geometry.
    Shape,
}

/// Where a value lies in its element, which [`Warning::InvalidValue`] and
/// [`Warning::ValueNotSupported`] name.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ValuePlace {
    /// The text of the element, such as the offset of `wp:posOffset`.
    Text,
    /// An attribute of the element.
    Attribute(Name),
    /// A property of the CSS declarations that an attribute of the element holds, such as
    /// `mso-position-horizontal-relative` in the `style` of a VML shape.
    Property {
        /// The attribute, such as `style`.
        attribute: Name,
        /// The property.
        property: Name,
    },
}

impl fmt::Display for ValuePlace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Text => f.write_str("the text"),
            Self::Attribute(attribute) => write!(f, "attribute {attribute}"),
            Self::Property {
                attribute,
                property,
            } => write!(f, "property {property} of attribute {attribute}"),
        }
    }
}

/// The reading that the layout takes for a value that does not read.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReadAs {
    /// The value is 0, as Word for Windows reads a value of half points that does not read.
    Zero,
    /// The value counts as missing, as if the element had no such attribute.
    Missing,
    /// The value reads as the value of its type with this name, as the schema spells it, when
    /// unrecognized text uses a different fallback from a missing value, such as `subSup` for
    /// the place of an n-ary operator's limits (`m:limLoc`).
    Value(&'static str),
}

/// Why a part or a drawing is left out.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Reason {
    /// The package has no part of that name.
    Missing,
    /// The part is not XML that the reader takes, or has no root element.
    NotXml,
    /// The drawing names no part of the package: its relationship ID names no relationship of
    /// its part, or one to a file outside the package, or it links a file outside the package
    /// in place of a part, such as a linked image (`r:link` of `a:blip`, `o:href` of
    /// `v:imagedata`).
    Unlinked,
    /// The layout does not draw what the part holds, other than a chart part, which gives its
    /// own reason ([`Reason::Chart`]), or the drawing, such as a drawing canvas, ink, a VML group, polyline, arc,
    /// curve or image element, a floating VML picture whose colors change, a VML shape or
    /// picture without a CSS width or height, other than a floating line, a VML picture in its
    /// text line in another element than `v:shape`, or a VML shape after the first of its
    /// `w:pict` or `w:object`, or a VML text path with a letter whose outline the caller
    /// cannot give.
    Unsupported,
    /// An earlier entry of the package has a name that differs from this one only in ASCII
    /// case, which the package format forbids, and the reader keeps the earlier one.
    Equivalent,
    /// A place or a size that the values of a drawing or of its wrap polygon give lies beyond
    /// [`Length::FILE_LIMIT`], such as a point of a custom path with a tiny size and a far
    /// point.
    OutOfRange,
    /// The reader takes the drawing, but a step of its layout gives no place for what it
    /// holds, such as the value axis of a chart whose numbers leave the digits of a decimal,
    /// or a plot area without room in the chart's frame.
    NotPlaced,
    /// F-Office does not draw the chart that the part holds, for this reason.
    Chart(ChartReason),
}

/// Why F-Office does not draw a chart, which [`Reason::Chart`] names: the first condition of
/// its drawn case that the chart does not meet, in the order in which the readers test them.
/// The reader of the part that holds the chart tests its drawing first (a chart of Office 2016
/// and later, a floating chart, a chart in a drawing group), before its chart part is read;
/// then the model of the chart part, the drawn case (one clustered column chart with both axes
/// shown, its labels, legend, title and series), and the scope of the target's rule of the plot
/// area (quirk `ChartPlotArea`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChartReason {
    /// The chart is one of Office 2016 and later (`cx:chart`), such as a waterfall chart.
    ChartEx,
    /// The chart is a part of a drawing group (`wpg:graphicFrame` of `wpg:wgp`).
    InGroup,
    /// The part has no chart (`c:chart`) or no plot area (`c:plotArea`).
    NoPlotArea,
    /// The plot area holds a chart group other than bars, lines and scatter points, such as a
    /// pie, an area or a 3-D chart.
    OtherGroup,
    /// A bar group has no direction that reads (`c:barDir`, which the schema requires).
    NoBarDirection,
    /// The plot area holds no chart group, or more than one, such as bars with a line.
    NotOneGroup,
    /// The one chart group is lines (`c:lineChart`), which the rule of
    /// `ChartPlotArea::DefaultChart` does not draw.
    Lines,
    /// The lines are stacked or stacked to 100 % (`c:grouping` of `c:lineChart`).
    StackedLines,
    /// The line group adds drop lines, high-low lines or up-down bars.
    LineExtras,
    /// A series of the line group shows markers at its points (`c:marker`) that F-Office does
    /// not draw: a symbol other than a circle, a diamond, a square, a triangle, an x and a star,
    /// a look other than a solid fill and a solid outline of a set width, or a look of the
    /// chart's style on a series that sets its own line.
    LineMarkers,
    /// A series of the line group takes the colors of the chart's style (no `c:spPr`) in a
    /// group of more than six series.
    StyleColors,
    /// A series of the line group has no properties (`c:spPr`) in a chart that names a chart
    /// style (`c:style`), which is not supported.
    ChartStyle,
    /// A series of the line or scatter group is smoothed (`c:smooth`), which the target does not
    /// draw (`ChartSmoothLines::Unknown`).
    SmoothLines,
    /// A series' line has a stroke that the target does not draw: under
    /// `ChartLineStrokes::Unknown` no width that reads, caps or joins that are not written round,
    /// or a dash; under `StyleRound` a flat or square cap, a miter or bevel join, or a dash of
    /// its own (`a:custDash`).
    LineLook,
    /// The one chart group is scatter points (`c:scatterChart`), which the target does not draw
    /// (`ChartScatter::Unknown`).
    Scatter,
    /// The scatter group's style is other than straight lines and markers (`c:scatterStyle`
    /// other than `lineMarker`), or than smooth lines and markers (`smoothMarker`) on a target
    /// that draws smooth lines, which is not supported.
    ScatterStyle,
    /// The scatter group lets the colors of its points vary (`c:varyColors` not off).
    VariedColors,
    /// A series of the scatter group adds a trendline or error bars (`c:trendline`,
    /// `c:errBars`).
    SeriesExtras,
    /// The scatter chart has not one value axis at the bottom (`c:axPos val="b"`), its x axis,
    /// and one at the left (`l`).
    ScatterAxes,
    /// The scatter chart's x axis draws gridlines (`c:majorGridlines` or `c:minorGridlines`).
    XGridlines,
    /// The scatter chart has a legend, which is not supported.
    ScatterLegend,
    /// The bars are horizontal (`c:barDir val="bar"`), on a target that does not draw them
    /// (`ChartHorizontalBars::Unknown`) or in the scope of Word's default chart.
    HorizontalBars,
    /// The bars are stacked, stacked to 100 % or one behind the other, not clustered
    /// (`c:grouping`).
    NotClustered,
    /// The plot area has not one category axis and one value axis, such as a date axis in
    /// place of the category axis.
    Axes,
    /// An axis is deleted (`c:delete`) or shows its labels other than next to it
    /// (`c:tickLblPos`).
    AxisNotShown,
    /// The value axis has a logarithm, runs from its highest value, or sets a major unit not
    /// above zero or a minimum not below its maximum.
    ValueScale,
    /// The legend stands at the top right corner (`c:legendPos val="tr"`).
    LegendTopRight,
    /// The title is one that F-Office does not know: an automatic one that is not deleted and
    /// that the target does not hide, a title of its own whose automatic title is deleted, or
    /// one whose size does not read.
    UnknownTitle,
    /// A series has no solid fill that reads.
    SeriesFill,
    /// A series has no cached value for each of its points.
    SeriesValues,
    /// The bar group has no series.
    NoSeries,
    /// The series have different numbers of values.
    SeriesLengths,
    /// Every value is zero.
    AllZero,
    /// The chart shows no title, which the rule of `ChartPlotArea::DefaultChart` needs.
    Untitled,
    /// The legend does not stand at the bottom, or the chart has none, which the rule of
    /// `ChartPlotArea::DefaultChart` needs.
    LegendNotAtBottom,
    /// The value axis sets its minimum, maximum or major unit, outside the scope of the rule
    /// of `ChartPlotArea::DefaultChart`.
    SetScale,
    /// A value is below zero, outside the scope of the rule of `ChartPlotArea::DefaultChart`.
    NegativeValue,
    /// An axis crosses the other elsewhere than at the automatic zero, outside the scope of
    /// the rule of `ChartPlotArea::FontLines`.
    SetCrossing,
    /// The plot area has a manual layout other than one in the edge mode, outside the scope
    /// of the rule of `ChartPlotArea::FontLines`.
    OtherPlotPlace,
    /// A series has no name while the legend stands at the left or the right, outside the
    /// scope of the rule of `ChartPlotArea::FontLines`.
    UnnamedSeriesBesideLegend,
    /// An axis shows a title, outside the scope of the rule of `ChartPlotArea::FontLines`.
    AxisTitle,
    /// The value labels have a number format other than General, outside the scope of the
    /// rule of `ChartPlotArea::FontLines`.
    OtherNumberFormat,
    /// The plot area shows a data table (`c:dTable`), the series' values in a table below the
    /// plot, which F-Office does not draw.
    DataTable,
    /// A pie's series or one of its points is pulled out of the circle (`c:explosion` above 0),
    /// which F-Office does not draw.
    PieExplosion,
    /// A pie shows data labels at a position whose room F-Office does not know: one other than
    /// the center, the inner end, the outer end, the best fit and the default, or one that its
    /// points do not share.
    PieLabels,
}

/// A limit of F-Office's work that a value of the file can reach, which
/// [`Warning::LimitReached`] names. It bounds the work, and is not a measure of Word.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Limit {
    /// The largest multiple of automatic line spacing (`MAX_LINE_MULTIPLE`): a `w:line` of the
    /// rule `auto`, or a DrawingML share of a line, beyond it or below its negative.
    LineMultiple,
    /// The most grid columns of a table (`MAX_GRID_COLUMNS`): a `w:gridSpan` or a
    /// `w:gridBefore` above it, a `w:tblGrid` of more columns, or a row that would widen the
    /// grid beyond it.
    GridColumns,
    /// The most trials of balanced columns (`MAX_BALANCE_TRIALS`): a section whose columns
    /// end at a continuous section break and fit within no trial, which keeps its columns as
    /// they fill.
    BalanceTrials,
    /// The most items of a page with the dashes of table lines (`MAX_DASHED_PAGE_ITEMS`): a
    /// piece of a dashed table line whose dashes would take its page beyond them, which is
    /// drawn whole.
    TableDashes,
    /// The range of a length: a line of a table row whose edges lie beyond it, which no file
    /// gives, since every length that a reader takes lies within `Length::FILE_LIMIT`, and
    /// which leaves the row's lines whole, not cut at their junctions.
    LineRange,
    /// The largest font size of a run (`MAX_FONT_SIZE`): a `w:sz` or a `w:szCs` above it.
    FontSize,
    /// The most fields open at one place of a story (`MAX_FIELD_DEPTH`): a field that begins
    /// while that many are open, which is read as content of the field around it.
    FieldDepth,
}

impl Warning {
    /// The warning's kind, a short name that stays the same across versions and holds no name
    /// of the file, for a caller that counts warnings or writes them where the names of the
    /// file may not go.
    #[must_use]
    pub fn kind(&self) -> &'static str {
        match self {
            Self::PartSkipped { .. } => "part-skipped",
            Self::RelationshipsSkipped { .. } => "relationships-skipped",
            Self::DrawingSkipped { drawing, .. } => match drawing {
                Drawing::Picture => "picture-skipped",
                Drawing::Chart => "chart-skipped",
                Drawing::SmartArt => "smartart-skipped",
                Drawing::Shape => "shape-skipped",
            },
            Self::WrapPolygonSkipped { .. } => "wrap-polygon-skipped",
            Self::ArtBorderNotDrawn { .. } => "art-border-not-drawn",
            Self::FontSubstituted { .. } => "font-substituted",
            Self::TextNotDrawn { .. } => "text-not-drawn",
            Self::FontNotFound { .. } => "font-not-found",
            Self::ScriptNotShaped { .. } => "script-not-shaped",
            Self::FontFileNotRead { .. } => "font-file-not-read",
            Self::InkNotMeasured { .. } => "ink-not-measured",
            Self::GlyphMissing { .. } => "glyph-missing",
            Self::InvalidValue { .. } => "invalid-value",
            Self::ValueNotSupported { .. } => "value-not-supported",
            Self::NoteIdRepeated { .. } => "note-id-repeated",
            Self::NoteMissing { .. } => "note-missing",
            Self::UndeclaredPrefix { .. } => "undeclared-prefix",
            Self::LimitReached { .. } => "limit-reached",
            Self::Metafile { warning, .. } => warning.kind(),
            Self::DrawingMl { warning, .. } => warning.kind(),
            Self::FeatureNotSupported { feature, .. } => feature.kind(),
        }
    }
}

/// The text of [`Warning::TextNotDrawn`].
fn not_drawn(f: &mut fmt::Formatter<'_>, asked: Option<&Name>, tried: &[Name]) -> fmt::Result {
    match asked {
        Some(asked) => write!(f, "text in font {asked} is not drawn")?,
        None => f.write_str("text that names no font is not drawn")?,
    }
    no_face(f, tried)
}

/// The text of [`Warning::FontNotFound`].
fn not_found(f: &mut fmt::Formatter<'_>, asked: Option<&Name>, tried: &[Name]) -> fmt::Result {
    match asked {
        Some(asked) => write!(f, "font {asked} is not found")?,
        None => f.write_str("the font of a mark, tab or break that names no font is not found")?,
    }
    no_face(f, tried)
}

/// The text of [`Warning::ScriptNotShaped`].
fn not_shaped(f: &mut fmt::Formatter<'_>, font: Option<&Name>, cause: ShapeFailure) -> fmt::Result {
    match font {
        Some(font) => write!(
            f,
            "text of a shaped script in {font} is not shaped: {cause}"
        ),
        None => write!(
            f,
            "text of a shaped script in a font of an unknown family is not shaped: {cause}"
        ),
    }
}

/// The end of the text of a warning of a font that no face draws: the families `tried`.
fn no_face(f: &mut fmt::Formatter<'_>, tried: &[Name]) -> fmt::Result {
    f.write_str(": the fonts have no face of ")?;
    for (index, family) in tried.iter().enumerate() {
        if index > 0 {
            f.write_str(", ")?;
        }
        write!(f, "{family}")?;
    }
    f.write_str(", nor one that stands in for them")
}

/// Coarse Unicode script or block for a character that rendered as `.notdef`, carrying no
/// document prose or raw code points.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum UnicodeBlock {
    /// Basic Latin (U+0000–U+007F).
    BasicLatin,
    /// Latin-1 Supplement and Latin Extended blocks.
    LatinExtended,
    /// Greek and Coptic / Greek Extended.
    Greek,
    /// Cyrillic and Cyrillic extensions.
    Cyrillic,
    /// Hebrew.
    Hebrew,
    /// Arabic and Arabic presentation forms.
    Arabic,
    /// Devanagari and Devanagari Extended.
    Devanagari,
    /// Thai.
    Thai,
    /// CJK Unified Ideographs, radicals, and CJK punctuation/compatibility.
    Cjk,
    /// Hiragana.
    Hiragana,
    /// Katakana and Katakana Phonetic Extensions.
    Katakana,
    /// Hangul Jamo and Hangul Syllables.
    Hangul,
    /// General punctuation, arrows, box drawing, geometric shapes, dingbats, and symbols.
    Symbols,
    /// Mathematical operators and mathematical alphanumeric symbols.
    Mathematical,
    /// Emoticons, pictographs, and supplemental emoji symbols.
    Emoji,
    /// Private Use Area code points.
    PrivateUse,
    /// Any other Unicode block.
    Other,
}

impl UnicodeBlock {
    /// Classifies `ch` into a coarse Unicode script or block.
    #[must_use]
    pub const fn of(ch: char) -> Self {
        match ch {
            '\u{0000}'..='\u{007F}' => Self::BasicLatin,
            '\u{0080}'..='\u{02AF}'
            | '\u{1E00}'..='\u{1EFF}'
            | '\u{2C60}'..='\u{2C7F}'
            | '\u{A720}'..='\u{A7FF}' => Self::LatinExtended,
            '\u{0370}'..='\u{03FF}' | '\u{1F00}'..='\u{1FFF}' => Self::Greek,
            '\u{0400}'..='\u{052F}' | '\u{2DE0}'..='\u{2DFF}' | '\u{A640}'..='\u{A69F}' => {
                Self::Cyrillic
            }
            '\u{0590}'..='\u{05FF}' | '\u{FB1D}'..='\u{FB4F}' => Self::Hebrew,
            '\u{0600}'..='\u{06FF}'
            | '\u{0750}'..='\u{077F}'
            | '\u{08A0}'..='\u{08FF}'
            | '\u{FB50}'..='\u{FDFF}'
            | '\u{FE70}'..='\u{FEFF}' => Self::Arabic,
            '\u{0900}'..='\u{097F}' | '\u{A8E0}'..='\u{A8FF}' => Self::Devanagari,
            '\u{0E00}'..='\u{0E7F}' => Self::Thai,
            '\u{1100}'..='\u{11FF}'
            | '\u{3130}'..='\u{318F}'
            | '\u{A960}'..='\u{A97F}'
            | '\u{AC00}'..='\u{D7FF}' => Self::Hangul,
            '\u{3040}'..='\u{309F}' => Self::Hiragana,
            '\u{30A0}'..='\u{30FF}' | '\u{31F0}'..='\u{31FF}' => Self::Katakana,
            '\u{2E80}'..='\u{303F}'
            | '\u{3100}'..='\u{312F}'
            | '\u{3190}'..='\u{31EF}'
            | '\u{3200}'..='\u{9FFF}'
            | '\u{F900}'..='\u{FAFF}'
            | '\u{FE30}'..='\u{FE4F}'
            | '\u{FF00}'..='\u{FFEF}'
            | '\u{20000}'..='\u{2FFFF}' => Self::Cjk,
            '\u{2200}'..='\u{22FF}'
            | '\u{27C0}'..='\u{27EF}'
            | '\u{2980}'..='\u{2AFF}'
            | '\u{1D400}'..='\u{1D7FF}' => Self::Mathematical,
            '\u{1F000}'..='\u{1FAFF}' => Self::Emoji,
            '\u{2000}'..='\u{21FF}'
            | '\u{2300}'..='\u{27BF}'
            | '\u{27F0}'..='\u{297F}'
            | '\u{2B00}'..='\u{2BFF}' => Self::Symbols,
            '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{10FFFF}' => Self::PrivateUse,
            _ => Self::Other,
        }
    }

    /// Stable machine-readable identifier for this block.
    #[must_use]
    pub const fn kind(self) -> &'static str {
        match self {
            Self::BasicLatin => "basic-latin",
            Self::LatinExtended => "latin-extended",
            Self::Greek => "greek",
            Self::Cyrillic => "cyrillic",
            Self::Hebrew => "hebrew",
            Self::Arabic => "arabic",
            Self::Devanagari => "devanagari",
            Self::Thai => "thai",
            Self::Cjk => "cjk",
            Self::Hiragana => "hiragana",
            Self::Katakana => "katakana",
            Self::Hangul => "hangul",
            Self::Symbols => "symbols",
            Self::Mathematical => "mathematical",
            Self::Emoji => "emoji",
            Self::PrivateUse => "private-use",
            Self::Other => "other",
        }
    }

    /// Human-readable name for this Unicode block.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::BasicLatin => "Basic Latin",
            Self::LatinExtended => "Latin Extended",
            Self::Greek => "Greek",
            Self::Cyrillic => "Cyrillic",
            Self::Hebrew => "Hebrew",
            Self::Arabic => "Arabic",
            Self::Devanagari => "Devanagari",
            Self::Thai => "Thai",
            Self::Cjk => "CJK Unified Ideographs",
            Self::Hiragana => "Hiragana",
            Self::Katakana => "Katakana",
            Self::Hangul => "Hangul",
            Self::Symbols => "Punctuation & Symbols",
            Self::Mathematical => "Mathematical Operators",
            Self::Emoji => "Emoji",
            Self::PrivateUse => "Private Use",
            Self::Other => "Other Unicode",
        }
    }
}

impl fmt::Display for UnicodeBlock {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.label())
    }
}

/// A font family requested by the document that resolved natively to a face of that family.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MatchedFont {
    /// The family requested by the document.
    pub asked: Name,
    /// The family name of the face that drew it, when known.
    pub used: Option<Name>,
    /// The version of the face that drew it, when known.
    pub version: Option<Name>,
}

/// How the layout of a face that draws another family stands to that family's layout.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SubstituteLayout {
    /// A face with the family's glyph widths at most, such as Liberation Sans for Arial, so
    /// that lines can break where the family's do not.
    #[default]
    Widths,
    /// A verified metric-compatible stand-in whose advance widths and line metrics match the
    /// target's own face of the family, so lines break in the same places.
    Metrics,
    /// An open font made from the target's own face of the family, which has its layout.
    Exact,
    /// An open font made for another version of a family than the target's own face of it.
    OtherVersion {
        /// The family that the open font stands in for.
        family: Name,
        /// The version of the family that it was made for, such as "7.06".
        made_for: Name,
        /// The version of the target's own face of the family, such as "5.01.2x".
        target: Name,
    },
    /// A fallback font of another family used because neither the requested family nor a
    /// metric-compatible stand-in was available, so lines can break in other places.
    Fallback,
}

/// The text of the warning of a substituted font.
fn substituted(
    f: &mut fmt::Formatter<'_>,
    asked: &Name,
    used: Option<&Name>,
    version: Option<&Name>,
    layout: &SubstituteLayout,
) -> fmt::Result {
    let Some(used) = used else {
        return write!(f, "font {asked} is drawn with another font");
    };
    write!(f, "font {asked} is drawn with {used}")?;
    let Some(version) = version else {
        return Ok(());
    };
    match layout {
        SubstituteLayout::Widths => Ok(()),
        SubstituteLayout::Metrics => write!(f, " {version}, which matches its metrics"),
        SubstituteLayout::Exact => write!(f, " {version}, which has its layout"),
        SubstituteLayout::Fallback => write!(f, " {version} as a fallback"),
        SubstituteLayout::OtherVersion {
            family,
            made_for,
            target,
        } => write!(
            f,
            " {version}, made for {family} {made_for}; this target has {family} {target}, so \
             lines can break in other places"
        ),
    }
}

/// The text of [`Warning::GlyphMissing`].
fn glyph_missing(
    f: &mut fmt::Formatter<'_>,
    font: Option<&Name>,
    block: UnicodeBlock,
    count: u32,
) -> fmt::Result {
    let unit = if count == 1 { "glyph" } else { "glyphs" };
    match font {
        Some(font) => write!(f, "font {font} is missing {count} {unit} in {block}"),
        None => write!(
            f,
            "a font of an unknown family is missing {count} {unit} in {block}"
        ),
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PartSkipped { part, reason } => write!(f, "part {part} is skipped: {reason}"),
            Self::RelationshipsSkipped { part } => write!(
                f,
                "the relationships of part {part} do not read, and what they name is left out"
            ),
            Self::DrawingSkipped {
                drawing,
                part,
                reason,
            } => write!(f, "a {drawing} of part {part} is left out: {reason}"),
            Self::WrapPolygonSkipped { part, reason } => write!(
                f,
                "a wrap polygon of part {part} is left out, and the text keeps out of its \
                 drawing's box: {reason}"
            ),
            Self::ArtBorderNotDrawn { style, size } => write!(
                f,
                "a page border side of the art style {style} at {size} pt is not drawn: the \
                 caller gave no picture of it"
            ),
            Self::FontSubstituted {
                asked,
                used,
                version,
                layout,
            } => substituted(f, asked, used.as_ref(), version.as_ref(), layout),
            Self::TextNotDrawn { asked, tried } => not_drawn(f, asked.as_ref(), tried),
            Self::FontNotFound { asked, tried } => not_found(f, asked.as_ref(), tried),
            Self::ScriptNotShaped { font, cause } => not_shaped(f, font.as_ref(), *cause),
            Self::FontFileNotRead { file, cause } => write!(
                f,
                "font file {file} did not load, and its face counts as missing: {cause}"
            ),
            Self::InkNotMeasured {
                font: Some(font),
                cause,
            } => write!(
                f,
                "the ink of a glyph of {font} is not measured, and the glyph is placed as one \
                 without ink: {cause}"
            ),
            Self::InkNotMeasured { font: None, cause } => write!(
                f,
                "the ink of a glyph of a font of an unknown family is not measured, and the \
                 glyph is placed as one without ink: {cause}"
            ),
            Self::GlyphMissing { font, block, count } => {
                glyph_missing(f, font.as_ref(), *block, *count)
            }
            Self::InvalidValue {
                part,
                element,
                place,
                read_as,
            } => {
                match place {
                    ValuePlace::Text => f.write_str("the text")?,
                    _ => write!(f, "the value of {place}")?,
                }
                write!(
                    f,
                    " of element {element} in part {part} does not read and {read_as}"
                )
            }
            Self::ValueNotSupported {
                part,
                element,
                place,
                value,
            } => write!(
                f,
                "the value {value} of {place} of element {element} in part {part} is drawn as \
                 another value"
            ),
            Self::NoteIdRepeated { part, id } => write!(
                f,
                "a note of part {part} has the ID {id} of an earlier note, and one of the two is kept"
            ),
            Self::NoteMissing { part, note, id } => write!(
                f,
                "a reference of part {part} names the {note} {id}, which no note has, and its \
                 number is drawn without a note"
            ),
            Self::UndeclaredPrefix { part, prefix } => write!(
                f,
                "part {part} uses the namespace prefix {prefix} without a declaration, and \
                 no reader takes an element of it"
            ),
            Self::LimitReached { part, limit } => write!(f, "in part {part}, {limit}"),
            Self::Metafile { part, warning } => write!(f, "in the picture {part}, {warning}"),
            Self::DrawingMl { part, warning } => write!(f, "in part {part}, {warning}"),
            Self::FeatureNotSupported { part, feature } => write!(f, "in part {part}, {feature}"),
        }
    }
}

impl fmt::Display for ReadAs {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Zero => f.write_str("reads as 0"),
            Self::Missing => f.write_str("counts as missing"),
            Self::Value(name) => write!(f, "reads as {name}"),
        }
    }
}

impl fmt::Display for Drawing {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Picture => "picture",
            Self::Chart => "chart",
            Self::SmartArt => "SmartArt graphic",
            Self::Shape => "shape",
        })
    }
}

impl fmt::Display for Limit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::LineMultiple => {
                "a paragraph asks for a larger multiple of automatic line spacing than F-Office \
                 takes, and its spacing stops at the limit"
            }
            Self::GridColumns => {
                "a table asks for more grid columns than F-Office takes, and its grid stops at \
                 the limit"
            }
            Self::BalanceTrials => {
                "a section's balanced columns fit within no trial that F-Office makes, and they \
                 stay as they fill"
            }
            Self::TableDashes => {
                "a page's table lines have more dashes than F-Office draws, and a line past the \
                 limit is drawn whole"
            }
            Self::LineRange => {
                "a table line lies beyond the range of a length, and the lines of its row are \
                 drawn whole"
            }
            Self::FontSize => {
                "a run asks for a larger font size than F-Office takes, and its size stops at the \
                 limit"
            }
            Self::FieldDepth => {
                "a field begins inside more fields than F-Office keeps open, and it is read as \
                 the content of the field around it"
            }
        })
    }
}

/// Whether a note reference names a footnote or an endnote, which [`Warning::NoteMissing`] says.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NoteKind {
    /// A footnote (`w:footnoteReference`).
    Footnote,
    /// An endnote (`w:endnoteReference`).
    Endnote,
}

impl fmt::Display for NoteKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Footnote => "footnote",
            Self::Endnote => "endnote",
        })
    }
}

impl fmt::Display for Reason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Missing => "the package has no such part",
            Self::NotXml => "the part is not XML that reads",
            Self::Unlinked => "it names no part of the package",
            Self::Unsupported => "F-Office does not draw what it holds",
            Self::Equivalent => "an earlier entry has a name that differs only in case",
            Self::OutOfRange => {
                "a place or a size that its values give lies beyond the range of a length"
            }
            Self::NotPlaced => "its layout gives no place for what it holds",
            Self::Chart(reason) => return write!(f, "F-Office does not draw a chart {reason}"),
        })
    }
}

impl fmt::Display for ChartReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::ChartEx => "of Office 2016 and later",
            Self::InGroup => "in a drawing group",
            Self::NoPlotArea => "without a plot area",
            Self::OtherGroup => {
                "whose plot area holds a chart group other than bars, lines and scatter points"
            }
            Self::NoBarDirection => "with a bar group whose direction does not read",
            Self::NotOneGroup => "whose plot area holds no chart group or more than one",
            Self::Lines => "of lines on this target",
            Self::StackedLines => "of stacked lines",
            Self::LineExtras => "of lines with drop lines, high-low lines or up-down bars",
            Self::LineMarkers => "of lines with markers of another kind",
            Self::StyleColors => "of more than six lines in the colors of the chart's style",
            Self::ChartStyle => {
                "of lines in the look of a chart style other than style 2 that it names"
            }
            Self::SmoothLines => "of smoothed lines",
            Self::LineLook => "of lines without a width, round caps and round joins",
            Self::Scatter => "of scatter points on this target",
            Self::ScatterStyle => "of scatter points in a style other than lines and markers",
            Self::VariedColors => "of scatter points whose colors vary",
            Self::SeriesExtras => "with a trendline or error bars",
            Self::ScatterAxes => {
                "of scatter points without one value axis below and one at the left"
            }
            Self::XGridlines => "of scatter points with gridlines of the x axis",
            Self::ScatterLegend => "of scatter points with a legend",
            Self::HorizontalBars => "of horizontal bars",
            Self::NotClustered => "whose bars are not clustered",
            Self::Axes => "without one category axis and one value axis",
            Self::AxisNotShown => "with an axis that is deleted or whose labels are not next to it",
            Self::ValueScale => "whose value axis has a scale that it does not draw",
            Self::LegendTopRight => "whose legend stands at the top right corner",
            Self::UnknownTitle => "whose title it does not know",
            Self::SeriesFill => "with a series without a solid fill",
            Self::SeriesValues => "with a series without a cached value for each point",
            Self::NoSeries => "without a series",
            Self::SeriesLengths => "whose series differ in their numbers of values",
            Self::AllZero => "whose values are all zero",
            Self::Untitled => "without a title on this target",
            Self::LegendNotAtBottom => "whose legend is not at the bottom on this target",
            Self::SetScale => "whose value axis sets its scale on this target",
            Self::NegativeValue => "with a value below zero on this target",
            Self::SetCrossing => "whose axes cross elsewhere than at zero on this target",
            Self::OtherPlotPlace => "whose plot area has another manual layout on this target",
            Self::UnnamedSeriesBesideLegend => {
                "with a series without a name beside its legend on this target"
            }
            Self::AxisTitle => "with an axis title on this target",
            Self::OtherNumberFormat => {
                "whose value labels have a number format other than General on this target"
            }
            Self::DataTable => "whose plot area shows a data table",
            Self::PieExplosion => "of a pie whose slices are pulled out",
            Self::PieLabels => "of a pie with data labels at another position",
        })
    }
}

/// The warnings of a layout.
pub type Warnings = f_office_warnings::Warnings<Warning>;

/// A value of a layout with its warnings.
pub type Warned<T> = f_office_warnings::Warned<T, Warning>;

/// The warning of a drawing that the layout leaves out.
pub(crate) fn skipped(drawing: Drawing, part: &str, reason: Reason) -> Warning {
    Warning::DrawingSkipped {
        drawing,
        part: Name::new(part),
        reason,
    }
}

/// The warnings of the records of an EMF or WMF picture of `part`, from one play into a frame
/// of one inch. Which records its player leaves out depends on the file only, so one play for
/// each story part that shows it gives them, however many times and at whatever size the layout
/// draws it.
pub(crate) fn of_metafile(image: &Image, part: &str, warnings: &mut Warnings) {
    let inch = Length::from_units(Length::UNITS_PER_INCH);
    let frame = Frame {
        x: Length::ZERO,
        y: Length::ZERO,
        width: inch,
        height: inch,
    };
    let Some(bytes) = image.load_bytes() else {
        return;
    };
    let played = match image.format {
        ImageFormat::Emf => f_office_emf::play(&bytes, frame),
        ImageFormat::Wmf => f_office_emf::play_wmf(&bytes, frame),
        _ => return,
    };
    if let Some(played) = played {
        let part = Name::new(part);
        warnings.extend(played.warnings, |warning| Warning::Metafile {
            part: part.clone(),
            warning,
        });
    }
}

fn font_family_name(fonts: &dyn Fonts, font: FontId) -> Option<Name> {
    fonts
        .family_name(font)
        .map(|family| Name::new(&family))
        .filter(|family| !family.as_str().is_empty())
}

/// Counts rendered `.notdef` glyphs (`id == 0`) in `list`, grouped by `(Some(font), UnicodeBlock)`.
/// Never records raw document text or code points.
pub(crate) fn collect_missing_glyphs(
    list: &DisplayList,
    out: &mut BTreeMap<(Option<FontId>, UnicodeBlock), u32>,
) {
    fn walk(items: &[Item], out: &mut BTreeMap<(Option<FontId>, UnicodeBlock), u32>) {
        for item in items {
            match item {
                Item::Glyphs(run) => {
                    for glyph in &run.glyphs {
                        if glyph.id != 0 {
                            continue;
                        }
                        let ch = run
                            .glyph_text(glyph)
                            .and_then(|text| text.chars().find(|ch| !ch.is_control()));
                        let block = ch.map_or(UnicodeBlock::Other, UnicodeBlock::of);
                        out.entry((Some(run.font), block))
                            .and_modify(|count| *count = count.saturating_add(1))
                            .or_insert(1);
                    }
                }
                Item::Group(group) => walk(&group.items, out),
                _ => {}
            }
        }
    }
    for page in list.pages() {
        walk(page.items(), out);
    }
}

/// Returns deduplicated native font matches recorded in `notes`.
pub(crate) fn matched_fonts(notes: &FontNotes, fonts: &dyn Fonts) -> Vec<MatchedFont> {
    let mut seen = BTreeSet::new();
    for (asked, font) in &notes.matched {
        seen.insert(MatchedFont {
            asked: Name::new(asked),
            used: font_family_name(fonts, *font),
            version: fonts.face_version(*font).map(|version| Name::new(&version)),
        });
    }
    seen.into_iter().collect()
}

fn push_font_failures(notes: &FontNotes, fonts: &dyn Fonts, warnings: &mut Warnings) {
    for &(font, cause) in &notes.unshaped {
        warnings.push(Warning::ScriptNotShaped {
            font: font_family_name(fonts, font),
            cause,
        });
    }
    for &(font, cause) in &notes.ink_not_measured {
        warnings.push(Warning::InkNotMeasured {
            font: font_family_name(fonts, font),
            cause,
        });
    }
    for (&(font, block), &count) in &notes.missing_glyphs {
        if count > 0 {
            warnings.push(Warning::GlyphMissing {
                font: font.and_then(|font| font_family_name(fonts, font)),
                block,
                count,
            });
        }
    }
    for not_read in fonts.files_not_read() {
        warnings.push(Warning::FontFileNotRead {
            file: Name::new(&not_read.file),
            cause: not_read.cause,
        });
    }
}

/// The warnings of the faces that the shapers chose: each family that a face of another
/// family drew, each family whose text no face drew, each other family that it found no face of,
/// each font whose text of a shaped script
/// the caller could not shape, each font with a glyph whose ink the caller could not
/// measure, once for each cause, each font with missing `.notdef` glyphs by Unicode block,
/// and each font file that did not load when the caller chose one of its faces.
pub(crate) fn of_fonts(notes: &FontNotes, fonts: &dyn Fonts, warnings: &mut Warnings) {
    for ((asked, font), resolution) in &notes.substituted {
        let layout = match resolution {
            FontResolution::Fallback => SubstituteLayout::Fallback,
            FontResolution::StandIn => fonts.substitute_layout(&FamilyName::new(asked), *font),
        };
        warnings.push(Warning::FontSubstituted {
            asked: Name::new(asked),
            used: font_family_name(fonts, *font),
            version: fonts.face_version(*font).map(|version| Name::new(&version)),
            layout,
        });
    }
    for (asked, tried) in &notes.not_drawn {
        warnings.push(Warning::TextNotDrawn {
            asked: asked.as_deref().map(Name::new),
            tried: tried.iter().map(|family| Name::new(family)).collect(),
        });
    }
    // A family whose text is left out warns of that only, though its marks take no face too.
    for (asked, tried) in notes.faceless.difference(&notes.not_drawn) {
        warnings.push(Warning::FontNotFound {
            asked: asked.as_deref().map(Name::new),
            tried: tried.iter().map(|family| Name::new(family)).collect(),
        });
    }
    push_font_failures(notes, fonts, warnings);
}

#[cfg(test)]
mod tests;