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<'_> {
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 {
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)
}
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)
}
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)
}
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()
}
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)
}
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)
}
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)
}
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)
}
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))
}
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)
}
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))
}
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 {
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))
}
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,
})
}
}
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
}
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]>,
}
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))
}
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,
)),
}
}
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)
}
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))
}
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))
}
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(())
}
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)
}
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)
}
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,
))
}
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)
}
pub(super) struct ChartText {
pub(super) font: FontId,
pub(super) size: Length,
pub(super) glyphs: Vec<(u32, String)>,
pub(super) advances: Vec<Length>,
pub(super) lead: Length,
trail: Length,
}
impl ChartText {
pub(super) fn width(&self) -> Length {
self.lead + self.advances.iter().copied().sum()
}
pub(super) fn room(&self) -> Length {
self.width() + self.trail
}
fn with_blank_after(mut self, width: Length) -> Self {
match self.advances.last_mut() {
Some(last) => *last += width,
None => self.lead += width,
}
self
}
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)
}
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,
}))
}
}
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()
}
}