Reintroduce ProMotion support (#7347)

Antonio Scandurra and Nathan created

This re-introduces the changes of #7305 but this time we create a
display link using the `NSScreen` associated with the window. We're
hoping we'll get these frame requests more reliably, and this seems
supported by the fact that awakening my laptop restores the frame
requests.

Release Notes:

- See #7305.

Co-authored-by: Nathan <nathan@zed.dev>
# Conflicts:
#	crates/gpui/src/window.rs

Change summary

crates/gpui/src/app.rs                  | 13 +----
crates/gpui/src/platform.rs             |  1 
crates/gpui/src/platform/mac/window.rs  | 66 +++++++++++++++++++++-----
crates/gpui/src/platform/test/window.rs |  2 
crates/gpui/src/window.rs               | 48 ++++++++++++++-----
5 files changed, 91 insertions(+), 39 deletions(-)

Detailed changes

crates/gpui/src/app.rs 🔗

@@ -652,27 +652,20 @@ impl AppContext {
                     }
                 }
             } else {
-                for window in self.windows.values() {
-                    if let Some(window) = window.as_ref() {
-                        if window.dirty {
-                            window.platform_window.invalidate();
-                        }
-                    }
-                }
-
                 #[cfg(any(test, feature = "test-support"))]
                 for window in self
                     .windows
                     .values()
                     .filter_map(|window| {
                         let window = window.as_ref()?;
-                        window.dirty.then_some(window.handle)
+                        window.dirty.get().then_some(window.handle)
                     })
                     .collect::<Vec<_>>()
                 {
                     self.update_window(window, |_, cx| cx.draw()).unwrap();
                 }
 
+                #[allow(clippy::collapsible_else_if)]
                 if self.pending_effects.is_empty() {
                     break;
                 }
@@ -749,7 +742,7 @@ impl AppContext {
     fn apply_refresh_effect(&mut self) {
         for window in self.windows.values_mut() {
             if let Some(window) = window.as_mut() {
-                window.dirty = true;
+                window.dirty.set(true);
             }
         }
     }

crates/gpui/src/platform.rs 🔗

@@ -175,7 +175,6 @@ pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
     fn on_close(&self, callback: Box<dyn FnOnce()>);
     fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
     fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool;
-    fn invalidate(&self);
     fn draw(&self, scene: &Scene);
 
     fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;

crates/gpui/src/platform/mac/window.rs 🔗

@@ -16,8 +16,8 @@ use cocoa::{
     },
     base::{id, nil},
     foundation::{
-        NSArray, NSAutoreleasePool, NSDictionary, NSFastEnumeration, NSInteger, NSPoint, NSRect,
-        NSSize, NSString, NSUInteger,
+        NSArray, NSAutoreleasePool, NSDefaultRunLoopMode, NSDictionary, NSFastEnumeration,
+        NSInteger, NSPoint, NSRect, NSSize, NSString, NSUInteger,
     },
 };
 use core_graphics::display::CGRect;
@@ -168,6 +168,7 @@ unsafe fn build_classes() {
             sel!(displayLayer:),
             display_layer as extern "C" fn(&Object, Sel, id),
         );
+        decl.add_method(sel!(step:), step as extern "C" fn(&Object, Sel, id));
 
         decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
         decl.add_method(
@@ -260,6 +261,10 @@ unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const C
         sel!(windowDidMove:),
         window_did_move as extern "C" fn(&Object, Sel, id),
     );
+    decl.add_method(
+        sel!(windowDidChangeScreen:),
+        window_did_change_screen as extern "C" fn(&Object, Sel, id),
+    );
     decl.add_method(
         sel!(windowDidBecomeKey:),
         window_did_change_key_status as extern "C" fn(&Object, Sel, id),
@@ -320,7 +325,8 @@ struct MacWindowState {
     handle: AnyWindowHandle,
     executor: ForegroundExecutor,
     native_window: id,
-    native_view: NonNull<id>,
+    native_view: NonNull<Object>,
+    display_link: id,
     renderer: MetalRenderer,
     kind: WindowKind,
     request_frame_callback: Option<Box<dyn FnMut()>>,
@@ -522,14 +528,16 @@ impl MacWindow {
 
             let native_view: id = msg_send![VIEW_CLASS, alloc];
             let native_view = NSView::init(native_view);
-
             assert!(!native_view.is_null());
 
+            let display_link = start_display_link(native_window, native_view);
+
             let window = Self(Arc::new(Mutex::new(MacWindowState {
                 handle,
                 executor,
                 native_window,
-                native_view: NonNull::new_unchecked(native_view as *mut _),
+                native_view: NonNull::new_unchecked(native_view),
+                display_link,
                 renderer: MetalRenderer::new(instance_buffer_pool),
                 kind: options.kind,
                 request_frame_callback: None,
@@ -664,6 +672,7 @@ impl MacWindow {
             }
 
             window.0.lock().move_traffic_light();
+
             pool.drain();
 
             window
@@ -684,10 +693,19 @@ impl MacWindow {
     }
 }
 
+unsafe fn start_display_link(native_screen: id, native_view: id) -> id {
+    let display_link: id =
+        msg_send![native_screen, displayLinkWithTarget: native_view selector: sel!(step:)];
+    let main_run_loop: id = msg_send![class!(NSRunLoop), mainRunLoop];
+    let _: () = msg_send![display_link, addToRunLoop: main_run_loop forMode: NSDefaultRunLoopMode];
+    display_link
+}
+
 impl Drop for MacWindow {
     fn drop(&mut self) {
-        let this = self.0.lock();
+        let mut this = self.0.lock();
         let window = this.native_window;
+        this.display_link = nil;
         this.executor
             .spawn(async move {
                 unsafe {
@@ -1001,13 +1019,6 @@ impl PlatformWindow for MacWindow {
         }
     }
 
-    fn invalidate(&self) {
-        let this = self.0.lock();
-        unsafe {
-            let _: () = msg_send![this.native_window.contentView(), setNeedsDisplay: YES];
-        }
-    }
-
     fn draw(&self, scene: &crate::Scene) {
         let mut this = self.0.lock();
         this.renderer.draw(scene);
@@ -1354,6 +1365,19 @@ extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
     }
 }
 
+extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
+    let window_state = unsafe { get_window_state(this) };
+    let mut lock = window_state.as_ref().lock();
+    unsafe {
+        let screen = lock.native_window.screen();
+        if screen != nil {
+            lock.display_link = start_display_link(screen, lock.native_view.as_ptr());
+        } else {
+            lock.display_link = nil;
+        }
+    }
+}
+
 extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
     let window_state = unsafe { get_window_state(this) };
     let lock = window_state.lock();
@@ -1503,6 +1527,22 @@ extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
     }
 }
 
+extern "C" fn step(this: &Object, _: Sel, display_link: id) {
+    let window_state = unsafe { get_window_state(this) };
+    let mut lock = window_state.lock();
+    if lock.display_link == display_link {
+        if let Some(mut callback) = lock.request_frame_callback.take() {
+            drop(lock);
+            callback();
+            window_state.lock().request_frame_callback = Some(callback);
+        }
+    } else {
+        unsafe {
+            let _: () = msg_send![display_link, invalidate];
+        }
+    }
+}
+
 extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
     unsafe { msg_send![class!(NSArray), array] }
 }

crates/gpui/src/platform/test/window.rs 🔗

@@ -284,8 +284,6 @@ impl PlatformWindow for TestWindow {
         unimplemented!()
     }
 
-    fn invalidate(&self) {}
-
     fn draw(&self, _scene: &crate::Scene) {}
 
     fn sprite_atlas(&self) -> sync::Arc<dyn crate::PlatformAtlas> {

crates/gpui/src/window.rs 🔗

@@ -22,7 +22,7 @@ use smallvec::SmallVec;
 use std::{
     any::{Any, TypeId},
     borrow::{Borrow, BorrowMut},
-    cell::RefCell,
+    cell::{Cell, RefCell},
     collections::hash_map::Entry,
     fmt::{Debug, Display},
     future::Future,
@@ -34,7 +34,7 @@ use std::{
         atomic::{AtomicUsize, Ordering::SeqCst},
         Arc,
     },
-    time::Duration,
+    time::{Duration, Instant},
 };
 use util::{measure, ResultExt};
 
@@ -269,7 +269,8 @@ pub struct Window {
     bounds: WindowBounds,
     bounds_observers: SubscriberSet<(), AnyObserver>,
     active: bool,
-    pub(crate) dirty: bool,
+    pub(crate) dirty: Rc<Cell<bool>>,
+    pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
     pub(crate) refreshing: bool,
     pub(crate) drawing: bool,
     activation_observers: SubscriberSet<(), AnyObserver>,
@@ -334,13 +335,29 @@ impl Window {
         let content_size = platform_window.content_size();
         let scale_factor = platform_window.scale_factor();
         let bounds = platform_window.bounds();
+        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
+        let dirty = Rc::new(Cell::new(false));
+        let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
 
         platform_window.on_request_frame(Box::new({
             let mut cx = cx.to_async();
+            let dirty = dirty.clone();
+            let last_input_timestamp = last_input_timestamp.clone();
             move || {
-                measure("frame duration", || {
-                    handle.update(&mut cx, |_, cx| cx.draw()).log_err();
-                })
+                if dirty.get() {
+                    measure("frame duration", || {
+                        handle
+                            .update(&mut cx, |_, cx| {
+                                cx.draw();
+                                cx.present();
+                            })
+                            .log_err();
+                    })
+                } else if last_input_timestamp.get().elapsed() < Duration::from_secs(1) {
+                    // Keep presenting the current scene for 1 extra second since the
+                    // last input to prevent the display from underclocking the refresh rate.
+                    handle.update(&mut cx, |_, cx| cx.present()).log_err();
+                }
             }
         }));
         platform_window.on_resize(Box::new({
@@ -408,7 +425,8 @@ impl Window {
             bounds,
             bounds_observers: SubscriberSet::new(),
             active: false,
-            dirty: false,
+            dirty,
+            last_input_timestamp,
             refreshing: false,
             drawing: false,
             activation_observers: SubscriberSet::new(),
@@ -466,7 +484,7 @@ impl<'a> WindowContext<'a> {
     pub fn refresh(&mut self) {
         if !self.window.drawing {
             self.window.refreshing = true;
-            self.window.dirty = true;
+            self.window.dirty.set(true);
         }
     }
 
@@ -915,9 +933,10 @@ impl<'a> WindowContext<'a> {
         &self.window.next_frame.z_index_stack
     }
 
-    /// Draw pixels to the display for this window based on the contents of its scene.
+    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
+    /// the contents of the new [Scene], use [present].
     pub(crate) fn draw(&mut self) {
-        self.window.dirty = false;
+        self.window.dirty.set(false);
         self.window.drawing = true;
 
         if let Some(requested_handler) = self.window.rendered_frame.requested_input_handler.as_mut()
@@ -1053,16 +1072,19 @@ impl<'a> WindowContext<'a> {
                 .clone()
                 .retain(&(), |listener| listener(&event, self));
         }
+        self.window.refreshing = false;
+        self.window.drawing = false;
+    }
 
+    fn present(&self) {
         self.window
             .platform_window
             .draw(&self.window.rendered_frame.scene);
-        self.window.refreshing = false;
-        self.window.drawing = false;
     }
 
     /// Dispatch a mouse or keyboard event on the window.
     pub fn dispatch_event(&mut self, event: PlatformInput) -> bool {
+        self.window.last_input_timestamp.set(Instant::now());
         // Handlers may set this to false by calling `stop_propagation`.
         self.app.propagate_event = true;
         // Handlers may set this to true by calling `prevent_default`.
@@ -2006,7 +2028,7 @@ impl<'a, V: 'static> ViewContext<'a, V> {
         }
 
         if !self.window.drawing {
-            self.window_cx.window.dirty = true;
+            self.window_cx.window.dirty.set(true);
             self.window_cx.app.push_effect(Effect::Notify {
                 emitter: self.view.model.entity_id,
             });