// Copyright © SixtyFPS GmbH // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0 // CADisplayLink based frame throttle, shared between macOS and the other Apple // platforms (iOS, etc.). The display link target, the throttle and the tick // logic are identical; only the way the `CADisplayLink` is obtained differs, so // that part lives in the platform-specific `try_create` below. use std::rc::Weak; use i_slint_core as corelib; use i_slint_core::platform::WindowAdapter as _; use objc2::rc::Retained; use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send}; use objc2_foundation::{NSObject, NSObjectProtocol, NSRunLoop, NSRunLoopCommonModes}; use objc2_quartz_core::CADisplayLink; use crate::winitwindowadapter::WinitWindowAdapter; struct DisplayLinkTargetIvars { window_adapter: Weak, } define_class!( #[unsafe(super = NSObject)] #[thread_kind = MainThreadOnly] #[ivars = DisplayLinkTargetIvars] struct DisplayLinkTarget; unsafe impl NSObjectProtocol for DisplayLinkTarget {} impl DisplayLinkTarget { #[unsafe(method(tick:))] fn tick(&self, display_link: &CADisplayLink) { let Some(adapter) = self.ivars().window_adapter.upgrade() else { // The window is gone, so there is nothing for this display link to drive. return; }; corelib::window::WindowInner::from_pub(adapter.window()) .context() .update_timers_and_animations(); // Call draw() directly rather than request_redraw(), because // during modal tracking loops (e.g. context menus) winit's // event loop is blocked and would never process RedrawRequested. if let Err(e) = adapter.draw() { i_slint_core::debug_log!("Error rendering during modal loop: {e}"); display_link.setPaused(true); return; } if !adapter.window().has_active_animations() && !adapter.pending_redraw() { display_link.setPaused(true); } } } ); impl DisplayLinkTarget { fn new(mtm: MainThreadMarker, window_adapter: Weak) -> Retained { let this = Self::alloc(mtm).set_ivars(DisplayLinkTargetIvars { window_adapter }); unsafe { msg_send![super(this), init] } } } struct CADisplayLinkFrameThrottle { // The display link retains its target per Apple docs, so storing both here // without a back-reference from target to display link avoids a retain cycle. _target: Retained, display_link: Retained, } impl Drop for CADisplayLinkFrameThrottle { fn drop(&mut self) { self.display_link.invalidate(); } } impl super::FrameThrottle for CADisplayLinkFrameThrottle { fn request_throttled_redraw(&self, winit_window: &winit::window::Window) { request_screen_frame_rate(&self.display_link, winit_window); self.display_link.setPaused(false); } } /// macOS already drives the link at the display's rate, so there is nothing to ask for. #[cfg(target_os = "macos")] fn request_screen_frame_rate(_display_link: &CADisplayLink, _winit_window: &winit::window::Window) { } /// Ask for the screen's full refresh rate, which iOS otherwise limits to 60Hz. /// /// On iPhone the request is granted only when the bundle sets /// `CADisableMinimumFrameDurationOnPhone`; see the iOS platform guide under `docs/astro`. /// The minimum leaves the system room to halve the rate when it needs to. #[cfg(ios_and_friends)] fn request_screen_frame_rate(display_link: &CADisplayLink, winit_window: &winit::window::Window) { use objc2::sel; use objc2_quartz_core::CAFrameRateRange; // -[CADisplayLink setPreferredFrameRateRange:] is only available on iOS 15.0+, // while the platform guide's template still deploys back to 13.0. if !display_link.respondsToSelector(sel!(setPreferredFrameRateRange:)) { return; } // Ask on every redraw rather than once at creation, so that a window moving to // a screen with a different rate picks the new one up. let Some(millihertz) = winit_window.current_monitor().and_then(|monitor| monitor.refresh_rate_millihertz()) else { return; }; let max = millihertz as f32 / 1000.; // A 60Hz screen has nothing to unlock, and asking would only widen the range // downwards, leaving the system free to settle at 30. if max <= 60. { return; } display_link.setPreferredFrameRateRange(CAFrameRateRange::new(max / 2., max, max)); } /// Register `display_link` on the main run loop and wrap it into a throttle that /// starts out paused (the tick is driven on demand via `request_throttled_redraw`). fn into_throttle( target: Retained, display_link: Retained, ) -> Box { // Use NSRunLoopCommonModes so the callback fires during modal tracking loops // (context menus, window resize, scrolling, etc.) unsafe { display_link.addToRunLoop_forMode(&NSRunLoop::mainRunLoop(), NSRunLoopCommonModes); } display_link.setPaused(true); Box::new(CADisplayLinkFrameThrottle { _target: target, display_link }) } #[cfg(target_os = "macos")] pub(super) fn try_create( window_adapter: Weak, winit_window: &winit::window::Window, ) -> Option> { use objc2::runtime::AnyClass; use objc2::sel; // -[NSView displayLinkWithTarget:selector:] is only available on macOS // 14.0+. The CADisplayLink class itself is reachable on older macOS via // QuartzCore, so check for the selector instead of the class. if !AnyClass::get(c"NSView")?.responds_to(sel!(displayLinkWithTarget:selector:)) { return None; } let mtm = MainThreadMarker::new().expect("frame throttle must be created on main thread"); let ns_view = crate::macos::ns_view(winit_window)?; let target = DisplayLinkTarget::new(mtm, window_adapter); let display_link = unsafe { ns_view.displayLinkWithTarget_selector(&target, sel!(tick:)) }; Some(into_throttle(target, display_link)) } #[cfg(ios_and_friends)] pub(super) fn try_create( window_adapter: Weak, _winit_window: &winit::window::Window, ) -> Option> { use objc2::sel; let mtm = MainThreadMarker::new().expect("frame throttle must be created on main thread"); let target = DisplayLinkTarget::new(mtm, window_adapter); let display_link = unsafe { CADisplayLink::displayLinkWithTarget_selector(&target, sel!(tick:)) }; Some(into_throttle(target, display_link)) }