use std::time::{Duration, Instant};
use gpui_kit::{Action, App, Context, EventEmitter, KeyBinding, KeyBindingContextPredicate, Task, actions};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ClockEvent {
Moved(f64),
Playing(bool),
}
pub struct Clock {
position: f64,
range: Option<(f64, f64)>,
playing: bool,
rate: f64,
looping: bool,
step: f64,
ticker: Option<Task<()>>,
}
impl EventEmitter<ClockEvent> for Clock {}
const TICK: Duration = Duration::from_millis(16);
pub const RATES: [f64; 9] = [0.1, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0];
impl Default for Clock {
fn default() -> Self {
Self { position: 0.0, range: None, playing: false, rate: 1.0, looping: false, step: 1.0 / 30.0, ticker: None }
}
}
impl Clock {
pub fn new() -> Self {
Self::default()
}
pub fn position(&self) -> f64 {
self.position
}
pub fn range(&self) -> Option<(f64, f64)> {
self.range
}
pub fn is_playing(&self) -> bool {
self.playing
}
pub fn rate(&self) -> f64 {
self.rate
}
pub fn step(&self) -> f64 {
self.step
}
pub fn set_range(&mut self, start: f64, end: f64, cx: &mut Context<Self>) {
self.range = Some((start.min(end), start.max(end)));
let p = self.clamp(self.position);
if p != self.position {
self.seek(p, cx);
}
cx.notify();
}
pub fn set_step(&mut self, seconds: f64) {
if seconds.is_finite() && seconds > 0.0 {
self.step = seconds;
}
}
pub fn set_looping(&mut self, looping: bool) {
self.looping = looping;
}
fn clamp(&self, t: f64) -> f64 {
match self.range {
Some((a, b)) => t.clamp(a, b),
None => t.max(0.0),
}
}
pub fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
let t = self.clamp(t);
if t != self.position {
self.position = t;
cx.emit(ClockEvent::Moved(t));
cx.notify();
}
}
pub fn step_by(&mut self, frames: i64, cx: &mut Context<Self>) {
self.pause(cx);
let index = (self.position / self.step).round() + frames as f64;
self.seek(index * self.step, cx);
}
pub fn play(&mut self, cx: &mut Context<Self>) {
if self.playing {
return;
}
if let Some((a, b)) = self.range
&& self.position >= b
{
self.seek(a, cx);
}
self.playing = true;
cx.emit(ClockEvent::Playing(true));
self.ticker = Some(cx.spawn(async move |this, cx| {
let mut last = Instant::now();
loop {
cx.background_executor().timer(TICK).await;
let now = Instant::now();
let dt = now.duration_since(last).as_secs_f64();
last = now;
if this.update(cx, |c, cx| c.advance(dt, cx)).unwrap_or(false) {
continue;
}
break;
}
}));
cx.notify();
}
pub fn pause(&mut self, cx: &mut Context<Self>) {
if !self.playing {
return;
}
self.playing = false;
self.ticker = None;
cx.emit(ClockEvent::Playing(false));
cx.notify();
}
pub fn toggle_play(&mut self, cx: &mut Context<Self>) {
if self.playing { self.pause(cx) } else { self.play(cx) }
}
pub fn set_rate(&mut self, rate: f64, cx: &mut Context<Self>) {
if rate.is_finite() && rate > 0.0 {
self.rate = rate;
cx.notify();
}
}
pub fn change_rate(&mut self, faster: bool, cx: &mut Context<Self>) {
let i = RATES.iter().position(|r| (*r - self.rate).abs() < 1e-9).unwrap_or(3);
let j = if faster { (i + 1).min(RATES.len() - 1) } else { i.saturating_sub(1) };
self.set_rate(RATES[j], cx);
}
fn advance(&mut self, dt: f64, cx: &mut Context<Self>) -> bool {
if !self.playing {
return false;
}
let next = self.position + dt * self.rate;
match self.range {
Some((a, b)) if next > b => {
if self.looping {
self.seek(a + (next - b) % (b - a).max(f64::EPSILON), cx);
} else {
self.seek(b, cx);
self.pause(cx);
return false;
}
}
_ => self.seek(next, cx),
}
true
}
}
actions!(
kitchen_views,
[
TogglePlay,
StepForward,
StepBack,
JumpForward,
JumpBack,
Faster,
Slower,
]
);
pub const PLAYBACK_KEYS: &[(&str, &[&str])] = &[
("toggle_play", &["space"]),
("step_forward", &["right", "."]),
("step_back", &["left", ","]),
("jump_forward", &["shift-right"]),
("jump_back", &["shift-left"]),
("faster", &["]"]),
("slower", &["["]),
];
pub const SECTION: &str = "playback";
fn action(name: &str) -> Option<Box<dyn Action>> {
Some(match name {
"toggle_play" => Box::new(TogglePlay),
"step_forward" => Box::new(StepForward),
"step_back" => Box::new(StepBack),
"jump_forward" => Box::new(JumpForward),
"jump_back" => Box::new(JumpBack),
"faster" => Box::new(Faster),
"slower" => Box::new(Slower),
_ => return None,
})
}
pub fn binding(command: &str, key: &str, context: &str, cx: &App) -> Option<KeyBinding> {
let context = KeyBindingContextPredicate::parse(context).ok().map(std::rc::Rc::new);
KeyBinding::load(key, action(command)?, context, false, None, cx).ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_playback_key_names_an_action() {
assert!(PLAYBACK_KEYS.iter().all(|(name, _)| action(name).is_some()));
assert_eq!(RATES[3], 1.0, "the default rate is in the list");
}
}