f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
//! A drawn pie, on a target whose plot rules draw pies: the largest circle centered in its plot
//! area ([`Layout::pie_plot`]), cut into one slice for each point of its first series. The
//! slices start at the first slice angle, clockwise from the top, and go on clockwise in the
//! points' order, each as wide as its value's share of the values' sum. The title and the
//! legend stand as a column chart's; the legend names the points. A 3-D pie is one picture of
//! its plot area ([`PiePicture`]).

use f_office_drawingml::color::{DrawColor, on_white};
use f_office_drawingml::custom::circle_arc;
use f_office_effects::{Angle, Picture, Pie, Scene, Share, Slice};
use f_office_paint::Rgb;
use f_office_paint::{
    Image, ImageColor, ImageFormat, ImageItem, InkConversion, Item, Opacity, PathCommand, Point,
};
use f_office_units::scale::{DEGREE, FULL_TURN, PERCENT, QUARTER_TURN, THOUSANDTHS};
use f_office_units::{Edges, Length};

use super::bars::{SHARE_EXPONENT, SHARE_SCALE};
use super::labels::{
    LabelPoint, apply_point_layout, category_name_at, data_label_props, push_label_lines,
    resolve_point_label, written_plain_text,
};
use super::{DrawnText, layout_edges, path, ten_power};
use crate::chart::{
    Columns, DataLabelPosition, Decimal, LabelFormat, LegendPlace, PercentMode, PieExplosion,
    PieLabelPlace, PieView, PlotPlace, Series, SeriesFill, SeriesLabels, Title,
};
use crate::layout::Layout;
use crate::params::{
    CHART_LINES_UNTITLED_TOP, CHART_PIE_3D_MARGIN, CHART_PIE_3D_PIXELS_PER_INCH,
    CHART_PIE_3D_THICKNESS, CHART_PIE_INNER_END_GAP, CHART_PIE_OUTER_END_ACROSS,
    CHART_PIE_OUTER_END_DOWN, CHART_PIE_OUTER_END_SLIDE, CHART_PIE_OUTER_END_WIDTH,
    CHART_PIE_OUTSIDE_LABEL_SHARE, CHART_PLOT_RIGHT, CHART_TITLE_TOP,
};
use crate::props::RunProps;

impl Layout<'_> {
    /// The items of the pie `chart`, whose first slice starts at `first_angle` degrees and
    /// whose slices take `fills` in the points' order, seen in `view` for a 3-D pie, with its
    /// data labels at `place` and its slice pull-outs `explosion`, and the text it draws, or
    /// `None` when it has a manual layout or no room, or a value below 0, whose slice these
    /// rules do not place. A 3-D pie draws its data labels at the center alone
    /// ([`PiePicture::label_center`]).
    pub(super) fn pie(
        &mut self,
        chart: &Columns,
        (first_angle, view, fills, place): (i64, Option<PieView>, &[DrawColor], PieLabelPlace),
        explosion: &PieExplosion,
        frame: Edges<Length>,
    ) -> Option<(Vec<Item>, DrawnText)> {
        let (plot, legend_plot) = self.pie_plot(chart, frame, view.is_some())?;
        let series = chart.series.first()?;
        let angles = slice_angles(&series.values, first_angle)?;
        let colors = self.slice_colors(fills)?;
        let mut items = Vec::with_capacity(angles.len() * 2 + 2);
        let labels = if let Some(view) = view {
            let shrinks = place.outside() && chart.plot_place == PlotPlace::Automatic;
            let picture = PiePicture::of(
                picture_plot(plot, shrinks)?,
                view,
                &angles,
                &colors,
                &explosion.slices,
            )?;
            items.push(picture.item());
            self.pie_labels(
                chart,
                series,
                (&angles, &explosion.slices, frame),
                |bisector, pull, size, pos| {
                    let eff = pie_place_of(pos).unwrap_or(place);
                    picture.label_box_center(eff, bisector, pull, size)
                },
            )
        } else {
            let (center, base_radius) = circle_of(plot, place.outside())?;
            let radius = exploded_radius(base_radius, explosion.series)?;
            items.extend(pie_slices(
                (center, radius),
                &angles,
                &colors,
                &explosion.slices,
            )?);
            self.pie_labels(
                chart,
                series,
                (&angles, &explosion.slices, frame),
                |bisector, pull, size, pos| {
                    let eff = pie_place_of(pos).unwrap_or(place);
                    let apex = slice_center(center, radius, bisector, pull)?;
                    box_center(eff, (apex, radius), bisector, size)
                },
            )
        };
        let data_labels = labels.map(|labels| items.extend(labels)).is_some();
        let (axes_and_legend, extra) = self.radial_chrome(chart, legend_plot, frame);
        items.extend(extra);
        Some((
            items,
            DrawnText {
                axes_and_legend,
                data_labels,
            },
        ))
    }

    /// The items of the doughnut `chart`, whose first slice starts at `first_angle` degrees and
    /// whose inner hole is `hole_size` percent of the outer diameter (`0` draws a solid circle),
    /// with one concentric ring per series from inside out and centered data labels at each
    /// ring's midpoint. Automatic layouts shrink the outer circle by
    /// [`CHART_PIE_OUTSIDE_LABEL_SHARE`] whenever any series shows data labels; manual layouts
    /// keep their box size while the legend stays beside the automatic plot area.
    pub(super) fn doughnut(
        &mut self,
        chart: &Columns,
        (first_angle, hole_size): (i64, u32),
        frame: Edges<Length>,
    ) -> Option<(Vec<Item>, DrawnText)> {
        let (plot, legend_plot) = self.pie_plot(chart, frame, true)?;
        let shrinks = chart.plot_place == PlotPlace::Automatic
            && chart
                .series
                .iter()
                .any(|series| !matches!(series.labels, SeriesLabels::Hidden));
        let (center, outer) = circle_of(plot, shrinks)?;
        let hole = outer.checked_mul(i64::from(hole_size))?.div_round(PERCENT);
        let band = outer - hole;
        let rings = i64::try_from(chart.series.len()).ok().filter(|&n| n > 0)?;
        let mut items = Vec::with_capacity(chart.categories * chart.series.len() * 2 + 2);
        let mut data_labels = true;
        for (index, series) in chart.series.iter().enumerate() {
            let idx = i64::try_from(index).ok()?;
            let r_in = hole + band.checked_mul(idx)?.div_round(rings);
            let r_out = hole + band.checked_mul(idx + 1)?.div_round(rings);
            let angles = slice_angles(&series.values, first_angle)?;
            let SeriesFill::Points(fills) = &series.fill else {
                return None;
            };
            let colors = self.slice_colors(fills)?;
            items.extend(doughnut_slices((center, r_in, r_out), &angles, &colors)?);
            let zeros = vec![0_u32; angles.len()];
            let r_mid = Length::from_units(r_in.units().midpoint(r_out.units()));
            let drawn = self.pie_labels(
                chart,
                series,
                (&angles, &zeros, frame),
                |bisector, _, _, _| Some(circle_arc(center, r_mid, [bisector, 0])?.0),
            );
            if let Some(drawn) = drawn {
                items.extend(drawn);
            } else {
                data_labels = false;
            }
        }
        let (axes_and_legend, extra) = self.radial_chrome(chart, legend_plot, frame);
        items.extend(extra);
        Some((
            items,
            DrawnText {
                axes_and_legend,
                data_labels,
            },
        ))
    }

    /// Title and legend items for a radial chart (pie or doughnut), plus whether both drew.
    fn radial_chrome(
        &mut self,
        chart: &Columns,
        legend_plot: Edges<Length>,
        frame: Edges<Length>,
    ) -> (bool, Vec<Item>) {
        let mut items = Vec::new();
        let title = chart.title.as_ref().map_or(Some(()), |title| {
            self.chart_title(title, frame)
                .map(|lines| items.extend(lines))
        });
        let legend = chart.legend.map_or(Some(()), |_| {
            self.chart_legend(chart, legend_plot, frame)
                .map(|legend| items.extend(legend))
        });
        (title.is_some() && legend.is_some(), items)
    }

    /// The colors of the fills `fills` on white, or `None` when one does not resolve.
    fn slice_colors(&self, fills: &[DrawColor]) -> Option<Vec<Rgb>> {
        let theme = &self.shaper.theme().shapes;
        fills
            .iter()
            .map(|fill| {
                let (rgb, alpha) = fill.resolve(&theme.colors)?;
                Some(on_white(rgb, alpha))
            })
            .collect()
    }

    /// The data labels `labels` of a pie's `values` on their slices, whose starts and swings
    /// are `angles` and whose pull-outs are `explosions`: none when they are hidden; else each
    /// label's text, at the labels' size and font in a text box with their insets and the face's
    /// single line, stands with the box's center where `box_center` puts it for its slice's
    /// bisector, pull-out, and the box's size, and its baseline the single line's ascent below
    /// the box's top inset. `None` when the labels show more than the values, a label is not
    /// drawn, or a value of 0 has a label, whose place these rules do not know.
    fn pie_labels(
        &mut self,
        chart: &Columns,
        series: &Series,
        (angles, explosions, frame): (&[(i64, i64)], &[u32], Edges<Length>),
        box_center: impl Fn(i64, u32, (Length, Length), DataLabelPosition) -> Option<Point>,
    ) -> Option<Vec<Item>> {
        let series_labels = match &series.labels {
            SeriesLabels::Hidden => return Some(Vec::new()),
            SeriesLabels::Values(labels) => labels,
            SeriesLabels::Other => return None,
        };
        let integer_percents = slice_percents(&series.values, None);
        let series_fmt_percents = match &series_labels.parts.percent {
            PercentMode::Format(fmt) => slice_percents(&series.values, Some(fmt)),
            _ => None,
        };
        let mut items = Vec::with_capacity(series.values.len());
        for (idx, ((value, &(start, swing)), &pull)) in
            series.values.iter().zip(angles).zip(explosions).enumerate()
        {
            let Some(value) = *value else {
                continue;
            };
            if swing == 0 {
                return None;
            }
            let Some((labels, rich_lines, layout)) = resolve_point_label(series_labels, idx) else {
                continue;
            };
            let cached = PrecomputedPercents {
                integer: integer_percents.as_deref(),
                series_fmt: series_fmt_percents.as_deref(),
            };
            let percent = slice_percent_at(
                (&labels.parts.percent, &series_labels.parts.percent),
                (&series.values, idx),
                &cached,
            )
            .ok()?;
            let props = data_label_props(labels);
            let lines = self.lines_of(&props)?;
            let color = self.label_color(labels.fill.as_ref());
            let insets = labels.insets;
            let point = LabelPoint {
                series_name: series.name.as_deref(),
                category_name: category_name_at(chart, idx),
                category_index: idx,
                value,
                percent,
                rich_lines,
            };
            let shaped = self.data_label_lines(&props, labels, &point)?;
            let max_width = shaped.iter().map(|(t, _)| t.width()).max()?;
            let line_count = i64::try_from(shaped.len()).ok()?;
            let room = insets.left + max_width + insets.right;
            let height = insets.top + lines.single_line.checked_mul(line_count)? + insets.bottom;
            let middle = box_center(start + swing / 2, pull, (room, height), labels.position)?;
            let auto_place = (
                middle.x - room.div_toward_zero(2) + insets.left,
                middle.y - height.div_toward_zero(2) + insets.top + lines.single_top,
            );
            let place = apply_point_layout(auto_place, layout, frame, (insets, lines))?;
            push_label_lines(
                &mut items,
                shaped,
                place,
                (max_width, lines.single_line),
                color,
            )?;
        }
        Some(items)
    }
}

/// Maps a point's explicit `DataLabelPosition` onto the radial [`PieLabelPlace`].
const fn pie_place_of(position: DataLabelPosition) -> Option<PieLabelPlace> {
    match position {
        DataLabelPosition::Center => Some(PieLabelPlace::Center),
        DataLabelPosition::InsideEnd => Some(PieLabelPlace::InnerEnd),
        DataLabelPosition::OutsideEnd => Some(PieLabelPlace::OuterEnd),
        _ => None,
    }
}

/// Precomputed percentage tables for one pie/doughnut series.
struct PrecomputedPercents<'a> {
    integer: Option<&'a [Option<String>]>,
    series_fmt: Option<&'a [Option<String>]>,
}

/// Returns the formatted percentage string for slice `idx` under `mode`, reusing precomputed
/// series tables where possible.
fn slice_percent_at(
    (mode, series_mode): (&PercentMode, &PercentMode),
    (values, idx): (&[Option<Decimal>], usize),
    cached: &PrecomputedPercents<'_>,
) -> Result<Option<String>, ()> {
    match mode {
        PercentMode::Hidden => Ok(None),
        PercentMode::Integer => Ok(cached.integer.ok_or(())?.get(idx).ok_or(())?.clone()),
        PercentMode::Format(fmt) => {
            if mode == series_mode
                && let Some(list) = cached.series_fmt
            {
                return Ok(list.get(idx).ok_or(())?.clone());
            }
            let list = slice_percents(values, Some(fmt)).ok_or(())?;
            Ok(list.get(idx).ok_or(())?.clone())
        }
    }
}

/// Formats each pie/doughnut slice's share as a percentage string. When `percent_format` is
/// `None` (default or `"0%"`), uses exact integer percentages with largest-remainder (Hamilton)
/// rounding so non-blank slices sum to 100%. When `percent_format` is `Some(fmt)` (such as
/// `"0.0%"`), formats each slice's exact share independently through `fmt`.
fn slice_percents(
    values: &[Option<Decimal>],
    percent_format: Option<&LabelFormat>,
) -> Option<Vec<Option<String>>> {
    let (scaled, total) = scaled_slice_totals(values)?;
    match percent_format {
        Some(fmt) => slice_formatted_percents(&scaled, total, fmt),
        None => slice_hamilton_percents(&scaled, total),
    }
}

/// Scales non-blank non-negative slice values to a common integer exponent and returns their sum.
fn scaled_slice_totals(values: &[Option<Decimal>]) -> Option<(Vec<Option<i128>>, i128)> {
    let low = values.iter().flatten().map(|value| value.exponent).min()?;
    let scaled: Vec<Option<i128>> = values
        .iter()
        .map(|value| match value {
            None => Some(None),
            Some(value) => i128::from(value.digits)
                .checked_mul(ten_power(value.exponent, low)?)
                .filter(|digits| *digits >= 0)
                .map(Some),
        })
        .collect::<Option<Vec<_>>>()?;
    let total = scaled
        .iter()
        .flatten()
        .try_fold(0_i128, |sum, &value| sum.checked_add(value))?;
    (total > 0).then_some((scaled, total))
}

/// Formats each non-blank slice's exact fractional share independently using `fmt`.
fn slice_formatted_percents(
    scaled: &[Option<i128>],
    total: i128,
    fmt: &LabelFormat,
) -> Option<Vec<Option<String>>> {
    scaled
        .iter()
        .map(|&entry| {
            let Some(value) = entry else {
                return Some(None);
            };
            let rounded = (value.checked_mul(SHARE_SCALE)? + total / 2) / total;
            let share = Decimal {
                digits: i64::try_from(rounded).ok()?,
                exponent: SHARE_EXPONENT,
            };
            Some(Some(written_plain_text(fmt, share)?.0))
        })
        .collect()
}

/// Formats each non-blank slice's share as an integer percentage (`"{n}%"`) using
/// largest-remainder (Hamilton) rounding so the slices sum to 100%.
fn slice_hamilton_percents(scaled: &[Option<i128>], total: i128) -> Option<Vec<Option<String>>> {
    let percent_i128 = i128::from(PERCENT);
    let mut floors: Vec<Option<i128>> = Vec::with_capacity(scaled.len());
    let mut remainders: Vec<(usize, i128)> = Vec::new();
    let mut sum_floors = 0_i128;
    for (idx, &entry) in scaled.iter().enumerate() {
        let Some(value) = entry else {
            floors.push(None);
            continue;
        };
        let numerator = value.checked_mul(percent_i128)?;
        let floor = numerator / total;
        sum_floors = sum_floors.checked_add(floor)?;
        floors.push(Some(floor));
        remainders.push((idx, numerator % total));
    }
    let shortfall = usize::try_from(percent_i128.checked_sub(sum_floors)?).ok()?;
    remainders.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    for &(idx, _) in remainders.iter().take(shortfall) {
        if let Some(slot) = floors.get_mut(idx).and_then(Option::as_mut) {
            *slot += 1;
        }
    }
    Some(
        floors
            .into_iter()
            .map(|slot| slot.map(|pct| format!("{pct}%")))
            .collect(),
    )
}

/// The shrunk radius of a 2-D pie whose base radius is `base` and whose series pull-out is
/// `series` percent: `base / (1 + series / 100)`. Per-point explosions do not shrink the 2-D
/// radius.
pub(super) fn exploded_radius(base: Length, series: u32) -> Option<Length> {
    if series == 0 {
        return Some(base);
    }
    Some(
        base.checked_mul(PERCENT)?
            .div_round(PERCENT.checked_add(i64::from(series))?),
    )
}

/// The apex of a 2-D pie slice pulled out by `explosion` percent of `radius` along `bisector`
/// (in 60,000ths of a degree clockwise from the right), from the pie's `center`.
pub(super) fn slice_center(
    center: Point,
    radius: Length,
    bisector: i64,
    explosion: u32,
) -> Option<Point> {
    if explosion == 0 {
        return Some(center);
    }
    let shift = radius.checked_mul(i64::from(explosion))?.div_round(PERCENT);
    Some(circle_arc(center, shift, [bisector, 0])?.0)
}

/// The paths of the slices of a 2-D pie around `center` of `radius`, whose starts and swings
/// are `angles`, in `colors`, pulled out by `explosions` percent of `radius`; a slice of no
/// swing has none. `None` when a slice's arc does not fit the units.
fn pie_slices(
    (center, radius): (Point, Length),
    angles: &[(i64, i64)],
    colors: &[Rgb],
    explosions: &[u32],
) -> Option<Vec<Item>> {
    let mut items = Vec::with_capacity(angles.len());
    for ((&(start, swing), &color), &explosion) in angles.iter().zip(colors).zip(explosions) {
        if swing == 0 {
            continue;
        }
        let apex = slice_center(center, radius, start + swing / 2, explosion)?;
        let (from, curves) = circle_arc(apex, radius, [start, swing])?;
        let mut commands = vec![PathCommand::MoveTo(apex), PathCommand::LineTo(from)];
        commands.extend(curves);
        commands.push(PathCommand::Close);
        items.push(path(commands, color));
    }
    Some(items)
}

/// The annular slices of one ring of a doughnut around `center` between `inner` and `outer`
/// radii, whose starts and swings are `angles`, in `colors`; a slice of no swing has none.
/// When `inner` is zero, each slice is drawn as a solid wedge from `center`.
fn doughnut_slices(
    (center, inner, outer): (Point, Length, Length),
    angles: &[(i64, i64)],
    colors: &[Rgb],
) -> Option<Vec<Item>> {
    let mut items = Vec::with_capacity(angles.len());
    for (&(start, swing), &color) in angles.iter().zip(colors) {
        if swing == 0 {
            continue;
        }
        items.push(annular_wedge(
            (center, inner, outer),
            (start, swing),
            color,
        )?);
    }
    Some(items)
}

/// One annular sector (or solid pie wedge when `inner == Length::ZERO`, or full-turn ring with
/// opposite-wound cutout when `swing == FULL_TURN`) around `center` in `color`.
fn annular_wedge(
    (center, inner, outer): (Point, Length, Length),
    (start, swing): (i64, i64),
    color: Rgb,
) -> Option<Item> {
    let (outer_from, outer_curves) = circle_arc(center, outer, [start, swing])?;
    if inner <= Length::ZERO {
        let mut commands = vec![PathCommand::MoveTo(center), PathCommand::LineTo(outer_from)];
        commands.extend(outer_curves);
        commands.push(PathCommand::Close);
        return Some(path(commands, color));
    }
    let (inner_end, inner_curves) = circle_arc(center, inner, [start + swing, -swing])?;
    let mut commands = vec![PathCommand::MoveTo(outer_from)];
    commands.extend(outer_curves);
    if swing == FULL_TURN {
        commands.push(PathCommand::Close);
        commands.push(PathCommand::MoveTo(inner_end));
        commands.extend(inner_curves);
        commands.push(PathCommand::Close);
    } else {
        commands.push(PathCommand::LineTo(inner_end));
        commands.extend(inner_curves);
        commands.push(PathCommand::Close);
    }
    Some(path(commands, color))
}

/// The picture of a 3-D pie over its plot area: an image of its scene ([`Scene`]) of
/// [`CHART_PIE_3D_PIXELS_PER_INCH`] across and down, and one pixel more, with the pie
/// [`CHART_PIE_3D_THICKNESS`] of its radius thick and [`CHART_PIE_3D_MARGIN`] at each side.
pub(super) struct PiePicture {
    /// The plot area that the picture covers.
    plot: Edges<Length>,
    /// The picture, whose scene is the pie.
    picture: Picture,
}

impl PiePicture {
    /// The picture of a 3-D pie seen in `view` over the plot area `plot`, whose slices' starts
    /// and swings are `angles`, in `colors`, pulled out by `explosions` percent of the slice
    /// radius. `None` when the plot area has no pixels or the scene's numbers do not fit.
    pub(super) fn of(
        plot: Edges<Length>,
        view: PieView,
        angles: &[(i64, i64)],
        colors: &[Rgb],
        explosions: &[u32],
    ) -> Option<Self> {
        let pixels = |side: Length| {
            let whole = side
                .checked_mul(CHART_PIE_3D_PIXELS_PER_INCH)?
                .div_round(Length::UNITS_PER_INCH);
            u32::try_from(whole.units())
                .ok()
                .filter(|&n| n > 0)?
                .checked_add(1)
        };
        let slices = angles
            .iter()
            .zip(colors)
            .zip(explosions)
            .filter(|(((_, swing), _), _)| *swing != 0)
            .map(|((&(start, swing), color), &explosion)| Slice {
                start: Angle::from_sixty_thousandths(start),
                swing: Angle::from_sixty_thousandths(swing),
                color: [color.r, color.g, color.b],
                explosion,
            })
            .collect();
        let scene = Scene::Pie(Pie {
            tilt: Angle::from_sixty_thousandths(view.tilt.checked_mul(DEGREE)?),
            angle_of_view: Angle::from_sixty_thousandths(view.field_of_view.checked_mul(DEGREE)?),
            thickness: Share::ratio(CHART_PIE_3D_THICKNESS.0, CHART_PIE_3D_THICKNESS.1)?,
            margin: Share::ratio(CHART_PIE_3D_MARGIN.0, CHART_PIE_3D_MARGIN.1)?,
            slices,
        });
        Some(Self {
            plot,
            picture: Picture {
                width: pixels(plot.right - plot.left)?,
                height: pixels(plot.bottom - plot.top)?,
                scene,
            },
        })
    }

    /// The picture's item, an image over the plot area.
    pub(super) fn item(&self) -> Item {
        Item::Image(ImageItem {
            x: self.plot.left,
            y: self.plot.top,
            width: self.plot.right - self.plot.left,
            height: self.plot.bottom - self.plot.top,
            clip: None,
            turn: None,
            image: Image {
                format: ImageFormat::EffectPicture,
                data: self.picture.encode().into(),
                opacity: Opacity::FULL,
                color: ImageColor::Original,
                inks: InkConversion::EmbeddedProfile,
            },
        })
    }

    /// Maps a [`f_office_effects::PicturePoint`] in picture shares into page coordinates inside
    /// `self.plot`.
    fn plot_point(&self, point: f_office_effects::PicturePoint) -> Option<Point> {
        let whole = i64::from(Share::ratio(1, 1)?.hundred_thousandths());
        let at = |start: Length, side: Length, share: Share| {
            Some(
                start
                    + side
                        .checked_mul(i64::from(share.hundred_thousandths()))?
                        .div_round(whole),
            )
        };
        let plot = self.plot;
        Some(Point {
            x: at(plot.left, plot.right - plot.left, point.across)?,
            y: at(plot.top, plot.bottom - plot.top, point.down)?,
        })
    }

    /// Projected point on a slice's top face at `reach` of its radius along `bisector`.
    fn top_point_at(&self, bisector: i64, reach: Share, explosion: u32) -> Option<Point> {
        let point = self.picture.slice_top_point(
            Angle::from_sixty_thousandths(bisector),
            reach,
            explosion,
        )?;
        self.plot_point(point)
    }

    /// The center of the text box of a data label at the center of the slice whose bisector
    /// lies at `bisector` (in 60,000ths of a degree clockwise from the right) and whose pull-out
    /// is `explosion` percent: the point of the slice's top face at half the slice radius on the
    /// bisector, where the picture shows it. `None` when the pie does not fit the picture.
    pub(super) fn label_center(&self, bisector: i64, explosion: u32) -> Option<Point> {
        self.top_point_at(bisector, Share::ratio(1, 2)?, explosion)
    }

    /// The center of the text box of `size` for a 3-D pie data label at `place`:
    /// - `Center`: half-radius on the slice's top face ([`Self::label_center`]).
    /// - `InnerEnd`: inside the slice's top-face rim along the projected bisector ray by
    ///   [`CHART_PIE_INNER_END_GAP`] plus half the box's reach along that ray.
    /// - `OuterEnd`: outside the slice's outer silhouette rim (bottom rim on the front half, top
    ///   rim on the back half) using the 2-D `outer_end` offsets along the projected bisector ray.
    /// - `BestFit`: `None`, whose place these rules do not know.
    pub(super) fn label_box_center(
        &self,
        place: PieLabelPlace,
        bisector: i64,
        explosion: u32,
        size: (Length, Length),
    ) -> Option<Point> {
        match place {
            PieLabelPlace::Center => self.label_center(bisector, explosion),
            PieLabelPlace::InnerEnd => {
                let center = self.top_point_at(bisector, Share::ratio(0, 1)?, explosion)?;
                let rim = self.top_point_at(bisector, Share::ratio(1, 1)?, explosion)?;
                inner_end_along(center, rim, size)
            }
            PieLabelPlace::OuterEnd => {
                let center = self.top_point_at(bisector, Share::ratio(0, 1)?, explosion)?;
                let top_rim = self.top_point_at(bisector, Share::ratio(1, 1)?, explosion)?;
                let sil = self.plot_point(
                    self.picture
                        .slice_rim_point(Angle::from_sixty_thousandths(bisector), explosion)?,
                )?;
                outer_end_along(sil, (top_rim.x - center.x, top_rim.y - center.y), size)
            }
            PieLabelPlace::BestFit => None,
        }
    }
}

/// The plot area of the picture of a 3-D pie in the plot area `plot`: `plot` itself, or when
/// it `shrinks`, for data labels that may stand outside the pie in an automatic layout, a
/// smaller one with the same center, each of whose half sides shrinks as a 2-D pie's radius
/// does ([`inside_labels_radius`]). A manual layout's box keeps its size. `None` when the plot
/// area has no room.
pub(super) fn picture_plot(plot: Edges<Length>, shrinks: bool) -> Option<Edges<Length>> {
    if !shrinks {
        return Some(plot);
    }
    let shrunk = |low: Length, high: Length| {
        let half = (high - low).div_toward_zero(2);
        let middle = low + half;
        let kept = inside_labels_radius(half).filter(|&kept| kept > Length::ZERO)?;
        Some((middle - kept, middle + kept))
    };
    let (left, right) = shrunk(plot.left, plot.right)?;
    let (top, bottom) = shrunk(plot.top, plot.bottom)?;
    Some(Edges {
        left,
        top,
        right,
        bottom,
    })
}

/// The center of the text box of `size` (its width and height) of a pie's data label at
/// `place`, on the slice whose bisector lies at `bisector` (in 60,000ths of a degree clockwise
/// from the right) in the circle around `center` of `radius`: at the center, at half the radius
/// on the bisector; at the inner end, [`inner_end`]; at the outer end, [`outer_end`]. `None` at
/// the best fit, whose place these rules do not know.
pub(super) fn box_center(
    place: PieLabelPlace,
    (center, radius): (Point, Length),
    bisector: i64,
    size: (Length, Length),
) -> Option<Point> {
    match place {
        PieLabelPlace::Center => {
            Some(circle_arc(center, radius.div_toward_zero(2), [bisector, 0])?.0)
        }
        PieLabelPlace::InnerEnd => inner_end((center, radius), bisector, size),
        PieLabelPlace::OuterEnd => outer_end((center, radius), bisector, size),
        PieLabelPlace::BestFit => None,
    }
}

/// The point where the bisector at `bisector` meets the circle around `center` of `radius`,
/// and its offsets across and down from the center.
fn bisector_end(center: Point, radius: Length, bisector: i64) -> Option<(Point, Length, Length)> {
    let (end, _) = circle_arc(center, radius, [bisector, 0])?;
    Some((end, end.x - center.x, end.y - center.y))
}

/// The center of a label's text box of `(width, height)` at the inner end of its slice: on the
/// bisector, so far in that the box's edge meets the bisector [`CHART_PIE_INNER_END_GAP`] of
/// the radius inside the circle.
fn inner_end(
    (center, radius): (Point, Length),
    bisector: i64,
    (width, height): (Length, Length),
) -> Option<Point> {
    let (_, across, down) = bisector_end(center, radius, bisector)?;
    let reach = [(width, across), (height, down)]
        .into_iter()
        .filter(|(_, part)| *part != Length::ZERO)
        .map(|(side, part)| {
            i128::from(side.units()) * i128::from(radius.units())
                / (i128::from(part.units().abs()) * 2)
        })
        .min()?;
    let (gap, whole) = CHART_PIE_INNER_END_GAP;
    let gap = radius.checked_mul(gap)?.div_round(whole);
    let reach = Length::from_units(i64::try_from(reach).ok()?);
    Some(circle_arc(center, radius - gap - reach, [bisector, 0])?.0)
}

/// Inner-end label box center along a projected 3-D pie bisector ray from `center` to `rim`.
fn inner_end_along(center: Point, rim: Point, (width, height): (Length, Length)) -> Option<Point> {
    let scale = i128::from(THOUSANDTHS) * i128::from(THOUSANDTHS);
    let (across, down) = (rim.x - center.x, rim.y - center.y);
    let reach = [(width, across), (height, down)]
        .into_iter()
        .filter(|(_, part)| *part != Length::ZERO)
        .map(|(side, part)| i128::from(side.units()) * scale / (i128::from(part.units().abs()) * 2))
        .min()?;
    let (gap, whole) = CHART_PIE_INNER_END_GAP;
    let gap = i128::from(gap) * scale / i128::from(whole);
    let keep = (scale - gap - reach).max(0);
    let step = |delta: Length| {
        i64::try_from(i128::from(delta.units()) * keep / scale)
            .ok()
            .map(Length::from_units)
    };
    Some(Point {
        x: center.x + step(across)?,
        y: center.y + step(down)?,
    })
}

/// The center of a label's text box of `(width, height)` at the outer end of its slice. Its
/// point lies [`CHART_PIE_OUTER_END_ACROSS`] of the bisector's end's offset across beyond that
/// end, and [`CHART_PIE_OUTER_END_DOWN`] of its offset down. Within 45 degrees of the
/// horizontal the box's near side stands at the point, and its center the tangent of the
/// bisector's angle from the horizontal times half the box's height beyond it down; within 45
/// degrees of the vertical the box's near top or bottom stands at the point, and its center
/// slides across from it as [`outer_end_slide`] says. The box takes
/// [`CHART_PIE_OUTER_END_WIDTH`] of its width.
fn outer_end(
    (center, radius): (Point, Length),
    bisector: i64,
    size: (Length, Length),
) -> Option<Point> {
    let (end, across, down) = bisector_end(center, radius, bisector)?;
    outer_end_along(end, (across, down), size)
}

/// Outer-end label box center beyond `end` along the bisector vector `(across, down)`.
fn outer_end_along(
    end: Point,
    (across, down): (Length, Length),
    (width, height): (Length, Length),
) -> Option<Point> {
    let ((out, whole), (below, of)) = (CHART_PIE_OUTER_END_ACROSS, CHART_PIE_OUTER_END_DOWN);
    let (wide, by) = CHART_PIE_OUTER_END_WIDTH;
    let half_width = width.checked_mul(wide)?.div_round(by * 2);
    let half_height = height.div_toward_zero(2);
    let (ax, ay) = (across.units().abs(), down.units().abs());
    if ax == 0 && ay == 0 {
        return None;
    }
    let (shift_x, shift_y) = if ax >= ay {
        (half_width, half_height.checked_mul(ay)?.div_round(ax))
    } else {
        (outer_end_slide(half_width, ax, ay)?, half_height)
    };
    Some(Point {
        x: end.x
            + across.checked_mul(out)?.div_round(whole)
            + shift_x.checked_mul(across.units().signum())?,
        y: end.y
            + down.checked_mul(below)?.div_round(of)
            + shift_y.checked_mul(down.units().signum())?,
    })
}

/// How far across from its point the center of a label at the outer end stands, within 45
/// degrees of the vertical, whose bisector's end lies `ax` across and `ay` down from the
/// circle's center: [`CHART_PIE_OUTER_END_SLIDE`] times the tangent of the bisector's angle
/// from the vertical, up to 1, of the box's half width `half_width`.
fn outer_end_slide(half_width: Length, ax: i64, ay: i64) -> Option<Length> {
    let lean = ax.checked_mul(CHART_PIE_OUTER_END_SLIDE)?;
    if lean >= ay {
        return Some(half_width);
    }
    Some(half_width.checked_mul(lean)?.div_round(ay))
}

/// The center and the radius of a pie's circle in the plot area `plot`: the largest circle
/// centered in it, or a smaller one when its data labels may stand outside it
/// (`outside_labels`, [`inside_labels_radius`]). `None` when the plot area or the circle has
/// no room.
fn circle_of(plot: Edges<Length>, outside_labels: bool) -> Option<(Point, Length)> {
    let (width, height) = (plot.right - plot.left, plot.bottom - plot.top);
    if width <= Length::ZERO || height <= Length::ZERO {
        return None;
    }
    let center = Point {
        x: plot.left + width.div_toward_zero(2),
        y: plot.top + height.div_toward_zero(2),
    };
    let largest = width.min(height).div_toward_zero(2);
    let radius = if outside_labels {
        inside_labels_radius(largest).filter(|&radius| radius > Length::ZERO)?
    } else {
        largest
    };
    Some((center, radius))
}

/// The radius of a pie whose data labels may stand outside its circle, in a plot area whose
/// largest circle has the radius `largest`: with [`CHART_PLOT_RIGHT`], the share
/// [`CHART_PIE_OUTSIDE_LABEL_SHARE`] of the largest circle's with it.
pub(super) fn inside_labels_radius(largest: Length) -> Option<Length> {
    let (kept, whole) = CHART_PIE_OUTSIDE_LABEL_SHARE;
    let with_edge = (largest + CHART_PLOT_RIGHT)
        .checked_mul(kept)?
        .div_toward_zero(whole);
    Some(with_edge - CHART_PLOT_RIGHT)
}

impl Layout<'_> {
    /// The plot area of a pie or doughnut in `frame`, and the plot area of its automatic layout
    /// ([`Self::automatic_pie_plot`]), beside which its legend stands. When `manual_layout` is
    /// true (3-D pies and doughnuts), a manual layout uses the layout's box, inner or outer alike;
    /// otherwise a manual layout returns `None`.
    pub(super) fn pie_plot(
        &mut self,
        chart: &Columns,
        frame: Edges<Length>,
        manual_layout: bool,
    ) -> Option<(Edges<Length>, Edges<Length>)> {
        let automatic = self.automatic_pie_plot(chart, frame)?;
        let plot = match chart.plot_place {
            PlotPlace::Automatic => automatic,
            PlotPlace::Manual(layout) if manual_layout => layout_edges(frame, layout.edges)?,
            PlotPlace::Manual(_) | PlotPlace::Other => return None,
        };
        Some((plot, automatic))
    }

    /// The plot area of a pie of automatic layout in `frame`: the frame less
    /// [`CHART_PLOT_RIGHT`] at the left and the right and [`CHART_LINES_UNTITLED_TOP`] at the
    /// top and the bottom, less a title's room at the top ([`Self::pie_title_room`]) and the
    /// legend's room on its side, as a column chart's legend takes it. A pie has no axis labels,
    /// so no label's line widens these edges.
    fn automatic_pie_plot(
        &mut self,
        chart: &Columns,
        frame: Edges<Length>,
    ) -> Option<Edges<Length>> {
        let top = match &chart.title {
            Some(title) => self.pie_title_room(title, frame)?,
            None => CHART_LINES_UNTITLED_TOP,
        };
        let mut plot = Edges {
            left: frame.left + CHART_PLOT_RIGHT,
            top: frame.top + top,
            right: frame.right - CHART_PLOT_RIGHT,
            bottom: frame.bottom - CHART_LINES_UNTITLED_TOP,
        };
        let Some(place) = chart.legend else {
            return Some(plot);
        };
        let lines = self.legend_lines(chart)?;
        match place {
            LegendPlace::Bottom => {
                plot.bottom -= self.horizontal_legend_room(chart, lines, frame)?;
            }
            LegendPlace::Top => plot.top += self.horizontal_legend_room(chart, lines, frame)?,
            LegendPlace::Left => plot.left += self.side_legend(chart, lines)?,
            LegendPlace::Right => plot.right -= self.side_legend(chart, lines)?,
        }
        Some(plot)
    }

    /// The room of the title `title` above a pie's plot area: its lines in its own face at its
    /// size and [`CHART_TITLE_TOP`].
    fn pie_title_room(&mut self, title: &Title, frame: Edges<Length>) -> Option<Length> {
        let props = RunProps {
            font_ascii: Some(title.font.clone()),
            font_hansi: Some(title.font.clone()),
            size: Some(title.size),
            ..RunProps::default()
        };
        let line = self.line_of(&props)?;
        Some(line.checked_mul(self.title_line_count(title, frame)?)? + CHART_TITLE_TOP)
    }
}

/// The start and the swing of each point's slice, in 60,000ths of a degree clockwise from the
/// right: the first starts `first_angle` degrees clockwise from the top, each starts where the
/// one before ends, a blank point (`None`) has no swing, and the ends lie at the running sums'
/// shares of a turn, rounded. `None` when a value is below 0, the values sum to 0, or a sum
/// leaves an `i128`.
pub(super) fn slice_angles(
    values: &[Option<Decimal>],
    first_angle: i64,
) -> Option<Vec<(i64, i64)>> {
    let low = values.iter().flatten().map(|value| value.exponent).min()?;
    let scaled = values
        .iter()
        .map(|value| match value {
            None => Some(0_i128),
            Some(value) => i128::from(value.digits)
                .checked_mul(ten_power(value.exponent, low)?)
                .filter(|digits| *digits >= 0),
        })
        .collect::<Option<Vec<_>>>()?;
    let total = scaled
        .iter()
        .try_fold(0_i128, |sum, &value| sum.checked_add(value))?;
    if total == 0 {
        return None;
    }
    let first = first_angle.checked_mul(DEGREE)? - QUARTER_TURN;
    let (mut sum, mut start) = (0_i128, first);
    let mut angles = Vec::with_capacity(scaled.len());
    for value in scaled {
        sum = sum.checked_add(value)?;
        let end = first + i64::try_from(rounded_share(sum, total)?).ok()?;
        angles.push((start, end - start));
        start = end;
    }
    Some(angles)
}

/// `part` รท `whole` of a turn, in 60,000ths of a degree, rounded to the nearest, a half up.
fn rounded_share(part: i128, whole: i128) -> Option<i128> {
    let turns = part.checked_mul(i128::from(FULL_TURN))?.checked_mul(2)?;
    Some((turns / whole + 1) / 2)
}