返回 CodeWhale
motion.rs
1 //! Motion: the few things that move, and the promise that nothing else does.
2 //!
3 //! Motion is allowed for a change of state, work in progress or spatial
4 //! continuity. This module is that layer without an animation dependency.
5 //!
6 //! - A [`MotionStep`] eases a value from where it is to a target in `0..=1`,
7 //! sampled at an instant the caller passes in. Nothing here reads a clock,
8 //! spawns a thread or waits.
9 //! - [`MotionPolicy`] says what may move. `Full` animates; `Reduced` and
10 //! `Still` jump straight to the end state, and every helper takes the
11 //! policy so a component cannot forget it. Color steps run at truecolor
12 //! only: at 256 and 16 colors the in-between values snap into visible
13 //! flicker, so the step is skipped (§4.3).
14 //! - [`MotionSet::next_frame_at`] is the whole scheduler: the next instant a
15 //! redraw is due, never sooner than the frame cap, and `None` once
16 //! everything has settled, so an idle screen asks for zero redraws.
17 //!
18 //! The host owns the loop. After each draw it calls `next_frame_at(now,
19 //! policy)` and sleeps until that instant, or until an event, whichever comes
20 //! first. `None` means sleep until an event.
21
22 use std::borrow::Cow;
23 use std::time::{Duration, Instant};
24
25 use ratatui::{
26 buffer::Buffer,
27 layout::Rect,
28 style::{Color, Modifier, Style},
29 };
30 use unicode_segmentation::UnicodeSegmentation;
31
32 use crate::{
33 MotionMode, Paint, Role, Theme,
34 color::{
35 ColorDepth, blend, contrast_ratio, is_truecolor, mix_oklab, oklab_ramp, specular_lift,
36 },
37 glyphs, text, tokens,
38 };
39
40 /// A redraw is never due sooner than this after it was asked for: 60 frames
41 /// a second. A step lasts 120 to 340 ms, so that is 7 to 20 frames.
42 pub const MOTION_FRAME_INTERVAL: Duration = Duration::from_micros(16_667);
43
44 /// The fastest cap a [`MotionSet`] accepts (120 frames a second, the
45 /// engine's draw cap). A faster request is raised to this.
46 pub const MOTION_MIN_FRAME_INTERVAL: Duration = Duration::from_micros(8_333);
47
48 /// How a step eases. Nothing overshoots: every curve stays inside `0..=1`
49 /// and never reverses.
50 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
51 pub enum MotionEasing {
52 Linear,
53 /// Fast, then settling: for things arriving.
54 #[default]
55 EaseOut,
56 /// Slow, then leaving: for things exiting.
57 EaseIn,
58 }
59
60 impl MotionEasing {
61 /// The eased progress for `t` in `0..=1`. Outside the range clamps; a
62 /// NaN counts as finished.
63 #[must_use]
64 pub fn apply(self, t: f32) -> f32 {
65 let t = if t.is_nan() { 1.0 } else { t.clamp(0.0, 1.0) };
66 match self {
67 Self::Linear => t,
68 Self::EaseOut => 1.0 - (1.0 - t).powi(3),
69 Self::EaseIn => t * t * t,
70 }
71 }
72 }
73
74 /// What a step moves. A color step needs a concrete truecolor ground; a
75 /// spatial step moves cells and works at any depth.
76 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
77 pub enum MotionChannel {
78 /// A column offset or a reveal width.
79 Space,
80 /// A role blend.
81 Tint,
82 }
83
84 /// How long a step takes and how it eases.
85 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
86 pub struct MotionTiming {
87 pub duration: Duration,
88 pub easing: MotionEasing,
89 pub channel: MotionChannel,
90 }
91
92 impl MotionTiming {
93 /// A row's state changed (`duration_state`, 120 ms, ease out).
94 pub const STATE: Self = Self::tint(
95 Duration::from_millis(tokens::MOTION_DURATION_STATE_MS as u64),
96 MotionEasing::EaseOut,
97 );
98 /// Something arrived (`duration_arrive`, 180 ms, ease out).
99 pub const ARRIVE: Self = Self::tint(
100 Duration::from_millis(tokens::MOTION_DURATION_ARRIVE_MS as u64),
101 MotionEasing::EaseOut,
102 );
103 /// Something left (`duration_state`, 120 ms, ease in).
104 pub const EXIT: Self = Self::tint(
105 Duration::from_millis(tokens::MOTION_DURATION_STATE_MS as u64),
106 MotionEasing::EaseIn,
107 );
108 /// A panel's width or position settles (`duration_panel`, 340 ms, ease
109 /// out).
110 pub const PANEL: Self = Self::space(
111 Duration::from_millis(tokens::MOTION_DURATION_PANEL_MS as u64),
112 MotionEasing::EaseOut,
113 );
114
115 /// A role blend.
116 #[must_use]
117 pub const fn tint(duration: Duration, easing: MotionEasing) -> Self {
118 Self {
119 duration,
120 easing,
121 channel: MotionChannel::Tint,
122 }
123 }
124
125 /// A column offset or reveal width.
126 #[must_use]
127 pub const fn space(duration: Duration, easing: MotionEasing) -> Self {
128 Self {
129 duration,
130 easing,
131 channel: MotionChannel::Space,
132 }
133 }
134 }
135
136 /// What may move, from the person's setting and what the terminal can show.
137 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
138 pub struct MotionPolicy {
139 mode: MotionMode,
140 tints: bool,
141 }
142
143 impl MotionPolicy {
144 /// `mode` on the terminal `theme` describes.
145 #[must_use]
146 pub fn new(mode: MotionMode, theme: &Theme) -> Self {
147 Self {
148 mode,
149 tints: can_blend(theme),
150 }
151 }
152
153 #[must_use]
154 pub const fn mode(self) -> MotionMode {
155 self.mode
156 }
157
158 /// Whether anything moves at all: `Full` only.
159 #[must_use]
160 pub const fn animates(self) -> bool {
161 self.mode.animates()
162 }
163
164 /// Whether a step on `channel` runs, or jumps to its end state.
165 #[must_use]
166 pub const fn allows(self, channel: MotionChannel) -> bool {
167 self.animates()
168 && match channel {
169 MotionChannel::Space => true,
170 MotionChannel::Tint => self.tints,
171 }
172 }
173 }
174
175 /// Colors blend only at truecolor on a known ground: the in-between values
176 /// of a 256-color blend are other roles, and an unknown ground has nothing
177 /// to blend with.
178 fn can_blend(theme: &Theme) -> bool {
179 theme.paints_grounds() && theme.depth() == ColorDepth::TrueColor
180 }
181
182 pub const ACTIVITY_SWEEP_TRAVEL: Duration =
183 Duration::from_millis(tokens::MOTION_SWEEP_ACTIVE_MS as u64);
184 pub const ACTIVITY_SWEEP_PEAK: f32 = tokens::MOTION_SWEEP_STRENGTH;
185 const ACTIVITY_SWEEP_HALF_WIDTH: f32 = tokens::MOTION_SWEEP_WIDTH_CELLS * 0.5;
186 const ACTIVITY_SWEEP_LEAD: f32 = 5.0;
187
188 #[must_use]
189 pub fn activity_sweep_strength(elapsed: Duration, width: usize, offset: f32) -> f32 {
190 let Some(since) = elapsed.checked_sub(crate::spin::EARN_DELAY) else {
191 return 0.0;
192 };
193 let phase = since.as_millis() % tokens::MOTION_LOOP_BREATHE_MS as u128;
194 let travel = tokens::MOTION_SWEEP_ACTIVE_MS as u128;
195 if phase >= travel || width == 0 {
196 return 0.0;
197 }
198 let center = phase as f32 / travel as f32 * (width as f32 + 2.0 * ACTIVITY_SWEEP_LEAD)
199 - ACTIVITY_SWEEP_LEAD;
200 let distance = (offset - center).abs();
201 if distance >= ACTIVITY_SWEEP_HALF_WIDTH {
202 return 0.0;
203 }
204 0.5 * (1.0 + (std::f32::consts::PI * distance / ACTIVITY_SWEEP_HALF_WIDTH).cos())
205 * ACTIVITY_SWEEP_PEAK
206 }
207
208 #[must_use]
209 pub fn activity_sweep_ink(fg: Color, ground: Color, highlight: Color, strength: f32) -> Color {
210 if strength <= 0.0 || !is_truecolor(fg) || !is_truecolor(highlight) {
211 return fg;
212 }
213 let ink = blend(highlight, fg, strength);
214 match (contrast_ratio(fg, ground), contrast_ratio(ink, ground)) {
215 (Some(before), Some(after)) if after >= before.min(4.5) => ink,
216 _ => fg,
217 }
218 }
219
220 pub fn paint_working_glow(
221 buf: &mut Buffer,
222 area: Rect,
223 label: &str,
224 elapsed: Duration,
225 policy: MotionPolicy,
226 highlight: Color,
227 background: Color,
228 ) {
229 if !policy.allows(MotionChannel::Tint)
230 || elapsed < crate::spin::EARN_DELAY
231 || !is_truecolor(highlight)
232 || !is_truecolor(background)
233 {
234 return;
235 }
236 let area = area.intersection(buf.area);
237 if area.is_empty() {
238 return;
239 }
240 let label = text::display_safe(label);
241 let width = text::width(&label).min(usize::from(area.width));
242 if width == 0 {
243 return;
244 }
245 let mut offset = 0usize;
246 for grapheme in label.graphemes(true) {
247 let cells = text::width(grapheme);
248 if cells == 0 {
249 continue;
250 }
251 if offset + cells > width {
252 break;
253 }
254 let cell = &mut buf[(area.x + offset as u16, area.y)];
255 let strength =
256 activity_sweep_strength(elapsed, width, offset as f32 + (cells - 1) as f32 / 2.0);
257 if strength > 0.0 && cell.symbol() == grapheme && !grapheme.chars().all(char::is_whitespace)
258 {
259 let ground = if is_truecolor(cell.bg) {
260 cell.bg
261 } else {
262 background
263 };
264 cell.fg = activity_sweep_ink(cell.fg, ground, highlight, strength);
265 }
266 offset += cells;
267 }
268 }
269
270 /// Perceptual OKLab working-glow ink with WCAG contrast guard.
271 ///
272 /// Lifts `fg` toward `highlight` in OKLab with a subtle specular highlight so
273 /// active labels glow cleanly without sRGB midtone dullness.
274 #[must_use]
275 pub fn activity_sweep_ink_oklab(
276 fg: Color,
277 ground: Color,
278 highlight: Color,
279 strength: f32,
280 ) -> Color {
281 if strength <= 0.0 || !is_truecolor(fg) || !is_truecolor(highlight) {
282 return fg;
283 }
284 let ink = specular_lift(fg, highlight, strength);
285 match (contrast_ratio(fg, ground), contrast_ratio(ink, ground)) {
286 (Some(before), Some(after)) if after >= before.min(4.5) => ink,
287 _ => fg,
288 }
289 }
290
291 /// Apply the perceptual OKLab active-turn glow sweep over `label` inside
292 /// `area`. Cleanly no-ops under `Reduced`/`Still` motion or non-truecolor
293 /// policies.
294 pub fn paint_working_glow_oklab(
295 buf: &mut Buffer,
296 area: Rect,
297 label: &str,
298 elapsed: Duration,
299 policy: MotionPolicy,
300 highlight: Color,
301 background: Color,
302 ) {
303 if !policy.allows(MotionChannel::Tint)
304 || elapsed < crate::spin::EARN_DELAY
305 || !is_truecolor(highlight)
306 || !is_truecolor(background)
307 {
308 return;
309 }
310 let area = area.intersection(buf.area);
311 if area.is_empty() {
312 return;
313 }
314 let label = text::display_safe(label);
315 let width = text::width(&label).min(usize::from(area.width));
316 if width == 0 {
317 return;
318 }
319 let mut offset = 0usize;
320 for grapheme in label.graphemes(true) {
321 let cells = text::width(grapheme);
322 if cells == 0 {
323 continue;
324 }
325 if offset + cells > width {
326 break;
327 }
328 let cell = &mut buf[(area.x + offset as u16, area.y)];
329 let strength =
330 activity_sweep_strength(elapsed, width, offset as f32 + (cells - 1) as f32 / 2.0);
331 if strength > 0.0 && cell.symbol() == grapheme && !grapheme.chars().all(char::is_whitespace)
332 {
333 let ground = if is_truecolor(cell.bg) {
334 cell.bg
335 } else {
336 background
337 };
338 cell.fg = activity_sweep_ink_oklab(cell.fg, ground, highlight, strength);
339 }
340 offset += cells;
341 }
342 }
343
344 /// Dual-harmonic luminous border shimmer strength in `0.0..=1.0` at perimeter
345 /// step `pos` of `perimeter`.
346 ///
347 /// Combines a primary clockwise travelling light crest (2.4 s period) with a
348 /// softer counter-propagating harmonic whisper (3.9 s period). Rests at `0.0`
349 /// during [`crate::spin::EARN_DELAY`] or when `perimeter == 0`.
350 #[must_use]
351 pub fn border_shimmer_strength(elapsed: Duration, perimeter: usize, pos: usize) -> f32 {
352 if perimeter == 0 {
353 return 0.0;
354 }
355 let Some(since) = elapsed.checked_sub(crate::spin::EARN_DELAY) else {
356 return 0.0;
357 };
358 let u = (pos % perimeter) as f64 / perimeter as f64;
359 let t_primary = (since.as_millis() % 2_400) as f64 / 2_400.0;
360 let t_counter = (since.as_millis() % 3_900) as f64 / 3_900.0;
361 let phase_a = (u - t_primary) * std::f64::consts::TAU;
362 let phase_b = (u + t_counter) * std::f64::consts::TAU;
363 let primary = ((phase_a.cos() + 1.0) * 0.5).powi(4) as f32;
364 let secondary = ((phase_b.cos() + 1.0) * 0.5).powi(3) as f32;
365 (0.72 * primary + 0.28 * secondary).clamp(0.0, 1.0)
366 }
367
368 fn is_shimmer_border_glyph(symbol: &str) -> bool {
369 matches!(
370 symbol,
371 "╭" | "╮" | "╰" | "╯" | "─" | "│" | "┌" | "┐" | "└" | "┘" | "+" | "-" | "|"
372 )
373 }
374
375 /// Glide a dual-harmonic OKLab luminous shimmer along an already-painted box
376 /// border around `area`.
377 ///
378 /// Only modulates box-drawing border cells; titles, metadata spans and interior
379 /// content stay untouched. Cleanly no-ops under `Reduced`/`Still` motion or
380 /// non-truecolor policies.
381 pub fn paint_border_shimmer(
382 buf: &mut Buffer,
383 area: Rect,
384 elapsed: Duration,
385 policy: MotionPolicy,
386 base_border: Color,
387 highlight: Color,
388 peak_highlight: Color,
389 ) {
390 if !policy.allows(MotionChannel::Tint)
391 || elapsed < crate::spin::EARN_DELAY
392 || !is_truecolor(base_border)
393 || !is_truecolor(highlight)
394 || !is_truecolor(peak_highlight)
395 {
396 return;
397 }
398 let clipped = area.intersection(buf.area);
399 if clipped.width < 3 || clipped.height < 3 {
400 return;
401 }
402 let w = usize::from(area.width);
403 let h = usize::from(area.height);
404 let perimeter = 2 * (w + h).saturating_sub(4);
405 if perimeter == 0 {
406 return;
407 }
408 let stops = [base_border, highlight, peak_highlight];
409 let mut apply_cell = |x: u16, y: u16, pos: usize| {
410 if !clipped.contains((x, y).into()) {
411 return;
412 }
413 let cell = &mut buf[(x, y)];
414 if cell.modifier.contains(Modifier::REVERSED) || !is_shimmer_border_glyph(cell.symbol()) {
415 return;
416 }
417 let strength = border_shimmer_strength(elapsed, perimeter, pos);
418 if strength <= 0.01 {
419 return;
420 }
421 let lit = if strength > 0.65 {
422 specular_lift(
423 oklab_ramp(&stops, strength),
424 peak_highlight,
425 (strength - 0.65) * 0.5,
426 )
427 } else {
428 mix_oklab(base_border, highlight, strength)
429 };
430 cell.set_fg(lit);
431 };
432
433 let mut pos = 0usize;
434 for dx in 0..area.width {
435 apply_cell(area.x + dx, area.y, pos);
436 pos += 1;
437 }
438 for dy in 1..area.height.saturating_sub(1) {
439 apply_cell(area.right() - 1, area.y + dy, pos);
440 pos += 1;
441 }
442 for dx in (0..area.width).rev() {
443 apply_cell(area.x + dx, area.bottom() - 1, pos);
444 pos += 1;
445 }
446 for dy in (1..area.height.saturating_sub(1)).rev() {
447 apply_cell(area.x, area.y + dy, pos);
448 pos += 1;
449 }
450 }
451
452 /// One value easing from where it is to a target, both in `0..=1`.
453 ///
454 /// `0.0` is the start state (the `from` role, the home column, nothing
455 /// revealed) and `1.0` the end state. A new step starts at rest.
456 #[derive(Clone, Copy, Debug, PartialEq)]
457 pub struct MotionStep {
458 from: f32,
459 to: f32,
460 start: Option<Instant>,
461 duration: Duration,
462 easing: MotionEasing,
463 }
464
465 impl Default for MotionStep {
466 fn default() -> Self {
467 Self::at_rest(0.0)
468 }
469 }
470
471 impl MotionStep {
472 /// A step that is not moving, at `value` (clamped to `0..=1`).
473 #[must_use]
474 pub fn at_rest(value: f32) -> Self {
475 let value = unit(value);
476 Self {
477 from: value,
478 to: value,
479 start: None,
480 duration: Duration::ZERO,
481 easing: MotionEasing::Linear,
482 }
483 }
484
485 /// Where the step is going.
486 #[must_use]
487 pub const fn target(&self) -> f32 {
488 self.to
489 }
490
491 /// The value at `now`, in `0..=1`. Before the start it is the start
492 /// value; at and after the end it is the target.
493 #[must_use]
494 pub fn at(&self, now: Instant) -> f32 {
495 let Some(start) = self.start else {
496 return self.to;
497 };
498 let elapsed = now.saturating_duration_since(start);
499 if self.duration.is_zero() || elapsed >= self.duration {
500 return self.to;
501 }
502 let t = elapsed.as_secs_f32() / self.duration.as_secs_f32();
503 unit(self.from + (self.to - self.from) * self.easing.apply(t))
504 }
505
506 /// Whether the step has reached its target at `now`.
507 #[must_use]
508 pub fn is_settled(&self, now: Instant) -> bool {
509 self.start.is_none_or(|start| {
510 self.duration.is_zero() || now.saturating_duration_since(start) >= self.duration
511 })
512 }
513
514 /// Whether this step still needs frames: it is moving, and `policy`
515 /// lets it move.
516 #[must_use]
517 pub fn is_live(&self, now: Instant, policy: MotionPolicy) -> bool {
518 policy.animates() && !self.is_settled(now)
519 }
520
521 /// Head for `target` (clamped to `0..=1`). Mid-flight it starts from
522 /// where the step is now, so nothing jumps. Asking for the target the
523 /// step already has changes nothing and does not restart it, so a
524 /// component may call this on every event. Returns whether anything
525 /// changed.
526 ///
527 /// Where the policy does not let `timing.channel` move, the step jumps
528 /// to `target` and is settled.
529 pub fn go(
530 &mut self,
531 target: f32,
532 now: Instant,
533 timing: MotionTiming,
534 policy: MotionPolicy,
535 ) -> bool {
536 if !target.is_finite() {
537 return false;
538 }
539 let target = unit(target);
540 if target == self.to {
541 return false;
542 }
543 *self = if policy.allows(timing.channel) && !timing.duration.is_zero() {
544 Self {
545 from: self.at(now),
546 to: target,
547 start: Some(now),
548 duration: timing.duration,
549 easing: timing.easing,
550 }
551 } else {
552 Self::at_rest(target)
553 };
554 true
555 }
556
557 /// Stop where the step is going, at once. Input wins: a key press
558 /// settles every running step.
559 pub fn settle(&mut self) {
560 *self = Self::at_rest(self.to);
561 }
562
563 /// The redraw this step wants after `now`, or `None` once it is settled
564 /// (or the policy does not animate).
565 #[must_use]
566 pub fn next_frame_at(&self, now: Instant, policy: MotionPolicy) -> Option<Instant> {
567 self.is_live(now, policy)
568 .then(|| now.checked_add(MOTION_FRAME_INTERVAL))
569 .flatten()
570 }
571
572 /// The value to show: eased where `policy` lets `channel` move, the
573 /// target where it does not. The one place the policy is applied at
574 /// paint time, so a mode changed mid-flight cannot leave a ghost.
575 fn shown(&self, now: Instant, policy: MotionPolicy, channel: MotionChannel) -> f32 {
576 if policy.allows(channel) {
577 self.at(now)
578 } else {
579 self.to
580 }
581 }
582
583 /// Progress for a draw-in, in `0..=1`: eased where `policy` lets space
584 /// move, the target where it does not. Feed it to a data display's
585 /// `drawn`.
586 #[must_use]
587 pub fn drawn(&self, now: Instant, policy: MotionPolicy) -> f32 {
588 self.shown(now, policy, MotionChannel::Space)
589 }
590
591 /// A column between `from` and `to`: slide a marker, nudge a panel.
592 #[must_use]
593 pub fn offset(&self, now: Instant, policy: MotionPolicy, from: u16, to: u16) -> u16 {
594 let v = self.shown(now, policy, MotionChannel::Space);
595 let (a, b) = (f32::from(from), f32::from(to));
596 (a + (b - a) * v).round().clamp(0.0, f32::from(u16::MAX)) as u16
597 }
598
599 /// How many of `width` columns are shown: `0` before, `width` after.
600 #[must_use]
601 pub fn reveal(&self, now: Instant, policy: MotionPolicy, width: u16) -> u16 {
602 self.offset(now, policy, 0, width)
603 }
604
605 /// Ink: [`Theme::fg`] blended from `from` toward `to`. At the ends it is
606 /// exactly `theme.fg(from)` and `theme.fg(to)`; between, a blend at
607 /// truecolor, and a jump to the nearer role anywhere else.
608 #[must_use]
609 pub fn fg(
610 &self,
611 now: Instant,
612 policy: MotionPolicy,
613 theme: &Theme,
614 from: Role,
615 to: Role,
616 ) -> Style {
617 let v = self.shown(now, policy, MotionChannel::Tint);
618 match ends(v, from, to) {
619 Some(role) => theme.fg(role),
620 None if !can_blend(theme) => theme.fg(nearer(v, from, to)),
621 None => match (theme.fg(from).fg, theme.fg(to).fg) {
622 (Some(a), Some(b)) => Style::default().fg(blend(b, a, v)),
623 _ => theme.fg(nearer(v, from, to)),
624 },
625 }
626 }
627
628 /// A ground: [`Theme::bg`] blended from `from` toward `to`. A ground the
629 /// terminal keeps (unpainted, or `NO_COLOR`) is not blended through: the
630 /// step jumps to the nearer role.
631 #[must_use]
632 pub fn bg(
633 &self,
634 now: Instant,
635 policy: MotionPolicy,
636 theme: &Theme,
637 from: Role,
638 to: Role,
639 ) -> Style {
640 let v = self.shown(now, policy, MotionChannel::Tint);
641 match ends(v, from, to) {
642 Some(role) => theme.bg(role),
643 None if !can_blend(theme) => theme.bg(nearer(v, from, to)),
644 None => match (theme.bg(from).bg, theme.bg(to).bg) {
645 (Some(a), Some(b)) => Style::default().bg(blend(b, a, v)),
646 _ => theme.bg(nearer(v, from, to)),
647 },
648 }
649 }
650 }
651
652 fn unit(v: f32) -> f32 {
653 if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }
654 }
655
656 fn ends(v: f32, from: Role, to: Role) -> Option<Role> {
657 if v <= 0.0 {
658 Some(from)
659 } else if v >= 1.0 {
660 Some(to)
661 } else {
662 None
663 }
664 }
665
666 fn nearer(v: f32, from: Role, to: Role) -> Role {
667 if v >= 0.5 { to } else { from }
668 }
669
670 /// A component's few named motions, and the schedule for all of them.
671 #[derive(Clone, Debug)]
672 pub struct MotionSet {
673 steps: Vec<(&'static str, MotionStep)>,
674 interval: Duration,
675 }
676
677 impl Default for MotionSet {
678 fn default() -> Self {
679 Self::new()
680 }
681 }
682
683 impl MotionSet {
684 #[must_use]
685 pub fn new() -> Self {
686 Self {
687 steps: Vec::new(),
688 interval: MOTION_FRAME_INTERVAL,
689 }
690 }
691
692 /// Cap redraws at one per `interval` (at least
693 /// [`MOTION_MIN_FRAME_INTERVAL`]): 33 ms holds a slow terminal to 30
694 /// frames a second.
695 #[must_use]
696 pub fn with_frame_interval(mut self, interval: Duration) -> Self {
697 self.interval = interval.max(MOTION_MIN_FRAME_INTERVAL);
698 self
699 }
700
701 /// Head the motion called `name` for `target`; see [`MotionStep::go`].
702 /// A name seen for the first time starts at rest at `0.0`.
703 pub fn go(
704 &mut self,
705 name: &'static str,
706 target: f32,
707 now: Instant,
708 timing: MotionTiming,
709 policy: MotionPolicy,
710 ) -> bool {
711 let at = match self.steps.iter().position(|(n, _)| *n == name) {
712 Some(at) => at,
713 None => {
714 self.steps.push((name, MotionStep::default()));
715 self.steps.len() - 1
716 }
717 };
718 self.steps[at].1.go(target, now, timing, policy)
719 }
720
721 /// The motion called `name`, or one at rest at `0.0`.
722 #[must_use]
723 pub fn step(&self, name: &str) -> MotionStep {
724 self.steps
725 .iter()
726 .find(|(n, _)| *n == name)
727 .map_or_else(MotionStep::default, |(_, step)| *step)
728 }
729
730 /// Settle every motion at its target now. Input wins.
731 pub fn settle_all(&mut self) {
732 for (_, step) in &mut self.steps {
733 step.settle();
734 }
735 }
736
737 /// Whether every motion has reached its target at `now`.
738 #[must_use]
739 pub fn is_settled(&self, now: Instant) -> bool {
740 self.steps.iter().all(|(_, step)| step.is_settled(now))
741 }
742
743 /// When the next redraw is due: one frame interval after `now` while any
744 /// motion is live, and `None` once everything is settled or the policy
745 /// does not animate. Ask right after a draw, with the instant it was
746 /// drawn at, so the interval is the cap between draws.
747 #[must_use]
748 pub fn next_frame_at(&self, now: Instant, policy: MotionPolicy) -> Option<Instant> {
749 self.steps
750 .iter()
751 .any(|(_, step)| step.is_live(now, policy))
752 .then(|| now.checked_add(self.interval))
753 .flatten()
754 }
755 }
756
757 /// The earliest of several components' [`MotionSet::next_frame_at`]
758 /// answers; `None` when none of them wants a frame.
759 #[must_use]
760 pub fn soonest_frame(due: impl IntoIterator<Item = Option<Instant>>) -> Option<Instant> {
761 due.into_iter().flatten().min()
762 }
763
764 /// What one frame may spend, and the earliest redraw anyone asked for.
765 ///
766 /// Kept from the first draft of this package. The host makes one per frame,
767 /// each component claims what it draws, and the host reads
768 /// [`FrameBudget::next_frame_in`] after the draw. Only the first
769 /// [`claim_spinner`](Self::claim_spinner) and
770 /// [`claim_horizon`](Self::claim_horizon) return `true`: a second spinner is
771 /// drawn as the still `●` plus its word (hiding it would hide real work), and
772 /// a second horizon is not drawn.
773 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
774 pub struct FrameBudget {
775 next: Option<Duration>,
776 spinners: usize,
777 horizons: usize,
778 }
779
780 impl FrameBudget {
781 #[must_use]
782 pub fn new() -> Self {
783 Self::default()
784 }
785
786 /// A redraw wanted `after` from now (`None` asks for nothing), as
787 /// [`spin::next_frame_in`](crate::spin::next_frame_in) answers.
788 pub fn request(&mut self, after: Option<Duration>) {
789 if let Some(after) = after {
790 self.next = Some(self.next.map_or(after, |current| current.min(after)));
791 }
792 }
793
794 /// A redraw due at `at`, as [`MotionSet::next_frame_at`] answers. An
795 /// instant already past asks for a frame now.
796 pub fn request_at(&mut self, now: Instant, at: Option<Instant>) {
797 self.request(at.map(|at| at.saturating_duration_since(now)));
798 }
799
800 /// The soonest redraw anyone asked for; `None` when nothing moves, so an
801 /// idle screen sleeps until an event.
802 #[must_use]
803 pub fn next_frame_in(&self) -> Option<Duration> {
804 self.next
805 }
806
807 /// Whether this is the frame's first spinner.
808 pub fn claim_spinner(&mut self) -> bool {
809 self.spinners += 1;
810 self.spinners == 1
811 }
812
813 /// Whether this is the frame's first horizon rule.
814 pub fn claim_horizon(&mut self) -> bool {
815 self.horizons += 1;
816 self.horizons == 1
817 }
818 }
819
820 /// The words [`MotionDemo`] shows.
821 #[derive(Clone, Debug, PartialEq, Eq)]
822 pub struct MotionDemoWords {
823 pub working: Cow<'static, str>,
824 pub done: Cow<'static, str>,
825 pub slide: Cow<'static, str>,
826 pub detail: Cow<'static, str>,
827 }
828
829 impl Default for MotionDemoWords {
830 fn default() -> Self {
831 Self {
832 working: Cow::Borrowed("Working"),
833 done: Cow::Borrowed("Done"),
834 slide: Cow::Borrowed("Selected"),
835 detail: Cow::Borrowed("patch applied to 3 files"),
836 }
837 }
838 }
839
840 /// The reference component for this module: one state change, painted at
841 /// one instant.
842 ///
843 /// Three rows. The first is a state mark and word whose ink eases from
844 /// `Muted` to `Live` (a tint). The mark and the word always say the real
845 /// state, so a frame caught mid-step is never ambiguous. The second slides a
846 /// selection marker across, and the third reveals a line of detail. Where
847 /// the policy does not animate, every row is its end state.
848 #[derive(Clone, Debug)]
849 pub struct MotionDemo<'a> {
850 motions: &'a MotionSet,
851 now: Instant,
852 policy: MotionPolicy,
853 done: bool,
854 words: MotionDemoWords,
855 }
856
857 impl<'a> MotionDemo<'a> {
858 #[must_use]
859 pub fn new(motions: &'a MotionSet, now: Instant, policy: MotionPolicy, done: bool) -> Self {
860 Self {
861 motions,
862 now,
863 policy,
864 done,
865 words: MotionDemoWords::default(),
866 }
867 }
868
869 #[must_use]
870 pub fn with_words(mut self, words: MotionDemoWords) -> Self {
871 self.words = words;
872 self
873 }
874
875 /// Start the three motions toward `done` (or back to working).
876 pub fn start(motions: &mut MotionSet, done: bool, now: Instant, policy: MotionPolicy) {
877 let target = if done { 1.0 } else { 0.0 };
878 motions.go("ink", target, now, MotionTiming::ARRIVE, policy);
879 motions.go(
880 "slide",
881 target,
882 now,
883 MotionTiming::space(MotionTiming::ARRIVE.duration, MotionEasing::EaseOut),
884 policy,
885 );
886 motions.go("reveal", target, now, MotionTiming::PANEL, policy);
887 }
888 }
889
890 impl Paint for MotionDemo<'_> {
891 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
892 let area = area.intersection(buf.area);
893 if area.is_empty() {
894 return;
895 }
896 let (now, policy) = (self.now, self.policy);
897 let row = |i: u16| (area.height > i).then_some(area.y + i);
898 let put = |buf: &mut Buffer, x: u16, y: u16, s: &str, style: Style, max: u16| {
899 if x < area.right() {
900 buf.set_stringn(x, y, s, usize::from(max.min(area.right() - x)), style);
901 }
902 };
903
904 if let Some(y) = row(0) {
905 let ink = self
906 .motions
907 .step("ink")
908 .fg(now, policy, theme, Role::Muted, Role::Live);
909 let (mark, word) = if self.done {
910 (glyphs::DONE, &self.words.done)
911 } else {
912 (glyphs::CURRENT, &self.words.working)
913 };
914 let mark = glyphs::pick(mark, theme.ascii());
915 put(buf, area.x, y, mark, ink, area.width);
916 let x = area.x.saturating_add(text::width(mark) as u16 + 1);
917 put(
918 buf,
919 x,
920 y,
921 &text::display_safe(word),
922 theme.fg(Role::Foreground),
923 area.width,
924 );
925 }
926
927 if let Some(y) = row(1) {
928 let marker = glyphs::pick(glyphs::SELECTION, theme.ascii());
929 let label = text::display_safe(&self.words.slide);
930 let used = text::width(marker) + 1 + text::width(&label);
931 let span = area.width.saturating_sub(used as u16).min(24);
932 let x = area
933 .x
934 .saturating_add(self.motions.step("slide").offset(now, policy, 0, span));
935 put(buf, x, y, marker, theme.fg(Role::Accent), area.width);
936 let lx = x.saturating_add(text::width(marker) as u16 + 1);
937 put(buf, lx, y, &label, theme.fg(Role::Foreground), area.width);
938 }
939
940 if let Some(y) = row(2) {
941 let detail = text::display_safe(&self.words.detail);
942 let full = text::width(&detail).min(usize::from(area.width)) as u16;
943 let shown = self.motions.step("reveal").reveal(now, policy, full);
944 put(buf, area.x, y, &detail, theme.fg(Role::Muted), shown);
945 }
946 }
947
948 fn height(&self, _width: u16, _theme: &Theme) -> u16 {
949 3
950 }
951 }
952
953 #[cfg(test)]
954 mod activity_sweep_tests {
955 use super::*;
956
957 #[test]
958 fn sweep_rests_during_the_earn_delay_and_the_end_of_each_loop() {
959 let earn = crate::spin::EARN_DELAY;
960 assert_eq!(activity_sweep_strength(earn / 2, 12, 0.0), 0.0);
961 let rest = earn + ACTIVITY_SWEEP_TRAVEL + Duration::from_millis(100);
962 for offset in 0..12 {
963 assert_eq!(activity_sweep_strength(rest, 12, offset as f32), 0.0);
964 }
965 let midway = earn + ACTIVITY_SWEEP_TRAVEL / 2;
966 let peak = activity_sweep_strength(midway, 12, 6.0);
967 assert!((peak - ACTIVITY_SWEEP_PEAK).abs() < 1e-3, "{peak}");
968 assert!(activity_sweep_strength(midway, 12, 1.0) < 0.1);
969 let next_loop = midway + Duration::from_millis(tokens::MOTION_LOOP_BREATHE_MS as u64);
970 assert_eq!(activity_sweep_strength(next_loop, 12, 6.0), peak);
971 }
972 }
973
973 lines RUST