Debian Codegraph @

src/components/time_series/auto_y.rs

raw symbols SCIP
1 use std::{
2 borrow::Cow,
3 time::{Duration, Instant},
4 };
5
6 use ratatui::{Frame, layout::Rect};
7 use timeless::data::ChunkedData;
8
9 use super::{
10 AxisBound, ChartScaling, GraphData, GraphDrawCtx, TimeGraph, TimeseriesConfig, TimeseriesState,
11 };
12
13 struct GraphHeightCacheInner {
14 best_point: (Instant, f64),
15 right_edge: Instant,
16 period: u64,
17 }
18
19 #[derive(Default)]
20 pub struct GraphHeightCache {
21 inner: Option<GraphHeightCacheInner>,
22 }
23
24 impl GraphHeightCache {
25 /// Get the cached height if it exists, or update it otherwise.
26 pub(crate) fn get_or_update<
27 'a,
28 F: Into<f64> + Clone + Copy + 'a,
29 S: Iterator<Item = &'a ChunkedData<F>>,
30 >(
31 &mut self, last_time: &Instant, current_display_time: u64, sources: S, times: &[Instant],
32 ) -> f64 {
33 let visible_duration = Duration::from_millis(current_display_time);
34
35 let (mut biggest, mut biggest_time, oldest_to_check) = if let Some(GraphHeightCacheInner {
36 best_point,
37 right_edge,
38 period,
39 }) = self.inner.as_ref()
40 && *period == current_display_time
41 && last_time.duration_since(best_point.0) < visible_duration
42 {
43 (best_point.1, best_point.0, *right_edge)
44 } else {
45 let visible_duration = Duration::from_millis(current_display_time);
46
47 let visible_left_bound = match last_time.checked_sub(visible_duration) {
48 Some(v) => v,
49 None => {
50 // On some systems (like Windows) it can be possible that the
51 // current display time causes subtraction to fail if, for example,
52 // the uptime of the system is too low and current_display_time is
53 // too high. See https://github.com/ClementTsang/bottom/issues/1825.
54 //
55 // As such, we instead take the oldest visible time. This is a bit
56 // inefficient, but since it should only happen rarely, it's fine.
57 times
58 .iter()
59 .take_while(|t| last_time.duration_since(**t) < visible_duration)
60 .last()
61 .cloned()
62 .unwrap_or(*last_time)
63 }
64 };
65
66 (0.0, visible_left_bound, visible_left_bound)
67 };
68
69 for source in sources {
70 for (&time, &v) in source
71 .iter_along_base(times)
72 .rev()
73 .take_while(|&(&time, _)| time >= oldest_to_check)
74 {
75 let v = v.into();
76 if v > biggest {
77 biggest = v;
78 biggest_time = time;
79 }
80 }
81 }
82
83 self.inner = Some(GraphHeightCacheInner {
84 best_point: (biggest_time, biggest),
85 right_edge: *last_time,
86 period: current_display_time,
87 });
88
89 biggest
90 }
91 }
92
93 /// A time series graph that automatically adjusts the y-axis based on the data provided.
94 pub struct AutoYAxisTimeGraph {
95 state: TimeseriesState,
96 height_cache: GraphHeightCache,
97 }
98
99 impl AutoYAxisTimeGraph {
100 pub(crate) fn new(config: TimeseriesConfig, autohide_timer: Option<Instant>) -> Self {
101 AutoYAxisTimeGraph {
102 state: TimeseriesState::new(config, autohide_timer),
103 height_cache: GraphHeightCache::default(),
104 }
105 }
106
107 pub(crate) fn state_mut(&mut self) -> &mut TimeseriesState {
108 &mut self.state
109 }
110
111 pub(crate) fn y_max<'a, F, S>(&mut self, sources: S, times: &[Instant]) -> f64
112 where
113 F: Into<f64> + Clone + Copy + 'a,
114 S: Iterator<Item = &'a ChunkedData<F>>,
115 {
116 if let Some(last_time) = times.last() {
117 self.height_cache.get_or_update(
118 last_time,
119 self.state.current_display_time(),
120 sources,
121 times,
122 )
123 } else {
124 0.0
125 }
126 }
127
128 pub(crate) fn draw<F: Copy + Default + Into<f64>>(
129 &self, f: &mut Frame<'_>, draw_loc: Rect, ctx: GraphDrawCtx<'_>, y_bounds: AxisBound,
130 y_labels: &[Cow<'_, str>], scaling: ChartScaling, data: Vec<GraphData<'_, F>>,
131 ) {
132 TimeGraph {
133 x_min: -(self.state.current_display_time() as f64),
134 hide_x_labels: ctx.hide_x_labels,
135 y_bounds,
136 y_labels,
137 graph_style: ctx.graph_style,
138 general_widget_style: ctx.general_widget_style,
139 border_style: ctx.border_style,
140 border_type: ctx.border_type,
141 title: ctx.title,
142 is_selected: ctx.is_selected,
143 is_expanded: ctx.is_expanded,
144 title_style: ctx.title_style,
145 legend_position: ctx.legend_position,
146 legend_constraints: ctx.legend_constraints,
147 marker: ctx.marker,
148 scaling,
149 }
150 .draw(f, draw_loc, data)
151 }
152 }
153
154 #[cfg(test)]
155 mod tests {
156 use super::*;
157
158 #[test]
159 fn empty_sources_returns_zero() {
160 let mut cache = GraphHeightCache::default();
161 let last_time = Instant::now();
162 let times: Vec<Instant> = vec![];
163 let sources: Vec<ChunkedData<f64>> = vec![];
164
165 let result = cache.get_or_update(&last_time, 1_000, sources.iter(), &times);
166 assert_eq!(result, 0.0);
167 assert!(cache.inner.is_some());
168 }
169 }