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