Skip to main content

waft_shell/
lib.rs

1//! The one [`EmbedderClient`] the framework provides: owns the [`AppCell`] and
2//! translates host pushes into binding methods.
3//!
4//! Dart has no type for this — the engine owns the isolate. [`App`] stays in
5//! foundation. This crate sits above scheduler and gestures so the isolate
6//! can name both.
7#![feature(arbitrary_self_types)]
8
9use std::cell::RefMut;
10use std::rc::Rc;
11use std::time::Duration;
12
13use waft_embedder::{
14    AppExitReply, AppLifecycleState, ClipboardEvent, DragReport, EditCommand, EmbedderClient,
15    Frame, Instant, KeyData, MenuId, NotificationActivation, OpenRequest, PlatformRef, PointerData,
16    PointerDataPacket, PointerDataPacketConverter, PointerReport, RequestId, TextEditingValue,
17    TextInputAction, TrayIconEvent, TrayIconId, ViewError, ViewFocusEvent, ViewId,
18};
19use waft_foundation::{App, AppCell};
20use waft_gestures::GestureBinding;
21use waft_painting::PaintingBinding;
22use waft_rendering::RendererBinding;
23use waft_scheduler::{FrameTarget, SchedulerBinding};
24use waft_services::{KeyEventManager, ServicesBinding, TextInput};
25
26/// Host-facing isolate: the [`AppCell`] plus the methods the embedder pushes.
27///
28/// Every push is one call into the app: the `App` is borrowed for the binding call and
29/// released before the cell's checkpoint, where the microtasks and futures the event queued
30/// run.
31pub struct Shell {
32    app: Rc<AppCell>,
33    platform: PlatformRef,
34    /// The platform time the app clock was last advanced to.
35    clock: Duration,
36    /// 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.
37    origin: Option<Instant>,
38    /// What the framework was last told of each pointing device, as `RuntimeController` keeps it.
39    pointer_data_packet_converter: PointerDataPacketConverter,
40}
41
42impl Shell {
43    /// Builds the heap from `platform`, then runs application setup.
44    ///
45    /// Setup (later widgets `run_app`) requests the first frame when it
46    /// installs work that needs one.
47    pub fn new(platform: PlatformRef, setup: impl FnOnce(&mut App)) -> Shell {
48        let shell = Shell {
49            app: AppCell::with_platform(platform.clone()),
50            platform,
51            clock: Duration::ZERO,
52            origin: None,
53            pointer_data_packet_converter: PointerDataPacketConverter::new(),
54        };
55        shell.handle_event(|app| {
56            // Flutter's engine collects the platform's fonts before the framework runs.
57            PaintingBinding::instance(app).install_platform_fonts(app);
58            setup(app);
59        });
60        shell
61    }
62
63    /// The `App`, borrowed until the guard drops. A host that needs the whole thing, a borrow
64    /// and then the checkpoint, takes [`cell`](Self::cell).
65    pub fn app(&self) -> RefMut<'_, App> {
66        self.app.borrow_mut()
67    }
68
69    pub fn cell(&self) -> &Rc<AppCell> {
70        &self.app
71    }
72
73    /// One platform event: `f` on the borrowed `App`, then the checkpoint.
74    fn handle_event<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
75        let result = f(&mut self.app.borrow_mut());
76        self.app.checkpoint();
77        result
78    }
79
80    /// An input or platform push: the app clock catches up with the platform's first, as Dart's
81    /// timers measure real time from the moment they are created, then `f` runs.
82    fn push<R>(&mut self, f: impl FnOnce(&mut App) -> R) -> R {
83        if let Some(origin) = self.origin {
84            let elapsed = self.platform.now().saturating_duration_since(origin);
85            self.advance_clock(elapsed);
86        }
87        self.handle_event(f)
88    }
89
90    /// Moves the app clock up to the platform's `elapsed`, firing the timers that came due as
91    /// Dart's VM does after the event loop was away: once each, their ticks jumping over the
92    /// periods that passed.
93    fn advance_clock(&mut self, elapsed: Duration) {
94        if elapsed <= self.clock {
95            return;
96        }
97        self.app.elapse_to(elapsed);
98        self.clock = elapsed;
99    }
100
101    /// dart:ui's `onMetricsChanged`, which the framework sets to
102    /// `RendererBinding.handleMetricsChanged`. `_addView`, `_removeView` and `_updateDisplays`
103    /// invoke it as `_updateWindowMetrics` does: a view coming or going, and a change to the
104    /// screens, reach the app only this way.
105    fn metrics_changed(&mut self) {
106        self.push(|app| RendererBinding::instance(app).handle_metrics_changed(app));
107    }
108}
109
110impl EmbedderClient for Shell {
111    /// The app's timers run to the platform's clock, and the frame's time is its vsync's target,
112    /// as the engine hands `_beginFrame` (`Animator::BeginFrame`); a frame drawn outside a vsync
113    /// takes the platform's clock.
114    fn frame(&mut self, views: &[ViewId], frame: Frame) {
115        self.origin = Some(self.platform.now() - frame.elapsed);
116        self.advance_clock(frame.elapsed);
117        let time_stamp = frame.vsync.map_or(frame.elapsed, |vsync| vsync.target);
118        // The engine runs `_beginFrame` and `_drawFrame` as two native tasks: two calls.
119        self.handle_event(|app| SchedulerBinding::on_begin_frame(app, views, Some(time_stamp)));
120        self.handle_event(|app| SchedulerBinding::on_draw_frame(app, views));
121    }
122
123    /// The framework hears which view came, then "metrics changed", as `_addView` invokes it;
124    /// then a frame is scheduled, as `RuntimeController::AddView` schedules one once the view is
125    /// added. Without it, a build scheduled while the app had no view, such as the one that puts
126    /// the new view's window on it, would wait for an event of the view's window, which a Wayland
127    /// window, unseen until it presents a picture, never sends.
128    fn view_added(&mut self, id: ViewId) {
129        self.push(|app| {
130            let callback = app.platform_callbacks().on_view_added.clone();
131            if let Some(callback) = callback {
132                callback(app, id);
133            }
134        });
135        self.metrics_changed();
136        self.handle_event(|app| SchedulerBinding::schedule_frame(app, FrameTarget::View(id)));
137    }
138
139    fn view_metrics_changed(&mut self, _id: ViewId) {
140        self.metrics_changed();
141    }
142
143    /// The framework hears which view went, then "metrics changed", as `_removeView` invokes
144    /// it.
145    fn view_removed(&mut self, id: ViewId) {
146        self.push(|app| {
147            let callback = app.platform_callbacks().on_view_removed.clone();
148            if let Some(callback) = callback {
149                callback(app, id);
150            }
151        });
152        self.metrics_changed();
153    }
154
155    /// "Metrics changed", as `_updateDisplays` invokes it.
156    fn screens_changed(&mut self) {
157        self.metrics_changed();
158    }
159
160    fn view_focus_changed(&mut self, event: ViewFocusEvent) {
161        self.push(|app| {
162            let callback = app.platform_callbacks().on_view_focus_change.clone();
163            if let Some(callback) = callback {
164                callback(app, event);
165            }
166        });
167    }
168
169    fn drag_report(&mut self, report: DragReport) {
170        self.push(|app| {
171            let callback = app.platform_callbacks().on_drag.clone();
172            if let Some(callback) = callback {
173                callback(app, report);
174            }
175        });
176    }
177
178    fn clipboard_event(&mut self, view: ViewId, event: ClipboardEvent) {
179        self.push(|app| {
180            let callback = app.platform_callbacks().on_clipboard_event.clone();
181            if let Some(callback) = callback {
182                callback(app, view, event);
183            }
184        });
185    }
186
187    fn edit_command(&mut self, view: ViewId, command: EditCommand) {
188        self.push(|app| {
189            let callback = app.platform_callbacks().on_edit_command.clone();
190            if let Some(callback) = callback {
191                callback(app, view, command);
192            }
193        });
194    }
195
196    fn menu_selected(&mut self, id: MenuId) {
197        self.push(|app| {
198            let callback = app.platform_callbacks().on_menu_selected.clone();
199            if let Some(callback) = callback {
200                callback(app, id);
201            }
202        });
203    }
204
205    fn dock_menu_selected(&mut self, id: MenuId) {
206        self.push(|app| {
207            let callback = app.platform_callbacks().on_dock_menu_selected.clone();
208            if let Some(callback) = callback {
209                callback(app, id);
210            }
211        });
212    }
213
214    fn tray_icon_event(&mut self, icon: TrayIconId, event: TrayIconEvent) {
215        self.push(|app| {
216            let callback = app.platform_callbacks().on_tray_icon_event.clone();
217            if let Some(callback) = callback {
218                callback(app, icon, event);
219            }
220        });
221    }
222
223    fn open_requested(&mut self, request: OpenRequest) {
224        self.push(|app| app.open_requested(request));
225    }
226
227    fn notification_activated(&mut self, activation: NotificationActivation) {
228        self.push(|app| app.notification_activated(activation));
229    }
230
231    fn pointer_reports(&mut self, reports: Vec<PointerReport>) {
232        let packet = PointerDataPacket::new(reports.into_iter().map(PointerData::from).collect());
233        let platform = &self.platform;
234        let packet = self
235            .pointer_data_packet_converter
236            .convert(&packet, |view_id| platform.view(view_id).is_some());
237        self.push(|app| GestureBinding::instance(app).handle_pointer_data_packet(app, packet));
238    }
239
240    fn key_data(&mut self, data: KeyData) -> bool {
241        self.push(|app| KeyEventManager::instance(app).handle_key_data(app, data))
242    }
243
244    fn pop_route(&mut self, view: ViewId) -> bool {
245        self.push(|app| {
246            let callback = app.platform_callbacks().on_pop_route.clone();
247            callback.is_some_and(|callback| callback(app, view))
248        })
249    }
250
251    fn view_close_requested(&mut self, view: ViewId) {
252        self.push(|app| {
253            let callback = app.platform_callbacks().on_view_close_requested.clone();
254            if let Some(callback) = callback {
255                callback(app, view);
256            }
257        });
258    }
259
260    fn window_changed(&mut self, view: ViewId) {
261        self.push(|app| {
262            let callback = app.platform_callbacks().on_window_changed.clone();
263            if let Some(callback) = callback {
264                callback(app, view);
265            }
266        });
267    }
268
269    fn view_request_failed(&mut self, request: RequestId, error: ViewError) {
270        self.push(|app| {
271            let callback = app.platform_callbacks().on_view_request_failed.clone();
272            if let Some(callback) = callback {
273                callback(app, request, error);
274            }
275        });
276    }
277
278    /// The binding's answer goes to `reply` at the checkpoint of the call in which the
279    /// observers decide: this push's own when they answer at once.
280    fn request_app_exit(&mut self, reply: AppExitReply) {
281        self.push(|app| {
282            let answer = ServicesBinding::instance(app).handle_request_app_exit(app);
283            app.spawn(async move |_cx| reply.answer(answer.await));
284        });
285    }
286
287    /// On `resumed` or `inactive`, every view is marked to present and asked for a frame before
288    /// the bindings hear the state: a view that did not change while the app was away would
289    /// otherwise present nothing.
290    fn app_lifecycle_state_changed(&mut self, state: AppLifecycleState) {
291        self.push(|app| {
292            if matches!(
293                state,
294                AppLifecycleState::Resumed | AppLifecycleState::Inactive
295            ) {
296                RendererBinding::instance(app).handle_mark_all_views_need_render(app);
297                SchedulerBinding::schedule_forced_frame(app, FrameTarget::EveryView);
298            }
299            ServicesBinding::instance(app).handle_lifecycle_message(app, state);
300        });
301    }
302
303    fn platform_brightness_changed(&mut self) {
304        self.push(|app| {
305            let callback = app
306                .platform_callbacks()
307                .on_platform_brightness_changed
308                .clone();
309            if let Some(callback) = callback {
310                callback.call(app);
311            }
312        });
313    }
314
315    fn locales_changed(&mut self) {
316        self.push(|app| {
317            let callback = app.platform_callbacks().on_locale_changed.clone();
318            if let Some(callback) = callback {
319                callback.call(app);
320            }
321        });
322    }
323
324    fn system_fonts_changed(&mut self) {
325        self.push(|app| {
326            PaintingBinding::instance(app).handle_system_fonts_did_change(app);
327        });
328    }
329
330    fn clipboard_changed(&mut self) {
331        self.push(|app| ServicesBinding::instance(app).handle_clipboard_changed(app));
332    }
333
334    fn wake(&mut self, elapsed: Duration) {
335        self.advance_clock(elapsed);
336        // A wake with no time behind it is a post from a native callback.
337        self.app.wake();
338    }
339
340    fn text_input_editing_value(&mut self, _view: ViewId, value: TextEditingValue) {
341        self.push(|app| TextInput::instance(app).update_editing_value(app, value));
342    }
343
344    fn text_input_action(&mut self, _view: ViewId, action: TextInputAction) {
345        self.push(|app| TextInput::instance(app).perform_action(app, action));
346    }
347
348    fn text_input_closed(&mut self, _view: ViewId) {
349        self.push(|app| TextInput::instance(app).connection_closed(app));
350    }
351
352    fn system_context_menu_hidden(&mut self) {
353        self.push(waft_services::SystemContextMenuController::dispatch_system_hide);
354    }
355
356    fn custom_context_menu_action(&mut self, callback_id: &str) {
357        let callback_id = callback_id.to_string();
358        self.push(move |app| {
359            waft_services::SystemContextMenuController::dispatch_custom_action(app, &callback_id);
360        });
361    }
362}
363
364#[cfg(test)]
365mod tests {
366    use std::cell::{Cell, RefCell};
367    use std::rc::Rc;
368    use std::time::Duration;
369
370    use waft_embedder::{
371        AppLifecycleState, Contact, EmbedderClient, Frame, KeyData, KeyEventType,
372        PointerDeviceKind, PointerReport, ReportedChange, ViewId,
373    };
374    use waft_foundation::App;
375    use waft_gestures::{GestureBinding, PointerRoute};
376    use waft_scheduler::{FrameTarget, SchedulerBinding};
377    use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey, PhysicalKeyboardKey};
378    use waft_test::{IMPLICIT_VIEW_ID, TestPlatform};
379
380    use super::Shell;
381
382    /// A platform with the one view a pointer packet, a focus event or a frame is addressed to.
383    fn platform_with_a_view() -> TestPlatform {
384        TestPlatform::new().with_views(&[IMPLICIT_VIEW_ID])
385    }
386
387    #[test]
388    fn a_read_started_by_a_task_the_drop_spawns_is_in_time() {
389        use std::cell::RefCell;
390
391        use waft_embedder::{
392            ClipboardReadFuture, DataTransferItem, DragChange, DragReport, DraggedItems,
393        };
394
395        struct Text([String; 1]);
396
397        impl DataTransferItem for Text {
398            fn types(&self) -> &[String] {
399                &self.0
400            }
401
402            fn read(&self, _mime: &str) -> ClipboardReadFuture {
403                Box::pin(std::future::ready(Ok(b"hi".to_vec())))
404            }
405        }
406
407        let read = Rc::new(RefCell::new(None));
408        let read_slot = Rc::clone(&read);
409        let platform = Rc::new(platform_with_a_view());
410        let mut shell = Shell::new(platform, move |app: &mut App| {
411            app.platform_callbacks_mut().on_drag = Some(Rc::new(move |app, report| {
412                let read_slot = Rc::clone(&read_slot);
413                let item = Rc::clone(&report.items[0]);
414                // Dropping the task lets it run, as a Dart future does.
415                let _reading = app.spawn(async move |_cx| {
416                    *read_slot.borrow_mut() = Some(item.read("text/plain").await);
417                });
418            }));
419        });
420        let dragged = DraggedItems::new(vec![Box::new(Text(["text/plain".to_owned()]))]);
421        let drop = DragReport {
422            view_id: IMPLICIT_VIEW_ID,
423            change: DragChange::Dropped,
424            physical_position: None,
425            items: dragged.items(),
426        };
427        dragged.report_drop(|| shell.drag_report(drop));
428        assert_eq!(*read.borrow(), Some(Ok(b"hi".to_vec())));
429    }
430
431    #[test]
432    fn a_clipboard_event_reaches_the_platform_callback_with_its_view() {
433        use waft_embedder::{ClipboardEvent, CopyRequest};
434
435        let seen = Rc::new(Cell::new(None));
436        let seen_slot = Rc::clone(&seen);
437        let mut shell = Shell::new(Rc::new(platform_with_a_view()), move |app: &mut App| {
438            app.platform_callbacks_mut().on_clipboard_event =
439                Some(Rc::new(move |_app, view, event| {
440                    seen_slot.set(Some((view, matches!(event, ClipboardEvent::Cut(_)))));
441                }));
442        });
443        let request = CopyRequest::new(|_items, _options| Box::pin(std::future::ready(Ok(()))));
444        shell.clipboard_event(IMPLICIT_VIEW_ID, ClipboardEvent::Cut(request));
445        assert_eq!(seen.get(), Some((IMPLICIT_VIEW_ID, true)));
446    }
447
448    #[test]
449    fn an_open_request_waits_for_the_apps_handler() {
450        use std::cell::RefCell;
451
452        use waft_embedder::OpenRequest;
453
454        let seen = Rc::new(RefCell::new(Vec::new()));
455        let mut shell = Shell::new(Rc::new(platform_with_a_view()), |_app: &mut App| {});
456        shell.open_requested(OpenRequest {
457            files: Vec::new(),
458            links: vec!["https://example.org/launch".to_owned()],
459        });
460        let slot = Rc::clone(&seen);
461        shell
462            .app
463            .borrow_mut()
464            .set_open_requested_handler(Some(Rc::new(move |_app, request: OpenRequest| {
465                slot.borrow_mut().extend(request.links)
466            })));
467        shell.open_requested(OpenRequest {
468            files: Vec::new(),
469            links: vec!["https://example.org/later".to_owned()],
470        });
471        assert_eq!(
472            *seen.borrow(),
473            ["https://example.org/launch", "https://example.org/later"],
474            "the launch's request waited for the handler"
475        );
476    }
477
478    #[test]
479    fn a_notification_click_waits_for_the_apps_handler() {
480        use std::cell::RefCell;
481
482        use waft_embedder::NotificationActivation;
483
484        let seen = Rc::new(RefCell::new(Vec::new()));
485        let mut shell = Shell::new(Rc::new(platform_with_a_view()), |_app: &mut App| {});
486        let click = |action: Option<&str>| NotificationActivation {
487            id: "message-7".to_owned(),
488            action: action.map(str::to_owned),
489            reply: None,
490        };
491        shell.notification_activated(click(None));
492        let slot = Rc::clone(&seen);
493        shell
494            .app
495            .borrow_mut()
496            .set_notification_activated_handler(Some(Rc::new(move |_app, activation| {
497                slot.borrow_mut().push(activation)
498            })));
499        shell.notification_activated(click(Some("later")));
500        assert_eq!(
501            *seen.borrow(),
502            [click(None), click(Some("later"))],
503            "the click that started the app waited for the handler"
504        );
505    }
506
507    #[test]
508    fn menu_choices_edit_commands_and_tray_icon_events_reach_their_callbacks() {
509        use std::cell::RefCell;
510
511        use waft_embedder::{EditCommand, Offset, TrayIconEvent};
512
513        let seen = Rc::new(RefCell::new(Vec::new()));
514        let slot = Rc::clone(&seen);
515        let mut shell = Shell::new(Rc::new(platform_with_a_view()), move |app: &mut App| {
516            let callbacks = app.platform_callbacks_mut();
517            let menu = Rc::clone(&slot);
518            callbacks.on_menu_selected = Some(Rc::new(move |_app, id| {
519                menu.borrow_mut().push(format!("menu {id}"));
520            }));
521            let dock = Rc::clone(&slot);
522            callbacks.on_dock_menu_selected = Some(Rc::new(move |_app, id| {
523                dock.borrow_mut().push(format!("dock {id}"));
524            }));
525            let edit = Rc::clone(&slot);
526            callbacks.on_edit_command = Some(Rc::new(move |_app, view, command| {
527                edit.borrow_mut().push(format!("{view:?} {command:?}"));
528            }));
529            let tray = Rc::clone(&slot);
530            callbacks.on_tray_icon_event = Some(Rc::new(move |_app, icon, event| {
531                tray.borrow_mut().push(format!("tray {icon} {event:?}"));
532            }));
533        });
534        shell.menu_selected(3);
535        shell.dock_menu_selected(4);
536        shell.edit_command(IMPLICIT_VIEW_ID, EditCommand::Undo);
537        shell.tray_icon_event(
538            7,
539            TrayIconEvent::Activated {
540                position: Offset::new(1.0, 2.0),
541            },
542        );
543        assert_eq!(
544            *seen.borrow(),
545            [
546                "menu 3".to_owned(),
547                "dock 4".to_owned(),
548                format!("{IMPLICIT_VIEW_ID:?} Undo"),
549                format!(
550                    "tray 7 {:?}",
551                    TrayIconEvent::Activated {
552                        position: Offset::new(1.0, 2.0)
553                    }
554                ),
555            ]
556        );
557    }
558
559    #[test]
560    fn a_change_of_the_clipboard_reaches_the_services_bindings_listenable() {
561        use waft_foundation::{ListenableObject, Listener};
562        use waft_services::ServicesBinding;
563
564        let heard = Rc::new(Cell::new(0));
565        let counter = Rc::clone(&heard);
566        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app: &mut App| {
567            let clipboard = ServicesBinding::instance(app).clipboard(app);
568            clipboard.add_listener(
569                app,
570                Listener::new(move |_app| counter.set(counter.get() + 1)),
571            );
572        });
573        shell.clipboard_changed();
574        assert_eq!(heard.get(), 1);
575    }
576
577    /// A reply to `shell.request_app_exit`, and the answer it was given so far.
578    fn recorded_reply() -> (
579        waft_embedder::AppExitReply,
580        Rc<Cell<Option<waft_embedder::AppExitResponse>>>,
581    ) {
582        let answer = Rc::new(Cell::new(None));
583        let given = Rc::clone(&answer);
584        let reply = waft_embedder::AppExitReply::new(move |response| given.set(Some(response)));
585        (reply, answer)
586    }
587
588    #[test]
589    fn a_view_added_or_removed_reaches_the_framework_with_its_id() {
590        let heard = Rc::new(std::cell::RefCell::new(Vec::new()));
591        let (added, removed) = (Rc::clone(&heard), Rc::clone(&heard));
592        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app: &mut App| {
593            let callbacks = app.platform_callbacks_mut();
594            callbacks.on_view_added = Some(Rc::new(move |_app, view| {
595                added.borrow_mut().push(("added", view))
596            }));
597            callbacks.on_view_removed = Some(Rc::new(move |_app, view| {
598                removed.borrow_mut().push(("removed", view))
599            }));
600        });
601        shell.view_added(ViewId(4));
602        shell.view_removed(ViewId(4));
603        assert_eq!(
604            *heard.borrow(),
605            [("added", ViewId(4)), ("removed", ViewId(4))]
606        );
607    }
608
609    #[test]
610    fn a_view_added_while_no_frame_is_pending_gets_a_frame() {
611        let platform = Rc::new(TestPlatform::new().with_views(&[ViewId(2)]));
612        let mut shell = Shell::new(platform.clone(), |_app| {});
613        assert_eq!(platform.take_frame_requests(), [], "no frame is pending");
614        shell.view_added(ViewId(2));
615        assert_eq!(platform.take_frame_requests(), [ViewId(2)]);
616    }
617
618    #[test]
619    fn a_view_close_request_reaches_the_framework() {
620        let heard = Rc::new(Cell::new(None));
621        let heard_slot = Rc::clone(&heard);
622        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app: &mut App| {
623            app.platform_callbacks_mut().on_view_close_requested =
624                Some(Rc::new(move |_app, view| heard_slot.set(Some(view))));
625        });
626        shell.view_close_requested(ViewId(3));
627        assert_eq!(heard.get(), Some(ViewId(3)));
628    }
629
630    #[test]
631    fn a_window_change_reaches_the_framework() {
632        let heard = Rc::new(Cell::new(None));
633        let heard_slot = Rc::clone(&heard);
634        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app: &mut App| {
635            app.platform_callbacks_mut().on_window_changed =
636                Some(Rc::new(move |_app, view| heard_slot.set(Some(view))));
637        });
638        shell.window_changed(ViewId(5));
639        assert_eq!(heard.get(), Some(ViewId(5)));
640    }
641
642    #[test]
643    fn a_lifecycle_state_the_host_reports_reaches_the_scheduler_with_the_states_between() {
644        let mut shell = Shell::new(Rc::new(TestPlatform::new()), |_app| {});
645        shell.app_lifecycle_state_changed(AppLifecycleState::Resumed);
646        shell.app_lifecycle_state_changed(AppLifecycleState::Hidden);
647        let mut app = shell.app();
648        assert_eq!(
649            SchedulerBinding::lifecycle_state(&mut app),
650            Some(AppLifecycleState::Hidden)
651        );
652        assert!(!SchedulerBinding::frames_enabled(&mut app));
653    }
654
655    #[test]
656    fn resuming_marks_every_view_to_be_rendered_and_asks_each_for_a_frame() {
657        use waft_rendering::RendererBinding;
658
659        let platform = Rc::new(TestPlatform::new().with_views(&[IMPLICIT_VIEW_ID, ViewId(1)]));
660        let first = platform.test_view(IMPLICIT_VIEW_ID);
661        let mut shell = Shell::new(platform.clone(), |_app| {});
662        let render_view = {
663            let mut app = shell.app();
664            let binding = RendererBinding::instance(&mut app);
665            binding.init_render_view(&mut app, first.clone())
666        };
667        let at = |ms| Frame {
668            elapsed: Duration::from_millis(ms),
669            vsync: None,
670        };
671        shell.frame(&[IMPLICIT_VIEW_ID], at(16));
672        shell.frame(&[IMPLICIT_VIEW_ID], at(32));
673        assert_eq!(
674            first.presented(),
675            1,
676            "nothing changed after the first frame"
677        );
678
679        shell.app_lifecycle_state_changed(AppLifecycleState::Hidden);
680        platform.take_frame_requests();
681        shell.app_lifecycle_state_changed(AppLifecycleState::Resumed);
682        assert_eq!(
683            platform.take_frame_requests(),
684            [IMPLICIT_VIEW_ID, ViewId(1)]
685        );
686        assert!(render_view.needs_composite_frame(&shell.app()));
687        shell.frame(&[IMPLICIT_VIEW_ID], at(48));
688        assert_eq!(first.presented(), 2, "drawn again though nothing changed");
689    }
690
691    #[test]
692    fn request_app_exit_is_answered_by_the_services_binding() {
693        use waft_embedder::AppExitResponse;
694        use waft_foundation::{Handle, Task};
695        use waft_services::{ServicesBinding, ServicesBindingOverridesObject};
696
697        #[derive(Default)]
698        struct Refusing;
699
700        impl ServicesBindingOverridesObject for Refusing {
701            fn handle_request_app_exit(
702                self: Handle<Self>,
703                _app: &mut App,
704            ) -> Task<AppExitResponse> {
705                Task::ready(AppExitResponse::Cancel)
706            }
707        }
708
709        let mut shell = Shell::new(Rc::new(TestPlatform::new()), |_app| {});
710        let (reply, answer) = recorded_reply();
711        shell.request_app_exit(reply);
712        assert_eq!(answer.get(), Some(AppExitResponse::Exit));
713
714        let refusing = shell.app().create(Refusing);
715        let binding = ServicesBinding::instance(&mut shell.app());
716        binding.set_overrides(&mut shell.app(), Rc::new(refusing));
717        let (reply, answer) = recorded_reply();
718        shell.request_app_exit(reply);
719        assert_eq!(answer.get(), Some(AppExitResponse::Cancel));
720    }
721
722    /// The reply is answered inside the call that decides.
723    #[test]
724    fn request_app_exit_answers_during_the_call_in_which_the_framework_decides() {
725        use waft_embedder::AppExitResponse;
726        use waft_foundation::{Completer, Handle, Task};
727        use waft_services::{ServicesBinding, ServicesBindingOverridesObject};
728
729        struct Deciding {
730            decision: Completer<AppExitResponse>,
731        }
732
733        impl ServicesBindingOverridesObject for Deciding {
734            fn handle_request_app_exit(self: Handle<Self>, app: &mut App) -> Task<AppExitResponse> {
735                let decision = app.get(self).decision.future();
736                app.spawn(async move |_cx| decision.await)
737            }
738        }
739
740        let decision = Completer::new();
741        let mut shell = Shell::new(Rc::new(TestPlatform::new()), |_app| {});
742        let deciding = shell.app().create(Deciding {
743            decision: decision.clone(),
744        });
745        let binding = ServicesBinding::instance(&mut shell.app());
746        binding.set_overrides(&mut shell.app(), Rc::new(deciding));
747
748        let (reply, answer) = recorded_reply();
749        shell.request_app_exit(reply);
750        assert_eq!(answer.get(), None);
751
752        decision.complete(&mut shell.app(), AppExitResponse::Exit);
753        assert_eq!(answer.get(), None, "the task resumes at a checkpoint");
754        shell.wake(Duration::ZERO);
755        assert_eq!(answer.get(), Some(AppExitResponse::Exit));
756    }
757
758    #[test]
759    fn new_runs_setup_and_frame_runs_both_scheduler_phases() {
760        let platform = Rc::new(platform_with_a_view());
761        let mut setup_ran = false;
762        let mut shell = Shell::new(platform.clone(), |_app: &mut App| {
763            setup_ran = true;
764        });
765        assert!(setup_ran);
766        assert!(platform.frame_requests().is_empty());
767
768        SchedulerBinding::schedule_frame(&mut shell.app(), FrameTarget::View(IMPLICIT_VIEW_ID));
769        assert_eq!(platform.frame_requests(), [IMPLICIT_VIEW_ID]);
770        shell.frame(
771            &[IMPLICIT_VIEW_ID],
772            Frame {
773                elapsed: Duration::from_millis(16),
774                vsync: None,
775            },
776        );
777    }
778
779    #[test]
780    fn a_reported_press_reaches_gesture_binding_numbered_by_the_converter() {
781        let ran = Rc::new(Cell::new(false));
782        let ran_flag = Rc::clone(&ran);
783        let platform = Rc::new(platform_with_a_view());
784        let mut shell = Shell::new(platform, |app| {
785            let binding = GestureBinding::instance(app);
786            binding.pointer_router(app).add_route(
787                app,
788                1,
789                PointerRoute::new(move |_app, _event| {
790                    ran_flag.set(true);
791                }),
792                None,
793            );
794        });
795
796        shell.pointer_reports(vec![PointerReport {
797            view_id: IMPLICIT_VIEW_ID,
798            time_stamp: Duration::ZERO,
799            device: 0,
800            kind: PointerDeviceKind::Mouse,
801            position: [0.0, 0.0],
802            change: ReportedChange::Down { buttons: 1 },
803            contact: Contact::default(),
804        }]);
805        assert!(ran.get(), "the first press is pointer 1");
806    }
807
808    #[test]
809    fn key_data_reaches_the_hardware_keyboard() {
810        let seen = Rc::new(Cell::new(0));
811        let seen_flag = Rc::clone(&seen);
812        let platform = Rc::new(TestPlatform::new());
813        let mut shell = Shell::new(platform, |app| {
814            HardwareKeyboard::instance(app).add_handler(
815                app,
816                Rc::new(move |_app: &mut App, _event: &KeyEvent| {
817                    seen_flag.set(seen_flag.get() + 1);
818                    true
819                }),
820            );
821        });
822
823        let key_a = KeyData {
824            event_type: KeyEventType::Down,
825            physical: PhysicalKeyboardKey::KEY_A.usb_hid_usage,
826            logical: LogicalKeyboardKey::KEY_A.key_id,
827            character: Some("a".to_owned()),
828            ..KeyData::default()
829        };
830        assert!(shell.key_data(key_a), "the handler claimed the event");
831        assert_eq!(seen.get(), 1);
832
833        let keyboard = HardwareKeyboard::instance(&mut shell.app());
834        assert!(keyboard.is_logical_key_pressed(&shell.app(), LogicalKeyboardKey::KEY_A));
835    }
836
837    #[test]
838    fn wake_and_frame_advance_the_app_clock_and_fire_due_timers() {
839        let platform = Rc::new(TestPlatform::new());
840        let fired = Rc::new(Cell::new(Vec::new()));
841        let mut shell = Shell::new(platform, |app| {
842            for (name, delay) in [("early", 10), ("late", 30)] {
843                let fired = Rc::clone(&fired);
844                waft_foundation::Timer::new(
845                    app,
846                    Duration::from_millis(delay),
847                    waft_foundation::Listener::new(move |_app| {
848                        let mut log = fired.take();
849                        log.push(name);
850                        fired.set(log);
851                    }),
852                );
853            }
854        });
855        assert!(fired.take().is_empty());
856
857        shell.wake(Duration::from_millis(15));
858        assert_eq!(fired.take(), vec!["early"]);
859
860        shell.frame(
861            &[IMPLICIT_VIEW_ID],
862            Frame {
863                elapsed: Duration::from_millis(32),
864                vsync: None,
865            },
866        );
867        assert_eq!(fired.take(), vec!["late"]);
868    }
869
870    #[test]
871    fn a_late_wake_catches_a_periodic_timer_up_as_dart_does() {
872        let platform = Rc::new(TestPlatform::new());
873        let ticks = Rc::new(Cell::new(Vec::new()));
874        let heard = Rc::clone(&ticks);
875        let mut shell = Shell::new(platform, move |app| {
876            let heard = Rc::clone(&heard);
877            waft_foundation::Timer::periodic(app, Duration::from_millis(1), move |app, timer| {
878                let mut seen = heard.take();
879                seen.push(timer.tick(app));
880                heard.set(seen);
881            });
882        });
883
884        // The app was away for 100 s; its 1 ms timer fires once and its tick jumps.
885        shell.wake(Duration::from_secs(100));
886        assert_eq!(ticks.take(), [100_000]);
887    }
888
889    /// The refresh period of the frames below, a 60 Hz display's, in the microseconds the
890    /// framework's frame times are counted in.
891    const REFRESH: Duration = Duration::from_micros(16_667);
892
893    /// A frame drawn at the vsync `start`, whose picture is for the next one, its drawing begun at
894    /// `elapsed` on the platform's clock.
895    fn frame_at_vsync(start: Duration, elapsed: Duration) -> Frame {
896        Frame {
897            elapsed,
898            vsync: Some(waft_embedder::FrameVsync {
899                start,
900                target: start + REFRESH,
901            }),
902        }
903    }
904
905    /// The times a running ticker hears in each frame `frames` hands the shell.
906    fn ticks_at(frames: &[Frame]) -> Vec<Duration> {
907        use waft_scheduler::{FrameCallback, Ticker};
908
909        let ticks = Rc::new(Cell::new(Vec::new()));
910        let heard = Rc::clone(&ticks);
911        // The ticker runs for as long as something keeps it.
912        let ticker = Rc::new(RefCell::new(None));
913        let kept = Rc::clone(&ticker);
914        let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app| {
915            let on_tick = FrameCallback::new(move |_app, elapsed| {
916                let mut ticks = heard.take();
917                ticks.push(elapsed);
918                heard.set(ticks);
919            });
920            let ticker = Ticker::new(app, on_tick, None);
921            ticker.start(app);
922            *kept.borrow_mut() = Some(ticker);
923        });
924        for frame in frames {
925            shell.frame(&[IMPLICIT_VIEW_ID], *frame);
926        }
927        ticks.take()
928    }
929
930    #[test]
931    fn a_frame_whose_drawing_starts_late_still_advances_by_the_vsync_interval() {
932        let ticks = ticks_at(&[
933            frame_at_vsync(Duration::ZERO, Duration::from_millis(1)),
934            // The next refresh's drawing begins 20 ms late, three refreshes after the first.
935            frame_at_vsync(REFRESH, Duration::from_millis(37)),
936        ]);
937        assert_eq!(ticks, [Duration::ZERO, REFRESH]);
938    }
939
940    #[test]
941    fn a_frame_drawn_outside_a_vsync_takes_the_platforms_clock() {
942        let at = |ms| Frame {
943            elapsed: Duration::from_millis(ms),
944            vsync: None,
945        };
946        let ticks = ticks_at(&[at(1), at(37)]);
947        assert_eq!(ticks, [Duration::ZERO, Duration::from_millis(36)]);
948    }
949
950    #[test]
951    fn a_vsync_frame_after_timers_fire_them_at_the_platforms_clock() {
952        let platform = Rc::new(TestPlatform::new());
953        let fired = Rc::new(Cell::new(false));
954        let fired_flag = Rc::clone(&fired);
955        let mut shell = Shell::new(platform, move |app| {
956            let fired_flag = Rc::clone(&fired_flag);
957            waft_foundation::Timer::new(
958                app,
959                Duration::from_millis(30),
960                waft_foundation::Listener::new(move |_app| fired_flag.set(true)),
961            );
962        });
963        // The vsync's target is past the timer's time, but the platform's clock is not.
964        shell.frame(
965            &[IMPLICIT_VIEW_ID],
966            frame_at_vsync(Duration::from_millis(20), Duration::from_millis(25)),
967        );
968        assert!(
969            !fired.get(),
970            "a timer runs to the platform's clock, not the vsync's"
971        );
972        shell.frame(
973            &[IMPLICIT_VIEW_ID],
974            frame_at_vsync(Duration::from_millis(30), Duration::from_millis(31)),
975        );
976        assert!(fired.get());
977    }
978
979    #[test]
980    fn a_view_coming_or_going_and_a_change_to_the_screens_are_metrics_changes() {
981        use waft_foundation::Handle;
982        use waft_rendering::{RendererBinding, RendererBindingOverridesObject};
983
984        struct CountingMetricsChanges {
985            count: Rc<Cell<usize>>,
986        }
987
988        impl RendererBindingOverridesObject for CountingMetricsChanges {
989            fn will_draw_frame(self: Handle<Self>, _app: &mut App) {}
990
991            fn did_draw_frame(self: Handle<Self>, _app: &mut App) {}
992
993            fn did_handle_metrics_changed(self: Handle<Self>, app: &mut App) {
994                let count = &app.get(self).count;
995                count.set(count.get() + 1);
996            }
997        }
998
999        let count = Rc::new(Cell::new(0));
1000        let mut shell = Shell::new(Rc::new(platform_with_a_view()), |_app| {});
1001        let counting = shell.app().create(CountingMetricsChanges {
1002            count: Rc::clone(&count),
1003        });
1004        let binding = RendererBinding::instance(&mut shell.app());
1005        binding.set_overrides(&mut shell.app(), Rc::new(counting));
1006
1007        shell.view_added(ViewId(1));
1008        assert_eq!(count.get(), 1, "a view added");
1009        shell.view_removed(ViewId(1));
1010        assert_eq!(count.get(), 2, "a view removed");
1011        shell.screens_changed();
1012        assert_eq!(count.get(), 3, "the screens changed");
1013    }
1014
1015    #[test]
1016    fn view_focus_is_delivered_through_the_dispatcher_callback() {
1017        use waft_embedder::{ViewFocusDirection, ViewFocusEvent, ViewFocusState};
1018        let received = Rc::new(Cell::new(None));
1019        let sink = received.clone();
1020        let platform = Rc::new(platform_with_a_view());
1021        let mut shell = Shell::new(platform, move |app| {
1022            app.platform_callbacks_mut().on_view_focus_change = Some(Rc::new(move |app, event| {
1023                let sink = sink.clone();
1024                app.schedule_microtask(waft_foundation::Listener::new(move |_| {
1025                    sink.set(Some(event))
1026                }));
1027            }));
1028        });
1029        shell.view_focus_changed(ViewFocusEvent {
1030            view_id: IMPLICIT_VIEW_ID,
1031            state: ViewFocusState::Focused,
1032            direction: ViewFocusDirection::Backward,
1033        });
1034        let event = received
1035            .get()
1036            .expect("the shell checkpoints the callback's microtask");
1037        assert_eq!(event.view_id, IMPLICIT_VIEW_ID);
1038        assert_eq!(event.state, ViewFocusState::Focused);
1039        assert_eq!(event.direction, ViewFocusDirection::Backward);
1040    }
1041}