waft-shell 0.18.2

Framework-side embedder client for Waft
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
//! The one [`EmbedderClient`] the framework provides: owns the [`AppCell`] and
//! translates host pushes into binding methods.
//!
//! Dart has no type for this — the engine owns the isolate. [`App`] stays in
//! foundation. This crate sits above scheduler and gestures so the isolate
//! can name both.
#![feature(arbitrary_self_types)]

use std::cell::RefMut;
use std::rc::Rc;
use std::time::Duration;

use waft_embedder::{
    AppExitReply, AppLifecycleState, ClipboardEvent, DragReport, EditCommand, EmbedderClient,
    Frame, Instant, KeyData, MenuId, NotificationActivation, OpenRequest, PlatformRef, PointerData,
    PointerDataPacket, PointerDataPacketConverter, PointerReport, RequestId, ServiceExtensionCall,
    TextEditingValue, TextInputAction, TrayIconEvent, TrayIconId, ViewError, ViewFocusEvent,
    ViewId,
};
use waft_foundation::{App, AppCell, ServiceExtensions};
use waft_gestures::GestureBinding;
use waft_painting::PaintingBinding;
use waft_rendering::RendererBinding;
use waft_scheduler::{FrameTarget, SchedulerBinding};
use waft_services::{KeyEventManager, ServicesBinding, TextInput};

/// Host-facing isolate: the [`AppCell`] plus the methods the embedder pushes.
///
/// Every push is one call into the app: the `App` is borrowed for the binding call and
/// released before the cell's checkpoint, where the microtasks and futures the event queued
/// run.
pub struct Shell {
    app: Rc<AppCell>,
    platform: PlatformRef,
    /// The platform time the app clock was last advanced to.
    clock: Duration,
    /// The platform's `now` at its `elapsed` zero, known once a frame has reported its `elapsed`; lets every push, not only a frame or wake, move the app clock to the platform's.
    origin: Option<Instant>,
    /// What the framework was last told of each pointing device, as `RuntimeController` keeps it.
    pointer_data_packet_converter: PointerDataPacketConverter,
}

impl Shell {
    /// Builds the heap from `platform`, then runs application setup.
    ///
    /// Setup (later widgets `run_app`) requests the first frame when it
    /// installs work that needs one.
    pub fn new(platform: PlatformRef, setup: impl FnOnce(&mut App)) -> Shell {
        let shell = Shell {
            app: AppCell::with_platform(platform.clone()),
            platform,
            clock: Duration::ZERO,
            origin: None,
            pointer_data_packet_converter: PointerDataPacketConverter::new(),
        };
        shell.handle_event(|app| {
            // Flutter's engine collects the platform's fonts before the framework runs.
            PaintingBinding::instance(app).install_platform_fonts(app);
            setup(app);
        });
        shell
    }

    /// The `App`, borrowed until the guard drops. A host that needs the whole thing, a borrow
    /// and then the checkpoint, takes [`cell`](Self::cell).
    pub fn app(&self) -> RefMut<'_, App> {
        self.app.borrow_mut()
    }

    pub fn cell(&self) -> &Rc<AppCell> {
        &self.app
    }

    /// One platform event: `f` on the borrowed `App`, then the checkpoint.
    fn handle_event<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
        let result = f(&mut self.app.borrow_mut());
        self.app.checkpoint();
        result
    }

    /// An input or platform push: the app clock catches up with the platform's first, as Dart's
    /// timers measure real time from the moment they are created, then `f` runs.
    fn push<R>(&mut self, f: impl FnOnce(&mut App) -> R) -> R {
        if let Some(origin) = self.origin {
            let elapsed = self.platform.now().saturating_duration_since(origin);
            self.advance_clock(elapsed);
        }
        self.handle_event(f)
    }

    /// Moves the app clock up to the platform's `elapsed`, firing the timers that came due as
    /// Dart's VM does after the event loop was away: once each, their ticks jumping over the
    /// periods that passed.
    fn advance_clock(&mut self, elapsed: Duration) {
        if elapsed <= self.clock {
            return;
        }
        self.app.elapse_to(elapsed);
        self.clock = elapsed;
    }

    /// dart:ui's `onMetricsChanged`, which the framework sets to
    /// `RendererBinding.handleMetricsChanged`. `_addView`, `_removeView` and `_updateDisplays`
    /// invoke it as `_updateWindowMetrics` does: a view coming or going, and a change to the
    /// screens, reach the app only this way.
    fn metrics_changed(&mut self) {
        self.push(|app| RendererBinding::instance(app).handle_metrics_changed(app));
    }
}

impl EmbedderClient for Shell {
    /// The app's timers run to the platform's clock, and the frame's time is its vsync's target,
    /// as the engine hands `_beginFrame` (`Animator::BeginFrame`); a frame drawn outside a vsync
    /// takes the platform's clock.
    fn frame(&mut self, views: &[ViewId], frame: Frame) {
        self.origin = Some(self.platform.now() - frame.elapsed);
        self.advance_clock(frame.elapsed);
        let time_stamp = frame.vsync.map_or(frame.elapsed, |vsync| vsync.target);
        // The engine runs `_beginFrame` and `_drawFrame` as two native tasks: two calls.
        self.handle_event(|app| SchedulerBinding::on_begin_frame(app, views, Some(time_stamp)));
        self.handle_event(|app| SchedulerBinding::on_draw_frame(app, views));
    }

    /// The framework hears which view came, then "metrics changed", as `_addView` invokes it;
    /// then a frame is scheduled, as `RuntimeController::AddView` schedules one once the view is
    /// added. Without it, a build scheduled while the app had no view, such as the one that puts
    /// the new view's window on it, would wait for an event of the view's window, which a Wayland
    /// window, unseen until it presents a picture, never sends.
    fn view_added(&mut self, id: ViewId) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_view_added.clone();
            if let Some(callback) = callback {
                callback(app, id);
            }
        });
        self.metrics_changed();
        self.handle_event(|app| SchedulerBinding::schedule_frame(app, FrameTarget::View(id)));
    }

    fn view_metrics_changed(&mut self, _id: ViewId) {
        self.metrics_changed();
    }

    /// The framework hears which view went, then "metrics changed", as `_removeView` invokes
    /// it.
    fn view_removed(&mut self, id: ViewId) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_view_removed.clone();
            if let Some(callback) = callback {
                callback(app, id);
            }
        });
        self.metrics_changed();
    }

    /// "Metrics changed", as `_updateDisplays` invokes it.
    fn screens_changed(&mut self) {
        self.metrics_changed();
    }

    fn view_focus_changed(&mut self, event: ViewFocusEvent) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_view_focus_change.clone();
            if let Some(callback) = callback {
                callback(app, event);
            }
        });
    }

    fn drag_report(&mut self, report: DragReport) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_drag.clone();
            if let Some(callback) = callback {
                callback(app, report);
            }
        });
    }

    fn clipboard_event(&mut self, view: ViewId, event: ClipboardEvent) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_clipboard_event.clone();
            if let Some(callback) = callback {
                callback(app, view, event);
            }
        });
    }

    fn edit_command(&mut self, view: ViewId, command: EditCommand) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_edit_command.clone();
            if let Some(callback) = callback {
                callback(app, view, command);
            }
        });
    }

    fn menu_selected(&mut self, id: MenuId) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_menu_selected.clone();
            if let Some(callback) = callback {
                callback(app, id);
            }
        });
    }

    fn dock_menu_selected(&mut self, id: MenuId) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_dock_menu_selected.clone();
            if let Some(callback) = callback {
                callback(app, id);
            }
        });
    }

    fn tray_icon_event(&mut self, icon: TrayIconId, event: TrayIconEvent) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_tray_icon_event.clone();
            if let Some(callback) = callback {
                callback(app, icon, event);
            }
        });
    }

    fn open_requested(&mut self, request: OpenRequest) {
        self.push(|app| app.open_requested(request));
    }

    fn notification_activated(&mut self, activation: NotificationActivation) {
        self.push(|app| app.notification_activated(activation));
    }

    fn pointer_reports(&mut self, reports: Vec<PointerReport>) {
        let packet = PointerDataPacket::new(reports.into_iter().map(PointerData::from).collect());
        let platform = &self.platform;
        let packet = self
            .pointer_data_packet_converter
            .convert(&packet, |view_id| platform.view(view_id).is_some());
        self.push(|app| GestureBinding::instance(app).handle_pointer_data_packet(app, packet));
    }

    fn key_data(&mut self, data: KeyData) -> bool {
        self.push(|app| KeyEventManager::instance(app).handle_key_data(app, data))
    }

    fn pop_route(&mut self, view: ViewId) -> bool {
        self.push(|app| {
            let callback = app.platform_callbacks().on_pop_route.clone();
            callback.is_some_and(|callback| callback(app, view))
        })
    }

    fn view_close_requested(&mut self, view: ViewId) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_view_close_requested.clone();
            if let Some(callback) = callback {
                callback(app, view);
            }
        });
    }

    fn window_changed(&mut self, view: ViewId) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_window_changed.clone();
            if let Some(callback) = callback {
                callback(app, view);
            }
        });
    }

    fn view_request_failed(&mut self, request: RequestId, error: ViewError) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_view_request_failed.clone();
            if let Some(callback) = callback {
                callback(app, request, error);
            }
        });
    }

    /// The binding's answer goes to `reply` at the checkpoint of the call in which the
    /// observers decide: this push's own when they answer at once.
    fn request_app_exit(&mut self, reply: AppExitReply) {
        self.push(|app| {
            let answer = ServicesBinding::instance(app).handle_request_app_exit(app);
            app.spawn(async move |_cx| reply.answer(answer.await));
        });
    }

    /// The extension's answer goes to `call.reply` when its task ends: at this push's checkpoint
    /// when it answers at once.
    fn service_extension_call(&mut self, call: ServiceExtensionCall) {
        self.push(move |app| {
            let ServiceExtensionCall {
                name,
                params,
                reply,
            } = call;
            let answer = ServiceExtensions::call(app, &name, params);
            app.spawn(async move |_cx| reply.answer(answer.await));
        });
    }

    /// On `resumed` or `inactive`, every view is marked to present and asked for a frame before
    /// the bindings hear the state: a view that did not change while the app was away would
    /// otherwise present nothing.
    fn app_lifecycle_state_changed(&mut self, state: AppLifecycleState) {
        self.push(|app| {
            if matches!(
                state,
                AppLifecycleState::Resumed | AppLifecycleState::Inactive
            ) {
                RendererBinding::instance(app).handle_mark_all_views_need_render(app);
                SchedulerBinding::schedule_forced_frame(app, FrameTarget::EveryView);
            }
            ServicesBinding::instance(app).handle_lifecycle_message(app, state);
        });
    }

    fn platform_brightness_changed(&mut self) {
        self.push(|app| {
            let callback = app
                .platform_callbacks()
                .on_platform_brightness_changed
                .clone();
            if let Some(callback) = callback {
                callback.call(app);
            }
        });
    }

    fn locales_changed(&mut self) {
        self.push(|app| {
            let callback = app.platform_callbacks().on_locale_changed.clone();
            if let Some(callback) = callback {
                callback.call(app);
            }
        });
    }

    fn system_fonts_changed(&mut self) {
        self.push(|app| {
            PaintingBinding::instance(app).handle_system_fonts_did_change(app);
        });
    }

    fn clipboard_changed(&mut self) {
        self.push(|app| ServicesBinding::instance(app).handle_clipboard_changed(app));
    }

    fn wake(&mut self, elapsed: Duration) {
        self.advance_clock(elapsed);
        // A wake with no time behind it is a post from a native callback.
        self.app.wake();
    }

    fn text_input_editing_value(&mut self, _view: ViewId, value: TextEditingValue) {
        self.push(|app| TextInput::instance(app).update_editing_value(app, value));
    }

    fn text_input_action(&mut self, _view: ViewId, action: TextInputAction) {
        self.push(|app| TextInput::instance(app).perform_action(app, action));
    }

    fn text_input_closed(&mut self, _view: ViewId) {
        self.push(|app| TextInput::instance(app).connection_closed(app));
    }

    fn system_context_menu_hidden(&mut self) {
        self.push(waft_services::SystemContextMenuController::dispatch_system_hide);
    }

    fn custom_context_menu_action(&mut self, callback_id: &str) {
        let callback_id = callback_id.to_string();
        self.push(move |app| {
            waft_services::SystemContextMenuController::dispatch_custom_action(app, &callback_id);
        });
    }
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;
    use std::time::Duration;

    use waft_embedder::{
        AppLifecycleState, Contact, EmbedderClient, Frame, KeyData, KeyEventType,
        PointerDeviceKind, PointerReport, ReportedChange, ViewId,
    };
    use waft_foundation::App;
    use waft_gestures::{GestureBinding, PointerRoute};
    use waft_scheduler::{FrameTarget, SchedulerBinding};
    use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey, PhysicalKeyboardKey};
    use waft_test::{IMPLICIT_VIEW_ID, TestPlatform};

    use super::Shell;

    /// A platform with the one view a pointer packet, a focus event or a frame is addressed to.
    fn platform_with_a_view() -> TestPlatform {
        TestPlatform::new().with_views(&[IMPLICIT_VIEW_ID])
    }

    #[test]
    fn a_read_started_by_a_task_the_drop_spawns_is_in_time() {
        use std::cell::RefCell;

        use waft_embedder::{
            ClipboardReadFuture, DataTransferItem, DragChange, DragReport, DraggedItems,
        };

        struct Text([String; 1]);

        impl DataTransferItem for Text {
            fn types(&self) -> &[String] {
                &self.0
            }

            fn read(&self, _mime: &str) -> ClipboardReadFuture {
                Box::pin(std::future::ready(Ok(b"hi".to_vec())))
            }
        }

        let read = Rc::new(RefCell::new(None));
        let read_slot = Rc::clone(&read);
        let platform = Rc::new(platform_with_a_view());
        let mut shell = Shell::new(platform, move |app: &mut App| {
            app.platform_callbacks_mut().on_drag = Some(Rc::new(move |app, report| {
                let read_slot = Rc::clone(&read_slot);
                let item = Rc::clone(&report.items[0]);
                // Dropping the task lets it run, as a Dart future does.
                let _reading = app.spawn(async move |_cx| {
                    *read_slot.borrow_mut() = Some(item.read("text/plain").await);
                });
            }));
        });
        let dragged = DraggedItems::new(vec![Box::new(Text(["text/plain".to_owned()]))]);
        let drop = DragReport {
            view_id: IMPLICIT_VIEW_ID,
            change: DragChange::Dropped,
            physical_position: None,
            items: dragged.items(),
        };
        dragged.report_drop(|| shell.drag_report(drop));
        assert_eq!(*read.borrow(), Some(Ok(b"hi".to_vec())));
    }

    #[test]
    fn a_clipboard_event_reaches_the_platform_callback_with_its_view() {
        use waft_embedder::{ClipboardEvent, CopyRequest};

        let seen = Rc::new(Cell::new(None));
        let seen_slot = Rc::clone(&seen);
        let mut shell = Shell::new(Rc::new(platform_with_a_view()), move |app: &mut App| {
            app.platform_callbacks_mut().on_clipboard_event =
                Some(Rc::new(move |_app, view, event| {
                    seen_slot.set(Some((view, matches!(event, ClipboardEvent::Cut(_)))));
                }));
        });
        let request = CopyRequest::new(|_items, _options| Box::pin(std::future::ready(Ok(()))));
        shell.clipboard_event(IMPLICIT_VIEW_ID, ClipboardEvent::Cut(request));
        assert_eq!(seen.get(), Some((IMPLICIT_VIEW_ID, true)));
    }

    #[test]
    fn an_open_request_waits_for_the_apps_handler() {
        use std::cell::RefCell;

        use waft_embedder::OpenRequest;

        let seen = Rc::new(RefCell::new(Vec::new()));
        let mut shell = Shell::new(Rc::new(platform_with_a_view()), |_app: &mut App| {});
        shell.open_requested(OpenRequest {
            files: Vec::new(),
            links: vec!["https://example.org/launch".to_owned()],
        });
        let slot = Rc::clone(&seen);
        shell
            .app
            .borrow_mut()
            .set_open_requested_handler(Some(Rc::new(move |_app, request: OpenRequest| {
                slot.borrow_mut().extend(request.links)
            })));
        shell.open_requested(OpenRequest {
            files: Vec::new(),
            links: vec!["https://example.org/later".to_owned()],
        });
        assert_eq!(
            *seen.borrow(),
            ["https://example.org/launch", "https://example.org/later"],
            "the launch's request waited for the handler"
        );
    }

    #[test]
    fn a_notification_click_waits_for_the_apps_handler() {
        use std::cell::RefCell;

        use waft_embedder::NotificationActivation;

        let seen = Rc::new(RefCell::new(Vec::new()));
        let mut shell = Shell::new(Rc::new(platform_with_a_view()), |_app: &mut App| {});
        let click = |action: Option<&str>| NotificationActivation {
            id: "message-7".to_owned(),
            action: action.map(str::to_owned),
            reply: None,
        };
        shell.notification_activated(click(None));
        let slot = Rc::clone(&seen);
        shell
            .app
            .borrow_mut()
            .set_notification_activated_handler(Some(Rc::new(move |_app, activation| {
                slot.borrow_mut().push(activation)
            })));
        shell.notification_activated(click(Some("later")));
        assert_eq!(
            *seen.borrow(),
            [click(None), click(Some("later"))],
            "the click that started the app waited for the handler"
        );
    }

    #[test]
    fn menu_choices_edit_commands_and_tray_icon_events_reach_their_callbacks() {
        use std::cell::RefCell;

        use waft_embedder::{EditCommand, Offset, TrayIconEvent};

        let seen = Rc::new(RefCell::new(Vec::new()));
        let slot = Rc::clone(&seen);
        let mut shell = Shell::new(Rc::new(platform_with_a_view()), move |app: &mut App| {
            let callbacks = app.platform_callbacks_mut();
            let menu = Rc::clone(&slot);
            callbacks.on_menu_selected = Some(Rc::new(move |_app, id| {
                menu.borrow_mut().push(format!("menu {id}"));
            }));
            let dock = Rc::clone(&slot);
            callbacks.on_dock_menu_selected = Some(Rc::new(move |_app, id| {
                dock.borrow_mut().push(format!("dock {id}"));
            }));
            let edit = Rc::clone(&slot);
            callbacks.on_edit_command = Some(Rc::new(move |_app, view, command| {
                edit.borrow_mut().push(format!("{view:?} {command:?}"));
            }));
            let tray = Rc::clone(&slot);
            callbacks.on_tray_icon_event = Some(Rc::new(move |_app, icon, event| {
                tray.borrow_mut().push(format!("tray {icon} {event:?}"));
            }));
        });
        shell.menu_selected(3);
        shell.dock_menu_selected(4);
        shell.edit_command(IMPLICIT_VIEW_ID, EditCommand::Undo);
        shell.tray_icon_event(
            7,
            TrayIconEvent::Activated {
                position: Offset::new(1.0, 2.0),
            },
        );
        assert_eq!(
            *seen.borrow(),
            [
                "menu 3".to_owned(),
                "dock 4".to_owned(),
                format!("{IMPLICIT_VIEW_ID:?} Undo"),
                format!(
                    "tray 7 {:?}",
                    TrayIconEvent::Activated {
                        position: Offset::new(1.0, 2.0)
                    }
                ),
            ]
        );
    }

    #[test]
    fn a_change_of_the_clipboard_reaches_the_services_bindings_listenable() {
        use waft_foundation::{ListenableObject, Listener};
        use waft_services::ServicesBinding;

        let heard = Rc::new(Cell::new(0));
        let counter = Rc::clone(&heard);
        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app: &mut App| {
            let clipboard = ServicesBinding::instance(app).clipboard(app);
            clipboard.add_listener(
                app,
                Listener::new(move |_app| counter.set(counter.get() + 1)),
            );
        });
        shell.clipboard_changed();
        assert_eq!(heard.get(), 1);
    }

    /// A reply to `shell.request_app_exit`, and the answer it was given so far.
    fn recorded_reply() -> (
        waft_embedder::AppExitReply,
        Rc<Cell<Option<waft_embedder::AppExitResponse>>>,
    ) {
        let answer = Rc::new(Cell::new(None));
        let given = Rc::clone(&answer);
        let reply = waft_embedder::AppExitReply::new(move |response| given.set(Some(response)));
        (reply, answer)
    }

    #[test]
    fn a_view_added_or_removed_reaches_the_framework_with_its_id() {
        let heard = Rc::new(std::cell::RefCell::new(Vec::new()));
        let (added, removed) = (Rc::clone(&heard), Rc::clone(&heard));
        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app: &mut App| {
            let callbacks = app.platform_callbacks_mut();
            callbacks.on_view_added = Some(Rc::new(move |_app, view| {
                added.borrow_mut().push(("added", view))
            }));
            callbacks.on_view_removed = Some(Rc::new(move |_app, view| {
                removed.borrow_mut().push(("removed", view))
            }));
        });
        shell.view_added(ViewId(4));
        shell.view_removed(ViewId(4));
        assert_eq!(
            *heard.borrow(),
            [("added", ViewId(4)), ("removed", ViewId(4))]
        );
    }

    #[test]
    fn a_view_added_while_no_frame_is_pending_gets_a_frame() {
        let platform = Rc::new(TestPlatform::new().with_views(&[ViewId(2)]));
        let mut shell = Shell::new(platform.clone(), |_app| {});
        assert_eq!(platform.take_frame_requests(), [], "no frame is pending");
        shell.view_added(ViewId(2));
        assert_eq!(platform.take_frame_requests(), [ViewId(2)]);
    }

    #[test]
    fn a_view_close_request_reaches_the_framework() {
        let heard = Rc::new(Cell::new(None));
        let heard_slot = Rc::clone(&heard);
        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app: &mut App| {
            app.platform_callbacks_mut().on_view_close_requested =
                Some(Rc::new(move |_app, view| heard_slot.set(Some(view))));
        });
        shell.view_close_requested(ViewId(3));
        assert_eq!(heard.get(), Some(ViewId(3)));
    }

    #[test]
    fn a_window_change_reaches_the_framework() {
        let heard = Rc::new(Cell::new(None));
        let heard_slot = Rc::clone(&heard);
        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app: &mut App| {
            app.platform_callbacks_mut().on_window_changed =
                Some(Rc::new(move |_app, view| heard_slot.set(Some(view))));
        });
        shell.window_changed(ViewId(5));
        assert_eq!(heard.get(), Some(ViewId(5)));
    }

    #[test]
    fn a_lifecycle_state_the_host_reports_reaches_the_scheduler_with_the_states_between() {
        let mut shell = Shell::new(Rc::new(TestPlatform::new()), |_app| {});
        shell.app_lifecycle_state_changed(AppLifecycleState::Resumed);
        shell.app_lifecycle_state_changed(AppLifecycleState::Hidden);
        let mut app = shell.app();
        assert_eq!(
            SchedulerBinding::lifecycle_state(&mut app),
            Some(AppLifecycleState::Hidden)
        );
    }

    // Waft pauses each view out of sight in its host, not every view while the app is hidden:
    // a view the app added in another application's window, still in sight, keeps drawing.
    #[test]
    fn a_view_is_given_frames_while_the_app_is_hidden() {
        let platform = Rc::new(TestPlatform::new().with_views(&[IMPLICIT_VIEW_ID]));
        let mut shell = Shell::new(platform.clone(), |_app| {});
        shell.app_lifecycle_state_changed(AppLifecycleState::Hidden);
        platform.take_frame_requests();

        SchedulerBinding::schedule_frame(&mut shell.app(), FrameTarget::View(IMPLICIT_VIEW_ID));
        assert_eq!(platform.take_frame_requests(), [IMPLICIT_VIEW_ID]);
    }

    #[test]
    fn resuming_marks_every_view_to_be_rendered_and_asks_each_for_a_frame() {
        use waft_rendering::RendererBinding;

        let platform = Rc::new(TestPlatform::new().with_views(&[IMPLICIT_VIEW_ID, ViewId(1)]));
        let first = platform.test_view(IMPLICIT_VIEW_ID);
        let mut shell = Shell::new(platform.clone(), |_app| {});
        let render_view = {
            let mut app = shell.app();
            let binding = RendererBinding::instance(&mut app);
            binding.init_render_view(&mut app, first.clone())
        };
        let at = |ms| Frame {
            elapsed: Duration::from_millis(ms),
            vsync: None,
        };
        shell.frame(&[IMPLICIT_VIEW_ID], at(16));
        shell.frame(&[IMPLICIT_VIEW_ID], at(32));
        assert_eq!(
            first.presented(),
            1,
            "nothing changed after the first frame"
        );

        shell.app_lifecycle_state_changed(AppLifecycleState::Hidden);
        platform.take_frame_requests();
        shell.app_lifecycle_state_changed(AppLifecycleState::Resumed);
        assert_eq!(
            platform.take_frame_requests(),
            [IMPLICIT_VIEW_ID, ViewId(1)]
        );
        assert!(render_view.needs_composite_frame(&shell.app()));
        shell.frame(&[IMPLICIT_VIEW_ID], at(48));
        assert_eq!(first.presented(), 2, "drawn again though nothing changed");
    }

    #[test]
    fn request_app_exit_is_answered_by_the_services_binding() {
        use waft_embedder::AppExitResponse;
        use waft_foundation::{Handle, Task};
        use waft_services::{ServicesBinding, ServicesBindingOverridesObject};

        #[derive(Default)]
        struct Refusing;

        impl ServicesBindingOverridesObject for Refusing {
            fn handle_request_app_exit(
                self: Handle<Self>,
                _app: &mut App,
            ) -> Task<AppExitResponse> {
                Task::ready(AppExitResponse::Cancel)
            }
        }

        let mut shell = Shell::new(Rc::new(TestPlatform::new()), |_app| {});
        let (reply, answer) = recorded_reply();
        shell.request_app_exit(reply);
        assert_eq!(answer.get(), Some(AppExitResponse::Exit));

        let refusing = shell.app().create(Refusing);
        let binding = ServicesBinding::instance(&mut shell.app());
        binding.set_overrides(&mut shell.app(), Rc::new(refusing));
        let (reply, answer) = recorded_reply();
        shell.request_app_exit(reply);
        assert_eq!(answer.get(), Some(AppExitResponse::Cancel));
    }

    /// A host's call reaches the framework's table, and the answer comes back through the reply.
    #[test]
    fn a_service_extension_call_is_answered_by_the_framework() {
        use std::cell::RefCell;

        use waft_embedder::{
            ServiceExtensionCall, ServiceExtensionParams, ServiceExtensionReply,
            ServiceExtensionResult,
        };
        use waft_foundation::{ServiceExtensions, Task};

        let mut shell = Shell::new(Rc::new(TestPlatform::new()), |app| {
            ServiceExtensions::register(
                app,
                "ext.test.greet",
                Rc::new(|_app, params| {
                    Task::ready(Ok(serde_json::json!({ "greeting": params.get("name") })))
                }),
            );
        });
        let answer: Rc<RefCell<Option<ServiceExtensionResult>>> = Rc::new(RefCell::new(None));
        let to = Rc::clone(&answer);
        shell.service_extension_call(ServiceExtensionCall {
            name: "ext.test.greet".to_owned(),
            params: ServiceExtensionParams::new([("name".to_owned(), "WaOS".to_owned())]),
            reply: ServiceExtensionReply::new(move |result| *to.borrow_mut() = Some(result)),
        });
        assert_eq!(
            answer.borrow_mut().take(),
            Some(Ok(serde_json::json!({ "greeting": "WaOS" })))
        );
    }

    /// The reply is answered inside the call that decides.
    #[test]
    fn request_app_exit_answers_during_the_call_in_which_the_framework_decides() {
        use waft_embedder::AppExitResponse;
        use waft_foundation::{Completer, Handle, Task};
        use waft_services::{ServicesBinding, ServicesBindingOverridesObject};

        struct Deciding {
            decision: Completer<AppExitResponse>,
        }

        impl ServicesBindingOverridesObject for Deciding {
            fn handle_request_app_exit(self: Handle<Self>, app: &mut App) -> Task<AppExitResponse> {
                let decision = app.get(self).decision.future();
                app.spawn(async move |_cx| decision.await)
            }
        }

        let decision = Completer::new();
        let mut shell = Shell::new(Rc::new(TestPlatform::new()), |_app| {});
        let deciding = shell.app().create(Deciding {
            decision: decision.clone(),
        });
        let binding = ServicesBinding::instance(&mut shell.app());
        binding.set_overrides(&mut shell.app(), Rc::new(deciding));

        let (reply, answer) = recorded_reply();
        shell.request_app_exit(reply);
        assert_eq!(answer.get(), None);

        decision.complete(&mut shell.app(), AppExitResponse::Exit);
        assert_eq!(answer.get(), None, "the task resumes at a checkpoint");
        shell.wake(Duration::ZERO);
        assert_eq!(answer.get(), Some(AppExitResponse::Exit));
    }

    #[test]
    fn new_runs_setup_and_frame_runs_both_scheduler_phases() {
        let platform = Rc::new(platform_with_a_view());
        let mut setup_ran = false;
        let mut shell = Shell::new(platform.clone(), |_app: &mut App| {
            setup_ran = true;
        });
        assert!(setup_ran);
        assert!(platform.frame_requests().is_empty());

        SchedulerBinding::schedule_frame(&mut shell.app(), FrameTarget::View(IMPLICIT_VIEW_ID));
        assert_eq!(platform.frame_requests(), [IMPLICIT_VIEW_ID]);
        shell.frame(
            &[IMPLICIT_VIEW_ID],
            Frame {
                elapsed: Duration::from_millis(16),
                vsync: None,
            },
        );
    }

    #[test]
    fn a_reported_press_reaches_gesture_binding_numbered_by_the_converter() {
        let ran = Rc::new(Cell::new(false));
        let ran_flag = Rc::clone(&ran);
        let platform = Rc::new(platform_with_a_view());
        let mut shell = Shell::new(platform, |app| {
            let binding = GestureBinding::instance(app);
            binding.pointer_router(app).add_route(
                app,
                1,
                PointerRoute::new(move |_app, _event| {
                    ran_flag.set(true);
                }),
                None,
            );
        });

        shell.pointer_reports(vec![PointerReport {
            view_id: IMPLICIT_VIEW_ID,
            time_stamp: Duration::ZERO,
            device: 0,
            kind: PointerDeviceKind::Mouse,
            position: [0.0, 0.0],
            change: ReportedChange::Down { buttons: 1 },
            contact: Contact::default(),
        }]);
        assert!(ran.get(), "the first press is pointer 1");
    }

    #[test]
    fn key_data_reaches_the_hardware_keyboard() {
        let seen = Rc::new(Cell::new(0));
        let seen_flag = Rc::clone(&seen);
        let platform = Rc::new(TestPlatform::new());
        let mut shell = Shell::new(platform, |app| {
            HardwareKeyboard::instance(app).add_handler(
                app,
                Rc::new(move |_app: &mut App, _event: &KeyEvent| {
                    seen_flag.set(seen_flag.get() + 1);
                    true
                }),
            );
        });

        let key_a = KeyData {
            event_type: KeyEventType::Down,
            physical: PhysicalKeyboardKey::KEY_A.usb_hid_usage,
            logical: LogicalKeyboardKey::KEY_A.key_id,
            character: Some("a".to_owned()),
            ..KeyData::default()
        };
        assert!(shell.key_data(key_a), "the handler claimed the event");
        assert_eq!(seen.get(), 1);

        let keyboard = HardwareKeyboard::instance(&mut shell.app());
        assert!(keyboard.is_logical_key_pressed(&shell.app(), LogicalKeyboardKey::KEY_A));
    }

    #[test]
    fn wake_and_frame_advance_the_app_clock_and_fire_due_timers() {
        let platform = Rc::new(TestPlatform::new());
        let fired = Rc::new(Cell::new(Vec::new()));
        let mut shell = Shell::new(platform, |app| {
            for (name, delay) in [("early", 10), ("late", 30)] {
                let fired = Rc::clone(&fired);
                waft_foundation::Timer::new(
                    app,
                    Duration::from_millis(delay),
                    waft_foundation::Listener::new(move |_app| {
                        let mut log = fired.take();
                        log.push(name);
                        fired.set(log);
                    }),
                );
            }
        });
        assert!(fired.take().is_empty());

        shell.wake(Duration::from_millis(15));
        assert_eq!(fired.take(), vec!["early"]);

        shell.frame(
            &[IMPLICIT_VIEW_ID],
            Frame {
                elapsed: Duration::from_millis(32),
                vsync: None,
            },
        );
        assert_eq!(fired.take(), vec!["late"]);
    }

    #[test]
    fn a_late_wake_catches_a_periodic_timer_up_as_dart_does() {
        let platform = Rc::new(TestPlatform::new());
        let ticks = Rc::new(Cell::new(Vec::new()));
        let heard = Rc::clone(&ticks);
        let mut shell = Shell::new(platform, move |app| {
            let heard = Rc::clone(&heard);
            waft_foundation::Timer::periodic(app, Duration::from_millis(1), move |app, timer| {
                let mut seen = heard.take();
                seen.push(timer.tick(app));
                heard.set(seen);
            });
        });

        // The app was away for 100 s; its 1 ms timer fires once and its tick jumps.
        shell.wake(Duration::from_secs(100));
        assert_eq!(ticks.take(), [100_000]);
    }

    /// The refresh period of the frames below, a 60 Hz display's, in the microseconds the
    /// framework's frame times are counted in.
    const REFRESH: Duration = Duration::from_micros(16_667);

    /// A frame drawn at the vsync `start`, whose picture is for the next one, its drawing begun at
    /// `elapsed` on the platform's clock.
    fn frame_at_vsync(start: Duration, elapsed: Duration) -> Frame {
        Frame {
            elapsed,
            vsync: Some(waft_embedder::FrameVsync {
                start,
                target: start + REFRESH,
            }),
        }
    }

    /// The times a running ticker hears in each frame `frames` hands the shell.
    fn ticks_at(frames: &[Frame]) -> Vec<Duration> {
        use waft_scheduler::{FrameCallback, Ticker};

        let ticks = Rc::new(Cell::new(Vec::new()));
        let heard = Rc::clone(&ticks);
        // The ticker runs for as long as something keeps it.
        let ticker = Rc::new(RefCell::new(None));
        let kept = Rc::clone(&ticker);
        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app| {
            let on_tick = FrameCallback::new(move |_app, elapsed| {
                let mut ticks = heard.take();
                ticks.push(elapsed);
                heard.set(ticks);
            });
            let ticker = Ticker::new(app, on_tick, None);
            ticker.start(app);
            *kept.borrow_mut() = Some(ticker);
        });
        for frame in frames {
            shell.frame(&[IMPLICIT_VIEW_ID], *frame);
        }
        ticks.take()
    }

    #[test]
    fn a_frame_whose_drawing_starts_late_still_advances_by_the_vsync_interval() {
        let ticks = ticks_at(&[
            frame_at_vsync(Duration::ZERO, Duration::from_millis(1)),
            // The next refresh's drawing begins 20 ms late, three refreshes after the first.
            frame_at_vsync(REFRESH, Duration::from_millis(37)),
        ]);
        assert_eq!(ticks, [Duration::ZERO, REFRESH]);
    }

    #[test]
    fn a_frame_drawn_outside_a_vsync_takes_the_platforms_clock() {
        let at = |ms| Frame {
            elapsed: Duration::from_millis(ms),
            vsync: None,
        };
        let ticks = ticks_at(&[at(1), at(37)]);
        assert_eq!(ticks, [Duration::ZERO, Duration::from_millis(36)]);
    }

    #[test]
    fn a_vsync_frame_after_timers_fire_them_at_the_platforms_clock() {
        let platform = Rc::new(TestPlatform::new());
        let fired = Rc::new(Cell::new(false));
        let fired_flag = Rc::clone(&fired);
        let mut shell = Shell::new(platform, move |app| {
            let fired_flag = Rc::clone(&fired_flag);
            waft_foundation::Timer::new(
                app,
                Duration::from_millis(30),
                waft_foundation::Listener::new(move |_app| fired_flag.set(true)),
            );
        });
        // The vsync's target is past the timer's time, but the platform's clock is not.
        shell.frame(
            &[IMPLICIT_VIEW_ID],
            frame_at_vsync(Duration::from_millis(20), Duration::from_millis(25)),
        );
        assert!(
            !fired.get(),
            "a timer runs to the platform's clock, not the vsync's"
        );
        shell.frame(
            &[IMPLICIT_VIEW_ID],
            frame_at_vsync(Duration::from_millis(30), Duration::from_millis(31)),
        );
        assert!(fired.get());
    }

    #[test]
    fn a_view_coming_or_going_and_a_change_to_the_screens_are_metrics_changes() {
        use waft_foundation::Handle;
        use waft_rendering::{RendererBinding, RendererBindingOverridesObject};

        struct CountingMetricsChanges {
            count: Rc<Cell<usize>>,
        }

        impl RendererBindingOverridesObject for CountingMetricsChanges {
            fn will_draw_frame(self: Handle<Self>, _app: &mut App) {}

            fn did_draw_frame(self: Handle<Self>, _app: &mut App) {}

            fn did_handle_metrics_changed(self: Handle<Self>, app: &mut App) {
                let count = &app.get(self).count;
                count.set(count.get() + 1);
            }
        }

        let count = Rc::new(Cell::new(0));
        let mut shell = Shell::new(Rc::new(platform_with_a_view()), |_app| {});
        let counting = shell.app().create(CountingMetricsChanges {
            count: Rc::clone(&count),
        });
        let binding = RendererBinding::instance(&mut shell.app());
        binding.set_overrides(&mut shell.app(), Rc::new(counting));

        shell.view_added(ViewId(1));
        assert_eq!(count.get(), 1, "a view added");
        shell.view_removed(ViewId(1));
        assert_eq!(count.get(), 2, "a view removed");
        shell.screens_changed();
        assert_eq!(count.get(), 3, "the screens changed");
    }

    #[test]
    fn view_focus_is_delivered_through_the_dispatcher_callback() {
        use waft_embedder::{ViewFocusDirection, ViewFocusEvent, ViewFocusState};
        let received = Rc::new(Cell::new(None));
        let sink = received.clone();
        let platform = Rc::new(platform_with_a_view());
        let mut shell = Shell::new(platform, move |app| {
            app.platform_callbacks_mut().on_view_focus_change = Some(Rc::new(move |app, event| {
                let sink = sink.clone();
                app.schedule_microtask(waft_foundation::Listener::new(move |_| {
                    sink.set(Some(event))
                }));
            }));
        });
        shell.view_focus_changed(ViewFocusEvent {
            view_id: IMPLICIT_VIEW_ID,
            state: ViewFocusState::Focused,
            direction: ViewFocusDirection::Backward,
        });
        let event = received
            .get()
            .expect("the shell checkpoints the callback's microtask");
        assert_eq!(event.view_id, IMPLICIT_VIEW_ID);
        assert_eq!(event.state, ViewFocusState::Focused);
        assert_eq!(event.direction, ViewFocusDirection::Backward);
    }
}