Skip to main content

egui_pop_views/timeline/
ruler.rs

1//! The ruler's arithmetic, without egui: which steps its ticks and labels
2//! take at a zoom, where they go, and what snapping lands on.
3
4use super::scale::TimeScale;
5use super::state::TimeView;
6
7/// The least room between two minor ticks, in points.
8pub const MIN_TICK_GAP: f32 = 6.0;
9/// The room kept between two labels, in points.
10pub const LABEL_GAP: f32 = 10.0;
11/// Where a label starts after its tick, in points.
12pub const LABEL_INSET: f32 = 3.0;
13
14/// The ruler's steps at a zoom, in seconds: a label at each major tick, a
15/// short tick at each minor one (the grid snapping lands on).
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct Ticks {
18    pub major: f64,
19    pub minor: f64,
20}
21
22/// A tick of the ruler.
23#[derive(Clone, Debug, PartialEq)]
24pub struct Mark {
25    pub time: f64,
26    /// Points from the ruler's left edge.
27    pub x: f32,
28    pub major: bool,
29    /// A major tick's label.
30    pub label: Option<String>,
31}
32
33/// The steps the ruler takes for `view` across `width` points: the finest
34/// whose labels, measured by `measure` (their width in points), never
35/// overlap; and under it the finest grid that divides it and keeps
36/// [`MIN_TICK_GAP`].
37pub fn ticks(
38    scale: &TimeScale,
39    view: &TimeView,
40    width: f32,
41    measure: &dyn Fn(&str) -> f32,
42) -> Ticks {
43    let width = width.max(1.0);
44    let per_point = view.duration.max(f64::MIN_POSITIVE) / f64::from(width);
45    let mut steps = scale.steps();
46    // Past the coarsest step, doubling it.
47    let mut last = steps.last().copied().unwrap_or(1.0);
48    while last / per_point < f64::from(width) {
49        last *= 2.0;
50        steps.push(last);
51    }
52    let room = |step: f64| (step / per_point) as f32;
53    let widest = |step: f64| {
54        // The widest labels sit at the ends (the most digits, a sign).
55        [view.start, view.end(), view.start + view.duration / 2.0]
56            .iter()
57            .map(|t| measure(&scale.label(scale.round_to(*t, step), step)))
58            .fold(0.0_f32, f32::max)
59    };
60    let major = steps
61        .iter()
62        .copied()
63        .find(|s| room(*s) >= MIN_TICK_GAP && room(*s) >= widest(*s) + LABEL_INSET + LABEL_GAP)
64        .unwrap_or(last);
65    let minor = steps
66        .iter()
67        .copied()
68        .filter(|s| *s <= major && room(*s) >= MIN_TICK_GAP)
69        .find(|s| {
70            let r = major / s;
71            (r - r.round()).abs() < 1e-6
72        })
73        .unwrap_or(major);
74    Ticks { major, minor }
75}
76
77/// The ticks in view and their labels.
78pub fn marks(scale: &TimeScale, view: &TimeView, width: f32, ticks: Ticks) -> Vec<Mark> {
79    let origin = scale.origin();
80    let every = (ticks.major / ticks.minor).round().max(1.0) as i64;
81    let first = ((view.start - origin) / ticks.minor).floor() as i64;
82    let last = ((view.end() - origin) / ticks.minor).ceil() as i64;
83    // A tick for every few points at most: never more than the width holds.
84    if last - first > i64::from(width as i32) + 2 {
85        return Vec::new();
86    }
87    (first..=last)
88        .map(|k| {
89            let time = origin + k as f64 * ticks.minor;
90            let major = k.rem_euclid(every) == 0;
91            Mark {
92                time,
93                x: view.x_of(time, width),
94                major,
95                label: major.then(|| scale.label(time, ticks.major)),
96            }
97        })
98        .collect()
99}
100
101/// What a time snapped to.
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103pub enum Snapped {
104    /// Nothing: the time as given (on the scale's units).
105    Free,
106    Grid,
107    Marker,
108    Playhead,
109    /// An end of the range.
110    Range,
111    /// An edge of a clip.
112    Clip,
113}
114
115/// Points a time is pulled to, with what each is.
116#[derive(Clone, Debug, Default)]
117pub struct SnapTargets {
118    /// The grid's step (the ruler's minor ticks), if it snaps to the grid.
119    pub grid: Option<f64>,
120    pub points: Vec<(f64, Snapped)>,
121}
122
123/// `time` snapped: to the nearest point within `reach` seconds, else to the
124/// grid when there is one, else onto the scale's units.
125pub fn snap(scale: &TimeScale, time: f64, targets: &SnapTargets, reach: f64) -> (f64, Snapped) {
126    let near = targets
127        .points
128        .iter()
129        .map(|(t, what)| ((t - time).abs(), *t, *what))
130        .filter(|(d, _, _)| *d <= reach)
131        .min_by(|a, b| a.0.total_cmp(&b.0));
132    if let Some((_, t, what)) = near {
133        return (t, what);
134    }
135    match targets.grid {
136        Some(step) => (scale.round_to(time, step), Snapped::Grid),
137        None => (scale.quantize(time), Snapped::Free),
138    }
139}
140
141/// Where a span `length` long starting near `start` snaps: whichever of its
142/// edges is nearer a point within `reach` lands on it; otherwise its start
143/// goes onto the grid (or the scale's units). Its new start, and what it
144/// snapped to.
145pub fn snap_span(
146    scale: &TimeScale,
147    start: f64,
148    length: f64,
149    targets: &SnapTargets,
150    reach: f64,
151) -> (f64, Snapped) {
152    let nearest = |t: f64| {
153        targets
154            .points
155            .iter()
156            .map(|(p, what)| ((p - t).abs(), *p - t, *what))
157            .filter(|(d, _, _)| *d <= reach)
158            .min_by(|a, b| a.0.total_cmp(&b.0))
159    };
160    let by_start = nearest(start);
161    let by_end = nearest(start + length);
162    let pick = match (by_start, by_end) {
163        (Some(a), Some(b)) => Some(if b.0 < a.0 { b } else { a }),
164        (a, b) => a.or(b),
165    };
166    if let Some((_, shift, what)) = pick {
167        return (start + shift, what);
168    }
169    match targets.grid {
170        Some(step) => (scale.round_to(start, step), Snapped::Grid),
171        None => (scale.quantize(start), Snapped::Free),
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use crate::timeline::scale::{FrameRate, Tempo};
179
180    /// A monospaced font of 7 points a character.
181    fn mono(text: &str) -> f32 {
182        text.chars().count() as f32 * 7.0
183    }
184
185    fn scales() -> Vec<TimeScale> {
186        vec![
187            TimeScale::Seconds,
188            TimeScale::frames(25),
189            TimeScale::Frames(FrameRate::NTSC),
190            TimeScale::beats(128.0),
191            TimeScale::Beats(Tempo::new(90.0, 3, 4).offset(0.3)),
192        ]
193    }
194
195    #[test]
196    fn labels_never_overlap_at_any_zoom() {
197        for scale in scales() {
198            for width in [180.0_f32, 640.0, 1400.0] {
199                let mut duration = 0.05;
200                while duration < 200_000.0 {
201                    for start in [-duration / 3.0, 0.0, 12.34, 3599.0] {
202                        let view = TimeView::new(start, duration);
203                        let t = ticks(&scale, &view, width, &mono);
204                        let marks = marks(&scale, &view, width, t);
205                        let mut end = f32::NEG_INFINITY;
206                        let mut labels = 0;
207                        for m in marks.iter().filter(|m| m.major) {
208                            let label = m.label.as_deref().unwrap();
209                            let from = m.x + LABEL_INSET;
210                            assert!(
211                                from >= end,
212                                "{scale:?} {view:?} {width}: `{label}` at {from} over the last label ending at {end}"
213                            );
214                            end = from + mono(label);
215                            if m.x >= 0.0 && m.x <= width {
216                                labels += 1;
217                            }
218                        }
219                        // Something to read once there is room for two.
220                        if width >= 640.0 {
221                            assert!(labels >= 1, "{scale:?} {view:?} {width}: no label");
222                        }
223                        assert!(t.minor <= t.major && t.minor > 0.0);
224                    }
225                    duration *= 1.7;
226                }
227            }
228        }
229    }
230
231    #[test]
232    fn tick_spacing_follows_the_zoom() {
233        let s = TimeScale::Seconds;
234        let at = |duration: f64| ticks(&s, &TimeView::new(0.0, duration), 600.0, &mono);
235        // A minute across 600 points: "0:05" every 5 s (50 points), a tick a second.
236        assert_eq!(
237            at(60.0),
238            Ticks {
239                major: 5.0,
240                minor: 1.0
241            }
242        );
243        // An hour: "10:00" every 10 minutes ("1:00:00" is too wide for 5).
244        assert_eq!(at(3600.0).major, 600.0);
245        // Two seconds: tenths labelled.
246        assert_eq!(at(2.0).major, 0.2);
247        // Frames: never finer than one frame.
248        let f = TimeScale::frames(25);
249        let t = ticks(&f, &TimeView::new(0.0, 0.2), 600.0, &mono);
250        assert!(t.minor >= 0.04 - 1e-12, "{t:?}");
251        // Beats at 128 BPM over 8 bars: a label every bar, a tick every
252        // half beat.
253        let b = TimeScale::beats(128.0);
254        let t = ticks(&b, &TimeView::new(0.0, 15.0), 600.0, &mono);
255        assert_eq!(
256            t,
257            Ticks {
258                major: 1.875,
259                minor: 0.234375
260            }
261        );
262    }
263
264    #[test]
265    fn snapping_prefers_near_points_then_the_grid() {
266        let s = TimeScale::Seconds;
267        let targets = SnapTargets {
268            grid: Some(1.0),
269            points: vec![(10.3, Snapped::Marker), (10.6, Snapped::Playhead)],
270        };
271        assert_eq!(snap(&s, 10.4, &targets, 0.2), (10.3, Snapped::Marker));
272        assert_eq!(snap(&s, 10.55, &targets, 0.2), (10.6, Snapped::Playhead));
273        assert_eq!(snap(&s, 12.4, &targets, 0.2), (12.0, Snapped::Grid));
274        let free = SnapTargets::default();
275        assert_eq!(snap(&s, 12.4, &free, 0.2), (12.4, Snapped::Free));
276        // Frames stay whole even free.
277        let f = TimeScale::frames(25);
278        assert_eq!(snap(&f, 1.01, &free, 0.2), (1.0, Snapped::Free));
279    }
280
281    #[test]
282    fn a_span_snaps_by_its_nearer_edge() {
283        let s = TimeScale::Seconds;
284        let targets = SnapTargets {
285            grid: Some(1.0),
286            points: vec![(10.0, Snapped::Clip), (20.0, Snapped::Playhead)],
287        };
288        // Its end is nearer the clip's edge than its start the playhead.
289        assert_eq!(snap_span(&s, 6.1, 4.0, &targets, 0.5), (6.0, Snapped::Clip));
290        assert_eq!(
291            snap_span(&s, 19.8, 4.0, &targets, 0.5),
292            (20.0, Snapped::Playhead)
293        );
294        // Nothing near: its start on the grid.
295        assert_eq!(
296            snap_span(&s, 13.4, 4.0, &targets, 0.5),
297            (13.0, Snapped::Grid)
298        );
299    }
300}