Skip to main content

kitchen_views/
clock.rs

1//! One clock every view follows. A workspace holds one [`Clock`]; the video, the traces, the
2//! raster, the keypoints all draw what is at its position, and any of them moves it (a click on
3//! the timeline, a frame step in the video). The position is in seconds of the **reference**
4//! clock (usually the ephys recording's); each source maps its own time onto it with an
5//! [`crate::sync::Alignment`].
6//!
7//! Playback advances the position with the wall clock times the rate, on the UI thread at
8//! display rate; views draw the frame or sample at the new position. Frame steps move by the
9//! clock's step (the video's frame interval when a video is open).
10//!
11//! The playback keys are their own section (`[playback]`), bound only where a workspace says
12//! (its key context): [`PLAYBACK_KEYS`], [`binding`].
13
14use std::time::{Duration, Instant};
15
16use gpui_kit::{Action, App, Context, EventEmitter, KeyBinding, KeyBindingContextPredicate, Task, actions};
17
18/// What the clock tells the views.
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub enum ClockEvent {
21    /// The position changed (seek, step, or playback).
22    Moved(f64),
23    /// Playback started or stopped.
24    Playing(bool),
25}
26
27/// The shared time cursor of a workspace.
28pub struct Clock {
29    position: f64,
30    /// Where time runs (the longest source); none until a source is open.
31    range: Option<(f64, f64)>,
32    playing: bool,
33    /// Seconds of the reference clock per second of wall time.
34    rate: f64,
35    looping: bool,
36    /// A frame step, in seconds.
37    step: f64,
38    ticker: Option<Task<()>>,
39}
40
41impl EventEmitter<ClockEvent> for Clock {}
42
43/// How often playback moves the clock (about the display's rate).
44const TICK: Duration = Duration::from_millis(16);
45
46/// The rates playback steps through (`[` and `]`).
47pub const RATES: [f64; 9] = [0.1, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0];
48
49impl Default for Clock {
50    fn default() -> Self {
51        Self { position: 0.0, range: None, playing: false, rate: 1.0, looping: false, step: 1.0 / 30.0, ticker: None }
52    }
53}
54
55impl Clock {
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// The position, in seconds of the reference clock.
61    pub fn position(&self) -> f64 {
62        self.position
63    }
64
65    pub fn range(&self) -> Option<(f64, f64)> {
66        self.range
67    }
68
69    pub fn is_playing(&self) -> bool {
70        self.playing
71    }
72
73    pub fn rate(&self) -> f64 {
74        self.rate
75    }
76
77    pub fn step(&self) -> f64 {
78        self.step
79    }
80
81    /// Where time runs; the position is kept inside.
82    pub fn set_range(&mut self, start: f64, end: f64, cx: &mut Context<Self>) {
83        self.range = Some((start.min(end), start.max(end)));
84        let p = self.clamp(self.position);
85        if p != self.position {
86            self.seek(p, cx);
87        }
88        cx.notify();
89    }
90
91    /// A frame step of `seconds` (a video's frame interval).
92    pub fn set_step(&mut self, seconds: f64) {
93        if seconds.is_finite() && seconds > 0.0 {
94            self.step = seconds;
95        }
96    }
97
98    /// Playback wraps to the start at the end, instead of stopping.
99    pub fn set_looping(&mut self, looping: bool) {
100        self.looping = looping;
101    }
102
103    fn clamp(&self, t: f64) -> f64 {
104        match self.range {
105            Some((a, b)) => t.clamp(a, b),
106            None => t.max(0.0),
107        }
108    }
109
110    /// Moves to `t` (kept in the range).
111    pub fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
112        let t = self.clamp(t);
113        if t != self.position {
114            self.position = t;
115            cx.emit(ClockEvent::Moved(t));
116            cx.notify();
117        }
118    }
119
120    /// Moves by `frames` steps (negative: back). Pauses playback: a step is a precise look.
121    pub fn step_by(&mut self, frames: i64, cx: &mut Context<Self>) {
122        self.pause(cx);
123        // Onto the step grid, so repeated steps land on frames and not between them
124        let index = (self.position / self.step).round() + frames as f64;
125        self.seek(index * self.step, cx);
126    }
127
128    /// Plays at the clock's rate.
129    pub fn play(&mut self, cx: &mut Context<Self>) {
130        if self.playing {
131            return;
132        }
133        if let Some((a, b)) = self.range
134            && self.position >= b
135        {
136            self.seek(a, cx);
137        }
138        self.playing = true;
139        cx.emit(ClockEvent::Playing(true));
140        self.ticker = Some(cx.spawn(async move |this, cx| {
141            let mut last = Instant::now();
142            loop {
143                cx.background_executor().timer(TICK).await;
144                let now = Instant::now();
145                let dt = now.duration_since(last).as_secs_f64();
146                last = now;
147                if this.update(cx, |c, cx| c.advance(dt, cx)).unwrap_or(false) {
148                    continue;
149                }
150                break;
151            }
152        }));
153        cx.notify();
154    }
155
156    pub fn pause(&mut self, cx: &mut Context<Self>) {
157        if !self.playing {
158            return;
159        }
160        self.playing = false;
161        self.ticker = None;
162        cx.emit(ClockEvent::Playing(false));
163        cx.notify();
164    }
165
166    pub fn toggle_play(&mut self, cx: &mut Context<Self>) {
167        if self.playing { self.pause(cx) } else { self.play(cx) }
168    }
169
170    /// Playback at `rate` (seconds of recording per second).
171    pub fn set_rate(&mut self, rate: f64, cx: &mut Context<Self>) {
172        if rate.is_finite() && rate > 0.0 {
173            self.rate = rate;
174            cx.notify();
175        }
176    }
177
178    /// The next rate of [`RATES`] up (`faster`) or down.
179    pub fn change_rate(&mut self, faster: bool, cx: &mut Context<Self>) {
180        let i = RATES.iter().position(|r| (*r - self.rate).abs() < 1e-9).unwrap_or(3);
181        let j = if faster { (i + 1).min(RATES.len() - 1) } else { i.saturating_sub(1) };
182        self.set_rate(RATES[j], cx);
183    }
184
185    /// Playback moves by `dt` seconds of wall time; whether it goes on.
186    fn advance(&mut self, dt: f64, cx: &mut Context<Self>) -> bool {
187        if !self.playing {
188            return false;
189        }
190        let next = self.position + dt * self.rate;
191        match self.range {
192            Some((a, b)) if next > b => {
193                if self.looping {
194                    self.seek(a + (next - b) % (b - a).max(f64::EPSILON), cx);
195                } else {
196                    self.seek(b, cx);
197                    self.pause(cx);
198                    return false;
199                }
200            }
201            _ => self.seek(next, cx),
202        }
203        true
204    }
205}
206
207actions!(
208    kitchen_views,
209    [
210        /// Play or pause.
211        TogglePlay,
212        /// One frame forward.
213        StepForward,
214        /// One frame back.
215        StepBack,
216        /// Ten frames forward.
217        JumpForward,
218        /// Ten frames back.
219        JumpBack,
220        /// Play faster.
221        Faster,
222        /// Play slower.
223        Slower,
224    ]
225);
226
227/// The `[playback]` section of `keybindings.toml`: commands and their default keys.
228pub const PLAYBACK_KEYS: &[(&str, &[&str])] = &[
229    ("toggle_play", &["space"]),
230    ("step_forward", &["right", "."]),
231    ("step_back", &["left", ","]),
232    ("jump_forward", &["shift-right"]),
233    ("jump_back", &["shift-left"]),
234    ("faster", &["]"]),
235    ("slower", &["["]),
236];
237
238/// The playback section's name.
239pub const SECTION: &str = "playback";
240
241fn action(name: &str) -> Option<Box<dyn Action>> {
242    Some(match name {
243        "toggle_play" => Box::new(TogglePlay),
244        "step_forward" => Box::new(StepForward),
245        "step_back" => Box::new(StepBack),
246        "jump_forward" => Box::new(JumpForward),
247        "jump_back" => Box::new(JumpBack),
248        "faster" => Box::new(Faster),
249        "slower" => Box::new(Slower),
250        _ => return None,
251    })
252}
253
254/// The binding of `command` to `key` in the key context `context` (a workspace's, so the space
255/// bar plays the video there and does something else elsewhere). An app resolves `[playback]`
256/// with kitchen-shell's `keys::resolve` and binds what this gives.
257pub fn binding(command: &str, key: &str, context: &str, cx: &App) -> Option<KeyBinding> {
258    let context = KeyBindingContextPredicate::parse(context).ok().map(std::rc::Rc::new);
259    KeyBinding::load(key, action(command)?, context, false, None, cx).ok()
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn every_playback_key_names_an_action() {
268        assert!(PLAYBACK_KEYS.iter().all(|(name, _)| action(name).is_some()));
269        assert_eq!(RATES[3], 1.0, "the default rate is in the list");
270    }
271}