Skip to main content

egui_pop_views/
plot.rs

1//! Charts: time series, scatters and bars, on `egui_plot`.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! It wraps egui_plot (MIT OR Apache-2.0), which draws the axes, the
7//! grid, the legend and the series and takes the zoom, the pan and the
8//! box zoom, and adds what an egui-pop view has:
9//!
10//! - the kit's look: the `plot` component's background, frame, axis
11//!   text and grid, the `plot-cursor` component's time cursor (its line,
12//!   its head, its colour under the pointer), and each series in its
13//!   slot of the categorical palette (`palette.category.*`,
14//!   [`DataPalette`]), or in the slot an entity's path hashes to
15//!   ([`Series::entity`]);
16//! - an accessible summary: the plot is one node, named by its label,
17//!   described by its series (their names, kinds, point counts and
18//!   ranges) and its time cursor;
19//! - the point under the pointer, nearest within [`HOVER_RADIUS`], in
20//!   the output and marked on the plot;
21//! - time: an x axis in a timeline's [`TimeScale`] (seconds, timecode,
22//!   bars and beats, [`Plot::time_scale`]), a time cursor the application
23//!   gives ([`Plot::time_cursor`]) or a timeline's playhead, dragged both
24//!   ways ([`Plot::timeline`]), its range highlighted, and every series'
25//!   value at the pointer in a tooltip ([`Plot::values_tooltip`]);
26//! - stepped lines ([`Kind::Steps`]) and error bands ([`Band`]);
27//! - decimation: a line, a stepped line or a band with more points in
28//!   view than [`DECIMATION_THRESHOLD`] is drawn from the points the
29//!   pixels can show (four a pixel column at most), read in the time
30//!   range in view only when sorted by x ([`Plot::decimation`]);
31//! - the `plots` collector ([`PlotPlugin`]): every plot drawn with its
32//!   series, ranges and hovered point, for agents.
33//!
34//! ```
35//! use egui_pop_views::plot::{Plot, Series};
36//!
37//! fn ui(ui: &mut egui::Ui, now: f64) {
38//!     let series = [
39//!         Series::line("Temperature", (0..100).map(|i| [i as f64, (i as f64 / 10.0).sin()])),
40//!         Series::points("Samples", [[10.0, 0.5], [40.0, -0.3]]),
41//!     ];
42//!     let out = Plot::new("sensors", &series)
43//!         .label("Sensors")
44//!         .time_cursor(Some(now))
45//!         .height(200.0)
46//!         .show(ui);
47//!     if let Some(h) = out.hovered {
48//!         // `h.series`, `h.index`, `h.x`, `h.y`.
49//!     }
50//! }
51//! ```
52//!
53//! Over a timeline's time:
54//!
55//! ```
56//! use egui_pop_views::plot::{Band, Plot, Series};
57//! use egui_pop_views::timeline::{TimeScale, TimelineState};
58//!
59//! fn ui(ui: &mut egui::Ui, timeline: &mut TimelineState) {
60//!     let series = [
61//!         Series::line("speed", (0..=40).map(|i| [i as f64 / 2.0, (i as f64 / 6.0).sin()]))
62//!             .entity("/robot/speed"),
63//!         Series::steps("gear", [[0.0, 1.0], [6.0, 2.0], [12.0, 3.0]]),
64//!     ];
65//!     let bands = [Band::new(0, (0..=40).map(|i| {
66//!         let y = (i as f64 / 6.0).sin();
67//!         [i as f64 / 2.0, y - 0.2, y + 0.2]
68//!     }))];
69//!     // The playhead is the cursor; dragging the cursor moves the playhead.
70//!     Plot::new("robot", &series).bands(&bands).timeline(timeline).show(ui);
71//! }
72//! ```
73
74use std::collections::BTreeMap;
75use std::hash::{Hash, Hasher};
76use std::sync::{Arc, Mutex};
77
78use egui::{
79    Color32, Context, CursorIcon, Id, Order, Pos2, Rect, Response, RichText, Role, Sense, Shape,
80    Stroke, TextStyle, Ui, Vec2b, pos2, vec2,
81};
82use egui_plot::{
83    AxisHints, Bar, BarChart, Corner, FilledArea, GridInput, GridMark, Legend, Line, PlotMemory,
84    PlotPoint, PlotTransform, Points, Span,
85};
86#[cfg(feature = "api")]
87use egui_pop_api::{Ctx, Plugin, PluginError};
88#[cfg(feature = "api")]
89use egui_pop_core::debug::FnCollector;
90use egui_pop_core::kit::{Kit, KitCx, Part, State};
91use egui_pop_core::lock;
92use egui_pop_core::state::Slot;
93use egui_pop_core::strings::{Arg, tr, tr_args, tr_with};
94use egui_pop_core::theme::{DataPalette, Tokens};
95use egui_pop_core::tokens::Value;
96use egui_pop_model::ids::PluginId;
97use serde::Serialize;
98use serde_json::{Value as Json, json};
99
100use crate::strings as s;
101
102use crate::timeline::{TimeRange, TimeScale, TimeView, TimelineState, TimelineTokens, ruler};
103
104mod decimate;
105
106/// What a navigation zoom command multiplies a plot's zoom by.
107const NAV_ZOOM: f32 = 1.25;
108/// A navigation pan moves a plot's view by this part of its size.
109const NAV_PAN: f32 = 0.1;
110
111use decimate::Window;
112
113/// How far from a point, in points on screen, the pointer still hovers
114/// it.
115pub const HOVER_RADIUS: f32 = 16.0;
116
117/// Above how many points in view a line, a stepped line or a band is
118/// decimated by default ([`Plot::decimation`]).
119pub const DECIMATION_THRESHOLD: usize = 1000;
120
121/// Above how many points a series' order and ranges are kept between
122/// passes, while its points look the same ([`stats`]).
123const STATS_KEPT: usize = 4096;
124
125/// How a series is drawn.
126#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
127#[serde(rename_all = "lowercase")]
128#[non_exhaustive]
129pub enum Kind {
130    /// A line through its points, in order.
131    Line,
132    /// Its points alone (a scatter).
133    Points,
134    /// A bar from 0 to each point's y, at its x.
135    Bars,
136    /// A stepped line: each value held until the next point's x (a state,
137    /// a gear, a count that changes at instants).
138    Steps,
139}
140
141impl Kind {
142    fn word(self, ctx: &Context) -> String {
143        tr(
144            ctx,
145            match self {
146                Kind::Line => &s::PLOT_LINE,
147                Kind::Points => &s::PLOT_POINTS,
148                Kind::Bars => &s::PLOT_BARS,
149                Kind::Steps => &s::PLOT_STEPS,
150            },
151        )
152    }
153}
154
155/// A series of a plot: a name, a kind and its points.
156#[derive(Clone, Debug, PartialEq)]
157pub struct Series {
158    /// Its name in the legend, the accessible summary and the collector.
159    pub name: String,
160    pub kind: Kind,
161    /// Its points, `[x, y]`.
162    pub points: Vec<[f64; 2]>,
163    /// Its slot of the categorical palette (default: its place among the
164    /// plot's series). Give an entity the same slot in every plot, so its
165    /// colour follows it.
166    pub slot: Option<usize>,
167    /// A colour of its own, over the palette's.
168    pub color: Option<Color32>,
169}
170
171impl Series {
172    pub fn new(
173        name: impl Into<String>,
174        kind: Kind,
175        points: impl IntoIterator<Item = [f64; 2]>,
176    ) -> Self {
177        Self {
178            name: name.into(),
179            kind,
180            points: points.into_iter().collect(),
181            slot: None,
182            color: None,
183        }
184    }
185
186    /// A line through `points`.
187    pub fn line(name: impl Into<String>, points: impl IntoIterator<Item = [f64; 2]>) -> Self {
188        Self::new(name, Kind::Line, points)
189    }
190
191    /// `points` alone, a scatter.
192    pub fn points(name: impl Into<String>, points: impl IntoIterator<Item = [f64; 2]>) -> Self {
193        Self::new(name, Kind::Points, points)
194    }
195
196    /// Bars of `[x, height]`.
197    pub fn bars(name: impl Into<String>, points: impl IntoIterator<Item = [f64; 2]>) -> Self {
198        Self::new(name, Kind::Bars, points)
199    }
200
201    /// A stepped line through `points`, sorted by x: each y held until
202    /// the next x.
203    pub fn steps(name: impl Into<String>, points: impl IntoIterator<Item = [f64; 2]>) -> Self {
204        Self::new(name, Kind::Steps, points)
205    }
206
207    /// Its slot of the categorical palette.
208    pub fn slot(mut self, slot: usize) -> Self {
209        self.slot = Some(slot);
210        self
211    }
212
213    /// The slot an entity's path hashes to ([`entity_slot`]): the entity
214    /// keeps its colour in every plot and every run, whatever else is
215    /// shown.
216    pub fn entity(self, path: &str) -> Self {
217        self.slot(entity_slot(path))
218    }
219
220    /// A colour of its own.
221    pub fn color(mut self, color: Color32) -> Self {
222        self.color = Some(color);
223        self
224    }
225
226    /// Its x and y ranges, `None` without a finite point.
227    pub fn ranges(&self) -> Option<([f64; 2], [f64; 2])> {
228        let mut it = self
229            .points
230            .iter()
231            .filter(|p| p[0].is_finite() && p[1].is_finite());
232        let first = it.next()?;
233        let mut x = [first[0]; 2];
234        let mut y = [first[1]; 2];
235        for p in it {
236            x = [x[0].min(p[0]), x[1].max(p[0])];
237            y = [y[0].min(p[1]), y[1].max(p[1])];
238        }
239        Some((x, y))
240    }
241}
242
243/// The categorical palette's slot for an entity, from its path: a stable
244/// hash (FNV-1a), the same on every platform and in every run. The idea
245/// of colouring an entity by a hash of its path is Rerun's automatic
246/// colour; here it lands on the palette's slots rather than on a hue, so
247/// a kit's palette still holds. Two paths may share a slot: give one a
248/// slot of its own ([`Series::slot`]) when they meet in a plot.
249pub fn entity_slot(path: &str) -> usize {
250    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
251    for b in path.bytes() {
252        h ^= u64::from(b);
253        h = h.wrapping_mul(0x0000_0100_0000_01b3);
254    }
255    // A multiple of every palette length up to 12 (their least common
256    // multiple), small enough for a 32-bit `usize`: the slot modulo the
257    // palette's length is the hash's.
258    (h % 27_720) as usize
259}
260
261/// An error band: a fill between a minimum and a maximum along x, in the
262/// colour of a series of the plot, under the lines.
263#[derive(Clone, Debug, PartialEq)]
264#[non_exhaustive]
265pub struct Band {
266    /// The series whose colour it takes, by its index among the plot's
267    /// series.
268    pub series: usize,
269    /// `[x, min, max]`, sorted by x.
270    pub points: Vec<[f64; 3]>,
271}
272
273impl Band {
274    /// A band in the colour of series `series`, through `[x, min, max]`.
275    pub fn new(series: usize, points: impl IntoIterator<Item = [f64; 3]>) -> Self {
276        Self {
277            series,
278            points: points.into_iter().collect(),
279        }
280    }
281}
282
283/// The point under the pointer.
284#[derive(Clone, Debug, PartialEq, Serialize)]
285pub struct Hovered {
286    /// The series' index in the slice given to [`Plot::new`].
287    pub series: usize,
288    /// Its name.
289    pub name: String,
290    /// The point's index in the series.
291    pub index: usize,
292    pub x: f64,
293    pub y: f64,
294}
295
296/// A series' value at an x.
297#[derive(Clone, Debug, PartialEq, Serialize)]
298#[non_exhaustive]
299pub struct ValueAt {
300    /// The series' index in the slice given to [`Plot::new`].
301    pub series: usize,
302    pub name: String,
303    pub y: f64,
304}
305
306/// Every line's and stepped line's value at an x: a line's between its
307/// two points around it, a stepped line's the last point's at or before
308/// it. Scatters and bars have none.
309#[derive(Clone, Debug, PartialEq, Serialize)]
310#[non_exhaustive]
311pub struct ValuesAt {
312    pub x: f64,
313    /// `x` as the time scale writes it, when the plot has one.
314    pub text: Option<String>,
315    pub values: Vec<ValueAt>,
316}
317
318/// What [`Plot::show`] returns.
319#[derive(Debug)]
320#[non_exhaustive]
321pub struct PlotOutput {
322    /// The plot area, named and described for screen readers.
323    pub response: Response,
324    /// The point under the pointer, if one is within [`HOVER_RADIUS`].
325    pub hovered: Option<Hovered>,
326    /// The pointer's position in the plot's values, while over it.
327    pub pointer: Option<[f64; 2]>,
328    /// What the plot shows, `([x_min, y_min], [x_max, y_max])`.
329    pub bounds: ([f64; 2], [f64; 2]),
330    /// Where the time cursor was dragged to this pass (on the scale's
331    /// units: whole frames on frames); a bound timeline's playhead is
332    /// already there.
333    pub cursor_dragged: Option<f64>,
334    /// The time cursor is under the pointer or dragged.
335    pub cursor_hovered: bool,
336    /// The values at the pointer while it is over the plot, else at the
337    /// time cursor.
338    pub values: Option<ValuesAt>,
339}
340
341/// The time cursor's head (`plot-cursor.head`).
342#[derive(Clone, Copy, Debug, PartialEq, Eq)]
343#[non_exhaustive]
344pub enum CursorHead {
345    /// A line alone.
346    None,
347    /// A triangle at the top, pointing down at the time.
348    Triangle,
349}
350
351/// The time cursor's look beyond the kit's box: its head and its size.
352#[derive(Clone, Copy, Debug, PartialEq)]
353#[non_exhaustive]
354pub struct CursorLook {
355    pub head: CursorHead,
356    /// The head's width, in points (`plot-cursor.head-size`).
357    pub head_size: f32,
358}
359
360impl CursorLook {
361    /// The look the theme installed in `ctx` gives.
362    pub fn of(ctx: &Context) -> CursorLook {
363        let t = Tokens::of(ctx);
364        let head = match t.resolved().value("plot-cursor.head") {
365            Some(Value::Other(Json::String(s))) if s == "triangle" => CursorHead::Triangle,
366            _ => CursorHead::None,
367        };
368        CursorLook {
369            head,
370            head_size: t
371                .resolved()
372                .dimension("plot-cursor.head-size")
373                .unwrap_or(10.0)
374                .max(0.0),
375        }
376    }
377}
378
379/// The plot's grid (`plot.grid-color`, `plot.grid-fade`).
380#[derive(Clone, Copy, Debug, PartialEq)]
381#[non_exhaustive]
382pub struct GridLook {
383    /// The lines at their strongest.
384    pub color: Color32,
385    /// How much fainter denser lines are, 0 to 1.
386    pub fade: f32,
387}
388
389impl GridLook {
390    /// The grid the theme installed in `ctx` gives; the plot's axis text
391    /// colour and egui_plot's fade without one.
392    pub fn of(ctx: &Context) -> GridLook {
393        let t = Tokens::of(ctx);
394        GridLook {
395            color: t
396                .color("plot.grid-color")
397                .unwrap_or_else(|| Kit::of(ctx).plot.style(State::REST).text),
398            fade: t
399                .resolved()
400                .dimension("plot.grid-fade")
401                .unwrap_or(0.5)
402                .clamp(0.0, 1.0),
403        }
404    }
405}
406
407/// A plot widget.
408#[derive(Debug)]
409pub struct Plot<'a> {
410    id: String,
411    series: &'a [Series],
412    label: Option<String>,
413    height: Option<f32>,
414    time_cursor: Option<f64>,
415    x_label: Option<String>,
416    y_label: Option<String>,
417    legend: Option<bool>,
418    link_x: Option<String>,
419    link_cursor: Option<String>,
420    interactive: bool,
421    bar_width: f64,
422    scale: Option<TimeScale>,
423    timeline: Option<&'a mut TimelineState>,
424    drag_cursor: bool,
425    range: Option<TimeRange>,
426    bands: &'a [Band],
427    values_tooltip: Option<bool>,
428    emphasis: Option<usize>,
429    decimation: Option<usize>,
430}
431
432impl<'a> Plot<'a> {
433    /// A plot named `id` (in the collector and egui's memory) showing
434    /// `series`.
435    pub fn new(id: impl Into<String>, series: &'a [Series]) -> Self {
436        Self {
437            id: id.into(),
438            series,
439            label: None,
440            height: None,
441            time_cursor: None,
442            x_label: None,
443            y_label: None,
444            legend: None,
445            link_x: None,
446            link_cursor: None,
447            interactive: true,
448            bar_width: 0.8,
449            scale: None,
450            timeline: None,
451            drag_cursor: false,
452            range: None,
453            bands: &[],
454            values_tooltip: None,
455            emphasis: None,
456            decimation: Some(DECIMATION_THRESHOLD),
457        }
458    }
459
460    /// Decimates the lines, stepped lines and bands with more than
461    /// `threshold` points in view: each pixel column draws at most four
462    /// of its points (the first, the lowest, the highest and the last),
463    /// which cover the same pixels as all of them. `None` draws every
464    /// point. Default: [`DECIMATION_THRESHOLD`].
465    ///
466    /// A series sorted by x (a time series) is read in the x range in
467    /// view only, found by binary search: a pass costs the points in
468    /// view, whatever the series' length. A series that is not sorted is
469    /// drawn whole, as egui_plot draws it. The point under the pointer
470    /// ([`PlotOutput::hovered`]) and the values at the pointer are read
471    /// in the full series, never in the points drawn.
472    pub fn decimation(mut self, threshold: Option<usize>) -> Self {
473        self.decimation = threshold;
474        self
475    }
476
477    /// Its accessible name (default: "Chart").
478    pub fn label(mut self, label: impl Into<String>) -> Self {
479        self.label = Some(label.into());
480        self
481    }
482
483    /// Its height (default: what is available, or egui_plot's aspect).
484    pub fn height(mut self, height: f32) -> Self {
485        self.height = Some(height);
486        self
487    }
488
489    /// A vertical line at `time` (an x value), the time a timeline
490    /// shows; `None`, none. The application passes it every pass.
491    pub fn time_cursor(mut self, time: Option<f64>) -> Self {
492        self.time_cursor = time;
493        self
494    }
495
496    /// The time cursor follows the pointer when dragged; where it went is
497    /// [`PlotOutput::cursor_dragged`] (default: off; on with a timeline).
498    pub fn drag_cursor(mut self, on: bool) -> Self {
499        self.drag_cursor = on;
500        self
501    }
502
503    /// The x axis in a timeline's scale: x values are seconds, the ticks
504    /// and labels the timeline ruler's (`1:05`, `00:00:02:10`, `17.2`).
505    pub fn time_scale(mut self, scale: TimeScale) -> Self {
506        self.scale = Some(scale);
507        self
508    }
509
510    /// Follows a timeline: its scale on the x axis, its playhead as the
511    /// time cursor, its range highlighted; dragging the cursor moves the
512    /// playhead (on the scale's units, inside its bounds). Draw the
513    /// timeline in the same pass, before or after: each shows what the
514    /// other did.
515    pub fn timeline(mut self, state: &'a mut TimelineState) -> Self {
516        self.timeline = Some(state);
517        self
518    }
519
520    /// A span of x highlighted under the series (a timeline's range); a
521    /// timeline given by [`Plot::timeline`] gives its own.
522    pub fn highlight_range(mut self, range: Option<TimeRange>) -> Self {
523        self.range = range;
524        self
525    }
526
527    /// Error bands under the lines ([`Band`]).
528    pub fn bands(mut self, bands: &'a [Band]) -> Self {
529        self.bands = bands;
530        self
531    }
532
533    /// While the pointer is over the plot, a tooltip lists every line's
534    /// value at its x, marked on the lines (default: on with a time scale
535    /// or a timeline).
536    pub fn values_tooltip(mut self, on: bool) -> Self {
537        self.values_tooltip = Some(on);
538        self
539    }
540
541    /// Draws one series thicker, the one an application has selected or
542    /// hovered elsewhere.
543    pub fn emphasize(mut self, series: Option<usize>) -> Self {
544        self.emphasis = series;
545        self
546    }
547
548    /// The x axis' title.
549    pub fn x_label(mut self, label: impl Into<String>) -> Self {
550        self.x_label = Some(label.into());
551        self
552    }
553
554    /// The y axis' title.
555    pub fn y_label(mut self, label: impl Into<String>) -> Self {
556        self.y_label = Some(label.into());
557        self
558    }
559
560    /// Shows the legend (default: with two series or more).
561    pub fn legend(mut self, on: bool) -> Self {
562        self.legend = Some(on);
563        self
564    }
565
566    /// Zooms and pans the x axis together with the other plots of
567    /// `group` (egui_plot's linked axes).
568    pub fn link_x(mut self, group: impl Into<String>) -> Self {
569        self.link_x = Some(group.into());
570        self
571    }
572
573    /// Shows the pointer's x as a line in the other plots of `group`
574    /// (egui_plot's linked cursors).
575    pub fn link_cursor(mut self, group: impl Into<String>) -> Self {
576        self.link_cursor = Some(group.into());
577        self
578    }
579
580    /// Takes the zoom, the pan and the box zoom (default: on).
581    pub fn interactive(mut self, on: bool) -> Self {
582        self.interactive = on;
583        self
584    }
585
586    /// The width a bar takes of the space between two x values, shared
587    /// by the bar series side by side (default: 0.8).
588    pub fn bar_width(mut self, width: f64) -> Self {
589        self.bar_width = width;
590        self
591    }
592
593    /// The colour series `index` is drawn in.
594    pub fn color_of(palette: &DataPalette, series: &Series, index: usize) -> Color32 {
595        series
596            .color
597            .unwrap_or_else(|| palette.series(series.slot.unwrap_or(index)))
598    }
599
600    pub fn show(self, ui: &mut Ui) -> PlotOutput {
601        let Plot {
602            id: plot_id,
603            series,
604            label,
605            height,
606            mut time_cursor,
607            x_label,
608            y_label,
609            legend,
610            link_x,
611            link_cursor,
612            interactive,
613            bar_width,
614            mut scale,
615            mut timeline,
616            mut drag_cursor,
617            mut range,
618            bands,
619            values_tooltip,
620            emphasis,
621            decimation,
622        } = self;
623        let mut looping = false;
624        if let Some(state) = timeline.as_deref() {
625            scale = Some(state.scale);
626            time_cursor = Some(state.playhead);
627            range = state.range;
628            looping = state.looping;
629            drag_cursor = true;
630        }
631        let tooltip = values_tooltip.unwrap_or(scale.is_some());
632        let id = Id::unique(("egui_pop_views::plot", &plot_id));
633        let kit = Kit::of(ui.ctx());
634        let tokens = Tokens::of(ui.ctx());
635        // Last pass's hover: the area's text under the pointer.
636        let hovered_before = ui.ctx().read_response(id).is_some_and(|r| r.hovered());
637        let state = if hovered_before {
638            State::HOVER
639        } else {
640            State::REST
641        };
642        let style = *kit.plot.style(state);
643        let grid = GridLook::of(ui.ctx());
644        let colors: Vec<Color32> = series
645            .iter()
646            .enumerate()
647            .map(|(i, s)| Self::color_of(&tokens.palette, s, i))
648            .collect();
649        let slot = ui.painter().add(Shape::Noop);
650        let legend = legend.unwrap_or(series.len() > 1);
651
652        // What the decimation needs: each series' order and ranges, and
653        // the x range egui_plot showed last pass (the whole data while
654        // its bounds are automatic).
655        let ctx = ui.ctx().clone();
656        let series_stats: Vec<Stats> = series
657            .iter()
658            .enumerate()
659            .map(|(i, s)| stats(&ctx, id.with(("stats", i)), &s.points))
660            .collect();
661        let band_stats: Vec<Stats> = bands
662            .iter()
663            .enumerate()
664            .map(|(b, band)| stats(&ctx, id.with(("band-stats", b)), &band.points))
665            .collect();
666        let memory = PlotMemory::load(&ctx, id);
667        let auto = memory.as_ref().map_or(Vec2b::TRUE, |m| m.auto_bounds);
668        let data_x = series_stats
669            .iter()
670            .chain(&band_stats)
671            .filter_map(|st| st.ranges.map(|r| r.0))
672            .reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])]);
673        let view_x = if auto.x {
674            data_x
675        } else {
676            memory
677                .as_ref()
678                .map(|m| [m.bounds().min()[0], m.bounds().max()[0]])
679        }
680        .filter(|r| r[0].is_finite() && r[1].is_finite());
681        let reads_view = |kind: Option<Kind>, st: &Stats| {
682            decimation.is_some()
683                && view_x.is_some()
684                && st.sorted
685                && kind.is_none_or(|k| matches!(k, Kind::Line | Kind::Steps))
686        };
687        let trimmed = series
688            .iter()
689            .zip(&series_stats)
690            .any(|(s, st)| reads_view(Some(s.kind), st))
691            || band_stats.iter().any(|st| reads_view(None, st));
692        let mut plot = egui_plot::Plot::new(plot_id.as_str())
693            .id(id)
694            .show_background(false)
695            .grid_color(grid.color)
696            .grid_fade(grid.fade)
697            .cursor_color(style.text)
698            .allow_zoom(interactive)
699            .allow_drag(interactive)
700            .allow_scroll(interactive)
701            .allow_boxed_zoom(interactive)
702            .allow_double_click_reset(interactive);
703        if let Some(h) = height {
704            plot = plot.height(h);
705        }
706        if legend {
707            plot = plot.legend(
708                Legend::default()
709                    .position(Corner::RightTop)
710                    .follow_insertion_order(true),
711            );
712        }
713        // The x axis' labels this pass, for the collector.
714        let x_ticks: Arc<Mutex<Vec<String>>> = Arc::default();
715        if let Some(sc) = scale {
716            let font = TextStyle::Body.resolve(ui.style());
717            let digit = ui
718                .painter()
719                .layout_no_wrap("0".into(), font, Color32::WHITE)
720                .size()
721                .x;
722            let major = Arc::new(Mutex::new(f64::INFINITY));
723            let (to_label, seen) = (Arc::clone(&major), Arc::clone(&x_ticks));
724            plot = plot.x_grid_spacer(move |input: GridInput| {
725                let (ticks, marks) = time_marks(&sc, input, digit);
726                *lock(&major) = ticks.major;
727                *lock(&seen) = marks.iter().filter_map(|m| m.label.clone()).collect();
728                marks
729                    .iter()
730                    .map(|m| GridMark {
731                        value: m.time,
732                        step_size: if m.major { ticks.major } else { ticks.minor },
733                    })
734                    .collect()
735            });
736            let mut axis = AxisHints::new_x()
737                .formatter(move |mark: GridMark, _| {
738                    let major = *lock(&to_label);
739                    if mark.step_size >= major * (1.0 - 1e-9) {
740                        sc.label(mark.value, major)
741                    } else {
742                        String::new()
743                    }
744                })
745                // The ruler already spaced the labels for their width.
746                .label_spacing(1.0..=2.0);
747            if let Some(l) = &x_label {
748                axis = axis.label(l.clone());
749            }
750            plot = plot.custom_x_axes(vec![axis]);
751        } else if let Some(l) = &x_label {
752            plot = plot.x_axis_label(l.clone());
753        }
754        if let Some(l) = &y_label {
755            plot = plot.y_axis_label(l.clone());
756        }
757        if tooltip {
758            // The tooltip says the values: no coordinates beside the
759            // pointer.
760            plot = plot.label_formatter(|_| None);
761        }
762        if let Some(g) = &link_x {
763            plot = plot.link_axis(Id::unique(("egui_pop_views::plot::axis", g)), [true, false]);
764        }
765        if let Some(g) = &link_cursor {
766            plot = plot.link_cursor(
767                Id::unique(("egui_pop_views::plot::cursor", g)),
768                [true, false],
769            );
770        }
771        // A series read in the x range in view only: egui_plot fits an
772        // automatic y to every point of it, as it would to the full one.
773        if auto.y && !auto.x {
774            let kinds = series
775                .iter()
776                .map(|s| Some(s.kind))
777                .chain(bands.iter().map(|_| None));
778            for (kind, st) in kinds.zip(series_stats.iter().chain(&band_stats)) {
779                if reads_view(kind, st)
780                    && let Some((_, y)) = st.ranges
781                {
782                    plot = plot.include_y(y[0]).include_y(y[1]);
783                }
784            }
785        }
786        let bar_series: Vec<usize> = (0..series.len())
787            .filter(|&i| series[i].kind == Kind::Bars)
788            .collect();
789        let bar_w = bar_width / bar_series.len().max(1) as f64;
790        let bar_offset = |i: usize| {
791            let j = bar_series.iter().position(|&b| b == i).unwrap_or(0) as f64;
792            (j - (bar_series.len() as f64 - 1.0) / 2.0) * bar_w
793        };
794        let ring = style.text;
795        let tl = TimelineTokens::of(ui.ctx());
796        // The navigation commands sent to the plot as the canvas in use
797        // (`egui_pop_core::canvas`, docs/design/navigation.md): fit and
798        // frame the selection give egui_plot its automatic bounds back,
799        // the zooms go around the centre, the pans move a tenth of the
800        // view; `view.hand` toggles hand mode (a primary drag already
801        // pans a plot). A plot has no 100 %.
802        let nav = if interactive {
803            egui_pop_core::canvas::take(&ctx, id)
804        } else {
805            Vec::new()
806        };
807        for c in &nav {
808            if c == "view.hand" {
809                egui_pop_core::canvas::set_hand(&ctx, !egui_pop_core::canvas::hand(&ctx));
810            }
811        }
812        let inner = ui
813            .scope(|ui| {
814                // egui_plot reads its axis text, its legend's and its
815                // background from the visuals.
816                let v = ui.visuals_mut();
817                v.override_text_color = Some(style.text);
818                v.extreme_bg_color = style.fill;
819                plot.show(ui, |p| {
820                    let b = p.plot_bounds();
821                    let center = b.center();
822                    let size = vec2(b.width() as f32, b.height() as f32);
823                    for c in &nav {
824                        match c.as_str() {
825                            "view.fit" | "view.frame_selection" => p.set_auto_bounds(Vec2b::TRUE),
826                            "view.zoom_in" => p.zoom_bounds(vec2(NAV_ZOOM, NAV_ZOOM), center),
827                            "view.zoom_out" => {
828                                p.zoom_bounds(vec2(1.0 / NAV_ZOOM, 1.0 / NAV_ZOOM), center);
829                            }
830                            "view.pan_left" => p.translate_bounds(vec2(-size.x * NAV_PAN, 0.0)),
831                            "view.pan_right" => p.translate_bounds(vec2(size.x * NAV_PAN, 0.0)),
832                            "view.pan_up" => p.translate_bounds(vec2(0.0, size.y * NAV_PAN)),
833                            "view.pan_down" => p.translate_bounds(vec2(0.0, -size.y * NAV_PAN)),
834                            _ => {}
835                        }
836                    }
837                    // The range first, under everything.
838                    if let Some(r) = range.filter(|r| r.end > r.start) {
839                        let edge = if looping {
840                            tl.range_edge
841                        } else {
842                            tl.range_edge_idle
843                        };
844                        p.span(
845                            Span::new("", r.start..=r.end)
846                                .fill(tl.range_fill)
847                                .border(Stroke::new(1.0, edge)),
848                        );
849                    }
850                    // The pixel columns the decimation reads.
851                    let ppp = p.ctx().pixels_per_point();
852                    let columns = (p.response().rect.width() * ppp).ceil().max(1.0) as usize;
853                    let window = view_x.map(|r| Window::new(r[0], r[1], columns));
854                    let mut drawn = Vec::with_capacity(series.len());
855                    for (b, band) in bands.iter().enumerate() {
856                        let Some(color) = colors.get(band.series) else {
857                            continue;
858                        };
859                        let rows = match window {
860                            Some(w) if reads_view(None, &band_stats[b]) => {
861                                let range = decimate::span(&band.points, &w);
862                                if decimation.is_some_and(|t| range.len() > t) {
863                                    let mut out = Vec::with_capacity(3 * columns + 2);
864                                    decimate::band(&band.points, &w, &mut out);
865                                    out
866                                } else {
867                                    band_rows(&band.points[range])
868                                }
869                            }
870                            _ => band_rows(&band.points),
871                        };
872                        let xs: Vec<f64> = rows.iter().map(|q| q[0]).collect();
873                        let lo: Vec<f64> = rows.iter().map(|q| q[1]).collect();
874                        let hi: Vec<f64> = rows.iter().map(|q| q[2]).collect();
875                        p.add(
876                            FilledArea::new("", &xs, &lo, &hi)
877                                .fill_color(color.gamma_multiply(0.25))
878                                .allow_hover(false)
879                                .id(("band", b)),
880                        );
881                    }
882                    for (i, s) in series.iter().enumerate() {
883                        let color = colors[i];
884                        let emphasized = emphasis == Some(i);
885                        // A line or a stepped line sorted by x: the points
886                        // in view, decimated past the threshold.
887                        let points = match window {
888                            Some(w) if reads_view(Some(s.kind), &series_stats[i]) => {
889                                let range = decimate::span(&s.points, &w);
890                                if decimation.is_some_and(|t| range.len() > t) {
891                                    let mut out = Vec::with_capacity(4 * columns + 2);
892                                    decimate::line(&s.points, &w, &mut out);
893                                    out
894                                } else {
895                                    s.points[range].to_vec()
896                                }
897                            }
898                            _ => s.points.clone(),
899                        };
900                        drawn.push(points.len());
901                        match s.kind {
902                            Kind::Line => p.line(
903                                Line::new(s.name.clone(), points)
904                                    .color(color)
905                                    .width(2.0)
906                                    .highlight(emphasized)
907                                    .id(("series", i)),
908                            ),
909                            Kind::Steps => p.line(
910                                // No band: egui_plot draws a dense line as
911                                // one band of its columns' ranges, which
912                                // joins a step's vertical edges into slopes.
913                                Line::new(s.name.clone(), step_points(&points))
914                                    .color(color)
915                                    .width(2.0)
916                                    .allow_band(false)
917                                    .highlight(emphasized)
918                                    .id(("series", i)),
919                            ),
920                            Kind::Points => p.points(
921                                Points::new(s.name.clone(), points)
922                                    .color(color)
923                                    .radius(3.0)
924                                    .filled(true)
925                                    .highlight(emphasized)
926                                    .id(("series", i)),
927                            ),
928                            Kind::Bars => {
929                                let off = bar_offset(i);
930                                let bars = points
931                                    .iter()
932                                    .map(|q| {
933                                        Bar::new(q[0] + off, q[1])
934                                            .width(bar_w)
935                                            .fill(color)
936                                            .stroke(Stroke::NONE)
937                                    })
938                                    .collect();
939                                p.bar_chart(
940                                    BarChart::new(s.name.clone(), bars)
941                                        .color(color)
942                                        .highlight(emphasized)
943                                        .id(("series", i)),
944                                );
945                            }
946                        }
947                    }
948                    let pointer = p.pointer_coordinate().map(|q| [q.x, q.y]);
949                    let hovered = p.response().hover_pos().and_then(|pos| {
950                        nearest(
951                            series,
952                            &series_stats,
953                            p.transform(),
954                            pos,
955                            &|i| bar_offset(i),
956                            bar_w,
957                        )
958                    });
959                    if let Some(h) = &hovered {
960                        let s = &series[h.series];
961                        let x = if s.kind == Kind::Bars {
962                            h.x + bar_offset(h.series)
963                        } else {
964                            h.x
965                        };
966                        p.points(
967                            Points::new("", vec![[x, h.y]])
968                                .radius(5.0)
969                                .filled(false)
970                                .color(ring)
971                                .allow_hover(false),
972                        );
973                    }
974                    (hovered, pointer, drawn, columns)
975                })
976            })
977            .inner;
978        let response = inner.response.clone();
979        if interactive && (response.hovered() || response.has_focus()) {
980            egui_pop_core::canvas::mark_active(&ctx, id);
981        }
982        let transform = inner.transform;
983        let (hovered, pointer, drawn, columns) = inner.inner;
984        let frame = *transform.frame();
985
986        // Points read for last pass's x range: if this pass panned, zoomed
987        // or resized the plot, draw again with the range it shows now.
988        if trimmed {
989            let auto_now = PlotMemory::load(&ctx, id).is_none_or(|m| m.auto_bounds.x);
990            let b = transform.bounds();
991            let moved = if auto_now {
992                !auto.x
993            } else {
994                auto.x || view_x != Some([b.min()[0], b.max()[0]])
995            };
996            let columns_now = (frame.width() * ctx.pixels_per_point()).ceil().max(1.0) as usize;
997            if moved || columns_now != columns {
998                ctx.request_repaint();
999            }
1000        }
1001
1002        // The kit's box under the plot, now that its frame is known.
1003        kit.plot.paint_under(
1004            ui,
1005            slot,
1006            &Part {
1007                rect: frame,
1008                room: frame,
1009                state,
1010                label: None,
1011            },
1012            None,
1013        );
1014
1015        // The time cursor: dragged, then drawn where it is now.
1016        let mut cursor_dragged = None;
1017        let mut cursor_hovered = false;
1018        if let Some(t) = time_cursor.filter(|t| t.is_finite()) {
1019            let look = CursorLook::of(ui.ctx());
1020            let mut cursor_state = State::REST;
1021            let mut at = t;
1022            if drag_cursor && frame.width() > 0.0 {
1023                let half = (look.head_size / 2.0).max(5.0);
1024                let x = transform
1025                    .position_from_point_x(t)
1026                    .clamp(frame.left(), frame.right());
1027                let r = ui.interact(
1028                    Rect::from_x_y_ranges(x - half..=x + half, frame.y_range()),
1029                    id.with("time_cursor"),
1030                    Sense::DRAG,
1031                );
1032                let text = match scale {
1033                    Some(sc) => sc.format(t),
1034                    None => number(t),
1035                };
1036                let name = tr(ui.ctx(), &s::PLOT_CURSOR);
1037                egui_pop_core::a11y::name(&r, Role::Slider, &name);
1038                ui.ctx()
1039                    .accesskit_node_builder(r.id, |node| node.set_value(text));
1040                if r.dragged()
1041                    && let Some(p) = r.interact_pointer_pos()
1042                {
1043                    let mut to = transform.value_from_position(p).x;
1044                    if let Some(sc) = scale {
1045                        to = sc.quantize(to);
1046                    }
1047                    if let Some(state) = &mut timeline {
1048                        state.set_playhead(to);
1049                        to = state.playhead;
1050                    }
1051                    if to != t {
1052                        cursor_dragged = Some(to);
1053                    }
1054                    at = to;
1055                }
1056                cursor_hovered = r.hovered() || r.dragged();
1057                if cursor_hovered {
1058                    ui.ctx().set_cursor_icon(CursorIcon::ResizeHorizontal);
1059                }
1060                cursor_state = State::REST
1061                    .with(State::HOVER, cursor_hovered)
1062                    .with(State::ACTIVE, r.dragged());
1063            }
1064            time_cursor = Some(at);
1065            let x = transform.position_from_point_x(at);
1066            if (frame.left()..=frame.right()).contains(&x) {
1067                // The kit's `plot-cursor`: a line across the part's
1068                // middle, and its head.
1069                let painter = ui.painter().with_clip_rect(frame);
1070                kit.plot_cursor.paint(
1071                    &KitCx {
1072                        painter: &painter,
1073                        ppp: ui.ctx().pixels_per_point(),
1074                    },
1075                    &Part {
1076                        rect: Rect::from_x_y_ranges(x..=x, frame.y_range()),
1077                        room: frame,
1078                        state: cursor_state,
1079                        label: None,
1080                    },
1081                );
1082                if look.head == CursorHead::Triangle && look.head_size > 0.0 {
1083                    let fill = kit.plot_cursor.style(cursor_state).fill;
1084                    let w = look.head_size / 2.0;
1085                    let top = frame.top();
1086                    painter.add(Shape::convex_polygon(
1087                        vec![
1088                            pos2(x - w, top),
1089                            pos2(x + w, top),
1090                            pos2(x, top + look.head_size * 0.7),
1091                        ],
1092                        fill,
1093                        Stroke::NONE,
1094                    ));
1095                }
1096            }
1097        }
1098
1099        // The values at the pointer, else at the cursor.
1100        let over = ui
1101            .ctx()
1102            .pointer_hover_pos()
1103            .filter(|p| frame.contains(*p) && (response.hovered() || cursor_hovered));
1104        let values_x = over
1105            .map(|p| transform.value_from_position(p).x)
1106            .or(time_cursor.filter(|t| t.is_finite()));
1107        let values = values_x.map(|x| ValuesAt {
1108            x,
1109            text: scale.map(|sc| sc.format(x)),
1110            values: values_at(series, x),
1111        });
1112        if tooltip
1113            && let (Some(pos), Some(v)) = (over, &values)
1114            && !v.values.is_empty()
1115        {
1116            let painter = ui.painter().with_clip_rect(frame);
1117            let x = transform.position_from_point_x(v.x);
1118            for value in &v.values {
1119                let y = transform.position_from_point_y(value.y);
1120                painter.circle(
1121                    pos2(x, y),
1122                    3.5,
1123                    colors[value.series],
1124                    Stroke::new(1.0, style.fill),
1125                );
1126            }
1127            values_tooltip_ui(ui, id, pos, v, &colors);
1128        }
1129        let ranges: Vec<Option<([f64; 2], [f64; 2])>> =
1130            series_stats.iter().map(|st| st.ranges).collect();
1131
1132        let label = label.unwrap_or_else(|| tr(ui.ctx(), &s::PLOT));
1133        let cursor_text = time_cursor.filter(|t| t.is_finite()).map(|t| match scale {
1134            Some(sc) => sc.format(t),
1135            None => number(t),
1136        });
1137        let summary = summary_with(ui.ctx(), series, &ranges, cursor_text);
1138        egui_pop_core::a11y::name(&response, Role::Figure, &label);
1139        let description = summary.clone();
1140        ui.ctx()
1141            .accesskit_node_builder(response.id, |node| node.set_description(description));
1142
1143        let b = transform.bounds();
1144        let bounds = (b.min(), b.max());
1145        let x_ticks = std::mem::take(&mut *lock(&x_ticks));
1146        Plots::of(ui.ctx()).record(
1147            &plot_id,
1148            Record {
1149                label,
1150                summary,
1151                series: series
1152                    .iter()
1153                    .enumerate()
1154                    .map(|(i, s)| {
1155                        let ranges = ranges[i];
1156                        json!({
1157                            "name": s.name,
1158                            "kind": s.kind,
1159                            "points": s.points.len(),
1160                            "drawn": drawn.get(i),
1161                            "x": ranges.map(|r| r.0),
1162                            "y": ranges.map(|r| r.1),
1163                            "color": format!("#{:02x}{:02x}{:02x}", colors[i].r(), colors[i].g(), colors[i].b()),
1164                        })
1165                    })
1166                    .collect(),
1167                bounds,
1168                hovered: hovered.clone(),
1169                time_cursor,
1170                scale: scale.map(|sc| sc.kind()),
1171                x_ticks,
1172                range: range.map(|r| [r.start, r.end]),
1173                values: values.clone(),
1174                pass: ui.ctx().cumulative_pass_nr(),
1175            },
1176        );
1177        PlotOutput {
1178            response,
1179            hovered,
1180            pointer,
1181            bounds,
1182            cursor_dragged,
1183            cursor_hovered,
1184            values,
1185        }
1186    }
1187}
1188
1189/// The tooltip listing the values, beside the pointer.
1190fn values_tooltip_ui(ui: &Ui, id: Id, pos: Pos2, v: &ValuesAt, colors: &[Color32]) {
1191    egui::Area::new(id.with("values"))
1192        .order(Order::Tooltip)
1193        .fixed_pos(pos + vec2(16.0, 16.0))
1194        .interactable(false)
1195        .constrain(true)
1196        .show(ui.ctx(), |ui| {
1197            egui::Frame::popup(ui.style()).show(ui, |ui| {
1198                let x = v.text.clone().unwrap_or_else(|| number(v.x));
1199                ui.label(RichText::new(x).monospace().strong());
1200                for value in &v.values {
1201                    ui.horizontal(|ui| {
1202                        let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), Sense::hover());
1203                        ui.painter().rect_filled(r, 2.0, colors[value.series]);
1204                        ui.label(format!("{}: {}", value.name, number(value.y)));
1205                    });
1206                }
1207            });
1208        });
1209}
1210
1211/// A stepped line's points: each y held until the next x.
1212fn step_points(points: &[[f64; 2]]) -> Vec<[f64; 2]> {
1213    let mut out = Vec::with_capacity(points.len() * 2);
1214    for (i, p) in points.iter().enumerate() {
1215        if i > 0 {
1216            out.push([p[0], points[i - 1][1]]);
1217        }
1218        out.push(*p);
1219    }
1220    out
1221}
1222
1223/// A band's rows to draw: those with every value a number, `min` and
1224/// `max` in order.
1225fn band_rows(points: &[[f64; 3]]) -> Vec<[f64; 3]> {
1226    points
1227        .iter()
1228        .filter(|q| q.iter().all(|v| v.is_finite()))
1229        .map(|q| [q[0], q[1].min(q[2]), q[1].max(q[2])])
1230        .collect()
1231}
1232
1233/// What the plot knows of a series' points beyond drawing them.
1234#[derive(Clone, Copy, Debug, PartialEq)]
1235struct Stats {
1236    /// Every x is a number, none smaller than the one before: the points
1237    /// in view are found by binary search.
1238    sorted: bool,
1239    /// The x and y ranges of the rows whose values are all numbers (a
1240    /// band's y range spans its minimums and maximums).
1241    ranges: Option<([f64; 2], [f64; 2])>,
1242}
1243
1244fn scan<const N: usize>(points: &[[f64; N]]) -> Stats {
1245    let mut sorted = true;
1246    let mut previous = f64::NEG_INFINITY;
1247    let mut ranges: Option<([f64; 2], [f64; 2])> = None;
1248    for p in points {
1249        // Not a number is not sorted either.
1250        if p[0] >= previous {
1251            previous = p[0];
1252        } else {
1253            sorted = false;
1254        }
1255        if p.iter().all(|v| v.is_finite()) {
1256            let (lo, hi) = p[1..]
1257                .iter()
1258                .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), &v| {
1259                    (a.min(v), b.max(v))
1260                });
1261            ranges = Some(match ranges {
1262                None => ([p[0], p[0]], [lo, hi]),
1263                Some((x, y)) => (
1264                    [x[0].min(p[0]), x[1].max(p[0])],
1265                    [y[0].min(lo), y[1].max(hi)],
1266                ),
1267            });
1268        }
1269    }
1270    Stats { sorted, ranges }
1271}
1272
1273/// A cheap print of a series' points: its buffer, its length and 64 of
1274/// its points spread along it.
1275fn fingerprint<const N: usize>(points: &[[f64; N]]) -> u64 {
1276    let mut h = std::collections::hash_map::DefaultHasher::new();
1277    (points.as_ptr() as usize).hash(&mut h);
1278    points.len().hash(&mut h);
1279    if let Some(last) = points.len().checked_sub(1) {
1280        for k in 0..64u64 {
1281            let i = (k * last as u64 / 63) as usize;
1282            for v in points[i] {
1283                v.to_bits().hash(&mut h);
1284            }
1285        }
1286    }
1287    h.finish()
1288}
1289
1290/// A series' order and ranges. Past [`STATS_KEPT`] points they are kept
1291/// in `ctx` under `key` and read again only when the points' print
1292/// changes (another buffer, another length, one of 64 points spread
1293/// along it changed), so a pass over a long series costs the points in
1294/// view: a long series edited in place where none of these change keeps
1295/// its last ranges in the summary until one does.
1296fn stats<const N: usize>(ctx: &Context, key: Id, points: &[[f64; N]]) -> Stats {
1297    if points.len() <= STATS_KEPT {
1298        return scan(points);
1299    }
1300    let print = fingerprint(points);
1301    if let Some((p, st)) = ctx.data(|d| d.get_temp::<(u64, Stats)>(key))
1302        && p == print
1303    {
1304        return st;
1305    }
1306    let st = scan(points);
1307    ctx.data_mut(|d| d.insert_temp(key, (print, st)));
1308    st
1309}
1310
1311/// Each line's and stepped line's value at `x` (their points sorted by
1312/// x); none outside a series' x range. The points around `x` are found by
1313/// binary search.
1314pub fn values_at(series: &[Series], x: f64) -> Vec<ValueAt> {
1315    if !x.is_finite() {
1316        return Vec::new();
1317    }
1318    series
1319        .iter()
1320        .enumerate()
1321        .filter_map(|(i, s)| {
1322            if !matches!(s.kind, Kind::Line | Kind::Steps) {
1323                return None;
1324            }
1325            let finite = |p: &&[f64; 2]| p[0].is_finite() && p[1].is_finite();
1326            let first = s.points.iter().find(finite)?;
1327            let last = s.points.iter().rev().find(finite)?;
1328            if x < first[0] || x > last[0] {
1329                return None;
1330            }
1331            // The first point past x, and the points around it.
1332            let k = s.points.partition_point(|p| p[0] <= x || p[0].is_nan());
1333            let a = s.points[..k].iter().rev().find(finite)?;
1334            let b = s.points[k..].iter().find(finite);
1335            let y = match (s.kind, b) {
1336                (Kind::Line, Some(b)) => {
1337                    let f = (x - a[0]) / (b[0] - a[0]);
1338                    a[1] + (b[1] - a[1]) * f
1339                }
1340                _ => a[1],
1341            };
1342            Some(ValueAt {
1343                series: i,
1344                name: s.name.clone(),
1345                y,
1346            })
1347        })
1348        .collect()
1349}
1350
1351/// The time axis' ticks for egui_plot's grid: the timeline ruler's for
1352/// the span in view and the plot's width (from the grid's input: its
1353/// step is egui_plot's least grid spacing, 8 points), labels measured as
1354/// `digit` points a character.
1355fn time_marks(scale: &TimeScale, input: GridInput, digit: f32) -> (ruler::Ticks, Vec<ruler::Mark>) {
1356    // egui_plot's `grid_spacing` minimum, which `base_step_size` is.
1357    const LEAST_SPACING: f64 = 8.0;
1358    let (a, b) = input.bounds;
1359    let span = b - a;
1360    let per_point = input.base_step_size / LEAST_SPACING;
1361    if !(span.is_finite() && span > 0.0 && per_point.is_finite() && per_point > 0.0) {
1362        let none = ruler::Ticks {
1363            major: f64::INFINITY,
1364            minor: f64::INFINITY,
1365        };
1366        return (none, Vec::new());
1367    }
1368    let width = (span / per_point) as f32;
1369    let view = TimeView::new(a, span);
1370    let measure = |text: &str| text.chars().count() as f32 * digit;
1371    let ticks = ruler::ticks(scale, &view, width, &measure);
1372    let marks = ruler::marks(scale, &view, width, ticks);
1373    (ticks, marks)
1374}
1375
1376/// The point nearest `pos` on screen, within [`HOVER_RADIUS`]; a bar
1377/// is hovered anywhere over it. Read in the full series, never in the
1378/// points drawn: a series sorted by x only within the radius' x range,
1379/// found by binary search.
1380fn nearest(
1381    series: &[Series],
1382    stats: &[Stats],
1383    transform: &PlotTransform,
1384    pos: Pos2,
1385    bar_offset: &dyn Fn(usize) -> f64,
1386    bar_w: f64,
1387) -> Option<Hovered> {
1388    let mut best: Option<(f32, usize, usize)> = None;
1389    // The x range within reach, a point wider for the rounding.
1390    let reach = HOVER_RADIUS + 1.0;
1391    let a = transform.value_from_position(pos2(pos.x - reach, pos.y)).x;
1392    let b = transform.value_from_position(pos2(pos.x + reach, pos.y)).x;
1393    let (lo, hi) = (a.min(b), a.max(b));
1394    for (i, s) in series.iter().enumerate() {
1395        let range = if s.kind != Kind::Bars && stats.get(i).is_some_and(|st| st.sorted) {
1396            let from = s.points.partition_point(|q| q[0] < lo);
1397            from..s.points.partition_point(|q| q[0] <= hi).max(from)
1398        } else {
1399            0..s.points.len()
1400        };
1401        for (j, q) in s.points[range.clone()].iter().enumerate() {
1402            let j = range.start + j;
1403            if !(q[0].is_finite() && q[1].is_finite()) {
1404                continue;
1405            }
1406            let d = if s.kind == Kind::Bars {
1407                let x = q[0] + bar_offset(i);
1408                let a = transform.position_from_point(&PlotPoint::new(x - bar_w / 2.0, 0.0));
1409                let b = transform.position_from_point(&PlotPoint::new(x + bar_w / 2.0, q[1]));
1410                if Rect::from_two_pos(a, b).contains(pos) {
1411                    0.0
1412                } else {
1413                    continue;
1414                }
1415            } else {
1416                let p = transform.position_from_point(&PlotPoint::new(q[0], q[1]));
1417                let d = p.distance(pos);
1418                if d > HOVER_RADIUS {
1419                    continue;
1420                }
1421                d
1422            };
1423            if best.is_none_or(|b| d < b.0) {
1424                best = Some((d, i, j));
1425            }
1426        }
1427    }
1428    best.map(|(_, i, j)| Hovered {
1429        series: i,
1430        name: series[i].name.clone(),
1431        index: j,
1432        x: series[i].points[j][0],
1433        y: series[i].points[j][1],
1434    })
1435}
1436
1437/// A number as the summary says it: up to four significant decimals.
1438fn number(v: f64) -> String {
1439    if v == 0.0 || !v.is_finite() {
1440        return format!("{v}");
1441    }
1442    let decimals = (3 - v.abs().log10().floor() as i32).clamp(0, 6) as usize;
1443    let s = format!("{v:.decimals$}");
1444    if s.contains('.') {
1445        s.trim_end_matches('0').trim_end_matches('.').to_string()
1446    } else {
1447        s
1448    }
1449}
1450
1451/// The accessible description: each series, then the time cursor.
1452pub fn summary(ctx: &Context, series: &[Series], time_cursor: Option<f64>) -> String {
1453    let ranges: Vec<_> = series.iter().map(Series::ranges).collect();
1454    summary_with(
1455        ctx,
1456        series,
1457        &ranges,
1458        time_cursor.filter(|t| t.is_finite()).map(number),
1459    )
1460}
1461
1462/// The description with each series' ranges known and the time cursor
1463/// already written (in a time scale's text, or as a number).
1464fn summary_with(
1465    ctx: &Context,
1466    series: &[Series],
1467    ranges: &[Option<([f64; 2], [f64; 2])>],
1468    time_cursor: Option<String>,
1469) -> String {
1470    let mut parts: Vec<String> = series
1471        .iter()
1472        .zip(ranges)
1473        .map(|(s, ranges)| {
1474            let kind = s.kind.word(ctx);
1475            match *ranges {
1476                Some((x, y)) => tr_with(
1477                    ctx,
1478                    &s::PLOT_SERIES,
1479                    &[
1480                        ("name", Arg::Str(&s.name)),
1481                        ("kind", Arg::Str(&kind)),
1482                        ("count", (s.points.len()).into()),
1483                        ("x_min", Arg::Str(&number(x[0]))),
1484                        ("x_max", Arg::Str(&number(x[1]))),
1485                        ("y_min", Arg::Str(&number(y[0]))),
1486                        ("y_max", Arg::Str(&number(y[1]))),
1487                    ],
1488                ),
1489                None => tr_args(
1490                    ctx,
1491                    &s::PLOT_SERIES_EMPTY,
1492                    &[("name", &s.name), ("kind", &kind)],
1493                ),
1494            }
1495        })
1496        .collect();
1497    if let Some(t) = time_cursor {
1498        parts.push(tr_args(ctx, &s::PLOT_TIME_CURSOR, &[("time", &t)]));
1499    }
1500    parts.join(". ")
1501}
1502
1503/// A plot as last drawn.
1504#[derive(Clone, Debug)]
1505struct Record {
1506    label: String,
1507    summary: String,
1508    series: Vec<Json>,
1509    bounds: ([f64; 2], [f64; 2]),
1510    hovered: Option<Hovered>,
1511    time_cursor: Option<f64>,
1512    scale: Option<&'static str>,
1513    x_ticks: Vec<String>,
1514    range: Option<[f64; 2]>,
1515    values: Option<ValuesAt>,
1516    pass: u64,
1517}
1518
1519#[derive(Clone, Debug, Default)]
1520struct Shared(Arc<Mutex<BTreeMap<String, Record>>>);
1521
1522const SLOT: Slot<Shared> = Slot::new("views.plot");
1523
1524/// The plots drawn in a context, by id: what the `plots` collector
1525/// shows.
1526#[derive(Clone, Debug)]
1527pub struct Plots {
1528    ctx: Context,
1529    records: Arc<Mutex<BTreeMap<String, Record>>>,
1530}
1531
1532impl Plots {
1533    /// The context's plots.
1534    pub fn of(ctx: &Context) -> Self {
1535        Self {
1536            ctx: ctx.clone(),
1537            records: SLOT.get_or_insert_with(ctx, Shared::default).0,
1538        }
1539    }
1540
1541    fn record(&self, id: &str, record: Record) {
1542        lock(&self.records).insert(id.to_string(), record);
1543    }
1544
1545    /// The ids of the plots drawn in the last two passes.
1546    pub fn ids(&self) -> Vec<String> {
1547        let now = self.ctx.cumulative_pass_nr();
1548        lock(&self.records)
1549            .iter()
1550            .filter(|(_, r)| r.pass + 1 >= now)
1551            .map(|(id, _)| id.clone())
1552            .collect()
1553    }
1554
1555    /// What a plot showed when last drawn: its label, its summary, its
1556    /// series (name, kind, point count, x and y ranges, colour), the
1557    /// bounds in view, the hovered point, the time cursor, the time
1558    /// scale and the x axis' labels, the highlighted range and the values
1559    /// at the pointer or the cursor.
1560    pub fn state(&self, id: &str) -> Option<Json> {
1561        lock(&self.records).get(id).map(|r| {
1562            json!({
1563                "label": r.label,
1564                "summary": r.summary,
1565                "series": r.series,
1566                "bounds": { "min": r.bounds.0, "max": r.bounds.1 },
1567                "hovered": r.hovered,
1568                "time_cursor": r.time_cursor,
1569                "scale": r.scale,
1570                "x_ticks": r.x_ticks,
1571                "range": r.range,
1572                "values": r.values,
1573            })
1574        })
1575    }
1576
1577    /// What the `plots` collector shows: every plot drawn in the last two
1578    /// passes, by id.
1579    pub fn describe(&self) -> Json {
1580        let ids = self.ids();
1581        let plots: serde_json::Map<String, Json> = ids
1582            .into_iter()
1583            .filter_map(|id| self.state(&id).map(|s| (id, s)))
1584            .collect();
1585        json!({ "plots": plots })
1586    }
1587}
1588
1589/// The plugin's id.
1590pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.plot");
1591
1592/// Declares the `plots` collector. Connect it when an application's
1593/// plots should be read by agents; the widgets draw without it.
1594#[cfg(feature = "api")]
1595#[derive(Debug, Default)]
1596pub struct PlotPlugin;
1597
1598#[cfg(feature = "api")]
1599impl Plugin for PlotPlugin {
1600    fn id(&self) -> PluginId {
1601        PLUGIN
1602    }
1603
1604    fn title(&self) -> String {
1605        "Plots".into()
1606    }
1607
1608    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1609        let egui = ctx.app().egui();
1610        ctx.collector(
1611            FnCollector::new(
1612                "plots",
1613                "The plots drawn, by id: their label and accessible summary, their series (name, kind, point count, x and y ranges, colour), the bounds in view, the point under the pointer (series, index, x, y), the time cursor, the time scale and the x axis' labels, the highlighted range, and every line's value at the pointer or the cursor.",
1614            )
1615            .snapshot(move |_| Plots::of(&egui).describe()),
1616        )?;
1617        Ok(())
1618    }
1619}
1620
1621#[cfg(test)]
1622mod tests {
1623    use super::*;
1624
1625    #[test]
1626    fn a_series_knows_its_ranges() {
1627        let s = Series::line("a", [[1.0, 5.0], [3.0, -2.0], [f64::NAN, 9.0], [2.0, 0.0]]);
1628        assert_eq!(s.ranges(), Some(([1.0, 3.0], [-2.0, 5.0])));
1629        assert_eq!(Series::points("b", []).ranges(), None);
1630    }
1631
1632    #[test]
1633    fn numbers_keep_four_significant_digits() {
1634        assert_eq!(number(0.0), "0");
1635        assert_eq!(number(12.5), "12.5");
1636        assert_eq!(number(1234.5678), "1235");
1637        assert_eq!(number(0.012_345), "0.01235");
1638        assert_eq!(number(-3.0), "-3");
1639    }
1640
1641    #[test]
1642    fn the_summary_says_each_series_and_the_cursor() {
1643        let ctx = Context::default();
1644        let series = [
1645            Series::line("Speed", [[0.0, 1.0], [10.0, 3.5]]),
1646            Series::bars("Count", []),
1647        ];
1648        let s = summary(&ctx, &series, Some(4.0));
1649        assert_eq!(
1650            s,
1651            "Speed (line): 2 points, x from 0 to 10, y from 1 to 3.5. Count (bars): no points. Time cursor at 4"
1652        );
1653    }
1654
1655    #[test]
1656    fn a_stepped_line_holds_each_value_until_the_next_point() {
1657        assert_eq!(
1658            step_points(&[[0.0, 1.0], [2.0, 3.0], [5.0, 2.0]]),
1659            vec![[0.0, 1.0], [2.0, 1.0], [2.0, 3.0], [5.0, 3.0], [5.0, 2.0]]
1660        );
1661        assert!(step_points(&[]).is_empty());
1662    }
1663
1664    #[test]
1665    fn values_at_an_x_interpolate_lines_and_hold_steps() {
1666        let series = [
1667            Series::line("speed", [[0.0, 0.0], [10.0, 5.0]]),
1668            Series::steps("gear", [[0.0, 1.0], [4.0, 2.0], [8.0, 3.0]]),
1669            Series::points("samples", [[4.0, 9.0]]),
1670            Series::line("late", [[6.0, 1.0], [9.0, 1.0]]),
1671        ];
1672        let v = values_at(&series, 4.0);
1673        let pairs: Vec<(&str, f64)> = v.iter().map(|v| (v.name.as_str(), v.y)).collect();
1674        assert_eq!(pairs, vec![("speed", 2.0), ("gear", 2.0)]);
1675        let v = values_at(&series, 7.0);
1676        let pairs: Vec<(&str, f64)> = v.iter().map(|v| (v.name.as_str(), v.y)).collect();
1677        assert_eq!(pairs, vec![("speed", 3.5), ("gear", 2.0), ("late", 1.0)]);
1678        // At the last point, its value; past it, none.
1679        assert_eq!(values_at(&series, 10.0)[0].y, 5.0);
1680        assert!(values_at(&series, 11.0).is_empty());
1681    }
1682
1683    #[test]
1684    fn an_entity_keeps_its_slot() {
1685        let a = entity_slot("/world/robot/left_wheel");
1686        assert_eq!(a, entity_slot("/world/robot/left_wheel"));
1687        // FNV-1a's offset basis for the empty path.
1688        assert_eq!(
1689            entity_slot(""),
1690            (0xcbf2_9ce4_8422_2325_u64 % 27_720) as usize
1691        );
1692        let palette = Tokens::default().palette;
1693        let s = Series::line("left", []).entity("/world/robot/left_wheel");
1694        assert_eq!(Plot::color_of(&palette, &s, 0), palette.series(a));
1695        // Spread over the slots: twenty paths take at least five colours.
1696        let slots: std::collections::BTreeSet<usize> = (0..20)
1697            .map(|i| entity_slot(&format!("/sensor/{i}")) % palette.category.len())
1698            .collect();
1699        assert!(slots.len() >= 5, "{slots:?}");
1700    }
1701
1702    /// The labels the axis shows for `span` seconds across `width` points.
1703    fn labels(scale: TimeScale, from: f64, span: f64, width: f64) -> Vec<String> {
1704        let input = GridInput {
1705            bounds: (from, from + span),
1706            base_step_size: span / width * 8.0,
1707        };
1708        let (_, marks) = time_marks(&scale, input, 7.0);
1709        marks.into_iter().filter_map(|m| m.label).collect()
1710    }
1711
1712    #[test]
1713    fn the_time_axis_ticks_follow_the_scale() {
1714        // Seconds: a minute across 600 points, a label every ten seconds.
1715        let l = labels(TimeScale::Seconds, 0.0, 60.0, 600.0);
1716        assert_eq!(l.first().map(String::as_str), Some("0:00"));
1717        assert!(l.contains(&"0:10".to_string()), "{l:?}");
1718        // Frames: timecode labels, two seconds at 25 fps.
1719        let l = labels(TimeScale::frames(25), 0.0, 2.0, 800.0);
1720        assert!(
1721            l.iter().all(|s| s.len() == 11 && s.starts_with("00:00:0")),
1722            "{l:?}"
1723        );
1724        assert!(
1725            l.contains(&"00:00:00:10".to_string()) && l.contains(&"00:00:02:00".to_string()),
1726            "{l:?}"
1727        );
1728        // Bars and beats at 120 BPM: a bar is two seconds, labelled by bar.
1729        let l = labels(TimeScale::beats(120.0), 0.0, 16.0, 400.0);
1730        assert!(
1731            l.contains(&"1".to_string()) && l.contains(&"2".to_string()),
1732            "{l:?}"
1733        );
1734        // Nothing to show: no ticks.
1735        assert!(labels(TimeScale::Seconds, 0.0, 0.0, 400.0).is_empty());
1736    }
1737
1738    #[test]
1739    fn a_series_takes_its_slot_or_its_place() {
1740        let palette = Tokens::default().palette;
1741        let a = Series::line("a", []);
1742        assert_eq!(Plot::color_of(&palette, &a, 2), palette.category[2]);
1743        let b = Series::line("b", []).slot(7);
1744        assert_eq!(Plot::color_of(&palette, &b, 0), palette.category[7]);
1745        // Past the last slot, round again.
1746        assert_eq!(palette.series(12), palette.category[2]);
1747        let c = Series::line("c", []).color(Color32::RED);
1748        assert_eq!(Plot::color_of(&palette, &c, 0), Color32::RED);
1749    }
1750
1751    /// A noisy series of `n` samples over `[0, length]`, sorted by x.
1752    fn noisy(n: usize, length: f64) -> Vec<[f64; 2]> {
1753        let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
1754        (0..n)
1755            .map(|i| {
1756                seed ^= seed << 13;
1757                seed ^= seed >> 7;
1758                seed ^= seed << 17;
1759                let noise = (seed >> 11) as f64 / (1u64 << 53) as f64 - 0.5;
1760                let x = i as f64 * length / (n - 1) as f64;
1761                [x, (x * 0.3).sin() + noise]
1762            })
1763            .collect()
1764    }
1765
1766    #[test]
1767    fn a_series_knows_whether_it_is_sorted() {
1768        let st = scan(&[[0.0, 1.0], [1.0, f64::NAN], [1.0, 3.0], [4.0, -2.0]]);
1769        assert!(st.sorted);
1770        assert_eq!(st.ranges, Some(([0.0, 4.0], [-2.0, 3.0])));
1771        assert!(!scan(&[[0.0, 1.0], [2.0, 1.0], [1.0, 1.0]]).sorted);
1772        assert!(!scan(&[[0.0, 1.0], [f64::NAN, 1.0], [1.0, 1.0]]).sorted);
1773        // A band's y range spans its minimums and maximums.
1774        let st = scan(&[[0.0, 1.0, 2.0], [1.0, -1.0, 0.5]]);
1775        assert_eq!(st.ranges, Some(([0.0, 1.0], [-1.0, 2.0])));
1776        // The same as the series says.
1777        let s = Series::line("a", noisy(5_000, 10.0));
1778        assert_eq!(scan(&s.points).ranges, s.ranges());
1779        // A long series' stats are kept while its points look the same.
1780        let ctx = Context::default();
1781        let key = Id::unique("stats");
1782        let mut points = noisy(10_000, 10.0);
1783        assert!(stats(&ctx, key, &points).sorted);
1784        points.swap(0, 9_999);
1785        assert!(!stats(&ctx, key, &points).sorted);
1786    }
1787
1788    #[test]
1789    fn hover_finds_the_true_sample_not_a_decimated_one() {
1790        let points = noisy(1_000_000, 100.0);
1791        let series = [Series::line("noisy", points.clone())];
1792        let frame = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 200.0));
1793        let bounds = egui_plot::PlotBounds::from_min_max([0.0, -2.0], [100.0, 2.0]);
1794        let transform = PlotTransform::new(frame, bounds, false);
1795        let sorted = [scan(&series[0].points)];
1796        assert!(sorted[0].sorted);
1797        let unsorted = [Stats {
1798            sorted: false,
1799            ranges: None,
1800        }];
1801        let window = Window::new(0.0, 100.0, 800);
1802        let mut drawn = Vec::new();
1803        decimate::line(&points, &window, &mut drawn);
1804        for (x, dy) in [(37.5, 0.2), (61.0, -0.3), (99.9, 0.0), (0.05, 0.1)] {
1805            let y = (x * 0.3_f64).sin() + dy;
1806            let pos = transform.position_from_point(&PlotPoint::new(x, y));
1807            let fast = nearest(&series, &sorted, &transform, pos, &|_| 0.0, 0.8);
1808            let full = nearest(&series, &unsorted, &transform, pos, &|_| 0.0, 0.8);
1809            assert_eq!(fast, full, "at {x}, {y}");
1810            let h = fast.expect("a sample under the pointer");
1811            assert_eq!([h.x, h.y], points[h.index]);
1812        }
1813        // In the dense middle, the nearest sample is none of the column's
1814        // four drawn points.
1815        let pos = transform.position_from_point(&PlotPoint::new(37.5, (37.5_f64 * 0.3).sin()));
1816        let h = nearest(&series, &sorted, &transform, pos, &|_| 0.0, 0.8).expect("a sample");
1817        assert!(!drawn.contains(&[h.x, h.y]), "{h:?}");
1818    }
1819}