Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

22.6 KB
Raw Blame
diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
index 0294b7d..09adcdd 100644
--- a/crates/gpui/src/platform.rs
+++ b/crates/gpui/src/platform.rs
@@ -793,6 +793,18 @@ pub enum TextInputStateChange {
     ContentChanged,
 }
 
+/// What [`PlatformWindow::frame_request_toggle`] asks of the platform.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum FrameRequests {
+    /// Stop requesting frames.
+    Stop,
+    /// Request a frame every display refresh again.
+    Start,
+    /// Deliver one frame as soon as possible without restarting the
+    /// per-refresh requests.
+    Once,
+}
+
 #[expect(missing_docs)]
 pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
     #[cfg(all(target_os = "linux", feature = "wayland"))]
@@ -843,6 +855,12 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
     fn toggle_fullscreen(&self);
     fn is_fullscreen(&self) -> bool;
     fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
+    /// Returns a switch over the frame requests delivered to
+    /// [`Self::on_request_frame`]. Windows stop them while they have nothing to
+    /// draw. Platforms without one keep requesting frames.
+    fn frame_request_toggle(&self) -> Option<Box<dyn Fn(FrameRequests)>> {
+        None
+    }
     fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
     fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
     fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 393e517..bb20879 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -9,7 +9,8 @@ use crate::{
     Hsla, InputHandler, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke,
     KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite,
     MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,
-    PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
+    FrameRequests, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
+    PolychromeSprite,
     Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage,
     RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
     SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, BackdropBlur, ScaledPixels, Scene, Shadow, SharedString, Size,
@@ -120,6 +121,109 @@ struct WindowInvalidatorInner {
     pub dirty_views: FxHashSet<EntityId>,
     pub update_count: usize,
     pub frame_dirty: FrameDirtyAccumulator,
+    pub frame_pacer: Rc<FramePacer>,
+}
+
+/// Stops the platform's frame requests once a window has had nothing to draw
+/// for [`FramePacer::IDLE_DELAY`]. While stopped, an invalidation or a
+/// next-frame callback asks for a single frame, and the per-refresh requests
+/// only restart if work is still pending after it (an animation). Without this
+/// an idle window wakes the main thread on every display refresh, and a window
+/// that redraws a few times a second (a level meter, a clock) keeps the
+/// requests running between its redraws.
+pub(crate) struct FramePacer {
+    toggle: Option<Box<dyn Fn(FrameRequests)>>,
+    paused: Cell<bool>,
+    once_pending: Cell<bool>,
+    busy_at: Cell<Instant>,
+}
+
+impl FramePacer {
+    /// Long enough that steady low-rate redraws (30fps video, timers) never
+    /// stop and restart the frame source between frames.
+    const IDLE_DELAY: Duration = Duration::from_millis(100);
+
+    fn new(toggle: Option<Box<dyn Fn(FrameRequests)>>) -> Self {
+        FramePacer {
+            toggle,
+            paused: Cell::new(false),
+            once_pending: Cell::new(false),
+            busy_at: Cell::new(Instant::now()),
+        }
+    }
+
+    fn wake(&self) {
+        if let Some(toggle) = &self.toggle
+            && self.paused.get()
+            && !self.once_pending.replace(true)
+        {
+            toggle(FrameRequests::Once);
+        }
+    }
+
+    /// A frame request that arrived while the app was mid-update and could not
+    /// run. While requests are stopped nothing else would draw what woke the
+    /// window, so ask for another single frame.
+    fn missed_frame(&self) {
+        if let Some(toggle) = &self.toggle
+            && self.paused.get()
+        {
+            self.once_pending.set(true);
+            toggle(FrameRequests::Once);
+        }
+    }
+
+    /// `busy`: the frame did work. `pending`: work is left for the next frame.
+    fn frame_finished(&self, busy: bool, pending: bool, now: Instant) {
+        let Some(toggle) = &self.toggle else {
+            return;
+        };
+        if self.paused.get() {
+            self.once_pending.set(false);
+            if pending {
+                self.paused.set(false);
+                self.busy_at.set(now);
+                toggle(FrameRequests::Start);
+            } else {
+                // Also stops a link the platform restarted on its own (a window
+                // shown again while it had nothing to draw).
+                toggle(FrameRequests::Stop);
+            }
+        } else if busy || pending {
+            self.busy_at.set(now);
+        } else if now.duration_since(self.busy_at.get()) >= Self::IDLE_DELAY {
+            self.paused.set(true);
+            toggle(FrameRequests::Stop);
+        }
+    }
+}
+
+/// Applies a platform notification to the window now, or on the next turn of
+/// the run loop when it arrived while the app was already being updated. AppKit
+/// delivers moves, resizes and appearance changes synchronously from inside the
+/// `setFrame:`/`orderFront:` calls an update makes (opening or positioning a
+/// window), and dropping them leaves the window's bounds or appearance stale.
+fn update_window_or_defer(
+    handle: AnyWindowHandle,
+    cx: &mut crate::AsyncApp,
+    update: fn(&mut Window, &mut App),
+) {
+    let Err(error) = handle.update(cx, |_, window, cx| update(window, cx)) else {
+        return;
+    };
+    if !error.is::<std::cell::BorrowMutError>() {
+        Result::<(), _>::Err(error).log_err();
+        return;
+    }
+    let executor = cx.foreground_executor().clone();
+    let mut cx = cx.clone();
+    executor
+        .spawn(async move {
+            handle
+                .update(&mut cx, |_, window, cx| update(window, cx))
+                .log_err();
+        })
+        .detach();
 }
 
 /// Per-frame invalidation bookkeeping, drained at draw time and emitted to the
@@ -138,7 +242,7 @@ pub(crate) struct WindowInvalidator {
 }
 
 impl WindowInvalidator {
-    pub fn new() -> Self {
+    pub fn new(frame_pacer: Rc<FramePacer>) -> Self {
         WindowInvalidator {
             inner: Rc::new(RefCell::new(WindowInvalidatorInner {
                 dirty: true,
@@ -146,6 +250,7 @@ impl WindowInvalidator {
                 dirty_views: FxHashSet::default(),
                 update_count: 0,
                 frame_dirty: FrameDirtyAccumulator::default(),
+                frame_pacer,
             })),
         }
     }
@@ -157,6 +262,9 @@ impl WindowInvalidator {
         if inner.draw_phase == DrawPhase::None {
             Self::record_frame_dirty(&mut inner);
             inner.dirty = true;
+            let frame_pacer = inner.frame_pacer.clone();
+            drop(inner);
+            frame_pacer.wake();
             cx.push_effect(Effect::Notify { emitter: entity });
             true
         } else {
@@ -174,6 +282,9 @@ impl WindowInvalidator {
         if dirty {
             inner.update_count += 1;
             Self::record_frame_dirty(&mut inner);
+            let frame_pacer = inner.frame_pacer.clone();
+            drop(inner);
+            frame_pacer.wake();
         }
     }
 
@@ -1390,7 +1501,8 @@ impl Window {
         let scale_factor = platform_window.scale_factor();
         let appearance = platform_window.appearance();
         let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
-        let invalidator = WindowInvalidator::new();
+        let frame_pacer = Rc::new(FramePacer::new(platform_window.frame_request_toggle()));
+        let invalidator = WindowInvalidator::new(frame_pacer.clone());
         let active = Rc::new(Cell::new(platform_window.is_active()));
         let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
         let needs_present = Rc::new(Cell::new(false));
@@ -1507,12 +1619,24 @@ impl Window {
             let invalidator = invalidator.clone();
             let active = active.clone();
             let needs_present = needs_present.clone();
-            let next_frame_callbacks = next_frame_callbacks.clone();
+            let pending_frame_callbacks = next_frame_callbacks.clone();
             let input_rate_tracker = input_rate_tracker.clone();
             move |request_frame_options| {
-                let thermal_state = handle
-                    .update(&mut cx, |_, _, cx| cx.thermal_state())
-                    .log_err();
+                let next_frame_callbacks = &pending_frame_callbacks;
+                let thermal = handle.update(&mut cx, |_, _, cx| cx.thermal_state());
+                let thermal_state = match thermal {
+                    Ok(thermal_state) => Some(thermal_state),
+                    // AppKit can ask for a frame from inside an update
+                    // (`displayLayer:` while a window is shown); draw it once
+                    // the update returns.
+                    Err(error) if error.is::<std::cell::BorrowMutError>() => {
+                        frame_pacer.missed_frame();
+                        return;
+                    }
+                    // A frame can still arrive for a window that was just closed
+                    // (its display link or a pending wake); there is nothing to draw.
+                    Err(_) => return,
+                };
 
                 // Throttle frame rate based on conditions:
                 // - Thermal pressure (Serious/Critical): cap to ~60fps
@@ -1546,13 +1670,17 @@ impl Window {
                         handle
                             .update(&mut cx, |_, window, _| window.complete_frame())
                             .log_err();
+                        frame_pacer.frame_finished(true, true, now);
                         return;
                     }
                 }
                 last_frame_time.set(Some(now));
 
+                let mut busy = request_frame_options.force_render
+                    || request_frame_options.require_presentation;
                 let next_frame_callbacks = next_frame_callbacks.take();
                 if !next_frame_callbacks.is_empty() {
+                    busy = true;
                     handle
                         .update(&mut cx, |_, window, cx| {
                             for callback in next_frame_callbacks {
@@ -1570,6 +1698,7 @@ impl Window {
                     || (active.get() && input_rate_tracker.borrow_mut().is_high_rate());
 
                 if invalidator.is_dirty() || request_frame_options.force_render {
+                    busy = true;
                     measure("frame duration", || {
                         handle
                             .update(&mut cx, |_, window, cx| {
@@ -1585,6 +1714,7 @@ impl Window {
                             .log_err();
                     })
                 } else if needs_present {
+                    busy = true;
                     handle
                         .update(&mut cx, |_, window, _| window.present())
                         .log_err();
@@ -1595,38 +1725,41 @@ impl Window {
                         window.complete_frame();
                     })
                     .log_err();
+
+                let pending = invalidator.is_dirty() || !pending_frame_callbacks.borrow().is_empty();
+                frame_pacer.frame_finished(busy, pending, now);
             }
         }));
         platform_window.on_resize(Box::new({
             let mut cx = cx.to_async();
             move |_, _| {
-                handle
-                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
-                    .log_err();
+                update_window_or_defer(handle, &mut cx, |window, cx| {
+                    window.bounds_changed(cx)
+                });
             }
         }));
         platform_window.on_moved(Box::new({
             let mut cx = cx.to_async();
             move || {
-                handle
-                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
-                    .log_err();
+                update_window_or_defer(handle, &mut cx, |window, cx| {
+                    window.bounds_changed(cx)
+                });
             }
         }));
         platform_window.on_appearance_changed(Box::new({
             let mut cx = cx.to_async();
             move || {
-                handle
-                    .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
-                    .log_err();
+                update_window_or_defer(handle, &mut cx, |window, cx| {
+                    window.appearance_changed(cx)
+                });
             }
         }));
         platform_window.on_button_layout_changed(Box::new({
             let mut cx = cx.to_async();
             move || {
-                handle
-                    .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
-                    .log_err();
+                update_window_or_defer(handle, &mut cx, |window, cx| {
+                    window.button_layout_changed(cx)
+                });
             }
         }));
         platform_window.on_active_status_change(Box::new({
@@ -2263,6 +2396,8 @@ impl Window {
     /// Schedule the given closure to be run directly after the current frame is rendered.
     pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
         RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
+        let frame_pacer = self.invalidator.inner.borrow().frame_pacer.clone();
+        frame_pacer.wake();
     }
 
     /// Schedule a frame to be drawn on the next animation frame.
@@ -6807,6 +6942,114 @@ pub fn outline(
     }
 }
 
+#[cfg(test)]
+mod frame_pacer_tests {
+    use super::{FramePacer, FrameRequests, Instant};
+    use std::{cell::RefCell, rc::Rc, time::Duration};
+
+    fn recording_pacer() -> (FramePacer, Rc<RefCell<Vec<FrameRequests>>>, Instant) {
+        let calls = Rc::new(RefCell::new(Vec::new()));
+        let recorded = calls.clone();
+        let pacer = FramePacer::new(Some(Box::new(move |request| {
+            recorded.borrow_mut().push(request)
+        })));
+        let created = pacer.busy_at.get();
+        (pacer, calls, created)
+    }
+
+    fn stopped_pacer() -> (FramePacer, Rc<RefCell<Vec<FrameRequests>>>, Instant) {
+        let (pacer, calls, start) = recording_pacer();
+        pacer.frame_finished(false, false, start + FramePacer::IDLE_DELAY);
+        calls.borrow_mut().clear();
+        (pacer, calls, start + FramePacer::IDLE_DELAY)
+    }
+
+    #[test]
+    fn idle_frames_stop_requests_only_after_the_delay() {
+        let (pacer, calls, start) = recording_pacer();
+        pacer.frame_finished(false, false, start + Duration::from_millis(99));
+        assert!(calls.borrow().is_empty());
+        pacer.frame_finished(false, false, start + FramePacer::IDLE_DELAY);
+        assert_eq!(*calls.borrow(), [FrameRequests::Stop]);
+    }
+
+    #[test]
+    fn busy_or_pending_frames_restart_the_delay() {
+        let (pacer, calls, start) = recording_pacer();
+        pacer.frame_finished(true, false, start + Duration::from_millis(90));
+        pacer.frame_finished(false, true, start + Duration::from_millis(150));
+        pacer.frame_finished(false, false, start + Duration::from_millis(240));
+        assert!(calls.borrow().is_empty());
+        pacer.frame_finished(false, false, start + Duration::from_millis(250));
+        assert_eq!(*calls.borrow(), [FrameRequests::Stop]);
+    }
+
+    #[test]
+    fn a_stopped_window_asks_for_one_frame_per_wake() {
+        let (pacer, calls, now) = stopped_pacer();
+        pacer.wake();
+        pacer.wake();
+        assert_eq!(*calls.borrow(), [FrameRequests::Once]);
+        // The single frame drew everything: requests stay stopped.
+        pacer.frame_finished(true, false, now + Duration::from_millis(50));
+        pacer.wake();
+        assert_eq!(
+            *calls.borrow(),
+            [FrameRequests::Once, FrameRequests::Stop, FrameRequests::Once]
+        );
+    }
+
+    #[test]
+    fn work_left_after_a_single_frame_restarts_requests() {
+        let (pacer, calls, now) = stopped_pacer();
+        pacer.wake();
+        pacer.frame_finished(true, true, now + Duration::from_millis(5));
+        assert_eq!(*calls.borrow(), [FrameRequests::Once, FrameRequests::Start]);
+        // Running again: wakes ask for nothing, and the idle delay applies anew.
+        pacer.wake();
+        pacer.frame_finished(false, false, now + Duration::from_millis(50));
+        assert_eq!(*calls.borrow(), [FrameRequests::Once, FrameRequests::Start]);
+        pacer.frame_finished(false, false, now + Duration::from_millis(105));
+        assert_eq!(
+            *calls.borrow(),
+            [FrameRequests::Once, FrameRequests::Start, FrameRequests::Stop]
+        );
+    }
+
+    #[test]
+    fn a_frame_from_a_link_the_platform_restarted_stops_it_again() {
+        let (pacer, calls, now) = stopped_pacer();
+        pacer.frame_finished(false, false, now + Duration::from_millis(8));
+        assert_eq!(*calls.borrow(), [FrameRequests::Stop]);
+    }
+
+    #[test]
+    fn a_frame_missed_while_stopped_asks_for_another() {
+        let (pacer, calls, _) = stopped_pacer();
+        pacer.missed_frame();
+        assert_eq!(*calls.borrow(), [FrameRequests::Once]);
+        pacer.wake();
+        assert_eq!(*calls.borrow(), [FrameRequests::Once]);
+    }
+
+    #[test]
+    fn a_frame_missed_while_running_asks_for_nothing() {
+        let (pacer, calls, _) = recording_pacer();
+        pacer.missed_frame();
+        assert!(calls.borrow().is_empty());
+    }
+
+    #[test]
+    fn without_a_platform_toggle_nothing_is_tracked() {
+        let pacer = FramePacer::new(None);
+        let start = pacer.busy_at.get();
+        pacer.frame_finished(false, false, start + FramePacer::IDLE_DELAY);
+        assert!(!pacer.paused.get());
+        pacer.wake();
+        assert!(!pacer.once_pending.get());
+    }
+}
+
 #[cfg(test)]
 mod tests {
     use crate::{
diff --git a/crates/gpui_macos/src/window.rs b/crates/gpui_macos/src/window.rs
index f5b2c1a..96f7826 100644
--- a/crates/gpui_macos/src/window.rs
+++ b/crates/gpui_macos/src/window.rs
@@ -24,7 +24,7 @@ use cocoa::{
 };
 use dispatch2::DispatchQueue;
 use gpui::{
-    AnyWindowHandle, BackgroundExecutor, Bounds, Capslock, CursorStyle, ExternalPaths,
+    AnyWindowHandle, BackgroundExecutor, Bounds, Capslock, CursorStyle, ExternalPaths, FrameRequests,
     FileDropEvent, ForegroundExecutor, KeyDownEvent, Keystroke, Modifiers, ModifiersChangedEvent,
     MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, PlatformAtlas,
     PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PromptButton,
@@ -499,6 +499,7 @@ struct MacWindowState {
     frame_source: Option<WindowFrameSource>,
     renderer: renderer::Renderer,
     request_frame_callback: Option<Box<dyn FnMut(RequestFrameOptions)>>,
+    frame_requests_paused: bool,
     event_callback: Option<Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>>,
     activate_callback: Option<Box<dyn FnMut(bool)>>,
     resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
@@ -657,6 +658,9 @@ impl MacWindowState {
 
     fn start_display_link(&mut self) {
         self.stop_display_link();
+        if self.frame_requests_paused {
+            return;
+        }
         unsafe {
             if !self
                 .native_window
@@ -896,6 +900,7 @@ impl MacWindow {
                 frame_source: None,
                 renderer,
                 request_frame_callback: None,
+                frame_requests_paused: false,
                 event_callback: None,
                 activate_callback: None,
                 resize_callback: None,
@@ -1670,6 +1675,57 @@ impl PlatformWindow for MacWindow {
         self.0.as_ref().lock().request_frame_callback = Some(callback);
     }
 
+    fn frame_request_toggle(&self) -> Option<Box<dyn Fn(FrameRequests)>> {
+        let window_state = Arc::downgrade(&self.0);
+        Some(Box::new(move |request| {
+            let Some(window_state) = window_state.upgrade() else {
+                return;
+            };
+            let mut lock = window_state.lock();
+            match request {
+                FrameRequests::Stop => {
+                    lock.frame_requests_paused = true;
+                    lock.stop_display_link();
+                }
+                FrameRequests::Start => {
+                    lock.frame_requests_paused = false;
+                    lock.start_display_link();
+                }
+                FrameRequests::Once => {
+                    let visible = unsafe {
+                        lock.native_window
+                            .occlusionState()
+                            .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
+                    };
+                    if !visible {
+                        // A hidden window draws nothing now; let the occlusion
+                        // handler start its link when it is shown, and the
+                        // first frame after that draws what changed meanwhile.
+                        lock.frame_requests_paused = false;
+                        return;
+                    }
+                    // Draw the frame that woke the window now: a restarted
+                    // display link first fires a refresh or two later.
+                    let window_state = Arc::downgrade(&window_state);
+                    lock.foreground_executor
+                        .spawn(async move {
+                            let Some(window_state) = window_state.upgrade() else {
+                                return;
+                            };
+                            let Some(mut callback) =
+                                window_state.lock().request_frame_callback.take()
+                            else {
+                                return;
+                            };
+                            callback(Default::default());
+                            window_state.lock().request_frame_callback = Some(callback);
+                        })
+                        .detach();
+                }
+            }
+        }))
+    }
+
     fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>) {
         self.0.as_ref().lock().event_callback = Some(callback);
     }