use crate::error::Error;
use crate::host::{ClipboardPayload, HostProjection, HostText};
use crate::layout::{CellBox, HitKind, HitMap, MAX_PIXMAP_AXIS, PAD};
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> {
Err(Error::UnsupportedLayout("scatter"))
}
}
pub(crate) fn render_timeseries(
surface: &Surface,
layout: &SeriesLayout,
request: &FrameRequest,
) -> 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 theme = surface.theme();
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 = 52u32;
let right = 10u32;
let top: u32 = if request.caption.is_some() { 18 } else { 10 };
let bottom = 22u32;
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(PAD, 4, caption, theme.accent, pixmap_w.saturating_sub(PAD));
}
let (xmin, xmax, ymin, ymax) = bounds(&viewed_series);
let xticks = axis_ticks(xmin, xmax, 5);
let yticks = axis_ticks(ymin, ymax, 5);
pm.fill_rect(plot_x0, plot_y0, plot_w, plot_h, theme.header);
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();
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, theme.grid);
buf.clear();
fmt_num(*t, &mut buf);
let tw = crate::font::measure(&buf).saturating_add(4);
let tx = plot_x0.saturating_sub(tw.min(plot_x0));
pm.text(tx, py.saturating_sub(3), &buf, theme.text, tw);
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: 12,
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, theme.grid);
buf.clear();
fmt_num(*t, &mut buf);
let tw = crate::font::measure(&buf).saturating_add(2);
let ty = plot_y0.saturating_add(plot_h).saturating_add(4);
pm.text(px.saturating_sub(tw / 2), ty, &buf, theme.text, tw);
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: 10,
header: false,
kind: HitKind::TickX,
});
}
let palette = [theme.series, theme.accent, theme.crosshair];
for (si, series) in viewed_series.iter().enumerate() {
let color = palette[si % palette.len()];
let mut prev: Option<(i32, i32)> = 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);
let xi = px as i32;
let yi = py as i32;
if let Some((ax, ay)) = prev {
pm.line(ax, ay, xi, yi, color);
}
prev = Some((xi, yi));
let hit_w = 6u32;
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,
});
}
let legend_y = plot_y0.saturating_add(4);
let legend_x = plot_x0
.saturating_add(6)
.saturating_add((si as u32).saturating_mul(80));
pm.fill_rect(legend_x, legend_y, 8, 4, color);
pm.text(
legend_x.saturating_add(12),
legend_y.saturating_sub(1),
&series.name,
theme.text,
70,
);
}
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.vline(px, plot_y0, plot_h, theme.crosshair);
pm.hline(plot_x0, py, plot_w, theme.crosshair);
pm.fill_rect(
px.saturating_sub(2),
py.saturating_sub(2),
5,
5,
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)?
}
_ => 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,
) -> 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).saturating_add(16).max(48);
let mut pm = Pixmap::new(tw.max(40), 22, theme.tooltip)?;
pm.fill_rect(0, 0, pm.width(), 1, theme.accent);
pm.text(6, 7, &label, theme.text, pm.width().saturating_sub(8));
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 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 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();
}
}