gpui-ce 0.3.0

A community fork of Zed's GPU-accelerated UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use std::{ops::Sub, time::Duration};

use crate::{AnyMotion, Lerp, Progress};

/// A value sampled from an [`Animated`], together with its activity and progress.
#[derive(Clone)]
pub struct AnimatedSample<T> {
    /// The interpolated value at the sampled time.
    pub value: T,

    /// Whether another sample may produce a different value.
    pub is_active: bool,

    /// Eased presentation progress from the interruption point to the target. An easing curve may
    /// take it outside `0.0..=1.0`.
    pub progress: Progress,
}

/// A value that animates toward a target, and keeps the state it needs to change course.
///
/// `Animated` stores the logical target, the motion, and when the current run started. When the
/// target changes mid-run, the new run starts from the value on screen at that moment, so the
/// motion doesn't jump. [`Transition`](crate::Transition) and style transitions are built on it.
///
/// `Time` is the clock type. The default is [`std::time::Instant`]. Any `Time` that subtracts to a
/// [`Duration`](std::time::Duration) works, and a `Duration` makes the examples deterministic.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// use gpui::{Animated, Motion, millis, secs};
///
/// let motion = Motion::new(secs(1));
/// let mut value = Animated::<f32, Duration>::new(0.0, motion.clone());
///
/// assert!(value.set(10.0, &motion, Duration::ZERO));
/// assert_eq!(value.sample(millis(500)).value, 5.0);
///
/// // Setting the same target again changes nothing.
/// assert!(!value.set(10.0, &motion, millis(500)));
/// ```
#[derive(Clone)]
pub struct Animated<T, Time = std::time::Instant> {
    value: T,
    initial_value: T,
    last_value: T,
    motion: AnyMotion,
    reverse_progress: bool,
    settled_progress: Option<Progress>,
    started_at: Option<Time>,
}

impl<T, Time> Animated<T, Time>
where
    T: Lerp + Clone + PartialEq,
    Time: Copy + Sub<Time, Output = Duration>,
{
    /// Creates a value at rest at `value`. `motion` describes how later changes animate.
    pub fn new(value: T, motion: impl Into<AnyMotion>) -> Self {
        Self {
            initial_value: value.clone(),
            last_value: value.clone(),
            value,
            motion: motion.into(),
            reverse_progress: false,
            settled_progress: None,
            started_at: None,
        }
    }

    /// Returns the logical target: the value most recently given to [`set`](Self::set).
    ///
    /// This is not the value on screen during a run. Use [`sample`](Self::sample) for that.
    pub fn value(&self) -> &T {
        &self.value
    }

    /// Returns eased presentation progress without changing state.
    /// The result may overshoot zero through one.
    ///
    /// A value with no active or previously settled run is already presenting
    /// its logical target and therefore reports [`Progress::END`].
    pub(crate) fn progress_at(&self, now: Time) -> Progress {
        self.started_at.map_or_else(
            || self.settled_progress.unwrap_or(Progress::END),
            |started_at| {
                self.presentation_progress(self.motion.sample_at(started_at, now).progress)
            },
        )
    }

    fn presentation_progress(&self, progress: Progress) -> Progress {
        if self.reverse_progress {
            progress.reversed()
        } else {
            progress
        }
    }

    /// Sets a new target and starts a run from the current presentation.
    ///
    /// The run begins at `now`, using `motion`, and starts from the value on screen at that
    /// moment. Returns `true` if the target changed. Setting the current target again returns
    /// `false` and leaves the run alone.
    ///
    /// Reverse-first playback flips motion progress into anchor-to-target progress. A custom
    /// easing curve that starts away from zero can still cause an initial jump.
    pub fn set(&mut self, value: T, motion: impl Into<AnyMotion>, now: Time) -> bool {
        self.retarget(value, motion, now, true)
    }

    /// Updates the logical value and restarts from the initial value.
    pub(crate) fn restart(&mut self, value: T, motion: impl Into<AnyMotion>, now: Time) -> bool {
        self.retarget(value, motion, now, false)
    }

    fn retarget(
        &mut self,
        value: T,
        motion: impl Into<AnyMotion>,
        now: Time,
        continuous: bool,
    ) -> bool {
        if self.value == value {
            return false;
        }

        let current = self.sample(now);
        self.last_value = if continuous {
            current.value
        } else {
            self.initial_value.clone()
        };
        self.value = value;
        self.motion = motion.into();
        // Reverse-first playback uses the opposite interpolation axis. Flip
        // its progress so easing that starts at zero begins at the anchor.
        self.reverse_progress = self.motion.starts_in_reverse();
        self.settled_progress = None;
        self.started_at = Some(now);
        true
    }

    /// Sets the target and the value on screen to `value`, with no animation.
    ///
    /// This stops any run in progress.
    pub fn jump_to(&mut self, value: T) {
        self.value = value.clone();
        self.last_value = value;
        self.settled_progress = None;
        self.started_at = None;
    }

    /// Aligns an inactive END presentation with its logical target.
    ///
    /// Style transitions present the authored target at this endpoint, even if
    /// interpolation produced a different value. Keeping the same value as the
    /// next interruption anchor prevents a jump on a later retarget.
    pub(crate) fn adopt_completed_target(&mut self) {
        if self.started_at.is_none() && self.settled_progress == Some(Progress::END) {
            self.last_value = self.value.clone();
            self.settled_progress = None;
        }
    }

    /// Restores the value this animation was created with, with no animation.
    ///
    /// This stops any run in progress.
    pub fn reset(&mut self) {
        self.value = self.initial_value.clone();
        self.last_value = self.initial_value.clone();
        self.settled_progress = None;
        self.started_at = None;
    }

    /// Returns the value presented at `now`, and whether the animation can still change.
    ///
    /// Call this once per frame. After a run finishes, the sample returns its final value with
    /// `is_active` set to `false`, and that value becomes the anchor for the next change. Before a
    /// run starts, sampling returns the last settled value.
    pub fn sample(&mut self, now: Time) -> AnimatedSample<T> {
        let Some(started_at) = self.started_at else {
            return AnimatedSample {
                value: self.last_value.clone(),
                is_active: false,
                progress: self.settled_progress.unwrap_or(Progress::END),
            };
        };

        let sample = self.motion.sample_at(started_at, now);
        let progress = self.presentation_progress(sample.progress);
        let value = self.last_value.lerp(&self.value, progress.get());

        if !sample.is_active {
            self.last_value = value.clone();
            self.settled_progress = Some(progress);
            self.started_at = None;
        }

        AnimatedSample {
            value,
            is_active: sample.is_active,
            progress,
        }
    }

    pub(crate) fn scale_by(&mut self, ratio: f32)
    where
        T: std::ops::Mul<f32, Output = T>,
    {
        self.last_value = self.last_value.clone() * ratio;
        self.value = self.value.clone() * ratio;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::{Direction, Motion, SpringConfig};

    fn assert_sample(sample: AnimatedSample<f32>, value: f32, progress: Progress, is_active: bool) {
        assert_eq!(
            (sample.value, sample.progress, sample.is_active),
            (value, progress, is_active)
        );
    }

    #[test]
    fn animated_value_supports_a_complete_lifecycle() {
        let motion = Motion::new(Duration::from_secs(1));
        let mut animated = Animated::<f32, Duration>::new(2.0, motion.clone());

        assert_eq!(animated.value(), &2.0);
        assert_eq!(animated.progress_at(Duration::ZERO), Progress::END);
        assert_sample(animated.sample(Duration::ZERO), 2.0, Progress::END, false);

        assert!(animated.set(10.0, &motion, Duration::ZERO));
        assert_eq!(animated.sample(Duration::from_millis(500)).value, 6.0);
        assert_eq!(
            animated.progress_at(Duration::from_millis(500)),
            Progress::clamped(0.5)
        );

        assert_sample(
            animated.sample(Duration::from_secs(1)),
            10.0,
            Progress::END,
            false,
        );
        assert!(!animated.set(10.0, &motion, Duration::from_secs(2)));

        animated.jump_to(8.0);
        assert_sample(
            animated.sample(Duration::from_secs(2)),
            8.0,
            Progress::END,
            false,
        );

        animated.scale_by(2.0);
        assert_eq!(animated.value(), &16.0);

        let immediate = Motion::default();
        assert!(animated.set(12.0, &immediate, Duration::from_secs(2)));
        assert_sample(
            animated.sample(Duration::from_secs(2)),
            12.0,
            Progress::END,
            false,
        );
        animated.reset();

        assert_eq!(animated.value(), &2.0);
        assert_sample(
            animated.sample(Duration::from_millis(500)),
            2.0,
            Progress::END,
            false,
        );
    }

    #[test]
    fn animated_exercises_retargeting_and_non_monotonic_motion() {
        let motion = Motion::new(Duration::from_secs(1));
        let mut continuous = Animated::<f32, Duration>::new(0.0, motion.clone());
        let mut restarting = Animated::<f32, Duration>::new(0.0, motion.clone());

        assert!(continuous.set(10.0, &motion, Duration::ZERO));
        assert!(restarting.set(10.0, &motion, Duration::ZERO));
        assert_eq!(continuous.sample(Duration::from_millis(500)).value, 5.0);
        assert_eq!(restarting.sample(Duration::from_millis(500)).value, 5.0);

        assert!(continuous.set(20.0, &motion, Duration::from_millis(500)));
        assert!(restarting.restart(20.0, &motion, Duration::from_millis(500)));

        let continuous_anchor = continuous.sample(Duration::from_millis(500));
        let restarting_anchor = restarting.sample(Duration::from_millis(500));
        assert_eq!(continuous_anchor.value, 5.0);
        assert_eq!(restarting_anchor.value, 0.0);
        assert!(continuous_anchor.is_active);
        assert!(restarting_anchor.is_active);

        assert_eq!(continuous.sample(Duration::from_secs(1)).value, 12.5);
        assert_eq!(restarting.sample(Duration::from_secs(1)).value, 10.0);
        assert!(!continuous.set(20.0, &motion, Duration::from_secs(1)));
        assert!(!restarting.restart(20.0, &motion, Duration::from_secs(1)));

        let non_monotonic = Motion::new(Duration::from_secs(1)).with_easing(|progress| {
            if progress < 0.5 {
                progress * 2.0
            } else {
                (1.0 - progress) * 2.0
            }
        });
        let mut animated = Animated::<f32, Duration>::new(0.0, non_monotonic.clone());

        assert!(animated.set(1.0, &non_monotonic, Duration::ZERO));
        assert_sample(animated.sample(Duration::ZERO), 0.0, Progress::START, true);
        assert_sample(
            animated.sample(Duration::from_millis(500)),
            1.0,
            Progress::END,
            true,
        );
        assert_sample(
            animated.sample(Duration::from_secs(1)),
            0.0,
            Progress::START,
            false,
        );
        assert_sample(
            animated.sample(Duration::from_secs(2)),
            0.0,
            Progress::START,
            false,
        );
        assert_eq!(
            animated.progress_at(Duration::from_secs(2)),
            Progress::START
        );
        assert_eq!(animated.value(), &1.0);

        animated.jump_to(2.0);
        assert_sample(
            animated.sample(Duration::from_secs(3)),
            2.0,
            Progress::END,
            false,
        );
        let spring =
            Motion::new(Duration::from_secs(1)).with_spring(SpringConfig::new(100.0, 6.0, 1.0));
        let mut animated = Animated::<f32, Duration>::new(0.0, spring.clone());
        assert!(animated.set(1.0, &spring, Duration::ZERO));

        assert!(
            (1..100).any(|step| { animated.sample(Duration::from_millis(step * 10)).value > 1.0 })
        );
        assert_eq!(animated.sample(Duration::from_secs(1)).value, 1.0);
    }

    #[test]
    fn animated_keeps_the_motion_that_started_each_run() {
        let one_second = Motion::new(Duration::from_secs(1));
        let two_seconds = Motion::new(Duration::from_secs(2));
        let mut animated = Animated::<f32, Duration>::new(0.0, one_second.clone());

        assert!(animated.set(10.0, &one_second, Duration::ZERO));
        assert_eq!(animated.sample(Duration::from_millis(500)).value, 5.0);
        assert_eq!(
            animated.progress_at(Duration::from_millis(750)),
            Progress::clamped(0.75)
        );

        assert!(animated.set(20.0, &two_seconds, Duration::from_millis(500)));
        assert_eq!(animated.sample(Duration::from_millis(500)).value, 5.0);
        assert_eq!(animated.sample(Duration::from_millis(1_500)).value, 12.5);
    }

    #[test]
    fn delayed_retargeting_holds_the_interruption_anchor() {
        let motion = Motion::new(Duration::from_secs(1)).with_delay(Duration::from_millis(100));
        let mut animated = Animated::<f32, Duration>::new(0.0, motion.clone());

        assert!(animated.set(10.0, &motion, Duration::ZERO));
        assert_sample(
            animated.sample(Duration::from_millis(100)),
            0.0,
            Progress::START,
            true,
        );
        assert_eq!(animated.sample(Duration::from_millis(600)).value, 5.0);

        assert!(animated.set(20.0, &motion, Duration::from_millis(600)));
        for milliseconds in [600, 650, 700] {
            assert_sample(
                animated.sample(Duration::from_millis(milliseconds)),
                5.0,
                Progress::START,
                true,
            );
        }
        assert_eq!(animated.sample(Duration::from_millis(1_200)).value, 12.5);
    }

    #[test]
    fn reverse_first_retargeting_starts_at_the_current_presentation() {
        let motion = Motion::new(Duration::from_secs(1)).direction(Direction::Reverse);
        let mut animated = Animated::<f32, Duration>::new(0.0, motion.clone());

        assert!(animated.set(10.0, &motion, Duration::ZERO));
        assert_sample(animated.sample(Duration::ZERO), 0.0, Progress::START, true);
        assert_sample(
            animated.sample(Duration::from_millis(500)),
            5.0,
            Progress::clamped(0.5),
            true,
        );

        assert!(animated.set(20.0, &motion, Duration::from_millis(500)));
        assert_sample(
            animated.sample(Duration::from_millis(500)),
            5.0,
            Progress::START,
            true,
        );
        assert_eq!(animated.sample(Duration::from_secs(1)).value, 12.5);
        assert_sample(
            animated.sample(Duration::from_millis(1_500)),
            20.0,
            Progress::END,
            false,
        );

        let alternating = Motion::new(Duration::from_secs(1))
            .iterations(2)
            .direction(Direction::AlternateReverse);
        assert!(animated.set(30.0, &alternating, Duration::from_secs(2)));
        assert_eq!(animated.sample(Duration::from_secs(2)).value, 20.0);
        assert_eq!(animated.sample(Duration::from_secs(3)).value, 30.0);
        assert_sample(
            animated.sample(Duration::from_secs(4)),
            20.0,
            Progress::START,
            false,
        );
    }

    #[test]
    fn finite_iterations_settle_at_their_sampled_presentation() {
        let restarting_motion = Motion::new(Duration::from_secs(1)).iterations(3);
        let mut restarting = Animated::<f32, Duration>::new(0.0, restarting_motion.clone());
        assert!(restarting.set(10.0, &restarting_motion, Duration::ZERO));
        assert_sample(
            restarting.sample(Duration::from_secs(1)),
            10.0,
            Progress::END,
            true,
        );
        assert_sample(
            restarting.sample(Duration::from_millis(1_500)),
            5.0,
            Progress::clamped(0.5),
            true,
        );
        assert_sample(
            restarting.sample(Duration::from_secs(3)),
            10.0,
            Progress::END,
            false,
        );

        let alternating_motion = Motion::new(Duration::from_secs(1))
            .iterations(2)
            .alternate();
        let mut idle = Animated::<f32, Duration>::new(4.0, alternating_motion.clone());
        assert_sample(idle.sample(Duration::ZERO), 4.0, Progress::END, false);
        idle.jump_to(6.0);
        assert_sample(idle.sample(Duration::ZERO), 6.0, Progress::END, false);

        let mut alternating = Animated::<f32, Duration>::new(0.0, alternating_motion.clone());
        assert!(alternating.set(10.0, &alternating_motion, Duration::ZERO));
        assert_sample(
            alternating.sample(Duration::from_secs(1)),
            10.0,
            Progress::END,
            true,
        );
        assert_sample(
            alternating.sample(Duration::from_secs(2)),
            0.0,
            Progress::START,
            false,
        );
        assert_sample(
            alternating.sample(Duration::from_secs(20)),
            0.0,
            Progress::START,
            false,
        );

        let zero_forever = Motion::new(Duration::ZERO).repeat_forever();
        assert!(alternating.set(20.0, &zero_forever, Duration::from_secs(21)));
        assert_sample(
            alternating.sample(Duration::from_secs(21)),
            0.0,
            Progress::START,
            false,
        );
    }
}