Skip to main content

waft_widgets/
view.rs

1//! Flutter counterpart: `widgets/view.dart` (`View`, `RawView`, the view scopes).
2//!
3//! `View` wraps its child in `MediaQuery::from_view`, a `FocusTraversalGroup` parented on the
4//! root scope, and a `FocusScope` over its own scope node, and, for a view in a window, a
5//! `WindowScope` over the window. `ViewCollection` and `ViewAnchor`
6//! place further views beside or under a tree.
7
8use std::any::Any;
9use std::collections::HashSet;
10use std::fmt;
11use std::panic::Location;
12use std::rc::Rc;
13
14use waft_embedder::{ViewFocusDirection, ViewFocusEvent, ViewFocusState, ViewId, ViewRef};
15use waft_foundation::{
16    App, DiagnosticsNode, DiagnosticsTreeStyle, Handle, ListenableObject, Listener, OptionRetained,
17    ValueKey,
18};
19use waft_rendering::{AnyRenderObject, PipelineOwner, RenderHandle, RenderView, RendererBinding};
20use waft_scheduler::{FrameTarget, SchedulerBinding};
21
22use crate::binding::{WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef};
23use crate::framework::{
24    AnyElement, BuildContext, CreationLocation, Element, ElementBase, ElementData,
25    ElementLifecycle, InheritedWidget, IntoWidget, KeyRef, RenderObjectElement,
26    RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget, RenderTreeRootElement,
27    Slot, State, StateData, StatefulWidget, StatelessWidget, Widget, WidgetKind, WidgetRef,
28    downcast_widget,
29};
30use crate::widgets::focus_manager::{FocusManager, FocusNodeLeaf, FocusScopeNode};
31use crate::widgets::focus_scope::FocusScope;
32use crate::widgets::focus_traversal::FocusTraversalPolicyRef;
33use crate::widgets::focus_traversal::{FocusTraversalGroup, ReadingOrderTraversalPolicy};
34use crate::widgets::lookup_boundary::LookupBoundary;
35use crate::widgets::media_query::MediaQuery;
36use crate::window::WindowScopeOfView;
37use waft_foundation::Ref;
38
39/// Bootstraps a render tree that is rendered into the provided `FlutterView`.
40///
41/// The content rendered into that view is determined by the provided
42/// [`child`](Self::child). Descendants within the same `LookupBoundary` can look up the view
43/// they are rendered into via [`View::of`] and [`View::maybe_of`].
44///
45/// The provided [`child`](Self::child) is wrapped in a `MediaQuery` constructed from the given
46/// view, a `FocusScope`, and a [`RawView`] widget.
47///
48/// For most use cases, using `MediaQuery.of`, or its associated "...Of" methods are a more
49/// appropriate way of obtaining the information that a `FlutterView` exposes. For example,
50/// using `MediaQuery.sizeOf` will expose the _logical_ device size (`MediaQueryData.size`)
51/// rather than the physical size (`FlutterView.physicalSize`). Similarly, while
52/// `FlutterView.padding` conveys the information from the operating system, the
53/// `MediaQueryData.padding` attribute (obtained from `MediaQuery.paddingOf`) further adjusts
54/// this information to be aware of the context of the widget; e.g. the `Scaffold` widget
55/// adjusts the values for its various children.
56///
57/// Each `FlutterView` can be associated with at most one [`View`] widget in the widget tree.
58/// Two or more [`View`] widgets configured with the same `FlutterView` must never exist within
59/// the same widget tree at the same time. This limitation is enforced by a `GlobalKey`
60/// that derives its identity from the [`view`](Self::view) provided to this widget.
61///
62/// Since the [`View`] widget bootstraps its own independent render tree, neither it nor any of
63/// its descendants will insert a `RenderObject` into an existing render tree. Therefore, the
64/// [`View`] widget can only be used in those parts of the widget tree where it is not required
65/// to participate in the construction of the surrounding render tree. In other words, the
66/// widget may only be used in a non-rendering zone of the widget tree (see
67/// `WidgetsBinding` for a definition of rendering and non-rendering zones).
68pub struct View {
69    pub key: Option<KeyRef>,
70    /// The `FlutterView` into which [`child`](Self::child) is drawn.
71    pub view: ViewRef,
72    /// The widget below this widget in the tree, which will be drawn into the
73    /// [`view`](Self::view).
74    pub child: WidgetRef,
75}
76
77impl View {
78    /// Create a [`View`] widget to bootstrap a render tree that is rendered into the provided
79    /// `FlutterView`.
80    #[cfg_attr(debug_assertions, track_caller)]
81    pub fn new<K>(view: ViewRef, child: impl IntoWidget<K>) -> View {
82        View {
83            key: None,
84            view,
85            child: child.into_widget(),
86        }
87    }
88
89    /// Dart `View(key:)`.
90    pub fn key(mut self, key: KeyRef) -> View {
91        self.key = Some(key);
92        self
93    }
94
95    /// Returns the `FlutterView` that the provided `context` will render into.
96    ///
97    /// Returns `None` if the `context` is not associated with a `FlutterView`.
98    ///
99    /// The method creates a dependency on the `context`, which will be informed when the
100    /// identity of the `FlutterView` changes (i.e. the `context` is moved to render into a
101    /// different `FlutterView` then before). The dependency is not triggered when the
102    /// properties on the `FlutterView` itself change.
103    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<ViewRef> {
104        LookupBoundary::depend_on_inherited_widget_of_exact_type::<ViewScope>(app, context)
105            .map(|scope| Rc::clone(&scope.view))
106    }
107
108    /// Returns the `FlutterView` that the provided `context` will render into.
109    ///
110    /// Throws if the `context` is not associated with a `FlutterView`.
111    ///
112    /// The method creates a dependency on the `context`, which will be informed when the
113    /// identity of the `FlutterView` changes (i.e. the `context` is moved to render into a
114    /// different `FlutterView` then before). The dependency is not triggered when the
115    /// properties on the `FlutterView` itself change.
116    pub fn of(app: &mut App, context: BuildContext) -> ViewRef {
117        View::maybe_of(app, context).expect(
118            "View.of() was called with a context that does not contain a View widget. No View \
119             widget ancestor could be found starting from the context that was passed to \
120             View.of(). This usually means that the provided context is not associated with a \
121             View.",
122        )
123    }
124
125    /// The id of the view `context` renders into, or `None` for a context in no view: above
126    /// every `View`, in a test's tree without one, or no longer in the tree.
127    ///
128    /// Unlike [`View::maybe_of`], this creates no dependency, so it may be asked outside a build,
129    /// as when a ticker is created or its state activated.
130    pub fn maybe_id_of(app: &App, context: BuildContext) -> Option<ViewId> {
131        if context.lifecycle(app) != ElementLifecycle::Active {
132            return None;
133        }
134        context
135            .get_inherited_widget_of_exact_type::<ViewScope>(app)
136            .map(|scope| scope.view.id())
137    }
138
139    /// Returns the `PipelineOwner` parent to which a child `View` should attach its
140    /// `PipelineOwner` to.
141    ///
142    /// If `context` has a `View` ancestor, it returns the `PipelineOwner` that manages the
143    /// render tree of that view. If there is no `View` ancestor,
144    /// `RendererBinding.rootPipelineOwner` is returned instead.
145    pub fn pipeline_owner_of(app: &mut App, context: BuildContext) -> Handle<PipelineOwner> {
146        let scoped = context
147            .depend_on_inherited_widget_of_exact_type::<PipelineOwnerScope>(app)
148            .map(|scope| scope.pipeline_owner.handle());
149        scoped.unwrap_or_else(|| RendererBinding::instance(app).root_pipeline_owner(app))
150    }
151}
152
153impl fmt::Debug for View {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        f.debug_struct("View")
156            .field("view", &self.view.id())
157            .finish_non_exhaustive()
158    }
159}
160
161impl StatefulWidget for View {
162    type State = ViewState;
163
164    fn key(&self) -> Option<&KeyRef> {
165        self.key.as_ref()
166    }
167
168    fn create_state(&self) -> ViewState {
169        ViewState {
170            state: StateData::new(),
171            scope_node: None,
172            policy: None,
173            view_has_focus: false,
174            observer: None,
175            scope_listener: None,
176        }
177    }
178}
179
180/// The state of a [`View`], including synchronization with native view focus.
181pub struct ViewState {
182    state: StateData<View>,
183    scope_node: Option<Ref<FocusScopeNode>>,
184    policy: Option<FocusTraversalPolicyRef>,
185    /// Whether the native view owns focus, independently of its widget subtree.
186    view_has_focus: bool,
187    /// Retains the observer identity for removal on disposal.
188    observer: Option<WidgetsBindingObserverRef>,
189    /// Retains the bound callback identity for removal on disposal.
190    scope_listener: Option<Listener>,
191}
192
193impl ViewState {
194    /// The focus scope node this view's subtree is scoped by.
195    fn scope_node(self: Handle<Self>, app: &App) -> Handle<FocusScopeNode> {
196        app.get(self)
197            .scope_node
198            .handle()
199            .expect("created in init_state")
200    }
201
202    /// Requests native focus when the framework focuses a descendant of this view.
203    fn scope_focus_change_listener(self: Handle<Self>, app: &mut App) {
204        let has_focus = self.scope_node(app).has_focus(app);
205        if app.get(self).view_has_focus == has_focus || !has_focus {
206            return;
207        }
208        self.widget(app)
209            .view
210            .host()
211            .request_focus_change(ViewFocusState::Focused, ViewFocusDirection::Forward);
212    }
213}
214
215impl WidgetsBindingObserverObject for ViewState {
216    fn did_change_view_focus(self: Handle<Self>, app: &mut App, event: ViewFocusEvent) {
217        let view_id = self.widget(app).view.id();
218        app.get_mut(self).view_has_focus = match event.state {
219            ViewFocusState::Focused => event.view_id == view_id,
220            ViewFocusState::Unfocused => false,
221        };
222        if event.view_id != view_id {
223            return;
224        }
225        match event.state {
226            ViewFocusState::Focused => {
227                let scope = self.scope_node(app).as_node();
228                let policy = app
229                    .get(self)
230                    .policy
231                    .handle()
232                    .expect("created in init_state");
233                let next_focus = match event.direction {
234                    ViewFocusDirection::Forward => {
235                        policy.find_first_focus(app, scope, true).unwrap_or(scope)
236                    }
237                    ViewFocusDirection::Backward => policy.find_last_focus(app, scope, true),
238                    ViewFocusDirection::Undefined => scope,
239                };
240                next_focus.request_focus(app, None);
241            }
242            ViewFocusState::Unfocused => {
243                FocusManager::instance(app)
244                    .root_scope(app)
245                    .handle()
246                    .request_scope_focus(app);
247            }
248        }
249    }
250}
251
252impl State for ViewState {
253    type Widget = View;
254    crate::state_accessors!();
255
256    fn init_state(self: Handle<Self>, app: &mut App) {
257        let scope_node = FocusScopeNode::new(app);
258        scope_node.set_debug_label(app, Some("View Scope".to_string()));
259        let policy = ReadingOrderTraversalPolicy::new(app).into_erased();
260        let this = app.get_mut(self);
261        this.scope_node = Some(scope_node.clone());
262        this.policy = Some(policy);
263        let observer: WidgetsBindingObserverRef = Rc::new(self);
264        WidgetsBinding::instance(app).add_observer(app, observer.clone());
265        app.get_mut(self).observer = Some(observer);
266        let listener = Listener::handle_method(self, ViewState::scope_focus_change_listener);
267        scope_node.add_listener(app, listener.clone());
268        app.get_mut(self).scope_listener = Some(listener);
269    }
270
271    fn dispose(self: Handle<Self>, app: &mut App) {
272        if let Some(observer) = app.get_mut(self).observer.take() {
273            WidgetsBinding::instance(app).remove_observer(app, &observer);
274        }
275        if let Some(listener) = app.get_mut(self).scope_listener.take() {
276            self.scope_node(app).remove_listener(app, &listener);
277        }
278        self.scope_node(app).dispose(app);
279    }
280
281    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
282        let (view, child) = {
283            let widget = self.widget(app);
284            (Rc::clone(&widget.view), widget.child.clone())
285        };
286        let scope_node = app
287            .get(self)
288            .scope_node
289            .clone()
290            .expect("created in init_state");
291        let policy = app.get(self).policy.clone().expect("created in init_state");
292        let manager = FocusManager::instance(app);
293        let root_scope = manager.root_scope(app).clone();
294        // Attach this view's focus subtree directly to the root scope rather than nesting it
295        // under an enclosing view's scope (which happens when a view is rendered inside another
296        // via a `ViewAnchor`). Each view is an independent focus root: nesting would otherwise
297        // make an ancestor view report `has_focus` when a descendant view is focused.
298        let child = match view.window() {
299            Some(window) => WindowScopeOfView {
300                view: Rc::clone(&view),
301                window,
302                child,
303            }
304            .into_widget(),
305            None => child,
306        };
307        let scoped = FocusTraversalGroup::new(
308            FocusScope::with_external_focus_node(child, scope_node).include_semantics(false),
309        )
310        .policy(policy)
311        .parent_node(root_scope.into_erased());
312        let content = MediaQuery::from_view(None, Rc::clone(&view), scoped);
313        RawView::new(view, content).into_widget()
314    }
315}
316
317/// The lower level workhorse widget for [`View`] that bootstraps a render tree for a
318/// `FlutterView`.
319///
320/// This widget does not have any dependencies on other widgets which is why it can be used
321/// as a root widget for the widget tree.
322///
323/// The [`View`] widget wraps this widget in some additional widgets to expose information
324/// about the `FlutterView` to the widget tree. It is not necessary to have a [`View`] widget
325/// as the root of the tree, but only [`RawView`] widgets at the roots of the tree will not
326/// have access to `MediaQuery` and other information exposed by the [`View`] widget.
327pub struct RawView {
328    pub key: Option<KeyRef>,
329    /// The `FlutterView` into which [`child`](Self::child) is drawn.
330    pub view: ViewRef,
331    /// The widget below this widget in the tree, which will be drawn into the
332    /// [`view`](Self::view).
333    pub child: WidgetRef,
334}
335
336impl RawView {
337    /// Creates a [`RawView`] widget to bootstrap a render tree that is rendered into the
338    /// provided `FlutterView`.
339    #[cfg_attr(debug_assertions, track_caller)]
340    pub fn new<K>(view: ViewRef, child: impl IntoWidget<K>) -> RawView {
341        RawView {
342            key: None,
343            view,
344            child: child.into_widget(),
345        }
346    }
347
348    /// Dart `RawView(key:)`.
349    pub fn key(mut self, key: KeyRef) -> RawView {
350        self.key = Some(key);
351        self
352    }
353}
354
355impl fmt::Debug for RawView {
356    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357        f.debug_struct("RawView")
358            .field("view", &self.view.id())
359            .finish_non_exhaustive()
360    }
361}
362
363impl StatelessWidget for RawView {
364    fn key(&self) -> Option<&KeyRef> {
365        self.key.as_ref()
366    }
367
368    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
369        let view = Rc::clone(&self.view);
370        let child = self.child.clone();
371        RawViewInternal::new(
372            Rc::clone(&self.view),
373            Rc::new(
374                move |_app: &mut App, _context: BuildContext, owner: Ref<PipelineOwner>| {
375                    let scoped = PipelineOwnerScope::new(owner, child.clone());
376                    ViewScope::new(Rc::clone(&view), scoped).into_widget()
377                },
378            ),
379        )
380        .into_widget()
381    }
382}
383
384/// Dart's `_RawViewContentBuilder`.
385type RawViewContentBuilder = Rc<dyn Fn(&mut App, BuildContext, Ref<PipelineOwner>) -> WidgetRef>;
386
387/// Dart's `_RawViewInternal`: the render object widget behind [`RawView`], keyed by its view
388/// so two views never share an element.
389pub struct RawViewInternal {
390    key: KeyRef,
391    view: ViewRef,
392    builder: RawViewContentBuilder,
393    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
394    created: Option<CreationLocation>,
395}
396
397impl RawViewInternal {
398    fn new(view: ViewRef, builder: RawViewContentBuilder) -> RawViewInternal {
399        RawViewInternal {
400            key: ValueKey::new(view.id().0).into(),
401            view,
402            builder,
403            created: None,
404        }
405    }
406
407    #[cfg_attr(debug_assertions, track_caller)]
408    fn into_widget(mut self) -> WidgetRef {
409        self.created = Some(CreationLocation::of_caller());
410        Rc::new(self)
411    }
412}
413
414impl fmt::Debug for RawViewInternal {
415    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
416        f.debug_struct("RawViewInternal")
417            .field("view", &self.view.id())
418            .finish_non_exhaustive()
419    }
420}
421
422impl RenderObjectWidget for RawViewInternal {
423    type RenderObject = RenderView;
424
425    fn key(&self) -> Option<&KeyRef> {
426        Some(&self.key)
427    }
428
429    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
430        RenderView::new(app, None, None, Rc::clone(&self.view)).as_object()
431    }
432}
433
434impl Widget for RawViewInternal {
435    fn key(&self) -> Option<&KeyRef> {
436        Some(&self.key)
437    }
438
439    fn creation_location(&self) -> Option<&'static Location<'static>> {
440        self.created.and_then(CreationLocation::location)
441    }
442
443    fn record_creation_location(&mut self, location: CreationLocation) {
444        self.created = Some(location);
445    }
446
447    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
448        RawViewElement::new(app, this).as_element()
449    }
450
451    fn as_any(&self) -> &dyn std::any::Any {
452        self
453    }
454
455    fn widget_type(&self) -> std::any::TypeId {
456        std::any::TypeId::of::<RawViewInternal>()
457    }
458
459    fn kind(&self) -> WidgetKind {
460        WidgetKind::Other
461    }
462}
463
464/// Dart's `_RawViewElement`: the root of a render tree, with its own `PipelineOwner`, which asks
465/// for a frame of the element's view when a render object in it needs layout or paint.
466pub struct RawViewElement {
467    element: ElementData,
468    render_object_element: RenderObjectElementData,
469    /// Dart's `late final _pipelineOwner`, made when the element mounts, where Dart first reads
470    /// it: its callbacks reach this element.
471    pipeline_owner: Option<Ref<PipelineOwner>>,
472    child: Option<AnyElement>,
473    /// Is `None` if the view is currently not attached.
474    parent_pipeline_owner: Option<Handle<PipelineOwner>>,
475}
476
477impl RawViewElement {
478    fn new(app: &mut App, widget: WidgetRef) -> Handle<RawViewElement> {
479        app.create(RawViewElement {
480            element: ElementData::new(widget),
481            render_object_element: RenderObjectElementData::default(),
482            pipeline_owner: None,
483            child: None,
484            parent_pipeline_owner: None,
485        })
486        .into_tree_node(app)
487    }
488
489    /// Dart's initializer of `_pipelineOwner`. Semantics callbacks wait with accessibility.
490    fn create_pipeline_owner(self: Handle<Self>, app: &mut App) -> Ref<PipelineOwner> {
491        // The view is the widget's key, so it is this element's for its whole life.
492        let view = Self::widget_of(self.as_element().widget(app)).view.id();
493        PipelineOwner::new(
494            app,
495            Some(Listener::new(move |app| {
496                SchedulerBinding::ensure_visual_update(app, FrameTarget::View(view));
497            })),
498            Some(Rc::new(move |app: &mut App, is_dirty: bool| {
499                self.handle_flush_paint(app, is_dirty);
500            })),
501        )
502    }
503
504    fn handle_flush_paint(self: Handle<Self>, app: &mut App, is_dirty: bool) {
505        if is_dirty {
506            let root_node = self.pipeline_owner(app).root_node(app);
507            if let Some(render_view) =
508                root_node.and_then(|root_node| root_node.downcast::<RenderView>(app))
509            {
510                render_view.mark_needs_composite_frame(app);
511            }
512        }
513    }
514
515    /// The `RenderView` at the root of this view's render tree.
516    pub fn render_view(self: Handle<Self>, app: &App) -> RenderHandle<RenderView> {
517        self.typed_render_object(app)
518    }
519
520    /// The pipeline owner that lays out and paints this view's render tree.
521    ///
522    /// # Panics
523    ///
524    /// Before the element mounts.
525    pub fn pipeline_owner(self: Handle<Self>, app: &App) -> Handle<PipelineOwner> {
526        app.get(self)
527            .pipeline_owner
528            .handle()
529            .expect("a RawViewElement makes its pipeline owner when it mounts")
530    }
531
532    fn update_child(self: Handle<Self>, app: &mut App) {
533        let builder = Self::widget_of(self.as_element().widget(app))
534            .builder
535            .clone();
536        let owner = app
537            .get(self)
538            .pipeline_owner
539            .clone()
540            .expect("a RawViewElement makes its pipeline owner when it mounts");
541        let built = builder(app, self.as_element(), owner);
542        let child = app.get(self).child;
543        let child = self
544            .as_element()
545            .update_child(app, child, Some(built), None);
546        app.get_mut(self).child = child;
547    }
548
549    fn attach_view(
550        self: Handle<Self>,
551        app: &mut App,
552        parent_pipeline_owner: Option<Handle<PipelineOwner>>,
553    ) {
554        debug_assert!(app.get(self).parent_pipeline_owner.is_none());
555        let parent_pipeline_owner = parent_pipeline_owner
556            .unwrap_or_else(|| View::pipeline_owner_of(app, self.as_element()));
557        let owner = app
558            .get(self)
559            .pipeline_owner
560            .clone()
561            .expect("a RawViewElement makes its pipeline owner when it mounts");
562        parent_pipeline_owner.adopt_child(app, owner);
563        let render_view = self.render_view(app);
564        RendererBinding::instance(app).add_render_view(app, render_view);
565        app.get_mut(self).parent_pipeline_owner = Some(parent_pipeline_owner);
566    }
567
568    fn detach_view(self: Handle<Self>, app: &mut App) {
569        if let Some(parent_pipeline_owner) = app.get(self).parent_pipeline_owner {
570            let render_view = self.render_view(app);
571            RendererBinding::instance(app).remove_render_view(app, render_view);
572            let owner = self.pipeline_owner(app);
573            parent_pipeline_owner.drop_child(app, owner);
574            app.get_mut(self).parent_pipeline_owner = None;
575        }
576    }
577}
578
579impl RenderObjectElementWidget for RawViewElement {
580    type Widget = RawViewInternal;
581
582    fn widget_of(widget: &WidgetRef) -> &RawViewInternal {
583        downcast_widget::<RawViewInternal>(&**widget).expect("a RawViewElement holds its widget")
584    }
585}
586
587impl RenderObjectElement for RawViewElement {
588    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
589        &app.get(self).render_object_element
590    }
591
592    fn render_object_element_data_mut(
593        self: Handle<Self>,
594        app: &mut App,
595    ) -> &mut RenderObjectElementData {
596        &mut app.get_mut(self).render_object_element
597    }
598}
599
600impl RenderTreeRootElement for RawViewElement {}
601
602impl Element for RawViewElement {
603    crate::element_accessors!();
604
605    const IS_RENDER_OBJECT_ELEMENT: bool = true;
606
607    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
608        self.render_object_element_data(app).render_object()
609    }
610
611    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
612        None
613    }
614
615    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
616        let _ = app;
617        false
618    }
619
620    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
621        if let Some(child) = app.get(self).child {
622            visitor(child);
623        }
624    }
625
626    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
627        debug_assert!(app.get(self).child == Some(child));
628        app.get_mut(self).child = None;
629    }
630
631    fn mount(
632        self: Handle<Self>,
633        app: &mut App,
634        parent: Option<AnyElement>,
635        new_slot: Option<Slot>,
636    ) {
637        RenderObjectElement::mount(self, app, parent, new_slot);
638        let owner = self.create_pipeline_owner(app);
639        app.get_mut(self).pipeline_owner = Some(owner.clone());
640        debug_assert!(owner.root_node(app).is_none());
641        let render_view = self.render_view(app);
642        owner.set_root_node(app, Some(render_view.as_object()));
643        self.attach_view(app, None);
644        self.update_child(app);
645        render_view.prepare_initial_frame(app);
646    }
647
648    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
649        RenderObjectElement::update(self, app, new_widget);
650        self.update_child(app);
651    }
652
653    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
654        RenderObjectElement::perform_rebuild(self, app);
655        self.update_child(app);
656    }
657
658    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
659        ElementBase::did_change_dependencies(self, app);
660        if app.get(self).parent_pipeline_owner.is_none() {
661            return;
662        }
663        let new_parent_pipeline_owner = View::pipeline_owner_of(app, self.as_element());
664        if Some(new_parent_pipeline_owner) != app.get(self).parent_pipeline_owner {
665            self.detach_view(app);
666            self.attach_view(app, Some(new_parent_pipeline_owner));
667        }
668    }
669
670    fn activate(self: Handle<Self>, app: &mut App) {
671        ElementBase::activate(self, app);
672        let owner = self.pipeline_owner(app);
673        debug_assert!(owner.root_node(app).is_none());
674        let render_view = self.render_view(app);
675        owner.set_root_node(app, Some(render_view.as_object()));
676        self.attach_view(app, None);
677    }
678
679    fn deactivate(self: Handle<Self>, app: &mut App) {
680        self.detach_view(app);
681        let owner = self.pipeline_owner(app);
682        debug_assert!(owner.root_node(app) == Some(self.render_view(app).as_object()));
683        owner.set_root_node(app, None); // To satisfy the assert in the super class.
684        RenderObjectElement::deactivate(self, app);
685    }
686
687    fn unmount(self: Handle<Self>, app: &mut App) {
688        // Dart disposes its pipeline owner here; ours has no resources beyond the arena
689        // slot, which goes with the element.
690        RenderObjectElement::unmount(self, app);
691    }
692
693    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
694        RenderObjectElement::update_parent_data(self, app, parent_data_element);
695    }
696
697    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
698        RenderTreeRootElement::update_slot(self, app, new_slot);
699    }
700
701    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
702        RenderTreeRootElement::attach_render_object(self, app, new_slot);
703    }
704
705    fn detach_render_object(self: Handle<Self>, app: &mut App) {
706        RenderTreeRootElement::detach_render_object(self, app);
707    }
708
709    fn insert_render_object_child(
710        self: Handle<Self>,
711        app: &mut App,
712        child: AnyRenderObject,
713        slot: Option<Slot>,
714    ) {
715        debug_assert!(slot.is_none());
716        let render_view = self.render_view(app);
717        render_view.set_child(app, Some(child.as_box().expect("a view holds a box")));
718    }
719
720    fn move_render_object_child(
721        self: Handle<Self>,
722        _app: &mut App,
723        _child: AnyRenderObject,
724        _old_slot: Option<Slot>,
725        _new_slot: Option<Slot>,
726    ) {
727        debug_assert!(false, "a view has one child");
728    }
729
730    fn remove_render_object_child(
731        self: Handle<Self>,
732        app: &mut App,
733        child: AnyRenderObject,
734        slot: Option<Slot>,
735    ) {
736        debug_assert!(slot.is_none());
737        let render_view = self.render_view(app);
738        debug_assert!(render_view.child(app).map(|current| current.as_object()) == Some(child));
739        render_view.set_child(app, None);
740    }
741}
742
743/// Dart's `_ViewScope`: the view a subtree renders into.
744pub struct ViewScope {
745    pub view: ViewRef,
746    pub child: WidgetRef,
747}
748
749impl ViewScope {
750    /// Creates a `ViewScope`; Dart's arguments are all required.
751    #[cfg_attr(debug_assertions, track_caller)]
752    pub fn new<K>(view: ViewRef, child: impl IntoWidget<K>) -> ViewScope {
753        ViewScope {
754            view,
755            child: child.into_widget(),
756        }
757    }
758}
759
760impl fmt::Debug for ViewScope {
761    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762        f.debug_struct("ViewScope")
763            .field("view", &self.view.id())
764            .finish_non_exhaustive()
765    }
766}
767
768impl InheritedWidget for ViewScope {
769    fn child(&self) -> &WidgetRef {
770        &self.child
771    }
772
773    fn update_should_notify(&self, old_widget: &ViewScope) -> bool {
774        !std::ptr::addr_eq(Rc::as_ptr(&self.view), Rc::as_ptr(&old_widget.view))
775    }
776}
777
778/// Dart's `_PipelineOwnerScope`: the pipeline owner a subtree's views attach to.
779#[derive(Debug)]
780pub struct PipelineOwnerScope {
781    pub pipeline_owner: Ref<PipelineOwner>,
782    pub child: WidgetRef,
783}
784
785impl PipelineOwnerScope {
786    /// Creates a `PipelineOwnerScope`; Dart's arguments are all required.
787    #[cfg_attr(debug_assertions, track_caller)]
788    pub fn new<K>(
789        pipeline_owner: Ref<PipelineOwner>,
790        child: impl IntoWidget<K>,
791    ) -> PipelineOwnerScope {
792        PipelineOwnerScope {
793            pipeline_owner,
794            child: child.into_widget(),
795        }
796    }
797}
798
799impl InheritedWidget for PipelineOwnerScope {
800    fn child(&self) -> &WidgetRef {
801        &self.child
802    }
803
804    fn update_should_notify(&self, old_widget: &PipelineOwnerScope) -> bool {
805        self.pipeline_owner != old_widget.pipeline_owner
806    }
807}
808
809/// Dart's `_MultiChildComponentWidget`: views that each bootstrap a render tree of their
810/// own, and at most one child that takes part in the surrounding render tree. Subclasses
811/// choose what to make public.
812pub struct MultiChildComponentWidget {
813    key: Option<KeyRef>,
814    views: Vec<WidgetRef>,
815    child: Option<WidgetRef>,
816    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
817    created: Option<CreationLocation>,
818}
819
820impl MultiChildComponentWidget {
821    fn new(key: Option<KeyRef>, views: Vec<WidgetRef>, child: Option<WidgetRef>) -> Self {
822        MultiChildComponentWidget {
823            key,
824            views,
825            child,
826            created: None,
827        }
828    }
829
830    #[cfg_attr(debug_assertions, track_caller)]
831    fn into_widget(mut self) -> WidgetRef {
832        self.created = Some(CreationLocation::of_caller());
833        Rc::new(self)
834    }
835}
836
837impl fmt::Debug for MultiChildComponentWidget {
838    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839        f.debug_struct("MultiChildComponentWidget")
840            .field("views", &self.views.len())
841            .field("has_child", &self.child.is_some())
842            .finish()
843    }
844}
845
846impl Widget for MultiChildComponentWidget {
847    fn key(&self) -> Option<&KeyRef> {
848        self.key.as_ref()
849    }
850
851    fn creation_location(&self) -> Option<&'static Location<'static>> {
852        self.created.and_then(CreationLocation::location)
853    }
854
855    fn record_creation_location(&mut self, location: CreationLocation) {
856        self.created = Some(location);
857    }
858
859    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
860        MultiChildComponentElement::new(app, this).as_element()
861    }
862
863    fn as_any(&self) -> &dyn Any {
864        self
865    }
866
867    fn widget_type(&self) -> std::any::TypeId {
868        std::any::TypeId::of::<MultiChildComponentWidget>()
869    }
870
871    fn kind(&self) -> WidgetKind {
872        WidgetKind::Other
873    }
874}
875
876/// A collection of sibling [`View`]s.
877///
878/// This widget can only be used in places were a [`View`] widget is allowed, i.e. in a
879/// non-rendering zone of the widget tree. In practical terms, it can be used at the root of
880/// the widget tree outside of any [`View`] widget, as a child of a [`ViewAnchor`], or in the
881/// `view` slot of a [`ViewAnchor`]. It cannot be used as a normal child of a widget that
882/// expects a `RenderObject` as its child.
883pub struct ViewCollection {
884    pub key: Option<KeyRef>,
885    /// The [`View`] widgets that are part of this collection.
886    pub views: Vec<WidgetRef>,
887    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
888    created: Option<CreationLocation>,
889}
890
891impl ViewCollection {
892    pub fn new(views: Vec<WidgetRef>) -> ViewCollection {
893        ViewCollection {
894            key: None,
895            views,
896            created: None,
897        }
898    }
899
900    /// Dart `ViewCollection(key:)`.
901    pub fn key(mut self, key: KeyRef) -> ViewCollection {
902        self.key = Some(key);
903        self
904    }
905
906    #[cfg_attr(debug_assertions, track_caller)]
907    pub fn into_widget(mut self) -> WidgetRef {
908        self.created = Some(CreationLocation::of_caller());
909        Rc::new(self)
910    }
911}
912
913impl fmt::Debug for ViewCollection {
914    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
915        f.debug_struct("ViewCollection")
916            .field("views", &self.views.len())
917            .finish()
918    }
919}
920
921impl Widget for ViewCollection {
922    fn key(&self) -> Option<&KeyRef> {
923        self.key.as_ref()
924    }
925
926    fn creation_location(&self) -> Option<&'static Location<'static>> {
927        self.created.and_then(CreationLocation::location)
928    }
929
930    fn record_creation_location(&mut self, location: CreationLocation) {
931        self.created = Some(location);
932    }
933
934    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
935        MultiChildComponentElement::new(app, this).as_element()
936    }
937
938    fn as_any(&self) -> &dyn Any {
939        self
940    }
941
942    fn widget_type(&self) -> std::any::TypeId {
943        std::any::TypeId::of::<ViewCollection>()
944    }
945
946    fn kind(&self) -> WidgetKind {
947        WidgetKind::Other
948    }
949}
950
951/// Decorates a `child` widget with a side [`View`].
952///
953/// This widget must have a [`View`] ancestor, into which the `child` widget is rendered. The
954/// `view` widget is rendered into a view of its own, while the `child` renders into the
955/// enclosing one.
956#[derive(Debug)]
957pub struct ViewAnchor {
958    pub key: Option<KeyRef>,
959    /// The widget that defines the view anchored to this widget.
960    pub view: Option<WidgetRef>,
961    /// The widget below this widget in the tree, rendered into the enclosing view.
962    pub child: WidgetRef,
963}
964
965impl ViewAnchor {
966    #[cfg_attr(debug_assertions, track_caller)]
967    pub fn new<K>(child: impl IntoWidget<K>) -> ViewAnchor {
968        ViewAnchor {
969            key: None,
970            view: None,
971            child: child.into_widget(),
972        }
973    }
974
975    /// Dart `ViewAnchor(key:)`.
976    pub fn key(mut self, key: KeyRef) -> ViewAnchor {
977        self.key = Some(key);
978        self
979    }
980
981    /// Dart `ViewAnchor(view:)`.
982    #[cfg_attr(debug_assertions, track_caller)]
983    pub fn view<K>(mut self, view: impl IntoWidget<K>) -> ViewAnchor {
984        self.view = Some(view.into_widget());
985        self
986    }
987}
988
989impl StatelessWidget for ViewAnchor {
990    fn key(&self) -> Option<&KeyRef> {
991        self.key.as_ref()
992    }
993
994    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
995        MultiChildComponentWidget::new(
996            None,
997            self.view
998                .iter()
999                .map(|view| LookupBoundary::new(view.clone()).into_widget())
1000                .collect(),
1001            Some(self.child.clone()),
1002        )
1003        .into_widget()
1004    }
1005}
1006
1007thread_local! {
1008    /// Dart's `_MultiChildComponentElement._viewSlot`: one object every view child is
1009    /// slotted with, told apart from a render slot by identity.
1010    static VIEW_SLOT: Rc<dyn Any> = Rc::new(());
1011}
1012
1013fn view_slot() -> Slot {
1014    Slot::Custom(VIEW_SLOT.with(Rc::clone))
1015}
1016
1017fn is_view_slot(slot: Option<&Slot>) -> bool {
1018    matches!(slot, Some(Slot::Custom(slot)) if VIEW_SLOT.with(|view_slot| Rc::ptr_eq(view_slot, slot)))
1019}
1020
1021/// Dart's `_MultiChildComponentElement`.
1022pub struct MultiChildComponentElement {
1023    element: ElementData,
1024    view_elements: Vec<AnyElement>,
1025    forgotten_view_elements: HashSet<AnyElement>,
1026    child_element: Option<AnyElement>,
1027}
1028
1029impl MultiChildComponentElement {
1030    fn new(app: &mut App, widget: WidgetRef) -> Handle<MultiChildComponentElement> {
1031        app.create(MultiChildComponentElement {
1032            element: ElementData::new(widget),
1033            view_elements: Vec::new(),
1034            forgotten_view_elements: HashSet::new(),
1035            child_element: None,
1036        })
1037        .into_tree_node(app)
1038    }
1039
1040    /// The views and the child the widget carries, whichever of the two widget types it is.
1041    fn parts(widget: &WidgetRef) -> (Vec<WidgetRef>, Option<WidgetRef>) {
1042        if let Some(collection) = downcast_widget::<ViewCollection>(&**widget) {
1043            return (collection.views.clone(), None);
1044        }
1045        let widget = downcast_widget::<MultiChildComponentWidget>(&**widget)
1046            .expect("a MultiChildComponentElement holds a ViewCollection or a ViewAnchor's widget");
1047        (widget.views.clone(), widget.child.clone())
1048    }
1049
1050    fn debug_assert_children(self: Handle<Self>, app: &App) -> bool {
1051        let (views, child) = Self::parts(self.as_element().widget(app));
1052        let this = app.get(self);
1053        // Each view widget must have a corresponding element.
1054        debug_assert!(this.view_elements.len() == views.len());
1055        // Iff there is a child widget, it must have a corresponding element.
1056        debug_assert!(this.child_element.is_none() == child.is_none());
1057        // The child element is not also a view element.
1058        debug_assert!(
1059            this.child_element
1060                .is_none_or(|child| !this.view_elements.contains(&child))
1061        );
1062        true
1063    }
1064
1065    /// Dart's `_debugCheckMustAttachRenderObject`: in the [`ViewCollection`] configuration,
1066    /// no ancestor may expect a render object in this element's slot.
1067    fn debug_check_must_attach_render_object(
1068        self: Handle<Self>,
1069        app: &App,
1070        slot: Option<&Slot>,
1071    ) -> bool {
1072        if !cfg!(debug_assertions) || Self::parts(self.as_element().widget(app)).1.is_some() {
1073            return true;
1074        }
1075        let mut has_ancestor_render_object_element = false;
1076        let mut ancestor_wants_render_object = true;
1077        self.as_element()
1078            .visit_ancestor_elements(app, &mut |ancestor| {
1079                if !ancestor.debug_expects_render_object_for_slot(app, slot) {
1080                    ancestor_wants_render_object = false;
1081                    return false;
1082                }
1083                if ancestor.is_render_object_element() {
1084                    has_ancestor_render_object_element = true;
1085                    return false;
1086                }
1087                true
1088            });
1089        debug_assert!(
1090            !(has_ancestor_render_object_element && ancestor_wants_render_object),
1091            "A ViewCollection cannot be inserted into a slot its ancestor expects a render \
1092             object in; move it into the view property of a ViewAnchor widget or to the root \
1093             of the widget tree."
1094        );
1095        true
1096    }
1097
1098    /// The body of `performRebuild`: the child in this element's own slot, the views in the
1099    /// view slot.
1100    fn update_children(self: Handle<Self>, app: &mut App) {
1101        let (views, child) = Self::parts(self.as_element().widget(app));
1102        let slot = self.as_element().slot(app);
1103        let child_element = app.get(self).child_element;
1104        let child_element = self
1105            .as_element()
1106            .update_child(app, child_element, child, slot);
1107        app.get_mut(self).child_element = child_element;
1108
1109        let old_views = app.get(self).view_elements.clone();
1110        let is_forgotten =
1111            |app: &App, child: AnyElement| app.get(self).forgotten_view_elements.contains(&child);
1112        let slots: Vec<Option<Slot>> = views.iter().map(|_| Some(view_slot())).collect();
1113        let view_elements = self.as_element().update_children(
1114            app,
1115            &old_views,
1116            &views,
1117            Some(&is_forgotten),
1118            Some(&slots),
1119        );
1120        let this = app.get_mut(self);
1121        this.view_elements = view_elements;
1122        this.forgotten_view_elements.clear();
1123    }
1124}
1125
1126impl Element for MultiChildComponentElement {
1127    crate::element_accessors!();
1128
1129    /// Dart's `_MultiChildComponentElement.debugDescribeChildren`: the child, then each view
1130    /// named `view 1`, `view 2`, … offstage.
1131    fn debug_describe_children(
1132        self: Handle<Self>,
1133        app: &App,
1134    ) -> Vec<std::rc::Rc<dyn DiagnosticsNode>> {
1135        let this = app.get(self);
1136        let mut children: Vec<std::rc::Rc<dyn DiagnosticsNode>> = Vec::new();
1137        if let Some(child) = this.child_element {
1138            children.push(std::rc::Rc::new(child.to_diagnostics_node(app, None)));
1139        }
1140        for (index, element) in this.view_elements.iter().enumerate() {
1141            children.push(std::rc::Rc::new(
1142                element
1143                    .to_diagnostics_node(app, Some(format!("view {}", index + 1)))
1144                    .with_style(DiagnosticsTreeStyle::Offstage),
1145            ));
1146        }
1147        children
1148    }
1149
1150    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
1151        ElementBase::attach_render_object(self, app, new_slot.clone());
1152        debug_assert!(self.debug_check_must_attach_render_object(app, new_slot.as_ref()));
1153    }
1154
1155    fn mount(
1156        self: Handle<Self>,
1157        app: &mut App,
1158        parent: Option<AnyElement>,
1159        new_slot: Option<Slot>,
1160    ) {
1161        ElementBase::mount(self, app, parent, new_slot.clone());
1162        debug_assert!(self.debug_check_must_attach_render_object(app, new_slot.as_ref()));
1163        debug_assert!(app.get(self).view_elements.is_empty());
1164        debug_assert!(app.get(self).child_element.is_none());
1165        self.update_children(app);
1166        ElementBase::perform_rebuild(self, app);
1167        debug_assert!(self.debug_assert_children(app));
1168    }
1169
1170    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
1171        ElementBase::update_slot(self, app, new_slot.clone());
1172        debug_assert!(self.debug_check_must_attach_render_object(app, new_slot.as_ref()));
1173    }
1174
1175    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
1176        // Cannot switch from ViewAnchor config to ViewCollection config.
1177        debug_assert!(
1178            Self::parts(&new_widget).1.is_none()
1179                == Self::parts(self.as_element().widget(app)).1.is_none()
1180        );
1181        ElementBase::update(self, app, new_widget);
1182        self.as_element().rebuild(app, true);
1183        debug_assert!(self.debug_assert_children(app));
1184    }
1185
1186    fn debug_expects_render_object_for_slot(
1187        self: Handle<Self>,
1188        _app: &App,
1189        slot: Option<&Slot>,
1190    ) -> bool {
1191        !is_view_slot(slot)
1192    }
1193
1194    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
1195        self.update_children(app);
1196        ElementBase::perform_rebuild(self, app); // clears the dirty flag
1197        debug_assert!(self.debug_assert_children(app));
1198    }
1199
1200    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
1201        let this = app.get_mut(self);
1202        if this.child_element == Some(child) {
1203            this.child_element = None;
1204        } else {
1205            debug_assert!(this.view_elements.contains(&child));
1206            debug_assert!(!this.forgotten_view_elements.contains(&child));
1207            this.forgotten_view_elements.insert(child);
1208        }
1209    }
1210
1211    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
1212        let this = app.get(self);
1213        if let Some(child) = this.child_element {
1214            visitor(child);
1215        }
1216        for child in &this.view_elements {
1217            if !this.forgotten_view_elements.contains(child) {
1218                visitor(*child);
1219            }
1220        }
1221    }
1222
1223    fn debug_doing_build(self: Handle<Self>, _app: &App) -> bool {
1224        false // This element does not have a concept of "building".
1225    }
1226
1227    fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
1228        app.get(self).child_element
1229    }
1230}
1231
1232#[cfg(test)]
1233mod tests {
1234    use std::cell::RefCell;
1235    use std::rc::Rc;
1236    use std::time::Duration;
1237    use waft_foundation::Ref;
1238
1239    use waft_embedder::{Size, ViewConstraints, ViewId};
1240    use waft_foundation::{App, AppCell, Handle};
1241    use waft_rendering::{BoxConstraints, RenderView};
1242    use waft_scheduler::{FrameCallback, SchedulerBinding, Ticker};
1243    use waft_test::TestPlatform;
1244
1245    use crate::binding::WidgetsBinding;
1246    use crate::framework::{
1247        BuildContext, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
1248    };
1249    use crate::test_harness::{binding_pump, binding_pump_view, pump_every_view};
1250    use crate::testing::{find, test_widgets};
1251    use crate::widgets::basic::SizedBox;
1252    use crate::widgets::ticker_provider::{
1253        SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData,
1254    };
1255
1256    /// A view's render tree lives under the view's own `PipelineOwner`, which asks for a frame of
1257    /// its view when a render object in it needs layout or paint.
1258    #[test]
1259    fn a_dirty_render_object_under_a_view_schedules_a_frame() {
1260        test_widgets(|tester| {
1261            let key = GlobalKey::new();
1262            tester.pump_widget(
1263                SizedBox::new()
1264                    .key(key.clone().into())
1265                    .width(10.0)
1266                    .height(10.0),
1267            );
1268            tester.pump_by(Duration::from_millis(16));
1269            for _ in 0..4 {
1270                tester.pump();
1271            }
1272            let mut app = tester.cell.borrow_mut();
1273            assert!(
1274                !SchedulerBinding::has_scheduled_frame(&mut app),
1275                "the tree is idle before the probe"
1276            );
1277            let render_object = key
1278                .current_context(&app)
1279                .expect("mounted")
1280                .find_render_object(&app)
1281                .expect("a render object");
1282
1283            render_object.mark_needs_paint(&mut app);
1284            assert!(SchedulerBinding::has_scheduled_frame(&mut app));
1285
1286            drop(app);
1287            tester.pump_by(Duration::from_millis(16));
1288            let mut app = tester.cell.borrow_mut();
1289            assert!(!SchedulerBinding::has_scheduled_frame(&mut app));
1290            render_object.mark_needs_layout(&mut app);
1291            assert!(SchedulerBinding::has_scheduled_frame(&mut app));
1292        });
1293    }
1294
1295    /// Flutter view_test.dart: `RenderView sizes itself to child if constraints allow it
1296    /// (constrained)`.
1297    #[test]
1298    fn a_view_given_loose_constraints_lays_out_at_its_content_size() {
1299        test_widgets(|tester| {
1300            let size = Size::new(30.0, 60.0);
1301            let view_constraints = ViewConstraints::new(0.0, 333.0, 0.0, 666.0);
1302            let box_constraints = BoxConstraints::from_view_constraints(view_constraints)
1303                / tester.device_pixel_ratio();
1304            tester.view().set_physical_constraints(view_constraints);
1305            tester.pump_widget(SizedBox::new().width(size.width()).height(size.height()));
1306
1307            let render_view = tester.render_object(find::by_type::<crate::View>());
1308            let app = tester.cell.borrow();
1309            let render_view = render_view
1310                .downcast::<RenderView>(&app)
1311                .expect("a view's render object is a RenderView");
1312            assert_eq!(render_view.constraints(&app), box_constraints);
1313            assert_eq!(render_view.size(&app), size);
1314            let child = render_view.child(&app).expect("the view has a child");
1315            assert_eq!(child.constraints(&app), box_constraints);
1316            assert_eq!(child.size(&app), size);
1317        });
1318    }
1319
1320    /// The size a view laid itself out at within loose constraints comes with its frame, in
1321    /// physical pixels, as Flutter's `RenderView.compositeFrame` renders the scene at
1322    /// `configuration.toPhysicalSize(size)`.
1323    #[test]
1324    fn a_view_given_loose_constraints_presents_its_frame_at_its_content_size() {
1325        test_widgets(|tester| {
1326            let device_pixel_ratio = tester.device_pixel_ratio();
1327            tester
1328                .view()
1329                .set_physical_constraints(ViewConstraints::new(0.0, 333.0, 0.0, 666.0));
1330            tester.pump_widget(SizedBox::new().width(30.0).height(60.0));
1331
1332            assert_eq!(
1333                tester.view().last_frame_size(),
1334                Some(Size::new(30.0, 60.0) * device_pixel_ratio)
1335            );
1336        });
1337    }
1338
1339    /// Flutter view_constraints_test.dart: `Properly constraints the physical size`.
1340    #[test]
1341    fn a_view_given_tight_constraints_presents_its_frame_at_their_size() {
1342        test_widgets(|tester| {
1343            tester
1344                .view()
1345                .set_physical_constraints(ViewConstraints::tight(1008.0, 2198.0));
1346            tester.view().set_device_pixel_ratio(1.912500023841858);
1347            tester.pump_widget(SizedBox::new());
1348
1349            assert_eq!(
1350                tester.view().last_frame_size(),
1351                Some(Size::new(1008.0, 2198.0))
1352            );
1353        });
1354    }
1355
1356    /// Flutter view_test.dart: platform focus parks on the root and restores the view's history.
1357    #[test]
1358    fn platform_focus_enters_parks_and_restores_the_view() {
1359        use crate::{Focus, FocusManager, FocusNode, FocusNodeLeaf, Row};
1360        use waft_embedder::{
1361            ViewFocusDirection as Direction, ViewFocusEvent, ViewFocusState as State,
1362        };
1363        test_widgets(|tester| {
1364            let (first, last) = tester.update(|app| (FocusNode::new(app), FocusNode::new(app)));
1365            tester.pump_widget(crate::Directionality::new(
1366                waft_embedder::TextDirection::Ltr,
1367                Row::new().children(vec![
1368                    Focus::new(SizedBox::new().width(20.0).height(20.0))
1369                        .focus_node(first.erase())
1370                        .into_widget(),
1371                    Focus::new(SizedBox::new().width(20.0).height(20.0))
1372                        .focus_node(last.erase())
1373                        .into_widget(),
1374                ]),
1375            ));
1376            let cell = Rc::clone(&tester.cell);
1377            let view_id = waft_embedder::View::id(&**tester.view());
1378            let event = |state, direction| {
1379                let mut app = cell.borrow_mut();
1380                WidgetsBinding::instance(&mut app).handle_view_focus_changed(
1381                    &mut app,
1382                    ViewFocusEvent {
1383                        view_id,
1384                        state,
1385                        direction,
1386                    },
1387                );
1388                drop(app);
1389                cell.checkpoint();
1390            };
1391            event(State::Focused, Direction::Forward);
1392            assert!(first.has_primary_focus(&cell.borrow()));
1393            event(State::Unfocused, Direction::Undefined);
1394            {
1395                let mut app = cell.borrow_mut();
1396                assert!(
1397                    FocusManager::instance(&mut app)
1398                        .root_scope(&app)
1399                        .handle()
1400                        .has_primary_focus(&app)
1401                );
1402            }
1403            event(State::Focused, Direction::Undefined);
1404            assert!(first.has_primary_focus(&cell.borrow()));
1405            event(State::Unfocused, Direction::Undefined);
1406            event(State::Focused, Direction::Backward);
1407            assert!(last.has_primary_focus(&cell.borrow()));
1408            event(State::Unfocused, Direction::Undefined);
1409            event(State::Focused, Direction::Undefined);
1410            assert!(last.has_primary_focus(&cell.borrow()));
1411        });
1412    }
1413
1414    const FIRST: ViewId = ViewId(1);
1415    const SECOND: ViewId = ViewId(2);
1416
1417    /// An app with the widgets binding, on a platform that gives it views [`FIRST`] and
1418    /// [`SECOND`].
1419    fn app_with_two_views() -> (Rc<AppCell>, Rc<TestPlatform>) {
1420        let platform = Rc::new(
1421            TestPlatform::new()
1422                .on(waft_embedder::TargetPlatform::MacOS)
1423                .with_views(&[FIRST, SECOND]),
1424        );
1425        let cell = AppCell::with_platform(platform.clone());
1426        WidgetsBinding::instance(&mut cell.borrow_mut());
1427        (cell, platform)
1428    }
1429
1430    /// How many frames each of [`FIRST`] and [`SECOND`] was presented.
1431    fn presented(platform: &TestPlatform) -> [u32; 2] {
1432        [FIRST, SECOND].map(|view| platform.test_view(view).presented())
1433    }
1434
1435    /// Attaches `root` as the whole tree and runs the first frame.
1436    /// `run_widget` and the timer turn that attaches the root and draws the warm-up frame.
1437    fn mount_root(cell: &AppCell, root: WidgetRef) {
1438        crate::binding::run_widget(&mut cell.borrow_mut(), root);
1439        cell.elapse(Duration::ZERO);
1440    }
1441
1442    /// The elapsed times a `Ticking` widget's ticker ticked at.
1443    type Ticks = Rc<RefCell<Vec<Duration>>>;
1444
1445    /// A widget whose ticker runs from its first build, recording the elapsed time of each tick.
1446    /// It builds its child, or a small box.
1447    #[derive(Debug)]
1448    struct Ticking {
1449        key: Option<KeyRef>,
1450        ticks: Ticks,
1451        child: Option<WidgetRef>,
1452    }
1453
1454    impl Ticking {
1455        fn new(ticks: &Ticks) -> Ticking {
1456            Ticking {
1457                key: None,
1458                ticks: Rc::clone(ticks),
1459                child: None,
1460            }
1461        }
1462
1463        fn key(mut self, key: KeyRef) -> Ticking {
1464            self.key = Some(key);
1465            self
1466        }
1467
1468        fn child(mut self, child: WidgetRef) -> Ticking {
1469            self.child = Some(child);
1470            self
1471        }
1472    }
1473
1474    impl StatefulWidget for Ticking {
1475        type State = TickingState;
1476
1477        fn key(&self) -> Option<&KeyRef> {
1478            self.key.as_ref()
1479        }
1480
1481        fn create_state(&self) -> TickingState {
1482            TickingState {
1483                state: StateData::new(),
1484                single_ticker_provider: SingleTickerProviderStateMixinData::new(),
1485                ticker: None,
1486            }
1487        }
1488    }
1489
1490    struct TickingState {
1491        state: StateData<Ticking>,
1492        single_ticker_provider: SingleTickerProviderStateMixinData,
1493        ticker: Option<Ref<Ticker>>,
1494    }
1495
1496    impl SingleTickerProviderStateMixin for TickingState {
1497        fn single_ticker_provider_data(
1498            self: Handle<Self>,
1499            app: &App,
1500        ) -> &SingleTickerProviderStateMixinData {
1501            &app.get(self).single_ticker_provider
1502        }
1503
1504        fn single_ticker_provider_data_mut(
1505            self: Handle<Self>,
1506            app: &mut App,
1507        ) -> &mut SingleTickerProviderStateMixinData {
1508            &mut app.get_mut(self).single_ticker_provider
1509        }
1510    }
1511
1512    impl State for TickingState {
1513        type Widget = Ticking;
1514        crate::state_accessors!();
1515
1516        fn init_state(self: Handle<Self>, app: &mut App) {
1517            let ticks = Rc::clone(&self.widget(app).ticks);
1518            let ticker = SingleTickerProviderStateMixin::create_ticker(
1519                self,
1520                app,
1521                FrameCallback::new(move |_app, elapsed| ticks.borrow_mut().push(elapsed)),
1522            );
1523            let _ticking = ticker.start(app);
1524            app.get_mut(self).ticker = Some(ticker);
1525        }
1526
1527        fn activate(self: Handle<Self>, app: &mut App) {
1528            SingleTickerProviderStateMixin::activate(self, app);
1529        }
1530
1531        fn dispose(self: Handle<Self>, app: &mut App) {
1532            if let Some(ticker) = app.get_mut(self).ticker.take() {
1533                ticker.dispose(app);
1534            }
1535            SingleTickerProviderStateMixin::dispose(self, app);
1536        }
1537
1538        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1539            self.widget(app)
1540                .child
1541                .clone()
1542                .unwrap_or_else(|| SizedBox::new().width(10.0).height(10.0).into_widget())
1543        }
1544    }
1545
1546    fn millis(ms: u64) -> Duration {
1547        Duration::from_millis(ms)
1548    }
1549
1550    #[test]
1551    fn a_view_collection_bootstraps_one_render_tree_per_view() {
1552        use waft_rendering::RendererBinding;
1553
1554        let (cell, platform) = app_with_two_views();
1555        mount_root(
1556            &cell,
1557            super::ViewCollection::new(vec![
1558                super::View::new(platform.test_view(FIRST), SizedBox::new()).into_widget(),
1559                super::View::new(platform.test_view(SECOND), SizedBox::new()).into_widget(),
1560            ])
1561            .into_widget(),
1562        );
1563        let mut app = cell.borrow_mut();
1564        let binding = RendererBinding::instance(&mut app);
1565        assert_eq!(binding.render_views(&app).len(), 2);
1566        assert_eq!(platform.test_view(FIRST).presented(), 1);
1567        assert_eq!(platform.test_view(SECOND).presented(), 1);
1568    }
1569
1570    #[test]
1571    fn a_view_anchor_renders_its_child_in_place_and_its_view_beside_it() {
1572        use waft_rendering::RendererBinding;
1573
1574        let (cell, platform) = app_with_two_views();
1575        mount_root(
1576            &cell,
1577            super::View::new(
1578                platform.test_view(FIRST),
1579                super::ViewAnchor::new(SizedBox::new().width(10.0).height(10.0)).view(
1580                    super::View::new(platform.test_view(SECOND), SizedBox::new()),
1581                ),
1582            )
1583            .into_widget(),
1584        );
1585        let mut app = cell.borrow_mut();
1586        let binding = RendererBinding::instance(&mut app);
1587        assert_eq!(binding.render_views(&app).len(), 2);
1588        assert_eq!(platform.test_view(FIRST).presented(), 1);
1589        assert_eq!(platform.test_view(SECOND).presented(), 1);
1590    }
1591
1592    #[test]
1593    fn a_view_whose_frames_are_held_stays_idle_while_another_animates() {
1594        let (cell, platform) = app_with_two_views();
1595        let (shown, hidden) = (Ticks::default(), Ticks::default());
1596        mount_root(
1597            &cell,
1598            super::ViewCollection::new(vec![
1599                super::View::new(platform.test_view(FIRST), Ticking::new(&shown)).into_widget(),
1600                super::View::new(platform.test_view(SECOND), Ticking::new(&hidden)).into_widget(),
1601            ])
1602            .into_widget(),
1603        );
1604        let (hidden_ticks, hidden_presented) = (
1605            hidden.borrow().len(),
1606            platform.test_view(SECOND).presented(),
1607        );
1608
1609        // The host holds the frames asked of a hidden window: only the shown view's come.
1610        for frame in 1..=5 {
1611            binding_pump_view(&mut cell.borrow_mut(), FIRST, millis(16 * frame));
1612        }
1613        assert_eq!(shown.borrow().len(), 1 + 5, "the shown view animates");
1614        assert_eq!(
1615            hidden.borrow().len(),
1616            hidden_ticks,
1617            "the hidden view's ticker waits"
1618        );
1619        assert_eq!(
1620            platform.test_view(SECOND).presented(),
1621            hidden_presented,
1622            "the hidden view draws nothing"
1623        );
1624        assert!(
1625            platform.has_frame_request(SECOND),
1626            "its ticker's request is held, not lost"
1627        );
1628
1629        // Shown again, it is given the frame it asked for.
1630        binding_pump(&mut cell.borrow_mut(), millis(96));
1631        assert_eq!(hidden.borrow().len(), hidden_ticks + 1);
1632    }
1633
1634    #[test]
1635    fn two_views_at_different_rates_each_animate_at_their_own() {
1636        let (cell, platform) = app_with_two_views();
1637        let (slow, fast) = (Ticks::default(), Ticks::default());
1638        mount_root(
1639            &cell,
1640            super::ViewCollection::new(vec![
1641                super::View::new(platform.test_view(FIRST), Ticking::new(&slow)).into_widget(),
1642                super::View::new(platform.test_view(SECOND), Ticking::new(&fast)).into_widget(),
1643            ])
1644            .into_widget(),
1645        );
1646        slow.borrow_mut().clear();
1647        fast.borrow_mut().clear();
1648
1649        // The first view is on a 60 Hz screen, the second on a 120 Hz one. Both tickers started
1650        // in the warm-up frame, at the time the epoch then starts again from: the first frame
1651        // after it, the second view's at 8 ms. So each ticks at its own view's frames with the
1652        // time since 8 ms.
1653        for ms in (8..=48).step_by(8) {
1654            if ms % 16 == 0 {
1655                binding_pump_view(&mut cell.borrow_mut(), FIRST, millis(ms));
1656            }
1657            binding_pump_view(&mut cell.borrow_mut(), SECOND, millis(ms));
1658        }
1659        assert_eq!(*slow.borrow(), [millis(8), millis(24), millis(40)]);
1660        assert_eq!(
1661            *fast.borrow(),
1662            [0, 8, 16, 24, 32, 40].map(millis),
1663            "each ticks at its own view's frames"
1664        );
1665    }
1666
1667    #[test]
1668    fn a_global_key_subtree_moved_to_another_view_keeps_its_state_and_ticks_there() {
1669        let (cell, platform) = app_with_two_views();
1670        let key = GlobalKey::new();
1671        let ticks = Ticks::default();
1672        let tree = |in_first: bool| -> WidgetRef {
1673            let ticking =
1674                || -> WidgetRef { Ticking::new(&ticks).key(key.clone().into()).into_widget() };
1675            let (first, second): (WidgetRef, WidgetRef) = if in_first {
1676                (ticking(), SizedBox::new().into_widget())
1677            } else {
1678                (SizedBox::new().into_widget(), ticking())
1679            };
1680            super::ViewCollection::new(vec![
1681                super::View::new(platform.test_view(FIRST), first).into_widget(),
1682                super::View::new(platform.test_view(SECOND), second).into_widget(),
1683            ])
1684            .into_widget()
1685        };
1686        mount_root(&cell, tree(true));
1687        let state = key
1688            .current_state::<TickingState>(&cell.borrow_mut())
1689            .expect("mounted in the first view");
1690
1691        mount_root(&cell, tree(false));
1692        assert_eq!(
1693            key.current_state::<TickingState>(&cell.borrow_mut()),
1694            Some(state),
1695            "the same state, now in the second view"
1696        );
1697
1698        let before = ticks.borrow().len();
1699        binding_pump_view(&mut cell.borrow_mut(), FIRST, millis(16));
1700        assert_eq!(
1701            ticks.borrow().len(),
1702            before,
1703            "no tick at the old view's frame"
1704        );
1705        binding_pump_view(&mut cell.borrow_mut(), SECOND, millis(16));
1706        assert_eq!(
1707            ticks.borrow().len(),
1708            before + 1,
1709            "it ticks at its new view's"
1710        );
1711    }
1712
1713    #[test]
1714    fn an_anchored_view_paints_only_at_its_own_frame() {
1715        let (cell, platform) = app_with_two_views();
1716        let key = GlobalKey::new();
1717        mount_root(
1718            &cell,
1719            super::View::new(
1720                platform.test_view(FIRST),
1721                super::ViewAnchor::new(SizedBox::new().width(10.0).height(10.0)).view(
1722                    super::View::new(
1723                        platform.test_view(SECOND),
1724                        SizedBox::new().key(key.clone().into()),
1725                    ),
1726                ),
1727            )
1728            .into_widget(),
1729        );
1730        let mut app = cell.borrow_mut();
1731        let in_anchored = key
1732            .current_context(&app)
1733            .and_then(|context| context.find_render_object(&app))
1734            .expect("the anchored view's render object");
1735        // The frame after the warm-up frame presents each view again.
1736        pump_every_view(&mut app, millis(8));
1737        assert_eq!(presented(&platform), [2, 2]);
1738        platform.take_frame_requests();
1739
1740        in_anchored.mark_needs_paint(&mut app);
1741        assert_eq!(
1742            platform.take_frame_requests(),
1743            [SECOND],
1744            "asked of the anchored view alone"
1745        );
1746        binding_pump_view(&mut app, FIRST, millis(16));
1747        assert_eq!(
1748            presented(&platform),
1749            [2, 2],
1750            "the enclosing view had nothing to paint, and left the anchored view alone"
1751        );
1752        assert!(in_anchored.debug_needs_paint(&app));
1753
1754        binding_pump_view(&mut app, SECOND, millis(16));
1755        assert_eq!(presented(&platform), [2, 3]);
1756        assert!(!in_anchored.debug_needs_paint(&app));
1757    }
1758
1759    #[test]
1760    fn a_request_for_another_view_made_during_a_frame_is_not_lost() {
1761        let (cell, platform) = app_with_two_views();
1762        let key = GlobalKey::new();
1763        mount_root(
1764            &cell,
1765            super::ViewCollection::new(vec![
1766                super::View::new(platform.test_view(FIRST), SizedBox::new()).into_widget(),
1767                super::View::new(
1768                    platform.test_view(SECOND),
1769                    SizedBox::new().key(key.clone().into()),
1770                )
1771                .into_widget(),
1772            ])
1773            .into_widget(),
1774        );
1775        let mut app = cell.borrow_mut();
1776        let in_second = key
1777            .current_context(&app)
1778            .and_then(|context| context.find_render_object(&app))
1779            .expect("the second view's render object");
1780        platform.take_frame_requests();
1781
1782        SchedulerBinding::schedule_frame_callback(
1783            &mut app,
1784            FrameCallback::new(move |app, _time_stamp| in_second.mark_needs_paint(app)),
1785            Some(FIRST),
1786            false,
1787            true,
1788        );
1789        binding_pump(&mut app, millis(16));
1790        assert_eq!(
1791            platform.take_frame_requests(),
1792            [SECOND],
1793            "asked during the first view's frame"
1794        );
1795        binding_pump_view(&mut app, SECOND, millis(32));
1796        assert_eq!(platform.test_view(SECOND).presented(), 2);
1797    }
1798
1799    /// Two views, each holding a keyed subtree, under a keyed subtree above both; answers the
1800    /// keys: above, in the first view, in the second.
1801    fn mount_keyed_views(cell: &AppCell, platform: &TestPlatform) -> [GlobalKey; 3] {
1802        let keys = [GlobalKey::new(), GlobalKey::new(), GlobalKey::new()];
1803        let keyed = |key: &GlobalKey, child: WidgetRef| -> WidgetRef {
1804            crate::KeyedSubtree::new(child)
1805                .key(key.clone().into())
1806                .into_widget()
1807        };
1808        mount_root(
1809            cell,
1810            keyed(
1811                &keys[0],
1812                super::ViewCollection::new(vec![
1813                    super::View::new(
1814                        platform.test_view(FIRST),
1815                        keyed(&keys[1], SizedBox::new().into_widget()),
1816                    )
1817                    .into_widget(),
1818                    super::View::new(
1819                        platform.test_view(SECOND),
1820                        keyed(&keys[2], SizedBox::new().into_widget()),
1821                    )
1822                    .into_widget(),
1823                ])
1824                .into_widget(),
1825            ),
1826        );
1827        keys
1828    }
1829
1830    /// Marks the element `key` is on dirty.
1831    fn mark_needs_build(app: &mut App, key: &GlobalKey) {
1832        key.current_context(app)
1833            .expect("mounted")
1834            .mark_needs_build(app);
1835    }
1836
1837    #[test]
1838    fn a_dirty_element_asks_for_a_frame_of_its_own_view_alone() {
1839        let (cell, platform) = app_with_two_views();
1840        let [_, in_first, in_second] = mount_keyed_views(&cell, &platform);
1841        let mut app = cell.borrow_mut();
1842        platform.take_frame_requests();
1843
1844        mark_needs_build(&mut app, &in_second);
1845        assert_eq!(platform.take_frame_requests(), [SECOND]);
1846        mark_needs_build(&mut app, &in_first);
1847        assert_eq!(
1848            platform.take_frame_requests(),
1849            [FIRST],
1850            "another view is asked too before the build pass, though one view was asked already"
1851        );
1852
1853        binding_pump_view(&mut app, FIRST, millis(16));
1854        assert!(
1855            !in_second
1856                .current_context(&app)
1857                .expect("mounted")
1858                .dirty(&app),
1859            "the first view's frame built the second view's dirty element"
1860        );
1861    }
1862
1863    #[test]
1864    fn a_dirty_element_above_every_view_asks_for_a_frame_of_each() {
1865        let (cell, platform) = app_with_two_views();
1866        let [above, _, _] = mount_keyed_views(&cell, &platform);
1867        let mut app = cell.borrow_mut();
1868        platform.take_frame_requests();
1869
1870        mark_needs_build(&mut app, &above);
1871        assert_eq!(platform.take_frame_requests(), [FIRST, SECOND]);
1872    }
1873
1874    #[test]
1875    fn a_post_frame_callback_for_no_view_runs_while_another_view_is_hidden() {
1876        let (cell, platform) = app_with_two_views();
1877        mount_keyed_views(&cell, &platform);
1878        let mut app = cell.borrow_mut();
1879        let ran = Rc::new(RefCell::new(Vec::new()));
1880        for (name, view) in [("no view", None), ("second view", Some(SECOND))] {
1881            let ran = Rc::clone(&ran);
1882            SchedulerBinding::add_post_frame_callback(
1883                &mut app,
1884                FrameCallback::new(move |_app, _time_stamp| ran.borrow_mut().push(name)),
1885                view,
1886            );
1887        }
1888
1889        // The second view is hidden: the host gives frames to the first alone.
1890        binding_pump_view(&mut app, FIRST, millis(16));
1891        assert_eq!(*ran.borrow(), ["no view"]);
1892        binding_pump_view(&mut app, SECOND, millis(16));
1893        assert_eq!(*ran.borrow(), ["no view", "second view"]);
1894    }
1895
1896    #[test]
1897    fn a_view_that_painted_nothing_presents_nothing() {
1898        let (cell, platform) = app_with_two_views();
1899        let [_, _, in_second] = mount_keyed_views(&cell, &platform);
1900        let mut app = cell.borrow_mut();
1901        // The frame after the warm-up frame presents each view again.
1902        pump_every_view(&mut app, millis(8));
1903        assert_eq!(presented(&platform), [2, 2]);
1904
1905        in_second
1906            .current_context(&app)
1907            .and_then(|context| context.find_render_object(&app))
1908            .expect("the second view's render object")
1909            .mark_needs_paint(&mut app);
1910        pump_every_view(&mut app, millis(16));
1911        assert_eq!(
1912            presented(&platform),
1913            [2, 3],
1914            "the first view keeps showing its last frame"
1915        );
1916    }
1917
1918    #[test]
1919    fn a_ticker_whose_widget_moves_to_another_view_while_its_view_is_hidden_ticks_there() {
1920        let (cell, platform) = app_with_two_views();
1921        let ticks = Ticks::default();
1922        let key = GlobalKey::new();
1923        let above = GlobalKey::new();
1924        let in_first = Rc::new(std::cell::Cell::new(true));
1925        let tree = {
1926            let (ticks, key, in_first) = (Rc::clone(&ticks), key.clone(), Rc::clone(&in_first));
1927            let platform = Rc::clone(&platform);
1928            crate::Builder::new(move |_app, _context| {
1929                let ticking = Ticking::new(&ticks).key(key.clone().into()).into_widget();
1930                let empty = || SizedBox::new().into_widget();
1931                let (first, second) = if in_first.get() {
1932                    (ticking, empty())
1933                } else {
1934                    (empty(), ticking)
1935                };
1936                super::ViewCollection::new(vec![
1937                    super::View::new(platform.test_view(FIRST), first).into_widget(),
1938                    super::View::new(platform.test_view(SECOND), second).into_widget(),
1939                ])
1940                .into_widget()
1941            })
1942            .key(above.clone().into())
1943            .into_widget()
1944        };
1945        mount_root(&cell, tree);
1946        let mut app = cell.borrow_mut();
1947        binding_pump_view(&mut app, FIRST, millis(16));
1948        let state = key.current_state::<TickingState>(&app);
1949
1950        // The first view is hidden from now on: the host gives the second view the frames it
1951        // asks for, and the first none. The second view's frame moves the widget, whose tick was
1952        // due at the first view's frame.
1953        in_first.set(false);
1954        mark_needs_build(&mut app, &above);
1955        let before = ticks.borrow().len();
1956        let mut second_view_frames = 0;
1957        for frame in 2..=5 {
1958            if platform.take_frame_request(SECOND) {
1959                second_view_frames += 1;
1960                binding_pump_view(&mut app, SECOND, millis(16 * frame));
1961            }
1962        }
1963        assert_eq!(
1964            key.current_state::<TickingState>(&app),
1965            state,
1966            "the same state"
1967        );
1968        assert_eq!(second_view_frames, 4, "the second view asks for each frame");
1969        assert_eq!(
1970            ticks.borrow().len(),
1971            before + 3,
1972            "it ticks at each of the second view's frames after the one that moved it"
1973        );
1974    }
1975
1976    #[test]
1977    fn a_ticker_above_every_view_ticks_at_every_frame() {
1978        let (cell, platform) = app_with_two_views();
1979        let ticks = Ticks::default();
1980        mount_root(
1981            &cell,
1982            Ticking::new(&ticks)
1983                .child(
1984                    super::ViewCollection::new(vec![
1985                        super::View::new(platform.test_view(FIRST), SizedBox::new()).into_widget(),
1986                        super::View::new(platform.test_view(SECOND), SizedBox::new()).into_widget(),
1987                    ])
1988                    .into_widget(),
1989                )
1990                .into_widget(),
1991        );
1992        let mut app = cell.borrow_mut();
1993        ticks.borrow_mut().clear();
1994
1995        // Both views are on one screen, then the second is on a screen of its own. The epoch
1996        // starts again at the first frame after the warm-up frame.
1997        pump_every_view(&mut app, millis(16));
1998        pump_every_view(&mut app, millis(32));
1999        binding_pump_view(&mut app, SECOND, millis(40));
2000        assert_eq!(*ticks.borrow(), [0, 16, 24].map(millis));
2001    }
2002}