1use crate::kept::{UiCell, UiLocal};
20use std::cell::Cell;
21use std::time::{Duration, Instant};
22
23use block2::RcBlock;
24use objc2::runtime::AnyObject;
25use objc2::{class, msg_send};
26use objc2_app_kit::NSWindowOcclusionState;
27use objc2_core_foundation::{CFRunLoop, kCFRunLoopCommonModes};
28
29#[derive(Debug, Clone, Copy, PartialEq)]
33pub enum StartGate {
34 Immediately,
36 WindowVisible,
38 After(Duration),
40}
41
42#[derive(Debug, Clone, Copy, Default)]
43pub struct SyncStats {
45 pub passes_after_draw: u64,
47 pub passes_right_after_draw: u64,
50 pub flushes: u64,
52 pub gated: u64,
54}
55
56thread_local! {
57 static SCHEDULED: Cell<bool> = const { Cell::new(false) };
58 static ENABLED: Cell<bool> = const { Cell::new(false) };
59 static GATE: Cell<StartGate> = const { Cell::new(StartGate::WindowVisible) };
60 static OPEN: Cell<bool> = const { Cell::new(false) };
61 static FIRST_PLACE: Cell<Option<Instant>> = const { Cell::new(None) };
62 static LAST_PLACE: Cell<Option<Instant>> = const { Cell::new(None) };
63 static DIRTY: Cell<bool> = const { Cell::new(false) };
64 static GAPS: UiCell<Vec<u32>> = const { UiCell::new(Vec::new()) };
66 static STATS: Cell<SyncStats> = const { Cell::new(SyncStats { passes_after_draw: 0, passes_right_after_draw: 0, flushes: 0, gated: 0 }) };
67}
68
69pub(crate) fn note_place() {
70 let now = Instant::now();
71 FIRST_PLACE.with(|f| if f.get().is_none() { f.set(Some(now)) });
72 LAST_PLACE.with(|l| l.set(Some(now)));
73 DIRTY.with(|d| d.set(true));
74 if ENABLED.with(Cell::get) && !SCHEDULED.with(|s| s.replace(true)) {
75 let main = CFRunLoop::main().expect("main run loop");
76 let block = RcBlock::new(|| {
77 SCHEDULED.with(|s| s.set(false));
78 on_pass();
79 });
80 unsafe { main.perform_block(kCFRunLoopCommonModes.map(|m| m.as_ref()), Some(&block)) };
83 main.wake_up();
84 }
85}
86
87pub fn gap_percentiles() -> Option<(u32, u32, u32)> {
90 GAPS.with_borrow(|g| {
91 let mut v = g.clone();
92 v.sort_unstable();
93 let at = |q: usize| v[(v.len() - 1) * q / 100];
94 (!v.is_empty()).then(|| (at(10), at(50), at(90)))
95 })
96}
97
98pub fn stats() -> SyncStats {
100 STATS.with(Cell::get)
101}
102
103pub fn set_flush_after_draw(enabled: bool, gate: StartGate) {
105 let _ = crate::host::mtm();
106 ENABLED.with(|e| e.set(enabled));
107 GATE.with(|g| g.set(gate));
108}
109
110fn on_pass() {
111 if !DIRTY.with(|d| d.replace(false)) {
112 return;
113 }
114 let mut stats = STATS.with(Cell::get);
115 stats.passes_after_draw += 1;
116 if let Some(t) = LAST_PLACE.with(Cell::get) {
117 let gap = t.elapsed();
118 GAPS.with_borrow_mut(|g| g.push(gap.as_micros().min(u32::MAX as u128) as u32));
119 if gap < Duration::from_millis(4) {
120 stats.passes_right_after_draw += 1;
121 }
122 }
123 if ENABLED.with(Cell::get) {
124 if gate_open() {
125 flush();
126 stats.flushes += 1;
127 } else {
128 stats.gated += 1;
129 }
130 }
131 STATS.with(|s| s.set(stats));
132}
133
134fn gate_open() -> bool {
135 if OPEN.with(Cell::get) {
136 return true;
137 }
138 let open = match GATE.with(Cell::get) {
139 StartGate::Immediately => true,
140 StartGate::After(d) => FIRST_PLACE.with(Cell::get).is_some_and(|t| t.elapsed() >= d),
141 StartGate::WindowVisible => crate::host::content_view()
142 .and_then(|v| v.window())
143 .is_some_and(|w| w.occlusionState().contains(NSWindowOcclusionState::Visible)),
144 };
145 OPEN.with(|o| o.set(open));
146 open
147}
148
149pub fn flush() {
151 let () = unsafe { msg_send![class!(CATransaction), flush] };
153}
154
155pub fn set_layer_presents_with_transaction(on: bool) -> bool {
159 let Some(content) = crate::host::content_view() else { return false };
160 let Some(layer) = content.layer() else { return false };
161 let layer: &AnyObject = &layer;
162 unsafe {
164 let responds: bool = msg_send![layer, respondsToSelector: objc2::sel!(setPresentsWithTransaction:)];
165 if !responds {
166 return false;
167 }
168 let () = msg_send![layer, setPresentsWithTransaction: on];
169 }
170 true
171}