1use std::time::{Duration, Instant};
15
16use gpui_kit::{Action, App, Context, EventEmitter, KeyBinding, KeyBindingContextPredicate, Task, actions};
17
18#[derive(Clone, Copy, Debug, PartialEq)]
20pub enum ClockEvent {
21 Moved(f64),
23 Playing(bool),
25}
26
27pub struct Clock {
29 position: f64,
30 range: Option<(f64, f64)>,
32 playing: bool,
33 rate: f64,
35 looping: bool,
36 step: f64,
38 ticker: Option<Task<()>>,
39}
40
41impl EventEmitter<ClockEvent> for Clock {}
42
43const TICK: Duration = Duration::from_millis(16);
45
46pub 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 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 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 pub fn set_step(&mut self, seconds: f64) {
93 if seconds.is_finite() && seconds > 0.0 {
94 self.step = seconds;
95 }
96 }
97
98 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 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 pub fn step_by(&mut self, frames: i64, cx: &mut Context<Self>) {
122 self.pause(cx);
123 let index = (self.position / self.step).round() + frames as f64;
125 self.seek(index * self.step, cx);
126 }
127
128 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 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 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 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 TogglePlay,
212 StepForward,
214 StepBack,
216 JumpForward,
218 JumpBack,
220 Faster,
222 Slower,
224 ]
225);
226
227pub 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
238pub 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
254pub 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}