Skip to main content

sealed_surface/
chart.rs

1//! Timeseries layout on the sealed painter (no JS series, no SVG text).
2
3use crate::appearance::{Appearance, MarkerStyle, TypeScale};
4use crate::error::Error;
5use crate::host::{ClipboardPayload, HostProjection, HostText};
6use crate::layout::{CellBox, HitKind, HitMap, MAX_PIXMAP_AXIS};
7use crate::model::{CellValue, Column, ColumnId, Grid, Row, RowId};
8use crate::raster::Pixmap;
9use crate::surface::{Frame, FrameRequest, Surface};
10
11/// Identifier for a series. Opaque to the host.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub struct SeriesId(pub u32);
14
15/// One sample. `x` is the independent axis (time or category index).
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub struct SeriesPoint {
18    /// Independent axis.
19    pub x: f64,
20    /// Dependent axis.
21    pub y: f64,
22}
23
24impl SeriesPoint {
25    /// Construct.
26    #[must_use]
27    pub const fn new(x: f64, y: f64) -> Self {
28        Self { x, y }
29    }
30}
31
32/// Named polyline.
33#[derive(Debug, Clone, PartialEq)]
34pub struct Series {
35    /// Opaque id.
36    pub id: SeriesId,
37    /// Legend / schema label. Painted as glyphs. Not a datum in sealed host text.
38    pub name: String,
39    /// Samples in x order (caller should sort).
40    pub points: Vec<SeriesPoint>,
41}
42
43impl Series {
44    /// Construct.
45    #[must_use]
46    pub fn new(id: u32, name: impl Into<String>, points: Vec<SeriesPoint>) -> Self {
47        Self {
48            id: SeriesId(id),
49            name: name.into(),
50            points,
51        }
52    }
53}
54
55/// Timeseries or scatter. Same samples; paint encoding differs.
56///
57/// Treemap is [`crate::TreeLayout`] — a different encoding, not a series.
58#[derive(Debug, Clone, Default, PartialEq)]
59pub struct SeriesLayout {
60    series: Vec<Series>,
61}
62
63impl SeriesLayout {
64    /// Empty layout.
65    #[must_use]
66    pub fn new() -> Self {
67        Self { series: Vec::new() }
68    }
69
70    /// One or more series.
71    ///
72    /// # Errors
73    ///
74    /// [`Error::InvalidGrid`] when `series` is empty.
75    pub fn try_new(series: Vec<Series>) -> Result<Self, Error> {
76        if series.is_empty() {
77            return Err(Error::InvalidGrid("at least one series is required"));
78        }
79        Ok(Self { series })
80    }
81
82    /// Series as supplied (pre-lens).
83    #[must_use]
84    pub fn series(&self) -> &[Series] {
85        &self.series
86    }
87
88    /// Paint a timeseries on `surface` (same PNG / host contract as tables).
89    ///
90    /// # Errors
91    ///
92    /// Raster failure or empty layout.
93    pub fn render(&self, surface: &Surface, request: &FrameRequest) -> Result<Frame, Error> {
94        surface.render_series(self, request)
95    }
96
97    /// Scatter: same samples as [`Self::render`], unconnected markers (no polyline).
98    ///
99    /// # Errors
100    ///
101    /// Raster failure or empty layout.
102    pub fn render_scatter(
103        &self,
104        surface: &Surface,
105        request: &FrameRequest,
106    ) -> Result<Frame, Error> {
107        surface.render_scatter(self, request)
108    }
109}
110
111#[derive(Clone, Copy, PartialEq, Eq)]
112enum PlotKind {
113    Line,
114    Scatter,
115}
116
117pub(crate) fn render_timeseries(
118    surface: &Surface,
119    layout: &SeriesLayout,
120    request: &FrameRequest,
121) -> Result<Frame, Error> {
122    render_plot(surface, layout, request, PlotKind::Line)
123}
124
125pub(crate) fn render_scatter_plot(
126    surface: &Surface,
127    layout: &SeriesLayout,
128    request: &FrameRequest,
129) -> Result<Frame, Error> {
130    render_plot(surface, layout, request, PlotKind::Scatter)
131}
132
133fn render_plot(
134    surface: &Surface,
135    layout: &SeriesLayout,
136    request: &FrameRequest,
137    kind: PlotKind,
138) -> Result<Frame, Error> {
139    if layout.series.is_empty() {
140        return Err(Error::InvalidGrid("at least one series is required"));
141    }
142    let viewed_series = surface.lens().apply_series(&layout.series);
143    let placeholder = surface.lens().style.glyph_str();
144    let Appearance {
145        theme,
146        type_scale: scale,
147        chart: style,
148    } = surface.appearance();
149
150    let vp = request.viewport;
151    let pixmap_w = vp.width.clamp(1, MAX_PIXMAP_AXIS);
152    let pixmap_h = vp.height.clamp(1, MAX_PIXMAP_AXIS);
153    let mut pm = Pixmap::new(pixmap_w, pixmap_h, theme.background)?;
154
155    let left = scale.plot_left();
156    let right = scale.pad();
157    let top: u32 = if request.caption.is_some() {
158        scale.header_height()
159    } else {
160        scale.pad()
161    };
162    let bottom = scale.plot_bottom();
163    let plot_x0 = left;
164    let plot_y0 = top;
165    let plot_w = pixmap_w.saturating_sub(left.saturating_add(right)).max(8);
166    let plot_h = pixmap_h.saturating_sub(top.saturating_add(bottom)).max(8);
167
168    if let Some(caption) = &request.caption {
169        pm.text_scaled(
170            scale.pad(),
171            scale.pixel(),
172            caption,
173            theme.accent,
174            pixmap_w.saturating_sub(scale.pad()),
175            scale,
176        );
177    }
178
179    let (xmin, xmax, ymin, ymax) = bounds(&viewed_series);
180    let ntick = usize::from(style.tick_count.max(2));
181    let (xmin, xmax, xticks) = if style.nice_ticks {
182        nice_axis(xmin, xmax, ntick)
183    } else {
184        (xmin, xmax, axis_ticks(xmin, xmax, ntick))
185    };
186    let (ymin, ymax, yticks) = if style.nice_ticks {
187        nice_axis(ymin, ymax, ntick)
188    } else {
189        (ymin, ymax, axis_ticks(ymin, ymax, ntick))
190    };
191
192    pm.fill_rect(plot_x0, plot_y0, plot_w, plot_h, style.plot_background);
193    pm.hline(plot_x0, plot_y0, plot_w, theme.grid);
194    pm.hline(
195        plot_x0,
196        plot_y0.saturating_add(plot_h.saturating_sub(1)),
197        plot_w,
198        theme.grid,
199    );
200    pm.vline(plot_x0, plot_y0, plot_h, theme.grid);
201    pm.vline(
202        plot_x0.saturating_add(plot_w.saturating_sub(1)),
203        plot_y0,
204        plot_h,
205        theme.grid,
206    );
207
208    let mut buf = String::with_capacity(16);
209    let mut boxes = Vec::new();
210
211    let grid_line = theme.grid;
212    for (i, t) in yticks.iter().enumerate() {
213        let py = map_y(*t, ymin, ymax, plot_y0, plot_h);
214        pm.hline(plot_x0, py, plot_w, grid_line);
215        buf.clear();
216        fmt_num(*t, &mut buf);
217        let tw = crate::font::measure(&buf, scale).saturating_add(4);
218        let tx = plot_x0.saturating_sub(tw.min(plot_x0));
219        pm.text_scaled(
220            tx,
221            py.saturating_sub(scale.pixel() * 3),
222            &buf,
223            theme.text,
224            tw,
225            scale,
226        );
227        boxes.push(CellBox {
228            row_index: None,
229            col_index: i as u32,
230            row: RowId(0),
231            col: ColumnId(i as u32),
232            x: tx,
233            y: py.saturating_sub(4),
234            w: tw.max(8),
235            h: scale.row_height().clamp(12, 16),
236            header: false,
237            kind: HitKind::TickY,
238        });
239    }
240    for (i, t) in xticks.iter().enumerate() {
241        let px = map_x(*t, xmin, xmax, plot_x0, plot_w);
242        pm.vline(px, plot_y0, plot_h, grid_line);
243        buf.clear();
244        fmt_num(*t, &mut buf);
245        let tw = crate::font::measure(&buf, scale).saturating_add(2);
246        let ty = plot_y0.saturating_add(plot_h).saturating_add(4);
247        pm.text_scaled(px.saturating_sub(tw / 2), ty, &buf, theme.text, tw, scale);
248        boxes.push(CellBox {
249            row_index: None,
250            col_index: i as u32,
251            row: RowId(0),
252            col: ColumnId(i as u32),
253            x: px.saturating_sub(tw / 2),
254            y: ty,
255            w: tw.max(8),
256            h: scale.row_height().clamp(10, 18),
257            header: false,
258            kind: HitKind::TickX,
259        });
260    }
261
262    let baseline_y = plot_y0.saturating_add(plot_h.saturating_sub(1));
263    for (si, series) in viewed_series.iter().enumerate() {
264        let color = style.series[si % style.series.len()];
265        let mut prev: Option<(u32, u32)> = None;
266        for (pi, pt) in series.points.iter().enumerate() {
267            let px = map_x(pt.x, xmin, xmax, plot_x0, plot_w);
268            let py = map_y(pt.y, ymin, ymax, plot_y0, plot_h);
269            if kind == PlotKind::Line {
270                if let Some((ax, ay)) = prev {
271                    if style.area_fill {
272                        fill_area_segment(
273                            &mut pm,
274                            ax,
275                            ay,
276                            px,
277                            py,
278                            baseline_y,
279                            plot_x0,
280                            plot_x0 + plot_w,
281                            color,
282                            style.area_alpha,
283                        );
284                    }
285                    pm.stroke_aa(
286                        f64::from(ax),
287                        f64::from(ay),
288                        f64::from(px),
289                        f64::from(py),
290                        color,
291                        style.stroke_px,
292                    );
293                }
294            }
295            prev = Some((px, py));
296            let hit_w = 8u32.max(scale.pixel() * 3);
297            boxes.push(CellBox {
298                row_index: Some(pi as u32),
299                col_index: si as u32,
300                row: RowId(pi as u32),
301                col: ColumnId(series.id.0),
302                x: px.saturating_sub(hit_w / 2),
303                y: py.saturating_sub(hit_w / 2),
304                w: hit_w,
305                h: hit_w,
306                header: false,
307                kind: HitKind::Sample,
308            });
309            if kind == PlotKind::Scatter {
310                let r = 2u32.max(scale.pixel());
311                paint_marker(&mut pm, px, py, color, r);
312            } else if matches!(style.markers, MarkerStyle::Last) && pi + 1 == series.points.len() {
313                pm.fill_rect(px.saturating_sub(2), py.saturating_sub(2), 5, 5, color);
314            }
315        }
316        let legend_y = plot_y0.saturating_add(4);
317        let legend_x = plot_x0
318            .saturating_add(6)
319            .saturating_add((si as u32).saturating_mul(scale.advance() * 8 + 16));
320        pm.fill_rect(legend_x, legend_y, 10, 4, color);
321        pm.text_scaled(
322            legend_x.saturating_add(14),
323            legend_y.saturating_sub(1),
324            &series.name,
325            theme.text,
326            scale.advance() * 8,
327            scale,
328        );
329    }
330
331    let mut nearest: Option<(usize, usize, u32, u32, f64)> = None;
332    if let Some(p) = request.pointer {
333        if p.x >= plot_x0 && p.y >= plot_y0 && p.x < plot_x0 + plot_w && p.y < plot_y0 + plot_h {
334            for (si, series) in viewed_series.iter().enumerate() {
335                for (pi, pt) in series.points.iter().enumerate() {
336                    let px = map_x(pt.x, xmin, xmax, plot_x0, plot_w);
337                    let py = map_y(pt.y, ymin, ymax, plot_y0, plot_h);
338                    let dx = i64::from(p.x) - i64::from(px);
339                    let dy = i64::from(p.y) - i64::from(py);
340                    let d2 = (dx * dx + dy * dy) as f64;
341                    let better = match nearest {
342                        None => true,
343                        Some((_, _, _, _, best)) => d2 < best,
344                    };
345                    if better {
346                        nearest = Some((si, pi, px, py, d2));
347                    }
348                }
349            }
350        }
351    }
352
353    if let Some((_, _, px, py, _)) = nearest {
354        pm.stroke_aa(
355            f64::from(px),
356            f64::from(plot_y0),
357            f64::from(px),
358            f64::from(plot_y0 + plot_h),
359            theme.crosshair,
360            1,
361        );
362        pm.stroke_aa(
363            f64::from(plot_x0),
364            f64::from(py),
365            f64::from(plot_x0 + plot_w),
366            f64::from(py),
367            theme.crosshair,
368            1,
369        );
370        if matches!(style.markers, MarkerStyle::Hover | MarkerStyle::Last) {
371            pm.fill_rect(
372                px.saturating_sub(3),
373                py.saturating_sub(3),
374                7,
375                7,
376                theme.crosshair,
377            );
378        }
379    }
380
381    let hits = HitMap { boxes };
382    let tooltip_png = match (request.pointer, nearest) {
383        (Some(_), Some((si, pi, _, _, _))) => {
384            series_tooltip(&viewed_series, si, pi, placeholder, theme, scale)?
385        }
386        _ => None,
387    };
388
389    let viewed = series_to_grid(&viewed_series)?;
390    let n = viewed.rows.len() as u32;
391    let host = series_host(surface, request, &viewed_series);
392
393    let png = pm.to_png()?;
394    Ok(Frame {
395        png,
396        hits,
397        host,
398        tooltip_png,
399        viewed,
400        content_width: pixmap_w,
401        content_height: pixmap_h,
402        visible_row_start: 0,
403        visible_row_end: n,
404    })
405}
406
407fn series_tooltip(
408    series: &[Series],
409    si: usize,
410    pi: usize,
411    placeholder: &str,
412    theme: crate::theme::Theme,
413    scale: TypeScale,
414) -> Result<Option<Vec<u8>>, Error> {
415    let Some(s) = series.get(si) else {
416        return Ok(None);
417    };
418    let Some(pt) = s.points.get(pi) else {
419        return Ok(None);
420    };
421    let mut label = String::new();
422    label.push_str(&s.name);
423    label.push_str(": ");
424    fmt_num(pt.y, &mut label);
425    if s.points.is_empty() {
426        label.push_str(placeholder);
427    }
428    let tw = crate::font::measure(&label, scale)
429        .saturating_add(16)
430        .max(48);
431    let th = scale.row_height().saturating_add(6).max(22);
432    let mut pm = Pixmap::new(tw.max(40), th, theme.tooltip)?;
433    pm.fill_rect(0, 0, pm.width(), 1, theme.accent);
434    pm.text_scaled(
435        6,
436        scale.pixel() * 2,
437        &label,
438        theme.text,
439        pm.width().saturating_sub(8),
440        scale,
441    );
442    Ok(Some(pm.to_png()?))
443}
444
445fn series_host(surface: &Surface, request: &FrameRequest, series: &[Series]) -> HostProjection {
446    if surface.mode().is_sealed() {
447        return HostProjection::sealed();
448    }
449    let mut text_nodes = Vec::new();
450    if let Some(caption) = &request.caption {
451        text_nodes.push(HostText {
452            kind: "caption",
453            text: caption.clone(),
454        });
455    }
456    let mut tsv = String::from("series\tx\ty\n");
457    for s in series {
458        for p in &s.points {
459            tsv.push_str(&s.name);
460            tsv.push('\t');
461            fmt_num(p.x, &mut tsv);
462            tsv.push('\t');
463            fmt_num(p.y, &mut tsv);
464            tsv.push('\n');
465        }
466    }
467    HostProjection {
468        text_nodes,
469        clipboard: Some(ClipboardPayload::Tsv(tsv)),
470    }
471}
472
473fn series_to_grid(series: &[Series]) -> Result<Grid, Error> {
474    let columns = vec![
475        Column::new(0, "series"),
476        Column::new(1, "x"),
477        Column::new(2, "y"),
478    ];
479    let mut rows = Vec::new();
480    let mut id = 0u32;
481    for s in series {
482        for p in &s.points {
483            let mut xs = String::new();
484            let mut ys = String::new();
485            fmt_num(p.x, &mut xs);
486            fmt_num(p.y, &mut ys);
487            rows.push(Row::new(
488                id,
489                vec![
490                    CellValue::text(s.name.clone()),
491                    CellValue::text(xs),
492                    CellValue::text(ys),
493                ],
494            ));
495            id += 1;
496        }
497    }
498    if rows.is_empty() {
499        rows.push(Row::new(
500            0,
501            vec![
502                CellValue::Redacted,
503                CellValue::Redacted,
504                CellValue::Redacted,
505            ],
506        ));
507    }
508    Grid::try_new(columns, rows)
509}
510
511fn bounds(series: &[Series]) -> (f64, f64, f64, f64) {
512    let mut xmin = f64::INFINITY;
513    let mut xmax = f64::NEG_INFINITY;
514    let mut ymin = f64::INFINITY;
515    let mut ymax = f64::NEG_INFINITY;
516    for s in series {
517        for p in &s.points {
518            xmin = xmin.min(p.x);
519            xmax = xmax.max(p.x);
520            ymin = ymin.min(p.y);
521            ymax = ymax.max(p.y);
522        }
523    }
524    if !xmin.is_finite() {
525        return (0.0, 1.0, 0.0, 1.0);
526    }
527    if (xmax - xmin).abs() < 1e-9 {
528        xmax = xmin + 1.0;
529    }
530    if (ymax - ymin).abs() < 1e-9 {
531        ymax = ymin + 1.0;
532    }
533    (xmin, xmax, ymin, ymax)
534}
535
536fn axis_ticks(min: f64, max: f64, n: usize) -> Vec<f64> {
537    let n = n.max(2);
538    let span = max - min;
539    (0..n)
540        .map(|i| min + span * (i as f64) / ((n - 1) as f64))
541        .collect()
542}
543
544fn nice_num(x: f64, round: bool) -> f64 {
545    if x <= 0.0 || !x.is_finite() {
546        return 1.0;
547    }
548    let exp = x.log10().floor();
549    let f = x / 10f64.powf(exp);
550    let nf = if round {
551        if f < 1.5 {
552            1.0
553        } else if f < 3.0 {
554            2.0
555        } else if f < 7.0 {
556            5.0
557        } else {
558            10.0
559        }
560    } else if f <= 1.0 {
561        1.0
562    } else if f <= 2.0 {
563        2.0
564    } else if f <= 5.0 {
565        5.0
566    } else {
567        10.0
568    };
569    nf * 10f64.powf(exp)
570}
571
572fn nice_axis(min: f64, max: f64, ntick: usize) -> (f64, f64, Vec<f64>) {
573    let ntick = ntick.max(2);
574    let range = nice_num(max - min, false);
575    let step = nice_num(range / (ntick as f64 - 1.0), true).max(1e-9);
576    let lo = (min / step).floor() * step;
577    let hi = (max / step).ceil() * step;
578    let mut ticks = Vec::new();
579    let mut x = lo;
580    let mut guard = 0u32;
581    while x <= hi + step * 0.5 && guard < 32 {
582        ticks.push(x);
583        x += step;
584        guard += 1;
585    }
586    if ticks.len() < 2 {
587        ticks = axis_ticks(min, max, ntick);
588        return (min, max, ticks);
589    }
590    (lo, hi, ticks)
591}
592
593#[allow(clippy::too_many_arguments)]
594fn fill_area_segment(
595    pm: &mut Pixmap,
596    x0: u32,
597    y0: u32,
598    x1: u32,
599    y1: u32,
600    baseline: u32,
601    clip_l: u32,
602    clip_r: u32,
603    color: crate::theme::Rgb,
604    alpha: u8,
605) {
606    let (xa, xb, ya, yb) = if x0 <= x1 {
607        (x0, x1, y0, y1)
608    } else {
609        (x1, x0, y1, y0)
610    };
611    if xb == xa {
612        return;
613    }
614    let dx = f64::from(xb - xa);
615    for x in xa..=xb {
616        if x < clip_l || x >= clip_r {
617            continue;
618        }
619        let t = f64::from(x - xa) / dx;
620        let y = (f64::from(ya) + (f64::from(yb) - f64::from(ya)) * t) as u32;
621        let (top, bot) = if y < baseline {
622            (y, baseline)
623        } else {
624            (baseline, y)
625        };
626        for yy in top..=bot {
627            pm.blend(x, yy, color, alpha);
628        }
629    }
630}
631
632fn map_x(x: f64, xmin: f64, xmax: f64, x0: u32, w: u32) -> u32 {
633    let t = ((x - xmin) / (xmax - xmin)).clamp(0.0, 1.0);
634    x0 + ((t * f64::from(w.saturating_sub(1))) as u32)
635}
636
637fn map_y(y: f64, ymin: f64, ymax: f64, y0: u32, h: u32) -> u32 {
638    let t = ((y - ymin) / (ymax - ymin)).clamp(0.0, 1.0);
639    y0 + (((1.0 - t) * f64::from(h.saturating_sub(1))) as u32)
640}
641
642fn paint_marker(pm: &mut Pixmap, px: u32, py: u32, color: crate::theme::Rgb, r: u32) {
643    let d = r.saturating_mul(2).saturating_add(1);
644    pm.fill_rect(px.saturating_sub(r), py.saturating_sub(r), d, d, color);
645}
646
647pub(crate) fn fmt_num(v: f64, out: &mut String) {
648    use std::fmt::Write as _;
649    let _ = write!(out, "{v:.2}");
650    while out.contains('.') && out.ends_with('0') {
651        out.pop();
652    }
653    if out.ends_with('.') {
654        out.pop();
655    }
656}