Skip to main content

egui_pop_views/timeline/
state.rs

1//! [`TimelineState`]: what a timeline shows and holds, serializable, and the
2//! edits made on it, without egui.
3
4use egui::Color32;
5use serde::{Deserialize, Serialize};
6
7use super::scale::TimeScale;
8use super::tracks::{Clip, ClipPlace, ClipSpan, Track};
9
10/// The fastest J or L shuttles, in either direction.
11pub const MAX_SPEED: f64 = 32.0;
12
13/// The part of time in view: from `start`, `duration` long (seconds).
14#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
15pub struct TimeView {
16    pub start: f64,
17    pub duration: f64,
18}
19
20impl Default for TimeView {
21    fn default() -> Self {
22        Self {
23            start: 0.0,
24            duration: 60.0,
25        }
26    }
27}
28
29impl TimeView {
30    pub fn new(start: f64, duration: f64) -> Self {
31        Self { start, duration }
32    }
33
34    pub fn end(&self) -> f64 {
35        self.start + self.duration
36    }
37
38    /// Where `time` is across `width` points (0 at the start).
39    pub fn x_of(&self, time: f64, width: f32) -> f32 {
40        ((time - self.start) / self.duration.max(f64::MIN_POSITIVE) * f64::from(width)) as f32
41    }
42
43    /// The time at `x` points across `width`.
44    pub fn time_at(&self, x: f32, width: f32) -> f64 {
45        self.start + f64::from(x) / f64::from(width.max(1.0)) * self.duration
46    }
47
48    /// Zoomed by `factor` (above 1: closer) keeping `at` where it is.
49    pub fn zoomed(&self, factor: f64, at: f64) -> TimeView {
50        let factor = if factor.is_finite() && factor > 0.0 {
51            factor
52        } else {
53            1.0
54        };
55        let duration = self.duration / factor;
56        let keep = (at - self.start) / self.duration.max(f64::MIN_POSITIVE);
57        TimeView {
58            start: at - keep * duration,
59            duration,
60        }
61    }
62
63    /// Whether `time` is in view.
64    pub fn contains(&self, time: f64) -> bool {
65        time >= self.start && time <= self.end()
66    }
67}
68
69/// A span of time, `start` before `end` (seconds).
70#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
71pub struct TimeRange {
72    pub start: f64,
73    pub end: f64,
74}
75
76impl TimeRange {
77    /// From the earlier of `a` and `b` to the later.
78    pub fn new(a: f64, b: f64) -> Self {
79        Self {
80            start: a.min(b),
81            end: a.max(b),
82        }
83    }
84
85    pub fn duration(&self) -> f64 {
86        self.end - self.start
87    }
88
89    pub fn contains(&self, time: f64) -> bool {
90        time >= self.start && time <= self.end
91    }
92
93    pub fn clamp(&self, time: f64) -> f64 {
94        time.clamp(self.start, self.end)
95    }
96}
97
98/// A marker, or a cue point (a DJ's hot cue, drawn as a pin).
99#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
100#[serde(rename_all = "snake_case")]
101pub enum MarkerKind {
102    #[default]
103    Marker,
104    Cue,
105}
106
107/// A named point in time.
108#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
109pub struct Marker {
110    /// Unique in its timeline.
111    pub id: u64,
112    pub time: f64,
113    pub label: String,
114    #[serde(default)]
115    pub kind: MarkerKind,
116    /// Its own colour; the theme's (`timeline.marker`) when `None`.
117    #[serde(default)]
118    pub color: Option<Color32>,
119}
120
121impl Marker {
122    pub fn new(id: u64, time: f64, label: impl Into<String>) -> Self {
123        Self {
124            id,
125            time,
126            label: label.into(),
127            kind: MarkerKind::Marker,
128            color: None,
129        }
130    }
131
132    pub fn kind(mut self, kind: MarkerKind) -> Self {
133        self.kind = kind;
134        self
135    }
136
137    pub fn color(mut self, color: Color32) -> Self {
138        self.color = Some(color);
139        self
140    }
141}
142
143/// Whether the timeline asks to play.
144#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
145#[serde(rename_all = "snake_case")]
146pub enum PlayState {
147    #[default]
148    Paused,
149    Playing,
150}
151
152/// The document's part of a timeline: what its history keeps, one step per
153/// change (the markers, the range, the loop, the tracks and their clips).
154#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
155#[serde(default)]
156pub struct TimelineDoc {
157    pub markers: Vec<Marker>,
158    pub range: Option<TimeRange>,
159    pub looping: bool,
160    pub tracks: Vec<Track>,
161}
162
163/// A change of a timeline's document, as its output reports it.
164#[derive(Clone, Debug, PartialEq)]
165#[non_exhaustive]
166pub enum Edit {
167    MarkerAdded(Marker),
168    MarkerMoved {
169        id: u64,
170        from: f64,
171        to: f64,
172    },
173    MarkerRemoved(Marker),
174    RangeSet {
175        from: Option<TimeRange>,
176        to: Option<TimeRange>,
177    },
178    LoopSet(bool),
179    ClipAdded {
180        track: u64,
181        clip: Clip,
182    },
183    /// A clip moved, along its track or to another.
184    ClipMoved {
185        id: u64,
186        from: ClipPlace,
187        to: ClipPlace,
188    },
189    /// A clip's start or end moved, its offset into its source following
190    /// its start.
191    ClipTrimmed {
192        id: u64,
193        from: ClipSpan,
194        to: ClipSpan,
195    },
196    ClipRemoved {
197        track: u64,
198        clip: Clip,
199    },
200    /// A clip split in two at `at`: clip `id` ends there, clip `new`
201    /// (added) starts there.
202    ClipSplit {
203        id: u64,
204        at: f64,
205        new: u64,
206    },
207    /// The document was replaced from the history (an undo, a redo).
208    Restored,
209}
210
211/// Everything a timeline shows: its scale, view, playhead, range, markers,
212/// tracks and clips, and the play state and speed it asks for. The application keeps it,
213/// draws it with [`Timeline`](super::Timeline) and moves the playhead while
214/// it plays ([`advance`](Self::advance)).
215#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
216#[serde(default)]
217pub struct TimelineState {
218    pub scale: TimeScale,
219    pub view: TimeView,
220    /// The document's span: the playhead stays inside, the view near it.
221    pub bounds: Option<TimeRange>,
222    pub playhead: f64,
223    pub range: Option<TimeRange>,
224    /// Playback goes round the range.
225    pub looping: bool,
226    pub markers: Vec<Marker>,
227    /// The marker the keys act on.
228    pub selected: Option<u64>,
229    /// Rows of clips under the ruler, from the top.
230    pub tracks: Vec<Track>,
231    /// The clips selected, the one selected last at the end (the keys act
232    /// on it).
233    pub selected_clips: Vec<u64>,
234    pub play: PlayState,
235    /// Asked speed, negative backwards (J), 1 by default.
236    pub speed: f64,
237}
238
239impl Default for TimelineState {
240    fn default() -> Self {
241        Self {
242            scale: TimeScale::Seconds,
243            view: TimeView::default(),
244            bounds: None,
245            playhead: 0.0,
246            range: None,
247            looping: false,
248            markers: Vec::new(),
249            selected: None,
250            tracks: Vec::new(),
251            selected_clips: Vec::new(),
252            play: PlayState::Paused,
253            speed: 1.0,
254        }
255    }
256}
257
258impl TimelineState {
259    /// A timeline on `scale` over `0..length` seconds, all of it in view.
260    pub fn new(scale: TimeScale, length: f64) -> Self {
261        Self {
262            scale,
263            view: TimeView::new(0.0, length.max(scale.unit())),
264            bounds: Some(TimeRange::new(0.0, length)),
265            ..Self::default()
266        }
267    }
268
269    pub fn is_playing(&self) -> bool {
270        self.play == PlayState::Playing
271    }
272
273    /// The document's part.
274    pub fn doc(&self) -> TimelineDoc {
275        TimelineDoc {
276            markers: self.markers.clone(),
277            range: self.range,
278            looping: self.looping,
279            tracks: self.tracks.clone(),
280        }
281    }
282
283    /// Replaces the document's part (an undo, a load).
284    pub fn set_doc(&mut self, doc: TimelineDoc) {
285        self.markers = doc.markers;
286        self.range = doc.range;
287        self.looping = doc.looping;
288        self.tracks = doc.tracks;
289        self.prune_selection();
290        if self
291            .selected
292            .is_some_and(|id| !self.markers.iter().any(|m| m.id == id))
293        {
294            self.selected = None;
295        }
296    }
297
298    /// `time` kept inside the bounds and on the scale (whole frames).
299    pub fn clamp(&self, time: f64) -> f64 {
300        let t = match self.bounds {
301            Some(b) => b.clamp(time),
302            None => time,
303        };
304        self.scale.quantize(t)
305    }
306
307    /// Moves the playhead (kept inside the bounds): whether it moved.
308    pub fn set_playhead(&mut self, time: f64) -> bool {
309        let t = self.clamp(time);
310        let moved = t != self.playhead;
311        self.playhead = t;
312        moved
313    }
314
315    /// Plays at `speed` (negative: backwards).
316    pub fn play_at(&mut self, speed: f64) {
317        self.play = PlayState::Playing;
318        self.speed = if speed.is_finite() && speed != 0.0 {
319            speed.clamp(-MAX_SPEED, MAX_SPEED)
320        } else {
321            1.0
322        };
323    }
324
325    /// Pauses, the speed back to 1.
326    pub fn pause(&mut self) {
327        self.play = PlayState::Paused;
328        self.speed = 1.0;
329    }
330
331    /// Space: plays forward at 1, or pauses.
332    pub fn toggle(&mut self) {
333        if self.is_playing() {
334            self.pause();
335        } else {
336            self.play_at(1.0);
337        }
338    }
339
340    /// J (`forward` false) or L: plays that way at 1, or twice as fast when
341    /// it already does, up to [`MAX_SPEED`].
342    pub fn shuttle(&mut self, forward: bool) {
343        let sign = if forward { 1.0 } else { -1.0 };
344        if self.is_playing() && self.speed * sign > 0.0 {
345            self.play_at((self.speed * 2.0).clamp(-MAX_SPEED, MAX_SPEED));
346        } else {
347            self.play_at(sign);
348        }
349    }
350
351    /// Moves the playhead by `by` seconds, pausing: whether it moved.
352    pub fn step_by(&mut self, by: f64) -> bool {
353        self.pause();
354        self.set_playhead(self.playhead + by)
355    }
356
357    /// Moves the playhead as playing does for `dt` seconds of the clock:
358    /// round the range when looping, else stopping at the bounds. Whether
359    /// it moved.
360    pub fn advance(&mut self, dt: f64) -> bool {
361        if !self.is_playing() || dt.is_nan() || dt <= 0.0 {
362            return false;
363        }
364        let before = self.playhead;
365        let mut t = self.playhead + dt * self.speed;
366        match self.range.filter(|r| self.looping && r.duration() > 0.0) {
367            Some(r) if r.contains(before) || (self.speed > 0.0 && before < r.start) => {
368                let span = r.duration();
369                if t > r.end {
370                    t = r.start + (t - r.start).rem_euclid(span);
371                } else if t < r.start && before >= r.start {
372                    t = r.end - (r.start - t).rem_euclid(span);
373                }
374            }
375            _ => {}
376        }
377        if let Some(b) = self.bounds
378            && (t >= b.end || t <= b.start)
379        {
380            t = b.clamp(t);
381            self.pause();
382        }
383        // Not quantized while playing: the frames shown follow the clock.
384        self.playhead = t;
385        self.playhead != before
386    }
387
388    pub fn marker(&self, id: u64) -> Option<&Marker> {
389        self.markers.iter().find(|m| m.id == id)
390    }
391
392    /// The id the next marker takes.
393    pub fn next_id(&self) -> u64 {
394        self.markers.iter().map(|m| m.id).max().map_or(1, |m| m + 1)
395    }
396
397    /// Adds a marker (its id taken if free, else the next one), in time
398    /// order; returns the id.
399    pub fn add_marker(&mut self, mut marker: Marker) -> u64 {
400        if marker.id == 0 || self.marker(marker.id).is_some() {
401            marker.id = self.next_id();
402        }
403        marker.time = self.clamp(marker.time);
404        let id = marker.id;
405        self.markers.push(marker);
406        self.sort_markers();
407        id
408    }
409
410    /// Moves a marker: its old time, `None` when there is no such marker.
411    pub fn move_marker(&mut self, id: u64, time: f64) -> Option<f64> {
412        let t = self.clamp(time);
413        let m = self.markers.iter_mut().find(|m| m.id == id)?;
414        let from = m.time;
415        m.time = t;
416        self.sort_markers();
417        Some(from)
418    }
419
420    pub fn remove_marker(&mut self, id: u64) -> Option<Marker> {
421        let at = self.markers.iter().position(|m| m.id == id)?;
422        if self.selected == Some(id) {
423            self.selected = None;
424        }
425        Some(self.markers.remove(at))
426    }
427
428    fn sort_markers(&mut self) {
429        self.markers
430            .sort_by(|a, b| a.time.total_cmp(&b.time).then(a.id.cmp(&b.id)));
431    }
432
433    /// The marker after the selected one (else after the playhead), or
434    /// before it (`forward` false).
435    pub fn neighbour_marker(&self, forward: bool) -> Option<u64> {
436        let (at, id) = match self.selected.and_then(|id| self.marker(id)) {
437            Some(m) => (m.time, Some(m.id)),
438            None => (self.playhead, None),
439        };
440        let key = |m: &Marker| (m.time, m.id);
441        let here = (at, id.unwrap_or(if forward { u64::MAX } else { 0 }));
442        let later = |m: &&Marker| {
443            let k = key(m);
444            k.0 > here.0 || (k.0 == here.0 && k.1 > here.1)
445        };
446        if forward {
447            self.markers.iter().find(later).map(|m| m.id)
448        } else {
449            self.markers
450                .iter()
451                .rev()
452                .find(|m| !later(m) && Some(m.id) != id)
453                .map(|m| m.id)
454        }
455    }
456
457    /// The in point at `time`: the range starts there (ends at its end, else
458    /// the bounds' end, else `time`).
459    pub fn in_at(&self, time: f64) -> TimeRange {
460        let t = self.clamp(time);
461        let end = match self.range {
462            Some(r) if r.end > t => r.end,
463            _ => self.bounds.map_or(t, |b| b.end).max(t),
464        };
465        TimeRange { start: t, end }
466    }
467
468    /// The out point at `time`.
469    pub fn out_at(&self, time: f64) -> TimeRange {
470        let t = self.clamp(time);
471        let start = match self.range {
472            Some(r) if r.start < t => r.start,
473            _ => self.bounds.map_or(t, |b| b.start).min(t),
474        };
475        TimeRange { start, end: t }
476    }
477
478    /// Where Home goes: the bounds' start, else 0.
479    pub fn home(&self) -> f64 {
480        self.bounds.map_or(0.0, |b| b.start)
481    }
482
483    /// Where End goes: the bounds' end, else the last marker or the range's
484    /// end, whichever is later.
485    pub fn end(&self) -> f64 {
486        match self.bounds {
487            Some(b) => b.end,
488            None => self
489                .markers
490                .iter()
491                .map(|m| m.time)
492                .chain(self.range.map(|r| r.end))
493                .fold(self.playhead, f64::max),
494        }
495    }
496
497    /// The shortest and longest the view may be.
498    pub fn zoom_limits(&self) -> (f64, f64) {
499        let least = match self.scale {
500            TimeScale::Seconds => 0.05,
501            TimeScale::Frames(r) => 5.0 / r.fps(),
502            TimeScale::Beats(t) => t.beat() / 2.0,
503        };
504        let most = self
505            .bounds
506            .map_or(86_400.0, |b| (b.duration() * 1.5).max(least * 2.0));
507        (least, most)
508    }
509
510    /// `view` within the zoom limits and near the bounds.
511    pub fn fit_view(&self, view: TimeView) -> TimeView {
512        let (least, most) = self.zoom_limits();
513        let duration = if view.duration.is_finite() {
514            view.duration.clamp(least, most)
515        } else {
516            most
517        };
518        // Zoomed past a limit: around the middle of what was asked.
519        let mut start = view.start + (view.duration - duration) / 2.0;
520        if !start.is_finite() {
521            start = 0.0;
522        }
523        if let Some(b) = self.bounds {
524            let margin = duration * 0.05;
525            let lo = b.start - margin;
526            let hi = (b.end + margin - duration).max(lo);
527            start = start.clamp(lo, hi);
528        }
529        TimeView { start, duration }
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536
537    fn state() -> TimelineState {
538        TimelineState::new(TimeScale::frames(25), 60.0)
539    }
540
541    #[test]
542    fn j_k_and_l_shuttle_and_double() {
543        let mut s = state();
544        s.shuttle(true);
545        assert_eq!((s.play, s.speed), (PlayState::Playing, 1.0));
546        s.shuttle(true);
547        s.shuttle(true);
548        assert_eq!(s.speed, 4.0);
549        s.shuttle(false);
550        assert_eq!(s.speed, -1.0);
551        s.shuttle(false);
552        assert_eq!(s.speed, -2.0);
553        for _ in 0..10 {
554            s.shuttle(false);
555        }
556        assert_eq!(s.speed, -MAX_SPEED);
557        s.pause();
558        assert_eq!((s.play, s.speed), (PlayState::Paused, 1.0));
559        s.toggle();
560        assert!(s.is_playing());
561    }
562
563    #[test]
564    fn playing_goes_round_a_looping_range_and_stops_at_the_end() {
565        let mut s = state();
566        s.range = Some(TimeRange::new(10.0, 12.0));
567        s.looping = true;
568        s.playhead = 11.5;
569        s.play_at(1.0);
570        s.advance(1.0);
571        assert!((s.playhead - 10.5).abs() < 1e-9, "{}", s.playhead);
572        // Backwards, round from its start to its end.
573        s.play_at(-1.0);
574        s.advance(1.0);
575        assert!((s.playhead - 11.5).abs() < 1e-9, "{}", s.playhead);
576        // Not looping: on to the end, where it pauses.
577        s.looping = false;
578        s.play_at(8.0);
579        s.advance(10.0);
580        assert_eq!((s.playhead, s.play), (60.0, PlayState::Paused));
581        // Paused, the clock moves nothing.
582        assert!(!s.advance(1.0));
583    }
584
585    #[test]
586    fn markers_keep_time_order_and_unique_ids() {
587        let mut s = state();
588        let a = s.add_marker(Marker::new(0, 20.0, "Chorus"));
589        let b = s.add_marker(Marker::new(a, 10.0, "Verse"));
590        assert_ne!(a, b);
591        assert_eq!(s.markers[0].label, "Verse");
592        // On whole frames, inside the bounds.
593        let c = s.add_marker(Marker::new(0, 70.013, "Late"));
594        assert_eq!(s.marker(c).unwrap().time, 60.0);
595        assert_eq!(s.move_marker(b, 30.01), Some(10.0));
596        assert_eq!(s.markers.last().unwrap().id, c);
597        assert_eq!(s.marker(b).unwrap().time, 30.0);
598        s.selected = Some(b);
599        assert_eq!(s.remove_marker(b).map(|m| m.label), Some("Verse".into()));
600        assert_eq!(s.selected, None);
601        assert_eq!(s.move_marker(b, 1.0), None);
602    }
603
604    #[test]
605    fn up_and_down_walk_the_markers() {
606        let mut s = state();
607        let a = s.add_marker(Marker::new(0, 10.0, "A"));
608        let b = s.add_marker(Marker::new(0, 20.0, "B"));
609        let c = s.add_marker(Marker::new(0, 20.0, "C"));
610        s.playhead = 15.0;
611        assert_eq!(s.neighbour_marker(true), Some(b));
612        assert_eq!(s.neighbour_marker(false), Some(a));
613        s.selected = Some(b);
614        assert_eq!(s.neighbour_marker(true), Some(c));
615        assert_eq!(s.neighbour_marker(false), Some(a));
616        s.selected = Some(c);
617        assert_eq!(s.neighbour_marker(true), None);
618        assert_eq!(s.neighbour_marker(false), Some(b));
619    }
620
621    #[test]
622    fn in_and_out_points_make_a_range() {
623        let mut s = state();
624        assert_eq!(s.in_at(10.0), TimeRange::new(10.0, 60.0));
625        assert_eq!(s.out_at(20.0), TimeRange::new(0.0, 20.0));
626        s.range = Some(s.in_at(10.0));
627        s.range = Some(s.out_at(20.0));
628        assert_eq!(s.range, Some(TimeRange::new(10.0, 20.0)));
629        // An out point before the in point starts the range again.
630        assert_eq!(s.out_at(5.0), TimeRange::new(0.0, 5.0));
631    }
632
633    #[test]
634    fn the_view_keeps_within_its_limits() {
635        let s = state();
636        let v = s.fit_view(TimeView::new(30.0, 0.001));
637        assert_eq!(v.duration, 0.2);
638        let v = s.fit_view(TimeView::new(-500.0, 30.0));
639        assert_eq!(v.start, -1.5);
640        let v = s.fit_view(TimeView::new(0.0, 1e9));
641        assert_eq!(v.duration, 90.0);
642        // Zooming keeps the time under the pointer in place.
643        let z = TimeView::new(0.0, 60.0).zoomed(2.0, 15.0);
644        assert_eq!((z.start, z.duration), (7.5, 30.0));
645    }
646
647    #[test]
648    fn the_state_round_trips_through_json() {
649        let mut s = state();
650        s.add_marker(
651            Marker::new(0, 1.0, "Drop")
652                .kind(MarkerKind::Cue)
653                .color(Color32::RED),
654        );
655        s.range = Some(TimeRange::new(1.0, 2.0));
656        let json = serde_json::to_string(&s).unwrap();
657        let back: TimelineState = serde_json::from_str(&json).unwrap();
658        assert_eq!(back, s);
659        let partial: TimelineState = serde_json::from_str(r#"{"playhead": 3.0}"#).unwrap();
660        assert_eq!(partial.playhead, 3.0);
661    }
662}