f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! 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};
use f_office_units::{Edges, Length};

use super::labels::data_label_props;
use super::{DrawnText, layout_edges, path, ten_power};
use crate::chart::{
    Columns, Decimal, LegendPlace, PieExplosion, PieLabelPlace, PieView, PlotPlace, 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(
                &series.labels,
                &series.values,
                &angles,
                &explosion.slices,
                |bisector, pull, _| {
                    (place == PieLabelPlace::Center)
                        .then(|| picture.label_center(bisector, pull))
                        .flatten()
                },
            )
        } 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(
                &series.labels,
                &series.values,
                &angles,
                &explosion.slices,
                |bisector, pull, size| {
                    let apex = slice_center(center, radius, bisector, pull)?;
                    box_center(place, (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(
                &series.labels,
                &series.values,
                &angles,
                &zeros,
                |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,
        labels: &SeriesLabels,
        values: &[Option<Decimal>],
        angles: &[(i64, i64)],
        explosions: &[u32],
        box_center: impl Fn(i64, u32, (Length, Length)) -> Option<Point>,
    ) -> Option<Vec<Item>> {
        let labels = match labels {
            SeriesLabels::Hidden => return Some(Vec::new()),
            SeriesLabels::Values(labels) => labels,
            SeriesLabels::Other => return None,
        };
        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 height = insets.top + lines.single_line + insets.bottom;
        let mut items = Vec::with_capacity(values.len());
        for ((value, &(start, swing)), &pull) in values.iter().zip(angles).zip(explosions) {
            let Some(value) = *value else {
                continue;
            };
            if swing == 0 {
                return None;
            }
            let (text, own) = self.written_text(&props, (&labels.format, value))?;
            let room = insets.left + text.width() + insets.right;
            let middle = box_center(start + swing / 2, pull, (room, height))?;
            let x = middle.x - room.div_toward_zero(2) + insets.left;
            let baseline = middle.y - height.div_toward_zero(2) + insets.top + lines.single_top;
            items.push(text.item(x, baseline, own.unwrap_or(color))?);
        }
        Some(items)
    }
}

/// 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,
            },
        })
    }

    /// 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> {
        let point = self.picture.slice_top_point(
            Angle::from_sixty_thousandths(bisector),
            Share::ratio(1, 2)?,
            explosion,
        )?;
        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)?,
        })
    }
}

/// 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)
}

/// 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,
    (width, height): (Length, Length),
) -> Option<Point> {
    let (end, across, down) = bisector_end(center, radius, bisector)?;
    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());
    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 -= lines.legend_room()?,
            LegendPlace::Top => plot.top += lines.legend_room()?,
            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)
}