Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui: Apply frame limits consistently and stabilize pacing (#66237)

Lukas Wirth2580a00264a7
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 0d83066db80..6be8eaeec8e 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -1327,11 +1327,34 @@ const THIRTY_FPS_INTERVAL: Duration = Duration::from_micros(33333);
const SIXTY_FPS_INTERVAL: Duration = Duration::from_micros(16667);
const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
-/// Display-link timestamps can straddle a target interval by fractions of a
-/// millisecond. Accepting that callback preserves an even display-frame divisor
-/// instead of occasionally waiting for an additional refresh.
-fn frame_request_arrived_too_early(elapsed: Duration, minimum_interval: Duration) -> bool {
- elapsed < minimum_interval.saturating_sub(FRAME_INTERVAL_TOLERANCE)
+/// Keeps throttled frames on a stable cadence despite callback delivery jitter.
+#[derive(Default)]
+struct FramePacer {
+ last_frame: Option<Instant>,
+}
+
+impl FramePacer {
+ fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
+ if let Some(interval) = minimum_interval
+ && let Some(last_frame) = self.last_frame
+ {
+ let deadline = last_frame + interval;
+ if now + FRAME_INTERVAL_TOLERANCE < deadline {
+ return true;
+ }
+ // Correct small dispatch delays without shifting subsequent deadlines,
+ // but bound the correction to a quarter interval. Larger delays restart
+ // the cadence so recovery cannot produce closely spaced catch-up frames.
+ self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
+ deadline
+ } else {
+ now
+ });
+ } else {
+ self.last_frame = Some(now);
+ }
+ false
+ }
}
fn minimum_frame_interval(
@@ -1697,7 +1720,6 @@ impl Window {
let needs_present = Rc::new(Cell::new(false));
let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
- let last_frame_time = Rc::new(Cell::new(None));
platform_window
.request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
@@ -1821,6 +1843,7 @@ impl Window {
let next_frame_callbacks = next_frame_callbacks.clone();
let input_rate_tracker = input_rate_tracker.clone();
let mut deferred_force_render = false;
+ let mut frame_pacer = FramePacer::default();
move |request_frame_options| {
#[cfg(feature = "profiler")]
let (_foreground_turn, window_id) = {
@@ -1866,16 +1889,24 @@ impl Window {
.update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
.log_err();
+ // Keep presenting briefly after high-rate input to prevent display
+ // underclocking, but subject to the same power limits as redraws.
+ let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate();
+ let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
+ let has_frame_demand = invalidator.is_dirty()
+ || force_render
+ || has_next_frame_callbacks
+ || request_frame_options.require_presentation
+ || needs_present.get()
+ || high_rate_input;
+
// Throttle frame rate based on conditions:
// - Thermal pressure (Serious/Critical): cap to ~60fps
// - Low power mode: cap to ~30fps
// - Inactive window (not focused): use its configured frame interval
- let should_throttle = !request_frame_options.require_presentation
- && (request_frame_options.force_render
- || !next_frame_callbacks.borrow().is_empty());
- let inactive_without_high_rate_input = should_throttle
- && !active.get()
- && !input_rate_tracker.borrow_mut().is_high_rate();
+ let should_throttle = !request_frame_options.require_presentation;
+ let inactive_without_high_rate_input =
+ should_throttle && !active.get() && !high_rate_input;
let (thermal_state, power_mode) =
power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown));
let min_frame_interval = minimum_frame_interval(
@@ -1887,42 +1918,34 @@ impl Window {
);
let now = Instant::now();
- if let Some(min_interval) = min_frame_interval {
- if let Some(last_frame) = last_frame_time.get()
- && frame_request_arrived_too_early(
- now.duration_since(last_frame),
- min_interval,
- )
- {
- // Don't lose a pending forced render to throttling.
- deferred_force_render |= force_render;
- // Deferred by throttling: ask demand-driven platforms to retry.
- handle
- .update(&mut cx, |_, window, _| {
- window.platform_window.schedule_frame();
- })
- .log_err();
- // The demand that entered this branch (a deferred forced
- // render or pending next-frame callbacks) is still
- // unserved; platforms that stop requesting frames for
- // idle windows need a wakeup to deliver the retry.
- invalidator.wake_platform();
- #[cfg(feature = "profiler")]
- profiler::journal::record_frame_skipped(
- window_id,
- Instant::now(),
- if inactive_without_high_rate_input {
- profiler::journal::FrameSkipReason::InactiveFrameRateLimit
- } else if power_mode == crate::PowerMode::LowPower {
- profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
- } else {
- profiler::journal::FrameSkipReason::ThermalFrameRateLimit
- },
- );
- return;
- }
+ // Idle display-link ticks must neither consume a frame slot nor
+ // wake a demand-driven frame source.
+ if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
+ // Don't lose a pending forced render to throttling.
+ deferred_force_render |= force_render;
+ // Deferred by throttling: ask demand-driven platforms to retry.
+ handle
+ .update(&mut cx, |_, window, _| {
+ window.platform_window.schedule_frame();
+ })
+ .log_err();
+ // The demand is still unserved; platforms that stop
+ // requesting frames for idle windows need a wakeup to retry.
+ invalidator.wake_platform();
+ #[cfg(feature = "profiler")]
+ profiler::journal::record_frame_skipped(
+ window_id,
+ Instant::now(),
+ if inactive_without_high_rate_input {
+ profiler::journal::FrameSkipReason::InactiveFrameRateLimit
+ } else if power_mode == crate::PowerMode::LowPower {
+ profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
+ } else {
+ profiler::journal::FrameSkipReason::ThermalFrameRateLimit
+ },
+ );
+ return;
}
- last_frame_time.set(Some(now));
let pending_next_frame_callbacks = next_frame_callbacks.take();
if !pending_next_frame_callbacks.is_empty() {
@@ -1935,14 +1958,10 @@ impl Window {
.log_err();
}
- // Keep presenting if input was recently arriving at a high rate (>= 60fps).
- // Once high-rate input is detected, we sustain presentation for 1 second
- // to prevent display underclocking during active input.
+ let should_draw = invalidator.is_dirty() || force_render;
let needs_present = request_frame_options.require_presentation
|| needs_present.get()
- || input_rate_tracker.borrow_mut().is_high_rate();
-
- let should_draw = invalidator.is_dirty() || force_render;
+ || high_rate_input;
if should_draw {
measure("frame duration", || {
handle
@@ -8131,7 +8150,7 @@ mod tests {
cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
let mut collector = journal.collector();
- for initially_dirty in [true, false] {
+ for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
// Keep the throttle closed without depending on short wall-clock deadlines.
let window = cx
.app
@@ -8157,13 +8176,15 @@ mod tests {
if initially_dirty {
window.refresh();
}
- window.on_next_frame({
- let callback_ran = callback_ran.clone();
- move |window, _| {
- callback_ran.set(true);
- window.refresh();
- }
- });
+ if schedule_callback {
+ window.on_next_frame({
+ let callback_ran = callback_ran.clone();
+ move |window, _| {
+ callback_ran.set(true);
+ window.refresh();
+ }
+ });
+ }
draws_before
})
.expect("schedule throttled frame");
@@ -8176,6 +8197,7 @@ mod tests {
caused_invalidation: false,
});
collector.collect_unseen();
+ let wakes_before = platform_window.frame_wake_count();
platform_window.simulate_frame_request(RequestFrameOptions {
signal_at: Some(Instant::now()),
..Default::default()
@@ -8192,6 +8214,8 @@ mod tests {
})
.expect("inspect deferred frame");
assert!(!callback_ran.get());
+ assert!(platform_window.frame_scheduled());
+ assert!(platform_window.frame_wake_count() > wakes_before);
assert!(collector.collect_unseen().entries.iter().any(|entry| {
matches!(
entry,
@@ -8216,7 +8240,7 @@ mod tests {
);
})
.expect("inspect presented frame");
- assert!(callback_ran.get());
+ assert_eq!(callback_ran.get(), schedule_callback);
}
}
@@ -8467,27 +8491,39 @@ mod tests {
}
#[test]
- fn frame_throttle_accepts_display_link_rounding() {
- assert!(!super::frame_request_arrived_too_early(
- Duration::from_micros(16_666),
- super::SIXTY_FPS_INTERVAL,
- ));
- assert!(!super::frame_request_arrived_too_early(
- Duration::from_micros(33_332),
- super::THIRTY_FPS_INTERVAL,
- ));
+ fn frame_throttle_tracks_display_refreshes() {
+ let start = super::Instant::now();
+ for (elapsed, interval) in [
+ (Duration::from_micros(16_666), super::SIXTY_FPS_INTERVAL),
+ (Duration::from_micros(33_332), super::THIRTY_FPS_INTERVAL),
+ ] {
+ let mut pacer = super::FramePacer::default();
+ assert!(!pacer.should_defer(start, Some(interval)));
+ assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
+ assert!(!pacer.should_defer(start + elapsed, Some(interval)));
+ }
}
#[test]
- fn frame_throttle_rejects_an_extra_display_refresh() {
- assert!(super::frame_request_arrived_too_early(
- Duration::from_micros(8_333),
- super::SIXTY_FPS_INTERVAL,
- ));
- assert!(super::frame_request_arrived_too_early(
- Duration::from_micros(16_666),
- super::THIRTY_FPS_INTERVAL,
- ));
+ fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
+ let start = super::Instant::now();
+ let interval = super::THIRTY_FPS_INTERVAL;
+ let mut pacer = super::FramePacer::default();
+ assert!(!pacer.should_defer(start, Some(interval)));
+ let delayed_frame = start + interval + Duration::from_millis(5);
+ assert!(!pacer.should_defer(delayed_frame, Some(interval)));
+ assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
+ assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
+
+ // Even a stall just short of another full interval must not cause a burst.
+ let after_stall = start + interval * 4 - Duration::from_millis(1);
+ assert!(!pacer.should_defer(after_stall, Some(interval)));
+ assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
+ assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
+ // Mandatory presentation bypasses the limit and establishes a fresh cadence.
+ let mandatory_frame = after_stall + interval + Duration::from_millis(2);
+ assert!(!pacer.should_defer(mandatory_frame, None));
+ assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
}
#[test]
@@ -8629,6 +8665,8 @@ mod tests {
fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let test_window = cx.test_window(window.into());
+ // This test exercises idle wakeups, not the inactive-window frame limit.
+ test_window.simulate_active_status_change(true);
// Windows start dirty, and that can predate waker installation;
// installing the waker must deliver the pending wake or the first