1use std::time::{Duration, Instant};
5
6use gpui_kit::{App, Global};
7
8#[derive(Clone, Copy, Debug)]
13pub struct MotionClock {
14 time_scale: f64,
15 last_real: Option<Instant>,
16 accumulated_secs: f64,
17}
18
19impl Global for MotionClock {}
20
21impl Default for MotionClock {
22 fn default() -> Self {
23 Self {
24 time_scale: 1.0,
25 last_real: None,
26 accumulated_secs: 0.0,
27 }
28 }
29}
30
31impl MotionClock {
32 pub fn new(time_scale: f64) -> Self {
33 Self {
34 time_scale: sanitize_scale(time_scale),
35 last_real: None,
36 accumulated_secs: 0.0,
37 }
38 }
39
40 pub fn time_scale(&self) -> f64 {
41 self.time_scale
42 }
43
44 pub fn set_time_scale(&mut self, scale: f64, now: Instant) {
45 self.advance(now);
46 self.time_scale = sanitize_scale(scale);
47 }
48
49 pub fn advance(&mut self, real_now: Instant) -> f64 {
51 if let Some(prev) = self.last_real {
52 let dt = real_now.saturating_duration_since(prev).as_secs_f64();
53 self.accumulated_secs += dt * self.time_scale;
54 }
55 self.last_real = Some(real_now);
56 self.accumulated_secs
57 }
58
59 pub fn current_secs(&self) -> f64 {
60 self.accumulated_secs
61 }
62
63 pub fn scale_duration(&self, duration: Duration) -> Duration {
64 if self.time_scale <= 0.0 || !self.time_scale.is_finite() {
65 return duration;
66 }
67 Duration::from_secs_f64(duration.as_secs_f64() / self.time_scale)
68 }
69}
70
71fn sanitize_scale(scale: f64) -> f64 {
72 if !scale.is_finite() || scale <= 0.0 {
73 1.0
74 } else {
75 scale.clamp(0.05, 4.0)
76 }
77}
78
79pub fn motion_now(cx: &mut App) -> f64 {
81 let real_now = cx.background_executor().now();
82 if !cx.has_global::<MotionClock>() {
83 cx.set_global(MotionClock::default());
84 }
85 cx.global_mut::<MotionClock>().advance(real_now)
86}
87
88pub fn time_scale(cx: &App) -> f64 {
90 cx.try_global::<MotionClock>()
91 .map_or(1.0, MotionClock::time_scale)
92}
93
94pub fn set_time_scale(scale: f64, cx: &mut App) {
96 let real_now = cx.background_executor().now();
97 if !cx.has_global::<MotionClock>() {
98 cx.set_global(MotionClock::default());
99 }
100 cx.global_mut::<MotionClock>()
101 .set_time_scale(scale, real_now);
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 #[test]
109 fn slow_motion_clock_scales_elapsed_time_smoothly() {
110 let t0 = Instant::now();
111 let mut clock = MotionClock::default();
112 assert_eq!(clock.advance(t0), 0.0);
113
114 let t1 = t0 + Duration::from_millis(100);
115 assert!((clock.advance(t1) - 0.1).abs() < 1e-6);
116
117 clock.set_time_scale(0.25, t1);
119 let t2 = t1 + Duration::from_millis(400);
120 assert!((clock.advance(t2) - 0.2).abs() < 1e-6);
121 }
122}