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 web dont repaint (#62327)

Cameron Mcloughlin417d03305ac1
diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
index 5523b9c0e0f..805ed375ce2 100644
--- a/crates/gpui/src/platform.rs
+++ b/crates/gpui/src/platform.rs
@@ -834,6 +834,9 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
fn zoom(&self);
fn toggle_fullscreen(&self);
fn is_fullscreen(&self) -> bool;
+ fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
+ None
+ }
fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
diff --git a/crates/gpui/src/platform/test/window.rs b/crates/gpui/src/platform/test/window.rs
index 8ab9147b36a..dc96e43dfee 100644
--- a/crates/gpui/src/platform/test/window.rs
+++ b/crates/gpui/src/platform/test/window.rs
@@ -11,6 +11,7 @@ use image::RgbaImage;
use parking_lot::Mutex;
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
use std::{
+ cell::Cell,
path::PathBuf,
rc::{Rc, Weak},
sync::{self, Arc},
@@ -35,6 +36,8 @@ pub(crate) struct TestWindowState {
resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
moved_callback: Option<Box<dyn FnMut()>>,
appearance_change_callback: Option<Box<dyn FnMut()>>,
+ request_frame_callback: Option<Box<dyn FnMut(RequestFrameOptions)>>,
+ frame_wake_count: Rc<Cell<usize>>,
input_handler: Option<PlatformInputHandler>,
is_fullscreen: bool,
appearance: WindowAppearance,
@@ -91,6 +94,8 @@ impl TestWindow {
resize_callback: None,
moved_callback: None,
appearance_change_callback: None,
+ request_frame_callback: None,
+ frame_wake_count: Rc::new(Cell::new(0)),
input_handler: None,
is_fullscreen: false,
appearance: WindowAppearance::Light,
@@ -133,6 +138,23 @@ impl TestWindow {
self.0.lock().appearance_change_callback = Some(callback);
}
+ /// Returns how many times this window's frame waker has been invoked.
+ pub fn frame_wake_count(&self) -> usize {
+ self.0.lock().frame_wake_count.get()
+ }
+
+ /// Delivers a frame request to the window, as the platform's frame source
+ /// would.
+ pub fn simulate_frame_request(&self, options: RequestFrameOptions) {
+ let mut lock = self.0.lock();
+ let Some(mut callback) = lock.request_frame_callback.take() else {
+ return;
+ };
+ drop(lock);
+ callback(options);
+ self.0.lock().request_frame_callback = Some(callback);
+ }
+
pub fn simulate_input(&mut self, event: PlatformInput) -> bool {
let mut lock = self.0.lock();
let Some(mut callback) = lock.input_callback.take() else {
@@ -286,7 +308,19 @@ impl PlatformWindow for TestWindow {
self.0.lock().is_fullscreen
}
- fn on_request_frame(&self, _callback: Box<dyn FnMut(RequestFrameOptions)>) {}
+ fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
+ // Recording invocations (rather than delivering a frame) lets tests
+ // assert the wake protocol without coupling to frame timing; tests
+ // deliver frames explicitly via `simulate_frame_request`.
+ let frame_wake_count = self.0.lock().frame_wake_count.clone();
+ Some(Rc::new(move || {
+ frame_wake_count.set(frame_wake_count.get() + 1);
+ }))
+ }
+
+ fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
+ self.0.lock().request_frame_callback = Some(callback);
+ }
fn on_input(&self, callback: Box<dyn FnMut(crate::PlatformInput) -> DispatchEventResult>) {
self.0.lock().input_callback = Some(callback)
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index cceadc8e2c8..3b766526462 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -120,6 +120,7 @@ struct WindowInvalidatorInner {
pub dirty_views: FxHashSet<EntityId>,
pub update_count: usize,
pub frame_dirty: FrameDirtyAccumulator,
+ pub platform_waker: Option<Rc<dyn Fn()>>,
}
/// Per-frame invalidation bookkeeping, drained at draw time and emitted to the
@@ -146,6 +147,7 @@ impl WindowInvalidator {
dirty_views: FxHashSet::default(),
update_count: 0,
frame_dirty: FrameDirtyAccumulator::default(),
+ platform_waker: None,
})),
}
}
@@ -156,8 +158,14 @@ impl WindowInvalidator {
inner.dirty_views.insert(entity);
if inner.draw_phase == DrawPhase::None {
Self::record_frame_dirty(&mut inner);
+ let became_dirty = !inner.dirty;
inner.dirty = true;
+ let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
+ drop(inner);
cx.push_effect(Effect::Notify { emitter: entity });
+ if let Some(waker) = waker {
+ waker();
+ }
true
} else {
false
@@ -170,11 +178,37 @@ impl WindowInvalidator {
pub fn set_dirty(&self, dirty: bool) {
let mut inner = self.inner.borrow_mut();
+ let became_dirty = dirty && !inner.dirty;
inner.dirty = dirty;
if dirty {
inner.update_count += 1;
Self::record_frame_dirty(&mut inner);
}
+ let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
+ drop(inner);
+ if let Some(waker) = waker {
+ waker();
+ }
+ }
+
+ pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
+ let mut inner = self.inner.borrow_mut();
+ inner.platform_waker = waker;
+ let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
+ drop(inner);
+ if let Some(waker) = waker {
+ waker();
+ }
+ }
+
+ /// Wakes the platform's frame-request source so a frame request is
+ /// delivered even if the platform stops requesting frames for idle
+ /// windows. No-op on platforms without a frame waker.
+ pub fn wake_platform(&self) {
+ let waker = self.inner.borrow().platform_waker.clone();
+ if let Some(waker) = waker {
+ waker();
+ }
}
pub fn set_phase(&self, phase: DrawPhase) {
@@ -1619,16 +1653,21 @@ impl Window {
handle
.update(&mut cx, |_, window, _| window.complete_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();
return;
}
}
last_frame_time.set(Some(now));
- let next_frame_callbacks = next_frame_callbacks.take();
- if !next_frame_callbacks.is_empty() {
+ let pending_next_frame_callbacks = next_frame_callbacks.take();
+ if !pending_next_frame_callbacks.is_empty() {
handle
.update(&mut cx, |_, window, cx| {
- for callback in next_frame_callbacks {
+ for callback in pending_next_frame_callbacks {
callback(window, cx);
}
})
@@ -1668,8 +1707,18 @@ impl Window {
window.complete_frame();
})
.log_err();
+
+ // Platforms that stop requesting frames for idle windows only
+ // deliver another request after a wakeup. If demand remains
+ // after this frame (the window was re-invalidated mid-draw, or
+ // animations scheduled next-frame callbacks), re-arm the frame
+ // source explicitly.
+ if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() {
+ invalidator.wake_platform();
+ }
}
}));
+ invalidator.set_platform_waker(platform_window.frame_waker());
platform_window.on_resize(Box::new({
let mut cx = cx.to_async();
move |_, _| {
@@ -2340,6 +2389,9 @@ 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));
+ // Next-frame callbacks create frame demand without dirtying the
+ // window, so the platform's frame source must be woken explicitly.
+ self.invalidator.wake_platform();
}
/// Schedule a frame to be drawn on the next animation frame.
@@ -6790,9 +6842,9 @@ mod tests {
AnyWindowHandle, AppContext as _, Bounds, Context, DragMoveEvent, Empty,
ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle,
InputEvent as _, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
- MouseMoveEvent, ParentElement, Pixels, Point, Render, StatefulInteractiveElement as _,
- Styled, TestAppContext, Window, WindowAppearance, WindowOptions, canvas, div, point, px,
- size,
+ MouseMoveEvent, ParentElement, Pixels, Point, Render, RequestFrameOptions,
+ StatefulInteractiveElement as _, Styled, TestAppContext, Window, WindowAppearance,
+ WindowOptions, canvas, div, point, px, size,
};
struct EmptyView;
@@ -6853,6 +6905,100 @@ mod tests {
.unwrap();
}
+ /// Platforms that stop requesting frames for idle windows (currently web)
+ /// rely on the frame waker firing whenever frame demand arises; a demand
+ /// source that skips the waker shows up there as a window that silently
+ /// stops repainting until unrelated activity wakes it.
+ #[gpui::test]
+ 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());
+
+ // Windows start dirty, and that can predate waker installation;
+ // installing the waker must deliver the pending wake or the first
+ // frame would never be requested.
+ assert!(
+ test_window.frame_wake_count() >= 1,
+ "opening a window must wake the frame source for the initial frame"
+ );
+
+ // Serve outstanding demand (present the frame drawn by `add_window`).
+ test_window.simulate_frame_request(RequestFrameOptions::default());
+
+ // An idle window must not wake on clean frames or plain updates, or
+ // the frame source could never stop.
+ let baseline = test_window.frame_wake_count();
+ test_window.simulate_frame_request(RequestFrameOptions::default());
+ window.update(cx, |_, _, _| {}).unwrap();
+ assert_eq!(
+ test_window.frame_wake_count(),
+ baseline,
+ "clean frames and non-notifying updates must not wake the frame source"
+ );
+
+ // Notifying a view in an idle window is the core demand signal.
+ window.update(cx, |_, _, cx| cx.notify()).unwrap();
+ assert!(
+ test_window.frame_wake_count() > baseline,
+ "notifying a view in an idle window must wake the frame source"
+ );
+
+ // Serving that demand returns to idle without further wakes.
+ test_window.simulate_frame_request(RequestFrameOptions::default());
+ let baseline = test_window.frame_wake_count();
+ test_window.simulate_frame_request(RequestFrameOptions::default());
+ assert_eq!(
+ test_window.frame_wake_count(),
+ baseline,
+ "serving demand must return the window to idle"
+ );
+
+ // Next-frame callbacks create demand without dirtying the window.
+ window
+ .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
+ .unwrap();
+ assert!(
+ test_window.frame_wake_count() > baseline,
+ "scheduling a next-frame callback in an idle window must wake the frame source"
+ );
+ }
+
+ /// A frame request that arrives while next-frame callbacks are pending
+ /// must never strand them: either the frame runs them, or (when the
+ /// inactive-window frame-rate throttle defers the frame) the waker fires
+ /// so another request is delivered.
+ #[gpui::test]
+ fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
+ let window = cx.add_window(|_, _| EmptyView);
+ let test_window = cx.test_window(window.into());
+ // Establish a recent last-frame time so the inactive-window throttle
+ // can engage on the next request.
+ test_window.simulate_frame_request(RequestFrameOptions::default());
+
+ let callback_ran = Rc::new(Cell::new(false));
+ window
+ .update(cx, {
+ let callback_ran = callback_ran.clone();
+ move |_, window, _| {
+ window.on_next_frame(move |_, _| callback_ran.set(true));
+ }
+ })
+ .unwrap();
+
+ let baseline = test_window.frame_wake_count();
+ test_window.simulate_frame_request(RequestFrameOptions::default());
+ // The test window is inactive, so this request throttles to ~30fps
+ // when it lands within the throttle interval of the previous frame
+ // (the common case here, but timing-dependent): the callback is
+ // deferred and the waker must re-arm the frame source. On a slow run
+ // the request instead lands outside the interval and runs the
+ // callback directly.
+ assert!(
+ test_window.frame_wake_count() > baseline || callback_ran.get(),
+ "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
+ );
+ }
+
#[gpui::test]
fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
diff --git a/crates/gpui_web/src/window.rs b/crates/gpui_web/src/window.rs
index 484014681b7..6261b954d3f 100644
--- a/crates/gpui_web/src/window.rs
+++ b/crates/gpui_web/src/window.rs
@@ -59,6 +59,7 @@ pub(crate) struct WebWindowInner {
mql_handle: RefCell<Option<MqlHandle>>,
pending_physical_size: Cell<Option<(u32, u32)>>,
raf_id: Cell<Option<i32>>,
+ raf_function: RefCell<Option<js_sys::Function>>,
}
pub struct WebWindow {
@@ -193,10 +194,11 @@ impl WebWindow {
mql_handle: RefCell::new(None),
pending_physical_size: Cell::new(None),
raf_id: Cell::new(None),
+ raf_function: RefCell::new(None),
});
let raf_closure = inner.create_raf_closure();
- inner.schedule_raf(&raf_closure);
+ inner.wake_frame_loop();
let resize_observer_closure = Self::create_resize_observer_closure(Rc::clone(&inner));
let resize_observer =
@@ -344,41 +346,40 @@ impl WebWindowInner {
}
fn create_raf_closure(self: &Rc<Self>) -> Closure<dyn FnMut()> {
- let raf_handle: Rc<RefCell<Option<js_sys::Function>>> = Rc::new(RefCell::new(None));
- let raf_handle_inner = Rc::clone(&raf_handle);
-
let this = Rc::clone(self);
let closure = Closure::new(move || {
+ // The request that fired is no longer pending; clear it before
+ // running the frame so wakeups issued while the frame executes
+ // (e.g. views invalidated during draw) schedule the next request
+ // instead of being swallowed.
+ this.raf_id.set(None);
this.with_callback(
|callbacks| &mut callbacks.request_frame,
|callback| {
callback(RequestFrameOptions {
- require_presentation: true,
+ require_presentation: false,
force_render: false,
})
},
);
-
- // Re-schedule for the next frame
- if let Some(ref func) = *raf_handle_inner.borrow() {
- this.raf_id
- .set(this.browser_window.request_animation_frame(func).ok());
- }
});
let js_func: js_sys::Function =
closure.as_ref().unchecked_ref::<js_sys::Function>().clone();
- *raf_handle.borrow_mut() = Some(js_func);
+ *self.raf_function.borrow_mut() = Some(js_func);
closure
}
- fn schedule_raf(&self, closure: &Closure<dyn FnMut()>) {
- self.raf_id.set(
- self.browser_window
- .request_animation_frame(closure.as_ref().unchecked_ref())
- .ok(),
- );
+ pub(crate) fn wake_frame_loop(&self) {
+ if self.raf_id.get().is_some() {
+ return;
+ }
+ let raf_function = self.raf_function.borrow();
+ if let Some(func) = raf_function.as_ref() {
+ self.raf_id
+ .set(self.browser_window.request_animation_frame(func).ok());
+ }
}
fn observe_canvas(&self, observer: &web_sys::ResizeObserver) {
@@ -513,6 +514,9 @@ impl Drop for WebWindow {
.cancel_animation_frame(raf_id)
.ok();
}
+ // A frame waker that outlives this window must not re-schedule the
+ // freed closure; without a stored function, `wake_frame_loop` no-ops.
+ self.inner.raf_function.borrow_mut().take();
if let Some(ref observer) = self._resize_observer {
observer.disconnect();
}
@@ -715,6 +719,19 @@ impl PlatformWindow for WebWindow {
self.inner.state.borrow().is_fullscreen
}
+ fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
+ // Hold the inner window weakly: the waker is stored in the window's
+ // invalidator, and `callbacks.request_frame` captures a clone of that
+ // invalidator, so a strong reference here would form a cycle and leak
+ // the window on close.
+ let inner = Rc::downgrade(&self.inner);
+ Some(Rc::new(move || {
+ if let Some(inner) = inner.upgrade() {
+ inner.wake_frame_loop();
+ }
+ }))
+ }
+
fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
self.inner.callbacks.borrow_mut().request_frame = Some(callback);
}