use std::time::{Duration, Instant};
use gpui_kit::{App, Global};
#[derive(Clone, Copy, Debug)]
pub struct MotionClock {
time_scale: f64,
last_real: Option<Instant>,
accumulated_secs: f64,
}
impl Global for MotionClock {}
impl Default for MotionClock {
fn default() -> Self {
Self {
time_scale: 1.0,
last_real: None,
accumulated_secs: 0.0,
}
}
}
impl MotionClock {
pub fn new(time_scale: f64) -> Self {
Self {
time_scale: sanitize_scale(time_scale),
last_real: None,
accumulated_secs: 0.0,
}
}
pub fn time_scale(&self) -> f64 {
self.time_scale
}
pub fn set_time_scale(&mut self, scale: f64, now: Instant) {
self.advance(now);
self.time_scale = sanitize_scale(scale);
}
pub fn advance(&mut self, real_now: Instant) -> f64 {
if let Some(prev) = self.last_real {
let dt = real_now.saturating_duration_since(prev).as_secs_f64();
self.accumulated_secs += dt * self.time_scale;
}
self.last_real = Some(real_now);
self.accumulated_secs
}
pub fn current_secs(&self) -> f64 {
self.accumulated_secs
}
pub fn scale_duration(&self, duration: Duration) -> Duration {
if self.time_scale <= 0.0 || !self.time_scale.is_finite() {
return duration;
}
Duration::from_secs_f64(duration.as_secs_f64() / self.time_scale)
}
}
fn sanitize_scale(scale: f64) -> f64 {
if !scale.is_finite() || scale <= 0.0 {
1.0
} else {
scale.clamp(0.05, 4.0)
}
}
pub fn motion_now(cx: &mut App) -> f64 {
let real_now = cx.background_executor().now();
if !cx.has_global::<MotionClock>() {
cx.set_global(MotionClock::default());
}
cx.global_mut::<MotionClock>().advance(real_now)
}
pub fn time_scale(cx: &App) -> f64 {
cx.try_global::<MotionClock>()
.map_or(1.0, MotionClock::time_scale)
}
pub fn set_time_scale(scale: f64, cx: &mut App) {
let real_now = cx.background_executor().now();
if !cx.has_global::<MotionClock>() {
cx.set_global(MotionClock::default());
}
cx.global_mut::<MotionClock>()
.set_time_scale(scale, real_now);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slow_motion_clock_scales_elapsed_time_smoothly() {
let t0 = Instant::now();
let mut clock = MotionClock::default();
assert_eq!(clock.advance(t0), 0.0);
let t1 = t0 + Duration::from_millis(100);
assert!((clock.advance(t1) - 0.1).abs() < 1e-6);
clock.set_time_scale(0.25, t1);
let t2 = t1 + Duration::from_millis(400);
assert!((clock.advance(t2) - 0.2).abs() < 1e-6);
}
}