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