Maintain smooth frame rates when ProMotion and direct mode are enabled (#7305)

This is achieved by starting a `CADisplayLink` that will invoke the
`on_request_frame` callback at the refresh interval of the display.

We only actually draw frames when the window was dirty, or for 2 extra
seconds after the last input event to ensure ProMotion doesn't downclock
the refresh rate when the user is actively interacting with the window.

Release Notes:

- Improved performance when using a ProMotion display with fast key
repeat rates.

---------

Co-authored-by: Nathan Sobo <nathan@zed.dev>
This commit is contained in:
Antonio Scandurra 2024-02-02 16:42:46 -07:00 committed by GitHub
parent f2ba969d5b
commit 15edc46827
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 50 additions and 37 deletions

View file

@ -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;
@ -321,6 +321,7 @@ struct MacWindowState {
executor: ForegroundExecutor,
native_window: id,
native_view: NonNull<id>,
display_link: id,
renderer: MetalRenderer,
kind: WindowKind,
request_frame_callback: Option<Box<dyn FnMut()>>,
@ -522,6 +523,10 @@ impl MacWindow {
let native_view: id = msg_send![VIEW_CLASS, alloc];
let native_view = NSView::init(native_view);
let display_link: id = msg_send![class!(CADisplayLink), displayLinkWithTarget: native_view selector: sel!(displayLayer:)];
let main_run_loop: id = msg_send![class!(NSRunLoop), mainRunLoop];
let _: () =
msg_send![display_link, addToRunLoop: main_run_loop forMode: NSDefaultRunLoopMode];
assert!(!native_view.is_null());
let window = Self(Arc::new(Mutex::new(MacWindowState {
@ -529,6 +534,7 @@ impl MacWindow {
executor,
native_window,
native_view: NonNull::new_unchecked(native_view as *mut _),
display_link,
renderer: MetalRenderer::new(true),
kind: options.kind,
request_frame_callback: None,
@ -687,6 +693,9 @@ impl Drop for MacWindow {
fn drop(&mut self) {
let this = self.0.lock();
let window = this.native_window;
unsafe {
let _: () = msg_send![this.display_link, invalidate];
}
this.executor
.spawn(async move {
unsafe {
@ -1000,13 +1009,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);