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 and continuous subscriptions. 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/// Whether this thread's frame registry still exists. At thread teardown it may be gone before
417/// the last frame callback is dropped; a destructor asks before touching reactive state.
418pub(crate) fn alive() -> bool {
419    DRIVER.try_with(|_| ()).is_ok()
420}
421/// Number of active subscriptions and pending single-frame clients (paused handles excluded).
422#[must_use]
423pub fn frame_consumer_count() -> usize {
424    DRIVER.with(|d| d.borrow().consumers.values().filter(|c| c.active).count())
425}
426
427/// Backend callback registry. Native APIs carry integer tickets, never pointers to Rust closures:
428/// a cancelled or late native callback cannot dereference freed memory. UI-thread only.
429#[doc(hidden)]
430pub mod native {
431    use super::{FrameCallback, FrameStamp, NATIVE_CALLBACKS};
432    pub fn register(cb: FrameCallback) -> u64 {
433        NATIVE_CALLBACKS.with(|c| {
434            let mut c = c.borrow_mut();
435            c.0 += 1;
436            let id = c.0;
437            c.1.insert(id, cb);
438            id
439        })
440    }
441    pub fn cancel(id: u64) {
442        NATIVE_CALLBACKS.with(|c| c.borrow_mut().1.remove(&id));
443    }
444    pub fn deliver(id: u64, stamp: FrameStamp) {
445        let cb = NATIVE_CALLBACKS.with(|c| c.borrow_mut().1.remove(&id));
446        if let Some(cb) = cb {
447            day_spec::ffi_guard::contain((), || cb(stamp));
448        }
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455    use std::cell::Cell;
456    use std::collections::VecDeque;
457
458    struct Manual {
459        pending: Rc<RefCell<VecDeque<(RNode, FrameCallback)>>>,
460        requests: Rc<Cell<usize>>,
461        cancellations: Rc<Cell<usize>>,
462    }
463    impl Manual {
464        fn new() -> Self {
465            DRIVER.with(|d| *d.borrow_mut() = Driver::default());
466            let pending = Rc::new(RefCell::new(VecDeque::new()));
467            let requests = Rc::new(Cell::new(0));
468            let cancellations = Rc::new(Cell::new(0));
469            let (q, r, c) = (pending.clone(), requests.clone(), cancellations.clone());
470            install_frame_requester(move |root, cb| {
471                r.set(r.get() + 1);
472                q.borrow_mut().push_back((root, cb));
473                let c = c.clone();
474                Box::new(move || c.set(c.get() + 1))
475            });
476            Self {
477                pending,
478                requests,
479                cancellations,
480            }
481        }
482        fn fire(&self, ts: f64) {
483            let (_, cb) = self
484                .pending
485                .borrow_mut()
486                .pop_front()
487                .expect("pending frame");
488            cb(FrameStamp {
489                timestamp: ts,
490                target_timestamp: Some(ts + 1.0 / 120.0),
491            });
492        }
493        fn clock() -> FrameClock {
494            FrameClock::for_root(RNode::default())
495        }
496    }
497    #[test]
498    fn clients_share_one_request_and_idle_after_delivery() {
499        let m = Manual::new();
500        let seen = Rc::new(RefCell::new(Vec::new()));
501        let s = seen.clone();
502        let a = Manual::clock().request(move |f| s.borrow_mut().push(f));
503        let s = seen.clone();
504        let b = Manual::clock().request(move |f| s.borrow_mut().push(f));
505        assert_eq!(m.requests.get(), 1);
506        m.fire(10.0);
507        assert_eq!(seen.borrow().len(), 2);
508        assert_eq!(seen.borrow()[0], seen.borrow()[1]);
509        assert_eq!(seen.borrow()[0].delta, Duration::ZERO);
510        assert!(seen.borrow()[0].target_timestamp.is_some());
511        assert!(!a.is_active() && !b.is_active());
512        assert!(m.pending.borrow().is_empty());
513    }
514    #[test]
515    fn dropping_last_client_cancels_and_late_delivery_is_harmless() {
516        let m = Manual::new();
517        let a = Manual::clock().request(|_| panic!("cancelled callback ran"));
518        drop(a);
519        assert_eq!(m.cancellations.get(), 1);
520        m.fire(10.0); // emulate a callback already queued before native cancellation
521        assert_eq!(frame_consumer_count(), 0);
522        assert_eq!(m.requests.get(), 1);
523    }
524    #[test]
525    fn cancellation_during_dispatch_skips_the_later_callback() {
526        let m = Manual::new();
527        let later = Rc::new(RefCell::new(None::<FrameHandle>));
528        let l = later.clone();
529        let _first = Manual::clock().request(move |_| {
530            l.borrow_mut().take();
531        });
532        *later.borrow_mut() =
533            Some(Manual::clock().request(|_| panic!("cancelled during dispatch")));
534        m.fire(1.0);
535        assert!(m.pending.borrow().is_empty());
536    }
537    #[test]
538    fn requests_from_a_callback_run_on_the_next_frame() {
539        let m = Manual::new();
540        let later = Rc::new(RefCell::new(None::<FrameHandle>));
541        let l = later.clone();
542        let seen = Rc::new(Cell::new(false));
543        let s = seen.clone();
544        let clock = Manual::clock();
545        let _first = clock.request(move |_| {
546            *l.borrow_mut() = Some(clock.request(move |_| s.set(true)));
547        });
548        m.fire(1.0);
549        assert!(!seen.get());
550        assert_eq!(m.requests.get(), 2);
551        m.fire(2.0);
552        assert!(seen.get());
553    }
554    #[test]
555    fn timestamps_are_unclamped_and_resume_starts_a_new_baseline() {
556        let m = Manual::new();
557        let seen = Rc::new(RefCell::new(Vec::new()));
558        let s = seen.clone();
559        let handle = Manual::clock().subscribe(move |f| {
560            s.borrow_mut().push(f.delta);
561            ControlFlow::Continue(())
562        });
563        m.fire(1.0);
564        m.fire(1.75);
565        assert_eq!(seen.borrow()[1], Duration::from_millis(750));
566        handle.pause();
567        m.fire(2.0); // cancelled pending frame
568        handle.resume();
569        m.fire(50.0);
570        assert_eq!(seen.borrow()[2], Duration::ZERO);
571    }
572    #[test]
573    fn stopping_then_waking_a_subscription_does_not_poll() {
574        let m = Manual::new();
575        let calls = Rc::new(Cell::new(0));
576        let c = calls.clone();
577        let handle = Manual::clock().subscribe(move |_| {
578            c.set(c.get() + 1);
579            ControlFlow::Break(())
580        });
581        m.fire(1.0);
582        assert!(!handle.is_active());
583        assert!(m.pending.borrow().is_empty());
584        handle.resume();
585        handle.resume();
586        assert_eq!(m.requests.get(), 2);
587        m.fire(5.0);
588        assert_eq!(calls.get(), 2);
589    }
590    #[test]
591    fn windows_have_independent_native_sources() {
592        let m = Manual::new();
593        let mut roots = slotmap::SlotMap::<RNode, ()>::with_key();
594        let one = roots.insert(());
595        let two = roots.insert(());
596        let _a = FrameClock::for_root(one).request(|_| {});
597        let b = FrameClock::for_root(two).subscribe(|_| ControlFlow::Continue(()));
598        assert_eq!(m.requests.get(), 2);
599        assert_eq!(m.pending.borrow()[0].0, one);
600        assert_eq!(m.pending.borrow()[1].0, two);
601        forget_window(two);
602        assert!(!b.is_active());
603        m.fire(1.0);
604        m.fire(1.0);
605        assert!(m.pending.borrow().is_empty());
606    }
607    #[test]
608    fn background_suspends_and_foreground_resets_delta() {
609        let m = Manual::new();
610        let seen = Rc::new(RefCell::new(Vec::new()));
611        let s = seen.clone();
612        let _handle = Manual::clock().subscribe(move |f| {
613            s.borrow_mut().push(f.delta);
614            ControlFlow::Continue(())
615        });
616        m.fire(1.0);
617        lifecycle(day_spec::Lifecycle::DidEnterBackground);
618        m.fire(2.0);
619        assert_eq!(seen.borrow().len(), 1);
620        lifecycle(day_spec::Lifecycle::WillEnterForeground);
621        m.fire(80.0);
622        assert_eq!(seen.borrow()[1], Duration::ZERO);
623    }
624    #[test]
625    fn malformed_and_backward_stamps_do_not_poison_the_clock() {
626        let m = Manual::new();
627        let seen = Rc::new(RefCell::new(Vec::new()));
628        let s = seen.clone();
629        let _handle = Manual::clock().subscribe(move |f| {
630            s.borrow_mut().push(f.delta);
631            ControlFlow::Continue(())
632        });
633        m.fire(f64::NAN);
634        m.fire(5.0);
635        m.fire(4.0);
636        m.fire(5.25);
637        assert_eq!(
638            *seen.borrow(),
639            vec![Duration::ZERO, Duration::ZERO, Duration::from_millis(250)]
640        );
641    }
642
643    #[test]
644    fn first_subscription_created_in_background_starts_on_foreground() {
645        let m = Manual::new();
646        lifecycle(day_spec::Lifecycle::DidEnterBackground);
647        let seen = Rc::new(Cell::new(false));
648        let s = seen.clone();
649        let _handle = Manual::clock().request(move |frame| {
650            assert_eq!(frame.delta, Duration::ZERO);
651            s.set(true);
652        });
653        assert_eq!(m.requests.get(), 0);
654        lifecycle(day_spec::Lifecycle::WillEnterForeground);
655        assert_eq!(m.requests.get(), 1);
656        m.fire(20.0);
657        assert!(seen.get());
658    }
659    #[test]
660    fn cancelled_native_tickets_can_never_run_a_new_callback() {
661        let calls = Rc::new(Cell::new(0));
662        let first = native::register(Box::new(|_| panic!("stale native ticket")));
663        native::cancel(first);
664        let c = calls.clone();
665        let second = native::register(Box::new(move |_| c.set(c.get() + 1)));
666        native::deliver(first, FrameStamp::new(1.0));
667        native::deliver(second, FrameStamp::new(1.0));
668        native::deliver(second, FrameStamp::new(2.0));
669        assert_eq!(calls.get(), 1);
670    }
671
672    #[test]
673    fn dropping_callbacks_can_cancel_other_handles() {
674        let m = Manual::new();
675        let inner = Manual::clock().request(|_| panic!("cancelled inner callback"));
676        let outer = Manual::clock().subscribe(move |_| {
677            let _ = &inner;
678            ControlFlow::Continue(())
679        });
680        drop(outer);
681        assert_eq!(frame_consumer_count(), 0);
682        m.fire(1.0);
683    }
684
685    #[test]
686    fn closing_a_window_drops_nested_handles_outside_the_driver_borrow() {
687        let m = Manual::new();
688        let inner = Manual::clock().request(|_| panic!("closed window"));
689        let _outer = Manual::clock().subscribe(move |_| {
690            let _ = &inner;
691            ControlFlow::Continue(())
692        });
693        forget_window(Manual::clock().root);
694        assert_eq!(frame_consumer_count(), 0);
695        m.fire(1.0);
696    }
697
698    #[test]
699    fn handles_drop_during_core_tls_teardown() {
700        const CHILD: &str = "DAY_CORE_FRAME_TEARDOWN_CHILD";
701        if std::env::var_os(CHILD).is_some() {
702            struct TeardownHandle {
703                handle: Option<FrameHandle>,
704                dropped: std::sync::mpsc::Sender<()>,
705            }
706            impl Drop for TeardownHandle {
707                fn drop(&mut self) {
708                    assert!(crate::try_tls_root(|_| ()).is_err());
709                    drop(self.handle.take());
710                    self.dropped.send(()).unwrap();
711                }
712            }
713            let (dropped, observed) = std::sync::mpsc::channel();
714            std::thread::spawn(move || {
715                let _m = Manual::new();
716                let paused = Manual::clock().subscribe(|_| ControlFlow::Continue(()));
717                paused.pause();
718                let held = TeardownHandle {
719                    handle: Some(paused),
720                    dropped: dropped.clone(),
721                };
722                let active = Manual::clock().subscribe(move |_| {
723                    let _ = &held;
724                    ControlFlow::Continue(())
725                });
726                let held = TeardownHandle {
727                    handle: Some(active),
728                    dropped,
729                };
730                // The driver owns the paused handle's capture; the native registry owns
731                // the active handle's capture. Both drop with core TLS unavailable, before
732                // and after the driver finishes destruction, regardless of TLS key order.
733                let _ = native::register(Box::new(move |_| drop(held)));
734            })
735            .join()
736            .unwrap();
737            for _ in 0..2 {
738                observed
739                    .recv_timeout(Duration::from_secs(5))
740                    .expect("frame handle was not dropped during thread shutdown");
741            }
742            return;
743        }
744        // A panic in a TLS destructor aborts the process, so isolate the regression.
745        let output = std::process::Command::new(std::env::current_exe().unwrap())
746            .args([
747                "--exact",
748                "frame::tests::handles_drop_during_core_tls_teardown",
749                "--nocapture",
750            ])
751            .env(CHILD, "1")
752            .output()
753            .unwrap();
754        assert!(
755            output.status.success(),
756            "{}",
757            String::from_utf8_lossy(&output.stderr)
758        );
759    }
760}