1use std::collections::HashMap;
19use std::panic::Location;
20use std::rc::Rc;
21use std::time::Duration;
22
23use waft_embedder::{
24 AppExitResponse, AppExitType, AppLifecycleState, ClipboardEvent, DragReport, EditCommand,
25 Locale, MediaChangeFuture, RequestId, TrayIconEvent, TrayIconId, ViewError, ViewFocusEvent,
26 ViewId, ViewRef, WindowConfig,
27};
28use waft_foundation::{App, Handle, Listener, OptionRetained, Ref, ServiceExtensions, Task, Timer};
29use waft_rendering::{RendererBinding, RendererBindingOverridesObject};
30use waft_scheduler::{FrameTarget, SchedulerBinding, SchedulerBindingOverridesObject};
31use waft_services::{
32 Clipboard, PredictiveBackEvent, SelectionChangedCause, ServicesBinding,
33 ServicesBindingOverridesObject,
34};
35
36use crate::framework::{
37 AnyElement, BuildOwner, CreationLocation, Element, ElementBase, ElementData, IntoWidget,
38 KeyRef, Slot, Widget, WidgetKind, WidgetRef, downcast_widget,
39};
40use crate::multi_view_app::MultiViewApp;
41use crate::view::View;
42use crate::widgets::actions::{Actions, Intent};
43use crate::widgets::focus_manager::{FocusManager, debug_describe_focus_tree};
44use crate::widgets::platform_menu_bar::{DefaultPlatformMenuDelegate, PlatformMenuDelegateRef};
45use crate::widgets::text_editing_intents::{
46 CopySelectionTextIntent, DeleteCharacterIntent, PasteTextIntent, RedoTextIntent,
47 SelectAllTextIntent, UndoTextIntent,
48};
49
50#[derive(Default)]
58pub struct WidgetsBinding {
59 initialized: bool,
62 build_owner: Option<Ref<BuildOwner>>,
63 root_element: Option<AnyElement>,
64 ready_to_produce_frames: bool,
65 did_send_first_frame: bool,
67 observers: Vec<WidgetsBindingObserverRef>,
68 back_gesture_observers: Vec<WidgetsBindingObserverRef>,
70 window_listeners: HashMap<ViewId, Vec<Listener>>,
72 platform_menu_delegate: Option<PlatformMenuDelegateRef>,
74 tray_icon_listeners: HashMap<TrayIconId, TrayIconListener>,
76}
77
78pub type TrayIconListener = Rc<dyn Fn(&mut App, TrayIconEvent)>;
80
81impl std::fmt::Display for WidgetsBinding {
82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 f.write_str("<WidgetsBinding>")
85 }
86}
87
88pub trait WidgetsBindingObserver {
101 fn did_change_metrics(&self, app: &mut App) {
103 let _ = app;
104 }
105
106 fn did_change_locales(&self, app: &mut App, locales: Option<&[Locale]>) {
111 let _ = (app, locales);
112 }
113
114 fn did_change_view_focus(&self, app: &mut App, event: ViewFocusEvent) {
116 let _ = (app, event);
117 }
118
119 fn did_change_drag(&self, app: &mut App, report: &DragReport) {
122 let _ = (app, report);
123 }
124
125 fn did_change_text_scale_factor(&self, app: &mut App) {
127 let _ = app;
128 }
129
130 fn did_change_platform_brightness(&self, app: &mut App) {
132 let _ = app;
133 }
134
135 fn did_change_caption_style(&self, app: &mut App) {
138 let _ = app;
139 }
140
141 fn did_change_app_lifecycle_state(&self, app: &mut App, state: AppLifecycleState) {
151 let _ = (app, state);
152 }
153
154 fn did_request_app_exit(&self, app: &mut App) -> Task<AppExitResponse> {
172 let _ = app;
173 Task::ready(AppExitResponse::Exit)
174 }
175
176 fn did_change_accessibility_features(&self, app: &mut App) {
178 let _ = app;
179 }
180
181 fn did_pop_route(&self, app: &mut App, view: ViewId) -> bool {
188 let _ = (app, view);
189 false
190 }
191
192 fn handle_start_back_gesture(&self, app: &mut App, back_event: PredictiveBackEvent) -> bool {
213 let _ = (app, back_event);
214 false
215 }
216
217 fn handle_update_back_gesture_progress(&self, app: &mut App, back_event: PredictiveBackEvent) {
226 let _ = (app, back_event);
227 }
228
229 fn handle_commit_back_gesture(&self, app: &mut App) {
240 let _ = app;
241 }
242
243 fn handle_cancel_back_gesture(&self, app: &mut App) {
253 let _ = app;
254 }
255
256 fn did_add_view(&self, app: &mut App, view: &ViewRef) {
264 let _ = (app, view);
265 }
266
267 fn did_remove_view(&self, app: &mut App, view: ViewId) {
269 let _ = (app, view);
270 }
271
272 fn did_fail_view_request(&self, app: &mut App, request: RequestId, error: &ViewError) {
274 let _ = (app, request, error);
275 }
276
277 fn did_request_view_close(&self, app: &mut App, view: ViewId) -> bool {
283 let _ = (app, view);
284 false
285 }
286}
287
288pub trait WidgetsBindingObserverObject: Sized + 'static {
291 fn did_change_metrics(self: Handle<Self>, app: &mut App) {
293 let _ = app;
294 }
295
296 fn did_change_locales(self: Handle<Self>, app: &mut App, locales: Option<&[Locale]>) {
298 let _ = (app, locales);
299 }
300
301 fn did_change_view_focus(self: Handle<Self>, app: &mut App, event: ViewFocusEvent) {
303 let _ = (app, event);
304 }
305
306 fn did_change_drag(self: Handle<Self>, app: &mut App, report: &DragReport) {
308 let _ = (app, report);
309 }
310
311 fn did_change_text_scale_factor(self: Handle<Self>, app: &mut App) {
313 let _ = app;
314 }
315
316 fn did_change_platform_brightness(self: Handle<Self>, app: &mut App) {
318 let _ = app;
319 }
320
321 fn did_change_caption_style(self: Handle<Self>, app: &mut App) {
323 let _ = app;
324 }
325
326 fn did_change_app_lifecycle_state(self: Handle<Self>, app: &mut App, state: AppLifecycleState) {
328 let _ = (app, state);
329 }
330
331 fn did_request_app_exit(self: Handle<Self>, app: &mut App) -> Task<AppExitResponse> {
333 let _ = app;
334 Task::ready(AppExitResponse::Exit)
335 }
336
337 fn did_change_accessibility_features(self: Handle<Self>, app: &mut App) {
339 let _ = app;
340 }
341
342 fn did_pop_route(self: Handle<Self>, app: &mut App, view: ViewId) -> bool {
344 let _ = (app, view);
345 false
346 }
347
348 fn handle_start_back_gesture(
350 self: Handle<Self>,
351 app: &mut App,
352 back_event: PredictiveBackEvent,
353 ) -> bool {
354 let _ = (app, back_event);
355 false
356 }
357
358 fn handle_update_back_gesture_progress(
360 self: Handle<Self>,
361 app: &mut App,
362 back_event: PredictiveBackEvent,
363 ) {
364 let _ = (app, back_event);
365 }
366
367 fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App) {
369 let _ = app;
370 }
371
372 fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App) {
374 let _ = app;
375 }
376
377 fn did_add_view(self: Handle<Self>, app: &mut App, view: &ViewRef) {
379 let _ = (app, view);
380 }
381
382 fn did_remove_view(self: Handle<Self>, app: &mut App, view: ViewId) {
384 let _ = (app, view);
385 }
386
387 fn did_fail_view_request(
389 self: Handle<Self>,
390 app: &mut App,
391 request: RequestId,
392 error: &ViewError,
393 ) {
394 let _ = (app, request, error);
395 }
396
397 fn did_request_view_close(self: Handle<Self>, app: &mut App, view: ViewId) -> bool {
399 let _ = (app, view);
400 false
401 }
402}
403
404impl<T: WidgetsBindingObserverObject> WidgetsBindingObserver for Handle<T> {
407 fn did_change_metrics(&self, app: &mut App) {
408 if app.tear_off_receiver_is_live(*self) {
409 T::did_change_metrics(*self, app);
410 }
411 }
412
413 fn did_change_locales(&self, app: &mut App, locales: Option<&[Locale]>) {
414 if app.tear_off_receiver_is_live(*self) {
415 T::did_change_locales(*self, app, locales);
416 }
417 }
418
419 fn did_change_view_focus(&self, app: &mut App, event: ViewFocusEvent) {
420 if app.tear_off_receiver_is_live(*self) {
421 T::did_change_view_focus(*self, app, event);
422 }
423 }
424
425 fn did_change_drag(&self, app: &mut App, report: &DragReport) {
426 if app.tear_off_receiver_is_live(*self) {
427 T::did_change_drag(*self, app, report);
428 }
429 }
430
431 fn did_change_text_scale_factor(&self, app: &mut App) {
432 if app.tear_off_receiver_is_live(*self) {
433 T::did_change_text_scale_factor(*self, app);
434 }
435 }
436
437 fn did_change_platform_brightness(&self, app: &mut App) {
438 if app.tear_off_receiver_is_live(*self) {
439 T::did_change_platform_brightness(*self, app);
440 }
441 }
442
443 fn did_change_caption_style(&self, app: &mut App) {
444 if app.tear_off_receiver_is_live(*self) {
445 T::did_change_caption_style(*self, app);
446 }
447 }
448
449 fn did_change_app_lifecycle_state(&self, app: &mut App, state: AppLifecycleState) {
450 if app.tear_off_receiver_is_live(*self) {
451 T::did_change_app_lifecycle_state(*self, app, state);
452 }
453 }
454
455 fn did_request_app_exit(&self, app: &mut App) -> Task<AppExitResponse> {
456 if !app.tear_off_receiver_is_live(*self) {
457 return Task::ready(AppExitResponse::Exit);
458 }
459 T::did_request_app_exit(*self, app)
460 }
461
462 fn did_change_accessibility_features(&self, app: &mut App) {
463 if app.tear_off_receiver_is_live(*self) {
464 T::did_change_accessibility_features(*self, app);
465 }
466 }
467
468 fn did_pop_route(&self, app: &mut App, view: ViewId) -> bool {
469 app.tear_off_receiver_is_live(*self) && T::did_pop_route(*self, app, view)
470 }
471
472 fn handle_start_back_gesture(&self, app: &mut App, back_event: PredictiveBackEvent) -> bool {
473 app.tear_off_receiver_is_live(*self) && T::handle_start_back_gesture(*self, app, back_event)
474 }
475
476 fn handle_update_back_gesture_progress(&self, app: &mut App, back_event: PredictiveBackEvent) {
477 if app.tear_off_receiver_is_live(*self) {
478 T::handle_update_back_gesture_progress(*self, app, back_event);
479 }
480 }
481
482 fn handle_commit_back_gesture(&self, app: &mut App) {
483 if app.tear_off_receiver_is_live(*self) {
484 T::handle_commit_back_gesture(*self, app);
485 }
486 }
487
488 fn handle_cancel_back_gesture(&self, app: &mut App) {
489 if app.tear_off_receiver_is_live(*self) {
490 T::handle_cancel_back_gesture(*self, app);
491 }
492 }
493
494 fn did_add_view(&self, app: &mut App, view: &ViewRef) {
495 if app.tear_off_receiver_is_live(*self) {
496 T::did_add_view(*self, app, view);
497 }
498 }
499
500 fn did_remove_view(&self, app: &mut App, view: ViewId) {
501 if app.tear_off_receiver_is_live(*self) {
502 T::did_remove_view(*self, app, view);
503 }
504 }
505
506 fn did_fail_view_request(&self, app: &mut App, request: RequestId, error: &ViewError) {
507 if app.tear_off_receiver_is_live(*self) {
508 T::did_fail_view_request(*self, app, request, error);
509 }
510 }
511
512 fn did_request_view_close(&self, app: &mut App, view: ViewId) -> bool {
513 app.tear_off_receiver_is_live(*self) && T::did_request_view_close(*self, app, view)
514 }
515}
516
517impl<T: WidgetsBindingObserverObject> WidgetsBindingObserver for Ref<T> {
519 fn did_change_metrics(&self, app: &mut App) {
520 T::did_change_metrics(self.handle(), app);
521 }
522
523 fn did_change_locales(&self, app: &mut App, locales: Option<&[Locale]>) {
524 T::did_change_locales(self.handle(), app, locales);
525 }
526
527 fn did_change_view_focus(&self, app: &mut App, event: ViewFocusEvent) {
528 T::did_change_view_focus(self.handle(), app, event);
529 }
530
531 fn did_change_drag(&self, app: &mut App, report: &DragReport) {
532 T::did_change_drag(self.handle(), app, report);
533 }
534
535 fn did_change_text_scale_factor(&self, app: &mut App) {
536 T::did_change_text_scale_factor(self.handle(), app);
537 }
538
539 fn did_change_platform_brightness(&self, app: &mut App) {
540 T::did_change_platform_brightness(self.handle(), app);
541 }
542
543 fn did_change_caption_style(&self, app: &mut App) {
544 T::did_change_caption_style(self.handle(), app);
545 }
546
547 fn did_change_app_lifecycle_state(&self, app: &mut App, state: AppLifecycleState) {
548 T::did_change_app_lifecycle_state(self.handle(), app, state);
549 }
550
551 fn did_request_app_exit(&self, app: &mut App) -> Task<AppExitResponse> {
552 T::did_request_app_exit(self.handle(), app)
553 }
554
555 fn did_change_accessibility_features(&self, app: &mut App) {
556 T::did_change_accessibility_features(self.handle(), app);
557 }
558
559 fn did_pop_route(&self, app: &mut App, view: ViewId) -> bool {
560 T::did_pop_route(self.handle(), app, view)
561 }
562
563 fn handle_start_back_gesture(&self, app: &mut App, back_event: PredictiveBackEvent) -> bool {
564 T::handle_start_back_gesture(self.handle(), app, back_event)
565 }
566
567 fn handle_update_back_gesture_progress(&self, app: &mut App, back_event: PredictiveBackEvent) {
568 T::handle_update_back_gesture_progress(self.handle(), app, back_event);
569 }
570
571 fn handle_commit_back_gesture(&self, app: &mut App) {
572 T::handle_commit_back_gesture(self.handle(), app);
573 }
574
575 fn handle_cancel_back_gesture(&self, app: &mut App) {
576 T::handle_cancel_back_gesture(self.handle(), app);
577 }
578
579 fn did_add_view(&self, app: &mut App, view: &ViewRef) {
580 T::did_add_view(self.handle(), app, view);
581 }
582
583 fn did_remove_view(&self, app: &mut App, view: ViewId) {
584 T::did_remove_view(self.handle(), app, view);
585 }
586
587 fn did_fail_view_request(&self, app: &mut App, request: RequestId, error: &ViewError) {
588 T::did_fail_view_request(self.handle(), app, request, error);
589 }
590
591 fn did_request_view_close(&self, app: &mut App, view: ViewId) -> bool {
592 T::did_request_view_close(self.handle(), app, view)
593 }
594}
595
596pub type WidgetsBindingObserverRef = Rc<dyn WidgetsBindingObserver>;
598
599fn remove_first(
602 observers: &mut Vec<WidgetsBindingObserverRef>,
603 observer: &WidgetsBindingObserverRef,
604) -> bool {
605 match observers
606 .iter()
607 .position(|registered| Rc::ptr_eq(registered, observer))
608 {
609 Some(index) => {
610 observers.remove(index);
611 true
612 }
613 None => false,
614 }
615}
616
617impl WidgetsBinding {
618 pub fn instance(app: &mut App) -> Handle<WidgetsBinding> {
623 let this: Handle<WidgetsBinding> = app.singleton();
624 if !app.get(this).initialized {
625 app.get_mut(this).initialized = true;
626 this.init_instances(app);
627 }
628 this
629 }
630
631 fn init_instances(self: Handle<Self>, app: &mut App) {
639 self.override_the_bindings_below(app);
640 let build_owner = BuildOwner::new(
641 app,
642 Some(Rc::new(|app: &mut App, element: AnyElement| {
643 WidgetsBinding::instance(app).handle_build_scheduled(app, element)
644 })),
645 );
646 app.get_mut(self).build_owner = Some(build_owner);
647 WidgetsBinding::assign_dispatcher_callbacks(app);
648 self.follow_caption_settings(app);
649 let platform_menu_delegate: PlatformMenuDelegateRef = DefaultPlatformMenuDelegate::new(app);
650 app.get_mut(self).platform_menu_delegate = Some(platform_menu_delegate);
651 WidgetsBinding::init_service_extensions(app);
652 }
653
654 fn init_service_extensions(app: &mut App) {
657 if !cfg!(debug_assertions) {
658 return;
659 }
660 ServiceExtensions::register_dump(app, "ext.waft.debugDumpApp", debug_dump_app);
661 ServiceExtensions::register(
663 app,
664 "ext.waft.didSendFirstFrameEvent",
665 Rc::new(|app, _params| {
666 let sent = WidgetsBinding::instance(app).debug_did_send_first_frame_event(app);
667 Task::ready(Ok(serde_json::json!({ "enabled": sent.to_string() })))
668 }),
669 );
670 ServiceExtensions::register_dump(
671 app,
672 "ext.waft.debugDumpFocusTree",
673 debug_describe_focus_tree,
674 );
675 crate::widgets::widget_inspector::init_service_extensions(app);
676 crate::widgets::driver::init_service_extensions(app);
677 }
678
679 pub fn platform_menu_delegate(self: Handle<Self>, app: &App) -> PlatformMenuDelegateRef {
682 Rc::clone(
683 app.get(self)
684 .platform_menu_delegate
685 .as_ref()
686 .expect("init_instances sets the platform menu delegate"),
687 )
688 }
689
690 pub fn set_platform_menu_delegate(
692 self: Handle<Self>,
693 app: &mut App,
694 delegate: PlatformMenuDelegateRef,
695 ) {
696 app.get_mut(self).platform_menu_delegate = Some(delegate);
697 }
698
699 fn override_the_bindings_below(self: Handle<Self>, app: &mut App) {
702 RendererBinding::instance(app).set_overrides(app, Rc::new(self));
704 SchedulerBinding::set_overrides(app, Rc::new(self));
706 ServicesBinding::instance(app).set_overrides(app, Rc::new(self));
708 }
709
710 fn assign_dispatcher_callbacks(app: &mut App) {
712 let callbacks = app.platform_callbacks_mut();
713 callbacks.on_platform_brightness_changed = Some(Listener::new(|app| {
714 WidgetsBinding::instance(app).handle_platform_brightness_changed(app)
715 }));
716 callbacks.on_view_focus_change = Some(Rc::new(|app, event| {
717 WidgetsBinding::instance(app).handle_view_focus_changed(app, event)
718 }));
719 callbacks.on_drag = Some(Rc::new(|app, report| {
720 WidgetsBinding::instance(app).handle_drag(app, &report)
721 }));
722 callbacks.on_clipboard_event = Some(Rc::new(|app, _view, event| {
723 WidgetsBinding::instance(app).handle_clipboard_event(app, event)
724 }));
725 callbacks.on_edit_command = Some(Rc::new(|app, _view, command| {
726 WidgetsBinding::instance(app).handle_edit_command(app, command)
727 }));
728 callbacks.on_tray_icon_event = Some(Rc::new(|app, icon, event| {
729 WidgetsBinding::instance(app).handle_tray_icon_event(app, icon, event)
730 }));
731 callbacks.on_locale_changed = Some(Listener::new(|app| {
732 WidgetsBinding::instance(app).handle_locale_changed(app)
733 }));
734 callbacks.on_pop_route = Some(Rc::new(|app, view| {
735 WidgetsBinding::instance(app).handle_pop_route(app, view)
736 }));
737 callbacks.on_view_added = Some(Rc::new(|app, view| {
738 WidgetsBinding::instance(app).handle_view_added(app, view)
739 }));
740 callbacks.on_view_removed = Some(Rc::new(|app, view| {
741 WidgetsBinding::instance(app).handle_view_removed(app, view)
742 }));
743 callbacks.on_view_close_requested = Some(Rc::new(|app, view| {
744 WidgetsBinding::instance(app).handle_view_close_requested(app, view)
745 }));
746 callbacks.on_window_changed = Some(Rc::new(|app, view| {
747 WidgetsBinding::instance(app).handle_window_changed(app, view)
748 }));
749 callbacks.on_view_request_failed = Some(Rc::new(|app, request_id, error| {
750 WidgetsBinding::instance(app).handle_view_request_failed(app, request_id, error)
751 }));
752 }
753
754 fn follow_caption_settings(self: Handle<Self>, app: &mut App) {
757 let Some(changed) = WidgetsBinding::caption_settings_changed(app) else {
758 return;
759 };
760 let _following = app.spawn(async move |cx| {
761 let mut changed = changed;
762 loop {
763 changed.await;
764 match cx.update(|app| self.take_caption_settings_change(app)) {
765 Some(next) => changed = next,
766 None => return,
767 }
768 }
769 });
770 }
771
772 fn caption_settings_changed(app: &App) -> Option<MediaChangeFuture> {
775 let platform = app.platform();
776 Some(platform.caption_settings()?.changed())
777 }
778
779 fn take_caption_settings_change(
782 self: Handle<Self>,
783 app: &mut App,
784 ) -> Option<MediaChangeFuture> {
785 let next = WidgetsBinding::caption_settings_changed(app)?;
786 self.handle_caption_style_changed(app);
787 Some(next)
788 }
789
790 pub fn focus_manager(self: Handle<Self>, app: &App) -> Handle<crate::FocusManager> {
795 self.build_owner(app).focus_manager(app)
796 }
797
798 pub fn build_owner(self: Handle<Self>, app: &App) -> Handle<BuildOwner> {
801 app.get(self)
802 .build_owner
803 .handle()
804 .expect("WidgetsBinding::instance must run first")
805 }
806
807 fn handle_build_scheduled(self: Handle<Self>, app: &mut App, element: AnyElement) {
810 let target = match View::maybe_id_of(app, element) {
813 Some(view) => FrameTarget::View(view),
814 None => FrameTarget::EveryView,
815 };
816 SchedulerBinding::ensure_visual_update(app, target);
817 }
818
819 pub fn debug_did_send_first_frame_event(self: Handle<Self>, app: &App) -> bool {
822 app.get(self).did_send_first_frame
823 }
824
825 pub fn root_element(self: Handle<Self>, app: &App) -> Option<AnyElement> {
829 app.get(self).root_element
830 }
831
832 pub fn ready_to_produce_frames(self: Handle<Self>, app: &App) -> bool {
835 app.get(self).ready_to_produce_frames
836 }
837
838 pub(crate) fn add_window_listener(
840 self: Handle<Self>,
841 app: &mut App,
842 view: ViewId,
843 listener: Listener,
844 ) {
845 app.get_mut(self)
846 .window_listeners
847 .entry(view)
848 .or_default()
849 .push(listener);
850 }
851
852 pub(crate) fn remove_window_listener(
854 self: Handle<Self>,
855 app: &mut App,
856 view: ViewId,
857 listener: &Listener,
858 ) {
859 let listeners = &mut app.get_mut(self).window_listeners;
860 if let Some(heard) = listeners.get_mut(&view) {
861 heard.retain(|kept| kept != listener);
862 if heard.is_empty() {
863 listeners.remove(&view);
864 }
865 }
866 }
867
868 fn handle_view_added(self: Handle<Self>, app: &mut App, view: ViewId) {
870 let Some(view) = app.platform().view(view) else {
871 return;
872 };
873 for observer in app.get(self).observers.clone() {
874 observer.did_add_view(app, &view);
875 }
876 }
877
878 fn handle_view_removed(self: Handle<Self>, app: &mut App, view: ViewId) {
880 for observer in app.get(self).observers.clone() {
881 observer.did_remove_view(app, view);
882 }
883 }
884
885 fn handle_view_close_requested(self: Handle<Self>, app: &mut App, view: ViewId) {
889 for observer in app.get(self).observers.clone() {
890 if observer.did_request_view_close(app, view) {
891 return;
892 }
893 }
894 let shown = app.platform().views();
895 if let Some(view) = shown.iter().find(|shown| shown.id() == view) {
896 close_or_ask_to_quit(app, view);
897 }
898 }
899
900 fn handle_window_changed(self: Handle<Self>, app: &mut App, view: ViewId) {
903 let listeners = app
904 .get(self)
905 .window_listeners
906 .get(&view)
907 .cloned()
908 .unwrap_or_default();
909 for listener in listeners {
910 listener.call(app);
911 }
912 }
913
914 fn handle_view_request_failed(
916 self: Handle<Self>,
917 app: &mut App,
918 request_id: RequestId,
919 error: ViewError,
920 ) {
921 for observer in app.get(self).observers.clone() {
922 observer.did_fail_view_request(app, request_id, &error);
923 }
924 }
925
926 pub fn schedule_attach_root_widget(self: Handle<Self>, app: &mut App, root_widget: WidgetRef) {
932 Timer::new(
933 app,
934 Duration::ZERO,
935 Listener::new(move |app| self.attach_root_widget(app, root_widget.clone())),
936 );
937 }
938
939 pub fn attach_root_widget(self: Handle<Self>, app: &mut App, root_widget: WidgetRef) {
948 self.attach_to_build_owner(
949 app,
950 RootWidget::new()
951 .child(root_widget)
952 .debug_short_description("[root]"),
953 );
954 }
955
956 pub fn attach_to_build_owner(self: Handle<Self>, app: &mut App, widget: RootWidget) {
965 let is_bootstrap_frame = app.get(self).root_element.is_none();
966 app.get_mut(self).ready_to_produce_frames = true;
967 let owner = self.build_owner(app);
968 let current = app.get(self).root_element.map(|element| {
969 element
970 .downcast::<RootElement>(app)
971 .expect("the root is a RootElement")
972 });
973 let root = widget.attach(app, owner, current);
974 app.get_mut(self).root_element = Some(root.as_element());
975 if is_bootstrap_frame {
976 SchedulerBinding::ensure_visual_update(app, FrameTarget::EveryView);
977 }
978 }
979
980 pub fn add_observer(self: Handle<Self>, app: &mut App, observer: WidgetsBindingObserverRef) {
987 app.get_mut(self).observers.push(observer);
988 }
989
990 pub fn remove_observer(
993 self: Handle<Self>,
994 app: &mut App,
995 observer: &WidgetsBindingObserverRef,
996 ) -> bool {
997 remove_first(&mut app.get_mut(self).back_gesture_observers, observer);
998
999 remove_first(&mut app.get_mut(self).observers, observer)
1000 }
1001
1002 fn is_observing(self: Handle<Self>, app: &App, observer: &WidgetsBindingObserverRef) -> bool {
1003 app.get(self)
1004 .observers
1005 .iter()
1006 .any(|registered| Rc::ptr_eq(registered, observer))
1007 }
1008
1009 #[cfg(test)]
1010 pub(crate) fn observer_count(self: Handle<Self>, app: &App) -> usize {
1011 app.get(self).observers.len()
1012 }
1013
1014 pub fn handle_text_scale_factor_changed(self: Handle<Self>, app: &mut App) {
1016 for observer in app.get(self).observers.clone() {
1017 observer.did_change_text_scale_factor(app);
1018 }
1019 }
1020
1021 pub fn handle_view_focus_changed(self: Handle<Self>, app: &mut App, event: ViewFocusEvent) {
1023 for observer in app.get(self).observers.clone() {
1024 observer.did_change_view_focus(app, event);
1025 }
1026 }
1027
1028 pub fn handle_drag(self: Handle<Self>, app: &mut App, report: &DragReport) {
1030 for observer in app.get(self).observers.clone() {
1031 observer.did_change_drag(app, report);
1032 }
1033 }
1034
1035 pub fn handle_clipboard_event(self: Handle<Self>, app: &mut App, event: ClipboardEvent) {
1041 let intent = intent_for_clipboard_event(&event);
1042 Clipboard::handle_event(app, event, |app| {
1043 let Some(primary_context) = FocusManager::instance(app)
1044 .primary_focus(app)
1045 .and_then(|focus| focus.context(app))
1046 else {
1047 return;
1048 };
1049 Actions::maybe_invoke(app, primary_context, &*intent);
1050 });
1051 }
1052
1053 pub fn handle_edit_command(self: Handle<Self>, app: &mut App, command: EditCommand) {
1057 let Some(primary_context) = FocusManager::instance(app)
1058 .primary_focus(app)
1059 .and_then(|focus| focus.context(app))
1060 else {
1061 return;
1062 };
1063 let intent = intent_for_edit_command(command);
1064 Actions::maybe_invoke(app, primary_context, &*intent);
1065 }
1066
1067 pub fn add_tray_icon_listener(
1071 self: Handle<Self>,
1072 app: &mut App,
1073 icon: TrayIconId,
1074 listener: TrayIconListener,
1075 ) {
1076 app.get_mut(self).tray_icon_listeners.insert(icon, listener);
1077 }
1078
1079 pub fn remove_tray_icon_listener(self: Handle<Self>, app: &mut App, icon: TrayIconId) {
1081 app.get_mut(self).tray_icon_listeners.remove(&icon);
1082 }
1083
1084 pub fn handle_tray_icon_event(
1087 self: Handle<Self>,
1088 app: &mut App,
1089 icon: TrayIconId,
1090 event: TrayIconEvent,
1091 ) {
1092 let listener = app.get(self).tray_icon_listeners.get(&icon).cloned();
1093 if let Some(listener) = listener {
1094 listener(app, event);
1095 }
1096 }
1097
1098 pub fn handle_platform_brightness_changed(self: Handle<Self>, app: &mut App) {
1100 for observer in app.get(self).observers.clone() {
1101 observer.did_change_platform_brightness(app);
1102 }
1103 }
1104
1105 pub fn handle_caption_style_changed(self: Handle<Self>, app: &mut App) {
1107 for observer in app.get(self).observers.clone() {
1108 observer.did_change_caption_style(app);
1109 }
1110 }
1111
1112 pub fn handle_locale_changed(self: Handle<Self>, app: &mut App) {
1119 let locales = app.platform().locales();
1120 self.dispatch_locales_changed(app, Some(&locales));
1121 }
1122
1123 pub fn dispatch_locales_changed(self: Handle<Self>, app: &mut App, locales: Option<&[Locale]>) {
1129 for observer in app.get(self).observers.clone() {
1130 observer.did_change_locales(app, locales);
1131 }
1132 }
1133
1134 pub fn handle_accessibility_features_changed(self: Handle<Self>, app: &mut App) {
1136 for observer in app.get(self).observers.clone() {
1137 observer.did_change_accessibility_features(app);
1138 }
1139 }
1140
1141 pub fn handle_pop_route(self: Handle<Self>, app: &mut App, view: ViewId) -> bool {
1147 for observer in app.get(self).observers.clone() {
1148 if observer.did_pop_route(app, view) {
1149 return true;
1150 }
1151 }
1152 false
1153 }
1154
1155 pub fn handle_start_back_gesture(
1162 self: Handle<Self>,
1163 app: &mut App,
1164 back_event: PredictiveBackEvent,
1165 ) -> bool {
1166 app.get_mut(self).back_gesture_observers.clear();
1167 for observer in app.get(self).observers.clone() {
1168 if observer.handle_start_back_gesture(app, back_event) {
1169 app.get_mut(self).back_gesture_observers.push(observer);
1170 }
1171 }
1172 !app.get(self).back_gesture_observers.is_empty()
1173 }
1174
1175 pub fn handle_update_back_gesture_progress(
1179 self: Handle<Self>,
1180 app: &mut App,
1181 back_event: PredictiveBackEvent,
1182 ) {
1183 if app.get(self).back_gesture_observers.is_empty() {
1184 return;
1185 }
1186
1187 for observer in app.get(self).back_gesture_observers.clone() {
1188 observer.handle_update_back_gesture_progress(app, back_event);
1189 }
1190 }
1191
1192 pub fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App, view: ViewId) -> bool {
1201 if app.get(self).back_gesture_observers.is_empty() {
1202 return self.handle_pop_route(app, view);
1208 }
1209 for observer in app.get(self).back_gesture_observers.clone() {
1210 observer.handle_commit_back_gesture(app);
1211 }
1212 true
1213 }
1214
1215 pub fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App) {
1219 for observer in app.get(self).back_gesture_observers.clone() {
1220 observer.handle_cancel_back_gesture(app);
1221 }
1222 }
1223
1224 pub fn is_root_widget_attached(self: Handle<Self>, app: &App) -> bool {
1229 app.get(self).root_element.is_some()
1230 }
1231}
1232
1233fn intent_for_edit_command(command: EditCommand) -> Box<dyn Intent> {
1235 match command {
1236 EditCommand::Undo => Box::new(UndoTextIntent::new(SelectionChangedCause::Keyboard)),
1237 EditCommand::Redo => Box::new(RedoTextIntent::new(SelectionChangedCause::Keyboard)),
1238 EditCommand::SelectAll => {
1239 Box::new(SelectAllTextIntent::new(SelectionChangedCause::Keyboard))
1240 }
1241 EditCommand::Delete => Box::new(DeleteCharacterIntent::new(true)),
1242 }
1243}
1244
1245fn intent_for_clipboard_event(event: &ClipboardEvent) -> Box<dyn Intent> {
1246 match event {
1247 ClipboardEvent::Copy(_) => Box::new(CopySelectionTextIntent::COPY),
1248 ClipboardEvent::Cut(_) => Box::new(CopySelectionTextIntent::cut(
1249 SelectionChangedCause::Keyboard,
1250 )),
1251 ClipboardEvent::Paste(_) => Box::new(PasteTextIntent::new(SelectionChangedCause::Keyboard)),
1252 }
1253}
1254
1255impl SchedulerBindingOverridesObject for WidgetsBinding {
1258 fn handle_app_lifecycle_state_changed(
1259 self: Handle<Self>,
1260 app: &mut App,
1261 state: AppLifecycleState,
1262 ) {
1263 for observer in app.get(self).observers.clone() {
1264 observer.did_change_app_lifecycle_state(app, state);
1265 }
1266 }
1267}
1268
1269impl ServicesBindingOverridesObject for WidgetsBinding {
1272 fn handle_request_app_exit(self: Handle<Self>, app: &mut App) -> Task<AppExitResponse> {
1273 let mut observers = app.get(self).observers.clone().into_iter();
1274 let Some(first) = observers.next() else {
1277 return Task::ready(AppExitResponse::Exit);
1278 };
1279 let mut response = first.did_request_app_exit(app);
1280 app.spawn(async move |cx| {
1281 let mut did_cancel = false;
1282 loop {
1283 if response.await == AppExitResponse::Cancel {
1284 did_cancel = true;
1285 }
1289 let Some(observer) = observers
1291 .by_ref()
1292 .find(|observer| cx.update(|app| self.is_observing(app, observer)))
1293 else {
1294 break;
1295 };
1296 response = cx.update(|app| observer.did_request_app_exit(app));
1297 }
1298 if did_cancel {
1299 AppExitResponse::Cancel
1300 } else {
1301 AppExitResponse::Exit
1302 }
1303 })
1304 }
1305}
1306
1307impl RendererBindingOverridesObject for WidgetsBinding {
1310 fn will_draw_frame(self: Handle<Self>, app: &mut App) {
1311 if let Some(root_element) = app.get(self).root_element {
1312 let owner = self.build_owner(app);
1313 owner.build_scope(app, root_element, None);
1314 }
1315 }
1316
1317 fn did_draw_frame(self: Handle<Self>, app: &mut App) {
1318 let owner = self.build_owner(app);
1319 owner.finalize_tree(app);
1320 if RendererBinding::instance(app).send_frames_to_engine(app) {
1321 app.get_mut(self).did_send_first_frame = true;
1322 }
1323 }
1324
1325 fn did_handle_metrics_changed(self: Handle<Self>, app: &mut App) {
1327 for observer in app.get(self).observers.clone() {
1328 observer.did_change_metrics(app);
1329 }
1330 }
1331}
1332
1333pub fn run_app(app: &mut App, content: WidgetRef) {
1363 run_app_with(app, content, WindowConfig::default());
1364}
1365
1366pub fn run_app_with(app: &mut App, content: WidgetRef, window: WindowConfig) {
1369 if app.platform().views().is_empty()
1370 && let Err(error) = app.platform().request_view(window, None)
1371 {
1372 no_window_for_the_app(&error);
1373 }
1374 run_widget(
1375 app,
1376 MultiViewApp::new(move |_app, view| view.initial_data().is_none().then(|| content.clone()))
1377 .into_widget(),
1378 );
1379}
1380
1381fn no_window_for_the_app(error: &ViewError) -> ! {
1382 panic!(
1383 "run_app: the platform gave the app no view and made no window for it ({error}); an app \
1384 embedded where views come later starts with MultiViewApp"
1385 )
1386}
1387
1388pub(crate) fn close_or_ask_to_quit(app: &mut App, view: &ViewRef) {
1391 if app.platform().views().len() <= 1 {
1392 let _answer =
1393 ServicesBinding::instance(app).exit_application(app, AppExitType::Cancelable, 0);
1394 return;
1395 }
1396 if let Some(window) = view.window() {
1397 window.close();
1398 }
1399}
1400
1401pub fn run_widget(app: &mut App, widget: WidgetRef) {
1406 let binding = WidgetsBinding::instance(app);
1407 run_widget_internal(app, binding, widget);
1408}
1409
1410fn run_widget_internal(app: &mut App, binding: Handle<WidgetsBinding>, widget: WidgetRef) {
1411 binding.schedule_attach_root_widget(app, widget);
1412 SchedulerBinding::schedule_warm_up_frame(app);
1413}
1414
1415pub fn debug_dump_app(app: &mut App) -> String {
1419 let mode = if cfg!(debug_assertions) {
1420 "DEBUG MODE"
1421 } else {
1422 "RELEASE MODE"
1423 };
1424 let tree = match WidgetsBinding::instance(app).root_element(app) {
1425 Some(root) => root.to_string_deep(app),
1426 None => "<no tree currently mounted>\n".to_owned(),
1427 };
1428 format!("WidgetsBinding - {mode}\n{tree}\n")
1429}
1430
1431#[derive(Debug, Default)]
1438pub struct RootWidget {
1439 pub key: Option<KeyRef>,
1440 pub child: Option<WidgetRef>,
1442 pub debug_short_description: Option<String>,
1444 created: Option<CreationLocation>,
1446}
1447
1448impl RootWidget {
1449 pub fn new() -> RootWidget {
1451 RootWidget::default()
1452 }
1453
1454 pub fn key(mut self, key: KeyRef) -> RootWidget {
1456 self.key = Some(key);
1457 self
1458 }
1459
1460 #[cfg_attr(debug_assertions, track_caller)]
1462 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> RootWidget {
1463 self.child = Some(child.into_widget());
1464 self
1465 }
1466
1467 pub fn debug_short_description(
1469 mut self,
1470 debug_short_description: impl Into<String>,
1471 ) -> RootWidget {
1472 self.debug_short_description = Some(debug_short_description.into());
1473 self
1474 }
1475
1476 #[cfg_attr(debug_assertions, track_caller)]
1485 pub fn attach(
1486 mut self,
1487 app: &mut App,
1488 owner: Handle<BuildOwner>,
1489 element: Option<Handle<RootElement>>,
1490 ) -> Handle<RootElement> {
1491 self.created = Some(CreationLocation::of_caller());
1492 let widget: WidgetRef = Rc::new(self);
1493 match element {
1494 None => {
1495 let mut created = None;
1496 owner.lock_state(app, |app| {
1497 let element = RootElement::new(app, widget.clone());
1498 element.as_element().assign_owner(app, owner);
1499 created = Some(element);
1500 });
1501 let element = created.expect("created while locked");
1502 owner.build_scope(
1503 app,
1504 element.as_element(),
1505 Some(Box::new(move |app| {
1506 element.as_element().mount(app, None, None)
1507 })),
1508 );
1509 element
1510 }
1511 Some(element) => {
1512 app.get_mut(element).new_widget = Some(widget);
1513 element.as_element().mark_needs_build(app);
1514 element
1515 }
1516 }
1517 }
1518}
1519
1520impl Widget for RootWidget {
1521 fn key(&self) -> Option<&KeyRef> {
1522 self.key.as_ref()
1523 }
1524
1525 fn creation_location(&self) -> Option<&'static Location<'static>> {
1526 self.created.and_then(CreationLocation::location)
1527 }
1528
1529 fn record_creation_location(&mut self, location: CreationLocation) {
1530 self.created = Some(location);
1531 }
1532
1533 fn to_string_short(&self) -> String {
1534 self.debug_short_description
1535 .clone()
1536 .unwrap_or_else(|| crate::describe_widget(self.type_name(), self.key()))
1537 }
1538
1539 fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
1540 RootElement::new(app, this).as_element()
1541 }
1542
1543 fn as_any(&self) -> &dyn std::any::Any {
1544 self
1545 }
1546
1547 fn widget_type(&self) -> std::any::TypeId {
1548 std::any::TypeId::of::<RootWidget>()
1549 }
1550
1551 fn kind(&self) -> WidgetKind {
1552 WidgetKind::Other
1553 }
1554}
1555
1556pub struct RootElement {
1566 element: ElementData,
1567 child: Option<AnyElement>,
1568 new_widget: Option<WidgetRef>,
1569}
1570
1571impl RootElement {
1572 fn new(app: &mut App, widget: WidgetRef) -> Handle<RootElement> {
1573 debug_assert!(downcast_widget::<RootWidget>(&*widget).is_some());
1574 app.create(RootElement {
1575 element: ElementData::new(widget),
1576 child: None,
1577 new_widget: None,
1578 })
1579 .into_tree_node(app)
1580 }
1581
1582 pub fn child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
1584 app.get(self).child
1585 }
1586
1587 fn rebuild_child(self: Handle<Self>, app: &mut App) {
1588 let child_widget = downcast_widget::<RootWidget>(&**self.as_element().widget(app))
1589 .expect("a RootElement holds a RootWidget")
1590 .child
1591 .clone();
1592 let child = app.get(self).child;
1593 let child = self
1594 .as_element()
1595 .update_child(app, child, child_widget, None);
1596 app.get_mut(self).child = child;
1597 }
1598}
1599
1600impl Element for RootElement {
1601 crate::element_accessors!();
1602
1603 fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
1604 if let Some(child) = app.get(self).child {
1605 visitor(child);
1606 }
1607 }
1608
1609 fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
1610 debug_assert!(app.get(self).child == Some(child));
1611 app.get_mut(self).child = None;
1612 }
1613
1614 fn mount(
1615 self: Handle<Self>,
1616 app: &mut App,
1617 parent: Option<AnyElement>,
1618 new_slot: Option<Slot>,
1619 ) {
1620 debug_assert!(parent.is_none()); debug_assert!(new_slot.is_none());
1622 ElementBase::mount(self, app, parent, new_slot);
1623 self.rebuild_child(app);
1624 debug_assert!(app.get(self).child.is_some());
1625 ElementBase::perform_rebuild(self, app); }
1627
1628 fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
1629 ElementBase::update(self, app, new_widget);
1630 self.rebuild_child(app);
1631 }
1632
1633 fn perform_rebuild(self: Handle<Self>, app: &mut App) {
1634 if let Some(new_widget) = app.get_mut(self).new_widget.take() {
1635 Element::update(self, app, new_widget);
1636 }
1637 ElementBase::perform_rebuild(self, app);
1638 debug_assert!(app.get(self).new_widget.is_none());
1639 }
1640
1641 fn debug_doing_build(self: Handle<Self>, _app: &App) -> bool {
1642 false }
1644
1645 fn debug_expects_render_object_for_slot(
1646 self: Handle<Self>,
1647 _app: &App,
1648 _slot: Option<&Slot>,
1649 ) -> bool {
1650 false
1651 }
1652}
1653
1654pub(crate) fn current_build_owner(app: &App) -> Option<Handle<BuildOwner>> {
1657 let binding = app.get_singleton::<WidgetsBinding>()?;
1658 app.get(binding).build_owner.handle()
1659}
1660
1661#[cfg(test)]
1662mod tests {
1663 use std::cell::Cell;
1664 use std::rc::Rc;
1665 use std::time::Duration;
1666
1667 use waft_embedder::Size;
1668 use waft_foundation::{App, AppCell, Completer, Handle};
1669 use waft_rendering::{
1670 AnyRenderObject, BoxConstraints, RenderBox, RenderConstrainedBox, RenderConstrainedBoxBase,
1671 RenderHandle, RendererBinding,
1672 };
1673 use waft_scheduler::SchedulerBinding;
1674 use waft_test::{IMPLICIT_VIEW_ID, TestPlatform};
1675
1676 use super::*;
1677 use crate::framework::{
1678 BuildContext, LeafRenderObjectWidget, RenderObjectWidget, State, StateData, StatefulWidget,
1679 };
1680 use crate::testing::{WidgetTester, test_widgets};
1681
1682 #[derive(Debug)]
1683 struct Sized {
1684 size: Size,
1685 }
1686
1687 impl RenderObjectWidget for Sized {
1688 type RenderObject = RenderConstrainedBox;
1689
1690 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1691 RenderConstrainedBox::new(app, BoxConstraints::tight(self.size), None).as_object()
1692 }
1693
1694 fn update_render_object(
1695 &self,
1696 app: &mut App,
1697 _context: BuildContext,
1698 render_object: RenderHandle<RenderConstrainedBox>,
1699 ) {
1700 render_object.set_additional_constraints(app, BoxConstraints::tight(self.size));
1701 }
1702 }
1703
1704 impl LeafRenderObjectWidget for Sized {}
1705
1706 #[derive(Debug)]
1707 struct Resizable {
1708 size: Rc<Cell<Size>>,
1709 state: Rc<Cell<Option<Handle<ResizableState>>>>,
1710 }
1711
1712 impl StatefulWidget for Resizable {
1713 type State = ResizableState;
1714
1715 fn create_state(&self) -> ResizableState {
1716 ResizableState {
1717 state: StateData::new(),
1718 }
1719 }
1720 }
1721
1722 struct ResizableState {
1723 state: StateData<Resizable>,
1724 }
1725
1726 impl State for ResizableState {
1727 type Widget = Resizable;
1728 crate::state_accessors!();
1729
1730 fn init_state(self: Handle<Self>, app: &mut App) {
1731 self.widget(app).state.set(Some(self));
1732 }
1733
1734 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1735 Sized {
1736 size: self.widget(app).size.get(),
1737 }
1738 .into_widget()
1739 }
1740 }
1741
1742 fn root_child_size(app: &mut App) -> Size {
1743 let render_view = RendererBinding::instance(app)
1744 .render_views(app)
1745 .into_iter()
1746 .next()
1747 .expect("run_app registered a render view");
1748 let child = render_view.child(app).expect("the view has a child");
1749 child.size(app)
1750 }
1751
1752 fn app_with_view() -> (Rc<AppCell>, Rc<waft_test::TestView>) {
1755 let view = Rc::new(waft_test::TestView::with_pixel_ratio(
1756 WidgetTester::SIZE.width() * WidgetTester::DEVICE_PIXEL_RATIO,
1757 WidgetTester::SIZE.height() * WidgetTester::DEVICE_PIXEL_RATIO,
1758 WidgetTester::DEVICE_PIXEL_RATIO,
1759 ));
1760 let platform = Rc::new(TestPlatform::new().with_view(view.clone()));
1761 (AppCell::with_platform(platform), view)
1762 }
1763
1764 #[test]
1765 fn run_app_attaches_on_the_next_timer_turn_and_draws_a_warm_up_frame() {
1766 let (cell, view) = app_with_view();
1767 let mut app = cell.borrow_mut();
1768 run_app(
1769 &mut app,
1770 Sized {
1771 size: Size::new(30.0, 20.0),
1772 }
1773 .into_widget(),
1774 );
1775 let binding = WidgetsBinding::instance(&mut app);
1776 assert!(!binding.is_root_widget_attached(&app));
1777 assert_eq!(view.presented(), 0);
1778
1779 drop(app);
1780 cell.elapse(Duration::ZERO);
1781 let mut app = cell.borrow_mut();
1782 assert!(binding.is_root_widget_attached(&app));
1783 let root = binding
1784 .root_element(&app)
1785 .and_then(|element| element.downcast::<RootElement>(&app))
1786 .expect("the root element is a RootElement");
1787 assert!(root.child(&app).is_some());
1788 assert_eq!(
1789 view.presented(),
1790 1,
1791 "the warm-up frame drew without a host frame"
1792 );
1793 assert_eq!(root_child_size(&mut app), Size::new(800.0, 600.0));
1794 }
1795
1796 #[test]
1797 fn set_state_schedules_a_frame_that_rebuilds_before_layout() {
1798 test_widgets(|tester| {
1799 let mut app = tester.cell.borrow_mut();
1800 let size = Rc::new(Cell::new(Size::new(30.0, 20.0)));
1801 let state = Rc::new(Cell::new(None));
1802 run_app(
1803 &mut app,
1804 Resizable {
1805 size: Rc::clone(&size),
1806 state: Rc::clone(&state),
1807 }
1808 .into_widget(),
1809 );
1810 drop(app);
1811 tester.cell.elapse(Duration::ZERO);
1812 let mut app = tester.cell.borrow_mut();
1813 assert_eq!(tester.view().presented(), 2, "the warm-up frame");
1815 tester.platform().take_frame_requests();
1816
1817 size.set(Size::new(50.0, 60.0));
1818 let state = state.get().expect("the state registered itself");
1819 state.set_state(&mut app, |_| {});
1820 assert_eq!(tester.platform().frame_requests(), [IMPLICIT_VIEW_ID]);
1821
1822 drop(app);
1823 tester.pump_by(Duration::from_millis(16));
1824 let mut app = tester.cell.borrow_mut();
1825 assert_eq!(tester.view().presented(), 3);
1826 assert_eq!(root_child_size(&mut app), Size::new(800.0, 600.0));
1827 let root = WidgetsBinding::instance(&mut app)
1828 .root_element(&app)
1829 .expect("attached");
1830 let mut leaves = Vec::new();
1831 collect_leaves(&app, root, &mut leaves);
1832 assert_eq!(leaves.len(), 1);
1833 });
1834 }
1835
1836 fn collect_leaves(app: &App, element: AnyElement, leaves: &mut Vec<AnyElement>) {
1837 let mut children = Vec::new();
1838 element.visit_children(app, &mut |child| children.push(child));
1839 if children.is_empty() {
1840 leaves.push(element);
1841 }
1842 for child in children {
1843 collect_leaves(app, child, leaves);
1844 }
1845 }
1846
1847 #[test]
1848 fn running_a_second_app_updates_the_root_in_place() {
1849 test_widgets(|tester| {
1850 let mut app = tester.cell.borrow_mut();
1851 run_app(
1852 &mut app,
1853 Sized {
1854 size: Size::new(30.0, 20.0),
1855 }
1856 .into_widget(),
1857 );
1858 drop(app);
1859 tester.cell.elapse(Duration::ZERO);
1860 let app = tester.cell.borrow();
1861 drop(app);
1862 tester.pump();
1863 let mut app = tester.cell.borrow_mut();
1864 let binding = WidgetsBinding::instance(&mut app);
1865 let first_root = binding.root_element(&app);
1866
1867 run_app(
1868 &mut app,
1869 Sized {
1870 size: Size::new(10.0, 10.0),
1871 }
1872 .into_widget(),
1873 );
1874 drop(app);
1875 tester.cell.elapse(Duration::ZERO);
1876 let app = tester.cell.borrow();
1877 assert_eq!(binding.root_element(&app), first_root);
1878 drop(app);
1879 tester.pump_by(Duration::from_millis(16));
1880 let mut app = tester.cell.borrow_mut();
1881 assert_eq!(
1882 RendererBinding::instance(&mut app).render_views(&app).len(),
1883 1
1884 );
1885 });
1886 }
1887
1888 struct ExitObserver {
1891 name: &'static str,
1892 log: Rc<std::cell::RefCell<Vec<&'static str>>>,
1893 answer: Completer<AppExitResponse>,
1894 }
1895
1896 impl ExitObserver {
1897 fn answering(
1898 name: &'static str,
1899 log: &Rc<std::cell::RefCell<Vec<&'static str>>>,
1900 response: AppExitResponse,
1901 ) -> ExitObserver {
1902 ExitObserver::deciding(name, log, Completer::completed(response))
1903 }
1904
1905 fn deciding(
1906 name: &'static str,
1907 log: &Rc<std::cell::RefCell<Vec<&'static str>>>,
1908 answer: Completer<AppExitResponse>,
1909 ) -> ExitObserver {
1910 ExitObserver {
1911 name,
1912 log: Rc::clone(log),
1913 answer,
1914 }
1915 }
1916 }
1917
1918 impl WidgetsBindingObserver for ExitObserver {
1919 fn did_request_app_exit(&self, app: &mut App) -> Task<AppExitResponse> {
1920 self.log.borrow_mut().push(self.name);
1921 let answer = self.answer.future();
1922 app.spawn(async move |_cx| answer.await)
1923 }
1924 }
1925
1926 struct AddingObserver {
1928 added: std::cell::RefCell<Option<WidgetsBindingObserverRef>>,
1929 }
1930
1931 impl WidgetsBindingObserver for AddingObserver {
1932 fn did_request_app_exit(&self, app: &mut App) -> Task<AppExitResponse> {
1933 if let Some(added) = self.added.take() {
1934 WidgetsBinding::instance(app).add_observer(app, added);
1935 }
1936 Task::ready(AppExitResponse::Exit)
1937 }
1938 }
1939
1940 fn add_observers(cell: &Rc<AppCell>, observers: impl IntoIterator<Item = ExitObserver>) {
1941 let mut app = cell.borrow_mut();
1942 let binding = WidgetsBinding::instance(&mut app);
1943 for observer in observers {
1944 binding.add_observer(&mut app, Rc::new(observer));
1945 }
1946 }
1947
1948 fn request_app_exit(cell: &Rc<AppCell>) -> Rc<Cell<Option<AppExitResponse>>> {
1951 let response = {
1952 let mut app = cell.borrow_mut();
1953 ServicesBinding::instance(&mut app).handle_request_app_exit(&mut app)
1954 };
1955 let answer = Rc::new(Cell::new(None));
1956 let out = Rc::clone(&answer);
1957 cell.borrow()
1958 .spawn(async move |_cx| out.set(Some(response.await)));
1959 cell.checkpoint();
1960 answer
1961 }
1962
1963 #[test]
1964 fn an_exit_request_asks_every_observer_even_after_one_cancels() {
1965 let cell = AppCell::new();
1966 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
1967 add_observers(
1968 &cell,
1969 [
1970 ExitObserver::answering("refusing", &log, AppExitResponse::Cancel),
1971 ExitObserver::answering("agreeing", &log, AppExitResponse::Exit),
1972 ],
1973 );
1974 let response = request_app_exit(&cell);
1975 assert_eq!(*log.borrow(), ["refusing", "agreeing"]);
1976 assert_eq!(response.get(), Some(AppExitResponse::Cancel));
1977 }
1978
1979 #[test]
1980 fn an_exit_request_exits_when_every_observer_agrees() {
1981 let cell = AppCell::new();
1982 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
1983 add_observers(
1984 &cell,
1985 [ExitObserver::answering(
1986 "agreeing",
1987 &log,
1988 AppExitResponse::Exit,
1989 )],
1990 );
1991 let response = request_app_exit(&cell);
1992 assert_eq!(*log.borrow(), ["agreeing"]);
1993 assert_eq!(response.get(), Some(AppExitResponse::Exit));
1994 }
1995
1996 #[test]
1997 fn an_exit_request_asks_each_observer_once_the_one_before_has_answered() {
1998 let cell = AppCell::new();
1999 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2000 let decision = Completer::new();
2001 add_observers(
2002 &cell,
2003 [
2004 ExitObserver::deciding("deciding", &log, decision.clone()),
2005 ExitObserver::answering("agreeing", &log, AppExitResponse::Exit),
2006 ],
2007 );
2008 let response = request_app_exit(&cell);
2009 assert_eq!(*log.borrow(), ["deciding"], "the first answer is awaited");
2010 assert_eq!(response.get(), None);
2011
2012 decision.complete(&mut cell.borrow_mut(), AppExitResponse::Exit);
2013 cell.checkpoint();
2014 assert_eq!(*log.borrow(), ["deciding", "agreeing"]);
2015 assert_eq!(response.get(), Some(AppExitResponse::Exit));
2016 }
2017
2018 #[test]
2021 fn an_observer_added_during_an_exit_request_is_asked_from_the_next_one_on() {
2022 let cell = AppCell::new();
2023 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2024 let added: WidgetsBindingObserverRef = Rc::new(ExitObserver::answering(
2025 "added",
2026 &log,
2027 AppExitResponse::Cancel,
2028 ));
2029 {
2030 let mut app = cell.borrow_mut();
2031 let adding = AddingObserver {
2032 added: std::cell::RefCell::new(Some(added)),
2033 };
2034 WidgetsBinding::instance(&mut app).add_observer(&mut app, Rc::new(adding));
2035 }
2036 let first = request_app_exit(&cell);
2037 assert!(log.borrow().is_empty(), "the added observer was not asked");
2038 assert_eq!(first.get(), Some(AppExitResponse::Exit));
2039
2040 let second = request_app_exit(&cell);
2041 assert_eq!(*log.borrow(), ["added"]);
2042 assert_eq!(second.get(), Some(AppExitResponse::Cancel));
2043 }
2044
2045 #[derive(Default)]
2047 struct LifecycleObserver {
2048 states: std::cell::RefCell<Vec<AppLifecycleState>>,
2049 }
2050
2051 impl WidgetsBindingObserver for LifecycleObserver {
2052 fn did_change_app_lifecycle_state(&self, _app: &mut App, state: AppLifecycleState) {
2053 self.states.borrow_mut().push(state);
2054 }
2055 }
2056
2057 #[test]
2058 fn the_scheduler_s_lifecycle_handler_tells_the_observers() {
2059 let cell = AppCell::new();
2060 let mut app = cell.borrow_mut();
2061 let observer = Rc::new(LifecycleObserver::default());
2062 WidgetsBinding::instance(&mut app).add_observer(&mut app, observer.clone());
2063
2064 SchedulerBinding::handle_app_lifecycle_state_changed(&mut app, AppLifecycleState::Paused);
2065
2066 assert_eq!(*observer.states.borrow(), [AppLifecycleState::Paused]);
2067 assert_eq!(
2068 SchedulerBinding::lifecycle_state(&mut app),
2069 Some(AppLifecycleState::Paused)
2070 );
2071 }
2072
2073 #[test]
2074 fn a_metrics_change_reaches_the_observers_and_the_media_query() {
2075 test_widgets(|tester| {
2076 let mut app = tester.cell.borrow_mut();
2077 let sizes = Rc::new(std::cell::RefCell::new(Vec::new()));
2078 let probe = crate::widgets::basic::Builder::new({
2079 let sizes = Rc::clone(&sizes);
2080 move |app, context| {
2081 sizes
2082 .borrow_mut()
2083 .push(crate::MediaQuery::size_of(app, context));
2084 Sized {
2085 size: Size::new(1.0, 1.0),
2086 }
2087 .into_widget()
2088 }
2089 });
2090 run_app(&mut app, probe.into_widget());
2091 drop(app);
2092 tester.cell.elapse(Duration::ZERO);
2093 tester.pump();
2094 assert_eq!(*sizes.borrow(), vec![Size::new(800.0, 600.0)]);
2095
2096 tester.view().set_physical_size(Size::new(1500.0, 600.0));
2097 tester.pump_by(Duration::from_millis(16));
2098 assert_eq!(
2099 *sizes.borrow(),
2100 vec![Size::new(800.0, 600.0), Size::new(500.0, 200.0)]
2101 );
2102 });
2103 }
2104
2105 #[test]
2106 fn a_change_of_the_caption_settings_reaches_the_media_query() {
2107 let text_scaled = |scale: f64| waft_embedder::CaptionStyle {
2108 text_scale: Some(waft_embedder::CaptionSetting::always(scale)),
2109 ..waft_embedder::CaptionStyle::default()
2110 };
2111 let settings = waft_test::MockCaptionSettings::new(text_scaled(1.5));
2112 let tester = &mut WidgetTester::with_platform(
2113 TestPlatform::new().with_caption_settings(Rc::new(settings.clone())),
2114 );
2115 let styles = Rc::new(std::cell::RefCell::new(Vec::new()));
2116 let probe = crate::widgets::basic::Builder::new({
2117 let styles = Rc::clone(&styles);
2118 move |app, context| {
2119 styles
2120 .borrow_mut()
2121 .push(crate::MediaQuery::caption_style_of(app, context));
2122 Sized {
2123 size: Size::new(1.0, 1.0),
2124 }
2125 .into_widget()
2126 }
2127 });
2128 tester.pump_widget(probe);
2129 assert_eq!(*styles.borrow(), vec![Some(text_scaled(1.5))]);
2130
2131 settings.set_style(text_scaled(2.0));
2132 tester.cell.checkpoint();
2133 tester.pump();
2134 assert_eq!(
2135 *styles.borrow(),
2136 vec![Some(text_scaled(1.5)), Some(text_scaled(2.0))]
2137 );
2138 }
2139
2140 #[test]
2141 fn the_media_query_has_no_caption_style_where_the_platform_keeps_no_caption_settings() {
2142 test_widgets(|tester| {
2143 let styles = Rc::new(std::cell::RefCell::new(Vec::new()));
2144 let probe = crate::widgets::basic::Builder::new({
2145 let styles = Rc::clone(&styles);
2146 move |app, context| {
2147 styles
2148 .borrow_mut()
2149 .push(crate::MediaQuery::caption_style_of(app, context));
2150 Sized {
2151 size: Size::new(1.0, 1.0),
2152 }
2153 .into_widget()
2154 }
2155 });
2156 tester.pump_widget(probe);
2157 assert_eq!(*styles.borrow(), vec![None]);
2158 });
2159 }
2160
2161 struct BackGestureObserver {
2163 name: &'static str,
2164 handles: Cell<bool>,
2165 log: Rc<std::cell::RefCell<Vec<String>>>,
2166 }
2167
2168 impl BackGestureObserver {
2169 fn new(
2170 name: &'static str,
2171 handles: bool,
2172 log: &Rc<std::cell::RefCell<Vec<String>>>,
2173 ) -> Rc<BackGestureObserver> {
2174 Rc::new(BackGestureObserver {
2175 name,
2176 handles: Cell::new(handles),
2177 log: Rc::clone(log),
2178 })
2179 }
2180
2181 fn note(&self, what: &str) {
2182 self.log.borrow_mut().push(format!("{} {what}", self.name));
2183 }
2184 }
2185
2186 impl WidgetsBindingObserver for BackGestureObserver {
2187 fn did_pop_route(&self, _app: &mut App, _view: ViewId) -> bool {
2188 self.note("didPopRoute");
2189 false
2190 }
2191
2192 fn handle_start_back_gesture(&self, _app: &mut App, _event: PredictiveBackEvent) -> bool {
2193 self.note("handleStartBackGesture");
2194 self.handles.get()
2195 }
2196
2197 fn handle_update_back_gesture_progress(&self, _app: &mut App, event: PredictiveBackEvent) {
2198 self.note(&format!(
2199 "handleUpdateBackGestureProgress {}",
2200 event.progress
2201 ));
2202 }
2203
2204 fn handle_commit_back_gesture(&self, _app: &mut App) {
2205 self.note("handleCommitBackGesture");
2206 }
2207
2208 fn handle_cancel_back_gesture(&self, _app: &mut App) {
2209 self.note("handleCancelBackGesture");
2210 }
2211 }
2212
2213 fn start_event() -> PredictiveBackEvent {
2215 PredictiveBackEvent::new(
2216 Some(waft_embedder::Offset::new(5.0, 300.0)),
2217 0.0,
2218 waft_services::SwipeEdge::Left,
2219 )
2220 }
2221
2222 fn update_event() -> PredictiveBackEvent {
2223 PredictiveBackEvent::new(
2224 Some(waft_embedder::Offset::new(100.0, 300.0)),
2225 0.35,
2226 waft_services::SwipeEdge::Left,
2227 )
2228 }
2229
2230 fn add_back_gesture_observers(
2231 app: &mut App,
2232 observers: impl IntoIterator<Item = Rc<BackGestureObserver>>,
2233 ) -> Handle<WidgetsBinding> {
2234 let binding = WidgetsBinding::instance(app);
2235 for observer in observers {
2236 binding.add_observer(app, observer);
2237 }
2238 binding
2239 }
2240
2241 #[test]
2244 fn a_back_gesture_s_start_asks_every_observer_and_answers_whether_one_handles_it() {
2245 let cell = AppCell::new();
2246 let mut app = cell.borrow_mut();
2247 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2248 let declining = BackGestureObserver::new("declining", false, &log);
2249 let handling = BackGestureObserver::new("handling", true, &log);
2250 let binding = add_back_gesture_observers(&mut app, [declining, Rc::clone(&handling)]);
2251 assert!(binding.handle_start_back_gesture(&mut app, start_event()));
2252 assert_eq!(
2253 *log.borrow(),
2254 [
2255 "declining handleStartBackGesture",
2256 "handling handleStartBackGesture"
2257 ]
2258 );
2259
2260 handling.handles.set(false);
2261 assert!(
2262 !binding.handle_start_back_gesture(&mut app, start_event()),
2263 "no observer handles it"
2264 );
2265 }
2266
2267 #[test]
2270 fn every_observer_that_handles_a_back_gesture_s_start_hears_its_progress() {
2271 let cell = AppCell::new();
2272 let mut app = cell.borrow_mut();
2273 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2274 let binding = add_back_gesture_observers(
2275 &mut app,
2276 [
2277 BackGestureObserver::new("first", true, &log),
2278 BackGestureObserver::new("declining", false, &log),
2279 BackGestureObserver::new("second", true, &log),
2280 ],
2281 );
2282 binding.handle_start_back_gesture(&mut app, start_event());
2283 log.borrow_mut().clear();
2284
2285 binding.handle_update_back_gesture_progress(&mut app, update_event());
2286 assert_eq!(
2287 *log.borrow(),
2288 [
2289 "first handleUpdateBackGestureProgress 0.35",
2290 "second handleUpdateBackGestureProgress 0.35"
2291 ]
2292 );
2293 }
2294
2295 #[test]
2298 fn committing_a_back_gesture_tells_only_the_observers_that_handle_it() {
2299 let cell = AppCell::new();
2300 let mut app = cell.borrow_mut();
2301 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2302 let binding = add_back_gesture_observers(
2303 &mut app,
2304 [
2305 BackGestureObserver::new("declining", false, &log),
2306 BackGestureObserver::new("handling", true, &log),
2307 ],
2308 );
2309 binding.handle_start_back_gesture(&mut app, start_event());
2310 log.borrow_mut().clear();
2311
2312 assert!(binding.handle_commit_back_gesture(&mut app, IMPLICIT_VIEW_ID));
2313 assert_eq!(*log.borrow(), ["handling handleCommitBackGesture"]);
2314 }
2315
2316 #[test]
2319 fn canceling_a_back_gesture_tells_only_the_observers_that_handle_it() {
2320 let cell = AppCell::new();
2321 let mut app = cell.borrow_mut();
2322 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2323 let binding = add_back_gesture_observers(
2324 &mut app,
2325 [
2326 BackGestureObserver::new("declining", false, &log),
2327 BackGestureObserver::new("handling", true, &log),
2328 ],
2329 );
2330 binding.handle_start_back_gesture(&mut app, start_event());
2331 log.borrow_mut().clear();
2332
2333 binding.handle_cancel_back_gesture(&mut app);
2334 assert_eq!(*log.borrow(), ["handling handleCancelBackGesture"]);
2335 }
2336
2337 #[test]
2338 fn a_back_gesture_no_observer_handles_hears_no_progress_and_pops_the_route_on_commit() {
2339 let cell = AppCell::new();
2340 let mut app = cell.borrow_mut();
2341 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2342 let binding = add_back_gesture_observers(
2343 &mut app,
2344 [BackGestureObserver::new("declining", false, &log)],
2345 );
2346 binding.handle_start_back_gesture(&mut app, start_event());
2347 log.borrow_mut().clear();
2348
2349 binding.handle_update_back_gesture_progress(&mut app, update_event());
2350 binding.handle_cancel_back_gesture(&mut app);
2351 assert!(log.borrow().is_empty());
2352
2353 assert!(
2354 !binding.handle_commit_back_gesture(&mut app, IMPLICIT_VIEW_ID),
2355 "no observer popped a route"
2356 );
2357 assert_eq!(*log.borrow(), ["declining didPopRoute"]);
2358 }
2359
2360 #[test]
2361 fn a_removed_observer_hears_no_more_of_the_back_gesture_it_handled() {
2362 let cell = AppCell::new();
2363 let mut app = cell.borrow_mut();
2364 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2365 let handling = BackGestureObserver::new("handling", true, &log);
2366 let binding = add_back_gesture_observers(&mut app, [Rc::clone(&handling)]);
2367 binding.handle_start_back_gesture(&mut app, start_event());
2368 log.borrow_mut().clear();
2369
2370 let registered: WidgetsBindingObserverRef = handling;
2371 binding.remove_observer(&mut app, ®istered);
2372 binding.handle_update_back_gesture_progress(&mut app, update_event());
2373 assert!(log.borrow().is_empty());
2374 }
2375
2376 #[test]
2377 fn removing_an_observer_added_twice_removes_one_registration() {
2378 let cell = AppCell::new();
2379 let mut app = cell.borrow_mut();
2380 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2381 let observer = BackGestureObserver::new("twice", true, &log);
2382 let binding =
2383 add_back_gesture_observers(&mut app, [Rc::clone(&observer), Rc::clone(&observer)]);
2384 binding.handle_start_back_gesture(&mut app, start_event());
2385 log.borrow_mut().clear();
2386
2387 let registered: WidgetsBindingObserverRef = observer;
2388 assert!(binding.remove_observer(&mut app, ®istered));
2389 binding.handle_update_back_gesture_progress(&mut app, update_event());
2390 assert_eq!(
2391 *log.borrow(),
2392 ["twice handleUpdateBackGestureProgress 0.35"]
2393 );
2394
2395 log.borrow_mut().clear();
2396 binding.handle_start_back_gesture(&mut app, start_event());
2397 assert_eq!(*log.borrow(), ["twice handleStartBackGesture"]);
2398
2399 assert!(binding.remove_observer(&mut app, ®istered));
2400 assert!(!binding.remove_observer(&mut app, ®istered));
2401 }
2402
2403 #[test]
2404 fn a_new_back_gesture_forgets_the_observers_of_the_last_one() {
2405 let cell = AppCell::new();
2406 let mut app = cell.borrow_mut();
2407 let log = Rc::new(std::cell::RefCell::new(Vec::new()));
2408 let observer = BackGestureObserver::new("observer", true, &log);
2409 let binding = add_back_gesture_observers(&mut app, [Rc::clone(&observer)]);
2410 binding.handle_start_back_gesture(&mut app, start_event());
2411 observer.handles.set(false);
2412 binding.handle_start_back_gesture(&mut app, start_event());
2413 log.borrow_mut().clear();
2414
2415 binding.handle_cancel_back_gesture(&mut app);
2416 assert!(log.borrow().is_empty());
2417 }
2418}