use crate::kept::{UiCell, UiLocal};
use std::cell::Cell;
use std::time::{Duration, Instant};
use block2::RcBlock;
use objc2::runtime::AnyObject;
use objc2::{class, msg_send};
use objc2_app_kit::NSWindowOcclusionState;
use objc2_core_foundation::{CFRunLoop, kCFRunLoopCommonModes};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum StartGate {
Immediately,
WindowVisible,
After(Duration),
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SyncStats {
pub passes_after_draw: u64,
pub passes_right_after_draw: u64,
pub flushes: u64,
pub gated: u64,
}
thread_local! {
static SCHEDULED: Cell<bool> = const { Cell::new(false) };
static ENABLED: Cell<bool> = const { Cell::new(false) };
static GATE: Cell<StartGate> = const { Cell::new(StartGate::WindowVisible) };
static OPEN: Cell<bool> = const { Cell::new(false) };
static FIRST_PLACE: Cell<Option<Instant>> = const { Cell::new(None) };
static LAST_PLACE: Cell<Option<Instant>> = const { Cell::new(None) };
static DIRTY: Cell<bool> = const { Cell::new(false) };
static GAPS: UiCell<Vec<u32>> = const { UiCell::new(Vec::new()) };
static STATS: Cell<SyncStats> = const { Cell::new(SyncStats { passes_after_draw: 0, passes_right_after_draw: 0, flushes: 0, gated: 0 }) };
}
pub(crate) fn note_place() {
let now = Instant::now();
FIRST_PLACE.with(|f| if f.get().is_none() { f.set(Some(now)) });
LAST_PLACE.with(|l| l.set(Some(now)));
DIRTY.with(|d| d.set(true));
if ENABLED.with(Cell::get) && !SCHEDULED.with(|s| s.replace(true)) {
let main = CFRunLoop::main().expect("main run loop");
let block = RcBlock::new(|| {
SCHEDULED.with(|s| s.set(false));
on_pass();
});
unsafe { main.perform_block(kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
main.wake_up();
}
}
pub fn gap_percentiles() -> Option<(u32, u32, u32)> {
GAPS.with_borrow(|g| {
let mut v = g.clone();
v.sort_unstable();
let at = |q: usize| v[(v.len() - 1) * q / 100];
(!v.is_empty()).then(|| (at(10), at(50), at(90)))
})
}
pub fn stats() -> SyncStats {
STATS.with(Cell::get)
}
pub fn set_flush_after_draw(enabled: bool, gate: StartGate) {
let _ = crate::host::mtm();
ENABLED.with(|e| e.set(enabled));
GATE.with(|g| g.set(gate));
}
fn on_pass() {
if !DIRTY.with(|d| d.replace(false)) {
return;
}
let mut stats = STATS.with(Cell::get);
stats.passes_after_draw += 1;
if let Some(t) = LAST_PLACE.with(Cell::get) {
let gap = t.elapsed();
GAPS.with_borrow_mut(|g| g.push(gap.as_micros().min(u32::MAX as u128) as u32));
if gap < Duration::from_millis(4) {
stats.passes_right_after_draw += 1;
}
}
if ENABLED.with(Cell::get) {
if gate_open() {
flush();
stats.flushes += 1;
} else {
stats.gated += 1;
}
}
STATS.with(|s| s.set(stats));
}
fn gate_open() -> bool {
if OPEN.with(Cell::get) {
return true;
}
let open = match GATE.with(Cell::get) {
StartGate::Immediately => true,
StartGate::After(d) => FIRST_PLACE.with(Cell::get).is_some_and(|t| t.elapsed() >= d),
StartGate::WindowVisible => crate::host::content_view()
.and_then(|v| v.window())
.is_some_and(|w| w.occlusionState().contains(NSWindowOcclusionState::Visible)),
};
OPEN.with(|o| o.set(open));
open
}
pub fn flush() {
let () = unsafe { msg_send![class!(CATransaction), flush] };
}
pub fn set_layer_presents_with_transaction(on: bool) -> bool {
let Some(content) = crate::host::content_view() else { return false };
let Some(layer) = content.layer() else { return false };
let layer: &AnyObject = &layer;
unsafe {
let responds: bool = msg_send![layer, respondsToSelector: objc2::sel!(setPresentsWithTransaction:)];
if !responds {
return false;
}
let () = msg_send![layer, setPresentsWithTransaction: on];
}
true
}