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