f-office-docx 0.2.4

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
//! The data labels of a drawn chart's bars where the target's quirk `ChartDataLabels` is
//! `OuterEnd`, and the labels of its axes where the target's quirk `ChartPlotArea` is
//! `FontLines`:
//! the value labels, whose width at the label size ends at one place before the plot area and
//! which stand at their values, and the category labels, each centered by that width in its
//! category width below the plot area. The glyphs of a label step by their advances at the
//! label size in the markup and are drawn at the size on the device.

use f_office_drawingml::color::{DrawColor, on_white};
use f_office_fonts::FontId;
use f_office_paint::{Glyph, GlyphRun, Item, Rgb};
use f_office_units::{Edges, Length};

use super::bars::{BarSpans, stacked_line_values};
use super::{
    Across, BarDirection, Clusters, LabelLines, ONE, ValueAxis, chart_props, marker_size, share,
};
use crate::chart::{
    Columns, DataLabelPosition, DataLabelText, Decimal, LabelFormat, LabelPiece, LineLook,
    PointLabelLayout, PointLabelOverride, SecondaryValueAxis, SeriesLabels,
};
use crate::layout::Layout;
use crate::params::{CHART_DATA_LABEL_GAP, CHART_LINE_DATA_LABEL_MARKER_MIN};
use crate::props::RunProps;

impl Layout<'_> {
    /// The labels of the chart's value axis unless it is deleted and of the axis across
    /// (`across`): the category labels below `plot.bottom` (when the category axis crosses at the
    /// value axis' lowest value or the labels stand low) or below `crossing` inside the plot area
    /// (when the category axis crosses inside and its labels stand next to it), or a scatter
    /// chart's x labels ([`Self::x_labels`]); and whether they are all the labels of the two axes.
    pub(super) fn axis_labels(
        &mut self,
        chart: &Columns,
        (axis, secondary, across): (&ValueAxis, Option<&ValueAxis>, Across<'_>),
        (plot, crossing, frame): (Edges<Length>, Length, Edges<Length>),
    ) -> (Vec<Item>, bool) {
        let (Some(lines), Some(value_lines)) = (self.label_lines(chart), self.value_lines(chart))
        else {
            return (Vec::new(), false);
        };
        let (mut items, mut all) = self.shown_value_labels(chart, axis, plot, value_lines);
        if let (Some(sec), Some(sec_axis)) = (chart.secondary_axis.as_deref(), secondary) {
            let (sec_items, sec_all) =
                self.shown_secondary_value_labels(chart, sec, sec_axis, plot);
            items.extend(sec_items);
            all &= sec_all;
        }
        if chart.axis_forms.category_hidden || chart.data_table.is_some() {
            return (items, all);
        }
        if let Across::Values(x_axis, _) = across {
            let general = LabelFormat::all_digits();
            let x_labels = (axis.crossing == axis.low)
                .then(|| self.x_labels(chart, (&x_axis, &general, chart.label_size), plot, lines))
                .flatten();
            all &= x_labels.is_some();
            items.extend(x_labels.into_iter().flatten());
        } else {
            // A chart without cached category names shows numbers, which these rules do not
            // draw.
            let anchor = if axis.crossing == axis.low || chart.axis_forms.low_labels {
                plot.bottom
            } else {
                crossing
            };
            let categories = self.category_labels(chart, (plot, anchor, frame), lines);
            all &= categories.is_some();
            items.extend(categories.into_iter().flatten());
        }
        (items, all)
    }

    /// The value labels ([`Self::value_labels`]) and whether each label of the axis has one,
    /// or none for a deleted value axis, which draws no labels.
    fn shown_value_labels(
        &mut self,
        chart: &Columns,
        axis: &ValueAxis,
        plot: Edges<Length>,
        lines: LabelLines,
    ) -> (Vec<Item>, bool) {
        if chart.axis_forms.value_deleted {
            return (Vec::new(), true);
        }
        let labels = self.value_labels(chart, axis, plot, lines);
        let all = labels.len() == axis.labels().count();
        (labels, all)
    }

    /// Left-aligned labels of a combination chart's secondary right value axis, starting one label
    /// gap right of `plot.right`.
    fn shown_secondary_value_labels(
        &mut self,
        chart: &Columns,
        sec: &SecondaryValueAxis,
        axis: &ValueAxis,
        plot: Edges<Length>,
    ) -> (Vec<Item>, bool) {
        if sec.labels_hidden {
            return (Vec::new(), true);
        }
        let props = chart_props(chart, sec.label_size);
        let Some(lines) = self.lines_of(&props) else {
            return (Vec::new(), false);
        };
        let (Some(gap), Some(down)) = (lines.label_gap(), lines.value_baseline()) else {
            return (Vec::new(), false);
        };
        let color = self.label_color(sec.label_fill.as_ref());
        let x = plot.right + gap;
        let labels: Vec<Item> = axis
            .labels()
            .filter_map(|value| {
                let (shaped, own) = self.written_text(&props, (&sec.format, value))?;
                let y = axis.along((plot.bottom, plot.top), value)?;
                shaped.item(x, y + down, own.unwrap_or(color))
            })
            .collect();
        let all = labels.len() == axis.labels().count();
        (labels, all)
    }

    /// One label for each value of the axis' labels, in the chart's label format
    /// ([`Columns::value_format`]), none when the target does not write it: it starts its width
    /// at the label size before the labels' gap before the plot area, and its baseline lies
    /// [`LabelLines::value_baseline`] below the exact place of its value, not the place on the
    /// device of its gridline.
    fn value_labels(
        &mut self,
        chart: &Columns,
        axis: &ValueAxis,
        plot: Edges<Length>,
        lines: LabelLines,
    ) -> Vec<Item> {
        let (Some(gap), Some(down), Some(format)) = (
            lines.label_gap(),
            lines.value_baseline(),
            chart.value_format.as_ref(),
        ) else {
            return Vec::new();
        };
        let end = plot.left - gap;
        let color = self.label_color(chart.value_label_fill.as_ref());
        let props = chart_props(chart, chart.value_label_size);
        axis.labels()
            .filter_map(|value| {
                let at = axis.along((plot.bottom, plot.top), value)?;
                self.value_label(&props, (format, value), color, |room| {
                    Some((end - room, at + down))
                })
            })
            .collect()
    }

    /// Shapes one resolved data label, computes its automatic place through `auto_place`,
    /// applies any per-point manual layout, and pushes its painted text items into `items`.
    fn push_resolved_label(
        &mut self,
        items: &mut Vec<Item>,
        (labels, point): (&DataLabelText, &LabelPoint<'_>),
        (layout, frame): (PointLabelLayout, Edges<Length>),
        auto_place: impl FnOnce(Length, i64, LabelLines) -> Option<(Length, Length)>,
    ) -> Option<()> {
        let props = data_label_props(labels);
        let lines = self.lines_of(&props)?;
        let color = self.label_color(labels.fill.as_ref());
        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 placed = auto_place(max_width, line_count, lines)?;
        let place = apply_point_layout(placed, layout, frame, (labels.insets, lines))?;
        push_label_lines(items, shaped, place, (max_width, lines.single_line), color)
    }

    /// The data labels of the series of a bar or column chart whose data labels show their
    /// values ([`SeriesLabels::Values`]): at the outer end of each bar for a clustered chart
    /// ([`data_label_place`]), and centered inside each bar segment for a stacked or
    /// 100%-stacked chart ([`centered_data_label_place`]), the bar's place in the plot area
    /// `plot` as [`Self::bars`] gives it before the device for bars that run in the direction
    /// `direction`. `None` when a label needs more than one face or a bar has no place.
    pub(super) fn data_labels(
        &mut self,
        chart: &Columns,
        (gap, overlap): (i64, i64),
        (axis, direction): (&ValueAxis, BarDirection),
        (plot, frame): (Edges<Length>, Edges<Length>),
    ) -> Option<Vec<Item>> {
        let clusters = Clusters::of(chart, (gap, overlap), direction.run(plot))?;
        let spans = BarSpans::of(chart)?;
        let half = clusters.thickness.div_toward_zero(2);
        let mut items = Vec::new();
        for (index, one) in (0_i64..).zip(chart.bar_series()) {
            let SeriesLabels::Values(series_labels) = &one.labels else {
                continue;
            };
            for (category, value) in (0_i64..).zip(&one.values) {
                let Some(value) = *value else {
                    continue;
                };
                let cat_idx = usize::try_from(category).ok()?;
                let Some((labels, rich_lines, layout)) =
                    resolve_point_label(series_labels, cat_idx)
                else {
                    continue;
                };
                let start = direction.at(plot, clusters.start((category, index))?);
                let point = LabelPoint {
                    series_name: one.name.as_deref(),
                    category_name: category_name_at(chart, cat_idx),
                    category_index: cat_idx,
                    value,
                    percent: None,
                    rich_lines,
                };
                self.push_resolved_label(
                    &mut items,
                    (labels, &point),
                    (layout, frame),
                    |max_width, line_count, lines| {
                        bar_data_label_place(
                            (axis, direction, plot),
                            (start, half),
                            (&spans, index, category, value),
                            (labels.position, max_width, line_count),
                            (labels.insets, lines),
                        )
                    },
                )?;
            }
        }
        Some(items)
    }

    /// The data labels of the line series of a line or combo chart whose data labels show their
    /// values ([`SeriesLabels::Values`]): placed relative to each point `(x, y)` at `ctr`, `t`,
    /// `b`, `l`, or `r` (`Default` = `r`), offset by half of `max(marker_size,
    /// CHART_LINE_DATA_LABEL_MARKER_MIN)` plus [`CHART_DATA_LABEL_GAP`].
    pub(super) fn line_data_labels(
        &mut self,
        chart: &Columns,
        looks: &[LineLook],
        axis: &ValueAxis,
        (plot, frame): (Edges<Length>, Edges<Length>),
    ) -> Option<Vec<Item>> {
        let stacked = stacked_line_values(chart)?;
        let offset = chart.bar_series().len();
        let mut items = Vec::new();
        for (index, (one, look)) in chart.line_series().iter().zip(looks).enumerate() {
            let SeriesLabels::Values(series_labels) = &one.labels else {
                continue;
            };
            let clearance = line_label_clearance(look, &self.shaper.theme().shapes);
            let plotted = stacked
                .get(index)
                .map_or(one.values.as_slice(), Vec::as_slice);
            for (category, (value, place_value)) in
                (0_i64..).zip(one.values.iter().zip(plotted.iter()))
            {
                let (Some(value), Some(place_value)) = (*value, *place_value) else {
                    continue;
                };
                let cat_idx = usize::try_from(category).ok()?;
                let Some((labels, rich_lines, layout)) =
                    resolve_point_label(series_labels, cat_idx)
                else {
                    continue;
                };
                let (_, x) =
                    self.point_across(chart, Across::Bands, plot, (offset + index, category))?;
                let y = axis.along((plot.bottom, plot.top), place_value)?;
                let point = LabelPoint {
                    series_name: one.name.as_deref(),
                    category_name: category_name_at(chart, cat_idx),
                    category_index: cat_idx,
                    value,
                    percent: None,
                    rich_lines,
                };
                self.push_resolved_label(
                    &mut items,
                    (labels, &point),
                    (layout, frame),
                    |max_width, line_count, lines| {
                        line_data_label_place(
                            (x, y),
                            (labels.position, clearance),
                            (max_width, line_count),
                            (labels.insets, lines),
                        )
                    },
                )?;
            }
        }
        Some(items)
    }

    /// Shapes one point's data label into one or more lines according to `point.rich_lines` or
    /// `labels.parts`.
    pub(super) fn data_label_lines(
        &mut self,
        props: &RunProps,
        labels: &DataLabelText,
        point: &LabelPoint<'_>,
    ) -> Option<Vec<(ChartText, Option<Rgb>)>> {
        if let Some(rich) = point.rich_lines {
            let mut shaped = Vec::with_capacity(rich.len());
            for line in rich {
                shaped.push((self.chart_text(props, line)?, None));
            }
            return (!shaped.is_empty()).then_some(shaped);
        }
        if labels.parts.is_value_only() {
            return Some(vec![
                self.written_text(props, (&labels.format, point.value))?,
            ]);
        }
        let (joined, own_color) = format_label_parts(labels, point)?;
        let mut shaped = Vec::new();
        for raw_line in joined.split('\n') {
            let line = raw_line.trim_end_matches('\r');
            shaped.push((self.chart_text(props, line)?, own_color));
        }
        (!shaped.is_empty()).then_some(shaped)
    }

    /// The color of a label's text: its fill, or black for the automatic color.
    pub(super) fn label_color(&self, fill: Option<&DrawColor>) -> Rgb {
        let theme = &self.shaper.theme().shapes;
        fill.and_then(|fill| fill.resolve(&theme.colors))
            .map_or(Rgb::BLACK, |(rgb, alpha)| on_white(rgb, alpha))
    }

    /// The glyph run of a label's `text` in the chart's font at the label size, drawn at the
    /// size on the device ([`Self::chart_text`]); `place` gives, from its width, where the first
    /// glyph starts and the baseline, or `None` when the label is not drawn.
    pub(super) fn chart_label(
        &mut self,
        chart: &Columns,
        text: &str,
        color: Rgb,
        place: impl FnOnce(Length) -> Option<(Length, Length)>,
    ) -> Option<Item> {
        let shaped = self.chart_text(&chart_props(chart, chart.label_size), text)?;
        let (x, baseline) = place(shaped.width())?;
        shaped.item(x, baseline, color)
    }

    /// The label of `value` in the label format `format` in the look `props`, placed by
    /// `place` from its width and drawn in `color`, or in the color that the format's section
    /// names ([`Self::written_text`]).
    pub(super) fn value_label(
        &mut self,
        props: &RunProps,
        (format, value): (&LabelFormat, Decimal),
        color: Rgb,
        place: impl FnOnce(Length) -> Option<(Length, Length)>,
    ) -> Option<Item> {
        let (shaped, own) = self.written_text(props, (format, value))?;
        let (x, baseline) = place(shaped.room())?;
        shaped.item(x, baseline, own.unwrap_or(color))
    }

    /// The text of `value` in the label format `format` in the look `props`, as
    /// [`LabelFormat::write`] writes it: its text pieces in one chart text, each blank as wide
    /// as a space, whatever its character, before the text, between its pieces or after it
    /// (its trail), with the color that the format's section names, if any. `None` when the
    /// format does not write the value, or when the text has no glyphs or needs more than one
    /// face.
    pub(super) fn written_text(
        &mut self,
        props: &RunProps,
        (format, value): (&LabelFormat, Decimal),
    ) -> Option<(ChartText, Option<Rgb>)> {
        let written = format.write(value)?;
        let mut text: Option<ChartText> = None;
        let mut blank = Length::ZERO;
        for piece in &written.pieces {
            match piece {
                // The target leaves the room of a space for the blank of any character.
                LabelPiece::Blank(_) => blank += self.chart_text(props, " ")?.width(),
                LabelPiece::Text(own) => {
                    let mut next = self.chart_text(props, own)?;
                    next.lead = blank;
                    blank = Length::ZERO;
                    text = Some(match text {
                        Some(before) => before.joined(next)?,
                        None => next,
                    });
                }
            }
        }
        let mut text = text?;
        text.trail = blank;
        Some((text, written.color))
    }

    /// A chart text in the look `props`: its glyphs step by their advances in the font at the
    /// size in the markup, not at the drawn size. A part of a ligature draws nothing and takes
    /// no room: its character follows the character of the glyph before it in that glyph's
    /// text. `None` when the text has no glyphs or needs more than one face.
    pub(super) fn chart_text(&mut self, props: &RunProps, text: &str) -> Option<ChartText> {
        let mut measured = Vec::new();
        self.shaper.measure(props, text, &mut measured);
        let first = measured.first()?.face;
        if measured.iter().any(|glyph| glyph.face != first) {
            return None;
        }
        let face = *self.shaper.faces().get(first)?;
        let per_em = i64::from(face.metrics.units_per_em.max(1));
        let (mut glyphs, mut advances) = (Vec::<(u32, String)>::new(), Vec::new());
        for glyph in &measured {
            if let Some((_, text)) = glyphs.last_mut().filter(|_| glyph.part) {
                text.push(glyph.ch);
                continue;
            }
            let units = self.shaper.font_advance(face.font, glyph.id)?;
            let advance = face.size.checked_mul(i64::from(units))?;
            advances.push(advance.div_toward_zero(per_em));
            glyphs.push((glyph.id, glyph.ch.to_string()));
        }
        Some(ChartText {
            font: face.font,
            size: self.device.snap(face.size),
            glyphs,
            advances,
            lead: Length::ZERO,
            trail: Length::ZERO,
        })
    }
}

/// Clearance from a line point's center to its data label's text box: half of the marker size
/// (floored at [`CHART_LINE_DATA_LABEL_MARKER_MIN`]) plus [`CHART_DATA_LABEL_GAP`].
fn line_label_clearance(look: &LineLook, theme: &f_office_drawingml::theme::ShapeTheme) -> Length {
    let diameter = look
        .marker
        .as_ref()
        .and_then(|marker| marker_size(marker, theme))
        .unwrap_or(Length::ZERO)
        .max(CHART_LINE_DATA_LABEL_MARKER_MIN);
    diameter.div_toward_zero(2) + CHART_DATA_LABEL_GAP
}

/// Context of one data point used to build multi-part or custom rich-text data label lines.
pub(super) struct LabelPoint<'a> {
    pub(super) series_name: Option<&'a str>,
    pub(super) category_name: Option<&'a str>,
    pub(super) category_index: usize,
    pub(super) value: Decimal,
    pub(super) percent: Option<String>,
    pub(super) rich_lines: Option<&'a [String]>,
}

/// Resolves the effective label specification, optional rich-text lines, and manual layout for
/// point `index`, returning `None` if this point's label is deleted or hidden.
pub(super) fn resolve_point_label(
    labels: &DataLabelText,
    index: usize,
) -> Option<(&DataLabelText, Option<&[String]>, PointLabelLayout)> {
    if let Some((_, over)) = labels.point_overrides.iter().find(|(i, _)| *i == index) {
        return match over {
            PointLabelOverride::Deleted => None,
            PointLabelOverride::Custom(spec) => {
                Some((&spec.label, spec.rich_lines.as_deref(), spec.layout))
            }
        };
    }
    labels
        .show_default
        .then_some((labels, None, PointLabelLayout::Automatic))
}

/// Applies a per-point manual layout (`Offset` or `Edge`) in chart-frame fractions to the
/// automatic `(box_x, top_baseline)` text anchor.
pub(super) fn apply_point_layout(
    (box_x, top_baseline): (Length, Length),
    layout: PointLabelLayout,
    frame: Edges<Length>,
    (insets, lines): (Edges<Length>, LabelLines),
) -> Option<(Length, Length)> {
    let frame_w = frame.right - frame.left;
    let frame_h = frame.bottom - frame.top;
    match layout {
        PointLabelLayout::Automatic => Some((box_x, top_baseline)),
        PointLabelLayout::Offset { dx, dy } => Some((
            box_x + share(frame_w, dx, ONE)?,
            top_baseline + share(frame_h, dy, ONE)?,
        )),
        PointLabelLayout::Edge { x, y } => Some((
            frame.left + share(frame_w, x, ONE)? + insets.left,
            frame.top + share(frame_h, y, ONE)? + insets.top + lines.single_top,
        )),
    }
}

/// Returns the cached category name at `index`, if present.
pub(super) fn category_name_at(chart: &Columns, index: usize) -> Option<&str> {
    chart
        .category_names
        .as_deref()
        .and_then(|names| names.get(index))
        .map(String::as_str)
}

/// Formats `value` through `format` into a plain string (each blank as one space) and its
/// optional section color.
pub(super) fn written_plain_text(
    format: &LabelFormat,
    value: Decimal,
) -> Option<(String, Option<Rgb>)> {
    let written = format.write(value)?;
    let mut text = String::new();
    for piece in &written.pieces {
        match piece {
            LabelPiece::Blank(_) => text.push(' '),
            LabelPiece::Text(part) => text.push_str(part),
        }
    }
    Some((text, written.color))
}

/// Joins the enabled label parts for `point` in OOXML order (`serName`, `catName`, `val`,
/// `percent`) using `labels.parts.effective_separator()`.
fn format_label_parts(
    labels: &DataLabelText,
    point: &LabelPoint<'_>,
) -> Option<(String, Option<Rgb>)> {
    let parts_cfg = &labels.parts;
    let mut pieces = Vec::new();
    let mut own_color = None;
    if parts_cfg.show_ser_name {
        pieces.push(point.series_name?.to_owned());
    }
    if parts_cfg.show_cat_name {
        let cat = point
            .category_name
            .map_or_else(|| (point.category_index + 1).to_string(), str::to_owned);
        pieces.push(cat);
    }
    if parts_cfg.show_val {
        let (val_text, color) = written_plain_text(&labels.format, point.value)?;
        own_color = color;
        pieces.push(val_text);
    }
    if parts_cfg.percent.is_shown() {
        pieces.push(point.percent.clone()?);
    }
    (!pieces.is_empty()).then(|| (pieces.join(parts_cfg.effective_separator()), own_color))
}

/// Emits one glyph run per line in `shaped`, horizontally centered inside `max_width` starting at
/// `box_x` and stepping downward by `single_line` from `top_baseline`.
pub(super) fn push_label_lines(
    items: &mut Vec<Item>,
    shaped: Vec<(ChartText, Option<Rgb>)>,
    (box_x, top_baseline): (Length, Length),
    (max_width, single_line): (Length, Length),
    color: Rgb,
) -> Option<()> {
    for (line_idx, (text, own)) in (0_i64..).zip(shaped) {
        let x = box_x + (max_width - text.width()).div_toward_zero(2);
        let baseline = top_baseline + single_line.checked_mul(line_idx)?;
        items.push(text.item(x, baseline, own.unwrap_or(color))?);
    }
    Some(())
}

/// Places one line point's data label relative to `(x, y)` at `position` (`Default` = `Right`).
fn line_data_label_place(
    (x, y): (Length, Length),
    (position, clearance): (DataLabelPosition, Length),
    (width, line_count): (Length, i64),
    (insets, lines): (Edges<Length>, LabelLines),
) -> Option<(Length, Length)> {
    let text_height = lines.single_line.checked_mul(line_count)?;
    let extra_height = lines.single_line.checked_mul(line_count - 1)?;
    let x_room = insets.left + width + insets.right;
    let y_room = insets.top + text_height + insets.bottom;
    let center_x = x - x_room.div_toward_zero(2) + insets.left;
    let center_y = y - y_room.div_toward_zero(2) + insets.top + lines.single_top;
    let place = match position {
        DataLabelPosition::Center => (center_x, center_y),
        DataLabelPosition::Right | DataLabelPosition::Default => {
            (x + clearance + insets.left, center_y)
        }
        DataLabelPosition::Left => (x - clearance - insets.right - width, center_y),
        DataLabelPosition::Top => (
            center_x,
            y - clearance - insets.top - (lines.line - lines.top) - extra_height,
        ),
        DataLabelPosition::Bottom => (center_x, y + clearance + insets.top + lines.single_top),
        _ => return None,
    };
    Some(place)
}

/// Places one bar's data label at `position` (`Default` resolves to `OutsideEnd` for clustered
/// bars and `Center` for stacked/100%-stacked bars).
fn bar_data_label_place(
    (axis, direction, plot): (&ValueAxis, BarDirection, Edges<Length>),
    bar_run: (Length, Length),
    (spans, series, category, value): (&BarSpans, i64, i64, Decimal),
    (position, width, line_count): (DataLabelPosition, Length, i64),
    box_look: (Edges<Length>, LabelLines),
) -> Option<(Length, Length)> {
    let (from, to, resolved) = match spans {
        BarSpans::Clustered => (
            axis.crossing,
            value,
            if position == DataLabelPosition::Default {
                DataLabelPosition::OutsideEnd
            } else {
                position
            },
        ),
        BarSpans::Stacked(segments) => {
            let (from, to) = segments.get(series, category)?;
            (
                from,
                to,
                if position == DataLabelPosition::Default {
                    DataLabelPosition::Center
                } else {
                    position
                },
            )
        }
    };
    let span = direction.values(plot);
    let from_px = axis.along(span, from)?;
    let to_px = axis.along(span, to)?;
    let beyond = to >= from;
    let place = match resolved {
        DataLabelPosition::OutsideEnd => data_label_place(
            direction,
            bar_run,
            (to_px, beyond),
            (width, line_count),
            box_look,
        )?,
        DataLabelPosition::InsideEnd => data_label_place(
            direction,
            bar_run,
            (to_px, !beyond),
            (width, line_count),
            box_look,
        )?,
        DataLabelPosition::InsideBase => data_label_place(
            direction,
            bar_run,
            (from_px, beyond),
            (width, line_count),
            box_look,
        )?,
        DataLabelPosition::Center => {
            let value_mid = from_px + (to_px - from_px).div_toward_zero(2);
            centered_data_label_place(direction, bar_run, value_mid, (width, line_count), box_look)?
        }
        _ => return None,
    };
    Some(place)
}

/// Where the text of a stacked bar segment's centered data label (`ctr` or default) starts and
/// where its baseline lies: the text box of `insets` around `width` and `lines.single_line` is
/// centered horizontally and vertically on the segment's midpoint.
fn centered_data_label_place(
    direction: BarDirection,
    (start, half): (Length, Length),
    value_mid: Length,
    (width, line_count): (Length, i64),
    (insets, lines): (Edges<Length>, LabelLines),
) -> Option<(Length, Length)> {
    let (mid_x, mid_y) = match direction {
        BarDirection::Up => (start + half, value_mid),
        BarDirection::Right => (value_mid, start - half),
    };
    let x_room = insets.left + width + insets.right;
    let y_room = insets.top + lines.single_line.checked_mul(line_count)? + insets.bottom;
    Some((
        mid_x - x_room.div_toward_zero(2) + insets.left,
        mid_y - y_room.div_toward_zero(2) + insets.top + lines.single_top,
    ))
}

/// Where the text of a bar's data label starts and where its baseline lies, for a bar that
/// runs in the direction `direction`, starts at `start` along the run and is twice `half`
/// thick, and that ends at `end` on the value axis, at or beyond the axis' crossing when
/// `beyond`: for a text `width` wide in a text box with the insets `insets` and of a face with
/// the lines `lines`.
///
/// For bars that run up, the box is centered on the bar. Above a bar at or above the axis'
/// crossing, the baseline lies [`CHART_DATA_LABEL_GAP`], the box's top inset and the face's win
/// descent above the bar's end; below a bar under it, the gap, the box's top inset and the
/// ascent of the face's single line below the bar's end. The bottom inset does not move a
/// label.
///
/// For bars that run right, right of a bar at or right of the axis' crossing, the text starts
/// the gap and the box's left inset beyond the bar's end; left of a bar below it, the text ends
/// the gap and the box's right inset before the bar's end. Up and down, the box of the insets
/// and the face's single line is centered on the bar.
fn data_label_place(
    direction: BarDirection,
    (start, half): (Length, Length),
    (end, beyond): (Length, bool),
    (width, line_count): (Length, i64),
    (insets, lines): (Edges<Length>, LabelLines),
) -> Option<(Length, Length)> {
    let place = match direction {
        BarDirection::Up => {
            let room = insets.left + width + insets.right;
            let x = start + half - room.div_toward_zero(2) + insets.left;
            let extra = lines.single_line.checked_mul(line_count - 1)?;
            let baseline = if beyond {
                end - CHART_DATA_LABEL_GAP - insets.top - (lines.line - lines.top) - extra
            } else {
                end + CHART_DATA_LABEL_GAP + insets.top + lines.single_top
            };
            (x, baseline)
        }
        BarDirection::Right => {
            let x = if beyond {
                end + CHART_DATA_LABEL_GAP + insets.left
            } else {
                end - CHART_DATA_LABEL_GAP - insets.right - width
            };
            let room = insets.top + lines.single_line.checked_mul(line_count)? + insets.bottom;
            let middle = start - half;
            (
                x,
                middle - room.div_toward_zero(2) + insets.top + lines.single_top,
            )
        }
    };
    Some(place)
}

/// A chart text shaped in one face ([`Layout::chart_text`]).
pub(super) struct ChartText {
    /// The face's font.
    pub(super) font: FontId,
    /// The size that the text is drawn at, on the device.
    pub(super) size: Length,
    /// Each glyph and the characters it draws: its own, and those of the parts of a ligature
    /// after it.
    pub(super) glyphs: Vec<(u32, String)>,
    /// Each glyph's advance at the size in the markup, with the blanks of a label format after
    /// it.
    pub(super) advances: Vec<Length>,
    /// The blank before the first glyph: the blanks of a label format before its text.
    pub(super) lead: Length,
    /// The blank after the last glyph: the blanks of a label format after its text, which a
    /// value label's room counts and a data label's width does not.
    trail: Length,
}

impl ChartText {
    /// The blank before the first glyph and the sum of the advances: the width by which a
    /// data label is placed, without its trail.
    pub(super) fn width(&self) -> Length {
        self.lead + self.advances.iter().copied().sum()
    }

    /// The width and the blank after the last glyph: the room by which a value label of an axis
    /// is placed.
    pub(super) fn room(&self) -> Length {
        self.width() + self.trail
    }

    /// The text with a blank `width` wide after its last glyph.
    fn with_blank_after(mut self, width: Length) -> Self {
        match self.advances.last_mut() {
            Some(last) => *last += width,
            None => self.lead += width,
        }
        self
    }

    /// The text followed by `next`, with `next`'s blank before it, or `None` when `next` is
    /// in another face.
    fn joined(self, next: Self) -> Option<Self> {
        if (self.font, self.size) != (next.font, next.size) {
            return None;
        }
        let mut joined = self.with_blank_after(next.lead);
        joined.glyphs.extend(next.glyphs);
        joined.advances.extend(next.advances);
        Some(joined)
    }

    /// The glyph run of the text with its blank before it at `x`, on the baseline `baseline`,
    /// in `color`.
    pub(super) fn item(self, mut x: Length, baseline: Length, color: Rgb) -> Option<Item> {
        x += self.lead;
        let mut shown = String::new();
        let mut glyphs = Vec::with_capacity(self.glyphs.len());
        for ((id, text), advance) in self.glyphs.into_iter().zip(self.advances) {
            let text_start = u32::try_from(shown.len()).ok()?;
            shown.push_str(&text);
            glyphs.push(Glyph {
                id,
                x,
                y: baseline,
                text_start,
                text_end: u32::try_from(shown.len()).ok()?,
            });
            x += advance;
        }
        Some(Item::Glyphs(GlyphRun {
            font: self.font,
            size: self.size,
            color,
            text: shown,
            glyphs,
            outline: None,
            filled: true,
            effect: false,
            turn: None,
        }))
    }
}

/// The run properties of the data labels `labels`: their font at their size.
pub(super) fn data_label_props(labels: &DataLabelText) -> RunProps {
    RunProps {
        font_ascii: Some(labels.font.clone()),
        font_hansi: Some(labels.font.clone()),
        size: Some(labels.size),
        ..RunProps::default()
    }
}