Skip to main content

waft_rendering/
pipeline_owner.rs

1//! Flutter counterpart: `rendering/object.dart` (`PipelineOwner`).
2//!
3//! Semantics callbacks and the semantics half of [`PipelineManifold`] wait.
4//!
5//! The invariant a later editor could break: the lists of render objects waiting for a pass
6//! retain them, as Dart's lists do. A render object disposed while it waits for a pass, as one
7//! removed from a view held out of the frames, stays alive until that pass, which skips it by
8//! Flutter's own filter: it is no longer this owner's.
9
10use std::rc::Rc;
11
12use waft_foundation::{App, Handle, Listener, Retained, ValueChanged};
13
14use crate::layer::ErasedLayer;
15use crate::object::AnyRenderObject;
16use crate::painting_context::PaintingContext;
17use waft_foundation::Ref;
18
19/// Manages a tree of [`PipelineOwner`]s.
20///
21/// All [`PipelineOwner`]s within a tree are attached to the same
22/// [`PipelineManifold`], which gives them access to shared functionality such
23/// as requesting a visual update (by calling
24/// [`request_visual_update`](Self::request_visual_update)). As such, the
25/// [`PipelineManifold`] gives the [`PipelineOwner`]s access to functionality
26/// usually provided by the bindings without tying the [`PipelineOwner`]s to a
27/// particular binding implementation.
28///
29/// The root of the [`PipelineOwner`] tree is attached to a [`PipelineManifold`] by
30/// passing the manifold to [`PipelineOwner::attach`]. Children are attached to the
31/// same [`PipelineManifold`] as their parent when they are adopted via
32/// [`PipelineOwner::adopt_child`].
33///
34/// Dart's `semanticsEnabled` and the listeners that report its changes wait with
35/// semantics.
36pub trait PipelineManifold {
37    /// Called by a [`PipelineOwner`] connected to this [`PipelineManifold`] when a
38    /// `RenderObject` associated with that pipeline owner wishes to update its
39    /// visual appearance.
40    ///
41    /// Typical implementations of this function will schedule a task to flush the
42    /// various stages of the pipeline. This function might be called multiple
43    /// times in quick succession. Implementations should take care to discard
44    /// duplicate calls quickly.
45    ///
46    /// A [`PipelineOwner`] connected to this [`PipelineManifold`] will call its
47    /// `on_need_visual_update` callback instead of this method if it has been
48    /// configured with one ([`PipelineOwner::new`]).
49    ///
50    /// See also:
51    ///
52    ///  * `SchedulerBinding::ensure_visual_update`, which [`PipelineManifold`]
53    ///    implementations typically call to implement this method.
54    fn request_visual_update(&self, app: &mut App);
55}
56
57/// Signature for a function that is called when the pipeline owner and child owner
58/// finished the paint phase.
59///
60/// The `bool` is `is_dirty`: whether the pipeline owner had dirty render objects that needed to
61/// be painted.
62pub type FlushedPaintCallback = ValueChanged<bool>;
63
64/// The pipeline owner manages the rendering pipeline.
65///
66/// Flutter's counterpart is `PipelineOwner`.
67pub struct PipelineOwner {
68    on_need_visual_update: Option<Listener>,
69    /// Called when this pipeline owner and child owner have finished the paint phase.
70    ///
71    /// The `is_dirty` parameter is true if the pipeline owner has dirty render objects that
72    /// needed to be painted.
73    on_flushed_paint: Option<FlushedPaintCallback>,
74    manifold: Option<Rc<dyn PipelineManifold>>,
75    root_node: Option<AnyRenderObject>,
76    /// The relayout boundaries to lay out at the next layout pass, each retained until that pass.
77    nodes_needing_layout: Vec<Retained<AnyRenderObject>>,
78    /// The render objects whose compositing bits to update at the next pass, each retained until
79    /// that pass.
80    nodes_needing_compositing_bits_update: Vec<Retained<AnyRenderObject>>,
81    should_merge_dirty_nodes: bool,
82    /// Dart's `_debugAllowMutationsToDirtySubtrees`.
83    debug_allow_mutations_to_dirty_subtrees: bool,
84    debug_doing_layout: bool,
85    debug_doing_child_layout: bool,
86    /// The repaint boundaries to paint at the next paint pass, each retained until that pass.
87    nodes_needing_paint: Vec<Retained<AnyRenderObject>>,
88    debug_doing_paint: bool,
89    children: Vec<Ref<PipelineOwner>>,
90    debug_parent: Option<Handle<PipelineOwner>>,
91}
92
93impl PipelineOwner {
94    /// Creates a pipeline owner.
95    ///
96    /// Typically created by the binding, but can be created separately to drive
97    /// off-screen render objects through the rendering pipeline.
98    pub fn new(
99        app: &mut App,
100        on_need_visual_update: Option<Listener>,
101        on_flushed_paint: Option<FlushedPaintCallback>,
102    ) -> Ref<PipelineOwner> {
103        app.create(PipelineOwner {
104            on_need_visual_update,
105            on_flushed_paint,
106            manifold: None,
107            root_node: None,
108            nodes_needing_layout: Vec::new(),
109            nodes_needing_compositing_bits_update: Vec::new(),
110            should_merge_dirty_nodes: false,
111            debug_allow_mutations_to_dirty_subtrees: false,
112            debug_doing_layout: false,
113            debug_doing_child_layout: false,
114            nodes_needing_paint: Vec::new(),
115            debug_doing_paint: false,
116            children: Vec::new(),
117            debug_parent: None,
118        })
119    }
120
121    /// Calls the `on_need_visual_update` callback given to [`new`](Self::new) if there is
122    /// one, otherwise asks the [`PipelineManifold`] this owner is attached to.
123    ///
124    /// Used to notify the pipeline owner that an associated render object wishes
125    /// to update its visual appearance.
126    pub fn request_visual_update(self: Handle<Self>, app: &mut App) {
127        if let Some(callback) = app.get(self).on_need_visual_update.clone() {
128            callback.call(app);
129        } else if let Some(manifold) = app.get(self).manifold.clone() {
130            manifold.request_visual_update(app);
131        }
132    }
133
134    /// The unique object managed by this pipeline that has no parent.
135    pub fn root_node(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
136        app.get(self).root_node
137    }
138
139    /// Sets the unique object managed by this pipeline that has no parent.
140    pub fn set_root_node(self: Handle<Self>, app: &mut App, value: Option<AnyRenderObject>) {
141        let current = app.get(self).root_node;
142        if current == value {
143            return;
144        }
145        if let Some(old) = current {
146            old.detach(app);
147        }
148        app.get_mut(self).root_node = value;
149        if let Some(new) = value {
150            new.attach(app, self);
151        }
152    }
153
154    /// Relayout boundaries which need to be laid out in the next
155    /// [`flush_layout`](Self::flush_layout) pass.
156    pub fn nodes_needing_layout(self: Handle<Self>, app: &App) -> Vec<AnyRenderObject> {
157        handles(&app.get(self).nodes_needing_layout)
158    }
159
160    pub(crate) fn add_node_needing_layout(
161        self: Handle<Self>,
162        app: &mut App,
163        node: AnyRenderObject,
164    ) {
165        let retained = Retained::keep(app, node);
166        app.get_mut(self).nodes_needing_layout.push(retained);
167    }
168
169    pub(crate) fn add_node_needing_compositing_bits_update(
170        self: Handle<Self>,
171        app: &mut App,
172        node: AnyRenderObject,
173    ) {
174        let retained = Retained::keep(app, node);
175        app.get_mut(self)
176            .nodes_needing_compositing_bits_update
177            .push(retained);
178    }
179
180    pub(crate) fn remove_node_needing_paint(
181        self: Handle<Self>,
182        app: &mut App,
183        node: AnyRenderObject,
184    ) {
185        app.get_mut(self)
186            .nodes_needing_paint
187            .retain(|candidate| *candidate != node);
188    }
189
190    /// Whether this pipeline is currently in the layout phase.
191    ///
192    /// Always `false` when debug assertions are disabled.
193    pub fn debug_doing_layout(self: Handle<Self>, app: &App) -> bool {
194        if !cfg!(debug_assertions) {
195            return false;
196        }
197        app.get(self).debug_doing_layout
198    }
199
200    /// See [`AnyRenderObject::invoke_layout_callback`]: runs `callback` with mutations to
201    /// dirty subtrees allowed, then asks [`flush_layout`](Self::flush_layout) to merge the
202    /// nodes it dirtied before continuing.
203    pub(crate) fn enable_mutations_to_dirty_subtrees(
204        self: Handle<Self>,
205        app: &mut App,
206        callback: impl FnOnce(&mut App),
207    ) {
208        debug_assert!(app.get(self).debug_doing_layout);
209        let old_state = app.get(self).debug_allow_mutations_to_dirty_subtrees;
210        if cfg!(debug_assertions) {
211            app.get_mut(self).debug_allow_mutations_to_dirty_subtrees = true;
212        }
213        callback(app);
214        app.get_mut(self).should_merge_dirty_nodes = true;
215        if cfg!(debug_assertions) {
216            app.get_mut(self).debug_allow_mutations_to_dirty_subtrees = old_state;
217        }
218    }
219
220    /// Update the layout information for all dirty render objects.
221    pub fn flush_layout(self: Handle<Self>, app: &mut App) {
222        if cfg!(debug_assertions) {
223            app.get_mut(self).debug_doing_layout = true;
224        }
225        while !app.get(self).nodes_needing_layout.is_empty() {
226            debug_assert!(!app.get(self).should_merge_dirty_nodes);
227            let mut dirty_nodes = std::mem::take(&mut app.get_mut(self).nodes_needing_layout);
228            dirty_nodes.sort_by_key(|node| node.depth(app));
229            let mut i = 0;
230            while i < dirty_nodes.len() {
231                if app.get(self).should_merge_dirty_nodes {
232                    app.get_mut(self).should_merge_dirty_nodes = false;
233                    if !app.get(self).nodes_needing_layout.is_empty() {
234                        app.get_mut(self)
235                            .nodes_needing_layout
236                            .extend(dirty_nodes.drain(i..));
237                        break;
238                    }
239                }
240                let node = dirty_nodes[i].handle();
241                if node.needs_layout(app) && node.owner(app) == Some(self) {
242                    node.layout_without_resize(app);
243                }
244                i += 1;
245            }
246            app.get_mut(self).should_merge_dirty_nodes = false;
247        }
248        if cfg!(debug_assertions) {
249            app.get_mut(self).debug_doing_child_layout = true;
250        }
251        let children: Vec<Handle<PipelineOwner>> = app
252            .get(self)
253            .children
254            .iter()
255            .map(|child| child.handle())
256            .collect();
257        for child in children {
258            child.flush_layout(app);
259        }
260        debug_assert!(
261            app.get(self).nodes_needing_layout.is_empty(),
262            "Child PipelineOwners must not dirty nodes in their parent."
263        );
264        app.get_mut(self).should_merge_dirty_nodes = false;
265        if cfg!(debug_assertions) {
266            app.get_mut(self).debug_doing_layout = false;
267            app.get_mut(self).debug_doing_child_layout = false;
268        }
269    }
270
271    /// Updates the [`AnyRenderObject::needs_compositing`] bits.
272    ///
273    /// Called as part of the rendering pipeline after [`flush_layout`](Self::flush_layout) and
274    /// before [`flush_paint`](Self::flush_paint).
275    pub fn flush_compositing_bits(self: Handle<Self>, app: &mut App) {
276        let mut dirty_nodes =
277            std::mem::take(&mut app.get_mut(self).nodes_needing_compositing_bits_update);
278        dirty_nodes.sort_by_key(|node| node.depth(app));
279        for node in dirty_nodes.iter().map(Retained::handle) {
280            if node.needs_compositing_bits_update(app) && node.owner(app) == Some(self) {
281                node.update_compositing_bits(app);
282            }
283        }
284        let children: Vec<Handle<PipelineOwner>> = app
285            .get(self)
286            .children
287            .iter()
288            .map(|child| child.handle())
289            .collect();
290        for child in children {
291            child.flush_compositing_bits(app);
292        }
293        debug_assert!(
294            app.get(self)
295                .nodes_needing_compositing_bits_update
296                .is_empty(),
297            "Child PipelineOwners must not dirty nodes in their parent."
298        );
299    }
300
301    /// Nodes with a dirty layer or paint state, to be updated in the next
302    /// [`flush_paint`](Self::flush_paint) pass.
303    pub fn nodes_needing_paint(self: Handle<Self>, app: &App) -> Vec<AnyRenderObject> {
304        handles(&app.get(self).nodes_needing_paint)
305    }
306
307    pub(crate) fn add_node_needing_paint(self: Handle<Self>, app: &mut App, node: AnyRenderObject) {
308        let retained = Retained::keep(app, node);
309        app.get_mut(self).nodes_needing_paint.push(retained);
310    }
311
312    /// Whether this pipeline is currently in the paint phase.
313    ///
314    /// Only meaningful when asserts are enabled.
315    pub fn debug_doing_paint(self: Handle<Self>, app: &App) -> bool {
316        app.get(self).debug_doing_paint
317    }
318
319    /// Update the display lists for all render objects.
320    ///
321    /// This function is one of the core stages of the rendering pipeline. Painting occurs after
322    /// layout and before the scene is recomposited so that scene is composited with up-to-date
323    /// display lists for every render object.
324    ///
325    /// A frame paints each of its views by
326    /// [`flush_paint_without_children`](Self::flush_paint_without_children) instead.
327    pub fn flush_paint(self: Handle<Self>, app: &mut App) {
328        if cfg!(debug_assertions) {
329            app.get_mut(self).debug_doing_paint = true;
330        }
331        let is_dirty = self.paint_dirty_nodes(app);
332        let children: Vec<Handle<PipelineOwner>> = app
333            .get(self)
334            .children
335            .iter()
336            .map(|child| child.handle())
337            .collect();
338        for child in children {
339            child.flush_paint(app);
340        }
341        self.did_flush_paint(app, is_dirty);
342        debug_assert!(
343            app.get(self).nodes_needing_paint.is_empty(),
344            "Child PipelineOwners must not dirty nodes in their parent."
345        );
346        if cfg!(debug_assertions) {
347            app.get_mut(self).debug_doing_paint = false;
348        }
349    }
350
351    /// [`flush_paint`](Self::flush_paint) for this owner's render objects alone: the views
352    /// anchored in a view, whose owners are its owner's children, paint at frames of their own.
353    pub fn flush_paint_without_children(self: Handle<Self>, app: &mut App) {
354        if cfg!(debug_assertions) {
355            app.get_mut(self).debug_doing_paint = true;
356        }
357        let is_dirty = self.paint_dirty_nodes(app);
358        self.did_flush_paint(app, is_dirty);
359        if cfg!(debug_assertions) {
360            app.get_mut(self).debug_doing_paint = false;
361        }
362    }
363
364    /// Calls the `on_flushed_paint` callback given to [`new`](Self::new), if there is one.
365    fn did_flush_paint(self: Handle<Self>, app: &mut App, is_dirty: bool) {
366        if let Some(on_flushed_paint) = app.get(self).on_flushed_paint.clone() {
367            on_flushed_paint(app, is_dirty);
368        }
369    }
370
371    /// The paint pass over this owner's dirty render objects, deepest first; answers whether
372    /// there were any.
373    fn paint_dirty_nodes(self: Handle<Self>, app: &mut App) -> bool {
374        let mut dirty_nodes = std::mem::take(&mut app.get_mut(self).nodes_needing_paint);
375        let is_dirty = !dirty_nodes.is_empty();
376        dirty_nodes.sort_by_key(|node| std::cmp::Reverse(node.depth(app)));
377        for node in dirty_nodes.iter().map(Retained::handle) {
378            if (node.needs_paint(app) || node.needs_composited_layer_update(app))
379                && node.owner(app) == Some(self)
380            {
381                // Flutter asserts this of every listed node, which in Flutter is never disposed
382                // before the pass; here a listed node may be, its layer gone, and is skipped above.
383                debug_assert!(node.layer(app).is_some());
384                if node
385                    .layer(app)
386                    .is_some_and(|layer| layer.as_layer().attached(app))
387                {
388                    debug_assert!(node.is_repaint_boundary(app));
389                    if node.needs_paint(app) {
390                        PaintingContext::repaint_composited_child(app, node);
391                    } else {
392                        PaintingContext::update_layer_properties(app, node);
393                    }
394                } else {
395                    node.skipped_painting_on_layer(app);
396                }
397            }
398        }
399        is_dirty
400    }
401
402    /// Mark this [`PipelineOwner`] as attached to the given [`PipelineManifold`].
403    ///
404    /// Typically, this is only called directly on the root [`PipelineOwner`].
405    /// Children are automatically attached to their parent's [`PipelineManifold`]
406    /// when [`adopt_child`](Self::adopt_child) is called.
407    pub fn attach(self: Handle<Self>, app: &mut App, manifold: Rc<dyn PipelineManifold>) {
408        debug_assert!(app.get(self).manifold.is_none());
409        app.get_mut(self).manifold = Some(Rc::clone(&manifold));
410        let children: Vec<Handle<PipelineOwner>> = app
411            .get(self)
412            .children
413            .iter()
414            .map(|child| child.handle())
415            .collect();
416        for child in children {
417            child.attach(app, Rc::clone(&manifold));
418        }
419    }
420
421    /// Mark this [`PipelineOwner`] as detached.
422    ///
423    /// Typically, this is only called directly on the root [`PipelineOwner`].
424    /// Children are automatically detached from their parent's [`PipelineManifold`]
425    /// when [`drop_child`](Self::drop_child) is called.
426    pub fn detach(self: Handle<Self>, app: &mut App) {
427        debug_assert!(app.get(self).manifold.is_some());
428        app.get_mut(self).manifold = None;
429        let children: Vec<Handle<PipelineOwner>> = app
430            .get(self)
431            .children
432            .iter()
433            .map(|child| child.handle())
434            .collect();
435        for child in children {
436            child.detach(app);
437        }
438    }
439
440    /// Adds `child` to this [`PipelineOwner`].
441    pub fn adopt_child(self: Handle<Self>, app: &mut App, child: Ref<PipelineOwner>) {
442        debug_assert!(app.get(&child).debug_parent.is_none());
443        debug_assert!(!app.get(self).children.contains(&child));
444        debug_assert!(
445            !app.get(self).debug_doing_child_layout,
446            "Cannot modify child list after layout."
447        );
448        let kept = child;
449        let child = kept.handle();
450        app.get_mut(self).children.push(kept);
451        if cfg!(debug_assertions) {
452            app.get_mut(child).debug_parent = Some(self);
453        }
454        if let Some(manifold) = app.get(self).manifold.clone() {
455            child.attach(app, manifold);
456        }
457    }
458
459    /// Removes a child [`PipelineOwner`] previously added via
460    /// [`adopt_child`](Self::adopt_child).
461    pub fn drop_child(self: Handle<Self>, app: &mut App, child: Handle<PipelineOwner>) {
462        debug_assert_eq!(app.get(child).debug_parent, Some(self));
463        debug_assert!(app.get(self).children.iter().any(|kept| kept == child));
464        debug_assert!(
465            !app.get(self).debug_doing_child_layout,
466            "Cannot modify child list after layout."
467        );
468        let children = &mut app.get_mut(self).children;
469        let index = children
470            .iter()
471            .position(|candidate| candidate == child)
472            .expect("child was in the list");
473        children.remove(index);
474        if cfg!(debug_assertions) {
475            app.get_mut(child).debug_parent = None;
476        }
477        if app.get(self).manifold.is_some() {
478            child.detach(app);
479        }
480    }
481
482    /// Calls `visitor` for each immediate child of this [`PipelineOwner`].
483    pub fn visit_children(
484        self: Handle<Self>,
485        app: &App,
486        visitor: &mut dyn FnMut(Handle<PipelineOwner>),
487    ) {
488        for child in &app.get(self).children {
489            visitor(child.handle());
490        }
491    }
492}
493
494/// The render objects `retained` holds, as the bare handles a caller reads them by.
495fn handles(retained: &[Retained<AnyRenderObject>]) -> Vec<AnyRenderObject> {
496    retained.iter().map(Retained::handle).collect()
497}
498
499#[cfg(test)]
500mod tests {
501    use std::cell::{Cell, RefCell};
502    use std::rc::Rc;
503
504    use waft_embedder::{Offset, Size};
505    use waft_foundation::{App, AppCell};
506
507    use super::*;
508    use crate::box_::{RenderBox, RenderBoxData};
509    use crate::layer::{ContainerLayer, OffsetLayer};
510    use crate::object::{RenderHandle, RenderObject, RenderObjectData};
511
512    struct TestLeaf {
513        render_object: RenderObjectData,
514        render_box: RenderBoxData,
515        on_layout: Option<Rc<dyn Fn()>>,
516        repaint_boundary: bool,
517    }
518
519    impl RenderObject for TestLeaf {
520        crate::render_object_accessors!();
521
522        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
523            if let Some(on_layout) = self.get(app).on_layout.clone() {
524                on_layout();
525            }
526            let size = self
527                .render_box_data(app)
528                .constraints
529                .as_ref()
530                .map(|constraints| constraints.smallest())
531                .unwrap_or(Size::ZERO);
532            self.set_size(app, size);
533        }
534
535        fn is_repaint_boundary(self: RenderHandle<Self>, app: &App) -> bool {
536            self.get(app).repaint_boundary
537        }
538    }
539
540    impl RenderBox for TestLeaf {
541        crate::render_box_accessors!();
542    }
543
544    fn leaf(on_layout: Option<Rc<dyn Fn()>>) -> TestLeaf {
545        TestLeaf {
546            render_object: RenderObjectData::new(),
547            render_box: RenderBoxData::new(),
548            on_layout,
549            repaint_boundary: false,
550        }
551    }
552
553    /// `pipeline_owner_tree_test.dart`: parent's render objects are laid out
554    /// before child's render objects.
555    #[test]
556    fn parent_pipeline_lays_out_before_child_pipeline() {
557        let cell = AppCell::new();
558        let mut app = cell.borrow_mut();
559        let log = Rc::new(RefCell::new(Vec::new()));
560
561        let root_log = Rc::clone(&log);
562        let root_node = RenderHandle::new_box(
563            &mut app,
564            leaf(Some(Rc::new(move || {
565                root_log.borrow_mut().push("layout parent")
566            }))),
567        );
568        let root = PipelineOwner::new(&mut app, None, None);
569        root.set_root_node(&mut app, Some(root_node.as_object()));
570        root_node.schedule_initial_layout(&mut app);
571
572        let child_log = Rc::clone(&log);
573        let child_node = RenderHandle::new_box(
574            &mut app,
575            leaf(Some(Rc::new(move || {
576                child_log.borrow_mut().push("layout child")
577            }))),
578        );
579        let child = PipelineOwner::new(&mut app, None, None);
580        child.set_root_node(&mut app, Some(child_node.as_object()));
581        child_node.schedule_initial_layout(&mut app);
582
583        root.adopt_child(&mut app, child);
584        root.flush_layout(&mut app);
585        assert_eq!(*log.borrow(), ["layout parent", "layout child"]);
586    }
587
588    /// A render object disposed while it waits for a pass, as one removed from a view held out of
589    /// the frames: the pass skips it, as no longer this owner's, and it is freed at the checkpoint
590    /// after. For each list on its own, since a render object in one list stays alive through the
591    /// other lists' passes. Flutter has no such test: there a render object in these lists cannot
592    /// be freed before the pass.
593    #[test]
594    fn a_render_object_disposed_while_it_waits_for_a_pass_is_skipped_then_freed() {
595        type Wait = fn(&mut App, AnyRenderObject);
596        type Pass = fn(Handle<PipelineOwner>, &mut App);
597        let lists: [(&str, Wait, Pass); 3] = [
598            (
599                "layout",
600                |app, node| node.schedule_initial_layout(app),
601                PipelineOwner::flush_layout,
602            ),
603            (
604                "compositing bits",
605                |app, node| node.mark_needs_compositing_bits_update(app),
606                PipelineOwner::flush_compositing_bits,
607            ),
608            (
609                "paint",
610                |app, node| {
611                    let root_layer = OffsetLayer::new(app, Offset::ZERO);
612                    root_layer.as_layer().attach(app, node.id());
613                    node.schedule_initial_paint(app, root_layer.as_container_layer());
614                },
615                PipelineOwner::flush_paint,
616            ),
617        ];
618        for (list, wait, pass) in lists {
619            let cell = AppCell::new();
620            let mut app = cell.borrow_mut();
621            let owner = PipelineOwner::new(&mut app, None, None);
622            let boundary = TestLeaf {
623                repaint_boundary: true,
624                ..leaf(None)
625            };
626            let node = RenderHandle::new_box(&mut app, boundary).as_object();
627            owner.set_root_node(&mut app, Some(node));
628            wait(&mut app, node);
629            owner.set_root_node(&mut app, None);
630            node.dispose(&mut app);
631            drop(app);
632            cell.checkpoint();
633
634            pass(owner.handle(), &mut cell.borrow_mut());
635            cell.checkpoint();
636
637            assert!(!cell.borrow().contains(node), "freed after the {list} pass");
638        }
639    }
640
641    #[test]
642    fn set_root_node_attaches_and_replacing_detaches() {
643        let cell = AppCell::new();
644        let mut app = cell.borrow_mut();
645        let owner = PipelineOwner::new(&mut app, None, None);
646        let first = RenderHandle::new_box(&mut app, leaf(None));
647        let second = RenderHandle::new_box(&mut app, leaf(None));
648        owner.set_root_node(&mut app, Some(first.as_object()));
649        assert!(first.attached(&app));
650        assert_eq!(first.owner(&app), Some(owner.handle()));
651
652        owner.set_root_node(&mut app, Some(second.as_object()));
653        assert!(!first.attached(&app));
654        assert!(second.attached(&app));
655    }
656
657    #[test]
658    fn schedule_initial_layout_then_flush() {
659        let cell = AppCell::new();
660        let mut app = cell.borrow_mut();
661        let owner = PipelineOwner::new(&mut app, None, None);
662        let node = RenderHandle::new_box(&mut app, leaf(None));
663        owner.set_root_node(&mut app, Some(node.as_object()));
664        node.schedule_initial_layout(&mut app);
665        assert!(node.debug_needs_layout(&app));
666        owner.flush_layout(&mut app);
667        assert!(!node.debug_needs_layout(&app));
668        assert_eq!(node.size(&app), Size::ZERO);
669    }
670
671    /// Counts the visual updates requested through it.
672    struct CountingManifold {
673        requests: Cell<u32>,
674    }
675
676    impl PipelineManifold for CountingManifold {
677        fn request_visual_update(&self, _app: &mut App) {
678            self.requests.set(self.requests.get() + 1);
679        }
680    }
681
682    #[test]
683    fn an_owner_without_a_callback_requests_visual_updates_through_its_manifold() {
684        let cell = AppCell::new();
685        let mut app = cell.borrow_mut();
686        let manifold = Rc::new(CountingManifold {
687            requests: Cell::new(0),
688        });
689        let root = PipelineOwner::new(&mut app, None, None);
690        let adopted_before = PipelineOwner::new(&mut app, None, None);
691        root.adopt_child(&mut app, adopted_before.clone());
692
693        adopted_before.request_visual_update(&mut app);
694        assert_eq!(
695            manifold.requests.get(),
696            0,
697            "unattached owners request nothing"
698        );
699
700        root.attach(&mut app, manifold.clone());
701        root.request_visual_update(&mut app);
702        adopted_before.request_visual_update(&mut app);
703        assert_eq!(
704            manifold.requests.get(),
705            2,
706            "attach reaches existing children"
707        );
708
709        let adopted_after = PipelineOwner::new(&mut app, None, None);
710        root.adopt_child(&mut app, adopted_after.clone());
711        adopted_after.request_visual_update(&mut app);
712        assert_eq!(manifold.requests.get(), 3, "adopt_child attaches the child");
713
714        root.drop_child(&mut app, adopted_after.handle());
715        adopted_after.request_visual_update(&mut app);
716        assert_eq!(manifold.requests.get(), 3, "drop_child detaches the child");
717
718        root.detach(&mut app);
719        adopted_before.request_visual_update(&mut app);
720        assert_eq!(manifold.requests.get(), 3, "detach reaches the children");
721    }
722
723    #[test]
724    fn a_callback_takes_precedence_over_the_manifold() {
725        let cell = AppCell::new();
726        let mut app = cell.borrow_mut();
727        let manifold = Rc::new(CountingManifold {
728            requests: Cell::new(0),
729        });
730        let callbacks = Rc::new(Cell::new(0));
731        let owner = PipelineOwner::new(
732            &mut app,
733            Some(Listener::new({
734                let callbacks = callbacks.clone();
735                move |_app| callbacks.set(callbacks.get() + 1)
736            })),
737            None,
738        );
739        owner.attach(&mut app, manifold.clone());
740        owner.request_visual_update(&mut app);
741        assert_eq!((callbacks.get(), manifold.requests.get()), (1, 0));
742    }
743}