use crate::appearance::{Appearance, MarkerStyle, TypeScale};
use crate::error::Error;
use crate::host::{ClipboardPayload, HostProjection, HostText};
use crate::layout::{CellBox, HitKind, HitMap, MAX_PIXMAP_AXIS};
use crate::model::{CellValue, Column, ColumnId, Grid, Row, RowId};
use crate::raster::Pixmap;
use crate::surface::{Frame, FrameRequest, Surface};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SeriesId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SeriesPoint {
pub x: f64,
pub y: f64,
}
impl SeriesPoint {
#[must_use]
pub const fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Series {
pub id: SeriesId,
pub name: String,
pub points: Vec<SeriesPoint>,
}
impl Series {
#[must_use]
pub fn new(id: u32, name: impl Into<String>, points: Vec<SeriesPoint>) -> Self {
Self {
id: SeriesId(id),
name: name.into(),
points,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SeriesLayout {
series: Vec<Series>,
}
impl SeriesLayout {
#[must_use]
pub fn new() -> Self {
Self { series: Vec::new() }
}
pub fn try_new(series: Vec<Series>) -> Result<Self, Error> {
if series.is_empty() {
return Err(Error::InvalidGrid("at least one series is required"));
}
Ok(Self { series })
}
#[must_use]
pub fn series(&self) -> &[Series] {
&self.series
}
pub fn render(&self, surface: &Surface, request: &FrameRequest) -> Result<Frame, Error> {
surface.render_series(self, request)
}
pub fn render_scatter(
&self,
surface: &Surface,
request: &FrameRequest,
) -> Result<Frame, Error> {
surface.render_scatter(self, request)
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum PlotKind {
Line,
Scatter,
}
pub(crate) fn render_timeseries(
surface: &Surface,
layout: &SeriesLayout,
request: &FrameRequest,
) -> Result<Frame, Error> {
render_plot(surface, layout, request, PlotKind::Line)
}
pub(crate) fn render_scatter_plot(
surface: &Surface,
layout: &SeriesLayout,
request: &FrameRequest,
) -> Result<Frame, Error> {
render_plot(surface, layout, request, PlotKind::Scatter)
}
fn render_plot(
surface: &Surface,
layout: &SeriesLayout,
request: &FrameRequest,
kind: PlotKind,
) -> Result<Frame, Error> {
if layout.series.is_empty() {
return Err(Error::InvalidGrid("at least one series is required"));
}
let viewed_series = surface.lens().apply_series(&layout.series);
let placeholder = surface.lens().style.glyph_str();
let Appearance {
theme,
type_scale: scale,
chart: style,
} = surface.appearance();
let vp = request.viewport;
let pixmap_w = vp.width.clamp(1, MAX_PIXMAP_AXIS);
let pixmap_h = vp.height.clamp(1, MAX_PIXMAP_AXIS);
let mut pm = Pixmap::new(pixmap_w, pixmap_h, theme.background)?;
let left = scale.plot_left();
let right = scale.pad();
let top: u32 = if request.caption.is_some() {
scale.header_height()
} else {
scale.pad()
};
let bottom = scale.plot_bottom();
let plot_x0 = left;
let plot_y0 = top;
let plot_w = pixmap_w.saturating_sub(left.saturating_add(right)).max(8);
let plot_h = pixmap_h.saturating_sub(top.saturating_add(bottom)).max(8);
if let Some(caption) = &request.caption {
pm.text_scaled(
scale.pad(),
scale.pixel(),
caption,
theme.accent,
pixmap_w.saturating_sub(scale.pad()),
scale,
);
}
let (xmin, xmax, ymin, ymax) = bounds(&viewed_series);
let ntick = usize::from(style.tick_count.max(2));
let (xmin, xmax, xticks) = if style.nice_ticks {
nice_axis(xmin, xmax, ntick)
} else {
(xmin, xmax, axis_ticks(xmin, xmax, ntick))
};
let (ymin, ymax, yticks) = if style.nice_ticks {
nice_axis(ymin, ymax, ntick)
} else {
(ymin, ymax, axis_ticks(ymin, ymax, ntick))
};
pm.fill_rect(plot_x0, plot_y0, plot_w, plot_h, style.plot_background);
pm.hline(plot_x0, plot_y0, plot_w, theme.grid);
pm.hline(
plot_x0,
plot_y0.saturating_add(plot_h.saturating_sub(1)),
plot_w,
theme.grid,
);
pm.vline(plot_x0, plot_y0, plot_h, theme.grid);
pm.vline(
plot_x0.saturating_add(plot_w.saturating_sub(1)),
plot_y0,
plot_h,
theme.grid,
);
let mut buf = String::with_capacity(16);
let mut boxes = Vec::new();
let grid_line = theme.grid;
for (i, t) in yticks.iter().enumerate() {
let py = map_y(*t, ymin, ymax, plot_y0, plot_h);
pm.hline(plot_x0, py, plot_w, grid_line);
buf.clear();
fmt_num(*t, &mut buf);
let tw = crate::font::measure(&buf, scale).saturating_add(4);
let tx = plot_x0.saturating_sub(tw.min(plot_x0));
pm.text_scaled(
tx,
py.saturating_sub(scale.pixel() * 3),
&buf,
theme.text,
tw,
scale,
);
boxes.push(CellBox {
row_index: None,
col_index: i as u32,
row: RowId(0),
col: ColumnId(i as u32),
x: tx,
y: py.saturating_sub(4),
w: tw.max(8),
h: scale.row_height().clamp(12, 16),
header: false,
kind: HitKind::TickY,
});
}
for (i, t) in xticks.iter().enumerate() {
let px = map_x(*t, xmin, xmax, plot_x0, plot_w);
pm.vline(px, plot_y0, plot_h, grid_line);
buf.clear();
fmt_num(*t, &mut buf);
let tw = crate::font::measure(&buf, scale).saturating_add(2);
let ty = plot_y0.saturating_add(plot_h).saturating_add(4);
pm.text_scaled(px.saturating_sub(tw / 2), ty, &buf, theme.text, tw, scale);
boxes.push(CellBox {
row_index: None,
col_index: i as u32,
row: RowId(0),
col: ColumnId(i as u32),
x: px.saturating_sub(tw / 2),
y: ty,
w: tw.max(8),
h: scale.row_height().clamp(10, 18),
header: false,
kind: HitKind::TickX,
});
}
let baseline_y = plot_y0.saturating_add(plot_h.saturating_sub(1));
for (si, series) in viewed_series.iter().enumerate() {
let color = style.series[si % style.series.len()];
let mut prev: Option<(u32, u32)> = None;
for (pi, pt) in series.points.iter().enumerate() {
let px = map_x(pt.x, xmin, xmax, plot_x0, plot_w);
let py = map_y(pt.y, ymin, ymax, plot_y0, plot_h);
if kind == PlotKind::Line {
if let Some((ax, ay)) = prev {
if style.area_fill {
fill_area_segment(
&mut pm,
ax,
ay,
px,
py,
baseline_y,
plot_x0,
plot_x0 + plot_w,
color,
style.area_alpha,
);
}
pm.stroke_aa(
f64::from(ax),
f64::from(ay),
f64::from(px),
f64::from(py),
color,
style.stroke_px,
);
}
}
prev = Some((px, py));
let hit_w = 8u32.max(scale.pixel() * 3);
boxes.push(CellBox {
row_index: Some(pi as u32),
col_index: si as u32,
row: RowId(pi as u32),
col: ColumnId(series.id.0),
x: px.saturating_sub(hit_w / 2),
y: py.saturating_sub(hit_w / 2),
w: hit_w,
h: hit_w,
header: false,
kind: HitKind::Sample,
});
if kind == PlotKind::Scatter {
let r = 2u32.max(scale.pixel());
paint_marker(&mut pm, px, py, color, r);
} else if matches!(style.markers, MarkerStyle::Last) && pi + 1 == series.points.len() {
pm.fill_rect(px.saturating_sub(2), py.saturating_sub(2), 5, 5, color);
}
}
let legend_y = plot_y0.saturating_add(4);
let legend_x = plot_x0
.saturating_add(6)
.saturating_add((si as u32).saturating_mul(scale.advance() * 8 + 16));
pm.fill_rect(legend_x, legend_y, 10, 4, color);
pm.text_scaled(
legend_x.saturating_add(14),
legend_y.saturating_sub(1),
&series.name,
theme.text,
scale.advance() * 8,
scale,
);
}
let mut nearest: Option<(usize, usize, u32, u32, f64)> = None;
if let Some(p) = request.pointer {
if p.x >= plot_x0 && p.y >= plot_y0 && p.x < plot_x0 + plot_w && p.y < plot_y0 + plot_h {
for (si, series) in viewed_series.iter().enumerate() {
for (pi, pt) in series.points.iter().enumerate() {
let px = map_x(pt.x, xmin, xmax, plot_x0, plot_w);
let py = map_y(pt.y, ymin, ymax, plot_y0, plot_h);
let dx = i64::from(p.x) - i64::from(px);
let dy = i64::from(p.y) - i64::from(py);
let d2 = (dx * dx + dy * dy) as f64;
let better = match nearest {
None => true,
Some((_, _, _, _, best)) => d2 < best,
};
if better {
nearest = Some((si, pi, px, py, d2));
}
}
}
}
}
if let Some((_, _, px, py, _)) = nearest {
pm.stroke_aa(
f64::from(px),
f64::from(plot_y0),
f64::from(px),
f64::from(plot_y0 + plot_h),
theme.crosshair,
1,
);
pm.stroke_aa(
f64::from(plot_x0),
f64::from(py),
f64::from(plot_x0 + plot_w),
f64::from(py),
theme.crosshair,
1,
);
if matches!(style.markers, MarkerStyle::Hover | MarkerStyle::Last) {
pm.fill_rect(
px.saturating_sub(3),
py.saturating_sub(3),
7,
7,
theme.crosshair,
);
}
}
let hits = HitMap { boxes };
let tooltip_png = match (request.pointer, nearest) {
(Some(_), Some((si, pi, _, _, _))) => {
series_tooltip(&viewed_series, si, pi, placeholder, theme, scale)?
}
_ => None,
};
let viewed = series_to_grid(&viewed_series)?;
let n = viewed.rows.len() as u32;
let host = series_host(surface, request, &viewed_series);
let png = pm.to_png()?;
Ok(Frame {
png,
hits,
host,
tooltip_png,
viewed,
content_width: pixmap_w,
content_height: pixmap_h,
visible_row_start: 0,
visible_row_end: n,
})
}
fn series_tooltip(
series: &[Series],
si: usize,
pi: usize,
placeholder: &str,
theme: crate::theme::Theme,
scale: TypeScale,
) -> Result<Option<Vec<u8>>, Error> {
let Some(s) = series.get(si) else {
return Ok(None);
};
let Some(pt) = s.points.get(pi) else {
return Ok(None);
};
let mut label = String::new();
label.push_str(&s.name);
label.push_str(": ");
fmt_num(pt.y, &mut label);
if s.points.is_empty() {
label.push_str(placeholder);
}
let tw = crate::font::measure(&label, scale)
.saturating_add(16)
.max(48);
let th = scale.row_height().saturating_add(6).max(22);
let mut pm = Pixmap::new(tw.max(40), th, theme.tooltip)?;
pm.fill_rect(0, 0, pm.width(), 1, theme.accent);
pm.text_scaled(
6,
scale.pixel() * 2,
&label,
theme.text,
pm.width().saturating_sub(8),
scale,
);
Ok(Some(pm.to_png()?))
}
fn series_host(surface: &Surface, request: &FrameRequest, series: &[Series]) -> HostProjection {
if surface.mode().is_sealed() {
return HostProjection::sealed();
}
let mut text_nodes = Vec::new();
if let Some(caption) = &request.caption {
text_nodes.push(HostText {
kind: "caption",
text: caption.clone(),
});
}
let mut tsv = String::from("series\tx\ty\n");
for s in series {
for p in &s.points {
tsv.push_str(&s.name);
tsv.push('\t');
fmt_num(p.x, &mut tsv);
tsv.push('\t');
fmt_num(p.y, &mut tsv);
tsv.push('\n');
}
}
HostProjection {
text_nodes,
clipboard: Some(ClipboardPayload::Tsv(tsv)),
}
}
fn series_to_grid(series: &[Series]) -> Result<Grid, Error> {
let columns = vec![
Column::new(0, "series"),
Column::new(1, "x"),
Column::new(2, "y"),
];
let mut rows = Vec::new();
let mut id = 0u32;
for s in series {
for p in &s.points {
let mut xs = String::new();
let mut ys = String::new();
fmt_num(p.x, &mut xs);
fmt_num(p.y, &mut ys);
rows.push(Row::new(
id,
vec![
CellValue::text(s.name.clone()),
CellValue::text(xs),
CellValue::text(ys),
],
));
id += 1;
}
}
if rows.is_empty() {
rows.push(Row::new(
0,
vec![
CellValue::Redacted,
CellValue::Redacted,
CellValue::Redacted,
],
));
}
Grid::try_new(columns, rows)
}
fn bounds(series: &[Series]) -> (f64, f64, f64, f64) {
let mut xmin = f64::INFINITY;
let mut xmax = f64::NEG_INFINITY;
let mut ymin = f64::INFINITY;
let mut ymax = f64::NEG_INFINITY;
for s in series {
for p in &s.points {
xmin = xmin.min(p.x);
xmax = xmax.max(p.x);
ymin = ymin.min(p.y);
ymax = ymax.max(p.y);
}
}
if !xmin.is_finite() {
return (0.0, 1.0, 0.0, 1.0);
}
if (xmax - xmin).abs() < 1e-9 {
xmax = xmin + 1.0;
}
if (ymax - ymin).abs() < 1e-9 {
ymax = ymin + 1.0;
}
(xmin, xmax, ymin, ymax)
}
fn axis_ticks(min: f64, max: f64, n: usize) -> Vec<f64> {
let n = n.max(2);
let span = max - min;
(0..n)
.map(|i| min + span * (i as f64) / ((n - 1) as f64))
.collect()
}
fn nice_num(x: f64, round: bool) -> f64 {
if x <= 0.0 || !x.is_finite() {
return 1.0;
}
let exp = x.log10().floor();
let f = x / 10f64.powf(exp);
let nf = if round {
if f < 1.5 {
1.0
} else if f < 3.0 {
2.0
} else if f < 7.0 {
5.0
} else {
10.0
}
} else if f <= 1.0 {
1.0
} else if f <= 2.0 {
2.0
} else if f <= 5.0 {
5.0
} else {
10.0
};
nf * 10f64.powf(exp)
}
fn nice_axis(min: f64, max: f64, ntick: usize) -> (f64, f64, Vec<f64>) {
let ntick = ntick.max(2);
let range = nice_num(max - min, false);
let step = nice_num(range / (ntick as f64 - 1.0), true).max(1e-9);
let lo = (min / step).floor() * step;
let hi = (max / step).ceil() * step;
let mut ticks = Vec::new();
let mut x = lo;
let mut guard = 0u32;
while x <= hi + step * 0.5 && guard < 32 {
ticks.push(x);
x += step;
guard += 1;
}
if ticks.len() < 2 {
ticks = axis_ticks(min, max, ntick);
return (min, max, ticks);
}
(lo, hi, ticks)
}
#[allow(clippy::too_many_arguments)]
fn fill_area_segment(
pm: &mut Pixmap,
x0: u32,
y0: u32,
x1: u32,
y1: u32,
baseline: u32,
clip_l: u32,
clip_r: u32,
color: crate::theme::Rgb,
alpha: u8,
) {
let (xa, xb, ya, yb) = if x0 <= x1 {
(x0, x1, y0, y1)
} else {
(x1, x0, y1, y0)
};
if xb == xa {
return;
}
let dx = f64::from(xb - xa);
for x in xa..=xb {
if x < clip_l || x >= clip_r {
continue;
}
let t = f64::from(x - xa) / dx;
let y = (f64::from(ya) + (f64::from(yb) - f64::from(ya)) * t) as u32;
let (top, bot) = if y < baseline {
(y, baseline)
} else {
(baseline, y)
};
for yy in top..=bot {
pm.blend(x, yy, color, alpha);
}
}
}
fn map_x(x: f64, xmin: f64, xmax: f64, x0: u32, w: u32) -> u32 {
let t = ((x - xmin) / (xmax - xmin)).clamp(0.0, 1.0);
x0 + ((t * f64::from(w.saturating_sub(1))) as u32)
}
fn map_y(y: f64, ymin: f64, ymax: f64, y0: u32, h: u32) -> u32 {
let t = ((y - ymin) / (ymax - ymin)).clamp(0.0, 1.0);
y0 + (((1.0 - t) * f64::from(h.saturating_sub(1))) as u32)
}
fn paint_marker(pm: &mut Pixmap, px: u32, py: u32, color: crate::theme::Rgb, r: u32) {
let d = r.saturating_mul(2).saturating_add(1);
pm.fill_rect(px.saturating_sub(r), py.saturating_sub(r), d, d, color);
}
pub(crate) fn fmt_num(v: f64, out: &mut String) {
use std::fmt::Write as _;
let _ = write!(out, "{v:.2}");
while out.contains('.') && out.ends_with('0') {
out.pop();
}
if out.ends_with('.') {
out.pop();
}
}