f-office-docx 0.2.2

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
//! The pie and doughnut charts of a chart part (`c:pieChart`, ECMA-376 Part 1, 21.2.2.141;
//! `c:pie3DChart`, 21.2.2.140; `c:doughnutChart`, 21.2.2.50): a radial group as the part writes
//! it, and the drawn case that a target whose plot rules draw pies or doughnuts
//! ([`PlotRules::draws_pies`], [`PlotRules::draws_pies_3d`], [`PlotRules::doughnut_group`]) draws
//! of it.

use f_office_drawingml::color::DrawColor;
use f_office_drawingml::shape::{Geometry, ShapeLook};
use f_office_units::scale::{DEGREE, FULL_TURN, PERCENT, QUARTER_TURN};
use f_office_warnings::{Warned, Warnings};
use f_office_xml::NodeId;

use super::{
    AxisTitles, ChartGroup, ChartModel, ChartReason, ChartSeries, Columns, DataLabelPosition,
    DrawingMlWarning, DrawnLines, ElementLook, FILLS, Flag, Group, LabelMarkup, Look, Part,
    PieLabelPlace, PlotRules, Series, SeriesFill, SetScale, StyleLineMode, StylePalette,
    categories_of, category_names, drawn_legend, drawn_title, plot_place, read_value,
    style_color_for,
};
use crate::ns::{A, C};
use crate::params::{
    CHART_VIEW_DEFAULT_PERSPECTIVE, CHART_VIEW_DEFAULT_TILT, CHART_VIEW_LARGEST_PERSPECTIVE,
};
use crate::reader::PartReader;

/// A pie group (`c:pieChart` or `c:pie3DChart`) as the part writes it.
pub(super) struct PieGroup {
    /// Where the first slice starts, in degrees clockwise from the top: `c:firstSliceAng` of a
    /// 2-D pie, the view's turn of a 3-D pie, 0 when it does not read.
    first_angle: i64,
    /// The view of a 3-D pie, `None` for a 2-D pie.
    view: Option<PieView>,
    /// The series (`c:ser`), in their order; a pie draws the first.
    series: Vec<ChartSeries>,
    /// Whether the group writes that the colors of its points do not vary (`c:varyColors` of
    /// `0` or `false`), so that each slice has its series' color.
    uniform_colors: bool,
    /// The fill that each point of the first series sets for itself.
    point_fills: Vec<PointFill>,
    /// The pull-out of the first series (`c:explosion` on `c:ser`), in percent of the radius,
    /// `0` when it does not read.
    series_explosion: u32,
    /// The own pull-out of each point of the first series (`c:explosion` on `c:dPt`), in percent
    /// of the radius, by its index; a point's own `0` overrides the series' pull-out.
    point_explosions: Vec<(usize, u32)>,
    /// Where the first series' data labels stand.
    label_position: DataLabelPosition,
}

/// The view of a 3-D pie (`c:view3D` of the chart, ECMA-376 Part 1, 21.2.2.228).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PieView {
    /// How far the view looks down onto the pie, in degrees from its side (`c:rotX`), 0 when
    /// it does not read.
    pub(crate) tilt: i64,
    /// The view's field of view, in degrees (`c:perspective`, whose value is twice that
    /// angle), [`CHART_VIEW_DEFAULT_PERSPECTIVE`] when it does not read.
    pub(crate) field_of_view: i64,
}

/// The largest tilt of a view (`ST_RotX`, ECMA-376 Part 1, 21.2.3.38): a quarter turn.
const LARGEST_TILT: i64 = QUARTER_TURN / DEGREE;

impl PieView {
    /// Reads the view `node` of a 3-D pie, or ECMA-376 defaults (`rotX = 15`, `perspective = 30`)
    /// when `c:view3D` is omitted, with its turn (`c:rotY`), 0 when it does not read. When
    /// `c:view3D` is present with `c:rAngAx` on, Word ignores `c:perspective="0"` and uses the
    /// default perspective.
    fn read(reader: &mut PartReader, node: Option<NodeId>) -> (Self, i64) {
        let Some(view) = node else {
            return (
                Self {
                    tilt: CHART_VIEW_DEFAULT_TILT,
                    field_of_view: CHART_VIEW_DEFAULT_PERSPECTIVE / 2,
                },
                0,
            );
        };
        let right_angles = Flag::of(reader.doc, view, "rAngAx").is_on();
        let mut value = |name: &str, largest: i64| {
            read_value(reader, view, name, |v| {
                v.parse::<i64>().ok().filter(|a| (0..=largest).contains(a))
            })
        };
        let tilt = value("rotX", LARGEST_TILT).unwrap_or(0);
        let turn = value("rotY", LARGEST_ANGLE).unwrap_or(0);
        let perspective = if right_angles {
            CHART_VIEW_DEFAULT_PERSPECTIVE
        } else {
            value("perspective", CHART_VIEW_LARGEST_PERSPECTIVE)
                .unwrap_or(CHART_VIEW_DEFAULT_PERSPECTIVE)
        };
        let field_of_view = perspective / 2;
        (
            Self {
                tilt,
                field_of_view,
            },
            turn,
        )
    }
}

/// The fill that a point of a series sets for itself (`c:dPt`).
pub(super) struct PointFill {
    /// The point's index (`c:idx`).
    index: usize,
    /// Its solid fill (`a:solidFill` of its `c:spPr`).
    fill: Look<Option<DrawColor>>,
    /// Whether its properties name a fill of any kind, such as `a:solidFill`, `a:gradFill` or
    /// `a:noFill`; a slice whose point and series name none takes its chart style's color.
    written: bool,
    /// Whether its properties explicitly set `a:noFill`.
    no_fill: bool,
}

/// The largest first slice angle in degrees (`ST_FirstSliceAng`, ECMA-376 Part 1, 21.2.3.15):
/// a full turn.
const LARGEST_ANGLE: i64 = FULL_TURN / DEGREE;

impl PieGroup {
    /// Reads the pie group `node`, whose series are `series` and whose data labels are
    /// `group_labels`; a 3-D pie (`c:pie3DChart`) with its chart's view `view`.
    pub(super) fn read(
        reader: &mut PartReader,
        node: NodeId,
        (series, group_labels): (Vec<NodeId>, Option<NodeId>),
        view: Option<NodeId>,
    ) -> Self {
        let (first_angle, view) = if reader.doc.is(node, C, "pie3DChart") {
            let (view, turn) = PieView::read(reader, view);
            (turn, Some(view))
        } else {
            let first_angle = read_value(reader, node, "firstSliceAng", |v| {
                v.parse::<i64>()
                    .ok()
                    .filter(|a| (0..=LARGEST_ANGLE).contains(a))
            })
            .unwrap_or(0);
            (first_angle, None)
        };
        let points = series
            .first()
            .map_or_else(PiePoints::default, |&ser| points_of(reader, ser));
        let doc = reader.doc;
        let uniform_colors = Flag::of(doc, node, "varyColors") == Flag::Off;
        let label_position = series
            .first()
            .and_then(|&ser| doc.child(ser, C, "dLbls").or(group_labels))
            .map_or(DataLabelPosition::Default, |labels| {
                DataLabelPosition::for_pie(doc, labels)
            });
        let series = series
            .into_iter()
            .map(|ser| {
                ChartSeries::read(reader, (ser, group_labels), |_, props| Some(props), "val")
            })
            .collect();
        Self {
            first_angle,
            view,
            series,
            uniform_colors,
            point_fills: points.fills,
            series_explosion: points.series_explosion,
            point_explosions: points.point_explosions,
            label_position,
        }
    }
}

impl PieGroup {
    /// Whether a target whose plot rules are `rules` draws this pie: a 2-D pie where it draws
    /// pies, a 3-D pie where it draws them, seen from above and with a field of view.
    fn drawn(&self, rules: PlotRules) -> bool {
        match self.view {
            None => rules.draws_pies(),
            Some(view) => rules.draws_pies_3d() && view.tilt > 0,
        }
    }

    /// The style color that a slice without a fill takes, in a chart that takes the style look
    /// (`style_look`): none when the first series names a fill, else by the series' place when
    /// the colors of the points do not vary, and else by the slice's place.
    fn slice_style(&self, palette: Option<StylePalette>) -> SliceStyle {
        let named = self.series.first().is_some_and(|first| first.fill_written);
        match palette {
            None => SliceStyle::Unstyled,
            Some(_) if named => SliceStyle::Unstyled,
            Some(palette) if self.uniform_colors => SliceStyle::BySeries {
                palette,
                index: 0,
                count: self.series.len(),
            },
            Some(palette) => SliceStyle::ByPoint(palette),
        }
    }
}

/// A doughnut group (`c:doughnutChart`, ECMA-376 Part 1, 21.2.2.50) as the part writes it.
pub(super) struct DoughnutGroup {
    /// Where the first slice starts, in degrees clockwise from the top (`c:firstSliceAng`), 0
    /// when it does not read.
    first_angle: i64,
    /// The inner hole diameter as a percentage of the outer diameter (`c:holeSize`), `0` when the
    /// part omits `c:holeSize` (matching Word, which draws no hole when omitted).
    hole_size: u32,
    /// Whether the group writes that the colors of its points do not vary (`c:varyColors` of
    /// `0` or `false`), so that each ring has its series' color.
    uniform_colors: bool,
    /// The series (`c:ser`), in their order from innermost ring to outermost ring.
    series: Vec<DoughnutSeries>,
}

/// One series (ring) of a [`DoughnutGroup`].
struct DoughnutSeries {
    series: ChartSeries,
    points: PiePoints,
    label_position: DataLabelPosition,
}

impl DoughnutGroup {
    /// Reads the doughnut group `node`, whose series are `series` and whose data labels are
    /// `group_labels`.
    pub(super) fn read(
        reader: &mut PartReader,
        node: NodeId,
        (series, group_labels): (Vec<NodeId>, Option<NodeId>),
    ) -> Self {
        let first_angle = read_value(reader, node, "firstSliceAng", |v| {
            v.parse::<i64>()
                .ok()
                .filter(|a| (0..=LARGEST_ANGLE).contains(a))
        })
        .unwrap_or(0);
        let hole_size = read_value(reader, node, "holeSize", |v| {
            f_office_drawingml::chart_percent(v)
                .filter(|&n| (0..PERCENT).contains(&n))
                .and_then(|n| u32::try_from(n).ok())
        })
        .unwrap_or(0);
        let uniform_colors = Flag::of(reader.doc, node, "varyColors") == Flag::Off;
        let series = series
            .into_iter()
            .map(|ser| {
                let points = points_of(reader, ser);
                let label_position = reader
                    .doc
                    .child(ser, C, "dLbls")
                    .or(group_labels)
                    .map_or(DataLabelPosition::Default, |labels| {
                        DataLabelPosition::of(reader.doc, labels)
                    });
                let series =
                    ChartSeries::read(reader, (ser, group_labels), |_, props| Some(props), "val");
                DoughnutSeries {
                    series,
                    points,
                    label_position,
                }
            })
            .collect();
        Self {
            first_angle,
            hole_size,
            uniform_colors,
            series,
        }
    }
}

/// The positions at which a pie draws its data labels.
const PIE_LABEL_POSITIONS: [DataLabelPosition; 3] = [
    DataLabelPosition::Center,
    DataLabelPosition::InsideEnd,
    DataLabelPosition::OutsideEnd,
];

/// The positions at which a doughnut draws its data labels: omitted (`Default`) or `Center`,
/// both centered on each ring's midpoint.
const DOUGHNUT_LABEL_POSITIONS: [DataLabelPosition; 2] =
    [DataLabelPosition::Default, DataLabelPosition::Center];

/// Where the data labels `labels` at `position` stand on a pie, or [`ChartReason::PieLabels`]
/// for a position whose room F-Office does not know.
fn label_place(
    labels: &LabelMarkup,
    position: DataLabelPosition,
) -> Result<PieLabelPlace, ChartReason> {
    if matches!(labels, LabelMarkup::Hidden) {
        return Ok(PieLabelPlace::Center);
    }
    match position {
        DataLabelPosition::Center => Ok(PieLabelPlace::Center),
        DataLabelPosition::InsideEnd => Ok(PieLabelPlace::InnerEnd),
        DataLabelPosition::OutsideEnd => Ok(PieLabelPlace::OuterEnd),
        DataLabelPosition::Default | DataLabelPosition::BestFit => Ok(PieLabelPlace::BestFit),
        DataLabelPosition::InsideBase
        | DataLabelPosition::Top
        | DataLabelPosition::Bottom
        | DataLabelPosition::Left
        | DataLabelPosition::Right
        | DataLabelPosition::Other => Err(ChartReason::PieLabels),
    }
}

/// The point properties read from the first series of a pie: each point's own fill, the series'
/// pull-out, and each point's own pull-out.
#[derive(Default)]
struct PiePoints {
    fills: Vec<PointFill>,
    series_explosion: u32,
    point_explosions: Vec<(usize, u32)>,
}

/// The own fills and pull-outs of the points of the series `ser` by their index, and the series'
/// own pull-out.
fn points_of(reader: &mut PartReader, ser: NodeId) -> PiePoints {
    let doc = reader.doc;
    let series_explosion = explosion_of(reader, ser).unwrap_or(0);
    let mut fills = Vec::new();
    let mut point_explosions = Vec::new();
    for point in doc.child_elements(ser).filter(|&n| doc.is(n, C, "dPt")) {
        let Some(index) = read_value(reader, point, "idx", |v| v.parse::<usize>().ok()) else {
            continue;
        };
        if let Some(explosion) = explosion_of(reader, point) {
            point_explosions.push((index, explosion));
        }
        fills.push(point_fill(doc, point, index));
    }
    PiePoints {
        fills,
        series_explosion,
        point_explosions,
    }
}

/// The own fills of the points (`c:dPt`) of `ser`.
pub(super) fn point_fills_of(reader: &mut PartReader, ser: NodeId) -> Vec<PointFill> {
    points_of(reader, ser).fills
}

/// The own solid fill of the point `point` at `index` (`c:dPt`).
fn point_fill(doc: &f_office_xml::Document, point: NodeId, index: usize) -> PointFill {
    let mut warnings = Warnings::new();
    let props = doc.child(point, C, "spPr");
    let written =
        props.is_some_and(|props| FILLS.iter().any(|name| doc.child(props, A, name).is_some()));
    let fill = props
        .and_then(|props| doc.child(props, A, "solidFill"))
        .and_then(|solid| DrawColor::read(doc, solid, &mut warnings));
    let no_fill = props.is_some_and(|props| doc.child(props, A, "noFill").is_some());
    PointFill {
        index,
        fill: Warned::new(fill, warnings),
        written,
        no_fill,
    }
}

/// The pull-out (`c:explosion`) set on a series or point, in percent of the radius.
fn explosion_of(reader: &mut PartReader, node: NodeId) -> Option<u32> {
    read_value(reader, node, "explosion", |v| v.parse::<u32>().ok())
}

/// The resolved pull-out of each of `count` slices: the series' `series` pull-out, overridden by
/// each point's own entry in `points`.
fn slice_explosions(count: usize, series: u32, points: &[(usize, u32)]) -> Vec<u32> {
    let mut slices = vec![series; count];
    for &(index, value) in points {
        if let Some(slot) = slices.get_mut(index) {
            *slot = value;
        }
    }
    slices
}

/// The part that F-Office draws of a chart whose plot area holds the one pie group of `chart`,
/// on a target whose plot rules `rules` draw pies: its first series' slices, each in its
/// point's own fill, else the series' fill, else the chart style's color ([`SliceStyle`]), and
/// its data labels where they show the values alone at the center, the inner end or the outer
/// end. Pulled-out slices (`c:explosion`) are drawn where `rules` draw them
/// ([`PlotRules::pie_explosion`]). Its data labels stand at a position whose room F-Office knows
/// ([`label_place`]), its first series has a cached value for each point, not all zero, and a
/// fill for each point; its legend and title are as a column chart's, and its chart area without
/// properties takes the style look as a column chart's does. The size of its text is the
/// legend's, or the chart text's without a legend. Any other chart gives the reason of the first
/// condition that it does not meet.
pub(super) fn part(chart: ChartModel, rules: PlotRules) -> Result<Look<Part>, ChartReason> {
    let ChartModel {
        groups,
        legend,
        title,
        plot_layout,
        data_table,
        blanks,
        area,
        text,
        style,
        ..
    } = chart;
    let Some(Group::Pie(pie)) = groups.into_iter().next() else {
        return Err(ChartReason::OtherGroup);
    };
    if !pie.drawn(rules) {
        return Err(ChartReason::OtherGroup);
    }
    let palette = rules
        .draws_style_look()
        .then(|| StylePalette::of(style.map(|s| s.number), true))
        .flatten();
    let style_look = palette.is_some();
    let style = pie.slice_style(palette);
    let first = pie.series.into_iter().next().ok_or(ChartReason::NoSeries)?;
    let label_place = label_place(&first.labels, pie.label_position)?;
    let mut warnings = Warnings::new();
    let values = first.values.drawn((true, blanks), rules)?;
    let slices = slice_explosions(values.len(), pie.series_explosion, &pie.point_explosions);
    let explosion = rules.pie_explosion(pie.series_explosion, slices)?;
    let fills = slice_fills(
        first.fill,
        pie.point_fills,
        (values.len(), style),
        &mut warnings,
    )?;
    let labels = first
        .labels
        .drawn((&PIE_LABEL_POSITIONS, true, rules), &text, &mut warnings);
    let series = vec![Series {
        fill: SeriesFill::Color(fills.first().cloned().ok_or(ChartReason::NoSeries)?),
        values,
        name: first.name,
        labels,
    }];
    let group = ChartGroup::Pie {
        first_angle: pie.first_angle,
        view: pie.view,
        fills,
        labels: label_place,
        explosion,
    };
    radial_part(
        RadialFrame {
            legend,
            title,
            plot_layout,
            data_table: data_table.is_some(),
            area,
            text,
        },
        (series, Some(first.categories), group),
        (style_look, rules),
        warnings,
    )
}

/// The part that F-Office draws of a chart whose plot area holds one doughnut group
/// (`c:doughnutChart`), on a target whose plot rules `rules` draw doughnuts
/// ([`PlotRules::doughnut_group`]). Each series draws one concentric ring from inside out, with
/// its slice fills in [`SeriesFill::Points`], and default or centered data labels on each ring's
/// midpoint. Non-zero slice explosions and non-center data label positions are left out.
pub(super) fn doughnut_part(
    chart: ChartModel,
    rules: PlotRules,
) -> Result<Look<Part>, ChartReason> {
    let ChartModel {
        groups,
        legend,
        title,
        plot_layout,
        data_table,
        blanks,
        area,
        text,
        style,
        ..
    } = chart;
    let Some(Group::Doughnut(doughnut)) = groups.into_iter().next() else {
        return Err(ChartReason::OtherGroup);
    };
    let group = rules.doughnut_group(doughnut.first_angle, doughnut.hole_size)?;
    if doughnut.series.is_empty() {
        return Err(ChartReason::NoSeries);
    }
    let palette = rules
        .draws_style_look()
        .then(|| StylePalette::of(style.map(|s| s.number), true))
        .flatten();
    let style_look = palette.is_some();
    let mut warnings = Warnings::new();
    let (series, first_categories) =
        doughnut_series(doughnut, (blanks, palette, rules), &text, &mut warnings)?;
    radial_part(
        RadialFrame {
            legend,
            title,
            plot_layout,
            data_table: data_table.is_some(),
            area,
            text,
        },
        (series, first_categories, group),
        (style_look, rules),
        warnings,
    )
}

/// Cached categories of a series, as [`category_names`] accepts them.
type CategoryTexts = Option<super::CategoryCache>;

/// Resolves every ring series of `doughnut` into drawn [`Series`] with per-point fills, returning
/// the first series' category names alongside them.
fn doughnut_series(
    doughnut: DoughnutGroup,
    (blanks, palette, rules): (super::BlankPoints, Option<StylePalette>, PlotRules),
    text: &super::ChartText,
    warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<(Vec<Series>, CategoryTexts), ChartReason> {
    let count = doughnut.series.len();
    let uniform = doughnut.uniform_colors;
    let mut first_categories = None;
    let mut drawn = Vec::with_capacity(count);
    for (index, ring) in doughnut.series.into_iter().enumerate() {
        if ring.points.series_explosion > 0
            || ring.points.point_explosions.iter().any(|&(_, e)| e > 0)
        {
            return Err(ChartReason::PieExplosion);
        }
        if !matches!(ring.series.labels, LabelMarkup::Hidden)
            && !DOUGHNUT_LABEL_POSITIONS.contains(&ring.label_position)
        {
            return Err(ChartReason::PieLabels);
        }
        let values = ring.series.values.drawn((true, blanks), rules)?;
        let style = doughnut_slice_style(palette, ring.series.fill_written, uniform, index, count);
        let fills = slice_fills(
            ring.series.fill,
            ring.points.fills,
            (values.len(), style),
            warnings,
        )?;
        let labels =
            ring.series
                .labels
                .drawn((&DOUGHNUT_LABEL_POSITIONS, true, rules), text, warnings);
        if index == 0 {
            first_categories = Some(ring.series.categories);
        }
        drawn.push(Series {
            fill: SeriesFill::Points(fills),
            values,
            name: ring.series.name,
            labels,
        });
    }
    Ok((drawn, first_categories))
}

/// Style-color assignment for one ring of a doughnut group.
const fn doughnut_slice_style(
    palette: Option<StylePalette>,
    fill_written: bool,
    uniform: bool,
    index: usize,
    count: usize,
) -> SliceStyle {
    match palette {
        None => SliceStyle::Unstyled,
        Some(_) if fill_written => SliceStyle::Unstyled,
        Some(palette) if uniform => SliceStyle::BySeries {
            palette,
            index,
            count,
        },
        Some(palette) => SliceStyle::ByPoint(palette),
    }
}

/// Frame fields shared when building a drawn [`Part`] for a pie or doughnut chart.
struct RadialFrame {
    legend: Option<super::Legend>,
    title: super::TitleState,
    plot_layout: Option<super::ManualLayout>,
    data_table: bool,
    area: ElementLook,
    text: super::ChartText,
}

/// Builds the drawn [`Part`] for a radial chart (pie or doughnut) once its `series` and `group`
/// have been resolved.
fn radial_part(
    frame: RadialFrame,
    (series, first_categories, group): (Vec<Series>, CategoryTexts, ChartGroup),
    (style_look, rules): (bool, PlotRules),
    mut warnings: Warnings<DrawingMlWarning>,
) -> Result<Look<Part>, ChartReason> {
    let categories = categories_of(&series, frame.data_table)?;
    let legend = drawn_legend(frame.legend, &frame.text)?;
    let label_size = legend.size;
    let title = drawn_title(frame.title, rules, &frame.text, &mut warnings)?;
    let plot_place = plot_place(frame.plot_layout.as_ref());
    let line_mode = if style_look {
        StyleLineMode::Tinted
    } else {
        StyleLineMode::None
    };
    let lines = DrawnLines::of(
        frame.area,
        (ElementLook::none(), None),
        (None, ElementLook::none(), None),
        (false, line_mode),
        &mut warnings,
    );
    warnings.extend(legend.fill.warnings, std::convert::identity);
    let none = || ShapeLook::plain(Geometry::Line, None, None);
    let part = Part {
        area: lines.area,
        columns: Columns {
            series,
            categories,
            group,
            title,
            legend: legend.place,
            legend_box: legend.layout,
            label_size,
            legend_size: label_size,
            value_label_size: label_size,
            font: legend.font.clone(),
            gridlines: None,
            axis: none(),
            value_axis: none(),
            ticks: lines.ticks,
            plot_place,
            scale: SetScale::default(),
            category_crossing: Some(super::CategoryCrossing::AutoZero),
            axis_titles: AxisTitles::NONE,
            value_format: None,
            category_names: category_names(first_categories, None, categories, rules),
            value_label_fill: None,
            category_label_fill: None,
            legend_font: legend.font,
            legend_fill: legend.fill.value,
            legend_text: legend.text,
            other_labels: false,
            axis_forms: super::AxisForms::default(),
            secondary_axis: None,
            data_table: None,
        },
    };
    Ok(Warned::new(part, warnings))
}

/// Which color of the chart's style a slice takes when neither its point nor its series names a
/// fill.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SliceStyle {
    /// None: the target does not draw the style look, the chart names an unsupported chart style,
    /// or the series names a fill.
    Unstyled,
    /// The style's color of the slice's place among the points, as the style colors the series
    /// of a column group: the colors of the points vary (`c:varyColors` on or not written).
    ByPoint(StylePalette),
    /// The style's color of the series' place `index` in a group of `count` series: the colors of
    /// the points do not vary.
    BySeries {
        palette: StylePalette,
        index: usize,
        count: usize,
    },
}

impl SliceStyle {
    /// The color of slice `index` of `count` slices, [`ChartReason::SeriesFill`] when the slice
    /// takes no style color, or [`ChartReason::StyleColors`] when the style's color of its place
    /// is not known.
    fn color(self, index: usize, count: usize) -> Result<DrawColor, ChartReason> {
        let color = match self {
            Self::Unstyled => return Err(ChartReason::SeriesFill),
            Self::ByPoint(palette) => style_color_for(palette, index, count),
            Self::BySeries {
                palette,
                index: series,
                count: total,
            } => style_color_for(palette, series, total),
        };
        color.ok_or(ChartReason::StyleColors)
    }
}

/// The fill of each of `count` slices: its point's own solid fill, else the series' fill `own`,
/// else, when the point names no fill, the color that `style` gives it. The fills that F-Office
/// draws add their warnings to `warnings`; a slice without a fill gives the reason of
/// [`SliceStyle::color`], or [`ChartReason::SeriesFill`] when its point names another fill.
pub(super) fn slice_fills(
    own: Look<Option<DrawColor>>,
    mut point_fills: Vec<PointFill>,
    (count, style): (usize, SliceStyle),
    warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<Vec<DrawColor>, ChartReason> {
    let mut series_warnings = Some(own.warnings);
    (0..count)
        .map(|index| {
            let written = point_fills.iter().any(|p| p.index == index && p.written);
            let point = point_fills
                .iter()
                .position(|p| p.index == index && p.fill.value.is_some())
                .map(|at| point_fills.swap_remove(at).fill);
            let look = point.unwrap_or_else(|| {
                Warned::new(
                    own.value.clone(),
                    series_warnings.take().unwrap_or_default(),
                )
            });
            warnings.extend(look.warnings, std::convert::identity);
            match look.value {
                Some(fill) => Ok(fill),
                None if written => Err(ChartReason::SeriesFill),
                None => style.color(index, count),
            }
        })
        .collect()
}

/// Whether `point_fills` carries at least one drawn solid/`noFill` override within `0..count`
/// (or covers every point in `0..count` when `require_all` is true).
pub(super) fn has_bar_point_override(
    point_fills: &[PointFill],
    count: usize,
    require_all: bool,
) -> bool {
    let drawn = |p: &PointFill| p.fill.value.is_some() || p.no_fill;
    if require_all {
        count > 0 && (0..count).all(|i| point_fills.iter().any(|p| p.index == i && drawn(p)))
    } else {
        point_fills.iter().any(|p| p.index < count && drawn(p))
    }
}

/// Resolves per-point `c:dPt` fills for a bar/column series of `count` points with base solid
/// fill `own` (or `base_no_fill`), returning `SeriesFill::Points` for a single-series bar chart
/// when every point has a solid color (so its legend lists categories), or
/// `SeriesFill::BarPoints` otherwise.
pub(super) fn resolve_bar_point_fills(
    own: Look<Option<DrawColor>>,
    base_no_fill: bool,
    mut point_fills: Vec<PointFill>,
    (count, single_series): (usize, bool),
    warnings: &mut Warnings<DrawingMlWarning>,
) -> Result<SeriesFill, ChartReason> {
    warnings.extend(own.warnings, std::convert::identity);
    let base = own.value;
    let mut resolved = Vec::with_capacity(count);
    let fallback = |base: &Option<DrawColor>| match (base, base_no_fill) {
        (Some(c), _) => Ok(Some(c.clone())),
        (None, true) => Ok(None),
        (None, false) => Err(ChartReason::SeriesFill),
    };
    for index in 0..count {
        let point = point_fills
            .iter()
            .position(|p| p.index == index)
            .map(|at| point_fills.swap_remove(at));
        let color = match point {
            Some(p) => {
                warnings.extend(p.fill.warnings, std::convert::identity);
                match p.fill.value {
                    Some(c) => Some(c),
                    None if p.no_fill => None,
                    None => fallback(&base)?,
                }
            }
            None => fallback(&base)?,
        };
        resolved.push(color);
    }
    if single_series && resolved.iter().all(Option::is_some) {
        Ok(SeriesFill::Points(resolved.into_iter().flatten().collect()))
    } else {
        Ok(SeriesFill::BarPoints {
            base,
            points: resolved,
        })
    }
}