1#![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
27pub struct Shell {
33 app: Rc<AppCell>,
34 platform: PlatformRef,
35 clock: Duration,
37 origin: Option<Instant>,
39 pointer_data_packet_converter: PointerDataPacketConverter,
41}
42
43impl Shell {
44 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 PaintingBinding::instance(app).install_platform_fonts(app);
59 setup(app);
60 });
61 shell
62 }
63
64 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 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 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 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 fn metrics_changed(&mut self) {
107 self.push(|app| RendererBinding::instance(app).handle_metrics_changed(app));
108 }
109}
110
111impl EmbedderClient for Shell {
112 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 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 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 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 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 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 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 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 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 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 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 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 }
668
669 #[test]
672 fn a_view_is_given_frames_while_the_app_is_hidden() {
673 let platform = Rc::new(TestPlatform::new().with_views(&[IMPLICIT_VIEW_ID]));
674 let mut shell = Shell::new(platform.clone(), |_app| {});
675 shell.app_lifecycle_state_changed(AppLifecycleState::Hidden);
676 platform.take_frame_requests();
677
678 SchedulerBinding::schedule_frame(&mut shell.app(), FrameTarget::View(IMPLICIT_VIEW_ID));
679 assert_eq!(platform.take_frame_requests(), [IMPLICIT_VIEW_ID]);
680 }
681
682 #[test]
683 fn resuming_marks_every_view_to_be_rendered_and_asks_each_for_a_frame() {
684 use waft_rendering::RendererBinding;
685
686 let platform = Rc::new(TestPlatform::new().with_views(&[IMPLICIT_VIEW_ID, ViewId(1)]));
687 let first = platform.test_view(IMPLICIT_VIEW_ID);
688 let mut shell = Shell::new(platform.clone(), |_app| {});
689 let render_view = {
690 let mut app = shell.app();
691 let binding = RendererBinding::instance(&mut app);
692 binding.init_render_view(&mut app, first.clone())
693 };
694 let at = |ms| Frame {
695 elapsed: Duration::from_millis(ms),
696 vsync: None,
697 };
698 shell.frame(&[IMPLICIT_VIEW_ID], at(16));
699 shell.frame(&[IMPLICIT_VIEW_ID], at(32));
700 assert_eq!(
701 first.presented(),
702 1,
703 "nothing changed after the first frame"
704 );
705
706 shell.app_lifecycle_state_changed(AppLifecycleState::Hidden);
707 platform.take_frame_requests();
708 shell.app_lifecycle_state_changed(AppLifecycleState::Resumed);
709 assert_eq!(
710 platform.take_frame_requests(),
711 [IMPLICIT_VIEW_ID, ViewId(1)]
712 );
713 assert!(render_view.needs_composite_frame(&shell.app()));
714 shell.frame(&[IMPLICIT_VIEW_ID], at(48));
715 assert_eq!(first.presented(), 2, "drawn again though nothing changed");
716 }
717
718 #[test]
719 fn request_app_exit_is_answered_by_the_services_binding() {
720 use waft_embedder::AppExitResponse;
721 use waft_foundation::{Handle, Task};
722 use waft_services::{ServicesBinding, ServicesBindingOverridesObject};
723
724 #[derive(Default)]
725 struct Refusing;
726
727 impl ServicesBindingOverridesObject for Refusing {
728 fn handle_request_app_exit(
729 self: Handle<Self>,
730 _app: &mut App,
731 ) -> Task<AppExitResponse> {
732 Task::ready(AppExitResponse::Cancel)
733 }
734 }
735
736 let mut shell = Shell::new(Rc::new(TestPlatform::new()), |_app| {});
737 let (reply, answer) = recorded_reply();
738 shell.request_app_exit(reply);
739 assert_eq!(answer.get(), Some(AppExitResponse::Exit));
740
741 let refusing = shell.app().create(Refusing);
742 let binding = ServicesBinding::instance(&mut shell.app());
743 binding.set_overrides(&mut shell.app(), Rc::new(refusing));
744 let (reply, answer) = recorded_reply();
745 shell.request_app_exit(reply);
746 assert_eq!(answer.get(), Some(AppExitResponse::Cancel));
747 }
748
749 #[test]
751 fn a_service_extension_call_is_answered_by_the_framework() {
752 use std::cell::RefCell;
753
754 use waft_embedder::{
755 ServiceExtensionCall, ServiceExtensionParams, ServiceExtensionReply,
756 ServiceExtensionResult,
757 };
758 use waft_foundation::{ServiceExtensions, Task};
759
760 let mut shell = Shell::new(Rc::new(TestPlatform::new()), |app| {
761 ServiceExtensions::register(
762 app,
763 "ext.test.greet",
764 Rc::new(|_app, params| {
765 Task::ready(Ok(serde_json::json!({ "greeting": params.get("name") })))
766 }),
767 );
768 });
769 let answer: Rc<RefCell<Option<ServiceExtensionResult>>> = Rc::new(RefCell::new(None));
770 let to = Rc::clone(&answer);
771 shell.service_extension_call(ServiceExtensionCall {
772 name: "ext.test.greet".to_owned(),
773 params: ServiceExtensionParams::new([("name".to_owned(), "WaOS".to_owned())]),
774 reply: ServiceExtensionReply::new(move |result| *to.borrow_mut() = Some(result)),
775 });
776 assert_eq!(
777 answer.borrow_mut().take(),
778 Some(Ok(serde_json::json!({ "greeting": "WaOS" })))
779 );
780 }
781
782 #[test]
784 fn request_app_exit_answers_during_the_call_in_which_the_framework_decides() {
785 use waft_embedder::AppExitResponse;
786 use waft_foundation::{Completer, Handle, Task};
787 use waft_services::{ServicesBinding, ServicesBindingOverridesObject};
788
789 struct Deciding {
790 decision: Completer<AppExitResponse>,
791 }
792
793 impl ServicesBindingOverridesObject for Deciding {
794 fn handle_request_app_exit(self: Handle<Self>, app: &mut App) -> Task<AppExitResponse> {
795 let decision = app.get(self).decision.future();
796 app.spawn(async move |_cx| decision.await)
797 }
798 }
799
800 let decision = Completer::new();
801 let mut shell = Shell::new(Rc::new(TestPlatform::new()), |_app| {});
802 let deciding = shell.app().create(Deciding {
803 decision: decision.clone(),
804 });
805 let binding = ServicesBinding::instance(&mut shell.app());
806 binding.set_overrides(&mut shell.app(), Rc::new(deciding));
807
808 let (reply, answer) = recorded_reply();
809 shell.request_app_exit(reply);
810 assert_eq!(answer.get(), None);
811
812 decision.complete(&mut shell.app(), AppExitResponse::Exit);
813 assert_eq!(answer.get(), None, "the task resumes at a checkpoint");
814 shell.wake(Duration::ZERO);
815 assert_eq!(answer.get(), Some(AppExitResponse::Exit));
816 }
817
818 #[test]
819 fn new_runs_setup_and_frame_runs_both_scheduler_phases() {
820 let platform = Rc::new(platform_with_a_view());
821 let mut setup_ran = false;
822 let mut shell = Shell::new(platform.clone(), |_app: &mut App| {
823 setup_ran = true;
824 });
825 assert!(setup_ran);
826 assert!(platform.frame_requests().is_empty());
827
828 SchedulerBinding::schedule_frame(&mut shell.app(), FrameTarget::View(IMPLICIT_VIEW_ID));
829 assert_eq!(platform.frame_requests(), [IMPLICIT_VIEW_ID]);
830 shell.frame(
831 &[IMPLICIT_VIEW_ID],
832 Frame {
833 elapsed: Duration::from_millis(16),
834 vsync: None,
835 },
836 );
837 }
838
839 #[test]
840 fn a_reported_press_reaches_gesture_binding_numbered_by_the_converter() {
841 let ran = Rc::new(Cell::new(false));
842 let ran_flag = Rc::clone(&ran);
843 let platform = Rc::new(platform_with_a_view());
844 let mut shell = Shell::new(platform, |app| {
845 let binding = GestureBinding::instance(app);
846 binding.pointer_router(app).add_route(
847 app,
848 1,
849 PointerRoute::new(move |_app, _event| {
850 ran_flag.set(true);
851 }),
852 None,
853 );
854 });
855
856 shell.pointer_reports(vec![PointerReport {
857 view_id: IMPLICIT_VIEW_ID,
858 time_stamp: Duration::ZERO,
859 device: 0,
860 kind: PointerDeviceKind::Mouse,
861 position: [0.0, 0.0],
862 change: ReportedChange::Down { buttons: 1 },
863 contact: Contact::default(),
864 }]);
865 assert!(ran.get(), "the first press is pointer 1");
866 }
867
868 #[test]
869 fn key_data_reaches_the_hardware_keyboard() {
870 let seen = Rc::new(Cell::new(0));
871 let seen_flag = Rc::clone(&seen);
872 let platform = Rc::new(TestPlatform::new());
873 let mut shell = Shell::new(platform, |app| {
874 HardwareKeyboard::instance(app).add_handler(
875 app,
876 Rc::new(move |_app: &mut App, _event: &KeyEvent| {
877 seen_flag.set(seen_flag.get() + 1);
878 true
879 }),
880 );
881 });
882
883 let key_a = KeyData {
884 event_type: KeyEventType::Down,
885 physical: PhysicalKeyboardKey::KEY_A.usb_hid_usage,
886 logical: LogicalKeyboardKey::KEY_A.key_id,
887 character: Some("a".to_owned()),
888 ..KeyData::default()
889 };
890 assert!(shell.key_data(key_a), "the handler claimed the event");
891 assert_eq!(seen.get(), 1);
892
893 let keyboard = HardwareKeyboard::instance(&mut shell.app());
894 assert!(keyboard.is_logical_key_pressed(&shell.app(), LogicalKeyboardKey::KEY_A));
895 }
896
897 #[test]
898 fn wake_and_frame_advance_the_app_clock_and_fire_due_timers() {
899 let platform = Rc::new(TestPlatform::new());
900 let fired = Rc::new(Cell::new(Vec::new()));
901 let mut shell = Shell::new(platform, |app| {
902 for (name, delay) in [("early", 10), ("late", 30)] {
903 let fired = Rc::clone(&fired);
904 waft_foundation::Timer::new(
905 app,
906 Duration::from_millis(delay),
907 waft_foundation::Listener::new(move |_app| {
908 let mut log = fired.take();
909 log.push(name);
910 fired.set(log);
911 }),
912 );
913 }
914 });
915 assert!(fired.take().is_empty());
916
917 shell.wake(Duration::from_millis(15));
918 assert_eq!(fired.take(), vec!["early"]);
919
920 shell.frame(
921 &[IMPLICIT_VIEW_ID],
922 Frame {
923 elapsed: Duration::from_millis(32),
924 vsync: None,
925 },
926 );
927 assert_eq!(fired.take(), vec!["late"]);
928 }
929
930 #[test]
931 fn a_late_wake_catches_a_periodic_timer_up_as_dart_does() {
932 let platform = Rc::new(TestPlatform::new());
933 let ticks = Rc::new(Cell::new(Vec::new()));
934 let heard = Rc::clone(&ticks);
935 let mut shell = Shell::new(platform, move |app| {
936 let heard = Rc::clone(&heard);
937 waft_foundation::Timer::periodic(app, Duration::from_millis(1), move |app, timer| {
938 let mut seen = heard.take();
939 seen.push(timer.tick(app));
940 heard.set(seen);
941 });
942 });
943
944 shell.wake(Duration::from_secs(100));
946 assert_eq!(ticks.take(), [100_000]);
947 }
948
949 const REFRESH: Duration = Duration::from_micros(16_667);
952
953 fn frame_at_vsync(start: Duration, elapsed: Duration) -> Frame {
956 Frame {
957 elapsed,
958 vsync: Some(waft_embedder::FrameVsync {
959 start,
960 target: start + REFRESH,
961 }),
962 }
963 }
964
965 fn ticks_at(frames: &[Frame]) -> Vec<Duration> {
967 use waft_scheduler::{FrameCallback, Ticker};
968
969 let ticks = Rc::new(Cell::new(Vec::new()));
970 let heard = Rc::clone(&ticks);
971 let ticker = Rc::new(RefCell::new(None));
973 let kept = Rc::clone(&ticker);
974 let mut shell = Shell::new(Rc::new(TestPlatform::new()), move |app| {
975 let on_tick = FrameCallback::new(move |_app, elapsed| {
976 let mut ticks = heard.take();
977 ticks.push(elapsed);
978 heard.set(ticks);
979 });
980 let ticker = Ticker::new(app, on_tick, None);
981 ticker.start(app);
982 *kept.borrow_mut() = Some(ticker);
983 });
984 for frame in frames {
985 shell.frame(&[IMPLICIT_VIEW_ID], *frame);
986 }
987 ticks.take()
988 }
989
990 #[test]
991 fn a_frame_whose_drawing_starts_late_still_advances_by_the_vsync_interval() {
992 let ticks = ticks_at(&[
993 frame_at_vsync(Duration::ZERO, Duration::from_millis(1)),
994 frame_at_vsync(REFRESH, Duration::from_millis(37)),
996 ]);
997 assert_eq!(ticks, [Duration::ZERO, REFRESH]);
998 }
999
1000 #[test]
1001 fn a_frame_drawn_outside_a_vsync_takes_the_platforms_clock() {
1002 let at = |ms| Frame {
1003 elapsed: Duration::from_millis(ms),
1004 vsync: None,
1005 };
1006 let ticks = ticks_at(&[at(1), at(37)]);
1007 assert_eq!(ticks, [Duration::ZERO, Duration::from_millis(36)]);
1008 }
1009
1010 #[test]
1011 fn a_vsync_frame_after_timers_fire_them_at_the_platforms_clock() {
1012 let platform = Rc::new(TestPlatform::new());
1013 let fired = Rc::new(Cell::new(false));
1014 let fired_flag = Rc::clone(&fired);
1015 let mut shell = Shell::new(platform, move |app| {
1016 let fired_flag = Rc::clone(&fired_flag);
1017 waft_foundation::Timer::new(
1018 app,
1019 Duration::from_millis(30),
1020 waft_foundation::Listener::new(move |_app| fired_flag.set(true)),
1021 );
1022 });
1023 shell.frame(
1025 &[IMPLICIT_VIEW_ID],
1026 frame_at_vsync(Duration::from_millis(20), Duration::from_millis(25)),
1027 );
1028 assert!(
1029 !fired.get(),
1030 "a timer runs to the platform's clock, not the vsync's"
1031 );
1032 shell.frame(
1033 &[IMPLICIT_VIEW_ID],
1034 frame_at_vsync(Duration::from_millis(30), Duration::from_millis(31)),
1035 );
1036 assert!(fired.get());
1037 }
1038
1039 #[test]
1040 fn a_view_coming_or_going_and_a_change_to_the_screens_are_metrics_changes() {
1041 use waft_foundation::Handle;
1042 use waft_rendering::{RendererBinding, RendererBindingOverridesObject};
1043
1044 struct CountingMetricsChanges {
1045 count: Rc<Cell<usize>>,
1046 }
1047
1048 impl RendererBindingOverridesObject for CountingMetricsChanges {
1049 fn will_draw_frame(self: Handle<Self>, _app: &mut App) {}
1050
1051 fn did_draw_frame(self: Handle<Self>, _app: &mut App) {}
1052
1053 fn did_handle_metrics_changed(self: Handle<Self>, app: &mut App) {
1054 let count = &app.get(self).count;
1055 count.set(count.get() + 1);
1056 }
1057 }
1058
1059 let count = Rc::new(Cell::new(0));
1060 let mut shell = Shell::new(Rc::new(platform_with_a_view()), |_app| {});
1061 let counting = shell.app().create(CountingMetricsChanges {
1062 count: Rc::clone(&count),
1063 });
1064 let binding = RendererBinding::instance(&mut shell.app());
1065 binding.set_overrides(&mut shell.app(), Rc::new(counting));
1066
1067 shell.view_added(ViewId(1));
1068 assert_eq!(count.get(), 1, "a view added");
1069 shell.view_removed(ViewId(1));
1070 assert_eq!(count.get(), 2, "a view removed");
1071 shell.screens_changed();
1072 assert_eq!(count.get(), 3, "the screens changed");
1073 }
1074
1075 #[test]
1076 fn view_focus_is_delivered_through_the_dispatcher_callback() {
1077 use waft_embedder::{ViewFocusDirection, ViewFocusEvent, ViewFocusState};
1078 let received = Rc::new(Cell::new(None));
1079 let sink = received.clone();
1080 let platform = Rc::new(platform_with_a_view());
1081 let mut shell = Shell::new(platform, move |app| {
1082 app.platform_callbacks_mut().on_view_focus_change = Some(Rc::new(move |app, event| {
1083 let sink = sink.clone();
1084 app.schedule_microtask(waft_foundation::Listener::new(move |_| {
1085 sink.set(Some(event))
1086 }));
1087 }));
1088 });
1089 shell.view_focus_changed(ViewFocusEvent {
1090 view_id: IMPLICIT_VIEW_ID,
1091 state: ViewFocusState::Focused,
1092 direction: ViewFocusDirection::Backward,
1093 });
1094 let event = received
1095 .get()
1096 .expect("the shell checkpoints the callback's microtask");
1097 assert_eq!(event.view_id, IMPLICIT_VIEW_ID);
1098 assert_eq!(event.state, ViewFocusState::Focused);
1099 assert_eq!(event.direction, ViewFocusDirection::Backward);
1100 }
1101}