f-office-docx 0.2.3

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
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
//! Run properties (`w:rPr`): fonts, sizes, character formats and text effects.

use f_office_drawingml::color::{ColorNames, DrawColor};
use f_office_drawingml::gradient::LinearGradient;
use f_office_units::Length;
use f_office_units::scale::DRAWING_WHOLE;
use f_office_xml::NodeId;
use f_office_xml::enumeration::{Case, Values, another, own};

use super::border::{BORDER_LINE, LineStyle};
use super::color::{HIGHLIGHT, parse_color, read_text_color};
use super::{Color, SetIn, overlay, read_shading};
use crate::ns::{W, W14};
use crate::on_off::{self, off_also_for_none};
use crate::reader::PartReader;
use crate::warnings::Feature;

/// A font named directly or through the theme.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FontRef {
    /// A font family name.
    Name(String),
    /// The theme's minor (body) Latin font.
    MinorLatin,
    /// The theme's major (heading) Latin font.
    MajorLatin,
    /// The theme's minor (body) complex script font.
    MinorBidi,
    /// The theme's major (heading) complex script font.
    MajorBidi,
    /// The theme's minor (body) East Asian font.
    MinorEastAsia,
    /// The theme's major (heading) East Asian font.
    MajorEastAsia,
}

impl FontRef {
    /// The font that the typeface of a DrawingML run names (`a:latin typeface`): the theme's
    /// minor or major Latin font for the references `+mn-lt` and `+mj-lt`, else the family of
    /// that name.
    pub(crate) fn of_typeface(face: &str) -> Self {
        match face {
            "+mn-lt" => Self::MinorLatin,
            "+mj-lt" => Self::MajorLatin,
            name => Self::Name(name.to_owned()),
        }
    }
}

/// Run properties. `None` means "not set here", so that the cascade can fill it in.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RunProps {
    /// The font for ASCII characters.
    pub font_ascii: Option<FontRef>,
    /// The font for other Latin characters.
    pub font_hansi: Option<FontRef>,
    /// Bold.
    pub bold: Option<bool>,
    /// Italic.
    pub italic: Option<bool>,
    /// Font size in half-points.
    pub size: Option<i64>,
    /// Text color.
    pub color: Option<Color>,
    /// The underline (`w:u`): its kind, or [`Underline::None`].
    pub underline: Option<Underline>,
    /// The line through the text: a single one (`w:strike`), a double one (`w:dstrike`), or
    /// none.
    pub strike: Option<Strike>,
    /// Whether the run belongs to a tracked change, which marks its lines in the margin: it
    /// lies in `w:ins` or `w:del`, or its `w:rPr` holds `w:rPrChange`.
    pub changed: Option<bool>,
    /// The fill behind the text (`w:shd`).
    pub shading: Option<Color>,
    /// The highlight behind the text (`w:highlight`), which covers the shading.
    pub highlight: Option<Color>,
    /// Show all letters as capitals.
    pub caps: Option<bool>,
    /// Show lower-case letters as smaller capitals.
    pub small_caps: Option<bool>,
    /// Superscript or subscript.
    pub vertical: Option<VerticalAlign>,
    /// The scripts of an equation that the run of the equation is in, which set its size and
    /// rise in place of `vertical`.
    pub math_script: Option<MathScript>,
    /// Whether the run is text of an equation: `Some(true)` for a math run other than normal text
    /// (`m:nor`) or a character that a structure draws itself (which asks for the upright face
    /// whatever its italic, as the italic of math is the mathematical italic letters), and
    /// `Some(false)` for normal text (`m:nor`) inside an equation (which draws as paragraph text
    /// while holding its spaces as equation spaces so justification does not stretch or break
    /// them).
    pub math: Option<bool>,
    /// How far the text is raised (positive) or lowered (negative) from the baseline
    /// (`w:position`, in half-points).
    pub position: Option<Length>,
    /// Hidden text, which is not drawn.
    pub hidden: Option<bool>,
    /// The text of a phantom of an equation that is not shown: it takes its room in the line
    /// and draws nothing.
    pub phantom: Option<bool>,
    /// The smallest font size in half-points that is kerned (`w:kern`); 0 turns kerning off.
    pub kern: Option<i64>,
    /// Extra space after each character, negative to condense (`w:spacing` in `w:rPr`).
    pub spacing: Option<Length>,
    /// The width of the characters in percent of their normal width (`w:w`).
    pub scale: Option<i64>,
    /// The line along the outline of each glyph (`w14:textOutline`).
    pub outline: Option<TextOutline>,
    /// The fill of each glyph's interior (`w14:textFill`).
    pub text_fill: Option<TextFill>,
    /// The shadow of the run's text (`w14:shadow`), when it shows.
    pub shadow: Option<TextShadow>,
    /// The glow around the run's text (`w14:glow`), when it shows.
    pub glow: Option<TextGlow>,
    /// The reflection under the run's text (`w14:reflection`), when it shows.
    pub reflection: Option<Box<TextReflection>>,
    /// Legacy WordprocessingML text shadow (`w:shadow`).
    pub legacy_shadow: Option<bool>,
    /// Legacy WordprocessingML hollow text outline (`w:outline`).
    pub legacy_outline: Option<bool>,
    /// Legacy WordprocessingML embossed text relief (`w:emboss`).
    pub emboss: Option<bool>,
    /// Legacy WordprocessingML engraved/imprinted text relief (`w:imprint`).
    pub imprint: Option<bool>,
    /// Whether the run has a reflection or a 3-D format (`w14:reflection` or `w14:props3d`),
    /// whatever their values. F-Office does not draw these effects.
    pub effect: Option<bool>,
    /// Whether standard ligatures are on (`w14:ligatures`).
    pub ligatures: Option<bool>,
    /// The font for complex script characters, such as Arabic and Hebrew (`w:rFonts w:cs`).
    pub font_cs: Option<Box<FontRef>>,
    /// The font size of complex script characters in half-points (`w:szCs`).
    pub size_cs: Option<i64>,
    /// Bold for complex script characters (`w:bCs`).
    pub bold_cs: Option<bool>,
    /// Italic for complex script characters (`w:iCs`).
    pub italic_cs: Option<bool>,
    /// Whether every character of the run takes complex script properties (`w:cs`).
    pub complex: Option<bool>,
    /// The run direction (`w:rtl`), which also selects complex script formatting.
    pub rtl: Option<bool>,
    /// For a run that shows a page number or page count that Word computes: the direction of
    /// the number, in place of `rtl`. It is that of the run of the field's code, and right
    /// to left in a header or footer. No markup sets it; the reader of fields does.
    pub field_rtl: Option<bool>,
    /// Whether the run lies in the shown result of a text form field (`FORMTEXT`). No markup
    /// sets it; the reader of fields does.
    pub form_text: Option<bool>,
    /// The font for East Asian characters, such as Chinese, Japanese and Korean
    /// (`w:rFonts w:eastAsia`).
    pub font_east_asia: Option<Box<FontRef>>,
    /// Whether the punctuation that Latin and East Asian fonts share, such as quotes and
    /// dashes, takes the East Asian font (`w:rFonts w:hint="eastAsia"`).
    pub east_asian_hint: Option<bool>,
    /// The script of the language of East Asian text (`w:lang w:eastAsia`), which picks the
    /// theme's font for that script.
    pub east_asian_script: Option<EastAsianScript>,
    /// The language of the run's Latin text (`w:lang w:val`). Runs of different languages are
    /// different text objects in Word's PDFs.
    pub lang: Option<Box<str>>,
    /// The script of the language of the run's complex script text (`w:lang w:bidi`), which
    /// decides the face of the digits of a run with `w:rtl`.
    pub bidi_script: Option<BidiScript>,
    /// The class of the run's bidi language (`w:lang w:bidi`), which decides the order of a
    /// number in a sequence of runs with `w:rtl`.
    pub bidi_class: Option<BidiLanguageClass>,
    /// Whether the text of the run uses the document character grid (`w:rPr/w:snapToGrid`);
    /// `None` means on.
    pub snap_to_grid: Option<bool>,
    /// Whether the run carries an active character border (`w:rPr/w:bdr` with a line style other
    /// than `none`/`nil` or with `w:frame="1"`), under which Word for Windows writes each space
    /// as its own PDF text object.
    pub(crate) bordered: Option<bool>,
    /// The properties that show a feature that F-Office does not draw, which the layout warns
    /// of where the run draws text.
    pub unsupported: UnsupportedProperties,
}

/// The class of a bidi language (`w:lang w:bidi`) for the order of a number in a sequence
/// of runs with `w:rtl`: the classes that the measured languages fall into.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BidiLanguageClass {
    /// An Arabic language other than that of Morocco, and a run without a bidi language: a
    /// number with no letter before it is an Arabic number, and a slash joins no numbers.
    #[default]
    Arabic,
    /// Another language of a right-to-left script that is not the Hebrew script, such as
    /// Persian (`fa-IR`) and Urdu (`ur-PK`), and the Arabic of Morocco (`ar-MA`): a slash
    /// joins no numbers.
    OtherRightToLeft,
    /// Every other language, such as Hebrew (`he-IL`) and English (`en-US`): the order of
    /// UAX 9.
    Unicode,
}

impl BidiLanguageClass {
    /// The class of a language tag such as `ar-SA`. An unrecognized tag falls back to the
    /// non-Arabic right-to-left class.
    #[must_use]
    pub fn of(lang: &str) -> Self {
        let lang = lang.to_ascii_lowercase();
        match lang.split('-').next().unwrap_or_default() {
            "ar" if lang == "ar-ma" => Self::OtherRightToLeft,
            "ar" => Self::Arabic,
            "fa" | "prs" | "ur" | "ps" | "ug" | "sd" | "ku" | "syr" | "dv" => {
                Self::OtherRightToLeft
            }
            _ => Self::Unicode,
        }
    }

    /// Whether a number with no letter before it in its sequence of runs with `w:rtl` is
    /// an Arabic number, as a number after an Arabic letter.
    #[must_use]
    pub fn starts_with_arabic_number(self) -> bool {
        self == Self::Arabic
    }

    /// Whether a slash is a neutral character, which joins no two groups of digits.
    #[must_use]
    pub fn has_neutral_slash(self) -> bool {
        self != Self::Unicode
    }
}

/// The script of a bidi language (`w:lang w:bidi`), as far as a measured rule tells the
/// scripts apart.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BidiScript {
    /// Hebrew (`he`).
    Hebrew,
    /// Every other language, such as Arabic (`ar-SA`) and Persian (`fa-IR`).
    Other,
}

impl BidiScript {
    /// The script of a language tag such as `he-IL`.
    #[must_use]
    pub fn of(lang: &str) -> Self {
        let primary = lang.split('-').next().unwrap_or_default();
        if primary.eq_ignore_ascii_case("he") {
            Self::Hebrew
        } else {
            Self::Other
        }
    }
}

/// The theme script of an East Asian language.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EastAsianScript {
    /// Japanese (`Jpan`).
    Japanese,
    /// Simplified Chinese (`Hans`).
    Simplified,
    /// Traditional Chinese, of Taiwan, Hong Kong and Macao (`Hant`).
    Traditional,
    /// Korean (`Hang`).
    Korean,
}

impl EastAsianScript {
    /// The script of a language tag such as `ja-JP`, if it is East Asian.
    #[must_use]
    pub fn of(lang: &str) -> Option<Self> {
        let lang = lang.to_ascii_lowercase();
        if lang.starts_with("ja") {
            Some(Self::Japanese)
        } else if lang.starts_with("ko") {
            Some(Self::Korean)
        } else if matches!(lang.as_str(), "zh-tw" | "zh-hk" | "zh-mo") {
            Some(Self::Traditional)
        } else if lang.starts_with("zh") {
            Some(Self::Simplified)
        } else {
            None
        }
    }

    /// The name of the script in the theme's `a:font` elements.
    #[must_use]
    pub fn theme_name(self) -> &'static str {
        match self {
            Self::Japanese => "Jpan",
            Self::Simplified => "Hans",
            Self::Traditional => "Hant",
            Self::Korean => "Hang",
        }
    }
}

/// The `w14:textOutline` of a run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextOutline {
    /// No line (`w14:noFill`), which removes an inherited one.
    None,
    /// A solid line (`w14:solidFill`).
    Solid {
        /// The line width.
        width: Length,
        /// The line color.
        color: OutlineColor,
    },
}

/// The fill of a run's text (`w14:textFill`, [MS-DOCX] 2.6.1).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TextFill {
    /// No interior fill (`w14:noFill`): hollow when outlined, hidden when not.
    None,
    /// A solid fill (`w14:solidFill`) whose color overrides `w:color` and may carry opacity.
    Solid(DrawColor),
    /// An opaque linear gradient fill (`w14:gradFill`).
    Gradient(Box<LinearGradient>),
}

/// The shadow of a run's text (`w14:shadow`, [MS-DOCX] 2.6.1, `CT_Shadow`): how far it lies
/// from the glyphs and in which direction, how far it blurs, and its color.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TextShadow {
    /// The radius of its blur (`w14:blurRad`), 0 for a sharp shadow.
    pub blur: Length,
    /// How far it lies from the glyphs (`w14:dist`).
    pub distance: Length,
    /// The direction in which it lies, in 60,000ths of a degree clockwise from the right
    /// (`w14:dir`).
    pub direction: i64,
    /// Its color, in the theme's colors for a color of the theme, when the shadow is neither
    /// scaled nor skewed (`sx` and `sy` of 100%, `kx` and `ky` of 0); `None` for a scaled or
    /// skewed shadow, or a color that the theme or F-Office's reading of colors does not give.
    pub color: Option<[u8; 3]>,
    /// The transparency of the shadow's color (`w14:alpha`), in 1,000ths of a percent: 0 for an
    /// opaque color (also when `w14:alpha` is missing), up to 100,000 for wholly transparent.
    pub transparency: i64,
}

/// The glow around a run's text (`w14:glow`, [MS-DOCX] 2.6.1, `CT_Glow`): its radius, its
/// color, and its transparency.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TextGlow {
    /// The radius of the glow (`w14:rad`).
    pub radius: Length,
    /// Its color, in the theme's colors for a color of the theme; `None` when the color cannot
    /// be resolved.
    pub color: Option<[u8; 3]>,
    /// The transparency of the glow's color (`w14:alpha`), in 1,000ths of a percent: 0 for an
    /// opaque color (also when `w14:alpha` is missing), up to 100,000 for wholly transparent.
    pub transparency: i64,
}

/// The reflection under a run's text (`w14:reflection`, [MS-DOCX] 2.5.3.26, `CT_Reflection`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TextReflection {
    /// Blur radius (`w14:blurRad`), 0 when missing.
    pub blur: Length,
    /// Distance (`w14:dist`), 0 when missing.
    pub distance: Length,
    /// Starting opacity in 1,000ths of a percent (`w14:stA`, 0..=100,000).
    pub start_alpha: i64,
    /// Starting fade position in 1,000ths of a percent (`w14:stPos`, 0..=100,000).
    pub start_pos: i64,
    /// Ending opacity in 1,000ths of a percent (`w14:endA`, 0..=100,000).
    pub end_alpha: i64,
    /// Ending fade position in 1,000ths of a percent (`w14:endPos`, 0..=100,000).
    pub end_pos: i64,
    /// Whether this is an unskewed downward reflection (`dir = 90°`, `sx = 100%`, `sy = -100%`,
    /// `kx = ky = 0`).
    pub downward: bool,
}

/// The color of a text outline.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutlineColor {
    /// Red, green and blue (`w14:srgbClr`).
    Rgb([u8; 3]),
    /// A color of the theme (`w14:schemeClr`).
    Scheme,
}

/// One step into a part of an equation that Word sets apart from its base.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MathStep {
    /// A superscript (`m:sup`), also the upper limit of an n-ary operator.
    Superscript,
    /// A superscript beside a subscript: of a sub-superscript (`m:sSubSup`) or of a
    /// pre-sub-superscript (`m:sPre`), or the upper limit of an n-ary operator whose lower limit
    /// shows. The `MATH` table keeps a gap between the two scripts, so the superscript does not
    /// take the cramped shift alone.
    SuperscriptBesideSubscript,
    /// A subscript (`m:sub`), also the lower limit of an n-ary operator.
    Subscript,
    /// The numerator of a stacked fraction (`m:num`).
    Numerator,
    /// The denominator of a stacked fraction (`m:den`).
    Denominator,
    /// The degree of a radical (`m:deg`), in script-script style at any depth, which the
    /// layout raises once the root sign is chosen.
    Degree,
    /// The upper limit of an n-ary operator that a display draws with the larger variant of
    /// its glyph.
    UpperLimit(Limit),
    /// The lower limit of an n-ary operator that a display draws with the larger variant of
    /// its glyph.
    LowerLimit(Limit),
    /// The limit of a lower- or upper-limit structure (`m:limLow` or `m:limUpp`), sized one
    /// script level down and shifted once its base and limit are measured.
    Limit {
        /// Whether the limit lies under the base (`m:limLow`, cramped).
        lower: bool,
    },
}

/// A limit of an n-ary operator that a display draws with the larger variant of its glyph:
/// the operator's character, and whether the limit stands beside the operator (`m:limLoc`
/// `subSup`) rather than over or under it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limit {
    /// The operator's character.
    pub operator: char,
    /// Whether the limit stands beside the operator.
    pub beside: bool,
}

/// The style of a part of an equation, which sets its size and the space around its
/// operators: display and text style at the equation's size, script style and script-script
/// style smaller.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum MathStyle {
    /// The outermost level of a display (`m:oMathPara`).
    Display,
    /// The outermost level of an equation in a line, and the parts of a display's fraction.
    Text,
    /// A script or a limit, and the parts of a fraction in text style.
    Script,
    /// A script or a fraction's part inside a part in script style.
    ScriptScript,
}

impl MathStyle {
    /// The level of the script glyphs of a part in this style: a script in script style and a
    /// script of a script in script-script style. Display and text style keep the base glyphs.
    /// The level follows the style that gives the part its size.
    #[must_use]
    pub fn script_level(self) -> Option<f_office_fonts::ScriptLevel> {
        match self {
            Self::Display | Self::Text => None,
            Self::Script => Some(f_office_fonts::ScriptLevel::Script),
            Self::ScriptScript => Some(f_office_fonts::ScriptLevel::ScriptOfScript),
        }
    }

    /// The style one step in: a script takes script style, or script-script style inside a
    /// script, and the parts of a fraction the style after the fraction's own.
    #[must_use]
    pub fn inside(self, step: MathStep) -> Self {
        match (step, self) {
            (MathStep::Degree, _) | (_, Self::Script | Self::ScriptScript) => Self::ScriptScript,
            (
                MathStep::Superscript
                | MathStep::SuperscriptBesideSubscript
                | MathStep::Subscript
                | MathStep::UpperLimit(_)
                | MathStep::LowerLimit(_)
                | MathStep::Limit { .. },
                _,
            )
            | (MathStep::Numerator | MathStep::Denominator, Self::Text) => Self::Script,
            (MathStep::Numerator | MathStep::Denominator, Self::Display) => Self::Text,
        }
    }
}

/// Whether stacked fractions inside a display equation step down in size like inline fractions
/// (`m:mathPr/m:smallFrac`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum SmallFractions {
    /// Display fractions stay at text size at every depth (`m:smallFrac` absent or off).
    #[default]
    Off,
    /// Display fractions step down in size like inline fractions (`m:smallFrac` on).
    On,
}

/// Whether an equation is inline or a display (`m:oMathPara`), and whether an enclosing
/// multi-element delimiter has stepped a display's outermost style down to [`MathStyle::Text`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum EquationMode {
    /// Inline equation (`m:oMath` outside `m:oMathPara`).
    #[default]
    Inline,
    /// Display equation (`m:oMathPara`) in [`MathStyle::Display`].
    Display,
    /// Display equation stepped down to [`MathStyle::Text`] while keeping `m:smallFrac=off`
    /// full-size fraction sizing.
    DisplayText,
}

/// The parts of an equation that a run lies in, from the outermost: scripts (`m:sup` and
/// `m:sub`, also as the limits of `m:nary`) and the parts of stacked fractions, each with the
/// size of its structure's control properties when they give one, and whether the equation is
/// a display (`m:oMathPara`). Steps beyond [`crate::params::MATH_SCRIPT_DEPTH`] count as the
/// last one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MathScript {
    steps: [Option<MathStep>; crate::params::MATH_SCRIPT_DEPTH],
    /// For each step, the size in half-points that shifts its part: the size that the control
    /// properties (`m:ctrlPr`) of the equation's outermost structure give, or the paragraph's
    /// size, if known.
    control_sizes: [Option<i64>; crate::params::MATH_SCRIPT_DEPTH],
    mode: EquationMode,
    /// Whether display fractions step down in size like inline fractions (`m:smallFrac`).
    small_frac: SmallFractions,
    large: bool,
    /// The character that the run draws with the middle of its ink on the math axis, as a
    /// delimiter of `m:d` and an n-ary operator inside a line do, if it is one.
    on_axis: Option<char>,
    /// Whether the run lies in a cramped part that no step gives, such as the element of a
    /// radical, at any depth.
    cramped: bool,
    /// Whether the run lies in a structure of the equation, such as a fraction or a delimiter,
    /// with the size that the control properties of the outermost such structure give.
    outermost: OutermostStructure,
}

/// Whether a part of an equation lies in a structure, and the size in half-points that the
/// control properties (`m:ctrlPr`) of the outermost structure that holds it give, if any.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum OutermostStructure {
    /// The part lies in no structure.
    #[default]
    Outside,
    /// The part lies in a structure.
    Inside { control_size: Option<i64> },
}

impl MathScript {
    /// The outermost level of a display of equations.
    #[must_use]
    pub fn display() -> Self {
        Self {
            mode: EquationMode::Display,
            ..Self::default()
        }
    }

    /// The same part, for an n-ary operator that a display draws with the larger variant of
    /// its glyph.
    #[must_use]
    pub fn large(self) -> Self {
        Self {
            large: true,
            ..self
        }
    }

    /// Whether the run is an n-ary operator drawn with the larger variant of its glyph.
    #[must_use]
    pub fn is_large(self) -> bool {
        self.large
    }

    /// The same part, for a run that draws `ch` with the middle of its glyph's ink on the math
    /// axis, as a delimiter of `m:d` and an n-ary operator inside a line do.
    #[must_use]
    pub fn on_axis(self, ch: char) -> Self {
        Self {
            on_axis: Some(ch),
            ..self
        }
    }

    /// The character that the run draws with the middle of its ink on the math axis, if any.
    #[must_use]
    pub fn axis_character(self) -> Option<char> {
        self.on_axis
    }

    /// The same part, cramped: a superscript inside it, at any depth, rises by the cramped
    /// shift, as one in a fraction's denominator does. The element of a radical is cramped.
    #[must_use]
    pub fn cramped(self) -> Self {
        Self {
            cramped: true,
            ..self
        }
    }

    /// Whether the part is cramped by [`Self::cramped`].
    #[must_use]
    pub fn is_cramped(self) -> bool {
        self.cramped
    }
    /// The same part, inside a structure of the equation whose control properties
    /// (`m:ctrlPr`) give the size `control_size` in half-points, if any. The first structure
    /// that a run enters is the outermost structure of the equation that holds it, and its
    /// size stays with every structure further in.
    #[must_use]
    pub fn in_structure(self, control_size: Option<i64>) -> Self {
        if self.outermost != OutermostStructure::Outside {
            return self;
        }
        Self {
            outermost: OutermostStructure::Inside { control_size },
            ..self
        }
    }

    /// The same part without the outermost structure's size, which only the reading of the
    /// equation uses: what a run's properties keep, so that runs in one part stay equal.
    #[must_use]
    pub fn without_outermost(self) -> Self {
        Self {
            outermost: OutermostStructure::Outside,
            ..self
        }
    }

    /// Whether the part lies in no structure of its equation: at the equation's top level.
    #[must_use]
    pub fn in_no_structure(self) -> bool {
        self.outermost == OutermostStructure::Outside
    }

    /// The size in half-points that the control properties of the outermost structure of the
    /// equation that holds the run give, if any: the size of the fences of a delimiter.
    #[must_use]
    pub fn outermost_size(self) -> Option<i64> {
        match self.outermost {
            OutermostStructure::Outside => None,
            OutermostStructure::Inside { control_size } => control_size,
        }
    }

    /// Whether the run lies in a limit of an n-ary operator that a display draws with the
    /// larger variant of its glyph, at any depth.
    #[must_use]
    pub fn in_limit(self) -> bool {
        self.steps()
            .any(|step| matches!(step, MathStep::UpperLimit(_) | MathStep::LowerLimit(_)))
    }

    /// Whether the run lies in a superscript or a subscript (`m:sup`, `m:sub`), at any depth.
    #[must_use]
    pub fn in_script(self) -> bool {
        self.steps().any(|step| {
            matches!(
                step,
                MathStep::Superscript | MathStep::SuperscriptBesideSubscript | MathStep::Subscript
            )
        })
    }

    /// The part one step further in, of a structure whose control properties (`m:ctrlPr`)
    /// give the size `control_size` in half-points, if any. Inside an outermost structure, the
    /// step takes that structure's size instead, which shifts every part of the equation that
    /// it holds, or none when that structure gives no size.
    #[must_use]
    pub fn inside(self, step: MathStep, control_size: Option<i64>) -> Self {
        let size = match self.outermost {
            OutermostStructure::Outside => control_size,
            OutermostStructure::Inside {
                control_size: outermost,
            } => outermost,
        };
        let mut inner = self;
        let free = inner
            .steps
            .iter_mut()
            .zip(inner.control_sizes.iter_mut())
            .find(|(s, _)| s.is_none());
        if let Some((free_step, free_size)) = free {
            *free_step = Some(step);
            *free_size = size;
        }
        inner
    }

    /// Whether every step whose size is known shifts its part by `half_points`, the size of the
    /// run's own text. A part that another size shifts keeps its base glyphs.
    #[must_use]
    pub fn shifted_at(self, half_points: i64) -> bool {
        self.control_sizes
            .iter()
            .flatten()
            .all(|size| *size == half_points)
    }

    /// The same part, with the paragraph's size `half_points` for each step whose structure
    /// gives no size: the size that shifts the parts of an equation whose outermost structure
    /// has no control properties.
    #[must_use]
    pub fn at_paragraph_size(self, half_points: i64) -> Self {
        let mut sized = self;
        for (step, size) in sized.steps.iter().zip(sized.control_sizes.iter_mut()) {
            if step.is_some() && size.is_none() {
                *size = Some(half_points);
            }
        }
        sized
    }

    /// How many steps deep the run is: 0 outside every script and fraction.
    #[must_use]
    pub fn depth(self) -> usize {
        self.steps.iter().flatten().count()
    }

    /// Whether the equation is a display (`m:oMathPara`).
    #[must_use]
    pub fn is_display(self) -> bool {
        !matches!(self.mode, EquationMode::Inline)
    }

    /// Steps the outermost style of a display equation down to [`MathStyle::Text`] (as inside
    /// a multi-element delimiter) while keeping [`Self::is_display`] for `m:smallFrac` sizing.
    #[must_use]
    pub(crate) const fn in_text_style(mut self) -> Self {
        if matches!(self.mode, EquationMode::Display) {
            self.mode = EquationMode::DisplayText;
        }
        self
    }

    /// The outermost style before any step of this script.
    #[must_use]
    pub(crate) fn outermost_style(self) -> MathStyle {
        if matches!(self.mode, EquationMode::Display) {
            MathStyle::Display
        } else {
            MathStyle::Text
        }
    }

    /// Sets whether display fractions step down in size (`m:smallFrac`).
    #[must_use]
    pub(crate) const fn with_small_frac(mut self, small_frac: SmallFractions) -> Self {
        self.small_frac = small_frac;
        self
    }

    /// The style one step in for this equation: in a display without `m:smallFrac`, stacked
    /// fractions step `Display` to `Text` and keep `Text`, `Script` and `ScriptScript` at their
    /// own size; inline or under `m:smallFrac`, every step follows [`MathStyle::inside`].
    #[must_use]
    pub(crate) fn step_style(self, style: MathStyle, step: MathStep) -> MathStyle {
        if self.is_display()
            && self.small_frac == SmallFractions::Off
            && matches!(step, MathStep::Numerator | MathStep::Denominator)
        {
            match style {
                MathStyle::Display => MathStyle::Text,
                other => other,
            }
        } else {
            style.inside(step)
        }
    }

    /// The style of the run's part: display or text style at the outermost level, and the
    /// style that each step in gives.
    #[must_use]
    pub fn style(self) -> MathStyle {
        self.steps().fold(self.outermost_style(), |style, step| {
            self.step_style(style, step)
        })
    }

    /// The steps from the outermost.
    pub fn steps(self) -> impl Iterator<Item = MathStep> {
        self.steps.into_iter().flatten()
    }

    /// The steps from the outermost, each with the size in half-points that the control
    /// properties of its structure give, if any.
    pub fn steps_with_control_sizes(self) -> impl Iterator<Item = (MathStep, Option<i64>)> {
        self.steps
            .into_iter()
            .zip(self.control_sizes)
            .filter_map(|(step, size)| step.map(|step| (step, size)))
    }
}

/// The `w:vertAlign` of a run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VerticalAlign {
    /// On the baseline.
    Baseline,
    /// Smaller and raised.
    Superscript,
    /// Smaller and lowered.
    Subscript,
}

/// The properties that a page number or page count that Word computes, and the box of a check
/// box form field, take from the first run of the field's code, where the target says so: the
/// faces, the sizes, bold and italic, and for a page number or page count the color, as that run
/// sets them directly, each `None` where it sets none.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CodeFormat {
    font_ascii: Option<FontRef>,
    font_hansi: Option<FontRef>,
    font_cs: Option<Box<FontRef>>,
    size: Option<i64>,
    size_cs: Option<i64>,
    bold: Option<bool>,
    bold_cs: Option<bool>,
    italic: Option<bool>,
    italic_cs: Option<bool>,
    color: CodeColor,
    style: CodeStyle,
}

/// The color that a value takes from the first run of its field's code.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum CodeColor {
    /// The color of the run that shows the value.
    #[default]
    Own,
    /// The code run's direct color, or none where it sets none.
    Code(Option<Color>),
}

/// The character style that a value takes from the code run of its field.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
enum CodeStyle {
    /// The character style of the run that shows the value.
    #[default]
    Own,
    /// The code run's character style, or none where it sets none.
    Code(Option<String>),
}

impl CodeFormat {
    /// The format that the direct properties `props` of a code run give.
    #[must_use]
    pub fn of(props: &RunProps) -> Self {
        Self {
            font_ascii: props.font_ascii.clone(),
            font_hansi: props.font_hansi.clone(),
            font_cs: props.font_cs.clone(),
            size: props.size,
            size_cs: props.size_cs,
            bold: props.bold,
            bold_cs: props.bold_cs,
            italic: props.italic,
            italic_cs: props.italic_cs,
            color: CodeColor::Code(props.color),
            style: CodeStyle::Own,
        }
    }

    /// This format with the code run's character style (`w:rStyle`) in place of the showing
    /// run's own, also where the code run sets none.
    #[must_use]
    pub(crate) fn with_style(self, style: Option<String>) -> Self {
        Self {
            style: CodeStyle::Code(style),
            ..self
        }
    }

    /// The character style for the run that shows the value, with the code run's style in place
    /// of `own` where set.
    #[must_use]
    pub(crate) fn style_over<'a>(&'a self, own: Option<&'a str>) -> Option<&'a str> {
        match &self.style {
            CodeStyle::Own => own,
            CodeStyle::Code(style) => style.as_deref(),
        }
    }

    /// This format without the code run's color: the value keeps the color of its own run, as
    /// the box of a check box does.
    #[must_use]
    pub fn with_own_color(self) -> Self {
        Self {
            color: CodeColor::Own,
            ..self
        }
    }

    /// The direct properties `props` of the run that shows the value, with these in place of
    /// its own, also where these are not set.
    #[must_use]
    pub fn over(&self, props: &RunProps) -> RunProps {
        RunProps {
            font_ascii: self.font_ascii.clone(),
            font_hansi: self.font_hansi.clone(),
            font_cs: self.font_cs.clone(),
            size: self.size,
            size_cs: self.size_cs,
            bold: self.bold,
            bold_cs: self.bold_cs,
            italic: self.italic,
            italic_cs: self.italic_cs,
            color: match self.color {
                CodeColor::Own => props.color,
                CodeColor::Code(color) => color,
            },
            ..props.clone()
        }
    }
}

impl RunProps {
    /// The font size in half-points at which the run draws: its size, or Word's default size
    /// ([`crate::params::DEFAULT_FONT_SIZE`]) when it has none, or one of 0 or below.
    #[must_use]
    pub fn drawn_half_points(&self) -> i64 {
        self.size
            .filter(|size| *size > 0)
            .unwrap_or(crate::params::DEFAULT_FONT_SIZE)
    }

    /// Whether all characters take complex script formatting, independently of direction.
    #[must_use]
    pub fn uses_complex_formatting(&self) -> bool {
        self.complex.unwrap_or(false) || self.rtl.unwrap_or(false)
    }

    /// Overlays `other` on `self`: every property set in `other` wins. It names each field of
    /// `other`, so that a new field does not compile until it is overlaid here.
    pub fn apply(&mut self, other: &Self) {
        macro_rules! apply_all {
            ($($field:ident),+ $(,)?) => {{
                let Self { $($field,)+ unsupported } = other;
                $(overlay(&mut self.$field, $field.as_ref());)+
                self.unsupported.apply(unsupported);
            }};
        }
        apply_all!(
            font_ascii,
            font_hansi,
            bold,
            italic,
            size,
            color,
            underline,
            strike,
            changed,
            shading,
            highlight,
            caps,
            small_caps,
            vertical,
            math_script,
            math,
            position,
            hidden,
            phantom,
            kern,
            spacing,
            scale,
            outline,
            text_fill,
            shadow,
            glow,
            reflection,
            legacy_shadow,
            legacy_outline,
            emboss,
            imprint,
            effect,
            ligatures,
            font_cs,
            size_cs,
            bold_cs,
            italic_cs,
            complex,
            rtl,
            field_rtl,
            form_text,
            font_east_asia,
            east_asian_hint,
            east_asian_script,
            lang,
            bidi_script,
            bidi_class,
            snap_to_grid,
            bordered,
        );
    }

    /// Overlays the resolved run properties of a style layer (`other`: table style, paragraph
    /// style, or character style) onto `self`, combining ECMA-376 Part 1, 17.7.3 toggle
    /// properties with XOR when `defaults` does not turn the toggle on, and with normal overlay
    /// otherwise.
    pub(crate) fn apply_style_layer(&mut self, other: &Self, defaults: &Self) {
        let prev = (
            self.bold,
            self.bold_cs,
            self.italic,
            self.italic_cs,
            self.caps,
            self.small_caps,
            self.hidden,
            self.legacy_shadow,
            self.legacy_outline,
            self.emboss,
            self.imprint,
        );
        self.apply(other);
        self.bold = combine_toggle(prev.0, other.bold, defaults.bold);
        self.bold_cs = combine_toggle(prev.1, other.bold_cs, defaults.bold_cs);
        self.italic = combine_toggle(prev.2, other.italic, defaults.italic);
        self.italic_cs = combine_toggle(prev.3, other.italic_cs, defaults.italic_cs);
        self.caps = combine_toggle(prev.4, other.caps, defaults.caps);
        self.small_caps = combine_toggle(prev.5, other.small_caps, defaults.small_caps);
        self.hidden = combine_toggle(prev.6, other.hidden, defaults.hidden);
        self.legacy_shadow = combine_toggle(prev.7, other.legacy_shadow, defaults.legacy_shadow);
        self.legacy_outline = combine_toggle(prev.8, other.legacy_outline, defaults.legacy_outline);
        self.emboss = combine_toggle(prev.9, other.emboss, defaults.emboss);
        self.imprint = combine_toggle(prev.10, other.imprint, defaults.imprint);
    }
}

/// Combines one ECMA-376 Part 1, 17.7.3 toggle property across style layers: XOR when `default`
/// does not turn the toggle on, normal overlay otherwise.
fn combine_toggle(prev: Option<bool>, layer: Option<bool>, default: Option<bool>) -> Option<bool> {
    if default == Some(true) {
        layer.or(prev)
    } else if layer == Some(true) {
        Some(!prev.unwrap_or(false))
    } else {
        prev
    }
}

impl RunProps {
    /// The properties for East Asian characters: the East Asian font in place of the others.
    /// Without one, the others stay.
    #[must_use]
    pub fn east_asian(&self) -> Self {
        let font = self
            .font_east_asia
            .as_deref()
            .cloned()
            .or_else(|| self.font_hansi.clone())
            .or_else(|| self.font_ascii.clone());
        Self {
            font_ascii: font.clone(),
            font_hansi: font,
            ..self.clone()
        }
    }

    /// The size of text with complex script formatting. A run whose text all takes complex
    /// script formatting (`w:rtl` or `w:cs`) has its complex script size, or the default size
    /// when no level gives one; the complex script characters of another run have their
    /// complex script size, or else the run's size.
    fn complex_size(&self) -> Option<i64> {
        if self.uses_complex_formatting() {
            self.size_cs
        } else {
            self.size_cs.or(self.size)
        }
    }

    /// The properties for complex script characters: the complex script font, size, bold and
    /// italic in place of the others. Without a complex script font, the run's font stays, and
    /// the size is [`Self::complex_size`].
    #[must_use]
    pub fn complex_script(&self) -> Self {
        let font = self
            .font_cs
            .as_deref()
            .cloned()
            .or_else(|| self.font_ascii.clone());
        Self {
            font_ascii: font.clone(),
            font_hansi: font,
            size: self.complex_size(),
            bold: self.bold_cs,
            italic: self.italic_cs,
            ..self.clone()
        }
    }

    /// Whether the text of a run with the properties `other` is measured as one text with
    /// the text of a run with these, so that their letters join: the properties are the
    /// same, but for the class of the bidi language and the unsupported properties, which change
    /// no glyph that F-Office draws, for the kind of equation text (`Some(true)` vs `Some(false)`)
    /// when both are inside an equation and neither asks for italic, and for a missing hint
    /// against the default hint, which every face choice reads alike.
    #[must_use]
    pub fn joins(&self, other: &Self) -> bool {
        let italic = |props: &Self| props.italic == Some(true) || props.italic_cs == Some(true);
        let math =
            if self.math.is_some() == other.math.is_some() && !(italic(self) || italic(other)) {
                self.math
            } else {
                other.math
            };
        let hint = |props: &Self| props.east_asian_hint.unwrap_or(false);
        let east_asian_hint = if hint(self) == hint(other) {
            self.east_asian_hint
        } else {
            other.east_asian_hint
        };
        let snap = |props: &Self| props.snap_to_grid.unwrap_or(true);
        let snap_to_grid = if snap(self) == snap(other) {
            self.snap_to_grid
        } else {
            other.snap_to_grid
        };
        if self.bidi_class == other.bidi_class
            && self.unsupported == other.unsupported
            && other.math == math
            && other.east_asian_hint == east_asian_hint
            && other.snap_to_grid == snap_to_grid
        {
            return self == other;
        }
        let measured_alike = Self {
            bidi_class: self.bidi_class,
            unsupported: self.unsupported.clone(),
            math,
            east_asian_hint,
            snap_to_grid,
            ..other.clone()
        };
        *self == measured_alike
    }

    /// Whether the run's bidi language, its own or the document defaults', is Hebrew. A run
    /// that names none is not.
    #[must_use]
    pub fn hebrew_language(&self) -> bool {
        self.bidi_script == Some(BidiScript::Hebrew)
    }

    /// Whether the digits of the run have a face of their own: in a run with `w:rtl` whose
    /// bidi language is not Hebrew. With a Hebrew bidi language they take the complex
    /// script font, as the run's other characters.
    #[must_use]
    pub fn has_digit_face(&self) -> bool {
        self.rtl.unwrap_or(false) && self.bidi_script != Some(BidiScript::Hebrew)
    }

    /// The properties for the digits of a run with `w:rtl`: the run's own fonts with the
    /// size of [`Self::complex_size`] and the complex script bold and italic.
    #[must_use]
    pub fn complex_digits(&self) -> Self {
        Self {
            size: self.complex_size(),
            bold: self.bold_cs,
            italic: self.italic_cs,
            ..self.clone()
        }
    }

    /// Reads a `w:rPr` element.
    pub(crate) fn read(reader: &mut PartReader, rpr: NodeId) -> Self {
        let mut props = Self::default();
        props.read_into(reader, rpr);
        props
    }

    /// Reads the children of a `w:rPr` element onto `self`, overwriting only the properties
    /// that this element sets.
    pub(crate) fn read_into(&mut self, reader: &mut PartReader, rpr: NodeId) {
        for child in reader.doc.child_elements(rpr) {
            self.read_child(reader, child);
        }
    }

    fn read_child(&mut self, reader: &mut PartReader, child: NodeId) {
        let doc = reader.doc;
        let Some(element) = doc.element(child) else {
            return;
        };
        let local = element.name.local;
        if doc.is(child, W, local)
            && let Some((property, shows)) = unsupported_property(reader, child, local)
        {
            self.unsupported.set(property, SetIn::read(shows, reader));
        }
        match local {
            "rFonts" => self.read_fonts(reader, child),
            "b" => self.bold = Some(off_also_for_none(doc, child)),
            "i" => self.italic = Some(off_also_for_none(doc, child)),
            "bCs" => self.bold_cs = Some(off_also_for_none(doc, child)),
            "iCs" => self.italic_cs = Some(off_also_for_none(doc, child)),
            "szCs" => self.size_cs = reader.font_size(child, "val"),
            "rtl" => self.rtl = Some(off_also_for_none(doc, child)),
            "cs" => self.complex = Some(off_also_for_none(doc, child)),
            "bdr" => {
                let visible = doc
                    .attribute(child, Some(W), "val")
                    .and_then(|name| BORDER_LINE.find(name))
                    .is_some_and(|(style, ..)| *style != LineStyle::None);
                let frame = doc
                    .attribute(child, Some(W), "frame")
                    .and_then(on_off::read)
                    == Some(true);
                self.bordered = Some(visible || frame);
            }
            "lang" => {
                if let Some(lang) = doc.attribute(child, Some(W), "eastAsia") {
                    self.east_asian_script = EastAsianScript::of(lang);
                }
                if let Some(lang) = doc.attribute(child, Some(W), "val") {
                    self.lang = Some(lang.into());
                }
                if let Some(lang) = doc.attribute(child, Some(W), "bidi") {
                    self.bidi_script = Some(BidiScript::of(lang));
                    self.bidi_class = Some(BidiLanguageClass::of(lang));
                }
            }
            "caps" => self.caps = Some(off_also_for_none(doc, child)),
            "smallCaps" => self.small_caps = Some(off_also_for_none(doc, child)),
            "sz" => self.size = reader.font_size(child, "val"),
            "color" => self.color = read_text_color(reader, child),
            "u" => self.underline = reader.enumeration(child, "val", UNDERLINE),
            "strike" => {
                self.strike = Some(Strike::of(Strike::Single, off_also_for_none(doc, child)));
            }
            "dstrike" => {
                self.strike = Strike::with_double(self.strike, off_also_for_none(doc, child));
            }
            // A tracked change of the formatting, and in a paragraph mark's properties an
            // inserted mark, mark the line in the margin.
            "rPrChange" | "ins" | "moveTo" => self.changed = Some(true),
            "shd" => self.shading = read_shading(reader, child),
            "highlight" => {
                self.highlight = reader
                    .enumeration(child, "val", HIGHLIGHT)
                    .map(|rgb| rgb.map_or(Color::Auto, Color::Rgb));
            }
            "vertAlign" => self.vertical = reader.enumeration(child, "val", RUN_V_ALIGN),
            "position" => {
                self.position = reader
                    .half_points(child, "val")
                    .and_then(Length::from_half_points);
            }
            "vanish" => self.hidden = Some(off_also_for_none(doc, child)),
            "snapToGrid" => self.snap_to_grid = Some(off_also_for_none(doc, child)),
            "kern" => self.kern = reader.half_points(child, "val"),
            "spacing" => self.spacing = reader.twips(child, "val"),
            // ECMA-376 Part 1, 17.3.2.43: a percentage from 1 to 600.
            "w" => self.scale = reader.text_scale(child, "val"),
            local if doc.is(child, W14, local) => self.read_word_2010(reader, child, local),
            local if doc.is(child, W, local) => self.read_legacy_effect(reader, child, local),
            _ => {}
        }
    }

    /// Records a legacy WordprocessingML text effect toggle (`w:shadow`, `w:outline`, `w:emboss`,
    /// `w:imprint`).
    fn read_legacy_effect(&mut self, reader: &PartReader, child: NodeId, local: &str) {
        let on = || Some(off_also_for_none(reader.doc, child));
        match local {
            "shadow" => self.legacy_shadow = on(),
            "outline" => self.legacy_outline = on(),
            "emboss" => self.emboss = on(),
            "imprint" => self.imprint = on(),
            _ => {}
        }
    }

    /// Reads a run property of Word 2010 (`w14`, [MS-DOCX] 2.6.1): the outline and the fill
    /// of the text, its effects and its ligatures. F-Office draws no fill and no effect of
    /// them, and keeps each as an unsupported property, which shows its feature where F-Office
    /// draws it as another or leaves it out.
    fn read_word_2010(&mut self, reader: &mut PartReader, node: NodeId, local: &str) {
        if let Some(effect) = TextEffect::named(local) {
            if effect.draws_paths() {
                self.effect = Some(true);
            }
            let shows = effect.shows(reader, node);
            if effect == TextEffect::Shadow {
                self.shadow = shows.then(|| text_shadow(reader, node));
            } else if effect == TextEffect::Glow {
                self.glow = shows.then(|| text_glow(reader, node));
            } else if effect == TextEffect::Reflection {
                self.reflection = shows.then(|| Box::new(text_reflection(reader, node)));
            }
            self.unsupported.set(
                UnsupportedProperty::Effect(effect),
                SetIn::read(shows, reader),
            );
            return;
        }
        match local {
            "textOutline" => {
                let shows = outline_fill_replaced(reader, node);
                self.unsupported.set(
                    UnsupportedProperty::TextOutlineFill,
                    SetIn::read(shows, reader),
                );
                self.outline = text_outline(reader, node).or(self.outline);
            }
            "textFill" => {
                let (fill, unsupported) = text_fill(reader, node);
                self.unsupported.set(
                    UnsupportedProperty::TextFill,
                    SetIn::read(unsupported, reader),
                );
                self.text_fill = fill.or(self.text_fill.take());
            }
            // Every value that names standard ligatures turns them on, such as
            // `standardContextual`, and `all` does too.
            "ligatures" => {
                self.ligatures = reader
                    .doc
                    .attribute(node, Some(W14), "val")
                    .map(|v| v.starts_with("standard") || v == "all");
            }
            _ => {}
        }
    }

    fn read_fonts(&mut self, reader: &mut PartReader, node: NodeId) {
        if let Some(font) = font_ref(reader, node, "ascii") {
            self.font_ascii = Some(font);
        }
        if let Some(font) = font_ref(reader, node, "hAnsi") {
            self.font_hansi = Some(font);
        }
        if let Some(font) = font_ref(reader, node, "cs") {
            self.font_cs = Some(Box::new(font));
        }
        if let Some(font) = font_ref(reader, node, "eastAsia") {
            self.font_east_asia = Some(Box::new(font));
        }
        if let Some(hint) = reader.enumeration(node, "hint", HINT) {
            self.east_asian_hint = Some(hint);
        }
    }
}

/// `ST_Theme`, a font of the theme that a run's `w:rFonts` names for a slot: the complex script
/// fonts, the East Asian fonts and the Latin fonts, which `majorAscii` and `majorHAnsi` name
/// alike. Text outside the type counts as missing, so the slot takes the font that it names,
/// where F-Office read it as the minor Latin font, or the major one for text that starts with
/// `major`, before.
pub(super) static THEME_FONT: Values<FontRef> = Values::new(&THEME_FONTS);

/// The names of [`THEME_FONT`], a static of their own since a [`FontRef`] can hold a name.
static THEME_FONTS: [Case<FontRef>; 8] = [
    own("majorAscii", FontRef::MajorLatin),
    own("majorHAnsi", FontRef::MajorLatin),
    own("minorAscii", FontRef::MinorLatin),
    own("minorHAnsi", FontRef::MinorLatin),
    own("majorBidi", FontRef::MajorBidi),
    own("minorBidi", FontRef::MinorBidi),
    own("majorEastAsia", FontRef::MajorEastAsia),
    own("minorEastAsia", FontRef::MinorEastAsia),
];

/// `ST_Hint` of a run's `w:rFonts`: whether the characters that the East Asian and the other
/// fonts share take the East Asian font. A complex script hint, `cs`, is drawn as the default
/// one. Text outside the type counts as missing, so the run takes its style's hint, where
/// F-Office read it as the default hint before.
pub(super) const HINT: &Values<bool> = &Values::new(&[
    own("default", false),
    own("eastAsia", true),
    another("cs", false),
]);

/// The font of the slot `slot` of the `w:rFonts` element `node`: the theme's font that the
/// slot's theme attribute names, else the font that the slot names.
fn font_ref(reader: &mut PartReader, node: NodeId, slot: &str) -> Option<FontRef> {
    let theme_attribute = if slot == "cs" {
        "cstheme".to_owned()
    } else {
        format!("{slot}Theme")
    };
    reader
        .enumeration(node, &theme_attribute, &THEME_FONT)
        .or_else(|| {
            reader
                .doc
                .attribute(node, Some(W), slot)
                .map(|name| FontRef::Name(name.to_owned()))
        })
}

/// A kind of underline (`ST_Underline`, ECMA-376 Part 1, 17.18.99). A target whose quirk
/// `UnderlineForms` is `ByKind` draws each kind in its own form; the others draw every kind
/// but `None` as a single underline.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Underline {
    /// No underline.
    #[default]
    None,
    /// A single line, which `w:u` without `w:val` also means in a link of a table of contents.
    Single,
    /// A single line under the words and none under the spaces.
    Words,
    /// Two lines.
    Double,
    /// One thick line.
    Thick,
    /// A row of dots.
    Dotted,
    /// A row of thick dots.
    DottedHeavy,
    /// A row of dashes.
    Dash,
    /// A row of thick dashes.
    DashedHeavy,
    /// A row of long dashes.
    DashLong,
    /// A row of thick long dashes.
    DashLongHeavy,
    /// Dashes and dots in turn.
    DotDash,
    /// Thick dashes and dots in turn.
    DashDotHeavy,
    /// A dash and two dots in turn.
    DotDotDash,
    /// A thick dash and two thick dots in turn.
    DashDotDotHeavy,
    /// A wave.
    Wave,
    /// A thick wave.
    WavyHeavy,
    /// Two waves.
    WavyDouble,
}

/// `ST_Underline` of a run's `w:u`. Text outside the type counts as missing, so the run takes
/// its style's underline, where F-Office drew it as a single underline before. The kinds other
/// than `single` and `none` read as drawn as another value, because only a target whose quirk
/// `UnderlineForms` is `ByKind` draws them in their own form, and the waves on none.
pub(crate) const UNDERLINE: &Values<Underline> = &Values::new(&[
    own("single", Underline::Single),
    own("none", Underline::None),
    another("words", Underline::Words),
    another("double", Underline::Double),
    another("thick", Underline::Thick),
    another("dotted", Underline::Dotted),
    another("dottedHeavy", Underline::DottedHeavy),
    another("dash", Underline::Dash),
    another("dashedHeavy", Underline::DashedHeavy),
    another("dashLong", Underline::DashLong),
    another("dashLongHeavy", Underline::DashLongHeavy),
    another("dotDash", Underline::DotDash),
    another("dashDotHeavy", Underline::DashDotHeavy),
    another("dotDotDash", Underline::DotDotDash),
    another("dashDotDotHeavy", Underline::DashDotDotHeavy),
    another("wave", Underline::Wave),
    another("wavyHeavy", Underline::WavyHeavy),
    another("wavyDouble", Underline::WavyDouble),
]);

/// The line through a run's text.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Strike {
    /// No line.
    #[default]
    None,
    /// One line (`w:strike`).
    Single,
    /// Two lines (`w:dstrike`), which a target whose quirk `UnderlineForms` is `ByKind` draws
    /// as two lines and the others as one.
    Double,
}

impl Strike {
    /// `kind` when the property is on, else no line.
    const fn of(kind: Self, on: bool) -> Self {
        if on { kind } else { Self::None }
    }

    /// The line through a run's text read so far, `read`, after a double strike that is `on`
    /// or off: on, two lines; off, it takes back only a double strike of the same run, so that
    /// it leaves a single strike, of the run or of its styles, as it is.
    fn with_double(read: Option<Self>, on: bool) -> Option<Self> {
        match read {
            _ if on => Some(Self::Double),
            Some(Self::Double) => Some(Self::None),
            other => other,
        }
    }

    /// Whether the run has a line through its text.
    #[must_use]
    pub const fn is_on(self) -> bool {
        !matches!(self, Self::None)
    }
}

/// `ST_VerticalAlignRun` of a run's `w:vertAlign`. Text outside the type counts as missing, so
/// the run takes its style's position, where F-Office read it as the baseline before.
pub(super) const RUN_V_ALIGN: &Values<VerticalAlign> = &Values::new(&[
    own("baseline", VerticalAlign::Baseline),
    own("superscript", VerticalAlign::Superscript),
    own("subscript", VerticalAlign::Subscript),
]);

/// The marks of `ST_Em` that a run's emphasis mark (`w:em`) draws: every value but `none`.
const EMPHASIS_MARKS: [&str; 4] = ["dot", "comma", "circle", "underDot"];

/// The unsupported property of the run property `node`, a WordprocessingML element of the name
/// `local`, if it is one, and whether it shows its feature: an outline, a shadow, an emboss or
/// an imprint that is on (ECMA-376 Part 1, 17.3.2.23, 17.3.2.31, 17.3.2.13, 17.3.2.18), a
/// double strike that is on (17.3.2.9), a border of a line style other than none (17.3.2.4), a
/// width to fit the text into above 0 (17.3.2.14), an emphasis mark (17.3.2.12), and two lines
/// in one or text turned in its line (17.3.2.10).
fn unsupported_property(
    reader: &mut PartReader,
    node: NodeId,
    local: &str,
) -> Option<(UnsupportedProperty, bool)> {
    let doc = reader.doc;
    let on = || off_also_for_none(doc, node);
    let value = || doc.attribute(node, Some(W), "val");
    let unsupported = match local {
        "outline" => (UnsupportedProperty::Outline, on()),
        "shadow" => (UnsupportedProperty::Shadow, on()),
        "emboss" => (UnsupportedProperty::Emboss, on()),
        "imprint" => (UnsupportedProperty::Imprint, on()),
        "dstrike" => (UnsupportedProperty::DoubleStrike, on()),
        "bdr" => (
            UnsupportedProperty::Border,
            value()
                .and_then(|name| BORDER_LINE.find(name))
                .is_some_and(|(style, ..)| *style != LineStyle::None),
        ),
        "fitText" => (
            UnsupportedProperty::FitText,
            reader
                .twips(node, "val")
                .is_some_and(|width| width > Length::ZERO),
        ),
        "em" => (
            UnsupportedProperty::Emphasis,
            value().is_some_and(|mark| EMPHASIS_MARKS.contains(&mark)),
        ),
        "eastAsianLayout" => (
            UnsupportedProperty::EastAsianLayout,
            ["combine", "vert"].into_iter().any(|name| {
                doc.attribute(node, Some(W), name).and_then(on_off::read) == Some(true)
            }),
        ),
        _ => return None,
    };
    Some(unsupported)
}

/// Reads a `w14:*` EMU length attribute of `node`, 0 when missing or unreadable.
fn emu_length_attr(reader: &mut PartReader, node: NodeId, name: &str) -> Length {
    Length::from_emus(size(reader, node, name)).unwrap_or(Length::ZERO)
}

/// Reads a `w14:shadow`: its lengths, each 0 when it is missing or does not read, and the color
/// of [`TextShadow::color`].
fn text_shadow(reader: &mut PartReader, node: NodeId) -> TextShadow {
    // `ST_PositiveFixedAngle`: a whole number from 0 to below a whole turn.
    let direction = reader
        .or_missing_in(node, (Some(W14), "dir"), |value| {
            f_office_drawingml::integer(value)
                .filter(|angle| (0..f_office_units::scale::FULL_TURN).contains(angle))
        })
        .unwrap_or(0);
    let doc = reader.doc;
    let untransformed = percent(reader, node, "sx") == DRAWING_WHOLE
        && percent(reader, node, "sy") == DRAWING_WHOLE
        && percent(reader, node, "kx") == 0
        && percent(reader, node, "ky") == 0;
    let transparency = transparency(reader, node)
        .unwrap_or(0)
        .clamp(0, DRAWING_WHOLE);
    let color = untransformed
        .then(|| {
            f_office_drawingml::color::DrawColor::read_in(
                doc,
                node,
                f_office_drawingml::color::ColorNames::Word2010,
                reader.drawing_warnings(),
            )
            .and_then(|color| color.resolve(reader.scheme()))
            .map(|(rgb, _)| [rgb.r, rgb.g, rgb.b])
        })
        .flatten();
    TextShadow {
        blur: emu_length_attr(reader, node, "blurRad"),
        distance: emu_length_attr(reader, node, "dist"),
        direction,
        color,
        transparency,
    }
}

/// Reads a `w14:glow`: its radius in EMU (`w14:rad`), its resolved color, and its transparency
/// (`w14:alpha`).
fn text_glow(reader: &mut PartReader, node: NodeId) -> TextGlow {
    let radius = Length::from_emus(size(reader, node, "rad")).unwrap_or(Length::ZERO);
    let transparency = transparency(reader, node)
        .unwrap_or(0)
        .clamp(0, DRAWING_WHOLE);
    let color = f_office_drawingml::color::DrawColor::read_in(
        reader.doc,
        node,
        f_office_drawingml::color::ColorNames::Word2010,
        reader.drawing_warnings(),
    )
    .and_then(|color| color.resolve(reader.scheme()))
    .map(|(rgb, _)| [rgb.r, rgb.g, rgb.b]);
    TextGlow {
        radius,
        color,
        transparency,
    }
}

/// Reads a `w14:reflection`: its blur radius, distance, opacity ramp (`stA`, `stPos`, `endA`,
/// `endPos`), and whether it is a standard unskewed downward reflection (`dir = 90°`, `sx = 100%`,
/// `sy = -100%`, `kx = ky = 0`).
fn text_reflection(reader: &mut PartReader, node: NodeId) -> TextReflection {
    let direction = reader
        .or_missing_in(node, (Some(W14), "dir"), |value| {
            f_office_drawingml::integer(value)
                .filter(|angle| (0..f_office_units::scale::FULL_TURN).contains(angle))
        })
        .unwrap_or(f_office_units::scale::QUARTER_TURN);
    let downward = direction == f_office_units::scale::QUARTER_TURN
        && percent(reader, node, "sx") == DRAWING_WHOLE
        && percent(reader, node, "sy") == -DRAWING_WHOLE
        && percent(reader, node, "kx") == 0
        && percent(reader, node, "ky") == 0;
    TextReflection {
        blur: emu_length_attr(reader, node, "blurRad"),
        distance: emu_length_attr(reader, node, "dist"),
        start_alpha: percent(reader, node, "stA").clamp(0, DRAWING_WHOLE),
        start_pos: percent(reader, node, "stPos").clamp(0, DRAWING_WHOLE),
        end_alpha: percent(reader, node, "endA").clamp(0, DRAWING_WHOLE),
        end_pos: percent(reader, node, "endPos").clamp(0, DRAWING_WHOLE),
        downward,
    }
}

/// Reads a `w14:textOutline`. A gradient (`w14:gradFill`) is not read, and a solid color that is
/// not opaque is read as opaque ([`outline_fill_replaced`]).
fn text_outline(reader: &mut PartReader, node: NodeId) -> Option<TextOutline> {
    let doc = reader.doc;
    if doc.child(node, W14, "noFill").is_some() {
        return Some(TextOutline::None);
    }
    if doc.child(node, W14, "gradFill").is_some() {
        return None;
    }
    let fill = doc.child(node, W14, "solidFill")?;
    let color = if let Some(rgb) = doc.child(fill, W14, "srgbClr") {
        match doc.attribute(rgb, Some(W14), "val").map(parse_color)? {
            Color::Rgb(rgb) => OutlineColor::Rgb(rgb),
            Color::Auto => return None,
        }
    } else {
        doc.child(fill, W14, "schemeClr")?;
        OutlineColor::Scheme
    };
    // The width is an `ST_LineWidth` in EMU, read as DrawingML reads it.
    let width = reader
        .or_missing_in(node, (Some(W14), "w"), f_office_drawingml::emu_length)
        .unwrap_or(Length::ZERO);
    Some(TextOutline::Solid { width, color })
}

/// Whether F-Office draws the fill of the line along a run's glyphs (`w14:textOutline`) as
/// another one: it does not draw a gradient (`w14:gradFill`), and it draws a solid fill of a
/// color that is not opaque as opaque. An empty fill (`w14:noFill`) draws no line, as Word does.
fn outline_fill_replaced(reader: &mut PartReader, node: NodeId) -> bool {
    let doc = reader.doc;
    if doc.child(node, W14, "noFill").is_some() {
        return false;
    }
    if doc.child(node, W14, "gradFill").is_some() {
        return true;
    }
    doc.child(node, W14, "solidFill")
        .is_some_and(|fill| translucent(reader, fill))
}

/// Reads a `w14:textFill` element and reports whether F-Office cannot draw it natively
/// (`Feature::TextFill`). Supports `w14:noFill`, `w14:solidFill` (with supported modifiers),
/// and opaque linear `w14:gradFill`.
fn text_fill(reader: &mut PartReader, node: NodeId) -> (Option<TextFill>, bool) {
    let doc = reader.doc;
    if doc.child(node, W14, "noFill").is_some() {
        return (Some(TextFill::None), false);
    }
    if let Some(grad) = doc.child(node, W14, "gradFill") {
        return match LinearGradient::read_word2010(doc, grad, reader.drawing_warnings()) {
            Some(gradient) => (Some(TextFill::Gradient(Box::new(gradient))), false),
            None => (None, true),
        };
    }
    if let Some(solid) = doc.child(node, W14, "solidFill") {
        return match DrawColor::read_in(doc, solid, ColorNames::Word2010, reader.drawing_warnings())
        {
            Some(color) => (Some(TextFill::Solid(color)), false),
            None => (None, translucent(reader, solid)),
        };
    }
    (None, false)
}

/// Whether the color of a solid fill `fill` is not opaque: its transparency is above 0.
fn translucent(reader: &mut PartReader, fill: NodeId) -> bool {
    transparency(reader, fill).is_some_and(|transparency| transparency > 0)
}

/// A run property that shows a feature that F-Office does not draw, when its value draws
/// something (**Unsupported run property**). The run keeps it with the part that sets it
/// ([`UnsupportedProperties`]), and the layout warns of its feature
/// ([`UnsupportedProperty::feature`]) once for each paragraph whose text shows it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum UnsupportedProperty {
    /// An outline of the glyphs (`w:outline`).
    Outline,
    /// A shadow of the glyphs (`w:shadow`).
    Shadow,
    /// An emboss (`w:emboss`).
    Emboss,
    /// An imprint (`w:imprint`).
    Imprint,
    /// A double strike (`w:dstrike`), which F-Office draws as a single strike on a target
    /// whose quirk `UnderlineForms` is `AllSingle`.
    DoubleStrike,
    /// A border around the text (`w:bdr`).
    Border,
    /// A width that the text is fitted into (`w:fitText`).
    FitText,
    /// An emphasis mark (`w:em`).
    Emphasis,
    /// Two lines in one or text turned in its line (`w:eastAsianLayout`).
    EastAsianLayout,
    /// A text effect of Word 2010.
    Effect(TextEffect),
    /// A fill of the text (`w14:textFill`), which F-Office draws in the run's color.
    TextFill,
    /// A fill of the line along the outline of the glyphs (`w14:textOutline`).
    TextOutlineFill,
}

impl UnsupportedProperty {
    /// Every unsupported property, which the tests read each of.
    #[cfg(test)]
    pub const ALL: [Self; 16] = [
        Self::Outline,
        Self::Shadow,
        Self::Emboss,
        Self::Imprint,
        Self::DoubleStrike,
        Self::Border,
        Self::FitText,
        Self::Emphasis,
        Self::EastAsianLayout,
        Self::Effect(TextEffect::Glow),
        Self::Effect(TextEffect::Shadow),
        Self::Effect(TextEffect::Reflection),
        Self::Effect(TextEffect::Scene),
        Self::Effect(TextEffect::Depth),
        Self::TextFill,
        Self::TextOutlineFill,
    ];

    /// The feature that the property shows.
    #[must_use]
    pub const fn feature(self) -> Feature {
        match self {
            Self::Outline | Self::Shadow | Self::Emboss | Self::Imprint | Self::Effect(_) => {
                Feature::TextEffect
            }
            Self::DoubleStrike => Feature::DoubleStrike,
            Self::Border => Feature::TextBorder,
            Self::FitText => Feature::FitText,
            Self::Emphasis | Self::EastAsianLayout => Feature::EastAsianLayout,
            Self::TextFill => Feature::TextFill,
            Self::TextOutlineFill => Feature::TextOutlineFill,
        }
    }
}

/// The unsupported properties that the layers of a run's cascade set, each with whether it shows
/// its feature and the part that sets it, in the order of [`UnsupportedProperty`]. A layer that
/// sets a property replaces the value of the layers below it, also to turn it off.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct UnsupportedProperties(Vec<(UnsupportedProperty, SetIn<bool>)>);

impl UnsupportedProperties {
    /// Sets `property` to `shows`, in the place of a value that a layer below set.
    pub(crate) fn set(&mut self, property: UnsupportedProperty, shows: SetIn<bool>) {
        match self.0.binary_search_by_key(&property, |(set, _)| *set) {
            Ok(at) => {
                if let Some((_, value)) = self.0.get_mut(at) {
                    *value = shows;
                }
            }
            Err(at) => self.0.insert(at, (property, shows)),
        }
    }

    /// Leaves the shadow of the run's text (`w14:shadow`) out, as one that F-Office draws.
    pub(crate) fn shadow_drawn(&mut self) {
        let shadow = UnsupportedProperty::Effect(TextEffect::Shadow);
        self.0.retain(|(set, _)| *set != shadow);
    }

    /// Leaves the glow of the run's text (`w14:glow`) out, as one that F-Office draws.
    pub(crate) fn glow_drawn(&mut self) {
        let glow = UnsupportedProperty::Effect(TextEffect::Glow);
        self.0.retain(|(set, _)| *set != glow);
    }

    /// Leaves the reflection of the run's text (`w14:reflection`) out, as one that F-Office draws.
    pub(crate) fn reflection_drawn(&mut self) {
        let reflection = UnsupportedProperty::Effect(TextEffect::Reflection);
        self.0.retain(|(set, _)| *set != reflection);
    }

    /// Leaves drawn legacy WordprocessingML text effects (`w:shadow`, `w:outline`, `w:emboss`,
    /// `w:imprint`) out of the unsupported properties list.
    pub(crate) fn legacy_effects_drawn(&mut self) {
        self.0.retain(|(set, _)| {
            !matches!(
                set,
                UnsupportedProperty::Outline
                    | UnsupportedProperty::Shadow
                    | UnsupportedProperty::Emboss
                    | UnsupportedProperty::Imprint
            )
        });
    }

    /// Overlays the properties that `other` sets on these.
    fn apply(&mut self, other: &Self) {
        for (property, shows) in &other.0 {
            self.set(*property, shows.clone());
        }
    }

    /// The features that the properties show, each with the name of the part that sets the
    /// property, in the order of [`UnsupportedProperty`].
    pub fn shown(&self) -> impl Iterator<Item = (Feature, &std::rc::Rc<f_office_warnings::Name>)> {
        self.0
            .iter()
            .filter(|(_, shows)| shows.value)
            .map(|(property, shows)| (property.feature(), &shows.part))
    }
}

/// A text effect of Word 2010 in a run's properties ([MS-DOCX] 2.6.1), which F-Office does not
/// draw.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum TextEffect {
    /// A glow around the glyphs (`w14:glow`).
    Glow,
    /// A shadow (`w14:shadow`).
    Shadow,
    /// A reflection (`w14:reflection`).
    Reflection,
    /// The camera and the light of a 3-D look (`w14:scene3d`).
    Scene,
    /// The bevels, the extrusion and the contour of a 3-D look (`w14:props3d`).
    Depth,
}

impl TextEffect {
    /// The effect that the element `local` of the `w14` namespace gives, if any.
    fn named(local: &str) -> Option<Self> {
        Some(match local {
            "glow" => Self::Glow,
            "shadow" => Self::Shadow,
            "reflection" => Self::Reflection,
            "scene3d" => Self::Scene,
            "props3d" => Self::Depth,
            _ => return None,
        })
    }

    /// Whether Word draws the text of a run with the effect as filled paths, whatever its
    /// values.
    fn draws_paths(self) -> bool {
        matches!(self, Self::Reflection | Self::Depth)
    }

    /// Whether the effect, with the values of `node`, draws something that can be seen. Each
    /// size, percentage and angle of these types is 0 when it is missing ([MS-DOCX] 2.5:
    /// `CT_Glow`, `CT_Shadow`, `CT_Reflection`, `CT_Bevel`, `CT_Props3D`), so these draw
    /// nothing: a glow of no radius, a shadow or a reflection scaled to 0 on one axis, a
    /// reflection of no opacity at its start and its end, a glow or a shadow of a color whose
    /// transparency is whole, and a 3-D look without a bevel of some width and height, an extrusion or
    /// a contour.
    ///
    /// A scene counts when its camera has a preset other than the flat view from the front
    /// (`orthographicFront`). The camera of text has a preset and nothing else ([MS-DOCX]
    /// 2.6.3.2, `CT_Camera`), so this check reads no turn, unlike the check of a shape's 3-D
    /// look, whose DrawingML camera can turn (`a:rot`). [MS-DOCX] Appendix B, note 51, says
    /// that Word 2010 and later write `orthographicFront` and ignore the preset when they read
    /// it, so this warning is conservative: an extra warning is safer than silently skipping an
    /// effect.
    fn shows(self, reader: &mut PartReader, node: NodeId) -> bool {
        let doc = reader.doc;
        let seen = |reader: &mut PartReader| {
            transparency(reader, node).is_none_or(|transparency| transparency < DRAWING_WHOLE)
        };
        match self {
            Self::Glow => size(reader, node, "rad") > 0 && seen(reader),
            Self::Shadow => scaled(reader, node) && seen(reader),
            Self::Reflection => {
                scaled(reader, node)
                    && (percent(reader, node, "stA") > 0 || percent(reader, node, "endA") > 0)
            }
            Self::Scene => doc.child(node, W14, "camera").is_some_and(|camera| {
                doc.attribute(camera, Some(W14), "prst") != Some("orthographicFront")
            }),
            Self::Depth => {
                let bevel = ["bevelT", "bevelB"]
                    .into_iter()
                    .filter_map(|name| doc.child(node, W14, name))
                    .any(|bevel| size(reader, bevel, "w") > 0 && size(reader, bevel, "h") > 0);
                bevel || size(reader, node, "extrusionH") > 0 || size(reader, node, "contourW") > 0
            }
        }
    }
}

/// The size in EMU of the attribute `name` of a text effect's element `node`
/// (`ST_PositiveCoordinate`), 0 when it is missing or does not read.
fn size(reader: &mut PartReader, node: NodeId, name: &str) -> i64 {
    reader
        .or_missing_in(node, (Some(W14), name), f_office_drawingml::emus)
        .unwrap_or(0)
}

/// The percentage in 1,000ths of a percent of the attribute `name` of a text effect's element
/// `node` (`ST_Percentage`, `ST_PositiveFixedPercentage`), 0 when it is missing or does not
/// read.
fn percent(reader: &mut PartReader, node: NodeId, name: &str) -> i64 {
    reader
        .or_missing_in(
            node,
            (Some(W14), name),
            f_office_drawingml::color::percentage,
        )
        .unwrap_or(0)
}

/// Whether a shadow or a reflection keeps a size on both axes: a scale (`sx`, `sy`) of 0 shrinks
/// it to nothing, and a negative scale flips it.
fn scaled(reader: &mut PartReader, node: NodeId) -> bool {
    percent(reader, node, "sx") != 0 && percent(reader, node, "sy") != 0
}

/// The transparency of the color of a fill or an effect `node`, in 1,000ths of a percent: the
/// value of its color's `w14:alpha`, which Word writes as the share of the color that lets the
/// page show through, unlike DrawingML's `a:alpha`; `None` for a color without one, which is
/// opaque.
fn transparency(reader: &mut PartReader, node: NodeId) -> Option<i64> {
    let doc = reader.doc;
    let alpha = doc
        .child_elements(node)
        .find_map(|color| doc.child(color, W14, "alpha"))?;
    reader.or_missing_in(
        alpha,
        (Some(W14), "val"),
        f_office_drawingml::color::percentage,
    )
}