返回 CodeWhale
display_refresh.rs
根目录 / crates / tui / src / tui / display_refresh.rs
1 //! One-shot primary-display refresh probe with fail-closed defaults.
2 //!
3 //! Adapted from Grok's host display-refresh probe: measure once per process,
4 //! clamp to sane bounds, and never panic into the render loop. SSH / missing
5 //! FFI paths fall back to the fixed [`crate::tui::frame_rate_limiter`] defaults.
6
7 use std::time::{Duration, Instant};
8
9 /// Inclusive lower bound for accepted refresh rates.
10 pub const MIN_HZ: u32 = 30;
11 /// Inclusive upper bound for accepted refresh rates.
12 pub const MAX_HZ: u32 = 240;
13 /// Safe fallback when probing is skipped or fails (≈8 fps / 120 ms underwater
14 /// atmosphere — not the draw-rate cap). Calmed from the historical 80 ms for
15 /// v0.9.4: the field still breathes, but the ambient cadence no longer feels
16 /// restless next to real content.
17 pub const FALLBACK_ANIMATION_MS: u64 = 120;
18 /// Absolute floor for adaptive animation intervals (≈ 4 fps).
19 pub const MIN_ANIMATION_HZ: u32 = 4;
20 /// Absolute ceiling for adaptive animation intervals (≈ 30 fps).
21 pub const MAX_ANIMATION_HZ: u32 = 30;
22 /// Ghostty keeps interactive feedback responsive, but ambient water must not
23 /// force a full-screen 60 FPS repaint while the user is idle.
24 pub const GHOSTTY_ATMOSPHERE_HZ: u32 = 30;
25 pub const GHOSTTY_INTERACTIVE_HZ: u32 = 60;
26
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28 pub enum DisplayRefreshSource {
29 None,
30 // Only constructed inside `#[cfg(target_os = "macos")]` in `probe_inner`
31 // below; non-macOS builds never build a value of this variant.
32 #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
33 MacosCoreGraphics,
34 EnvOverride,
35 }
36
37 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
38 pub struct DisplayRefreshProbeResult {
39 pub hz: Option<u32>,
40 pub source: DisplayRefreshSource,
41 /// Stable skip/error token when `hz` is `None`.
42 pub skip_reason: &'static str,
43 pub duration_ms: u64,
44 }
45
46 impl DisplayRefreshProbeResult {
47 #[must_use]
48 pub fn outcome(self) -> &'static str {
49 if self.hz.is_some() {
50 "ok"
51 } else if self.skip_reason == "error" {
52 "error"
53 } else {
54 "skipped"
55 }
56 }
57 }
58
59 // Keep outcome() public for diagnostics even when the TUI only logs the probe
60 // struct fields today.
61 const _: fn(DisplayRefreshProbeResult) -> &'static str = DisplayRefreshProbeResult::outcome;
62
63 /// Once per process. Infallible.
64 ///
65 /// Under `cfg(test)` the host panel is not consulted. The probe is
66 /// `OnceLock`-cached and reads real hardware, so a cadence test on a 60 Hz
67 /// developer machine computed a different interval than the same test on CI,
68 /// with no way to pin the input the way `low_motion` and `fancy_animations`
69 /// are already pinned (#5359). Tests get the unmeasured result — the same one
70 /// a headless CI runner sees — and any test that wants a specific panel says
71 /// so with [`DisplayRefreshPin`].
72 pub fn probe_display_refresh() -> DisplayRefreshProbeResult {
73 #[cfg(test)]
74 {
75 pinned_probe()
76 }
77 #[cfg(not(test))]
78 {
79 static CACHE: std::sync::OnceLock<DisplayRefreshProbeResult> = std::sync::OnceLock::new();
80 *CACHE.get_or_init(probe_uncached)
81 }
82 }
83
84 /// What a test observes when it has not pinned a panel: no measurement, so
85 /// [`animation_interval_for_hz`] falls back to [`FALLBACK_ANIMATION_MS`].
86 #[cfg(test)]
87 const UNMEASURED: DisplayRefreshProbeResult = DisplayRefreshProbeResult {
88 hz: None,
89 source: DisplayRefreshSource::None,
90 skip_reason: "not_probed_under_test",
91 duration_ms: 0,
92 };
93
94 #[cfg(test)]
95 thread_local! {
96 static PINNED: std::cell::Cell<Option<DisplayRefreshProbeResult>> =
97 const { std::cell::Cell::new(None) };
98 }
99
100 #[cfg(test)]
101 fn pinned_probe() -> DisplayRefreshProbeResult {
102 PINNED.with(|pinned| pinned.get().unwrap_or(UNMEASURED))
103 }
104
105 /// Pin the probe for the current thread until dropped.
106 ///
107 /// Thread-local rather than process-global: the cadence tests run in parallel
108 /// with everything else, and a shared cell would let one test's panel decide
109 /// another's interval.
110 #[cfg(test)]
111 pub(crate) struct DisplayRefreshPin {
112 previous: Option<DisplayRefreshProbeResult>,
113 }
114
115 #[cfg(test)]
116 impl DisplayRefreshPin {
117 /// Pin a measured panel at `hz`, as if the host reported it.
118 pub(crate) fn measured(hz: u32) -> Self {
119 let accepted = accept_hz(hz);
120 Self::install(DisplayRefreshProbeResult {
121 hz: accepted,
122 source: DisplayRefreshSource::EnvOverride,
123 skip_reason: if accepted.is_some() {
124 ""
125 } else {
126 "out_of_range"
127 },
128 duration_ms: 0,
129 })
130 }
131
132 fn install(next: DisplayRefreshProbeResult) -> Self {
133 let previous = PINNED.with(|pinned| pinned.replace(Some(next)));
134 Self { previous }
135 }
136 }
137
138 #[cfg(test)]
139 impl Drop for DisplayRefreshPin {
140 fn drop(&mut self) {
141 PINNED.with(|pinned| pinned.set(self.previous));
142 }
143 }
144
145 fn probe_uncached() -> DisplayRefreshProbeResult {
146 let start = Instant::now();
147 let (hz, source, skip_reason) = probe_inner();
148 DisplayRefreshProbeResult {
149 hz,
150 source,
151 skip_reason,
152 duration_ms: start.elapsed().as_millis() as u64,
153 }
154 }
155
156 fn probe_inner() -> (Option<u32>, DisplayRefreshSource, &'static str) {
157 if let Some(hz) = env_override_hz() {
158 return match accept_hz(hz) {
159 Some(hz) => (Some(hz), DisplayRefreshSource::EnvOverride, ""),
160 None => (None, DisplayRefreshSource::EnvOverride, "out_of_range"),
161 };
162 }
163 if is_remote_session() {
164 return (None, DisplayRefreshSource::None, "ssh");
165 }
166 #[cfg(target_os = "macos")]
167 {
168 match probe_macos() {
169 Ok(hz) => match accept_hz(hz) {
170 Some(hz) => (Some(hz), DisplayRefreshSource::MacosCoreGraphics, ""),
171 None => (
172 None,
173 DisplayRefreshSource::MacosCoreGraphics,
174 "out_of_range",
175 ),
176 },
177 Err(reason) => (None, DisplayRefreshSource::MacosCoreGraphics, reason),
178 }
179 }
180 #[cfg(not(target_os = "macos"))]
181 {
182 (None, DisplayRefreshSource::None, "unsupported")
183 }
184 }
185
186 fn env_override_hz() -> Option<u32> {
187 let raw = std::env::var("CODEWHALE_DISPLAY_HZ").ok()?;
188 raw.trim().parse().ok()
189 }
190
191 fn is_remote_session() -> bool {
192 std::env::var_os("SSH_CONNECTION").is_some()
193 || std::env::var_os("SSH_CLIENT").is_some()
194 || std::env::var_os("SSH_TTY").is_some()
195 }
196
197 fn terminal_is_ghostty_values(term_program: &str, term: &str) -> bool {
198 term_program.trim().eq_ignore_ascii_case("ghostty")
199 || term.to_ascii_lowercase().contains("ghostty")
200 }
201
202 /// Whether the current terminal is Ghostty. Tests keep this uncached because
203 /// they pin environment values; production caches the immutable startup env.
204 #[must_use]
205 pub fn terminal_is_ghostty() -> bool {
206 #[cfg(test)]
207 {
208 terminal_is_ghostty_values(
209 &std::env::var("TERM_PROGRAM").unwrap_or_default(),
210 &std::env::var("TERM").unwrap_or_default(),
211 )
212 }
213 #[cfg(not(test))]
214 {
215 static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
216 *CACHE.get_or_init(|| {
217 terminal_is_ghostty_values(
218 &std::env::var("TERM_PROGRAM").unwrap_or_default(),
219 &std::env::var("TERM").unwrap_or_default(),
220 )
221 })
222 }
223 }
224
225 #[must_use]
226 pub fn terminal_is_apple_terminal() -> bool {
227 #[cfg(test)]
228 {
229 false
230 }
231 #[cfg(not(test))]
232 {
233 static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
234 *CACHE.get_or_init(|| {
235 std::env::var("TERM_PROGRAM").is_ok_and(|program| program.trim() == "Apple_Terminal")
236 })
237 }
238 }
239
240 fn accept_hz(hz: u32) -> Option<u32> {
241 if (MIN_HZ..=MAX_HZ).contains(&hz) {
242 Some(hz)
243 } else {
244 None
245 }
246 }
247
248 #[cfg(target_os = "macos")]
249 fn probe_macos() -> Result<u32, &'static str> {
250 // CoreGraphics is available on macOS; use a minimal safe FFI for the main
251 // display mode. Fail closed on any error.
252 //
253 // CGDisplayModeGetRefreshRate returns 0 for some virtual displays — treat
254 // that as skipped rather than forcing a zero cadence.
255 unsafe extern "C" {
256 fn CGMainDisplayID() -> u32;
257 fn CGDisplayCopyDisplayMode(display: u32) -> *mut std::ffi::c_void;
258 fn CGDisplayModeGetRefreshRate(mode: *mut std::ffi::c_void) -> f64;
259 fn CGDisplayModeRelease(mode: *mut std::ffi::c_void);
260 }
261 // SAFETY: `mode` is null-checked and released after use.
262 unsafe {
263 let display = CGMainDisplayID();
264 let mode = CGDisplayCopyDisplayMode(display);
265 if mode.is_null() {
266 return Err("no_mode");
267 }
268 let rate = CGDisplayModeGetRefreshRate(mode);
269 CGDisplayModeRelease(mode);
270 if !rate.is_finite() || rate <= 0.0 {
271 return Err("zero_rate");
272 }
273 let hz = rate.round() as u32;
274 if hz == 0 {
275 return Err("zero_rate");
276 }
277 Ok(hz)
278 }
279 }
280
281 /// Convert a measured display Hz into a bounded animation interval.
282 ///
283 /// Policy: target roughly `display_hz / 8` for atmosphere (calm, not steppy
284 /// on high-Hz panels), clamped to [`MIN_ANIMATION_HZ`]..=[`MAX_ANIMATION_HZ`].
285 /// Missing measurement falls back to [`FALLBACK_ANIMATION_MS`] (≈8 fps /
286 /// 120 ms atmosphere). `low_motion` always wins (2.4s).
287 #[must_use]
288 pub fn animation_interval_for_hz(display_hz: Option<u32>, low_motion: bool) -> Duration {
289 if low_motion {
290 return Duration::from_millis(2_400);
291 }
292 match display_hz {
293 // No measurement, or a standard 60 Hz panel: keep the 120 ms
294 // atmosphere cadence so low-Hz hosts do not feel steppier.
295 None | Some(0..=60) => Duration::from_millis(FALLBACK_ANIMATION_MS),
296 // High-Hz panels: ~1/8 of refresh, bounded so we never thrash or stall.
297 Some(hz) => {
298 let target = (hz / 8).clamp(MIN_ANIMATION_HZ, MAX_ANIMATION_HZ);
299 let ms = (1000u32 / target.max(1)).max(1);
300 // Never slower than the fallback (only raise cadence).
301 Duration::from_millis(u64::from(ms).min(FALLBACK_ANIMATION_MS))
302 }
303 }
304 }
305
306 /// Convenience: probe once and return the animation interval for the current
307 /// motion policy. Safe to call every frame — probe is OnceLock-cached.
308 #[must_use]
309 pub fn adaptive_animation_interval_ms(low_motion: bool) -> u64 {
310 let probe = probe_display_refresh();
311 animation_interval_for_hz(probe.hz, low_motion).as_millis() as u64
312 }
313
314 /// Map measured Hz into a frame-rate limiter minimum interval, never exceeding
315 /// the historical 120 FPS draw cap and never undercutting low-motion 30 FPS.
316 #[must_use]
317 pub fn draw_min_interval_for_hz(display_hz: Option<u32>, low_motion: bool) -> Duration {
318 use super::frame_rate_limiter::{LOW_MOTION_MIN_FRAME_INTERVAL, MIN_FRAME_INTERVAL};
319 if low_motion {
320 return LOW_MOTION_MIN_FRAME_INTERVAL;
321 }
322 let Some(hz) = display_hz else {
323 return MIN_FRAME_INTERVAL;
324 };
325 // Cap draw rate at min(display_hz, 120). Never faster than MIN_FRAME_INTERVAL.
326 let capped = hz.clamp(30, 120);
327 let nanos = 1_000_000_000u64 / u64::from(capped);
328 Duration::from_nanos(nanos).max(MIN_FRAME_INTERVAL)
329 }
330
331 /// Content-driven draw cadence: atmosphere rate when only ambience moves;
332 /// full rate for stream / selection / input / hover.
333 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
334 pub enum DrawCadenceTier {
335 /// Only ambient life / ocean breath — use atmosphere interval.
336 Atmosphere,
337 /// Streaming, selection, input, or interactive hover — full draw cap.
338 Interactive,
339 }
340
341 /// Choose the draw min-interval for the current content tier.
342 #[must_use]
343 pub fn content_driven_draw_interval(
344 tier: DrawCadenceTier,
345 display_hz: Option<u32>,
346 low_motion: bool,
347 ) -> Duration {
348 if !low_motion && terminal_is_ghostty() {
349 let hz = match tier {
350 DrawCadenceTier::Atmosphere => GHOSTTY_ATMOSPHERE_HZ,
351 DrawCadenceTier::Interactive => GHOSTTY_INTERACTIVE_HZ,
352 };
353 return Duration::from_nanos(1_000_000_000u64 / u64::from(hz));
354 }
355 match tier {
356 DrawCadenceTier::Atmosphere => animation_interval_for_hz(display_hz, low_motion),
357 DrawCadenceTier::Interactive => draw_min_interval_for_hz(display_hz, low_motion),
358 }
359 }
360
361 /// Infer cadence tier from coarse app activity signals.
362 #[must_use]
363 pub fn cadence_tier_from_signals(
364 streaming_or_loading: bool,
365 selection_active: bool,
366 input_nonempty: bool,
367 pointer_hover_active: bool,
368 ) -> DrawCadenceTier {
369 if streaming_or_loading || selection_active || input_nonempty || pointer_hover_active {
370 DrawCadenceTier::Interactive
371 } else {
372 DrawCadenceTier::Atmosphere
373 }
374 }
375
376 #[cfg(test)]
377 mod tests {
378 use super::*;
379 use crate::tui::frame_rate_limiter::{LOW_MOTION_MIN_FRAME_INTERVAL, MIN_FRAME_INTERVAL};
380
381 #[test]
382 fn falls_back_to_default_when_probe_has_no_hz() {
383 let interval = animation_interval_for_hz(None, false);
384 assert_eq!(interval, Duration::from_millis(FALLBACK_ANIMATION_MS));
385 assert_eq!(FALLBACK_ANIMATION_MS, 120);
386 }
387
388 #[test]
389 fn low_motion_wins_over_measured_hz() {
390 let interval = animation_interval_for_hz(Some(144), true);
391 assert_eq!(interval, Duration::from_millis(2_400));
392 }
393
394 #[test]
395 fn high_hz_display_raises_cadence_but_stays_bounded() {
396 let interval = animation_interval_for_hz(Some(144), false);
397 // 144/8 = 18 → ~55ms: calmer than the old 1/5 divisor, still smooth.
398 assert!(interval >= Duration::from_millis(33));
399 assert!(interval <= Duration::from_millis(250));
400 }
401
402 #[test]
403 fn sixty_hz_keeps_historical_atmosphere_cadence() {
404 let interval = animation_interval_for_hz(Some(60), false);
405 // Standard panels stay on the 120 ms atmosphere floor.
406 assert_eq!(interval, Duration::from_millis(FALLBACK_ANIMATION_MS));
407 }
408
409 #[test]
410 fn ghostty_separates_ambient_and_interactive_cadence() {
411 let _guard = crate::test_support::lock_test_env();
412 let previous_program = std::env::var_os("TERM_PROGRAM");
413 let previous_term = std::env::var_os("TERM");
414 // SAFETY: serialized by the process-wide test environment lock.
415 unsafe {
416 std::env::set_var("TERM_PROGRAM", "Ghostty");
417 std::env::set_var("TERM", "xterm-ghostty");
418 }
419 assert_eq!(
420 content_driven_draw_interval(DrawCadenceTier::Atmosphere, Some(120), false),
421 Duration::from_nanos(1_000_000_000 / 30)
422 );
423 assert_eq!(
424 content_driven_draw_interval(DrawCadenceTier::Interactive, Some(120), false),
425 Duration::from_nanos(1_000_000_000 / 60)
426 );
427 // SAFETY: cleanup under the same lock.
428 unsafe {
429 match previous_program {
430 Some(value) => std::env::set_var("TERM_PROGRAM", value),
431 None => std::env::remove_var("TERM_PROGRAM"),
432 }
433 match previous_term {
434 Some(value) => std::env::set_var("TERM", value),
435 None => std::env::remove_var("TERM"),
436 }
437 }
438 }
439
440 #[test]
441 fn accept_hz_rejects_out_of_range() {
442 assert_eq!(accept_hz(10), None);
443 assert_eq!(accept_hz(60), Some(60));
444 assert_eq!(accept_hz(500), None);
445 }
446
447 #[test]
448 fn draw_cap_never_exceeds_historical_min_interval() {
449 let interval = draw_min_interval_for_hz(Some(240), false);
450 assert!(interval >= MIN_FRAME_INTERVAL);
451 }
452
453 #[test]
454 fn draw_cap_respects_low_motion() {
455 assert_eq!(
456 draw_min_interval_for_hz(Some(144), true),
457 LOW_MOTION_MIN_FRAME_INTERVAL
458 );
459 }
460
461 #[test]
462 fn probe_is_infallible_and_cached() {
463 let a = probe_display_refresh();
464 let b = probe_display_refresh();
465 assert_eq!(a, b);
466 // Either measured or skipped — never panics.
467 assert!(a.outcome() == "ok" || a.outcome() == "skipped" || a.outcome() == "error");
468 }
469
470 /// The real host probe, which `probe_display_refresh` no longer reaches
471 /// under test. Its result is whatever this machine reports, so assert only
472 /// the invariants that hold everywhere — but keep calling it, so the FFI
473 /// and env-override paths stay compiled and exercised rather than becoming
474 /// dead code the moment tests stopped consulting the panel.
475 #[test]
476 fn the_host_probe_itself_stays_infallible_and_in_range() {
477 let probe = probe_uncached();
478 assert!(
479 probe.outcome() == "ok" || probe.outcome() == "skipped" || probe.outcome() == "error"
480 );
481 if let Some(hz) = probe.hz {
482 assert!(
483 (MIN_HZ..=MAX_HZ).contains(&hz),
484 "{hz} outside accepted range"
485 );
486 assert!(probe.skip_reason.is_empty());
487 } else {
488 assert!(!probe.skip_reason.is_empty(), "a skip must name its reason");
489 }
490 }
491
492 #[test]
493 fn unpinned_tests_never_see_the_host_panel() {
494 let probe = probe_display_refresh();
495 assert_eq!(probe.hz, None, "a test must not inherit the developer's Hz");
496 assert_eq!(probe.skip_reason, "not_probed_under_test");
497 assert_eq!(
498 adaptive_animation_interval_ms(false),
499 FALLBACK_ANIMATION_MS,
500 "the unmeasured fallback is what CI computes"
501 );
502 }
503
504 #[test]
505 fn a_pinned_panel_drives_the_cadence_and_is_restored_on_drop() {
506 assert_eq!(probe_display_refresh().hz, None);
507 {
508 let _pin = DisplayRefreshPin::measured(144);
509 assert_eq!(probe_display_refresh().hz, Some(144));
510 assert_eq!(
511 adaptive_animation_interval_ms(false),
512 animation_interval_for_hz(Some(144), false).as_millis() as u64
513 );
514 assert!(adaptive_animation_interval_ms(false) < FALLBACK_ANIMATION_MS);
515 }
516 assert_eq!(
517 probe_display_refresh().hz,
518 None,
519 "the pin must not outlive its scope"
520 );
521 }
522
523 #[test]
524 fn a_pin_outside_the_accepted_range_reads_as_unmeasured() {
525 let _pin = DisplayRefreshPin::measured(1);
526 let probe = probe_display_refresh();
527 assert_eq!(probe.hz, None);
528 assert_eq!(probe.skip_reason, "out_of_range");
529 assert_eq!(adaptive_animation_interval_ms(false), FALLBACK_ANIMATION_MS);
530 }
531 }
532
532 lines RUST