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