#![allow(
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_sign_loss,
clippy::too_many_lines
)]
use crate::alpha::{
marks::{fill_style, ObservationAlpha},
AlphaTarget, AlphaUnitKind,
};
use crate::builder::PlotDescription;
use crate::layout::{AxisTick, PhysicalTextAlignment, PixelRect, ResolvedTextPlan};
use crate::render::backend::{
with_clip, Backend, FillStyle, LineStyle, PlacedText, PlannedTextPlacement, Point2D, TextAnchor,
};
use crate::spec::{PlotMeasureContext, PlotRenderResult};
use crate::Error;
#[cfg(test)]
use crate::Plot;
mod result;
#[derive(Debug)]
pub(crate) struct PreparedWaterfall {
pub(crate) range: (f64, f64),
spans: Vec<WaterfallSpan>,
total_candidates: [(f64, crate::Text); 2],
total_variants: Vec<Option<totals::TotalVariant>>,
}
pub(crate) struct WaterfallTotalsPrepare<'v> {
pub(crate) numeric: crate::numeric::source::NumericBinding<'v>,
pub(crate) axes: [crate::orchestrator::registration::BaseAxisRef<'v>; 2],
pub(crate) format: Option<&'v std::sync::Arc<crate::numeric::format::NumericFormat>>,
}
impl PreparedWaterfall {
pub(crate) fn alpha_guide(
&self,
_chart: &crate::builder::PlotDescription,
theme: &crate::theme::ResolvedTheme,
guide: &mut crate::decorations::legend::alpha::AlphaGuideBuilder<'_>,
) -> crate::Result<()> {
use crate::decorations::legend::alpha::{AlphaGlyphRole, AlphaUnit};
let fill = theme.marks.get_fills().get_bodies().get_waterfall_bar();
for span in &self.spans {
guide.fill(
AlphaGlyphRole::Fill,
AlphaUnitKind::Observation,
AlphaUnit::observation(span.alpha),
span.alpha.value,
fill.backend_style((0, 0, 0)),
fill.get_outline()
.is_some_and(|outline| outline.mapped_width().is_some()),
)?;
}
Ok(())
}
}
mod totals;
#[derive(Debug, Clone, Copy, PartialEq)]
struct WaterfallSpan {
alpha: ObservationAlpha,
start: f64,
end: f64,
delta: f64,
}
fn retained<'v>(
registered: Option<&'v crate::orchestrator::registration::PlotRegistration<'_>>,
) -> Result<&'v PreparedWaterfall, Error> {
if registered.is_none() {
return Err(Error::Render(
"Waterfall requires root-prepared spans".into(),
));
}
match crate::layout::interior::preference::panel(registered, "Waterfall")?.as_ref() {
crate::orchestrator::registration::FamilyRef::Waterfall(marks) => Ok(marks),
_ => Err(Error::Render(
"Waterfall requires root-prepared spans".into(),
)),
}
}
struct BodyGeometry {
breadth: f64,
low: f64,
high: f64,
connector_room: f64,
}
#[cfg(test)]
mod geometry_tests {
use super::*;
thread_local! {
pub(super) static ANNOTATION_PLAN_CALLS: std::cell::Cell<usize> =
const { std::cell::Cell::new(0) };
}
#[test]
fn natural_height_rejects_a_foreign_request_operation_before_annotations_with_cached_intrinsics(
) {
use crate::orchestrator::root::{Root, RootSource};
use std::cell::Cell;
let source = Plot::waterfall(
crate::CategoryValues::new("step", ["one"]).unwrap(),
crate::NumericValues::new("delta", [2.0]),
10.0,
)
.x_limits(0.0, 20.0)
.size(800, 600);
let mut witnessed = false;
crate::layout::plan_root(
source.description().sizing_request(),
|stage| Root::prepare(RootSource::Plot(source.description()), stage),
|root_a, assigned_a, _| {
let registered = &root_a.plots[0];
let intrinsic = root_a.plot_intrinsic(®istered.scope.id)?;
let request_a =
crate::text::TextRequestContext::new(®istered.appearance, &root_a.text);
let cached = crate::orchestrator::root::coordinate_intrinsic(
intrinsic,
&crate::orchestrator::root::intrinsic_inputs(
Some(registered),
&request_a,
&root_a.operation,
)?,
)?;
let crate::orchestrator::root::PlotIntrinsics::Coordinate { value } = intrinsic
else {
unreachable!("Waterfall coordinate intrinsic slot")
};
assert!(std::ptr::eq(value.get().unwrap().as_ref(), cached));
crate::layout::plan_root(
source.description().sizing_request(),
|stage| Root::prepare(RootSource::Plot(source.description()), stage),
|root_b, assigned_b, _| {
assert!(std::ptr::eq(registered.source, root_b.plots[0].source));
let request_b = crate::text::TextRequestContext::new(
®istered.appearance,
&root_b.text,
);
let resources_b = request_b.text.prepared_font_environment()?.operation().unwrap();
assert!(root_b.operation.same_operation(&resources_b));
assert!(!root_a.operation.same_operation(&resources_b));
assert!(registered.data(&root_a.operation).is_ok());
let mixed_cached = crate::orchestrator::root::coordinate_intrinsic(
intrinsic,
&crate::orchestrator::root::intrinsic_inputs(
Some(registered),
&request_b,
&root_a.operation,
)?,
)?;
assert!(std::ptr::eq(mixed_cached, cached));
let before = ANNOTATION_PLAN_CALLS.with(Cell::get);
let height = natural_body_height(
registered.source,
Some(registered),
intrinsic,
&root_a.operation,
&request_a,
800.0,
None,
)?;
assert!(height.is_finite() && height > 0.0);
assert_eq!(ANNOTATION_PLAN_CALLS.with(Cell::get), before + 1);
let error = natural_body_height(
registered.source,
Some(registered),
intrinsic,
&root_a.operation,
&request_b,
800.0,
None,
)
.unwrap_err();
assert!(matches!(
error,
Error::Render(message)
if message.message() == "row source belongs to a different source or operation"
));
assert_eq!(ANNOTATION_PLAN_CALLS.with(Cell::get), before + 1);
assert!(std::ptr::eq(value.get().unwrap().as_ref(), cached));
witnessed = true;
Ok(crate::layout::MeasuredLayout::new(
assigned_b.assigned_size()?,
(),
))
},
|_, _, (), _| Ok(()),
)?;
Ok(crate::layout::MeasuredLayout::new(
assigned_a.assigned_size()?,
(),
))
},
|_, _, (), _| Ok(()),
)
.unwrap();
assert!(witnessed);
}
}
impl BodyGeometry {
fn new(theme: &crate::text::TextRequestContext<'_, '_>) -> Self {
let breadth = theme
.marks
.get_extents()
.get_waterfall_body_category_breadth()
.as_f64();
let free = 1.0 - breadth;
let low = free / 2.0;
let high = 1.0 - low;
Self {
breadth,
low,
high,
connector_room: free,
}
}
}
fn mark_intrinsic_body_minimum(
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<(f64, f64), Error> {
let prepared = retained(registered)?;
let labels = ®istered
.expect("prepared Waterfall occurrence")
.axes
.categories(1)
.expect("prepared Waterfall categories")
.raw;
if labels.is_empty() || labels.len() != prepared.spans.len() {
return Err(Error::Render(
"Waterfall categories and scientific spans differ".into(),
));
}
let body = theme
.marks
.get_fills()
.get_bodies()
.get_waterfall_bar()
.backend_style((0, 0, 0));
let geometry = BodyGeometry::new(theme);
let mut pitch = 1.0_f64 / 1024.0;
let mut numeric = 0.0_f64;
for span in &prepared.spans {
let ink = crate::render::geometry::rectangular_fill_ink_bounds(&fill_style(
span.alpha.value,
body.clone(),
))?;
pitch = pitch.max(crate::layout::interior::ink_pitch(
1.0 / 1024.0,
geometry.breadth,
)?);
if let Some(ink) = ink {
pitch = pitch.max(crate::layout::interior::ink_pitch(
(-ink.bottom).max(0.0),
geometry.low,
)?);
pitch = pitch.max(crate::layout::interior::ink_pitch(
ink.top.max(0.0),
geometry.low,
)?);
numeric = numeric.max(ink.right - ink.left);
}
}
if prepared.spans.len() > 1 {
let connector = crate::render::geometry::line_ink_width(
&theme
.marks
.get_strokes()
.get_connectors()
.get_waterfall_connector()
.backend_style(),
)?;
pitch = pitch.max(crate::layout::interior::ink_pitch(
connector,
geometry.connector_room,
)?);
numeric = numeric.max(connector);
}
numeric = numeric.max(crate::render::geometry::line_ink_width(
&theme
.marks
.get_strokes()
.get_references()
.get_waterfall_reference()
.backend_style(),
)?);
let categories = f64::from(
u32::try_from(labels.len())
.map_err(|_| Error::Render("Waterfall category count exceeds spatial range".into()))?,
);
let mark_height = pitch * categories;
let height = mark_height;
if !height.is_finite() {
return Err(Error::Render(
"Waterfall mark/annotation hard span overflowed".into(),
));
}
Ok((
if registered.expect("prepared occurrence").raw_windows()[0].is_none() {
numeric
} else {
0.0
},
height,
))
}
pub(crate) fn intrinsic_body_minimum(
chart: &PlotDescription,
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
intrinsic: &crate::orchestrator::root::PlotIntrinsics,
operation: &crate::font::canonical::OperationContext,
theme: &crate::text::TextRequestContext<'_, '_>,
selected_ranges: Option<[(f64, f64); 2]>,
) -> Result<(f64, f64), Error> {
let marks = mark_intrinsic_body_minimum(registered, theme)?;
let axes = crate::orchestrator::root::coordinate_intrinsic(
intrinsic,
&crate::orchestrator::root::intrinsic_inputs(registered, theme, operation)?,
)?
.minimum(crate::orchestrator::registration::axis_tick_labels_visible(
registered, 1,
));
let prepared = retained(registered)?;
let mut height = 0.0_f64;
let input = registered
.and_then(|registered| registered.axes.coordinate())
.ok_or_else(|| Error::Render("Waterfall total axes missing".into()))?;
let projection = crate::layout::Projection::new(
selected_ranges.map_or_else(
|| {
chart
.x_axis_spec()
.window
.map_or(input.ranges()[0], crate::layout::RawWindow::pair)
},
|ranges| ranges[0],
),
selected_ranges.map_or_else(
|| {
chart
.y_axis_spec()
.window
.map_or(input.ranges()[1], crate::layout::RawWindow::pair)
},
|ranges| ranges[1],
),
(0.0, 1.0, 0.0, 1.0),
);
let totals = &prepared.selected_totals(&projection)?.totals;
let eligible = crate::data::source::collect_source(
totals
.iter()
.enumerate()
.filter(|(_, (_, text))| text.is_some())
.map(|(index, _)| Ok(index)),
)?;
for (index, text) in totals
.iter()
.enumerate()
.filter_map(|(index, (_, text))| Some((index, text.as_ref()?)))
{
let appearance = text.appearance(
crate::text::TextAppearance::from(&theme.typography.annotations.waterfall_total)
.layout(theme.text_layouts.total.as_ref()),
);
if !appearance.includes(index, &eligible) {
continue;
}
let plan = theme.measure_appearance_text(
text.as_str(),
appearance,
text.resolved_alignment(crate::text::TextAlignment::Center)
.into(),
"Waterfall total shelf intrinsic",
)?;
height = height.max(plan.occupied_size().1);
}
let shelf = if height > 0.0 {
theme
.annotations
.get_waterfall_shelf()
.lengths(total_shelf_size(totals, theme))?
.padding
.vertical()
.add_pixels(height)?
.pixels_rounded(crate::layout::kernel::SpatialRounding::Ceil)?
} else {
0.0
};
Ok((marks.0.max(axes.0), marks.1.max(axes.1) + shelf))
}
pub(crate) fn natural_body_height(
chart: &PlotDescription,
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
intrinsic: &crate::orchestrator::root::PlotIntrinsics,
operation: &crate::font::canonical::OperationContext,
theme: &crate::text::TextRequestContext<'_, '_>,
width: f64,
selected_ranges: Option<[(f64, f64); 2]>,
) -> Result<f64, Error> {
let resources = theme
.text
.prepared_font_environment()?
.operation()
.map_err(|error| Error::Render(error.to_string().into()))?;
if registered.is_none() {
return Err(Error::Render("natural Waterfall rows missing".into()));
}
let crate::orchestrator::registration::FamilyRef::Waterfall(marks) =
crate::layout::interior::preference::panel(registered, "natural Waterfall")?.as_ref()
else {
return Err(Error::Render("natural Waterfall rows missing".into()));
};
let axes = registered
.and_then(|registered| registered.axes.coordinate())
.ok_or_else(|| Error::Render("natural Waterfall axes missing".into()))?;
let labels = &axes
.categories(1)
.expect("prepared Waterfall categories")
.raw;
let range = selected_ranges.map_or_else(
|| {
chart
.x_axis_spec()
.window
.map_or(axes.ranges()[0], crate::layout::RawWindow::pair)
},
|ranges| ranges[0],
);
let panel = PixelRect::new(0.0, width, 0.0, 1.0);
let projection = crate::layout::Projection::new(
range,
selected_ranges.map_or_else(
|| {
chart
.y_axis_spec()
.window
.map_or(axes.ranges()[1], crate::layout::RawWindow::pair)
},
|ranges| ranges[1],
),
panel.as_tuple(),
);
let registered_owner = registered.expect("prepared Waterfall occurrence");
registered_owner.data(&resources)?;
let plan = plan_annotations(
&projection,
panel,
labels.len() as f64,
&marks.selected_totals(&projection)?.totals,
theme,
&crate::layout::fit::ROOT_SCOPE,
)
.map_err(crate::layout::fit::PlanError::into_error)?;
let hard = mark_intrinsic_body_minimum(registered, theme)?.1.max(
crate::orchestrator::root::coordinate_intrinsic(
intrinsic,
&crate::orchestrator::root::intrinsic_inputs(registered, theme, operation)?,
)?
.minimum(crate::orchestrator::registration::axis_tick_labels_visible(
registered, 1,
))
.1,
);
Ok(hard
.max(2.0 * theme.typography.axes.tick_label.font_size * labels.len() as f64)
.max(3.0 * width / 4.0)
+ plan.height)
}
pub(crate) fn prepare(
chart: &crate::builder::PlotDescription,
data: crate::data::PlotData<'_, '_>,
) -> Result<(PreparedWaterfall, Vec<String>), Error> {
let _scientific = crate::operation::scientific_preparation();
let label_col = chart
.x_col()
.ok_or_else(|| Error::Data("waterfall: label column not set".into()))?;
let delta_col = chart
.y_col()
.ok_or_else(|| Error::Data("waterfall: delta column not set".into()))?;
let base = chart
.waterfall_base()
.ok_or_else(|| Error::Data("waterfall: base value not set".into()))?;
let labels = crate::data::strict_strings(data, label_col, "waterfall")?;
let deltas = crate::data::strict_finite_f64(data, delta_col, "waterfall")?;
if labels.is_empty() || labels.len() != deltas.len() {
return Err(Error::Data(
"waterfall: labels and deltas must have equal non-zero lengths".into(),
));
}
if !base.is_finite() {
return Err(Error::Data("waterfall: base value must be finite".into()));
}
data.validate_row_source()?;
let alpha = chart.prepare_alpha(AlphaTarget::Fill, AlphaUnitKind::Observation, &[])?;
let (spans, range) = prepare_spans(base, &deltas, data, &alpha)?;
let running = spans.last().map_or(base, |span| span.end);
let [base_label, terminal_label] = chart.waterfall_labels_spec().map_or_else(
|| {
Ok::<_, Error>([
crate::Text::from(crate::data::source::copy_source_string("base")?),
crate::Text::from(crate::data::source::copy_source_string("total")?),
])
},
|labels| {
let [base, terminal] = labels.contents();
Ok([base.try_copy()?, terminal.try_copy()?])
},
)?;
let total_candidates = [(base, base_label), (running, terminal_label)];
Ok((
PreparedWaterfall {
range,
spans,
total_candidates,
total_variants: crate::data::source::collect_source((0..4).map(|_| Ok(None)))?,
},
labels,
))
}
fn prepare_spans(
base: f64,
deltas: &[f64],
data: crate::data::PlotData<'_, '_>,
alpha: &crate::alpha::PreparedAlpha,
) -> Result<(Vec<WaterfallSpan>, (f64, f64)), Error> {
let mut running = base;
let mut spans = Vec::new();
crate::data::source::reserve_source(&mut spans, deltas.len())?;
let mut range = (base, base);
for (index, delta) in deltas.iter().enumerate() {
let next = running + delta;
if !next.is_finite() {
return Err(Error::Data(
format!(
"waterfall: cumulative endpoint is non-finite at source row {}",
data.source_row(index)
)
.into(),
));
}
range.0 = range.0.min(next);
range.1 = range.1.max(next);
spans.push(WaterfallSpan {
alpha: ObservationAlpha::resolve(data, alpha, index)?,
start: running,
end: next,
delta: *delta,
});
running = next;
}
Ok((spans, range))
}
pub(crate) fn measure(
context: &PlotMeasureContext<'_, '_>,
request: &crate::text::TextRequestContext<'_, '_>,
) -> Result<PlotRenderResult, crate::layout::fit::PlanError> {
let prepared = retained(Some(context.registered))?;
let theme = request;
let labels = &context
.registered
.axes
.categories(1)
.expect("prepared Waterfall categories")
.raw;
let spans = &prepared.spans;
let base = prepared.total_candidates[0].0;
let terminal = prepared.total_candidates[1].0;
let x_range = context.axis_range(crate::layout::AxisSide::Bottom)?;
let panel = context.assignment.local.body;
let y_range = context.axis_range(crate::layout::AxisSide::Left)?;
let annotation_projection = crate::layout::Projection::new(x_range, y_range, panel.as_tuple())
.with_categories([None, Some(labels.len())]);
let selected_totals = prepared.selected_totals(&annotation_projection)?;
let annotations = plan_annotations(
&annotation_projection,
panel,
labels.len() as f64,
&selected_totals.totals,
request,
context.fit_scope,
)?;
let mark_minimum = mark_intrinsic_body_minimum(Some(context.registered), theme)?;
let axes_minimum = crate::orchestrator::root::coordinate_intrinsic(
context.intrinsic(),
&crate::orchestrator::root::intrinsic_inputs(
Some(context.registered),
theme,
context.operation,
)?,
)?
.minimum(crate::orchestrator::registration::axis_tick_labels_visible(
Some(context.registered),
1,
));
if annotations.height > panel.height() - mark_minimum.1.max(axes_minimum.1) {
return Err(context.fit_scope().failure(crate::layout::fit::FitKind::SpecializedGeometry, format!(
"waterfall: total annotations require {:.0}px while preserving the traced category tracks; increase chart height or shorten the configured labels",
annotations.height
)).into());
}
let mut mark_panel = panel;
mark_panel.y1 -= annotations.height;
let axes = context
.registered
.axes
.coordinate()
.ok_or_else(|| Error::Render("Waterfall native axes missing".into()))?;
let source = context.registered.source;
let pair = [axes.axis(source, 0), axes.axis(source, 1)];
let display = &axes
.categories(1)
.ok_or_else(|| Error::Render("Waterfall category display missing".into()))?;
let display = &display.ticks;
let mut pitch = mark_minimum.1 / labels.len() as f64;
let width = context.assignment.local.axis_label_width.max(1.0 / 1024.0);
let tick_appearance = theme.tick_text_appearance(crate::layout::AxisSide::Left);
if crate::orchestrator::registration::axis_tick_labels_visible(Some(context.registered), 1)
&& !tick_appearance.hidden()
&& !tick_appearance.layout.is_some_and(|request| {
request
.instructions()
.visibility
.as_ref()
.is_some_and(crate::text::TextVisibility::reduces)
})
{
let mut heights = crate::data::source::collect_source(display.iter().map(|_| Ok(0.0)))?;
for index in pair[1]
.authored()
.expect("coordinate authored intent")
.category_labels
.indices(display.len())
{
let plan = crate::layout::fit::measured(crate::layout::fit::text(
theme,
&display[index].label,
theme.tick_text_appearance(crate::layout::AxisSide::Left),
width,
PhysicalTextAlignment::End,
"y-axis tick label",
&context
.fit_scope()
.child(crate::layout::AddressRole::AxisLeft, 0)?,
))?;
heights[index] = plan.height() + 2.0 * crate::layout::LABEL_CLEARANCE;
}
let span = crate::layout::category_label_span(
&pair[1]
.authored()
.expect("coordinate authored intent")
.category_labels,
display.len(),
|index| Ok(heights[index]),
)?;
pitch = pitch.max(span / display.len() as f64);
}
let min = crate::layout::kernel::ceil_spatial_quanta(pitch)?;
let preferred = min.max(crate::layout::kernel::ceil_spatial_quanta(
2.0 * theme.typography.axes.tick_label.font_size,
)?);
let specs = crate::data::source::collect_source(labels.iter().map(|_| {
Ok(crate::layout::kernel::TrackSpec {
min,
preferred,
max: None,
flexible: true,
})
}))?;
let bands = crate::layout::interior::tracks::assign(
&specs,
(mark_panel.y0, mark_panel.y1),
0.0,
false,
context.fit_scope(),
)?;
let projection =
crate::layout::Projection::new(x_range, (0.0, labels.len() as f64), mark_panel.as_tuple());
let assigned = context
.axis_pair(crate::orchestrator::assignment::AxisPairScope::Pair)?
.axes;
let x = assigned[0].layout_ticks(
Vec::new(),
&projection,
crate::layout::AxisSide::Bottom,
theme,
context.fit_scope(),
context.registered.axis_numeric_binding(context.operation)?,
)?;
let ticks =
crate::data::source::collect_source(display.iter().zip(&bands).map(|(label, band)| {
Ok(AxisTick::new(
(f64::midpoint(band.0, band.1) - mark_panel.y0) / mark_panel.height()
* labels.len() as f64,
crate::data::source::copy_source_string(&label.label)?,
))
}))?;
let layout = crate::layout::Layout {
projection,
x_axis: crate::layout::Axis {
label: axes.copy_label(context.registered, 0)?,
ticks: x.ticks,
tick_labels_visible: true,
category_labels: pair[0]
.authored()
.expect("coordinate authored intent")
.category_labels
.clone(),
source: x.source,
numeric: x.numeric,
explicit_ticks: pair[0].exact_ticks()?.is_some(),
assigned_tick_width: None,
assigned_cells: None,
},
y_axis: crate::layout::Axis {
label: axes.copy_label(context.registered, 1)?,
ticks,
tick_labels_visible: crate::orchestrator::registration::axis_tick_labels_visible(
Some(context.registered),
1,
),
category_labels: pair[1]
.authored()
.expect("coordinate authored intent")
.category_labels
.clone(),
source: crate::layout::TickSource::SUPPLIED,
numeric: None,
explicit_ticks: false,
assigned_tick_width: Some(width),
assigned_cells: Some(crate::data::source::collect_source(
bands.iter().map(|band| Ok(*band)),
)?),
},
};
let mut bars = Vec::new();
let mut source_rows = Vec::new();
let mut connectors = Vec::new();
let accents = crate::theme::AccentColors::resolve(theme.marks.get_accents(), 2)?;
crate::data::source::reserve_source(&mut bars, spans.len())?;
crate::data::source::reserve_source(&mut source_rows, spans.len())?;
crate::data::source::reserve_source(&mut connectors, spans.len().saturating_sub(1))?;
let geometry = BodyGeometry::new(theme);
for (index, span) in spans.iter().enumerate() {
let (start, end, delta) = (&span.start, &span.end, &span.delta);
let y0 = index as f64 + geometry.low;
let y1 = index as f64 + geometry.high;
let left = layout.projection.project(*start, y0).0;
let right = layout.projection.project(*end, y1).0;
let band = bands[index];
let bottom = band.0 + geometry.low * (band.1 - band.0);
let top = band.0 + geometry.high * (band.1 - band.0);
layout.projection.validate_span(
crate::layout::AxisSide::Bottom,
(*start, *end),
(left, right),
*delta != 0.0,
"waterfall polygon width",
)?;
layout.projection.validate_span(
crate::layout::AxisSide::Left,
(y0, y1),
(bottom, top),
true,
"waterfall polygon height",
)?;
let color = accents.color(usize::from(*delta < 0.0))?;
bars.push((
[
Point2D::new(left, bottom),
Point2D::new(right, bottom),
Point2D::new(right, top),
Point2D::new(left, top),
],
fill_style(
span.alpha.value,
theme
.marks
.get_fills()
.get_bodies()
.get_waterfall_bar()
.backend_style(color),
),
));
source_rows.push(span.alpha.source_row);
if index + 1 < spans.len() {
let x = right;
let from_y = top;
let next = bands[index + 1];
let to_y = next.0 + geometry.low * (next.1 - next.0);
connectors.push((
[Point2D::new(x, from_y), Point2D::new(x, to_y)],
theme
.marks
.get_strokes()
.get_connectors()
.get_waterfall_connector()
.backend_style(),
));
}
}
let references = [base, terminal].map(|value| {
let (x, y0) = layout.projection.project(value, 0.0);
let (_, y1) = layout.projection.project(value, labels.len() as f64);
(
[Point2D::new(x, y0), Point2D::new(x, y1)],
theme
.marks
.get_strokes()
.get_references()
.get_waterfall_reference()
.backend_style(),
)
});
let AnnotationPlan {
items, baselines, ..
} = annotations;
let mut text = Vec::new();
let mut text_targets = Vec::new();
crate::data::source::reserve_source(&mut text, items.len())?;
crate::data::source::reserve_source(&mut text_targets, items.len())?;
for annotation in items {
text_targets.push(annotation.target);
let text_plan = annotation.text_plan;
let mut placement = annotation.placement;
placement.position.x += annotation.x;
placement.position.y +=
layout.projection.panel_box().y1 + annotation.row.map_or(0.0, |row| baselines[row]);
text.push(PlacedText {
placement,
plan: text_plan.translate_paint_region(
annotation.x,
layout.projection.panel_box().y1 + annotation.row.map_or(0.0, |row| baselines[row]),
),
});
}
let mut payload = WaterfallPayload {
clip: layout.projection.panel_box(),
bars,
source_rows,
connectors,
references,
text,
text_targets,
domain_expansions: [None; 2],
};
let mut geometry = crate::render::geometry::GeometrySnapshot::new();
let clip = crate::render::backend::validate_clip_region(payload.clip)?.panel();
for (index, (points, style)) in payload.bars.iter().enumerate() {
geometry.polygon(points, style, Some(clip))?;
if let Some((points, style)) = payload.connectors.get(index) {
geometry.line(points, style, Some(clip))?;
}
}
for (points, style) in &payload.references {
geometry.line(points, style, Some(clip))?;
}
let mut label_ink = crate::render::geometry::GeometrySnapshot::new();
let raw_windows = context.registered.raw_windows();
for (index, text) in payload.text.iter_mut().enumerate() {
let bounds = crate::layout::text::placement::footprint(text.placement, &text.plan)?;
let region = PixelRect::new(
if raw_windows[0].is_some() {
panel.x0
} else {
bounds.x0.min(panel.x0)
},
if raw_windows[0].is_some() {
panel.x1
} else {
bounds.x1.max(panel.x1)
},
mark_panel.y1,
panel.y1,
);
text.plan = crate::layout::text::placement::contain(
text.plan.clone(),
text.placement,
region,
&context.fit_scope().child(payload.text_targets[index], 0)?,
)?;
let mut one = crate::render::geometry::GeometrySnapshot::new();
one.text(text.placement, &text.plan, None)?;
label_ink.append(&one)?;
}
for text in &payload.text {
geometry.text(text.placement, &text.plan, None)?;
}
let mut full = crate::render::geometry::GeometrySnapshot::new();
for (points, style) in &payload.bars {
full.polygon(points, style, None)?;
}
for (points, style) in &payload.connectors {
full.line(points, style, None)?;
}
if let Some(bounds) = full
.bounds()
.iter()
.copied()
.reduce(crate::render::geometry::GeometryBox::union)
{
if bounds.bottom < clip.y0 || bounds.top > clip.y1 {
return Err(context
.fit_scope()
.failure(
crate::layout::fit::FitKind::SpecializedGeometry,
"Waterfall painted bars/connectors exceed their assigned category panel",
)
.into());
}
}
for (points, style) in &payload.references {
full.line(points, style, None)?;
}
if pair[0].can_expand() {
if let Some(bounds) = label_ink
.bounds()
.iter()
.copied()
.reduce(crate::render::geometry::GeometryBox::union)
{
let totals = (
prepared.total_candidates[0]
.0
.min(prepared.total_candidates[1].0),
prepared.total_candidates[0]
.0
.max(prepared.total_candidates[1].0),
);
let requests = crate::layout::interior::automatic_absolute_ink_expansions(
[totals, (0.0, labels.len() as f64)],
&layout.projection,
bounds,
[true, false],
context.fit_scope(),
)?;
payload.domain_expansions = crate::layout::interior::merge_mark_domain_expansions(
payload.domain_expansions,
requests,
);
}
if let Some(bounds) = full
.bounds()
.iter()
.copied()
.reduce(crate::render::geometry::GeometryBox::union)
{
let count = u32::try_from(labels.len()).map_err(|_| {
Error::Render("Waterfall category count exceeds spatial range".into())
})?;
let requests = crate::layout::interior::automatic_absolute_ink_expansions(
[prepared.range, (0.0, f64::from(count))],
&layout.projection,
bounds,
[true, false],
context.fit_scope(),
)?;
payload.domain_expansions = crate::layout::interior::merge_mark_domain_expansions(
payload.domain_expansions,
requests,
);
}
}
let mut result = PlotRenderResult::new(
layout,
crate::orchestrator::registration::guide_descriptor(Some(context.registered))?,
);
result.numeric_presentation = Some(selected_totals.numeric.clone());
result.y_domain = crate::spec::AxisDomain::Categorical;
result.y_tick_keys =
Some(crate::data::source::collect_source(labels.iter().map(
|label| crate::data::source::copy_source_string(label),
))?);
result.axes = Some(result.layout.measure_axes_with_inputs(
theme,
context.fit_scope(),
context.semantic_inputs(crate::orchestrator::assignment::AxisPairScope::Pair)?,
|| crate::layout::CoordinateLayoutInputs::new(theme),
)?);
result.producer_text =
crate::data::source::collect_source(payload.text.iter().map(|text| Ok(text.clone())))?;
result.marks = Some(crate::data::source::source_arc(
crate::layout::interior::SelectedMarkPlan {
payload: crate::layout::interior::MarkPayload::Waterfall(payload),
geometry,
},
)?);
Ok(result)
}
#[derive(Debug)]
pub(crate) struct WaterfallPayload {
clip: PixelRect,
bars: Vec<([Point2D; 4], FillStyle)>,
source_rows: Vec<usize>,
connectors: Vec<([Point2D; 2], LineStyle)>,
references: [([Point2D; 2], LineStyle); 2],
text: Vec<PlacedText>,
text_targets: Vec<crate::layout::AddressRole>,
pub(crate) domain_expansions: [Option<crate::layout::interior::DomainExpansion>; 2],
}
impl WaterfallPayload {
pub(crate) fn observe_sources(
&self,
round: &mut crate::layout::kernel::FeedbackRound,
) -> Result<(), Error> {
round.observe_count(self.source_rows.len())?;
for &row in &self.source_rows {
round.observe_count(row)?;
}
Ok(())
}
pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
with_clip(backend, self.clip, |backend| {
for (index, (points, style)) in self.bars.iter().enumerate() {
backend.draw_polygon(points, style)?;
if let Some((points, style)) = self.connectors.get(index) {
backend.draw_line(points, style)?;
}
}
for (points, style) in &self.references {
backend.draw_line(points, style)?;
}
Ok(())
})?;
for text in &self.text {
text.draw(backend)?;
}
Ok(())
}
}
struct Annotation {
target: crate::layout::AddressRole,
text_plan: ResolvedTextPlan,
x: f64,
placement: PlannedTextPlacement,
row: Option<usize>,
}
struct AnnotationPlan {
items: Vec<Annotation>,
height: f64,
baselines: Vec<f64>,
}
struct ShelfRow {
intervals: Vec<(i64, i64)>,
above: i64,
below: i64,
}
fn total_shelf_size(
candidates: &[(f64, Option<crate::Text>); 2],
theme: &crate::text::TextRequestContext<'_, '_>,
) -> f64 {
candidates
.iter()
.filter_map(|(_, text)| text.as_ref())
.map(|text| {
text.appearance(&theme.typography.annotations.waterfall_total)
.theme
.get_font_size()
})
.reduce(f64::max)
.unwrap_or(theme.typography.annotations.waterfall_total.get_font_size())
}
fn plan_annotations(
projection: &crate::layout::Projection,
panel: PixelRect,
source_y: f64,
candidates: &[(f64, Option<crate::Text>); 2],
request: &crate::text::TextRequestContext<'_, '_>,
scope: &crate::layout::fit::FitScope,
) -> Result<AnnotationPlan, crate::layout::fit::PlanError> {
#[cfg(test)]
geometry_tests::ANNOTATION_PLAN_CALLS.with(|calls| calls.set(calls.get() + 1));
let frame = crate::layout::Layout {
projection: projection.clone(),
..crate::layout::Layout::envelope(panel)
};
let appearance = request.theme.clone();
let request = crate::text::TextRequestContext {
theme: &appearance,
..*request
};
let directional = request.reproject_text(&frame);
let theme = &directional;
let mut rows: Vec<ShelfRow> = Vec::new();
let mut items = Vec::new();
let mut miss = None;
crate::data::source::reserve_source(&mut items, 2)?;
crate::data::source::reserve_source(&mut rows, 2)?;
let metrics = theme
.annotations
.get_waterfall_shelf()
.lengths(total_shelf_size(candidates, theme))?;
let gap = metrics
.gap
.round(crate::layout::kernel::SpatialRounding::Ceil)?
.quanta();
let eligible = crate::data::source::collect_source(
candidates
.iter()
.enumerate()
.filter(|(_, (value, text))| {
text.is_some() && projection.contains_data(*value, source_y)
})
.map(|(index, _)| Ok(index)),
)?;
for (index, (value, text)) in candidates.iter().enumerate() {
let Some(text) = text else { continue };
let target = if index == 0 {
crate::layout::AddressRole::WaterfallBaseLabel
} else {
crate::layout::AddressRole::WaterfallTerminalLabel
};
if !projection.contains_data(*value, source_y) {
continue;
}
let appearance = text.appearance(
crate::text::TextAppearance::from(&theme.typography.annotations.waterfall_total)
.layout(theme.text_layouts.total.as_ref()),
);
let owner = if index == 0 {
"waterfall base annotation"
} else {
"waterfall terminal annotation"
};
let text_plan =
crate::layout::fit::measured(crate::layout::text::request::measure_occurrence(
theme,
text.as_str(),
appearance,
i64::MAX,
text.resolved_alignment(crate::text::TextAlignment::Center)
.into(),
owner,
scope,
(index, &eligible),
))?;
let width = text_plan.occupied_size().0;
let required_width = metrics
.padding
.horizontal()
.add_pixels(width)?
.pixels_rounded(crate::layout::kernel::SpatialRounding::Ceil)?;
if required_width > panel.width()
&& text_plan
.request
.as_ref()
.and_then(|request| request.instructions().overflow.as_ref())
.is_none_or(|overflow| overflow.failure == crate::text::TextFailure::Error)
{
crate::layout::fit::FitFailure::retain_least(&mut miss, scope.child(if index == 0 { crate::layout::AddressRole::WaterfallBaseLabel } else { crate::layout::AddressRole::WaterfallTerminalLabel }, 0)?.failure(crate::layout::fit::FitKind::Text, format!(
"waterfall: total annotation {:?} requires {:.0}px but only {:.0}px is available; increase chart width or shorten the configured label",
text.as_str(),
required_width,
panel.width()
)));
continue;
}
let (projected_x, _) = projection.project(*value, source_y);
let x_quanta = crate::layout::kernel::nearest_spatial_quanta(projected_x)?;
let half = crate::render::backend::nearest_even_text_half(text_plan.width_quanta)
.ok_or_else(|| Error::Render("Waterfall text half width overflow".into()))?;
let (anchor, offset) = match text_plan.style.alignment {
PhysicalTextAlignment::Start => (TextAnchor::Start, -half),
PhysicalTextAlignment::Center => (TextAnchor::Middle, 0),
PhysicalTextAlignment::End => (TextAnchor::End, text_plan.width_quanta - half),
};
let x = x_quanta as f64 / 1024.0;
let explicit = text_plan
.request
.as_ref()
.is_some_and(|request| request.instructions().anchor.is_some());
let placement = crate::layout::text::placement::resolve(
PlannedTextPlacement::baseline(
Point2D::new(
if explicit {
0.0
} else {
offset as f64 / 1024.0
},
0.0,
),
if explicit { TextAnchor::Middle } else { anchor },
0.0,
),
&text_plan,
None,
)?;
if text_plan.lines.is_empty() {
items.push(Annotation {
target,
text_plan,
x,
placement,
row: None,
});
continue;
}
let footprint = crate::layout::text::placement::footprint(placement, &text_plan)?;
let above = crate::layout::kernel::ceil_spatial_quanta(footprint.y1.max(0.0))?;
let below = crate::layout::kernel::ceil_spatial_quanta((-footprint.y0).max(0.0))?;
let lower = crate::layout::kernel::nearest_spatial_quanta(footprint.x0)?;
let upper = crate::layout::kernel::ceil_spatial_quanta(footprint.x1)?;
let bounds = (
x_quanta
.checked_add(lower)
.ok_or_else(|| Error::Render("Waterfall label left edge overflow".into()))?,
x_quanta
.checked_add(upper)
.ok_or_else(|| Error::Render("Waterfall label right edge overflow".into()))?,
);
let mut row = rows.len();
for (candidate, occupied) in rows.iter().enumerate() {
let mut fits = true;
for &(left, right) in &occupied.intervals {
if i128::from(bounds.1) + i128::from(gap) > i128::from(left)
&& i128::from(right) + i128::from(gap) > i128::from(bounds.0)
{
fits = false;
break;
}
}
if fits {
row = candidate;
break;
}
}
if row == rows.len() {
rows.push(ShelfRow {
intervals: Vec::new(),
above: 0,
below: 0,
});
}
crate::data::source::reserve_source(&mut rows[row].intervals, 1)?;
rows[row].intervals.push(bounds);
rows[row].above = rows[row].above.max(above);
rows[row].below = rows[row].below.max(below);
items.push(Annotation {
target,
text_plan,
x,
placement,
row: Some(row),
});
}
if let Some(failure) = miss {
return Err(failure.into());
}
let mut baselines = Vec::new();
crate::data::source::reserve_source(&mut baselines, rows.len())?;
let mut height = metrics.padding.bottom.times(u32::from(!rows.is_empty()));
for (index, row) in rows.iter().enumerate() {
let baseline =
height.add_quanta(crate::layout::kernel::LayoutScalar::from_quanta(row.below))?;
baselines
.push(baseline.pixels_rounded(crate::layout::kernel::SpatialRounding::NearestEven)?);
height = baseline
.add_quanta(crate::layout::kernel::LayoutScalar::from_quanta(row.above))?
.add_length(if index + 1 == rows.len() {
&metrics.padding.top
} else {
&metrics.row_gap
});
}
let height = height.pixels_rounded(crate::layout::kernel::SpatialRounding::Ceil)?;
let mut text = crate::data::source::collect_source(items.iter().map(|item| {
let mut placement = item.placement;
placement.position.x += item.x;
placement.position.y += item.row.map_or(0.0, |row| baselines[row]);
Ok(PlacedText {
placement,
plan: item.text_plan.clone(),
})
}))?;
let indices = crate::data::source::collect_source(items.iter().map(|item| {
Ok(usize::from(
item.target == crate::layout::AddressRole::WaterfallTerminalLabel,
))
}))?;
crate::layout::text::font_fit::uniform_placed(theme, &mut text, scope)?;
crate::layout::text::visibility::apply(
&mut text,
&indices,
PixelRect::new(panel.x0, panel.x1, 0.0, height),
false,
scope,
)?;
for (item, text) in items.iter_mut().zip(text) {
item.text_plan = text
.plan
.translate_paint_region(-item.x, -item.row.map_or(0.0, |row| baselines[row]));
}
Ok(AnnotationPlan {
items,
height,
baselines,
})
}