use std::cell::{Cell, RefCell};
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject};
use objc2::{DefinedClass, MainThreadOnly, define_class, msg_send, sel};
use objc2_app_kit::NSWindow;
const FALLBACK_INTERVAL: f64 = 0.1;
const STALLED_AFTER: f64 = 0.05;
#[link(name = "QuartzCore", kind = "framework")]
unsafe extern "C" {
fn CACurrentMediaTime() -> f64;
}
struct Ticks {
f: RefCell<Box<dyn FnMut(f64)>>,
last_display: Cell<f64>,
display: Cell<u64>,
fallback: Cell<u64>,
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitFrameTarget"]
#[ivars = Ticks]
struct FrameTarget;
impl FrameTarget {
#[unsafe(method(tick:))]
fn tick(&self, link: &AnyObject) {
let target: f64 = unsafe { msg_send![link, targetTimestamp] };
let t = self.ivars();
t.last_display.set(unsafe { CACurrentMediaTime() });
t.display.set(t.display.get() + 1);
self.call(target);
}
#[unsafe(method(fallback:))]
fn fallback(&self, _timer: &AnyObject) {
let t = self.ivars();
let now = unsafe { CACurrentMediaTime() };
if now - t.last_display.get() > STALLED_AFTER {
t.fallback.set(t.fallback.get() + 1);
self.call(now);
}
}
}
);
impl FrameTarget {
fn call(&self, at: f64) {
objc2::rc::autoreleasepool(|_| {
if let Ok(mut f) = self.ivars().f.try_borrow_mut() {
crate::failure::entry("a frame callback", (), || f(at));
}
});
}
}
pub struct FrameLoop {
link: Retained<AnyObject>,
timer: Retained<AnyObject>,
target: Retained<FrameTarget>,
}
impl FrameLoop {
pub fn counts(&self) -> (u64, u64) {
let t = self.target.ivars();
(t.display.get(), t.fallback.get())
}
}
impl Drop for FrameLoop {
fn drop(&mut self) {
unsafe {
let () = msg_send![&*self.link, invalidate];
let () = msg_send![&*self.timer, invalidate];
}
}
}
pub fn on_frame(window: &NSWindow, f: impl FnMut(f64) + 'static) -> FrameLoop {
let mtm = crate::mtm();
let ticks = Ticks { f: RefCell::new(Box::new(f)), last_display: Cell::new(0.0), display: Cell::new(0), fallback: Cell::new(0) };
let target = FrameTarget::alloc(mtm).set_ivars(ticks);
let target: Retained<FrameTarget> = unsafe { msg_send![super(target), init] };
unsafe {
let link: Retained<AnyObject> = msg_send![window, displayLinkWithTarget: &*target, selector: sel!(tick:)];
let run_loop: Retained<AnyObject> = msg_send![objc2::class!(NSRunLoop), mainRunLoop];
let () = msg_send![&*link, addToRunLoop: &*run_loop, forMode: objc2_foundation::NSRunLoopCommonModes];
let timer: Retained<AnyObject> = msg_send![
objc2::class!(NSTimer),
timerWithTimeInterval: FALLBACK_INTERVAL,
target: &*target,
selector: sel!(fallback:),
userInfo: Option::<&AnyObject>::None,
repeats: true
];
let () = msg_send![&*timer, setTolerance: FALLBACK_INTERVAL / 10.0];
let () = msg_send![&*run_loop, addTimer: &*timer, forMode: objc2_foundation::NSRunLoopCommonModes];
FrameLoop { link, timer, target }
}
}