Skip to main content

waft_foundation/
app.rs

1//! The one [`App`] and the arena of [`Handle`]s inside it. Not a Dart file.
2
3use std::any::type_name;
4use std::collections::{HashMap, VecDeque};
5use std::fmt::{self, Debug};
6use std::marker::PhantomData;
7use std::ops::Receiver;
8use std::rc::{Rc, Weak};
9use std::time::Duration;
10
11use slotmap::new_key_type;
12use waft_embedder::{
13    ClipboardEvent, DragReport, EditCommand, MenuId, NotificationActivation, OpenRequest,
14    PlatformRef, RequestId, TrayIconEvent, TrayIconId, ViewError, ViewFocusEvent, ViewId,
15};
16
17use crate::app_cell::{AppCell, AsyncApp};
18use crate::change_notifier::Listener;
19use crate::entity::EntityMap;
20use crate::executor::{ExecutorHandle, ForegroundExecutor, Task};
21use crate::handle_map::HandleMap;
22pub use crate::handle_map::{AnyRef, OptionRetained, Ref, Retained};
23use crate::timers::{Timer, TimerMode, Timers};
24
25/// Drain budget for one [`App::drain_microtasks`]: two callbacks scheduling
26/// each other forever must fail loud, not starve the event loop. Not a Dart
27/// or Flutter constant — the isolate drains until empty; a cycle there hangs.
28const MICROTASK_BUDGET: usize = 100_000;
29
30new_key_type! {
31    /// Untyped [`Handle`]. For a reference that may point at more than one type;
32    /// [`App::handle`] narrows it.
33    ///
34    /// A free bumps the generation, so a leftover id does not silently name the next occupant.
35    pub struct HandleId;
36}
37
38/// A Dart object, as far as Rust ownership is concerned, named without keeping it.
39///
40/// Flutter objects form cycles — an element names its widget and its render object, a notifier
41/// names its listeners, a listener often names the notifier. Dart allows that because the GC
42/// owns the objects. Here the object lives in [`App`] while a [`Ref`] keeps it (or the tree code,
43/// for a tree node); this is the id that names it.
44///
45/// `Copy` and owns nothing: the method receiver, the form layout and paint walk with, and what a
46/// field holds when it points back at what holds its object (a parent, an owner). Valid while
47/// something keeps the object: one on the stack is good until the next checkpoint, and one kept
48/// past it is a [`Ref`] or is checked with [`upgrade`](Handle::upgrade) or [`App::contains`].
49/// Stale is detected by generation.
50///
51/// Point access, not a lease: [`App::get`] / [`App::get_mut`] for one field, then drop the borrow
52/// before any call that can run framework code. Holding the object out of the arena for a whole
53/// pass (shaft-rs-next) meant a layout callback could not re-enter the node it was laying out.
54///
55/// [`App::get`] panics on stale — a typed handle is a promise the entry is live. [`App::handle`]
56/// returns [`None`] for an id that might be dead or the wrong type.
57///
58/// `PhantomData<fn() -> T>` so `Handle<T>: Copy` even when `T` is not.
59pub struct Handle<T> {
60    id: HandleId,
61    state: PhantomData<fn() -> T>,
62}
63
64impl<T> Handle<T> {
65    /// Unchecked. [`App::create`] mints these; [`App::handle`] is the checked path and
66    /// [`from_id`](Self::from_id) the trusted one.
67    pub(crate) fn new(id: HandleId) -> Handle<T> {
68        Handle {
69            id,
70            state: PhantomData,
71        }
72    }
73
74    /// Wraps an id that was minted for `T` without looking at the entry. The check is deferred to
75    /// [`App::get`], which panics on a stale or wrong-typed id. For a type-erased handle that
76    /// reconstructs the typed handle it was made from.
77    pub fn from_id(id: HandleId) -> Handle<T> {
78        Handle::new(id)
79    }
80
81    pub fn id(self) -> HandleId {
82        self.id
83    }
84}
85
86impl<T: 'static> Handle<T> {
87    /// A [`Ref`] while something still keeps the object, `None` once it is freed or its last
88    /// keeper has let go: GPUI's `WeakEntity::upgrade`.
89    ///
90    /// # Panics
91    ///
92    /// If the entry holds another type.
93    pub fn upgrade(self, app: &App) -> Option<Ref<T>> {
94        app.handles.upgrade(self)
95    }
96
97    /// A [`Ref`] to an object something is known to keep: an object keeping itself in a field
98    /// of its own or in a closure it stores, while its owner holds it.
99    ///
100    /// # Panics
101    ///
102    /// If nothing keeps the object, naming its type and where it was created, or with the
103    /// stale-read message if it is freed.
104    #[track_caller]
105    pub fn keep(self, app: &App) -> Ref<T> {
106        Retained::keep(app, self)
107    }
108}
109
110impl HandleId {
111    /// Dart's `identityHashCode`, as diagnostics show an object (`RenderPadding#00007`): the
112    /// slot the object holds in the arena, which no two live objects share.
113    pub fn identity_hash(self) -> u64 {
114        slotmap::Key::data(&self).as_ffi() & 0xFFFF_FFFF
115    }
116
117    /// The id as one number: its slot and generation, which name this object and no later
118    /// occupant of its slot. What a client is handed to name an object back, as the widget
119    /// inspector's ids are.
120    pub fn to_bits(self) -> u64 {
121        slotmap::Key::data(&self).as_ffi()
122    }
123
124    /// The id [`to_bits`](Self::to_bits) gave. A number that names no live object gives an id
125    /// that finds none.
126    pub fn from_bits(bits: u64) -> HandleId {
127        slotmap::KeyData::from_ffi(bits).into()
128    }
129
130    /// An [`AnyRef`] while something still keeps the object; see [`Handle::upgrade`].
131    pub fn upgrade(self, app: &App) -> Option<AnyRef> {
132        app.handles.upgrade_id(self)
133    }
134
135    /// An [`AnyRef`] to an object something is known to keep; see [`Handle::keep`].
136    #[track_caller]
137    pub fn keep(self, app: &App) -> AnyRef {
138        Retained::keep(app, self)
139    }
140}
141
142impl<T> Clone for Handle<T> {
143    fn clone(&self) -> Handle<T> {
144        *self
145    }
146}
147
148impl<T> Copy for Handle<T> {}
149
150/// An arena object's methods take `self: Handle<Self>`: the handle is the receiver, the
151/// object is `app.get(self)`.
152impl<T> Receiver for Handle<T> {
153    type Target = T;
154}
155
156impl<T> PartialEq for Handle<T> {
157    fn eq(&self, other: &Handle<T>) -> bool {
158        self.id == other.id
159    }
160}
161
162impl<T> Eq for Handle<T> {}
163
164impl<T> std::hash::Hash for Handle<T> {
165    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
166        self.id.hash(state)
167    }
168}
169
170impl<T> Debug for Handle<T> {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        write!(f, "Handle<{}>({:?})", type_name::<T>(), self.id)
173    }
174}
175
176impl<T> From<Handle<T>> for HandleId {
177    fn from(handle: Handle<T>) -> HandleId {
178        handle.id
179    }
180}
181
182/// Owns every Flutter object. Callbacks receive `&mut App` plus a [`Handle`] to themselves.
183///
184/// Lives in an [`AppCell`], which is what the shell and the tests hold; a task reaches it
185/// through [`AsyncApp`]. Private and `#[non_exhaustive]`: scheduler, timers, and further
186/// arenas are additive.
187#[non_exhaustive]
188pub struct App {
189    /// The cell this App lives in — gpui's `App::this`.
190    this: Weak<AppCell>,
191    handles: HandleMap,
192    pub(crate) entities: EntityMap,
193    /// The App is what keeps a singleton.
194    singletons: HashMap<std::any::TypeId, AnyRef>,
195    /// The receivers of the skipped tear-offs already reported, so each is reported once.
196    #[cfg(debug_assertions)]
197    skipped_tear_off_receivers: std::collections::HashSet<HandleId>,
198    #[cfg(debug_assertions)]
199    skipped_tear_offs: Vec<String>,
200    microtasks: VecDeque<Listener>,
201    timers: Timers,
202    /// The debug flags set on this app ([`set_debug_flag`](App::set_debug_flag)); one absent is
203    /// off.
204    debug_flags: HashMap<std::any::TypeId, bool>,
205    executor: ForegroundExecutor,
206    platform: PlatformRef,
207    /// The host's threads, told when to wake this application for its next timer.
208    dispatcher: std::sync::Arc<dyn waft_embedder::Dispatcher>,
209    platform_callbacks: PlatformCallbacks,
210    open_requests: UntilHandled<OpenRequest>,
211    notification_activations: UntilHandled<NotificationActivation>,
212}
213
214/// A debug flag an [`App`] keeps: a marker type per Dart `debug…` bool, declared in the crate
215/// that reads it (`waft_rendering::DebugPaintSizeEnabled`), so this crate needs to know none of
216/// them. Each crate keeps Dart's name as a function over the app.
217pub trait DebugFlag: 'static {
218    /// The flag's value until it is set: Dart's initializer, `false` for most.
219    const DEFAULT: bool = false;
220}
221
222/// What hears one kind of what the system asks of the app, and what it asked before there was a
223/// handler, which waits for one, as a launch's requests do.
224struct UntilHandled<T> {
225    handler: Option<Handler<T>>,
226    waiting: Vec<T>,
227}
228
229impl<T> Default for UntilHandled<T> {
230    fn default() -> UntilHandled<T> {
231        UntilHandled {
232            handler: None,
233            waiting: Vec::new(),
234        }
235    }
236}
237
238/// The app's handler for one kind of what the system asks of it.
239type Handler<T> = Rc<dyn Fn(&mut App, T)>;
240
241/// The app's handler for the system's requests to open files and links.
242pub type OpenRequestedCallback = Rc<dyn Fn(&mut App, OpenRequest)>;
243
244/// The app's handler for the clicks on its notifications.
245pub type NotificationActivatedCallback = Rc<dyn Fn(&mut App, NotificationActivation)>;
246
247/// The callbacks the framework assigns onto dart:ui's `PlatformDispatcher`
248/// (`onPlatformBrightnessChanged`, `onLocaleChanged`). The host's half of the dispatcher
249/// is the `Platform` the `App` holds; this is the half the framework sets and the host's
250/// client invokes.
251#[derive(Default)]
252pub struct PlatformCallbacks {
253    pub on_platform_brightness_changed: Option<Listener>,
254    pub on_locale_changed: Option<Listener>,
255    /// Flutter `PlatformDispatcher.onViewFocusChange`.
256    pub on_view_focus_change: Option<ViewFocusChangeCallback>,
257    /// What is dragged from outside the application over a view; no Flutter counterpart.
258    pub on_drag: Option<DragCallback>,
259    /// The user copied, cut or pasted in a view through the platform's own command; no Flutter
260    /// counterpart.
261    pub on_clipboard_event: Option<ClipboardEventCallback>,
262    /// The user chose an edit command for a view from the platform's own Edit menu; no Flutter
263    /// counterpart.
264    pub on_edit_command: Option<EditCommandCallback>,
265    /// The user chose an item of the app's menu bar. Flutter's `Menu.selectedCallback` on the
266    /// `flutter/menu` channel, which `DefaultPlatformMenuDelegate` handles.
267    pub on_menu_selected: Option<MenuSelectedCallback>,
268    /// The user chose an item of the Dock icon's menu; no Flutter counterpart, and the app's to
269    /// set.
270    pub on_dock_menu_selected: Option<MenuSelectedCallback>,
271    /// Something happened to one of the app's tray icons; no Flutter counterpart, and the app's to
272    /// set.
273    pub on_tray_icon_event: Option<TrayIconEventCallback>,
274    /// The user asked to go back in a view. Answers whether the application went back there.
275    /// Flutter's `popRoute` on `SystemChannels.navigation`, which names no view.
276    pub on_pop_route: Option<PopRouteCallback>,
277    /// The platform added a view: one the platform gave, or one the app asked for. Flutter's
278    /// `_addView` tells it only as `onMetricsChanged`.
279    pub on_view_added: Option<ViewChangeCallback>,
280    /// A view went.
281    pub on_view_removed: Option<ViewChangeCallback>,
282    /// The user asked to close a view. Flutter's engine reports it to the window's controller.
283    pub on_view_close_requested: Option<ViewCloseRequestedCallback>,
284    /// A view's window was minimized or restored, became occluded or shown, or moved. Flutter's
285    /// engine reports it to the window's controller.
286    pub on_window_changed: Option<WindowChangedCallback>,
287    /// A request for a view got no view.
288    pub on_view_request_failed: Option<ViewRequestFailedCallback>,
289}
290
291/// Flutter `PlatformDispatcher.onViewFocusChange`.
292pub type ViewFocusChangeCallback = Rc<dyn Fn(&mut App, ViewFocusEvent)>;
293
294/// The framework's handler for `EmbedderClient::drag_report`.
295pub type DragCallback = Rc<dyn Fn(&mut App, DragReport)>;
296
297/// The framework's handler for `EmbedderClient::clipboard_event`.
298pub type ClipboardEventCallback = Rc<dyn Fn(&mut App, ViewId, ClipboardEvent)>;
299
300/// The framework's handler for `EmbedderClient::edit_command`.
301pub type EditCommandCallback = Rc<dyn Fn(&mut App, ViewId, EditCommand)>;
302
303/// The handler for `EmbedderClient::menu_selected` and `dock_menu_selected`.
304pub type MenuSelectedCallback = Rc<dyn Fn(&mut App, MenuId)>;
305
306/// The app's handler for `EmbedderClient::tray_icon_event`.
307pub type TrayIconEventCallback = Rc<dyn Fn(&mut App, TrayIconId, TrayIconEvent)>;
308
309/// The framework's handler for `EmbedderClient::pop_route`.
310pub type PopRouteCallback = Rc<dyn Fn(&mut App, ViewId) -> bool>;
311
312/// The framework's handler for `EmbedderClient::view_added` and `view_removed`.
313pub type ViewChangeCallback = Rc<dyn Fn(&mut App, ViewId)>;
314
315/// The framework's handler for `EmbedderClient::view_close_requested`.
316pub type ViewCloseRequestedCallback = Rc<dyn Fn(&mut App, ViewId)>;
317
318/// The framework's handler for `EmbedderClient::window_changed`.
319pub type WindowChangedCallback = Rc<dyn Fn(&mut App, ViewId)>;
320
321/// The framework's handler for `EmbedderClient::view_request_failed`.
322pub type ViewRequestFailedCallback = Rc<dyn Fn(&mut App, RequestId, ViewError)>;
323
324impl App {
325    pub(crate) fn build(
326        this: Weak<AppCell>,
327        platform: PlatformRef,
328        executor: ForegroundExecutor,
329    ) -> App {
330        App {
331            this,
332            handles: HandleMap::new(),
333            entities: EntityMap::new(),
334            singletons: HashMap::new(),
335            #[cfg(debug_assertions)]
336            skipped_tear_off_receivers: std::collections::HashSet::new(),
337            #[cfg(debug_assertions)]
338            skipped_tear_offs: Vec::new(),
339            microtasks: VecDeque::new(),
340            timers: Timers::default(),
341            debug_flags: HashMap::new(),
342            executor,
343            dispatcher: platform.dispatcher(),
344            platform,
345            platform_callbacks: PlatformCallbacks::default(),
346            open_requests: UntilHandled::default(),
347            notification_activations: UntilHandled::default(),
348        }
349    }
350
351    /// The executor's polling side, for the cell's checkpoint.
352    pub(crate) fn executor_handle(&self) -> ExecutorHandle {
353        self.executor.handle()
354    }
355
356    /// This App as a task sees it: the handle an `async` body captures across its `await`s.
357    pub fn to_async(&self) -> AsyncApp {
358        AsyncApp::new(self.this.clone(), self.executor.handle())
359    }
360
361    /// Queues `f` as a task on this App: the continuation of a Dart `async` body.
362    ///
363    /// Dart runs an `async` body synchronously up to its first `await`; port that prefix
364    /// inline — including the call whose future is awaited — and spawn only what follows the
365    /// `await`. The continuation first runs at the next [`AppCell::checkpoint`], the end of
366    /// the current platform event, and thereafter at the checkpoint after whatever it awaited
367    /// completed; it cannot run inline, since the caller holds the App it would borrow.
368    ///
369    /// The returned [`Task`] is the continuation's future; dropping it does not cancel it.
370    pub fn spawn<R: 'static>(&self, f: impl AsyncFnOnce(&mut AsyncApp) -> R + 'static) -> Task<R> {
371        let mut cx = self.to_async();
372        self.executor.spawn(async move { f(&mut cx).await })
373    }
374
375    /// Runs `work` off the main thread, on the host's dispatcher, and answers its result as a
376    /// task: dart:isolate's `Isolate.run`. The task resolves at a checkpoint after the work is
377    /// done, since the executor wakes the host for it, and a panic in `work` resumes in
378    /// whoever awaits the task, as `Isolate.run` rethrows the isolate's error.
379    pub fn run_in_background<T: Send + 'static>(
380        &self,
381        work: impl FnOnce() -> T + Send + 'static,
382    ) -> Task<T> {
383        self.executor.run_in_background(work)
384    }
385
386    pub fn platform(&self) -> PlatformRef {
387        Rc::clone(&self.platform)
388    }
389
390    /// The dispatcher callbacks the framework has assigned.
391    pub fn platform_callbacks(&self) -> &PlatformCallbacks {
392        &self.platform_callbacks
393    }
394
395    pub fn platform_callbacks_mut(&mut self) -> &mut PlatformCallbacks {
396        &mut self.platform_callbacks
397    }
398
399    /// Sets what hears the system's requests to open files and links
400    /// (`EmbedderClient::open_requested`), and hands it at once the requests that came before it
401    /// was set, as a launch's do; with `None`, later requests wait for the next handler. No
402    /// Flutter counterpart: Flutter's embedders hand these to their plugins.
403    pub fn set_open_requested_handler(&mut self, handler: Option<OpenRequestedCallback>) {
404        self.set_handler(|app| &mut app.open_requests, handler);
405    }
406
407    /// Asks the app to open `request`: the handler hears it, or it waits for one. The host calls it
408    /// with what the system hands over (`EmbedderClient::open_requested`); the app calls it with
409    /// the files it decides its own command line names, at launch or as a later launch passes it
410    /// on (`waft-single-instance`), so every request reaches the one handler.
411    pub fn open_requested(&mut self, request: OpenRequest) {
412        self.hand_to_handler(|app| &mut app.open_requests, request);
413    }
414
415    /// Sets what hears the clicks on the app's notifications
416    /// (`EmbedderClient::notification_activated`), and hands it at once the clicks that came
417    /// before it was set, as the one that started the app does; with `None`, later clicks wait for
418    /// the next handler. No Flutter counterpart: Flutter's apps hear them through plugins.
419    pub fn set_notification_activated_handler(
420        &mut self,
421        handler: Option<NotificationActivatedCallback>,
422    ) {
423        self.set_handler(|app| &mut app.notification_activations, handler);
424    }
425
426    /// The user clicked a notification: the handler hears it, or it waits for one.
427    pub fn notification_activated(&mut self, activation: NotificationActivation) {
428        self.hand_to_handler(|app| &mut app.notification_activations, activation);
429    }
430
431    fn set_handler<T>(
432        &mut self,
433        queue: fn(&mut App) -> &mut UntilHandled<T>,
434        handler: Option<Handler<T>>,
435    ) {
436        queue(self).handler = handler.clone();
437        let Some(handler) = handler else {
438            return;
439        };
440        for waiting in std::mem::take(&mut queue(self).waiting) {
441            handler(self, waiting);
442        }
443    }
444
445    fn hand_to_handler<T>(&mut self, queue: fn(&mut App) -> &mut UntilHandled<T>, asked: T) {
446        match queue(self).handler.clone() {
447            Some(handler) => handler(self, asked),
448            None => queue(self).waiting.push(asked),
449        }
450    }
451
452    /// The App's one `T`, made with its default the first time it is asked for
453    /// (`SchedulerBinding.instance`, `kAlwaysCompleteAnimation`) and kept by the App for its
454    /// whole life: [`get_singleton`](App::get_singleton), or [`set_singleton`](App::set_singleton)
455    /// with `T::default()`, as `OnceLock::get_or_init` is its `get` or its `set`.
456    #[track_caller]
457    pub fn singleton<T: 'static + Default>(&mut self) -> Handle<T> {
458        match self.get_singleton() {
459            Some(existing) => existing,
460            None => self.set_singleton(T::default()),
461        }
462    }
463
464    /// Makes `state` the App's one `T`, kept by the App for its whole life: for a `T` the app
465    /// builds itself as it starts, from what only it knows, as a binding sets its `instance` in
466    /// `initInstances`.
467    ///
468    /// # Panics
469    ///
470    /// Where the App has a `T` already: one `T` per App.
471    #[track_caller]
472    pub fn set_singleton<T: 'static>(&mut self, state: T) -> Handle<T> {
473        assert!(
474            self.get_singleton::<T>().is_none(),
475            "the App has a {} already",
476            std::any::type_name::<T>()
477        );
478        let singleton = self.create(state);
479        let handle = singleton.handle();
480        self.singletons
481            .insert(std::any::TypeId::of::<T>(), singleton.to_any());
482        handle
483    }
484
485    /// The App's one `T`, or `None` where nothing made one yet: Dart's `instance` getter of a
486    /// binding, which reads and never creates.
487    pub fn get_singleton<T: 'static>(&self) -> Option<Handle<T>> {
488        self.singletons
489            .get(&std::any::TypeId::of::<T>())
490            .map(|singleton| Handle::new(singleton.handle()))
491    }
492
493    /// Dart's `scheduleMicrotask`: queues `callback` to run after the current
494    /// turn, before the next platform event — never inline.
495    ///
496    /// The host empties the queue with
497    /// [`drain_microtasks`](App::drain_microtasks) after every platform
498    /// event, and between `_beginFrame` and `_drawFrame` — where the engine,
499    /// which runs the two in one native task, puts an explicit flush.
500    pub fn schedule_microtask(&mut self, callback: Listener) {
501        self.microtasks.push_back(callback);
502    }
503
504    /// Runs queued microtasks until the queue is empty.
505    ///
506    /// A callback scheduled during the drain runs in the same drain, as
507    /// Dart's queue does. Call with no borrow of the App held.
508    ///
509    /// # Panics
510    ///
511    /// After `MICROTASK_BUDGET` callbacks in one drain, on the assumption
512    /// that two callbacks are scheduling each other in a cycle.
513    pub fn drain_microtasks(&mut self) {
514        let mut drained = 0usize;
515        while let Some(callback) = self.microtasks.pop_front() {
516            drained += 1;
517            assert!(
518                drained <= MICROTASK_BUDGET,
519                "microtasks did not converge after {MICROTASK_BUDGET} callbacks; \
520                 are two callbacks scheduling each other in a cycle?"
521            );
522            callback.call(self);
523        }
524    }
525
526    /// Whether any microtask is queued.
527    ///
528    /// The queue is empty when a new platform event begins, and the engine
529    /// explicitly flushes it between the two frame callbacks; the scheduler
530    /// asserts the latter.
531    pub fn has_pending_microtasks(&self) -> bool {
532        !self.microtasks.is_empty()
533    }
534
535    /// Dart's `Timer(duration, callback)`. Fires when the clock reaches
536    /// `now + duration` via [`AppCell::elapse`].
537    pub fn schedule_timer(&mut self, duration: Duration, callback: Listener) -> Timer {
538        let timer = self.timers.schedule(duration, callback);
539        self.update_timer_wakeup();
540        timer
541    }
542
543    /// Dart's `Timer.periodic(duration, callback)`. Fires whenever the clock
544    /// reaches each multiple of `duration` after `now`, until it is cancelled.
545    pub fn schedule_periodic_timer(
546        &mut self,
547        duration: Duration,
548        callback: impl Fn(&mut App, Timer) + 'static,
549    ) -> Timer {
550        let timer = self.timers.schedule_periodic(duration, Rc::new(callback));
551        self.update_timer_wakeup();
552        timer
553    }
554
555    /// Dart's `Timer.cancel()`. Idempotent.
556    pub fn cancel_timer(&mut self, timer: Timer) {
557        self.timers.cancel(timer);
558        // Cancelling the earliest timer moves the wakeup later, or leaves no timer at all.
559        self.update_timer_wakeup();
560    }
561
562    /// Dart's `Timer.isActive`.
563    pub fn timer_is_active(&self, timer: Timer) -> bool {
564        self.timers.is_active(timer)
565    }
566
567    /// Dart's `Timer.tick`: the fires a periodic timer has had.
568    pub fn timer_tick(&self, timer: Timer) -> u64 {
569        self.timers.tick(timer)
570    }
571
572    /// The App clock: what [`AppCell::elapse`] has advanced it to. Flutter's test binding's
573    /// `clock`; a frame a test pumps is stamped with it.
574    pub fn clock(&self) -> Duration {
575        self.timers.now()
576    }
577
578    /// Whether a [`Timer`] is waiting to fire: what flutter_test checks has not happened once a
579    /// test's tree is disposed.
580    pub fn has_pending_timers(&self) -> bool {
581        self.timers.has_pending()
582    }
583
584    /// Whether the debug flag `F` is on for this app: Dart's library-level `debug…` bools, kept
585    /// per app as its clock is, so two tests, or two apps, never share one. [`DebugFlag::DEFAULT`]
586    /// until set.
587    pub fn debug_flag<F: DebugFlag>(&self) -> bool {
588        self.debug_flags
589            .get(&std::any::TypeId::of::<F>())
590            .copied()
591            .unwrap_or(F::DEFAULT)
592    }
593
594    /// Turns the debug flag `F` on or off for this app; see [`debug_flag`](Self::debug_flag).
595    pub fn set_debug_flag<F: DebugFlag>(&mut self, value: bool) {
596        self.debug_flags.insert(std::any::TypeId::of::<F>(), value);
597    }
598
599    /// Fires the next timer due by `target`, if any, accounting for missed periods as `mode`
600    /// says.
601    pub(crate) fn fire_next_due(&mut self, target: Duration, mode: TimerMode) -> bool {
602        let Some((timer, callback)) = self.timers.pop_next_due(target, mode) else {
603            return false;
604        };
605        callback(self, timer);
606        true
607    }
608
609    /// Begins an event-loop turn, in which a zero-period timer may fire once.
610    pub(crate) fn begin_timer_turn(&mut self) {
611        self.timers.begin_turn();
612    }
613
614    pub(crate) fn advance_clock_to(&mut self, target: Duration) {
615        self.timers.advance_to(target);
616    }
617
618    /// Tells the host when to next wake this application for a timer, unless that is
619    /// already what it was told. Every path that can change the earliest waiting timer ends
620    /// here, and the call does nothing when that timer has not changed.
621    pub(crate) fn update_timer_wakeup(&mut self) {
622        if let Some(delay) = self.timers.timer_wakeup_if_changed() {
623            let wakeup = delay.map(|delay| self.platform.now() + delay);
624            self.dispatcher.wake_at(wakeup);
625        }
626    }
627
628    /// Puts `state` in the arena and answers the one [`Ref`] that keeps it: Dart's constructor
629    /// call. The object is freed at the checkpoint after the last `Ref` to it is dropped.
630    ///
631    /// A [`Ref`] is for Flutter's objects and the relations between them, as Dart's reference
632    /// is. The app's own data and the logic that changes it are an [`Entity`](crate::Entity),
633    /// which [`new_entity`](Self::new_entity) makes: a widget reads it in `build` and is rebuilt
634    /// by it when it notifies, where a `Ref` is what a controller, an animation or a scroll
635    /// position is held as.
636    ///
637    /// ```
638    /// # use waft_foundation::{App, AppCell};
639    /// let cell = AppCell::new();
640    /// let mut app = cell.borrow_mut();
641    /// let counter = app.create(0u32);      // a field holds this `Ref`, not the bare handle
642    /// *app.get_mut(&counter) += 1;
643    /// assert_eq!(*app.get(&counter), 1);
644    /// ```
645    ///
646    /// A tree node (an element, a state, a render object, a layer) is handed to the tree code at
647    /// once with [`Retained::into_tree_node`].
648    #[track_caller]
649    pub fn create<T: 'static>(&mut self, state: T) -> Ref<T> {
650        self.handles.create(state)
651    }
652
653    /// See [`Retained::into_tree_node`].
654    pub(crate) fn adopt_tree_node(&mut self, id: HandleId, keep: Rc<crate::handle_map::Keep>) {
655        self.handles.adopt_tree_node(id, keep);
656    }
657
658    /// The tree code is done with a node, at one of the four places Flutter's lifecycle ends one:
659    /// an element unmounted, a state disposed with its element, a render object or a layer
660    /// disposed. Marks it disposed and gives up the tree's part of its count, so it is freed at
661    /// the next checkpoint unless a [`Ref`] still keeps it.
662    ///
663    /// # Panics
664    ///
665    /// If the object is not a tree node ([`Retained::into_tree_node`]), or was released already.
666    pub fn release_tree_node(&mut self, node: impl Into<HandleId>) {
667        self.handles.release_tree_node(node.into());
668    }
669
670    /// Why [`Retained::keep`] found no keeper for `id`.
671    pub(crate) fn not_kept(&self, id: HandleId) -> String {
672        self.handles.not_kept(id)
673    }
674
675    /// Whether the entry exists: kept, or let go and waiting for the next checkpoint.
676    pub fn contains(&self, handle: impl Into<HandleId>) -> bool {
677        self.handles.contains(handle.into())
678    }
679
680    /// Records that Dart's `dispose` has run on the object. The object stays readable for as
681    /// long as something keeps it; this is a fact for tooling and for [`is_disposed`].
682    ///
683    /// [`is_disposed`]: Self::is_disposed
684    pub fn mark_disposed(&mut self, handle: impl Into<HandleId>) {
685        self.handles.mark_disposed(handle.into());
686    }
687
688    /// Whether a tear-off's receiver is still in the arena; a tear-off ([`Listener::handle_method`]
689    /// and its twins) runs only when it is. One whose receiver was freed without removing it is
690    /// skipped, as GPUI ends an observer when its receiver is gone; a debug build reports it once
691    /// per receiver, with the receiver's type and creation site.
692    pub fn tear_off_receiver_is_live(&mut self, receiver: impl Into<HandleId>) -> bool {
693        let receiver = receiver.into();
694        let live = self.handles.contains(receiver);
695        #[cfg(debug_assertions)]
696        if !live && self.skipped_tear_off_receivers.insert(receiver) {
697            let message = format!(
698                "waft: a listener whose receiver was freed without removing it was skipped: {}",
699                self.handles.debug_describe(receiver)
700            );
701            eprintln!("{message}");
702            self.skipped_tear_offs.push(message);
703        }
704        live
705    }
706
707    /// Records that the object has a `dispose` its holder must call, as Flutter's
708    /// `FlutterMemoryAllocations.dispatchObjectCreated` does: a debug build reports it if it is
709    /// freed without one ([`debug_take_not_disposed`]). A [`ChangeNotifier`] records itself when
710    /// it gets its first listener, as Dart's does; other types call this in their constructor.
711    /// Nothing in a release build.
712    ///
713    /// [`debug_take_not_disposed`]: Self::debug_take_not_disposed
714    /// [`ChangeNotifier`]: crate::ChangeNotifier
715    pub fn expect_dispose(&mut self, handle: impl Into<HandleId>) {
716        self.handles.expect_dispose(handle.into());
717    }
718
719    /// Flutter's "not disposed" leaks reported since the last call: objects that expected a
720    /// `dispose` ([`expect_dispose`](Self::expect_dispose)) and were freed without one, each with
721    /// its type and creation site. For a test that turns them into a failure.
722    #[cfg(debug_assertions)]
723    pub fn debug_take_not_disposed(&mut self) -> Vec<String> {
724        self.handles.take_not_disposed()
725    }
726
727    /// Flutter's "not collected" leaks reported since the last call: objects disposed
728    /// ([`mark_disposed`](Self::mark_disposed)) and still kept two checkpoints later, each with
729    /// its type and creation site; a ring of `Ref`s, or a holder that disposed an object and kept
730    /// it. For a test that turns them into a failure.
731    #[cfg(debug_assertions)]
732    pub fn debug_take_not_collected(&mut self) -> Vec<String> {
733        self.handles.take_not_collected()
734    }
735
736    /// Every object the arena holds, kept or waiting for the next checkpoint, with its type and
737    /// creation site: what a test's snapshot records to say afterwards which objects are new.
738    #[cfg(debug_assertions)]
739    pub fn debug_live_objects(&self) -> Vec<crate::DebugObject> {
740        self.handles.debug_live_objects()
741    }
742
743    /// The skipped tear-offs reported since the last call, for a test that turns them into a
744    /// failure.
745    #[cfg(debug_assertions)]
746    pub fn debug_take_skipped_tear_offs(&mut self) -> Vec<String> {
747        std::mem::take(&mut self.skipped_tear_offs)
748    }
749
750    /// A checkpoint begins: the frees from here on are dated by it in the stale-read message.
751    pub(crate) fn begin_checkpoint(&mut self) {
752        self.handles.begin_checkpoint();
753    }
754
755    /// Frees the objects whose last keeper went since the last sweep.
756    pub(crate) fn free_dropped_objects(&mut self) {
757        self.handles.free_dropped();
758    }
759
760    /// Whether Dart's `dispose` has run on the object ([`mark_disposed`], or the tree's
761    /// [`release_tree_node`]). `false` for a freed one.
762    ///
763    /// [`mark_disposed`]: Self::mark_disposed
764    /// [`release_tree_node`]: Self::release_tree_node
765    pub fn is_disposed(&self, handle: impl Into<HandleId>) -> bool {
766        self.handles.is_disposed(handle.into())
767    }
768
769    /// Narrow a [`HandleId`]. `None` if freed or the wrong type. [`get`](App::get) panics instead.
770    pub fn handle<T: 'static>(&self, handle: impl Into<HandleId>) -> Option<Handle<T>> {
771        self.handles.handle(handle.into())
772    }
773
774    /// # Panics
775    ///
776    /// If the object is freed; the message names its type, where it was created and the
777    /// checkpoint that freed it, while a debug build remembers them.
778    pub fn get<T: 'static>(&self, handle: impl ToHandle<T>) -> &T {
779        self.handles.get(handle.to_handle())
780    }
781
782    /// See [`get`](App::get).
783    pub fn get_mut<T: 'static>(&mut self, handle: impl ToHandle<T>) -> &mut T {
784        self.handles.get_mut(handle.to_handle())
785    }
786
787    /// Two live entries at once, for an object that works on another (a render object shaping
788    /// its text against the font collection).
789    ///
790    /// # Panics
791    ///
792    /// If either handle is stale, or both name the same entry.
793    pub fn get_disjoint_mut<A: 'static, B: 'static>(
794        &mut self,
795        a: impl ToHandle<A>,
796        b: impl ToHandle<B>,
797    ) -> (&mut A, &mut B) {
798        self.handles.get_disjoint_mut(a.to_handle(), b.to_handle())
799    }
800}
801
802/// What [`App::get`] reads through: a bare [`Handle`], or a borrowed [`Ref`], which reads without
803/// giving up its count. A `Ref` by value is not one, so a read never drops the last keeper.
804pub trait ToHandle<T> {
805    /// The handle to read through.
806    fn to_handle(self) -> Handle<T>;
807}
808
809impl<T> ToHandle<T> for Handle<T> {
810    fn to_handle(self) -> Handle<T> {
811        self
812    }
813}
814
815impl<T> ToHandle<T> for &Handle<T> {
816    fn to_handle(self) -> Handle<T> {
817        *self
818    }
819}
820
821impl<T> ToHandle<T> for &Ref<T> {
822    fn to_handle(self) -> Handle<T> {
823        self.handle()
824    }
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830    use crate::Timer;
831
832    #[derive(Debug, Default, PartialEq)]
833    struct Counter(i32);
834
835    #[derive(Debug, PartialEq)]
836    struct Label(&'static str);
837
838    #[test]
839    fn state_survives_a_round_trip_through_a_handle() {
840        let cell = AppCell::new();
841        let mut app = cell.borrow_mut();
842        let counter_ref = app.create(Counter(1));
843        let counter = counter_ref.handle();
844
845        assert_eq!(app.get(counter), &Counter(1));
846        app.get_mut(counter).0 = 7;
847        assert_eq!(app.get(counter), &Counter(7));
848    }
849
850    #[test]
851    fn handles_of_different_types_share_one_arena() {
852        let cell = AppCell::new();
853        let mut app = cell.borrow_mut();
854        let counter_ref = app.create(Counter(1));
855        let counter = counter_ref.handle();
856        let label_ref = app.create(Label("hello"));
857        let label = label_ref.handle();
858
859        assert_eq!(app.get(counter), &Counter(1));
860        assert_eq!(app.get(label), &Label("hello"));
861    }
862
863    #[test]
864    fn a_freed_entry_is_reused_but_its_handle_is_not() {
865        let cell = AppCell::new();
866        let first_id = cell.borrow_mut().create(Counter(1)).id();
867        cell.checkpoint();
868
869        let mut app = cell.borrow_mut();
870        let second_ref = app.create(Counter(2));
871        let second = second_ref.handle();
872        // slotmap: version in high 32 bits, index in low 32. Without reuse this test is vacuous.
873        let entry_index = |id: HandleId| slotmap::Key::data(&id).as_ffi() & 0xffff_ffff;
874        assert_eq!(
875            entry_index(second.id()),
876            entry_index(first_id),
877            "the freed entry is reused, so the version is what tells them apart"
878        );
879        assert_ne!(second.id(), first_id);
880        assert!(!app.contains(first_id));
881        assert!(app.contains(second));
882    }
883
884    #[test]
885    #[cfg(debug_assertions)]
886    fn a_dropped_ref_keeps_the_object_readable_until_the_checkpoint() {
887        let cell = AppCell::new();
888        let counter_ref = cell.borrow_mut().create(Counter(3));
889        let counter = counter_ref.handle();
890
891        drop(counter_ref);
892        {
893            let app = cell.borrow();
894            assert_eq!(app.get(counter), &Counter(3), "still readable");
895            assert!(app.contains(counter), "still in the arena");
896        }
897        cell.checkpoint();
898        assert!(!cell.borrow().contains(counter), "freed at the checkpoint");
899    }
900
901    #[test]
902    #[should_panic(expected = "stale handle")]
903    fn reading_through_a_stale_handle_panics() {
904        let cell = AppCell::new();
905        let counter = cell.borrow_mut().create(Counter(1)).handle();
906        cell.checkpoint();
907        cell.borrow().get(counter);
908    }
909
910    #[test]
911    fn the_checked_path_from_an_untyped_id_answers_none_rather_than_panicking() {
912        let cell = AppCell::new();
913        let counter_ref = cell.borrow_mut().create(Counter(1));
914        let counter = counter_ref.handle();
915        let id = counter.id();
916
917        assert_eq!(cell.borrow().handle::<Counter>(id), Some(counter));
918        assert_eq!(cell.borrow().handle::<Label>(id), None, "wrong type");
919
920        drop(counter_ref);
921        cell.checkpoint();
922        assert_eq!(cell.borrow().handle::<Counter>(id), None, "stale");
923    }
924
925    #[test]
926    fn a_singleton_the_app_made_is_the_one_read_back() {
927        let cell = AppCell::new();
928        let mut app = cell.borrow_mut();
929
930        let set = app.set_singleton(Counter(7));
931
932        assert_eq!(app.get_singleton::<Counter>(), Some(set));
933        assert_eq!(app.get(set).0, 7);
934        let asked: Handle<Counter> = app.singleton();
935        assert_eq!(asked, set, "asking makes no second one");
936    }
937
938    #[test]
939    #[should_panic(expected = "already")]
940    fn a_second_singleton_of_a_type_is_refused() {
941        let cell = AppCell::new();
942        let mut app = cell.borrow_mut();
943        app.set_singleton(Counter(1));
944        app.set_singleton(Counter(2));
945    }
946
947    #[test]
948    fn a_singleton_is_one_handle_per_type_per_app() {
949        let cell = AppCell::new();
950        let mut app = cell.borrow_mut();
951
952        let first: Handle<Counter> = app.singleton();
953        let second: Handle<Counter> = app.singleton();
954        assert_eq!(first, second);
955
956        app.get_mut(first).0 = 9;
957        assert_eq!(app.get(second).0, 9, "one entry behind both handles");
958
959        let other_cell = AppCell::new();
960        let mut other_app = other_cell.borrow_mut();
961        let elsewhere: Handle<Counter> = other_app.singleton();
962        assert_eq!(elsewhere.id(), first.id(), "ids may collide across Apps");
963        assert_eq!(other_app.get(elsewhere).0, 0, "but the state is per App");
964    }
965
966    #[test]
967    fn a_handle_is_copy_so_an_edge_can_be_a_plain_field() {
968        let cell = AppCell::new();
969        let mut app = cell.borrow_mut();
970        let counter_ref = app.create(Counter(1));
971        let counter = counter_ref.handle();
972
973        struct Edge {
974            target: Handle<Counter>,
975        }
976        let edge = Edge { target: counter };
977        let copied = edge.target;
978
979        assert_eq!(copied, counter);
980        assert_eq!(app.get(edge.target).0, 1);
981    }
982
983    #[test]
984    fn a_microtask_runs_on_drain_not_inline() {
985        let cell = AppCell::new();
986        let mut app = cell.borrow_mut();
987        let counter_ref = app.create(Counter(0));
988        let counter = counter_ref.handle();
989        app.schedule_microtask(crate::Listener::new(move |app| {
990            app.get_mut(counter).0 = 1;
991        }));
992        assert_eq!(app.get(counter).0, 0);
993        assert!(app.has_pending_microtasks());
994        app.drain_microtasks();
995        assert_eq!(app.get(counter).0, 1);
996        assert!(!app.has_pending_microtasks());
997    }
998
999    #[test]
1000    fn a_microtask_scheduled_during_drain_runs_in_the_same_drain() {
1001        let cell = AppCell::new();
1002        let mut app = cell.borrow_mut();
1003        let counter_ref = app.create(Counter(0));
1004        let counter = counter_ref.handle();
1005        app.schedule_microtask(crate::Listener::new(move |app| {
1006            app.get_mut(counter).0 = 1;
1007            app.schedule_microtask(crate::Listener::new(move |app| {
1008                app.get_mut(counter).0 = 2;
1009            }));
1010        }));
1011        app.drain_microtasks();
1012        assert_eq!(app.get(counter).0, 2);
1013    }
1014
1015    #[test]
1016    fn timers_fire_in_due_order_after_microtasks() {
1017        let cell = AppCell::new();
1018        let mut app = cell.borrow_mut();
1019        let log_ref = app.create(Vec::<&'static str>::new());
1020        let log = log_ref.handle();
1021        app.schedule_microtask(crate::Listener::new(move |app| {
1022            app.get_mut(log).push("micro");
1023        }));
1024        Timer::new(
1025            &mut app,
1026            Duration::from_millis(200),
1027            crate::Listener::new(move |app| {
1028                app.get_mut(log).push("late");
1029            }),
1030        );
1031        Timer::new(
1032            &mut app,
1033            Duration::from_millis(100),
1034            crate::Listener::new(move |app| {
1035                app.get_mut(log).push("early");
1036            }),
1037        );
1038        Timer::new(
1039            &mut app,
1040            Duration::from_millis(100),
1041            crate::Listener::new(move |app| {
1042                app.get_mut(log).push("early-second");
1043            }),
1044        );
1045        assert!(app.get(log).is_empty());
1046        drop(app);
1047        cell.elapse(Duration::from_millis(200));
1048        let app = cell.borrow();
1049        assert_eq!(
1050            app.get(log).as_slice(),
1051            ["micro", "early", "early-second", "late"]
1052        );
1053    }
1054
1055    #[test]
1056    fn cancel_prevents_a_timer_from_firing() {
1057        let cell = AppCell::new();
1058        let mut app = cell.borrow_mut();
1059        let counter_ref = app.create(Counter(0));
1060        let counter = counter_ref.handle();
1061        let timer = Timer::new(
1062            &mut app,
1063            Duration::from_millis(10),
1064            crate::Listener::new(move |app| {
1065                app.get_mut(counter).0 = 1;
1066            }),
1067        );
1068        assert!(timer.is_active(&app));
1069        timer.cancel(&mut app);
1070        assert!(!timer.is_active(&app));
1071        drop(app);
1072        cell.elapse(Duration::from_millis(10));
1073        let app = cell.borrow();
1074        assert_eq!(app.get(counter).0, 0);
1075    }
1076    #[test]
1077    fn get_disjoint_mut_borrows_two_entries_at_once() {
1078        let cell = AppCell::new();
1079        let mut app = cell.borrow_mut();
1080        let a_ref = app.create(1u32);
1081        let a = a_ref.handle();
1082        let b_ref = app.create(String::from("x"));
1083        let b = b_ref.handle();
1084        let (a_value, b_value) = app.get_disjoint_mut(a, b);
1085        *a_value += 1;
1086        b_value.push('y');
1087        assert_eq!(*app.get(a), 2);
1088        assert_eq!(app.get(b), "xy");
1089    }
1090
1091    #[test]
1092    #[should_panic(expected = "not two live entries")]
1093    fn get_disjoint_mut_rejects_the_same_entry_twice() {
1094        let cell = AppCell::new();
1095        let mut app = cell.borrow_mut();
1096        let a_ref = app.create(1u32);
1097        let a = a_ref.handle();
1098        let _ = app.get_disjoint_mut(a, a);
1099    }
1100
1101    #[test]
1102    fn from_id_reads_like_the_minted_handle() {
1103        let cell = AppCell::new();
1104        let mut app = cell.borrow_mut();
1105        let minted_ref = app.create(Counter(7));
1106        let minted = minted_ref.handle();
1107        let rebuilt = Handle::<Counter>::from_id(minted.id());
1108        assert_eq!(rebuilt, minted);
1109        assert_eq!(app.get(rebuilt).0, 7);
1110    }
1111
1112    #[test]
1113    #[should_panic(expected = "stale handle")]
1114    fn from_id_defers_the_stale_check_to_get() {
1115        let cell = AppCell::new();
1116        let id = cell.borrow_mut().create(Counter(0)).id();
1117        cell.checkpoint();
1118        let rebuilt = Handle::<Counter>::from_id(id);
1119        cell.borrow().get(rebuilt);
1120    }
1121}