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_macos: Fix animations running at 30 fps on M5 Macs (#65472)

Steve Shreeve0373366f43e3
diff --git a/Cargo.lock b/Cargo.lock
index ca85074ed1c..29a1c720485 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7553,6 +7553,7 @@ dependencies = [
"objc2-core-media",
"objc2-core-video",
"objc2-foundation 0.3.2",
+ "objc2-quartz-core 0.3.2",
"objc2-screen-capture-kit",
"objc2-uniform-type-identifiers",
"objc2-user-notifications",
diff --git a/Cargo.toml b/Cargo.toml
index 769f034e614..a2efeea218d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -801,7 +801,7 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = [
"std",
] }
objc2-security = { version = "0.3.2", default-features = false, features = ["std", "SecBase", "SecItem"] }
-objc2-quartz-core = { version = "=0.3.2", default-features = false, features = ["std", "CALayer", "CAMetalLayer"] }
+objc2-quartz-core = { version = "=0.3.2", default-features = false, features = ["std", "CALayer", "CAMetalDisplayLink", "CAMetalLayer", "objc2-metal"] }
objc2-screen-capture-kit = { version = "=0.3.2", default-features = false, features = [
"block2",
"dispatch2",
diff --git a/crates/gpui_apple/src/display_link.rs b/crates/gpui_apple/src/display_link.rs
new file mode 100644
index 00000000000..83d420594ec
--- /dev/null
+++ b/crates/gpui_apple/src/display_link.rs
@@ -0,0 +1,100 @@
+use objc2::{
+ AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send,
+ rc::Retained,
+ runtime::{AnyClass, ProtocolObject},
+};
+use objc2_foundation::{NSObject, NSObjectProtocol, NSRunLoop, NSRunLoopCommonModes};
+use objc2_quartz_core::{
+ CAMetalDisplayLink, CAMetalDisplayLinkDelegate, CAMetalDisplayLinkUpdate, CAMetalLayer,
+};
+
+struct MetalDisplayLinkDelegateIvars {
+ callback: Box<dyn Fn(&CAMetalDisplayLinkUpdate)>,
+}
+
+define_class!(
+ // SAFETY: `NSObject` has no subclassing requirements.
+ #[unsafe(super(NSObject))]
+ #[thread_kind = MainThreadOnly]
+ #[ivars = MetalDisplayLinkDelegateIvars]
+ struct MetalDisplayLinkDelegate;
+
+ unsafe impl NSObjectProtocol for MetalDisplayLinkDelegate {}
+
+ unsafe impl CAMetalDisplayLinkDelegate for MetalDisplayLinkDelegate {
+ #[unsafe(method(metalDisplayLink:needsUpdate:))]
+ fn needs_update(&self, _link: &CAMetalDisplayLink, update: &CAMetalDisplayLinkUpdate) {
+ // The callback may destroy its frame source, releasing our owner's retain.
+ let delegate = self.retain();
+ (delegate.ivars().callback)(update);
+ }
+ }
+);
+
+impl MetalDisplayLinkDelegate {
+ fn new(
+ main_thread: MainThreadMarker,
+ callback: impl Fn(&CAMetalDisplayLinkUpdate) + 'static,
+ ) -> Retained<Self> {
+ let this = Self::alloc(main_thread).set_ivars(MetalDisplayLinkDelegateIvars {
+ callback: Box::new(callback),
+ });
+ // SAFETY: `NSObject`'s `init` is its designated initializer.
+ unsafe { msg_send![super(this), init] }
+ }
+}
+
+/// A main-run-loop source of Metal drawables on macOS 14+ and iOS/iPadOS 17+.
+///
+/// Callbacks run on the run loop the link is registered with:
+/// <https://developer.apple.com/documentation/quartzcore/cametaldisplaylink>.
+/// This wrapper uses the main run loop because GPUI renders on the foreground thread.
+pub struct MetalFrameSource {
+ link: Retained<CAMetalDisplayLink>,
+ // The link holds its delegate weakly.
+ _delegate: Retained<MetalDisplayLinkDelegate>,
+ _main_thread: MainThreadMarker,
+}
+
+impl MetalFrameSource {
+ /// Whether this system has `CAMetalDisplayLink` (macOS 14+, iOS/iPadOS 17+).
+ pub fn is_available() -> bool {
+ AnyClass::get(c"CAMetalDisplayLink").is_some()
+ }
+
+ /// Starts delivering updates for `layer`, or returns `None` where
+ /// `CAMetalDisplayLink` is unavailable.
+ pub fn new(
+ layer: &CAMetalLayer,
+ main_thread: MainThreadMarker,
+ callback: impl Fn(&CAMetalDisplayLinkUpdate) + 'static,
+ ) -> Option<Self> {
+ if !Self::is_available() {
+ return None;
+ }
+ let delegate = MetalDisplayLinkDelegate::new(main_thread, callback);
+ let link = CAMetalDisplayLink::initWithMetalLayer(CAMetalDisplayLink::alloc(), layer);
+ link.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
+ // The default range follows the display and system power policy:
+ // https://developer.apple.com/documentation/quartzcore/cametaldisplaylink/preferredframeraterange
+ // SAFETY: the retained marker confines the source to the main thread,
+ // and the main run loop outlives the source.
+ unsafe { link.addToRunLoop_forMode(&NSRunLoop::mainRunLoop(), NSRunLoopCommonModes) };
+ Some(Self {
+ link,
+ _delegate: delegate,
+ _main_thread: main_thread,
+ })
+ }
+
+ /// A paused link delivers no updates and acquires no drawables.
+ pub fn set_paused(&self, paused: bool) {
+ self.link.setPaused(paused);
+ }
+}
+
+impl Drop for MetalFrameSource {
+ fn drop(&mut self) {
+ self.link.invalidate();
+ }
+}
diff --git a/crates/gpui_apple/src/gpui_apple.rs b/crates/gpui_apple/src/gpui_apple.rs
index 1e3d0e58515..4ce5848e583 100644
--- a/crates/gpui_apple/src/gpui_apple.rs
+++ b/crates/gpui_apple/src/gpui_apple.rs
@@ -6,6 +6,7 @@
//! while leaving application lifecycle, windowing, and input to each platform backend.
mod dispatcher;
+pub mod display_link;
pub mod keychain;
mod metal_atlas;
pub mod metal_renderer;
diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs
index e08652c3f6f..9ef50a3569f 100644
--- a/crates/gpui_apple/src/metal_renderer.rs
+++ b/crates/gpui_apple/src/metal_renderer.rs
@@ -118,12 +118,20 @@ impl InstanceBufferPool {
}
}
+enum DisplayLinkMode {
+ Detached,
+ Attached {
+ drawable: Option<Retained<ProtocolObject<dyn CAMetalDrawable>>>,
+ },
+}
+
pub struct MetalRenderer {
device: Retained<ProtocolObject<dyn MTLDevice>>,
layer: Option<Retained<CAMetalLayer>>,
is_apple_gpu: bool,
is_unified_memory: bool,
presents_with_transaction: bool,
+ display_link_mode: DisplayLinkMode,
/// For headless rendering, tracks whether output should be opaque
opaque: bool,
command_queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
@@ -410,6 +418,7 @@ impl MetalRenderer {
device,
layer,
presents_with_transaction: false,
+ display_link_mode: DisplayLinkMode::Detached,
is_apple_gpu,
is_unified_memory,
opaque,
@@ -449,6 +458,46 @@ impl MetalRenderer {
&self.sprite_atlas
}
+ /// Draw the next frame into `drawable` instead of asking the layer for one.
+ ///
+ /// A `CAMetalDisplayLink` hands out each frame's drawable early enough for
+ /// the frame to reach the display on time; `nextDrawable` would instead
+ /// wait for the compositor to release one. Pass `None` once the frame is
+ /// done, so a drawable the frame did not use goes back to the layer.
+ ///
+ /// Returns the drawable this replaces: after a frame, `Some` means the
+ /// frame neither drew nor presented.
+ ///
+ /// This is a setter rather than a guard scoped to one frame because the
+ /// window releases its lock on the renderer while GPUI draws.
+ pub fn set_frame_drawable(
+ &mut self,
+ drawable: Option<Retained<ProtocolObject<dyn CAMetalDrawable>>>,
+ ) -> Option<Retained<ProtocolObject<dyn CAMetalDrawable>>> {
+ match &mut self.display_link_mode {
+ DisplayLinkMode::Attached { drawable: current } => mem::replace(current, drawable),
+ DisplayLinkMode::Detached => {
+ // Only a live link hands out drawables, and a link is detached
+ // only after it has been invalidated.
+ debug_assert!(
+ drawable.is_none(),
+ "received a display link drawable while detached"
+ );
+ None
+ }
+ }
+ }
+
+ /// Record whether a `CAMetalDisplayLink` drives the layer. While one
+ /// does, frames are drawn only into the drawables it hands out.
+ pub fn set_display_link_attached(&mut self, attached: bool) {
+ self.display_link_mode = if attached {
+ DisplayLinkMode::Attached { drawable: None }
+ } else {
+ DisplayLinkMode::Detached
+ };
+ }
+
pub fn set_presents_with_transaction(&mut self, presents_with_transaction: bool) {
self.presents_with_transaction = presents_with_transaction;
if let Some(layer) = &self.layer {
@@ -539,20 +588,32 @@ impl MetalRenderer {
return;
}
};
- let viewport_size = layer.drawableSize();
+ let drawable = match &mut self.display_link_mode {
+ DisplayLinkMode::Attached { drawable } => {
+ let Some(drawable) = drawable.take() else {
+ log::error!("skipped a frame drawn outside its display link's update");
+ return;
+ };
+ drawable
+ }
+ DisplayLinkMode::Detached => {
+ let Some(drawable) = layer.nextDrawable() else {
+ log::error!(
+ "failed to retrieve next drawable, drawable size: {:?}",
+ layer.drawableSize()
+ );
+ return;
+ };
+ drawable
+ }
+ };
+ // A display link's drawable was sized when the link handed it out,
+ // which can be before a resize the layer has since taken.
+ let texture = drawable.texture();
let viewport_size: Size<DevicePixels> = size(
- (viewport_size.width.ceil() as i32).into(),
- (viewport_size.height.ceil() as i32).into(),
+ (texture.width() as i32).into(),
+ (texture.height() as i32).into(),
);
- let drawable = if let Some(drawable) = layer.nextDrawable() {
- drawable
- } else {
- log::error!(
- "failed to retrieve next drawable, drawable size: {:?}",
- viewport_size
- );
- return;
- };
let command_buffer = match self.render_frame(scene, &drawable.texture(), viewport_size) {
Ok(command_buffer) => command_buffer,
@@ -1857,6 +1918,51 @@ mod tests {
};
use objc2_metal::MTLCommandBufferStatus;
+ #[test]
+ fn display_link_mode_consumes_and_clears_drawables() -> Result<()> {
+ let mut renderer = MetalRenderer::new(Default::default(), false, false)?;
+ renderer.update_drawable_size(size(DevicePixels(64), DevicePixels(64)));
+ let drawable = renderer
+ .layer()
+ .and_then(|layer| layer.nextDrawable())
+ .context("window renderer must supply a drawable")?;
+
+ renderer.set_display_link_attached(true);
+ assert!(matches!(
+ renderer.display_link_mode,
+ DisplayLinkMode::Attached { drawable: None }
+ ));
+ assert!(
+ renderer
+ .set_frame_drawable(Some(drawable.clone()))
+ .is_none()
+ );
+ assert!(matches!(
+ renderer.display_link_mode,
+ DisplayLinkMode::Attached { drawable: Some(_) }
+ ));
+ renderer.draw(&Scene::default());
+ assert!(matches!(
+ renderer.display_link_mode,
+ DisplayLinkMode::Attached { drawable: None }
+ ));
+ // A frame that drew consumed its drawable; one that didn't hands it back.
+ assert!(
+ renderer
+ .set_frame_drawable(Some(drawable.clone()))
+ .is_none()
+ );
+ assert!(renderer.set_frame_drawable(None).is_some());
+
+ renderer.set_frame_drawable(Some(drawable));
+ renderer.set_display_link_attached(false);
+ assert!(matches!(
+ renderer.display_link_mode,
+ DisplayLinkMode::Detached
+ ));
+ Ok(())
+ }
+
#[test]
fn render_core_video_surface() {
let surface_properties_key = unsafe { kCVPixelBufferIOSurfacePropertiesKey };
diff --git a/crates/gpui_macos/Cargo.toml b/crates/gpui_macos/Cargo.toml
index cf2f85f063f..b4f9ddee9ce 100644
--- a/crates/gpui_macos/Cargo.toml
+++ b/crates/gpui_macos/Cargo.toml
@@ -47,6 +47,7 @@ objc2-core-graphics = { workspace = true, features = ["CGColor", "objc2"] }
objc2-core-media = { workspace = true, optional = true }
objc2-core-video = { workspace = true, features = ["CVHostTime"] }
objc2-foundation.workspace = true
+objc2-quartz-core.workspace = true
objc2-screen-capture-kit = { workspace = true, optional = true }
objc2-uniform-type-identifiers.workspace = true
objc2-user-notifications.workspace = true
diff --git a/crates/gpui_macos/src/display_link.rs b/crates/gpui_macos/src/display_link.rs
index 658b9f24ace..90a25979a1e 100644
--- a/crates/gpui_macos/src/display_link.rs
+++ b/crates/gpui_macos/src/display_link.rs
@@ -1,4 +1,8 @@
-//! Frame pacing for macOS windows, built on `CVDisplayLink`.
+//! Frame pacing for macOS windows.
+//!
+//! On macOS 14 and later a window is paced by a `CAMetalDisplayLink` on its
+//! layer ([`gpui_apple::display_link::MetalFrameSource`]). Earlier systems use
+//! the shared `CVDisplayLink` registry described below ([`WindowFrameSource`]).
//!
//! CVDisplayLink has no safe teardown: `CVDisplayLinkStop` merely flags the
//! link's io thread to exit "soon" and returns immediately, and there is no
@@ -57,9 +61,11 @@ use dispatch2::{
_dispatch_source_type_data_add, DispatchObject, DispatchQueue, DispatchRetained, DispatchSource,
};
use gpui::{FrameRequestSource, PlatformFrameSignal};
+use gpui_apple::display_link::MetalFrameSource;
use gpui_util::ResultExt;
use scheduler::Instant;
use std::{
+ cell::{Cell, RefCell},
collections::{BTreeMap, btree_map},
ffi::c_void,
sync::{Arc, Mutex, MutexGuard, PoisonError},
@@ -288,6 +294,54 @@ fn unsubscribe(display_id: CGDirectDisplayID, subscriber_id: SubscriberId) {
}
}
+/// A window's `CAMetalDisplayLink`, shared with GPUI's frame waker so that a
+/// wake reaches the current link without taking the window's lock.
+///
+/// The link pauses after any update in which GPUI neither drew, presented,
+/// nor asked for another frame, so an idle window acquires no drawables. GPUI
+/// decides when frames are needed (including presenting after high-rate
+/// input); this only stops the link between those decisions.
+#[derive(Default)]
+pub struct MetalFrames {
+ source: RefCell<Option<MetalFrameSource>>,
+ /// Whether GPUI asked for a frame since the current update began.
+ woken: Cell<bool>,
+}
+
+impl MetalFrames {
+ pub fn replace(&self, source: Option<MetalFrameSource>) {
+ *self.source.borrow_mut() = source;
+ }
+
+ pub fn is_attached(&self) -> bool {
+ self.source.borrow().is_some()
+ }
+
+ pub fn wake(&self) {
+ self.woken.set(true);
+ // A source being replaced starts unpaused, so skipping it is safe.
+ if let Ok(source) = self.source.try_borrow()
+ && let Some(source) = source.as_ref()
+ {
+ source.set_paused(false);
+ }
+ }
+
+ pub fn begin_frame(&self) {
+ self.woken.set(false);
+ }
+
+ /// Ends an update, pausing the link if GPUI neither used its drawable nor
+ /// asked for another frame while it ran. Returns whether it paused.
+ pub fn end_frame(&self, used_drawable: bool) -> bool {
+ let pause = !used_drawable && !self.woken.get();
+ if pause && let Some(source) = self.source.borrow().as_ref() {
+ source.set_paused(true);
+ }
+ pause
+ }
+}
+
/// A per-window source of frame requests, paced by the display the window is
/// on. The wrapped dispatch source coalesces vsync ticks from the display's
/// io thread and invokes `callback(data)` on the main queue.
@@ -534,6 +588,56 @@ mod sys {
#[cfg(test)]
mod tests {
use super::*;
+ use objc2::AnyThread;
+ use objc2_quartz_core::CAMetalDisplayLink;
+
+ #[test]
+ fn metal_frames_pause_only_when_gpui_neither_draws_nor_asks_again() {
+ let frames = MetalFrames::default();
+
+ frames.begin_frame();
+ assert!(
+ !frames.end_frame(true),
+ "a frame that drew keeps the link running"
+ );
+
+ frames.begin_frame();
+ frames.wake();
+ assert!(
+ !frames.end_frame(false),
+ "a wake during the update, like a throttled frame's retry, keeps it running"
+ );
+
+ frames.wake();
+ frames.begin_frame();
+ assert!(
+ frames.end_frame(false),
+ "a wake before the update was served by it"
+ );
+
+ frames.begin_frame();
+ assert!(frames.end_frame(false), "an idle update pauses the link");
+ }
+
+ #[test]
+ fn a_renderer_draws_normally_after_its_display_link_is_invalidated() {
+ if !MetalFrameSource::is_available() {
+ return;
+ }
+ let mut renderer =
+ crate::renderer::MetalRenderer::new(Default::default(), false, false).unwrap();
+ renderer.update_drawable_size(gpui::size(gpui::DevicePixels(64), gpui::DevicePixels(64)));
+ let layer = renderer.layer().expect("window renderer has a layer");
+ // The link is never added to a run loop: attaching it to the layer is
+ // the state under test.
+ let link = CAMetalDisplayLink::initWithMetalLayer(CAMetalDisplayLink::alloc(), layer);
+ renderer.set_display_link_attached(true);
+ renderer.draw(&gpui::Scene::default());
+
+ link.invalidate();
+ renderer.set_display_link_attached(false);
+ renderer.draw(&gpui::Scene::default());
+ }
#[test]
fn host_timestamp_preserves_request_age_at_different_clock_rates() {
diff --git a/crates/gpui_macos/src/window.rs b/crates/gpui_macos/src/window.rs
index 01807c773aa..32a6a540092 100644
--- a/crates/gpui_macos/src/window.rs
+++ b/crates/gpui_macos/src/window.rs
@@ -1,5 +1,5 @@
use crate::{
- BoolExt, MacDisplay, NSRange, NSStringExt, TISCopyCurrentKeyboardInputSource,
+ BoolExt, MacDisplay, MetalFrames, NSRange, NSStringExt, TISCopyCurrentKeyboardInputSource,
TISGetInputSourceProperty, WindowFrameSource, events::platform_input_from_native,
kTISPropertyInputSourceIsASCIICapable, kTISPropertyInputSourceType, kTISTypeKeyboardInputMode,
ns_string, renderer,
@@ -25,6 +25,7 @@ use core_foundation_sys::number::{CFBooleanGetValue, CFBooleanRef};
use core_graphics::display::CGDirectDisplayID;
use ctor::ctor;
use futures::channel::oneshot;
+use gpui_apple::display_link::MetalFrameSource;
use gpui_util::ResultExt;
use objc2::{
AnyThread, MainThreadMarker, Message, class, msg_send,
@@ -64,9 +65,9 @@ use std::{
os::unix::ffi::OsStrExt,
path::PathBuf,
ptr::{self, NonNull},
- rc::Rc,
+ rc::{Rc, Weak},
sync::{
- Arc, Once, Weak,
+ Arc, Once,
atomic::{AtomicBool, Ordering},
},
time::Duration,
@@ -637,6 +638,15 @@ unsafe fn apply_simple_fullscreen_plan(
}
}
+/// What paces a window's frames. The choice depends only on the OS version,
+/// so it is made once per window.
+enum FrameSource {
+ /// macOS 14+: a `CAMetalDisplayLink` that hands out each frame's drawable.
+ Metal(Rc<MetalFrames>),
+ /// Earlier systems: the shared `CVDisplayLink` registry, joined on first start.
+ DisplayLink(Option<WindowFrameSource>),
+}
+
struct MacWindowState {
handle: AnyWindowHandle,
foreground_executor: ForegroundExecutor,
@@ -647,7 +657,7 @@ struct MacWindowState {
background_appearance: WindowBackgroundAppearance,
cursor_style: CursorStyle,
cursor_visible: Arc<AtomicBool>,
- frame_source: Option<WindowFrameSource>,
+ frame_source: FrameSource,
renderer: renderer::Renderer,
request_frame_callback: Option<Box<dyn FnMut(RequestFrameOptions)>>,
event_callback: Option<Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>>,
@@ -814,7 +824,9 @@ impl MacWindowState {
}
}
- fn start_display_link(&mut self) {
+ /// `window_state` is the handle this state lives in; a Metal link holds it
+ /// weakly to deliver frames.
+ fn start_display_link(&mut self, window_state: &Rc<Mutex<MacWindowState>>) {
self.stop_display_link();
if !self
.native_window()
@@ -823,21 +835,51 @@ impl MacWindowState {
{
return;
}
- let screen: *mut AnyObject = unsafe { msg_send![self.native_window, screen] };
- let Some(display_id) = display_id_for_screen(screen) else {
- // AppKit can temporarily report no screen while displays are being reconfigured.
- return;
- };
- let data = self.native_view.as_ptr() as *mut c_void;
- self.frame_source
- .get_or_insert_with(|| WindowFrameSource::new(data, step))
- .start(display_id)
- .log_err();
+ match &mut self.frame_source {
+ FrameSource::Metal(metal_frames) => {
+ let Some(layer) = self.renderer.layer() else {
+ return;
+ };
+ let main_thread =
+ crate::main_thread_marker().expect("macOS windows require the main thread");
+ let window_state = Rc::downgrade(window_state);
+ let source = MetalFrameSource::new(layer, main_thread, move |update| {
+ if let Some(window_state) = window_state.upgrade() {
+ metal_frame(&window_state, update);
+ }
+ });
+ if let Some(source) = source {
+ metal_frames.replace(Some(source));
+ self.renderer.set_display_link_attached(true);
+ }
+ }
+ FrameSource::DisplayLink(frame_source) => {
+ let screen: *mut AnyObject = unsafe { msg_send![self.native_window, screen] };
+ let Some(display_id) = display_id_for_screen(screen) else {
+ // AppKit can temporarily report no screen while displays are being reconfigured.
+ return;
+ };
+ let data = self.native_view.as_ptr() as *mut c_void;
+ frame_source
+ .get_or_insert_with(|| WindowFrameSource::new(data, step))
+ .start(display_id)
+ .log_err();
+ }
+ }
}
fn stop_display_link(&mut self) {
- if let Some(frame_source) = self.frame_source.as_mut() {
- frame_source.stop();
+ match &mut self.frame_source {
+ FrameSource::Metal(metal_frames) => {
+ if metal_frames.is_attached() {
+ // Detach the link rather than pause it, so that a synchronous
+ // draw can use the layer's `nextDrawable`.
+ metal_frames.replace(None);
+ self.renderer.set_display_link_attached(false);
+ }
+ }
+ FrameSource::DisplayLink(Some(frame_source)) => frame_source.stop(),
+ FrameSource::DisplayLink(None) => {}
}
}
@@ -931,9 +973,13 @@ impl MacWindowState {
}
}
-unsafe impl Send for MacWindowState {}
-
-pub(crate) struct MacWindow(Arc<Mutex<MacWindowState>>, MainThreadMarker);
+pub(crate) struct MacWindow(
+ Rc<Mutex<MacWindowState>>,
+ MainThreadMarker,
+ /// The Metal link's frame waker, kept outside the lock so waking never
+ /// waits on it. `None` when a `CVDisplayLink` paces frames.
+ Option<Rc<MetalFrames>>,
+);
impl MacWindow {
pub fn open(
@@ -1062,7 +1108,8 @@ impl MacWindow {
let native_view: *mut AnyObject = msg_send![native_view, initWithFrame: content_bounds];
assert!(!native_view.is_null());
- let state = Arc::new(Mutex::new(MacWindowState {
+ let metal_frames = MetalFrameSource::is_available().then(Rc::<MetalFrames>::default);
+ let state = Rc::new(Mutex::new(MacWindowState {
handle,
foreground_executor,
background_executor,
@@ -1072,7 +1119,10 @@ impl MacWindow {
background_appearance: WindowBackgroundAppearance::Opaque,
cursor_style: CursorStyle::Arrow,
cursor_visible,
- frame_source: None,
+ frame_source: match &metal_frames {
+ Some(metal_frames) => FrameSource::Metal(metal_frames.clone()),
+ None => FrameSource::DisplayLink(None),
+ },
renderer,
request_frame_callback: None,
event_callback: None,
@@ -1116,21 +1166,21 @@ impl MacWindow {
accesskit_adapter: None,
sheet_parent: None,
}));
- let mut window = Self(state, marker);
+ let mut window = Self(state, marker, metal_frames);
(*native_window)
.class()
.instance_variable(WINDOW_STATE_IVAR)
.expect("GPUI window state ivar")
.load_ptr::<*mut c_void>(&*native_window)
- .write(Arc::into_raw(window.0.clone()).cast_mut().cast());
+ .write(Rc::into_raw(window.0.clone()).cast_mut().cast());
let _: () = msg_send![native_window, setDelegate: native_window];
(*native_view)
.class()
.instance_variable(WINDOW_STATE_IVAR)
.expect("GPUI view state ivar")
.load_ptr::<*mut c_void>(&*native_view)
- .write(Arc::into_raw(window.0.clone()).cast_mut().cast());
+ .write(Rc::into_raw(window.0.clone()).cast_mut().cast());
if let Some(title) = titlebar
.as_ref()
@@ -1352,7 +1402,7 @@ impl Drop for MacWindow {
let mut this = self.0.lock();
// `accesskit_macos::SubclassingAdapter::for_window` strong-retains the
// window's content view, and that content view keeps the `GPUIView` it
- // hosts alive. Together with the `Arc<Mutex<MacWindowState>>` parked in
+ // hosts alive. Together with the `Rc<Mutex<MacWindowState>>` parked in
// both views' `windowState` ivar, that forms
// `MacWindowState -> adapter -> content view -> GPUIView -> MacWindowState`,
// a cycle the delegate/`frame_source` teardown below cannot break. Drop
@@ -1362,7 +1412,10 @@ impl Drop for MacWindow {
this.renderer.destroy();
let window = this.native_window;
let sheet_parent = this.sheet_parent.take();
- this.frame_source.take();
+ match &mut this.frame_source {
+ FrameSource::Metal(metal_frames) => metal_frames.replace(None),
+ FrameSource::DisplayLink(frame_source) => drop(frame_source.take()),
+ }
unsafe {
let _: () = msg_send![this.native_window, setDelegate: ptr::null_mut::<AnyObject>()];
}
@@ -2095,6 +2148,23 @@ impl PlatformWindow for MacWindow {
this.renderer.draw(scene);
}
+ // GPUI calls this without waking the frame waker when a window only needs
+ // a present, so a paused Metal link must resume here too.
+ fn schedule_frame(&self) {
+ if let Some(metal_frames) = &self.2 {
+ metal_frames.wake();
+ }
+ }
+
+ fn frame_waker(&self) -> Option<Rc<dyn Fn()>> {
+ let metal_frames = Rc::downgrade(self.2.as_ref()?);
+ Some(Rc::new(move || {
+ if let Some(metal_frames) = metal_frames.upgrade() {
+ metal_frames.wake();
+ }
+ }))
+ }
+
fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
self.0.lock().renderer.sprite_atlas().clone()
}
@@ -2430,14 +2500,14 @@ unsafe fn is_gpui_window(window: *mut AnyObject) -> bool {
}
}
-unsafe fn get_window_state(object: &AnyObject) -> Arc<Mutex<MacWindowState>> {
+unsafe fn get_window_state(object: &AnyObject) -> Rc<Mutex<MacWindowState>> {
unsafe {
let raw = *object
.class()
.instance_variable(WINDOW_STATE_IVAR)
.expect("GPUI window state ivar")
.load::<*mut c_void>(object);
- let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
+ let rc1 = Rc::from_raw(raw as *mut Mutex<MacWindowState>);
let rc2 = rc1.clone();
mem::forget(rc1);
rc2
@@ -2451,7 +2521,7 @@ unsafe fn drop_window_state(object: &AnyObject) {
.instance_variable(WINDOW_STATE_IVAR)
.expect("GPUI window state ivar")
.load::<*mut c_void>(object);
- Arc::from_raw(raw as *mut Mutex<MacWindowState>);
+ Rc::from_raw(raw as *mut Mutex<MacWindowState>);
}
}
@@ -2781,7 +2851,7 @@ extern "C" fn handle_key_event(
extern "C" fn handle_view_event(this: &AnyObject, _: Sel, native_event: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
- let weak_window_state = Arc::downgrade(&window_state);
+ let weak_window_state = Rc::downgrade(&window_state);
let mut lock = window_state.as_ref().lock();
let window_height = lock.content_size().height;
let native_event_type: NSEventType = unsafe { msg_send![native_event, type] };
@@ -2950,7 +3020,7 @@ fn visibility(state: &MacWindowState) -> WindowVisibility {
}
}
-fn report_visibility(window_state: &Arc<Mutex<MacWindowState>>) {
+fn report_visibility(window_state: &Rc<Mutex<MacWindowState>>) {
let state = window_state.lock();
if state.last_visibility.is_none() {
return;
@@ -2991,7 +3061,7 @@ extern "C" fn window_did_change_occlusion_state(this: &AnyObject, _: Sel, _: *mu
.contains(NSWindowOcclusionState::Visible)
{
lock.move_traffic_light();
- lock.start_display_link();
+ lock.start_display_link(&window_state);
} else {
lock.stop_display_link();
}
@@ -3056,7 +3126,7 @@ extern "C" fn window_did_fail_to_exit_fullscreen(this: &AnyObject, _: Sel, _: *m
extern "C" fn window_did_exit_fullscreen(this: &AnyObject, _: Sel, _: *mut AnyObject) {
// SAFETY: This method is registered only on GPUI window classes, which initialize
- // WINDOW_STATE_IVAR with an Arc<Mutex<MacWindowState>> during window creation.
+ // WINDOW_STATE_IVAR with an Rc<Mutex<MacWindowState>> during window creation.
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
lock.is_exiting_fullscreen = false;
@@ -3091,7 +3161,7 @@ extern "C" fn window_did_move(this: &AnyObject, _: Sel, _: *mut AnyObject) {
}
// Update the window scale factor and drawable size, and call the resize callback if any.
-fn update_window_scale_factor(window_state: &Arc<Mutex<MacWindowState>>) {
+fn update_window_scale_factor(window_state: &Rc<Mutex<MacWindowState>>) {
let mut lock = window_state.as_ref().lock();
let scale_factor = lock.scale_factor();
let size = lock.content_size();
@@ -3120,13 +3190,13 @@ fn update_window_scale_factor(window_state: &Arc<Mutex<MacWindowState>>) {
extern "C" fn window_did_change_screen(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let window_state = unsafe { get_window_state(this) };
let mut lock = window_state.as_ref().lock();
- lock.start_display_link();
+ lock.start_display_link(&window_state);
drop(lock);
update_window_scale_factor(&window_state);
report_display_change(&window_state);
}
-fn report_display_change(window_state: &Arc<Mutex<MacWindowState>>) {
+fn report_display_change(window_state: &Rc<Mutex<MacWindowState>>) {
let executor = window_state.lock().foreground_executor.clone();
// AppKit can post screen changes while GPUI is updating a window, e.g.
// from `setFrame:`, so deliver after that update completes.
@@ -3208,7 +3278,7 @@ extern "C" fn window_did_change_key_status(this: &AnyObject, selector: Sel, _: *
let mut lock = window_state.lock();
lock.request_frame_callback = Some(callback);
lock.renderer.set_presents_with_transaction(false);
- lock.start_display_link();
+ lock.start_display_link(&window_state);
}
} else {
lock.activated_least_once = true;
@@ -3334,7 +3404,7 @@ extern "C" fn display_layer(this: &AnyObject, _: Sel, _: *mut AnyObject) {
let mut lock = window_state.lock();
lock.request_frame_callback = Some(callback);
lock.renderer.set_presents_with_transaction(false);
- lock.start_display_link();
+ lock.start_display_link(&window_state);
}
}
@@ -3344,14 +3414,14 @@ extern "C" fn step(view: *mut c_void) {
let mut lock = window_state.lock();
if let Some(mut callback) = lock.request_frame_callback.take() {
- let (signal_at, signal_source) = lock
- .frame_source
- .as_ref()
- .and_then(WindowFrameSource::take_signal)
- .map_or(
- (None, FrameRequestSource::NativeCallback),
- |(at, source)| (Some(at), source),
- );
+ let signal = match &lock.frame_source {
+ FrameSource::DisplayLink(Some(frame_source)) => frame_source.take_signal(),
+ _ => None,
+ };
+ let (signal_at, signal_source) = signal.map_or(
+ (None, FrameRequestSource::NativeCallback),
+ |(at, source)| (Some(at), source),
+ );
drop(lock);
callback(RequestFrameOptions {
signal_at,
@@ -3362,6 +3432,35 @@ extern "C" fn step(view: *mut c_void) {
}
}
+fn metal_frame(
+ window_state: &Rc<Mutex<MacWindowState>>,
+ update: &objc2_quartz_core::CAMetalDisplayLinkUpdate,
+) {
+ let signal_at = PlatformFrameSignal::capture(scheduler::Instant::now);
+ let mut lock = window_state.lock();
+ let FrameSource::Metal(metal_frames) = &lock.frame_source else {
+ return;
+ };
+ let metal_frames = metal_frames.clone();
+ let Some(mut callback) = lock.request_frame_callback.take() else {
+ return;
+ };
+ lock.renderer.set_frame_drawable(Some(update.drawable()));
+ drop(lock);
+ metal_frames.begin_frame();
+ callback(RequestFrameOptions {
+ signal_at,
+ signal_source: FrameRequestSource::NativeCallback,
+ ..Default::default()
+ });
+ let mut lock = window_state.lock();
+ lock.request_frame_callback = Some(callback);
+ // A frame with nothing to draw leaves its drawable unused; releasing it
+ // lets the link hand it out again.
+ let used_drawable = lock.renderer.set_frame_drawable(None).is_none();
+ metal_frames.end_frame(used_drawable);
+}
+
extern "C" fn valid_attributes_for_marked_text(_: &AnyObject, _: Sel) -> *mut AnyObject {
unsafe { msg_send![class!(NSArray), array] }
}
@@ -3764,7 +3863,7 @@ async fn synthetic_drag(
/// Sends the specified FileDropEvent using `PlatformInput::FileDrop` to the window
/// state and updates the window state according to the event passed.
fn send_file_drop_event(
- window_state: Arc<Mutex<MacWindowState>>,
+ window_state: Rc<Mutex<MacWindowState>>,
file_drop_event: FileDropEvent,
) -> bool {
let external_files_dragged = match file_drop_event {