Skip to main content

day_core/
frame.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Window-scoped display scheduling (docs/frames.md). Native frame requests are shared by
5//! one-shot clients, continuous subscriptions and the legacy `frame_clock` piece. No timers,
6//! no implicit physics clamp, and no native request when there is no demand.
7
8use std::cell::RefCell;
9use std::collections::HashMap;
10use std::marker::PhantomData;
11use std::ops::ControlFlow;
12use std::rc::Rc;
13use std::time::Duration;
14
15use crate::tree::RNode;
16use day_spec::{CancelFrame, FrameCallback, FrameStamp};
17
18/// A frame opportunity, not confirmation that pixels were presented. All clients of a window
19/// receive the same timestamp. `delta` belongs to this subscription: zero on its first frame
20/// and after an explicit pause/resume. It is not clamped; simulation clients choose their policy.
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub struct Frame {
23    pub timestamp: Duration,
24    pub delta: Duration,
25    pub target_timestamp: Option<Duration>,
26}
27
28type Callback = Rc<RefCell<Box<dyn FnMut(Frame) -> ControlFlow<()>>>>;
29type Requester = Rc<dyn Fn(RNode, FrameCallback) -> CancelFrame>;
30struct Consumer {
31    root: RNode,
32    cb: Callback,
33    active: bool,
34    generation: u64,
35    last: Option<f64>,
36}
37#[derive(Default)]
38struct Source {
39    ticket: u64,
40    armed: bool,
41    dispatching: bool,
42    cancel: Option<CancelFrame>,
43}
44#[derive(Default)]
45struct Driver {
46    requester: Option<Requester>,
47    consumers: HashMap<u64, Consumer>,
48    sources: HashMap<RNode, Source>,
49    next_id: u64,
50    suspended: bool,
51}
52
53day_reactive::tls_slots! {
54    frame;
55    static DRIVER: RefCell<Driver> = RefCell::new(Driver::default());
56    static NATIVE_CALLBACKS: RefCell<(u64, HashMap<u64, FrameCallback>)> = RefCell::new((0, HashMap::new()));
57    /// The first and the latest frame timestamp seen (ms), for `uptime_secs` where the
58    /// process has no clock of its own (wasm).
59    static STAMPS: std::cell::Cell<Option<(f64, f64)>> = std::cell::Cell::new(None);
60}
61
62/// How long the app has run, from the frame clock: the span between the first and the latest
63/// frame timestamp a backend delivered. The exit line uses it on wasm, where `Instant` does not
64/// exist; `None` before any frame.
65#[must_use]
66pub fn uptime_secs() -> Option<u64> {
67    STAMPS.with(|s| {
68        s.get()
69            .map(|(first, last)| ((last - first).max(0.0) / 1000.0) as u64)
70    })
71}
72
73/// Seconds on a monotonic clock from an arbitrary origin, for timing work on any target. Native
74/// builds read `Instant`; the web, where `Instant` is unavailable, reads the clock the facade
75/// installed with [`install_monotonic_clock`] (`performance.now()`), and `0.0` before one is
76/// installed.
77#[must_use]
78pub fn now_secs() -> f64 {
79    #[cfg(not(target_arch = "wasm32"))]
80    {
81        day_spec::frame_timestamp()
82    }
83    #[cfg(target_arch = "wasm32")]
84    {
85        MONOTONIC_CLOCK.get().map_or(0.0, |f| f())
86    }
87}
88
89#[cfg(target_arch = "wasm32")]
90static MONOTONIC_CLOCK: std::sync::OnceLock<fn() -> f64> = std::sync::OnceLock::new();
91
92/// Install the host's monotonic clock for [`now_secs`] on a target without `Instant`. The first
93/// registration wins; native targets ignore it.
94pub fn install_monotonic_clock(f: fn() -> f64) {
95    #[cfg(target_arch = "wasm32")]
96    {
97        let _ = MONOTONIC_CLOCK.set(f);
98    }
99    #[cfg(not(target_arch = "wasm32"))]
100    {
101        let _ = f;
102    }
103}
104
105/// Install the native scheduler at launch. The requester MUST deliver asynchronously; tests may
106/// retain the callback and deliver chosen timestamps manually. Replaces no live registrations.
107pub fn install_frame_requester(f: impl Fn(RNode, FrameCallback) -> CancelFrame + 'static) {
108    DRIVER.with(|d| d.borrow_mut().requester = Some(Rc::new(f)));
109}
110
111/// A reusable source bound to one window. Capture `current()` while building a page, then use it
112/// from input handlers or other UI-thread code. A closed window cancels all its registrations.
113#[derive(Clone, Copy, Debug)]
114pub struct FrameClock {
115    root: RNode,
116    ui_thread: PhantomData<Rc<()>>,
117}
118impl FrameClock {
119    /// The current page's window (the initial window outside a page build).
120    #[must_use]
121    pub fn current() -> Self {
122        Self::for_root(crate::toolbar::current_page_window())
123    }
124    pub(crate) fn for_root(root: RNode) -> Self {
125        Self {
126            root,
127            ui_thread: PhantomData,
128        }
129    }
130    /// Run once at the next frame opportunity. Retain the returned handle until delivery;
131    /// dropping it cancels. Requests made inside a callback run on a subsequent frame.
132    pub fn request(self, cb: impl FnOnce(Frame) + 'static) -> FrameHandle {
133        let mut cb = Some(cb);
134        self.subscribe(move |frame| {
135            if let Some(cb) = cb.take() {
136                cb(frame);
137            }
138            ControlFlow::Break(())
139        })
140    }
141    /// Run while the callback returns `Continue(())`. `Break(())` pauses the subscription;
142    /// `resume()` can start it again. Drop or `cancel()` removes it permanently.
143    pub fn subscribe(self, cb: impl FnMut(Frame) -> ControlFlow<()> + 'static) -> FrameHandle {
144        let id = DRIVER.with(|d| {
145            let mut d = d.borrow_mut();
146            d.next_id += 1;
147            let id = d.next_id;
148            d.consumers.insert(
149                id,
150                Consumer {
151                    root: self.root,
152                    cb: Rc::new(RefCell::new(Box::new(cb))),
153                    active: true,
154                    generation: 0,
155                    last: None,
156                },
157            );
158            id
159        });
160        arm(self.root);
161        FrameHandle {
162            id,
163            ui_thread: PhantomData,
164        }
165    }
166}
167
168/// Request one frame in the current window. Prefer a captured [`FrameClock`] from event handlers.
169pub fn request(cb: impl FnOnce(Frame) + 'static) -> FrameHandle {
170    FrameClock::current().request(cb)
171}
172/// Subscribe in the current window. Dropping the returned handle cancels the subscription.
173pub fn subscribe(cb: impl FnMut(Frame) -> ControlFlow<()> + 'static) -> FrameHandle {
174    FrameClock::current().subscribe(cb)
175}
176
177/// Owns a registration. UI-thread only. Keep it alive for as long as the callback is wanted.
178#[must_use = "dropping the frame handle cancels the callback"]
179pub struct FrameHandle {
180    id: u64,
181    ui_thread: PhantomData<Rc<()>>,
182}
183impl FrameHandle {
184    pub fn pause(&self) {
185        set_active(self.id, false);
186    }
187    pub fn resume(&self) {
188        set_active(self.id, true);
189    }
190    #[must_use]
191    pub fn is_active(&self) -> bool {
192        DRIVER.with(|d| d.borrow().consumers.get(&self.id).is_some_and(|c| c.active))
193    }
194    pub fn cancel(&self) {
195        remove(self.id);
196    }
197    /// Keep the registration for this reactive scope; dispose cancels it. This is optional:
198    /// clients without a mounted piece can own the handle directly.
199    pub fn in_scope(self) {
200        day_reactive::Scope::current().on_cleanup(move || drop(self));
201    }
202}
203impl Drop for FrameHandle {
204    fn drop(&mut self) {
205        self.cancel();
206    }
207}
208
209fn set_active(id: u64, active: bool) {
210    let root = DRIVER.with(|d| {
211        let mut d = d.borrow_mut();
212        let c = d.consumers.get_mut(&id)?;
213        if c.active != active {
214            c.active = active;
215            c.generation += 1;
216            c.last = None;
217        }
218        Some(c.root)
219    });
220    if let Some(root) = root {
221        reconcile(root);
222    }
223}
224fn remove(id: u64) {
225    // User closures can own other handles. Drop them outside the driver borrow so their
226    // destructors can cancel those registrations without re-entering a borrowed RefCell.
227    // Native Quit can leave pages/callback captures alive until core TLS destruction.
228    // Their handles must not re-enter the dying root; its registries already own cleanup.
229    let Ok(removed) = DRIVER.try_with(|d| d.borrow_mut().consumers.remove(&id)) else {
230        return;
231    };
232    let root = removed.as_ref().map(|c| c.root);
233    drop(removed);
234    if let Some(root) = root {
235        reconcile(root);
236    }
237}
238fn reconcile(root: RNode) {
239    let cancel = DRIVER.with(|d| {
240        let mut d = d.borrow_mut();
241        let active = !d.suspended && d.consumers.values().any(|c| c.root == root && c.active);
242        if active {
243            return None;
244        }
245        let source = d.sources.get_mut(&root)?;
246        source.ticket += 1;
247        source.armed = false;
248        source.cancel.take()
249    });
250    if let Some(cancel) = cancel {
251        cancel();
252    }
253    arm(root);
254}
255fn arm(root: RNode) {
256    let request = DRIVER.with(|d| {
257        let mut d = d.borrow_mut();
258        if d.suspended || !d.consumers.values().any(|c| c.root == root && c.active) {
259            return None;
260        }
261        let requester = d.requester.clone()?;
262        let source = d.sources.entry(root).or_default();
263        if source.armed || source.dispatching {
264            return None;
265        }
266        source.ticket += 1;
267        source.armed = true;
268        Some((requester, source.ticket))
269    });
270    if let Some((requester, ticket)) = request {
271        let cancel = requester(root, Box::new(move |stamp| tick(root, ticket, stamp)));
272        DRIVER.with(|d| {
273            if let Some(s) = d.borrow_mut().sources.get_mut(&root) {
274                s.cancel = Some(cancel);
275            }
276        });
277    }
278}
279fn tick(root: RNode, ticket: u64, stamp: FrameStamp) {
280    STAMPS.with(|s| {
281        let first = s.get().map_or(stamp.timestamp, |(first, _)| first);
282        s.set(Some((first, stamp.timestamp)));
283    });
284    let callbacks = DRIVER.with(|d| {
285        let mut d = d.borrow_mut();
286        let Some(source) = d.sources.get_mut(&root) else {
287            return Vec::new();
288        };
289        if !source.armed || source.ticket != ticket {
290            return Vec::new();
291        }
292        source.armed = false;
293        source.cancel.take();
294        if Duration::try_from_secs_f64(stamp.timestamp).is_err() {
295            return Vec::new();
296        }
297        source.dispatching = true;
298        let mut callbacks: Vec<_> = d
299            .consumers
300            .iter()
301            .filter(|(_, c)| c.root == root && c.active)
302            .map(|(&id, c)| (id, c.generation, c.cb.clone()))
303            .collect();
304        callbacks.sort_by_key(|c| c.0);
305        callbacks
306    });
307    day_reactive::batch(|| {
308        for (id, generation, cb) in callbacks {
309            let frame = DRIVER.with(|d| {
310                let mut d = d.borrow_mut();
311                if d.suspended {
312                    return None;
313                }
314                let c = d.consumers.get_mut(&id)?;
315                if !c.active || c.generation != generation {
316                    return None;
317                }
318                // Ignore backward stamps without moving the baseline backwards.
319                let ts = stamp.timestamp.max(c.last.unwrap_or(stamp.timestamp));
320                let delta = c.last.map_or(0.0, |last| ts - last);
321                c.last = Some(ts);
322                Some(Frame {
323                    timestamp: Duration::from_secs_f64(ts),
324                    delta: Duration::from_secs_f64(delta),
325                    target_timestamp: stamp
326                        .target_timestamp
327                        .filter(|t| t.is_finite() && *t >= ts)
328                        .and_then(|t| Duration::try_from_secs_f64(t).ok()),
329                })
330            });
331            let Some(frame) = frame else {
332                continue;
333            };
334            let flow = day_spec::ffi_guard::contain(ControlFlow::Break(()), || {
335                cb.try_borrow_mut()
336                    .map_or(ControlFlow::Break(()), |mut f| f(frame))
337            });
338            if flow.is_break() {
339                DRIVER.with(|d| {
340                    if let Some(c) = d.borrow_mut().consumers.get_mut(&id)
341                        && c.generation == generation
342                    {
343                        c.active = false;
344                        c.last = None;
345                    }
346                });
347            }
348        }
349    });
350    day_reactive::flush_now();
351    DRIVER.with(|d| {
352        if let Some(source) = d.borrow_mut().sources.get_mut(&root) {
353            source.dispatching = false;
354        }
355    });
356    reconcile(root);
357}
358
359/// Suspend display work when the app backgrounds; foreground resumes demand with a fresh delta.
360/// Desktop loss of keyboard focus alone does not suspend visible windows.
361pub(crate) fn lifecycle(phase: day_spec::Lifecycle) {
362    match phase {
363        day_spec::Lifecycle::DidEnterBackground => suspend(true),
364        day_spec::Lifecycle::WillEnterForeground | day_spec::Lifecycle::DidBecomeActive => {
365            suspend(false);
366        }
367        _ => {}
368    }
369}
370fn suspend(suspended: bool) {
371    let roots = DRIVER.with(|d| {
372        let mut d = d.borrow_mut();
373        if d.suspended == suspended {
374            return Vec::new();
375        }
376        d.suspended = suspended;
377        for c in d.consumers.values_mut() {
378            c.last = None;
379            c.generation += 1;
380        }
381        // A first subscription may have been created while suspended, before that window
382        // ever acquired a native source. Include its demand when foregrounding too.
383        d.sources
384            .keys()
385            .copied()
386            .chain(d.consumers.values().map(|c| c.root))
387            .collect::<std::collections::HashSet<_>>()
388            .into_iter()
389            .collect::<Vec<_>>()
390    });
391    for root in roots {
392        reconcile(root);
393    }
394}
395pub(crate) fn forget_window(root: RNode) {
396    let (cancel, removed) = DRIVER.with(|d| {
397        let mut d = d.borrow_mut();
398        let ids: Vec<_> = d
399            .consumers
400            .iter()
401            .filter(|(_, c)| c.root == root)
402            .map(|(&id, _)| id)
403            .collect();
404        let removed: Vec<_> = ids
405            .into_iter()
406            .filter_map(|id| d.consumers.remove(&id))
407            .collect();
408        (d.sources.remove(&root).and_then(|s| s.cancel), removed)
409    });
410    drop(removed);
411    if let Some(cancel) = cancel {
412        cancel();
413    }
414}
415
416/// Legacy `frame_clock` registration. New code should own a [`FrameHandle`].
417#[derive(Clone, Copy, Debug, PartialEq, Eq)]
418pub struct FrameConsumer(u64);
419pub fn add_frame_consumer(mut cb: impl FnMut(Duration) + 'static) -> FrameConsumer {
420    let mut first = true;
421    let handle = subscribe(move |frame| {
422        // Preserve the original first-frame and <=100ms simulation contract for existing games.
423        cb(if std::mem::take(&mut first) {
424            Duration::from_secs_f64(1.0 / 60.0)
425        } else {
426            frame.delta.min(Duration::from_millis(100))
427        });
428        ControlFlow::Continue(())
429    });
430    let id = handle.id;
431    std::mem::forget(handle);
432    FrameConsumer(id)
433}
434pub fn remove_frame_consumer(c: FrameConsumer) {
435    remove(c.0);
436}
437/// Number of active subscriptions and pending single-frame clients (paused handles excluded).
438#[must_use]
439pub fn frame_consumer_count() -> usize {
440    DRIVER.with(|d| d.borrow().consumers.values().filter(|c| c.active).count())
441}
442
443/// Backend callback registry. Native APIs carry integer tickets, never pointers to Rust closures:
444/// a cancelled or late native callback cannot dereference freed memory. UI-thread only.
445#[doc(hidden)]
446pub mod native {
447    use super::{FrameCallback, FrameStamp, NATIVE_CALLBACKS};
448    pub fn register(cb: FrameCallback) -> u64 {
449        NATIVE_CALLBACKS.with(|c| {
450            let mut c = c.borrow_mut();
451            c.0 += 1;
452            let id = c.0;
453            c.1.insert(id, cb);
454            id
455        })
456    }
457    pub fn cancel(id: u64) {
458        NATIVE_CALLBACKS.with(|c| c.borrow_mut().1.remove(&id));
459    }
460    pub fn deliver(id: u64, stamp: FrameStamp) {
461        let cb = NATIVE_CALLBACKS.with(|c| c.borrow_mut().1.remove(&id));
462        if let Some(cb) = cb {
463            day_spec::ffi_guard::contain((), || cb(stamp));
464        }
465    }
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use std::cell::Cell;
472    use std::collections::VecDeque;
473
474    struct Manual {
475        pending: Rc<RefCell<VecDeque<(RNode, FrameCallback)>>>,
476        requests: Rc<Cell<usize>>,
477        cancellations: Rc<Cell<usize>>,
478    }
479    impl Manual {
480        fn new() -> Self {
481            DRIVER.with(|d| *d.borrow_mut() = Driver::default());
482            let pending = Rc::new(RefCell::new(VecDeque::new()));
483            let requests = Rc::new(Cell::new(0));
484            let cancellations = Rc::new(Cell::new(0));
485            let (q, r, c) = (pending.clone(), requests.clone(), cancellations.clone());
486            install_frame_requester(move |root, cb| {
487                r.set(r.get() + 1);
488                q.borrow_mut().push_back((root, cb));
489                let c = c.clone();
490                Box::new(move || c.set(c.get() + 1))
491            });
492            Self {
493                pending,
494                requests,
495                cancellations,
496            }
497        }
498        fn fire(&self, ts: f64) {
499            let (_, cb) = self
500                .pending
501                .borrow_mut()
502                .pop_front()
503                .expect("pending frame");
504            cb(FrameStamp {
505                timestamp: ts,
506                target_timestamp: Some(ts + 1.0 / 120.0),
507            });
508        }
509        fn clock() -> FrameClock {
510            FrameClock::for_root(RNode::default())
511        }
512    }
513    #[test]
514    fn clients_share_one_request_and_idle_after_delivery() {
515        let m = Manual::new();
516        let seen = Rc::new(RefCell::new(Vec::new()));
517        let s = seen.clone();
518        let a = Manual::clock().request(move |f| s.borrow_mut().push(f));
519        let s = seen.clone();
520        let b = Manual::clock().request(move |f| s.borrow_mut().push(f));
521        assert_eq!(m.requests.get(), 1);
522        m.fire(10.0);
523        assert_eq!(seen.borrow().len(), 2);
524        assert_eq!(seen.borrow()[0], seen.borrow()[1]);
525        assert_eq!(seen.borrow()[0].delta, Duration::ZERO);
526        assert!(seen.borrow()[0].target_timestamp.is_some());
527        assert!(!a.is_active() && !b.is_active());
528        assert!(m.pending.borrow().is_empty());
529    }
530    #[test]
531    fn dropping_last_client_cancels_and_late_delivery_is_harmless() {
532        let m = Manual::new();
533        let a = Manual::clock().request(|_| panic!("cancelled callback ran"));
534        drop(a);
535        assert_eq!(m.cancellations.get(), 1);
536        m.fire(10.0); // emulate a callback already queued before native cancellation
537        assert_eq!(frame_consumer_count(), 0);
538        assert_eq!(m.requests.get(), 1);
539    }
540    #[test]
541    fn cancellation_during_dispatch_skips_the_later_callback() {
542        let m = Manual::new();
543        let later = Rc::new(RefCell::new(None::<FrameHandle>));
544        let l = later.clone();
545        let _first = Manual::clock().request(move |_| {
546            l.borrow_mut().take();
547        });
548        *later.borrow_mut() =
549            Some(Manual::clock().request(|_| panic!("cancelled during dispatch")));
550        m.fire(1.0);
551        assert!(m.pending.borrow().is_empty());
552    }
553    #[test]
554    fn requests_from_a_callback_run_on_the_next_frame() {
555        let m = Manual::new();
556        let later = Rc::new(RefCell::new(None::<FrameHandle>));
557        let l = later.clone();
558        let seen = Rc::new(Cell::new(false));
559        let s = seen.clone();
560        let clock = Manual::clock();
561        let _first = clock.request(move |_| {
562            *l.borrow_mut() = Some(clock.request(move |_| s.set(true)));
563        });
564        m.fire(1.0);
565        assert!(!seen.get());
566        assert_eq!(m.requests.get(), 2);
567        m.fire(2.0);
568        assert!(seen.get());
569    }
570    #[test]
571    fn timestamps_are_unclamped_and_resume_starts_a_new_baseline() {
572        let m = Manual::new();
573        let seen = Rc::new(RefCell::new(Vec::new()));
574        let s = seen.clone();
575        let handle = Manual::clock().subscribe(move |f| {
576            s.borrow_mut().push(f.delta);
577            ControlFlow::Continue(())
578        });
579        m.fire(1.0);
580        m.fire(1.75);
581        assert_eq!(seen.borrow()[1], Duration::from_millis(750));
582        handle.pause();
583        m.fire(2.0); // cancelled pending frame
584        handle.resume();
585        m.fire(50.0);
586        assert_eq!(seen.borrow()[2], Duration::ZERO);
587    }
588    #[test]
589    fn stopping_then_waking_a_subscription_does_not_poll() {
590        let m = Manual::new();
591        let calls = Rc::new(Cell::new(0));
592        let c = calls.clone();
593        let handle = Manual::clock().subscribe(move |_| {
594            c.set(c.get() + 1);
595            ControlFlow::Break(())
596        });
597        m.fire(1.0);
598        assert!(!handle.is_active());
599        assert!(m.pending.borrow().is_empty());
600        handle.resume();
601        handle.resume();
602        assert_eq!(m.requests.get(), 2);
603        m.fire(5.0);
604        assert_eq!(calls.get(), 2);
605    }
606    #[test]
607    fn windows_have_independent_native_sources() {
608        let m = Manual::new();
609        let mut roots = slotmap::SlotMap::<RNode, ()>::with_key();
610        let one = roots.insert(());
611        let two = roots.insert(());
612        let _a = FrameClock::for_root(one).request(|_| {});
613        let b = FrameClock::for_root(two).subscribe(|_| ControlFlow::Continue(()));
614        assert_eq!(m.requests.get(), 2);
615        assert_eq!(m.pending.borrow()[0].0, one);
616        assert_eq!(m.pending.borrow()[1].0, two);
617        forget_window(two);
618        assert!(!b.is_active());
619        m.fire(1.0);
620        m.fire(1.0);
621        assert!(m.pending.borrow().is_empty());
622    }
623    #[test]
624    fn background_suspends_and_foreground_resets_delta() {
625        let m = Manual::new();
626        let seen = Rc::new(RefCell::new(Vec::new()));
627        let s = seen.clone();
628        let _handle = Manual::clock().subscribe(move |f| {
629            s.borrow_mut().push(f.delta);
630            ControlFlow::Continue(())
631        });
632        m.fire(1.0);
633        lifecycle(day_spec::Lifecycle::DidEnterBackground);
634        m.fire(2.0);
635        assert_eq!(seen.borrow().len(), 1);
636        lifecycle(day_spec::Lifecycle::WillEnterForeground);
637        m.fire(80.0);
638        assert_eq!(seen.borrow()[1], Duration::ZERO);
639    }
640    #[test]
641    fn malformed_and_backward_stamps_do_not_poison_the_clock() {
642        let m = Manual::new();
643        let seen = Rc::new(RefCell::new(Vec::new()));
644        let s = seen.clone();
645        let _handle = Manual::clock().subscribe(move |f| {
646            s.borrow_mut().push(f.delta);
647            ControlFlow::Continue(())
648        });
649        m.fire(f64::NAN);
650        m.fire(5.0);
651        m.fire(4.0);
652        m.fire(5.25);
653        assert_eq!(
654            *seen.borrow(),
655            vec![Duration::ZERO, Duration::ZERO, Duration::from_millis(250)]
656        );
657    }
658
659    #[test]
660    fn first_subscription_created_in_background_starts_on_foreground() {
661        let m = Manual::new();
662        lifecycle(day_spec::Lifecycle::DidEnterBackground);
663        let seen = Rc::new(Cell::new(false));
664        let s = seen.clone();
665        let _handle = Manual::clock().request(move |frame| {
666            assert_eq!(frame.delta, Duration::ZERO);
667            s.set(true);
668        });
669        assert_eq!(m.requests.get(), 0);
670        lifecycle(day_spec::Lifecycle::WillEnterForeground);
671        assert_eq!(m.requests.get(), 1);
672        m.fire(20.0);
673        assert!(seen.get());
674    }
675    #[test]
676    fn cancelled_native_tickets_can_never_run_a_new_callback() {
677        let calls = Rc::new(Cell::new(0));
678        let first = native::register(Box::new(|_| panic!("stale native ticket")));
679        native::cancel(first);
680        let c = calls.clone();
681        let second = native::register(Box::new(move |_| c.set(c.get() + 1)));
682        native::deliver(first, FrameStamp::new(1.0));
683        native::deliver(second, FrameStamp::new(1.0));
684        native::deliver(second, FrameStamp::new(2.0));
685        assert_eq!(calls.get(), 1);
686    }
687
688    #[test]
689    fn dropping_callbacks_can_cancel_other_handles() {
690        let m = Manual::new();
691        let inner = Manual::clock().request(|_| panic!("cancelled inner callback"));
692        let outer = Manual::clock().subscribe(move |_| {
693            let _ = &inner;
694            ControlFlow::Continue(())
695        });
696        drop(outer);
697        assert_eq!(frame_consumer_count(), 0);
698        m.fire(1.0);
699    }
700
701    #[test]
702    fn closing_a_window_drops_nested_handles_outside_the_driver_borrow() {
703        let m = Manual::new();
704        let inner = Manual::clock().request(|_| panic!("closed window"));
705        let _outer = Manual::clock().subscribe(move |_| {
706            let _ = &inner;
707            ControlFlow::Continue(())
708        });
709        forget_window(Manual::clock().root);
710        assert_eq!(frame_consumer_count(), 0);
711        m.fire(1.0);
712    }
713
714    #[test]
715    fn handles_drop_during_core_tls_teardown() {
716        const CHILD: &str = "DAY_CORE_FRAME_TEARDOWN_CHILD";
717        if std::env::var_os(CHILD).is_some() {
718            struct TeardownHandle {
719                handle: Option<FrameHandle>,
720                dropped: std::sync::mpsc::Sender<()>,
721            }
722            impl Drop for TeardownHandle {
723                fn drop(&mut self) {
724                    assert!(crate::try_tls_root(|_| ()).is_err());
725                    drop(self.handle.take());
726                    self.dropped.send(()).unwrap();
727                }
728            }
729            let (dropped, observed) = std::sync::mpsc::channel();
730            std::thread::spawn(move || {
731                let _m = Manual::new();
732                let paused = Manual::clock().subscribe(|_| ControlFlow::Continue(()));
733                paused.pause();
734                let held = TeardownHandle {
735                    handle: Some(paused),
736                    dropped: dropped.clone(),
737                };
738                let active = Manual::clock().subscribe(move |_| {
739                    let _ = &held;
740                    ControlFlow::Continue(())
741                });
742                let held = TeardownHandle {
743                    handle: Some(active),
744                    dropped,
745                };
746                // The driver owns the paused handle's capture; the native registry owns
747                // the active handle's capture. Both drop with core TLS unavailable, before
748                // and after the driver finishes destruction, regardless of TLS key order.
749                let _ = native::register(Box::new(move |_| drop(held)));
750            })
751            .join()
752            .unwrap();
753            for _ in 0..2 {
754                observed
755                    .recv_timeout(Duration::from_secs(5))
756                    .expect("frame handle was not dropped during thread shutdown");
757            }
758            return;
759        }
760        // A panic in a TLS destructor aborts the process, so isolate the regression.
761        let output = std::process::Command::new(std::env::current_exe().unwrap())
762            .args([
763                "--exact",
764                "frame::tests::handles_drop_during_core_tls_teardown",
765                "--nocapture",
766            ])
767            .env(CHILD, "1")
768            .output()
769            .unwrap();
770        assert!(
771            output.status.success(),
772            "{}",
773            String::from_utf8_lossy(&output.stderr)
774        );
775    }
776}