use f_office_paint::{Glyph, GlyphRun, Item, Rgb, Turn};
use f_office_units::{Edges, Length};
use super::labels::ChartText;
use super::{LabelLines, chart_props};
use crate::chart::{ChartGroup, Columns, PlotPlace};
use crate::layout::Layout;
use crate::params::CHART_TURNED_LABEL_CUT_SHARE;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum CategoryForm {
Upright(Vec<Vec<String>>),
Diagonal(Vec<Length>),
Vertical(Length),
}
impl CategoryForm {
pub(super) fn room(&self, lines: LabelLines) -> Option<Length> {
match self {
Self::Upright(rows) => {
let most = rows.iter().map(Vec::len).max().unwrap_or(1).max(1);
lines.line.checked_mul(i64::try_from(most).ok()? - 1)
}
Self::Diagonal(widths) => {
let widest = widths.iter().copied().max().unwrap_or(Length::ZERO);
Some((diagonal(widest + lines.line)? - lines.line).max(Length::ZERO))
}
Self::Vertical(widest) => Some((*widest - lines.line).max(Length::ZERO)),
}
}
pub(super) fn left_reach(&self, span: Length) -> Option<Length> {
let Self::Diagonal(widths) = self else {
return None;
};
let count = i64::try_from(widths.len()).ok()?.max(1);
let mut reach: Option<Length> = None;
for (index, width) in (0_i64..).zip(widths) {
let middle = span
.checked_mul(index.checked_mul(2)? + 1)?
.div_toward_zero(count.checked_mul(2)?);
let past = diagonal(*width)? - middle;
reach = Some(reach.map_or(past, |reach| reach.max(past)));
}
reach
}
}
enum Wrapped {
Lines(Vec<String>),
Wider,
}
impl Layout<'_> {
pub(super) fn below_form(
&mut self,
chart: &Columns,
span: Length,
frame: Edges<Length>,
) -> Option<CategoryForm> {
let (
ChartGroup::Columns { .. }
| ChartGroup::Columns3D { .. }
| ChartGroup::Lines { .. }
| ChartGroup::Combo { .. },
Some(names),
) = (&chart.group, &chart.category_names)
else {
return None;
};
let lines = self.label_lines(chart)?;
let width = span.div_toward_zero(i64::try_from(names.len()).ok()?.max(1));
let form = self.category_form(chart, width, lines.line)?;
if matches!(form, CategoryForm::Upright(_)) {
return Some(form);
}
let room = self.below_base(chart)?
+ form.room(lines)?
+ self.legend_bottom(chart, lines, frame)?;
let (part, whole) = CHART_TURNED_LABEL_CUT_SHARE;
let limit = (frame.bottom - frame.top).checked_mul(part)?;
(room.checked_mul(whole)? <= limit).then_some(form)
}
pub(super) fn category_form(
&mut self,
chart: &Columns,
width: Length,
line: Length,
) -> Option<CategoryForm> {
let names = chart.category_names.as_ref()?;
let props = chart_props(chart, chart.label_size);
let mut rows = Vec::with_capacity(names.len());
let mut turned = false;
for name in names {
if name.is_empty() {
rows.push(Vec::new());
continue;
}
let wrap = wrapped(name, width, |text| {
self.chart_text(&props, text).map(|shaped| shaped.width())
})?;
match wrap {
Wrapped::Lines(lines) => rows.push(lines),
Wrapped::Wider => turned = true,
}
}
let automatic = chart.plot_place == PlotPlace::Automatic;
if turned {
return self.turned_form(chart, width, line).filter(|_| automatic);
}
(automatic || rows.iter().all(|lines| lines.len() <= 1))
.then_some(CategoryForm::Upright(rows))
}
fn turned_form(
&mut self,
chart: &Columns,
width: Length,
line: Length,
) -> Option<CategoryForm> {
let props = chart_props(chart, chart.label_size);
let mut widths = Vec::new();
for name in chart.category_names.iter().flatten() {
widths.push(if name.is_empty() {
Length::ZERO
} else {
self.chart_text(&props, name)?.width()
});
}
if width < line {
None
} else if diagonal(width)? < line {
let widest = widths.iter().copied().max().unwrap_or(Length::ZERO);
Some(CategoryForm::Vertical(widest))
} else {
Some(CategoryForm::Diagonal(widths))
}
}
pub(super) fn category_labels(
&mut self,
chart: &Columns,
(plot, anchor, frame): (Edges<Length>, Length, Edges<Length>),
lines: LabelLines,
) -> Option<Vec<Item>> {
let names = chart.category_names.as_ref()?;
let count = i64::try_from(names.len()).ok()?;
let span = plot.right - plot.left;
let form = self.below_form(chart, span, frame)?;
let color = self.label_color(chart.category_label_fill.as_ref());
let mut items = Vec::new();
for (index, name) in (0_i64..).zip(names) {
if name.is_empty() {
continue;
}
let share = span.checked_mul(index.checked_mul(2)? + 1)?;
let middle = plot.left + share.div_toward_zero(count * 2);
let place = (middle, anchor, lines);
items.extend(self.category_items(chart, (&form, index, name), color, place)?);
}
Some(items)
}
fn category_items(
&mut self,
chart: &Columns,
(form, index, name): (&CategoryForm, i64, &str),
color: Rgb,
(middle, bottom, lines): (Length, Length, LabelLines),
) -> Option<Vec<Item>> {
match form {
CategoryForm::Upright(rows) => {
let rows = rows.get(usize::try_from(index).ok()?)?;
let baseline = bottom + lines.category_baseline()?;
self.upright_category(chart, rows, color, (middle, baseline, lines))
}
CategoryForm::Diagonal(_) => Some(vec![self.turned_category(
chart,
name,
color,
(middle, bottom, lines),
)?]),
CategoryForm::Vertical(_) => Some(vec![self.vertical_category(
chart,
name,
color,
(middle, bottom, lines),
)?]),
}
}
fn upright_category(
&mut self,
chart: &Columns,
rows: &[String],
color: Rgb,
(middle, baseline, lines): (Length, Length, LabelLines),
) -> Option<Vec<Item>> {
let mut items = Vec::with_capacity(rows.len());
for (row, text) in (0_i64..).zip(rows) {
let down = baseline + lines.line.checked_mul(row)?;
items.push(self.chart_label(chart, text, color, |width| {
Some((middle - width.div_toward_zero(2), down))
})?);
}
Some(items)
}
fn turned_category(
&mut self,
chart: &Columns,
name: &str,
color: Rgb,
(middle, bottom, lines): (Length, Length, LabelLines),
) -> Option<Item> {
let shaped = self.chart_text(&chart_props(chart, chart.label_size), name)?;
let half = lines.line.div_toward_zero(2);
let end_middle = bottom + lines.category_baseline()? - lines.top + diagonal(half)?;
let to_baseline = diagonal(lines.top - half)?;
let along = diagonal(shaped.width())?;
let start = (
middle + to_baseline - along,
end_middle + to_baseline + along,
);
let part = diagonal_part()?;
let turn = Turn {
xx: part,
yx: -part,
xy: part,
yy: part,
};
shaped.turned_item(start, (turn, color), |reached| {
diagonal(reached).map(|step| (step, -step))
})
}
fn vertical_category(
&mut self,
chart: &Columns,
name: &str,
color: Rgb,
(middle, bottom, lines): (Length, Length, LabelLines),
) -> Option<Item> {
let shaped = self.chart_text(&chart_props(chart, chart.label_size), name)?;
let half = lines.line.div_toward_zero(2);
let start = (
middle + lines.top - half,
bottom + lines.category_baseline()? - lines.top + shaped.width(),
);
shaped.turned_item(start, (UPWARD, color), |reached| {
Some((Length::ZERO, -reached))
})
}
}
pub(super) const UPWARD: Turn = Turn {
xx: 0,
yx: -Turn::SCALE,
xy: Turn::SCALE,
yy: 0,
};
impl ChartText {
pub(super) fn turned_item(
self,
(x, y): (Length, Length),
(turn, color): (Turn, Rgb),
mut step: impl FnMut(Length) -> Option<(Length, Length)>,
) -> Option<Item> {
let (font, size) = (self.font, self.size);
let mut shown = String::new();
let mut glyphs = Vec::with_capacity(self.glyphs.len());
let mut reached = self.lead;
for ((id, text), advance) in self.glyphs.into_iter().zip(self.advances) {
let (across, down) = step(reached)?;
let text_start = u32::try_from(shown.len()).ok()?;
shown.push_str(&text);
glyphs.push(Glyph {
id,
x: x + across,
y: y + down,
text_start,
text_end: u32::try_from(shown.len()).ok()?,
});
reached += advance;
}
Some(Item::Glyphs(GlyphRun {
font,
size,
color,
text: shown,
glyphs,
outline: None,
filled: true,
effect: false,
turn: Some(turn),
}))
}
}
pub(super) fn diagonal(length: Length) -> Option<Length> {
diagonal_units(length.units()).map(Length::from_units)
}
fn diagonal_part() -> Option<i32> {
let scale = i64::from(Turn::SCALE);
let side = diagonal_units(scale)?;
let next = side.checked_mul(2)? + 1;
let nearest = if next.checked_mul(next)? < scale.checked_mul(scale)?.checked_mul(2)? {
side + 1
} else {
side
};
i32::try_from(nearest).ok()
}
fn diagonal_units(units: i64) -> Option<i64> {
let square = i128::from(units).checked_mul(i128::from(units))? / 2;
let side = i64::try_from(square.isqrt()).ok()?;
Some(if units < 0 { -side } else { side })
}
fn wrapped(
text: &str,
width: Length,
mut measure: impl FnMut(&str) -> Option<Length>,
) -> Option<Wrapped> {
let mut rows: Vec<String> = Vec::new();
for word in text.split(' ') {
if let Some(last) = rows.last_mut() {
let joined = format!("{last} {word}");
if measure(&joined)? <= width {
*last = joined;
continue;
}
}
if measure(word)? > width {
return Some(Wrapped::Wider);
}
rows.push(word.to_owned());
}
Some(Wrapped::Lines(rows))
}
#[cfg(test)]
pub(super) fn wrapped_lines(
text: &str,
width: Length,
measure: impl FnMut(&str) -> Option<Length>,
) -> Option<Vec<String>> {
match wrapped(text, width, measure)? {
Wrapped::Lines(lines) => Some(lines),
Wrapped::Wider => None,
}
}