Skip to main content

waft_widgets/
binding.rs

1//! Flutter counterpart: `widgets/binding.dart` (`WidgetsBinding`, `RootWidget`,
2//! `RootElement`, `runApp`).
3//!
4//! The memory-pressure and push-route observer callbacks, `performReassemble`, and the
5//! platform menu owner wait. The back-gesture handlers (`handle_start_back_gesture` and the
6//! three after it) take a predictive back gesture to the observers that handle it, but no host
7//! reports one yet. `handleAppLifecycleStateChanged` tells the observers each lifecycle state
8//! the host reports, and `handleRequestAppExit` asks them whenever the host asks the app to
9//! quit. The windowing owner, which keeps the window controllers and hears every view
10//! event first, is here (`windowing.rs`); a view it does not claim goes to the observers.
11//! `run_app` builds its content in every view the app is given (`multi_view_app.rs`), and asks
12//! for a window where it is given none. The binding follows the platform's caption settings
13//! itself, for as long as the app runs, since they tell their changes by a future where the
14//! other settings call the dispatcher, and tells the observers each change. The host's copy,
15//! cut and paste, which Flutter's engines never send, go to the primary focus as text editing
16//! intents.
17
18use 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/// The glue between the widgets layer and the Flutter engine.
51///
52/// The [`WidgetsBinding`] manages a single [`Element`] tree rooted at
53/// [`root_element`](Self::root_element). This element tree is created by
54/// [`attach_root_widget`](Self::attach_root_widget), and its build is scheduled onto the
55/// renderer's frame: the tree is built before the render tree is laid out and painted, and
56/// finalized after.
57#[derive(Default)]
58pub struct WidgetsBinding {
59    /// Whether the binding is set up: Dart's `_instance` being assigned, which comes before
60    /// the parts `init_instances` builds, since they ask for the binding.
61    initialized: bool,
62    build_owner: Option<Ref<BuildOwner>>,
63    root_element: Option<AnyElement>,
64    ready_to_produce_frames: bool,
65    /// Dart's `!_needToReportFirstFrame`: a frame has been drawn and sent to the host.
66    did_send_first_frame: bool,
67    observers: Vec<WidgetsBindingObserverRef>,
68    /// The observers that are currently handling an active predictive back gesture.
69    back_gesture_observers: Vec<WidgetsBindingObserverRef>,
70    /// Who hears each change of a view's window, by the view: each view's `WindowScope`.
71    window_listeners: HashMap<ViewId, Vec<Listener>>,
72    /// Flutter's `platformMenuDelegate`.
73    platform_menu_delegate: Option<PlatformMenuDelegateRef>,
74    /// Who hears each tray icon's events, by the icon's id.
75    tray_icon_listeners: HashMap<TrayIconId, TrayIconListener>,
76}
77
78/// What hears a tray icon's events (`WidgetsBinding::add_tray_icon_listener`).
79pub type TrayIconListener = Rc<dyn Fn(&mut App, TrayIconEvent)>;
80
81impl std::fmt::Display for WidgetsBinding {
82    /// Dart's `BindingBase.toString`: `<WidgetsBinding>`.
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.write_str("<WidgetsBinding>")
85    }
86}
87
88/// Interface for classes that register with the Widgets layer binding.
89///
90/// This can be used by any class, not just widgets. It provides an interface which is used
91/// by [`WidgetsBinding::add_observer`] and [`WidgetsBinding::remove_observer`] to notify
92/// objects of changes in the environment, such as changes to the device metrics or
93/// accessibility settings. It is used to implement features such as `MediaQuery`.
94///
95/// A `State` registers itself through the object twin
96/// [`WidgetsBindingObserverObject`], whose handle is the observer. The push-route and
97/// memory-pressure callbacks wait with their platform events; only the ones the renderer
98/// raises, the locale list, going back, predictive back gestures, the app's lifecycle states
99/// and exit requests are here.
100pub trait WidgetsBindingObserver {
101    /// Called when the application's dimensions change. For example, when a phone is rotated.
102    fn did_change_metrics(&self, app: &mut App) {
103        let _ = app;
104    }
105
106    /// Called when the system tells the app that the user's locale has changed. For example,
107    /// if the user changes the system language settings.
108    ///
109    /// This method exposes notifications from `PlatformDispatcher.onLocaleChanged`.
110    fn did_change_locales(&self, app: &mut App, locales: Option<&[Locale]>) {
111        let _ = (app, locales);
112    }
113
114    /// Called when the platform reports a change in the focus state of a view.
115    fn did_change_view_focus(&self, app: &mut App, event: ViewFocusEvent) {
116        let _ = (app, event);
117    }
118
119    /// Called when what is dragged from outside the application enters, moves over, is dropped
120    /// on or leaves a view. Flutter has no counterpart: external drops are a plugin there.
121    fn did_change_drag(&self, app: &mut App, report: &DragReport) {
122        let _ = (app, report);
123    }
124
125    /// Called when the platform's text scale factor changes.
126    fn did_change_text_scale_factor(&self, app: &mut App) {
127        let _ = app;
128    }
129
130    /// Called when the platform brightness changes.
131    fn did_change_platform_brightness(&self, app: &mut App) {
132        let _ = app;
133    }
134
135    /// Called when the user changes their caption style in the system's settings. Flutter has
136    /// no counterpart: it reads no caption settings.
137    fn did_change_caption_style(&self, app: &mut App) {
138        let _ = app;
139    }
140
141    /// Called when the system puts the app in the background or returns the app to the
142    /// foreground.
143    ///
144    /// This method exposes notifications from `SystemChannels.lifecycle`.
145    ///
146    /// See also:
147    ///
148    ///  * [`AppLifecycleListener`](crate::AppLifecycleListener), an alternative API for
149    ///    responding to application lifecycle changes.
150    fn did_change_app_lifecycle_state(&self, app: &mut App, state: AppLifecycleState) {
151        let _ = (app, state);
152    }
153
154    /// Called when a request is received from the system to exit the application.
155    ///
156    /// If any observer responds with [`AppExitResponse::Cancel`], it will cancel the exit.
157    /// All observers will be asked before exiting.
158    ///
159    /// Not all exits are cancelable, so not all exits will call this function. Do not rely on
160    /// this function as a place to save critical data, because you will be disappointed. There
161    /// are a number of ways that the application can exit without letting the application know
162    /// first: power can be unplugged, the battery removed, the application can be killed in a
163    /// task manager or command line, or the device could have a rapid unplanned disassembly
164    /// (i.e. it could explode). In all of those cases (and probably others), no notification
165    /// will be given to the application that it is about to exit.
166    ///
167    /// See also:
168    ///
169    ///  * [`ServicesBinding::exit_application`] for a function to call that will request
170    ///    that the application exits.
171    fn did_request_app_exit(&self, app: &mut App) -> Task<AppExitResponse> {
172        let _ = app;
173        Task::ready(AppExitResponse::Exit)
174    }
175
176    /// Called when the system changes the set of currently active accessibility features.
177    fn did_change_accessibility_features(&self, app: &mut App) {
178        let _ = app;
179    }
180
181    /// Called when the user asks to go back in `view`, which on Android is the back button or
182    /// the back gesture in the activity whose window the view is.
183    ///
184    /// Answers whether this observer went back. The first one that answers `true` stops
185    /// the others from being asked. An observer that belongs to one view answers for that view
186    /// alone.
187    fn did_pop_route(&self, app: &mut App, view: ViewId) -> bool {
188        let _ = (app, view);
189        false
190    }
191
192    /// Called at the start of a predictive back gesture.
193    ///
194    /// Observers are notified in registration order until one returns true or all observers
195    /// have been notified. If an observer returns true then that observer, and only that
196    /// observer, will be notified of subsequent events in this same gesture (for example
197    /// [`handle_update_back_gesture_progress`](Self::handle_update_back_gesture_progress),
198    /// etc.).
199    ///
200    /// Observers are expected to return true if they were able to handle the notification, for
201    /// example by starting a predictive back animation, and false otherwise.
202    /// `PredictiveBackPageTransitionsBuilder` uses this mechanism to listen for predictive back
203    /// gestures.
204    ///
205    /// If all observers indicate they are not handling this back gesture by returning false,
206    /// then a navigation pop will result when
207    /// [`handle_commit_back_gesture`](Self::handle_commit_back_gesture) is called, as in a
208    /// non-predictive system back gesture.
209    ///
210    /// Currently, this is only used on Android devices that support the predictive back
211    /// feature.
212    fn handle_start_back_gesture(&self, app: &mut App, back_event: PredictiveBackEvent) -> bool {
213        let _ = (app, back_event);
214        false
215    }
216
217    /// Called when a predictive back gesture moves.
218    ///
219    /// The observer which was notified of this gesture's
220    /// [`handle_start_back_gesture`](Self::handle_start_back_gesture) is the same observer
221    /// notified for this.
222    ///
223    /// Currently, this is only used on Android devices that support the predictive back
224    /// feature.
225    fn handle_update_back_gesture_progress(&self, app: &mut App, back_event: PredictiveBackEvent) {
226        let _ = (app, back_event);
227    }
228
229    /// Called when a predictive back gesture is finished successfully, indicating that the
230    /// current route should be popped.
231    ///
232    /// The observer which was notified of this gesture's
233    /// [`handle_start_back_gesture`](Self::handle_start_back_gesture) is the same observer
234    /// notified for this. If there is none, then a navigation pop will result, as in a
235    /// non-predictive system back gesture.
236    ///
237    /// Currently, this is only used on Android devices that support the predictive back
238    /// feature.
239    fn handle_commit_back_gesture(&self, app: &mut App) {
240        let _ = app;
241    }
242
243    /// Called when a predictive back gesture is canceled, indicating that no navigation should
244    /// occur.
245    ///
246    /// The observer which was notified of this gesture's
247    /// [`handle_start_back_gesture`](Self::handle_start_back_gesture) is the same observer
248    /// notified for this.
249    ///
250    /// Currently, this is only used on Android devices that support the predictive back
251    /// feature.
252    fn handle_cancel_back_gesture(&self, app: &mut App) {
253        let _ = app;
254    }
255
256    /// Called when the platform adds a view for the app, whoever started it: one the app asked
257    /// for in a window (`Platform::request_view`) or on a layer of its own
258    /// (`ViewEmbedder::add_view`), which says which request it answers (`View::request_id`), or
259    /// one the system made or restored, a phone's screen, a web page's element, a host app's
260    /// view, a task Android brings back from Recents; each says what it is for
261    /// (`View::initial_data`). Flutter tells this only as [`did_change_metrics`](Self::did_change_metrics),
262    /// and a listener compares `platformDispatcher.views` with what it had.
263    fn did_add_view(&self, app: &mut App, view: &ViewRef) {
264        let _ = (app, view);
265    }
266
267    /// Called when such a view goes.
268    fn did_remove_view(&self, app: &mut App, view: ViewId) {
269        let _ = (app, view);
270    }
271
272    /// Called when the app's request `request` for a view got none, and why.
273    fn did_fail_view_request(&self, app: &mut App, request: RequestId, error: &ViewError) {
274        let _ = (app, request, error);
275    }
276
277    /// Called when the user asks to close such a view: whoever builds it decides.
278    ///
279    /// Answers whether this observer handled it. The first one that answers `true` stops the
280    /// others from being asked, as with [`did_pop_route`](Self::did_pop_route); where none does,
281    /// the view closes, or, the app's last, asks to quit.
282    fn did_request_view_close(&self, app: &mut App, view: ViewId) -> bool {
283        let _ = (app, view);
284        false
285    }
286}
287
288/// The object side of [`WidgetsBindingObserver`]: implement it on an arena object (a
289/// `State`) and register `Rc::new(handle)`.
290pub trait WidgetsBindingObserverObject: Sized + 'static {
291    /// See [`WidgetsBindingObserver::did_change_metrics`].
292    fn did_change_metrics(self: Handle<Self>, app: &mut App) {
293        let _ = app;
294    }
295
296    /// See [`WidgetsBindingObserver::did_change_locales`].
297    fn did_change_locales(self: Handle<Self>, app: &mut App, locales: Option<&[Locale]>) {
298        let _ = (app, locales);
299    }
300
301    /// See [`WidgetsBindingObserver::did_change_view_focus`].
302    fn did_change_view_focus(self: Handle<Self>, app: &mut App, event: ViewFocusEvent) {
303        let _ = (app, event);
304    }
305
306    /// See [`WidgetsBindingObserver::did_change_drag`].
307    fn did_change_drag(self: Handle<Self>, app: &mut App, report: &DragReport) {
308        let _ = (app, report);
309    }
310
311    /// See [`WidgetsBindingObserver::did_change_text_scale_factor`].
312    fn did_change_text_scale_factor(self: Handle<Self>, app: &mut App) {
313        let _ = app;
314    }
315
316    /// See [`WidgetsBindingObserver::did_change_platform_brightness`].
317    fn did_change_platform_brightness(self: Handle<Self>, app: &mut App) {
318        let _ = app;
319    }
320
321    /// See [`WidgetsBindingObserver::did_change_caption_style`].
322    fn did_change_caption_style(self: Handle<Self>, app: &mut App) {
323        let _ = app;
324    }
325
326    /// See [`WidgetsBindingObserver::did_change_app_lifecycle_state`].
327    fn did_change_app_lifecycle_state(self: Handle<Self>, app: &mut App, state: AppLifecycleState) {
328        let _ = (app, state);
329    }
330
331    /// See [`WidgetsBindingObserver::did_request_app_exit`].
332    fn did_request_app_exit(self: Handle<Self>, app: &mut App) -> Task<AppExitResponse> {
333        let _ = app;
334        Task::ready(AppExitResponse::Exit)
335    }
336
337    /// See [`WidgetsBindingObserver::did_change_accessibility_features`].
338    fn did_change_accessibility_features(self: Handle<Self>, app: &mut App) {
339        let _ = app;
340    }
341
342    /// See [`WidgetsBindingObserver::did_pop_route`].
343    fn did_pop_route(self: Handle<Self>, app: &mut App, view: ViewId) -> bool {
344        let _ = (app, view);
345        false
346    }
347
348    /// See [`WidgetsBindingObserver::handle_start_back_gesture`].
349    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    /// See [`WidgetsBindingObserver::handle_update_back_gesture_progress`].
359    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    /// See [`WidgetsBindingObserver::handle_commit_back_gesture`].
368    fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App) {
369        let _ = app;
370    }
371
372    /// See [`WidgetsBindingObserver::handle_cancel_back_gesture`].
373    fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App) {
374        let _ = app;
375    }
376
377    /// See [`WidgetsBindingObserver::did_add_view`].
378    fn did_add_view(self: Handle<Self>, app: &mut App, view: &ViewRef) {
379        let _ = (app, view);
380    }
381
382    /// See [`WidgetsBindingObserver::did_remove_view`].
383    fn did_remove_view(self: Handle<Self>, app: &mut App, view: ViewId) {
384        let _ = (app, view);
385    }
386
387    /// See [`WidgetsBindingObserver::did_fail_view_request`].
388    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    /// See [`WidgetsBindingObserver::did_request_view_close`].
398    fn did_request_view_close(self: Handle<Self>, app: &mut App, view: ViewId) -> bool {
399        let _ = (app, view);
400        false
401    }
402}
403
404/// An object the binding names without keeping, as an observer: once the object is freed, the
405/// binding skips it as it skips a tear-off ([`App::tear_off_receiver_is_live`]).
406impl<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
517/// A kept object as an observer: the binding's list keeps it, as Dart's `_observers` does.
518impl<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
596/// A registered observer; removed again by identity of the `Rc`.
597pub type WidgetsBindingObserverRef = Rc<dyn WidgetsBindingObserver>;
598
599/// Dart's `List.remove` on a list of observers: removes the first registration of `observer`,
600/// and answers whether there was one.
601fn 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    /// The current [`WidgetsBinding`], created on first use (Flutter's
619    /// `WidgetsFlutterBinding.ensureInitialized`).
620    ///
621    /// Creating it creates the renderer, gesture, and scheduler bindings below it.
622    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    /// Flutter's `initInstances`: the bindings below first, as Dart's `super.initInstances()`
632    /// runs first, then the [`BuildOwner`], whose focus manager registers with this binding,
633    /// then the dispatcher callbacks and the caption settings followed.
634    ///
635    /// The bindings below come before the build owner so that the focus manager does not hear
636    /// the lifecycle state the host started in, which the services binding reads when it is
637    /// set up.
638    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    /// Dart's `WidgetsBinding.initServiceExtensions`, in a debug build: the element tree's and
655    /// the focus tree's dumps, each answering `{"data": text}`.
656    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        // A string, not a boolean, as Flutter's tools read it.
662        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    /// The [`PlatformMenuDelegate`] the app's [`PlatformMenuBar`] hands its menus to: by default
680    /// a [`DefaultPlatformMenuDelegate`], which hands them to the host's menu bar.
681    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    /// Replaces the [`PlatformMenuDelegate`], as Flutter's `platformMenuDelegate` setter does.
691    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    /// Registers this binding's overrides with the bindings below it, setting each of them up
700    /// on first use.
701    fn override_the_bindings_below(self: Handle<Self>, app: &mut App) {
702        // Flutter's `WidgetsBinding` overrides `RendererBinding.drawFrame`.
703        RendererBinding::instance(app).set_overrides(app, Rc::new(self));
704        // And `SchedulerBinding.handleAppLifecycleStateChanged`.
705        SchedulerBinding::set_overrides(app, Rc::new(self));
706        // And `ServicesBinding.handleRequestAppExit`.
707        ServicesBinding::instance(app).set_overrides(app, Rc::new(self));
708    }
709
710    /// The dispatcher callbacks Flutter's `initInstances` assigns to the binding's handlers.
711    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    /// Tells the observers each change of the platform's caption settings, for as long as the
755    /// app runs; a platform that keeps none has none to tell.
756    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    /// Resolves at the next change of the platform's caption settings; `None` where it keeps
773    /// none.
774    fn caption_settings_changed(app: &App) -> Option<MediaChangeFuture> {
775        let platform = app.platform();
776        Some(platform.caption_settings()?.changed())
777    }
778
779    /// Tells the observers the caption settings changed, and answers the future of their next
780    /// change, asked before the observers read the style so that no change goes unheard.
781    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    /// The object in charge of the focus tree.
791    ///
792    /// Rarely used directly. Instead, consider using `FocusScope::of` to obtain the
793    /// `FocusScopeNode` for a given `BuildContext`.
794    pub fn focus_manager(self: Handle<Self>, app: &App) -> Handle<crate::FocusManager> {
795        self.build_owner(app).focus_manager(app)
796    }
797
798    /// The [`BuildOwner`] in charge of executing the build pipeline for the widget tree
799    /// rooted at this binding.
800    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    /// `element` was marked dirty: a frame of its view is asked for, or of every view for an
808    /// element above every view, and the first of them builds it.
809    fn handle_build_scheduled(self: Handle<Self>, app: &mut App, element: AnyElement) {
810        // Flutter's debug checks against building during `drawFrame`'s locked phases wait
811        // with diagnostics.
812        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    /// Whether a frame has been drawn and sent to the host: Dart's
820    /// `debugDidSendFirstFrameEvent`. Until then a dump finds no tree, or a tree not built yet.
821    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    /// The [`Element`] that is at the root of the element tree hierarchy.
826    ///
827    /// This is initialized the first time [`run_app`] is called.
828    pub fn root_element(self: Handle<Self>, app: &App) -> Option<AnyElement> {
829        app.get(self).root_element
830    }
831
832    /// Whether the binding is ready to produce frames: Flutter's `framesEnabled` override
833    /// waits for the root widget.
834    pub fn ready_to_produce_frames(self: Handle<Self>, app: &App) -> bool {
835        app.get(self).ready_to_produce_frames
836    }
837
838    /// `listener` hears each change of the window of `view` from now on: a `WindowScope`.
839    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    /// `listener` hears the window of `view` no more.
853    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    /// The host added a view, whoever started it: the observers hear of it.
869    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    /// The host removed a view: the observers hear of it.
879    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    /// The user asked to close `view`: the first observer that handles it decides, and where none
886    /// does, the close rule closes it, as Flutter's window delegate destroys a window by default
887    /// (`onWindowCloseRequested`).
888    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    /// The window of `view` was minimized or restored, became occluded or shown, or moved: the
901    /// view's `WindowScope` hears it.
902    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    /// The request `request_id` got no view: the observers hear why.
915    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    /// Schedules a `Timer` for attaching the root widget.
927    ///
928    /// This is called by [`run_app`] to configure the widget tree. Consider using
929    /// [`attach_root_widget`](Self::attach_root_widget) if you want to build the widget tree
930    /// synchronously.
931    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    /// Takes a widget and attaches it to the [`root_element`](Self::root_element), creating
940    /// it if necessary.
941    ///
942    /// This is called by [`run_app`] to configure the widget tree.
943    ///
944    /// See also:
945    ///
946    ///  * [`run_app`], which bootstraps the widget tree.
947    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    /// Called by [`attach_root_widget`](Self::attach_root_widget) to attach the provided
957    /// [`RootWidget`] to the [`build_owner`](Self::build_owner).
958    ///
959    /// This creates the [`root_element`](Self::root_element), if necessary, or re-uses an
960    /// existing one.
961    ///
962    /// This method is rarely called directly, but it can be useful in tests to restore the
963    /// element tree to a previous version by providing the [`RootWidget`] of that version.
964    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    /// Registers the given object as a binding observer. Binding observers are notified when
981    /// various application events occur, for example when the system locale changes.
982    /// Generally, one widget in the widget tree registers itself as a binding observer, and
983    /// converts the system state into inherited widgets.
984    ///
985    /// The observer is removed again with the same `Rc` (Dart's `Set.remove` by identity).
986    pub fn add_observer(self: Handle<Self>, app: &mut App, observer: WidgetsBindingObserverRef) {
987        app.get_mut(self).observers.push(observer);
988    }
989
990    /// Unregisters the given observer. This should be used sparingly as it is relatively
991    /// expensive (O(N) in the number of registered observers).
992    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    /// Called when the platform's text scale factor changes: tells the observers.
1015    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    /// Notifies observers that the platform focus of a view has changed.
1022    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    /// Tells the observers of an external drag over a view.
1029    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    /// The user copied, cut or pasted through the platform's own command: its intent goes to the
1036    /// primary focus, as `EditableTextState.performSelector` sends a macOS selector's, while the
1037    /// event is the clipboard ([`Clipboard::handle_event`]), so a paste reads what the user
1038    /// pasted. No Flutter counterpart: its engines paste into a text field through its text
1039    /// input connection.
1040    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    /// The user chose an edit command from the platform's own Edit menu: the command's text
1054    /// editing intent goes to the primary focus, as a key's shortcut sends it. No Flutter
1055    /// counterpart: Flutter's macOS embedder sends the command to its text input plugin.
1056    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    /// Has `listener` hear the events of the tray icon `icon`, in place of whatever heard them
1068    /// before: a [`PlatformTrayIcon`](crate::widgets::platform_tray_icon::PlatformTrayIcon)'s
1069    /// icon, or one the app added itself. No Flutter counterpart: Flutter has no tray.
1070    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    /// Stops the events of the tray icon `icon` reaching its listener.
1080    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    /// Something happened to the tray icon `icon`, as the host reports it: its listener hears it,
1085    /// and nothing does when it has none.
1086    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    /// Called when the platform brightness changes: tells the observers.
1099    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    /// Called when the user's caption style changes: tells the observers.
1106    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    /// Called when the system locale changes.
1113    ///
1114    /// Calls [`dispatch_locales_changed`](Self::dispatch_locales_changed) to notify the
1115    /// binding observers.
1116    ///
1117    /// This method exposes notifications from `PlatformDispatcher.onLocaleChanged`.
1118    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    /// Notify all the observers that the locale has changed (using
1124    /// [`WidgetsBindingObserver::did_change_locales`]), giving them the `locales` argument.
1125    ///
1126    /// This is called by [`handle_locale_changed`](Self::handle_locale_changed) when the
1127    /// `PlatformDispatcher.onLocaleChanged` notification is received.
1128    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    /// Called when the set of active accessibility features changes: tells the observers.
1135    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    /// Called when the user asks to go back in `view`: asks each observer in turn and stops at
1142    /// the first that says it went back.
1143    ///
1144    /// Answers whether any of them did. When none did there was nothing left to go back
1145    /// to in the view, and the host does whatever the platform does without the application.
1146    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    /// Called when a predictive back gesture starts: asks every observer whether it handles
1156    /// the gesture, and keeps each that says it does as the one the rest of the gesture goes
1157    /// to.
1158    ///
1159    /// Answers whether any observer handles it. Dart's `_handleStartBackGesture`, which
1160    /// `SystemChannels.backGesture` calls.
1161    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    /// Called when a predictive back gesture moves: tells the observers that handle it.
1176    ///
1177    /// Dart's `_handleUpdateBackGestureProgress`.
1178    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    /// Called when a predictive back gesture in `view` finishes successfully: tells the
1193    /// observers that handle it, or, when none does, goes back in `view` as Back does
1194    /// ([`handle_pop_route`](Self::handle_pop_route)).
1195    ///
1196    /// Answers whether the application handled it; `false` means none of the observers
1197    /// handled the gesture and nothing went back, and the host does what the platform does
1198    /// without the application, as after [`handle_pop_route`](Self::handle_pop_route). Dart's
1199    /// `_handleCommitBackGesture`.
1200    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            // If the predictive back was not handled, then the route should be popped
1203            // like a normal, non-predictive back. For example, this will happen if a
1204            // back gesture occurs but no predictive back route transition exists to
1205            // handle it. The back gesture should still cause normal pop even if it
1206            // doesn't cause a predictive transition.
1207            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    /// Called when a predictive back gesture is canceled: tells the observers that handle it.
1216    ///
1217    /// Dart's `_handleCancelBackGesture`.
1218    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    /// Whether the [`root_element`](Self::root_element) has been initialized.
1225    ///
1226    /// This will be false until [`run_app`] is called (or `WidgetTester.pumpWidget` is
1227    /// called in the context of a `TestWidgetsFlutterBinding`).
1228    pub fn is_root_widget_attached(self: Handle<Self>, app: &App) -> bool {
1229        app.get(self).root_element.is_some()
1230    }
1231}
1232
1233/// The text editing intent of the platform's command behind `event`, as a key would invoke it.
1234fn 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
1255/// Flutter's `WidgetsBinding` override of `handleAppLifecycleStateChanged`, which tells every
1256/// observer after the scheduler's own body has run.
1257impl 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
1269/// Flutter's `WidgetsBinding` override of `handleRequestAppExit`, which asks every observer,
1270/// each once the one before it has answered.
1271impl 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        // Dart's `async` body runs up to its first `await` within the call, which asks the
1275        // first observer; the others are asked as the answers before theirs arrive.
1276        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                    // Don't early return. For the case where someone is just using the
1286                    // observer to know when exit happens, we want to call all the
1287                    // observers, even if we already know we're going to cancel.
1288                }
1289                // One removed while an earlier one was answering is not asked (Flutter #190343).
1290                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
1307/// Flutter's `WidgetsBinding.drawFrame`: build the dirty widgets, let the renderer draw,
1308/// then unmount what fell out of the tree.
1309impl 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    /// `WidgetsBinding.handleMetricsChanged` after `super`: tells the observers.
1326    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
1333/// Inflate the given widget and attach it to the view.
1334///
1335/// The widget is given constraints during layout that force it to fill the entire view. If
1336/// you wish to align your widget to one side of the view (e.g., the top), consider using the
1337/// `Align` widget. If you wish to center your widget, you can also use the `Center` widget.
1338///
1339/// Calling [`run_app`] again will detach the previous root widget from the view and attach
1340/// the given widget in its place. The new widget tree is compared against the previous widget
1341/// tree and any differences are applied to the underlying render tree, similar to what
1342/// happens when a `StatefulWidget` rebuilds after calling `State::set_state`.
1343///
1344/// Initializes the binding using [`WidgetsBinding::instance`] if necessary.
1345///
1346/// The root widget is attached on the next timer turn, as Dart's `Timer.run` does, and the
1347/// first frame is scheduled.
1348///
1349/// `content` is built in every view the platform hosts for the app that carries no initial data,
1350/// each with its own state ([`MultiViewApp`]). Where the platform gives the app no view
1351/// at start, as on a desktop, it asks for a window with the default configuration
1352/// ([`run_app_with`] takes one); a platform that gives the app its own view, as a phone does, has
1353/// it there at start. A request to close the
1354/// app's last view asks to quit, as Cmd-Q does. Flutter's `runApp` needs the implicit view,
1355/// which Waft has no more.
1356///
1357/// # Panics
1358///
1359/// Where the platform gives the app no view at start and makes no window for it: an app
1360/// embedded where views come later starts with [`MultiViewApp`] instead, as Flutter's web
1361/// multi-view apps start with `runWidget`.
1362pub fn run_app(app: &mut App, content: WidgetRef) {
1363    run_app_with(app, content, WindowConfig::default());
1364}
1365
1366/// [`run_app`], asking for a window configured as `window` where the platform gives the app no
1367/// view at start, as on a desktop. Where it gives one, as a phone does, `window` goes unused.
1368pub 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
1388/// The close rule of `run_app` and [`MultiViewApp`]: a request to close the app's last view asks
1389/// to quit, as Cmd-Q does, so the exit listeners may refuse, and any other view's window closes.
1390pub(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
1401/// Inflate the given widget and bootstrap the widget tree.
1402///
1403/// Unlike [`run_app`], this method does not define a `View` widget: the given `widget`
1404/// must contain one (or the tree has no render tree to attach to).
1405pub 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
1415/// Dart's `debugDumpApp`, answering its text where Dart prints it: the binding and build mode,
1416/// then the element tree from the root as `toStringDeep` shows it, each element on one line
1417/// with its widget's properties.
1418pub 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/// A wrapper widget that will be used as the root of the widget tree.
1432///
1433/// An instance of this widget is created by [`WidgetsBinding::attach_root_widget`].
1434///
1435/// It is used as the root of the widget tree, and provides a [`RootElement`] which does not
1436/// have a render object itself and instead delegates rendering to its child.
1437#[derive(Debug, Default)]
1438pub struct RootWidget {
1439    pub key: Option<KeyRef>,
1440    /// The widget below this widget in the tree.
1441    pub child: Option<WidgetRef>,
1442    /// A short description of this widget used by debugging aids.
1443    pub debug_short_description: Option<String>,
1444    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
1445    created: Option<CreationLocation>,
1446}
1447
1448impl RootWidget {
1449    /// Creates a `RootWidget`; Dart's named arguments are the setters.
1450    pub fn new() -> RootWidget {
1451        RootWidget::default()
1452    }
1453
1454    /// Dart `RootWidget(key:)`.
1455    pub fn key(mut self, key: KeyRef) -> RootWidget {
1456        self.key = Some(key);
1457        self
1458    }
1459
1460    /// Dart `RootWidget(child:)`.
1461    #[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    /// Dart `RootWidget(debug_short_description:)`.
1468    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    /// Inflate this widget and attaches the resulting [`RootElement`] to the provided
1477    /// [`BuildOwner`].
1478    ///
1479    /// If `element` is `None`, this function will create a new element. Otherwise, the given
1480    /// element will have an update scheduled to switch to this widget.
1481    ///
1482    /// Used by [`WidgetsBinding::attach_to_build_owner`] (which is indirectly called by
1483    /// [`run_app`]) to bootstrap applications.
1484    #[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
1556/// The root of the element tree.
1557///
1558/// This element class is the instantiation of a [`RootWidget`]. It can be used only as the
1559/// root of an [`Element`] tree (it cannot be mounted into another [`Element`]; its parent
1560/// must be `None`).
1561///
1562/// In typical usage, it will be instantiated for a [`RootWidget`] by calling
1563/// [`RootWidget::attach`]. In this usage, it is normally instantiated by the bootstrapping
1564/// logic in the `WidgetsFlutterBinding` singleton created by [`run_app`].
1565pub 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    /// The child element, if any.
1583    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()); // We are the root!
1621        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); // clears the "dirty" flag
1626    }
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 // This element doesn't have a build phase.
1643    }
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
1654/// The build owner a `GlobalKey` resolves against: the binding's, as Dart's
1655/// `WidgetsBinding.instance.buildOwner` reads it; `None` before the binding exists.
1656pub(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    /// An app with flutter_test's view and no tree yet, for the cases on `run_app` itself, which
1753    /// a [`WidgetTester`]'s pre-test tree would already have attached.
1754    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            // The pre-test tree drew the tester's first frame; `run_app`'s warm-up frame is the next.
1814            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    /// An observer that logs each exit request it is asked, and answers once `answer`
1889    /// completes.
1890    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    /// Adds `added` to the binding's observers the first time it is asked to exit.
1927    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    /// Asks the app to exit as the host does, through the services binding, and awaits the
1949    /// answer in a task; `None` while it is still on its way.
1950    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    /// The exit part of Flutter's "Rentrant observer callbacks do not result in exceptions":
2019    /// the request asks the observers there were when it arrived.
2020    #[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    /// Records every lifecycle state it is told of.
2046    #[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    /// Logs each back-gesture callback it hears, and handles a gesture's start while `handles`.
2162    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    /// The events binding_test.dart sends on `flutter/backgesture`.
2214    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    /// The dispatch of `startBackGesture`. binding_test.dart's `handleStartBackGesture` case
2242    /// tests instead that a throwing observer is reported, which a panic here does not allow.
2243    #[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    /// The dispatch of `updateBackGestureProgress` to every observer that handled the start,
2268    /// where binding_test.dart's `handleUpdateBackGestureProgress` case tests a throwing one.
2269    #[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    /// The dispatch of `commitBackGesture`, where binding_test.dart's `handleCommitBackGesture`
2296    /// case tests a throwing observer.
2297    #[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    /// The dispatch of `cancelBackGesture`, where binding_test.dart's `handleCancelBackGesture`
2317    /// case tests a throwing observer.
2318    #[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, &registered);
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, &registered));
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, &registered));
2400        assert!(!binding.remove_observer(&mut app, &registered));
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}