Skip to main content

weirdnet_chart/
viewport.rs

1//! The visible time window: pan, zoom and following the live edge.
2
3use crate::scale::LinearScale;
4use crate::time::{DAY, Timestamp};
5
6/// The visible time range `[start, end]` of a chart.
7///
8/// While *following*, new data keeps the newest sample at the right edge (less a small
9/// margin). Panning back in time stops following; [`Chart`](crate::Chart) turns it back on when
10/// the view is panned or zoomed back to the newest sample.
11#[derive(Clone, Copy, Debug, PartialEq)]
12pub struct Viewport {
13    start: Timestamp,
14    end: Timestamp,
15    following: bool,
16    min_span: i64,
17    max_span: i64,
18    right_margin: f64,
19}
20
21impl Default for Viewport {
22    /// The last hour before the Unix epoch, following.
23    fn default() -> Self {
24        Viewport::new(-3_600_000, 0)
25    }
26}
27
28impl Viewport {
29    /// A following viewport over `[start, end]`.
30    pub fn new(start: Timestamp, end: Timestamp) -> Viewport {
31        let mut v = Viewport { start: 0, end: 1, following: true, min_span: 1, max_span: 1_000 * 365 * DAY, right_margin: 0.03 };
32        v.set_range(start, end);
33        v
34    }
35
36    /// The first visible time.
37    pub fn start(&self) -> Timestamp {
38        self.start
39    }
40
41    /// The last visible time.
42    pub fn end(&self) -> Timestamp {
43        self.end
44    }
45
46    /// `end - start`, at least 1.
47    pub fn span(&self) -> i64 {
48        self.end - self.start
49    }
50
51    /// Whether new data scrolls the view.
52    pub fn is_following(&self) -> bool {
53        self.following
54    }
55
56    /// Turns following on or off.
57    pub fn set_following(&mut self, following: bool) {
58        self.following = following;
59    }
60
61    /// The fraction of the span left empty to the right of the newest sample while following.
62    pub fn right_margin(&self) -> f64 {
63        self.right_margin
64    }
65
66    /// Sets the right margin (clamped to `0.0..=0.5`).
67    pub fn set_right_margin(&mut self, fraction: f64) {
68        self.right_margin = fraction.clamp(0.0, 0.5);
69    }
70
71    /// Limits how far zoom can go in and out, in milliseconds.
72    pub fn set_span_limits(&mut self, min_span: i64, max_span: i64) {
73        self.min_span = min_span.max(1);
74        self.max_span = max_span.max(self.min_span);
75        let (s, e) = (self.start, self.end);
76        self.set_range(s, e);
77    }
78
79    /// Shows `[start, end]`, keeping the centre if the span has to be clamped.
80    pub fn set_range(&mut self, start: Timestamp, end: Timestamp) {
81        let (start, end) = if end < start { (end, start) } else { (start, end) };
82        let span = (end - start).clamp(self.min_span, self.max_span);
83        let mid = start + (end - start) / 2;
84        self.start = mid - span / 2;
85        self.end = self.start + span;
86    }
87
88    /// Moves the window by `delta` milliseconds (positive is later). Moving back stops following.
89    pub fn pan(&mut self, delta: i64) {
90        self.start = self.start.saturating_add(delta);
91        self.end = self.end.saturating_add(delta);
92        if delta < 0 {
93            self.following = false;
94        }
95    }
96
97    /// Moves the window by a fraction of its span (positive is later).
98    pub fn pan_fraction(&mut self, fraction: f64) {
99        self.pan((self.span() as f64 * fraction).round() as i64);
100    }
101
102    /// Moves the window for a drag of `dx` pixels across a plot `width` pixels wide:
103    /// dragging right shows earlier times.
104    pub fn pan_pixels(&mut self, dx: f64, width: f64) {
105        if width > 0.0 {
106            self.pan_fraction(-dx / width);
107        }
108    }
109
110    /// Scales the span by `factor` (below 1 zooms in) keeping the time at `anchor` (a fraction
111    /// of the width, 0 is the left edge) in place.
112    pub fn zoom(&mut self, factor: f64, anchor: f64) {
113        if !(factor.is_finite() && factor > 0.0) {
114            return;
115        }
116        let anchor = anchor.clamp(0.0, 1.0);
117        let span = self.span() as f64;
118        let new_span = (span * factor).clamp(self.min_span as f64, self.max_span as f64);
119        let pivot = self.start as f64 + span * anchor;
120        self.start = (pivot - new_span * anchor).round() as i64;
121        self.end = self.start + new_span.round() as i64;
122    }
123
124    /// [`zoom`](Self::zoom) around pixel `x` of a plot `width` pixels wide.
125    pub fn zoom_at_pixel(&mut self, factor: f64, x: f64, width: f64) {
126        if width > 0.0 {
127            self.zoom(factor, x / width);
128        }
129    }
130
131    /// While following, shifts the window so `latest` sits at the right edge less the margin.
132    pub fn follow_to(&mut self, latest: Timestamp) {
133        if self.following {
134            let span = self.span();
135            let margin = (span as f64 * self.right_margin).round() as i64;
136            self.end = latest + margin;
137            self.start = self.end - span;
138        }
139    }
140
141    /// The time at pixel `x` of a plot from `left` that is `width` pixels wide.
142    pub fn time_at(&self, x: f64, left: f64, width: f64) -> Timestamp {
143        self.scale(left, left + width).invert(x).round() as Timestamp
144    }
145
146    /// A scale from this window onto `[x0, x1]`.
147    pub fn scale(&self, x0: f64, x1: f64) -> LinearScale {
148        LinearScale::new((self.start as f64, self.end as f64), (x0, x1))
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn pan_and_zoom() {
158        let mut v = Viewport::new(0, 1000);
159        v.pan_pixels(50.0, 100.0);
160        assert_eq!((v.start(), v.end()), (-500, 500));
161        assert!(!v.is_following());
162        v.zoom(0.5, 1.0);
163        assert_eq!((v.start(), v.end()), (0, 500));
164        v.zoom_at_pixel(2.0, 0.0, 100.0);
165        assert_eq!((v.start(), v.end()), (0, 1000));
166        assert_eq!(v.time_at(50.0, 0.0, 100.0), 500);
167    }
168
169    #[test]
170    fn follows_the_live_edge() {
171        let mut v = Viewport::new(0, 1000);
172        v.set_right_margin(0.1);
173        v.follow_to(5000);
174        assert_eq!((v.start(), v.end()), (4100, 5100));
175        v.pan(-10);
176        v.follow_to(9000);
177        assert_eq!(v.end(), 5090);
178    }
179
180    #[test]
181    fn span_limits_clamp() {
182        let mut v = Viewport::new(0, 1000);
183        v.set_span_limits(100, 2000);
184        v.zoom(0.001, 0.5);
185        assert_eq!(v.span(), 100);
186        v.zoom(1000.0, 0.5);
187        assert_eq!(v.span(), 2000);
188        v.set_range(10, 10);
189        assert_eq!(v.span(), 100);
190    }
191}