inset-foundation 0.19.0

App, Handle, and Entity for Inset
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//! The one [`App`] and the arena of [`Handle`]s inside it. Not a Dart file.

use std::any::type_name;
use std::collections::{HashMap, VecDeque};
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::ops::Receiver;
use std::rc::{Rc, Weak};
use std::time::Duration;

use inset_embedder::{
    ClipboardEvent, DragReport, EditCommand, MenuId, NotificationActivation, OpenRequest,
    PlatformRef, RequestId, TrayIconEvent, TrayIconId, ViewError, ViewFocusEvent, ViewId,
};
use slotmap::new_key_type;

use crate::app_cell::{AppCell, AsyncApp};
use crate::change_notifier::Listener;
use crate::entity::EntityMap;
use crate::executor::{ExecutorHandle, ForegroundExecutor, Task};
use crate::handle_map::HandleMap;
pub use crate::handle_map::{RetainedHandle, RetainedHandleId};
use crate::timers::{Timer, Timers};

/// Drain budget for one [`App::drain_microtasks`]: two callbacks scheduling
/// each other forever must fail loud, not starve the event loop. Not a Dart
/// or Flutter constant — the isolate drains until empty; a cycle there hangs.
const MICROTASK_BUDGET: usize = 100_000;

new_key_type! {
    /// Untyped [`Handle`]. For a reference that may point at more than one type;
    /// [`App::handle`] narrows it.
    ///
    /// Destroy bumps the generation, so a leftover id does not silently name the next occupant.
    pub struct HandleId;
}

/// A Dart object, as far as Rust ownership is concerned.
///
/// Flutter objects form cycles — an element names its widget and its render object, a notifier
/// names its listeners, a listener often names the notifier. Dart allows that because the GC
/// owns the objects. Here the object lives in [`App`]; what you store is this id.
///
/// `Copy` and owns nothing. A parent–child edge is a field, not an `Rc`. Do not add a refcount:
/// that would drop `Copy` and is the `Entity` design, reserved for user stores. Stale is
/// detected by generation, not by keeping the entry alive.
///
/// Point access, not a lease: [`App::get`] / [`App::get_mut`] for one field, then drop the borrow
/// before any call that can run framework code. Holding the object out of the arena for a whole
/// pass (shaft-rs-next) meant a layout callback could not re-enter the node it was laying out.
///
/// [`App::get`] panics on stale — a typed handle is a promise the entry is live. [`App::handle`]
/// returns [`None`] for an id that might be dead or the wrong type.
///
/// `PhantomData<fn() -> T>` so `Handle<T>: Copy` even when `T` is not.
pub struct Handle<T> {
    id: HandleId,
    state: PhantomData<fn() -> T>,
}

impl<T> Handle<T> {
    /// Unchecked. [`App::create`] mints these; [`App::handle`] is the checked path and
    /// [`from_id`](Self::from_id) the trusted one.
    pub(crate) fn new(id: HandleId) -> Handle<T> {
        Handle {
            id,
            state: PhantomData,
        }
    }

    /// Wraps an id that was minted for `T` without looking at the entry. The check is deferred to
    /// [`App::get`], which panics on a stale or wrong-typed id. For a type-erased handle that
    /// reconstructs the typed handle it was made from.
    pub fn from_id(id: HandleId) -> Handle<T> {
        Handle::new(id)
    }

    pub fn id(self) -> HandleId {
        self.id
    }
}

impl<T> Clone for Handle<T> {
    fn clone(&self) -> Handle<T> {
        *self
    }
}

impl<T> Copy for Handle<T> {}

/// An arena object's methods take `self: Handle<Self>`: the handle is the receiver, the
/// object is `app.get(self)`.
impl<T> Receiver for Handle<T> {
    type Target = T;
}

impl<T> PartialEq for Handle<T> {
    fn eq(&self, other: &Handle<T>) -> bool {
        self.id == other.id
    }
}

impl<T> Eq for Handle<T> {}

impl<T> std::hash::Hash for Handle<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.id.hash(state)
    }
}

impl<T> Debug for Handle<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Handle<{}>({:?})", type_name::<T>(), self.id)
    }
}

impl<T> From<Handle<T>> for HandleId {
    fn from(handle: Handle<T>) -> HandleId {
        handle.id
    }
}

/// Owns every Flutter object. Callbacks receive `&mut App` plus a [`Handle`] to themselves.
///
/// Lives in an [`AppCell`], which is what the shell and the tests hold; a task reaches it
/// through [`AsyncApp`]. Private and `#[non_exhaustive]`: scheduler, timers, and further
/// arenas are additive.
#[non_exhaustive]
pub struct App {
    /// The cell this App lives in — gpui's `App::this`.
    this: Weak<AppCell>,
    handles: HandleMap,
    pub(crate) entities: EntityMap,
    singletons: HashMap<std::any::TypeId, HandleId>,
    microtasks: VecDeque<Listener>,
    timers: Timers,
    executor: ForegroundExecutor,
    platform: PlatformRef,
    /// The host's threads, told when to wake this application for its next timer.
    dispatcher: std::sync::Arc<dyn inset_embedder::Dispatcher>,
    platform_callbacks: PlatformCallbacks,
    open_requests: UntilHandled<OpenRequest>,
    notification_activations: UntilHandled<NotificationActivation>,
}

/// What hears one kind of what the system asks of the app, and what it asked before there was a
/// handler, which waits for one, as a launch's requests do.
struct UntilHandled<T> {
    handler: Option<Handler<T>>,
    waiting: Vec<T>,
}

impl<T> Default for UntilHandled<T> {
    fn default() -> UntilHandled<T> {
        UntilHandled {
            handler: None,
            waiting: Vec::new(),
        }
    }
}

/// The app's handler for one kind of what the system asks of it.
type Handler<T> = Rc<dyn Fn(&mut App, T)>;

/// The app's handler for the system's requests to open files and links.
pub type OpenRequestedCallback = Rc<dyn Fn(&mut App, OpenRequest)>;

/// The app's handler for the clicks on its notifications.
pub type NotificationActivatedCallback = Rc<dyn Fn(&mut App, NotificationActivation)>;

/// The callbacks the framework assigns onto dart:ui's `PlatformDispatcher`
/// (`onPlatformBrightnessChanged`, `onLocaleChanged`). The host's half of the dispatcher
/// is the `Platform` the `App` holds; this is the half the framework sets and the host's
/// client invokes.
#[derive(Default)]
pub struct PlatformCallbacks {
    pub on_platform_brightness_changed: Option<Listener>,
    pub on_locale_changed: Option<Listener>,
    /// Flutter `PlatformDispatcher.onViewFocusChange`.
    pub on_view_focus_change: Option<ViewFocusChangeCallback>,
    /// What is dragged from outside the application over a view; no Flutter counterpart.
    pub on_drag: Option<DragCallback>,
    /// The user copied, cut or pasted in a view through the platform's own command; no Flutter
    /// counterpart.
    pub on_clipboard_event: Option<ClipboardEventCallback>,
    /// The user chose an edit command for a view from the platform's own Edit menu; no Flutter
    /// counterpart.
    pub on_edit_command: Option<EditCommandCallback>,
    /// The user chose an item of the app's menu bar. Flutter's `Menu.selectedCallback` on the
    /// `flutter/menu` channel, which `DefaultPlatformMenuDelegate` handles.
    pub on_menu_selected: Option<MenuSelectedCallback>,
    /// The user chose an item of the Dock icon's menu; no Flutter counterpart, and the app's to
    /// set.
    pub on_dock_menu_selected: Option<MenuSelectedCallback>,
    /// Something happened to one of the app's tray icons; no Flutter counterpart, and the app's to
    /// set.
    pub on_tray_icon_event: Option<TrayIconEventCallback>,
    /// The user asked to go back. Answers whether the application went back. Flutter's
    /// `popRoute` on `SystemChannels.navigation`.
    pub on_pop_route: Option<PopRouteCallback>,
    /// The platform added a view: one the platform gave, or one the app asked for. Flutter's
    /// `_addView` tells it only as `onMetricsChanged`.
    pub on_view_added: Option<ViewChangeCallback>,
    /// A view went.
    pub on_view_removed: Option<ViewChangeCallback>,
    /// The user asked to close a view. Flutter's engine reports it to the window's controller.
    pub on_view_close_requested: Option<ViewCloseRequestedCallback>,
    /// A view's window was minimized or restored, became occluded or shown, or moved. Flutter's
    /// engine reports it to the window's controller.
    pub on_window_changed: Option<WindowChangedCallback>,
    /// A request for a view got no view.
    pub on_view_request_failed: Option<ViewRequestFailedCallback>,
}

/// Flutter `PlatformDispatcher.onViewFocusChange`.
pub type ViewFocusChangeCallback = Rc<dyn Fn(&mut App, ViewFocusEvent)>;

/// The framework's handler for `EmbedderClient::drag_report`.
pub type DragCallback = Rc<dyn Fn(&mut App, DragReport)>;

/// The framework's handler for `EmbedderClient::clipboard_event`.
pub type ClipboardEventCallback = Rc<dyn Fn(&mut App, ViewId, ClipboardEvent)>;

/// The framework's handler for `EmbedderClient::edit_command`.
pub type EditCommandCallback = Rc<dyn Fn(&mut App, ViewId, EditCommand)>;

/// The handler for `EmbedderClient::menu_selected` and `dock_menu_selected`.
pub type MenuSelectedCallback = Rc<dyn Fn(&mut App, MenuId)>;

/// The app's handler for `EmbedderClient::tray_icon_event`.
pub type TrayIconEventCallback = Rc<dyn Fn(&mut App, TrayIconId, TrayIconEvent)>;

/// The framework's handler for `EmbedderClient::pop_route`.
pub type PopRouteCallback = Rc<dyn Fn(&mut App) -> bool>;

/// The framework's handler for `EmbedderClient::view_added` and `view_removed`.
pub type ViewChangeCallback = Rc<dyn Fn(&mut App, ViewId)>;

/// The framework's handler for `EmbedderClient::view_close_requested`.
pub type ViewCloseRequestedCallback = Rc<dyn Fn(&mut App, ViewId)>;

/// The framework's handler for `EmbedderClient::window_changed`.
pub type WindowChangedCallback = Rc<dyn Fn(&mut App, ViewId)>;

/// The framework's handler for `EmbedderClient::view_request_failed`.
pub type ViewRequestFailedCallback = Rc<dyn Fn(&mut App, RequestId, ViewError)>;

impl App {
    pub(crate) fn build(
        this: Weak<AppCell>,
        platform: PlatformRef,
        executor: ForegroundExecutor,
    ) -> App {
        App {
            this,
            handles: HandleMap::new(),
            entities: EntityMap::new(),
            singletons: HashMap::new(),
            microtasks: VecDeque::new(),
            timers: Timers::default(),
            executor,
            dispatcher: platform.dispatcher(),
            platform,
            platform_callbacks: PlatformCallbacks::default(),
            open_requests: UntilHandled::default(),
            notification_activations: UntilHandled::default(),
        }
    }

    /// The executor's polling side, for the cell's checkpoint.
    pub(crate) fn executor_handle(&self) -> ExecutorHandle {
        self.executor.handle()
    }

    /// This App as a task sees it: the handle an `async` body captures across its `await`s.
    pub fn to_async(&self) -> AsyncApp {
        AsyncApp::new(self.this.clone(), self.executor.handle())
    }

    /// Queues `f` as a task on this App: the continuation of a Dart `async` body.
    ///
    /// Dart runs an `async` body synchronously up to its first `await`; port that prefix
    /// inline — including the call whose future is awaited — and spawn only what follows the
    /// `await`. The continuation first runs at the next [`AppCell::checkpoint`], the end of
    /// the current platform event, and thereafter at the checkpoint after whatever it awaited
    /// completed; it cannot run inline, since the caller holds the App it would borrow.
    ///
    /// The returned [`Task`] is the continuation's future; dropping it does not cancel it.
    pub fn spawn<R: 'static>(&self, f: impl AsyncFnOnce(&mut AsyncApp) -> R + 'static) -> Task<R> {
        let mut cx = self.to_async();
        self.executor.spawn(async move { f(&mut cx).await })
    }

    /// Runs `work` off the main thread, on the host's dispatcher, and answers its result as a
    /// task: dart:isolate's `Isolate.run`. The task resolves at a checkpoint after the work is
    /// done, since the executor wakes the host for it, and a panic in `work` resumes in
    /// whoever awaits the task, as `Isolate.run` rethrows the isolate's error.
    pub fn run_in_background<T: Send + 'static>(
        &self,
        work: impl FnOnce() -> T + Send + 'static,
    ) -> Task<T> {
        self.executor.run_in_background(work)
    }

    pub fn platform(&self) -> PlatformRef {
        Rc::clone(&self.platform)
    }

    /// The dispatcher callbacks the framework has assigned.
    pub fn platform_callbacks(&self) -> &PlatformCallbacks {
        &self.platform_callbacks
    }

    pub fn platform_callbacks_mut(&mut self) -> &mut PlatformCallbacks {
        &mut self.platform_callbacks
    }

    /// Sets what hears the system's requests to open files and links
    /// (`EmbedderClient::open_requested`), and hands it at once the requests that came before it
    /// was set, as a launch's do; with `None`, later requests wait for the next handler. No
    /// Flutter counterpart: Flutter's embedders hand these to their plugins.
    pub fn set_open_requested_handler(&mut self, handler: Option<OpenRequestedCallback>) {
        self.set_handler(|app| &mut app.open_requests, handler);
    }

    /// Asks the app to open `request`: the handler hears it, or it waits for one. The host calls it
    /// with what the system hands over (`EmbedderClient::open_requested`); the app calls it with
    /// the files it decides its own command line names, at launch or as a later launch passes it
    /// on (`inset-single-instance`), so every request reaches the one handler.
    pub fn open_requested(&mut self, request: OpenRequest) {
        self.hand_to_handler(|app| &mut app.open_requests, request);
    }

    /// Sets what hears the clicks on the app's notifications
    /// (`EmbedderClient::notification_activated`), and hands it at once the clicks that came
    /// before it was set, as the one that started the app does; with `None`, later clicks wait for
    /// the next handler. No Flutter counterpart: Flutter's apps hear them through plugins.
    pub fn set_notification_activated_handler(
        &mut self,
        handler: Option<NotificationActivatedCallback>,
    ) {
        self.set_handler(|app| &mut app.notification_activations, handler);
    }

    /// The user clicked a notification: the handler hears it, or it waits for one.
    pub fn notification_activated(&mut self, activation: NotificationActivation) {
        self.hand_to_handler(|app| &mut app.notification_activations, activation);
    }

    fn set_handler<T>(
        &mut self,
        queue: fn(&mut App) -> &mut UntilHandled<T>,
        handler: Option<Handler<T>>,
    ) {
        queue(self).handler = handler.clone();
        let Some(handler) = handler else {
            return;
        };
        for waiting in std::mem::take(&mut queue(self).waiting) {
            handler(self, waiting);
        }
    }

    fn hand_to_handler<T>(&mut self, queue: fn(&mut App) -> &mut UntilHandled<T>, asked: T) {
        match queue(self).handler.clone() {
            Some(handler) => handler(self, asked),
            None => queue(self).waiting.push(asked),
        }
    }

    /// One `T` per App (`SchedulerBinding.instance`, `kAlwaysCompleteAnimation`). Do not destroy it — the stored id goes stale and the next call panics.
    pub fn singleton<T: 'static + Default>(&mut self) -> Handle<T> {
        if let Some(&id) = self.singletons.get(&std::any::TypeId::of::<T>()) {
            return Handle::new(id);
        }
        let handle = self.create(T::default());
        self.singletons
            .insert(std::any::TypeId::of::<T>(), handle.id());
        handle
    }

    /// Dart's `scheduleMicrotask`: queues `callback` to run after the current
    /// turn, before the next platform event — never inline.
    ///
    /// The host empties the queue with
    /// [`drain_microtasks`](App::drain_microtasks) after every platform
    /// event, and between `_beginFrame` and `_drawFrame` — where the engine,
    /// which runs the two in one native task, puts an explicit flush.
    pub fn schedule_microtask(&mut self, callback: Listener) {
        self.microtasks.push_back(callback);
    }

    /// Runs queued microtasks until the queue is empty.
    ///
    /// A callback scheduled during the drain runs in the same drain, as
    /// Dart's queue does. Call with no borrow of the App held.
    ///
    /// # Panics
    ///
    /// After `MICROTASK_BUDGET` callbacks in one drain, on the assumption
    /// that two callbacks are scheduling each other in a cycle.
    pub fn drain_microtasks(&mut self) {
        let mut drained = 0usize;
        while let Some(callback) = self.microtasks.pop_front() {
            drained += 1;
            assert!(
                drained <= MICROTASK_BUDGET,
                "microtasks did not converge after {MICROTASK_BUDGET} callbacks; \
                 are two callbacks scheduling each other in a cycle?"
            );
            callback.call(self);
        }
    }

    /// Whether any microtask is queued.
    ///
    /// The queue is empty when a new platform event begins, and the engine
    /// explicitly flushes it between the two frame callbacks; the scheduler
    /// asserts the latter.
    pub fn has_pending_microtasks(&self) -> bool {
        !self.microtasks.is_empty()
    }

    /// Dart's `Timer(duration, callback)`. Fires when the clock reaches
    /// `now + duration` via [`AppCell::elapse`].
    pub fn schedule_timer(&mut self, duration: Duration, callback: Listener) -> Timer {
        let timer = self.timers.schedule(duration, callback);
        self.update_timer_wakeup();
        timer
    }

    /// Dart's `Timer.cancel()`. Idempotent.
    pub fn cancel_timer(&mut self, timer: Timer) {
        self.timers.cancel(timer);
        // Cancelling the earliest timer moves the wakeup later, or leaves no timer at all.
        self.update_timer_wakeup();
    }

    /// Dart's `Timer.isActive`.
    pub fn timer_is_active(&self, timer: Timer) -> bool {
        self.timers.is_active(timer)
    }

    /// The App clock: what [`AppCell::elapse`] has advanced it to.
    pub(crate) fn clock(&self) -> Duration {
        self.timers.now()
    }

    /// Fires the next timer due by `target`, if any.
    pub(crate) fn fire_next_due(&mut self, target: Duration) -> bool {
        let Some(callback) = self.timers.pop_next_due(target) else {
            return false;
        };
        callback.call(self);
        true
    }

    pub(crate) fn advance_clock_to(&mut self, target: Duration) {
        self.timers.advance_to(target);
    }

    /// Tells the host when to next wake this application for a timer, unless that is
    /// already what it was told. Every path that can change the earliest waiting timer ends
    /// here, and the call does nothing when that timer has not changed.
    pub(crate) fn update_timer_wakeup(&mut self) {
        if let Some(delay) = self.timers.timer_wakeup_if_changed() {
            let wakeup = delay.map(|delay| self.platform.now() + delay);
            self.dispatcher.wake_at(wakeup);
        }
    }

    pub fn create<T: 'static>(&mut self, state: T) -> Handle<T> {
        self.handles.create(state)
    }

    /// Dart's `dispose`: see [`HandleMap::destroy`].
    pub fn destroy(&mut self, handle: impl Into<HandleId>) {
        self.handles.destroy(handle.into());
    }

    /// Whether the entry exists: live, or destroyed but still retained.
    pub fn contains(&self, handle: impl Into<HandleId>) -> bool {
        self.handles.contains(handle.into())
    }

    /// A [`RetainedHandle`] that keeps the object past its owner's `destroy`; see
    /// [`HandleMap::retain`]. `T` is the Copy handle to keep (`Handle<U>` or an erased handle).
    pub fn retain<T: Copy + Into<HandleId>>(&mut self, handle: T) -> RetainedHandle<T> {
        self.handles.retain(handle)
    }

    /// A [`RetainedHandleId`] when the holder has only the id; see [`HandleMap::retain_id`].
    pub fn retain_id(&mut self, id: HandleId) -> RetainedHandleId {
        self.handles.retain_id(id)
    }

    /// Gives a [`RetainedHandle`] back now; a dropped one is released at the next checkpoint.
    pub fn release<T>(&mut self, handle: RetainedHandle<T>) {
        self.handles.release(handle);
    }

    /// See [`release`](Self::release).
    pub fn release_id(&mut self, handle: RetainedHandleId) {
        self.handles.release_id(handle);
    }

    pub(crate) fn release_dropped_retained_handles(&mut self) {
        self.handles.release_dropped_retained_handles();
    }

    /// Whether the owner destroyed the object while a [`RetainedHandle`] still keeps it.
    pub fn is_disposed(&self, handle: impl Into<HandleId>) -> bool {
        self.handles.is_disposed(handle.into())
    }

    /// Narrow a [`HandleId`]. `None` if stale or the wrong type. [`get`](App::get) panics instead.
    pub fn handle<T: 'static>(&self, handle: impl Into<HandleId>) -> Option<Handle<T>> {
        self.handles.handle(handle.into())
    }

    /// # Panics
    ///
    /// If the handle is stale.
    pub fn get<T: 'static>(&self, handle: Handle<T>) -> &T {
        self.handles.get(handle)
    }

    /// See [`get`](App::get).
    pub fn get_mut<T: 'static>(&mut self, handle: Handle<T>) -> &mut T {
        self.handles.get_mut(handle)
    }

    /// Two live entries at once, for an object that works on another (a render object shaping
    /// its text against the font collection).
    ///
    /// # Panics
    ///
    /// If either handle is stale, or both name the same entry.
    pub fn get_disjoint_mut<A: 'static, B: 'static>(
        &mut self,
        a: Handle<A>,
        b: Handle<B>,
    ) -> (&mut A, &mut B) {
        self.handles.get_disjoint_mut(a, b)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Timer;

    #[derive(Debug, Default, PartialEq)]
    struct Counter(i32);

    #[derive(Debug, PartialEq)]
    struct Label(&'static str);

    #[test]
    fn state_survives_a_round_trip_through_a_handle() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let counter = app.create(Counter(1));

        assert_eq!(app.get(counter), &Counter(1));
        app.get_mut(counter).0 = 7;
        assert_eq!(app.get(counter), &Counter(7));
    }

    #[test]
    fn handles_of_different_types_share_one_arena() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let counter = app.create(Counter(1));
        let label = app.create(Label("hello"));

        assert_eq!(app.get(counter), &Counter(1));
        assert_eq!(app.get(label), &Label("hello"));
    }

    #[test]
    fn a_destroyed_entry_is_reused_but_its_handle_is_not() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let first = app.create(Counter(1));
        let first_id = first.id();
        app.destroy(first);

        let second = app.create(Counter(2));
        // slotmap: version in high 32 bits, index in low 32. Without reuse this test is vacuous.
        let entry_index = |id: HandleId| slotmap::Key::data(&id).as_ffi() & 0xffff_ffff;
        assert_eq!(
            entry_index(second.id()),
            entry_index(first_id),
            "the freed entry is reused, so the version is what tells them apart"
        );
        assert_ne!(second.id(), first_id);
        assert!(!app.contains(first_id));
        assert!(app.contains(second));
    }

    #[test]
    #[should_panic(expected = "stale handle")]
    fn reading_through_a_stale_handle_panics() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let counter = app.create(Counter(1));
        app.destroy(counter);
        app.get(counter);
    }

    #[test]
    fn the_checked_path_from_an_untyped_id_answers_none_rather_than_panicking() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let counter = app.create(Counter(1));
        let id = counter.id();

        assert_eq!(app.handle::<Counter>(id), Some(counter));
        assert_eq!(app.handle::<Label>(id), None, "wrong type");

        app.destroy(counter);
        assert_eq!(app.handle::<Counter>(id), None, "stale");
    }

    #[test]
    fn a_singleton_is_one_handle_per_type_per_app() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();

        let first: Handle<Counter> = app.singleton();
        let second: Handle<Counter> = app.singleton();
        assert_eq!(first, second);

        app.get_mut(first).0 = 9;
        assert_eq!(app.get(second).0, 9, "one entry behind both handles");

        let other_cell = AppCell::new();
        let mut other_app = other_cell.borrow_mut();
        let elsewhere: Handle<Counter> = other_app.singleton();
        assert_eq!(elsewhere.id(), first.id(), "ids may collide across Apps");
        assert_eq!(other_app.get(elsewhere).0, 0, "but the state is per App");
    }

    #[test]
    fn a_handle_is_copy_so_an_edge_can_be_a_plain_field() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let counter = app.create(Counter(1));

        struct Edge {
            target: Handle<Counter>,
        }
        let edge = Edge { target: counter };
        let copied = edge.target;

        assert_eq!(copied, counter);
        assert_eq!(app.get(edge.target).0, 1);
    }

    #[test]
    fn a_microtask_runs_on_drain_not_inline() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let counter = app.create(Counter(0));
        app.schedule_microtask(crate::Listener::new(move |app| {
            app.get_mut(counter).0 = 1;
        }));
        assert_eq!(app.get(counter).0, 0);
        assert!(app.has_pending_microtasks());
        app.drain_microtasks();
        assert_eq!(app.get(counter).0, 1);
        assert!(!app.has_pending_microtasks());
    }

    #[test]
    fn a_microtask_scheduled_during_drain_runs_in_the_same_drain() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let counter = app.create(Counter(0));
        app.schedule_microtask(crate::Listener::new(move |app| {
            app.get_mut(counter).0 = 1;
            app.schedule_microtask(crate::Listener::new(move |app| {
                app.get_mut(counter).0 = 2;
            }));
        }));
        app.drain_microtasks();
        assert_eq!(app.get(counter).0, 2);
    }

    #[test]
    fn timers_fire_in_due_order_after_microtasks() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let log = app.create(Vec::<&'static str>::new());
        app.schedule_microtask(crate::Listener::new(move |app| {
            app.get_mut(log).push("micro");
        }));
        Timer::new(
            &mut app,
            Duration::from_millis(200),
            crate::Listener::new(move |app| {
                app.get_mut(log).push("late");
            }),
        );
        Timer::new(
            &mut app,
            Duration::from_millis(100),
            crate::Listener::new(move |app| {
                app.get_mut(log).push("early");
            }),
        );
        Timer::new(
            &mut app,
            Duration::from_millis(100),
            crate::Listener::new(move |app| {
                app.get_mut(log).push("early-second");
            }),
        );
        assert!(app.get(log).is_empty());
        drop(app);
        cell.elapse(Duration::from_millis(200));
        let app = cell.borrow();
        assert_eq!(
            app.get(log).as_slice(),
            ["micro", "early", "early-second", "late"]
        );
    }

    #[test]
    fn cancel_prevents_a_timer_from_firing() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let counter = app.create(Counter(0));
        let timer = Timer::new(
            &mut app,
            Duration::from_millis(10),
            crate::Listener::new(move |app| {
                app.get_mut(counter).0 = 1;
            }),
        );
        assert!(timer.is_active(&app));
        timer.cancel(&mut app);
        assert!(!timer.is_active(&app));
        drop(app);
        cell.elapse(Duration::from_millis(10));
        let app = cell.borrow();
        assert_eq!(app.get(counter).0, 0);
    }
    #[test]
    fn get_disjoint_mut_borrows_two_entries_at_once() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let a = app.create(1u32);
        let b = app.create(String::from("x"));
        let (a_value, b_value) = app.get_disjoint_mut(a, b);
        *a_value += 1;
        b_value.push('y');
        assert_eq!(*app.get(a), 2);
        assert_eq!(app.get(b), "xy");
    }

    #[test]
    #[should_panic(expected = "not two live entries")]
    fn get_disjoint_mut_rejects_the_same_entry_twice() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let a = app.create(1u32);
        let _ = app.get_disjoint_mut(a, a);
    }

    #[test]
    fn from_id_reads_like_the_minted_handle() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let minted = app.create(Counter(7));
        let rebuilt = Handle::<Counter>::from_id(minted.id());
        assert_eq!(rebuilt, minted);
        assert_eq!(app.get(rebuilt).0, 7);
    }

    #[test]
    #[should_panic(expected = "stale handle")]
    fn from_id_defers_the_stale_check_to_get() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let minted = app.create(Counter(0));
        let id = minted.id();
        app.destroy(minted);
        let rebuilt = Handle::<Counter>::from_id(id);
        app.get(rebuilt);
    }
}