excelerate 0.16.0

Read, write and recalculate spreadsheets: xlsx, xls, ods, csv, html, and a 518-function formula engine
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
//! Charts: what a chart draws, what it reads, and where it sits.
//!
//!
//! A chart is two parts. The drawing of a sheet holds a frame - the anchor,
//! the name - pointing at `xl/charts/chartN.xml`, and that part holds the
//! chart itself: plots, their series, the axes, the title, the legend. Both
//! halves land in one [`Chart`] on [`crate::model::Worksheet::charts`].
//!
//! **What is modelled and what is carried.** A chart part is mostly about
//! looks: fills, line widths, fonts, label positions, effects, each in its own
//! corner of `DrawingML`. The model names what a program asks of a chart -
//! kind, series and the cells they read, axes and their scale, title, legend -
//! and keeps everything else as the markup it was written in, in slots that
//! say where it stood. A series edited through the model keeps its colour.
//!
//! **How it is written.** A chart the program did not touch goes back byte for
//! byte, whatever the file held beyond the model. One that was changed is
//! rendered from the model and its carried markup; one created in code gets
//! the defaults Excel writes for a new chart. Which is which is decided by
//! comparing the chart with what was read, so there is no dirty flag to
//! forget.
//!
//! **`chartEx`** - waterfall, funnel, treemap, sunburst, histogram, box and
//! whisker, region map - is a different schema from Office 2016 and lands in
//! [`ChartEx`] on [`crate::model::Worksheet::extended_charts`]. It is written
//! the same way, by comparison, but edited in place rather than rendered: its
//! part keeps the formatting the model does not name.

use crate::coordinate::{Col, Row};
use crate::model::DefinedName;

/// A chart on a sheet.
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub struct Chart {
    /// The name the frame carries, which is what the selection pane shows.
    pub name: String,
    /// Where the chart sits on the sheet.
    ///
    /// A chart inside a group of shapes reports the group's anchor, and moving
    /// it is not written: the group positions its members, and taking one out
    /// of it is an edit of the group.
    pub anchor: Anchor,
    /// The title above the plot, when the chart has one of its own.
    pub title: Option<Title>,
    /// Whether the automatic title was switched off. A chart of one series
    /// with no title of its own shows that series' name unless this is set.
    pub auto_title_deleted: bool,
    /// The plots, in drawing order. A combination chart - columns with a line
    /// over them - has more than one.
    pub plots: Vec<Plot>,
    /// The axes the plots refer to by id.
    pub axes: Vec<ChartAxis>,
    /// The legend, when there is one.
    pub legend: Option<Legend>,
    /// The fill and outline of the chart area (`c:chartSpace/c:spPr`);
    /// `None` leaves the look to the application's default.
    pub format: Option<ShapeFormat>,
    /// The fill and outline of the plot area (`c:plotArea/c:spPr`).
    pub plot_format: Option<ShapeFormat>,
    /// Everything the model does not name, where it stood.
    pub markup: ChartMarkup,
    /// The part this chart was read from; `None` for a chart made in code.
    pub origin: Option<ChartOrigin>,
}

impl Chart {
    /// Whether the chart still says what it said when it was read, and so
    /// goes back as the bytes that arrived.
    #[must_use]
    pub fn is_unchanged(&self) -> bool {
        self.origin
            .as_ref()
            .is_some_and(|o| self.same_placement(&o.read) && self.same_content(&o.read))
    }

    /// Takes the chart as it stands for what was read.
    ///
    /// For edits that change the carried bytes and the model the same way -
    /// a row inserted above the data moves both the series in the part and
    /// the series here - so the chart still counts as untouched.
    pub(crate) fn settle(&mut self) {
        if let Some(mut origin) = self.origin.take() {
            origin.read = Box::new(self.clone());
            self.origin = Some(origin);
        }
    }

    /// Whether the frame is where, and what, it was.
    pub(crate) fn same_placement(&self, other: &Self) -> bool {
        self.name == other.name && self.anchor == other.anchor
    }

    /// Whether the chart part would say the same thing.
    pub(crate) fn same_content(&self, other: &Self) -> bool {
        // Destructured so a field added later cannot be forgotten here.
        let Self {
            name: _,
            anchor: _,
            title,
            auto_title_deleted,
            plots,
            axes,
            legend,
            format,
            plot_format,
            markup,
            origin: _,
        } = self;
        *title == other.title
            && *auto_title_deleted == other.auto_title_deleted
            && *plots == other.plots
            && *axes == other.axes
            && *legend == other.legend
            && *format == other.format
            && *plot_format == other.plot_format
            && *markup == other.markup
    }

    /// Every formula the chart reads through, for an edit that rewrites them.
    pub(crate) fn formulas_mut(&mut self) -> Vec<&mut String> {
        let mut out = Vec::new();
        let titles = self
            .title
            .iter_mut()
            .chain(self.axes.iter_mut().filter_map(|a| a.title.as_mut()));
        out.extend(
            titles
                .filter_map(|t| t.text.as_mut())
                .filter_map(ChartText::formula_mut),
        );
        for series in self.plots.iter_mut().flat_map(|p| &mut p.series) {
            out.extend(series.name.as_mut().and_then(ChartText::formula_mut));
            for data in [
                &mut series.categories,
                &mut series.values,
                &mut series.bubble_sizes,
            ] {
                out.extend(data.as_mut().and_then(DataSource::formula_mut));
            }
        }
        out
    }

    /// Every stretch of carried markup, for an edit that rewrites the
    /// references inside it: a data label or a trend line can read a cell too.
    pub(crate) fn markups_mut(&mut self) -> Vec<&mut String> {
        let ChartMarkup {
            before_chart,
            before_plot_area,
            plot_area_layout,
            after_axes,
            after_legend,
            after_chart,
        } = &mut self.markup;
        let mut out = vec![
            before_chart,
            before_plot_area,
            plot_area_layout,
            after_axes,
            after_legend,
            after_chart,
        ];
        out.extend(self.title.as_mut().map(|t| &mut t.markup));
        out.extend(self.legend.as_mut().map(|l| &mut l.markup));
        for axis in &mut self.axes {
            let AxisMarkup {
                gridlines,
                ticks,
                tail,
            } = &mut axis.markup;
            out.extend([gridlines, ticks, tail]);
            out.extend(axis.title.as_mut().map(|t| &mut t.markup));
        }
        for plot in &mut self.plots {
            out.push(&mut plot.markup);
            // A label can show a cell (`c:dLbl/c:tx/c:strRef`), and the
            // point's label keeps its own copy of the element.
            let mut labels: Vec<&mut DataLabels> = plot.labels.iter_mut().collect();
            for series in &mut plot.series {
                labels.extend(series.labels.as_mut());
                let SeriesMarkup {
                    after_format,
                    before_data,
                    after_data,
                } = &mut series.markup;
                out.extend([after_format, before_data, after_data]);
                for data in [
                    &mut series.categories,
                    &mut series.values,
                    &mut series.bubble_sizes,
                ] {
                    if let Some(DataSource::Levels { formula, markup }) = data {
                        out.push(markup);
                        out.extend(formula.as_mut());
                    }
                }
            }
            for labels in labels {
                out.extend(labels.source.as_mut());
                out.extend(labels.points.iter_mut().filter_map(|l| l.source.as_mut()));
            }
        }
        out
    }
}

/// Where the chart came from, so an untouched one can go back as it was.
///
/// Opaque on purpose: nothing in it is a property of the chart.
#[derive(Debug, Clone, PartialEq)]
pub struct ChartOrigin {
    /// The drawing part holding the frame.
    pub(crate) drawing: String,
    /// The chart part.
    pub(crate) part: String,
    /// The chart as it was read.
    pub(crate) read: Box<Chart>,
    /// The attributes of the root element, namespace declarations included:
    /// the carried markup uses whatever prefixes they bind.
    pub(crate) root_attributes: String,
    /// The prefix the part gave the chart namespace, empty for a default
    /// namespace (which is how excelize writes it).
    pub(crate) prefix: String,
    /// Whether the frame sits inside a group of shapes.
    pub(crate) grouped: bool,
}

impl ChartOrigin {
    /// The chart part inside the package.
    #[must_use]
    pub fn part(&self) -> &str {
        &self.part
    }

    /// The drawing part the frame lives in.
    #[must_use]
    pub fn drawing(&self) -> &str {
        &self.drawing
    }
}

/// Where a drawing object sits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Anchor {
    /// Between two cells: each corner is tied to its own.
    TwoCell {
        /// The top left corner.
        from: Marker,
        /// The bottom right corner.
        to: Marker,
        /// What moving or resizing the cells underneath does to the object.
        /// `None` is the format's default, which behaves as
        /// [`EditAs::TwoCell`].
        edit_as: Option<EditAs>,
    },
    /// At a cell, with a size of its own in EMU.
    OneCell {
        /// The top left corner.
        from: Marker,
        /// Width, in EMU (914 400 to the inch).
        width: i64,
        /// Height, in EMU.
        height: i64,
    },
    /// At a point on the sheet, in EMU, whatever the cells do.
    Absolute {
        /// Distance from the left edge of the sheet.
        x: i64,
        /// Distance from the top edge.
        y: i64,
        /// Width.
        width: i64,
        /// Height.
        height: i64,
    },
}

impl Default for Anchor {
    /// Eight columns by fifteen rows from `A1`, the size Excel gives a new
    /// chart.
    fn default() -> Self {
        Self::TwoCell {
            from: Marker::default(),
            to: Marker {
                col: Col::new(8).unwrap_or_default(),
                row: Row::new(15).unwrap_or_default(),
                ..Marker::default()
            },
            edit_as: None,
        }
    }
}

/// A corner of an object: a cell, and how far into it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Marker {
    /// The column.
    pub col: Col,
    /// How far right of the column's left edge, in EMU.
    pub col_offset: i64,
    /// The row.
    pub row: Row,
    /// How far below the row's top edge, in EMU.
    pub row_offset: i64,
}

/// What a two-cell anchor does when the cells under it move.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditAs {
    /// Moves and resizes with the cells.
    TwoCell,
    /// Moves with its top left cell, keeping its size.
    OneCell,
    /// Stays where it is.
    Absolute,
}

impl EditAs {
    /// Reads the `editAs` attribute.
    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "twoCell" => Some(Self::TwoCell),
            "oneCell" => Some(Self::OneCell),
            "absolute" => Some(Self::Absolute),
            _ => None,
        }
    }

    /// The attribute value, as the file spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::TwoCell => "twoCell",
            Self::OneCell => "oneCell",
            Self::Absolute => "absolute",
        }
    }
}

/// Text a chart shows: typed in, or read from a cell.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChartText {
    /// Read from a cell, and the value it had when the file was saved.
    Reference {
        /// The cell, as a formula: `Sheet1!$B$1`.
        formula: String,
        /// What the cell held.
        cache: Option<String>,
    },
    /// Typed into the chart.
    Text {
        /// The words, paragraphs separated by `\n`.
        text: String,
        /// The formatted text it was read from, carried whole: it is used
        /// again as long as it still says `text`, and dropped for plain text
        /// once `text` is changed.
        rich: Option<String>,
    },
}

impl ChartText {
    /// Plain text, with no formatting.
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text {
            text: text.into(),
            rich: None,
        }
    }

    /// The words shown, whichever way they got there.
    #[must_use]
    pub fn shown(&self) -> Option<&str> {
        match self {
            Self::Reference { cache, .. } => cache.as_deref(),
            Self::Text { text, .. } => Some(text),
        }
    }

    fn formula_mut(&mut self) -> Option<&mut String> {
        match self {
            Self::Reference { formula, .. } => Some(formula),
            Self::Text { .. } => None,
        }
    }
}

/// A title over the chart or beside an axis.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Title {
    /// What it says; `None` when Excel makes the text up - a series name over
    /// the chart, nothing beside an axis.
    pub text: Option<ChartText>,
    /// Where it was put by hand; `None` - where Excel puts it.
    pub layout: Option<ManualLayout>,
    /// Overlay, formatting and a layout the model does not read, carried as
    /// written.
    pub markup: String,
}

/// Where a title or a legend was put by hand: `c:manualLayout` with both
/// modes `edge`, the top-left corner as a share of the chart area in
/// 100 000ths. A layout in `factor` mode stays in the markup.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ManualLayout {
    /// Left edge, from the chart area's left.
    pub x: i32,
    /// Top edge, from the chart area's top.
    pub y: i32,
    /// Width, when the layout sets one.
    pub w: Option<i32>,
    /// Height, when the layout sets one.
    pub h: Option<i32>,
}

/// One plot: a chart type and the series drawn that way.
#[derive(Debug, Clone, PartialEq)]
pub struct Plot {
    /// The chart type and what it needs said about itself.
    pub kind: PlotKind,
    /// Whether each point gets its own colour. Excel sets it for pies.
    pub vary_colors: Option<bool>,
    /// The series, in the order the file lists them.
    pub series: Vec<Series>,
    /// Ids of the axes this plot is drawn against, from [`Chart::axes`].
    /// Two for a flat chart, three for a 3-D one; none for a pie.
    pub axis_ids: Vec<u32>,
    /// Data labels for every series of the plot that has none of its own.
    pub labels: Option<DataLabels>,
    /// Lines from each point down to the category axis (`c:dropLines`), on a
    /// line or area plot.
    pub drop_lines: Option<ChartLines>,
    /// A line from the highest value to the lowest at each category
    /// (`c:hiLowLines`), on a stock or line plot.
    pub high_low_lines: Option<ChartLines>,
    /// Bars from the first series to the last at each category
    /// (`c:upDownBars`): the candles of a stock chart with an opening price.
    pub up_down_bars: Option<UpDownBars>,
    /// Whether the series of a line plot show markers (`c:marker` of
    /// `c:lineChart`; no other plot has it). With it on, a series with no
    /// `c:marker` of its own gets automatic ones - Excel's "line with
    /// markers"; its plain "line" also writes it on, and turns each series'
    /// markers off with `symbol none`. `None` when the file does not say.
    pub show_markers: Option<bool>,
    /// What follows - gap width, overlap, hole size, smoothing - carried as
    /// written.
    pub markup: String,
}

impl Plot {
    /// A plot of that kind and nothing else yet.
    #[must_use]
    pub const fn new(kind: PlotKind) -> Self {
        Self {
            kind,
            vary_colors: None,
            series: Vec::new(),
            axis_ids: Vec::new(),
            labels: None,
            drop_lines: None,
            high_low_lines: None,
            up_down_bars: None,
            show_markers: None,
            markup: String::new(),
        }
    }
}

/// Lines a plot draws besides its series (`c:dropLines`, `c:hiLowLines`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ChartLines {
    /// Their colour and width; `None` leaves them to the chart style.
    pub format: Option<ShapeFormat>,
}

/// The bars between the first and the last series of a stock or line plot
/// (`c:upDownBars`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct UpDownBars {
    /// The space between bars, as a percentage of a bar's width (0 to 500);
    /// `None` for the default, 150.
    pub gap_width: Option<u16>,
    /// The fill and outline of a bar where the last series ends above the
    /// first - a day that closed up (`c:upBars`); `None` for the style's.
    pub up: Option<ShapeFormat>,
    /// The same where it ends below (`c:downBars`).
    pub down: Option<ShapeFormat>,
    /// The element as read; `None` for one made in code.
    pub source: Option<String>,
}

/// The chart types of the 2006 schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PlotKind {
    /// Columns or bars.
    Bar {
        /// Upright columns or sideways bars.
        direction: BarDirection,
        /// Side by side or stacked.
        grouping: Grouping,
        /// Drawn in 3-D.
        three_d: bool,
    },
    /// Lines.
    Line {
        /// On their own or stacked.
        grouping: Grouping,
        /// Drawn in 3-D.
        three_d: bool,
    },
    /// Filled areas.
    Area {
        /// On their own or stacked.
        grouping: Grouping,
        /// Drawn in 3-D.
        three_d: bool,
    },
    /// A pie.
    Pie {
        /// Drawn in 3-D.
        three_d: bool,
    },
    /// A pie with a hole.
    Doughnut,
    /// A pie with some slices pulled out into a second pie or a bar.
    OfPie {
        /// A bar rather than a second pie.
        bar: bool,
    },
    /// Points at x and y.
    Scatter(ScatterStyle),
    /// A spider web.
    Radar(RadarStyle),
    /// Points at x and y with a size.
    Bubble,
    /// High, low, close and optionally open.
    Stock,
    /// A surface.
    Surface {
        /// Drawn in 3-D.
        three_d: bool,
        /// Only the wires, no fill.
        wireframe: bool,
    },
}

impl PlotKind {
    /// The chart element that draws this kind of plot: `barChart`,
    /// `pie3DChart` and the rest, as the file names them.
    #[must_use]
    pub const fn element(self) -> &'static str {
        match self {
            Self::Bar { three_d: false, .. } => "barChart",
            Self::Bar { three_d: true, .. } => "bar3DChart",
            Self::Line { three_d: false, .. } => "lineChart",
            Self::Line { three_d: true, .. } => "line3DChart",
            Self::Area { three_d: false, .. } => "areaChart",
            Self::Area { three_d: true, .. } => "area3DChart",
            Self::Pie { three_d: false } => "pieChart",
            Self::Pie { three_d: true } => "pie3DChart",
            Self::Doughnut => "doughnutChart",
            Self::OfPie { .. } => "ofPieChart",
            Self::Scatter(_) => "scatterChart",
            Self::Radar(_) => "radarChart",
            Self::Bubble => "bubbleChart",
            Self::Stock => "stockChart",
            Self::Surface { three_d: false, .. } => "surfaceChart",
            Self::Surface { three_d: true, .. } => "surface3DChart",
        }
    }

    /// Whether the plot is drawn against axes at all.
    #[must_use]
    pub const fn has_axes(self) -> bool {
        !matches!(self, Self::Pie { .. } | Self::Doughnut | Self::OfPie { .. })
    }

    /// Whether the series place their points by x and y values rather than by
    /// category.
    #[must_use]
    pub const fn plots_xy(self) -> bool {
        matches!(self, Self::Scatter(_) | Self::Bubble)
    }
}

/// Which way the bars go.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BarDirection {
    /// Upright: columns.
    #[default]
    Column,
    /// Sideways: bars.
    Bar,
}

/// How the series of a plot are laid out against each other.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Grouping {
    /// Each series on its own, one behind another.
    #[default]
    Standard,
    /// Side by side.
    Clustered,
    /// On top of each other.
    Stacked,
    /// On top of each other, scaled to 100 %.
    PercentStacked,
}

impl Grouping {
    /// Reads the `grouping` value.
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match value {
            "clustered" => Self::Clustered,
            "stacked" => Self::Stacked,
            "percentStacked" => Self::PercentStacked,
            _ => Self::Standard,
        }
    }

    /// The value, as the file spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Standard => "standard",
            Self::Clustered => "clustered",
            Self::Stacked => "stacked",
            Self::PercentStacked => "percentStacked",
        }
    }
}

/// How a scatter plot joins its points.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ScatterStyle {
    /// As the series' own formatting says.
    None,
    /// Straight lines.
    Line,
    /// Straight lines with markers.
    LineMarker,
    /// Markers only.
    #[default]
    Marker,
    /// Smooth lines.
    Smooth,
    /// Smooth lines with markers.
    SmoothMarker,
}

impl ScatterStyle {
    /// Reads the `scatterStyle` value.
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match value {
            "none" => Self::None,
            "line" => Self::Line,
            "lineMarker" => Self::LineMarker,
            "smooth" => Self::Smooth,
            "smoothMarker" => Self::SmoothMarker,
            _ => Self::Marker,
        }
    }

    /// The value, as the file spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Line => "line",
            Self::LineMarker => "lineMarker",
            Self::Marker => "marker",
            Self::Smooth => "smooth",
            Self::SmoothMarker => "smoothMarker",
        }
    }
}

/// How a radar plot draws its series.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RadarStyle {
    /// Lines.
    #[default]
    Standard,
    /// Lines with markers.
    Marker,
    /// Filled.
    Filled,
}

impl RadarStyle {
    /// Reads the `radarStyle` value.
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match value {
            "marker" => Self::Marker,
            "filled" => Self::Filled,
            _ => Self::Standard,
        }
    }

    /// The value, as the file spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Standard => "standard",
            Self::Marker => "marker",
            Self::Filled => "filled",
        }
    }
}

/// One series of a plot.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Series {
    /// Its index, which picks its default colour.
    pub index: u32,
    /// Its place in the drawing order.
    pub order: u32,
    /// The name the legend shows.
    pub name: Option<ChartText>,
    /// The categories along the axis; for a scatter or bubble plot, the x
    /// values.
    pub categories: Option<DataSource>,
    /// The values plotted; for a scatter or bubble plot, the y values.
    pub values: Option<DataSource>,
    /// The size of each bubble, for a bubble plot.
    pub bubble_sizes: Option<DataSource>,
    /// Fill and outline of the series (`c:spPr`); `None` leaves them to the
    /// chart style.
    pub format: Option<ShapeFormat>,
    /// The markers of a line, scatter or radar series (`c:marker`).
    pub marker: Option<SeriesMarker>,
    /// Points formatted apart from the rest (`c:dPt`): a pie gives each slice
    /// its own colour this way.
    pub data_points: Vec<DataPoint>,
    /// The series' data labels (`c:dLbls`), which win over the plot's.
    pub labels: Option<DataLabels>,
    /// Formatting around the data, carried as written.
    pub markup: SeriesMarkup,
}

/// What a series says beyond the model, split where the data sits.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SeriesMarkup {
    /// Between the fill and the marker: `invertIfNegative`,
    /// `pictureOptions`, `explosion`.
    pub after_format: String,
    /// Trend lines and error bars - what sits between the labels and the
    /// data.
    pub before_data: String,
    /// Smoothing, bar shape, extensions - everything after the data.
    pub after_data: String,
}

/// Fill and outline of a series, a point or a label (`c:spPr`).
///
/// The fields are what a program asks; `source` is the element as read, so
/// picture fills, effects, dashes and colour transforms the model does not name
/// survive. It is written back as is while the fields still say what it says;
/// a changed field is written from the model into it, the rest kept.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ShapeFormat {
    /// The fill; `None` when the element does not state one.
    pub fill: Option<Fill>,
    /// The outline (`a:ln`); `None` when there is none.
    pub line: Option<LineFormat>,
    /// The element as read; `None` for one made in code.
    pub source: Option<String>,
}

impl ShapeFormat {
    /// A solid fill of one colour.
    #[must_use]
    pub fn solid(color: ChartColor) -> Self {
        Self {
            fill: Some(Fill::Solid(color)),
            ..Self::default()
        }
    }
}

/// An outline.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LineFormat {
    /// The colour of the stroke; `Some(Fill::None)` hides the line.
    pub fill: Option<Fill>,
    /// The width in EMU (12 700 to the point); `None` for the default.
    pub width: Option<u32>,
}

/// How an area is filled.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fill {
    /// Not filled (`a:noFill`).
    None,
    /// One colour (`a:solidFill`).
    Solid(ChartColor),
    /// Colours blending into each other (`a:gradFill`). A changed gradient
    /// that was read keeps what the model does not name: flip, rotation with
    /// the shape, the tile and the focus of a radial one (`a:fillToRect`).
    Gradient {
        /// The colours and where they sit, in the order the file lists them.
        stops: Vec<GradientStop>,
        /// The direction of a linear gradient (`a:lin ang`), in 60 000ths of
        /// a degree clockwise from left to right: `5400000` runs top to
        /// bottom. `None` for a radial one or when the file does not say.
        angle: Option<u32>,
        /// The shape of a radial gradient (`a:path`); it wins over `angle`
        /// when both are set, the file having room for only one.
        path: Option<GradientPath>,
    },
    /// Two colours in a pattern (`a:pattFill`).
    Pattern {
        /// The pattern, as the file names it: `pct50`, `dkDnDiag`, `smGrid`
        /// and fifty more (`ST_PresetPatternVal`).
        // ponytail: a name rather than an enum of 54; make it one if a
        // program has to tell them apart.
        preset: Option<String>,
        /// The colour of the pattern's lines and dots (`a:fgClr`).
        foreground: Option<ChartColor>,
        /// The colour behind them (`a:bgClr`).
        background: Option<ChartColor>,
    },
    /// A picture, or a colour of a kind the model does not read: kept in
    /// [`ShapeFormat::source`], not described here.
    Other,
}

/// A colour of a gradient and where it sits (`a:gs`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GradientStop {
    /// How far along, in thousandths of a percent: `0` to `100000`.
    pub position: u32,
    /// The colour there.
    pub color: ChartColor,
}

/// The shape a radial gradient spreads in (`a:path`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GradientPath {
    /// Following the shape's outline.
    Shape,
    /// A circle.
    Circle,
    /// A rectangle.
    Rect,
}

impl GradientPath {
    /// Reads the `path` value.
    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "shape" => Self::Shape,
            "circle" => Self::Circle,
            "rect" => Self::Rect,
            _ => return None,
        })
    }

    /// The value, as the file spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Shape => "shape",
            Self::Circle => "circle",
            Self::Rect => "rect",
        }
    }
}

/// A `DrawingML` colour: a value or a theme colour, and what is done to it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChartColor {
    /// The colour before the transforms.
    pub base: ColorBase,
    /// Transforms, applied in order.
    pub transforms: Vec<ColorTransform>,
}

impl ChartColor {
    /// A plain colour, `RRGGBB`.
    #[must_use]
    pub const fn rgb(rgb: u32) -> Self {
        Self {
            base: ColorBase::Rgb(rgb),
            transforms: Vec::new(),
        }
    }

    /// A colour of the theme, by the name the file uses: `accent1`, `tx1`.
    #[must_use]
    pub fn scheme(name: impl Into<String>) -> Self {
        Self {
            base: ColorBase::Scheme(name.into()),
            transforms: Vec::new(),
        }
    }

    /// The colour as `RRGGBB`, the theme colours looked up in `theme` (the
    /// workbook's [`crate::model::Spreadsheet::theme`]) or in Office's default
    /// one. `None` for a name no theme defines, such as the placeholder
    /// `phClr`. Alpha is not applied.
    #[must_use]
    pub fn resolve(&self, theme: Option<&str>) -> Option<u32> {
        let mut rgb = match &self.base {
            ColorBase::Rgb(rgb) => *rgb & 0x00FF_FFFF,
            ColorBase::Scheme(name) => crate::shared::palette::rgb_of(
                &crate::style::Color::Theme {
                    id: scheme_id(name)?,
                    tint: 0,
                },
                theme,
            )?,
        };
        for t in &self.transforms {
            rgb = t.apply(rgb);
        }
        Some(rgb)
    }

    /// The colour as a cell style states one. A theme colour lightened or
    /// darkened the way Excel's palette does it (`lumMod`, with `lumOff` to
    /// lighten) stays a theme colour with a tint; anything else is resolved
    /// against `theme` into RGB.
    pub(crate) fn to_style(&self, theme: Option<&str>) -> Option<crate::style::Color> {
        use crate::style::Color;
        if let ColorBase::Scheme(name) = &self.base
            && let Some(id) = scheme_id(name)
        {
            // Tints are in millionths, the transforms in thousandths of a
            // percent.
            let tint = match self.transforms.as_slice() {
                [] => Some(0),
                [ColorTransform::LumMod(m)] if (0..=100_000).contains(m) => {
                    Some((m - 100_000) * 10)
                }
                [ColorTransform::LumMod(m), ColorTransform::LumOff(o)]
                    if (0..=100_000).contains(o) && m.checked_add(*o) == Some(100_000) =>
                {
                    Some(o * 10)
                }
                _ => None,
            };
            if let Some(tint) = tint {
                return Some(Color::Theme { id, tint });
            }
        }
        self.resolve(theme)
            .map(|rgb| Color::Argb(0xFF00_0000 | rgb))
    }

    /// A cell style's colour as `DrawingML` states it; `None` for
    /// [`crate::style::Color::Auto`], which leaves the colour to the reader.
    #[cfg(feature = "write")]
    pub(crate) fn from_style(color: &crate::style::Color) -> Option<Self> {
        use crate::style::Color;
        match color {
            Color::Theme { id, tint } => {
                let name = *SCHEME_NAMES.get(usize::try_from(*id).ok()?)?;
                let mut color = Self::scheme(name);
                let tint = tint.clamp(&-1_000_000, &1_000_000) / 10;
                if tint < 0 {
                    color
                        .transforms
                        .push(ColorTransform::LumMod(100_000 + tint));
                } else if tint > 0 {
                    color
                        .transforms
                        .push(ColorTransform::LumMod(100_000 - tint));
                    color.transforms.push(ColorTransform::LumOff(tint));
                }
                Some(color)
            }
            Color::Auto => None,
            other => crate::shared::palette::rgb_of(other, None).map(Self::rgb),
        }
    }
}

/// The names a text colour uses for the theme's colours, in the order
/// [`crate::style::Color::Theme`] counts them.
#[cfg(feature = "write")]
const SCHEME_NAMES: [&str; 12] = [
    "bg1", "tx1", "bg2", "tx2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6",
    "hlink", "folHlink",
];

/// Where a theme colour's name sits in [`SCHEME_NAMES`].
fn scheme_id(name: &str) -> Option<u32> {
    Some(match name {
        "lt1" | "bg1" => 0,
        "dk1" | "tx1" => 1,
        "lt2" | "bg2" => 2,
        "dk2" | "tx2" => 3,
        "accent1" => 4,
        "accent2" => 5,
        "accent3" => 6,
        "accent4" => 7,
        "accent5" => 8,
        "accent6" => 9,
        "hlink" => 10,
        "folHlink" => 11,
        _ => return None,
    })
}

/// Where a [`ChartColor`] starts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColorBase {
    /// `a:srgbClr`, or the value a system colour had when saved.
    Rgb(u32),
    /// `a:schemeClr`: a theme colour by name.
    Scheme(String),
}

/// A transform of a [`ChartColor`], in thousandths of a percent as the file
/// writes them: `100000` is 100 %.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorTransform {
    /// Luminance multiplied by this much.
    LumMod(i32),
    /// Luminance raised by this much.
    LumOff(i32),
    /// Mixed with white: this much of the colour is kept.
    Tint(i32),
    /// Mixed with black: this much of the colour is kept.
    Shade(i32),
    /// Opacity.
    Alpha(i32),
}

impl ColorTransform {
    /// Reads a transform element by its local name.
    #[must_use]
    pub fn parse(name: &str, value: i32) -> Option<Self> {
        Some(match name {
            "lumMod" => Self::LumMod(value),
            "lumOff" => Self::LumOff(value),
            "tint" => Self::Tint(value),
            "shade" => Self::Shade(value),
            "alpha" => Self::Alpha(value),
            _ => return None,
        })
    }

    /// The element name and value.
    #[must_use]
    pub const fn parts(self) -> (&'static str, i32) {
        match self {
            Self::LumMod(v) => ("lumMod", v),
            Self::LumOff(v) => ("lumOff", v),
            Self::Tint(v) => ("tint", v),
            Self::Shade(v) => ("shade", v),
            Self::Alpha(v) => ("alpha", v),
        }
    }

    // ponytail: tint and shade mix in sRGB; Office mixes in linear RGB, so a
    // strong tint comes out a little darker here. Gamma-correct if it shows.
    fn apply(self, rgb: u32) -> u32 {
        let (_, v) = self.parts();
        let f = f64::from(v) / 100_000.0;
        match self {
            Self::LumMod(_) => crate::shared::palette::map_lightness(rgb, |l| l * f),
            Self::LumOff(_) => crate::shared::palette::map_lightness(rgb, |l| l + f),
            Self::Tint(_) => map_channels(rgb, |c| c * f + (1.0 - f)),
            Self::Shade(_) => map_channels(rgb, |c| c * f),
            Self::Alpha(_) => rgb,
        }
    }
}

fn map_channels(rgb: u32, f: impl Fn(f64) -> f64) -> u32 {
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "clamped to 0..=255 first"
    )]
    let channel = |shift: u32| {
        let c = f64::from((rgb >> shift) & 0xFF) / 255.0;
        (f(c) * 255.0).round().clamp(0.0, 255.0) as u32
    };
    (channel(16) << 16) | (channel(8) << 8) | channel(0)
}

/// The markers of a series (`c:marker`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SeriesMarker {
    /// The shape; `None` for the chart's default.
    pub symbol: Option<MarkerSymbol>,
    /// The size in points, 2 to 72.
    pub size: Option<u8>,
    /// The marker's own fill and outline (`c:spPr`); `None` leaves them to
    /// the series.
    pub format: Option<ShapeFormat>,
    /// The element as read; `None` for one made in code.
    pub source: Option<String>,
}

/// The shape of a marker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MarkerSymbol {
    /// Whatever the series' index picks.
    Auto,
    /// No marker.
    None,
    /// A circle.
    Circle,
    /// A short horizontal bar.
    Dash,
    /// A diamond.
    Diamond,
    /// A small dot.
    Dot,
    /// A picture.
    Picture,
    /// A plus sign.
    Plus,
    /// A square.
    Square,
    /// A star.
    Star,
    /// A triangle.
    Triangle,
    /// An x.
    X,
}

impl MarkerSymbol {
    /// Reads the `symbol` value.
    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "auto" => Self::Auto,
            "none" => Self::None,
            "circle" => Self::Circle,
            "dash" => Self::Dash,
            "diamond" => Self::Diamond,
            "dot" => Self::Dot,
            "picture" => Self::Picture,
            "plus" => Self::Plus,
            "square" => Self::Square,
            "star" => Self::Star,
            "triangle" => Self::Triangle,
            "x" => Self::X,
            _ => return None,
        })
    }

    /// The value, as the file spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::None => "none",
            Self::Circle => "circle",
            Self::Dash => "dash",
            Self::Diamond => "diamond",
            Self::Dot => "dot",
            Self::Picture => "picture",
            Self::Plus => "plus",
            Self::Square => "square",
            Self::Star => "star",
            Self::Triangle => "triangle",
            Self::X => "x",
        }
    }
}

/// One point of a series formatted apart from the rest (`c:dPt`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DataPoint {
    /// The point's index in the series.
    pub index: u32,
    /// Its fill and outline.
    pub format: Option<ShapeFormat>,
    /// Its own marker (`c:marker`), on a line, scatter or radar series;
    /// `None` leaves it to the series.
    pub marker: Option<SeriesMarker>,
    /// The element as read, which also holds what is not modelled: a pulled-out
    /// slice, 3-D bubble; `None` for one made in code.
    pub source: Option<String>,
}

/// Data labels of a series or a plot (`c:dLbls`).
///
/// Number format, font and fill are not modelled and stay in `source`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "independent switches, one element each in the file"
)]
pub struct DataLabels {
    /// Labels of single points that differ from the rest (`c:dLbl`).
    pub points: Vec<DataLabel>,
    /// Hidden altogether (`c:delete`).
    pub deleted: bool,
    /// Where each label sits relative to its point; `None` for the default.
    pub position: Option<LabelPosition>,
    /// Shows the legend key beside the label.
    pub show_legend_key: bool,
    /// Shows the value.
    pub show_value: bool,
    /// Shows the category.
    pub show_category_name: bool,
    /// Shows the series name.
    pub show_series_name: bool,
    /// Shows the share of the whole, on a pie.
    pub show_percent: bool,
    /// The element as read; `None` for one made in code.
    pub source: Option<String>,
}

/// The label of one point, set apart from the rest (`c:dLbl`).
///
/// Its own text, layout, number format, font and fill are not modelled and
/// stay in `source`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "independent switches, one element each in the file"
)]
pub struct DataLabel {
    /// The point's index in the series.
    pub index: u32,
    /// This point has no label (`c:delete`).
    pub deleted: bool,
    /// Where the label sits relative to its point; `None` for the default.
    pub position: Option<LabelPosition>,
    /// Shows the legend key beside the label.
    pub show_legend_key: bool,
    /// Shows the value.
    pub show_value: bool,
    /// Shows the category.
    pub show_category_name: bool,
    /// Shows the series name.
    pub show_series_name: bool,
    /// Shows the share of the whole, on a pie.
    pub show_percent: bool,
    /// The element as read; `None` for one made in code.
    pub source: Option<String>,
}

/// Where a data label sits (`c:dLblPos`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LabelPosition {
    /// Wherever it fits, on a pie.
    BestFit,
    /// Below the point.
    Bottom,
    /// Centred on it.
    Center,
    /// Inside the bar, at its base.
    InsideBase,
    /// Inside the bar, at its end.
    InsideEnd,
    /// Left of the point.
    Left,
    /// Past the end of the bar or slice.
    OutsideEnd,
    /// Right of the point.
    Right,
    /// Above the point.
    Top,
}

impl LabelPosition {
    /// Reads the `dLblPos` value.
    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "bestFit" => Self::BestFit,
            "b" => Self::Bottom,
            "ctr" => Self::Center,
            "inBase" => Self::InsideBase,
            "inEnd" => Self::InsideEnd,
            "l" => Self::Left,
            "outEnd" => Self::OutsideEnd,
            "r" => Self::Right,
            "t" => Self::Top,
            _ => return None,
        })
    }

    /// The value, as the file spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::BestFit => "bestFit",
            Self::Bottom => "b",
            Self::Center => "ctr",
            Self::InsideBase => "inBase",
            Self::InsideEnd => "inEnd",
            Self::Left => "l",
            Self::OutsideEnd => "outEnd",
            Self::Right => "r",
            Self::Top => "t",
        }
    }
}

/// Where a series gets its numbers or labels.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum DataSource {
    /// Numbers.
    Numbers {
        /// The cells, as a formula; `None` for numbers typed into the chart.
        formula: Option<String>,
        /// The number format the values were shown in.
        format_code: Option<String>,
        /// How many points there are, gaps included.
        count: Option<u32>,
        /// The values when the file was saved, by point index. A missing
        /// index is a gap.
        points: Vec<(u32, f64)>,
    },
    /// Text.
    Strings {
        /// The cells, as a formula; `None` for labels typed into the chart.
        formula: Option<String>,
        /// How many points there are, gaps included.
        count: Option<u32>,
        /// The labels when the file was saved, by point index.
        points: Vec<(u32, String)>,
    },
    /// Categories in several levels - region, then city - carried whole
    /// besides the formula.
    Levels {
        /// The cells, as a formula.
        formula: Option<String>,
        /// The element as written, formula included.
        markup: String,
    },
}

impl DataSource {
    /// Numbers read from cells, with nothing cached: Excel fills the cache in
    /// when it opens the file.
    #[must_use]
    pub fn numbers(formula: impl Into<String>) -> Self {
        Self::Numbers {
            formula: Some(formula.into()),
            format_code: None,
            count: None,
            points: Vec::new(),
        }
    }

    /// Labels read from cells, with nothing cached.
    #[must_use]
    pub fn strings(formula: impl Into<String>) -> Self {
        Self::Strings {
            formula: Some(formula.into()),
            count: None,
            points: Vec::new(),
        }
    }

    /// The cells the data is read from.
    #[must_use]
    pub fn formula(&self) -> Option<&str> {
        match self {
            Self::Numbers { formula, .. }
            | Self::Strings { formula, .. }
            | Self::Levels { formula, .. } => formula.as_deref(),
        }
    }

    /// The same, to rewrite. A multi-level source keeps its formula inside
    /// the carried markup as well, so it is left to that markup's own rewrite.
    fn formula_mut(&mut self) -> Option<&mut String> {
        match self {
            Self::Numbers { formula, .. } | Self::Strings { formula, .. } => formula.as_mut(),
            Self::Levels { .. } => None,
        }
    }
}

/// An axis.
#[derive(Debug, Clone, PartialEq)]
pub struct ChartAxis {
    /// What the axis measures.
    pub kind: AxisKind,
    /// The id plots refer to it by.
    pub id: u32,
    /// The id of the axis this one crosses.
    pub cross_axis: u32,
    /// Which edge of the plot it runs along.
    pub position: AxisPosition,
    /// Hidden: the axis exists for the plot to be drawn against, but is not
    /// shown.
    pub deleted: bool,
    /// Runs from maximum to minimum.
    pub reversed: bool,
    /// Lowest value shown; automatic when `None`.
    pub min: Option<f64>,
    /// Highest value shown; automatic when `None`.
    pub max: Option<f64>,
    /// Base of a logarithmic scale.
    pub log_base: Option<f64>,
    /// The title beside the axis.
    pub title: Option<Title>,
    /// The number format of the labels, and whether it follows the source
    /// cells.
    pub number_format: Option<(String, bool)>,
    /// Formatting, carried as written.
    pub markup: AxisMarkup,
}

impl ChartAxis {
    /// An axis of categories along the bottom, crossing `cross_axis`.
    #[must_use]
    pub fn category(id: u32, cross_axis: u32) -> Self {
        Self::new(AxisKind::Category, id, cross_axis, AxisPosition::Bottom)
    }

    /// An axis of values up the left side, crossing `cross_axis`.
    #[must_use]
    pub fn value(id: u32, cross_axis: u32) -> Self {
        Self::new(AxisKind::Value, id, cross_axis, AxisPosition::Left)
    }

    /// An axis with nothing set beyond what it is and where.
    #[must_use]
    pub fn new(kind: AxisKind, id: u32, cross_axis: u32, position: AxisPosition) -> Self {
        Self {
            kind,
            id,
            cross_axis,
            position,
            deleted: false,
            reversed: false,
            min: None,
            max: None,
            log_base: None,
            title: None,
            number_format: None,
            markup: AxisMarkup::default(),
        }
    }
}

/// What an axis says beyond the model, split where the model's elements sit.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct AxisMarkup {
    /// The major and minor gridlines.
    pub gridlines: String,
    /// Tick marks, label position, line and label formatting.
    pub ticks: String,
    /// Where it crosses, label spacing, units, extensions.
    pub tail: String,
}

/// What an axis measures.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AxisKind {
    /// Categories, spaced evenly.
    Category,
    /// Numbers.
    Value,
    /// Dates, spaced by time.
    Date,
    /// The series, front to back on a 3-D chart.
    Series,
}

impl AxisKind {
    /// The element name.
    #[must_use]
    pub const fn element(self) -> &'static str {
        match self {
            Self::Category => "catAx",
            Self::Value => "valAx",
            Self::Date => "dateAx",
            Self::Series => "serAx",
        }
    }
}

/// An edge of the plot area.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AxisPosition {
    /// Along the bottom.
    #[default]
    Bottom,
    /// Up the left.
    Left,
    /// Up the right.
    Right,
    /// Along the top.
    Top,
}

impl AxisPosition {
    /// Reads the `axPos` value.
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match value {
            "l" => Self::Left,
            "r" => Self::Right,
            "t" => Self::Top,
            _ => Self::Bottom,
        }
    }

    /// The value, as the file spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Bottom => "b",
            Self::Left => "l",
            Self::Right => "r",
            Self::Top => "t",
        }
    }
}

/// A legend.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Legend {
    /// Where it sits; with a `layout` it is only where the plot area makes
    /// room for it.
    pub position: LegendPosition,
    /// Where it was put by hand.
    pub layout: Option<ManualLayout>,
    /// Hidden entries, overlay, formatting and a layout the model does not
    /// read, carried as written.
    pub markup: String,
}

/// Where the legend sits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LegendPosition {
    /// Below the plot.
    Bottom,
    /// Left of it.
    Left,
    /// Right of it.
    #[default]
    Right,
    /// Above it.
    Top,
    /// In the top right corner.
    TopRight,
}

impl LegendPosition {
    /// Reads the `legendPos` value.
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match value {
            "b" => Self::Bottom,
            "l" => Self::Left,
            "t" => Self::Top,
            "tr" => Self::TopRight,
            _ => Self::Right,
        }
    }

    /// The value, as the file spells it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Bottom => "b",
            Self::Left => "l",
            Self::Right => "r",
            Self::Top => "t",
            Self::TopRight => "tr",
        }
    }
}

/// What a chart says beyond the model, split where the model's elements sit.
///
/// Each slot is the markup between two elements the model does name, so a
/// chart rendered from the model puts everything back in the order the schema
/// demands.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ChartMarkup {
    /// Before the chart: the 1904 flag, language, rounded corners, style.
    pub before_chart: String,
    /// Between the title and the plot area: 3-D view, floor and walls.
    pub before_plot_area: String,
    /// The layout of the plot area.
    pub plot_area_layout: String,
    /// After the axes, inside the plot area: data table, fill, extensions.
    pub after_axes: String,
    /// After the legend: visible cells only, blanks, extensions.
    pub after_legend: String,
    /// After the chart: chart area formatting, text, print settings.
    pub after_chart: String,
}

/// A chart of the 2016 schema: waterfall, funnel, treemap and the rest.
///
/// An untouched one goes back as the bytes it came in. A changed one has what
/// the model names rewritten inside its part - the frame's name and anchor, the
/// title, each series' layout, name, visibility and data - and keeps the rest.
/// One made in code gets a part of its own with Excel's defaults.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ChartEx {
    /// The name the frame carries.
    pub name: String,
    /// Where the chart sits on the sheet.
    pub anchor: Anchor,
    /// The chart part inside the package; empty for a chart made in code.
    pub part: String,
    /// The title, when it has one of its own.
    pub title: Option<ChartText>,
    /// The series, each with the data it reads.
    pub series: Vec<ExSeries>,
    /// The legend; `None` when the chart has none.
    pub legend: Option<ExLegend>,
    /// Where it was read from; `None` for a chart made in code.
    pub origin: Option<ChartExOrigin>,
}

impl ChartEx {
    /// A new chart with one series of `layout` reading `dimensions`.
    #[must_use]
    pub fn new(layout: SeriesLayout, dimensions: Vec<Dimension>, anchor: Anchor) -> Self {
        Self {
            anchor,
            series: vec![ExSeries::new(layout, dimensions)],
            ..Self::default()
        }
    }

    /// Whether the chart still says what it said when it was read.
    #[must_use]
    pub fn is_unchanged(&self) -> bool {
        self.origin
            .as_ref()
            .is_some_and(|o| self.same_placement(&o.read) && self.same_content(&o.read))
    }

    /// Whether the frame is where, and what, it was.
    pub(crate) fn same_placement(&self, other: &Self) -> bool {
        self.name == other.name && self.anchor == other.anchor
    }

    /// Whether the chart part would say the same thing.
    pub(crate) fn same_content(&self, other: &Self) -> bool {
        self.title == other.title && self.series == other.series && self.legend == other.legend
    }

    /// Takes the chart as it stands for what was read, for an edit that moved
    /// the bytes and the model the same way.
    pub(crate) fn settle(&mut self) {
        if let Some(mut origin) = self.origin.take() {
            origin.read = Box::new(self.clone());
            self.origin = Some(origin);
        }
    }
}

/// Where a 2016 chart came from, so an untouched one goes back as it was.
///
/// Opaque on purpose: nothing in it is a property of the chart.
#[derive(Debug, Clone, PartialEq)]
pub struct ChartExOrigin {
    /// The drawing part holding the frame.
    pub(crate) drawing: String,
    /// The frame's drawing object id.
    pub(crate) id: u32,
    /// Whether the frame sits inside a group of shapes.
    pub(crate) grouped: bool,
    /// The chart as it was read.
    pub(crate) read: Box<ChartEx>,
}

impl ChartExOrigin {
    /// The drawing part the frame lives in.
    #[must_use]
    pub fn drawing(&self) -> &str {
        &self.drawing
    }
}

/// One series of a [`ChartEx`].
#[derive(Debug, Clone, PartialEq)]
pub struct ExSeries {
    /// How the series is drawn, which is what makes the chart a waterfall or a
    /// funnel.
    pub layout: SeriesLayout,
    /// The name the legend shows.
    pub name: Option<ChartText>,
    /// Hidden from the chart.
    pub hidden: bool,
    /// The data it reads, one dimension per role.
    pub dimensions: Vec<Dimension>,
    /// Points with a look of their own (`cx:dataPt`): a waterfall colours
    /// rises, falls and totals this way.
    pub points: Vec<ExPoint>,
    /// What the data labels show; `None` when there are none.
    pub labels: Option<ExLabels>,
    /// How a histogram sorts values into bins; `None` for other layouts.
    pub binning: Option<Binning>,
    /// The points of a waterfall drawn as totals from the axis rather than
    /// as steps, by point index (`cx:subtotals`).
    pub subtotals: Vec<u32>,
}

impl ExSeries {
    /// A series of `layout` reading `dimensions`, with nothing else set.
    #[must_use]
    pub fn new(layout: SeriesLayout, dimensions: Vec<Dimension>) -> Self {
        Self {
            layout,
            name: None,
            hidden: false,
            dimensions,
            points: Vec::new(),
            labels: None,
            binning: None,
            subtotals: Vec::new(),
        }
    }
}

/// One point of a [`ChartEx`] series with a fill or outline of its own.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExPoint {
    /// The point's index in the series.
    pub index: u32,
    /// Its fill and outline.
    pub format: ShapeFormat,
}

/// The data labels of a [`ChartEx`] series (`cx:dataLabels`).
///
/// Number format, text style, separator and labels of single points are not
/// modelled; a changed one keeps them in its part.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ExLabels {
    /// Where they sit; `None` leaves it to the layout.
    pub position: Option<LabelPosition>,
    /// They show the series name.
    pub series_name: bool,
    /// They show the category.
    pub category_name: bool,
    /// They show the value.
    pub value: bool,
}

/// How a histogram sorts its values into bins (`cx:binning`).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Binning {
    /// A bin holds its left edge and not its right (`intervalClosed="l"`);
    /// Excel's default is the other way round.
    pub closed_left: bool,
    /// Values at or below this go into one bin of their own.
    pub underflow: Option<BinEdge>,
    /// Values above this go into one bin of their own.
    pub overflow: Option<BinEdge>,
    /// How wide or how many the bins are; `None` lets Excel choose.
    pub bins: Option<Bins>,
}

/// Where a histogram's overflow or underflow bin starts.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BinEdge {
    /// Where Excel puts it.
    Auto,
    /// At this value.
    Value(f64),
}

/// The bins of a histogram.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Bins {
    /// Each this wide (`cx:binSize`).
    Width(f64),
    /// This many (`cx:binCount`).
    Count(u32),
}

/// The legend of a [`ChartEx`] (`cx:legend`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ExLegend {
    /// The side it sits on; a 2016 chart has no top-right corner, and
    /// [`LegendPosition::TopRight`] is written as the right side.
    pub position: LegendPosition,
    /// Drawn over the plot rather than beside it.
    pub overlay: bool,
}

/// What a [`ChartEx`] series draws.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SeriesLayout {
    /// Box and whisker.
    BoxWhisker,
    /// Histogram columns.
    ClusteredColumn,
    /// Funnel.
    Funnel,
    /// The cumulative line of a Pareto chart.
    ParetoLine,
    /// Filled map.
    RegionMap,
    /// Sunburst.
    Sunburst,
    /// Treemap.
    Treemap,
    /// Waterfall.
    Waterfall,
    /// A layout newer than this crate.
    Unknown,
}

impl SeriesLayout {
    /// Reads the `layoutId` attribute.
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match value {
            "boxWhisker" => Self::BoxWhisker,
            "clusteredColumn" => Self::ClusteredColumn,
            "funnel" => Self::Funnel,
            "paretoLine" => Self::ParetoLine,
            "regionMap" => Self::RegionMap,
            "sunburst" => Self::Sunburst,
            "treemap" => Self::Treemap,
            "waterfall" => Self::Waterfall,
            _ => Self::Unknown,
        }
    }

    /// The attribute value; `None` for a layout this crate does not know.
    #[must_use]
    pub const fn as_str(self) -> Option<&'static str> {
        Some(match self {
            Self::BoxWhisker => "boxWhisker",
            Self::ClusteredColumn => "clusteredColumn",
            Self::Funnel => "funnel",
            Self::ParetoLine => "paretoLine",
            Self::RegionMap => "regionMap",
            Self::Sunburst => "sunburst",
            Self::Treemap => "treemap",
            Self::Waterfall => "waterfall",
            Self::Unknown => return None,
        })
    }
}

/// One dimension of the data a [`ChartEx`] series reads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dimension {
    /// What the dimension is for.
    pub role: DimensionRole,
    /// Numbers rather than text.
    pub numeric: bool,
    /// The cells, as a formula. Excel writes a hidden defined name here -
    /// `_xlchart.v1.0` - rather than the range: see [`Dimension::reference`].
    pub formula: Option<String>,
    /// The values when the file was saved: one list per level, each by point
    /// index. A hierarchy - a treemap's region and city - has several.
    pub levels: Vec<Vec<(u32, String)>>,
}

impl Dimension {
    /// The range the dimension reads, looking through the hidden name Excel
    /// puts in its place.
    #[must_use]
    pub fn reference<'a>(&'a self, names: &'a [DefinedName]) -> Option<&'a str> {
        let formula = self.formula.as_deref()?;
        Some(
            names
                .iter()
                .find(|n| n.sheet.is_none() && n.name == formula)
                .map_or(formula, |n| n.formula.as_str()),
        )
    }

    /// What the cells it reads show now, by point index - category labels
    /// for a chart to draw from the book rather than from the cached
    /// [`Self::levels`]. `sheet` is the chart's own sheet. See
    /// [`crate::formula::chart::dimension_strings`].
    #[cfg(feature = "formulas")]
    #[must_use]
    pub fn strings(
        &self,
        book: &crate::model::Spreadsheet,
        sheet: usize,
    ) -> Option<Vec<(u32, String)>> {
        crate::formula::chart::dimension_strings(book, sheet, self)
    }
}

/// What a dimension of chart data is for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DimensionRole {
    /// Category labels.
    Categories,
    /// Values.
    Values,
    /// Sizes, as in a treemap.
    Sizes,
    /// X values.
    X,
    /// Y values.
    Y,
    /// Numbers a map colours by.
    ColorValues,
    /// Text a map colours by.
    ColorStrings,
    /// Map region ids.
    EntityIds,
}

impl DimensionRole {
    /// Reads the `type` attribute.
    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        Some(match value {
            "cat" => Self::Categories,
            "val" => Self::Values,
            "size" => Self::Sizes,
            "x" => Self::X,
            "y" => Self::Y,
            "colorVal" => Self::ColorValues,
            "colorStr" => Self::ColorStrings,
            "entityId" => Self::EntityIds,
            _ => return None,
        })
    }

    /// The attribute value.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Categories => "cat",
            Self::Values => "val",
            Self::Sizes => "size",
            Self::X => "x",
            Self::Y => "y",
            Self::ColorValues => "colorVal",
            Self::ColorStrings => "colorStr",
            Self::EntityIds => "entityId",
        }
    }
}